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 warn!(\n\n \"repository root {:?} doesn't have expected name '{}'\",\n\n path, repo_name\n\n );\n\n }\n\n Ok(path)\n\n}\n", "file_path": "tools/smithy-rs-tool-common/src/git.rs", "rank": 0, "score": 453760.62584228115 }, { "content": "fn fix_readme(path: impl AsRef<Path>) -> Result<(bool, String)> {\n\n let mut contents = fs::read_to_string(path.as_ref())\n\n .with_context(|| format!(\"failure to read readme: {:?}\", path.as_ref()))?;\n\n let updated = anchor::replace_anchor(&mut contents, &anchor::anchors(\"footer\"), README_FOOTER)?;\n\n Ok((updated, contents))\n\n}\n", "file_path": "tools/sdk-lints/src/readmes.rs", "rank": 2, "score": 381498.0090024575 }, { "content": "fn assert_send_sync<T: Send + Sync + 'static>() {}\n", "file_path": "aws/sdk/integration-tests/kms/tests/sensitive-it.rs", "rank": 3, "score": 380006.14821127534 }, { "content": "/// Recursively discovers Cargo.toml files in the given `path` and adds them to `manifests`.\n\nfn discover_manifests(manifests: &mut Vec<PathBuf>, path: impl AsRef<Path>) -> anyhow::Result<()> {\n\n let path = path.as_ref();\n\n\n\n for entry in fs::read_dir(path)? {\n\n let entry = entry?;\n\n if entry.path().is_dir() {\n\n discover_manifests(manifests, entry.path())?;\n\n } else if entry.path().is_file()\n\n && entry.path().file_name() == Some(OsStr::new(\"Cargo.toml\"))\n\n {\n\n manifests.push(entry.path());\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{update_manifest, DependencyContext};\n", "file_path": "tools/sdk-versioner/src/main.rs", "rank": 4, "score": 376255.69273369433 }, { "content": "/// Recursively discovers Cargo.toml files in the given `path` and adds them to `manifests`.\n\nfn discover_manifests(manifests: &mut Vec<PathBuf>, path: impl AsRef<Path>) -> anyhow::Result<()> {\n\n let path = path.as_ref();\n\n\n\n for entry in fs::read_dir(path)? {\n\n let entry = entry?;\n\n if entry.path().is_dir() {\n\n discover_manifests(manifests, entry.path())?;\n\n } else if entry.path().is_file()\n\n && entry.path().file_name() == Some(OsStr::new(\"Cargo.toml\"))\n\n {\n\n manifests.push(entry.path());\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{update_manifest, Args};\n", "file_path": "tools/sdk-versioner/src/v1.rs", "rank": 5, "score": 376255.69273369445 }, { "content": "#[track_caller]\n\nfn assert_file_contents<P: AsRef<Path>>(path: P, contents: &str) {\n\n let actual = fs::read_to_string(path.as_ref()).unwrap();\n\n pretty_assertions::assert_str_eq!(contents, actual);\n\n}\n\n\n", "file_path": "tools/sdk-sync/tests/e2e_test.rs", "rank": 6, "score": 367861.3532651767 }, { "content": "fn run_with_args(in_path: impl AsRef<Path>, args: &[&str]) -> String {\n\n let mut cmd = get_test_bin(\"cargo-api-linter\");\n\n cmd.current_dir(in_path.as_ref());\n\n cmd.arg(\"api-linter\");\n\n for &arg in args {\n\n cmd.arg(arg);\n\n }\n\n let output = cmd.output().expect(\"failed to start cargo-api-linter\");\n\n match output.status.code() {\n\n Some(1) => { /* expected */ }\n\n _ => handle_failure(\"cargo-api-linter\", &output).unwrap(),\n\n }\n\n let (stdout, _) = output_text(&output);\n\n stdout\n\n}\n\n\n", "file_path": "tools/api-linter/tests/integration_test.rs", "rank": 7, "score": 365899.93894121534 }, { "content": "pub fn handle_failure(operation_name: &str, output: &Output) -> Result<(), anyhow::Error> {\n\n if !output.status.success() {\n\n return Err(capture_error(operation_name, output));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/smithy-rs-tool-common/src/shell.rs", "rank": 8, "score": 358829.1744114224 }, { "content": "/// Parses a semver version number and adds additional error context when parsing fails.\n\npub fn parse_version(manifest_path: &Path, version: &str) -> Result<Version, Error> {\n\n Version::parse(version)\n\n .map_err(|err| Error::InvalidCrateVersion(manifest_path.into(), version.into(), err.into()))\n\n}\n\n\n", "file_path": "tools/publisher/src/package.rs", "rank": 9, "score": 358487.0308898762 }, { "content": "/// Returns (stdout, stderr)\n\npub fn output_text(output: &Output) -> (String, String) {\n\n (\n\n String::from_utf8_lossy(&output.stdout).to_string(),\n\n String::from_utf8_lossy(&output.stderr).to_string(),\n\n )\n\n}\n\n\n", "file_path": "tools/smithy-rs-tool-common/src/shell.rs", "rank": 10, "score": 354868.1545027826 }, { "content": "fn ls(path: impl AsRef<Path>) -> Result<impl Iterator<Item = PathBuf>> {\n\n Ok(fs::read_dir(path.as_ref())\n\n .with_context(|| format!(\"failed to ls: {:?}\", path.as_ref()))?\n\n .map(|res| res.map(|e| e.path()))\n\n .collect::<Result<Vec<_>, io::Error>>()?\n\n .into_iter())\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 11, "score": 348361.14124822896 }, { "content": "#[cfg_attr(test, mockall::automock)]\n\npub trait Git: Send + Sync {\n\n /// Returns the repository path\n\n fn path(&self) -> &Path;\n\n\n\n /// Clones the repository to the given path\n\n fn clone_to(&self, path: &Path) -> Result<()>;\n\n\n\n /// Returns commit hash of HEAD (i.e., `git rev-parse HEAD`)\n\n fn get_head_revision(&self) -> Result<CommitHash>;\n\n\n\n /// Stages the given path (i.e., `git add ${path}`)\n\n fn stage(&self, path: &Path) -> Result<()>;\n\n\n\n /// Commits the staged files on behalf of the given author using a bot commiter.\n\n fn commit_on_behalf(\n\n &self,\n\n bot_name: &str,\n\n bot_email: &str,\n\n author_name: &str,\n\n author_email: &str,\n", "file_path": "tools/sdk-sync/src/git.rs", "rank": 12, "score": 348343.12375667854 }, { "content": "/// Normalizes XML for comparison during Smithy Protocol tests\n\n///\n\n/// This will normalize documents and attempts to determine if it is OK to sort members or not by\n\n/// using a heuristic to determine if the tag represents a list (which should not be reordered)\n\npub fn normalize_xml(s: &str) -> Result<String, roxmltree::Error> {\n\n let rotree = roxmltree::Document::parse(s)?;\n\n let root = rotree.root().first_child().unwrap();\n\n Ok(unparse_tag(root, 1))\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/xml.rs", "rank": 13, "score": 347017.25462464005 }, { "content": "/// Unescapes a JSON-escaped string.\n\n/// If there are no escape sequences, it directly returns the reference.\n\npub fn unescape_string(value: &str) -> Result<Cow<str>, EscapeError> {\n\n let bytes = value.as_bytes();\n\n for (index, byte) in bytes.iter().enumerate() {\n\n if *byte == b'\\\\' {\n\n return unescape_string_inner(&bytes[0..index], &bytes[index..]).map(Cow::Owned);\n\n }\n\n }\n\n Ok(Cow::Borrowed(value))\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-json/src/escape.rs", "rank": 14, "score": 343770.00675309123 }, { "content": "fn hash_crate(path: &Path) -> Result<String> {\n\n let output = std::process::Command::new(\"crate-hasher\")\n\n .arg(path.to_str().expect(\"nothing special about these paths\"))\n\n .output()?;\n\n shell::handle_failure(\"run crate-hasher\", &output)?;\n\n let (stdout, _stderr) = shell::output_text(&output);\n\n Ok(stdout.trim().into())\n\n}\n\n\n", "file_path": "tools/publisher/src/subcommand/generate_version_manifest.rs", "rank": 15, "score": 334082.4318716354 }, { "content": "pub fn anchors(name: &str) -> (String, String) {\n\n (\n\n format!(\"{}{} -->\", ANCHOR_START, name),\n\n format!(\"{}{} -->\", ANCHOR_END, name),\n\n )\n\n}\n\n\n\nconst ANCHOR_START: &str = \"<!-- anchor_start:\";\n\nconst ANCHOR_END: &str = \"<!-- anchor_end:\";\n\n\n", "file_path": "tools/sdk-lints/src/anchor.rs", "rank": 16, "score": 332698.5942031846 }, { "content": "/// Parse a property line into a key-value pair\n\nfn parse_property_line(line: &str) -> Result<(&str, &str), PropertyError> {\n\n let line = prepare_line(line, true);\n\n let (k, v) = line.split_once('=').ok_or(PropertyError::NoEquals)?;\n\n let k = k.trim_matches(WHITESPACE);\n\n let v = v.trim_matches(WHITESPACE);\n\n if k.is_empty() {\n\n return Err(PropertyError::NoName);\n\n }\n\n Ok((k, v))\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/parse.rs", "rank": 17, "score": 329201.82097599993 }, { "content": "fn split_file_names(value: &str) -> Vec<PathBuf> {\n\n value\n\n .split(is_newline)\n\n .filter(|s| !s.is_empty())\n\n .map(PathBuf::from)\n\n .collect::<Vec<_>>()\n\n}\n\n\n", "file_path": "tools/sdk-sync/src/git.rs", "rank": 18, "score": 325781.6505316544 }, { "content": "fn is_send_sync<T: Send + Sync>(_: T) {}\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 19, "score": 325730.31282097066 }, { "content": "/// A callback that, when inserted into a request body, will be called for corresponding lifecycle events.\n\npub trait BodyCallback: Send + Sync {\n\n /// This lifecycle function is called for each chunk **successfully** read. If an error occurs while reading a chunk,\n\n /// this method will not be called. This method takes `&mut self` so that implementors may modify an implementing\n\n /// struct/enum's internal state. Implementors may return an error.\n\n fn update(&mut self, bytes: &[u8]) -> Result<(), BoxError> {\n\n // \"Use\" bytes so that the compiler won't complain.\n\n let _ = bytes;\n\n Ok(())\n\n }\n\n\n\n /// This callback is called once all chunks have been read. If the callback encountered one or more errors\n\n /// while running `update`s, this is how those errors are raised. Implementors may return a [`HeaderMap`][HeaderMap]\n\n /// that will be appended to the HTTP body as a trailer. This is only useful to do for streaming requests.\n\n fn trailers(&self) -> Result<Option<HeaderMap<HeaderValue>>, BoxError> {\n\n Ok(None)\n\n }\n\n\n\n /// Create a new `BodyCallback` from an existing one. This is called when a `BodyCallback` needs to be\n\n /// re-initialized with default state. For example: when a request has a body that needs to be\n\n /// rebuilt, all callbacks for that body need to be run again but with a fresh internal state.\n", "file_path": "rust-runtime/aws-smithy-http/src/callback.rs", "rank": 20, "score": 323767.1441781061 }, { "content": "fn path(name: &str, ext: &str) -> String {\n\n format!(\"aws-sig-v4-test-suite/{}/{}.{}\", name, name, ext)\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-sigv4/src/http_request/test.rs", "rank": 21, "score": 319823.07058587734 }, { "content": "fn read(path: &str) -> String {\n\n println!(\"Loading `{}` for test case...\", path);\n\n match std::fs::read_to_string(path) {\n\n // This replacement is necessary for tests to pass on Windows, as reading the\n\n // sigv4 snapshots from the file system results in CRLF line endings being inserted.\n\n Ok(value) => value.replace(\"\\r\\n\", \"\\n\"),\n\n Err(err) => {\n\n panic!(\"failed to load test case `{}`: {}\", path, err);\n\n }\n\n }\n\n}\n\n\n\npub(crate) fn test_canonical_request(name: &str) -> String {\n\n // Tests fail if there's a trailing newline in the file, and pre-commit requires trailing newlines\n\n read(&path(name, \"creq\")).trim().to_string()\n\n}\n\n\n\npub(crate) fn test_sts(name: &str) -> String {\n\n read(&path(name, \"sts\"))\n\n}\n", "file_path": "aws/rust-runtime/aws-sigv4/src/http_request/test.rs", "rank": 22, "score": 318001.9844182061 }, { "content": "#[track_caller]\n\nfn assert_no_file<P: AsRef<Path>>(path: P) {\n\n if path.as_ref().exists() {\n\n panic!(\"Path {:?} exists when it shouldn't\", path.as_ref());\n\n }\n\n}\n\n\n", "file_path": "tools/sdk-sync/tests/e2e_test.rs", "rank": 23, "score": 316731.745961871 }, { "content": "pub fn external_opaque_type_in_output() -> impl SimpleTrait {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "tools/api-linter/test-workspace/test-crate/src/lib.rs", "rank": 24, "score": 315543.2881760808 }, { "content": "#[track_caller]\n\nfn assert_file_exists<P: AsRef<Path>>(path: P) {\n\n if !path.as_ref().exists() {\n\n panic!(\"Path {:?} doesn't exist when it should\", path.as_ref());\n\n }\n\n}\n\n\n", "file_path": "tools/sdk-sync/tests/e2e_test.rs", "rank": 25, "score": 312523.0220321064 }, { "content": "#[track_caller]\n\npub fn assert_ok(inp: Result<(), ProtocolTestFailure>) {\n\n match inp {\n\n Ok(_) => (),\n\n Err(e) => {\n\n eprintln!(\"{}\", e);\n\n panic!(\"Protocol test failed\");\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/lib.rs", "rank": 26, "score": 312398.2246541719 }, { "content": "fn assert_send_fut<T: Send + 'static>(_: T) {}\n", "file_path": "aws/sdk/integration-tests/kms/tests/sensitive-it.rs", "rank": 27, "score": 312161.4183753024 }, { "content": "fn noarg_is_send_sync<T: Send + Sync>() {}\n\n\n\n// Statically check that a fully type-erased client is still Send + Sync.\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 28, "score": 309661.2137833611 }, { "content": "fn repo_root() -> &'static Path {\n\n REPO_ROOT.as_path()\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 29, "score": 309031.2629813605 }, { "content": "/// Confirms that cargo exists on the path.\n\npub fn confirm_installed_on_path() -> Result<()> {\n\n handle_failure(\n\n \"discover cargo version\",\n\n &Command::new(\"cargo\")\n\n .arg(\"version\")\n\n .output()\n\n .context(\"cargo is not installed on the PATH\")?,\n\n )\n\n .context(\"cargo is not installed on the PATH\")\n\n}\n", "file_path": "tools/publisher/src/cargo.rs", "rank": 30, "score": 307645.17223767145 }, { "content": "/// Resolve the AWS Endpoint for a given region\n\n///\n\n/// To provide a static endpoint, [`Endpoint`](aws_smithy_http::endpoint::Endpoint) implements this trait.\n\n/// Example usage:\n\n/// ```rust\n\n/// # mod dynamodb {\n\n/// # use aws_types::endpoint::ResolveAwsEndpoint;\n\n/// # pub struct ConfigBuilder;\n\n/// # impl ConfigBuilder {\n\n/// # pub fn endpoint(&mut self, resolver: impl ResolveAwsEndpoint + 'static) {\n\n/// # // ...\n\n/// # }\n\n/// # }\n\n/// # pub struct Config;\n\n/// # impl Config {\n\n/// # pub fn builder() -> ConfigBuilder {\n\n/// # ConfigBuilder\n\n/// # }\n\n/// # }\n\n/// # }\n\n/// use aws_smithy_http::endpoint::Endpoint;\n\n/// use http::Uri;\n\n/// let config = dynamodb::Config::builder()\n\n/// .endpoint(\n\n/// Endpoint::immutable(Uri::from_static(\"http://localhost:8080\"))\n\n/// );\n\n/// ```\n\n/// Each AWS service generates their own implementation of `ResolveAwsEndpoint`.\n\npub trait ResolveAwsEndpoint: Send + Sync + Debug {\n\n /// Resolves the AWS endpoint for a given region.\n\n // TODO(https://github.com/awslabs/smithy-rs/issues/866): Create `ResolveEndpointError`\n\n fn resolve_endpoint(&self, region: &Region) -> Result<AwsEndpoint, BoxError>;\n\n}\n\n\n\n/// The scope for AWS credentials.\n\n#[derive(Clone, Default, Debug)]\n\npub struct CredentialScope {\n\n region: Option<SigningRegion>,\n\n service: Option<SigningService>,\n\n}\n\n\n\nimpl CredentialScope {\n\n /// Creates a builder for [`CredentialScope`].\n\n pub fn builder() -> credential_scope::Builder {\n\n credential_scope::Builder::default()\n\n }\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-types/src/endpoint.rs", "rank": 31, "score": 307475.41171868425 }, { "content": "/// Provide a [`Region`](Region) to use with AWS requests\n\n///\n\n/// For most cases [`default_provider`](crate::default_provider::region::default_provider) will be the best option, implementing\n\n/// a standard provider chain.\n\npub trait ProvideRegion: Send + Sync + Debug {\n\n /// Load a region from this provider\n\n fn region(&self) -> future::ProvideRegion<'_>;\n\n}\n\n\n\nimpl ProvideRegion for Region {\n\n fn region(&self) -> future::ProvideRegion<'_> {\n\n future::ProvideRegion::ready(Some(self.clone()))\n\n }\n\n}\n\n\n\nimpl<'a> ProvideRegion for &'a Region {\n\n fn region(&self) -> future::ProvideRegion<'_> {\n\n future::ProvideRegion::ready(Some((*self).clone()))\n\n }\n\n}\n\n\n\nimpl ProvideRegion for Box<dyn ProvideRegion> {\n\n fn region(&self) -> future::ProvideRegion<'_> {\n\n self.as_ref().region()\n", "file_path": "aws/rust-runtime/aws-config/src/meta/region.rs", "rank": 32, "score": 307441.16530671576 }, { "content": "/// Asynchronous Credentials Provider\n\npub trait ProvideCredentials: Send + Sync + Debug {\n\n /// Returns a future that provides credentials.\n\n fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>\n\n where\n\n Self: 'a;\n\n}\n\n\n\nimpl ProvideCredentials for Credentials {\n\n fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>\n\n where\n\n Self: 'a,\n\n {\n\n future::ProvideCredentials::ready(Ok(self.clone()))\n\n }\n\n}\n\n\n\nimpl ProvideCredentials for Arc<dyn ProvideCredentials> {\n\n fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>\n\n where\n\n Self: 'a,\n", "file_path": "aws/rust-runtime/aws-types/src/credentials/provider.rs", "rank": 33, "score": 307429.1142417055 }, { "content": "#[track_caller]\n\npub fn assert_uris_match(left: &Uri, right: &Uri) {\n\n if left == right {\n\n return;\n\n }\n\n assert_eq!(left.authority(), right.authority());\n\n assert_eq!(left.scheme(), right.scheme());\n\n assert_eq!(left.path(), right.path());\n\n assert_eq!(\n\n extract_params(left),\n\n extract_params(right),\n\n \"Query parameters did not match. left: {}, right: {}\",\n\n left,\n\n right\n\n );\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/lib.rs", "rank": 34, "score": 307097.6189811263 }, { "content": "/// Unescape XML encoded characters\n\n///\n\n/// This function will unescape the 4 literal escapes:\n\n/// - `&lt;`, `&gt;`, `&amp;`, `&quot;`, and `&apos;`\n\n/// - Decimal escapes: `&#123;`\n\n/// - Hex escapes: `&#xD;`\n\n///\n\n/// If no escape sequences are present, Cow<&'str> will be returned, avoiding the need\n\n/// to copy the String.\n\npub fn unescape(s: &str) -> Result<Cow<str>, XmlError> {\n\n // no &, no need to escape anything\n\n if !s.contains('&') {\n\n return Ok(Cow::Borrowed(s));\n\n }\n\n // this will be strictly larger than required avoiding the need for another allocation\n\n let mut res = String::with_capacity(s.len());\n\n // could consider memchr as performance optimization\n\n let mut sections = s.split('&');\n\n // push content before the first &\n\n if let Some(prefix) = sections.next() {\n\n res.push_str(prefix);\n\n }\n\n for section in sections {\n\n // entities look like &<somedata>;\n\n match section.find(';') {\n\n Some(idx) => {\n\n let entity = &section[..idx];\n\n match entity {\n\n \"lt\" => res.push('<'),\n", "file_path": "rust-runtime/aws-smithy-xml/src/unescape.rs", "rank": 35, "score": 306118.80553079944 }, { "content": "fn hydrate_template(template_string: &str, sdk_version: &Version, msrv: &str) -> Result<String> {\n\n let reg = Handlebars::new();\n\n reg.render_template(\n\n template_string,\n\n &json!({\n\n \"sdk_version\": format!(\"{}\", sdk_version),\n\n \"msrv\": msrv\n\n }),\n\n )\n\n .context(\"Failed to hydrate README template\")\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::hydrate_template;\n\n use semver::Version;\n\n\n\n #[test]\n\n fn test_hydrate() {\n\n let hydrated = hydrate_template(\n", "file_path": "tools/publisher/src/subcommand/hydrate_readme.rs", "rank": 36, "score": 305848.9314428388 }, { "content": " #[async_trait]\n\n trait AnotherTrait: Send + Sync {\n\n async fn creds(&self) -> Credentials;\n\n }\n\n\n\n struct AnotherTraitWrapper<T> {\n\n inner: T,\n\n }\n\n\n\n impl<T> Debug for AnotherTraitWrapper<T> {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"wrapper\")\n\n }\n\n }\n\n\n\n impl<T: AnotherTrait> ProvideCredentials for AnotherTraitWrapper<T> {\n\n fn provide_credentials<'a>(&'a self) -> credentials::future::ProvideCredentials<'a>\n\n where\n\n Self: 'a,\n\n {\n\n credentials::future::ProvideCredentials::new(\n", "file_path": "aws/rust-runtime/aws-config/src/meta/credentials/credential_fn.rs", "rank": 37, "score": 305765.6837614615 }, { "content": "/// Validate that `CHANGELOG.next.toml` follows best practices\n\nfn check_changelog_next(path: impl AsRef<Path>) -> std::result::Result<Changelog, Vec<LintError>> {\n\n let contents = std::fs::read_to_string(path)\n\n .context(\"failed to read CHANGELOG.next\")\n\n .map_err(|e| vec![LintError::via_display(e)])?;\n\n let parsed: Changelog = toml::from_str(&contents)\n\n .context(\"Invalid changelog format\")\n\n .map_err(|e| vec![LintError::via_display(e)])?;\n\n let mut errors = vec![];\n\n for entry in parsed.aws_sdk_rust.iter().chain(parsed.smithy_rs.iter()) {\n\n if let Err(e) = entry.validate() {\n\n errors.push(LintError::via_display(e))\n\n }\n\n }\n\n if errors.is_empty() {\n\n Ok(parsed)\n\n } else {\n\n Err(errors)\n\n }\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/changelog.rs", "rank": 38, "score": 305279.2987911139 }, { "content": "/// Set the default docs.rs anchor block\n\n///\n\n/// `[package.metadata.docs.rs]` is used as the head anchor. A comment `# End of docs.rs metadata` is used\n\n/// as the tail anchor.\n\nfn fix_docs_rs(contents: &str) -> Result<String> {\n\n let mut new = contents.to_string();\n\n replace_anchor(\n\n &mut new,\n\n &(\"[package.metadata.docs.rs]\", \"# End of docs.rs metadata\"),\n\n DEFAULT_DOCS_RS_SECTION,\n\n )?;\n\n Ok(new)\n\n}\n", "file_path": "tools/sdk-lints/src/lint_cargo_toml.rs", "rank": 39, "score": 305010.8628001346 }, { "content": "fn validate_metadata(value: Cow<'static, str>) -> Result<Cow<'static, str>, InvalidMetadataValue> {\n\n fn valid_character(c: char) -> bool {\n\n match c {\n\n _ if c.is_ascii_alphanumeric() => true,\n\n '!' | '#' | '$' | '%' | '&' | '\\'' | '*' | '+' | '-' | '.' | '^' | '_' | '`' | '|'\n\n | '~' => true,\n\n _ => false,\n\n }\n\n }\n\n if !value.chars().all(valid_character) {\n\n return Err(InvalidMetadataValue);\n\n }\n\n Ok(value)\n\n}\n\n\n\n#[doc(hidden)]\n\n/// Additional metadata that can be bundled with framework or feature metadata.\n\n#[derive(Clone, Debug)]\n\n#[non_exhaustive]\n\npub struct AdditionalMetadata {\n", "file_path": "aws/rust-runtime/aws-http/src/user_agent.rs", "rank": 40, "score": 304758.7580078308 }, { "content": "pub fn external_in_fn_input(_one: &SomeStruct, _two: impl SimpleTrait) {}\n\n\n", "file_path": "tools/api-linter/test-workspace/test-crate/src/lib.rs", "rank": 41, "score": 304434.90728907415 }, { "content": "fn acquire_release_from_file(path: &Path) -> Result<Release> {\n\n let parsed = VersionsManifest::from_file(path).context(\"failed to parse versions.toml file\")?;\n\n release_metadata(parsed)\n\n}\n\n\n", "file_path": "tools/publisher/src/subcommand/yank_release.rs", "rank": 42, "score": 303803.02872923174 }, { "content": "/// Returns the file mode (permissions) for the given path\n\nfn file_mode(path: &Path, metadata: &Metadata) -> Result<u32> {\n\n use std::os::unix::fs::PermissionsExt;\n\n\n\n if metadata.file_type().is_symlink() {\n\n let actual_path = std::fs::read_link(path).context(\"follow symlink\")?;\n\n let actual_metadata = std::fs::metadata(&actual_path).context(\"file metadata\")?;\n\n file_mode(&actual_path, &actual_metadata)\n\n } else {\n\n Ok(metadata.permissions().mode())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::FileMetadata;\n\n\n\n #[test]\n\n fn hash_entry() {\n\n let metadata = FileMetadata {\n\n path: \"src/something.rs\".into(),\n\n mode: 0o100644,\n\n sha256: \"521fe5c9ece1aa1f8b66228171598263574aefc6fa4ba06a61747ec81ee9f5a3\".into(),\n\n };\n\n assert_eq!(\"100644 src/something.rs 521fe5c9ece1aa1f8b66228171598263574aefc6fa4ba06a61747ec81ee9f5a3\\n\", metadata.hash_entry());\n\n }\n\n}\n", "file_path": "tools/crate-hasher/src/file_list.rs", "rank": 43, "score": 303187.94953283784 }, { "content": "fn all_cargo_tomls() -> Result<impl Iterator<Item = PathBuf>> {\n\n Ok(all_runtime_crates()?.map(|pkg| pkg.join(\"Cargo.toml\")))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{date_based_release_metadata, version_based_release_metadata};\n\n use time::OffsetDateTime;\n\n\n\n #[test]\n\n fn test_date_based_release_metadata() {\n\n let now = OffsetDateTime::from_unix_timestamp(100_000_000).unwrap();\n\n let result = date_based_release_metadata(now, \"some-manifest.json\");\n\n assert_eq!(\"March 3rd, 1973\", result.title);\n\n assert_eq!(\"release-1973-03-03\", result.tag);\n\n assert_eq!(\"some-manifest.json\", result.manifest_name);\n\n }\n\n\n\n #[test]\n\n fn test_version_based_release_metadata() {\n\n let now = OffsetDateTime::from_unix_timestamp(100_000_000).unwrap();\n\n let result = version_based_release_metadata(now, \"0.11.0\", \"some-other-manifest.json\");\n\n assert_eq!(\"v0.11.0 (March 3rd, 1973)\", result.title);\n\n assert_eq!(\"v0.11.0\", result.tag);\n\n assert_eq!(\"some-other-manifest.json\", result.manifest_name);\n\n }\n\n}\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 44, "score": 301315.8978288244 }, { "content": "fn all_runtime_crates() -> Result<impl Iterator<Item = PathBuf>> {\n\n Ok(aws_runtime_crates()?.chain(smithy_rs_crates()?))\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 45, "score": 301315.8978288244 }, { "content": "fn load_repo_root() -> Result<PathBuf> {\n\n let output = Command::new(\"git\")\n\n .arg(\"rev-parse\")\n\n .arg(\"--show-toplevel\")\n\n .output()\n\n .with_context(|| \"couldn't load repo root\")?;\n\n Ok(PathBuf::from(String::from_utf8(output.stdout)?.trim()))\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 46, "score": 300572.71707482147 }, { "content": "pub fn capture_error(operation_name: &str, output: &Output) -> anyhow::Error {\n\n let message = format!(\n\n \"Failed to {name}:\\nStatus: {status}\\nStdout: {stdout}\\nStderr: {stderr}\\n\",\n\n name = operation_name,\n\n status = if let Some(code) = output.status.code() {\n\n format!(\"{}\", code)\n\n } else {\n\n \"Killed by signal\".to_string()\n\n },\n\n stdout = String::from_utf8_lossy(&output.stdout),\n\n stderr = String::from_utf8_lossy(&output.stderr)\n\n );\n\n anyhow::Error::msg(message)\n\n}\n", "file_path": "tools/smithy-rs-tool-common/src/shell.rs", "rank": 47, "score": 300529.41852578433 }, { "content": "fn check_copyright_header(path: impl AsRef<Path>) -> Vec<LintError> {\n\n if !needs_copyright_header(path.as_ref()) {\n\n return vec![];\n\n }\n\n let contents = match fs::read_to_string(path.as_ref()) {\n\n Ok(contents) => contents,\n\n Err(err) if format!(\"{}\", err).contains(\"No such file or directory\") => {\n\n eprintln!(\"Note: {} does not exist\", path.as_ref().display());\n\n return vec![];\n\n }\n\n Err(e) => return vec![LintError::via_display(e)],\n\n };\n\n if !has_copyright_header(&contents) {\n\n return vec![LintError::new(format!(\n\n \"{} is missing copyright header\",\n\n path.as_ref().display()\n\n ))];\n\n }\n\n return vec![];\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/copyright.rs", "rank": 48, "score": 300527.61567763623 }, { "content": "fn package<T>(path: impl AsRef<Path>) -> Result<std::result::Result<Package<T>, Vec<LintError>>>\n\nwhere\n\n T: DeserializeOwned,\n\n{\n\n let parsed = Manifest::from_path_with_metadata(path).context(\"failed to parse Cargo.toml\")?;\n\n match parsed.package {\n\n Some(package) => Ok(Ok(package)),\n\n None => Ok(Err(vec![LintError::new(\"missing `[package]` section\")])),\n\n }\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/lint_cargo_toml.rs", "rank": 49, "score": 299737.0599717834 }, { "content": "fn aws_runtime_crates() -> Result<impl Iterator<Item = PathBuf>> {\n\n let aws_crate_root = repo_root().join(\"aws\").join(\"rust-runtime\");\n\n Ok(ls(aws_crate_root)?.filter(|path| is_crate(path.as_path())))\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 50, "score": 297836.56532427896 }, { "content": "fn smithy_rs_crates() -> Result<impl Iterator<Item = PathBuf>> {\n\n let smithy_crate_root = repo_root().join(\"rust-runtime\");\n\n Ok(ls(smithy_crate_root)?.filter(|path| is_crate(path.as_path())))\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 51, "score": 297836.56532427896 }, { "content": "pub fn fmt_string<T: AsRef<str>>(t: T) -> String {\n\n utf8_percent_encode(t.as_ref(), BASE_SET).to_string()\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/query.rs", "rank": 52, "score": 294396.5250384793 }, { "content": "/// Escapes a string for embedding in a JSON string value.\n\npub fn escape_string(value: &str) -> Cow<str> {\n\n let bytes = value.as_bytes();\n\n for (index, byte) in bytes.iter().enumerate() {\n\n match byte {\n\n 0..=0x1F | b'\"' | b'\\\\' => {\n\n return Cow::Owned(escape_string_inner(&bytes[0..index], &bytes[index..]))\n\n }\n\n _ => {}\n\n }\n\n }\n\n Cow::Borrowed(value)\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-json/src/escape.rs", "rank": 53, "score": 294022.1924478418 }, { "content": "/// Default Region Provider chain\n\n///\n\n/// This provider will check the following sources in order:\n\n/// 1. [Environment variables](EnvironmentVariableRegionProvider)\n\n/// 2. [Profile file](crate::profile::region::ProfileFileRegionProvider)\n\n/// 3. [EC2 IMDSv2](crate::imds::region)\n\npub fn default_provider() -> impl ProvideRegion {\n\n Builder::default().build()\n\n}\n\n\n\n/// Default region provider chain\n\n#[derive(Debug)]\n\npub struct DefaultRegionChain(RegionProviderChain);\n\n\n\nimpl DefaultRegionChain {\n\n /// Load a region from this chain\n\n pub async fn region(&self) -> Option<Region> {\n\n self.0.region().await\n\n }\n\n\n\n /// Builder for [`DefaultRegionChain`]\n\n pub fn builder() -> Builder {\n\n Builder::default()\n\n }\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/default_provider/region.rs", "rank": 54, "score": 292018.97755075357 }, { "content": "/// Assert that two XML documents are equivalent\n\n///\n\n/// This will normalize documents and attempts to determine if it is OK to sort members or not by\n\n/// using a heuristic to determine if the tag represents a list (which should not be reordered)\n\npub fn try_xml_equivalent(actual: &str, expected: &str) -> Result<(), ProtocolTestFailure> {\n\n let norm_1 = normalize_xml(actual).map_err(|e| ProtocolTestFailure::InvalidBodyFormat {\n\n expected: \"actual document to be valid XML\".to_string(),\n\n found: format!(\"{}\\n{}\", e, actual),\n\n })?;\n\n let norm_2 = normalize_xml(expected).map_err(|e| ProtocolTestFailure::InvalidBodyFormat {\n\n expected: \"expected document to be valid XML\".to_string(),\n\n found: format!(\"{}\", e),\n\n })?;\n\n if norm_1 == norm_2 {\n\n Ok(())\n\n } else {\n\n Err(ProtocolTestFailure::BodyDidNotMatch {\n\n comparison: pretty_comparison(&norm_1, &norm_2),\n\n hint: \"\".to_string(),\n\n })\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/xml.rs", "rank": 55, "score": 291503.11514113325 }, { "content": "fn load_vcs_files() -> Result<Vec<PathBuf>> {\n\n let tracked_files = Command::new(\"git\")\n\n .arg(\"ls-tree\")\n\n .arg(\"-r\")\n\n .arg(\"HEAD\")\n\n .arg(\"--name-only\")\n\n .current_dir(load_repo_root()?)\n\n .output()\n\n .context(\"couldn't load VCS tracked files\")?;\n\n let mut output = String::from_utf8(tracked_files.stdout)?;\n\n let changed_files = Command::new(\"git\")\n\n .arg(\"diff\")\n\n .arg(\"--name-only\")\n\n .output()?;\n\n output.push_str(std::str::from_utf8(changed_files.stdout.as_slice())?);\n\n let files = output\n\n .lines()\n\n .map(|line| PathBuf::from(line.trim().to_string()));\n\n Ok(files.collect())\n\n}\n\n\n\nlazy_static! {\n\n static ref REPO_ROOT: PathBuf = load_repo_root().unwrap();\n\n static ref VCS_FILES: Vec<PathBuf> = load_vcs_files().unwrap();\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/main.rs", "rank": 56, "score": 288891.2144559798 }, { "content": "fn pretty_comparison(left: &str, right: &str) -> PrettyString {\n\n PrettyString(format!(\n\n \"{}\",\n\n Comparison::new(&PrettyStr(left), &PrettyStr(right))\n\n ))\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/lib.rs", "rank": 57, "score": 288466.2461074706 }, { "content": "/// Strip the /hostedzone/ prefix from zone-id\n\npub fn trim_hosted_zone(zone: &mut Option<String>) {\n\n const PREFIXES: &[&str; 2] = &[\"/hostedzone/\", \"hostedzone/\"];\n\n\n\n for prefix in PREFIXES {\n\n if let Some(core_zone) = zone.as_deref().unwrap_or_default().strip_prefix(prefix) {\n\n *zone = Some(core_zone.to_string());\n\n return;\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::hosted_zone_preprocessor::trim_hosted_zone;\n\n\n\n struct OperationInput {\n\n hosted_zone: Option<String>,\n\n }\n\n\n\n #[test]\n", "file_path": "aws/rust-runtime/aws-inlineable/src/hosted_zone_preprocessor.rs", "rank": 58, "score": 287422.479859064 }, { "content": "/// Async trait with a `sleep` function.\n\npub trait AsyncSleep: std::fmt::Debug + Send + Sync {\n\n /// Returns a future that sleeps for the given `duration` of time.\n\n fn sleep(&self, duration: Duration) -> Sleep;\n\n}\n\n\n\nimpl<T> AsyncSleep for Box<T>\n\nwhere\n\n T: AsyncSleep,\n\n T: ?Sized,\n\n{\n\n fn sleep(&self, duration: Duration) -> Sleep {\n\n T::sleep(self, duration)\n\n }\n\n}\n\n\n\nimpl<T> AsyncSleep for Arc<T>\n\nwhere\n\n T: AsyncSleep,\n\n T: ?Sized,\n\n{\n\n fn sleep(&self, duration: Duration) -> Sleep {\n\n T::sleep(self, duration)\n\n }\n\n}\n\n\n\n#[cfg(feature = \"rt-tokio\")]\n", "file_path": "rust-runtime/aws-smithy-async/src/rt/sleep.rs", "rank": 59, "score": 285772.62000313343 }, { "content": "#[async_trait]\n\npub trait Handler<B, T, Fut>: Clone + Send + Sized + 'static {\n\n #[doc(hidden)]\n\n type Sealed: sealed::HiddenTrait;\n\n\n\n async fn call(self, req: Request<B>) -> Response<BoxBody>;\n\n}\n", "file_path": "rust-runtime/inlineable/src/server_operation_handler_trait.rs", "rank": 60, "score": 285088.21836744546 }, { "content": "fn check_crate_license(package: Package, path: impl AsRef<Path>) -> Result<Vec<LintError>> {\n\n let mut errors = vec![];\n\n match package.license {\n\n Some(license) if license == \"Apache-2.0\" => {}\n\n incorrect_license => errors.push(LintError::new(format!(\n\n \"invalid license: {:?}\",\n\n incorrect_license\n\n ))),\n\n };\n\n if !path\n\n .as_ref()\n\n .parent()\n\n .expect(\"path must have parent\")\n\n .join(\"LICENSE\")\n\n .exists()\n\n {\n\n errors.push(LintError::new(\"LICENSE file missing\"));\n\n }\n\n Ok(errors)\n\n}\n", "file_path": "tools/sdk-lints/src/lint_cargo_toml.rs", "rank": 61, "score": 281674.664220745 }, { "content": "fn not_pub_external_in_fn_input(_one: &SomeStruct, _two: impl SimpleTrait) {}\n\n\n", "file_path": "tools/api-linter/test-workspace/test-crate/src/lib.rs", "rank": 62, "score": 281372.1463125976 }, { "content": "/// Conditionally quotes and escapes a header value if the header value contains a comma or quote.\n\npub fn quote_header_value<'a>(value: impl Into<Cow<'a, str>>) -> Cow<'a, str> {\n\n let value = value.into();\n\n if value.trim().len() != value.len()\n\n || value.contains('\"')\n\n || value.contains(',')\n\n || value.contains('(')\n\n || value.contains(')')\n\n {\n\n Cow::Owned(format!(\n\n \"\\\"{}\\\"\",\n\n value.replace('\\\\', \"\\\\\\\\\").replace('\"', \"\\\\\\\"\")\n\n ))\n\n } else {\n\n value\n\n }\n\n}\n\n\n\n/// Given two [`HeaderMap`][HeaderMap]s, merge them together and return the merged `HeaderMap`. If the\n\n/// two `HeaderMap`s share any keys, values from the right `HeaderMap` be appended to the left `HeaderMap`.\n\npub(crate) fn append_merge_header_maps(\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 63, "score": 281039.8432591505 }, { "content": "pub fn fmt_string<T: AsRef<str>>(t: T, greedy: bool) -> String {\n\n let uri_set = if greedy { GREEDY } else { BASE_SET };\n\n percent_encoding::utf8_percent_encode(t.as_ref(), uri_set).to_string()\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/label.rs", "rank": 64, "score": 277959.0423431264 }, { "content": "/// Given a `location`, this function looks for the `aws-sdk-rust` git repository. If found,\n\n/// it resolves the `sdk/` directory. Otherwise, it returns the original `location`.\n\npub fn resolve_publish_location(location: &Path) -> PathBuf {\n\n match Repository::new(SDK_REPO_NAME, location) {\n\n // If the given path was the `aws-sdk-rust` repo root, then resolve the `sdk/` directory to publish from\n\n Ok(sdk_repo) => sdk_repo.root.join(SDK_REPO_CRATE_PATH),\n\n // Otherwise, publish from the given path (likely the smithy-rs runtime bundle)\n\n Err(_) => location.into(),\n\n }\n\n}\n", "file_path": "tools/publisher/src/repo.rs", "rank": 65, "score": 277954.6502680318 }, { "content": "fn add_header(map: &mut HeaderMap<HeaderValue>, key: &'static str, value: &str) {\n\n map.insert(key, HeaderValue::try_from(value).expect(key));\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-sigv4/src/http_request/sign.rs", "rank": 66, "score": 276619.4525997353 }, { "content": "fn try_json_eq(actual: &str, expected: &str) -> Result<(), ProtocolTestFailure> {\n\n let actual_json: serde_json::Value =\n\n serde_json::from_str(actual).map_err(|e| ProtocolTestFailure::InvalidBodyFormat {\n\n expected: \"json\".to_owned(),\n\n found: e.to_string() + actual,\n\n })?;\n\n let expected_json: serde_json::Value =\n\n serde_json::from_str(expected).expect(\"expected value must be valid JSON\");\n\n match assert_json_eq_no_panic(&actual_json, &expected_json) {\n\n Ok(()) => Ok(()),\n\n Err(message) => Err(ProtocolTestFailure::BodyDidNotMatch {\n\n comparison: pretty_comparison(actual, expected),\n\n hint: message,\n\n }),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/lib.rs", "rank": 67, "score": 274075.80028898874 }, { "content": "/// Ensure that there are no uncommited changes to the changelog\n\nfn no_uncommited_changes(path: &Path) -> Result<()> {\n\n let unstaged = !Command::new(\"git\")\n\n .arg(\"diff\")\n\n .arg(\"--exit-code\")\n\n .arg(path)\n\n .status()?\n\n .success();\n\n let staged = !Command::new(\"git\")\n\n .arg(\"diff\")\n\n .arg(\"--exit-code\")\n\n .arg(\"--staged\")\n\n .arg(path)\n\n .status()?\n\n .success();\n\n if unstaged || staged {\n\n bail!(\"Uncommitted changes to {}\", path.display())\n\n }\n\n Ok(())\n\n}\n\n\n\npub struct ReleaseMetadata {\n\n pub title: String,\n\n pub tag: String,\n\n pub manifest_name: String,\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/changelog.rs", "rank": 68, "score": 271152.38366773335 }, { "content": "pub fn external_in_fn_output() -> SomeStruct {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "tools/api-linter/test-workspace/test-crate/src/lib.rs", "rank": 69, "score": 267175.7574493881 }, { "content": "pub fn deserialize_string_list(\n\n decoder: &mut ScopedDecoder,\n\n) -> Result<std::vec::Vec<std::string::String>, XmlError> {\n\n let mut out = std::vec::Vec::new();\n\n while let Some(mut tag) = decoder.next_tag() {\n\n match dbg!(tag.start_el()) {\n\n s if s.matches(\"member\") => {\n\n out.push(dbg!({\n\n aws_smithy_xml::decode::try_data(&mut tag)?.to_string()\n\n }));\n\n }\n\n _ => {}\n\n };\n\n }\n\n println!(\"done\");\n\n Ok(out)\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-xml/tests/handwritten_parsers.rs", "rank": 70, "score": 266684.37072470214 }, { "content": "/// Writes the given `headers` to a `buffer`.\n\npub fn write_headers_to<B: BufMut>(headers: &[Header], mut buffer: B) -> Result<(), Error> {\n\n for header in headers {\n\n header.write_to(&mut buffer)?;\n\n }\n\n Ok(())\n\n}\n\n\n\n/// Event Stream message.\n\n#[non_exhaustive]\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct Message {\n\n headers: Vec<Header>,\n\n payload: Bytes,\n\n}\n\n\n\nimpl Message {\n\n /// Creates a new message with the given `payload`. Headers can be added later.\n\n pub fn new(payload: impl Into<Bytes>) -> Message {\n\n Message {\n\n headers: Vec::new(),\n", "file_path": "rust-runtime/aws-smithy-eventstream/src/frame.rs", "rank": 71, "score": 265315.5319768742 }, { "content": "fun patchFile(path: File, operation: (String) -> String) {\n\n val patchedContents = path.readLines().joinToString(\"\\n\", transform = operation)\n\n path.writeText(patchedContents)\n\n}\n", "file_path": "buildSrc/src/main/kotlin/ManifestPatcher.kt", "rank": 72, "score": 264087.3012551937 }, { "content": "fn render_handauthored<'a>(entries: impl Iterator<Item = &'a HandAuthoredEntry>, out: &mut String) {\n\n let (breaking, non_breaking) = entries.partition::<Vec<_>, _>(|entry| entry.meta.breaking);\n\n\n\n if !breaking.is_empty() {\n\n out.push_str(\"**Breaking Changes:**\\n\");\n\n for change in breaking {\n\n change.render(out);\n\n out.push('\\n');\n\n }\n\n out.push('\\n')\n\n }\n\n\n\n if !non_breaking.is_empty() {\n\n out.push_str(\"**New this release:**\\n\");\n\n for change in non_breaking {\n\n change.render(out);\n\n out.push('\\n');\n\n }\n\n out.push('\\n');\n\n }\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/changelog.rs", "rank": 73, "score": 263316.4444483045 }, { "content": "pub fn deserialize_nested_string_list(\n\n decoder: &mut ScopedDecoder,\n\n) -> Result<std::vec::Vec<std::vec::Vec<std::string::String>>, XmlError> {\n\n let mut out = std::vec::Vec::new();\n\n while let Some(mut tag) = decoder.next_tag() {\n\n match tag.start_el() {\n\n s if s.matches(\"member\") => {\n\n out.push(deserialize_string_list(&mut tag)?);\n\n }\n\n _ => {}\n\n }\n\n }\n\n Ok(out)\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-xml/tests/handwritten_parsers.rs", "rank": 74, "score": 263073.73100692965 }, { "content": "pub fn fmt_timestamp(t: &DateTime, format: Format) -> Result<String, DateTimeFormatError> {\n\n Ok(crate::query::fmt_string(t.fmt(format)?))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::label::fmt_string;\n\n use http::Uri;\n\n use proptest::proptest;\n\n\n\n #[test]\n\n fn greedy_params() {\n\n assert_eq!(fmt_string(\"a/b\", false), \"a%2Fb\");\n\n assert_eq!(fmt_string(\"a/b\", true), \"a/b\");\n\n }\n\n\n\n proptest! {\n\n #[test]\n\n fn test_encode_request(s: String) {\n\n let _: Uri = format!(\"http://host.example.com/{}\", fmt_string(&s, false)).parse().expect(\"all strings should be encoded properly\");\n\n let _: Uri = format!(\"http://host.example.com/{}\", fmt_string(&s, true)).parse().expect(\"all strings should be encoded properly\");\n\n }\n\n }\n\n}\n", "file_path": "rust-runtime/aws-smithy-http/src/label.rs", "rank": 75, "score": 259832.29682034894 }, { "content": "pub fn fmt_timestamp(t: &DateTime, format: Format) -> Result<String, DateTimeFormatError> {\n\n Ok(fmt_string(t.fmt(format)?))\n\n}\n\n\n\n/// Simple abstraction to enable appending params to a string as query params\n\n///\n\n/// ```rust\n\n/// use aws_smithy_http::query::Writer;\n\n/// let mut s = String::from(\"www.example.com\");\n\n/// let mut q = Writer::new(&mut s);\n\n/// q.push_kv(\"key\", \"value\");\n\n/// q.push_v(\"another_value\");\n\n/// assert_eq!(s, \"www.example.com?key=value&another_value\");\n\n/// ```\n\npub struct Writer<'a> {\n\n out: &'a mut String,\n\n prefix: char,\n\n}\n\n\n\nimpl<'a> Writer<'a> {\n", "file_path": "rust-runtime/aws-smithy-http/src/query.rs", "rank": 76, "score": 259832.29682034894 }, { "content": "pub fn main() -> Result<()> {\n\n let file_list = FileList::discover(&Args::parse().location)?;\n\n println!(\"{}\", file_list.sha256());\n\n Ok(())\n\n}\n", "file_path": "tools/crate-hasher/src/main.rs", "rank": 77, "score": 259778.72935480828 }, { "content": "/// Expects and parses a complete document value.\n\npub fn expect_document<'a, I>(tokens: &mut Peekable<I>) -> Result<Document, Error>\n\nwhere\n\n I: Iterator<Item = Result<Token<'a>, Error>>,\n\n{\n\n expect_document_inner(tokens, 0)\n\n}\n\n\n\nconst MAX_DOCUMENT_RECURSION: usize = 256;\n\n\n", "file_path": "rust-runtime/aws-smithy-json/src/deserialize/token.rs", "rank": 78, "score": 259685.68034017674 }, { "content": "fn remove_trailing_zeros(string: &mut String) {\n\n while let Some(b'0') = string.as_bytes().last() {\n\n string.pop();\n\n }\n\n}\n\n\n\npub(crate) mod epoch_seconds {\n\n use super::remove_trailing_zeros;\n\n use super::DateTimeParseError;\n\n use crate::DateTime;\n\n use std::str::FromStr;\n\n\n\n /// Formats a `DateTime` into the Smithy epoch seconds date-time format.\n\n pub(crate) fn format(date_time: &DateTime) -> String {\n\n if date_time.subsecond_nanos == 0 {\n\n format!(\"{}\", date_time.seconds)\n\n } else {\n\n let mut result = format!(\"{}.{:0>9}\", date_time.seconds, date_time.subsecond_nanos);\n\n remove_trailing_zeros(&mut result);\n\n result\n", "file_path": "rust-runtime/aws-smithy-types/src/date_time/format.rs", "rank": 79, "score": 258268.05528614728 }, { "content": "fn warn_if_unsupported_timeout_is_set(profile: &Profile, var: &'static str) {\n\n if profile.get(var).is_some() {\n\n tracing::warn!(\n\n \"Profile '{}' set {} timeout but that feature is currently unimplemented so the setting will be ignored. \\\n\n To help us prioritize support for this feature, please upvote aws-sdk-rust#151 (https://github.com/awslabs/aws-sdk-rust/issues/151)\",\n\n profile.name(),\n\n var\n\n )\n\n }\n\n}\n", "file_path": "aws/rust-runtime/aws-config/src/profile/timeout_config.rs", "rank": 80, "score": 256608.03559797624 }, { "content": "fn warn_if_unsupported_timeout_is_set(env: &Env, var: &'static str) {\n\n if env.get(var).is_ok() {\n\n tracing::warn!(\n\n \"Environment variable for '{}' timeout was set but that feature is currently unimplemented so the setting will be ignored. \\\n\n To help us prioritize support for this feature, please upvote aws-sdk-rust#151 (https://github.com/awslabs/aws-sdk-rust/issues/151)\",\n\n var\n\n )\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::{\n\n EnvironmentVariableTimeoutConfigProvider, ENV_VAR_API_CALL_ATTEMPT_TIMEOUT,\n\n ENV_VAR_API_CALL_TIMEOUT,\n\n };\n\n use aws_smithy_types::timeout;\n\n use aws_smithy_types::tristate::TriState;\n\n use aws_types::os_shim_internal::Env;\n\n use std::time::Duration;\n", "file_path": "aws/rust-runtime/aws-config/src/environment/timeout_config.rs", "rank": 81, "score": 256608.0355979762 }, { "content": "fn deserialize_xml_map(inp: &str) -> Result<XmlMap, XmlError> {\n\n let mut doc = Document::new(inp);\n\n let mut root = doc.root_element()?;\n\n let mut my_map: Option<HashMap<String, FooEnum>> = None;\n\n while let Some(mut tag) = root.next_tag() {\n\n if tag.start_el().matches(\"values\") {\n\n my_map = Some(deserialize_foo_enum_map(&mut tag)?);\n\n }\n\n }\n\n Ok(XmlMap {\n\n values: my_map.ok_or_else(|| XmlError::custom(\"missing map\"))?,\n\n })\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-xml/tests/handwritten_parsers.rs", "rank": 82, "score": 256105.44415016513 }, { "content": "fn deserialize_xml_attribute(inp: &str) -> Result<XmlAttribute, XmlError> {\n\n let mut doc = Document::new(inp);\n\n let mut root = doc.root_element()?;\n\n #[allow(unused_assignments)]\n\n let mut foo: Option<String> = None;\n\n let mut bar: Option<String> = None;\n\n foo = root.start_el().attr(\"foo\").map(|attr| attr.to_string());\n\n while let Some(mut tag) = root.next_tag() {\n\n if tag.start_el().matches(\"bar\") {\n\n bar = Some(try_data(&mut tag)?.to_string());\n\n }\n\n }\n\n Ok(XmlAttribute {\n\n foo: foo.ok_or_else(|| XmlError::custom(\"missing foo\"))?,\n\n bar: bar.ok_or_else(|| XmlError::custom(\"missing bar\"))?,\n\n })\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-xml/tests/handwritten_parsers.rs", "rank": 83, "score": 256105.44415016513 }, { "content": "/// Determine the SSO token path for a given start_url\n\nfn sso_token_path(start_url: &str, home: &str) -> PathBuf {\n\n // hex::encode returns a lowercase string\n\n let mut out = PathBuf::with_capacity(home.len() + \"/.aws/sso/cache\".len() + \".json\".len() + 40);\n\n out.push(home);\n\n out.push(\".aws/sso/cache\");\n\n out.push(&hex::encode(digest::digest(\n\n &digest::SHA1_FOR_LEGACY_USE_ONLY,\n\n start_url.as_bytes(),\n\n )));\n\n out.set_extension(\"json\");\n\n out\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::json_credentials::InvalidJsonCredentials;\n\n use crate::sso::{load_token, parse_token_json, sso_token_path, LoadTokenError, SsoToken};\n\n use aws_smithy_types::DateTime;\n\n use aws_types::os_shim_internal::{Env, Fs};\n\n use aws_types::region::Region;\n", "file_path": "aws/rust-runtime/aws-config/src/sso.rs", "rank": 84, "score": 255686.8418554362 }, { "content": "pub fn external_in_fn_output_generic() -> Option<SomeStruct> {\n\n unimplemented!()\n\n}\n\n\n\n// Try to trick api-linter here by putting something in a private module and re-exporting it\n\nmod private_module {\n\n use external_lib::SomeStruct;\n\n\n\n pub fn something(_one: &SomeStruct) {}\n\n}\n\npub use private_module::something;\n\n\n\npub struct StructWithExternalFields {\n\n pub field: SomeStruct,\n\n pub optional_field: Option<SomeStruct>,\n\n}\n\n\n\nimpl StructWithExternalFields {\n\n pub fn new(_field: impl Into<SomeStruct>, _optional_field: Option<SomeOtherStruct>) -> Self {\n\n unimplemented!()\n\n }\n\n}\n\n\n", "file_path": "tools/api-linter/test-workspace/test-crate/src/lib.rs", "rank": 85, "score": 255645.15677702788 }, { "content": "fn log_command(command: Command) -> Command {\n\n let mut message = String::new();\n\n if let Some(cwd) = command.get_current_dir() {\n\n message.push_str(&format!(\"[in {:?}]: \", cwd));\n\n }\n\n message.push_str(command.get_program().to_str().expect(\"valid str\"));\n\n for arg in command.get_args() {\n\n message.push(' ');\n\n message.push_str(arg.to_str().expect(\"valid str\"));\n\n }\n\n debug!(\"{}\", message);\n\n command\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::env;\n\n\n\n fn bin_path(script: &'static str) -> PathBuf {\n", "file_path": "tools/sdk-sync/src/git.rs", "rank": 86, "score": 254186.0750647405 }, { "content": "/// Prepare a line for parsing\n\n///\n\n/// Because leading whitespace is significant, this method should only be called after determining\n\n/// whether a line represents a property (no whitespace) or a sub-property (whitespace).\n\n/// This function preprocesses a line to simplify parsing:\n\n/// 1. Strip leading and trailing whitespace\n\n/// 2. Remove trailing comments\n\n///\n\n/// Depending on context, comment characters may need to be preceded by whitespace to be considered\n\n/// comments.\n\nfn prepare_line(line: &str, comments_need_whitespace: bool) -> &str {\n\n let line = line.trim_matches(WHITESPACE);\n\n let mut prev_char_whitespace = false;\n\n let mut comment_idx = None;\n\n for (idx, chr) in line.char_indices() {\n\n if (COMMENT.contains(&chr)) && (prev_char_whitespace || !comments_need_whitespace) {\n\n comment_idx = Some(idx);\n\n break;\n\n }\n\n prev_char_whitespace = chr.is_whitespace();\n\n }\n\n comment_idx\n\n .map(|idx| &line[..idx])\n\n .unwrap_or(line)\n\n // trimming the comment might result in more whitespace that needs to be handled\n\n .trim_matches(WHITESPACE)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/parse.rs", "rank": 87, "score": 253694.1159449973 }, { "content": "/// Decode `input` from base64 using the standard base64 alphabet\n\n///\n\n/// If input is not a valid base64 encoded string, this function will return `DecodeError`.\n\npub fn decode<T: AsRef<str>>(input: T) -> Result<Vec<u8>, DecodeError> {\n\n decode_inner(input.as_ref())\n\n}\n\n\n\n/// Failure to decode a base64 value.\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\n#[non_exhaustive]\n\npub enum DecodeError {\n\n /// Encountered an invalid byte.\n\n InvalidByte,\n\n /// Encountered an invalid base64 padding value.\n\n InvalidPadding,\n\n /// Input wasn't long enough to be a valid base64 value.\n\n InvalidLength,\n\n}\n\n\n\nimpl Error for DecodeError {}\n\n\n\nimpl fmt::Display for DecodeError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n use DecodeError::*;\n\n match self {\n\n InvalidByte => write!(f, \"invalid byte\"),\n\n InvalidPadding => write!(f, \"invalid padding\"),\n\n InvalidLength => write!(f, \"invalid length\"),\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-types/src/base64.rs", "rank": 88, "score": 253593.13958164578 }, { "content": "pub fn get_canaries_to_run(clients: Clients, env: CanaryEnv) -> Vec<(&'static str, CanaryFuture)> {\n\n let canaries = vec![\n\n paginator_canary::mk_canary(&clients, &env),\n\n s3_canary::mk_canary(&clients, &env),\n\n transcribe_canary::mk_canary(&clients, &env),\n\n ];\n\n\n\n canaries\n\n .into_iter()\n\n .flatten()\n\n .map(|(name, fut)| {\n\n (\n\n name,\n\n Box::pin(fut.instrument(info_span!(\"run_canary\", name = name))) as _,\n\n )\n\n })\n\n .collect()\n\n}\n\n\n\n#[derive(Clone)]\n", "file_path": "tools/ci-cdk/canary-lambda/src/canary.rs", "rank": 89, "score": 252836.87698240022 }, { "content": "pub fn escape(s: &str) -> Cow<str> {\n\n let mut remaining = s;\n\n if !s.contains(ESCAPES) {\n\n return Cow::Borrowed(s);\n\n }\n\n let mut out = String::new();\n\n while let Some(idx) = remaining.find(ESCAPES) {\n\n out.push_str(&remaining[..idx]);\n\n remaining = &remaining[idx..];\n\n let mut idxs = remaining.char_indices();\n\n let (_, chr) = idxs.next().expect(\"must not be none\");\n\n match chr {\n\n '>' => out.push_str(\"&gt;\"),\n\n '<' => out.push_str(\"&lt;\"),\n\n '\\'' => out.push_str(\"&apos;\"),\n\n '\"' => out.push_str(\"&quot;\"),\n\n '&' => out.push_str(\"&amp;\"),\n\n // push a hex escape sequence\n\n other => {\n\n write!(&mut out, \"&#x{:X};\", other as u32).expect(\"write to string cannot fail\")\n", "file_path": "rust-runtime/aws-smithy-xml/src/escape.rs", "rank": 90, "score": 252807.86195502648 }, { "content": "/// Validate that a string is a valid identifier\n\n///\n\n/// Identifiers must match `[A-Za-z0-9_\\-/.%@:\\+]+`\n\nfn validate_identifier(input: &str) -> Result<&str, ()> {\n\n input\n\n .chars()\n\n .all(|ch| {\n\n ch.is_ascii_alphanumeric()\n\n || ['_', '-', '/', '.', '%', '@', ':', '+']\n\n .iter()\n\n .any(|c| *c == ch)\n\n })\n\n .then(|| input)\n\n .ok_or(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::HashMap;\n\n\n\n use tracing_test::traced_test;\n\n\n\n use crate::profile::parser::parse::RawProfileSet;\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/normalize.rs", "rank": 91, "score": 251492.28473078733 }, { "content": "fn deserialize_flat_xml_map(inp: &str) -> Result<FlatXmlMap, XmlError> {\n\n let mut doc = Document::new(inp);\n\n let mut root = doc.root_element()?;\n\n let mut my_map: Option<HashMap<String, FooEnum>> = None;\n\n while let Some(mut tag) = root.next_tag() {\n\n if tag.start_el().matches(\"myMap\") {\n\n let mut _my_map = my_map.unwrap_or_default();\n\n deserialize_foo_enum_map_entry(&mut tag, &mut _my_map)?;\n\n my_map = Some(_my_map);\n\n }\n\n }\n\n Ok(FlatXmlMap {\n\n my_map: my_map.unwrap(),\n\n })\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-xml/tests/handwritten_parsers.rs", "rank": 92, "score": 250380.3027995763 }, { "content": "fn maintainers() -> Vec<&'static str> {\n\n include_str!(\"../smithy-rs-maintainers.txt\")\n\n .lines()\n\n .collect()\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/changelog.rs", "rank": 93, "score": 249810.834971451 }, { "content": "fn is_comment_line(line: &str) -> bool {\n\n line.starts_with(COMMENT)\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/parse.rs", "rank": 94, "score": 249553.94187786305 }, { "content": "fn is_empty_line(line: &str) -> bool {\n\n line.trim_matches(WHITESPACE).is_empty()\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/parse.rs", "rank": 95, "score": 249553.94187786305 }, { "content": "fn needs_copyright_header(path: &Path) -> bool {\n\n let mut need_extensions = NEEDS_HEADER.iter().map(OsStr::new);\n\n need_extensions.any(|extension| path.extension().unwrap_or_default() == extension)\n\n}\n\n\n", "file_path": "tools/sdk-lints/src/copyright.rs", "rank": 96, "score": 249157.93791432335 }, { "content": "pub fn main() -> anyhow::Result<()> {\n\n let opt = Args::parse().validate()?;\n\n\n\n let start_time = Instant::now();\n\n let mut manifest_paths = Vec::new();\n\n for crate_path in &opt.crate_paths {\n\n discover_manifests(&mut manifest_paths, crate_path)?;\n\n }\n\n\n\n for manifest_path in manifest_paths {\n\n update_manifest(&manifest_path, &opt)?;\n\n }\n\n\n\n println!(\"Finished in {:?}\", start_time.elapsed());\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/sdk-versioner/src/v1.rs", "rank": 97, "score": 248753.42739192996 }, { "content": "fn fix_dep_sets(versions: &BTreeMap<String, Version>, metadata: &mut toml::Value) -> Result<usize> {\n\n let mut changed = fix_dep_set(versions, \"dependencies\", metadata)?;\n\n changed += fix_dep_set(versions, \"dev-dependencies\", metadata)?;\n\n changed += fix_dep_set(versions, \"build-dependencies\", metadata)?;\n\n Ok(changed)\n\n}\n\n\n", "file_path": "tools/publisher/src/subcommand/fix_manifests.rs", "rank": 98, "score": 248388.85494187486 }, { "content": "fn rewrite_url_encoded_map_keys(input: &str) -> (String, String) {\n\n let mut itr = input.split('=');\n\n let (key, value) = (itr.next().unwrap(), itr.next().unwrap());\n\n\n\n let regex = Regex::new(r\"^(.+)\\.\\d+\\.(.+)$\").unwrap();\n\n if let Some(captures) = regex.captures(key) {\n\n let rewritten_key = format!(\n\n \"{}.N.{}\",\n\n captures.get(1).unwrap().as_str(),\n\n captures.get(2).unwrap().as_str()\n\n );\n\n (rewritten_key, value.to_string())\n\n } else {\n\n (key.to_string(), value.to_string())\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/urlencoded.rs", "rank": 99, "score": 246836.11700557868 } ]
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": "exonum/benches/criterion/block.rs", "rank": 0, "score": 384147.1200120703 }, { "content": "fn bench_hash(b: &mut Bencher, &count: &usize) {\n\n let data = (0..count).map(|x| (x % 255) as u8).collect::<Vec<u8>>();\n\n b.iter(|| hash(&data))\n\n}\n\n\n", "file_path": "exonum/benches/criterion/crypto.rs", "rank": 1, "score": 371236.47607601655 }, { "content": "fn proof_list_append(b: &mut Bencher, db: &dyn Database, len: usize) {\n\n let mut rng: StdRng = SeedableRng::from_seed(SEED);\n\n let data = (0..len)\n\n .map(|_| {\n\n let mut chunk = vec![0; CHUNK_SIZE];\n\n rng.fill_bytes(&mut chunk);\n\n chunk\n\n })\n\n .collect::<Vec<_>>();\n\n\n\n b.iter_with_setup(\n\n || db.fork(),\n\n |storage| {\n\n let mut table = ProofListIndex::new(NAME, &storage);\n\n assert!(table.is_empty());\n\n for item in &data {\n\n table.push(item.clone());\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 2, "score": 363640.67052052415 }, { "content": "fn bench_verify_messages_simple(b: &mut Bencher, &size: &usize) {\n\n let messages = gen_messages(MESSAGES_COUNT, size);\n\n b.iter_with_setup(\n\n || messages.clone(),\n\n |messages| {\n\n for message in messages {\n\n let _ = Message::from_raw_buffer(message).unwrap();\n\n }\n\n },\n\n )\n\n}\n\n\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 3, "score": 359896.8832234405 }, { "content": "fn proof_map_insert_with_merge(b: &mut Bencher, db: &dyn Database, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || {\n\n let fork = db.fork();\n\n {\n\n let mut table: ProofMapIndex<_, Hash, Vec<u8>> = ProofMapIndex::new(NAME, &fork);\n\n table.clear();\n\n }\n\n db.merge(fork.into_patch()).unwrap();\n\n },\n\n |_| {\n\n let fork = db.fork();\n\n {\n\n let mut table = ProofMapIndex::new(NAME, &fork);\n\n assert!(table.keys().next().is_none());\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n }\n\n db.merge(fork.into_patch()).unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 4, "score": 358807.26733036153 }, { "content": "fn bench_verify_messages_event_loop(b: &mut Bencher, &size: &usize) {\n\n let messages = gen_messages(MESSAGES_COUNT, size);\n\n\n\n let verifier = MessageVerifier::new();\n\n let mut core = Core::new().unwrap();\n\n\n\n b.iter_with_setup(\n\n || messages.clone(),\n\n |messages| {\n\n core.run(verifier.send_all(messages)).unwrap();\n\n },\n\n );\n\n verifier.join();\n\n}\n\n\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 5, "score": 354687.4722321867 }, { "content": "fn proof_map_insert_without_merge(b: &mut Bencher, db: &dyn Database, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || db.fork(),\n\n |storage| {\n\n let mut table = ProofMapIndex::new(NAME, &storage);\n\n assert!(table.keys().next().is_none());\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 6, "score": 354148.52012714895 }, { "content": "fn proof_map_index_verify_proofs(b: &mut Bencher, db: &dyn Database, len: usize) {\n\n let data = generate_random_kv(len);\n\n let storage = db.fork();\n\n let mut table = ProofMapIndex::new(NAME, &storage);\n\n\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n let table_merkle_root = table.object_hash();\n\n let proofs: Vec<_> = data.iter().map(|item| table.get_proof(item.0)).collect();\n\n\n\n b.iter(|| {\n\n for (i, proof) in proofs.iter().enumerate() {\n\n let checked_proof = proof.clone().check().unwrap();\n\n assert_eq!(*checked_proof.entries().next().unwrap().1, data[i].1);\n\n assert_eq!(checked_proof.root_hash(), table_merkle_root);\n\n }\n\n });\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 7, "score": 354148.52012714895 }, { "content": "fn proof_map_index_build_proofs(b: &mut Bencher, db: &dyn Database, len: usize) {\n\n let data = generate_random_kv(len);\n\n let storage = db.fork();\n\n let mut table = ProofMapIndex::new(NAME, &storage);\n\n\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n let table_merkle_root = table.object_hash();\n\n let mut proofs = Vec::with_capacity(data.len());\n\n\n\n b.iter(|| {\n\n proofs.clear();\n\n proofs.extend(data.iter().map(|item| table.get_proof(item.0)));\n\n });\n\n\n\n for (i, proof) in proofs.into_iter().enumerate() {\n\n let checked_proof = proof.check().unwrap();\n\n assert_eq!(*checked_proof.entries().next().unwrap().1, data[i].1);\n\n assert_eq!(checked_proof.root_hash(), table_merkle_root);\n\n }\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 8, "score": 354148.52012714895 }, { "content": "fn bench_sign(b: &mut Bencher, &count: &usize) {\n\n let (_, secret_key) = gen_keypair();\n\n let data = (0..count).map(|x| (x % 255) as u8).collect::<Vec<u8>>();\n\n b.iter(|| sign(&data, &secret_key))\n\n}\n\n\n", "file_path": "exonum/benches/criterion/crypto.rs", "rank": 10, "score": 323713.005742918 }, { "content": "fn bench_verify(b: &mut Bencher, &count: &usize) {\n\n let (public_key, secret_key) = gen_keypair();\n\n let data = (0..count).map(|x| (x % 255) as u8).collect::<Vec<u8>>();\n\n let signature = sign(&data, &secret_key);\n\n b.iter(|| verify(&signature, &data, &public_key))\n\n}\n\n\n", "file_path": "exonum/benches/criterion/crypto.rs", "rank": 11, "score": 323713.005742918 }, { "content": "pub fn bench_block(criterion: &mut Criterion) {\n\n use log::LevelFilter;\n\n use std::panic;\n\n\n\n log::set_max_level(LevelFilter::Off);\n\n\n\n execute_block_rocksdb(\n\n criterion,\n\n \"block/timestamping\",\n\n timestamping::Timestamping.into(),\n\n timestamping::transactions(SeedableRng::from_seed([2; 32])),\n\n );\n\n\n\n // We expect lots of panics here, so we switch their reporting off.\n\n let panic_hook = panic::take_hook();\n\n panic::set_hook(Box::new(|_| ()));\n\n execute_block_rocksdb(\n\n criterion,\n\n \"block/timestamping_panic\",\n\n timestamping::Timestamping.into(),\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 12, "score": 323652.4209248029 }, { "content": "pub fn bench_verify_transactions(c: &mut Criterion) {\n\n crypto::init();\n\n\n\n let parameters = (7..12).map(|i| 1 << i).collect::<Vec<_>>();\n\n\n\n c.bench(\n\n \"transactions/simple\",\n\n ParameterizedBenchmark::new(\"size\", bench_verify_messages_simple, parameters.clone())\n\n .throughput(|_| Throughput::Elements(MESSAGES_COUNT))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n c.bench(\n\n \"transactions/event_loop\",\n\n ParameterizedBenchmark::new(\"size\", bench_verify_messages_event_loop, parameters.clone())\n\n .throughput(|_| Throughput::Elements(MESSAGES_COUNT))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n}\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 13, "score": 306314.3106695909 }, { "content": "fn generate_random_kv(len: usize) -> Vec<(Hash, Vec<u8>)> {\n\n let mut rng: StdRng = SeedableRng::from_seed(SEED);\n\n let mut exists_keys = HashSet::new();\n\n let mut base = [0; KEY_SIZE];\n\n rng.fill_bytes(&mut base);\n\n let base = base;\n\n\n\n let kv_generator = |_| {\n\n let mut v = vec![0; CHUNK_SIZE];\n\n // Generate only unique keys.\n\n let mut k = base;\n\n let byte: usize = rng.gen_range(0, 31);\n\n k[byte] = rng.gen::<u8>();\n\n\n\n rng.fill_bytes(&mut v);\n\n while exists_keys.contains(&k) {\n\n rng.fill_bytes(&mut k);\n\n }\n\n exists_keys.insert(k);\n\n (Hash::new(k), v)\n\n };\n\n\n\n (0..len).map(kv_generator).collect::<Vec<_>>()\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 14, "score": 305763.6340221539 }, { "content": "/// Verifies that transactions with the specified hashes are present in the pool.\n\n///\n\n/// We do this to ensure proper transaction processing. The assertions are performed before\n\n/// the benchmark and do not influence its timings.\n\nfn assert_transactions_in_pool(blockchain: &Blockchain, tx_hashes: &[Hash]) {\n\n let snapshot = blockchain.snapshot();\n\n let schema = Schema::new(&snapshot);\n\n\n\n assert!(tx_hashes\n\n .iter()\n\n .all(|hash| schema.transactions_pool().contains(&hash)\n\n && !schema.transactions_locations().contains(&hash)));\n\n assert_eq!(tx_hashes.len() as u64, schema.transactions_pool_len());\n\n}\n\n\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 15, "score": 299723.62916387466 }, { "content": "fn create_blockchain(db: impl Database, services: Vec<Box<dyn Service>>) -> Blockchain {\n\n use exonum::{\n\n blockchain::{GenesisConfig, ValidatorKeys},\n\n crypto,\n\n };\n\n use std::sync::Arc;\n\n\n\n let dummy_channel = mpsc::channel(0);\n\n let service_keypair = (PublicKey::zero(), SecretKey::zero());\n\n let mut blockchain = Blockchain::new(\n\n Arc::new(db) as Arc<dyn Database>,\n\n services,\n\n service_keypair.0,\n\n service_keypair.1,\n\n ApiSender::new(dummy_channel.0),\n\n );\n\n\n\n let consensus_keypair = crypto::gen_keypair();\n\n let config = GenesisConfig::new(iter::once(ValidatorKeys {\n\n consensus_key: consensus_keypair.0,\n\n service_key: service_keypair.0,\n\n }));\n\n blockchain.initialize(config).unwrap();\n\n\n\n blockchain\n\n}\n\n\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 17, "score": 285901.657823751 }, { "content": "/// Checks if there is enough votes for a particular configuration hash.\n\nfn enough_votes_to_commit(snapshot: &Fork, cfg_hash: &Hash) -> bool {\n\n let actual_config = CoreSchema::new(snapshot).actual_configuration();\n\n\n\n let schema = Schema::new(snapshot);\n\n let votes = schema.votes_by_config_hash(cfg_hash);\n\n let votes_count = votes.iter().filter(MaybeVote::is_consent).count();\n\n\n\n let config: ConfigurationServiceConfig = get_service_config(&actual_config);\n\n\n\n let majority_count = match config.majority_count {\n\n Some(majority_count) => majority_count as usize,\n\n _ => State::byzantine_majority_count(actual_config.validator_keys.len()),\n\n };\n\n\n\n votes_count >= majority_count\n\n}\n\n\n", "file_path": "services/configuration/src/transactions.rs", "rank": 18, "score": 278686.34658005077 }, { "content": "fn proof_list_append(b: &mut Bencher, len: usize) {\n\n let mut rng: StdRng = SeedableRng::from_seed(SEED);\n\n let data = (0..len)\n\n .map(|_| {\n\n let mut chunk = vec![0; CHUNK_SIZE];\n\n rng.fill_bytes(&mut chunk);\n\n chunk\n\n })\n\n .collect::<Vec<_>>();\n\n\n\n let db = TemporaryDB::default();\n\n b.iter_with_setup(\n\n || (db.fork(), data.clone()),\n\n |(storage, data)| {\n\n let mut table = ProofListIndex::new(NAME, &storage);\n\n assert!(table.is_empty());\n\n for item in data {\n\n table.push(item);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 19, "score": 272474.9404495843 }, { "content": "fn generate_action() -> impl Strategy<Value = SetAction<u8>> {\n\n prop_oneof![\n\n (0..8u8).prop_map(SetAction::Put),\n\n (0..8u8).prop_map(SetAction::Remove),\n\n strategy::Just(SetAction::Clear),\n\n strategy::Just(SetAction::MergeFork),\n\n ]\n\n}\n\n\n\nimpl<V> Modifier<HashSet<V>> for SetAction<V>\n\nwhere\n\n V: Eq + Hash,\n\n{\n\n fn modify(self, set: &mut HashSet<V>) {\n\n match self {\n\n SetAction::Put(v) => {\n\n set.insert(v);\n\n }\n\n SetAction::Remove(v) => {\n\n set.remove(&v);\n", "file_path": "exonum/tests/collections/set.rs", "rank": 20, "score": 269280.7663570501 }, { "content": "fn gen_messages(count: u64, tx_size: usize) -> Vec<Vec<u8>> {\n\n use exonum_merkledb::BinaryValue;\n\n let (p, s) = crypto::gen_keypair();\n\n (0..count)\n\n .map(|_| {\n\n let msg = Message::new(\n\n RawTransaction::new(\n\n 0,\n\n ServiceTransaction::from_raw_unchecked(0, vec![0; tx_size]),\n\n ),\n\n p,\n\n &s,\n\n );\n\n msg.into_bytes()\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 21, "score": 269157.57264237525 }, { "content": "fn proof_map_insert_with_merge(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || (TemporaryDB::default(), data.clone()),\n\n |(db, data)| {\n\n let fork = db.fork();\n\n {\n\n let mut table = ProofMapIndex::new(NAME, &fork);\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 22, "score": 268866.6243274637 }, { "content": "fn plain_map_index_read(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = MapIndex::new(NAME, &fork);\n\n assert!(table.keys().next().is_none());\n\n for item in data.clone() {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> = MapIndex::new(NAME, &snapshot);\n\n for item in &data {\n\n let value = index.get(&item.0);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 23, "score": 268866.6243274637 }, { "content": "fn plain_map_index_insert(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || (TemporaryDB::default(), data.clone()),\n\n |(db, data)| {\n\n let fork = db.fork();\n\n {\n\n let mut table = MapIndex::new(NAME, &fork);\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 24, "score": 268866.6243274637 }, { "content": "fn plain_map_index_iter(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = MapIndex::new(NAME, &fork);\n\n assert!(table.keys().next().is_none());\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> = MapIndex::new(NAME, &snapshot);\n\n for (key, value) in &index {\n\n black_box(key);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 25, "score": 268866.6243274637 }, { "content": "fn proof_map_insert_without_merge(b: &mut Bencher, len: usize) {\n\n let db = TemporaryDB::default();\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || (db.fork(), data.clone()),\n\n |(storage, data)| {\n\n let mut table = ProofMapIndex::new(NAME, &storage);\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 26, "score": 265396.167803123 }, { "content": "fn proof_map_index_build_proofs(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let storage = db.fork();\n\n let mut table = ProofMapIndex::new(NAME, &storage);\n\n\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n let table_root_hash = table.object_hash();\n\n let mut proofs = Vec::with_capacity(data.len());\n\n\n\n b.iter(|| {\n\n proofs.clear();\n\n proofs.extend(data.iter().map(|item| table.get_proof(item.0)));\n\n });\n\n\n\n for (i, proof) in proofs.into_iter().enumerate() {\n\n let checked_proof = proof.check().unwrap();\n\n assert_eq!(*checked_proof.entries().next().unwrap().1, data[i].1);\n\n assert_eq!(checked_proof.root_hash(), table_root_hash);\n\n }\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 27, "score": 265396.167803123 }, { "content": "fn plain_map_index_with_family_iter(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = MapIndex::new_in_family(NAME, FAMILY, &fork);\n\n assert!(table.keys().next().is_none());\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> =\n\n MapIndex::new_in_family(NAME, FAMILY, &snapshot);\n\n for (key, value) in &index {\n\n black_box(key);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 28, "score": 265396.167803123 }, { "content": "fn plain_map_index_with_family_read(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = MapIndex::new_in_family(NAME, FAMILY, &fork);\n\n assert!(table.keys().next().is_none());\n\n for item in data.clone() {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> =\n\n MapIndex::new_in_family(NAME, FAMILY, &snapshot);\n\n for item in &data {\n\n let value = index.get(&item.0);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 29, "score": 265396.167803123 }, { "content": "fn proof_map_index_verify_proofs(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let storage = db.fork();\n\n let mut table = ProofMapIndex::new(NAME, &storage);\n\n\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n let table_root_hash = table.object_hash();\n\n let proofs: Vec<_> = data.iter().map(|item| table.get_proof(item.0)).collect();\n\n\n\n b.iter(|| {\n\n for (i, proof) in proofs.iter().enumerate() {\n\n let checked_proof = proof.clone().check().unwrap();\n\n assert_eq!(*checked_proof.entries().next().unwrap().1, data[i].1);\n\n assert_eq!(checked_proof.root_hash(), table_root_hash);\n\n }\n\n });\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 30, "score": 265396.167803123 }, { "content": "fn plain_map_index_with_family_insert(b: &mut Bencher, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || (TemporaryDB::default(), data.clone()),\n\n |(db, data)| {\n\n let fork = db.fork();\n\n {\n\n let mut table = MapIndex::new_in_family(NAME, FAMILY, &fork);\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 31, "score": 265396.167803123 }, { "content": "fn generate_random_kv(len: usize) -> Vec<(Hash, Vec<u8>)> {\n\n let mut rng: StdRng = SeedableRng::from_seed(SEED);\n\n let mut exists_keys = HashSet::new();\n\n let mut base = [0; KEY_SIZE];\n\n rng.fill_bytes(&mut base);\n\n let base = base;\n\n\n\n let kv_generator = |_| {\n\n let mut v = vec![0; CHUNK_SIZE];\n\n // Generate only unique keys.\n\n let mut k = base;\n\n let byte: usize = rng.gen_range(0, 31);\n\n k[byte] = rng.gen::<u8>();\n\n\n\n rng.fill_bytes(&mut v);\n\n while exists_keys.contains(&k) {\n\n rng.fill_bytes(&mut k);\n\n }\n\n exists_keys.insert(k);\n\n (Hash::new(k), v)\n\n };\n\n\n\n (0..len).map(kv_generator).collect::<Vec<_>>()\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 32, "score": 261001.36312992923 }, { "content": "/// Calculates a hash of a bytes slice.\n\n///\n\n/// Type of a hash depends on a chosen crypto backend (via `...-crypto` cargo feature).\n\n///\n\n/// # Examples\n\n///\n\n/// The example below calculates the hash of the indicated data.\n\n///\n\n/// ```\n\n/// # extern crate exonum_crypto;\n\n///\n\n/// # exonum_crypto::init();\n\n/// let data = [1, 2, 3];\n\n/// let hash = exonum_crypto::hash(&data);\n\n/// ```\n\npub fn hash(data: &[u8]) -> Hash {\n\n let dig = crypto_impl::hash(data);\n\n Hash(dig)\n\n}\n\n\n", "file_path": "components/crypto/src/lib.rs", "rank": 33, "score": 260966.17634231856 }, { "content": "fn execute_block(blockchain: &Blockchain, height: u64, txs: &[Hash]) -> (Hash, Patch) {\n\n blockchain.create_patch(\n\n ValidatorId::zero(),\n\n Height(height),\n\n txs,\n\n &mut BTreeMap::new(),\n\n )\n\n}\n\n\n\nmod timestamping {\n\n use super::{gen_keypair_from_rng, BoxedTx};\n\n use crate::proto;\n\n use exonum::{\n\n blockchain::{ExecutionResult, Service, Transaction, TransactionContext},\n\n crypto::{CryptoHash, Hash, PublicKey, SecretKey},\n\n messages::{Message, RawTransaction, Signed},\n\n };\n\n use exonum_merkledb::Snapshot;\n\n use rand::rngs::StdRng;\n\n\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 34, "score": 260798.83668652506 }, { "content": "// Converts raw data to a database.\n\nfn data_to_db(data: BTreeMap<[u8; 32], u64>) -> TemporaryDB {\n\n let db = TemporaryDB::new();\n\n let fork = db.fork();\n\n {\n\n let mut table = ProofMapIndex::new(INDEX_NAME, &fork);\n\n for (key, value) in data {\n\n table.put(&key, value);\n\n }\n\n }\n\n db.merge(fork.into_patch()).unwrap();\n\n db\n\n}\n\n\n\nmacro_rules! proof_map_tests {\n\n (cases = $cases:expr,sizes = $sizes:expr,bytes = $bytes:expr) => {\n\n proptest! {\n\n #![proptest_config(Config::with_cases($cases))]\n\n\n\n #[test]\n\n fn proof_of_presence(\n", "file_path": "exonum/tests/proof_map_index.rs", "rank": 35, "score": 254072.96002171625 }, { "content": "/// Calculates hash of a bytes slice.\n\npub fn hash(data: &[u8]) -> Hash {\n\n sha256::hash(data)\n\n}\n", "file_path": "components/crypto/src/crypto_lib/sodiumoxide/mod.rs", "rank": 36, "score": 253067.4352733459 }, { "content": "/// Removes all keys from the table that start with the specified prefix.\n\npub fn remove_keys_with_prefix<V>(table: &mut BTreeMap<Vec<u8>, V>, prefix: &[u8]) {\n\n if prefix.is_empty() {\n\n // If the prefix is empty, we can be more efficient by clearing\n\n // the entire changes in the patch.\n\n table.clear();\n\n } else {\n\n // Remove all keys starting from `prefix`.\n\n let mut tail = table.split_off(prefix);\n\n if let Some(next_prefix) = next_prefix(prefix) {\n\n tail = tail.split_off(&next_prefix);\n\n table.append(&mut tail);\n\n }\n\n }\n\n}\n\n\n\n/// Map containing changes with a corresponding key.\n\n#[derive(Debug, Clone)]\n\npub struct Changes {\n\n data: BTreeMap<Vec<u8>, Change>,\n\n prefixes_to_remove: Vec<Vec<u8>>,\n", "file_path": "components/merkledb/src/db.rs", "rank": 37, "score": 252703.23645686667 }, { "content": "pub fn bench_storage(c: &mut Criterion) {\n\n ::exonum::crypto::init();\n\n\n\n bench_fn_rocksdb(c, \"storage/proof_list/append\", proof_list_append);\n\n bench_fn_rocksdb(\n\n c,\n\n \"storage/proof_map/insert/no_merge\",\n\n proof_map_insert_without_merge,\n\n );\n\n bench_fn_rocksdb(\n\n c,\n\n \"storage/proof_map/insert/merge\",\n\n proof_map_insert_with_merge,\n\n );\n\n bench_fn_rocksdb(\n\n c,\n\n \"storage/proof_map/proofs/build\",\n\n proof_map_index_build_proofs,\n\n );\n\n bench_fn_rocksdb(\n\n c,\n\n \"storage/proof_map/proofs/validate\",\n\n proof_map_index_verify_proofs,\n\n );\n\n}\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 38, "score": 249326.0816477416 }, { "content": "pub fn bench_crypto(c: &mut Criterion) {\n\n ::exonum::crypto::init();\n\n\n\n // Testing crypto functions with different data sizes.\n\n //\n\n // 2^6 = 64 - is relatively small message, and our starting test point.\n\n // 2^16 = 65536 - is relatively big message, and our end point.\n\n\n\n c.bench(\n\n \"hash\",\n\n ParameterizedBenchmark::new(\"hash\", bench_hash, (6..16).map(|i| pow(2, i)))\n\n .throughput(|s| Throughput::Bytes((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)),\n\n );\n\n c.bench(\n\n \"sign\",\n\n ParameterizedBenchmark::new(\"sign\", bench_sign, (6..16).map(|i| pow(2, i)))\n\n .throughput(|s| Throughput::Bytes((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)),\n\n );\n\n c.bench(\n\n \"verify\",\n\n ParameterizedBenchmark::new(\"verify\", bench_verify, (6..16).map(|i| pow(2, i)))\n\n .throughput(|s| Throughput::Bytes((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)),\n\n );\n\n}\n", "file_path": "exonum/benches/criterion/crypto.rs", "rank": 39, "score": 249326.0816477416 }, { "content": "/// Converts an arbitrary array of data to the Curve25519-compatible private key.\n\npub fn convert_to_private_key(key: &mut [u8; 32]) {\n\n let converted = convert_ed_sk_to_curve25519(key);\n\n\n\n key.copy_from_slice(&converted);\n\n}\n\n\n", "file_path": "components/crypto/src/crypto_lib/sodiumoxide/x25519.rs", "rank": 40, "score": 249291.87902835288 }, { "content": "fn before_commit(service: &dyn Service, fork: &mut Fork) {\n\n match panic::catch_unwind(panic::AssertUnwindSafe(|| service.before_commit(fork))) {\n\n Ok(..) => fork.flush(),\n\n Err(err) => {\n\n if err.is::<StorageError>() {\n\n // Continue panic unwind if the reason is StorageError.\n\n panic::resume_unwind(err);\n\n }\n\n fork.rollback();\n\n error!(\n\n \"{} service before_commit failed with error: {:?}\",\n\n service.service_name(),\n\n err\n\n );\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Blockchain {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "exonum/src/blockchain/mod.rs", "rank": 41, "score": 245693.87839816167 }, { "content": "fn hash_leaf_node(value: &[u8]) -> Hash {\n\n HashTag::Blob.hash_stream().update(value).hash()\n\n}\n\n\n", "file_path": "components/merkledb/src/proof_list_index/tests.rs", "rank": 42, "score": 245289.5665316811 }, { "content": "fn hash_branch_node(value: &[u8]) -> Hash {\n\n HashTag::ListBranchNode.hash_stream().update(value).hash()\n\n}\n\n\n", "file_path": "components/merkledb/src/proof_list_index/tests.rs", "rank": 43, "score": 245289.5665316811 }, { "content": "#[bench]\n\nfn bench_msg_short_1000(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: false,\n\n len: 1000,\n\n times: 1000,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:9792\".parse().unwrap(),\n\n \"127.0.0.1:9793\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 46, "score": 242892.38356320743 }, { "content": "#[bench]\n\nfn bench_msg_short_10_000(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: false,\n\n len: 1000,\n\n times: 10_000,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:9792\".parse().unwrap(),\n\n \"127.0.0.1:9793\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 47, "score": 242892.38356320743 }, { "content": "#[bench]\n\nfn bench_msg_long_10(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: false,\n\n len: 100_000,\n\n times: 10,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:9984\".parse().unwrap(),\n\n \"127.0.0.1:9985\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 48, "score": 242892.38356320743 }, { "content": "#[bench]\n\nfn bench_msg_short_100(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: false,\n\n len: 100,\n\n times: 100,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:6990\".parse().unwrap(),\n\n \"127.0.0.1:6991\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 49, "score": 242892.38356320743 }, { "content": "#[bench]\n\nfn bench_msg_long_100(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: false,\n\n len: 100_000,\n\n times: 100,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:9946\".parse().unwrap(),\n\n \"127.0.0.1:9947\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 50, "score": 242892.38356320743 }, { "content": "#[bench]\n\nfn bench_msg_long_100_nodelay(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: true,\n\n len: 100_000,\n\n times: 100,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:9198\".parse().unwrap(),\n\n \"127.0.0.1:9199\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n", "file_path": "exonum/src/events/benches.rs", "rank": 51, "score": 239965.77279681448 }, { "content": "#[bench]\n\nfn bench_msg_short_100_nodelay(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: true,\n\n len: 100,\n\n times: 100,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:4990\".parse().unwrap(),\n\n \"127.0.0.1:4991\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 52, "score": 239965.77279681448 }, { "content": "fn bench_binary_key_concat(b: &mut Bencher) {\n\n b.iter_with_setup(\n\n || (\"prefixed.key\", Hash::zero(), ProofPath::new(&Hash::zero())),\n\n |(prefix, key, path)| {\n\n let mut v = vec![0; prefix.size() + key.size() + path.size()];\n\n let mut pos = prefix.write(&mut v);\n\n pos += key.write(&mut v[pos..]);\n\n path.write(&mut v[pos..]);\n\n black_box(v);\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/encoding.rs", "rank": 53, "score": 239965.7727968145 }, { "content": "#[bench]\n\nfn bench_msg_short_1000_nodelay(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: true,\n\n len: 100,\n\n times: 1000,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:5990\".parse().unwrap(),\n\n \"127.0.0.1:5991\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 54, "score": 239965.7727968145 }, { "content": "#[bench]\n\nfn bench_msg_short_10_000_nodelay(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: true,\n\n len: 100,\n\n times: 10_000,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:5990\".parse().unwrap(),\n\n \"127.0.0.1:5991\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 55, "score": 239965.77279681448 }, { "content": "#[bench]\n\nfn bench_msg_long_10_nodelay(b: &mut Bencher) {\n\n let cfg = BenchConfig {\n\n tcp_nodelay: true,\n\n len: 100_000,\n\n times: 10,\n\n };\n\n let addrs = [\n\n \"127.0.0.1:9198\".parse().unwrap(),\n\n \"127.0.0.1:9199\".parse().unwrap(),\n\n ];\n\n bench_network(b, addrs, &cfg);\n\n}\n\n\n", "file_path": "exonum/src/events/benches.rs", "rank": 56, "score": 239965.7727968145 }, { "content": "pub fn bench_refs(c: &mut Criterion) {\n\n c.bench_function(\"refs/index/create/default\", move |b| {\n\n let db = TemporaryDB::new();\n\n let fork = db.fork();\n\n bench_fn(b, &fork, |fork| bench_with_index_access(fork));\n\n });\n\n\n\n c.bench_function(\"refs/index/create/get_or_create\", move |b| {\n\n let db = TemporaryDB::new();\n\n let fork = db.fork();\n\n bench_fn(b, &fork, |fork| bench_with_object_access(fork));\n\n });\n\n}\n", "file_path": "components/merkledb/benches/refs.rs", "rank": 57, "score": 236989.89202654263 }, { "content": "pub fn bench_encoding(c: &mut Criterion) {\n\n exonum_crypto::init();\n\n bench_binary_value(c, \"bytes\", gen_bytes_data);\n\n bench_binary_value(c, \"simple\", gen_sample_data);\n\n bench_binary_value(c, \"cursor\", gen_cursor_data);\n\n bench_binary_value(c, \"branch_node\", gen_branch_node_data);\n\n c.bench_function(\"encoding/storage_key/concat\", bench_binary_key_concat);\n\n}\n", "file_path": "components/merkledb/benches/encoding.rs", "rank": 58, "score": 236989.89202654263 }, { "content": "pub fn bench_storage(c: &mut Criterion) {\n\n exonum_crypto::init();\n\n // MapIndex\n\n bench_fn(c, \"storage/plain_map/insert\", plain_map_index_insert);\n\n bench_fn(c, \"storage/plain_map/iter\", plain_map_index_iter);\n\n bench_fn(\n\n c,\n\n \"storage/plain_map_with_family/insert\",\n\n plain_map_index_with_family_insert,\n\n );\n\n bench_fn(\n\n c,\n\n \"storage/plain_map_with_family/iter\",\n\n plain_map_index_with_family_iter,\n\n );\n\n bench_fn(c, \"storage/plain_map/read\", plain_map_index_read);\n\n bench_fn(\n\n c,\n\n \"storage/plain_map_with_family/read\",\n\n plain_map_index_with_family_read,\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 59, "score": 236989.89202654263 }, { "content": "fn gen_primitive_socket_addr(idx: u8) -> SocketAddr {\n\n let addr = Ipv4Addr::new(idx, idx, idx, idx);\n\n SocketAddr::new(IpAddr::V4(addr), u16::from(idx))\n\n}\n\n\n", "file_path": "exonum/src/sandbox/mod.rs", "rank": 60, "score": 234997.02872840525 }, { "content": "fn bench_fn_rocksdb<F>(c: &mut Criterion, name: &str, benchmark: F)\n\nwhere\n\n F: Fn(&mut Bencher, &dyn Database, usize) + 'static,\n\n{\n\n let item_counts = ITEM_COUNTS.iter().cloned();\n\n c.bench(\n\n name,\n\n ParameterizedBenchmark::new(\n\n \"items\",\n\n move |b: &mut Bencher, &len: &usize| {\n\n let tempdir = TempDir::new(\"exonum\").unwrap();\n\n let options = DbOptions::default();\n\n let db = RocksDB::open(tempdir.path(), &options).unwrap();\n\n benchmark(b, &db, len)\n\n },\n\n item_counts,\n\n )\n\n .throughput(|s| Throughput::Elements((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n}\n\n\n", "file_path": "exonum/benches/criterion/storage.rs", "rank": 61, "score": 231425.65077172304 }, { "content": "/// This function checks that the given database is compatible with the current `MerkleDB` version.\n\npub fn check_database(db: &mut dyn Database) -> Result<()> {\n\n let fork = db.fork();\n\n {\n\n let mut view = View::new(&fork, DB_METADATA);\n\n if let Some(saved_version) = view.get::<_, u8>(VERSION_NAME) {\n\n if saved_version != DB_VERSION {\n\n return Err(Error::new(format!(\n\n \"Database version doesn't match: actual {}, expected {}\",\n\n saved_version, DB_VERSION\n\n )));\n\n }\n\n\n\n return Ok(());\n\n } else {\n\n view.put(VERSION_NAME, DB_VERSION);\n\n }\n\n }\n\n db.merge(fork.into_patch())\n\n}\n", "file_path": "components/merkledb/src/db.rs", "rank": 62, "score": 231360.43724355294 }, { "content": "/// Simplified compared to real life / testkit, but we don't need to test *everything*\n\n/// here.\n\npub fn create_block(blockchain: &mut Blockchain, transactions: Vec<Signed<RawTransaction>>) {\n\n use exonum::helpers::{Round, ValidatorId};\n\n use exonum::messages::{Precommit, Propose};\n\n use std::time::SystemTime;\n\n\n\n let tx_hashes: Vec<_> = transactions.iter().map(Signed::hash).collect();\n\n let height = blockchain.last_block().height().next();\n\n\n\n let fork = blockchain.fork();\n\n {\n\n let mut schema = Schema::new(&fork);\n\n for tx in transactions {\n\n schema.add_transaction_into_pool(tx.clone())\n\n }\n\n }\n\n blockchain.merge(fork.into_patch()).unwrap();\n\n\n\n let (block_hash, patch) =\n\n blockchain.create_patch(ValidatorId(0), height, &tx_hashes, &mut BTreeMap::new());\n\n let (consensus_public_key, consensus_secret_key) = consensus_keys();\n", "file_path": "exonum/tests/explorer/blockchain/mod.rs", "rank": 63, "score": 229438.66934313407 }, { "content": "fn generate_action() -> impl Strategy<Value = SetAction<u8>> {\n\n prop_oneof![\n\n (0..8u8).prop_map(SetAction::Put),\n\n (0..8u8).prop_map(SetAction::Remove),\n\n strategy::Just(SetAction::Clear),\n\n strategy::Just(SetAction::MergeFork),\n\n ]\n\n}\n\n\n\nimpl<V> Modifier<HashSet<V>> for SetAction<V>\n\nwhere\n\n V: Eq + Hash,\n\n{\n\n fn modify(self, set: &mut HashSet<V>) {\n\n match self {\n\n SetAction::Put(v) => {\n\n set.insert(v);\n\n }\n\n SetAction::Remove(v) => {\n\n set.remove(&v);\n", "file_path": "components/merkledb/tests/set.rs", "rank": 64, "score": 223587.64440070296 }, { "content": "fn tx_hashes(transactions: &[Signed<RawTransaction>]) -> Vec<Hash> {\n\n let mut hashes = transactions.iter().map(Signed::hash).collect::<Vec<_>>();\n\n hashes.sort();\n\n hashes\n\n}\n\n\n", "file_path": "exonum/src/sandbox/consensus/transactions.rs", "rank": 65, "score": 221805.76872985097 }, { "content": "fn bench_fn<F>(c: &mut Criterion, name: &str, benchmark: F)\n\nwhere\n\n F: Fn(&mut Bencher, usize) + 'static,\n\n{\n\n let item_counts = ITEM_COUNTS.iter().cloned();\n\n c.bench(\n\n name,\n\n ParameterizedBenchmark::new(\n\n \"items\",\n\n move |b: &mut Bencher, &len: &usize| benchmark(b, len),\n\n item_counts,\n\n )\n\n .throughput(|s| Throughput::Elements((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 66, "score": 220618.39567981102 }, { "content": "fn assert_proof_of_absence<V: BinaryValue + ObjectHash + Debug>(\n\n proof: ListProof<V>,\n\n expected_hash: Hash,\n\n len: u64,\n\n) {\n\n let validation_result = proof.validate(expected_hash, len);\n\n assert!(validation_result.is_ok());\n\n assert!(validation_result.unwrap().is_empty());\n\n\n\n if let ListProof::Absent(proof) = proof {\n\n let actual_hash = HashTag::hash_list_node(proof.length(), proof.merkle_root());\n\n assert_eq!(expected_hash, actual_hash);\n\n } else {\n\n panic!(\"Unexpected proof {:?}\", proof);\n\n }\n\n}\n", "file_path": "components/merkledb/src/proof_list_index/tests.rs", "rank": 67, "score": 219260.6099841576 }, { "content": "/// Resets bits higher than the given pos.\n\nfn reset_bits(value: &mut u8, pos: u16) {\n\n let reset_bits_mask = !(255_u8 << pos as u8);\n\n *value &= reset_bits_mask;\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n\npub enum ChildKind {\n\n Left,\n\n Right,\n\n}\n\n\n\nimpl ops::Not for ChildKind {\n\n type Output = Self;\n\n\n\n fn not(self) -> Self {\n\n match self {\n\n ChildKind::Left => ChildKind::Right,\n\n ChildKind::Right => ChildKind::Left,\n\n }\n\n }\n", "file_path": "components/merkledb/src/proof_map_index/key.rs", "rank": 68, "score": 218117.06827178109 }, { "content": "fn assert_service_execute(blockchain: &Blockchain, db: &mut dyn Database) {\n\n let (_, patch) =\n\n blockchain.create_patch(ValidatorId::zero(), Height(1), &[], &mut BTreeMap::new());\n\n db.merge(patch).unwrap();\n\n let snapshot = db.snapshot();\n\n let index = ListIndex::new(IDX_NAME, &snapshot);\n\n assert_eq!(index.len(), 1);\n\n assert_eq!(index.get(0), Some(1));\n\n}\n\n\n", "file_path": "exonum/src/blockchain/tests.rs", "rank": 69, "score": 215874.81849018496 }, { "content": "/// Finds a prefix immediately following the supplied one.\n\npub fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {\n\n let change_idx = prefix.iter().rposition(|&byte| byte < u8::max_value());\n\n change_idx.map(|idx| {\n\n let mut next_prefix = prefix.to_vec();\n\n next_prefix[idx] += 1;\n\n for byte in &mut next_prefix[(idx + 1)..] {\n\n *byte = 0;\n\n }\n\n next_prefix\n\n })\n\n}\n\n\n", "file_path": "components/merkledb/src/db.rs", "rank": 70, "score": 213740.28791668476 }, { "content": "fn create_rocksdb(tempdir: &TempDir) -> RocksDB {\n\n let options = DbOptions::default();\n\n RocksDB::open(tempdir.path(), &options).unwrap()\n\n}\n\n\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 71, "score": 213703.81525880838 }, { "content": "fn assert_service_execute_panic(blockchain: &Blockchain, db: &mut dyn Database) {\n\n let (_, patch) =\n\n blockchain.create_patch(ValidatorId::zero(), Height(1), &[], &mut BTreeMap::new());\n\n db.merge(patch).unwrap();\n\n let snapshot = db.snapshot();\n\n let index: ListIndex<_, u32> = ListIndex::new(IDX_NAME, &snapshot);\n\n assert!(index.is_empty());\n\n}\n\n\n\nmod memorydb_tests {\n\n use futures::sync::mpsc;\n\n\n\n use crate::blockchain::{Blockchain, Service};\n\n use crate::crypto::gen_keypair;\n\n use crate::node::ApiSender;\n\n use exonum_merkledb::{Database, TemporaryDB};\n\n\n\n use super::{ServiceGood, ServicePanic, ServicePanicStorageError};\n\n\n\n fn create_database() -> Box<dyn Database> {\n", "file_path": "exonum/src/blockchain/tests.rs", "rank": 72, "score": 213375.8893238942 }, { "content": "fn bench_fn<T, F>(b: &mut Bencher, index_access: T, benchmark: F)\n\nwhere\n\n T: IndexAccess,\n\n F: Fn(T),\n\n{\n\n b.iter(|| benchmark(index_access.clone()))\n\n}\n\n\n", "file_path": "components/merkledb/benches/refs.rs", "rank": 73, "score": 212438.21118781337 }, { "content": "/// This routine is adapted from the *old* Path's `path_relative_from`\n\n/// function, which works differently from the new `relative_from` function.\n\n/// In particular, this handles the case on unix where both paths are\n\n/// absolute but with only the root as the common directory.\n\n///\n\n/// @see https://github.com/rust-lang/rust/blob/e1d0de82cc40b666b88d4a6d2c9dcbc81d7ed27f/src/librustc_back/rpath.rs#L116-L158\n\npub fn path_relative_from(path: impl AsRef<Path>, base: impl AsRef<Path>) -> Option<PathBuf> {\n\n let path = path.as_ref();\n\n let base = base.as_ref();\n\n\n\n if path.is_absolute() != base.is_absolute() {\n\n if path.is_absolute() {\n\n Some(PathBuf::from(path))\n\n } else {\n\n None\n\n }\n\n } else {\n\n let mut ita = path.components();\n\n let mut itb = base.components();\n\n let mut comps: Vec<Component> = vec![];\n\n loop {\n\n match (ita.next(), itb.next()) {\n\n (None, None) => break,\n\n (Some(a), None) => {\n\n comps.push(a);\n\n comps.extend(ita.by_ref());\n", "file_path": "exonum/src/helpers/mod.rs", "rank": 75, "score": 212068.24731679377 }, { "content": "/// Computes the root hash of the Merkle Patricia tree backing the specified entries\n\n/// in the map view.\n\n///\n\n/// The tree is not restored in full; instead, we add the paths to\n\n/// the tree in their lexicographic order (i.e., according to the `PartialOrd` implementation\n\n/// of `ProofPath`) and keep track of the rightmost nodes (the right contour) of the tree.\n\n/// It is easy to see that adding paths in the lexicographic order means that only\n\n/// the nodes in the right contour may be updated on each step. Further, on each step\n\n/// zero or more nodes are evicted from the contour, and a single new node is\n\n/// added to it.\n\n///\n\n/// `entries` are assumed to be sorted by the path in increasing order.\n\nfn collect(entries: &[MapProofEntry]) -> Result<Hash, MapProofError> {\n\n fn common_prefix(x: &ProofPath, y: &ProofPath) -> ProofPath {\n\n x.prefix(x.common_prefix_len(y))\n\n }\n\n\n\n fn hash_branch(left_child: &MapProofEntry, right_child: &MapProofEntry) -> Hash {\n\n let mut branch = BranchNode::empty();\n\n branch.set_child(ChildKind::Left, &left_child.path, &left_child.hash);\n\n branch.set_child(ChildKind::Right, &right_child.path, &right_child.hash);\n\n branch.object_hash()\n\n }\n\n\n\n /// Folds two last entries in a contour and replaces them with the folded entry.\n\n ///\n\n /// Returns an updated common prefix between two last entries in the contour.\n\n fn fold(contour: &mut Vec<MapProofEntry>, last_prefix: ProofPath) -> Option<ProofPath> {\n\n let last_entry = contour.pop().unwrap();\n\n let penultimate_entry = contour.pop().unwrap();\n\n\n\n contour.push(MapProofEntry {\n", "file_path": "components/merkledb/src/proof_map_index/proof.rs", "rank": 76, "score": 211609.24323132593 }, { "content": "/// Creates a wallet with the given name and a random key.\n\nfn create_wallet(testkit: &mut TestKit, name: &str) -> (Signed<RawTransaction>, SecretKey) {\n\n let (pubkey, key) = crypto::gen_keypair();\n\n let tx = TxCreateWallet::sign(name, &pubkey, &key);\n\n testkit.create_block_with_transaction(tx.clone());\n\n (tx, key)\n\n}\n\n\n", "file_path": "examples/cryptocurrency/tests/tx_logic.rs", "rank": 77, "score": 210369.02651256314 }, { "content": "/// Computes a secret key and a corresponding public key from a `Seed`.\n\n///\n\n/// # Examples\n\n///\n\n/// The example below generates a keypair that depends on the indicated seed.\n\n/// Indicating the same seed value always results in the same keypair.\n\n///\n\n/// ```\n\n/// # extern crate exonum_crypto;\n\n/// use exonum_crypto::{SEED_LENGTH, Seed};\n\n///\n\n/// # exonum_crypto::init();\n\n/// let (public_key, secret_key) = exonum_crypto::gen_keypair_from_seed(&Seed::new([1; SEED_LENGTH]));\n\n/// ```\n\npub fn gen_keypair_from_seed(seed: &Seed) -> (PublicKey, SecretKey) {\n\n let (impl_pub_key, impl_secret_key) = crypto_impl::gen_keypair_from_seed(&seed.0);\n\n (PublicKey(impl_pub_key), SecretKey(impl_secret_key))\n\n}\n\n\n", "file_path": "components/crypto/src/lib.rs", "rank": 78, "score": 205732.93646285846 }, { "content": "fn write_short_hex(f: &mut fmt::Formatter, slice: &[u8]) -> fmt::Result {\n\n for byte in slice.iter().take(BYTES_IN_DEBUG) {\n\n write!(f, \"{:02x}\", byte)?;\n\n }\n\n if slice.len() > BYTES_IN_DEBUG {\n\n write!(f, \"...\")?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/crypto/src/lib.rs", "rank": 79, "score": 205332.4306592103 }, { "content": "fn bench_network(b: &mut Bencher, addrs: [SocketAddr; 2], cfg: &BenchConfig) {\n\n b.iter(|| {\n\n let times = cfg.times;\n\n let len = cfg.len;\n\n let first = addrs[0];\n\n let second = addrs[1];\n\n\n\n let mut connect_list = ConnectList::default();\n\n\n\n let mut params1 = ConnectionParams::from_address(first);\n\n connect_list.add(params1.connect_info.clone());\n\n let first_key = params1.connect_info.public_key;\n\n\n\n let mut params2 = ConnectionParams::from_address(second);\n\n connect_list.add(params2.connect_info.clone());\n\n let second_key = params2.connect_info.public_key;\n\n\n\n let connect_list = SharedConnectList::from_connect_list(connect_list);\n\n\n\n let e1 = test_events(cfg, first, connect_list.clone());\n", "file_path": "exonum/src/events/benches.rs", "rank": 80, "score": 205301.25253302272 }, { "content": "struct Schema<T: ObjectAccess>(T);\n\n\n\nimpl<T: ObjectAccess> Schema<T> {\n\n fn new(object_access: T) -> Self {\n\n Self(object_access)\n\n }\n\n\n\n fn transactions(&self) -> RefMut<MapIndex<T, Hash, Transaction>> {\n\n self.0.get_object(\"transactions\")\n\n }\n\n\n\n fn blocks(&self) -> RefMut<ListIndex<T, Hash>> {\n\n self.0.get_object(\"blocks\")\n\n }\n\n\n\n fn wallets(&self) -> RefMut<ProofMapIndex<T, PublicKey, Wallet>> {\n\n self.0.get_object(\"wallets\")\n\n }\n\n\n\n fn wallets_history(&self, owner: &PublicKey) -> RefMut<ProofListIndex<T, Hash>> {\n", "file_path": "components/merkledb/examples/blockchain.rs", "rank": 81, "score": 202120.24070542905 }, { "content": "fn create_sample_block(testkit: &mut TestKit) {\n\n let height = testkit.height().next().0;\n\n if height == 2 || height == 5 {\n\n let tx = {\n\n let (pubkey, key) = crypto::gen_keypair();\n\n TxIncrement::sign(&pubkey, height as u64, &key)\n\n };\n\n testkit.api().send(tx.clone());\n\n }\n\n testkit.create_block();\n\n}\n\n\n", "file_path": "testkit/tests/counter/main.rs", "rank": 82, "score": 202007.46088468708 }, { "content": "fn bench_binary_value<F, V>(c: &mut Criterion, name: &str, f: F)\n\nwhere\n\n F: Fn() -> V + 'static + Clone + Copy,\n\n V: BinaryValue + ObjectHash + PartialEq + Debug,\n\n{\n\n // Checks that binary value is correct.\n\n let val = f();\n\n let bytes = val.to_bytes();\n\n let val2 = V::from_bytes(bytes.into()).unwrap();\n\n assert_eq!(val, val2);\n\n // Runs benchmarks.\n\n c.bench_function(\n\n &format!(\"encoding/{}/to_bytes\", name),\n\n move |b: &mut Bencher| {\n\n b.iter_with_setup(f, |data| black_box(data.to_bytes()));\n\n },\n\n );\n\n c.bench_function(\n\n &format!(\"encoding/{}/into_bytes\", name),\n\n move |b: &mut Bencher| {\n", "file_path": "components/merkledb/benches/encoding.rs", "rank": 83, "score": 201886.2420899605 }, { "content": "/// Computes a secret key and a corresponding public key from a `Seed`.\n\npub fn gen_keypair_from_seed(seed: &Seed) -> (PublicKey, SecretKey) {\n\n ed25519::keypair_from_seed(seed)\n\n}\n\n\n", "file_path": "components/crypto/src/crypto_lib/sodiumoxide/mod.rs", "rank": 84, "score": 201757.4202275165 }, { "content": "fn execute_block_rocksdb(\n\n criterion: &mut Criterion,\n\n bench_name: &'static str,\n\n service: Box<dyn Service>,\n\n mut tx_generator: impl Iterator<Item = Signed<RawTransaction>>,\n\n) {\n\n let tempdir = TempDir::new(\"exonum\").unwrap();\n\n let db = create_rocksdb(&tempdir);\n\n let mut blockchain = create_blockchain(db, vec![service]);\n\n\n\n // We don't particularly care how transactions are distributed in the blockchain\n\n // in the preparation phase.\n\n prepare_blockchain(\n\n &mut blockchain,\n\n tx_generator.by_ref(),\n\n PREPARE_TRANSACTIONS / TXS_IN_BLOCK[2],\n\n TXS_IN_BLOCK[2],\n\n );\n\n\n\n // Pre-cache transactions for the created block.\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 85, "score": 197879.00976307335 }, { "content": "struct MessageVerifier {\n\n tx_sender: Option<Sender<InternalRequest>>,\n\n tx_handler: MessagesHandlerRef,\n\n network_thread: JoinHandle<()>,\n\n handler_thread: JoinHandle<()>,\n\n api_sender: Option<Sender<ExternalMessage>>,\n\n network_sender: Option<Sender<NetworkEvent>>,\n\n}\n\n\n\nimpl MessageVerifier {\n\n fn new() -> Self {\n\n let channel = NodeChannel::new(&EventsPoolCapacity::default());\n\n let handler = MessagesHandlerRef::new();\n\n\n\n let handler_part = HandlerPart {\n\n handler: handler.clone(),\n\n internal_rx: channel.internal_events.1,\n\n network_rx: channel.network_events.1,\n\n api_rx: channel.api_requests.1,\n\n };\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 86, "score": 197865.6442143454 }, { "content": "struct MessagesHandler {\n\n txs_count: usize,\n\n expected_count: usize,\n\n finish_signal: Option<oneshot::Sender<()>>,\n\n}\n\n\n\nimpl MessagesHandler {\n\n fn new(expected_count: usize) -> (Self, oneshot::Receiver<()>) {\n\n let channel = oneshot::channel();\n\n\n\n let handler = MessagesHandler {\n\n txs_count: 0,\n\n expected_count,\n\n finish_signal: Some(channel.0),\n\n };\n\n (handler, channel.1)\n\n }\n\n\n\n fn is_finished(&self) -> bool {\n\n self.finish_signal.is_none()\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 87, "score": 197865.6442143454 }, { "content": "fn copy_secured(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<(), failure::Error> {\n\n let mut source_file = fs::File::open(&from)?;\n\n\n\n let mut destination_file = {\n\n let mut open_options = OpenOptions::new();\n\n open_options.create(true).write(true);\n\n #[cfg(unix)]\n\n open_options.mode(0o600);\n\n open_options.open(&to)?\n\n };\n\n\n\n std::io::copy(&mut source_file, &mut destination_file)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "exonum/tests/config.rs", "rank": 88, "score": 197580.84254142767 }, { "content": "// Makes large data set with unique keys\n\nfn generate_random_data(len: usize) -> Vec<([u8; KEY_SIZE], Vec<u8>)> {\n\n let mut rng = thread_rng();\n\n let mut exists_keys = HashSet::new();\n\n let mut base = [0; KEY_SIZE];\n\n rng.fill_bytes(&mut base);\n\n\n\n let kv_generator = |_| {\n\n let mut v = vec![0; 8];\n\n\n\n // Generate only unique keys\n\n let mut k = base;\n\n let byte: usize = rng.gen_range(0, 31);\n\n k[byte] = rng.gen::<u8>();\n\n\n\n rng.fill_bytes(&mut v);\n\n while exists_keys.contains(&k) {\n\n rng.fill_bytes(&mut k);\n\n }\n\n exists_keys.insert(k);\n\n (k, v)\n\n };\n\n\n\n (0..len).map(kv_generator).collect::<Vec<_>>()\n\n}\n\n\n", "file_path": "components/merkledb/src/proof_map_index/tests.rs", "rank": 89, "score": 197560.58383299276 }, { "content": "#[test]\n\nfn received_block_while_there_is_pending_block() {\n\n let sandbox = timestamping_sandbox();\n\n\n\n let tx = gen_timestamping_tx();\n\n\n\n let propose = ProposeBuilder::new(&sandbox).build();\n\n\n\n let block = BlockBuilder::new(&sandbox)\n\n .with_tx_hash(&compute_tx_hash(&[tx.clone()]))\n\n .with_state_hash(&sandbox.compute_state_hash(&[tx.clone()]))\n\n .build();\n\n\n\n sandbox.recv(&sandbox.create_status(\n\n &sandbox.public_key(ValidatorId(3)),\n\n Height(2),\n\n &block.hash(),\n\n 0,\n\n sandbox.secret_key(ValidatorId(3)),\n\n ));\n\n\n", "file_path": "exonum/src/sandbox/consensus/block_request.rs", "rank": 90, "score": 195289.83953902847 }, { "content": "#[derive(Clone)]\n\nstruct MessagesHandlerRef {\n\n // We need to reset the handler from the main thread and then access it from the\n\n // handler thread, hence the use of `Arc<RwLock<_>>`.\n\n inner: Arc<RwLock<MessagesHandler>>,\n\n}\n\n\n\nimpl MessagesHandlerRef {\n\n fn new() -> Self {\n\n let (handler, _) = MessagesHandler::new(0);\n\n MessagesHandlerRef {\n\n inner: Arc::new(RwLock::new(handler)),\n\n }\n\n }\n\n\n\n fn reset(&self, expected_count: usize) -> oneshot::Receiver<()> {\n\n let (handler, finish_signal) = MessagesHandler::new(expected_count);\n\n *self.inner.write().unwrap() = handler;\n\n finish_signal\n\n }\n\n}\n\n\n\nimpl EventHandler for MessagesHandlerRef {\n\n fn handle_event(&mut self, event: Event) {\n\n self.inner.write().unwrap().handle_event(event);\n\n }\n\n}\n\n\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 91, "score": 194527.25948896364 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]\n\nstruct Wallet {\n\n incoming: u32,\n\n outgoing: u32,\n\n history_root: Hash,\n\n}\n\n\n\nimpl BinaryValue for Wallet {\n\n fn to_bytes(&self) -> Vec<u8> {\n\n bincode::serialize(self).unwrap()\n\n }\n\n\n\n fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> {\n\n bincode::deserialize(bytes.as_ref()).map_err(From::from)\n\n }\n\n}\n\n\n", "file_path": "components/merkledb/examples/blockchain.rs", "rank": 92, "score": 192552.0808224695 }, { "content": "#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\n\nstruct Block {\n\n prev_block: Hash,\n\n transactions: Vec<Transaction>,\n\n}\n\n\n\nimpl BinaryValue for Block {\n\n fn to_bytes(&self) -> Vec<u8> {\n\n bincode::serialize(self).unwrap()\n\n }\n\n\n\n fn from_bytes(bytes: Cow<[u8]>) -> Result<Self, failure::Error> {\n\n bincode::deserialize(bytes.as_ref()).map_err(From::from)\n\n }\n\n}\n\n\n\nimpl Transaction {\n\n fn execute(&self, fork: &Fork) {\n\n let tx_hash = self.object_hash();\n\n\n\n let schema = Schema::new(fork);\n", "file_path": "components/merkledb/examples/blockchain.rs", "rank": 93, "score": 192397.7016042358 }, { "content": "fn _fork_iter<T, I>(db: &T, address: I)\n\nwhere\n\n T: Database,\n\n I: Into<IndexAddress> + Copy,\n\n{\n\n let fork = db.fork();\n\n {\n\n let view = View::new(&fork, address);\n\n let mut view = view;\n\n view.put(&vec![10], vec![10]);\n\n view.put(&vec![20], vec![20]);\n\n view.put(&vec![30], vec![30]);\n\n assert!(view.contains_raw_key(&[10]));\n\n }\n\n db.merge(fork.into_patch()).unwrap();\n\n\n\n let fork = db.fork();\n\n let mut view = View::new(&fork, address);\n\n assert!(view.contains_raw_key(&[10]));\n\n\n", "file_path": "components/merkledb/src/views/tests.rs", "rank": 94, "score": 192102.92780632924 }, { "content": "#[test]\n\nfn received_block_while_there_is_full_propose() {\n\n let sandbox = timestamping_sandbox();\n\n\n\n let tx = gen_timestamping_tx();\n\n\n\n let propose = ProposeBuilder::new(&sandbox)\n\n .with_height(Height(1))\n\n .with_validator(ValidatorId(2))\n\n .with_tx_hashes(&[tx.hash()])\n\n .build();\n\n\n\n let block = BlockBuilder::new(&sandbox)\n\n .with_tx_hash(&compute_tx_hash(&[tx.clone()]))\n\n .with_state_hash(&sandbox.compute_state_hash(&[tx.clone()]))\n\n .build();\n\n\n\n sandbox.recv(&sandbox.create_status(\n\n &sandbox.public_key(ValidatorId(3)),\n\n Height(2),\n\n &block.hash(),\n", "file_path": "exonum/src/sandbox/consensus/block_request.rs", "rank": 95, "score": 189506.00330348418 }, { "content": "/// Writes transactions to the pool and returns their hashes.\n\nfn prepare_txs(\n\n blockchain: &mut Blockchain,\n\n transactions: Vec<Signed<RawTransaction>>,\n\n) -> Vec<Hash> {\n\n let fork = blockchain.fork();\n\n\n\n let tx_hashes = {\n\n let mut schema = Schema::new(&fork);\n\n\n\n // In the case of the block within `Bencher::iter()`, some transactions\n\n // may already be present in the pool. We don't particularly care about this.\n\n transactions\n\n .into_iter()\n\n .map(|tx| {\n\n let hash = tx.hash();\n\n schema.add_transaction_into_pool(tx);\n\n hash\n\n })\n\n .collect()\n\n };\n\n\n\n blockchain.merge(fork.into_patch()).unwrap();\n\n tx_hashes\n\n}\n\n\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 96, "score": 189365.1712387557 }, { "content": "fn prepare_blockchain(\n\n blockchain: &mut Blockchain,\n\n generator: impl Iterator<Item = Signed<RawTransaction>>,\n\n blockchain_height: usize,\n\n txs_in_block: usize,\n\n) {\n\n let transactions: Vec<_> = generator.take(txs_in_block * blockchain_height).collect();\n\n\n\n for i in 0..blockchain_height {\n\n let start = txs_in_block * i;\n\n let end = txs_in_block * (i + 1);\n\n let tx_hashes = prepare_txs(blockchain, transactions[start..end].to_vec());\n\n assert_transactions_in_pool(blockchain, &tx_hashes);\n\n\n\n let (block_hash, patch) = execute_block(blockchain, i as u64, &tx_hashes);\n\n // We make use of the fact that `Blockchain::commit()` doesn't check\n\n // precommits in any way (they are checked beforehand by the consensus algorithm).\n\n blockchain\n\n .commit(patch, block_hash, iter::empty(), &mut BTreeMap::new())\n\n .unwrap();\n\n }\n\n}\n\n\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 97, "score": 189353.58944786596 }, { "content": "/// Computes a Merkle root hash for a the given list of hashes.\n\n///\n\n/// If `hashes` are empty then `Hash::zero()` value is returned.\n\npub fn root_hash(hashes: &[Hash]) -> Hash {\n\n if hashes.is_empty() {\n\n return Hash::zero();\n\n }\n\n\n\n let mut hashes: Vec<Hash> = hashes\n\n .iter()\n\n .map(|h| HashTag::hash_leaf(&h.to_bytes()))\n\n .collect();\n\n\n\n let mut end = hashes.len();\n\n let mut index = 0;\n\n\n\n while end > 1 {\n\n let first = hashes[index];\n\n\n\n let result = if index < end - 1 {\n\n HashTag::hash_node(&first, &hashes[index + 1])\n\n } else {\n\n HashTag::hash_single_node(&first)\n", "file_path": "components/merkledb/src/hash.rs", "rank": 98, "score": 189077.1970490832 }, { "content": "/// Returns the wallet identified by the given public key.\n\nfn get_wallet(testkit: &TestKit, pubkey: &PublicKey) -> Wallet {\n\n try_get_wallet(testkit, pubkey).expect(\"No wallet persisted\")\n\n}\n", "file_path": "examples/cryptocurrency/tests/tx_logic.rs", "rank": 99, "score": 187790.48631934723 } ]
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//==============================================================================\n\n// init\n\n//==============================================================================\n\n\n\n#[allow(unused)]\n\n#[no_mangle]\n\npub extern \"C\" fn dmtr_init(argc: c_int, argv: *mut *mut c_char) -> c_int {\n\n logging::initialize();\n\n trace!(\"dmtr_init()\");\n\n\n\n // TODO: Pass arguments to the underlying libOS.\n\n let libos: LibOS = LibOS::new();\n\n\n", "file_path": "src/demikernel/bindings.rs", "rank": 0, "score": 152221.33864199187 }, { "content": "pub fn pack_result<RT: Runtime>(rt: &RT, result: OperationResult<RT::Buf>, qd: QDesc, qt: u64) -> dmtr_qresult_t {\n\n match result {\n\n OperationResult::Connect => dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_CONNECT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n\n qr_value: unsafe { mem::zeroed() },\n\n },\n\n OperationResult::Accept(new_qd) => {\n\n let sin = unsafe { mem::zeroed() };\n\n let qr_value = dmtr_qr_value_t {\n\n ares: dmtr_accept_result_t {\n\n qd: new_qd.into(),\n\n addr: sin,\n\n },\n\n };\n\n dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_ACCEPT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n", "file_path": "src/catnip/interop.rs", "rank": 1, "score": 86176.03220198092 }, { "content": "pub fn pack_result<RT: Runtime>(rt: &RT, result: OperationResult<RT::Buf>, qd: QDesc, qt: u64) -> dmtr_qresult_t {\n\n match result {\n\n OperationResult::Connect => dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_CONNECT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n\n qr_value: unsafe { mem::zeroed() },\n\n },\n\n OperationResult::Accept(new_qd) => {\n\n let sin = unsafe { mem::zeroed() };\n\n let qr_value = dmtr_qr_value_t {\n\n ares: dmtr_accept_result_t {\n\n qd: new_qd.into(),\n\n addr: sin,\n\n },\n\n };\n\n dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_ACCEPT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n", "file_path": "src/catpowder/interop.rs", "rank": 2, "score": 86176.03220198092 }, { "content": "/// Converts a [sockaddr] into a [Ipv4Endpoint].\n\nfn sockaddr_to_ipv4endpoint(saddr: *const sockaddr) -> Result<Ipv4Endpoint, Fail> {\n\n // TODO: Review why we need byte ordering conversion here.\n\n let sin: libc::sockaddr_in = unsafe { *mem::transmute::<*const sockaddr, *const libc::sockaddr_in>(saddr) };\n\n let addr: Ipv4Addr = { Ipv4Addr::from(u32::from_be_bytes(sin.sin_addr.s_addr.to_le_bytes())) };\n\n let port: Port16 = Port16::try_from(u16::from_be(sin.sin_port))?;\n\n Ok(Ipv4Endpoint::new(addr, port))\n\n}\n", "file_path": "src/demikernel/bindings.rs", "rank": 3, "score": 78440.88159076037 }, { "content": "#[test]\n\nfn udp_push_pop() {\n\n let mut test = Test::new();\n\n let fill_char: u8 = 'a' as u8;\n\n let nsends: usize = 1000;\n\n let nreceives: usize = (10 * nsends) / 100;\n\n let local_addr: Ipv4Endpoint = test.local_addr();\n\n let remote_addr: Ipv4Endpoint = test.remote_addr();\n\n\n\n // Setup peer.\n\n let sockfd: QDesc = match test.libos.socket(libc::AF_INET, libc::SOCK_DGRAM, 0) {\n\n Ok(qd) => qd,\n\n Err(e) => panic!(\"failed to create socket: {:?}\", e.cause),\n\n };\n\n match test.libos.bind(sockfd, local_addr) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"bind failed: {:?}\", e.cause),\n\n };\n\n\n\n // Run peers.\n\n if test.is_server() {\n", "file_path": "tests/rust/pushpop.rs", "rank": 4, "score": 53511.583471003454 }, { "content": "#[test]\n\nfn tcp_push_pop() {\n\n let mut test: Test = Test::new();\n\n let fill_char: u8 = 'a' as u8;\n\n let nbytes: usize = 64 * 1024;\n\n let local_addr: Ipv4Endpoint = test.local_addr();\n\n let remote_addr: Ipv4Endpoint = test.remote_addr();\n\n\n\n // Setup peer.\n\n let sockqd: QDesc = match test.libos.socket(libc::AF_INET, libc::SOCK_STREAM, 0) {\n\n Ok(qd) => qd,\n\n Err(e) => panic!(\"failed to create socket: {:?}\", e.cause),\n\n };\n\n match test.libos.bind(sockqd, local_addr) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"bind failed: {:?}\", e.cause),\n\n };\n\n\n\n // Run peers.\n\n if test.is_server() {\n\n // Mark as a passive one.\n", "file_path": "tests/rust/pushpop.rs", "rank": 5, "score": 53511.583471003454 }, { "content": "#[test]\n\nfn udp_ping_pong() {\n\n let mut test: Test = Test::new();\n\n let fill_char: u8 = 'a' as u8;\n\n let local_addr: Ipv4Endpoint = test.local_addr();\n\n let remote_addr: Ipv4Endpoint = test.remote_addr();\n\n\n\n // Setup peer.\n\n let sockfd: QDesc = match test.libos.socket(libc::AF_INET, libc::SOCK_DGRAM, 0) {\n\n Ok(qd) => qd,\n\n Err(e) => panic!(\"failed to create socket: {:?}\", e.cause),\n\n };\n\n match test.libos.bind(sockfd, local_addr) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"bind failed: {:?}\", e.cause),\n\n };\n\n\n\n // Run peers.\n\n if test.is_server() {\n\n let mut npongs: usize = 0;\n\n loop {\n", "file_path": "tests/rust/pingpong.rs", "rank": 6, "score": 53511.583471003454 }, { "content": "#[test]\n\nfn tcp_ping_pong_single() {\n\n let mut test: Test = Test::new();\n\n let fill_char: u8 = 'a' as u8;\n\n let nrounds: usize = 1024;\n\n let local_addr: Ipv4Endpoint = test.local_addr();\n\n let remote_addr: Ipv4Endpoint = test.remote_addr();\n\n let expectbuf: Vec<u8> = test.mkbuf(fill_char);\n\n\n\n // Setup peer.\n\n let sockqd: QDesc = match test.libos.socket(libc::AF_INET, libc::SOCK_STREAM, 0) {\n\n Ok(qd) => qd,\n\n Err(e) => panic!(\"failed to create socket: {:?}\", e.cause),\n\n };\n\n match test.libos.bind(sockqd, local_addr) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"bind failed: {:?}\", e.cause),\n\n };\n\n\n\n // Run peers.\n\n if test.is_server() {\n", "file_path": "tests/rust/pingpong.rs", "rank": 7, "score": 52359.06067736652 }, { "content": "#[test]\n\nfn tcp_ping_pong_multiple() {\n\n let mut test: Test = Test::new();\n\n let fill_char: u8 = 'a' as u8;\n\n let nrounds: usize = 1024;\n\n let local_addr: Ipv4Endpoint = test.local_addr();\n\n let remote_addr: Ipv4Endpoint = test.remote_addr();\n\n let expectbuf: Vec<u8> = test.mkbuf(fill_char);\n\n\n\n // Setup peer.\n\n let sockqd: QDesc = match test.libos.socket(libc::AF_INET, libc::SOCK_STREAM, 0) {\n\n Ok(qd) => qd,\n\n Err(e) => panic!(\"failed to create socket: {:?}\", e.cause),\n\n };\n\n match test.libos.bind(sockqd, local_addr) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"bind failed: {:?}\", e.cause),\n\n };\n\n\n\n // Run peers.\n\n if test.is_server() {\n", "file_path": "tests/rust/pingpong.rs", "rank": 8, "score": 52359.06067736652 }, { "content": "#[test]\n\nfn test_unit_sga_alloc_free_single_small() {\n\n do_test_unit_sga_alloc_free_single(SGA_SIZE_SMALL)\n\n}\n\n\n\n/// Tests a single allocation and deallocation of a big scatter-gather array.\n", "file_path": "tests/rust/sga.rs", "rank": 9, "score": 49330.58542398686 }, { "content": "#[test]\n\nfn test_unit_sga_alloc_free_single_big() {\n\n do_test_unit_sga_alloc_free_single(SGA_SIZE_BIG)\n\n}\n\n\n\n//==============================================================================\n\n// test_unit_sga_alloc_free_loop_tight()\n\n//==============================================================================\n\n\n", "file_path": "tests/rust/sga.rs", "rank": 10, "score": 49330.58542398686 }, { "content": "#[test]\n\nfn test_unit_sga_alloc_free_loop_decoupled_small() {\n\n do_test_unit_sga_alloc_free_loop_decoupled(SGA_SIZE_SMALL)\n\n}\n\n\n\n/// Tests decoupled looped allocation and deallocation of big scatter-gather arrays.\n", "file_path": "tests/rust/sga.rs", "rank": 11, "score": 48442.604251360535 }, { "content": "#[test]\n\nfn test_unit_sga_alloc_free_loop_tight_small() {\n\n do_test_unit_sga_alloc_free_loop_tight(SGA_SIZE_SMALL)\n\n}\n\n\n\n/// Tests looped allocation and deallocation of big scatter-gather arrays.\n", "file_path": "tests/rust/sga.rs", "rank": 12, "score": 48442.604251360535 }, { "content": "#[test]\n\nfn test_unit_sga_alloc_free_loop_tight_big() {\n\n do_test_unit_sga_alloc_free_loop_tight(SGA_SIZE_BIG)\n\n}\n\n\n\n//==============================================================================\n\n// test_unit_sga_alloc_free_loop_decoupled()\n\n//==============================================================================\n\n\n", "file_path": "tests/rust/sga.rs", "rank": 13, "score": 48442.604251360535 }, { "content": "#[test]\n\nfn test_unit_sga_alloc_free_loop_decoupled_big() {\n\n do_test_unit_sga_alloc_free_loop_decoupled(SGA_SIZE_BIG)\n\n}\n", "file_path": "tests/rust/sga.rs", "rank": 14, "score": 48442.604251360535 }, { "content": "/// Tests for a single scatter-gather array allocation and deallocation.\n\nfn do_test_unit_sga_alloc_free_single(size: usize) {\n\n let libos: LibOS = LibOS::new();\n\n\n\n let sga: dmtr_sgarray_t = match libos.sgaalloc(size) {\n\n Ok(sga) => sga,\n\n Err(e) => panic!(\"failed to allocate sga: {:?}\", e.cause),\n\n };\n\n match libos.sgafree(sga) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"failed to release sga: {:?}\", e.cause),\n\n };\n\n}\n\n\n\n/// Tests a single allocation and deallocation of a small scatter-gather array.\n", "file_path": "tests/rust/sga.rs", "rank": 15, "score": 44028.38046350019 }, { "content": "/// Parses a [Ipv4Endpoint] into a [SockAddr].\n\nfn parse_addr(endpoint: Ipv4Endpoint) -> SockAddr {\n\n let ipv4: std::net::IpAddr = std::net::IpAddr::V4(endpoint.get_address());\n\n let ip: socket::IpAddr = socket::IpAddr::from_std(&ipv4);\n\n let portnum: Port16 = endpoint.get_port();\n\n let inet: InetAddr = InetAddr::new(ip, portnum.into());\n\n SockAddr::new_inet(inet)\n\n}\n\n\n", "file_path": "src/catnap/mod.rs", "rank": 16, "score": 43372.654200141566 }, { "content": "/// Parses a [Ipv4Endpoint] into a [SockAddr].\n\nfn parse_addr(endpoint: Ipv4Endpoint) -> SockAddr {\n\n let ipv4: std::net::IpAddr = std::net::IpAddr::V4(endpoint.get_address());\n\n let ip: socket::IpAddr = socket::IpAddr::from_std(&ipv4);\n\n let portnum: Port16 = endpoint.get_port();\n\n let inet: InetAddr = InetAddr::new(ip, portnum.into());\n\n SockAddr::new_inet(inet)\n\n}\n\n\n", "file_path": "src/catcollar/mod.rs", "rank": 17, "score": 43372.654200141566 }, { "content": "/// Tests decoupled looped allocation and deallocation of scatter-gather arrays.\n\nfn do_test_unit_sga_alloc_free_loop_decoupled(size: usize) {\n\n let mut sgas: Vec<dmtr_sgarray_t> = Vec::with_capacity(1_000);\n\n let libos: LibOS = LibOS::new();\n\n\n\n // Allocate and deallocate several times.\n\n for _ in 0..1_000 {\n\n // Allocate many scatter-gather arrays.\n\n for _ in 0..1_000 {\n\n let sga: dmtr_sgarray_t = match libos.sgaalloc(size) {\n\n Ok(sga) => sga,\n\n Err(e) => panic!(\"failed to allocate sga: {:?}\", e.cause),\n\n };\n\n sgas.push(sga);\n\n }\n\n\n\n // Deallocate all scatter-gather arrays.\n\n for _ in 0..1_000 {\n\n let sga: dmtr_sgarray_t = sgas.pop().expect(\"pop from empty vector?\");\n\n match libos.sgafree(sga) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"failed to release sga: {:?}\", e.cause),\n\n };\n\n }\n\n }\n\n}\n\n\n\n/// Tests decoupled looped allocation and deallocation of small scatter-gather arrays.\n", "file_path": "tests/rust/sga.rs", "rank": 18, "score": 43192.28037633709 }, { "content": "/// Tests looped allocation and deallocation of scatter-gather arrays.\n\nfn do_test_unit_sga_alloc_free_loop_tight(size: usize) {\n\n let libos: LibOS = LibOS::new();\n\n\n\n // Allocate and deallocate several times.\n\n for _ in 0..1_000_000 {\n\n let sga: dmtr_sgarray_t = match libos.sgaalloc(size) {\n\n Ok(sga) => sga,\n\n Err(e) => panic!(\"failed to allocate sga: {:?}\", e.cause),\n\n };\n\n match libos.sgafree(sga) {\n\n Ok(()) => (),\n\n Err(e) => panic!(\"failed to release sga: {:?}\", e.cause),\n\n };\n\n }\n\n}\n\n\n\n/// Tests looped allocation and deallocation of small scatter-gather arrays.\n", "file_path": "tests/rust/sga.rs", "rank": 19, "score": 43192.28037633709 }, { "content": " void *sga_buf;\n", "file_path": "include/dmtr/types.h", "rank": 30, "score": 32746.68889328553 }, { "content": " void *sgaseg_buf;\n", "file_path": "include/dmtr/types.h", "rank": 31, "score": 32746.68889328553 }, { "content": "/// Packs a [OperationResult] into a [dmtr_qresult_t].\n\nfn pack_result(rt: &PosixRuntime, result: OperationResult, qd: QDesc, qt: u64) -> dmtr_qresult_t {\n\n match result {\n\n OperationResult::Connect => dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_CONNECT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n\n qr_value: unsafe { mem::zeroed() },\n\n },\n\n OperationResult::Accept(new_qd) => {\n\n let sin = unsafe { mem::zeroed() };\n\n let qr_value = dmtr_qr_value_t {\n\n ares: dmtr_accept_result_t {\n\n qd: new_qd.into(),\n\n addr: sin,\n\n },\n\n };\n\n dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_ACCEPT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n", "file_path": "src/catnap/mod.rs", "rank": 32, "score": 32299.67300379192 }, { "content": "/// Packs a [OperationResult] into a [dmtr_qresult_t].\n\nfn pack_result(rt: &IoUringRuntime, result: OperationResult, qd: QDesc, qt: u64) -> dmtr_qresult_t {\n\n match result {\n\n OperationResult::Connect => dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_CONNECT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n\n qr_value: unsafe { mem::zeroed() },\n\n },\n\n OperationResult::Accept(new_qd) => {\n\n let sin = unsafe { mem::zeroed() };\n\n let qr_value = dmtr_qr_value_t {\n\n ares: dmtr_accept_result_t {\n\n qd: new_qd.into(),\n\n addr: sin,\n\n },\n\n };\n\n dmtr_qresult_t {\n\n qr_opcode: dmtr_opcode_t::DMTR_OPC_ACCEPT,\n\n qr_qd: qd.into(),\n\n qr_qt: qt,\n", "file_path": "src/catcollar/mod.rs", "rank": 33, "score": 31726.298530415086 }, { "content": "\n\n /// Returns a pointer to the underlying DPDK buffer stored in the target [Mbuf].\n\n pub fn get_ptr(&self) -> *mut rte_mbuf {\n\n self.ptr\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Clone Trait Implementation for DPDK-Managed Buffers\n\nimpl Clone for Mbuf {\n\n fn clone(&self) -> Self {\n\n let mbuf_ptr: *mut rte_mbuf = match MemoryPool::clone_mbuf(self.ptr) {\n\n Ok(mbuf_ptr) => mbuf_ptr,\n\n Err(e) => panic!(\"failed to clone mbuf: {:?}\", e.cause),\n\n };\n\n\n\n Mbuf::new(mbuf_ptr)\n", "file_path": "src/catnip/runtime/memory/mbuf.rs", "rank": 34, "score": 25.583295152026622 }, { "content": " unsafe {\n\n let buf_ptr = (*self.ptr).buf_addr as *mut u8;\n\n buf_ptr.offset((*self.ptr).data_off as isize)\n\n }\n\n }\n\n\n\n /// Returns the length of the data stored in the target [Mbuf].\n\n pub fn len(&self) -> usize {\n\n unsafe { (*self.ptr).data_len as usize }\n\n }\n\n\n\n /// Converts the target [Mbuf] into a mutable [u8] slice.\n\n pub unsafe fn slice_mut(&mut self) -> &mut [u8] {\n\n slice::from_raw_parts_mut(self.data_ptr(), self.len())\n\n }\n\n\n\n /// Converts the target [Mbuf] into a raw DPDK buffer.\n\n pub fn into_raw(mut self) -> *mut rte_mbuf {\n\n mem::replace(&mut self.ptr, ptr::null_mut())\n\n }\n", "file_path": "src/catnip/runtime/memory/mbuf.rs", "rank": 35, "score": 24.99089543711339 }, { "content": " }\n\n },\n\n }\n\n }\n\n\n\n /// Pushes a buffer to the target I/O user ring.\n\n pub fn pushto(&self, sockfd: i32, addr: SockAddr, buf: DataBuffer) -> Result<RequestId, Fail> {\n\n let request_id: RequestId = self.io_uring.borrow_mut().pushto(sockfd, addr, buf)?.into();\n\n Ok(request_id)\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Runtime Trait Implementation for I/O User Ring Runtime\n\nimpl Runtime for IoUringRuntime {}\n\n\n\n/// Conversion Trait Implementation for Request IDs\n\nimpl From<u64> for RequestId {\n\n fn from(val: u64) -> Self {\n\n RequestId(val)\n\n }\n\n}\n", "file_path": "src/catcollar/runtime/mod.rs", "rank": 36, "score": 23.86751041674709 }, { "content": "\n\n/// Future Trait Implementation for Push Operation Descriptors\n\nimpl Future for PushFuture {\n\n type Output = Result<(), Fail>;\n\n\n\n /// Polls the target [PushFuture].\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &mut PushFuture = self.get_mut();\n\n match socket::send(self_.fd, &self_.buf[..], socket::MsgFlags::empty()) {\n\n // Operation completed.\n\n Ok(nbytes) => {\n\n trace!(\"data pushed ({:?}/{:?} bytes)\", nbytes, self_.buf.len());\n\n Poll::Ready(Ok(()))\n\n },\n\n // Operation in progress.\n\n Err(e) if e == Errno::EWOULDBLOCK || e == Errno::EAGAIN => {\n\n ctx.waker().wake_by_ref();\n\n Poll::Pending\n\n },\n\n // Error.\n\n Err(e) => {\n\n warn!(\"push failed ({:?})\", e);\n\n Poll::Ready(Err(Fail::new(e as i32, \"operation failed\")))\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/catnap/futures/push.rs", "rank": 37, "score": 23.15162563513809 }, { "content": " name.as_ptr(),\n\n pool_size as u32,\n\n cache_size as u32,\n\n 0,\n\n data_room_size as u16,\n\n rte_socket_id() as i32,\n\n )\n\n };\n\n\n\n // Failed to create memory pool.\n\n if pool.is_null() {\n\n return Err(Fail::new(libc::EAGAIN, \"failed to create memory pool\"));\n\n }\n\n\n\n Ok(Self { pool })\n\n }\n\n\n\n /// Gets a raw pointer to the underlying memory pool.\n\n pub fn into_raw(&self) -> *mut rte_mempool {\n\n self.pool\n", "file_path": "src/catnip/runtime/memory/mempool.rs", "rank": 38, "score": 23.04739597349703 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::socket,\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n QDesc,\n\n};\n\nuse ::std::{\n\n future::Future,\n\n mem::size_of_val,\n\n os::unix::prelude::RawFd,\n\n pin::Pin,\n", "file_path": "src/catnap/futures/accept.rs", "rank": 39, "score": 23.034934753435355 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse crate::demikernel::dbuf::DataBuffer;\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::socket,\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n memory::Buffer,\n\n QDesc,\n\n};\n\nuse ::std::{\n\n future::Future,\n\n os::unix::prelude::RawFd,\n", "file_path": "src/catnap/futures/pop.rs", "rank": 40, "score": 22.869102298218984 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse crate::demikernel::dbuf::DataBuffer;\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::socket,\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n QDesc,\n\n};\n\nuse ::std::{\n\n future::Future,\n\n os::unix::prelude::RawFd,\n\n pin::Pin,\n", "file_path": "src/catnap/futures/push.rs", "rank": 41, "score": 22.86910229821898 }, { "content": "//==============================================================================\n\n// Exports\n\n//==============================================================================\n\n\n\npub use self::runtime::memory::DPDKBuf;\n\n\n\n//==============================================================================\n\n// Structures\n\n//==============================================================================\n\n\n\n/// Catnip LibOS\n\npub struct CatnipLibOS(InetStack<DPDKRuntime>);\n\n\n\n//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for Catnip LibOS\n\nimpl CatnipLibOS {\n\n pub fn new() -> Self {\n", "file_path": "src/catnip/mod.rs", "rank": 42, "score": 22.679341491867284 }, { "content": " }\n\n\n\n /// Removes `len` bytes at the beginning of the target [Mbuf].\n\n pub fn adjust(&mut self, len: usize) {\n\n assert!(len <= self.len());\n\n if unsafe { rte_pktmbuf_adj(self.ptr, len as u16) } == ptr::null_mut() {\n\n panic!(\"rte_pktmbuf_adj failed\");\n\n }\n\n }\n\n\n\n /// Removes `len` bytes at the end of the target [Mbuf].\n\n pub fn trim(&mut self, len: usize) {\n\n assert!(len <= self.len());\n\n if unsafe { rte_pktmbuf_trim(self.ptr, len as u16) } != 0 {\n\n panic!(\"rte_pktmbuf_trim failed\");\n\n }\n\n }\n\n\n\n /// Returns a pointer to the data stored in the target [Mbuf].\n\n pub fn data_ptr(&self) -> *mut u8 {\n", "file_path": "src/catnip/runtime/memory/mbuf.rs", "rank": 43, "score": 22.575788319945758 }, { "content": " };\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: ptr::null_mut(),\n\n sga_numsegs: 1,\n\n sga_segs: [sgaseg],\n\n sga_addr: unsafe { mem::zeroed() },\n\n })\n\n }\n\n\n\n /// Allocates a scatter-gather array.\n\n fn alloc_sgarray(&self, size: usize) -> Result<dmtr_sgarray_t, Fail> {\n\n let allocation: Box<[u8]> = unsafe { Box::new_uninit_slice(size).assume_init() };\n\n let ptr: *mut [u8] = Box::into_raw(allocation);\n\n let sgaseg = dmtr_sgaseg_t {\n\n sgaseg_buf: ptr as *mut _,\n\n sgaseg_len: size as u32,\n\n };\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: ptr::null_mut(),\n\n sga_numsegs: 1,\n", "file_path": "src/catcollar/runtime/memory.rs", "rank": 44, "score": 21.53632617609984 }, { "content": " dmtr_sgaseg_t {\n\n sgaseg_buf: dbuf_ptr as *mut c_void,\n\n sgaseg_len: size as u32,\n\n },\n\n )\n\n };\n\n\n\n // TODO: Drop the sga_addr field in the scatter-gather array.\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: mbuf_ptr as *mut c_void,\n\n sga_numsegs: 1,\n\n sga_segs: [sgaseg],\n\n sga_addr: unsafe { mem::zeroed() },\n\n })\n\n }\n\n\n\n /// Releases a scatter-gather array.\n\n pub fn free_sgarray(&self, sga: dmtr_sgarray_t) -> Result<(), Fail> {\n\n // Check arguments.\n\n // TODO: Drop this check once we support scatter-gather arrays with multiple segments.\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 45, "score": 21.39426571335772 }, { "content": "\n\n /// Returns the new queue descriptor of the incoming connection associated\n\n /// to the target accept operation descriptor.\n\n pub fn get_new_qd(&self) -> QDesc {\n\n self.new_qd\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Future Trait Implementation for Accept Operation Descriptors\n\nimpl Future for AcceptFuture {\n\n type Output = Result<RawFd, Fail>;\n\n\n\n /// Polls the underlying accept operation.\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &AcceptFuture = self.get_mut();\n\n match socket::accept(self_.fd as i32) {\n", "file_path": "src/catcollar/futures/accept.rs", "rank": 46, "score": 21.260740419628114 }, { "content": " /// Returns the new queue descriptor associated to the target [AcceptFuture].\n\n pub fn get_new_qd(&self) -> QDesc {\n\n self.new_qd\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Future Trait Implementation for Accept Operation Descriptors\n\nimpl Future for AcceptFuture {\n\n type Output = Result<RawFd, Fail>;\n\n\n\n /// Polls the target [AcceptFuture].\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &AcceptFuture = self.get_mut();\n\n match socket::accept(self_.fd as i32) {\n\n // Operation completed.\n\n Ok(new_fd) => {\n", "file_path": "src/catnap/futures/accept.rs", "rank": 47, "score": 21.01728378574989 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse ::libc::{\n\n c_void,\n\n socklen_t,\n\n};\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::socket,\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n QDesc,\n\n};\n\nuse ::std::{\n", "file_path": "src/catcollar/futures/accept.rs", "rank": 48, "score": 20.896993132969765 }, { "content": " LibOS::NetworkLibOS(libos) => libos.wait_any2(qts),\n\n }\n\n }\n\n }\n\n }\n\n\n\n pub fn new() -> Self {\n\n logging::initialize();\n\n let libos = NetworkLibOS::new();\n\n\n\n Self::NetworkLibOS(libos)\n\n }\n\n\n\n /// Creates a socket.\n\n pub fn socket(&mut self, domain: c_int, socket_type: c_int, protocol: c_int) -> Result<QDesc, Fail> {\n\n match self {\n\n LibOS::NetworkLibOS(libos) => libos.socket(domain, socket_type, protocol),\n\n }\n\n }\n\n\n", "file_path": "src/demikernel/libos.rs", "rank": 49, "score": 20.80651689941896 }, { "content": "//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Future Trait Implementation for Connect Operation Descriptors\n\nimpl Future for ConnectFuture {\n\n type Output = Result<(), Fail>;\n\n\n\n /// Polls the underlying connect operation.\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &mut ConnectFuture = self.get_mut();\n\n match socket::connect(self_.fd as i32, &self_.addr) {\n\n // Operation completed.\n\n Ok(()) => {\n\n trace!(\"connection established ({:?})\", self_.addr);\n\n Poll::Ready(Ok(()))\n\n },\n\n // Operation not ready yet.\n\n Err(errno) if errno == Errno::EINPROGRESS || errno == Errno::EALREADY => {\n\n trace!(\"connect in progress ({:?})\", errno);\n", "file_path": "src/catcollar/futures/connect.rs", "rank": 50, "score": 20.665865769958394 }, { "content": " inner: Rc::new(Inner::new(memory_config)?),\n\n })\n\n }\n\n\n\n /// Converts a runtime buffer into a scatter-gather array.\n\n pub fn into_sgarray(&self, buf: DPDKBuf) -> Result<dmtr_sgarray_t, Fail> {\n\n let (mbuf_ptr, sgaseg): (*mut rte_mbuf, dmtr_sgaseg_t) = match buf {\n\n // Heap-managed buffer.\n\n DPDKBuf::External(dbuf) => {\n\n let len: usize = dbuf.len();\n\n let dbuf_ptr: *const [u8] = DataBuffer::into_raw(dbuf)?;\n\n (\n\n ptr::null_mut(),\n\n dmtr_sgaseg_t {\n\n sgaseg_buf: dbuf_ptr as *mut c_void,\n\n sgaseg_len: len as u32,\n\n },\n\n )\n\n },\n\n // DPDK-managed buffer.\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 51, "score": 20.620926559057615 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::{\n\n socket,\n\n socket::SockAddr,\n\n },\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n QDesc,\n\n};\n\nuse ::std::{\n\n future::Future,\n", "file_path": "src/catcollar/futures/connect.rs", "rank": 52, "score": 20.5392964105599 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::{\n\n socket,\n\n socket::SockAddr,\n\n },\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n QDesc,\n\n};\n\nuse ::std::{\n\n future::Future,\n", "file_path": "src/catnap/futures/connect.rs", "rank": 53, "score": 20.5392964105599 }, { "content": " ptr,\n\n slice,\n\n};\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Memory Runtime Trait Implementation for I/O User Ring Runtime\n\nimpl MemoryRuntime for IoUringRuntime {\n\n /// Memory Buffer\n\n type Buf = DataBuffer;\n\n\n\n /// Creates a scatter-gather array from a memory buffer.\n\n fn into_sgarray(&self, buf: DataBuffer) -> Result<dmtr_sgarray_t, Fail> {\n\n let buf_copy: Box<[u8]> = (&buf[..]).into();\n\n let ptr: *mut [u8] = Box::into_raw(buf_copy);\n\n let sgaseg: dmtr_sgaseg_t = dmtr_sgaseg_t {\n\n sgaseg_buf: ptr as *mut c_void,\n\n sgaseg_len: buf.len() as u32,\n", "file_path": "src/catcollar/runtime/memory.rs", "rank": 54, "score": 20.51813238808085 }, { "content": " let sgaseg: dmtr_sgaseg_t = dmtr_sgaseg_t {\n\n sgaseg_buf: dbuf_ptr as *mut c_void,\n\n sgaseg_len: len as u32,\n\n };\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: ptr::null_mut(),\n\n sga_numsegs: 1,\n\n sga_segs: [sgaseg],\n\n sga_addr: unsafe { mem::zeroed() },\n\n })\n\n }\n\n\n\n /// Allocates a scatter-gather array.\n\n fn alloc_sgarray(&self, size: usize) -> Result<dmtr_sgarray_t, Fail> {\n\n // Allocate a heap-managed buffer.\n\n let dbuf: DataBuffer = DataBuffer::new(size)?;\n\n let dbuf_ptr: *const [u8] = DataBuffer::into_raw(dbuf)?;\n\n let sgaseg: dmtr_sgaseg_t = dmtr_sgaseg_t {\n\n sgaseg_buf: dbuf_ptr as *mut c_void,\n\n sgaseg_len: size as u32,\n", "file_path": "src/catpowder/runtime/memory.rs", "rank": 55, "score": 20.3839795578334 }, { "content": "//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for I/O User Ring Runtime\n\nimpl IoUringRuntime {\n\n /// Creates an I/O user ring runtime.\n\n pub fn new(now: Instant) -> Self {\n\n let io_uring: IoUring = IoUring::new(CATCOLLAR_NUM_RINGS).expect(\"cannot create io_uring\");\n\n Self {\n\n timer: TimerRc(Rc::new(Timer::new(now))),\n\n scheduler: Scheduler::default(),\n\n io_uring: Rc::new(RefCell::new(io_uring)),\n\n pending: HashMap::new(),\n\n }\n\n }\n\n\n\n /// Pushes a buffer to the target I/O user ring.\n\n pub fn push(&mut self, sockfd: RawFd, buf: DataBuffer) -> Result<RequestId, Fail> {\n\n let request_id: RequestId = self.io_uring.borrow_mut().push(sockfd, buf)?.into();\n", "file_path": "src/catcollar/runtime/mod.rs", "rank": 56, "score": 20.374036934953995 }, { "content": " /// Creates a data buffer from a raw pointer and a length.\n\n pub fn from_raw_parts(data: *mut u8, len: usize) -> Result<Self, Fail> {\n\n // Check if arguments are valid.\n\n if len == 0 {\n\n return Err(Fail::new(libc::EINVAL, \"zero-length buffer\"));\n\n }\n\n if data.is_null() {\n\n return Err(Fail::new(libc::EINVAL, \"null data pointer\"));\n\n }\n\n\n\n // Perform conversions.\n\n let data: Arc<[u8]> = unsafe {\n\n let data_ptr: &mut [u8] = slice::from_raw_parts_mut(data, len);\n\n Arc::from_raw(data_ptr)\n\n };\n\n\n\n Ok(Self {\n\n data: Some(data),\n\n offset: 0,\n\n len,\n", "file_path": "src/demikernel/dbuf.rs", "rank": 57, "score": 20.34684624714848 }, { "content": "\n\n /// Clones a scatter-gather array.\n\n pub fn clone_sgarray(&self, sga: &dmtr_sgarray_t) -> Result<DPDKBuf, Fail> {\n\n // Check arguments.\n\n // TODO: Drop this check once we support scatter-gather arrays with multiple segments.\n\n if sga.sga_numsegs != 1 {\n\n return Err(Fail::new(libc::EINVAL, \"scatter-gather array with invalid size\"));\n\n }\n\n\n\n let sgaseg: dmtr_sgaseg_t = sga.sga_segs[0];\n\n let (ptr, len): (*mut c_void, usize) = (sgaseg.sgaseg_buf, sgaseg.sgaseg_len as usize);\n\n\n\n // Clone underlying buffer.\n\n let buf: DPDKBuf = if !sga.sga_buf.is_null() {\n\n // Clone DPDK-managed buffer.\n\n let mbuf_ptr: *mut rte_mbuf = sga.sga_buf as *mut rte_mbuf;\n\n let body_clone: *mut rte_mbuf = match MemoryPool::clone_mbuf(mbuf_ptr) {\n\n Ok(mbuf_ptr) => mbuf_ptr,\n\n Err(e) => panic!(\"failed to clone mbuf: {:?}\", e.cause),\n\n };\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 58, "score": 20.332082147919614 }, { "content": "\n\n//==============================================================================\n\n// Structures\n\n//==============================================================================\n\n\n\n/// Network LibOS\n\npub enum LibOS {\n\n NetworkLibOS(NetworkLibOS),\n\n}\n\n\n\n//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for Network LibOSes\n\nimpl LibOS {\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"catnip-libos\")] {\n\n /// Waits on a pending operation in an I/O queue.\n\n pub fn wait2(&mut self, qt: QToken) -> Result<(QDesc, OperationResult<DPDKBuf>), Fail> {\n", "file_path": "src/demikernel/libos.rs", "rank": 59, "score": 20.08803395844661 }, { "content": "use ::runtime::{\n\n fail::Fail,\n\n memory::Buffer,\n\n types::{\n\n dmtr_sgarray_t,\n\n dmtr_sgaseg_t,\n\n },\n\n};\n\nuse ::std::{\n\n ffi::CString,\n\n mem,\n\n ptr,\n\n rc::Rc,\n\n slice,\n\n};\n\n\n\n//==============================================================================\n\n// Exports\n\n//==============================================================================\n\n\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 60, "score": 19.937498165078164 }, { "content": " };\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: ptr::null_mut(),\n\n sga_numsegs: 1,\n\n sga_segs: [sgaseg],\n\n sga_addr: unsafe { mem::zeroed() },\n\n })\n\n }\n\n\n\n /// Allocates a scatter-gather array.\n\n fn alloc_sgarray(&self, size: usize) -> Result<dmtr_sgarray_t, Fail> {\n\n // Allocate a heap-managed buffer.\n\n let dbuf: DataBuffer = DataBuffer::new(size)?;\n\n let dbuf_ptr: *const [u8] = DataBuffer::into_raw(dbuf)?;\n\n let sgaseg: dmtr_sgaseg_t = dmtr_sgaseg_t {\n\n sgaseg_buf: dbuf_ptr as *mut c_void,\n\n sgaseg_len: size as u32,\n\n };\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: ptr::null_mut(),\n", "file_path": "src/catnap/runtime.rs", "rank": 61, "score": 19.92802317489565 }, { "content": " }\n\n\n\n /// Allocates a mbuf in the target memory pool.\n\n pub fn alloc_mbuf(&self, size: Option<usize>) -> Result<*mut rte_mbuf, Fail> {\n\n // TODO: Drop the following warning once DPDK memory management is more stable.\n\n warn!(\"allocating mbuf from DPDK pool\");\n\n\n\n // Allocate mbuf.\n\n let mut mbuf_ptr: *mut rte_mbuf = unsafe { rte_pktmbuf_alloc(self.pool) };\n\n if mbuf_ptr.is_null() {\n\n return Err(Fail::new(libc::ENOMEM, \"cannot allocate more mbufs\"));\n\n }\n\n\n\n // Fill out some fields of the underlying mbuf.\n\n unsafe {\n\n let mut num_bytes: u16 = (*mbuf_ptr).buf_len - (*mbuf_ptr).data_off;\n\n\n\n if let Some(size) = size {\n\n // Check if allocated buffer is big enough.\n\n if (size as u16) > num_bytes {\n", "file_path": "src/catnip/runtime/memory/mempool.rs", "rank": 62, "score": 19.84178379624163 }, { "content": "// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Future Trait Implementation for Connect Operation Descriptors\n\nimpl Future for ConnectFuture {\n\n type Output = Result<(), Fail>;\n\n\n\n /// Polls the target [ConnectFuture].\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &mut ConnectFuture = self.get_mut();\n\n match socket::connect(self_.fd as i32, &self_.addr) {\n\n // Operation completed.\n\n Ok(_) => {\n\n trace!(\"connection established ({:?})\", self_.addr);\n\n Poll::Ready(Ok(()))\n\n },\n\n // Operation not ready yet.\n\n Err(e) if e == Errno::EINPROGRESS || e == Errno::EALREADY => {\n\n ctx.waker().wake_by_ref();\n\n Poll::Pending\n", "file_path": "src/catnap/futures/connect.rs", "rank": 63, "score": 19.47958568465673 }, { "content": " Ok(request_id)\n\n }\n\n\n\n /// Pops a buffer from the target I/O user ring.\n\n pub fn pop(&mut self, sockfd: RawFd, buf: DataBuffer) -> Result<RequestId, Fail> {\n\n let request_id: RequestId = self.io_uring.borrow_mut().pop(sockfd, buf)?.into();\n\n Ok(request_id)\n\n }\n\n\n\n /// Peeks for the completion of an operation in the target I/O user ring.\n\n pub fn peek(&mut self, request_id: RequestId) -> Result<Option<i32>, Fail> {\n\n // Check if pending request has completed.\n\n match self.pending.remove(&request_id) {\n\n // The target request has already completed.\n\n Some(size) => Ok(Some(size)),\n\n // The target request may not be completed.\n\n None => {\n\n // Peek the underlying io_uring.\n\n match self.io_uring.borrow_mut().wait() {\n\n // Some operation has completed.\n", "file_path": "src/catcollar/runtime/mod.rs", "rank": 64, "score": 19.320115330684324 }, { "content": " let mut mbuf: Mbuf = Mbuf::new(body_clone);\n\n // Adjust buffer length.\n\n // TODO: Replace the following method for computing the length of a mbuf once we have a proper Mbuf abstraction.\n\n let orig_len: usize = unsafe { ((*mbuf_ptr).buf_len - (*mbuf_ptr).data_off).into() };\n\n let trim: usize = orig_len - len;\n\n mbuf.trim(trim);\n\n DPDKBuf::Managed(mbuf)\n\n } else {\n\n // Clone heap-managed buffer.\n\n let seg_slice: &[u8] = unsafe { slice::from_raw_parts(ptr as *const u8, len) };\n\n let buf: DataBuffer = DataBuffer::from_slice(seg_slice);\n\n DPDKBuf::External(buf)\n\n };\n\n\n\n Ok(buf)\n\n }\n\n\n\n /// Returns a raw pointer to the underlying body pool.\n\n /// TODO: Review the need of this function after we are done with the refactor of the DPDK runtime.\n\n pub fn body_pool(&self) -> *mut rte_mempool {\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 65, "score": 19.298164130770115 }, { "content": "//==============================================================================\n\n// Structures\n\n//==============================================================================\n\n\n\n/// DPDK-Managed Buffer\n\n#[derive(Debug)]\n\npub struct Mbuf {\n\n /// Underlying DPDK buffer.\n\n ptr: *mut rte_mbuf,\n\n}\n\n\n\n//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for DPDK-Managed Buffers\n\nimpl Mbuf {\n\n /// Creates a [Mbuf].\n\n pub fn new(ptr: *mut rte_mbuf) -> Self {\n\n Mbuf { ptr }\n", "file_path": "src/catnip/runtime/memory/mbuf.rs", "rank": 66, "score": 19.254083277680046 }, { "content": " },\n\n // Operation failed.\n\n Err(e) => {\n\n warn!(\"failed to accept connection ({:?})\", e);\n\n Poll::Ready(Err(Fail::new(e as i32, \"operation failed\")))\n\n },\n\n }\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Standalone Functions\n\n//==============================================================================\n\n\n\n/// Sets TCP_NODELAY option in a socket.\n\nunsafe fn set_tcp_nodelay(fd: RawFd) -> i32 {\n\n let value: u32 = 1;\n\n let value_ptr: *const u32 = &value as *const u32;\n\n let option_len: socklen_t = size_of_val(&value) as socklen_t;\n\n libc::setsockopt(\n", "file_path": "src/catcollar/futures/accept.rs", "rank": 67, "score": 19.12697328903951 }, { "content": " let mbuf_ptr: *mut rte_mbuf = self.inner.body_pool.alloc_mbuf(Some(size))?;\n\n\n\n // Adjust various fields in the mbuf and create a scatter-gather segment out of it.\n\n unsafe {\n\n let buf_ptr: *mut u8 = (*mbuf_ptr).buf_addr as *mut u8;\n\n let data_ptr: *mut u8 = buf_ptr.offset((*mbuf_ptr).data_off as isize);\n\n (\n\n mbuf_ptr,\n\n dmtr_sgaseg_t {\n\n sgaseg_buf: data_ptr as *mut c_void,\n\n sgaseg_len: size as u32,\n\n },\n\n )\n\n }\n\n } else {\n\n // Allocate a heap-managed buffer.\n\n let dbuf: DataBuffer = DataBuffer::new(size)?;\n\n let dbuf_ptr: *const [u8] = DataBuffer::into_raw(dbuf)?;\n\n (\n\n ptr::null_mut(),\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 68, "score": 19.124814669427177 }, { "content": " let mut mbuf = match self.mm.alloc_body_mbuf() {\n\n Ok(mbuf) => mbuf,\n\n Err(e) => panic!(\"failed to allocate body mbuf: {:?}\", e.cause),\n\n };\n\n assert!(mbuf.len() >= bytes.len());\n\n unsafe { mbuf.slice_mut()[..bytes.len()].copy_from_slice(&bytes[..]) };\n\n mbuf.trim(mbuf.len() - bytes.len());\n\n mbuf\n\n },\n\n };\n\n unsafe {\n\n assert_eq!(rte_pktmbuf_chain(header_mbuf.get_ptr(), body_mbuf.into_raw()), 0);\n\n }\n\n let mut header_mbuf_ptr = header_mbuf.into_raw();\n\n let num_sent = unsafe { rte_eth_tx_burst(self.port_id, 0, &mut header_mbuf_ptr, 1) };\n\n assert_eq!(num_sent, 1);\n\n }\n\n // Otherwise, write in the inline space.\n\n else {\n\n let body_buf = unsafe { &mut header_mbuf.slice_mut()[header_size..(header_size + body.len())] };\n", "file_path": "src/catnip/runtime/network.rs", "rank": 69, "score": 19.015269424714145 }, { "content": " /// Clones a mbuf into a memory pool.\n\n pub fn clone_mbuf(mbuf_ptr: *mut rte_mbuf) -> Result<*mut rte_mbuf, Fail> {\n\n unsafe {\n\n let mempool_ptr: *mut rte_mempool = (*mbuf_ptr).pool;\n\n let mbuf_ptr_clone: *mut rte_mbuf = rte_pktmbuf_clone(mbuf_ptr, mempool_ptr);\n\n if mbuf_ptr_clone.is_null() {\n\n return Err(Fail::new(libc::EINVAL, \"cannot clone mbuf\"));\n\n }\n\n\n\n Ok(mbuf_ptr_clone)\n\n }\n\n }\n\n}\n", "file_path": "src/catnip/runtime/memory/mempool.rs", "rank": 70, "score": 18.822952661924923 }, { "content": " /// Returns the queue descriptor associated to the target pop operation descriptor.\n\n pub fn get_qd(&self) -> QDesc {\n\n self.qd\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Future Trait Implementation for Pop Operation Descriptors\n\nimpl Future for PopFuture {\n\n type Output = Result<DataBuffer, Fail>;\n\n\n\n /// Polls the underlying pop operation.\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &mut PopFuture = self.get_mut();\n\n match self_.rt.peek(self_.request_id) {\n\n // Operation completed.\n\n Ok(Some(size)) if size >= 0 => {\n", "file_path": "src/catcollar/futures/pop.rs", "rank": 71, "score": 18.681421059619694 }, { "content": " Err(e) => {\n\n warn!(\"failed to accept connection ({:?})\", e);\n\n Poll::Ready(Err(Fail::new(e as i32, \"operation failed\")))\n\n },\n\n }\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Standalone Functions\n\n//==============================================================================\n\n\n\n/// Sets TCP_NODELAY option in a socket.\n\nunsafe fn set_tcp_nodelay(fd: RawFd) -> i32 {\n\n let value: u32 = 1;\n\n let value_ptr: *const u32 = &value as *const u32;\n\n let option_len: socklen_t = size_of_val(&value) as socklen_t;\n\n libc::setsockopt(\n\n fd,\n\n libc::IPPROTO_TCP,\n", "file_path": "src/catnap/futures/accept.rs", "rank": 72, "score": 18.660245051598153 }, { "content": "\n\n /// Initiates a connection with a remote TCP pper.\n\n pub fn connect(&mut self, fd: QDesc, remote: Ipv4Endpoint) -> Result<QToken, Fail> {\n\n match self {\n\n LibOS::NetworkLibOS(libos) => libos.connect(fd, remote),\n\n }\n\n }\n\n\n\n /// Closes a socket.\n\n pub fn close(&mut self, fd: QDesc) -> Result<(), Fail> {\n\n match self {\n\n LibOS::NetworkLibOS(libos) => libos.close(fd),\n\n }\n\n }\n\n\n\n /// Pushes a scatter-gather array to a TCP socket.\n\n pub fn push(&mut self, fd: QDesc, sga: &dmtr_sgarray_t) -> Result<QToken, Fail> {\n\n match self {\n\n LibOS::NetworkLibOS(libos) => libos.push(fd, sga),\n\n }\n", "file_path": "src/demikernel/libos.rs", "rank": 73, "score": 18.615979554975667 }, { "content": "};\n\nuse ::std::{\n\n mem,\n\n ptr,\n\n slice,\n\n};\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Memory Runtime Trait Implementation for Linux Runtime\n\nimpl MemoryRuntime for LinuxRuntime {\n\n /// Memory Buffer\n\n type Buf = DataBuffer;\n\n\n\n /// Converts a runtime buffer into a scatter-gather array.\n\n fn into_sgarray(&self, dbuf: DataBuffer) -> Result<dmtr_sgarray_t, Fail> {\n\n let len: usize = dbuf.len();\n\n let dbuf_ptr: *const [u8] = DataBuffer::into_raw(dbuf)?;\n", "file_path": "src/catpowder/runtime/memory.rs", "rank": 74, "score": 18.489767509119332 }, { "content": " DPDKBuf::Managed(mbuf) => {\n\n let mbuf_ptr: *mut rte_mbuf = mbuf.get_ptr();\n\n let sgaseg: dmtr_sgaseg_t = dmtr_sgaseg_t {\n\n sgaseg_buf: mbuf.data_ptr() as *mut c_void,\n\n sgaseg_len: mbuf.len() as u32,\n\n };\n\n mem::forget(mbuf);\n\n (mbuf_ptr, sgaseg)\n\n },\n\n };\n\n\n\n // TODO: Drop the sga_addr field in the scatter-gather array.\n\n Ok(dmtr_sgarray_t {\n\n sga_buf: mbuf_ptr as *mut c_void,\n\n sga_numsegs: 1,\n\n sga_segs: [sgaseg],\n\n sga_addr: unsafe { mem::zeroed() },\n\n })\n\n }\n\n\n", "file_path": "src/catnip/runtime/memory/manager.rs", "rank": 75, "score": 18.463708498921502 }, { "content": "use ::std::{\n\n rc::Rc,\n\n time::{\n\n Duration,\n\n Instant,\n\n },\n\n};\n\n\n\n//==============================================================================\n\n// Structures\n\n//==============================================================================\n\n\n\n#[derive(Clone)]\n\npub struct TimerRc(pub Rc<Timer<TimerRc>>);\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\nimpl TimerPtr for TimerRc {\n", "file_path": "src/catnip/runtime/scheduler.rs", "rank": 76, "score": 18.43778127665782 }, { "content": " // Allocated buffer is not big enough, rollback allocation.\n\n rte_pktmbuf_free(mbuf_ptr);\n\n return Err(Fail::new(libc::EFAULT, \"cannot allocate a mbuf this big\"));\n\n }\n\n num_bytes = size as u16;\n\n }\n\n (*mbuf_ptr).data_len = num_bytes;\n\n (*mbuf_ptr).pkt_len = num_bytes as u32;\n\n }\n\n\n\n Ok(mbuf_ptr)\n\n }\n\n\n\n /// Releases a mbuf in the target memory pool.\n\n pub fn free_mbuf(mbuf_ptr: *mut rte_mbuf) {\n\n unsafe {\n\n rte_pktmbuf_free(mbuf_ptr);\n\n }\n\n }\n\n\n", "file_path": "src/catnip/runtime/memory/mempool.rs", "rank": 77, "score": 18.41922887988758 }, { "content": " }\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Memory Runtime Trait Implementation for POSIX Runtime\n\nimpl MemoryRuntime for PosixRuntime {\n\n /// Memory Buffer\n\n type Buf = DataBuffer;\n\n\n\n /// Converts a runtime buffer into a scatter-gather array.\n\n fn into_sgarray(&self, dbuf: DataBuffer) -> Result<dmtr_sgarray_t, Fail> {\n\n let len: usize = dbuf.len();\n\n let dbuf_ptr: *const [u8] = DataBuffer::into_raw(dbuf)?;\n\n let sgaseg: dmtr_sgaseg_t = dmtr_sgaseg_t {\n\n sgaseg_buf: dbuf_ptr as *mut c_void,\n\n sgaseg_len: len as u32,\n", "file_path": "src/catnap/runtime.rs", "rank": 78, "score": 18.2716339717374 }, { "content": "// Structures\n\n//==============================================================================\n\n\n\n/// DPDK Memory Pool\n\n#[derive(Debug)]\n\npub struct MemoryPool {\n\n /// Underlying memory pool.\n\n pool: *mut rte_mempool,\n\n}\n\n\n\n//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associated functions for memory pool.\n\nimpl MemoryPool {\n\n /// Creates a new memory pool.\n\n pub fn new(name: CString, data_room_size: usize, pool_size: usize, cache_size: usize) -> Result<Self, Fail> {\n\n let pool: *mut rte_mempool = unsafe {\n\n rte_pktmbuf_pool_create(\n", "file_path": "src/catnip/runtime/memory/mempool.rs", "rank": 79, "score": 18.21839666027591 }, { "content": " let port_id: u16 = unsafe { rte_eth_find_next_owned_by(0, owner) as u16 };\n\n Self::initialize_dpdk_port(\n\n port_id,\n\n &memory_manager,\n\n use_jumbo_frames,\n\n mtu,\n\n tcp_checksum_offload,\n\n udp_checksum_offload,\n\n )?;\n\n\n\n // TODO: Where is this function?\n\n // if unsafe { rte_lcore_count() } > 1 {\n\n // eprintln!(\"WARNING: Too many lcores enabled. Only 1 used.\");\n\n // }\n\n\n\n let local_link_addr: MacAddress = unsafe {\n\n let mut m: MaybeUninit<rte_ether_addr> = MaybeUninit::zeroed();\n\n // TODO: Why does bindgen say this function doesn't return an int?\n\n rte_eth_macaddr_get(port_id, m.as_mut_ptr());\n\n MacAddress::new(m.assume_init().addr_bytes)\n", "file_path": "src/catnip/runtime/mod.rs", "rank": 80, "score": 18.028988674775547 }, { "content": "//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for Push Operation Descriptors\n\nimpl PushFuture {\n\n /// Creates a descriptor for a push operation.\n\n pub fn new(qd: QDesc, fd: RawFd, buf: DataBuffer) -> Self {\n\n Self { qd, fd, buf }\n\n }\n\n\n\n /// Returns the queue descriptor associated to the target [PushFuture].\n\n pub fn get_qd(&self) -> QDesc {\n\n self.qd\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n", "file_path": "src/catnap/futures/push.rs", "rank": 81, "score": 17.87942438101231 }, { "content": " trace!(\"data received ({:?} bytes)\", size);\n\n let trim_size: usize = self_.buf.len() - (size as usize);\n\n let mut buf: DataBuffer = self_.buf.clone();\n\n buf.trim(trim_size);\n\n Poll::Ready(Ok(buf))\n\n },\n\n // Operation in progress, re-schedule future.\n\n Ok(None) => {\n\n trace!(\"pop in progress\");\n\n ctx.waker().wake_by_ref();\n\n Poll::Pending\n\n },\n\n // Underlying asynchronous operation failed.\n\n Ok(Some(size)) if size < 0 => {\n\n let errno: i32 = -size;\n\n warn!(\"pop failed ({:?})\", errno);\n\n Poll::Ready(Err(Fail::new(errno, \"I/O error\")))\n\n },\n\n // Operation failed.\n\n Err(e) => {\n\n warn!(\"pop failed ({:?})\", e);\n\n Poll::Ready(Err(e))\n\n },\n\n // Should not happen.\n\n _ => panic!(\"pop failed: unknown error\"),\n\n }\n\n }\n\n}\n", "file_path": "src/catcollar/futures/pop.rs", "rank": 82, "score": 17.798362213902475 }, { "content": " else {\n\n if header_size < MIN_PAYLOAD_SIZE {\n\n let padding_bytes = MIN_PAYLOAD_SIZE - header_size;\n\n let padding_buf = unsafe { &mut header_mbuf.slice_mut()[header_size..][..padding_bytes] };\n\n for byte in padding_buf {\n\n *byte = 0;\n\n }\n\n }\n\n let frame_size = std::cmp::max(header_size, MIN_PAYLOAD_SIZE);\n\n header_mbuf.trim(header_mbuf.len() - frame_size);\n\n let mut header_mbuf_ptr = header_mbuf.into_raw();\n\n let num_sent = unsafe { rte_eth_tx_burst(self.port_id, 0, &mut header_mbuf_ptr, 1) };\n\n assert_eq!(num_sent, 1);\n\n }\n\n }\n\n\n\n fn receive(&self) -> ArrayVec<DPDKBuf, RECEIVE_BATCH_SIZE> {\n\n let mut out = ArrayVec::new();\n\n\n\n let mut packets: [*mut rte_mbuf; RECEIVE_BATCH_SIZE] = unsafe { mem::zeroed() };\n", "file_path": "src/catnip/runtime/network.rs", "rank": 83, "score": 17.671876204234778 }, { "content": " let sendbuf: Vec<u8> = test.mkbuf(fill_char);\n\n let mut qt: QToken = match test.libos.pop(sockfd) {\n\n Ok(qt) => qt,\n\n Err(e) => panic!(\"failed to pop: {:?}\", e.cause),\n\n };\n\n\n\n // Spawn timeout thread.\n\n let (sender, receiver): (Sender<i32>, Receiver<i32>) = mpsc::channel();\n\n let t: JoinHandle<()> = thread::spawn(move || match receiver.recv_timeout(Duration::from_secs(60)) {\n\n Ok(_) => {},\n\n _ => process::exit(0),\n\n });\n\n\n\n // Wait for incoming data.\n\n // TODO: add type annotation to the following variable once we drop generics on OperationResult.\n\n let recvbuf = match test.libos.wait2(qt) {\n\n Ok((_, OperationResult::Pop(_, buf))) => buf,\n\n _ => panic!(\"server failed to wait()\"),\n\n };\n\n\n", "file_path": "tests/rust/pingpong.rs", "rank": 84, "score": 17.47302481823349 }, { "content": "\n\n//==============================================================================\n\n// sgaalloc\n\n//==============================================================================\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn dmtr_sgaalloc(size: libc::size_t) -> dmtr_sgarray_t {\n\n trace!(\"dmtr_sgalloc()\");\n\n\n\n // Issue sgaalloc operation.\n\n with_libos(|libos| -> dmtr_sgarray_t {\n\n match libos.sgaalloc(size) {\n\n Ok(sga) => sga,\n\n Err(e) => {\n\n warn!(\"sgaalloc() failed: {:?}\", e);\n\n dmtr_sgarray_t {\n\n sga_buf: ptr::null_mut() as *mut _,\n\n sga_numsegs: 0,\n\n sga_segs: [dmtr_sgaseg_t {\n\n sgaseg_buf: ptr::null_mut() as *mut c_void,\n", "file_path": "src/demikernel/bindings.rs", "rank": 85, "score": 17.44413650949563 }, { "content": "\n\n // Send packet.\n\n match self.socket.borrow().send_to(&buf, dest_sockaddr.get_addr()) {\n\n // Operation succeeded.\n\n Ok(_) => (),\n\n // Operation failed, drop packet.\n\n Err(e) => warn!(\"dropping packet: {:?}\", e),\n\n };\n\n }\n\n\n\n /// Receives a batch of [PacketBuf].\n\n fn receive(&self) -> ArrayVec<DataBuffer, RECEIVE_BATCH_SIZE> {\n\n // 4096B buffer size chosen arbitrarily, seems fine for now.\n\n // This use-case is an example for MaybeUninit in the docs\n\n let mut out: [MaybeUninit<u8>; 4096] = [unsafe { MaybeUninit::uninit().assume_init() }; 4096];\n\n if let Ok((nbytes, _origin_addr)) = self.socket.borrow().recv_from(&mut out[..]) {\n\n let mut ret = ArrayVec::new();\n\n unsafe {\n\n let bytes: [u8; 4096] = mem::transmute::<[MaybeUninit<u8>; 4096], [u8; 4096]>(out);\n\n let mut dbuf: DataBuffer = DataBuffer::from_slice(&bytes);\n", "file_path": "src/catpowder/runtime/network.rs", "rank": 86, "score": 17.35683190071062 }, { "content": " }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// Future Trait Implementation for Pushto Operation Descriptors\n\nimpl Future for PushtoFuture {\n\n type Output = Result<(), Fail>;\n\n\n\n /// Polls the target [PushtoFuture].\n\n fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let self_: &mut PushtoFuture = self.get_mut();\n\n match socket::sendto(self_.fd, &self_.buf[..], &self_.addr, MsgFlags::empty()) {\n\n // Operation completed.\n\n Ok(nbytes) => {\n\n trace!(\"data pushed ({:?}/{:?} bytes)\", nbytes, self_.buf.len());\n\n Poll::Ready(Ok(()))\n\n },\n", "file_path": "src/catnap/futures/pushto.rs", "rank": 87, "score": 17.272792323086016 }, { "content": "\n\n cfg_if::cfg_if! {\n\n if #[cfg(feature = \"catnip-libos\")] {\n\n /// Waits an a pending operation in an I/O queue.\n\n pub fn wait_any2(&mut self, qts: &[QToken]) -> Result<(usize, QDesc, OperationResult<DPDKBuf>), Fail> {\n\n match self {\n\n LibOS::NetworkLibOS(libos) => libos.wait_any2(qts),\n\n }\n\n }\n\n } else if #[cfg(feature = \"catpowder-libos\")] {\n\n /// Waits on a pending operation in an I/O queue.\n\n pub fn wait_any2(&mut self, qts: &[QToken]) -> Result<(usize, QDesc, OperationResult<DataBuffer>), Fail> {\n\n match self {\n\n LibOS::NetworkLibOS(libos) => libos.wait_any2(qts),\n\n }\n\n }\n\n } else {\n\n /// Waits on a pending operation in an I/O queue.\n\n pub fn wait_any2(&mut self, qts: &[QToken]) -> Result<(usize, QDesc, OperationResult), Fail> {\n\n match self {\n", "file_path": "src/demikernel/libos.rs", "rank": 88, "score": 17.19874928710329 }, { "content": " // Underlying file descriptor.\n\n fd: RawFd,\n\n /// Buffer to send.\n\n buf: DataBuffer,\n\n}\n\n\n\n//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for Pushto Operation Descriptors\n\nimpl PushtoFuture {\n\n /// Creates a descriptor for a pushto operation.\n\n pub fn new(qd: QDesc, fd: RawFd, addr: SockAddr, buf: DataBuffer) -> Self {\n\n Self { qd, addr, fd, buf }\n\n }\n\n\n\n /// Returns the queue descriptor associated to the target [PushtoFuture].\n\n pub fn get_qd(&self) -> QDesc {\n\n self.qd\n", "file_path": "src/catnap/futures/pushto.rs", "rank": 89, "score": 17.140083653522684 }, { "content": " type Target = InetStack<DPDKRuntime>;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\n/// Mutable De-Reference Trait Implementation for Catnip LibOS\n\nimpl DerefMut for CatnipLibOS {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n &mut self.0\n\n }\n\n}\n", "file_path": "src/catnip/mod.rs", "rank": 90, "score": 17.10408913330053 }, { "content": " }\n\n}\n\n\n\n/// Mutable De-Reference Trait Implementation for Catpowder LibOS\n\nimpl DerefMut for CatpowderLibOS {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n &mut self.0\n\n }\n\n}\n", "file_path": "src/catpowder/mod.rs", "rank": 91, "score": 16.99273039443716 }, { "content": "//==============================================================================\n\n// Test\n\n//==============================================================================\n\n\n\npub struct TestConfig(pub Config);\n\n\n\nimpl TestConfig {\n\n pub fn new() -> Self {\n\n let config = Config::new(std::env::var(\"CONFIG_PATH\").unwrap());\n\n\n\n Self(config)\n\n }\n\n\n\n fn addr(&self, k1: &str, k2: &str) -> Result<Ipv4Endpoint, Error> {\n\n let addr = &self.0.config_obj[k1][k2];\n\n let host_s = addr[\"host\"].as_str().ok_or(format_err!(\"Missing host\")).unwrap();\n\n let host = Ipv4Addr::from_str(host_s).unwrap();\n\n let port_i = addr[\"port\"].as_i64().ok_or(format_err!(\"Missing port\")).unwrap();\n\n let port = Port16::try_from(port_i as u16).unwrap();\n\n Ok(Ipv4Endpoint::new(host, port))\n", "file_path": "tests/rust/common/config.rs", "rank": 92, "score": 16.924569102775525 }, { "content": " pub fn wait_any(&mut self, qts: &[QToken]) -> Result<(usize, dmtr_qresult_t), Fail> {\n\n #[cfg(feature = \"profiler\")]\n\n timer!(\"catpowder::wait_any\");\n\n trace!(\"wait_any(): qts={:?}\", qts);\n\n\n\n let (i, qd, r): (usize, QDesc, OperationResult<DataBuffer>) = self.wait_any2(qts)?;\n\n Ok((i, pack_result(self.rt(), r, qd, qts[i].into())))\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// De-Reference Trait Implementation for Catpowder LibOS\n\nimpl Deref for CatpowderLibOS {\n\n type Target = InetStack<LinuxRuntime>;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n", "file_path": "src/catpowder/mod.rs", "rank": 93, "score": 16.899098377689196 }, { "content": " body_buf.copy_from_slice(&body[..]);\n\n\n\n if header_size + body.len() < MIN_PAYLOAD_SIZE {\n\n let padding_bytes = MIN_PAYLOAD_SIZE - (header_size + body.len());\n\n let padding_buf =\n\n unsafe { &mut header_mbuf.slice_mut()[(header_size + body.len())..][..padding_bytes] };\n\n for byte in padding_buf {\n\n *byte = 0;\n\n }\n\n }\n\n\n\n let frame_size = std::cmp::max(header_size + body.len(), MIN_PAYLOAD_SIZE);\n\n header_mbuf.trim(header_mbuf.len() - frame_size);\n\n\n\n let mut header_mbuf_ptr = header_mbuf.into_raw();\n\n let num_sent = unsafe { rte_eth_tx_burst(self.port_id, 0, &mut header_mbuf_ptr, 1) };\n\n assert_eq!(num_sent, 1);\n\n }\n\n }\n\n // No body on our packet, just send the headers.\n", "file_path": "src/catnip/runtime/network.rs", "rank": 94, "score": 16.823891923552136 }, { "content": "// Copyright (c) Microsoft Corporation.\n\n// Licensed under the MIT license.\n\n\n\n//==============================================================================\n\n// Imports\n\n//==============================================================================\n\n\n\nuse crate::demikernel::dbuf::DataBuffer;\n\nuse ::nix::{\n\n errno::Errno,\n\n sys::socket::{\n\n self,\n\n MsgFlags,\n\n SockAddr,\n\n },\n\n};\n\nuse ::runtime::{\n\n fail::Fail,\n\n QDesc,\n\n};\n", "file_path": "src/catnap/futures/pushto.rs", "rank": 95, "score": 16.700379477334003 }, { "content": " Ok(pack_result(self.rt(), result, qd, qt.into()))\n\n }\n\n\n\n /// Waits for any operation to complete.\n\n pub fn wait_any(&mut self, qts: &[QToken]) -> Result<(usize, dmtr_qresult_t), Fail> {\n\n #[cfg(feature = \"profiler\")]\n\n timer!(\"catnip::wait_any\");\n\n trace!(\"wait_any(): qts={:?}\", qts);\n\n\n\n let (i, qd, r): (usize, QDesc, OperationResult<DPDKBuf>) = self.wait_any2(qts)?;\n\n Ok((i, pack_result(self.rt(), r, qd, qts[i].into())))\n\n }\n\n}\n\n\n\n//==============================================================================\n\n// Trait Implementations\n\n//==============================================================================\n\n\n\n/// De-Reference Trait Implementation for Catnip LibOS\n\nimpl Deref for CatnipLibOS {\n", "file_path": "src/catnip/mod.rs", "rank": 96, "score": 16.667566041980486 }, { "content": " /// Underlying runtime.\n\n runtime: PosixRuntime,\n\n}\n\n\n\n//==============================================================================\n\n// Associate Functions\n\n//==============================================================================\n\n\n\n/// Associate Functions for Catnap LibOS\n\nimpl CatnapLibOS {\n\n /// Instantiates a Catnap LibOS.\n\n pub fn new() -> Self {\n\n logging::initialize();\n\n let qtable: IoQueueTable = IoQueueTable::new();\n\n let sockets: HashMap<QDesc, RawFd> = HashMap::new();\n\n let runtime: PosixRuntime = PosixRuntime::new(Instant::now());\n\n Self {\n\n qtable,\n\n sockets,\n\n runtime,\n", "file_path": "src/catnap/mod.rs", "rank": 97, "score": 16.556829341663462 }, { "content": " /// The data has been written when [`wait`ing](Self::wait) on the QToken returns.\n\n pub fn push(&mut self, qd: QDesc, sga: &dmtr_sgarray_t) -> Result<QToken, Fail> {\n\n #[cfg(feature = \"profiler\")]\n\n timer!(\"catnip::push\");\n\n trace!(\"push(): qd={:?}\", qd);\n\n match self.rt().clone_sgarray(sga) {\n\n Ok(buf) => {\n\n if buf.len() == 0 {\n\n return Err(Fail::new(libc::EINVAL, \"zero-length buffer\"));\n\n }\n\n let future = self.do_push(qd, buf)?;\n\n Ok(self.rt().schedule(future).into_raw().into())\n\n },\n\n Err(e) => Err(e),\n\n }\n\n }\n\n\n\n pub fn pushto(&mut self, qd: QDesc, sga: &dmtr_sgarray_t, to: Ipv4Endpoint) -> Result<QToken, Fail> {\n\n #[cfg(feature = \"profiler\")]\n\n timer!(\"catnip::pushto\");\n", "file_path": "src/catnip/mod.rs", "rank": 98, "score": 16.544578596778738 }, { "content": " Err(e) => panic!(\"failed to allocate header mbuf: {:?}\", e.cause),\n\n };\n\n let header_size = buf.header_size();\n\n assert!(header_size <= header_mbuf.len());\n\n buf.write_header(unsafe { &mut header_mbuf.slice_mut()[..header_size] });\n\n\n\n if let Some(body) = buf.take_body() {\n\n // Next, see how much space we have remaining and inline the body if we have room.\n\n let inline_space = header_mbuf.len() - header_size;\n\n\n\n // Chain a buffer\n\n if body.len() > inline_space {\n\n assert!(header_size + body.len() >= MIN_PAYLOAD_SIZE);\n\n\n\n // We're only using the header_mbuf for, well, the header.\n\n header_mbuf.trim(header_mbuf.len() - header_size);\n\n\n\n let body_mbuf = match body {\n\n DPDKBuf::Managed(mbuf) => mbuf,\n\n DPDKBuf::External(bytes) => {\n", "file_path": "src/catnip/runtime/network.rs", "rank": 99, "score": 16.53251906452466 } ]
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 let mut slen;\n\n let mut trans = 0;\n\n if p == pe {\n\n if MACHINE_EOF_TRANS[cs] > 0 {\n\n trans = (MACHINE_EOF_TRANS[cs] - 1) as usize;\n\n }\n\n }\n\n\n\n loop {\n\n if reset {\n", "file_path": "src/complex/universal_machine.rs", "rank": 0, "score": 274548.058477863 }, { "content": "pub fn find_syllables_indic(buffer: &mut Buffer) {\n\n let mut cs = 39usize;\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 let mut slen;\n\n let mut trans = 0;\n\n if p == pe {\n\n if MACHINE_EOF_TRANS[cs] > 0 {\n\n trans = (MACHINE_EOF_TRANS[cs] - 1) as usize;\n\n }\n\n }\n\n\n\n loop {\n\n if reset {\n", "file_path": "src/complex/indic_machine.rs", "rank": 1, "score": 269946.1604652368 }, { "content": "pub fn find_syllables_khmer(buffer: &mut Buffer) {\n\n let mut cs = 20usize;\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 let mut slen;\n\n let mut trans = 0;\n\n if p == pe {\n\n if MACHINE_EOF_TRANS[cs] > 0 {\n\n trans = (MACHINE_EOF_TRANS[cs] - 1) as usize;\n\n }\n\n }\n\n\n\n loop {\n\n if reset {\n", "file_path": "src/complex/khmer_machine.rs", "rank": 3, "score": 269946.16046523687 }, { "content": "pub fn preprocess_text_vowel_constraints(buffer: &mut Buffer) {\n\n if buffer\n\n .flags\n\n .contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE)\n\n {\n\n return;\n\n }\n\n\n\n // UGLY UGLY UGLY business of adding dotted-circle in the middle of\n\n // vowel-sequences that look like another vowel. Data for each script\n\n // collected from the USE script development spec.\n\n //\n\n // https://github.com/harfbuzz/harfbuzz/issues/1019\n\n let mut processed = false;\n\n buffer.clear_output();\n\n match buffer.props.script {\n\n Some(script::DEVANAGARI) => {\n\n buffer.idx = 0;\n\n while buffer.idx + 1 < buffer.len() {\n\n let mut matched = false;\n", "file_path": "src/complex/vowel_constraints.rs", "rank": 4, "score": 265584.8477253774 }, { "content": "fn reorder_marks_arabic(mut start: usize, end: usize, buffer: &mut Buffer) {\n\n let mut i = start;\n\n for cc in [220u8, 230].iter().cloned() {\n\n while i < end && buffer.info[i].modified_combining_class() < cc {\n\n i += 1;\n\n }\n\n\n\n if i == end {\n\n break;\n\n }\n\n\n\n if buffer.info[i].modified_combining_class() > cc {\n\n continue;\n\n }\n\n\n\n let mut j = i;\n\n while j < end &&\n\n buffer.info[j].modified_combining_class() == cc &&\n\n MODIFIER_COMBINING_MARKS.contains(&buffer.info[j].codepoint)\n\n {\n", "file_path": "src/complex/arabic.rs", "rank": 5, "score": 253538.64021763598 }, { "content": "/// Shape the contents of the buffer using the provided font and activating all\n\n/// OpenType features given in `features`.\n\n///\n\n/// This function consumes the `buffer` and returns a `GlyphBuffer` containing\n\n/// the resulting glyph indices and the corresponding positioning information.\n\n/// Once all the information from the `GlyphBuffer` has been processed as\n\n/// necessary you can reuse the `GlyphBuffer` as an `Buffer` (using\n\n/// `GlyphBuffer::clear`) and use that to call `shape` again with new\n\n/// data.\n\npub fn shape(font: &Font<'_>, mut buffer: Buffer, features: &[Feature]) -> GlyphBuffer {\n\n buffer.guess_segment_properties();\n\n unsafe {\n\n ffi::hb_shape(\n\n font.as_ptr(),\n\n buffer.as_ptr(),\n\n features.as_ptr() as *const _,\n\n features.len() as u32,\n\n )\n\n };\n\n GlyphBuffer(buffer)\n\n}\n", "file_path": "src/lib.rs", "rank": 6, "score": 246872.6301421483 }, { "content": "fn reorder_syllable(start: usize, end: usize, buffer: &mut Buffer) {\n\n use super::myanmar_machine::SyllableType;\n\n\n\n let syllable_type = match buffer.info[start].syllable() & 0x0F {\n\n 0 => SyllableType::ConsonantSyllable,\n\n 1 => SyllableType::PunctuationCluster,\n\n 2 => SyllableType::BrokenCluster,\n\n 3 => SyllableType::NonMyanmarCluster,\n\n _ => unreachable!(),\n\n };\n\n\n\n match syllable_type {\n\n // We already inserted dotted-circles, so just call the consonant_syllable.\n\n SyllableType::ConsonantSyllable | SyllableType::BrokenCluster => {\n\n initial_reordering_consonant_syllable(start, end, buffer);\n\n }\n\n SyllableType::PunctuationCluster | SyllableType::NonMyanmarCluster => {}\n\n }\n\n}\n\n\n", "file_path": "src/complex/myanmar.rs", "rank": 7, "score": 240886.3821364959 }, { "content": "fn reorder_syllable(start: usize, end: usize, buffer: &mut Buffer) {\n\n use super::universal_machine::SyllableType;\n\n\n\n let syllable_type = (buffer.info[start].syllable() & 0x0F) as u32;\n\n // Only a few syllable types need reordering.\n\n if (hb_flag_unsafe(syllable_type) &\n\n (hb_flag(SyllableType::ViramaTerminatedCluster as u32) |\n\n hb_flag(SyllableType::SakotTerminatedCluster as u32) |\n\n hb_flag(SyllableType::StandardCluster as u32) |\n\n hb_flag(SyllableType::BrokenCluster as u32) |\n\n 0)) == 0\n\n {\n\n return;\n\n }\n\n\n\n // Move things forward.\n\n if buffer.info[start].use_category() == Category::R && end - start > 1 {\n\n // Got a repha. Reorder it towards the end, but before the first post-base glyph.\n\n for i in start+1..end {\n\n let is_post_base_glyph =\n", "file_path": "src/complex/universal.rs", "rank": 8, "score": 240886.3821364959 }, { "content": "// Rules from:\n\n// https://docs.microsoft.com/en-us/typography/script-development/myanmar\n\nfn initial_reordering_consonant_syllable(start: usize, end: usize, buffer: &mut Buffer) {\n\n let mut base = end;\n\n let mut has_reph = false;\n\n\n\n {\n\n let mut limit = start;\n\n if start + 3 <= end &&\n\n buffer.info[start + 0].indic_category() == Category::Ra &&\n\n buffer.info[start + 1].indic_category() == Category::Symbol &&\n\n buffer.info[start + 2].indic_category() == Category::H\n\n {\n\n limit += 3;\n\n base = start;\n\n has_reph = true;\n\n }\n\n\n\n {\n\n if !has_reph {\n\n base = limit;\n\n }\n", "file_path": "src/complex/myanmar.rs", "rank": 9, "score": 232919.93136811053 }, { "content": "fn arabic_joining(buffer: &mut Buffer) {\n\n let mut prev: Option<usize> = None;\n\n let mut state = 0;\n\n\n\n // Check pre-context.\n\n for i in 0..buffer.context_len[0] {\n\n let c = buffer.context[0][i];\n\n let this_type = get_joining_type(c, c.general_category());\n\n if this_type == JoiningType::T {\n\n continue;\n\n }\n\n\n\n state = STATE_TABLE[state][this_type as usize].2 as usize;\n\n break;\n\n }\n\n\n\n for i in 0..buffer.len() {\n\n let this_type = get_joining_type(buffer.info[i].as_char(), buffer.info[i].general_category());\n\n if this_type == JoiningType::T {\n\n buffer.info[i].set_arabic_shaping_action(Action::NONE);\n", "file_path": "src/complex/arabic.rs", "rank": 10, "score": 226410.63682371157 }, { "content": "fn output_dotted_circle(buffer: &mut Buffer) {\n\n if let Some(ref mut info) = buffer.output_glyph(0x25CC) {\n\n info.reset_continuation();\n\n }\n\n}\n\n\n", "file_path": "src/complex/vowel_constraints.rs", "rank": 11, "score": 219014.81833426259 }, { "content": "fn output_with_dotted_circle(buffer: &mut Buffer) {\n\n output_dotted_circle(buffer);\n\n buffer.next_glyph();\n\n}\n\n\n", "file_path": "src/complex/vowel_constraints.rs", "rank": 12, "score": 219014.81833426259 }, { "content": "fn apply_stch(font: *mut ffi::hb_font_t, buffer: &mut Buffer) {\n\n if !buffer.scratch_flags.contains(BufferScratchFlags::COMPLEX0) {\n\n return;\n\n }\n\n\n\n // The Arabic shaper currently always processes in RTL mode, so we should\n\n // stretch / position the stretched pieces to the left / preceding glyphs.\n\n\n\n // We do a two pass implementation:\n\n // First pass calculates the exact number of extra glyphs we need,\n\n // We then enlarge buffer to have that much room,\n\n // Second pass applies the stretch, copying things to the end of buffer.\n\n\n\n let sign = {\n\n let mut scale = (0i32, 0i32);\n\n unsafe { ffi::hb_font_get_scale(font, &mut scale.0, &mut scale.1) };\n\n scale.0.signum()\n\n };\n\n\n\n let mut extra_glyphs_needed: usize = 0; // Set during MEASURE, used during CUT\n", "file_path": "src/complex/arabic.rs", "rank": 13, "score": 209906.49731627142 }, { "content": "fn preprocess_text(font: &Font, buffer: &mut Buffer) {\n\n // Hangul syllables come in two shapes: LV, and LVT. Of those:\n\n //\n\n // - LV can be precomposed, or decomposed. Lets call those\n\n // <LV> and <L,V>,\n\n // - LVT can be fully precomposed, partically precomposed, or\n\n // fully decomposed. Ie. <LVT>, <LV,T>, or <L,V,T>.\n\n //\n\n // The composition / decomposition is mechanical. However, not\n\n // all <L,V> sequences compose, and not all <LV,T> sequences\n\n // compose.\n\n //\n\n // Here are the specifics:\n\n //\n\n // - <L>: U+1100..115F, U+A960..A97F\n\n // - <V>: U+1160..11A7, U+D7B0..D7C7\n\n // - <T>: U+11A8..11FF, U+D7CB..D7FB\n\n //\n\n // - Only the <L,V> sequences for some of the U+11xx ranges combine.\n\n // - Only <LV,T> sequences for some of the Ts in U+11xx range combine.\n", "file_path": "src/complex/hangul.rs", "rank": 14, "score": 204692.16210632765 }, { "content": "fn final_reordering_impl(plan: &IndicShapePlan, script: Script, start: usize, end: usize, buffer: &mut Buffer) {\n\n // This function relies heavily on halant glyphs. Lots of ligation\n\n // and possibly multiple substitutions happened prior to this\n\n // phase, and that might have messed up our properties. Recover\n\n // from a particular case of that where we're fairly sure that a\n\n // class of OT_H is desired but has been lost.\n\n //\n\n // We don't call load_virama_glyph(), since we know it's already loaded.\n\n if let Some(virama_glyph) = plan.virama_glyph {\n\n for info in &mut buffer.info[start..end] {\n\n if info.codepoint == virama_glyph && info.is_ligated() && info.is_multiplied() {\n\n // This will make sure that this glyph passes is_halant() test.\n\n info.set_indic_category(Category::H);\n\n info.clear_ligated_and_multiplied();\n\n }\n\n }\n\n }\n\n\n\n // 4. Final reordering:\n\n //\n", "file_path": "src/complex/indic.rs", "rank": 15, "score": 202479.90783840383 }, { "content": "fn setup_topographical_masks(map: &Map, buffer: &mut Buffer) {\n\n use super::universal_machine::SyllableType;\n\n\n\n let mut masks = [0; 4];\n\n let mut all_masks = 0;\n\n for i in 0..4 {\n\n masks[i] = map.get_1_mask(TOPOGRAPHICAL_FEATURES[i]);\n\n if masks[i] == map.global_mask {\n\n masks[i] = 0;\n\n }\n\n\n\n all_masks |= masks[i];\n\n }\n\n\n\n if all_masks == 0 {\n\n return;\n\n }\n\n\n\n let other_masks = !all_masks;\n\n\n", "file_path": "src/complex/universal.rs", "rank": 16, "score": 201284.32637767238 }, { "content": "fn do_pua_shaping(font: &ttf_parser::Font, buffer: &mut Buffer) {\n\n let mut above_state = ABOVE_START_STATE[Consonant::NotConsonant as usize];\n\n let mut below_state = BELOW_START_STATE[Consonant::NotConsonant as usize];\n\n let mut base = 0;\n\n\n\n for i in 0..buffer.len() {\n\n let mt = get_mark_type(buffer.info[i].codepoint);\n\n\n\n if mt == Mark::NotMark {\n\n let ct = get_consonant_type(buffer.info[i].codepoint);\n\n above_state = ABOVE_START_STATE[ct as usize];\n\n below_state = BELOW_START_STATE[ct as usize];\n\n base = i;\n\n continue;\n\n }\n\n\n\n let above_edge = ABOVE_STATE_MACHINE[above_state as usize][mt as usize];\n\n let below_edge = BELOW_STATE_MACHINE[below_state as usize][mt as usize];\n\n above_state = above_edge.next_state;\n\n below_state = below_edge.next_state;\n", "file_path": "src/complex/thai.rs", "rank": 17, "score": 192594.70616396572 }, { "content": "fn insert_dotted_circles(font: &ttf_parser::Font, buffer: &mut Buffer) {\n\n use super::khmer_machine::SyllableType;\n\n\n\n if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {\n\n return;\n\n }\n\n\n\n // Note: This loop is extra overhead, but should not be measurable.\n\n // TODO Use a buffer scratch flag to remove the loop.\n\n let has_broken_syllables = buffer.info_slice().iter()\n\n .any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);\n\n\n\n if !has_broken_syllables {\n\n return;\n\n }\n\n\n\n let dottedcircle_glyph = match font.glyph_index('\\u{25CC}') {\n\n Some(g) => g.0 as u32,\n\n None => return,\n\n };\n", "file_path": "src/complex/khmer.rs", "rank": 18, "score": 189519.9751244188 }, { "content": "fn insert_dotted_circles(font: &ttf_parser::Font, buffer: &mut Buffer) {\n\n use super::universal_machine::SyllableType;\n\n\n\n if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {\n\n return;\n\n }\n\n\n\n // Note: This loop is extra overhead, but should not be measurable.\n\n // TODO Use a buffer scratch flag to remove the loop.\n\n let has_broken_syllables = buffer.info_slice().iter()\n\n .any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);\n\n\n\n if !has_broken_syllables {\n\n return;\n\n }\n\n\n\n let dottedcircle_glyph = match font.glyph_index('\\u{25CC}') {\n\n Some(g) => g.0 as u32,\n\n None => return,\n\n };\n", "file_path": "src/complex/universal.rs", "rank": 19, "score": 189519.9751244188 }, { "content": "fn insert_dotted_circles(font: &ttf_parser::Font, buffer: &mut Buffer) {\n\n use super::indic_machine::SyllableType;\n\n\n\n if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {\n\n return;\n\n }\n\n\n\n // Note: This loop is extra overhead, but should not be measurable.\n\n // TODO Use a buffer scratch flag to remove the loop.\n\n let has_broken_syllables = buffer.info_slice().iter()\n\n .any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);\n\n\n\n if !has_broken_syllables {\n\n return;\n\n }\n\n\n\n let dottedcircle_glyph = match font.glyph_index('\\u{25CC}') {\n\n Some(g) => g.0 as u32,\n\n None => return,\n\n };\n", "file_path": "src/complex/indic.rs", "rank": 20, "score": 189519.9751244188 }, { "content": "fn insert_dotted_circles(font: &ttf_parser::Font, buffer: &mut Buffer) {\n\n use super::myanmar_machine::SyllableType;\n\n\n\n if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {\n\n return;\n\n }\n\n\n\n // Note: This loop is extra overhead, but should not be measurable.\n\n // TODO Use a buffer scratch flag to remove the loop.\n\n let has_broken_syllables = buffer.info_slice().iter()\n\n .any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);\n\n\n\n if !has_broken_syllables {\n\n return;\n\n }\n\n\n\n let dottedcircle_glyph = match font.glyph_index('\\u{25CC}') {\n\n Some(g) => g.0 as u32,\n\n None => return,\n\n };\n", "file_path": "src/complex/myanmar.rs", "rank": 21, "score": 189519.9751244188 }, { "content": "fn final_reordering(plan: &IndicShapePlan, script: Script, buffer: &mut Buffer) {\n\n if buffer.is_empty() {\n\n return;\n\n }\n\n\n\n let mut start = 0;\n\n let mut end = buffer.next_syllable(0);\n\n while start < buffer.len() {\n\n final_reordering_impl(plan, script, start, end, buffer);\n\n start = end;\n\n end = buffer.next_syllable(start);\n\n }\n\n}\n\n\n", "file_path": "src/complex/indic.rs", "rank": 22, "score": 181938.14490734998 }, { "content": "/// Converts a multi-subtag BCP 47 language tag to language tags.\n\npub fn tags_from_complex_language(\n\n language: &str,\n\n tags: &mut smallvec::SmallVec<[Tag; 3]>,\n\n) -> bool {\n\n if subtag_matches(language, \"-fonnapa\") {\n\n // Undetermined; North American Phonetic Alphabet\n\n tags.push(Tag::from_bytes(b\"APPH\")); // Phonetic transcription—Americanist conventions\n\n return true;\n\n }\n\n if subtag_matches(language, \"-polyton\") {\n\n // Modern Greek (1453-); Polytonic Greek\n\n tags.push(Tag::from_bytes(b\"PGR \")); // Polytonic Greek\n\n return true;\n\n }\n\n if subtag_matches(language, \"-provenc\") {\n\n // Occitan (post 1500); Provençal\n\n tags.push(Tag::from_bytes(b\"PRO \")); // Provençal / Old Provençal\n\n return true;\n\n }\n\n if subtag_matches(language, \"-fonipa\") {\n", "file_path": "src/tag_table.rs", "rank": 23, "score": 148626.2758916375 }, { "content": "enum use_category_t {\n\n USE_O\t\t= 0,\t/* OTHER */\n\n\n\n USE_B\t\t= 1,\t/* BASE */\n\n USE_IND\t= 3,\t/* BASE_IND */\n\n USE_N\t\t= 4,\t/* BASE_NUM */\n\n USE_GB\t= 5,\t/* BASE_OTHER */\n\n USE_CGJ\t= 6,\t/* CGJ */\n\n// USE_F\t\t= 7,\t/* CONS_FINAL */\n\n USE_FM\t= 8,\t/* CONS_FINAL_MOD */\n\n// USE_M\t\t= 9,\t/* CONS_MED */\n\n// USE_CM\t= 10,\t/* CONS_MOD */\n\n USE_SUB\t= 11,\t/* CONS_SUB */\n\n USE_H\t\t= 12,\t/* HALANT */\n\n\n\n USE_HN\t= 13,\t/* HALANT_NUM */\n\n USE_ZWNJ\t= 14,\t/* Zero width non-joiner */\n\n USE_ZWJ\t= 15,\t/* Zero width joiner */\n\n USE_WJ\t= 16,\t/* Word joiner */\n\n USE_Rsv\t= 17,\t/* Reserved characters */\n", "file_path": "harfbuzz/src/hb-ot-shape-complex-use.hh", "rank": 24, "score": 136448.08938033314 }, { "content": "enum use_syllable_type_t {\n\n use_independent_cluster,\n\n use_virama_terminated_cluster,\n\n use_sakot_terminated_cluster,\n\n use_standard_cluster,\n\n use_number_joiner_terminated_cluster,\n\n use_numeral_cluster,\n\n use_symbol_cluster,\n\n use_broken_cluster,\n\n use_non_cluster,\n\n};\n\n\n\nvoid hb_complex_universal_setup_masks(const hb_shape_plan_t *plan, rb_buffer_t *buffer, hb_font_t *font HB_UNUSED)\n\n{\n\n const use_shape_plan_t *use_plan = (const use_shape_plan_t *)plan->data;\n\n\n\n /* Do this before allocating use_category(). */\n\n if (use_plan->arabic_plan) {\n\n setup_masks_arabic_plan(use_plan->arabic_plan, buffer, plan->props.script);\n\n }\n", "file_path": "harfbuzz/src/hb-ot-shape-complex-use.cc", "rank": 25, "score": 134057.6569836855 }, { "content": "#[test]\n\nfn use_008() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/2a670df15b73a5dc75a5cc491bde5ac93c5077dc.ttf\",\n\n \"\\u{11124}\\u{11134}\\u{11131}\",\n\n \"\",\n\n ),\n\n \"u11124=0+514|\\\n\n u11134=0+0|\\\n\n u11131=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 26, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_002() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/4cce528e99f600ed9c25a2b69e32eb94a03b4ae8.ttf\",\n\n \"\\u{1A48}\\u{1A58}\\u{1A25}\\u{1A48}\\u{1A58}\\u{1A25}\\u{1A6E}\\u{1A63}\",\n\n \"\",\n\n ),\n\n \"uni1A48=0+1212|\\\n\n uni1A25=0+1912|\\\n\n uni1A58=0+0|\\\n\n uni1A48=3+1212|\\\n\n uni1A6E=3+0|\\\n\n uni1A25=3+1912|\\\n\n uni1A58=3+0|\\\n\n uni1A63=3+1212\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 27, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_012() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/4afb0e8b9a86bb9bd73a1247de4e33fbe3c1fd93.ttf\",\n\n \"\\u{1C00}\\u{1C27}\\u{1C28}\\u{1C34}\\u{1C35}\",\n\n \"\",\n\n ),\n\n \"uni1C35=0+500|\\\n\n uni1C34=0+500|\\\n\n uni1C28=0+500|\\\n\n uni1C27=0+500|\\\n\n uni1C00=0+500\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 28, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_007() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/2a670df15b73a5dc75a5cc491bde5ac93c5077dc.ttf\",\n\n \"\\u{11124}\\u{11127}\\u{11131}\",\n\n \"\",\n\n ),\n\n \"u11124=0+514|\\\n\n u11127=0+0|\\\n\n uni25CC=0+547|\\\n\n u11131=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 29, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_005() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/2a670df15b73a5dc75a5cc491bde5ac93c5077dc.ttf\",\n\n \"\\u{11124}\\u{1112E}\",\n\n \"\",\n\n ),\n\n \"u11124=0+514|\\\n\n u11131=0+0|\\\n\n u11127=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 30, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_014() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/4afb0e8b9a86bb9bd73a1247de4e33fbe3c1fd93.ttf\",\n\n \"\\u{1102D}\\u{11046}\\u{11013}\\u{11046}\\u{11013}\\u{11046}\",\n\n \"\",\n\n ),\n\n \"u11013=0+500|\\\n\n u11046_u11013=0+500|\\\n\n u1102D_u11046=0+500|\\\n\n u11046=0+500\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 31, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_011() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/dcf774ca21062e7439f98658b18974ea8b956d0c.ttf\",\n\n \"\\u{11328}\\u{1134D}\\u{1CF4}\",\n\n \"\",\n\n ),\n\n \"gid1=0+793|\\\n\n gid2=0+0|\\\n\n gid3=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 32, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_003() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/f518eb6f6b5eec2946c9fbbbde44e45d46f5e2ac.ttf\",\n\n \"\\u{1A48}\\u{1A58}\\u{1A25}\\u{1A48}\\u{1A58}\\u{1A25}\\u{1A6E}\\u{1A63}\",\n\n \"\",\n\n ),\n\n \"uni1A48=0+1212|\\\n\n uni1A25=0+1912|\\\n\n uni1A58=0+0|\\\n\n uni1A48=3+1212|\\\n\n uni1A6E=3+1211|\\\n\n uni1A25=3+1912|\\\n\n uni1A58=3+0|\\\n\n uni1A63=3+1212\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 33, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_009() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/2a670df15b73a5dc75a5cc491bde5ac93c5077dc.ttf\",\n\n \"\\u{11124}\\u{11131}\\u{11134}\",\n\n \"\",\n\n ),\n\n \"u11124=0+514|\\\n\n u11131=0+0|\\\n\n uni25CC=0+547|\\\n\n u11134=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 34, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_013() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/4afb0e8b9a86bb9bd73a1247de4e33fbe3c1fd93.ttf\",\n\n \"\\u{0D4E}\\u{0D15}\\u{0D4D}\\u{0D15}\\u{0D46}\",\n\n \"\",\n\n ),\n\n \"uni0D15=0+500|\\\n\n uni0D4E=0+500|\\\n\n uni0D4D=0+500|\\\n\n uni0D46=3+500|\\\n\n uni0D15=3+500\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 35, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_001() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/fbb6c84c9e1fe0c39e152fbe845e51fd81f6748e.ttf\",\n\n \"\\u{1B1B}\\u{1B44}\\u{1B13}\\u{1B3E}\",\n\n \"\",\n\n ),\n\n \"gid3=0+990|\\\n\n gid7=0+2473|\\\n\n gid5=0@-293,-400+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 36, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_006() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/2a670df15b73a5dc75a5cc491bde5ac93c5077dc.ttf\",\n\n \"\\u{11124}\\u{11131}\\u{11127}\",\n\n \"\",\n\n ),\n\n \"u11124=0+514|\\\n\n u11131=0+0|\\\n\n u11127=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 37, "score": 130772.25881032654 }, { "content": "#[test]\n\nfn use_004() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/6ff0fbead4462d9f229167b4e6839eceb8465058.ttf\",\n\n \"\\u{11103}\\u{11128}\",\n\n \"--font-funcs=ot\",\n\n ),\n\n \"u11103=0+837|\\\n\n u11128=0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 38, "score": 130772.25881032654 }, { "content": "pub fn script_from_char(c: char) -> Script {\n\n use unicode_script as us;\n\n use crate::script;\n\n\n\n match us::Script::from(c) {\n\n us::Script::Common => script::COMMON,\n\n us::Script::Inherited => script::INHERITED,\n\n us::Script::Adlam => script::ADLAM,\n\n us::Script::Caucasian_Albanian => script::CAUCASIAN_ALBANIAN,\n\n us::Script::Ahom => script::AHOM,\n\n us::Script::Arabic => script::ARABIC,\n\n us::Script::Imperial_Aramaic => script::IMPERIAL_ARAMAIC,\n\n us::Script::Armenian => script::ARMENIAN,\n\n us::Script::Avestan => script::AVESTAN,\n\n us::Script::Balinese => script::BALINESE,\n\n us::Script::Bamum => script::BAMUM,\n\n us::Script::Bassa_Vah => script::BASSA_VAH,\n\n us::Script::Batak => script::BATAK,\n\n us::Script::Bengali => script::BENGALI,\n\n us::Script::Bhaiksuki => script::BHAIKSUKI,\n", "file_path": "src/unicode.rs", "rank": 39, "score": 129803.9354555165 }, { "content": "#[test]\n\nfn context_matching_001() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/4cce528e99f600ed9c25a2b69e32eb94a03b4ae8.ttf\",\n\n \"\\u{1A48}\\u{1A58}\\u{1A25}\\u{1A48}\\u{1A58}\\u{1A25}\\u{1A6E}\\u{1A63}\",\n\n \"\",\n\n ),\n\n \"uni1A48=0+1212|\\\n\n uni1A25=0+1912|\\\n\n uni1A58=0+0|\\\n\n uni1A48=3+1212|\\\n\n uni1A6E=3+0|\\\n\n uni1A25=3+1912|\\\n\n uni1A58=3+0|\\\n\n uni1A63=3+1212\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 40, "score": 127488.48197915318 }, { "content": "#[test]\n\nfn context_matching_003() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/f499fbc23865022234775c43503bba2e63978fe1.ttf\",\n\n \"\\u{09B0}\\u{09CD}\\u{09A5}\\u{09CD}\\u{09AF}\\u{09C0}\",\n\n \"\",\n\n ),\n\n \"gid1=0+1320|\\\n\n gid13=0+523|\\\n\n gid18=0+545\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 41, "score": 127488.48197915318 }, { "content": "#[test]\n\nfn context_matching_002() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/d629e7fedc0b350222d7987345fe61613fa3929a.ttf\",\n\n \"\\u{0915}\\u{093F}\\u{0915}\\u{093F}\",\n\n \"\",\n\n ),\n\n \"ivowelsign03deva=0+530|\\\n\n kadeva=0+1561|\\\n\n ivowelsign03deva=2+530|\\\n\n kadeva=2+1561\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 42, "score": 127488.48197915318 }, { "content": "#[test]\n\nfn use_syllable_013() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/3cc01fede4debd4b7794ccb1b16cdb9987ea7571.ttf\",\n\n \"\\u{1A3D}\\u{1A5A}\\u{1A63}\",\n\n \"\",\n\n ),\n\n \"uni1A3D=0+250|\\\n\n uni1A5A=0+0|\\\n\n uni1A63=0+250\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 43, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_014() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C9D}\\u{11CAA}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C9D.11CAA=0+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 44, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_012() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C92}\\u{11CAA}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C92.11CAA=0+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 45, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_004() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C84}\\u{11C71}\",\n\n \"\",\n\n ),\n\n \"u11C84=0+2200|\\\n\n u11C71=1+1600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 46, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_011() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11CA0}\\u{11CA9}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11CA0.11CA9=0+3000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 47, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_020() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C7F}\\u{11CB2}\\u{11C7D}\",\n\n \"\",\n\n ),\n\n \"u11C7F.11CB2=0+2400|\\\n\n u11C7D=2+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 48, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_015() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/3cc01fede4debd4b7794ccb1b16cdb9987ea7571.ttf\",\n\n \"\\u{1A3D}\\u{1A60}\\u{1A3D}\\u{1A63}\\u{1A60}\\u{1A3D}\\u{1A5A}\",\n\n \"\",\n\n ),\n\n \"uni1A3D=0+250|\\\n\n uni1A60=0+0|\\\n\n uni1A3D=2+250|\\\n\n uni1A63=2+250|\\\n\n uni1A60=2+0|\\\n\n uni1A3D=5+250|\\\n\n uni25CC=5+250|\\\n\n uni1A5A=5+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 49, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_001() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/96490dd2ff81233b335a650e7eb660e0e7b2eeea.ttf\",\n\n \"\\u{AA00}\\u{AA2D}\\u{AA29}\",\n\n \"\",\n\n ),\n\n \"a_cham=0+1121|\\\n\n uSign_cham=0@14,0+0|\\\n\n .notdef=0+600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 50, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_009() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C94}\\u{11CA9}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C94.11CA9=0+2600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 51, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_034() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C80}\\u{11C76}\\u{11CB1}\\u{11C75}\\u{11C8D}\",\n\n \"\",\n\n ),\n\n \"u11C80=0+2400|\\\n\n u11C76.11CB1=1+3200|\\\n\n u11C75=3+2000|\\\n\n u11C8D=4+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 52, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_024() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11CA1}\\u{11CA9}\\u{11C71}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11CA1.11CA9=0+3000|\\\n\n u11C71=3+1600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 53, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_032() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C83}\\u{11CB4}\\u{11C74}\\u{11C8D}\",\n\n \"\",\n\n ),\n\n \"u11C83.11CB4=0+2800|\\\n\n u11C74=2+2000|\\\n\n u11C8D=3+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 54, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_010() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C9E}\\u{11CA9}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C9E.11CA9=0+3200\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 55, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_010() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/28f497629c04ceb15546c9a70e0730125ed6698d.ttf\",\n\n \"\\u{11013}\\u{11044}\\u{11046}\",\n\n \"\",\n\n ),\n\n \"brm_KA=0+754|\\\n\n brm_vowelOO=0@-647,0+0|\\\n\n brm_virama=0@-524,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 56, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_017() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C80}\\u{11C72}\\u{11CAA}\",\n\n \"\",\n\n ),\n\n \"u11C80=0+2400|\\\n\n u11C72.11CAA=1+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 57, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_016() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11CA0}\\u{11CAA}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11CA0.11CAA=0+2400\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 58, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_015() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C9E}\\u{11CAA}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C9E.11CAA=0+2600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 59, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_025() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11CA1}\\u{11CAA}\\u{11C71}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11CA1.11CAA=0+2400|\\\n\n u11C71=3+1600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 60, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_007() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8A}\\u{11C94}\\u{11CA9}\",\n\n \"\",\n\n ),\n\n \"u11C8A.11C94.11CA9=0+2600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 61, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_027() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8E}\\u{11CB0}\\u{11CB2}\\u{11CB5}\",\n\n \"\",\n\n ),\n\n \"u11C8E.11CB0.11CB2=0+2000|\\\n\n u11CB5=0@-2000,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 62, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_indic3_001() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/3c96e7a303c58475a8c750bf4289bbe73784f37d.ttf\",\n\n \"\\u{0C95}\\u{0CCD}\\u{0CB0}\",\n\n \"\",\n\n ),\n\n \"uni0C95=0+1176|\\\n\n uni0CB0_uni0CCD.blwf=0+275\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 63, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_008() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C92}\\u{11CA9}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C92.11CA9=0+2600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 64, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_008() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/1ed7e9064f008f62de6ff0207bb4dd29409597a5.ttf\",\n\n \"\\u{11064}\\u{1107F}\\u{11052}\\u{11065}\\u{1107F}\\u{11053}\",\n\n \"\",\n\n ),\n\n \"brm_num100.1=0+2224|\\\n\n brm_num1000.2=3+1834\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 65, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_033() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8B}\\u{11CB3}\\u{11C74}\\u{11C8D}\\u{11C71}\",\n\n \"\",\n\n ),\n\n \"u11C8B.11CB3=0+2400|\\\n\n u11C74=2+2000|\\\n\n u11C8D=3+2000|\\\n\n u11C71=4+1600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 66, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_009() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/28f497629c04ceb15546c9a70e0730125ed6698d.ttf\",\n\n \"\\u{11013}\\u{11042}\\u{11046}\",\n\n \"\",\n\n ),\n\n \"brm_KA=0+754|\\\n\n brm_vowelEE=0@-383,0+0|\\\n\n brm_virama=0@-524,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 67, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_005() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C7E}\\u{11C8A}\",\n\n \"\",\n\n ),\n\n \"u11C7E=0+2600|\\\n\n u11C8A=1+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 68, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_011() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/28f497629c04ceb15546c9a70e0730125ed6698d.ttf\",\n\n \"\\u{11013}\\u{1103C}\",\n\n \"\",\n\n ),\n\n \"brm_KA=0+754|\\\n\n brm_vowelU=0@-403,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 69, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_030() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C81}\\u{11C74}\\u{11CB2}\\u{11C8B}\",\n\n \"\",\n\n ),\n\n \"u11C81=0+2400|\\\n\n u11C74.11CB2=1+2000|\\\n\n u11C8B=3+2400\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 70, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_022() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8C}\\u{11CB4}\\u{11C74}\",\n\n \"\",\n\n ),\n\n \"u11C8C.11CB4=0+2800|\\\n\n u11C74=2+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 71, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_012() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/86cdd983c4e4c4d7f27dd405d6ceb7d4b9ed3d35.ttf\",\n\n \"\\u{111C8}\\u{111C9}\\u{111C9}\",\n\n \"\",\n\n ),\n\n \"u111C8=0+500|\\\n\n u111C9=0@-500,0+0|\\\n\n u111C9=0@-500,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 72, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_031() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8B}\\u{11CB3}\\u{11C74}\\u{11C8D}\",\n\n \"\",\n\n ),\n\n \"u11C8B.11CB3=0+2400|\\\n\n u11C74=2+2000|\\\n\n u11C8D=3+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 73, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_003() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8A}\\u{11CB5}\",\n\n \"\",\n\n ),\n\n \"u11C8A=0+2000|\\\n\n u11CB5=0@-2000,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 74, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_019() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C80}\\u{11C7C}\\u{11CB3}\",\n\n \"\",\n\n ),\n\n \"u11C80=0+2400|\\\n\n u11C7C.11CB3=1+2200\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 75, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_006() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/373e67bf41ca264e260a9716162b71a23549e885.ttf\",\n\n \"\\u{A8AC}\\u{A8B4}\\u{A8B5}\",\n\n \"--no-glyph-names\",\n\n ),\n\n \"2=0+377|\\\n\n 3=0+242|\\\n\n 4=0+210\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 76, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_028() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C74}\\u{11C89}\\u{11CB2}\\u{11C75}\",\n\n \"\",\n\n ),\n\n \"u11C74=0+2000|\\\n\n u11C89.11CB2=1+2000|\\\n\n u11C75=3+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 77, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_006() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8A}\\u{11C92}\\u{11CA9}\",\n\n \"\",\n\n ),\n\n \"u11C8A.11C92.11CA9=0+2600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 78, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_005() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/074a5ae6b19de8f29772fdd5df2d3d833f81f5e6.ttf\",\n\n \"\\u{11320}\\u{20F0}\\u{11367}\",\n\n \"--no-glyph-names\",\n\n ),\n\n \"3=0+502|\\\n\n 1=0@33,0+0|\\\n\n 4=0@300,8+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 79, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_026() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8F}\\u{11CB0}\\u{11CB4}\\u{11CB6}\",\n\n \"\",\n\n ),\n\n \"u11C8F.11CB0.11CB4=0+3600|\\\n\n u11CB6=0@-3200,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 80, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_035() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C80}\\u{11C8D}\\u{11C94}\\u{11CAA}\\u{11CB1}\\u{11C74}\\u{11C8D}\",\n\n \"\",\n\n ),\n\n \"u11C80=0+2400|\\\n\n u11C8D.11C94.11CAA.11CB1.shorti=1+2600|\\\n\n u11C74=5+2000|\\\n\n u11C8D=6+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 81, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_023() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8A}\\u{11CA1}\\u{11CA9}\\u{11C71}\",\n\n \"\",\n\n ),\n\n \"u11C8A.11CA1.11CA9=0+3000|\\\n\n u11C71=3+1600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 82, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_003() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/e68a88939e0f06e34d2bc911f09b70890289c8fd.ttf\",\n\n \"\\u{AA00}\\u{AA35}\\u{AA33}\",\n\n \"\",\n\n ),\n\n \"a_cham=0+1121|\\\n\n laMedial_cham=0@-32,0+0|\\\n\n yaMedial_cham=0+542\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 83, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_013() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11C94}\\u{11CAA}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11C94.11CAA=0+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 84, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_029() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C7C}\\u{11CAA}\\u{11CB2}\\u{11C75}\",\n\n \"\",\n\n ),\n\n \"u11C7C.11CAA.11CB2=0+2200|\\\n\n u11C75=3+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 85, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_002() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C71}\",\n\n \"\",\n\n ),\n\n \"u11C71=0+1600\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 86, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_001() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8F}\",\n\n \"\",\n\n ),\n\n \"u11C8F=0+3000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 87, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_016() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/3cc01fede4debd4b7794ccb1b16cdb9987ea7571.ttf\",\n\n \"\\u{1A3D}\\u{1A60}\\u{1A3D}\\u{1A63}\\u{1A60}\\u{1A3D}\\u{1A60}\",\n\n \"\",\n\n ),\n\n \"uni1A3D=0+250|\\\n\n uni1A60=0+0|\\\n\n uni1A3D=2+250|\\\n\n uni1A63=2+250|\\\n\n uni1A60=2+0|\\\n\n uni1A3D=5+250|\\\n\n uni1A60=5+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 88, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_014() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/3cc01fede4debd4b7794ccb1b16cdb9987ea7571.ttf\",\n\n \"\\u{1A3D}\\u{1A60}\\u{1A3D}\\u{1A63}\\u{1A60}\\u{1A3D}\\u{1A59}\",\n\n \"\",\n\n ),\n\n \"uni1A3D=0+250|\\\n\n uni1A60=0+0|\\\n\n uni1A3D=2+250|\\\n\n uni1A63=2+250|\\\n\n uni1A60=2+0|\\\n\n uni1A3D=5+250|\\\n\n uni1A59=5+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 89, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_002() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/e68a88939e0f06e34d2bc911f09b70890289c8fd.ttf\",\n\n \"\\u{AA00}\\u{AA34}\\u{AA36}\",\n\n \"\",\n\n ),\n\n \"raMedial_cham_pre=0+400|\\\n\n a_cham=0+1121|\\\n\n waMedial_cham=0@-32,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 90, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_018() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8C}\\u{11CB1}\\u{11C8D}\",\n\n \"\",\n\n ),\n\n \"u11C8C.11CB1=0+2793|\\\n\n u11C8D=2+2000\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 91, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_004() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/e68a88939e0f06e34d2bc911f09b70890289c8fd.ttf\",\n\n \"\\u{AA00}\\u{AA35}\\u{AA36}\",\n\n \"\",\n\n ),\n\n \"a_cham=0+1121|\\\n\n laMedial_waMedial_cham=0@43,0+0\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 92, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_syllable_007() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/59a585a63b3df608fbeef00956c8c108deec7de6.ttf\",\n\n \"\\u{1BC7}\\u{1BEA}\\u{1BF3}\",\n\n \"--no-glyph-names\",\n\n ),\n\n \"1=0+749|\\\n\n 2=0+402|\\\n\n 4=0+535|\\\n\n 3=0+401\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 93, "score": 127335.29003879137 }, { "content": "#[test]\n\nfn use_marchen_021() {\n\n assert_eq!(\n\n shape(\n\n \"in-house/fonts/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf\",\n\n \"\\u{11C8D}\\u{11CB2}\\u{11C81}\",\n\n \"\",\n\n ),\n\n \"u11C8D.11CB2=0+2000|\\\n\n u11C81=2+2400\"\n\n );\n\n}\n\n\n", "file_path": "tests/shaping_in_house.rs", "rank": 94, "score": 127335.29003879137 }, { "content": "#[inline]\n\npub fn hb_flag_unsafe(x: u32) -> u32 {\n\n if x < 32 { 1 << x } else { 0 }\n\n}\n\n\n\n#[inline]\n\npub const fn hb_flag64(x: u32) -> u64 {\n\n 1 << x as u64\n\n}\n\n\n", "file_path": "src/complex/mod.rs", "rank": 95, "score": 124370.86311088756 }, { "content": "#[inline]\n\npub fn hb_flag64_unsafe(x: u32) -> u64 {\n\n if x < 64 { 1 << (x as u64) } else { 0 }\n\n}\n\n\n", "file_path": "src/complex/mod.rs", "rank": 96, "score": 124370.86311088756 }, { "content": "pub fn get_category(u: u32) -> Category {\n\n match u >> 12 {\n\n 0x0 => {\n\n if (0x0028..=0x003F).contains(&u) { return USE_TABLE[u as usize - 0x0028 + USE_OFFSET_0X0028]; }\n\n if (0x00A0..=0x00D7).contains(&u) { return USE_TABLE[u as usize - 0x00A0 + USE_OFFSET_0X00A0]; }\n\n if (0x0348..=0x034F).contains(&u) { return USE_TABLE[u as usize - 0x0348 + USE_OFFSET_0X0348]; }\n\n if (0x0900..=0x0DF7).contains(&u) { return USE_TABLE[u as usize - 0x0900 + USE_OFFSET_0X0900]; }\n\n if (0x0F18..=0x0FC7).contains(&u) { return USE_TABLE[u as usize - 0x0F18 + USE_OFFSET_0X0F18]; }\n\n }\n\n 0x1 => {\n\n if (0x1000..=0x109F).contains(&u) { return USE_TABLE[u as usize - 0x1000 + USE_OFFSET_0X1000]; }\n\n if (0x1700..=0x17EF).contains(&u) { return USE_TABLE[u as usize - 0x1700 + USE_OFFSET_0X1700]; }\n\n if (0x1900..=0x1A9F).contains(&u) { return USE_TABLE[u as usize - 0x1900 + USE_OFFSET_0X1900]; }\n\n if (0x1B00..=0x1C4F).contains(&u) { return USE_TABLE[u as usize - 0x1B00 + USE_OFFSET_0X1B00]; }\n\n if (0x1CD0..=0x1CFF).contains(&u) { return USE_TABLE[u as usize - 0x1CD0 + USE_OFFSET_0X1CD0]; }\n\n if (0x1DF8..=0x1DFF).contains(&u) { return USE_TABLE[u as usize - 0x1DF8 + USE_OFFSET_0X1DF8]; }\n\n }\n\n 0x2 => {\n\n if (0x2008..=0x2017).contains(&u) { return USE_TABLE[u as usize - 0x2008 + USE_OFFSET_0X2008]; }\n\n if (0x2060..=0x2087).contains(&u) { return USE_TABLE[u as usize - 0x2060 + USE_OFFSET_0X2060]; }\n", "file_path": "src/complex/universal_table.rs", "rank": 97, "score": 124364.72516898529 }, { "content": "fn parse_private_use_subtag(\n\n private_use_subtag: Option<&str>,\n\n prefix: &str,\n\n normalize: fn(&u8) -> u8,\n\n tags: &mut ThreeTags,\n\n) -> bool {\n\n let private_use_subtag = match private_use_subtag {\n\n Some(v) => v,\n\n None => return false,\n\n };\n\n\n\n let private_use_subtag = match private_use_subtag.find(prefix) {\n\n Some(idx) => &private_use_subtag[idx + prefix.len()..],\n\n None => return false,\n\n };\n\n\n\n let mut tag = SmallVec::<[u8; 4]>::new();\n\n for c in private_use_subtag.bytes().take(4) {\n\n if c.is_ascii_alphanumeric() {\n\n tag.push((normalize)(&c));\n", "file_path": "src/tag.rs", "rank": 98, "score": 124132.01031906379 }, { "content": "pub fn joining_type(u: char) -> JoiningType {\n\n let u = u as u32;\n\n match u >> 12 {\n\n 0x0 => {\n\n if (0x0600..=0x08E2).contains(&u) {\n\n return JOINING_TABLE[u as usize - 0x0600 + JOINING_OFFSET_0X0600];\n\n }\n\n }\n\n 0x1 => {\n\n if (0x1806..=0x18AA).contains(&u) {\n\n return JOINING_TABLE[u as usize - 0x1806 + JOINING_OFFSET_0X1806];\n\n }\n\n }\n\n 0x2 => {\n\n if (0x200C..=0x2069).contains(&u) {\n\n return JOINING_TABLE[u as usize - 0x200C + JOINING_OFFSET_0X200C];\n\n }\n\n }\n\n 0xA => {\n\n if (0xA840..=0xA873).contains(&u) {\n", "file_path": "src/complex/arabic_table.rs", "rank": 99, "score": 121889.28709163755 } ]
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![config.addr.clone()]\n\n } else {\n\n config.join_list.clone()\n\n };\n\n let transport_manager = TransportManager::new(root_list, engines.state()).await;\n\n let address_resolver = transport_manager.address_resolver();\n\n let node = Node::new(config.clone(), engines, transport_manager.clone()).await?;\n\n\n\n let ident =\n\n bootstrap_or_join_cluster(&config, &node, transport_manager.root_client()).await?;\n\n node.bootstrap(&ident).await?;\n\n let root = Root::new(transport_manager.clone(), &ident, config.clone());\n\n let initial_node_descs = root.bootstrap(&node).await?;\n\n address_resolver.set_initial_nodes(initial_node_descs);\n\n\n", "file_path": "src/server/src/bootstrap.rs", "rank": 0, "score": 240874.34356105587 }, { "content": "fn list_numeric_path(root: &Path) -> Result<Vec<(u64, PathBuf)>> {\n\n let mut values = vec![];\n\n for entry in std::fs::read_dir(root)? {\n\n let entry = entry?;\n\n let path = entry.path();\n\n if !path.is_dir() {\n\n continue;\n\n }\n\n if let Some(name) = path.file_name().and_then(OsStr::to_str) {\n\n let index: u64 = match name.parse() {\n\n Ok(id) => id,\n\n Err(_) => continue,\n\n };\n\n values.push((index, path));\n\n }\n\n }\n\n\n\n // The order in which filenames are read by successive calls to `readdir()` depends on the\n\n // filesystem implementation.\n\n values.sort_unstable();\n", "file_path": "src/server/src/raftgroup/snap/mod.rs", "rank": 1, "score": 225529.77579872077 }, { "content": "type LogResponse = Result<(), String>;\n\n\n\nimpl LogWriter {\n\n pub fn new(max_io_batch_size: u64, engine: Arc<raft_engine::Engine>) -> LogWriter {\n\n let (join_handle, sender) = start_log_writer(max_io_batch_size, engine);\n\n LogWriter {\n\n sender,\n\n _inner: Arc::new(WriterInner {\n\n handle: Some(join_handle),\n\n }),\n\n }\n\n }\n\n\n\n pub fn submit(&mut self, batch: raft_engine::LogBatch) -> oneshot::Receiver<LogResponse> {\n\n let (sender, receiver) = oneshot::channel();\n\n let req = LogRequest { batch, sender };\n\n match self.sender.start_send(req) {\n\n Ok(()) => {}\n\n Err(err) => {\n\n // Ignore disconnect error, since a available Sender is still hold.\n", "file_path": "src/server/src/raftgroup/io/log_writer.rs", "rank": 2, "score": 225272.1795751209 }, { "content": "pub fn take_propose_metrics(start_at: Instant, result: Result<()>) -> Result<()> {\n\n let elapsed = elapsed_seconds(start_at);\n\n match &result {\n\n Ok(()) => {\n\n RAFTGROUP_PROPOSE_TOTAL.ok.inc();\n\n RAFTGROUP_PROPOSE_DURATION_SECONDS.ok.observe(elapsed);\n\n }\n\n Err(Error::NotLeader(..)) => {\n\n RAFTGROUP_PROPOSE_TOTAL.not_leader.inc();\n\n RAFTGROUP_PROPOSE_DURATION_SECONDS\n\n .not_leader\n\n .observe(elapsed);\n\n }\n\n Err(Error::ServiceIsBusy(_)) => {\n\n RAFTGROUP_PROPOSE_TOTAL.busy.inc();\n\n RAFTGROUP_PROPOSE_DURATION_SECONDS.busy.observe(elapsed);\n\n }\n\n _ => {\n\n RAFTGROUP_PROPOSE_TOTAL.unknown.inc();\n\n RAFTGROUP_PROPOSE_DURATION_SECONDS.unknown.observe(elapsed);\n\n }\n\n }\n\n result\n\n}\n\n\n", "file_path": "src/server/src/raftgroup/metrics.rs", "rank": 3, "score": 223282.59114832716 }, { "content": "fn open_raft_engine(log_path: &Path) -> Result<raft_engine::Engine> {\n\n use raft_engine::{Config, Engine};\n\n let engine_dir = log_path.join(\"engine\");\n\n let snap_dir = log_path.join(\"snap\");\n\n create_dir_all_if_not_exists(&engine_dir)?;\n\n create_dir_all_if_not_exists(&snap_dir)?;\n\n let engine_cfg = Config {\n\n dir: engine_dir.to_str().unwrap().to_owned(),\n\n enable_log_recycle: false,\n\n ..Default::default()\n\n };\n\n Ok(Engine::open(engine_cfg)?)\n\n}\n\n\n", "file_path": "src/server/src/engine/mod.rs", "rank": 4, "score": 204053.30364358186 }, { "content": "/// Find the next available port to listen on.\n\npub fn next_avail_port() -> u16 {\n\n next_n_avail_port(1)[0]\n\n}\n\n\n", "file_path": "src/server/tests/helper/socket.rs", "rank": 5, "score": 194926.0865514347 }, { "content": "fn create_dir_all_if_not_exists<P: AsRef<Path>>(dir: &P) -> Result<()> {\n\n use std::io::ErrorKind;\n\n match std::fs::create_dir_all(dir.as_ref()) {\n\n Ok(()) => Ok(()),\n\n Err(err) if err.kind() == ErrorKind::AlreadyExists => Ok(()),\n\n Err(err) => Err(err.into()),\n\n }\n\n}\n", "file_path": "src/server/src/engine/mod.rs", "rank": 6, "score": 190429.10969323083 }, { "content": "#[inline]\n\nfn is_sst_file<P: AsRef<Path>>(path: P) -> bool {\n\n let path = path.as_ref();\n\n path.is_file() && path.extension().map(|ext| ext == \"sst\").unwrap_or_default()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::{path::Path, sync::Arc};\n\n\n\n use engula_api::server::v1::{\n\n shard_desc::{Partition, RangePartition},\n\n GroupDesc, ShardDesc,\n\n };\n\n use tempdir::TempDir;\n\n\n\n use super::*;\n\n use crate::{\n\n engine::{GroupEngine, WriteBatch, WriteStates},\n\n runtime::ExecutorOwner,\n\n EngineConfig,\n", "file_path": "src/server/src/node/replica/fsm/checkpoint.rs", "rank": 7, "score": 188039.6564797372 }, { "content": "pub fn make_admin_service(server: Server) -> AdminService {\n\n let router = Router::empty()\n\n .route(\n\n \"/metrics\",\n\n self::metrics::MetricsHandle::new(server.to_owned()),\n\n )\n\n .route(\"/job\", self::job::JobHandle::new(server.to_owned()))\n\n .route(\n\n \"/metadata\",\n\n self::metadata::MetadataHandle::new(server.to_owned()),\n\n )\n\n .route(\"/health\", self::health::HealthHandle)\n\n .route(\n\n \"/cordon\",\n\n self::cluster::CordonHandle::new(server.to_owned()),\n\n )\n\n .route(\n\n \"/uncordon\",\n\n self::cluster::UncordonHandle::new(server.to_owned()),\n\n )\n\n .route(\"/drain\", self::cluster::DrainHandle::new(server.to_owned()))\n\n .route(\n\n \"/node_status\",\n\n self::cluster::StatusHandle::new(server.to_owned()),\n\n )\n\n .route(\"/monitor\", self::monitor::MonitorHandle::new(server));\n\n let api = Router::nest(\"/admin\", router);\n\n AdminService::new(api)\n\n}\n", "file_path": "src/server/src/service/admin/mod.rs", "rank": 8, "score": 187121.514582621 }, { "content": "pub fn next_n_avail_port(n: usize) -> Vec<u16> {\n\n #[allow(clippy::needless_collect)]\n\n let sockets = (0..n)\n\n .into_iter()\n\n .map(|_| {\n\n let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();\n\n socket.set_reuse_address(true).unwrap();\n\n socket.set_reuse_port(true).unwrap();\n\n socket\n\n .bind(&\"127.0.0.1:0\".parse::<SocketAddr>().unwrap().into())\n\n .unwrap();\n\n socket\n\n })\n\n .collect::<Vec<_>>();\n\n sockets\n\n .into_iter()\n\n .map(|socket| {\n\n socket\n\n .local_addr()\n\n .unwrap()\n\n .as_socket_ipv4()\n\n .unwrap()\n\n .port()\n\n })\n\n .collect()\n\n}\n", "file_path": "src/server/tests/helper/socket.rs", "rank": 9, "score": 177279.4646280975 }, { "content": "pub fn add_shard(shard: ShardDesc) -> EvalResult {\n\n use crate::serverpb::v1::SyncOp;\n\n\n\n EvalResult {\n\n op: Some(SyncOp::add_shard(shard)),\n\n ..Default::default()\n\n }\n\n}\n", "file_path": "src/server/src/node/replica/eval/mod.rs", "rank": 10, "score": 170331.87458931978 }, { "content": "#[test]\n\nfn join_node() -> Result<()> {\n\n let mut ctx = TestContext::new(\"join-node\");\n\n let node_1_addr = ctx.next_listen_address();\n\n ctx.spawn_server(1, &node_1_addr, true, vec![]);\n\n\n\n let node_2_addr = ctx.next_listen_address();\n\n ctx.spawn_server(2, &node_2_addr, false, vec![node_1_addr.clone()]);\n\n\n\n block_on_current(async {\n\n node_client_with_retry(&node_1_addr).await;\n\n node_client_with_retry(&node_2_addr).await;\n\n });\n\n\n\n // At this point, initialization and join has been completed.\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/server/tests/bootstrap_test.rs", "rank": 11, "score": 168343.0363800603 }, { "content": "#[test]\n\nfn bootstrap_cluster() -> Result<()> {\n\n let mut ctx = TestContext::new(\"bootstrap-cluster\");\n\n let node_1_addr = ctx.next_listen_address();\n\n ctx.spawn_server(1, &node_1_addr, true, vec![]);\n\n\n\n block_on_current(async {\n\n node_client_with_retry(&node_1_addr).await;\n\n });\n\n\n\n // At this point, initialization has been completed.\n\n Ok(())\n\n}\n\n\n", "file_path": "src/server/tests/bootstrap_test.rs", "rank": 12, "score": 168343.0363800603 }, { "content": "pub fn setup_panic_hook() {\n\n let orig_hook = panic::take_hook();\n\n panic::set_hook(Box::new(move |panic_info| {\n\n // invoke the default handler and exit the process\n\n orig_hook(panic_info);\n\n tracing::error!(\"{:#?}\", panic_info);\n\n tracing::error!(\"{:#?}\", std::backtrace::Backtrace::force_capture());\n\n process::exit(1);\n\n }));\n\n}\n", "file_path": "src/server/tests/helper/init.rs", "rank": 13, "score": 164045.52816516455 }, { "content": "/// Returns a `Executor` view over the currently running `ExecutorOwner`.\n\n///\n\n/// # Panics\n\n///\n\n/// This will panic if called outside the context of a runtime.\n\npub fn current() -> Executor {\n\n Executor {\n\n handle: tokio::runtime::Handle::current(),\n\n }\n\n}\n\n\n\n#[inline]\n\nconst fn should_skip_slow_log<F: Future>() -> bool {\n\n const_str::contains!(std::any::type_name::<F>(), \"start_raft_group\")\n\n}\n", "file_path": "src/server/src/runtime/executor.rs", "rank": 14, "score": 162590.43539407826 }, { "content": "pub fn take_database_request_metrics(\n\n request: &collection_request_union::Request,\n\n) -> &'static Histogram {\n\n use collection_request_union::Request;\n\n\n\n match request {\n\n Request::Get(_) => {\n\n PROXY_SERVICE_DATABASE_REQUEST_TOTAL.get.inc();\n\n &PROXY_SERVICE_DATABASE_REQUEST_DURATION_SECONDS.get\n\n }\n\n Request::Put(_) => {\n\n PROXY_SERVICE_DATABASE_REQUEST_TOTAL.put.inc();\n\n &PROXY_SERVICE_DATABASE_REQUEST_DURATION_SECONDS.put\n\n }\n\n Request::Delete(_) => {\n\n PROXY_SERVICE_DATABASE_REQUEST_TOTAL.delete.inc();\n\n &PROXY_SERVICE_DATABASE_REQUEST_DURATION_SECONDS.delete\n\n }\n\n }\n\n}\n", "file_path": "src/server/src/service/metrics.rs", "rank": 15, "score": 161085.94588065534 }, { "content": "type SnapResult = Result<SnapshotChunk, tonic::Status>;\n\n\n\npub struct SnapshotChunkStream {\n\n info: SnapshotGuard,\n\n file: Option<File>,\n\n file_index: usize,\n\n}\n\n\n\npub async fn send_snapshot(\n\n snap_mgr: &SnapManager,\n\n replica_id: u64,\n\n snapshot_id: Vec<u8>,\n\n) -> Result<SnapshotChunkStream> {\n\n let snapshot_info = match snap_mgr.lock_snap(replica_id, &snapshot_id) {\n\n Some(snap_info) => snap_info,\n\n None => {\n\n return Err(Error::InvalidArgument(\"no such snapshot\".to_string()));\n\n }\n\n };\n\n\n", "file_path": "src/server/src/raftgroup/snap/send.rs", "rank": 16, "score": 158689.06581535484 }, { "content": "pub fn dispatch_creating_snap_task(\n\n replica_id: u64,\n\n mut sender: mpsc::Sender<Request>,\n\n state_machine: &impl StateMachine,\n\n snap_mgr: SnapManager,\n\n) {\n\n let builder = state_machine.snapshot_builder();\n\n crate::runtime::current().spawn(None, TaskPriority::IoLow, async move {\n\n match create_snapshot(replica_id, &snap_mgr, builder).await {\n\n Ok(_) => {\n\n info!(\"replica {replica_id} create snapshot success\");\n\n }\n\n Err(err) => {\n\n error!(\"replica {replica_id} create snapshot: {err}\");\n\n }\n\n };\n\n\n\n sender\n\n .send(Request::CreateSnapshotFinished)\n\n .await\n", "file_path": "src/server/src/raftgroup/snap/create.rs", "rank": 17, "score": 158285.001325163 }, { "content": "pub fn dispatch_downloading_snap_task(\n\n replica_id: u64,\n\n mut sender: mpsc::Sender<Request>,\n\n snap_mgr: SnapManager,\n\n tran_mgr: ChannelManager,\n\n from_replica: ReplicaDesc,\n\n mut msg: Message,\n\n) {\n\n crate::runtime::current().spawn(None, TaskPriority::IoLow, async move {\n\n match download_snap(replica_id, tran_mgr, snap_mgr, from_replica, &msg).await {\n\n Ok(snap_id) => {\n\n msg.snapshot.as_mut().unwrap().data = snap_id;\n\n let request = Request::InstallSnapshot { msg };\n\n sender.send(request).await.unwrap_or_default();\n\n }\n\n Err(err) => {\n\n error!(\"replica {replica_id} download snapshot: {err}\");\n\n let request = Request::RejectSnapshot { msg };\n\n sender.send(request).await.unwrap_or_default();\n\n }\n", "file_path": "src/server/src/raftgroup/snap/download.rs", "rank": 18, "score": 158285.001325163 }, { "content": "type DbResult<T> = Result<T, rocksdb::Error>;\n\n\n\npub(crate) struct RawDb {\n\n pub options: rocksdb::Options,\n\n pub db: rocksdb::DB,\n\n}\n\n\n\nimpl RawDb {\n\n #[inline]\n\n pub fn cf_handle(&self, name: &str) -> Option<Arc<rocksdb::BoundColumnFamily>> {\n\n self.db.cf_handle(name)\n\n }\n\n\n\n #[inline]\n\n pub fn create_cf<N: AsRef<str>>(&self, name: N) -> DbResult<()> {\n\n self.db.create_cf(name, &self.options)\n\n }\n\n\n\n #[inline]\n\n pub fn drop_cf(&self, name: &str) -> DbResult<()> {\n", "file_path": "src/server/src/engine/mod.rs", "rank": 19, "score": 157936.2696820575 }, { "content": "type ShardChunkResult = Result<ShardChunk, tonic::Status>;\n\n\n\npub struct ShardChunkStream {\n\n inner: Pin<Box<dyn futures::Stream<Item = ShardChunkResult> + Send + 'static>>,\n\n}\n\n\n\nimpl ShardChunkStream {\n\n pub fn new(shard_id: u64, chunk_size: usize, last_key: Vec<u8>, replica: Arc<Replica>) -> Self {\n\n let inner = shard_chunk_stream(shard_id, chunk_size, last_key, replica);\n\n ShardChunkStream {\n\n inner: Box::pin(inner),\n\n }\n\n }\n\n}\n\n\n\nimpl futures::Stream for ShardChunkStream {\n\n type Item = Result<ShardChunk, tonic::Status>;\n\n\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {\n\n let me = self.get_mut();\n\n Pin::new(&mut me.inner).poll_next(cx)\n\n }\n\n}\n", "file_path": "src/server/src/node/migrate/pull.rs", "rank": 20, "score": 156347.52240697487 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n std::env::set_var(\"PROTOC\", protoc_build::PROTOC);\n\n std::env::set_var(\"PROTOC_INCLUDE\", protoc_build::PROTOC_INCLUDE);\n\n\n\n let mut config = prost_build::Config::default();\n\n config.extern_path(\".engula.server.v1\", \"::engula_api::server::v1\");\n\n config.extern_path(\".engula.v1\", \"::engula_api::v1\");\n\n config.extern_path(\".eraftpb\", \"::raft::eraftpb\");\n\n tonic_build::configure().compile_with_config(\n\n config,\n\n &[\n\n \"proto/v1/metadata.proto\",\n\n \"proto/v1/raft.proto\",\n\n \"proto/v1/schedule.proto\",\n\n ],\n\n &[\"proto\", \"proto/include\", \"../api/\"],\n\n )?;\n\n Ok(())\n\n}\n", "file_path": "src/server/build.rs", "rank": 21, "score": 156272.49471490274 }, { "content": "fn other_store_error(e: raft_engine::Error) -> raft::Error {\n\n raft::Error::Store(raft::StorageError::Other(Box::new(e)))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::sync::Arc;\n\n\n\n use raft_engine::{Config, Engine};\n\n use tempdir::TempDir;\n\n use tracing::info;\n\n\n\n use super::*;\n\n use crate::runtime::*;\n\n\n\n fn mocked_entries(select_term: Option<u64>) -> Vec<(u64, u64)> {\n\n let entries = vec![\n\n // term 1\n\n (1, 1),\n\n (2, 1),\n", "file_path": "src/server/src/raftgroup/storage.rs", "rank": 22, "score": 155172.94439197562 }, { "content": "fn boxed(body: String) -> BoxBody {\n\n use http_body::Body;\n\n\n\n body.map_err(|_| panic!(\"\")).boxed_unsync()\n\n}\n", "file_path": "src/server/src/service/admin/service.rs", "rank": 23, "score": 150998.14952635037 }, { "content": "pub fn take_report_metrics() -> &'static Histogram {\n\n NODE_REPORT_TOTAL.inc();\n\n &NODE_REPORT_DURATION_SECONDS\n\n}\n\n\n", "file_path": "src/server/src/node/metrics.rs", "rank": 24, "score": 149790.13605418723 }, { "content": "pub fn take_pull_shard_metrics() -> &'static Histogram {\n\n NODE_PULL_SHARD_TOTAL.inc();\n\n &NODE_PULL_SHARD_DURATION_SECONDS\n\n}\n", "file_path": "src/server/src/node/metrics.rs", "rank": 25, "score": 147135.40733843314 }, { "content": "#[inline]\n\npub fn take_spawn_metrics(priority: TaskPriority) {\n\n match priority {\n\n TaskPriority::Real => EXECUTOR_SPAWN_TOTAL.real.inc(),\n\n TaskPriority::High => EXECUTOR_SPAWN_TOTAL.high.inc(),\n\n TaskPriority::Middle => EXECUTOR_SPAWN_TOTAL.middle.inc(),\n\n TaskPriority::Low => EXECUTOR_SPAWN_TOTAL.low.inc(),\n\n TaskPriority::IoHigh => EXECUTOR_SPAWN_TOTAL.io_high.inc(),\n\n TaskPriority::IoLow => EXECUTOR_SPAWN_TOTAL.io_low.inc(),\n\n }\n\n}\n", "file_path": "src/server/src/runtime/metrics.rs", "rank": 26, "score": 147135.40733843314 }, { "content": "pub fn take_apply_snapshot_metrics() -> &'static Histogram {\n\n RAFTGROUP_APPLY_SNAPSHOT_TOTAL.inc();\n\n &RAFTGROUP_APPLY_SNAPSHOT_DURATION_SECONDS\n\n}\n\n\n", "file_path": "src/server/src/raftgroup/metrics.rs", "rank": 27, "score": 147135.40733843314 }, { "content": "pub fn take_destory_replica_metrics() -> &'static Histogram {\n\n NODE_DESTORY_REPLICA_TOTAL.inc();\n\n &NODE_DESTORY_REPLICA_DURATION_SECONDS\n\n}\n\n\n", "file_path": "src/server/src/node/metrics.rs", "rank": 28, "score": 147135.40733843314 }, { "content": "pub fn take_create_snapshot_metrics() -> &'static Histogram {\n\n RAFTGROUP_CREATE_SNAPSHOT_TOTAL.inc();\n\n &RAFTGROUP_CREATE_SNAPSHOT_DURATION_SECONDS\n\n}\n\n\n", "file_path": "src/server/src/raftgroup/metrics.rs", "rank": 29, "score": 147135.40733843314 }, { "content": "pub fn take_download_snapshot_metrics() -> &'static Histogram {\n\n RAFTGROUP_DOWNLOAD_SNAPSHOT_TOTAL.inc();\n\n &RAFTGROUP_DOWNLOAD_SNAPSHOT_DURATION_SECONDS\n\n}\n\n\n", "file_path": "src/server/src/raftgroup/metrics.rs", "rank": 30, "score": 147135.40733843314 }, { "content": "pub fn apply_snapshot<M: StateMachine>(\n\n replica_id: u64,\n\n snap_mgr: &SnapManager,\n\n applier: &mut Applier<M>,\n\n snapshot: &Snapshot,\n\n) {\n\n record_latency!(take_apply_snapshot_metrics());\n\n let snap_id = &snapshot.data;\n\n let snap_info = snap_mgr\n\n .lock_snap(replica_id, snap_id)\n\n .expect(\"The snapshot should does not be gc before apply\");\n\n // TODO(walter) check snapshot data integrity.\n\n let snap_dir = snap_info.base_dir.join(SNAP_DATA);\n\n applier\n\n .apply_snapshot(&snap_dir)\n\n .expect(\"apply snapshot must success, because the data integrity might broken\");\n\n}\n", "file_path": "src/server/src/raftgroup/snap/apply.rs", "rank": 31, "score": 147135.40733843314 }, { "content": "pub fn elapsed_seconds(instant: Instant) -> f64 {\n\n let d = instant.elapsed();\n\n d.as_secs() as f64 + (d.subsec_nanos() as f64) / 1e9\n\n}\n", "file_path": "src/server/src/raftgroup/metrics.rs", "rank": 32, "score": 146432.52869149708 }, { "content": "fn group_role_digest(desc: &GroupDesc) -> String {\n\n let mut voters = vec![];\n\n let mut learners = vec![];\n\n for r in &desc.replicas {\n\n match ReplicaRole::from_i32(r.role) {\n\n Some(ReplicaRole::Voter | ReplicaRole::IncomingVoter | ReplicaRole::DemotingVoter) => {\n\n voters.push(r.id)\n\n }\n\n Some(ReplicaRole::Learner) => learners.push(r.id),\n\n _ => continue,\n\n }\n\n }\n\n format!(\"voters {voters:?} learners {learners:?}\")\n\n}\n\n\n", "file_path": "src/server/src/node/replica/fsm/mod.rs", "rank": 33, "score": 143418.39704653417 }, { "content": "fn change_replicas_digest(changes: &[ChangeReplica]) -> String {\n\n let mut add_voters = vec![];\n\n let mut remove_replicas = vec![];\n\n let mut add_learners = vec![];\n\n for cc in changes {\n\n match ChangeReplicaType::from_i32(cc.change_type) {\n\n Some(ChangeReplicaType::Add) => add_voters.push(cc.replica_id),\n\n Some(ChangeReplicaType::AddLearner) => add_learners.push(cc.replica_id),\n\n Some(ChangeReplicaType::Remove) => remove_replicas.push(cc.replica_id),\n\n _ => continue,\n\n }\n\n }\n\n format!(\"add voters {add_voters:?} learners {add_learners:?} remove {remove_replicas:?}\")\n\n}\n\n\n", "file_path": "src/server/src/node/replica/fsm/mod.rs", "rank": 34, "score": 143418.39704653417 }, { "content": "#[test]\n\nfn operation_with_leader_transfer() {\n\n block_on_current(async move {\n\n let mut ctx = TestContext::new(\"rw_test__operation_with_leader_transfer\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let app = c.app_client().await;\n\n\n\n let db = app.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Range {}))\n\n .await\n\n .unwrap();\n\n c.assert_collection_ready(&co.desc()).await;\n\n\n\n for i in 0..1000 {\n\n let k = format!(\"key-{i}\").as_bytes().to_vec();\n\n let v = format!(\"value-{i}\").as_bytes().to_vec();\n\n co.put(k.clone(), v).await.unwrap();\n\n let r = co.get(k.clone()).await.unwrap();\n", "file_path": "src/server/tests/rw_test.rs", "rank": 35, "score": 140023.44972200095 }, { "content": "#[test]\n\nfn operation_with_config_change() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"rw_test__operation_with_config_change\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let root_addr = nodes.get(&0).unwrap().clone();\n\n let c = ClusterClient::new(nodes).await;\n\n let app = c.app_client().await;\n\n\n\n let db = app.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Hash { slots: 3 }))\n\n .await\n\n .unwrap();\n\n c.assert_collection_ready(&co.desc()).await;\n\n c.assert_root_group_has_promoted().await;\n\n\n\n for i in 0..3000 {\n\n if i == 20 {\n\n ctx.stop_server(2).await;\n", "file_path": "src/server/tests/rw_test.rs", "rank": 36, "score": 140023.44972200095 }, { "content": "#[test]\n\nfn operation_with_shard_migration() {\n\n block_on_current(async move {\n\n let mut ctx = TestContext::new(\"rw_test__operation_with_shard_migration\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let app = c.app_client().await;\n\n\n\n let db = app.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Range {}))\n\n .await\n\n .unwrap();\n\n c.assert_collection_ready(&co.desc()).await;\n\n\n\n let source_state = c\n\n .find_router_group_state_by_key(&co.desc(), &[0])\n\n .await\n\n .unwrap();\n\n let prev_group_id = source_state.id;\n", "file_path": "src/server/tests/rw_test.rs", "rank": 37, "score": 140023.44972200095 }, { "content": "pub fn conf_state_from_group_descriptor(desc: &GroupDesc) -> ConfState {\n\n let mut cs = ConfState::default();\n\n let mut in_joint = false;\n\n for replica in desc.replicas.iter() {\n\n match ReplicaRole::from_i32(replica.role).unwrap_or(ReplicaRole::Voter) {\n\n ReplicaRole::Voter => {\n\n cs.voters.push(replica.id);\n\n }\n\n ReplicaRole::Learner => {\n\n cs.learners.push(replica.id);\n\n }\n\n ReplicaRole::IncomingVoter => {\n\n in_joint = true;\n\n cs.voters.push(replica.id);\n\n }\n\n ReplicaRole::DemotingVoter => {\n\n in_joint = true;\n\n cs.voters_outgoing.push(replica.id);\n\n cs.learners_next.push(replica.id);\n\n }\n\n }\n\n }\n\n if !in_joint {\n\n cs.voters_outgoing.clear();\n\n }\n\n cs\n\n}\n", "file_path": "src/server/src/raftgroup/mod.rs", "rank": 38, "score": 136584.73085774088 }, { "content": "pub fn take_group_request_metrics(\n\n request: &group_request_union::Request,\n\n) -> Option<&'static Histogram> {\n\n use group_request_union::Request;\n\n\n\n match request {\n\n Request::Get(_) => {\n\n GROUP_CLIENT_GROUP_REQUEST_TOTAL.get.inc();\n\n Some(&GROUP_CLIENT_GROUP_REQUEST_DURATION_SECONDS.get)\n\n }\n\n Request::Put(_) => {\n\n GROUP_CLIENT_GROUP_REQUEST_TOTAL.put.inc();\n\n Some(&GROUP_CLIENT_GROUP_REQUEST_DURATION_SECONDS.put)\n\n }\n\n Request::Delete(_) => {\n\n GROUP_CLIENT_GROUP_REQUEST_TOTAL.delete.inc();\n\n Some(&GROUP_CLIENT_GROUP_REQUEST_DURATION_SECONDS.delete)\n\n }\n\n Request::PrefixList(_) => {\n\n GROUP_CLIENT_GROUP_REQUEST_TOTAL.list.inc();\n", "file_path": "src/client/src/metrics.rs", "rank": 39, "score": 135019.41380238032 }, { "content": "pub fn take_batch_request_metrics(request: &BatchRequest) -> &'static Histogram {\n\n NODE_SERVICE_BATCH_REQUEST_SIZE.observe(request.requests.len() as f64);\n\n NODE_SERVICE_BATCH_REQUEST_TOTAL.inc();\n\n &NODE_SERVICE_BATCH_REQUEST_DURATION_SECONDS\n\n}\n\n\n\nmacro_rules! simple_node_method {\n\n ($name: ident) => {\n\n paste::paste! {\n\n lazy_static! {\n\n pub static ref [<NODE_SERVICE_ $name:upper _REQUEST_TOTAL>]: IntCounter = register_int_counter!(\n\n concat!(\"node_service_\", stringify!($name), \"_request_total\"),\n\n concat!(\"The total \", stringify!($name), \" requests of node service\")\n\n )\n\n .unwrap();\n\n pub static ref [<NODE_SERVICE_ $name:upper _REQUEST_DURATION_SECONDS>]: Histogram =\n\n register_histogram!(\n\n concat!(\"node_service_\", stringify!($name), \"_request_duration_seconds\"),\n\n concat!(\"The intervals of \", stringify!($name), \" requests of node service\"),\n\n exponential_buckets(0.00005, 1.8, 26).unwrap(),\n", "file_path": "src/server/src/service/metrics.rs", "rank": 40, "score": 133665.45343796068 }, { "content": "pub fn take_read_metrics(read_policy: ReadPolicy) -> &'static Histogram {\n\n match read_policy {\n\n ReadPolicy::LeaseRead => {\n\n RAFTGROUP_READ_TOTAL.lease_based.inc();\n\n &RAFTGROUP_READ_DURATION_SECONDS.lease_based\n\n }\n\n ReadPolicy::ReadIndex => {\n\n RAFTGROUP_READ_TOTAL.read_index.inc();\n\n &RAFTGROUP_READ_DURATION_SECONDS.read_index\n\n }\n\n ReadPolicy::Relaxed => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/server/src/raftgroup/metrics.rs", "rank": 41, "score": 133665.45343796068 }, { "content": "pub fn setup_panic_hook() {\n\n let orig_hook = panic::take_hook();\n\n panic::set_hook(Box::new(move |panic_info| {\n\n // invoke the default handler and exit the process\n\n orig_hook(panic_info);\n\n tracing::error!(\"{:#?}\", panic_info);\n\n process::exit(1);\n\n }));\n\n}\n", "file_path": "src/client/tests/transport_error_test.rs", "rank": 42, "score": 132859.17452808318 }, { "content": "#[allow(dead_code)]\n\npub fn block_on_current<F: Future>(future: F) -> F::Output {\n\n let rt = Builder::new_current_thread().enable_all().build().unwrap();\n\n rt.block_on(future)\n\n}\n\n\n", "file_path": "src/server/tests/helper/runtime.rs", "rank": 43, "score": 131116.93007790227 }, { "content": "pub fn take_group_request_metrics(request: &GroupRequest) -> Option<&'static Histogram> {\n\n use group_request_union::Request;\n\n\n\n match request.request.as_ref().and_then(|v| v.request.as_ref()) {\n\n Some(Request::Get(_)) => {\n\n NODE_SERVICE_GROUP_REQUEST_TOTAL.get.inc();\n\n Some(&NODE_SERVICE_GROUP_REQUEST_DURATION_SECONDS.get)\n\n }\n\n Some(Request::Put(_)) => {\n\n NODE_SERVICE_GROUP_REQUEST_TOTAL.put.inc();\n\n Some(&NODE_SERVICE_GROUP_REQUEST_DURATION_SECONDS.put)\n\n }\n\n Some(Request::Delete(_)) => {\n\n NODE_SERVICE_GROUP_REQUEST_TOTAL.delete.inc();\n\n Some(&NODE_SERVICE_GROUP_REQUEST_DURATION_SECONDS.delete)\n\n }\n\n Some(Request::PrefixList(_)) => {\n\n NODE_SERVICE_GROUP_REQUEST_TOTAL.list.inc();\n\n Some(&NODE_SERVICE_GROUP_REQUEST_DURATION_SECONDS.list)\n\n }\n", "file_path": "src/server/src/service/metrics.rs", "rank": 44, "score": 128932.90599598223 }, { "content": "#[crate::async_trait]\n\npub trait AddressResolver: Send + Sync {\n\n async fn resolve(&self, node_id: u64) -> Result<NodeDesc>;\n\n}\n\n\n\n/// A logic connection between two nodes. A [`Channel`] is bind to a specific target,\n\n/// the name lookup are finished by internal machenism.\n\n#[derive(Clone)]\n\npub struct Channel {\n\n transport_mgr: ChannelManager,\n\n sender: Option<mpsc::UnboundedSender<RaftMessage>>,\n\n}\n\n\n\n/// Manage transports. This structure is used by all groups.\n\n///\n\n/// A transport is recycled by manager, if it exceeds the idle intervals.\n\n#[derive(Clone)]\n\npub struct ChannelManager\n\nwhere\n\n Self: Send + Sync,\n\n{\n", "file_path": "src/server/src/raftgroup/io/transport.rs", "rank": 45, "score": 127538.65934155614 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n std::env::set_var(\"PROTOC\", protoc_build::PROTOC);\n\n std::env::set_var(\"PROTOC_INCLUDE\", protoc_build::PROTOC_INCLUDE);\n\n\n\n tonic_build::configure().compile(\n\n &[\n\n \"engula/v1/engula.proto\",\n\n \"engula/server/v1/node.proto\",\n\n \"engula/server/v1/root.proto\",\n\n ],\n\n &[\".\"],\n\n )?;\n\n Ok(())\n\n}\n", "file_path": "src/api/build.rs", "rank": 46, "score": 126400.44535085285 }, { "content": "#[allow(dead_code)]\n\npub fn spawn<F>(future: F) -> tokio::task::JoinHandle<F::Output>\n\nwhere\n\n F: Future + Send + 'static,\n\n F::Output: Send + 'static,\n\n{\n\n tokio::spawn(future)\n\n}\n", "file_path": "src/server/tests/helper/runtime.rs", "rank": 47, "score": 122839.34546535651 }, { "content": "pub fn from_source(status: tonic::Status) -> Error {\n\n if retryable_rpc_err(&status) {\n\n Error::Connect(status)\n\n } else if transport_err(&status) {\n\n Error::Transport(status)\n\n } else {\n\n Error::Rpc(status)\n\n }\n\n}\n", "file_path": "src/client/src/error.rs", "rank": 48, "score": 118087.42447463708 }, { "content": "pub fn from_source_or_details(status: tonic::Status) -> Error {\n\n use engula_api::server::v1;\n\n use prost::Message;\n\n\n\n if !status.details().is_empty() {\n\n if let Ok(err) = v1::Error::decode(status.details()) {\n\n return err.into();\n\n }\n\n }\n\n\n\n from_source(status)\n\n}\n\n\n", "file_path": "src/client/src/error.rs", "rank": 49, "score": 116042.97703164033 }, { "content": "pub fn transport_err(status: &tonic::Status) -> bool {\n\n // Cases:\n\n // - transport error: <inner messages>: connection reset\n\n // - transport error: <inner messages>: broken pipe\n\n // - error trying to connect: tcp connect error: Connection reset by peer (os error 104)\n\n // - error reading a body from connection: connection reset\n\n let mut cause = status.source();\n\n while let Some(err) = cause {\n\n if let Some(err) = err.downcast_ref::<std::io::Error>() {\n\n return transport_io_err(err);\n\n }\n\n cause = err.source();\n\n }\n\n false\n\n}\n\n\n", "file_path": "src/client/src/error.rs", "rank": 50, "score": 116042.97703164033 }, { "content": "/// Return the slot of the corresponding shard. `None` is returned if shard is range partition.\n\npub fn slot(shard: &ShardDesc) -> Option<u32> {\n\n match shard.partition.as_ref().unwrap() {\n\n Partition::Hash(hash) => Some(hash.slot_id),\n\n Partition::Range(_) => None,\n\n }\n\n}\n", "file_path": "src/api/src/shard.rs", "rank": 51, "score": 116042.97703164033 }, { "content": "#[inline]\n\npub fn start_key(shard: &ShardDesc) -> Vec<u8> {\n\n match shard.partition.as_ref().unwrap() {\n\n Partition::Hash(hash) => hash.slot_id.to_le_bytes().as_slice().to_owned(),\n\n Partition::Range(RangePartition { start, .. }) => start.as_slice().to_owned(),\n\n }\n\n}\n\n\n\n/// Return the end key of the corresponding shard.\n", "file_path": "src/api/src/shard.rs", "rank": 52, "score": 114105.25451438065 }, { "content": "pub fn retryable_rpc_err(status: &tonic::Status) -> bool {\n\n use tonic::Code;\n\n if status.code() == Code::Unavailable\n\n && status\n\n .message()\n\n .contains(\"error trying to connect: deadline has elapsed\")\n\n {\n\n // connection timeout.\n\n true\n\n } else {\n\n let mut cause = status.source();\n\n while let Some(err) = cause {\n\n if let Some(err) = err.downcast_ref::<std::io::Error>() {\n\n return retryable_io_err(err);\n\n } else if err\n\n .to_string()\n\n .ends_with(\"operation was canceled: connection closed\")\n\n {\n\n // The request is dropped in an internal queue, which is guaranteed to have not been\n\n // sent to the server. See https://github.com/hyperium/hyper/blob/bb3af17ce1a3841e9170adabcce595c7c8743ea7/src/client/dispatch.rs#L209 for details.\n\n return true;\n\n }\n\n cause = err.source();\n\n }\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/client/src/error.rs", "rank": 53, "score": 114105.25451438065 }, { "content": "#[inline]\n\npub fn end_key(shard: &ShardDesc) -> Vec<u8> {\n\n match shard.partition.as_ref().unwrap() {\n\n Partition::Hash(hash) => (hash.slot_id + 1).to_le_bytes().as_slice().to_owned(),\n\n Partition::Range(RangePartition { end, .. }) => end.as_slice().to_owned(),\n\n }\n\n}\n\n\n", "file_path": "src/api/src/shard.rs", "rank": 54, "score": 114105.25451438065 }, { "content": "/// Return whether a key belongs to the corresponding shard.\n\npub fn belong_to(shard: &ShardDesc, key: &[u8]) -> bool {\n\n match shard.partition.as_ref().unwrap() {\n\n Partition::Hash(hash) => hash.slot_id == key_slot(key, hash.slots),\n\n Partition::Range(RangePartition { start, end }) => in_range(start, end, key),\n\n }\n\n}\n\n\n\n/// Return the start key of the corresponding shard.\n", "file_path": "src/api/src/shard.rs", "rank": 55, "score": 111543.73168035783 }, { "content": "#[inline]\n\npub fn key_slot(key: &[u8], slots: u32) -> u32 {\n\n // TODO: it's temp hash impl..\n\n crc32fast::hash(key) % slots\n\n}\n\n\n", "file_path": "src/api/src/shard.rs", "rank": 56, "score": 111543.73168035783 }, { "content": "pub fn retryable_io_err(err: &std::io::Error) -> bool {\n\n use std::io::ErrorKind;\n\n\n\n matches!(err.kind(), ErrorKind::ConnectionRefused)\n\n}\n\n\n", "file_path": "src/client/src/error.rs", "rank": 57, "score": 109704.58973094437 }, { "content": "pub fn transport_io_err(err: &std::io::Error) -> bool {\n\n use std::io::ErrorKind;\n\n\n\n matches!(\n\n err.kind(),\n\n ErrorKind::ConnectionReset | ErrorKind::BrokenPipe\n\n )\n\n}\n\n\n", "file_path": "src/client/src/error.rs", "rank": 58, "score": 109704.58973094437 }, { "content": "#[test]\n\nfn single_node_server() {\n\n let mut ctx = TestContext::new(\"rw_test__single_node_server\");\n\n let node_1_addr = ctx.next_listen_address();\n\n ctx.spawn_server(1, &node_1_addr, true, vec![]);\n\n\n\n block_on_current(async {\n\n node_client_with_retry(&node_1_addr).await;\n\n\n\n let addrs = vec![node_1_addr];\n\n let client = EngulaClient::new(ClientOptions::default(), addrs)\n\n .await\n\n .unwrap();\n\n let db = client.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Hash { slots: 3 }))\n\n .await\n\n .unwrap();\n\n\n\n let k = \"book_name\".as_bytes().to_vec();\n\n let v = \"rust_in_actions\".as_bytes().to_vec();\n\n co.put(k.clone(), v).await.unwrap();\n\n let r = co.get(k).await.unwrap();\n\n let r = r.map(String::from_utf8);\n\n assert!(matches!(r, Some(Ok(v)) if v == \"rust_in_actions\"));\n\n });\n\n}\n\n\n", "file_path": "src/server/tests/rw_test.rs", "rank": 59, "score": 108152.81162318663 }, { "content": "fn apply_leave_joint(local_id: u64, desc: &mut GroupDesc) {\n\n let group_id = desc.id;\n\n for replica in &mut desc.replicas {\n\n let role = match ReplicaRole::from_i32(replica.role) {\n\n Some(ReplicaRole::IncomingVoter) => ReplicaRole::Voter,\n\n Some(ReplicaRole::DemotingVoter) => ReplicaRole::Learner,\n\n _ => continue,\n\n };\n\n replica.role = role as i32;\n\n }\n\n\n\n info!(\n\n \"group {group_id} replica {local_id} leave joint with {}\",\n\n group_role_digest(desc)\n\n );\n\n}\n\n\n", "file_path": "src/server/src/node/replica/fsm/mod.rs", "rank": 60, "score": 107457.77883207049 }, { "content": "enum TaskState {\n\n First(Instant),\n\n Polled(Duration),\n\n}\n\n\n", "file_path": "src/server/src/runtime/executor.rs", "rank": 61, "score": 106706.84082263752 }, { "content": "enum SnapshotRange {\n\n Target {\n\n target_key: Vec<u8>,\n\n },\n\n Prefix {\n\n prefix: Vec<u8>,\n\n },\n\n Range {\n\n start: Vec<u8>,\n\n end: Vec<u8>,\n\n },\n\n #[allow(dead_code)]\n\n HashRange {\n\n slot: u32,\n\n start: Vec<u8>,\n\n },\n\n}\n\n\n\npub(crate) struct Snapshot<'a> {\n\n collection_id: u64,\n", "file_path": "src/server/src/engine/group.rs", "rank": 62, "score": 106706.84082263752 }, { "content": "pub fn in_range(start: &[u8], end: &[u8], key: &[u8]) -> bool {\n\n start <= key && (key < end || end.is_empty())\n\n}\n\n\n", "file_path": "src/api/src/shard.rs", "rank": 63, "score": 105420.47075526428 }, { "content": "#[derive(PartialEq, Eq, Debug)]\n\nenum BalanceStatus {\n\n Overfull,\n\n Balanced,\n\n Underfull,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Allocator<T: AllocSource> {\n\n alloc_source: Arc<T>,\n\n ongoing_stats: Arc<OngoingStats>,\n\n config: RootConfig,\n\n}\n\n\n\nimpl<T: AllocSource> Allocator<T> {\n\n pub fn new(alloc_source: Arc<T>, ongoing_stats: Arc<OngoingStats>, config: RootConfig) -> Self {\n\n Self {\n\n alloc_source,\n\n config,\n\n ongoing_stats,\n\n }\n", "file_path": "src/server/src/root/allocator/mod.rs", "rank": 64, "score": 104589.8304486609 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nenum ActionStage {\n\n Next(usize),\n\n Doing(usize),\n\n}\n\n\n\npub struct ActionTask {\n\n task_id: u64,\n\n stage: ActionStage,\n\n actions: Vec<Box<dyn Action>>,\n\n}\n\n\n\nimpl ActionTask {\n\n pub fn new(task_id: u64, actions: Vec<Box<dyn Action>>) -> Self {\n\n ActionTask {\n\n task_id,\n\n stage: ActionStage::Next(0),\n\n actions,\n\n }\n\n }\n\n}\n", "file_path": "src/server/src/schedule/tasks/action.rs", "rank": 65, "score": 104589.8304486609 }, { "content": "#[test]\n\n#[ignore]\n\nfn single_server_large_read_write() {\n\n fn next_bytes(rng: &mut SmallRng, range: std::ops::Range<usize>) -> Vec<u8> {\n\n const BYTES: &[u8; 62] = b\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n\n let len = rng.gen_range(range);\n\n let mut buf = vec![0u8; len];\n\n rng.fill(buf.as_mut_slice());\n\n buf.iter_mut().for_each(|v| *v = BYTES[(*v % 62) as usize]);\n\n buf\n\n }\n\n\n\n block_on_current(async move {\n\n let mut ctx = TestContext::new(\"rw_test__single_server_large_read_write\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(1).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let app = c.app_client().await;\n\n\n\n let db = app.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Range {}))\n", "file_path": "src/server/tests/rw_test.rs", "rank": 66, "score": 104531.71157403984 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n\nasync fn create_group(c: &ClusterClient, group_id: u64, nodes: Vec<u64>) {\n\n let replicas = nodes\n\n .iter()\n\n .cloned()\n\n .map(|node_id| {\n\n let replica_id = group_id * 10 + node_id;\n\n ReplicaDesc {\n\n id: replica_id,\n\n node_id,\n\n role: ReplicaRole::Voter as i32,\n\n }\n\n })\n\n .collect::<Vec<_>>();\n\n let group_desc = GroupDesc {\n\n id: group_id,\n\n shards: vec![],\n\n replicas: replicas.clone(),\n\n ..Default::default()\n\n };\n\n for replica in replicas {\n\n c.create_replica(replica.node_id, replica.id, group_desc.clone())\n\n .await;\n\n }\n\n}\n\n\n", "file_path": "src/server/tests/group_test.rs", "rank": 67, "score": 103695.2530708044 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n", "file_path": "src/server/tests/rw_test.rs", "rank": 68, "score": 103695.2530708044 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n", "file_path": "src/server/tests/bootstrap_test.rs", "rank": 69, "score": 103695.2530708044 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n\nasync fn is_not_in_migration(c: &ClusterClient, dest_group_id: u64) -> bool {\n\n use collect_migration_state_response::State;\n\n if let Some(leader_node_id) = c.get_group_leader_node_id(dest_group_id).await {\n\n debug!(\"group {dest_group_id} node {leader_node_id} collect migration state\",);\n\n if let Ok(resp) = c\n\n .collect_migration_state(dest_group_id, leader_node_id)\n\n .await\n\n {\n\n debug!(\n\n \"group {dest_group_id} node {leader_node_id} collect migration state: {:?}\",\n\n resp.state\n\n );\n\n if resp.state == State::None as i32 {\n\n // migration is finished or aborted.\n\n return true;\n", "file_path": "src/server/tests/migration_test.rs", "rank": 70, "score": 103695.2530708044 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n", "file_path": "src/server/tests/admin_test.rs", "rank": 71, "score": 103695.2530708044 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n\nasync fn create_group(c: &ClusterClient, group_id: u64, nodes: Vec<u64>, shards: Vec<ShardDesc>) {\n\n let replicas = nodes\n\n .iter()\n\n .cloned()\n\n .map(|node_id| {\n\n let replica_id = group_id * 10 + node_id;\n\n ReplicaDesc {\n\n id: replica_id,\n\n node_id,\n\n role: ReplicaRole::Voter as i32,\n\n }\n\n })\n\n .collect::<Vec<_>>();\n\n let group_desc = GroupDesc {\n\n id: group_id,\n", "file_path": "src/server/tests/snapshot_test.rs", "rank": 72, "score": 103695.2530708044 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n", "file_path": "src/server/tests/client_test.rs", "rank": 73, "score": 103695.2530708044 }, { "content": "pub fn find_io_error(status: &tonic::Status) -> Option<&std::io::Error> {\n\n use tonic::Code;\n\n if status.code() == Code::Unavailable || status.code() == Code::Unknown {\n\n find_source::<std::io::Error>(status)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/client/src/error.rs", "rank": 74, "score": 102009.29393747415 }, { "content": "#[test]\n\nfn admin_basic() {\n\n block_on_current(async {\n\n let node_count = 4;\n\n let mut ctx = TestContext::new(\"db-col-mng-3\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(node_count).await;\n\n let addrs = nodes.values().cloned().collect::<Vec<_>>();\n\n\n\n let c = EngulaClient::new(ClientOptions::default(), addrs.to_owned())\n\n .await\n\n .unwrap();\n\n let sys_db = c.open_database(\"__system__\".to_owned()).await.unwrap();\n\n let sys_db_col = sys_db.open_collection(\"database\".to_owned()).await.unwrap();\n\n let sys_col_col = sys_db\n\n .open_collection(\"collection\".to_owned())\n\n .await\n\n .unwrap();\n\n\n\n // test create database.\n\n let new_db_name = \"db1\".to_owned();\n", "file_path": "src/server/tests/admin_test.rs", "rank": 75, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn admin_delete() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"db-col-mng-2\");\n\n ctx.mut_replica_testing_knobs()\n\n .disable_scheduler_orphan_replica_detecting_intervals = true;\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(1).await;\n\n let addrs = nodes.values().cloned().collect::<Vec<_>>();\n\n let c = EngulaClient::new(ClientOptions::default(), addrs.to_owned())\n\n .await\n\n .unwrap();\n\n {\n\n let db = c.create_database(\"test1\".into()).await.unwrap();\n\n let c1 = db\n\n .create_collection(\"test_co1\".into(), Some(Partition::Hash { slots: 1 }))\n\n .await\n\n .unwrap();\n\n c1.put(\"k1\".into(), \"v1\".into()).await.unwrap();\n\n db.delete_collection(\"test_co1\".into()).await.unwrap();\n\n assert!(db.open_collection(\"test_co1\".into()).await.is_err());\n", "file_path": "src/server/tests/admin_test.rs", "rank": 76, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn basic_migration() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"basic-migration\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let node_ids = nodes.keys().cloned().collect::<Vec<_>>();\n\n let c = ClusterClient::new(nodes).await;\n\n let (group_id_1, group_id_2, shard_desc) = create_two_groups(&c, node_ids, 1000).await;\n\n let shard_id = shard_desc.id;\n\n\n\n info!(\n\n \"issue accept shard {} request to group {}\",\n\n shard_id, group_id_2\n\n );\n\n\n\n move_shard(&c, &shard_desc, group_id_2, group_id_1).await;\n\n });\n\n}\n\n\n", "file_path": "src/server/tests/migration_test.rs", "rank": 77, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn add_replica() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"add-replica\");\n\n ctx.disable_all_balance();\n\n ctx.disable_all_node_scheduler();\n\n let nodes = ctx.bootstrap_servers(2).await;\n\n let c = ClusterClient::new(nodes).await;\n\n\n\n let group_id = 0;\n\n let new_replica_id = 123;\n\n\n\n let root_group = GroupDesc {\n\n id: group_id,\n\n ..Default::default()\n\n };\n\n\n\n info!(\"create new replica {new_replica_id} of group {group_id}\");\n\n\n\n // 1. create replica firstly\n\n c.create_replica(1, new_replica_id, root_group).await;\n", "file_path": "src/server/tests/group_test.rs", "rank": 78, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn move_replica() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"group-test--move-replica\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(4).await;\n\n let c = ClusterClient::new(nodes.clone()).await;\n\n let group_id = 10;\n\n let mut node_id_list = nodes.keys().cloned().collect::<Vec<_>>();\n\n let node_id = node_id_list.pop().unwrap();\n\n create_group(&c, group_id, node_id_list).await;\n\n\n\n info!(\"issue moving replicas request\");\n\n c.assert_group_leader(group_id).await;\n\n let follower = c.must_group_any_follower(group_id).await;\n\n let follower_id = follower.id;\n\n let mut group = c.group(group_id);\n\n group\n\n .move_replicas(\n\n vec![ReplicaDesc {\n\n id: 123123,\n", "file_path": "src/server/tests/group_test.rs", "rank": 79, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn cure_group() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"cure-group\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(4).await;\n\n let c = ClusterClient::new(nodes).await;\n\n\n\n let group_id = 100000000;\n\n let group_desc = GroupDesc {\n\n id: group_id,\n\n replicas: vec![\n\n ReplicaDesc {\n\n id: 100,\n\n node_id: 0,\n\n role: ReplicaRole::Voter as i32,\n\n },\n\n ReplicaDesc {\n\n id: 101,\n\n node_id: 1,\n\n role: ReplicaRole::Voter as i32,\n", "file_path": "src/server/tests/group_test.rs", "rank": 80, "score": 101460.86278728674 }, { "content": "#[ctor::ctor]\n\nfn init() {\n\n setup_panic_hook();\n\n tracing_subscriber::fmt::init();\n\n}\n\n\n\nasync fn create_group(c: &ClusterClient, group_id: u64, nodes: Vec<u64>, learners: Vec<u64>) {\n\n let learners = learners.into_iter().collect::<HashSet<_>>();\n\n let replicas = nodes\n\n .iter()\n\n .cloned()\n\n .map(|node_id| {\n\n let replica_id = group_id * 10 + node_id;\n\n ReplicaDesc {\n\n id: replica_id,\n\n node_id,\n\n role: if learners.contains(&node_id) {\n\n ReplicaRole::Learner as i32\n\n } else {\n\n ReplicaRole::Voter as i32\n\n },\n", "file_path": "src/server/tests/node_schedule_test.rs", "rank": 81, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn send_snapshot() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"snapshot_test__send_snapshot\");\n\n ctx.disable_all_balance();\n\n ctx.mut_raft_testing_knobs()\n\n .force_new_peer_receiving_snapshot = true;\n\n let nodes = ctx.bootstrap_servers(4).await;\n\n let c = ClusterClient::new(nodes.clone()).await;\n\n\n\n let mut node_ids = nodes.keys().cloned().collect::<Vec<_>>();\n\n let left_node_id = node_ids.pop().unwrap();\n\n\n\n let group_id = 123;\n\n let shard_id = 234;\n\n let shard_desc = ShardDesc {\n\n id: shard_id,\n\n collection_id: shard_id,\n\n partition: Some(shard_desc::Partition::Range(\n\n shard_desc::RangePartition::default(),\n\n )),\n", "file_path": "src/server/tests/snapshot_test.rs", "rank": 82, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn to_unreachable_peers() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"client_test__to_unreachable_peers\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let opts = ClientOptions {\n\n connect_timeout: Some(Duration::from_millis(50)),\n\n timeout: Some(Duration::from_millis(200)),\n\n };\n\n let client = c.app_client_with_options(opts).await;\n\n let db = client.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Hash { slots: 3 }))\n\n .await\n\n .unwrap();\n\n c.assert_collection_ready(&co.desc()).await;\n\n\n\n let k = \"key\".as_bytes().to_vec();\n\n let v = \"value\".as_bytes().to_vec();\n", "file_path": "src/server/tests/client_test.rs", "rank": 83, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn abort_migration() {\n\n block_on_current(async move {\n\n let mut ctx = TestContext::new(\"abort-migration\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let node_ids = nodes.keys().cloned().collect::<Vec<_>>();\n\n let c = ClusterClient::new(nodes).await;\n\n let (group_id_1, group_id_2, shard_desc) = create_two_groups(&c, node_ids, 0).await;\n\n let shard_id = shard_desc.id;\n\n\n\n info!(\n\n \"issue accept shard {} request to group {}\",\n\n shard_id, group_id_2\n\n );\n\n\n\n let src_epoch = c.must_group_epoch(group_id_1).await;\n\n c.group(group_id_1)\n\n .add_learner(123123, 1231231231)\n\n .await\n\n .unwrap();\n", "file_path": "src/server/tests/migration_test.rs", "rank": 84, "score": 101460.86278728674 }, { "content": "#[test]\n\nfn restart_cluster() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"bootstrap_test__restart_cluster\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n\n\n // Shutdown and restart servers.\n\n ctx.shutdown();\n\n\n\n let nodes = ctx.start_servers(nodes).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let app = c.app_client().await;\n\n app.create_database(\"db\".into()).await.unwrap();\n\n });\n\n}\n", "file_path": "src/server/tests/bootstrap_test.rs", "rank": 85, "score": 101460.86278728674 }, { "content": "enum TransferDescision {\n\n TransferOnly {\n\n group: u64,\n\n src_replica: u64,\n\n target_replica: u64,\n\n src_node: u64,\n\n target_node: u64,\n\n },\n\n // TODO: add create then transfer option?\n\n}\n\n\n\nimpl<T: AllocSource> LeaderCountPolicy<T> {\n\n pub fn with(alloc_source: Arc<T>) -> Self {\n\n Self { alloc_source }\n\n }\n\n\n\n pub fn compute_balance(&self) -> Result<LeaderAction> {\n\n let mean = self.mean_leader_count(NodeFilter::Schedulable);\n\n let candidate_nodes = self.alloc_source.nodes(NodeFilter::Schedulable);\n\n let ranked_nodes = Self::rank_nodes_for_leader(candidate_nodes, mean);\n", "file_path": "src/server/src/root/allocator/policy_leader_cnt.rs", "rank": 86, "score": 100705.60866253245 }, { "content": "#[derive(Debug)]\n\nenum ChangeReplicaKind {\n\n Simple,\n\n EnterJoint,\n\n LeaveJoint,\n\n}\n\n\n", "file_path": "src/server/src/node/replica/fsm/mod.rs", "rank": 87, "score": 100705.60866253245 }, { "content": "enum MetaAclGuard<'a> {\n\n Read(tokio::sync::RwLockReadGuard<'a, ()>),\n\n Write(tokio::sync::RwLockWriteGuard<'a, ()>),\n\n}\n\n\n\n/// ExecCtx contains the required infos during request execution.\n\n#[derive(Default, Clone)]\n\npub struct ExecCtx {\n\n pub group_id: u64,\n\n pub replica_id: u64,\n\n\n\n /// This is a forward request and here is the migrating shard.\n\n pub forward_shard_id: Option<u64>,\n\n /// The epoch of `GroupDesc` carried in this request.\n\n pub epoch: u64,\n\n\n\n /// The migration desc, filled by `check_request_early`.\n\n migration_desc: Option<MigrationDesc>,\n\n}\n\n\n", "file_path": "src/server/src/node/replica/mod.rs", "rank": 88, "score": 99583.26951679503 }, { "content": "fn apply_simple_change(local_id: u64, desc: &mut GroupDesc, change: &ChangeReplica) {\n\n let group_id = desc.id;\n\n let replica_id = change.replica_id;\n\n let node_id = change.node_id;\n\n let exist = find_replica_mut(desc, replica_id);\n\n check_not_in_joint_state(&exist);\n\n match ChangeReplicaType::from_i32(change.change_type) {\n\n Some(ChangeReplicaType::Add) => {\n\n info!(\"group {group_id} replica {local_id} add voter {replica_id}\");\n\n if let Some(replica) = exist {\n\n replica.role = ReplicaRole::Voter.into();\n\n } else {\n\n desc.replicas.push(ReplicaDesc {\n\n id: replica_id,\n\n node_id,\n\n role: ReplicaRole::Voter.into(),\n\n });\n\n }\n\n }\n\n Some(ChangeReplicaType::AddLearner) => {\n", "file_path": "src/server/src/node/replica/fsm/mod.rs", "rank": 89, "score": 99497.63103342369 }, { "content": "fn apply_enter_joint(local_id: u64, desc: &mut GroupDesc, changes: &[ChangeReplica]) {\n\n let group_id = desc.id;\n\n let roles = group_role_digest(desc);\n\n let mut outgoing_learners = HashSet::new();\n\n for change in changes {\n\n let replica_id = change.replica_id;\n\n let node_id = change.node_id;\n\n let exist = find_replica_mut(desc, replica_id);\n\n check_not_in_joint_state(&exist);\n\n let exist_role = exist.as_ref().and_then(|r| ReplicaRole::from_i32(r.role));\n\n let change = ChangeReplicaType::from_i32(change.change_type)\n\n .expect(\"such change replica operation isn't supported\");\n\n\n\n match (exist_role, change) {\n\n (Some(ReplicaRole::Learner), ChangeReplicaType::Add) => {\n\n exist.unwrap().role = ReplicaRole::IncomingVoter as i32;\n\n }\n\n (Some(ReplicaRole::Voter), ChangeReplicaType::AddLearner) => {\n\n exist.unwrap().role = ReplicaRole::DemotingVoter as i32;\n\n }\n", "file_path": "src/server/src/node/replica/fsm/mod.rs", "rank": 90, "score": 99497.63103342369 }, { "content": "#[test]\n\nfn cure_group() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"node-schedule-test--cure-group\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(4).await;\n\n let c = ClusterClient::new(nodes.clone()).await;\n\n\n\n let group_id = 10;\n\n let mut node_id_list = nodes.keys().cloned().collect::<Vec<_>>();\n\n node_id_list.pop();\n\n let offline_node_id = node_id_list.last().cloned().unwrap();\n\n\n\n info!(\"create new group {group_id}\");\n\n create_group(&c, group_id, node_id_list, vec![]).await;\n\n c.assert_group_leader(group_id).await;\n\n c.assert_root_group_has_promoted().await;\n\n\n\n info!(\"stop server {offline_node_id}\");\n\n c.assert_root_group_has_promoted().await;\n\n ctx.stop_server(offline_node_id).await;\n\n ctx.wait_election_timeout().await;\n\n c.assert_group_leader(group_id).await;\n\n\n\n info!(\"cure group by replace offline voters with new replicas\");\n\n ctx.wait_election_timeout().await;\n\n c.assert_group_not_contains_node(group_id, offline_node_id)\n\n .await;\n\n });\n\n}\n", "file_path": "src/server/tests/node_schedule_test.rs", "rank": 91, "score": 99356.71032504206 }, { "content": "#[test]\n\nfn single_replica_migration() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"single-replica-migration\");\n\n ctx.disable_all_balance();\n\n ctx.disable_all_node_scheduler();\n\n let nodes = ctx.bootstrap_servers(2).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let node_1_id = 0;\n\n let node_2_id = 1;\n\n let group_id_1 = 100000;\n\n let group_id_2 = 100001;\n\n let replica_1 = 1000000;\n\n let replica_2 = 2000000;\n\n let shard_id = 10000000;\n\n\n\n info!(\n\n \"create group {} at node {} with replica {} and shard {}\",\n\n group_id_1, node_1_id, replica_1, shard_id,\n\n );\n\n\n", "file_path": "src/server/tests/migration_test.rs", "rank": 92, "score": 99356.71032504206 }, { "content": "#[test]\n\nfn migration_with_offline_peers() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"migration-with-offline-peers\");\n\n ctx.disable_all_balance();\n\n ctx.disable_all_node_scheduler();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let mut node_ids = nodes.keys().cloned().collect::<Vec<_>>();\n\n node_ids.sort_unstable();\n\n let c = ClusterClient::new(nodes).await;\n\n let (group_id_1, group_id_2, shard_desc) = create_two_groups(&c, node_ids.clone(), 0).await;\n\n let shard_id = shard_desc.id;\n\n\n\n info!(\n\n \"issue accept shard {} request to group {}\",\n\n shard_id, group_id_2\n\n );\n\n\n\n c.assert_root_group_has_promoted().await;\n\n ctx.stop_server(*node_ids.last().unwrap()).await;\n\n ctx.wait_election_timeout().await;\n\n\n\n move_shard(&c, &shard_desc, group_id_2, group_id_1).await;\n\n });\n\n}\n\n\n", "file_path": "src/server/tests/migration_test.rs", "rank": 93, "score": 99356.71032504206 }, { "content": "#[test]\n\nfn balance_init_cluster() {\n\n block_on_current(async {\n\n let node_count = 4;\n\n let mut ctx = TestContext::new(\"db-col-mng-1\");\n\n ctx.disable_all_balance();\n\n let start = tokio::time::Instant::now();\n\n let nodes = ctx.bootstrap_servers(node_count).await;\n\n let addrs = nodes.values().cloned().collect::<Vec<_>>();\n\n tokio::time::sleep(Duration::from_secs(10)).await;\n\n\n\n loop {\n\n let m = curr_metadata(addrs.to_owned()).await;\n\n if m.balanced {\n\n break;\n\n }\n\n tokio::time::sleep(Duration::from_secs(1)).await;\n\n }\n\n\n\n let m = curr_metadata(addrs.to_owned()).await;\n\n let stats = m\n", "file_path": "src/server/tests/admin_test.rs", "rank": 94, "score": 99356.71032504206 }, { "content": "#[test]\n\nfn request_to_offline_leader() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"client_test__request_to_offline_leader\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let client = c.app_client().await;\n\n let db = client.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Hash { slots: 3 }))\n\n .await\n\n .unwrap();\n\n\n\n c.assert_collection_ready(&co.desc()).await;\n\n c.assert_root_group_has_promoted().await;\n\n\n\n for i in 0..1000 {\n\n let k = format!(\"key-{i}\").as_bytes().to_vec();\n\n let v = format!(\"value-{i}\").as_bytes().to_vec();\n\n match co.put(k.clone(), v).await {\n", "file_path": "src/server/tests/client_test.rs", "rank": 95, "score": 99356.71032504206 }, { "content": "#[test]\n\nfn cluster_put_and_get() {\n\n block_on_current(async {\n\n let mut ctx = TestContext::new(\"rw_test__cluster_put_and_get\");\n\n ctx.disable_all_balance();\n\n let nodes = ctx.bootstrap_servers(3).await;\n\n let c = ClusterClient::new(nodes).await;\n\n let app = c.app_client().await;\n\n\n\n let db = app.create_database(\"test_db\".to_string()).await.unwrap();\n\n let co = db\n\n .create_collection(\"test_co\".to_string(), Some(Partition::Hash { slots: 3 }))\n\n .await\n\n .unwrap();\n\n c.assert_collection_ready(&co.desc()).await;\n\n\n\n let k = \"book_name\".as_bytes().to_vec();\n\n let v = \"rust_in_actions\".as_bytes().to_vec();\n\n co.put(k.clone(), v).await.unwrap();\n\n let r = co.get(k).await.unwrap();\n\n let r = r.map(String::from_utf8);\n\n assert!(matches!(r, Some(Ok(v)) if v == \"rust_in_actions\"));\n\n });\n\n}\n\n\n", "file_path": "src/server/tests/rw_test.rs", "rank": 96, "score": 99356.71032504206 }, { "content": "#[crate::async_trait]\n\npub trait AllocSource {\n\n async fn refresh_all(&self) -> Result<()>;\n\n\n\n fn nodes(&self, filter: NodeFilter) -> Vec<NodeDesc>;\n\n\n\n fn groups(&self) -> HashMap<u64, GroupDesc>;\n\n\n\n fn node_replicas(&self, node_id: &u64) -> Vec<(ReplicaDesc, u64)>;\n\n\n\n fn replica_state(&self, replica_id: &u64) -> Option<ReplicaState>;\n\n\n\n fn replica_states(&self) -> Vec<ReplicaState>;\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct SysAllocSource {\n\n root: Arc<RootShared>,\n\n liveness: Arc<Liveness>,\n\n\n\n nodes: Arc<Mutex<Vec<NodeDesc>>>,\n\n groups: Arc<Mutex<GroupInfo>>,\n\n replicas: Arc<Mutex<ReplicaInfo>>,\n\n}\n\n\n", "file_path": "src/server/src/root/allocator/source.rs", "rank": 97, "score": 98290.18207751066 }, { "content": "#[crate::async_trait]\n\npub trait Task: Send {\n\n /// The unique id of the task.\n\n fn id(&self) -> u64;\n\n\n\n async fn poll(&mut self, ctx: &mut ScheduleContext<'_>) -> TaskState;\n\n}\n", "file_path": "src/server/src/schedule/task.rs", "rank": 98, "score": 97856.39384805073 }, { "content": "fn shard_chunk_stream(\n\n shard_id: u64,\n\n chunk_size: usize,\n\n mut last_key: Vec<u8>,\n\n replica: Arc<Replica>,\n\n) -> impl futures::Stream<Item = Result<ShardChunk, tonic::Status>> {\n\n async_stream::try_stream! {\n\n loop {\n\n match replica\n\n .fetch_shard_chunk(shard_id, &last_key, chunk_size)\n\n .await\n\n {\n\n Ok(shard_chunk) => {\n\n if shard_chunk.data.is_empty() {\n\n break;\n\n }\n\n\n\n last_key = shard_chunk.data.last().as_ref().unwrap().key.clone();\n\n yield shard_chunk;\n\n },\n\n Err(e) => {\n\n warn!(\"shard {shard_id} fetch shard chunk: {e:?}\");\n\n Err(e)?;\n\n unreachable!();\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/server/src/node/migrate/pull.rs", "rank": 99, "score": 97371.7312207495 } ]
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();\n\n}\n\n\n\n// Statically check that a type-erased middleware client is actually a valid Client.\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 0, "score": 409736.4939524224 }, { "content": "fn find_source<'a, E: Error + 'static>(err: &'a (dyn Error + 'static)) -> Option<&'a E> {\n\n let mut next = Some(err);\n\n while let Some(err) = next {\n\n if let Some(matching_err) = err.downcast_ref::<E>() {\n\n return Some(matching_err);\n\n }\n\n next = err.source();\n\n }\n\n None\n\n}\n\n\n\n#[derive(Default, Debug)]\n\n/// Builder for [`HyperAdapter`]\n\npub struct Builder {\n\n timeout: timeout::Settings,\n\n sleep: Option<Arc<dyn AsyncSleep>>,\n\n client_builder: hyper::client::Builder,\n\n}\n\n\n\nimpl Builder {\n", "file_path": "rust-runtime/aws-smithy-client/src/hyper_impls.rs", "rank": 1, "score": 408813.821246497 }, { "content": "type BoxError = Box<dyn Error + Send + Sync>;\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/middleware.rs", "rank": 2, "score": 405327.3963074114 }, { "content": "/// Convert a [`hyper::Error`] into a [`ConnectorError`]\n\nfn to_connector_error(err: hyper::Error) -> ConnectorError {\n\n if err.is_timeout() || find_source::<TimeoutError>(&err).is_some() {\n\n ConnectorError::timeout(err.into())\n\n } else if err.is_user() {\n\n ConnectorError::user(err.into())\n\n } else if err.is_closed() || err.is_canceled() || find_source::<std::io::Error>(&err).is_some()\n\n {\n\n ConnectorError::io(err.into())\n\n }\n\n // We sometimes receive this from S3: hyper::Error(IncompleteMessage)\n\n else if err.is_incomplete_message() {\n\n ConnectorError::other(err.into(), Some(ErrorKind::TransientError))\n\n } else {\n\n tracing::warn!(err = ?err, \"unrecognized error from Hyper. If this error should be retried, please file an issue.\");\n\n ConnectorError::other(err.into(), None)\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-client/src/hyper_impls.rs", "rank": 3, "score": 362849.76898785395 }, { "content": "type BoxError = Box<dyn Error + Send + Sync>;\n\n\n\n/// Successful SDK Result\n\n#[derive(Debug)]\n\npub struct SdkSuccess<O> {\n\n /// Raw Response from the service. (e.g. Http Response)\n\n pub raw: operation::Response,\n\n\n\n /// Parsed response from the service\n\n pub parsed: O,\n\n}\n\n\n\n/// Failed SDK Result\n\n#[derive(Debug)]\n\npub enum SdkError<E, R = operation::Response> {\n\n /// The request failed during construction. It was not dispatched over the network.\n\n ConstructionFailure(BoxError),\n\n\n\n /// The request failed during dispatch. An HTTP response was not received. The request MAY\n\n /// have been sent.\n", "file_path": "rust-runtime/aws-smithy-http/src/result.rs", "rank": 4, "score": 358283.5440137467 }, { "content": "fn noarg_is_send_sync<T: Send + Sync>() {}\n\n\n\n// Statically check that a fully type-erased client is still Send + Sync.\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 5, "score": 353972.9847554736 }, { "content": "fn is_send_sync<T: Send + Sync>(_: T) {}\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 6, "score": 342172.065208871 }, { "content": "fn check_send_sync<T: Send + Sync>(t: T) -> T {\n\n t\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::retry::{Config, NewRequestPolicy, RetryHandler, Standard};\n\n use aws_smithy_types::retry::ErrorKind;\n\n use std::time::Duration;\n\n\n\n fn assert_send_sync<T: Send + Sync>() {}\n\n\n\n fn test_config() -> Config {\n\n Config::default().with_base(|| 1_f64)\n\n }\n\n\n\n #[test]\n\n fn retry_handler_send_sync() {\n\n assert_send_sync::<RetryHandler>()\n\n }\n", "file_path": "rust-runtime/aws-smithy-client/src/retry.rs", "rank": 7, "score": 333864.64931818575 }, { "content": "fn assert_send_sync<T: Send + Sync + 'static>() {}\n", "file_path": "aws/sdk/integration-tests/kms/tests/sensitive-it.rs", "rank": 8, "score": 331027.76200801623 }, { "content": "type AnyMap = HashMap<TypeId, Box<dyn Any + Send + Sync>, BuildHasherDefault<IdHasher>>;\n\n\n\n// With TypeIds as keys, there's no need to hash them. They are already hashes\n\n// themselves, coming from the compiler. The IdHasher just holds the u64 of\n\n// the TypeId, and then returns it, instead of doing any bit fiddling.\n", "file_path": "rust-runtime/aws-smithy-http/src/property_bag.rs", "rank": 9, "score": 330203.90948716097 }, { "content": "pub trait ClassifyResponse<T, E>: Clone {\n\n fn classify(&self, response: Result<&T, &E>) -> RetryKind;\n\n}\n\n\n\nimpl<T, E> ClassifyResponse<T, E> for () {\n\n fn classify(&self, _: Result<&T, &E>) -> RetryKind {\n\n RetryKind::NotRetryable\n\n }\n\n}\n", "file_path": "rust-runtime/aws-smithy-http/src/retry.rs", "rank": 10, "score": 327076.38274305797 }, { "content": "/// Decode `input` from base64 using the standard base64 alphabet\n\n///\n\n/// If input is not a valid base64 encoded string, this function will return `DecodeError`.\n\npub fn decode<T: AsRef<str>>(input: T) -> Result<Vec<u8>, DecodeError> {\n\n decode_inner(input.as_ref())\n\n}\n\n\n\n/// Failure to decode a base64 value.\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\n#[non_exhaustive]\n\npub enum DecodeError {\n\n /// Encountered an invalid byte.\n\n InvalidByte,\n\n /// Encountered an invalid base64 padding value.\n\n InvalidPadding,\n\n /// Input wasn't long enough to be a valid base64 value.\n\n InvalidLength,\n\n}\n\n\n\nimpl Error for DecodeError {}\n\n\n\nimpl fmt::Display for DecodeError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n use DecodeError::*;\n\n match self {\n\n InvalidByte => write!(f, \"invalid byte\"),\n\n InvalidPadding => write!(f, \"invalid padding\"),\n\n InvalidLength => write!(f, \"invalid length\"),\n\n }\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-types/src/base64.rs", "rank": 11, "score": 323154.82808129635 }, { "content": "/// A Smithy middleware layer (i.e., factory).\n\n///\n\n/// This trait has a blanket implementation for all compatible types, and should never be\n\n/// implemented.\n\npub trait SmithyMiddleware<C>:\n\n Layer<\n\n aws_smithy_http_tower::dispatch::DispatchService<C>,\n\n Service = <Self as SmithyMiddleware<C>>::Service,\n\n>\n\n{\n\n /// Forwarding type to `<Self as Layer>::Service` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type Service: SmithyMiddlewareService + Send + Sync + Clone + 'static;\n\n}\n\n\n\nimpl<T, C> SmithyMiddleware<C> for T\n\nwhere\n\n T: Layer<aws_smithy_http_tower::dispatch::DispatchService<C>>,\n\n T::Service: SmithyMiddlewareService + Send + Sync + Clone + 'static,\n\n{\n\n type Service = T::Service;\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-client/src/bounds.rs", "rank": 12, "score": 314633.95266033366 }, { "content": "/// Encode `input` into base64 using the standard base64 alphabet\n\npub fn encode<T: AsRef<[u8]>>(input: T) -> String {\n\n encode_inner(input.as_ref())\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-types/src/base64.rs", "rank": 13, "score": 303509.06335227675 }, { "content": "/// A Smithy retry policy.\n\n///\n\n/// This trait has a blanket implementation for all compatible types, and should never be\n\n/// implemented.\n\npub trait SmithyRetryPolicy<O, T, E, Retry>:\n\n tower::retry::Policy<Operation<O, Retry>, SdkSuccess<T>, SdkError<E>> + Clone\n\n{\n\n /// Forwarding type to `O` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type O: ParseHttpResponse<Output = Result<T, Self::E>> + Send + Sync + Clone + 'static;\n\n /// Forwarding type to `E` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type E: Error;\n\n\n\n /// Forwarding type to `Retry` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type Retry: ClassifyResponse<SdkSuccess<T>, SdkError<Self::E>>;\n\n}\n\n\n\nimpl<R, O, T, E, Retry> SmithyRetryPolicy<O, T, E, Retry> for R\n\nwhere\n\n R: tower::retry::Policy<Operation<O, Retry>, SdkSuccess<T>, SdkError<E>> + Clone,\n\n O: ParseHttpResponse<Output = Result<T, E>> + Send + Sync + Clone + 'static,\n\n E: Error,\n\n Retry: ClassifyResponse<SdkSuccess<T>, SdkError<E>>,\n\n{\n\n type O = O;\n\n type E = E;\n\n type Retry = Retry;\n\n}\n", "file_path": "rust-runtime/aws-smithy-client/src/bounds.rs", "rank": 14, "score": 299229.82182944956 }, { "content": "#[allow(dead_code)]\n\nfn erased_is_send_sync() {\n\n noarg_is_send_sync::<crate::erase::DynConnector>();\n\n noarg_is_send_sync::<crate::erase::DynMiddleware<()>>();\n\n is_send_sync(\n\n Builder::new()\n\n .middleware(tower::layer::util::Identity::new())\n\n .connector_fn(|_| async { unreachable!() })\n\n .build()\n\n .into_dyn(),\n\n );\n\n}\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 16, "score": 284465.5944156966 }, { "content": "/// A Smithy middleware service that adjusts [`aws_smithy_http::operation::Request`]s.\n\n///\n\n/// This trait has a blanket implementation for all compatible types, and should never be\n\n/// implemented.\n\npub trait SmithyMiddlewareService:\n\n Service<\n\n aws_smithy_http::operation::Request,\n\n Response = aws_smithy_http::operation::Response,\n\n Error = aws_smithy_http_tower::SendOperationError,\n\n Future = <Self as SmithyMiddlewareService>::Future,\n\n>\n\n{\n\n /// Forwarding type to `<Self as Service>::Future` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type Future: Send + 'static;\n\n}\n\n\n\nimpl<T> SmithyMiddlewareService for T\n\nwhere\n\n T: Service<\n\n aws_smithy_http::operation::Request,\n\n Response = aws_smithy_http::operation::Response,\n\n Error = aws_smithy_http_tower::SendOperationError,\n\n >,\n\n T::Future: Send + 'static,\n\n{\n\n type Future = T::Future;\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-client/src/bounds.rs", "rank": 17, "score": 282800.14714995434 }, { "content": "/// Downcast errors coming out of hyper into an appropriate `ConnectorError`\n\nfn downcast_error(err: BoxError) -> ConnectorError {\n\n // is a `TimedOutError` (from aws_smithy_async::timeout) in the chain? if it is, this is a timeout\n\n if find_source::<TimedOutError>(err.as_ref()).is_some() {\n\n return ConnectorError::timeout(err);\n\n }\n\n // is the top of chain error actually already a `ConnectorError`? return that directly\n\n let err = match err.downcast::<ConnectorError>() {\n\n Ok(connector_error) => return *connector_error,\n\n Err(box_error) => box_error,\n\n };\n\n // generally, the top of chain will probably be a hyper error. Go through a set of hyper specific\n\n // error classifications\n\n let err = match err.downcast::<hyper::Error>() {\n\n Ok(hyper_error) => return to_connector_error(*hyper_error),\n\n Err(box_error) => box_error,\n\n };\n\n\n\n // otherwise, we have no idea!\n\n ConnectorError::other(err, None)\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-client/src/hyper_impls.rs", "rank": 18, "score": 279503.22303616535 }, { "content": "/// Asynchronous Credentials Provider\n\npub trait ProvideCredentials: Send + Sync + Debug {\n\n fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>\n\n where\n\n Self: 'a;\n\n}\n\n\n\nimpl ProvideCredentials for Credentials {\n\n fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>\n\n where\n\n Self: 'a,\n\n {\n\n future::ProvideCredentials::ready(Ok(self.clone()))\n\n }\n\n}\n\n\n\nimpl ProvideCredentials for Arc<dyn ProvideCredentials> {\n\n fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>\n\n where\n\n Self: 'a,\n\n {\n", "file_path": "aws/rust-runtime/aws-types/src/credentials/provider.rs", "rank": 19, "score": 276691.0508216169 }, { "content": "/// Provide a [`Region`](Region) to use with AWS requests\n\n///\n\n/// For most cases [`default_provider`](crate::default_provider::region::default_provider) will be the best option, implementing\n\n/// a standard provider chain.\n\npub trait ProvideRegion: Send + Sync + Debug {\n\n /// Load a region from this provider\n\n fn region(&self) -> future::ProvideRegion;\n\n}\n\n\n\nimpl ProvideRegion for Region {\n\n fn region(&self) -> future::ProvideRegion {\n\n future::ProvideRegion::ready(Some(self.clone()))\n\n }\n\n}\n\n\n\nimpl<'a> ProvideRegion for &'a Region {\n\n fn region(&self) -> future::ProvideRegion {\n\n future::ProvideRegion::ready(Some((*self).clone()))\n\n }\n\n}\n\n\n\nimpl ProvideRegion for Box<dyn ProvideRegion> {\n\n fn region(&self) -> future::ProvideRegion {\n\n self.as_ref().region()\n", "file_path": "aws/rust-runtime/aws-config/src/meta/region.rs", "rank": 20, "score": 276111.91064438084 }, { "content": "/// Async trait with a `sleep` function.\n\npub trait AsyncSleep: std::fmt::Debug + Send + Sync {\n\n /// Returns a future that sleeps for the given `duration` of time.\n\n fn sleep(&self, duration: Duration) -> Sleep;\n\n}\n\n\n\nimpl<T> AsyncSleep for Box<T>\n\nwhere\n\n T: AsyncSleep,\n\n T: ?Sized,\n\n{\n\n fn sleep(&self, duration: Duration) -> Sleep {\n\n T::sleep(self, duration)\n\n }\n\n}\n\n\n\nimpl<T> AsyncSleep for Arc<T>\n\nwhere\n\n T: AsyncSleep,\n\n T: ?Sized,\n\n{\n\n fn sleep(&self, duration: Duration) -> Sleep {\n\n T::sleep(self, duration)\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-async/src/rt/sleep.rs", "rank": 21, "score": 273826.54471796774 }, { "content": "#[allow(unused)]\n\npub fn is_error<B>(response: &http::Response<B>) -> bool {\n\n !response.status().is_success()\n\n}\n\n\n", "file_path": "rust-runtime/inlineable/src/json_errors.rs", "rank": 22, "score": 271984.0070534794 }, { "content": "/// RetryPartition represents a scope for cross request retry state\n\n///\n\n/// For example, a retry partition could be the id of a service. This would give each service a separate retry budget.\n\nstruct RetryPartition(Cow<'static, str>); */\n\n\n\n/// Shared state between multiple requests to the same client.\n", "file_path": "rust-runtime/aws-smithy-client/src/retry.rs", "rank": 23, "score": 269923.4362162091 }, { "content": "/// Connector which expects no traffic\n\npub fn no_traffic_connector() -> DynConnector {\n\n DynConnector::new(ReplayingConnection::new(vec![]))\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/test_case.rs", "rank": 24, "score": 268508.54388085974 }, { "content": "pub fn parse_generic_error(body: &[u8]) -> Result<aws_smithy_types::Error, XmlError> {\n\n let mut doc = Document::try_from(body)?;\n\n let mut root = doc.root_element()?;\n\n let mut err_builder = aws_smithy_types::Error::builder();\n\n while let Some(mut tag) = root.next_tag() {\n\n match tag.start_el().local() {\n\n \"Errors\" => {\n\n while let Some(mut error_tag) = tag.next_tag() {\n\n if let \"Error\" = error_tag.start_el().local() {\n\n while let Some(mut error_field) = error_tag.next_tag() {\n\n match error_field.start_el().local() {\n\n \"Code\" => {\n\n err_builder.code(try_data(&mut error_field)?);\n\n }\n\n \"Message\" => {\n\n err_builder.message(try_data(&mut error_field)?);\n\n }\n\n _ => {}\n\n }\n\n }\n", "file_path": "rust-runtime/inlineable/src/ec2_query_errors.rs", "rank": 25, "score": 267285.96599248017 }, { "content": "pub fn parse_generic_error(body: &[u8]) -> Result<aws_smithy_types::Error, XmlError> {\n\n let mut doc = Document::try_from(body)?;\n\n let mut root = doc.root_element()?;\n\n let mut err_builder = aws_smithy_types::Error::builder();\n\n while let Some(mut tag) = root.next_tag() {\n\n match tag.start_el().local() {\n\n \"Error\" => {\n\n while let Some(mut error_field) = tag.next_tag() {\n\n match error_field.start_el().local() {\n\n \"Code\" => {\n\n err_builder.code(try_data(&mut error_field)?);\n\n }\n\n \"Message\" => {\n\n err_builder.message(try_data(&mut error_field)?);\n\n }\n\n _ => {}\n\n }\n\n }\n\n }\n\n \"RequestId\" => {\n\n err_builder.request_id(try_data(&mut tag)?);\n\n }\n\n _ => {}\n\n }\n\n }\n\n Ok(err_builder.build())\n\n}\n\n\n", "file_path": "rust-runtime/inlineable/src/rest_xml_wrapped_errors.rs", "rank": 26, "score": 265111.3914616156 }, { "content": "pub fn parse_generic_error(body: &[u8]) -> Result<aws_smithy_types::Error, XmlError> {\n\n let mut doc = Document::try_from(body)?;\n\n let mut root = doc.root_element()?;\n\n let mut err = aws_smithy_types::Error::builder();\n\n while let Some(mut tag) = root.next_tag() {\n\n match tag.start_el().local() {\n\n \"Code\" => {\n\n err.code(try_data(&mut tag)?);\n\n }\n\n \"Message\" => {\n\n err.message(try_data(&mut tag)?);\n\n }\n\n \"RequestId\" => {\n\n err.request_id(try_data(&mut tag)?);\n\n }\n\n _ => {}\n\n }\n\n }\n\n Ok(err.build())\n\n}\n", "file_path": "rust-runtime/inlineable/src/rest_xml_unwrapped_errors.rs", "rank": 27, "score": 265111.3914616156 }, { "content": "/// Convert a `Result<T, E>` into an `SdkResult` that includes the operation response\n\nfn sdk_result<T, E>(\n\n parsed: Result<T, E>,\n\n raw: operation::Response,\n\n) -> Result<SdkSuccess<T>, SdkError<E>> {\n\n match parsed {\n\n Ok(parsed) => Ok(SdkSuccess { raw, parsed }),\n\n Err(err) => Err(SdkError::ServiceError { raw, err }),\n\n }\n\n}\n", "file_path": "rust-runtime/aws-smithy-http/src/middleware.rs", "rank": 28, "score": 263234.74138088303 }, { "content": "#[cfg(any(feature = \"native-tls\", feature = \"rustls\"))]\n\npub fn https() -> StandardClient {\n\n #[cfg(feature = \"rustls\")]\n\n let with_https = |b: Builder<_>| b.rustls();\n\n // If we are compiling this function & rustls is not enabled, then native-tls MUST be enabled\n\n #[cfg(not(feature = \"rustls\"))]\n\n let with_https = |b: Builder<_>| b.native_tls();\n\n\n\n with_https(aws_smithy_client::Builder::new())\n\n .build()\n\n .into_dyn_connector()\n\n}\n\n\n\nmod static_tests {\n\n #[cfg(any(feature = \"rustls\", feature = \"native-tls\"))]\n\n #[allow(dead_code)]\n\n fn construct_default_client() {\n\n let c = crate::Client::https();\n\n fn is_send_sync<T: Send + Sync>(_c: T) {}\n\n is_send_sync(c);\n\n }\n", "file_path": "aws/rust-runtime/aws-hyper/src/lib.rs", "rank": 29, "score": 262769.1328855149 }, { "content": "fn do_bench(config: &Config, input: &PutItemInput) {\n\n let operation = input\n\n .make_operation(&config)\n\n .now_or_never()\n\n .unwrap()\n\n .expect(\"operation failed to build\");\n\n let (http_request, _parts) = operation.into_request_response().0.into_parts();\n\n let body = http_request.body().bytes().unwrap();\n\n assert_eq!(body[0], b'{');\n\n}\n\n\n", "file_path": "aws/sdk/integration-tests/dynamodb/benches/serialization_bench.rs", "rank": 30, "score": 261985.74102943589 }, { "content": " #[async_trait]\n\n trait AnotherTrait: Send + Sync {\n\n async fn creds(&self) -> Credentials;\n\n }\n\n\n\n struct AnotherTraitWrapper<T> {\n\n inner: T,\n\n }\n\n\n\n impl<T> Debug for AnotherTraitWrapper<T> {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"wrapper\")\n\n }\n\n }\n\n\n\n impl<T: AnotherTrait> ProvideCredentials for AnotherTraitWrapper<T> {\n\n fn provide_credentials<'a>(&'a self) -> credentials::future::ProvideCredentials<'a>\n\n where\n\n Self: 'a,\n\n {\n\n credentials::future::ProvideCredentials::new(\n", "file_path": "aws/rust-runtime/aws-config/src/meta/credentials/credential_fn.rs", "rank": 31, "score": 255825.48710286425 }, { "content": "/// Returns a default sleep implementation based on the features enabled, or `None` if\n\n/// there isn't one available from this crate.\n\npub fn default_async_sleep() -> Option<Arc<dyn AsyncSleep>> {\n\n sleep_tokio()\n\n}\n\n\n\n/// Future returned by [`AsyncSleep`].\n\n#[non_exhaustive]\n\npub struct Sleep(Pin<Box<dyn Future<Output = ()> + Send + 'static>>);\n\n\n\nimpl Sleep {\n\n pub fn new(future: impl Future<Output = ()> + Send + 'static) -> Sleep {\n\n Sleep(Box::pin(future))\n\n }\n\n}\n\n\n\nimpl Future for Sleep {\n\n type Output = ();\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n self.0.as_mut().poll(cx)\n\n }\n", "file_path": "rust-runtime/aws-smithy-async/src/rt/sleep.rs", "rank": 32, "score": 252351.38847772585 }, { "content": "type BoxedResultFuture<T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send>>;\n\n\n\nimpl<S> Service<operation::Request> for DispatchService<S>\n\nwhere\n\n S: Service<http::Request<SdkBody>, Response = http::Response<SdkBody>> + Clone + Send + 'static,\n\n S::Error: Into<ConnectorError>,\n\n S::Future: Send + 'static,\n\n{\n\n type Response = operation::Response;\n\n type Error = SendOperationError;\n\n type Future = BoxedResultFuture<Self::Response, Self::Error>;\n\n\n\n fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {\n\n self.inner\n\n .poll_ready(cx)\n\n .map_err(|e| SendOperationError::RequestDispatchError(e.into()))\n\n }\n\n\n\n fn call(&mut self, req: operation::Request) -> Self::Future {\n\n let (req, property_bag) = req.into_parts();\n", "file_path": "rust-runtime/aws-smithy-http-tower/src/dispatch.rs", "rank": 33, "score": 251332.1462745046 }, { "content": "type BoxedResultFuture<T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send>>;\n\n\n\n/// ParseResponseService\n\n///\n\n/// Generic Parameter Listing:\n\n/// `S`: The inner service\n\n/// `O`: The type of the response parser whose output type is `Result<T, E>`\n\n/// `T`: The happy path return of the response parser\n\n/// `E`: The error path return of the response parser\n\n/// `R`: The type of the retry policy\n\nimpl<S, O, T, E, R> tower::Service<operation::Operation<O, R>> for ParseResponseService<S, O, R>\n\nwhere\n\n S: Service<operation::Request, Response = operation::Response, Error = SendOperationError>,\n\n S::Future: Send + 'static,\n\n O: ParseHttpResponse<Output = Result<T, E>> + Send + Sync + 'static,\n\n E: Error,\n\n{\n\n type Response = aws_smithy_http::result::SdkSuccess<T>;\n\n type Error = aws_smithy_http::result::SdkError<E>;\n\n type Future = BoxedResultFuture<Self::Response, Self::Error>;\n", "file_path": "rust-runtime/aws-smithy-http-tower/src/parse_response.rs", "rank": 34, "score": 249123.40930542717 }, { "content": "#[derive(Clone, Debug)]\n\nstruct HttpCredentialRetryPolicy;\n\n\n\nimpl ClassifyResponse<SdkSuccess<Credentials>, SdkError<CredentialsError>>\n\n for HttpCredentialRetryPolicy\n\n{\n\n fn classify(\n\n &self,\n\n response: Result<&SdkSuccess<credentials::Credentials>, &SdkError<CredentialsError>>,\n\n ) -> RetryKind {\n\n /* The following errors are retryable:\n\n * - Socket errors\n\n * - Networking timeouts\n\n * - 5xx errors\n\n * - Non-parseable 200 responses.\n\n * */\n\n match response {\n\n Ok(_) => RetryKind::NotRetryable,\n\n // socket errors, networking timeouts\n\n Err(SdkError::DispatchFailure(client_err))\n\n if client_err.is_timeout() || client_err.is_io() =>\n", "file_path": "aws/rust-runtime/aws-config/src/http_provider.rs", "rank": 35, "score": 244744.34053955384 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ImdsMiddleware {\n\n token_loader: TokenMiddleware,\n\n}\n\n\n\nimpl<S> tower::Layer<S> for ImdsMiddleware {\n\n type Service = AsyncMapRequestService<MapRequestService<S, UserAgentStage>, TokenMiddleware>;\n\n\n\n fn layer(&self, inner: S) -> Self::Service {\n\n AsyncMapRequestLayer::for_mapper(self.token_loader.clone())\n\n .layer(MapRequestLayer::for_mapper(UserAgentStage::new()).layer(inner))\n\n }\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/imds/client.rs", "rank": 36, "score": 239712.69181479275 }, { "content": "/// Resolve the AWS Endpoint for a given region\n\n///\n\n/// To provide a static endpoint, [`Endpoint`](aws_smithy_http::endpoint::Endpoint) implements this trait.\n\n/// Example usage:\n\n/// ```rust\n\n/// # mod dynamodb {\n\n/// # use aws_endpoint::ResolveAwsEndpoint;\n\n/// # pub struct ConfigBuilder;\n\n/// # impl ConfigBuilder {\n\n/// # pub fn endpoint(&mut self, resolver: impl ResolveAwsEndpoint + 'static) {\n\n/// # // ...\n\n/// # }\n\n/// # }\n\n/// # pub struct Config;\n\n/// # impl Config {\n\n/// # pub fn builder() -> ConfigBuilder {\n\n/// # ConfigBuilder\n\n/// # }\n\n/// # }\n\n/// # }\n\n/// use aws_smithy_http::endpoint::Endpoint;\n\n/// use http::Uri;\n\n/// let config = dynamodb::Config::builder()\n\n/// .endpoint(\n\n/// Endpoint::immutable(Uri::from_static(\"http://localhost:8080\"))\n\n/// );\n\n/// ```\n\n/// In the future, each AWS service will generate their own implementation of `ResolveAwsEndpoint`. This implementation\n\n/// may use endpoint discovery. The list of supported regions for a given service\n\n/// will be codegenerated from `endpoints.json`.\n\npub trait ResolveAwsEndpoint: Send + Sync {\n\n // TODO: consider if we want modeled error variants here\n\n fn resolve_endpoint(&self, region: &Region) -> Result<AwsEndpoint, BoxError>;\n\n}\n\n\n\n#[derive(Clone, Default, Debug)]\n\npub struct CredentialScope {\n\n region: Option<SigningRegion>,\n\n service: Option<SigningService>,\n\n}\n\n\n\nimpl CredentialScope {\n\n pub fn builder() -> credential_scope::Builder {\n\n credential_scope::Builder::default()\n\n }\n\n}\n\n\n\npub mod credential_scope {\n\n use crate::CredentialScope;\n\n use aws_types::region::SigningRegion;\n", "file_path": "aws/rust-runtime/aws-endpoint/src/lib.rs", "rank": 37, "score": 238756.0552700298 }, { "content": "#[allow(dead_code)]\n\n#[cfg(test)]\n\nfn sanity_retry() {\n\n Builder::new()\n\n .middleware(tower::layer::util::Identity::new())\n\n .connector_fn(|_| async { unreachable!() })\n\n .build()\n\n .check();\n\n}\n\n\n\n// Statically check that a hyper client can actually be used to build a Client.\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 38, "score": 238253.1748509192 }, { "content": "/// A low-level Smithy connector that maps from [`http::Request`] to [`http::Response`].\n\n///\n\n/// This trait has a blanket implementation for all compatible types, and should never be\n\n/// implemented.\n\npub trait SmithyConnector:\n\n Service<\n\n http::Request<SdkBody>,\n\n Response = http::Response<SdkBody>,\n\n Error = <Self as SmithyConnector>::Error,\n\n Future = <Self as SmithyConnector>::Future,\n\n > + Send\n\n + Sync\n\n + Clone\n\n + 'static\n\n{\n\n /// Forwarding type to `<Self as Service>::Error` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type Error: Into<ConnectorError> + Send + Sync + 'static;\n\n\n\n /// Forwarding type to `<Self as Service>::Future` for bound inference.\n\n ///\n\n /// See module-level docs for details.\n\n type Future: Send + 'static;\n", "file_path": "rust-runtime/aws-smithy-client/src/bounds.rs", "rank": 39, "score": 236792.28809640792 }, { "content": "#[derive(Clone)]\n\nstruct ImdsErrorPolicy;\n\n\n\nimpl ImdsErrorPolicy {\n\n fn classify(response: &operation::Response) -> RetryKind {\n\n let status = response.http().status();\n\n match status {\n\n _ if status.is_server_error() => RetryKind::Error(ErrorKind::ServerError),\n\n // 401 indicates that the token has expired, this is retryable\n\n _ if status.as_u16() == 401 => RetryKind::Error(ErrorKind::ServerError),\n\n _ => RetryKind::NotRetryable,\n\n }\n\n }\n\n}\n\n\n\n/// IMDS Retry Policy\n\n///\n\n/// Possible status codes:\n\n/// - 200 (OK)\n\n/// - 400 (Missing or invalid parameters) **Not Retryable**\n\n/// - 401 (Unauthorized, expired token) **Retryable**\n", "file_path": "aws/rust-runtime/aws-config/src/imds/client.rs", "rank": 40, "score": 236239.09347506124 }, { "content": "fn assert_send_fut<T: Send + 'static>(_: T) {}\n", "file_path": "aws/sdk/integration-tests/kms/tests/sensitive-it.rs", "rank": 41, "score": 235929.74745586587 }, { "content": "fn headers_to_map(headers: &http::HeaderMap<http::HeaderValue>) -> HashMap<String, Vec<String>> {\n\n let mut out: HashMap<_, Vec<_>> = HashMap::new();\n\n for (header_name, header_value) in headers.iter() {\n\n let entry = out.entry(header_name.to_string()).or_default();\n\n entry.push(header_value.to_str().unwrap().to_string());\n\n }\n\n out\n\n}\n\n\n\nimpl<'a, B> From<&'a http::Response<B>> for Response {\n\n fn from(resp: &'a http::Response<B>) -> Self {\n\n let status = resp.status().as_u16();\n\n let version = format!(\"{:?}\", resp.version());\n\n let headers = headers_to_map(resp.headers());\n\n Self {\n\n status,\n\n version,\n\n headers,\n\n }\n\n }\n", "file_path": "rust-runtime/aws-smithy-client/src/dvr.rs", "rank": 42, "score": 235651.50101539618 }, { "content": "#[allow(dead_code)]\n\nfn sanity_erase_connector() {\n\n Builder::new()\n\n .middleware(tower::layer::util::Identity::new())\n\n .connector_fn(|_| async { unreachable!() })\n\n .build()\n\n .into_dyn_connector()\n\n .check();\n\n}\n\n\n\n// Statically check that a fully type-erased client is actually a valid Client.\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 43, "score": 235112.1884166184 }, { "content": "#[allow(dead_code)]\n\nfn sanity_erase_middleware() {\n\n Builder::new()\n\n .middleware(tower::layer::util::Identity::new())\n\n .connector_fn(|_| async { unreachable!() })\n\n .build()\n\n .into_dyn_middleware()\n\n .check();\n\n}\n\n\n\n// Statically check that a type-erased connector client is actually a valid Client.\n", "file_path": "rust-runtime/aws-smithy-client/src/static_tests.rs", "rank": 44, "score": 235077.5943528228 }, { "content": "#[cfg(any(feature = \"native-tls\", feature = \"rustls\"))]\n\n#[test]\n\nfn test_default_client() {\n\n let client = Client::https();\n\n let _ = client.call(test_operation());\n\n}\n\n\n\n#[tokio::test]\n\nasync fn e2e_test() {\n\n let expected_req = http::Request::builder()\n\n .header(USER_AGENT, \"aws-sdk-rust/0.123.test os/windows/XPSP3 lang/rust/1.50.0\")\n\n .header(\"x-amz-user-agent\", \"aws-sdk-rust/0.123.test api/test-service/0.123 os/windows/XPSP3 lang/rust/1.50.0\")\n\n .header(AUTHORIZATION, \"AWS4-HMAC-SHA256 Credential=access_key/20210215/test-region/test-service-signing/aws4_request, SignedHeaders=host;x-amz-date;x-amz-user-agent, Signature=da249491d7fe3da22c2e09cbf910f37aa5b079a3cedceff8403d0b18a7bfab75\")\n\n .header(\"x-amz-date\", \"20210215T184017Z\")\n\n .uri(Uri::from_static(\"https://test-service.test-region.amazonaws.com/\"))\n\n .body(SdkBody::from(\"request body\")).unwrap();\n\n let events = vec![(\n\n expected_req,\n\n http::Response::builder()\n\n .status(200)\n\n .body(\"response body\")\n\n .unwrap(),\n", "file_path": "aws/rust-runtime/aws-hyper/tests/e2e_test.rs", "rank": 45, "score": 235003.60566426162 }, { "content": "pub fn parse_generic_error(\n\n payload: &Bytes,\n\n headers: &HeaderMap<HeaderValue>,\n\n) -> Result<SmithyError, DeserializeError> {\n\n let ErrorBody { code, message } = parse_error_body(payload.as_ref())?;\n\n\n\n let mut err_builder = SmithyError::builder();\n\n if let Some(code) = error_type_from_header(headers)\n\n .map_err(|_| DeserializeError::custom(\"X-Amzn-Errortype header was not valid UTF-8\"))?\n\n .or_else(|| code.as_deref())\n\n .map(|c| sanitize_error_code(c))\n\n {\n\n err_builder.code(code);\n\n }\n\n if let Some(message) = message {\n\n err_builder.message(message);\n\n }\n\n if let Some(request_id) = request_id(headers) {\n\n err_builder.request_id(request_id);\n\n }\n", "file_path": "rust-runtime/inlineable/src/json_errors.rs", "rank": 46, "score": 233627.7306974617 }, { "content": "/// Trait that provides an `ErrorKind` and an error code.\n\npub trait ProvideErrorKind {\n\n /// Returns the `ErrorKind` when the error is modeled as retryable\n\n ///\n\n /// If the error kind cannot be determined (e.g. the error is unmodeled at the error kind depends\n\n /// on an HTTP status code, return `None`.\n\n fn retryable_error_kind(&self) -> Option<ErrorKind>;\n\n\n\n /// Returns the `code` for this error if one exists\n\n fn code(&self) -> Option<&str>;\n\n}\n\n\n\n/// `RetryKind` describes how a request MAY be retried for a given response\n\n///\n\n/// A `RetryKind` describes how a response MAY be retried; it does not mandate retry behavior.\n\n/// The actual retry behavior is at the sole discretion of the RetryStrategy in place.\n\n/// A RetryStrategy may ignore the suggestion for a number of reasons including but not limited to:\n\n/// - Number of retry attempts exceeded\n\n/// - The required retry delay exceeds the maximum backoff configured by the client\n\n/// - No retry tokens are available due to service health\n\n#[non_exhaustive]\n", "file_path": "rust-runtime/aws-smithy-types/src/retry.rs", "rank": 47, "score": 233188.3019743815 }, { "content": "/// [`AsyncMapRequest`] defines an asynchronous middleware that transforms an [`operation::Request`].\n\n///\n\n/// Typically, these middleware will read configuration from the `PropertyBag` and use it to\n\n/// augment the request.\n\n///\n\n/// Most fundamental middleware is expressed as `AsyncMapRequest`'s synchronous cousin, `MapRequest`,\n\n/// including signing & endpoint resolution. `AsyncMapRequest` is used for async credential\n\n/// retrieval (e.g., from AWS STS's AssumeRole operation).\n\npub trait AsyncMapRequest {\n\n type Error: Into<BoxError> + 'static;\n\n type Future: Future<Output = Result<operation::Request, Self::Error>> + Send + 'static;\n\n\n\n fn apply(&self, request: operation::Request) -> Self::Future;\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/middleware.rs", "rank": 48, "score": 232979.17536381687 }, { "content": "pub fn fmt_string<T: AsRef<str>>(t: T) -> String {\n\n utf8_percent_encode(t.as_ref(), BASE_SET).to_string()\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/query.rs", "rank": 49, "score": 231790.67663596664 }, { "content": "/// Parses the S3 Extended Request ID out of S3 error response headers.\n\npub fn parse_extended_error(\n\n error: aws_smithy_types::Error,\n\n headers: &HeaderMap<HeaderValue>,\n\n) -> aws_smithy_types::Error {\n\n let mut builder = error.into_builder();\n\n let host_id = headers\n\n .get(\"x-amz-id-2\")\n\n .and_then(|header_value| header_value.to_str().ok());\n\n if let Some(host_id) = host_id {\n\n builder.custom(EXTENDED_REQUEST_ID, host_id);\n\n }\n\n builder.build()\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::s3_errors::{parse_extended_error, ErrorExt};\n\n\n\n #[test]\n\n fn add_error_fields() {\n", "file_path": "aws/rust-runtime/aws-inlineable/src/s3_errors.rs", "rank": 50, "score": 229151.0102935941 }, { "content": "/// Validate that the request had the standard JSON content-type header.\n\npub fn check_json_content_type<B>(req: &RequestParts<B>) -> Result<(), ContentTypeRejection> {\n\n let mime = req\n\n .headers()\n\n .ok_or(MissingJsonContentType)?\n\n .get(http::header::CONTENT_TYPE)\n\n .ok_or(MissingJsonContentType)?\n\n .to_str()\n\n .map_err(|_| MissingJsonContentType)?\n\n .parse::<mime::Mime>()\n\n .map_err(|_| MimeParsingFailed)?;\n\n\n\n if mime.type_() == \"application\"\n\n && (mime.subtype() == \"json\" || mime.suffix().filter(|name| *name == \"json\").is_some())\n\n {\n\n Ok(())\n\n } else {\n\n Err(ContentTypeRejection::MissingJsonContentType(MissingJsonContentType))\n\n }\n\n}\n", "file_path": "rust-runtime/aws-smithy-http-server/src/protocols.rs", "rank": 51, "score": 226827.56879159916 }, { "content": "fun RuntimeConfig.operationBuildError() = RuntimeType.operationModule(this).member(\"BuildError\")\n", "file_path": "codegen/src/main/kotlin/software/amazon/smithy/rust/codegen/smithy/generators/BuilderGenerator.kt", "rank": 52, "score": 226501.5293500055 }, { "content": "/// Returns a new credentials provider built with the given closure. This allows you\n\n/// to create an [`ProvideCredentials`] implementation from an async block that returns\n\n/// a [`credentials::Result`].\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use aws_types::Credentials;\n\n/// use aws_config::meta::credentials::provide_credentials_fn;\n\n///\n\n/// async fn load_credentials() -> Credentials {\n\n/// todo!()\n\n/// }\n\n///\n\n/// provide_credentials_fn(|| async {\n\n/// // Async process to retrieve credentials goes here\n\n/// let credentials = load_credentials().await;\n\n/// Ok(credentials)\n\n/// });\n\n/// ```\n\npub fn provide_credentials_fn<'c, T, F>(f: T) -> ProvideCredentialsFn<'c, T>\n\nwhere\n\n T: Fn() -> F + Send + Sync + 'c,\n\n F: Future<Output = credentials::Result> + Send + 'static,\n\n{\n\n ProvideCredentialsFn {\n\n f,\n\n phantom: Default::default(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::meta::credentials::credential_fn::provide_credentials_fn;\n\n use async_trait::async_trait;\n\n use aws_types::credentials::ProvideCredentials;\n\n use aws_types::{credentials, Credentials};\n\n use std::fmt::{Debug, Formatter};\n\n\n\n fn assert_send_sync<T: Send + Sync>() {}\n\n\n\n #[test]\n\n fn creds_are_send_sync() {\n\n assert_send_sync::<Credentials>()\n\n }\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/meta/credentials/credential_fn.rs", "rank": 53, "score": 226051.3502116152 }, { "content": "#[cfg(feature = \"default-provider\")]\n\npub fn from_env() -> ConfigLoader {\n\n ConfigLoader::default()\n\n}\n\n\n\n/// Load a default configuration from the environment\n\n///\n\n/// Convenience wrapper equivalent to `aws_config::from_env().load().await`\n\n#[cfg(feature = \"default-provider\")]\n\npub async fn load_from_env() -> aws_types::config::Config {\n\n from_env().load().await\n\n}\n\n\n\n#[cfg(feature = \"default-provider\")]\n\n/// Load default sources for all configuration with override support\n\npub use loader::ConfigLoader;\n\n\n\n#[cfg(feature = \"default-provider\")]\n\nmod loader {\n\n use crate::default_provider::{credentials, region, retry_config};\n\n use crate::meta::region::ProvideRegion;\n", "file_path": "aws/rust-runtime/aws-config/src/lib.rs", "rank": 54, "score": 224734.52277042973 }, { "content": "/// JSON token parser as a Rust iterator\n\n///\n\n/// This parser will parse and yield exactly one [Token] per iterator `next()` call.\n\n/// Validation is done on the fly, so it is possible for it to parse an invalid JSON document\n\n/// until it gets to the first [Error].\n\n///\n\n/// JSON string values are left escaped in the [Token::ValueString] as an [EscapedStr],\n\n/// which is a new type around a slice of original `input` bytes so that the caller can decide\n\n/// when to unescape and allocate into a [String].\n\n///\n\n/// The parser *will* accept multiple valid JSON values. For example, `b\"null true\"` will\n\n/// yield `ValueNull` and `ValueTrue`. It is the responsibility of the caller to handle this for\n\n/// their use-case.\n\npub fn json_token_iter(input: &[u8]) -> JsonTokenIterator {\n\n JsonTokenIterator {\n\n input,\n\n index: 0,\n\n state_stack: vec![State::Initial],\n\n }\n\n}\n\n\n\n/// Internal parser state for the iterator. Used to context between successive `next` calls.\n", "file_path": "rust-runtime/aws-smithy-json/src/deserialize.rs", "rank": 55, "score": 223748.901368069 }, { "content": "pub fn fmt_string<T: AsRef<str>>(t: T, greedy: bool) -> String {\n\n let uri_set = if greedy { GREEDY } else { BASE_SET };\n\n percent_encoding::utf8_percent_encode(t.as_ref(), uri_set).to_string()\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/label.rs", "rank": 56, "score": 221496.7172602608 }, { "content": "/// Read all the dates from the header map at `key` according the `format`\n\n///\n\n/// This is separate from `read_many` below because we need to invoke `DateTime::read` to take advantage\n\n/// of comma-aware parsing\n\npub fn many_dates(\n\n values: ValueIter<HeaderValue>,\n\n format: Format,\n\n) -> Result<Vec<DateTime>, ParseError> {\n\n let mut out = vec![];\n\n for header in values {\n\n let mut header = header\n\n .to_str()\n\n .map_err(|_| ParseError::new_with_message(\"header was not valid utf-8 string\"))?;\n\n while !header.is_empty() {\n\n let (v, next) = DateTime::read(header, format, ',').map_err(|err| {\n\n ParseError::new_with_message(format!(\"header could not be parsed as date: {}\", err))\n\n })?;\n\n out.push(v);\n\n header = next;\n\n }\n\n }\n\n Ok(out)\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 57, "score": 220920.62674408266 }, { "content": "/// Test connection used to capture a single request\n\n///\n\n/// If response is `None`, it will reply with a 200 response with an empty body\n\n///\n\n/// Example:\n\n/// ```rust,compile_fail\n\n/// let (server, request) = capture_request(None);\n\n/// let client = aws_sdk_sts::Client::from_conf_conn(conf, server);\n\n/// let _ = client.assume_role_with_saml().send().await;\n\n/// // web identity should be unsigned\n\n/// assert_eq!(\n\n/// request.expect_request().headers().get(\"AUTHORIZATION\"),\n\n/// None\n\n/// );\n\n/// ```\n\npub fn capture_request(\n\n response: Option<http::Response<SdkBody>>,\n\n) -> (CaptureRequestHandler, CaptureRequestReceiver) {\n\n let (tx, rx) = oneshot::channel();\n\n (\n\n CaptureRequestHandler(Arc::new(Mutex::new(Inner {\n\n response: Some(response.unwrap_or_else(|| {\n\n http::Response::builder()\n\n .status(200)\n\n .body(SdkBody::empty())\n\n .expect(\"unreachable\")\n\n })),\n\n sender: Some(tx),\n\n }))),\n\n CaptureRequestReceiver { receiver: rx },\n\n )\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-client/src/test_connection.rs", "rank": 58, "score": 219010.4423870531 }, { "content": "/// Parse `file` into a `RawProfileSet`\n\npub fn parse_profile_file(file: &File) -> Result<RawProfileSet, ProfileParseError> {\n\n let mut parser = Parser {\n\n data: HashMap::new(),\n\n state: State::Starting,\n\n location: Location {\n\n line_number: 0,\n\n path: file.path.to_string(),\n\n },\n\n };\n\n parser.parse_profile(&file.contents)?;\n\n Ok(parser.data)\n\n}\n\n\n\nimpl<'a> Parser<'a> {\n\n /// Parse `file` containing profile data into `self.data`.\n\n fn parse_profile(&mut self, file: &'a str) -> Result<(), ProfileParseError> {\n\n for (line_number, line) in file.lines().enumerate() {\n\n self.location.line_number = line_number + 1; // store a 1-indexed line number\n\n if is_empty_line(line) || is_comment_line(line) {\n\n continue;\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/parse.rs", "rank": 59, "score": 216424.11976314685 }, { "content": "pub fn fmt_timestamp(t: &DateTime, format: Format) -> Result<String, DateTimeFormatError> {\n\n Ok(crate::query::fmt_string(t.fmt(format)?))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::label::fmt_string;\n\n\n\n #[test]\n\n fn greedy_params() {\n\n assert_eq!(fmt_string(\"a/b\", false), \"a%2Fb\");\n\n assert_eq!(fmt_string(\"a/b\", true), \"a/b\");\n\n }\n\n}\n", "file_path": "rust-runtime/aws-smithy-http/src/label.rs", "rank": 60, "score": 215900.72620876643 }, { "content": "pub fn fmt_timestamp(t: &DateTime, format: Format) -> Result<String, DateTimeFormatError> {\n\n Ok(fmt_string(t.fmt(format)?))\n\n}\n\n\n\n/// Simple abstraction to enable appending params to a string as query params\n\n///\n\n/// ```rust\n\n/// use aws_smithy_http::query::Writer;\n\n/// let mut s = String::from(\"www.example.com\");\n\n/// let mut q = Writer::new(&mut s);\n\n/// q.push_kv(\"key\", \"value\");\n\n/// q.push_v(\"another_value\");\n\n/// assert_eq!(s, \"www.example.com?key=value&another_value\");\n\n/// ```\n\npub struct Writer<'a> {\n\n out: &'a mut String,\n\n prefix: char,\n\n}\n\n\n\nimpl<'a> Writer<'a> {\n", "file_path": "rust-runtime/aws-smithy-http/src/query.rs", "rank": 61, "score": 215900.72620876643 }, { "content": "pub fn headers_for_prefix<'a>(\n\n headers: &'a http::HeaderMap,\n\n key: &'a str,\n\n) -> impl Iterator<Item = (&'a str, &'a HeaderName)> {\n\n let lower_key = key.to_ascii_lowercase();\n\n headers\n\n .keys()\n\n .filter(move |k| k.as_str().starts_with(&lower_key))\n\n .map(move |h| (&h.as_str()[key.len()..], h))\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 62, "score": 215379.9922389654 }, { "content": "fun pubUseTypes(runtimeConfig: RuntimeConfig) = listOf(\n\n RuntimeType.Blob(runtimeConfig),\n\n RuntimeType.DateTime(runtimeConfig),\n\n CargoDependency.SmithyHttp(runtimeConfig).asType().member(\"result::SdkError\"),\n\n CargoDependency.SmithyHttp(runtimeConfig).asType().member(\"byte_stream::ByteStream\"),\n\n)\n\n\n", "file_path": "codegen/src/main/kotlin/software/amazon/smithy/rust/codegen/smithy/customizations/SmithyTypesPubUseGenerator.kt", "rank": 63, "score": 215355.00994744516 }, { "content": "/// Produces a signature for the given `request` and returns instructions\n\n/// that can be used to apply that signature to an HTTP request.\n\npub fn sign<'a>(\n\n request: SignableRequest<'a>,\n\n params: &'a SigningParams<'a>,\n\n) -> Result<SigningOutput<SigningInstructions>, Error> {\n\n tracing::trace!(request = ?request, params = ?params, \"signing request\");\n\n match params.settings.signature_location {\n\n SignatureLocation::Headers => {\n\n let (signing_headers, signature) =\n\n calculate_signing_headers(&request, params)?.into_parts();\n\n Ok(SigningOutput::new(\n\n SigningInstructions::new(Some(signing_headers), None),\n\n signature,\n\n ))\n\n }\n\n SignatureLocation::QueryParams => {\n\n let (params, signature) = calculate_signing_params(&request, params)?;\n\n Ok(SigningOutput::new(\n\n SigningInstructions::new(None, Some(params)),\n\n signature,\n\n ))\n\n }\n\n }\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-sigv4/src/http_request/sign.rs", "rank": 64, "score": 212942.33655627558 }, { "content": "pub fn default_provider() -> IdempotencyTokenProvider {\n\n IdempotencyTokenProvider::random()\n\n}\n\n\n\nimpl From<&'static str> for IdempotencyTokenProvider {\n\n fn from(token: &'static str) -> Self {\n\n Self::fixed(token)\n\n }\n\n}\n\n\n\nimpl IdempotencyTokenProvider {\n\n pub fn make_idempotency_token(&self) -> String {\n\n match &self.inner {\n\n Inner::Static(token) => token.to_string(),\n\n Inner::Random(rng) => {\n\n let input: u128 = rng.lock().unwrap().u128(..);\n\n uuid_v4(input)\n\n }\n\n }\n\n }\n", "file_path": "rust-runtime/inlineable/src/idempotency_token.rs", "rank": 65, "score": 211508.48516488436 }, { "content": "pub fn parse_response_headers(message: &Message) -> Result<ResponseHeaders, Error> {\n\n let (mut content_type, mut message_type, mut event_type, mut exception_type) =\n\n (None, None, None, None);\n\n for header in message.headers() {\n\n match header.name().as_str() {\n\n \":content-type\" => content_type = Some(header),\n\n \":message-type\" => message_type = Some(header),\n\n \":event-type\" => event_type = Some(header),\n\n \":exception-type\" => exception_type = Some(header),\n\n _ => {}\n\n }\n\n }\n\n let message_type = expect_header_str_value(message_type, \":message-type\")?;\n\n Ok(ResponseHeaders {\n\n content_type: content_type\n\n .map(|ct| expect_header_str_value(Some(ct), \":content-type\"))\n\n .transpose()?,\n\n message_type,\n\n smithy_type: if message_type.as_str() == \"event\" {\n\n expect_header_str_value(event_type, \":event-type\")?\n", "file_path": "rust-runtime/aws-smithy-eventstream/src/smithy.rs", "rank": 66, "score": 211179.33600689468 }, { "content": "pub fn set_header_if_absent<V>(\n\n request: http::request::Builder,\n\n key: HeaderName,\n\n value: V,\n\n) -> http::request::Builder\n\nwhere\n\n HeaderValue: TryFrom<V>,\n\n <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,\n\n{\n\n if !request\n\n .headers_ref()\n\n .map(|map| map.contains_key(&key))\n\n .unwrap_or(false)\n\n {\n\n request.header(key, value)\n\n } else {\n\n request\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 67, "score": 210562.13091914906 }, { "content": "/// Resolve a ProfileChain from a ProfileSet or return an error\n\npub fn resolve_chain<'a>(\n\n profile_set: &'a ProfileSet,\n\n profile_override: Option<&str>,\n\n) -> Result<ProfileChain<'a>, ProfileFileError> {\n\n if profile_set.is_empty() {\n\n return Err(ProfileFileError::NoProfilesDefined);\n\n }\n\n let mut source_profile_name =\n\n profile_override.unwrap_or_else(|| profile_set.selected_profile());\n\n let mut visited_profiles = vec![];\n\n let mut chain = vec![];\n\n let base = loop {\n\n let profile = profile_set.get_profile(source_profile_name).ok_or(\n\n ProfileFileError::MissingProfile {\n\n profile: source_profile_name.into(),\n\n message: format!(\n\n \"could not find source profile {} referenced from {}\",\n\n source_profile_name,\n\n visited_profiles.last().unwrap_or(&\"the root profile\")\n\n )\n", "file_path": "aws/rust-runtime/aws-config/src/profile/credentials/repr.rs", "rank": 68, "score": 210480.89588291917 }, { "content": "type CalculatedParams = Vec<(&'static str, Cow<'static, str>)>;\n\n\n", "file_path": "aws/rust-runtime/aws-sigv4/src/http_request/sign.rs", "rank": 69, "score": 210464.7821210255 }, { "content": "/// Expects a [Token::ValueString] or [Token::ValueNull]. If the value is a string, it interprets it as a base64 encoded [Blob] value.\n\npub fn expect_blob_or_null(token: Option<Result<Token<'_>, Error>>) -> Result<Option<Blob>, Error> {\n\n Ok(match expect_string_or_null(token)? {\n\n Some(value) => Some(Blob::new(base64::decode(value.as_escaped_str()).map_err(\n\n |err| {\n\n Error::new(\n\n ErrorReason::Custom(Cow::Owned(format!(\"failed to decode base64: {}\", err))),\n\n None,\n\n )\n\n },\n\n )?)),\n\n None => None,\n\n })\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-json/src/deserialize/token.rs", "rank": 70, "score": 210042.4643703667 }, { "content": "/// Normalizes XML for comparison during Smithy Protocol tests\n\n///\n\n/// This will normalize documents and attempts to determine if it is OK to sort members or not by\n\n/// using a heuristic to determine if the tag represents a list (which should not be reordered)\n\npub fn normalize_xml(s: &str) -> Result<String, roxmltree::Error> {\n\n let rotree = roxmltree::Document::parse(s)?;\n\n let root = rotree.root().first_child().unwrap();\n\n Ok(unparse_tag(root, 1))\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/xml.rs", "rank": 71, "score": 208935.6142087551 }, { "content": "/// Unescapes a JSON-escaped string.\n\n/// If there are no escape sequences, it directly returns the reference.\n\npub fn unescape_string(value: &str) -> Result<Cow<str>, Error> {\n\n let bytes = value.as_bytes();\n\n for (index, byte) in bytes.iter().enumerate() {\n\n if *byte == b'\\\\' {\n\n return unescape_string_inner(&bytes[0..index], &bytes[index..]).map(Cow::Owned);\n\n }\n\n }\n\n Ok(Cow::Borrowed(value))\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-json/src/escape.rs", "rank": 72, "score": 208930.5480770569 }, { "content": "fn test_operation() -> Operation<TestOperationParser, AwsErrorRetryPolicy> {\n\n let req = operation::Request::new(\n\n http::Request::builder()\n\n .uri(\"https://test-service.test-region.amazonaws.com/\")\n\n .body(SdkBody::from(\"request body\"))\n\n .unwrap(),\n\n )\n\n .augment(|req, mut conf| {\n\n set_endpoint_resolver(\n\n &mut conf,\n\n Arc::new(aws_endpoint::partition::endpoint::Metadata {\n\n uri_template: \"test-service.{region}.amazonaws.com\",\n\n protocol: Protocol::Https,\n\n credential_scope: Default::default(),\n\n signature_versions: SignatureVersion::V4,\n\n }),\n\n );\n\n aws_http::auth::set_provider(\n\n &mut conf,\n\n SharedCredentialsProvider::new(Credentials::from_keys(\n", "file_path": "aws/rust-runtime/aws-hyper/tests/e2e_test.rs", "rank": 73, "score": 206638.5669176057 }, { "content": "/// Read exactly one or none from a headers iterator\n\n///\n\n/// This function does not perform comma splitting like `read_many`\n\npub fn one_or_none<T: FromStr>(\n\n mut values: ValueIter<HeaderValue>,\n\n) -> Result<Option<T>, ParseError> {\n\n let first = match values.next() {\n\n Some(v) => v,\n\n None => return Ok(None),\n\n };\n\n let value = std::str::from_utf8(first.as_bytes())\n\n .map_err(|_| ParseError::new_with_message(\"invalid utf-8\"))?;\n\n match values.next() {\n\n None => T::from_str(value.trim())\n\n .map_err(|_| ParseError::new())\n\n .map(Some),\n\n Some(_) => Err(ParseError::new_with_message(\n\n \"expected a single value but found multiple\",\n\n )),\n\n }\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 74, "score": 205814.77545989744 }, { "content": "#[allow(unused)]\n\npub fn body_is_error(body: &[u8]) -> Result<bool, XmlError> {\n\n let mut doc = Document::try_from(body)?;\n\n let scoped = doc.root_element()?;\n\n Ok(scoped.start_el().matches(\"Response\"))\n\n}\n\n\n", "file_path": "rust-runtime/inlineable/src/ec2_query_errors.rs", "rank": 75, "score": 205808.8307857404 }, { "content": "pub fn read_many_primitive<T: Parse>(values: ValueIter<HeaderValue>) -> Result<Vec<T>, ParseError> {\n\n read_many(values, |v: &str| {\n\n T::parse_smithy_primitive(v).map_err(|primitive| {\n\n ParseError::new_with_message(format!(\n\n \"failed reading a list of primitives: {}\",\n\n primitive\n\n ))\n\n })\n\n })\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 76, "score": 204555.369583382 }, { "content": "class SmithyTypesPubUseGenerator(private val runtimeConfig: RuntimeConfig) : LibRsCustomization() {\n\n override fun section(section: LibRsSection) = writable {\n\n when (section) {\n\n LibRsSection.Body -> pubUseTypes(runtimeConfig).forEach {\n\n rust(\"pub use #T;\", it)\n\n }\n\n else -> { }\n\n }\n\n }\n\n}\n", "file_path": "codegen/src/main/kotlin/software/amazon/smithy/rust/codegen/smithy/customizations/SmithyTypesPubUseGenerator.kt", "rank": 77, "score": 204283.7827385661 }, { "content": "#[allow(unused)]\n\npub fn body_is_error(body: &[u8]) -> Result<bool, XmlError> {\n\n let mut doc = Document::try_from(body)?;\n\n let scoped = doc.root_element()?;\n\n Ok(scoped.start_el().matches(\"Error\"))\n\n}\n\n\n", "file_path": "rust-runtime/inlineable/src/rest_xml_unwrapped_errors.rs", "rank": 78, "score": 203993.61294119456 }, { "content": "#[allow(unused)]\n\npub fn body_is_error(body: &[u8]) -> Result<bool, XmlError> {\n\n let mut doc = Document::try_from(body)?;\n\n let scoped = doc.root_element()?;\n\n Ok(scoped.start_el().matches(\"ErrorResponse\"))\n\n}\n\n\n", "file_path": "rust-runtime/inlineable/src/rest_xml_wrapped_errors.rs", "rank": 79, "score": 203993.61294119462 }, { "content": "type BoxBody = http_body::combinators::BoxBody<Bytes, Error>;\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/body.rs", "rank": 80, "score": 203975.31423128577 }, { "content": "pub fn read_many_from_str<T: FromStr>(\n\n values: ValueIter<HeaderValue>,\n\n) -> Result<Vec<T>, ParseError> {\n\n read_many(values, |v: &str| {\n\n v.parse()\n\n .map_err(|_err| ParseError::new_with_message(\"failed during FromString conversion\"))\n\n })\n\n}\n\n\n", "file_path": "rust-runtime/aws-smithy-http/src/header.rs", "rank": 81, "score": 203520.77482704833 }, { "content": "type ConnectVec<B> = Vec<(http::Request<SdkBody>, http::Response<B>)>;\n\n\n\n#[derive(Debug)]\n\npub struct ValidateRequest {\n\n pub expected: http::Request<SdkBody>,\n\n pub actual: http::Request<SdkBody>,\n\n}\n\n\n\nimpl ValidateRequest {\n\n pub fn assert_matches(&self, ignore_headers: &[HeaderName]) {\n\n let (actual, expected) = (&self.actual, &self.expected);\n\n for (name, value) in expected.headers() {\n\n if !ignore_headers.contains(name) {\n\n let actual_header = actual\n\n .headers()\n\n .get(name)\n\n .unwrap_or_else(|| panic!(\"Header {:?} missing\", name));\n\n assert_eq!(\n\n actual_header.to_str().unwrap(),\n\n value.to_str().unwrap(),\n", "file_path": "rust-runtime/aws-smithy-client/src/test_connection.rs", "rank": 82, "score": 200431.5591707552 }, { "content": "#[derive(Clone, Debug)]\n\nstruct RequestLocalRetryState {\n\n attempts: u32,\n\n last_quota_usage: Option<usize>,\n\n}\n\n\n\nimpl Default for RequestLocalRetryState {\n\n fn default() -> Self {\n\n Self {\n\n // Starts at one to account for the initial request that failed and warranted a retry\n\n attempts: 1,\n\n last_quota_usage: None,\n\n }\n\n }\n\n}\n\n\n\nimpl RequestLocalRetryState {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n}\n\n\n\n/* TODO in followup PR:\n", "file_path": "rust-runtime/aws-smithy-client/src/retry.rs", "rank": 83, "score": 200168.61854612024 }, { "content": "#[derive(Clone, Debug)]\n\nstruct CrossRequestRetryState {\n\n quota_available: Arc<Mutex<usize>>,\n\n}\n\n\n\n// clippy is upset that we didn't use AtomicUsize here, but doing so makes the code\n\n// significantly more complicated for negligible benefit.\n\n#[allow(clippy::mutex_atomic)]\n\nimpl CrossRequestRetryState {\n\n pub fn new(initial_quota: usize) -> Self {\n\n Self {\n\n quota_available: Arc::new(Mutex::new(initial_quota)),\n\n }\n\n }\n\n\n\n fn quota_release(&self, value: Option<usize>, config: &Config) {\n\n let mut quota = self.quota_available.lock().unwrap();\n\n *quota += value.unwrap_or(config.no_retry_increment);\n\n }\n\n\n\n /// Attempt to acquire retry quota for `ErrorKind`\n", "file_path": "rust-runtime/aws-smithy-client/src/retry.rs", "rank": 84, "score": 200168.61854612027 }, { "content": "/// Load static credentials from a profile\n\n///\n\n/// Example:\n\n/// ```ini\n\n/// [profile B]\n\n/// aws_access_key_id = abc123\n\n/// aws_secret_access_key = def456\n\n/// ```\n\nfn static_creds_from_profile(profile: &Profile) -> Result<Credentials, ProfileFileError> {\n\n use static_credentials::*;\n\n let access_key = profile.get(AWS_ACCESS_KEY_ID);\n\n let secret_key = profile.get(AWS_SECRET_ACCESS_KEY);\n\n let session_token = profile.get(AWS_SESSION_TOKEN);\n\n if let (None, None, None) = (access_key, secret_key, session_token) {\n\n return Err(ProfileFileError::ProfileDidNotContainCredentials {\n\n profile: profile.name().to_string(),\n\n });\n\n }\n\n let access_key = access_key.ok_or_else(|| ProfileFileError::InvalidCredentialSource {\n\n profile: profile.name().to_string(),\n\n message: \"profile missing aws_access_key_id\".into(),\n\n })?;\n\n let secret_key = secret_key.ok_or_else(|| ProfileFileError::InvalidCredentialSource {\n\n profile: profile.name().to_string(),\n\n message: \"profile missing aws_secret_access_key\".into(),\n\n })?;\n\n Ok(Credentials::new(\n\n access_key,\n", "file_path": "aws/rust-runtime/aws-config/src/profile/credentials/repr.rs", "rank": 85, "score": 199498.44170623037 }, { "content": "pub fn validate_body<T: AsRef<[u8]>>(\n\n actual_body: T,\n\n expected_body: &str,\n\n media_type: MediaType,\n\n) -> Result<(), ProtocolTestFailure> {\n\n let body_str = std::str::from_utf8(actual_body.as_ref());\n\n match (media_type, body_str) {\n\n (MediaType::Json, Ok(actual_body)) => try_json_eq(actual_body, expected_body),\n\n (MediaType::Xml, Ok(actual_body)) => try_xml_equivalent(actual_body, expected_body),\n\n (MediaType::Json, Err(_)) => Err(ProtocolTestFailure::InvalidBodyFormat {\n\n expected: \"json\".to_owned(),\n\n found: \"input was not valid UTF-8\".to_owned(),\n\n }),\n\n (MediaType::Xml, Err(_)) => Err(ProtocolTestFailure::InvalidBodyFormat {\n\n expected: \"XML\".to_owned(),\n\n found: \"input was not valid UTF-8\".to_owned(),\n\n }),\n\n (MediaType::UrlEncodedForm, Ok(actual_body)) => {\n\n try_url_encoded_form_equivalent(actual_body, expected_body)\n\n }\n", "file_path": "rust-runtime/aws-smithy-protocol-test/src/lib.rs", "rank": 86, "score": 198156.71871938714 }, { "content": "/// Expects and parses a complete document value.\n\npub fn expect_document<'a, I>(tokens: &mut Peekable<I>) -> Result<Document, Error>\n\nwhere\n\n I: Iterator<Item = Result<Token<'a>, Error>>,\n\n{\n\n expect_document_inner(tokens, 0)\n\n}\n\n\n\nconst MAX_DOCUMENT_RECURSION: usize = 256;\n\n\n", "file_path": "rust-runtime/aws-smithy-json/src/deserialize/token.rs", "rank": 87, "score": 196490.0251565319 }, { "content": "fn main() {\n\n let out_dir = env::var_os(\"OUT_DIR\").expect(\"OUT_DIR not specified\");\n\n let out_path = Path::new(&out_dir).to_owned();\n\n\n\n generate_build_vars(&out_path);\n\n}\n", "file_path": "aws/rust-runtime/aws-types/build.rs", "rank": 88, "score": 196079.54778488076 }, { "content": "/// Validate that a string is a valid identifier\n\n///\n\n/// Identifiers must match `[A-Za-z0-9\\-_]+`\n\nfn validate_identifier(input: &str) -> Result<&str, ()> {\n\n input\n\n .chars()\n\n .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '\\\\')\n\n .then(|| input)\n\n .ok_or(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::HashMap;\n\n\n\n use tracing_test::traced_test;\n\n\n\n use crate::profile::parser::parse::RawProfileSet;\n\n use crate::profile::parser::source::FileKind;\n\n use crate::profile::ProfileSet;\n\n\n\n use super::{merge_in, ProfileName};\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/profile/parser/normalize.rs", "rank": 89, "score": 195666.87057058938 }, { "content": "class PubUseRetryConfig(private val runtimeConfig: RuntimeConfig) : LibRsCustomization() {\n\n override fun section(section: LibRsSection): Writable {\n\n return when (section) {\n\n is LibRsSection.Body -> writable { rust(\"pub use #T::RetryConfig;\", smithyTypesRetry(runtimeConfig)) }\n\n else -> emptySection\n\n }\n\n }\n\n}\n\n\n", "file_path": "codegen/src/main/kotlin/software/amazon/smithy/rust/codegen/smithy/customizations/RetryConfigDecorator.kt", "rank": 90, "score": 193592.3609245671 }, { "content": "#[derive(Debug)]\n\nstruct OperationError;\n\n\n\nimpl Display for OperationError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\nimpl Error for OperationError {}\n\n\n\nimpl ProvideErrorKind for OperationError {\n\n fn retryable_error_kind(&self) -> Option<ErrorKind> {\n\n Some(ErrorKind::ThrottlingError)\n\n }\n\n\n\n fn code(&self) -> Option<&str> {\n\n None\n\n }\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-hyper/tests/e2e_test.rs", "rank": 91, "score": 190840.16595096033 }, { "content": "/// Writes the given `headers` to a `buffer`.\n\npub fn write_headers_to<B: BufMut>(headers: &[Header], mut buffer: B) -> Result<(), Error> {\n\n for header in headers {\n\n header.write_to(&mut buffer)?;\n\n }\n\n Ok(())\n\n}\n\n\n\n/// Event Stream message.\n\n#[non_exhaustive]\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct Message {\n\n headers: Vec<Header>,\n\n payload: Bytes,\n\n}\n\n\n\nimpl Message {\n\n /// Creates a new message with the given `payload`. Headers can be added later.\n\n pub fn new(payload: impl Into<Bytes>) -> Message {\n\n Message {\n\n headers: Vec::new(),\n", "file_path": "rust-runtime/aws-smithy-eventstream/src/frame.rs", "rank": 92, "score": 190729.8085817232 }, { "content": "fn generate_build_vars(output_path: &Path) {\n\n let rust_version = rustc_version::version().expect(\"Could not retrieve rustc version\");\n\n let mut f = File::create(&output_path.join(\"build_env.rs\"))\n\n .expect(\"Could not create build environment\");\n\n f.write_all(format!(\"const RUST_VERSION: &str = \\\"{}\\\";\", rust_version).as_bytes())\n\n .expect(\"Unable to write rust version\");\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-types/build.rs", "rank": 93, "score": 189738.35000902673 }, { "content": "#[derive(Clone)]\n\nstruct Token {\n\n value: HeaderValue,\n\n expiry: SystemTime,\n\n}\n\n\n\n/// Token Middleware\n\n///\n\n/// Token middleware will load/cache a token when required and handle caching/expiry.\n\n///\n\n/// It will attach the token to the incoming request on the `x-aws-ec2-metadata-token` header.\n\n#[derive(Clone)]\n\npub(super) struct TokenMiddleware {\n\n client: Arc<aws_smithy_client::Client<DynConnector, MapRequestLayer<UserAgentStage>>>,\n\n token_parser: GetTokenResponseHandler,\n\n token: ExpiringCache<Token, ImdsError>,\n\n time_source: TimeSource,\n\n endpoint: Endpoint,\n\n token_ttl: Duration,\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/imds/client/token.rs", "rank": 94, "score": 189526.34199956607 }, { "content": "/// Convert a [`http_body::Body`] into a [`BoxBody`].\n\npub fn box_body<B>(body: B) -> BoxBody\n\nwhere\n\n B: http_body::Body<Data = Bytes> + Send + 'static,\n\n B::Error: Into<BoxError>,\n\n{\n\n body.map_err(Error::new).boxed_unsync()\n\n}\n", "file_path": "rust-runtime/aws-smithy-http-server/src/body.rs", "rank": 95, "score": 189351.32567874948 }, { "content": "fn record_body(\n\n body: &mut SdkBody,\n\n event_id: ConnectionId,\n\n direction: Direction,\n\n event_bus: Arc<Mutex<Vec<Event>>>,\n\n) -> JoinHandle<()> {\n\n let (sender, output_body) = hyper::Body::channel();\n\n let real_body = std::mem::replace(body, SdkBody::from(output_body));\n\n tokio::spawn(async move {\n\n let mut real_body = real_body;\n\n let mut sender = sender;\n\n loop {\n\n let data = real_body.data().await;\n\n match data {\n\n Some(Ok(data)) => {\n\n event_bus.lock().unwrap().push(Event {\n\n connection_id: event_id,\n\n action: Action::Data {\n\n data: BodyData::from(data.clone()),\n\n direction,\n", "file_path": "rust-runtime/aws-smithy-client/src/dvr/record.rs", "rank": 96, "score": 188139.8374688162 }, { "content": "/// Extract a signing config from a [`PropertyBag`](aws_smithy_http::property_bag::PropertyBag)\n\nfn signing_config(\n\n config: &PropertyBag,\n\n) -> Result<(&OperationSigningConfig, RequestConfig, Credentials), SigningStageError> {\n\n let operation_config = config\n\n .get::<OperationSigningConfig>()\n\n .ok_or(SigningStageError::MissingSigningConfig)?;\n\n let credentials = config\n\n .get::<Credentials>()\n\n .ok_or(SigningStageError::MissingCredentials)?\n\n .clone();\n\n let region = config\n\n .get::<SigningRegion>()\n\n .ok_or(SigningStageError::MissingSigningRegion)?;\n\n let signing_service = config\n\n .get::<SigningService>()\n\n .ok_or(SigningStageError::MissingSigningService)?;\n\n let payload_override = config.get::<SignableBody<'static>>();\n\n let request_config = RequestConfig {\n\n request_ts: config\n\n .get::<SystemTime>()\n", "file_path": "aws/rust-runtime/aws-sig-auth/src/middleware.rs", "rank": 97, "score": 187560.51029131954 }, { "content": "#[allow(unused)]\n\npub fn error_scope<'a, 'b>(doc: &'a mut Document<'b>) -> Result<ScopedDecoder<'b, 'a>, XmlError> {\n\n let root = doc\n\n .next_start_element()\n\n .ok_or_else(|| XmlError::custom(\"no root found searching for an Error\"))?;\n\n if !root.matches(\"Response\") {\n\n return Err(XmlError::custom(\"expected Response as root\"));\n\n }\n\n\n\n while let Some(el) = doc.next_start_element() {\n\n if el.matches(\"Errors\") && el.depth() == 1 {\n\n while let Some(el) = doc.next_start_element() {\n\n if el.matches(\"Error\") && el.depth() == 2 {\n\n return Ok(doc.scoped_to(el));\n\n }\n\n }\n\n }\n\n // otherwise, ignore it\n\n }\n\n Err(XmlError::custom(\"No Error found inside of Response\"))\n\n}\n", "file_path": "rust-runtime/inlineable/src/ec2_query_errors.rs", "rank": 98, "score": 187423.06869539813 }, { "content": "#[derive(Clone, Debug)]\n\nstruct CredentialsResponseParser {\n\n provider_name: &'static str,\n\n}\n\nimpl ParseStrictResponse for CredentialsResponseParser {\n\n type Output = credentials::Result;\n\n\n\n fn parse(&self, response: &Response<Bytes>) -> Self::Output {\n\n let str_resp =\n\n std::str::from_utf8(response.body().as_ref()).map_err(CredentialsError::unhandled)?;\n\n let json_creds = parse_json_credentials(str_resp).map_err(CredentialsError::unhandled)?;\n\n match json_creds {\n\n JsonCredentials::RefreshableCredentials {\n\n access_key_id,\n\n secret_access_key,\n\n session_token,\n\n expiration,\n\n } => Ok(Credentials::new(\n\n access_key_id,\n\n secret_access_key,\n\n Some(session_token.to_string()),\n\n Some(expiration),\n\n self.provider_name,\n\n )),\n\n JsonCredentials::Error { code, message } => Err(CredentialsError::provider_error(\n\n format!(\"failed to load credentials [{}]: {}\", code, message),\n\n )),\n\n }\n\n }\n\n}\n\n\n", "file_path": "aws/rust-runtime/aws-config/src/http_provider.rs", "rank": 99, "score": 186566.22755197424 } ]
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 CAPACITY: usize> {\n\n entries: [ArrayEntry<T>; CAPACITY],\n\n}\n\n\n\npub struct ArrayPtr<T> {\n\n ptr: *mut ArrayEntry<T>,\n\n _marker: PhantomData<T>,\n\n}\n\n\n\n#[repr(C)]\n", "file_path": "kernel-rs/src/arena.rs", "rank": 0, "score": 123885.57649545537 }, { "content": "/// A homogeneous memory allocator, equipped with the box type representing an allocation.\n\npub trait Arena: Sized {\n\n /// The value type of the allocator.\n\n type Data;\n\n\n\n /// The object handle type of the allocator.\n\n type Handle;\n\n\n\n /// The guard type for arena.\n\n type Guard<'s>;\n\n\n\n /// Creates handle from condition without increasing reference count.\n\n fn unforget<C: Fn(&Self::Data) -> bool>(&self, c: C) -> Option<Self::Handle>;\n\n\n\n /// Find or alloc.\n\n fn find_or_alloc<C: Fn(&Self::Data) -> bool, N: FnOnce(&mut Self::Data)>(\n\n &self,\n\n c: C,\n\n n: N,\n\n ) -> Option<Self::Handle>;\n\n\n", "file_path": "kernel-rs/src/arena.rs", "rank": 1, "score": 117246.17797174476 }, { "content": " uint blockno;\n", "file_path": "kernel/buf.h", "rank": 2, "score": 113883.15836960217 }, { "content": " uchar data[BSIZE];\n", "file_path": "kernel/buf.h", "rank": 3, "score": 113874.36872747849 }, { "content": " int valid; // has data been read from disk?\n", "file_path": "kernel/buf.h", "rank": 4, "score": 113874.36872747849 }, { "content": " uint dev;\n", "file_path": "kernel/buf.h", "rank": 5, "score": 113867.89194950831 }, { "content": " int disk; // does disk \"own\" buf?\n", "file_path": "kernel/buf.h", "rank": 6, "score": 113721.42888681279 }, { "content": "#[inline(never)]\n\npub fn spin_loop() -> ! {\n\n loop {\n\n spin_loop_hint();\n\n }\n\n}\n", "file_path": "kernel-rs/src/utils.rs", "rank": 7, "score": 111833.63481319281 }, { "content": "/// Return this CPU's ID.\n\n///\n\n/// It is safe to call this function with interrupts enabled, but the returned id may not be the\n\n/// current CPU since the scheduler can move the process to another CPU on time interrupt.\n\npub fn cpuid() -> usize {\n\n unsafe { r_tp() }\n\n}\n\n\n\n/// Return the current struct Proc *, or zero if none.\n\npub unsafe fn myproc() -> *mut Proc {\n\n push_off();\n\n let c = kernel().mycpu();\n\n let p = (*c).proc;\n\n pop_off();\n\n p\n\n}\n\n\n\n/// Frees a `Proc` structure and the data hanging from it, including user pages.\n\n/// Must provide a `ProcGuard`, and optionally, you can also provide a `SpinlockProtectedGuard`\n\n/// if you also want to clear `p`'s parent field into `ptr::null_mut()`.\n\n///\n\n/// # Note\n\n///\n\n/// If a `SpinlockProtectedGuard` was not provided, `p`'s parent field is not modified.\n", "file_path": "kernel-rs/src/proc.rs", "rank": 8, "score": 105192.94572391747 }, { "content": "struct PipeInner {\n\n data: [u8; PIPESIZE],\n\n\n\n /// Number of bytes read.\n\n nread: u32,\n\n\n\n /// Number of bytes written.\n\n nwrite: u32,\n\n\n\n /// Read fd is still open.\n\n readopen: bool,\n\n\n\n /// Write fd is still open.\n\n writeopen: bool,\n\n}\n\n\n\npub struct Pipe {\n\n inner: Spinlock<PipeInner>,\n\n\n\n /// WaitChannel for saying there are unread bytes in Pipe.data.\n", "file_path": "kernel-rs/src/pipe.rs", "rank": 9, "score": 101476.2102171778 }, { "content": "#[derive(Debug)]\n\nstruct Descriptor {\n\n idx: usize,\n\n ptr: *mut VirtqDesc,\n\n}\n\n\n\n// It needs repr(C) because it's read by device.\n\n// https://docs.oasis-open.org/virtio/virtio/v1.1/csprd01/virtio-v1.1-csprd01.html#x1-380006\n\n/// the (entire) avail ring, from the spec.\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 10, "score": 101316.16403816863 }, { "content": "/// Send one character to the uart.\n\n/// TODO(@coolofficials): This global function is temporary.\n\n/// After refactoring Console-Uart-Printer relationship, this function need to be removed.\n\npub fn putc(c: i32) {\n\n if c == BACKSPACE {\n\n // If the user typed backspace, overwrite with a space.\n\n Uart::putc_sync('\\u{8}' as i32);\n\n Uart::putc_sync(' ' as i32);\n\n Uart::putc_sync('\\u{8}' as i32);\n\n } else {\n\n Uart::putc_sync(c);\n\n };\n\n}\n\n\n\n/// Console input and output, to the uart.\n\n/// Reads are line at a time.\n\n/// Implements special input characters:\n\n/// newline -- end of line\n\n/// control-h -- backspace\n\n/// control-u -- kill line\n\n/// control-d -- end of file\n\n/// control-p -- print process list\n\nconst BACKSPACE: i32 = 0x100;\n", "file_path": "kernel-rs/src/console.rs", "rank": 11, "score": 100578.6543475704 }, { "content": "struct DescriptorPool {\n\n desc: *mut [VirtqDesc; NUM],\n\n\n\n /// Our own book-keeping.\n\n free: [bool; NUM], // TODO : Disk can be implemented using bitmap\n\n}\n\n\n\n/// A descriptor allocated by driver.\n\n///\n\n/// Invariant: `ptr` must indicate `idx`-th descriptor of the original pool.\n\n// TODO(@efenniht): `ptr` is redundant as the base pointer is stored in the pool. But if we remove\n\n// it, the invariant of this type indirectly depends on the original pool (not appeared as a field).\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 12, "score": 98423.84939573878 }, { "content": "#[derive(Copy, Clone)]\n\nstruct InflightInfo {\n\n b: *mut Buf<'static>,\n\n status: bool,\n\n}\n\n\n\n/// The format of the first descriptor in a disk request.\n\n/// To be followed by two more descriptors containing\n\n/// the block, and a one-byte status.\n\n// It needs repr(C) because it's struct for in-disk representation\n\n// which should follow C(=machine) representation\n\n// https://github.com/kaist-cp/rv6/issues/52\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 13, "score": 98423.84939573878 }, { "content": "#[repr(C)]\n\nstruct VirtqAvail {\n\n flags: u16,\n\n\n\n /// Tells the device how far to look in `ring`.\n\n idx: u16,\n\n\n\n /// `desc` indices the device should process.\n\n ring: [u16; NUM],\n\n}\n\n\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 14, "score": 98423.84939573878 }, { "content": "#[inline]\n\npub fn kernel() -> &'static Kernel {\n\n unsafe { &KERNEL }\n\n}\n\n\n\npub struct Kernel {\n\n panicked: AtomicBool,\n\n\n\n /// Sleeps waiting for there are some input in console buffer.\n\n pub console: Sleepablelock<Console>,\n\n\n\n /// TODO(@coolofficials): Kernel owns uart temporarily.\n\n /// This might be changed after refactoring relationship between Console-Uart-Printer.\n\n pub uart: Uart,\n\n\n\n pub printer: Spinlock<Printer>,\n\n\n\n kmem: Spinlock<Kmem>,\n\n\n\n /// The kernel's page table.\n\n pub page_table: PageTable<KVAddr>,\n", "file_path": "kernel-rs/src/kernel.rs", "rank": 15, "score": 97888.80243604252 }, { "content": "/// Shutdowns this machine, discarding all unsaved data.\n\n///\n\n/// This function uses SiFive Test Finalizer, which provides power management for QEMU virt device.\n\npub fn machine_poweroff(exitcode: u16) -> ! {\n\n const BASE_CODE: u32 = 0x3333;\n\n let code = ((exitcode as u32) << 16) | BASE_CODE;\n\n // SAFETY:\n\n // - FINISHER is identically mapped from physical address.\n\n // - FINISHER is for MMIO. Though this is not specified as document, see the implementation:\n\n // https://github.com/qemu/qemu/blob/stable-5.0/hw/riscv/virt.c#L60 and,\n\n // https://github.com/qemu/qemu/blob/stable-5.0/hw/riscv/sifive_test.c#L34\n\n unsafe {\n\n ptr::write_volatile(memlayout::FINISHER as *mut u32, code);\n\n }\n\n\n\n unreachable!(\"Power off failed\");\n\n}\n", "file_path": "kernel-rs/src/poweroff.rs", "rank": 16, "score": 95396.28058501339 }, { "content": "#[derive(Copy, Clone)]\n\n#[repr(C)]\n\nstruct VirtIOBlockOutHeader {\n\n typ: u32,\n\n reserved: u32,\n\n sector: usize,\n\n}\n\n\n\nimpl VirtIOBlockOutHeader {\n\n const fn zero() -> Self {\n\n Self {\n\n typ: 0,\n\n reserved: 0,\n\n sector: 0,\n\n }\n\n }\n\n\n\n fn new(write: bool, sector: usize) -> Self {\n\n let typ = if write {\n\n VIRTIO_BLK_T_OUT\n\n } else {\n\n VIRTIO_BLK_T_IN\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 17, "score": 93240.44952311137 }, { "content": "struct buf {\n\n int valid; // has data been read from disk?\n\n int disk; // does disk \"own\" buf?\n\n uint dev;\n\n uint blockno;\n\n struct sleeplock lock;\n\n uint refcnt;\n\n struct buf *prev; // LRU cache list\n\n struct buf *next;\n\n uchar data[BSIZE];\n", "file_path": "kernel/buf.h", "rank": 18, "score": 84989.49931967877 }, { "content": "static struct disk {\n\n // the virtio driver and device mostly communicate through a set of\n\n // structures in RAM. pages[] allocates that memory. pages[] is a\n\n // global (instead of calls to kalloc()) because it must consist of\n\n // two contiguous pages of page-aligned physical memory.\n\n char pages[2*PGSIZE];\n\n\n\n // pages[] is divided into three regions (descriptors, avail, and\n\n // used), as explained in Section 2.6 of the virtio specification\n\n // for the legacy interface.\n\n // https://docs.oasis-open.org/virtio/virtio/v1.1/virtio-v1.1.pdf\n\n \n\n // the first region of pages[] is a set (not a ring) of DMA\n\n // descriptors, with which the driver tells the device where to read\n\n // and write individual disk operations. there are NUM descriptors.\n\n // most commands consist of a \"chain\" (a linked list) of a couple of\n\n // these descriptors.\n\n // points into pages[].\n\n struct virtq_desc *desc;\n\n\n\n // next is a ring in which the driver writes descriptor numbers\n\n // that the driver would like the device to process. it only\n\n // includes the head descriptor of each chain. the ring has\n\n // NUM elements.\n\n // points into pages[].\n\n struct virtq_avail *avail;\n\n\n\n // finally a ring in which the device writes descriptor numbers that\n\n // the device has finished processing (just the head of each chain).\n\n // there are NUM used ring entries.\n\n // points into pages[].\n\n struct virtq_used *used;\n\n\n\n // our own book-keeping.\n\n char free[NUM]; // is a descriptor free?\n\n uint16 used_idx; // we've looked this far in used[2..NUM].\n\n\n\n // track info about in-flight operations,\n\n // for use when completion interrupt arrives.\n\n // indexed by first descriptor index of chain.\n\n struct {\n\n struct buf *b;\n\n char status;\n\n } info[NUM];\n\n\n\n // disk command headers.\n\n // one-for-one with descriptors, for convenience.\n\n struct virtio_blk_req ops[NUM];\n\n \n\n struct spinlock vdisk_lock;\n\n \n", "file_path": "kernel/virtio_disk.c", "rank": 19, "score": 83574.02492545801 }, { "content": "pub trait VAddr: Copy + Add<usize, Output = Self> {\n\n fn new(value: usize) -> Self;\n\n\n\n fn into_usize(&self) -> usize;\n\n\n\n fn is_null(&self) -> bool;\n\n\n\n fn is_page_aligned(&self) -> bool;\n\n\n\n /// Copy from either a user address, or kernel address.\n\n /// Returns Ok(()) on success, Err(()) on error.\n\n unsafe fn copyin(dst: &mut [u8], src: Self) -> Result<(), ()>;\n\n\n\n /// Copy to either a user address, or kernel address.\n\n /// Returns Ok(()) on success, Err(()) on error.\n\n unsafe fn copyout(dst: Self, src: &[u8]) -> Result<(), ()>;\n\n}\n\n\n\nimpl VAddr for KVAddr {\n\n fn new(value: usize) -> Self {\n", "file_path": "kernel-rs/src/vm.rs", "rank": 20, "score": 80799.03235176978 }, { "content": " struct virtq_used *used;\n", "file_path": "kernel/virtio_disk.c", "rank": 21, "score": 77730.87710238472 }, { "content": "#[inline]\n\npub fn px<A: VAddr>(level: usize, va: A) -> usize {\n\n (va.into_usize() >> pxshift(level)) & PXMASK\n\n}\n\n\n\n/// One beyond the highest possible virtual address.\n\n/// MAXVA is actually one bit less than the max allowed by\n\n/// Sv39, to avoid having to sign-extend virtual addresses\n\n/// that have the high bit set.\n\npub const MAXVA: usize = (1) << (9 + 9 + 9 + 12 - 1);\n\n\n\npub type PteT = usize;\n", "file_path": "kernel-rs/src/riscv.rs", "rank": 22, "score": 77727.10562561841 }, { "content": " uint16 used_idx; // we've looked this far in used[2..NUM].\n", "file_path": "kernel/virtio_disk.c", "rank": 23, "score": 74837.38145779309 }, { "content": "#define NBUF (MAXOPBLOCKS*3) // size of disk block cache\n", "file_path": "kernel/param.h", "rank": 24, "score": 73432.1685344086 }, { "content": "#define BSIZE 1024 // block size\n\n\n", "file_path": "kernel/fs.h", "rank": 25, "score": 73432.1685344086 }, { "content": " int valid; // inode has been read from disk?\n", "file_path": "kernel/file.h", "rank": 26, "score": 73423.37889228493 }, { "content": " char data[PIPESIZE];\n", "file_path": "kernel/pipe.c", "rank": 27, "score": 73423.37889228493 }, { "content": " int dev; // File system's disk device\n", "file_path": "kernel/stat.h", "rank": 28, "score": 73407.15806970597 }, { "content": " int dev;\n", "file_path": "kernel/log.c", "rank": 29, "score": 73407.15806970597 }, { "content": " uint dev; // Device number\n", "file_path": "kernel/file.h", "rank": 30, "score": 73407.15806970597 }, { "content": " short type; // copy of disk inode\n", "file_path": "kernel/file.h", "rank": 31, "score": 73341.13713102837 }, { "content": " uint32 type;\n", "file_path": "kernel/elf.h", "rank": 32, "score": 73336.38769068585 }, { "content": " int type;\n", "file_path": "user/sh.c", "rank": 33, "score": 73336.38769068585 }, { "content": " short type; // File type\n", "file_path": "kernel/fs.h", "rank": 34, "score": 73336.38769068585 }, { "content": " short type; // Type of file\n", "file_path": "kernel/stat.h", "rank": 35, "score": 73336.38769068585 }, { "content": " uint32 type; // VIRTIO_BLK_T_IN or ..._OUT\n", "file_path": "kernel/virtio.h", "rank": 36, "score": 73336.38769068585 }, { "content": " char buf[INPUT_BUF];\n", "file_path": "kernel/console.c", "rank": 37, "score": 73335.35441838964 }, { "content": " struct buf buf[NBUF];\n", "file_path": "kernel/bio.c", "rank": 38, "score": 73335.35441838964 }, { "content": "char buf[512];\n", "file_path": "user/wc.c", "rank": 39, "score": 73335.35441838964 }, { "content": "char buf[1024];\n", "file_path": "user/grep.c", "rank": 40, "score": 73335.35441838964 }, { "content": "char buf[512];\n", "file_path": "user/cat.c", "rank": 41, "score": 73335.35441838964 }, { "content": "struct buf;\n", "file_path": "kernel/defs.h", "rank": 42, "score": 73335.35441838964 }, { "content": "char buf[BUFSZ];\n", "file_path": "user/usertests.c", "rank": 43, "score": 73335.35441838964 }, { "content": "struct Run {\n\n next: *mut Run,\n\n}\n\n\n\npub struct Kmem {\n\n head: *mut Run,\n\n}\n\n\n\nimpl Kmem {\n\n pub const fn new() -> Self {\n\n Self {\n\n head: ptr::null_mut(),\n\n }\n\n }\n\n\n\n pub unsafe fn free(&mut self, pa: Page) {\n\n let mut r = pa.into_usize() as *mut Run;\n\n (*r).next = self.head;\n\n self.head = r;\n\n }\n", "file_path": "kernel-rs/src/kalloc.rs", "rank": 44, "score": 64089.97571867595 }, { "content": "/// Proc::info's spinlock must be held when using these.\n\nstruct ProcInfo {\n\n /// Process state.\n\n state: Procstate,\n\n\n\n /// If non-zero, sleeping on waitchannel.\n\n waitchannel: *const WaitChannel,\n\n\n\n /// Waitchannel saying child proc is dead.\n\n child_waitchannel: WaitChannel,\n\n\n\n /// Exit status to be returned to parent's wait.\n\n xstate: i32,\n\n\n\n /// Process ID.\n\n pid: i32,\n\n}\n\n\n\n/// Proc::data are private to the process, so lock need not be held.\n\npub struct ProcData {\n\n /// Virtual address of kernel stack.\n", "file_path": "kernel-rs/src/proc.rs", "rank": 45, "score": 62529.57444922613 }, { "content": "/// Assumption: `ptr` is `myproc()`, and ptr->info's spinlock is held.\n\nstruct ProcGuard {\n\n ptr: *const Proc,\n\n}\n\n\n\nimpl ProcGuard {\n\n fn deref_info(&self) -> &ProcInfo {\n\n unsafe { (*self.ptr).info.get_mut_unchecked() }\n\n }\n\n\n\n fn deref_mut_info(&mut self) -> &mut ProcInfo {\n\n unsafe { (*self.ptr).info.get_mut_unchecked() }\n\n }\n\n\n\n unsafe fn from_raw(ptr: *const Proc) -> Self {\n\n Self { ptr }\n\n }\n\n\n\n fn raw(&self) -> *const Proc {\n\n self.ptr\n\n }\n", "file_path": "kernel-rs/src/proc.rs", "rank": 46, "score": 62525.138227522024 }, { "content": "#[repr(C)]\n\nstruct ProgHdr {\n\n typ: u32,\n\n flags: ProgFlags,\n\n off: usize,\n\n vaddr: usize,\n\n paddr: usize,\n\n filesz: usize,\n\n memsz: usize,\n\n align: usize,\n\n}\n\n\n\nimpl ElfHdr {\n\n pub fn is_valid(&self) -> bool {\n\n self.magic == ELF_MAGIC\n\n }\n\n}\n\n\n\nimpl ProgHdr {\n\n pub fn is_prog_load(&self) -> bool {\n\n self.typ == ELF_PROG_LOAD\n", "file_path": "kernel-rs/src/exec.rs", "rank": 47, "score": 62525.138227522024 }, { "content": "/// Long-term locks for processes\n\nstruct RawSleeplock {\n\n /// Process holding lock. `-1` means unlocked.\n\n locked: Sleepablelock<i32>,\n\n\n\n /// Name of lock for debugging.\n\n name: &'static str,\n\n}\n\n\n\nimpl RawSleeplock {\n\n pub const fn new(name: &'static str) -> Self {\n\n Self {\n\n locked: Sleepablelock::new(\"sleep lock\", -1),\n\n name,\n\n }\n\n }\n\n\n\n pub fn acquire(&self) {\n\n let mut guard = self.locked.lock();\n\n while *guard != -1 {\n\n guard.sleep();\n", "file_path": "kernel-rs/src/sleeplock.rs", "rank": 48, "score": 62525.138227522024 }, { "content": "#[repr(C)]\n\nstruct ElfHdr {\n\n /// must equal ELF_MAGIC\n\n magic: u32,\n\n elf: [u8; 12],\n\n typ: u16,\n\n machine: u16,\n\n version: u32,\n\n entry: usize,\n\n phoff: usize,\n\n shoff: usize,\n\n flags: u32,\n\n ehsize: u16,\n\n phentsize: u16,\n\n phnum: u16,\n\n shentsize: u16,\n\n shnum: u16,\n\n shstrndx: u16,\n\n}\n\n\n\nbitflags! {\n", "file_path": "kernel-rs/src/exec.rs", "rank": 49, "score": 62525.138227522024 }, { "content": "/// Contents of the header block, used for the on-disk header block.\n\nstruct LogHeader {\n\n n: u32,\n\n block: [u32; LOGSIZE],\n\n}\n\n\n\n// `LogHeader` must be fit in a block.\n\nconst_assert!(mem::size_of::<LogHeader>() < BSIZE);\n\n\n\nimpl Log {\n\n pub fn new(dev: u32, start: i32, size: i32) -> Self {\n\n let mut log = Self {\n\n dev,\n\n start,\n\n size,\n\n outstanding: 0,\n\n committing: false,\n\n lh: ArrayVec::new(),\n\n };\n\n unsafe {\n\n log.recover_from_log();\n", "file_path": "kernel-rs/src/fs/log.rs", "rank": 50, "score": 61085.524522084204 }, { "content": "#[inline]\n\nfn pxshift(level: usize) -> usize {\n\n PGSHIFT + 9 * level\n\n}\n\n\n", "file_path": "kernel-rs/src/riscv.rs", "rank": 51, "score": 48946.85002919113 }, { "content": "void\n\nvirtio_disk_init(void)\n\n{\n\n uint32 status = 0;\n\n\n\n initlock(&disk.vdisk_lock, \"virtio_disk\");\n\n\n\n if(*R(VIRTIO_MMIO_MAGIC_VALUE) != 0x74726976 ||\n\n *R(VIRTIO_MMIO_VERSION) != 1 ||\n\n *R(VIRTIO_MMIO_DEVICE_ID) != 2 ||\n\n *R(VIRTIO_MMIO_VENDOR_ID) != 0x554d4551){\n\n panic(\"could not find virtio disk\");\n\n }\n\n \n\n status |= VIRTIO_CONFIG_S_ACKNOWLEDGE;\n\n *R(VIRTIO_MMIO_STATUS) = status;\n\n\n\n status |= VIRTIO_CONFIG_S_DRIVER;\n\n *R(VIRTIO_MMIO_STATUS) = status;\n\n\n\n // negotiate features\n\n uint64 features = *R(VIRTIO_MMIO_DEVICE_FEATURES);\n\n features &= ~(1 << VIRTIO_BLK_F_RO);\n\n features &= ~(1 << VIRTIO_BLK_F_SCSI);\n\n features &= ~(1 << VIRTIO_BLK_F_CONFIG_WCE);\n\n features &= ~(1 << VIRTIO_BLK_F_MQ);\n\n features &= ~(1 << VIRTIO_F_ANY_LAYOUT);\n\n features &= ~(1 << VIRTIO_RING_F_EVENT_IDX);\n\n features &= ~(1 << VIRTIO_RING_F_INDIRECT_DESC);\n\n *R(VIRTIO_MMIO_DRIVER_FEATURES) = features;\n\n\n\n // tell device that feature negotiation is complete.\n\n status |= VIRTIO_CONFIG_S_FEATURES_OK;\n\n *R(VIRTIO_MMIO_STATUS) = status;\n\n\n\n // tell device we're completely ready.\n\n status |= VIRTIO_CONFIG_S_DRIVER_OK;\n\n *R(VIRTIO_MMIO_STATUS) = status;\n\n\n\n *R(VIRTIO_MMIO_GUEST_PAGE_SIZE) = PGSIZE;\n\n\n\n // initialize queue 0.\n\n *R(VIRTIO_MMIO_QUEUE_SEL) = 0;\n\n uint32 max = *R(VIRTIO_MMIO_QUEUE_NUM_MAX);\n\n if(max == 0)\n\n panic(\"virtio disk has no queue 0\");\n\n if(max < NUM)\n\n panic(\"virtio disk max queue too short\");\n\n *R(VIRTIO_MMIO_QUEUE_NUM) = NUM;\n\n memset(disk.pages, 0, sizeof(disk.pages));\n\n *R(VIRTIO_MMIO_QUEUE_PFN) = ((uint64)disk.pages) >> PGSHIFT;\n\n\n\n // desc = pages -- num * virtq_desc\n\n // avail = pages + 0x40 -- 2 * uint16, then num * uint16\n\n // used = pages + 4096 -- 2 * uint16, then num * vRingUsedElem\n\n\n\n disk.desc = (struct virtq_desc *) disk.pages;\n\n disk.avail = (struct virtq_avail *)(disk.pages + NUM*sizeof(struct virtq_desc));\n\n disk.used = (struct virtq_used *) (disk.pages + PGSIZE);\n\n\n\n // all NUM descriptors start out unused.\n\n for(int i = 0; i < NUM; i++)\n\n disk.free[i] = 1;\n\n\n\n // plic.c and trap.c arrange for interrupts from VIRTIO0_IRQ.\n", "file_path": "kernel/virtio_disk.c", "rank": 52, "score": 48228.726998324644 }, { "content": "void\n\nvirtio_disk_rw(struct buf *b, int write)\n\n{\n\n uint64 sector = b->blockno * (BSIZE / 512);\n\n\n\n acquire(&disk.vdisk_lock);\n\n\n\n // the spec's Section 5.2 says that legacy block operations use\n\n // three descriptors: one for type/reserved/sector, one for the\n\n // data, one for a 1-byte status result.\n\n\n\n // allocate the three descriptors.\n\n int idx[3];\n\n while(1){\n\n if(alloc3_desc(idx) == 0) {\n\n break;\n\n }\n\n sleep(&disk.free[0], &disk.vdisk_lock);\n\n }\n\n\n\n // format the three descriptors.\n\n // qemu's virtio-blk.c reads them.\n\n\n\n struct virtio_blk_req *buf0 = &disk.ops[idx[0]];\n\n\n\n if(write)\n\n buf0->type = VIRTIO_BLK_T_OUT; // write the disk\n\n else\n\n buf0->type = VIRTIO_BLK_T_IN; // read the disk\n\n buf0->reserved = 0;\n\n buf0->sector = sector;\n\n\n\n disk.desc[idx[0]].addr = (uint64) buf0;\n\n disk.desc[idx[0]].len = sizeof(struct virtio_blk_req);\n\n disk.desc[idx[0]].flags = VRING_DESC_F_NEXT;\n\n disk.desc[idx[0]].next = idx[1];\n\n\n\n disk.desc[idx[1]].addr = (uint64) b->data;\n\n disk.desc[idx[1]].len = BSIZE;\n\n if(write)\n\n disk.desc[idx[1]].flags = 0; // device reads b->data\n\n else\n\n disk.desc[idx[1]].flags = VRING_DESC_F_WRITE; // device writes b->data\n\n disk.desc[idx[1]].flags |= VRING_DESC_F_NEXT;\n\n disk.desc[idx[1]].next = idx[2];\n\n\n\n disk.info[idx[0]].status = 0xff; // device writes 0 on success\n\n disk.desc[idx[2]].addr = (uint64) &disk.info[idx[0]].status;\n\n disk.desc[idx[2]].len = 1;\n\n disk.desc[idx[2]].flags = VRING_DESC_F_WRITE; // device writes the status\n\n disk.desc[idx[2]].next = 0;\n\n\n\n // record struct buf for virtio_disk_intr().\n\n b->disk = 1;\n\n disk.info[idx[0]].b = b;\n\n\n\n // tell the device the first index in our chain of descriptors.\n\n disk.avail->ring[disk.avail->idx % NUM] = idx[0];\n\n\n\n __sync_synchronize();\n\n\n\n // tell the device another avail ring entry is available.\n\n disk.avail->idx += 1; // not % NUM ...\n\n\n\n __sync_synchronize();\n\n\n\n *R(VIRTIO_MMIO_QUEUE_NOTIFY) = 0; // value is queue number\n\n\n\n // Wait for virtio_disk_intr() to say request has finished.\n\n while(b->disk == 1) {\n\n sleep(b, &disk.vdisk_lock);\n\n }\n\n\n\n disk.info[idx[0]].b = 0;\n\n free_chain(idx[0]);\n\n\n\n release(&disk.vdisk_lock);\n", "file_path": "kernel/virtio_disk.c", "rank": 53, "score": 48228.726998324644 }, { "content": "void\n\nvirtio_disk_intr()\n\n{\n\n acquire(&disk.vdisk_lock);\n\n\n\n // the device won't raise another interrupt until we tell it\n\n // we've seen this interrupt, which the following line does.\n\n // this may race with the device writing new entries to\n\n // the \"used\" ring, in which case we may process the new\n\n // completion entries in this interrupt, and have nothing to do\n\n // in the next interrupt, which is harmless.\n\n *R(VIRTIO_MMIO_INTERRUPT_ACK) = *R(VIRTIO_MMIO_INTERRUPT_STATUS) & 0x3;\n\n\n\n __sync_synchronize();\n\n\n\n // the device increments disk.used->idx when it\n\n // adds an entry to the used ring.\n\n\n\n while(disk.used_idx != disk.used->idx){\n\n __sync_synchronize();\n\n int id = disk.used->ring[disk.used_idx % NUM].id;\n\n\n\n if(disk.info[id].status != 0)\n\n panic(\"virtio_disk_intr status\");\n\n\n\n struct buf *b = disk.info[id].b;\n\n b->disk = 0; // disk is done with buf\n\n wakeup(b);\n\n\n\n disk.used_idx += 1;\n\n }\n\n\n\n release(&disk.vdisk_lock);\n", "file_path": "kernel/virtio_disk.c", "rank": 54, "score": 48228.726998324644 }, { "content": "#[cfg(not(test))]\n\n#[panic_handler]\n\nfn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {\n\n // Freeze other CPUs.\n\n kernel().panic();\n\n println!(\"{}\", info);\n\n\n\n crate::utils::spin_loop()\n\n}\n\n\n\n/// start() jumps here in supervisor mode on all CPUs.\n\npub unsafe fn kernel_main() -> ! {\n\n static STARTED: AtomicBool = AtomicBool::new(false);\n\n\n\n if cpuid() == 0 {\n\n // Initialize the kernel.\n\n\n\n // Console.\n\n Uart::init();\n\n consoleinit(&mut KERNEL.devsw);\n\n\n\n println!();\n", "file_path": "kernel-rs/src/kernel.rs", "rank": 55, "score": 42438.59997965993 }, { "content": " }\n\n}\n\n\n\nimpl<A: Arena, T: Deref<Target = A>> Rc<A, T> {\n\n pub unsafe fn from_unchecked(tag: T, inner: <<T as Deref>::Target as Arena>::Handle) -> Self {\n\n let inner = ManuallyDrop::new(inner);\n\n Self { tag, inner }\n\n }\n\n}\n\n\n\nimpl<A: Arena, T: Clone + Deref<Target = A>> Clone for Rc<A, T> {\n\n fn clone(&self) -> Self {\n\n let tag = self.tag.clone();\n\n let inner = ManuallyDrop::new(unsafe { tag.deref().dup(&self.inner) });\n\n Self { tag, inner }\n\n }\n\n}\n\n\n\nimpl<A: Arena, T: Clone + Deref<Target = A>> Arena for T {\n\n type Data = A::Data;\n", "file_path": "kernel-rs/src/arena.rs", "rank": 56, "score": 42164.30715248392 }, { "content": " {\n\n guard.reacquire_after(f)\n\n }\n\n}\n\n\n\nimpl<A: Arena, T: Deref<Target = A>> Deref for Rc<A, T> {\n\n type Target = <A as Arena>::Handle;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n self.inner.deref()\n\n }\n\n}\n\n\n\nimpl<A: Arena, T: Deref<Target = A>> Drop for Rc<A, T> {\n\n fn drop(&mut self) {\n\n // SAFETY: We can ensure the box is allocated from `self.tag` by the invariant of `Tag`.\n\n //\n\n // Drop AFTER the arena guard is dropped, as dropping val may cause the current thread\n\n // sleep.\n\n let _val = unsafe { self.tag.dealloc(ManuallyDrop::take(&mut self.inner)) };\n", "file_path": "kernel-rs/src/arena.rs", "rank": 57, "score": 42159.303287122624 }, { "content": " type Handle = Rc<A, T>;\n\n type Guard<'s> = <A as Arena>::Guard<'s>;\n\n\n\n fn unforget<C: Fn(&Self::Data) -> bool>(&self, c: C) -> Option<Self::Handle> {\n\n let tag = self.clone();\n\n let inner = ManuallyDrop::new(tag.deref().unforget(c)?);\n\n Some(Self::Handle { tag, inner })\n\n }\n\n\n\n fn find_or_alloc<C: Fn(&Self::Data) -> bool, N: FnOnce(&mut Self::Data)>(\n\n &self,\n\n c: C,\n\n n: N,\n\n ) -> Option<Self::Handle> {\n\n let tag = self.clone();\n\n let inner = ManuallyDrop::new(tag.deref().find_or_alloc(c, n)?);\n\n Some(Self::Handle { tag, inner })\n\n }\n\n\n\n fn alloc<F: FnOnce(&mut Self::Data)>(&self, f: F) -> Option<Self::Handle> {\n", "file_path": "kernel-rs/src/arena.rs", "rank": 58, "score": 42156.57253234703 }, { "content": "}\n\n\n\nimpl<T> ArrayEntry<T> {\n\n pub const fn new(data: T) -> Self {\n\n Self { refcnt: 0, data }\n\n }\n\n}\n\n\n\nimpl<T, const CAPACITY: usize> ArrayArena<T, CAPACITY> {\n\n // TODO(rv6): unsafe...\n\n pub const fn new(entries: [ArrayEntry<T>; CAPACITY]) -> Self {\n\n Self { entries }\n\n }\n\n}\n\n\n\nimpl<T> Deref for ArrayPtr<T> {\n\n type Target = T;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n unsafe { &(*self.ptr).data }\n", "file_path": "kernel-rs/src/arena.rs", "rank": 59, "score": 42152.69092628851 }, { "content": " for entry in &mut self.entries {\n\n self.head.prepend(&mut entry.list_entry);\n\n }\n\n }\n\n}\n\n\n\nimpl<T> Deref for MruPtr<T> {\n\n type Target = T;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n unsafe { &(*self.ptr).data }\n\n }\n\n}\n\n\n\nimpl<T> Drop for MruPtr<T> {\n\n fn drop(&mut self) {\n\n // HACK(@efenniht): we really need linear type here:\n\n // https://github.com/rust-lang/rfcs/issues/814\n\n panic!(\"MruPtr must never drop: use MruArena::dealloc instead.\");\n\n }\n", "file_path": "kernel-rs/src/arena.rs", "rank": 60, "score": 42152.41049475544 }, { "content": " }\n\n}\n\n\n\nimpl<T> Drop for ArrayPtr<T> {\n\n fn drop(&mut self) {\n\n // HACK(@efenniht): we really need linear type here:\n\n // https://github.com/rust-lang/rfcs/issues/814\n\n panic!(\"ArrayPtr must never drop: use ArrayArena::dealloc instead.\");\n\n }\n\n}\n\n\n\nimpl<T: 'static + ArenaObject, const CAPACITY: usize> Arena for Spinlock<ArrayArena<T, CAPACITY>> {\n\n type Data = T;\n\n type Handle = ArrayPtr<T>;\n\n type Guard<'s> = SpinlockGuard<'s, ArrayArena<T, CAPACITY>>;\n\n\n\n fn unforget<C: Fn(&Self::Data) -> bool>(&self, c: C) -> Option<Self::Handle> {\n\n let mut this = self.lock();\n\n\n\n for entry in &mut this.entries {\n", "file_path": "kernel-rs/src/arena.rs", "rank": 61, "score": 42149.34306015929 }, { "content": "pub struct MruEntry<T> {\n\n list_entry: ListEntry,\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 MruArena<T, const CAPACITY: usize> {\n\n entries: [MruEntry<T>; CAPACITY],\n\n head: ListEntry,\n\n}\n\n\n\npub struct MruPtr<T> {\n\n ptr: *mut MruEntry<T>,\n\n _marker: PhantomData<T>,\n\n}\n\n\n\npub struct Rc<A: Arena, T: Deref<Target = A>> {\n\n tag: T,\n\n inner: ManuallyDrop<<<T as Deref>::Target as Arena>::Handle>,\n", "file_path": "kernel-rs/src/arena.rs", "rank": 62, "score": 42149.183046002625 }, { "content": " let tag = self.clone();\n\n let inner = ManuallyDrop::new(tag.deref().alloc(f)?);\n\n Some(Self::Handle { tag, inner })\n\n }\n\n\n\n unsafe fn dup(&self, handle: &Self::Handle) -> Self::Handle {\n\n let tag = self.clone();\n\n let inner = ManuallyDrop::new(self.deref().dup(&handle.inner));\n\n Self::Handle { tag, inner }\n\n }\n\n\n\n /// # Safety\n\n ///\n\n /// `pbox` must be allocated from the pool.\n\n unsafe fn dealloc(&self, mut pbox: Self::Handle) {\n\n self.deref().dealloc(ManuallyDrop::take(&mut pbox.inner))\n\n }\n\n\n\n fn reacquire_after<'s, 'g: 's, F, R: 's>(guard: &'s mut Self::Guard<'g>, f: F) -> R\n\n where\n\n F: FnOnce() -> R,\n\n {\n\n A::reacquire_after(guard, f)\n\n }\n\n}\n", "file_path": "kernel-rs/src/arena.rs", "rank": 63, "score": 42148.68943364792 }, { "content": " let entry = unsafe {\n\n &mut *((list_entry as *const _ as usize - Self::LIST_ENTRY_OFFSET)\n\n as *mut MruEntry<T>)\n\n };\n\n if c(&entry.data) {\n\n debug_assert!(entry.refcnt != 0);\n\n return Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n });\n\n }\n\n list_entry = list_entry.next();\n\n }\n\n\n\n None\n\n }\n\n\n\n fn find_or_alloc<C: Fn(&Self::Data) -> bool, N: FnOnce(&mut Self::Data)>(\n\n &self,\n\n c: C,\n", "file_path": "kernel-rs/src/arena.rs", "rank": 64, "score": 42144.91542112677 }, { "content": " Self {\n\n refcnt: 0,\n\n data,\n\n list_entry: ListEntry::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl<T, const CAPACITY: usize> MruArena<T, CAPACITY> {\n\n // TODO(rv6): unsafe...\n\n pub const fn new(entries: [MruEntry<T>; CAPACITY]) -> Self {\n\n Self {\n\n entries,\n\n head: ListEntry::new(),\n\n }\n\n }\n\n\n\n pub fn init(&mut self) {\n\n self.head.init();\n\n\n", "file_path": "kernel-rs/src/arena.rs", "rank": 65, "score": 42144.621440557305 }, { "content": " if entry.refcnt != 0 && c(&entry.data) {\n\n return Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n });\n\n }\n\n }\n\n\n\n None\n\n }\n\n\n\n fn find_or_alloc<C: Fn(&Self::Data) -> bool, N: FnOnce(&mut Self::Data)>(\n\n &self,\n\n c: C,\n\n n: N,\n\n ) -> Option<Self::Handle> {\n\n let mut this = self.lock();\n\n\n\n let mut empty: *mut ArrayEntry<T> = ptr::null_mut();\n\n for entry in &mut this.entries {\n", "file_path": "kernel-rs/src/arena.rs", "rank": 66, "score": 42143.7819688699 }, { "content": "\n\n None\n\n }\n\n\n\n unsafe fn dup(&self, handle: &Self::Handle) -> Self::Handle {\n\n let mut _this = self.lock();\n\n\n\n // TODO: Make a MruArena trait and move this there.\n\n (*handle.ptr).refcnt += 1;\n\n Self::Handle {\n\n ptr: handle.ptr,\n\n _marker: PhantomData,\n\n }\n\n }\n\n\n\n /// # Safety\n\n ///\n\n /// `rc` must be allocated from `self`.\n\n unsafe fn dealloc(&self, handle: Self::Handle) {\n\n let mut this = self.lock();\n", "file_path": "kernel-rs/src/arena.rs", "rank": 67, "score": 42143.506915101876 }, { "content": " None\n\n }\n\n\n\n unsafe fn dup(&self, handle: &Self::Handle) -> Self::Handle {\n\n let mut _this = self.lock();\n\n\n\n // TODO: Make a ArrayArena trait and move this there.\n\n (*handle.ptr).refcnt += 1;\n\n Self::Handle {\n\n ptr: handle.ptr,\n\n _marker: PhantomData,\n\n }\n\n }\n\n\n\n /// # Safety\n\n ///\n\n /// `rc` must be allocated from `self`.\n\n unsafe fn dealloc(&self, handle: Self::Handle) {\n\n let mut this = self.lock();\n\n\n", "file_path": "kernel-rs/src/arena.rs", "rank": 68, "score": 42143.506915101876 }, { "content": " let entry = &mut *handle.ptr;\n\n if entry.refcnt == 1 {\n\n entry.data.finalize::<Self>(&mut this);\n\n }\n\n\n\n let entry = &mut *handle.ptr;\n\n entry.refcnt -= 1;\n\n mem::forget(handle);\n\n }\n\n\n\n fn reacquire_after<'s, 'g: 's, F, R: 's>(guard: &'s mut Self::Guard<'g>, f: F) -> R\n\n where\n\n F: FnOnce() -> R,\n\n {\n\n guard.reacquire_after(f)\n\n }\n\n}\n\n\n\nimpl<T> MruEntry<T> {\n\n pub const fn new(data: T) -> Self {\n", "file_path": "kernel-rs/src/arena.rs", "rank": 69, "score": 42143.00560738349 }, { "content": "use crate::list::*;\n\nuse crate::spinlock::{Spinlock, SpinlockGuard};\n\nuse core::marker::PhantomData;\n\nuse core::mem::{self, ManuallyDrop};\n\nuse core::ops::Deref;\n\nuse core::ptr;\n\n\n\n/// A homogeneous memory allocator, equipped with the box type representing an allocation.\n", "file_path": "kernel-rs/src/arena.rs", "rank": 70, "score": 42141.20080097019 }, { "content": " /// Failable allocation.\n\n fn alloc<F: FnOnce(&mut Self::Data)>(&self, f: F) -> Option<Self::Handle>;\n\n\n\n /// # Safety\n\n ///\n\n /// `handle` must be allocated from `self`.\n\n unsafe fn dup(&self, handle: &Self::Handle) -> Self::Handle;\n\n\n\n /// # Safety\n\n ///\n\n /// `pbox` must be allocated from the pool.\n\n ///\n\n /// Returns whether the object is finalized.\n\n unsafe fn dealloc(&self, pbox: Self::Handle);\n\n\n\n fn reacquire_after<'s, 'g: 's, F, R: 's>(guard: &'s mut Self::Guard<'g>, f: F) -> R\n\n where\n\n F: FnOnce() -> R;\n\n}\n\n\n", "file_path": "kernel-rs/src/arena.rs", "rank": 71, "score": 42140.987130413574 }, { "content": "}\n\n\n\nimpl<T: 'static + ArenaObject, const CAPACITY: usize> Spinlock<MruArena<T, CAPACITY>> {\n\n // TODO(rv6): a workarond for https://github.com/Gilnaa/memoffset/issues/49. Assumes\n\n // `list_entry` is located at the beginning of `MruEntry`.\n\n const LIST_ENTRY_OFFSET: usize = 0;\n\n // const LIST_ENTRY_OFFSET: usize = offset_of!(MruEntry<T>, list_entry);\n\n}\n\n\n\nimpl<T: 'static + ArenaObject, const CAPACITY: usize> Arena for Spinlock<MruArena<T, CAPACITY>> {\n\n type Data = T;\n\n type Handle = MruPtr<T>;\n\n type Guard<'s> = SpinlockGuard<'s, MruArena<T, CAPACITY>>;\n\n\n\n fn unforget<C: Fn(&Self::Data) -> bool>(&self, c: C) -> Option<Self::Handle> {\n\n let this = self.lock();\n\n\n\n // Is the block already cached?\n\n let mut list_entry = this.head.next();\n\n while list_entry as *const _ != &this.head as *const _ {\n", "file_path": "kernel-rs/src/arena.rs", "rank": 72, "score": 42140.383793075955 }, { "content": "\n\n fn alloc<F: FnOnce(&mut T)>(&self, f: F) -> Option<Self::Handle> {\n\n let this = self.lock();\n\n\n\n let mut list_entry = this.head.prev();\n\n while list_entry as *const _ != &this.head as *const _ {\n\n let entry = unsafe {\n\n &mut *((list_entry as *const _ as usize - Self::LIST_ENTRY_OFFSET)\n\n as *mut MruEntry<T>)\n\n };\n\n if entry.refcnt == 0 {\n\n entry.refcnt = 1;\n\n f(&mut entry.data);\n\n return Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n });\n\n }\n\n list_entry = list_entry.prev();\n\n }\n", "file_path": "kernel-rs/src/arena.rs", "rank": 73, "score": 42139.86800401891 }, { "content": " Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n })\n\n }\n\n\n\n fn alloc<F: FnOnce(&mut T)>(&self, f: F) -> Option<Self::Handle> {\n\n let mut this = self.lock();\n\n\n\n for entry in &mut this.entries {\n\n if entry.refcnt == 0 {\n\n entry.refcnt = 1;\n\n f(&mut entry.data);\n\n return Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n });\n\n }\n\n }\n\n\n", "file_path": "kernel-rs/src/arena.rs", "rank": 74, "score": 42139.71492331988 }, { "content": " n: N,\n\n ) -> Option<Self::Handle> {\n\n // Look through buffer cache for block on device dev.\n\n // If not found, allocate a buffer.\n\n // In either case, return locked buffer.\n\n\n\n let this = self.lock();\n\n\n\n // Is the block already cached?\n\n let mut list_entry = this.head.next();\n\n let mut empty = ptr::null_mut();\n\n while list_entry as *const _ != &this.head as *const _ {\n\n let entry = unsafe {\n\n &mut *((list_entry as *const _ as usize - Self::LIST_ENTRY_OFFSET)\n\n as *mut MruEntry<T>)\n\n };\n\n if c(&entry.data) {\n\n entry.refcnt += 1;\n\n return Some(Self::Handle {\n\n ptr: entry,\n", "file_path": "kernel-rs/src/arena.rs", "rank": 75, "score": 42138.18454433365 }, { "content": " if entry.refcnt != 0 {\n\n if c(&entry.data) {\n\n entry.refcnt += 1;\n\n return Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n });\n\n }\n\n } else if empty.is_null() {\n\n empty = entry;\n\n }\n\n }\n\n\n\n if empty.is_null() {\n\n return None;\n\n }\n\n\n\n let entry = unsafe { &mut *empty };\n\n entry.refcnt = 1;\n\n n(&mut entry.data);\n", "file_path": "kernel-rs/src/arena.rs", "rank": 76, "score": 42137.774222818036 }, { "content": " _marker: PhantomData,\n\n });\n\n } else if entry.refcnt == 0 {\n\n empty = entry;\n\n }\n\n list_entry = list_entry.next();\n\n }\n\n\n\n if empty.is_null() {\n\n return None;\n\n }\n\n\n\n let entry = unsafe { &mut *empty };\n\n entry.refcnt = 1;\n\n n(&mut entry.data);\n\n Some(Self::Handle {\n\n ptr: entry,\n\n _marker: PhantomData,\n\n })\n\n }\n", "file_path": "kernel-rs/src/arena.rs", "rank": 77, "score": 42137.4735482173 }, { "content": "\n\n let entry = &mut *handle.ptr;\n\n if entry.refcnt == 1 {\n\n entry.data.finalize::<Self>(&mut this);\n\n }\n\n\n\n let entry = &mut *handle.ptr;\n\n entry.refcnt -= 1;\n\n\n\n if entry.refcnt == 0 {\n\n entry.list_entry.remove();\n\n this.head.prepend(&mut entry.list_entry);\n\n }\n\n\n\n mem::forget(handle);\n\n }\n\n\n\n fn reacquire_after<'s, 'g: 's, F, R: 's>(guard: &'s mut Self::Guard<'g>, f: F) -> R\n\n where\n\n F: FnOnce() -> R,\n", "file_path": "kernel-rs/src/arena.rs", "rank": 78, "score": 42136.56309536642 }, { "content": "char zeroes[BSIZE];\n", "file_path": "mkfs/mkfs.c", "rank": 79, "score": 40517.63676274679 }, { "content": "struct {\n\n struct spinlock lock;\n\n struct buf buf[NBUF];\n\n\n\n // Linked list of all buffers, through prev/next.\n\n // Sorted by how recently the buffer was used.\n\n // head.next is most recent, head.prev is least.\n\n struct buf head;\n", "file_path": "kernel/bio.c", "rank": 80, "score": 40517.63676274679 }, { "content": "#!/usr/bin/env python3\n\n\n\nimport os, re, sys, glob\n\nfrom collections import defaultdict\n\n\n\npath = 'kernel-rs/**/*.rs'\n\n\n\nif len(sys.argv) > 1:\n\n path = sys.argv[1]\n\n\n\nif os.system('which count-unsafe > /dev/null 2>&1') != 0:\n\n print('''Please install count-unsafe by\\n\n\n`rustup update nightly && cargo +nightly install --git https://github.com/efenniht/count-unsafe`''')\n\n exit(-1)\n\n\n\nif os.system('which cloc > /dev/null 2>&1') != 0:\n\n print('''Please install cloc by `apt install cloc`''')\n\n exit(-1)\n\n\n\nspace = re.compile(r'\\s+')\n\n\n\nunsafes = defaultdict(lambda: 0)\n\n\n\nfor line in os.popen(f'count-unsafe {path}').readlines()[1:]:\n\n file, begin, end, cnt, ty = line.split(',')\n\n\n\n unsafes[file] += int(cnt)\n\n\n\nslocs = {}\n\n\n\nfor file in glob.glob(path, recursive=True):\n\n stat = os.popen(f'cloc {file}').readlines()[-2].strip()\n\n sloc = int(space.split(stat)[-1])\n\n\n\n slocs[file] = sloc\n\n\n\n print(f'{file} : {unsafes[file]}/{sloc} = {unsafes[file]*100//sloc}')\n\n\n\nprint('Total:')\n\n\n\nprint(f'{sum(unsafes.values())}/{sum(slocs.values())}')\n", "file_path": "count_unsafe.py", "rank": 81, "score": 40517.63676274679 }, { "content": " uint refcnt;\n", "file_path": "kernel/buf.h", "rank": 82, "score": 40450.989835193555 }, { "content": " struct sleeplock lock;\n", "file_path": "kernel/buf.h", "rank": 83, "score": 40450.989835193555 }, { "content": " struct buf *next;\n", "file_path": "kernel/buf.h", "rank": 84, "score": 40450.989835193555 }, { "content": " struct buf *prev; // LRU cache list\n", "file_path": "kernel/buf.h", "rank": 85, "score": 40450.989835193555 }, { "content": " mem::forget(desc);\n\n }\n\n}\n\n\n\nimpl Sleepablelock<Disk> {\n\n /// Return a locked Buf with the `latest` contents of the indicated block.\n\n /// If buf.valid is true, we don't need to access Disk.\n\n pub fn read(&self, dev: u32, blockno: u32) -> Buf<'static> {\n\n let mut buf = kernel().bcache.get_buf(dev, blockno).lock();\n\n if !buf.deref_inner().valid {\n\n unsafe {\n\n Disk::virtio_rw(&mut self.lock(), &mut buf, false);\n\n }\n\n buf.deref_mut_inner().valid = true;\n\n }\n\n buf\n\n }\n\n\n\n pub fn write(&self, b: &mut Buf<'static>) {\n\n unsafe { Disk::virtio_rw(&mut self.lock(), b, true) }\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 86, "score": 40394.244204155475 }, { "content": " let buf = &mut *self.info[id].b;\n\n\n\n // disk is done with buf\n\n buf.deref_mut_inner().disk = false;\n\n buf.vdisk_request_waitchannel.wakeup();\n\n\n\n self.used_idx += 1;\n\n }\n\n }\n\n}\n\n\n\nimpl InflightInfo {\n\n const fn zero() -> Self {\n\n Self {\n\n b: ptr::null_mut(),\n\n status: false,\n\n }\n\n }\n\n}\n\n\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 87, "score": 40386.7271064888 }, { "content": " }\n\n}\n\n\n\nimpl Disk {\n\n pub const fn zero() -> Self {\n\n Self {\n\n desc: DescriptorPool::zero(),\n\n avail: ptr::null_mut(),\n\n used: ptr::null_mut(),\n\n used_idx: 0,\n\n info: [InflightInfo::zero(); NUM],\n\n ops: [VirtIOBlockOutHeader::zero(); NUM],\n\n }\n\n }\n\n\n\n pub unsafe fn virtio_rw(\n\n this: &mut SleepablelockGuard<'_, Self>,\n\n b: &mut Buf<'static>,\n\n write: bool,\n\n ) {\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 88, "score": 40384.165453537236 }, { "content": " unsafe { &*self.ptr }\n\n }\n\n}\n\n\n\nimpl DerefMut for Descriptor {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n unsafe { &mut *self.ptr }\n\n }\n\n}\n\n\n\nimpl Drop for Descriptor {\n\n fn drop(&mut self) {\n\n // HACK(@efenniht): we really need linear type here:\n\n // https://github.com/rust-lang/rfcs/issues/814\n\n panic!(\"Descriptor must never drop: use DescriptorPool::free instead.\");\n\n }\n\n}\n\n\n\nimpl DescriptorPool {\n\n const fn zero() -> Self {\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 89, "score": 40382.452608485975 }, { "content": " };\n\n\n\n Self {\n\n typ,\n\n reserved: 0,\n\n sector,\n\n }\n\n }\n\n}\n\n\n\nimpl Descriptor {\n\n unsafe fn new(idx: usize, ptr: *mut VirtqDesc) -> Self {\n\n Self { idx, ptr }\n\n }\n\n}\n\n\n\nimpl Deref for Descriptor {\n\n type Target = VirtqDesc;\n\n\n\n fn deref(&self) -> &Self::Target {\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 90, "score": 40375.12506133103 }, { "content": "/// Driver for qemu's virtio disk device.\n\n/// Uses qemu's mmio interface to virtio.\n\n/// qemu presents a \"legacy\" virtio interface.\n\n///\n\n/// qemu ... -drive file=fs.img,if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0\n\nuse crate::{\n\n bio::Buf,\n\n kernel::kernel,\n\n page::RawPage,\n\n param::BSIZE,\n\n riscv::{PGSHIFT, PGSIZE},\n\n sleepablelock::{Sleepablelock, SleepablelockGuard},\n\n virtio::*,\n\n};\n\n\n\nuse core::array::IntoIter;\n\nuse core::mem;\n\nuse core::ops::{Deref, DerefMut};\n\nuse core::ptr;\n\nuse core::sync::atomic::{fence, Ordering};\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 91, "score": 40368.294102137545 }, { "content": " let sector: usize = (*b).blockno.wrapping_mul((BSIZE / 512) as u32) as _;\n\n\n\n // The spec's Section 5.2 says that legacy block operations use\n\n // three descriptors: one for type/reserved/sector, one for the\n\n // data, one for a 1-byte status result.\n\n\n\n // Allocate the three descriptors.\n\n let mut desc = loop {\n\n match this.desc.alloc_three_sectors() {\n\n Some(idx) => break idx,\n\n None => {\n\n this.wakeup();\n\n this.sleep();\n\n }\n\n }\n\n };\n\n\n\n // Format the three descriptors.\n\n // qemu's virtio-blk.c reads them.\n\n\n", "file_path": "kernel-rs/src/virtio_disk.rs", "rank": 92, "score": 40365.41978735182 }, { "content": "\n\nimpl FsTransaction<'_> {\n\n /// Caller has modified b->data and is done with the buffer.\n\n /// Record the block number and pin in the cache by increasing refcnt.\n\n /// commit()/write_log() will do the disk write.\n\n ///\n\n /// write() replaces write(); a typical use is:\n\n /// bp = kernel().file_system.disk.read(...)\n\n /// modify bp->data[]\n\n /// write(bp)\n\n unsafe fn write(&self, b: Buf<'static>) {\n\n self.fs.log().lock().write(b);\n\n }\n\n\n\n /// Zero a block.\n\n unsafe fn bzero(&self, dev: u32, bno: u32) {\n\n let mut buf = kernel().bcache.get_buf(dev, bno).lock();\n\n ptr::write_bytes(buf.deref_mut_inner().data.as_mut_ptr(), 0, BSIZE);\n\n buf.deref_mut_inner().valid = true;\n\n self.write(buf);\n", "file_path": "kernel-rs/src/fs/mod.rs", "rank": 98, "score": 39.223611207170364 } ]
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 = \"Reset value of the register\"]\n\n fn reset_value() -> Self::Type;\n\n}\n\n#[doc = \"This structure provides volatile access to register\"]\n\npub struct Reg<U, REG> {\n\n register: vcell::VolatileCell<U>,\n\n _marker: marker::PhantomData<REG>,\n\n}\n\nunsafe impl<U: Send, REG> Send for Reg<U, REG> {}\n\nimpl<U, REG> Reg<U, REG>\n\nwhere\n\n Self: Readable,\n\n U: Copy,\n\n{\n\n #[doc = \"Reads the contents of `Readable` register\"]\n\n #[doc = \"\"]\n\n #[doc = \"You can read the contents of a register in such way:\"]\n", "file_path": "src/generic.rs", "rank": 0, "score": 171985.54138555098 }, { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n println!(\"cargo:rustc-link-search={}\", out.display());\n\n println!(\"cargo:rerun-if-changed=device.x\");\n\n }\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n}\n", "file_path": "build.rs", "rank": 1, "score": 65686.33176443687 }, { "content": "#[doc = \"Reader of register VALUE\"]\n\npub type R = crate::R<u32, super::VALUE>;\n\n#[doc = \"Writer for register VALUE\"]\n\npub type W = crate::W<u32, super::VALUE>;\n\n#[doc = \"Register VALUE `reset()`'s with value 0xffff_ffff\"]\n\nimpl crate::ResetValue for super::VALUE {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0xffff_ffff\n\n }\n\n}\n\n#[doc = \"Reader of field `WDTVALUE`\"]\n\npub type WDTVALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `WDTVALUE`\"]\n\npub struct WDTVALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> WDTVALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/wdt/value.rs", "rank": 3, "score": 61029.9329813863 }, { "content": " #[inline(always)]\n\n pub unsafe fn bits(self, value: u32) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 0:31 - 31:0\\\\]\n\nThis register contains the current count value of the timer.\"]\n\n #[inline(always)]\n\n pub fn wdtvalue(&self) -> WDTVALUE_R {\n\n WDTVALUE_R::new((self.bits & 0xffff_ffff) as u32)\n\n }\n\n}\n\nimpl W {\n\n #[doc = \"Bits 0:31 - 31:0\\\\]\n\nThis register contains the current count value of the timer.\"]\n\n #[inline(always)]\n\n pub fn wdtvalue(&mut self) -> WDTVALUE_W {\n\n WDTVALUE_W { w: self }\n\n }\n\n}\n", "file_path": "src/wdt/value.rs", "rank": 4, "score": 61003.55201416244 }, { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "src/generic.rs", "rank": 10, "score": 60441.30014827357 }, { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "src/generic.rs", "rank": 11, "score": 60435.18781493757 }, { "content": "#[doc = \"Reader of register MPU_TYPE\"]\n\npub type R = crate::R<u32, super::MPU_TYPE>;\n\n#[doc = \"Writer for register MPU_TYPE\"]\n\npub type W = crate::W<u32, super::MPU_TYPE>;\n\n#[doc = \"Register MPU_TYPE `reset()`'s with value 0x0800\"]\n\nimpl crate::ResetValue for super::MPU_TYPE {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0x0800\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED24`\"]\n\npub type RESERVED24_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RESERVED24`\"]\n\npub struct RESERVED24_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED24_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 12, "score": 56840.86437806637 }, { "content": "#[doc = \"Reader of register FCFG_BNK_TYPE\"]\n\npub type R = crate::R<u32, super::FCFG_BNK_TYPE>;\n\n#[doc = \"Writer for register FCFG_BNK_TYPE\"]\n\npub type W = crate::W<u32, super::FCFG_BNK_TYPE>;\n\n#[doc = \"Register FCFG_BNK_TYPE `reset()`'s with value 0x04\"]\n\nimpl crate::ResetValue for super::FCFG_BNK_TYPE {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0x04\n\n }\n\n}\n\n#[doc = \"Reader of field `B7_TYPE`\"]\n\npub type B7_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B7_TYPE`\"]\n\npub struct B7_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> B7_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 13, "score": 56839.38334191685 }, { "content": "impl<'a> B4_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `B3_TYPE`\"]\n\npub type B3_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B3_TYPE`\"]\n\npub struct B3_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> B3_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12);\n\n self.w\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 14, "score": 56819.4459083927 }, { "content": " }\n\n}\n\n#[doc = \"Reader of field `B2_TYPE`\"]\n\npub type B2_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B2_TYPE`\"]\n\npub struct B2_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> B2_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `B1_TYPE`\"]\n\npub type B1_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B1_TYPE`\"]\n\npub struct B1_TYPE_W<'a> {\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 15, "score": 56818.72788828657 }, { "content": " #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `B6_TYPE`\"]\n\npub type B6_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B6_TYPE`\"]\n\npub struct B6_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> B6_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24);\n\n self.w\n\n }\n\n}\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 16, "score": 56818.67184811347 }, { "content": "#[doc = \"Reader of field `B5_TYPE`\"]\n\npub type B5_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B5_TYPE`\"]\n\npub struct B5_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> B5_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `B4_TYPE`\"]\n\npub type B4_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B4_TYPE`\"]\n\npub struct B4_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 17, "score": 56818.66508543187 }, { "content": " w: &'a mut W,\n\n}\n\nimpl<'a> B1_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `B0_TYPE`\"]\n\npub type B0_TYPE_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `B0_TYPE`\"]\n\npub struct B0_TYPE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> B0_TYPE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 18, "score": 56818.197980968995 }, { "content": " #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0xff << 24)) | (((value as u32) & 0xff) << 24);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `IREGION`\"]\n\npub type IREGION_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `IREGION`\"]\n\npub struct IREGION_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> IREGION_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16);\n\n self.w\n\n }\n\n}\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 19, "score": 56811.235087137175 }, { "content": "#[doc = \"Reader of field `DREGION`\"]\n\npub type DREGION_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `DREGION`\"]\n\npub struct DREGION_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> DREGION_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 20, "score": 56811.14246865808 }, { "content": "impl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub unsafe fn bits(self, value: u8) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !(0x7f << 1)) | (((value as u32) & 0x7f) << 1);\n\n self.w\n\n }\n\n}\n\n#[doc = \"Reader of field `SEPARATE`\"]\n\npub type SEPARATE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `SEPARATE`\"]\n\npub struct SEPARATE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SEPARATE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n\n #[inline(always)]\n\n pub fn set_bit(self) -> &'a mut W {\n\n self.bit(true)\n\n }\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 21, "score": 56810.30050234827 }, { "content": " self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 28:31 - 31:28\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b7_type(&self) -> B7_TYPE_R {\n\n B7_TYPE_R::new(((self.bits >> 28) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 24:27 - 27:24\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b6_type(&self) -> B6_TYPE_R {\n\n B6_TYPE_R::new(((self.bits >> 24) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 20:23 - 23:20\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 22, "score": 56804.129942405925 }, { "content": " #[doc = r\"Clears the field bit\"]\n\n #[inline(always)]\n\n pub fn clear_bit(self) -> &'a mut W {\n\n self.bit(false)\n\n }\n\n #[doc = r\"Writes raw bits to the field\"]\n\n #[inline(always)]\n\n pub fn bit(self, value: bool) -> &'a mut W {\n\n self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);\n\n self.w\n\n }\n\n}\n\nimpl R {\n\n #[doc = \"Bits 24:31 - 31:24\\\\]\n\nReads 0.\"]\n\n #[inline(always)]\n\n pub fn reserved24(&self) -> RESERVED24_R {\n\n RESERVED24_R::new(((self.bits >> 24) & 0xff) as u8)\n\n }\n\n #[doc = \"Bits 16:23 - 23:16\\\\]\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 23, "score": 56804.098483884176 }, { "content": " }\n\n #[doc = \"Bits 4:7 - 7:4\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b1_type(&self) -> B1_TYPE_R {\n\n B1_TYPE_R::new(((self.bits >> 4) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 0:3 - 3:0\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b0_type(&self) -> B0_TYPE_R {\n\n B0_TYPE_R::new((self.bits & 0x0f) as u8)\n\n }\n\n}\n\nimpl W {\n\n #[doc = \"Bits 28:31 - 31:28\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b7_type(&mut self) -> B7_TYPE_W {\n\n B7_TYPE_W { w: self }\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 24, "score": 56801.54500822248 }, { "content": " pub fn separate(&self) -> SEPARATE_R {\n\n SEPARATE_R::new((self.bits & 0x01) != 0)\n\n }\n\n}\n\nimpl W {\n\n #[doc = \"Bits 24:31 - 31:24\\\\]\n\nReads 0.\"]\n\n #[inline(always)]\n\n pub fn reserved24(&mut self) -> RESERVED24_W {\n\n RESERVED24_W { w: self }\n\n }\n\n #[doc = \"Bits 16:23 - 23:16\\\\]\n\nThe processor core uses only a unified MPU, this field always reads 0x0.\"]\n\n #[inline(always)]\n\n pub fn iregion(&mut self) -> IREGION_W {\n\n IREGION_W { w: self }\n\n }\n\n #[doc = \"Bits 8:15 - 15:8\\\\]\n\nNumber of supported MPU regions field. This field reads 0x08 indicating eight MPU regions.\"]\n\n #[inline(always)]\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 25, "score": 56792.792669335664 }, { "content": " pub fn b5_type(&self) -> B5_TYPE_R {\n\n B5_TYPE_R::new(((self.bits >> 20) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 16:19 - 19:16\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b4_type(&self) -> B4_TYPE_R {\n\n B4_TYPE_R::new(((self.bits >> 16) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 12:15 - 15:12\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b3_type(&self) -> B3_TYPE_R {\n\n B3_TYPE_R::new(((self.bits >> 12) & 0x0f) as u8)\n\n }\n\n #[doc = \"Bits 8:11 - 11:8\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b2_type(&self) -> B2_TYPE_R {\n\n B2_TYPE_R::new(((self.bits >> 8) & 0x0f) as u8)\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 26, "score": 56791.62009724162 }, { "content": "Internal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b3_type(&mut self) -> B3_TYPE_W {\n\n B3_TYPE_W { w: self }\n\n }\n\n #[doc = \"Bits 8:11 - 11:8\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b2_type(&mut self) -> B2_TYPE_W {\n\n B2_TYPE_W { w: self }\n\n }\n\n #[doc = \"Bits 4:7 - 7:4\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b1_type(&mut self) -> B1_TYPE_W {\n\n B1_TYPE_W { w: self }\n\n }\n\n #[doc = \"Bits 0:3 - 3:0\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b0_type(&mut self) -> B0_TYPE_W {\n\n B0_TYPE_W { w: self }\n\n }\n\n}\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 27, "score": 56791.2716035295 }, { "content": " }\n\n #[doc = \"Bits 24:27 - 27:24\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b6_type(&mut self) -> B6_TYPE_W {\n\n B6_TYPE_W { w: self }\n\n }\n\n #[doc = \"Bits 20:23 - 23:20\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b5_type(&mut self) -> B5_TYPE_W {\n\n B5_TYPE_W { w: self }\n\n }\n\n #[doc = \"Bits 16:19 - 19:16\\\\]\n\nInternal. Only to be used through TI provided API.\"]\n\n #[inline(always)]\n\n pub fn b4_type(&mut self) -> B4_TYPE_W {\n\n B4_TYPE_W { w: self }\n\n }\n\n #[doc = \"Bits 12:15 - 15:12\\\\]\n", "file_path": "src/flash/fcfg_bnk_type.rs", "rank": 28, "score": 56790.97083594839 }, { "content": " pub fn dregion(&mut self) -> DREGION_W {\n\n DREGION_W { w: self }\n\n }\n\n #[doc = \"Bits 1:7 - 7:1\\\\]\n\nReads 0.\"]\n\n #[inline(always)]\n\n pub fn reserved1(&mut self) -> RESERVED1_W {\n\n RESERVED1_W { w: self }\n\n }\n\n #[doc = \"Bit 0 - 0:0\\\\]\n\nThe processor core uses only a unified MPU, thus this field is always 0.\"]\n\n #[inline(always)]\n\n pub fn separate(&mut self) -> SEPARATE_W {\n\n SEPARATE_W { w: self }\n\n }\n\n}\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 29, "score": 56782.67457188003 }, { "content": "The processor core uses only a unified MPU, this field always reads 0x0.\"]\n\n #[inline(always)]\n\n pub fn iregion(&self) -> IREGION_R {\n\n IREGION_R::new(((self.bits >> 16) & 0xff) as u8)\n\n }\n\n #[doc = \"Bits 8:15 - 15:8\\\\]\n\nNumber of supported MPU regions field. This field reads 0x08 indicating eight MPU regions.\"]\n\n #[inline(always)]\n\n pub fn dregion(&self) -> DREGION_R {\n\n DREGION_R::new(((self.bits >> 8) & 0xff) as u8)\n\n }\n\n #[doc = \"Bits 1:7 - 7:1\\\\]\n\nReads 0.\"]\n\n #[inline(always)]\n\n pub fn reserved1(&self) -> RESERVED1_R {\n\n RESERVED1_R::new(((self.bits >> 1) & 0x7f) as u8)\n\n }\n\n #[doc = \"Bit 0 - 0:0\\\\]\n\nThe processor core uses only a unified MPU, thus this field is always 0.\"]\n\n #[inline(always)]\n", "file_path": "src/cpu_scs/mpu_type.rs", "rank": 30, "score": 56782.2961808963 }, { "content": "#[doc = \"Reader of register AESDATALEN1\"]\n\npub type R = crate::R<u32, super::AESDATALEN1>;\n\n#[doc = \"Writer for register AESDATALEN1\"]\n\npub type W = crate::W<u32, super::AESDATALEN1>;\n\n#[doc = \"Register AESDATALEN1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::AESDATALEN1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED29`\"]\n\npub type RESERVED29_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RESERVED29`\"]\n\npub struct RESERVED29_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED29_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/aesdatalen1.rs", "rank": 31, "score": 78.18219672471375 }, { "content": "#[doc = \"Reader of register REMAP\"]\n\npub type R = crate::R<u32, super::REMAP>;\n\n#[doc = \"Writer for register REMAP\"]\n\npub type W = crate::W<u32, super::REMAP>;\n\n#[doc = \"Register REMAP `reset()`'s with value 0x2000_0000\"]\n\nimpl crate::ResetValue for super::REMAP {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0x2000_0000\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED29`\"]\n\npub type RESERVED29_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RESERVED29`\"]\n\npub struct RESERVED29_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED29_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_fpb/remap.rs", "rank": 32, "score": 77.75488450350372 }, { "content": "#[doc = \"Reader of register MPU_RASR\"]\n\npub type R = crate::R<u32, super::MPU_RASR>;\n\n#[doc = \"Writer for register MPU_RASR\"]\n\npub type W = crate::W<u32, super::MPU_RASR>;\n\n#[doc = \"Register MPU_RASR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::MPU_RASR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED29`\"]\n\npub type RESERVED29_R = crate::R<u8, u8>;\n\n#[doc = \"Write proxy for field `RESERVED29`\"]\n\npub struct RESERVED29_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED29_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/mpu_rasr.rs", "rank": 33, "score": 76.91554205306718 }, { "content": "#[doc = \"Reader of register RESERVED3\"]\n\npub type R = crate::R<u32, super::RESERVED3>;\n\n#[doc = \"Writer for register RESERVED3\"]\n\npub type W = crate::W<u32, super::RESERVED3>;\n\n#[doc = \"Register RESERVED3 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED3 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart1/reserved3.rs", "rank": 34, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED4\"]\n\npub type R = crate::R<u32, super::RESERVED4>;\n\n#[doc = \"Writer for register RESERVED4\"]\n\npub type W = crate::W<u32, super::RESERVED4>;\n\n#[doc = \"Register RESERVED4 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED4 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart1/reserved4.rs", "rank": 35, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED1\"]\n\npub type R = crate::R<u32, super::RESERVED1>;\n\n#[doc = \"Writer for register RESERVED1\"]\n\npub type W = crate::W<u32, super::RESERVED1>;\n\n#[doc = \"Register RESERVED1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/ssi0/reserved1.rs", "rank": 36, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED2\"]\n\npub type R = crate::R<u32, super::RESERVED2>;\n\n#[doc = \"Writer for register RESERVED2\"]\n\npub type W = crate::W<u32, super::RESERVED2>;\n\n#[doc = \"Register RESERVED2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED2 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart1/reserved2.rs", "rank": 37, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED2\"]\n\npub type R = crate::R<u32, super::RESERVED2>;\n\n#[doc = \"Writer for register RESERVED2\"]\n\npub type W = crate::W<u32, super::RESERVED2>;\n\n#[doc = \"Register RESERVED2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED2 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/ssi1/reserved2.rs", "rank": 38, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED1\"]\n\npub type R = crate::R<u32, super::RESERVED1>;\n\n#[doc = \"Writer for register RESERVED1\"]\n\npub type W = crate::W<u32, super::RESERVED1>;\n\n#[doc = \"Register RESERVED1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/ssi1/reserved1.rs", "rank": 39, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED4\"]\n\npub type R = crate::R<u32, super::RESERVED4>;\n\n#[doc = \"Writer for register RESERVED4\"]\n\npub type W = crate::W<u32, super::RESERVED4>;\n\n#[doc = \"Register RESERVED4 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED4 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart0/reserved4.rs", "rank": 40, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED2\"]\n\npub type R = crate::R<u32, super::RESERVED2>;\n\n#[doc = \"Writer for register RESERVED2\"]\n\npub type W = crate::W<u32, super::RESERVED2>;\n\n#[doc = \"Register RESERVED2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED2 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart0/reserved2.rs", "rank": 41, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED1\"]\n\npub type R = crate::R<u32, super::RESERVED1>;\n\n#[doc = \"Writer for register RESERVED1\"]\n\npub type W = crate::W<u32, super::RESERVED1>;\n\n#[doc = \"Register RESERVED1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart0/reserved1.rs", "rank": 42, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED0\"]\n\npub type R = crate::R<u32, super::RESERVED0>;\n\n#[doc = \"Writer for register RESERVED0\"]\n\npub type W = crate::W<u32, super::RESERVED0>;\n\n#[doc = \"Register RESERVED0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED0 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart0/reserved0.rs", "rank": 43, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED0\"]\n\npub type R = crate::R<u32, super::RESERVED0>;\n\n#[doc = \"Writer for register RESERVED0\"]\n\npub type W = crate::W<u32, super::RESERVED0>;\n\n#[doc = \"Register RESERVED0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED0 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart1/reserved0.rs", "rank": 44, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED1\"]\n\npub type R = crate::R<u32, super::RESERVED1>;\n\n#[doc = \"Writer for register RESERVED1\"]\n\npub type W = crate::W<u32, super::RESERVED1>;\n\n#[doc = \"Register RESERVED1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart1/reserved1.rs", "rank": 45, "score": 72.35985858697923 }, { "content": "#[doc = \"Reader of register RESERVED3\"]\n\npub type R = crate::R<u32, super::RESERVED3>;\n\n#[doc = \"Writer for register RESERVED3\"]\n\npub type W = crate::W<u32, super::RESERVED3>;\n\n#[doc = \"Register RESERVED3 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED3 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/uart0/reserved3.rs", "rank": 46, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register RESERVED2\"]\n\npub type R = crate::R<u32, super::RESERVED2>;\n\n#[doc = \"Writer for register RESERVED2\"]\n\npub type W = crate::W<u32, super::RESERVED2>;\n\n#[doc = \"Register RESERVED2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED2 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\nimpl R {}\n\nimpl W {}\n", "file_path": "src/ssi0/reserved2.rs", "rank": 47, "score": 72.35985858697921 }, { "content": "#[doc = \"Reader of register OUT1\"]\n\npub type R = crate::R<u32, super::OUT1>;\n\n#[doc = \"Writer for register OUT1\"]\n\npub type W = crate::W<u32, super::OUT1>;\n\n#[doc = \"Register OUT1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OUT1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE_63_32`\"]\n\npub type VALUE_63_32_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE_63_32`\"]\n\npub struct VALUE_63_32_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_63_32_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/trng/out1.rs", "rank": 48, "score": 71.94173254777216 }, { "content": "#[doc = \"Reader of register CH2CMP\"]\n\npub type R = crate::R<u32, super::CH2CMP>;\n\n#[doc = \"Writer for register CH2CMP\"]\n\npub type W = crate::W<u32, super::CH2CMP>;\n\n#[doc = \"Register CH2CMP `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CH2CMP {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE`\"]\n\npub type VALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE`\"]\n\npub struct VALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/ch2cmp.rs", "rank": 49, "score": 71.94173254777215 }, { "content": "#[doc = \"Reader of register SEC\"]\n\npub type R = crate::R<u32, super::SEC>;\n\n#[doc = \"Writer for register SEC\"]\n\npub type W = crate::W<u32, super::SEC>;\n\n#[doc = \"Register SEC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SEC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE`\"]\n\npub type VALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE`\"]\n\npub struct VALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/sec.rs", "rank": 50, "score": 71.94173254777215 }, { "content": "#[doc = \"Reader of register CH0CMP\"]\n\npub type R = crate::R<u32, super::CH0CMP>;\n\n#[doc = \"Writer for register CH0CMP\"]\n\npub type W = crate::W<u32, super::CH0CMP>;\n\n#[doc = \"Register CH0CMP `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CH0CMP {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE`\"]\n\npub type VALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE`\"]\n\npub struct VALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/ch0cmp.rs", "rank": 51, "score": 71.94173254777216 }, { "content": "#[doc = \"Reader of register CH1CMP\"]\n\npub type R = crate::R<u32, super::CH1CMP>;\n\n#[doc = \"Writer for register CH1CMP\"]\n\npub type W = crate::W<u32, super::CH1CMP>;\n\n#[doc = \"Register CH1CMP `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CH1CMP {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE`\"]\n\npub type VALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE`\"]\n\npub struct VALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/ch1cmp.rs", "rank": 52, "score": 71.94173254777215 }, { "content": "#[doc = \"Reader of register SUBSEC\"]\n\npub type R = crate::R<u32, super::SUBSEC>;\n\n#[doc = \"Writer for register SUBSEC\"]\n\npub type W = crate::W<u32, super::SUBSEC>;\n\n#[doc = \"Register SUBSEC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SUBSEC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE`\"]\n\npub type VALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE`\"]\n\npub struct VALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/subsec.rs", "rank": 53, "score": 71.94173254777216 }, { "content": "#[doc = \"Reader of register OUT0\"]\n\npub type R = crate::R<u32, super::OUT0>;\n\n#[doc = \"Writer for register OUT0\"]\n\npub type W = crate::W<u32, super::OUT0>;\n\n#[doc = \"Register OUT0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::OUT0 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE_31_0`\"]\n\npub type VALUE_31_0_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE_31_0`\"]\n\npub struct VALUE_31_0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_31_0_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/trng/out0.rs", "rank": 54, "score": 71.94173254777218 }, { "content": "#[doc = \"Reader of register CH2CMPINC\"]\n\npub type R = crate::R<u32, super::CH2CMPINC>;\n\n#[doc = \"Writer for register CH2CMPINC\"]\n\npub type W = crate::W<u32, super::CH2CMPINC>;\n\n#[doc = \"Register CH2CMPINC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CH2CMPINC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `VALUE`\"]\n\npub type VALUE_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `VALUE`\"]\n\npub struct VALUE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> VALUE_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/ch2cmpinc.rs", "rank": 55, "score": 71.94173254777216 }, { "content": "#[doc = \"Reader of register SEQCTRL\"]\n\npub type R = crate::R<u32, super::SEQCTRL>;\n\n#[doc = \"Writer for register SEQCTRL\"]\n\npub type W = crate::W<u32, super::SEQCTRL>;\n\n#[doc = \"Register SEQCTRL `reset()`'s with value 0x0100\"]\n\nimpl crate::ResetValue for super::SEQCTRL {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0x0100\n\n }\n\n}\n\n#[doc = \"Reader of field `RESET`\"]\n\npub type RESET_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `RESET`\"]\n\npub struct RESET_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESET_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "src/pka/seqctrl.rs", "rank": 56, "score": 71.12180874457955 }, { "content": "#[doc = \"Reader of register TWOBIT\"]\n\npub type R = crate::R<u32, super::TWOBIT>;\n\n#[doc = \"Writer for register TWOBIT\"]\n\npub type W = crate::W<u32, super::TWOBIT>;\n\n#[doc = \"Register TWOBIT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TWOBIT {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `FROMN`\"]\n\npub type FROMN_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `FROMN`\"]\n\npub struct FROMN_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> FROMN_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/flash/twobit.rs", "rank": 57, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM3\"]\n\npub type R = crate::R<u32, super::STIM3>;\n\n#[doc = \"Writer for register STIM3\"]\n\npub type W = crate::W<u32, super::STIM3>;\n\n#[doc = \"Register STIM3 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM3 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM3`\"]\n\npub type STIM3_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM3`\"]\n\npub struct STIM3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM3_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim3.rs", "rank": 58, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register CTL\"]\n\npub type R = crate::R<u32, super::CTL>;\n\n#[doc = \"Writer for register CTL\"]\n\npub type W = crate::W<u32, super::CTL>;\n\n#[doc = \"Register CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CTL {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED2`\"]\n\npub type RESERVED2_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED2`\"]\n\npub struct RESERVED2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED2_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_batmon/ctl.rs", "rank": 59, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register BATMONP0\"]\n\npub type R = crate::R<u32, super::BATMONP0>;\n\n#[doc = \"Writer for register BATMONP0\"]\n\npub type W = crate::W<u32, super::BATMONP0>;\n\n#[doc = \"Register BATMONP0 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::BATMONP0 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED6`\"]\n\npub type RESERVED6_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED6`\"]\n\npub struct RESERVED6_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED6_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_batmon/batmonp0.rs", "rank": 60, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DMACH0CTL\"]\n\npub type R = crate::R<u32, super::DMACH0CTL>;\n\n#[doc = \"Writer for register DMACH0CTL\"]\n\npub type W = crate::W<u32, super::DMACH0CTL>;\n\n#[doc = \"Register DMACH0CTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DMACH0CTL {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED2`\"]\n\npub type RESERVED2_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED2`\"]\n\npub struct RESERVED2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED2_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/dmach0ctl.rs", "rank": 61, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM23\"]\n\npub type R = crate::R<u32, super::STIM23>;\n\n#[doc = \"Writer for register STIM23\"]\n\npub type W = crate::W<u32, super::STIM23>;\n\n#[doc = \"Register STIM23 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM23 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM23`\"]\n\npub type STIM23_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM23`\"]\n\npub struct STIM23_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM23_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim23.rs", "rank": 62, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM8\"]\n\npub type R = crate::R<u32, super::STIM8>;\n\n#[doc = \"Writer for register STIM8\"]\n\npub type W = crate::W<u32, super::STIM8>;\n\n#[doc = \"Register STIM8 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM8 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM8`\"]\n\npub type STIM8_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM8`\"]\n\npub struct STIM8_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM8_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim8.rs", "rank": 63, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register IRQEN\"]\n\npub type R = crate::R<u32, super::IRQEN>;\n\n#[doc = \"Writer for register IRQEN\"]\n\npub type W = crate::W<u32, super::IRQEN>;\n\n#[doc = \"Register IRQEN `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::IRQEN {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED2`\"]\n\npub type RESERVED2_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED2`\"]\n\npub struct RESERVED2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED2_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/irqen.rs", "rank": 64, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register BATTLL\"]\n\npub type R = crate::R<u32, super::BATTLL>;\n\n#[doc = \"Writer for register BATTLL\"]\n\npub type W = crate::W<u32, super::BATTLL>;\n\n#[doc = \"Register BATTLL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::BATTLL {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED11`\"]\n\npub type RESERVED11_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED11`\"]\n\npub struct RESERVED11_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED11_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_batmon/battll.rs", "rank": 65, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register SLEEPCNT\"]\n\npub type R = crate::R<u32, super::SLEEPCNT>;\n\n#[doc = \"Writer for register SLEEPCNT\"]\n\npub type W = crate::W<u32, super::SLEEPCNT>;\n\n#[doc = \"Register SLEEPCNT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SLEEPCNT {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED8`\"]\n\npub type RESERVED8_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED8`\"]\n\npub struct RESERVED8_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED8_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_dwt/sleepcnt.rs", "rank": 66, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register RIS\"]\n\npub type R = crate::R<u32, super::RIS>;\n\n#[doc = \"Writer for register RIS\"]\n\npub type W = crate::W<u32, super::RIS>;\n\n#[doc = \"Register RIS `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RIS {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED14`\"]\n\npub type RESERVED14_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED14`\"]\n\npub struct RESERVED14_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED14_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/gpt0/ris.rs", "rank": 67, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register MASK3\"]\n\npub type R = crate::R<u32, super::MASK3>;\n\n#[doc = \"Writer for register MASK3\"]\n\npub type W = crate::W<u32, super::MASK3>;\n\n#[doc = \"Register MASK3 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::MASK3 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED4`\"]\n\npub type RESERVED4_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED4`\"]\n\npub struct RESERVED4_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED4_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_dwt/mask3.rs", "rank": 68, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register RIS\"]\n\npub type R = crate::R<u32, super::RIS>;\n\n#[doc = \"Writer for register RIS\"]\n\npub type W = crate::W<u32, super::RIS>;\n\n#[doc = \"Register RIS `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RIS {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED14`\"]\n\npub type RESERVED14_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED14`\"]\n\npub struct RESERVED14_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED14_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/gpt1/ris.rs", "rank": 69, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register TPR\"]\n\npub type R = crate::R<u32, super::TPR>;\n\n#[doc = \"Writer for register TPR\"]\n\npub type W = crate::W<u32, super::TPR>;\n\n#[doc = \"Register TPR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TPR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED4`\"]\n\npub type RESERVED4_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED4`\"]\n\npub struct RESERVED4_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED4_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/tpr.rs", "rank": 70, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register KEYWRITEAREA\"]\n\npub type R = crate::R<u32, super::KEYWRITEAREA>;\n\n#[doc = \"Writer for register KEYWRITEAREA\"]\n\npub type W = crate::W<u32, super::KEYWRITEAREA>;\n\n#[doc = \"Register KEYWRITEAREA `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::KEYWRITEAREA {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED8`\"]\n\npub type RESERVED8_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED8`\"]\n\npub struct RESERVED8_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED8_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/keywritearea.rs", "rank": 71, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register SWRESET\"]\n\npub type R = crate::R<u32, super::SWRESET>;\n\n#[doc = \"Writer for register SWRESET\"]\n\npub type W = crate::W<u32, super::SWRESET>;\n\n#[doc = \"Register SWRESET `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SWRESET {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/swreset.rs", "rank": 72, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DFSR\"]\n\npub type R = crate::R<u32, super::DFSR>;\n\n#[doc = \"Writer for register DFSR\"]\n\npub type W = crate::W<u32, super::DFSR>;\n\n#[doc = \"Register DFSR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DFSR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED5`\"]\n\npub type RESERVED5_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED5`\"]\n\npub struct RESERVED5_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED5_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/dfsr.rs", "rank": 73, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DMASWRESET\"]\n\npub type R = crate::R<u32, super::DMASWRESET>;\n\n#[doc = \"Writer for register DMASWRESET\"]\n\npub type W = crate::W<u32, super::DMASWRESET>;\n\n#[doc = \"Register DMASWRESET `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DMASWRESET {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/dmaswreset.rs", "rank": 74, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register FSCR\"]\n\npub type R = crate::R<u32, super::FSCR>;\n\n#[doc = \"Writer for register FSCR\"]\n\npub type W = crate::W<u32, super::FSCR>;\n\n#[doc = \"Register FSCR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::FSCR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `FSCR`\"]\n\npub type FSCR_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `FSCR`\"]\n\npub struct FSCR_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> FSCR_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_tpiu/fscr.rs", "rank": 75, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register SYNC\"]\n\npub type R = crate::R<u32, super::SYNC>;\n\n#[doc = \"Writer for register SYNC\"]\n\npub type W = crate::W<u32, super::SYNC>;\n\n#[doc = \"Register SYNC `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYNC {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/sync.rs", "rank": 76, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register SYNCLF\"]\n\npub type R = crate::R<u32, super::SYNCLF>;\n\n#[doc = \"Writer for register SYNCLF\"]\n\npub type W = crate::W<u32, super::SYNCLF>;\n\n#[doc = \"Register SYNCLF `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SYNCLF {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_rtc/synclf.rs", "rank": 77, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register FBPROT\"]\n\npub type R = crate::R<u32, super::FBPROT>;\n\n#[doc = \"Writer for register FBPROT\"]\n\npub type W = crate::W<u32, super::FBPROT>;\n\n#[doc = \"Register FBPROT `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::FBPROT {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/flash/fbprot.rs", "rank": 78, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM16\"]\n\npub type R = crate::R<u32, super::STIM16>;\n\n#[doc = \"Writer for register STIM16\"]\n\npub type W = crate::W<u32, super::STIM16>;\n\n#[doc = \"Register STIM16 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM16 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM16`\"]\n\npub type STIM16_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM16`\"]\n\npub struct STIM16_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM16_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim16.rs", "rank": 79, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register ACTLR\"]\n\npub type R = crate::R<u32, super::ACTLR>;\n\n#[doc = \"Writer for register ACTLR\"]\n\npub type W = crate::W<u32, super::ACTLR>;\n\n#[doc = \"Register ACTLR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ACTLR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED10`\"]\n\npub type RESERVED10_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED10`\"]\n\npub struct RESERVED10_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED10_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/actlr.rs", "rank": 80, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DMACH0EXTADDR\"]\n\npub type R = crate::R<u32, super::DMACH0EXTADDR>;\n\n#[doc = \"Writer for register DMACH0EXTADDR\"]\n\npub type W = crate::W<u32, super::DMACH0EXTADDR>;\n\n#[doc = \"Register DMACH0EXTADDR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DMACH0EXTADDR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ADDR`\"]\n\npub type ADDR_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `ADDR`\"]\n\npub struct ADDR_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ADDR_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/dmach0extaddr.rs", "rank": 81, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register FPCAR\"]\n\npub type R = crate::R<u32, super::FPCAR>;\n\n#[doc = \"Writer for register FPCAR\"]\n\npub type W = crate::W<u32, super::FPCAR>;\n\n#[doc = \"Register FPCAR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::FPCAR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ADDRESS`\"]\n\npub type ADDRESS_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `ADDRESS`\"]\n\npub struct ADDRESS_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ADDRESS_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/fpcar.rs", "rank": 82, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DCRDR\"]\n\npub type R = crate::R<u32, super::DCRDR>;\n\n#[doc = \"Writer for register DCRDR\"]\n\npub type W = crate::W<u32, super::DCRDR>;\n\n#[doc = \"Register DCRDR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DCRDR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `DCRDR`\"]\n\npub type DCRDR_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `DCRDR`\"]\n\npub struct DCRDR_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> DCRDR_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/dcrdr.rs", "rank": 83, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register AUXSCECLK\"]\n\npub type R = crate::R<u32, super::AUXSCECLK>;\n\n#[doc = \"Writer for register AUXSCECLK\"]\n\npub type W = crate::W<u32, super::AUXSCECLK>;\n\n#[doc = \"Register AUXSCECLK `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::AUXSCECLK {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED9`\"]\n\npub type RESERVED9_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED9`\"]\n\npub struct RESERVED9_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED9_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_pmctl/auxsceclk.rs", "rank": 84, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register TAPR\"]\n\npub type R = crate::R<u32, super::TAPR>;\n\n#[doc = \"Writer for register TAPR\"]\n\npub type W = crate::W<u32, super::TAPR>;\n\n#[doc = \"Register TAPR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TAPR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED8`\"]\n\npub type RESERVED8_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED8`\"]\n\npub struct RESERVED8_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED8_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/gpt0/tapr.rs", "rank": 85, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM17\"]\n\npub type R = crate::R<u32, super::STIM17>;\n\n#[doc = \"Writer for register STIM17\"]\n\npub type W = crate::W<u32, super::STIM17>;\n\n#[doc = \"Register STIM17 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM17 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM17`\"]\n\npub type STIM17_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM17`\"]\n\npub struct STIM17_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM17_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim17.rs", "rank": 86, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register TRACECLKMUX\"]\n\npub type R = crate::R<u32, super::TRACECLKMUX>;\n\n#[doc = \"Writer for register TRACECLKMUX\"]\n\npub type W = crate::W<u32, super::TRACECLKMUX>;\n\n#[doc = \"Register TRACECLKMUX `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::TRACECLKMUX {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_tiprop/traceclkmux.rs", "rank": 87, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register SLEEPCTL\"]\n\npub type R = crate::R<u32, super::SLEEPCTL>;\n\n#[doc = \"Writer for register SLEEPCTL\"]\n\npub type W = crate::W<u32, super::SLEEPCTL>;\n\n#[doc = \"Register SLEEPCTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SLEEPCTL {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/aon_pmctl/sleepctl.rs", "rank": 88, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM14\"]\n\npub type R = crate::R<u32, super::STIM14>;\n\n#[doc = \"Writer for register STIM14\"]\n\npub type W = crate::W<u32, super::STIM14>;\n\n#[doc = \"Register STIM14 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM14 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM14`\"]\n\npub type STIM14_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM14`\"]\n\npub struct STIM14_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM14_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim14.rs", "rank": 89, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register ICLR\"]\n\npub type R = crate::R<u32, super::ICLR>;\n\n#[doc = \"Writer for register ICLR\"]\n\npub type W = crate::W<u32, super::ICLR>;\n\n#[doc = \"Register ICLR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ICLR {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED14`\"]\n\npub type RESERVED14_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED14`\"]\n\npub struct RESERVED14_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED14_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/gpt0/iclr.rs", "rank": 90, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DMAEV\"]\n\npub type R = crate::R<u32, super::DMAEV>;\n\n#[doc = \"Writer for register DMAEV\"]\n\npub type W = crate::W<u32, super::DMAEV>;\n\n#[doc = \"Register DMAEV `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DMAEV {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED12`\"]\n\npub type RESERVED12_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED12`\"]\n\npub struct RESERVED12_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED12_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/gpt1/dmaev.rs", "rank": 91, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM10\"]\n\npub type R = crate::R<u32, super::STIM10>;\n\n#[doc = \"Writer for register STIM10\"]\n\npub type W = crate::W<u32, super::STIM10>;\n\n#[doc = \"Register STIM10 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM10 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM10`\"]\n\npub type STIM10_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM10`\"]\n\npub struct STIM10_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM10_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim10.rs", "rank": 92, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register MAC_15_4_1\"]\n\npub type R = crate::R<u32, super::MAC_15_4_1>;\n\n#[doc = \"Writer for register MAC_15_4_1\"]\n\npub type W = crate::W<u32, super::MAC_15_4_1>;\n\n#[doc = \"Register MAC_15_4_1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::MAC_15_4_1 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `ADDR_32_63`\"]\n\npub type ADDR_32_63_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `ADDR_32_63`\"]\n\npub struct ADDR_32_63_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ADDR_32_63_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/fcfg1/mac_15_4_1.rs", "rank": 93, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register KEYWRITTENAREA\"]\n\npub type R = crate::R<u32, super::KEYWRITTENAREA>;\n\n#[doc = \"Writer for register KEYWRITTENAREA\"]\n\npub type W = crate::W<u32, super::KEYWRITTENAREA>;\n\n#[doc = \"Register KEYWRITTENAREA `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::KEYWRITTENAREA {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED8`\"]\n\npub type RESERVED8_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED8`\"]\n\npub struct RESERVED8_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED8_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/keywrittenarea.rs", "rank": 94, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register DMAPROTCTL\"]\n\npub type R = crate::R<u32, super::DMAPROTCTL>;\n\n#[doc = \"Writer for register DMAPROTCTL\"]\n\npub type W = crate::W<u32, super::DMAPROTCTL>;\n\n#[doc = \"Register DMAPROTCTL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DMAPROTCTL {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED1`\"]\n\npub type RESERVED1_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED1`\"]\n\npub struct RESERVED1_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED1_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/crypto/dmaprotctl.rs", "rank": 95, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM30\"]\n\npub type R = crate::R<u32, super::STIM30>;\n\n#[doc = \"Writer for register STIM30\"]\n\npub type W = crate::W<u32, super::STIM30>;\n\n#[doc = \"Register STIM30 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM30 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM30`\"]\n\npub type STIM30_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM30`\"]\n\npub struct STIM30_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM30_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim30.rs", "rank": 96, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register CFG\"]\n\npub type R = crate::R<u32, super::CFG>;\n\n#[doc = \"Writer for register CFG\"]\n\npub type W = crate::W<u32, super::CFG>;\n\n#[doc = \"Register CFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CFG {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED3`\"]\n\npub type RESERVED3_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED3`\"]\n\npub struct RESERVED3_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED3_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/gpt0/cfg.rs", "rank": 97, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register RESERVED000\"]\n\npub type R = crate::R<u32, super::RESERVED000>;\n\n#[doc = \"Writer for register RESERVED000\"]\n\npub type W = crate::W<u32, super::RESERVED000>;\n\n#[doc = \"Register RESERVED000 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::RESERVED000 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `RESERVED0`\"]\n\npub type RESERVED0_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `RESERVED0`\"]\n\npub struct RESERVED0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESERVED0_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_scs/reserved000.rs", "rank": 98, "score": 70.78403076489153 }, { "content": "#[doc = \"Reader of register STIM22\"]\n\npub type R = crate::R<u32, super::STIM22>;\n\n#[doc = \"Writer for register STIM22\"]\n\npub type W = crate::W<u32, super::STIM22>;\n\n#[doc = \"Register STIM22 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::STIM22 {\n\n type Type = u32;\n\n #[inline(always)]\n\n fn reset_value() -> Self::Type {\n\n 0\n\n }\n\n}\n\n#[doc = \"Reader of field `STIM22`\"]\n\npub type STIM22_R = crate::R<u32, u32>;\n\n#[doc = \"Write proxy for field `STIM22`\"]\n\npub struct STIM22_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> STIM22_W<'a> {\n\n #[doc = r\"Writes raw bits to the field\"]\n", "file_path": "src/cpu_itm/stim22.rs", "rank": 99, "score": 70.78403076489153 } ]
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);\n\n drop(builder);\n\n (auto, id)\n\n })\n\n .boxed()\n\n}\n\n\n", "file_path": "src/tests/arbitrary.rs", "rank": 0, "score": 125218.24145110953 }, { "content": "fn subi(con: Constraint) -> Result<Vec<Constraint>, ()> {\n\n match con {\n\n Constraint(\n\n Ty::Constructed(Constructed::Fun(d1, r1)),\n\n Ty::Constructed(Constructed::Fun(d2, r2)),\n\n ) => Ok(vec![Constraint(*d2, *d1), Constraint(*r1, *r2)]),\n\n Constraint(Ty::Constructed(Constructed::Bool), Ty::Constructed(Constructed::Bool)) => {\n\n Ok(vec![])\n\n }\n\n Constraint(\n\n Ty::Constructed(Constructed::Record(f1)),\n\n Ty::Constructed(Constructed::Record(f2)),\n\n ) => {\n\n if iter_set::difference(f2.keys(), f1.keys()).next().is_none() {\n\n Ok(iter_set::intersection(f1.keys(), f2.keys())\n\n .map(|key| Constraint(*f1[key].clone(), *f2[key].clone()))\n\n .collect())\n\n } else {\n\n Err(())\n\n }\n", "file_path": "src/biunify/reference.rs", "rank": 1, "score": 88668.48979423201 }, { "content": "pub fn arb_polar_ty(pol: Polarity) -> BoxedStrategy<Ty<Constructed, char>> {\n\n prop_oneof![\n\n LazyJust::new(|| Ty::Zero),\n\n prop::char::range('a', 'e').prop_map(Ty::UnboundVar),\n\n BoundVar.prop_map(Ty::BoundVar),\n\n ]\n\n .prop_recursive(32, 1000, 8, |inner| {\n\n prop_oneof![\n\n 3 => arb_polar_cons(inner.clone()).prop_map(Ty::Constructed),\n\n 1 => (inner.clone(), inner.clone()).prop_map(|(l, r)| Ty::Add(Box::new(l), Box::new(r))),\n\n 1 => inner.prop_map(Box::new).prop_map(Ty::Recursive),\n\n ]\n\n })\n\n .prop_filter(\"invalid polar type\", move |ty| check(pol, ty, &mut VecDeque::new(), 0))\n\n .boxed()\n\n}\n\n\n", "file_path": "src/tests/arbitrary.rs", "rank": 2, "score": 85705.87048227817 }, { "content": "fn atomic(con: &Constraint) -> Result<Bisubst, ()> {\n\n match con {\n\n &Constraint(Ty::UnboundVar(v), Ty::Constructed(_))\n\n | &Constraint(Ty::UnboundVar(v), Ty::UnboundVar(_)) => Ok(Bisubst::unit(\n\n v,\n\n Polarity::Neg,\n\n fixpoint(Ty::Add(\n\n Box::new(Ty::UnboundVar(v)),\n\n Box::new(bisubst(\n\n con.1.clone(),\n\n Polarity::Neg,\n\n (Polarity::Neg, v),\n\n Ty::BoundVar(0),\n\n )),\n\n )),\n\n )),\n\n &Constraint(Ty::Constructed(_), Ty::UnboundVar(v)) => Ok(Bisubst::unit(\n\n v,\n\n Polarity::Pos,\n\n fixpoint(Ty::Add(\n", "file_path": "src/biunify/reference.rs", "rank": 3, "score": 79796.47881424196 }, { "content": "pub trait Label: Clone {\n\n fn polarity(&self) -> Polarity;\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct ConstructorSet<C: Constructor> {\n\n set: SmallOrdSet<[KeyValuePair<C::Component, C>; 1]>,\n\n}\n\n\n\nimpl<C: Constructor> ConstructorSet<C> {\n\n pub fn iter(&self) -> impl Iterator<Item = &C> + Clone {\n\n self.set.values()\n\n }\n\n\n\n pub(crate) fn add(&mut self, pol: Polarity, con: Cow<C>) {\n\n match self.set.entry(con.component()) {\n\n small_ord_set::Entry::Occupied(mut entry) => entry.get_mut().join(&con, pol),\n\n small_ord_set::Entry::Vacant(entry) => {\n\n entry.insert(con.into_owned());\n\n }\n", "file_path": "src/cons.rs", "rank": 4, "score": 73489.83077399174 }, { "content": "fn shift(ty: &mut Ty<Constructed, char>, n: usize) {\n\n match ty {\n\n Ty::BoundVar(idx) => *idx += n,\n\n Ty::Add(l, r) => {\n\n shift(l, n);\n\n shift(r, n);\n\n }\n\n Ty::Constructed(Constructed::Fun(d, r)) => {\n\n shift(d, n);\n\n shift(r, n);\n\n }\n\n Ty::Constructed(Constructed::Record(fields)) => {\n\n fields.values_mut().for_each(|t| shift(t, n))\n\n }\n\n Ty::Recursive(t) => shift(t, n),\n\n _ => (),\n\n }\n\n}\n\n\n\npub(in crate::biunify) fn biunify(constraint: Constraint) -> Result<Bisubst, ()> {\n", "file_path": "src/biunify/reference.rs", "rank": 5, "score": 71030.72107607125 }, { "content": "pub trait Constructor: Clone + PartialOrd {\n\n type Component: Ord + Clone;\n\n type Label: Label;\n\n\n\n fn component(&self) -> Self::Component;\n\n fn join(&mut self, other: &Self, pol: Polarity);\n\n\n\n /// Visit the common type parameters of two constructors.\n\n fn visit_params_intersection<F, E>(&self, other: &Self, visit: F) -> Result<(), E>\n\n where\n\n F: FnMut(Self::Label, &StateSet, &StateSet) -> Result<(), E>;\n\n\n\n fn map<F>(self, mapper: F) -> Self\n\n where\n\n F: FnMut(Self::Label, StateSet) -> StateSet;\n\n}\n\n\n", "file_path": "src/cons.rs", "rank": 6, "score": 66597.91445644642 }, { "content": "#[derive(Debug)]\n\nstruct BoundVar;\n", "file_path": "src/tests/arbitrary.rs", "rank": 7, "score": 61323.76451175548 }, { "content": "fn bisubst(\n\n ty: Ty<Constructed, char>,\n\n pol: Polarity,\n\n var: (Polarity, char),\n\n mut sub: Ty<Constructed, char>,\n\n) -> Ty<Constructed, char> {\n\n match ty {\n\n Ty::Add(l, r) => Ty::Add(\n\n Box::new(bisubst(*l, pol, var, sub.clone())),\n\n Box::new(bisubst(*r, pol, var, sub)),\n\n ),\n\n Ty::Recursive(t) => {\n\n shift(&mut sub, 1);\n\n Ty::Recursive(Box::new(bisubst(*t, pol, var, sub)))\n\n }\n\n Ty::UnboundVar(v) if (pol, v) == var => sub,\n\n Ty::Constructed(Constructed::Fun(d, r)) => Ty::Constructed(Constructed::Fun(\n\n Box::new(bisubst(*d, -pol, var, sub.clone())),\n\n Box::new(bisubst(*r, pol, var, sub)),\n\n )),\n\n Ty::Constructed(Constructed::Record(fields)) => Ty::Constructed(Constructed::Record(\n\n fields\n\n .into_iter()\n\n .map(|(k, v)| (k, Box::new(bisubst(*v, pol, var, sub.clone()))))\n\n .collect(),\n\n )),\n\n _ => ty,\n\n }\n\n}\n\n\n", "file_path": "src/biunify/reference.rs", "rank": 8, "score": 61181.290566923286 }, { "content": "fn subst(\n\n ty: Ty<Constructed, char>,\n\n var: usize,\n\n sub: Ty<Constructed, char>,\n\n) -> Ty<Constructed, char> {\n\n match ty {\n\n Ty::Add(l, r) => Ty::Add(\n\n Box::new(subst(*l, var, sub.clone())),\n\n Box::new(subst(*r, var, sub)),\n\n ),\n\n Ty::Recursive(t) => Ty::Recursive(Box::new(subst(*t, var + 1, sub))),\n\n Ty::BoundVar(idx) if idx == var => sub,\n\n Ty::Constructed(Constructed::Fun(d, r)) => Ty::Constructed(Constructed::Fun(\n\n Box::new(subst(*d, var, sub.clone())),\n\n Box::new(subst(*r, var, sub)),\n\n )),\n\n Ty::Constructed(Constructed::Record(fields)) => Ty::Constructed(Constructed::Record(\n\n fields\n\n .into_iter()\n\n .map(|(k, v)| (k, Box::new(subst(*v, var, sub.clone()))))\n\n .collect(),\n\n )),\n\n _ => ty,\n\n }\n\n}\n\n\n", "file_path": "src/biunify/reference.rs", "rank": 9, "score": 61181.290566923286 }, { "content": "#[test]\n\nfn constructed() {\n\n let mut auto = Automaton::new();\n\n\n\n let mut builder = auto.builder();\n\n let lhs_id = builder.build_polar(\n\n Polarity::Pos,\n\n &Ty::Constructed(Constructed::Record(Default::default())),\n\n );\n\n let rhs_id = builder.build_polar(\n\n Polarity::Neg,\n\n &Ty::Add(\n\n Box::new(Ty::Zero),\n\n Box::new(Ty::Constructed(Constructed::Bool)),\n\n ),\n\n );\n\n drop(builder);\n\n\n\n assert!(auto.biunify(lhs_id, rhs_id).is_err());\n\n}\n\n\n", "file_path": "src/biunify/tests.rs", "rank": 10, "score": 60074.8669366213 }, { "content": "fn check(\n\n pol: Polarity,\n\n ty: &Ty<Constructed, char>,\n\n recs: &mut VecDeque<Polarity>,\n\n unguarded: usize,\n\n) -> bool {\n\n match ty {\n\n Ty::BoundVar(idx) => {\n\n if *idx < unguarded || *idx >= recs.len() {\n\n false\n\n } else {\n\n recs[*idx] == pol\n\n }\n\n }\n\n Ty::Constructed(Constructed::Fun(d, r)) => {\n\n check(-pol, d, recs, 0) && check(pol, r, recs, 0)\n\n }\n\n Ty::Constructed(Constructed::Record(fields)) => {\n\n fields.iter().all(|(_, t)| check(pol, t, recs, 0))\n\n }\n", "file_path": "src/tests/arbitrary.rs", "rank": 11, "score": 60071.80271315301 }, { "content": "struct BiMap {\n\n // maps nfa state set to corresponding dfa state\n\n ns2d: HashMap<Vec<StateId>, StateId>,\n\n // maps nfa state to set of dfa states containing it\n\n n2ds: HashMap<StateId, SmallOrdSet<[StateId; 4]>>,\n\n}\n\n\n\nimpl BiMap {\n\n fn with_capacity(cap: usize) -> Self {\n\n BiMap {\n\n ns2d: HashMap::with_capacity(cap),\n\n n2ds: HashMap::with_capacity(cap),\n\n }\n\n }\n\n\n\n fn insert(&mut self, ns: Vec<StateId>, d: StateId) {\n\n for &n in ns.iter() {\n\n self.n2ds.entry(n).or_default().insert(d);\n\n }\n\n self.ns2d.insert(ns, d);\n\n }\n\n}\n", "file_path": "src/auto/reduce/mod.rs", "rank": 12, "score": 58451.944633734354 }, { "content": "struct BoundVarTree(usize);\n\n\n\nimpl Strategy for BoundVar {\n\n type Tree = BoundVarTree;\n\n type Value = usize;\n\n\n\n fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> {\n\n let val: f64 = runner.rng().sample(Exp1);\n\n Ok(BoundVarTree(val as usize))\n\n }\n\n}\n\n\n\nimpl ValueTree for BoundVarTree {\n\n type Value = usize;\n\n\n\n fn current(&self) -> Self::Value {\n\n self.0\n\n }\n\n\n\n fn simplify(&mut self) -> bool {\n", "file_path": "src/tests/arbitrary.rs", "rank": 13, "score": 55424.48434443071 }, { "content": "fn arb_polar_cons(ty: BoxedStrategy<Ty<Constructed, char>>) -> BoxedStrategy<Constructed> {\n\n lazy_static! {\n\n static ref IDENT: SBoxedStrategy<Rc<str>> =\n\n string_regex(\"[a-z]\").unwrap().prop_map(Into::into).sboxed();\n\n }\n\n\n\n prop_oneof![\n\n LazyJust::new(|| Constructed::Bool),\n\n (ty.clone(), ty.clone()).prop_map(|(d, r)| Constructed::Fun(Box::new(d), Box::new(r))),\n\n btree_map(IDENT.clone(), ty.prop_map(Box::new), 0..8).prop_map(Constructed::Record)\n\n ]\n\n .boxed()\n\n}\n\n\n", "file_path": "src/tests/arbitrary.rs", "rank": 14, "score": 51974.840969686054 }, { "content": "mod arbitrary;\n\nmod build;\n\n\n\npub use self::arbitrary::{arb_auto_ty, arb_polar_ty};\n\npub use self::build::Constructed;\n\n\n\nuse std::cmp::Ordering;\n\nuse std::rc::Rc;\n\nuse std::vec;\n\n\n\nuse im::OrdMap;\n\nuse itertools::EitherOrBoth;\n\n\n\nuse crate::auto::StateSet;\n\nuse crate::Polarity;\n\n\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n\npub enum Constructor {\n\n Bool,\n\n Fun(StateSet, StateSet),\n", "file_path": "src/tests/mod.rs", "rank": 15, "score": 45444.744338815275 }, { "content": " F: FnMut(Self::Label, StateSet) -> StateSet,\n\n {\n\n match self {\n\n Constructor::Bool => Constructor::Bool,\n\n Constructor::Fun(d, r) => {\n\n Constructor::Fun(mapper(Label::Domain, d), mapper(Label::Range, r))\n\n }\n\n Constructor::Record(fields) => Constructor::Record(\n\n fields\n\n .into_iter()\n\n .map(|(label, set)| (label.clone(), mapper(Label::Label(label), set)))\n\n .collect(),\n\n ),\n\n }\n\n }\n\n}\n\n\n\nimpl Constructor {\n\n fn params(&self) -> Vec<(Label, StateSet)> {\n\n match self {\n", "file_path": "src/tests/mod.rs", "rank": 16, "score": 45443.335516045714 }, { "content": " })\n\n }\n\n },\n\n _ => unreachable!(),\n\n }\n\n }\n\n\n\n fn visit_params_intersection<F, E>(&self, other: &Self, mut visit: F) -> Result<(), E>\n\n where\n\n F: FnMut(Self::Label, &StateSet, &StateSet) -> Result<(), E>,\n\n {\n\n itertools::merge_join_by(self.params(), other.params(), |l, r| Ord::cmp(&l.0, &r.0))\n\n .try_for_each(|eob| match eob {\n\n EitherOrBoth::Both(l, r) => visit(l.0, &l.1, &r.1),\n\n _ => Ok(()),\n\n })\n\n }\n\n\n\n fn map<F>(self, mut mapper: F) -> Self\n\n where\n", "file_path": "src/tests/mod.rs", "rank": 17, "score": 45442.347009191406 }, { "content": " }\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]\n\npub enum Label {\n\n Domain,\n\n Range,\n\n Label(Rc<str>),\n\n}\n\n\n\nimpl crate::Label for Label {\n\n fn polarity(&self) -> Polarity {\n\n match self {\n\n Label::Domain => Polarity::Neg,\n\n Label::Range | Label::Label(_) => Polarity::Pos,\n\n }\n\n }\n\n}\n", "file_path": "src/tests/mod.rs", "rank": 18, "score": 45441.53890880879 }, { "content": " Record(OrdMap<Rc<str>, StateSet>),\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]\n\npub enum Component {\n\n Bool,\n\n Fun,\n\n Record,\n\n}\n\n\n\nimpl crate::Constructor for Constructor {\n\n type Label = Label;\n\n type Component = Component;\n\n\n\n fn component(&self) -> Self::Component {\n\n match self {\n\n Constructor::Bool => Component::Bool,\n\n Constructor::Fun(..) => Component::Fun,\n\n Constructor::Record(..) => Component::Record,\n\n }\n", "file_path": "src/tests/mod.rs", "rank": 19, "score": 45441.16600980364 }, { "content": " }\n\n\n\n fn join(&mut self, other: &Self, pol: Polarity) {\n\n match (self, other) {\n\n (Constructor::Bool, Constructor::Bool) => (),\n\n (Constructor::Fun(ld, lr), Constructor::Fun(rd, rr)) => {\n\n ld.union(rd);\n\n lr.union(rr);\n\n }\n\n (Constructor::Record(ref mut lhs), Constructor::Record(ref rhs)) => match pol {\n\n Polarity::Pos => {\n\n *lhs = lhs.clone().intersection_with(rhs.clone(), |mut l, r| {\n\n l.union(&r);\n\n l\n\n })\n\n }\n\n Polarity::Neg => {\n\n *lhs = lhs.clone().union_with(rhs.clone(), |mut l, r| {\n\n l.union(&r);\n\n l\n", "file_path": "src/tests/mod.rs", "rank": 20, "score": 45440.51621096471 }, { "content": " Constructor::Bool => vec![],\n\n Constructor::Fun(d, r) => vec![(Label::Domain, d.clone()), (Label::Range, r.clone())],\n\n Constructor::Record(fields) => fields\n\n .clone()\n\n .into_iter()\n\n .map(|(label, set)| (Label::Label(label), set))\n\n .collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl PartialOrd for Constructor {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n match (self, other) {\n\n (Constructor::Bool, Constructor::Bool) => Some(Ordering::Equal),\n\n (Constructor::Fun(..), Constructor::Fun(..)) => Some(Ordering::Equal),\n\n (Constructor::Record(ref lhs), Constructor::Record(ref rhs)) => {\n\n iter_set::cmp(lhs.keys(), rhs.keys()).map(Ordering::reverse)\n\n }\n\n _ => None,\n", "file_path": "src/tests/mod.rs", "rank": 21, "score": 45437.44736533161 }, { "content": "mod set;\n\n\n\npub use self::set::StateSet;\n\n\n\nuse std::ops::{Index, IndexMut, Range};\n\n\n\nuse crate::auto::{Automaton, ConstructorSet, FlowSet};\n\nuse crate::{Constructor, Polarity};\n\n\n\n#[derive(Debug)]\n\npub struct State<C: Constructor> {\n\n #[cfg(debug_assertions)]\n\n pub(crate) pol: Polarity,\n\n pub(crate) cons: ConstructorSet<C>,\n\n pub(crate) flow: FlowSet,\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]\n\npub struct StateId(u32);\n\n\n", "file_path": "src/auto/state/mod.rs", "rank": 22, "score": 44193.37468881683 }, { "content": "#[derive(Debug, Clone)]\n\npub struct StateRange(Range<u32>);\n\n\n\nimpl StateId {\n\n pub fn as_u32(self) -> u32 {\n\n self.0\n\n }\n\n\n\n pub fn shift(self, offset: u32) -> Self {\n\n StateId(self.0 + offset)\n\n }\n\n}\n\n\n\nimpl<C: Constructor> State<C> {\n\n pub(crate) fn new(_pol: Polarity) -> Self {\n\n State {\n\n #[cfg(debug_assertions)]\n\n pol: _pol,\n\n cons: ConstructorSet::default(),\n\n flow: FlowSet::default(),\n", "file_path": "src/auto/state/mod.rs", "rank": 23, "score": 44190.09273109188 }, { "content": "\n\nimpl<C: Constructor> Clone for State<C> {\n\n fn clone(&self) -> Self {\n\n State {\n\n #[cfg(debug_assertions)]\n\n pol: self.pol,\n\n cons: self.cons.clone(),\n\n flow: self.flow.clone(),\n\n }\n\n }\n\n}\n\n\n\nimpl<C: Constructor> Automaton<C> {\n\n pub(crate) fn next(&mut self) -> StateId {\n\n StateId(self.states.len() as u32)\n\n }\n\n\n\n pub(crate) fn add(&mut self, state: State<C>) -> StateId {\n\n let id = self.next();\n\n self.states.push(state);\n", "file_path": "src/auto/state/mod.rs", "rank": 24, "score": 44189.69311298086 }, { "content": "}\n\n\n\nimpl<C: Constructor> Index<StateId> for Automaton<C> {\n\n type Output = State<C>;\n\n\n\n fn index(&self, StateId(id): StateId) -> &Self::Output {\n\n self.states.index(id as usize)\n\n }\n\n}\n\n\n\nimpl<C: Constructor> IndexMut<StateId> for Automaton<C> {\n\n fn index_mut(&mut self, StateId(id): StateId) -> &mut Self::Output {\n\n self.states.index_mut(id as usize)\n\n }\n\n}\n\n\n\nimpl StateRange {\n\n pub fn shift(self, offset: u32) -> Self {\n\n StateRange((self.0.start + offset)..(self.0.end + offset))\n\n }\n", "file_path": "src/auto/state/mod.rs", "rank": 25, "score": 44188.66813964956 }, { "content": " id\n\n }\n\n\n\n pub fn add_from(&mut self, other: &Self) -> u32 {\n\n let offset = self.states.len() as u32;\n\n self.states.extend(\n\n other\n\n .states\n\n .iter()\n\n .cloned()\n\n .map(|state| state.shift(offset)),\n\n );\n\n offset\n\n }\n\n\n\n pub(crate) fn index_mut2(\n\n &mut self,\n\n StateId(i): StateId,\n\n StateId(j): StateId,\n\n ) -> (&mut State<C>, &mut State<C>) {\n", "file_path": "src/auto/state/mod.rs", "rank": 26, "score": 44186.62952210505 }, { "content": " }\n\n }\n\n\n\n pub fn constructors(&self) -> &ConstructorSet<C> {\n\n &self.cons\n\n }\n\n\n\n pub fn flow(&self) -> &FlowSet {\n\n &self.flow\n\n }\n\n\n\n fn shift(self, offset: u32) -> Self {\n\n State {\n\n #[cfg(debug_assertions)]\n\n pol: self.pol,\n\n cons: self.cons.shift(offset),\n\n flow: self.flow.shift(offset),\n\n }\n\n }\n\n}\n", "file_path": "src/auto/state/mod.rs", "rank": 27, "score": 44186.20967725771 }, { "content": " debug_assert_ne!(i, j);\n\n if i < j {\n\n let (l, r) = self.states.split_at_mut(j as usize);\n\n (&mut l[i as usize], &mut r[0])\n\n } else {\n\n let (l, r) = self.states.split_at_mut(i as usize);\n\n (&mut r[0], &mut l[j as usize])\n\n }\n\n }\n\n\n\n pub(crate) fn range_from(&mut self, StateId(start): StateId) -> StateRange {\n\n StateRange(start..(self.states.len() as u32))\n\n }\n\n\n\n pub(crate) fn enumerate(&self) -> impl Iterator<Item = (StateId, &State<C>)> {\n\n self.states\n\n .iter()\n\n .enumerate()\n\n .map(|(id, st)| (StateId(id as u32), st))\n\n }\n", "file_path": "src/auto/state/mod.rs", "rank": 28, "score": 44185.3193447967 }, { "content": "}\n\n\n\nimpl Iterator for StateRange {\n\n type Item = StateId;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n self.0.next().map(StateId)\n\n }\n\n}\n", "file_path": "src/auto/state/mod.rs", "rank": 29, "score": 44181.80546481817 }, { "content": "fn split(ty: Ty<Constructed, char>, var: usize) -> (Ty<Constructed, char>, Ty<Constructed, char>) {\n\n match ty {\n\n Ty::BoundVar(idx) if idx == var => (ty, Ty::Zero),\n\n Ty::Zero => (Ty::Zero, Ty::Zero),\n\n Ty::Add(l, r) => {\n\n let (la, lg) = split(*l, var);\n\n let (ra, rg) = split(*r, var);\n\n (\n\n Ty::Add(Box::new(la), Box::new(ra)),\n\n Ty::Add(Box::new(lg), Box::new(rg)),\n\n )\n\n }\n\n Ty::BoundVar(_) | Ty::UnboundVar(_) | Ty::Constructed(_) => (Ty::Zero, ty),\n\n Ty::Recursive(ref t) => {\n\n let (ta, tg) = split((**t).clone(), var + 1);\n\n (ta, subst(tg, var + 1, ty))\n\n }\n\n }\n\n}\n\n\n\npub(crate) fn fixpoint(ty: Ty<Constructed, char>) -> Ty<Constructed, char> {\n\n Ty::Recursive(Box::new(split(ty, 0).1))\n\n}\n\n\n", "file_path": "src/biunify/reference.rs", "rank": 31, "score": 34569.25978953573 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub enum Ty<C, V> {\n\n Zero,\n\n Add(Box<Ty<C, V>>, Box<Ty<C, V>>),\n\n UnboundVar(V),\n\n BoundVar(usize),\n\n Constructed(C),\n\n Recursive(Box<Ty<C, V>>),\n\n}\n", "file_path": "src/polar.rs", "rank": 32, "score": 26301.64991072918 }, { "content": "use std::collections::HashSet;\n\nuse std::ops;\n\n\n\nuse im::Vector;\n\nuse proptest::strategy::Strategy;\n\n\n\nuse crate::polar::Ty;\n\nuse crate::tests::{arb_polar_ty, Constructed};\n\nuse crate::Polarity;\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Hash)]\n\npub(in crate::biunify) struct Constraint(\n\n pub(in crate::biunify) Ty<Constructed, char>,\n\n pub(in crate::biunify) Ty<Constructed, char>,\n\n);\n\n\n\npub(in crate::biunify) fn arb_constraint() -> impl Strategy<Value = Constraint> {\n\n (arb_polar_ty(Polarity::Pos), arb_polar_ty(Polarity::Neg)).prop_map(|(l, r)| Constraint(l, r))\n\n}\n\n\n\nimpl Constraint {\n\n fn bisubst(self, sub: &Bisubst) -> Self {\n\n Constraint(\n\n sub.apply(self.0, Polarity::Pos),\n\n sub.apply(self.1, Polarity::Neg),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/biunify/reference.rs", "rank": 33, "score": 24404.989465199917 }, { "content": " biunify_all(vec![constraint])\n\n}\n\n\n\npub(in crate::biunify) fn biunify_all(mut cons: Vec<Constraint>) -> Result<Bisubst, ()> {\n\n let mut hyp = HashSet::new();\n\n let mut result = Bisubst::new();\n\n while let Some(con) = cons.pop() {\n\n if hyp.contains(&con) {\n\n continue;\n\n } else if let Ok(bisub) = atomic(&con) {\n\n hyp.insert(con);\n\n cons = cons.into_iter().map(|con| con.bisubst(&bisub)).collect();\n\n hyp = hyp.into_iter().map(|con| con.bisubst(&bisub)).collect();\n\n result *= bisub;\n\n } else if let Ok(sub) = subi(con.clone()) {\n\n hyp.insert(con);\n\n cons.extend(sub);\n\n } else {\n\n return Err(());\n\n }\n\n }\n\n\n\n Ok(result)\n\n}\n", "file_path": "src/biunify/reference.rs", "rank": 34, "score": 24398.29417659753 }, { "content": " Box::new(Ty::UnboundVar(v)),\n\n Box::new(bisubst(\n\n con.0.clone(),\n\n Polarity::Pos,\n\n (Polarity::Pos, v),\n\n Ty::BoundVar(0),\n\n )),\n\n )),\n\n )),\n\n _ => Err(()),\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub(in crate::biunify) struct Bisubst {\n\n sub: Vector<((Polarity, char), Ty<Constructed, char>)>,\n\n}\n\n\n\nimpl Bisubst {\n\n fn new() -> Self {\n", "file_path": "src/biunify/reference.rs", "rank": 35, "score": 24396.720405748485 }, { "content": " }\n\n Constraint(Ty::Recursive(lhs), rhs) => {\n\n let lhs = subst((*lhs).clone(), 0, Ty::Recursive(lhs));\n\n Ok(vec![Constraint(lhs, rhs)])\n\n }\n\n Constraint(lhs, Ty::Recursive(rhs)) => {\n\n let rhs = subst((*rhs).clone(), 0, Ty::Recursive(rhs));\n\n Ok(vec![Constraint(lhs, rhs)])\n\n }\n\n Constraint(Ty::Add(lhsa, lhsb), rhs) => {\n\n Ok(vec![Constraint(*lhsa, rhs.clone()), Constraint(*lhsb, rhs)])\n\n }\n\n Constraint(lhs, Ty::Add(rhsa, rhsb)) => {\n\n Ok(vec![Constraint(lhs.clone(), *rhsa), Constraint(lhs, *rhsb)])\n\n }\n\n Constraint(Ty::Zero, _) => Ok(vec![]),\n\n Constraint(_, Ty::Zero) => Ok(vec![]),\n\n _ => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/biunify/reference.rs", "rank": 36, "score": 24395.775543196036 }, { "content": " Bisubst { sub: Vector::new() }\n\n }\n\n\n\n fn unit(v: char, pol: Polarity, ty: Ty<Constructed, char>) -> Self {\n\n Bisubst {\n\n sub: Vector::unit(((pol, v), ty)),\n\n }\n\n }\n\n\n\n fn apply(&self, mut ty: Ty<Constructed, char>, pol: Polarity) -> Ty<Constructed, char> {\n\n for (v, sub) in &self.sub {\n\n ty = bisubst(ty, pol, *v, sub.clone())\n\n }\n\n ty\n\n }\n\n}\n\n\n\nimpl ops::MulAssign for Bisubst {\n\n fn mul_assign(&mut self, other: Self) {\n\n self.sub.append(other.sub)\n\n }\n\n}\n\n\n", "file_path": "src/biunify/reference.rs", "rank": 37, "score": 24395.228415531205 }, { "content": "use std::collections::BTreeMap;\n\nuse std::rc::Rc;\n\n\n\nuse super::{Constructor, Label};\n\nuse crate::auto::build::polar::Build;\n\nuse crate::auto::StateSet;\n\nuse crate::polar::Ty;\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub enum Constructed {\n\n Bool,\n\n Fun(Box<Ty<Constructed, char>>, Box<Ty<Constructed, char>>),\n\n Record(BTreeMap<Rc<str>, Box<Ty<Constructed, char>>>),\n\n}\n\n\n\nimpl Build<Constructor, char> for Constructed {\n\n fn map<'a, F>(&'a self, mut mapper: F) -> Constructor\n\n where\n\n F: FnMut(Label, &'a Ty<Self, char>) -> StateSet,\n\n {\n", "file_path": "src/tests/build.rs", "rank": 38, "score": 23237.31072805825 }, { "content": " prop_assert_eq!(\n\n auto.biunify_all(ids).is_ok(),\n\n reference::biunify_all(cons).is_ok()\n\n );\n\n }\n\n\n\n #[test]\n\n fn biunify_all_reduced(cons in vec(arb_constraint(), 0..16)) {\n\n let mut auto = Automaton::new();\n\n\n\n let mut builder = auto.builder();\n\n let ids: Vec<_> = cons.iter().flat_map(|con| {\n\n let lhs_id = builder.build_polar(Polarity::Pos, &con.0);\n\n let rhs_id = builder.build_polar(Polarity::Neg, &con.1);\n\n vec![(lhs_id, Polarity::Pos), (rhs_id, Polarity::Neg)]\n\n }).collect();\n\n drop(builder);\n\n\n\n let mut reduced = Automaton::new();\n\n let dfa_ids = reduced.reduce(&auto, ids);\n\n\n\n prop_assert_eq!(\n\n reduced.biunify_all(dfa_ids.tuples()).is_ok(),\n\n reference::biunify_all(cons).is_ok()\n\n );\n\n }\n\n}\n", "file_path": "src/biunify/tests.rs", "rank": 39, "score": 23233.85891256505 }, { "content": " }\n\n\n\n #[test]\n\n fn biunify_reduced(con in arb_constraint()) {\n\n let mut auto = Automaton::new();\n\n\n\n let mut builder = auto.builder();\n\n let lhs_id = builder.build_polar(Polarity::Pos, &con.0);\n\n let rhs_id = builder.build_polar(Polarity::Neg, &con.1);\n\n drop(builder);\n\n\n\n let mut reduced = Automaton::new();\n\n let dfa_ids: Vec<_> = reduced.reduce(&auto, [(lhs_id, Polarity::Pos), (rhs_id, Polarity::Neg)].iter().cloned()).collect();\n\n\n\n prop_assert_eq!(\n\n reduced.biunify(dfa_ids[0], dfa_ids[1]).is_ok(),\n\n reference::biunify(con).is_ok()\n\n );\n\n }\n\n}\n", "file_path": "src/biunify/tests.rs", "rank": 40, "score": 23233.696310531595 }, { "content": "proptest! {\n\n #![proptest_config(Config {\n\n cases: 1024,\n\n timeout: 10000,\n\n ..Config::default()\n\n })]\n\n\n\n #[test]\n\n fn biunify(con in arb_constraint()) {\n\n let mut auto = Automaton::new();\n\n\n\n let mut builder = auto.builder();\n\n let lhs_id = builder.build_polar(Polarity::Pos, &con.0);\n\n let rhs_id = builder.build_polar(Polarity::Neg, &con.1);\n\n drop(builder);\n\n\n\n prop_assert_eq!(\n\n auto.biunify(lhs_id, rhs_id).is_ok(),\n\n reference::biunify(con).is_ok()\n\n );\n", "file_path": "src/biunify/tests.rs", "rank": 41, "score": 23233.64937047857 }, { "content": "use itertools::Itertools;\n\nuse proptest::collection::vec;\n\nuse proptest::test_runner::Config;\n\nuse proptest::{prop_assert_eq, proptest};\n\n\n\nuse crate::auto::Automaton;\n\nuse crate::biunify::reference::{self, arb_constraint};\n\nuse crate::polar::Ty;\n\nuse crate::tests::Constructed;\n\nuse crate::Polarity;\n\n\n\n#[test]\n", "file_path": "src/biunify/tests.rs", "rank": 42, "score": 23232.86973726716 }, { "content": " false\n\n }\n\n\n\n fn complicate(&mut self) -> bool {\n\n false\n\n }\n\n}\n\n\n\nproptest! {\n\n #[test]\n\n fn polar_pos(_ in arb_polar_ty(Polarity::Pos)) {}\n\n\n\n #[test]\n\n fn polar_neg(_ in arb_polar_ty(Polarity::Neg)) {}\n\n\n\n #[test]\n\n fn auto_pos(_ in arb_auto_ty(Polarity::Pos)) {}\n\n\n\n #[test]\n\n fn auto_neg(_ in arb_auto_ty(Polarity::Neg)) {}\n\n}\n", "file_path": "src/tests/arbitrary.rs", "rank": 43, "score": 23231.452909529213 }, { "content": "use std::collections::VecDeque;\n\nuse std::rc::Rc;\n\n\n\nuse lazy_static::lazy_static;\n\nuse proptest::collection::btree_map;\n\nuse proptest::prelude::*;\n\nuse proptest::prop_oneof;\n\nuse proptest::proptest;\n\nuse proptest::strategy::{LazyJust, NewTree, ValueTree};\n\nuse proptest::string::string_regex;\n\nuse proptest::test_runner::TestRunner;\n\nuse rand_distr::Exp1;\n\n\n\nuse super::{Constructed, Constructor};\n\nuse crate::auto::{Automaton, StateId};\n\nuse crate::polar::Ty;\n\nuse crate::Polarity;\n\n\n", "file_path": "src/tests/arbitrary.rs", "rank": 44, "score": 23230.44365600214 }, { "content": "\n\nproptest! {\n\n #![proptest_config(Config {\n\n cases: 256,\n\n timeout: 10000,\n\n ..Config::default()\n\n })]\n\n\n\n #[test]\n\n fn biunify_all(cons in vec(arb_constraint(), 0..16)) {\n\n let mut auto = Automaton::new();\n\n\n\n let mut builder = auto.builder();\n\n let ids: Vec<_> = cons.iter().map(|con| {\n\n let lhs_id = builder.build_polar(Polarity::Pos, &con.0);\n\n let rhs_id = builder.build_polar(Polarity::Neg, &con.1);\n\n (lhs_id, rhs_id)\n\n }).collect();\n\n drop(builder);\n\n\n", "file_path": "src/biunify/tests.rs", "rank": 45, "score": 23229.935499993815 }, { "content": " match self {\n\n Constructed::Bool => Constructor::Bool,\n\n Constructed::Fun(lhs, rhs) => {\n\n Constructor::Fun(mapper(Label::Domain, lhs), mapper(Label::Range, rhs))\n\n }\n\n Constructed::Record(fields) => Constructor::Record(\n\n fields\n\n .iter()\n\n .map(|(label, ty)| (label.clone(), mapper(Label::Label(label.clone()), ty)))\n\n .collect(),\n\n ),\n\n }\n\n }\n\n}\n", "file_path": "src/tests/build.rs", "rank": 46, "score": 23226.85705721484 }, { "content": " Ty::Add(l, r) => check(pol, l, recs, unguarded) && check(pol, r, recs, unguarded),\n\n Ty::Recursive(t) => {\n\n recs.push_front(pol);\n\n let b = check(pol, t, recs, unguarded + 1);\n\n recs.pop_front();\n\n b\n\n }\n\n _ => true,\n\n }\n\n}\n\n\n", "file_path": "src/tests/arbitrary.rs", "rank": 47, "score": 23220.798529544445 }, { "content": " pub fn insert(&mut self, id: StateId) -> bool {\n\n self.set.insert(id)\n\n }\n\n\n\n pub fn union(&mut self, other: &Self) {\n\n self.set.extend(other)\n\n }\n\n\n\n pub fn iter(&self) -> Copied<slice::Iter<StateId>> {\n\n self.set.iter().copied()\n\n }\n\n\n\n pub(crate) fn shift(self, offset: u32) -> Self {\n\n StateSet {\n\n set: self.set.into_iter().map(|id| id.shift(offset)).collect(),\n\n }\n\n }\n\n\n\n pub(crate) fn unwrap_reduced(&self) -> StateId {\n\n debug_assert_eq!(self.set.len(), 1);\n", "file_path": "src/auto/state/set.rs", "rank": 48, "score": 23100.580162062557 }, { "content": "use std::iter::Copied;\n\nuse std::slice;\n\n\n\nuse small_ord_set::SmallOrdSet;\n\n\n\nuse crate::auto::state::StateId;\n\n\n\n/// A non-empty set of states, optimized for the common case where only one state is in the set.\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub struct StateSet {\n\n set: SmallOrdSet<[StateId; 1]>,\n\n}\n\n\n\nimpl StateSet {\n\n pub fn new(id: StateId) -> Self {\n\n StateSet {\n\n set: SmallOrdSet::from_buf([id]),\n\n }\n\n }\n\n\n", "file_path": "src/auto/state/set.rs", "rank": 49, "score": 23096.357284663616 }, { "content": " self.set[0]\n\n }\n\n}\n\n\n\nimpl<'a> IntoIterator for &'a StateSet {\n\n type IntoIter = Copied<slice::Iter<'a, StateId>>;\n\n type Item = StateId;\n\n\n\n fn into_iter(self) -> Self::IntoIter {\n\n self.iter()\n\n }\n\n}\n", "file_path": "src/auto/state/set.rs", "rank": 50, "score": 23091.21672806676 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl<C: Constructor> Default for Automaton<C> {\n\n fn default() -> Self {\n\n Automaton::new()\n\n }\n\n}\n\n\n\nimpl<C> fmt::Debug for Automaton<C>\n\nwhere\n\n C: Constructor + Debug,\n\n C::Label: fmt::Debug,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"Automaton\")\n\n .field(\"states\", &self.states)\n\n .field(\"biunify_cache\", &self.biunify_cache)\n\n .finish()\n\n }\n\n}\n", "file_path": "src/auto/mod.rs", "rank": 56, "score": 22226.176061809936 }, { "content": "pub mod flow;\n\npub mod state;\n\n\n\npub(crate) mod build;\n\n\n\nmod reduce;\n\n\n\npub use self::build::Build;\n\npub use self::state::{State, StateId, StateRange, StateSet};\n\n\n\npub(crate) use self::flow::FlowSet;\n\n\n\nuse std::collections::HashMap;\n\nuse std::fmt::{self, Debug};\n\nuse std::hash::BuildHasherDefault;\n\n\n\nuse seahash::SeaHasher;\n\n\n\nuse crate::{biunify, Constructor, ConstructorSet, Polarity};\n\n\n", "file_path": "src/auto/mod.rs", "rank": 57, "score": 22225.535690675548 }, { "content": "pub struct Automaton<C: Constructor> {\n\n pub(crate) states: Vec<State<C>>,\n\n pub(crate) biunify_cache:\n\n HashMap<(StateId, StateId), biunify::CacheEntry<C>, BuildHasherDefault<SeaHasher>>,\n\n}\n\n\n\nimpl<C: Constructor> Automaton<C> {\n\n pub fn new() -> Self {\n\n Automaton {\n\n states: Vec::new(),\n\n biunify_cache: HashMap::default(),\n\n }\n\n }\n\n\n\n pub fn clone_states<I>(&mut self, states: I) -> StateRange\n\n where\n\n I: IntoIterator<Item = (StateId, Polarity)>,\n\n {\n\n let mut reduced = Automaton::new();\n\n let range = reduced.reduce(&self, states);\n", "file_path": "src/auto/mod.rs", "rank": 59, "score": 22223.67708203878 }, { "content": "use std::collections::HashSet;\n\nuse std::hash::BuildHasherDefault;\n\n\n\nuse seahash::SeaHasher;\n\n\n\nuse crate::auto::{flow, Automaton, StateId};\n\nuse crate::Constructor;\n\n\n\nimpl<C: Constructor> Automaton<C> {\n\n pub fn subsume(&self, a: StateId, b: StateId) -> Result<(), ()> {\n\n let mut seen = HashSet::with_capacity_and_hasher(20, Default::default());\n\n self.subsume_impl(&mut seen, a, b)\n\n }\n\n\n\n fn subsume_impl(\n\n &self,\n\n seen: &mut HashSet<(StateId, StateId), BuildHasherDefault<SeaHasher>>,\n\n a: StateId,\n\n b: StateId,\n\n ) -> Result<(), ()> {\n", "file_path": "src/subsume/mod.rs", "rank": 60, "score": 22221.881290085646 }, { "content": " #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[a].pol, self[b].pol);\n\n\n\n if seen.insert((a, b)) {\n\n for lcon in self[a].cons.iter() {\n\n let rcon = match self[b].cons.get(lcon.component()) {\n\n Some(rcon) if lcon <= rcon => rcon,\n\n _ => return Err(()),\n\n };\n\n\n\n lcon.visit_params_intersection(rcon, |_, l, r| {\n\n self.subsume_impl(seen, l.unwrap_reduced(), r.unwrap_reduced())\n\n })?;\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn admissible(&mut self, pair: flow::Pair) -> bool {\n\n if self.has_flow(pair) {\n", "file_path": "src/subsume/mod.rs", "rank": 61, "score": 22219.99826351936 }, { "content": "\n\n let offset = self.add_from(&reduced);\n\n\n\n #[cfg(debug_assertions)]\n\n debug_assert!(self.check_flow());\n\n\n\n range.shift(offset)\n\n }\n\n\n\n pub(crate) fn merge(&mut self, pol: Polarity, target_id: StateId, source_id: StateId) {\n\n if target_id != source_id {\n\n let (target, source) = self.index_mut2(target_id, source_id);\n\n\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(target.pol, pol);\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(source.pol, pol);\n\n\n\n target.cons.merge(&source.cons, pol);\n\n self.merge_flow(pol, target_id, source_id);\n", "file_path": "src/auto/mod.rs", "rank": 62, "score": 22217.137636868832 }, { "content": " true\n\n } else {\n\n self.add_flow(pair);\n\n\n\n unimplemented!();\n\n\n\n self.remove_flow(pair);\n\n false\n\n }\n\n }\n\n}\n", "file_path": "src/subsume/mod.rs", "rank": 63, "score": 22209.24504668516 }, { "content": "use std::iter::once;\n\n\n\nuse proptest::proptest;\n\nuse proptest::test_runner::Config;\n\n\n\nuse crate::auto::Automaton;\n\nuse crate::tests::arb_auto_ty;\n\nuse crate::Polarity;\n\n\n\nproptest! {\n\n #![proptest_config(Config {\n\n cases: 1024,\n\n timeout: 10000,\n\n ..Config::default()\n\n })]\n\n\n\n #[test]\n\n fn reduce_one_pos((nfa, nfa_start) in arb_auto_ty(Polarity::Pos)) {\n\n let mut dfa = Automaton::new();\n\n dfa.reduce(&nfa, once((nfa_start, Polarity::Pos)));\n\n }\n\n\n\n #[test]\n\n fn reduce_one_neg((nfa, nfa_start) in arb_auto_ty(Polarity::Neg)) {\n\n let mut dfa = Automaton::new();\n\n dfa.reduce(&nfa, once((nfa_start, Polarity::Neg)));\n\n }\n\n}\n", "file_path": "src/auto/reduce/tests.rs", "rank": 64, "score": 22060.748834356582 }, { "content": "#[cfg(test)]\n\nmod tests;\n\n\n\nuse std::borrow::Cow;\n\nuse std::collections::HashMap;\n\nuse std::mem::replace;\n\n\n\nuse small_ord_set::SmallOrdSet;\n\n\n\nuse crate::auto::{Automaton, ConstructorSet, FlowSet, State, StateId, StateRange, StateSet};\n\nuse crate::{Constructor, Label, Polarity};\n\n\n\nimpl<C: Constructor> State<C> {\n\n fn merged<'a, I>(pol: Polarity, it: I) -> Self\n\n where\n\n C: 'a,\n\n I: IntoIterator<Item = &'a Self>,\n\n {\n\n it.into_iter().fold(State::new(pol), |mut l, r| {\n\n #[cfg(debug_assertions)]\n", "file_path": "src/auto/reduce/mod.rs", "rank": 65, "score": 21109.647101823677 }, { "content": " debug_assert_eq!(r.pol, pol);\n\n\n\n l.cons.merge(&r.cons, pol);\n\n l.flow.union(&r.flow);\n\n l\n\n })\n\n }\n\n}\n\n\n\nimpl<C: Constructor> Automaton<C> {\n\n pub fn reduce<I>(&mut self, nfa: &Self, nfa_ids: I) -> StateRange\n\n where\n\n I: IntoIterator<Item = (StateId, Polarity)>,\n\n {\n\n self.states.reserve(nfa.states.len());\n\n\n\n // Maps between sets of nfa states to corresponding dfa state.\n\n let mut map = BiMap::with_capacity(nfa.states.len());\n\n\n\n let start = self.next();\n", "file_path": "src/auto/reduce/mod.rs", "rank": 66, "score": 21102.292877026797 }, { "content": "\n\n let mut dfa_cons = ConstructorSet::default();\n\n for nfa_con in nfa_cons.iter() {\n\n let dfa_con = nfa_con.clone().map(|label, set| {\n\n let mut ids: Vec<_> = set.iter().collect();\n\n ids.sort();\n\n\n\n if let Some(&b) = map.ns2d.get(&ids) {\n\n StateSet::new(b)\n\n } else {\n\n let b_pol = a_pol * label.polarity();\n\n let state = State::merged(b_pol, ids.iter().map(|&id| &nfa[id]));\n\n let b = self.add(state);\n\n map.insert(ids, b);\n\n stack.push((b, b_pol));\n\n StateSet::new(b)\n\n }\n\n });\n\n\n\n dfa_cons.add(a_pol, Cow::Owned(dfa_con));\n", "file_path": "src/auto/reduce/mod.rs", "rank": 67, "score": 21099.952940727417 }, { "content": " // Stack of states to be converted from nfa states to dfa states.\n\n let mut stack: Vec<_> = nfa_ids\n\n .into_iter()\n\n .map(|(nfa_id, pol)| {\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(nfa[nfa_id].pol, pol);\n\n\n\n let dfa_id = self.add(nfa[nfa_id].clone());\n\n map.insert(vec![nfa_id], dfa_id);\n\n (dfa_id, pol)\n\n })\n\n .collect();\n\n let range = self.range_from(start);\n\n\n\n debug_assert!(stack.iter().map(|&(id, _)| id).eq(range.clone()));\n\n\n\n // Walk transitions and convert to dfa ids.\n\n while let Some((a, a_pol)) = stack.pop() {\n\n // Remove old nfa ids\n\n let nfa_cons = replace(&mut self[a].cons, ConstructorSet::default());\n", "file_path": "src/auto/reduce/mod.rs", "rank": 68, "score": 21099.183899835494 }, { "content": " }\n\n\n\n // Replace with dfa ids\n\n self[a].cons = dfa_cons;\n\n }\n\n\n\n // Populate flow\n\n for &a in map.ns2d.values() {\n\n // Remove old nfa ids\n\n let nfa_flow = replace(&mut self[a].flow, FlowSet::default());\n\n\n\n let dfa_flow = FlowSet::from_iter(\n\n nfa_flow\n\n .iter()\n\n .flat_map(|b| map.n2ds.get(&b).cloned())\n\n .flatten(),\n\n );\n\n\n\n // Replace with dfa ids\n\n self[a].flow = dfa_flow;\n\n }\n\n\n\n #[cfg(debug_assertions)]\n\n debug_assert!(self.check_flow());\n\n\n\n range\n\n }\n\n}\n\n\n", "file_path": "src/auto/reduce/mod.rs", "rank": 69, "score": 21091.79029989287 }, { "content": "pub mod auto;\n\npub mod cons;\n\npub mod polar;\n\n\n\nmod biunify;\n\nmod subsume;\n\n#[cfg(test)]\n\nmod tests;\n\n\n\npub use self::biunify::{Error as BiunifyError, Result as BiunifyResult};\n\npub use self::cons::{Constructor, ConstructorSet, Label};\n\n\n\nuse std::ops;\n\n\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum Polarity {\n\n Neg = -1,\n\n Pos = 1,\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 70, "score": 19.936559203616877 }, { "content": " static EMPTY: Lazy<FlowSet> = Lazy::new(|| FlowSet {\n\n set: HashSet::default()\n\n });\n\n\n\n EMPTY.clone()\n\n }\n\n}\n\n\n\nimpl<C: Constructor> Automaton<C> {\n\n pub(crate) fn add_flow(&mut self, pair: Pair) {\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[pair.pos].pol, Polarity::Pos);\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[pair.neg].pol, Polarity::Neg);\n\n\n\n let had_p = self[pair.pos].flow.set.insert(pair.neg).is_some();\n\n let had_n = self[pair.neg].flow.set.insert(pair.pos).is_some();\n\n debug_assert_eq!(had_p, had_n);\n\n }\n\n\n", "file_path": "src/auto/flow.rs", "rank": 71, "score": 14.715867314249051 }, { "content": "use std::hash::BuildHasherDefault;\n\nuse std::iter::FromIterator;\n\n\n\nuse im::{hashset, HashSet};\n\nuse seahash::SeaHasher;\n\nuse once_cell::sync::Lazy;\n\n\n\nuse crate::auto::{Automaton, StateId};\n\nuse crate::{Constructor, Polarity};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub struct Pair {\n\n pub neg: StateId,\n\n pub pos: StateId,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct FlowSet {\n\n set: HashSet<StateId, BuildHasherDefault<SeaHasher>>,\n\n}\n", "file_path": "src/auto/flow.rs", "rank": 72, "score": 13.75591718109888 }, { "content": "\n\nimpl Pair {\n\n pub(crate) fn from_pol(pol: Polarity, a: StateId, b: StateId) -> Self {\n\n let (pos, neg) = pol.flip(a, b);\n\n Pair { pos, neg }\n\n }\n\n\n\n pub fn get(&self, pol: Polarity) -> StateId {\n\n match pol {\n\n Polarity::Pos => self.pos,\n\n Polarity::Neg => self.neg,\n\n }\n\n }\n\n}\n\n\n\nimpl FlowSet {\n\n pub fn iter(&self) -> hashset::ConsumingIter<StateId> {\n\n self.set.clone().into_iter()\n\n }\n\n\n", "file_path": "src/auto/flow.rs", "rank": 73, "score": 11.987076207978767 }, { "content": " self.set.get_value(&cpt)\n\n }\n\n\n\n pub(crate) fn shift(self, offset: u32) -> Self {\n\n let set = self\n\n .set\n\n .into_iter()\n\n .map(|kvp| KeyValuePair {\n\n key: kvp.key,\n\n value: kvp.value.map(|_, set| set.shift(offset)),\n\n })\n\n .collect();\n\n ConstructorSet { set }\n\n }\n\n}\n\n\n\nimpl<C: Debug + Constructor> Debug for ConstructorSet<C> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_set().entries(self.iter()).finish()\n\n }\n", "file_path": "src/cons.rs", "rank": 74, "score": 11.094657677273705 }, { "content": " pub(crate) fn remove_flow(&mut self, pair: Pair) {\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[pair.pos].pol, Polarity::Pos);\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[pair.neg].pol, Polarity::Neg);\n\n\n\n let had_p = self[pair.pos].flow.set.remove(&pair.neg).is_some();\n\n let had_n = self[pair.neg].flow.set.remove(&pair.pos).is_some();\n\n debug_assert_eq!(had_p, had_n);\n\n }\n\n\n\n pub(crate) fn has_flow(&self, pair: Pair) -> bool {\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[pair.pos].pol, Polarity::Pos);\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[pair.neg].pol, Polarity::Neg);\n\n\n\n self[pair.neg].flow.set.contains(&pair.pos)\n\n }\n\n\n", "file_path": "src/auto/flow.rs", "rank": 75, "score": 10.731050423471984 }, { "content": "impl Polarity {\n\n pub(crate) fn flip<T>(self, a: T, b: T) -> (T, T) {\n\n match self {\n\n Polarity::Pos => (a, b),\n\n Polarity::Neg => (b, a),\n\n }\n\n }\n\n}\n\n\n\nimpl ops::Neg for Polarity {\n\n type Output = Self;\n\n\n\n fn neg(self) -> Self {\n\n match self {\n\n Polarity::Neg => Polarity::Pos,\n\n Polarity::Pos => Polarity::Neg,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 76, "score": 10.416696770375394 }, { "content": " }\n\n }\n\n\n\n pub(crate) fn intersection<'a>(\n\n &'a self,\n\n other: &'a Self,\n\n ) -> impl Iterator<Item = (&'a C, &'a C)> {\n\n merge_join_by(&self.set, &other.set, Ord::cmp).filter_map(|eob| match eob {\n\n EitherOrBoth::Both(l, r) => Some((&l.value, &r.value)),\n\n _ => None,\n\n })\n\n }\n\n\n\n pub(crate) fn merge(&mut self, other: &Self, pol: Polarity) {\n\n for con in other.iter() {\n\n self.add(pol, Cow::Borrowed(con));\n\n }\n\n }\n\n\n\n pub(crate) fn get(&self, cpt: C::Component) -> Option<&C> {\n", "file_path": "src/cons.rs", "rank": 77, "score": 10.266752153448786 }, { "content": " pub(crate) fn merge_flow(&mut self, pol: Polarity, a: StateId, source: StateId) {\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[a].pol, pol);\n\n #[cfg(debug_assertions)]\n\n debug_assert_eq!(self[source].pol, pol);\n\n\n\n for b in self[source].flow.iter() {\n\n self.add_flow(Pair::from_pol(pol, a, b));\n\n }\n\n }\n\n\n\n #[cfg(debug_assertions)]\n\n pub(in crate::auto) fn check_flow(&self) -> bool {\n\n self.enumerate().all(|(from, st)| {\n\n st.flow\n\n .iter()\n\n .all(|to| self[to].pol != st.pol && self[to].flow.set.contains(&from))\n\n })\n\n }\n\n}\n", "file_path": "src/auto/flow.rs", "rank": 78, "score": 9.061116866526854 }, { "content": "use std::borrow::Cow;\n\nuse std::fmt::{self, Debug};\n\n\n\nuse itertools::{merge_join_by, EitherOrBoth};\n\nuse small_ord_set::{self, KeyValuePair, SmallOrdSet};\n\n\n\nuse crate::auto::StateSet;\n\nuse crate::Polarity;\n\n\n", "file_path": "src/cons.rs", "rank": 79, "score": 8.551202652476409 }, { "content": "impl ops::Mul for Polarity {\n\n type Output = Self;\n\n\n\n fn mul(self, other: Self) -> Self {\n\n match self {\n\n Polarity::Neg => -other,\n\n Polarity::Pos => other,\n\n }\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 80, "score": 8.340464526410805 }, { "content": "}\n\n\n\nimpl<C: Constructor> Default for ConstructorSet<C> {\n\n fn default() -> Self {\n\n ConstructorSet {\n\n set: SmallOrdSet::default(),\n\n }\n\n }\n\n}\n", "file_path": "src/cons.rs", "rank": 81, "score": 8.130577238099551 }, { "content": " pub(in crate::auto) fn from_iter<I>(iter: I) -> Self\n\n where\n\n I: IntoIterator<Item = StateId>,\n\n {\n\n FlowSet {\n\n set: HashSet::from_iter(iter),\n\n }\n\n }\n\n\n\n pub(crate) fn shift(self, offset: u32) -> Self {\n\n FlowSet::from_iter(self.set.into_iter().map(|id| id.shift(offset)))\n\n }\n\n\n\n pub(in crate::auto) fn union(&mut self, other: &Self) {\n\n self.set.extend(other.iter());\n\n }\n\n}\n\n\n\nimpl Default for FlowSet {\n\n fn default() -> Self {\n", "file_path": "src/auto/flow.rs", "rank": 82, "score": 7.883612242413324 }, { "content": "[![Crates.io][ci]][cl] [![Docs.rs][di]][dl]\n\n\n\n[ci]: https://img.shields.io/crates/v/mlsub.svg\n\n[cl]: https://crates.io/crates/mlsub/\n\n\n\n[di]: https://docs.rs/mlsub/badge.svg\n\n[dl]: https://docs.rs/mlsub/\n\n\n\n# Mlsub\n\n\n", "file_path": "README.md", "rank": 83, "score": 1.6412934922421747 } ]
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 the entire slice (4 bytes) and handle them together\n\n if *program_counter >= instructions.len() {\n\n return None;\n\n }\n\n\n\n let opcode: Byte = instructions[*program_counter];\n\n *program_counter += 1;\n\n\n\n Some(match opcode {\n\n Halt::OPCODE => build::<Halt>(instructions, program_counter),\n\n Load::OPCODE => build::<Load>(instructions, program_counter),\n\n\n\n Add::OPCODE => build::<Add>(instructions, program_counter),\n\n Subtract::OPCODE => build::<Subtract>(instructions, program_counter),\n\n Multiply::OPCODE => build::<Multiply>(instructions, program_counter),\n\n Divide::OPCODE => build::<Divide>(instructions, program_counter),\n\n\n\n Jump::OPCODE => build::<Jump>(instructions, program_counter),\n\n JumpForward::OPCODE => build::<JumpForward>(instructions, program_counter),\n", "file_path": "kaylee/src/instructions.rs", "rank": 0, "score": 224780.84322221496 }, { "content": "/// Build the Instruction TraitObject from the program stream\n\npub fn build<T: 'static + Instruction>(instructions: &Program, program_counter: &mut usize) -> Result<Box<dyn Instruction>, InstructionDecodeError> {\n\n Ok(\n\n Box::new(\n\n T::new(\n\n consume_and_parse_values(\n\n T::signature(),\n\n instructions,\n\n program_counter,\n\n )?\n\n )\n\n )\n\n )\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 1, "score": 213417.49273909745 }, { "content": "/// Decodes the operand values from the Instruction Stream\n\npub fn consume_and_parse_values(signature: InstructionSignature, instructions: &Program, program_counter: &mut usize) -> Result<OperandValues, InstructionDecodeError> {\n\n let mut operand_values: OperandValues = [OperandValue::None, OperandValue::None, OperandValue::None];\n\n\n\n let original_pc = *program_counter;\n\n for (index, bytes) in signature.operands.iter().enumerate() {\n\n match bytes {\n\n OperandType::None => {\n\n operand_values[index] = OperandValue::None;\n\n }\n\n OperandType::RegisterId | OperandType::ConstantByte => {\n\n operand_values[index] = OperandValue::Byte(instructions[*program_counter]);\n\n *program_counter += 1;\n\n }\n\n OperandType::ConstantHalfWord => {\n\n operand_values[index] = OperandValue::HalfWord(((instructions[*program_counter] as HalfWord) << 8) | instructions[*program_counter + 1] as u16);\n\n *program_counter += 2;\n\n }\n\n OperandType::ConstantWord => {\n\n // @todo: This should really be u24\n\n let a = (instructions[*program_counter] as Word) << 16;\n", "file_path": "kaylee/src/instructions.rs", "rank": 2, "score": 213004.6736463315 }, { "content": "pub fn parse_hex(hex: &str) -> Result<Vec<u8>, ParseIntError> {\n\n let split = hex.split(\" \").collect::<Vec<&str>>();\n\n let mut results: Vec<u8> = vec![];\n\n for hex_string in split {\n\n let byte = u8::from_str_radix(&hex_string, 16);\n\n match byte {\n\n Ok(result) => { results.push(result) }\n\n Err(e) => { return Err(e) }\n\n }\n\n }\n\n\n\n Ok(results)\n\n}", "file_path": "kaylee/src/shared.rs", "rank": 3, "score": 143489.19242362797 }, { "content": "/// Helper for a common instruction execution. Executes callback with the values from two operands, setting a destination register\n\nfn basic_register_execution<I: Instruction, F: Fn(RegisterValue, RegisterValue) -> RegisterValue>(instruction: &I, vm: &mut Kaylee, callback: F) -> RegisterValue {\n\n let destination = instruction.operand_values()[0].as_register_id();\n\n\n\n let left = instruction.get_register_value_for_operand(1, vm).unwrap();\n\n let right = instruction.get_register_value_for_operand(2, vm).unwrap();\n\n\n\n let result = callback(left, right);\n\n\n\n vm.set_register(destination, result as RegisterValue).unwrap();\n\n result\n\n}\n\n\n\n/// Potential types of Operands\n\npub enum OperandType {\n\n None,\n\n RegisterId,\n\n ConstantByte,\n\n ConstantHalfWord,\n\n ConstantWord,\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 4, "score": 117023.70811912435 }, { "content": "/// Parse any source string into a Parsed vector of strings\n\n/// Does not actually parse to token enumerations. It simply splits a source into substrings.\n\n/// The assembler takes these split strings and assembles them into true bytecode\n\npub fn parse_asm(s: &str) -> IResult<&str, Parsed, (&str, ErrorKind)> {\n\n // separated_list0(many0(newline), line)(s)\n\n separated_list0(newline, line)(s)\n\n}\n\n\n", "file_path": "kaylee/src/asm/parser.rs", "rank": 5, "score": 98020.86935465212 }, { "content": "/// Parse a single line into a vector of tokens\n\npub fn line(s: &str) -> IResult<&str, Vec<&str>, (&str, ErrorKind)> {\n\n delimited(multispace0, instruction_parser, space0)(s)\n\n}\n\n\n", "file_path": "kaylee/src/asm/parser.rs", "rank": 6, "score": 97269.14614025429 }, { "content": "/// Prints an instruction in an Instruction Stream in a human readable format\n\npub fn display_instruction_with_values<T: 'static + Instruction>(instruction: &T) -> String {\n\n let mut output = String::new();\n\n output.push_str(T::signature().identifier.as_str());\n\n\n\n for (index, operand_type) in T::signature().operands.iter().enumerate() {\n\n match operand_type {\n\n OperandType::None => {}\n\n OperandType::RegisterId => {\n\n let value = instruction.operand_value(index).unwrap().as_constant_value();\n\n output.push_str(format!(\" ${value}\").as_str())\n\n }\n\n _ => {\n\n let value = instruction.operand_value(index).unwrap().as_constant_value();\n\n output.push_str(format!(\" #{value}\").as_str())\n\n }\n\n }\n\n }\n\n\n\n output\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 7, "score": 89469.4095759669 }, { "content": "/// Parse a single instruction into an operation and operands\n\nfn instruction_parser(s: &str) -> IResult<&str, Vec<&str>, (&str, ErrorKind)> {\n\n separated_list1(space1, alt((operation_keyword, operand_parser)))(s)\n\n}\n\n\n", "file_path": "kaylee/src/asm/parser.rs", "rank": 8, "score": 85907.16643691741 }, { "content": "#[proc_macro_derive(Instruction, attributes(opcode, signature))]\n\npub fn derive_instruction(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let struct_name = input.ident;\n\n\n\n let mut opcode: u8 = 0;\n\n let mut help = String::new();\n\n let mut identifier = String::new();\n\n let mut operands = [\n\n quote! { OperandType::None },\n\n quote! { OperandType::None },\n\n quote! { OperandType::None },\n\n ];\n\n\n\n let attributes = input.attrs;\n\n for attribute in attributes {\n\n let meta = attribute.parse_meta().unwrap();\n\n if let Meta::NameValue(value) = meta {\n\n if let Some(ident) = value.path.get_ident() {\n\n match ident.to_string().as_str() {\n\n \"opcode\" => {\n", "file_path": "kaylee_derive/src/lib.rs", "rank": 9, "score": 81464.27476873471 }, { "content": "/// Determine if a keyword is a valid operation\n\nfn is_valid_keyword_character(c: char) -> bool {\n\n is_alphabetic(c as u8) || c == '.' || c == '_'\n\n}\n\n\n", "file_path": "kaylee/src/asm/parser.rs", "rank": 10, "score": 72641.49534341281 }, { "content": "/// Parse a single keyword into a keyword token\n\nfn operation_keyword(s: &str) -> IResult<&str, &str, (&str, ErrorKind)> {\n\n preceded(space0, take_while1(is_valid_keyword_character))(s)\n\n}\n\n\n", "file_path": "kaylee/src/asm/parser.rs", "rank": 11, "score": 70697.77945065006 }, { "content": "/// Parse an operand\n\nfn operand_parser(s: &str) -> IResult<&str, &str, (&str, ErrorKind)> {\n\n preceded(alt((tag(\"$\"), tag(\"#\"))), digit1)(s)\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use nom::Err::Error;\n\n use nom::error::ErrorKind;\n\n\n\n use crate::asm::parser::{instruction_parser, is_valid_keyword_character, operand_parser, operation_keyword, parse_asm};\n\n\n\n #[test]\n\n pub fn test_is_valid_keyword_character() {\n\n assert!(is_valid_keyword_character('A'));\n\n assert!(is_valid_keyword_character('a'));\n\n assert!(is_valid_keyword_character('.'));\n\n assert!(is_valid_keyword_character('_'));\n\n\n\n assert_eq!(false, is_valid_keyword_character('&'));\n", "file_path": "kaylee/src/asm/parser.rs", "rank": 12, "score": 70697.77945065006 }, { "content": "/// Defines the Instruction itself\n\n/// This is built automatically with the derive(Instruction) macro\n\npub trait Instruction: Executable {\n\n // Also requires a `pub const OPCODE: u8`\n\n\n\n /// Create a new instruction with Concrete Values\n\n fn new(operand_values: OperandValues) -> Self where Self: Sized;\n\n\n\n /// Return the Instruction Signature\n\n fn signature() -> InstructionSignature where Self: Sized;\n\n\n\n /// Return the Instruction Documentation\n\n fn documentation() -> InstructionDocumentation where Self: Sized;\n\n\n\n /// Return a human-readable form of the instruction\n\n fn display(&self) -> String;\n\n\n\n /// Return the concrete OperandValues\n\n fn operand_values(&self) -> &OperandValues;\n\n\n\n /// Return a specific, concrete OperandValue\n\n fn operand_value(&self, index: usize) -> Result<&OperandValue, String> {\n", "file_path": "kaylee/src/instructions.rs", "rank": 13, "score": 67798.68877297603 }, { "content": "/// Allows an Instruction to be executable\n\npub trait Executable {\n\n // @todo: The only thing (other than the OPCODE constant) that is actually required w/o macro\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error>;\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 14, "score": 64112.08941983804 }, { "content": "type OperandValues = [OperandValue; 3];\n\n\n\n/// Value for an operand in the Instruction Stream\n\n#[derive(PartialOrd, PartialEq, Debug)]\n\npub enum OperandValue {\n\n Byte(Byte),\n\n HalfWord(HalfWord),\n\n Word(Word),\n\n None,\n\n}\n\n\n\n/// Decode a single operand from a byte in the Instruction Stream\n\nimpl TryFrom<Byte> for OperandValue {\n\n type Error = ();\n\n\n\n fn try_from(value: Byte) -> Result<Self, Self::Error> {\n\n Ok(OperandValue::Byte(value))\n\n }\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 15, "score": 63984.92327133664 }, { "content": "#[proc_macro_attribute]\n\npub fn values(_args: TokenStream, input: TokenStream) -> TokenStream {\n\n // We need to add the operand_values field.\n\n // @todo: This is probably not the best place for this, but it has to be in an attribute, not the derive()\n\n let mut ast = parse_macro_input!(input as DeriveInput);\n\n match &mut ast.data {\n\n syn::Data::Struct(ref mut struct_data) => {\n\n match &mut struct_data.fields {\n\n syn::Fields::Named(fields) => {\n\n fields\n\n .named\n\n .push(syn::Field::parse_named.parse2(quote! {\n\n operand_values: OperandValues\n\n }).unwrap());\n\n }\n\n _ => {\n\n ()\n\n }\n\n }\n\n\n\n return quote! {\n\n #ast\n\n }.into();\n\n }\n\n _ => panic!(\"`add_field` has to be used with structs \"),\n\n }\n\n}\n", "file_path": "kaylee_derive/src/lib.rs", "rank": 16, "score": 58528.877229234815 }, { "content": "///\n\n/// Errors/ Panics\n\n/// - `AssemblerError`: If the ConstantValue is a value larger than 3 bytes\n\n/// - `RuntimeError`: If the target ProgramIndex is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// JUMPF #4 // `33 00 01 FF` - Jumps forward 4 instructions (16 bytes)\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 51]\n\n#[signature = \"JUMPF #3\"]\n\npub struct JumpForward {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for JumpForward {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let forward = self.operand_values[0].as_constant_value();\n\n let steps = (forward * 4) as usize;\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 17, "score": 51831.68748814986 }, { "content": "//! Instructions for navigating and manipulating the program\n\n//! Opcodes reserved: 50 - 69\n\nuse std::fmt::Error;\n\n\n\nuse kaylee_derive::Instruction;\n\n\n\nuse crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues};\n\nuse crate::vm::{ExecutionResult, Kaylee, RegisterId};\n\n\n\n/// Jump: Resets the program counter to a constant value\n\n/// Operands:\n\n/// - 0: `#ADDRESS` | 3 Bytes | ProgramIndex | ProgramIndex to jump to\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError`: If the ProgramIndex is a value larger than 3 bytes\n\n/// - `RuntimeError`: If the target ProgramIndex is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// JUMP #500 // `32 00 01 FF` - Jumps to program index 500\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 18, "score": 51831.43012778727 }, { "content": "#[signature = \"JUMPB #3\"]\n\npub struct JumpBackward {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for JumpBackward {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let backward = self.operand_values[0].as_constant_value();\n\n let steps = ((backward + 1) * 4) as usize;\n\n\n\n vm.set_program_counter(vm.program_counter() - steps);\n\n Ok(ExecutionResult::Jumped(vm.program_counter()))\n\n }\n\n}\n\n\n\n/// JumpEqual: Moves the program counter to the value of a register if the value of two registers is equal\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId that holds the target ProgramIndex\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 19, "score": 51830.871464754135 }, { "content": "/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 50]\n\n#[signature = \"JUMP #3\"]\n\npub struct Jump {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Jump {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let destination = self.operand_values[0].as_program_index();\n\n\n\n vm.set_program_counter(destination);\n\n Ok(ExecutionResult::Jumped(destination))\n\n }\n\n}\n\n\n\n/// JumpForward: Moves the program forward a certain number of instructions\n\n/// Operands:\n\n/// - 0: `#NUM_OF_INSTRUCTIONS` | 3 Bytes | ConstantValue | Number of instructions to move forward\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 20, "score": 51829.696388624696 }, { "content": "///\n\n/// Errors/ Panics\n\n/// - `AssemblerError`: If any RegisterIds are out of bounds\n\n/// - `RuntimeError`: If the target ProgramIndex is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// JUMPE $0 $1 $2 // `34 00 01 02` - Jumps to the value of R1 if R2 and R3 are equal\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 53]\n\n#[signature = \"JUMPE $D $L $R\"]\n\npub struct JumpEqual {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for JumpEqual {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let destination = self.get_register_value_for_operand(0, vm).unwrap();\n\n let left = self.get_register_value_for_operand(1, vm).unwrap();\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 21, "score": 51828.31459306492 }, { "content": " let right = self.get_register_value_for_operand(2, vm).unwrap();\n\n\n\n if left == right {\n\n vm.set_program_counter(destination as RegisterId);\n\n return Ok(ExecutionResult::Jumped(vm.program_counter()));\n\n }\n\n\n\n Ok(ExecutionResult::NoAction)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::instructions::data::Load;\n\n use crate::instructions::machine::Halt;\n\n use crate::instructions::program::{Jump, JumpBackward, JumpEqual, JumpForward};\n\n use crate::program::Program;\n\n use crate::vm::Kaylee;\n\n\n\n #[test]\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 22, "score": 51827.755467347066 }, { "content": "\n\n vm.set_program_counter(vm.program_counter() + steps);\n\n Ok(ExecutionResult::Jumped(vm.program_counter()))\n\n }\n\n}\n\n\n\n/// JumpBackward: Moves the program backward a certain number of instructions\n\n/// Operands:\n\n/// - 0: `#NUM_OF_INSTRUCTIONS` | 3 Bytes | ConstantValue | Number of instructions to move forward\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError`: If the ConstantValue is a value larger than 3 bytes\n\n/// - `RuntimeError`: If the target ProgramIndex is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// JUMPF #4 // `34 00 01 FF` - Jumps backward 4 instructions (16 bytes)\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 52]\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 23, "score": 51825.72323208834 }, { "content": " fn test_jump() {\n\n let program = Program::from(vec![\n\n // A bunch of random load instructions\n\n Load::OPCODE, 0, 0, 100,\n\n Load::OPCODE, 1, 0, 100,\n\n Jump::OPCODE, 0, 0, 24,\n\n Load::OPCODE, 2, 0, 100,\n\n Load::OPCODE, 3, 0, 100,\n\n Load::OPCODE, 4, 0, 100,\n\n Load::OPCODE, 5, 0, 100,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.run(program);\n\n\n\n // Should set these\n\n assert_eq!(100, vm.register(0).unwrap());\n\n assert_eq!(100, vm.register(1).unwrap());\n\n\n\n // Should skip these\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 24, "score": 51823.36360947447 }, { "content": " let mut vm = Kaylee::new();\n\n vm.set_program_counter(12);\n\n vm.run(program);\n\n\n\n assert_eq!(100, vm.register(0).unwrap());\n\n assert_eq!(0, vm.register(1).unwrap());\n\n assert_eq!(100, vm.register(2).unwrap());\n\n assert_eq!(100, vm.register(3).unwrap());\n\n assert_eq!(0, vm.register(4).unwrap());\n\n assert_eq!(0, vm.register(5).unwrap());\n\n\n\n // And check on the counter itself\n\n assert_eq!(8, vm.program_counter());\n\n }\n\n\n\n #[test]\n\n fn test_jump_if_equal() {\n\n let program = Program::from(vec![\n\n // A bunch of random load instructions\n\n Load::OPCODE, 0, 0, 100,\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 25, "score": 51823.2817915138 }, { "content": " Load::OPCODE, 4, 0, 100,\n\n Load::OPCODE, 5, 0, 100,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(30, 24).unwrap();\n\n vm.set_register(29, 300).unwrap();\n\n vm.set_register(28, 200).unwrap();\n\n\n\n vm.run(program);\n\n\n\n // Should set these\n\n assert_eq!(100, vm.register(0).unwrap());\n\n assert_eq!(100, vm.register(1).unwrap());\n\n assert_eq!(100, vm.register(2).unwrap());\n\n assert_eq!(100, vm.register(3).unwrap());\n\n assert_eq!(100, vm.register(4).unwrap());\n\n assert_eq!(100, vm.register(5).unwrap());\n\n\n\n // And check on the counter itself\n\n assert_eq!(28, vm.program_counter());\n\n }\n\n}", "file_path": "kaylee/src/instructions/program.rs", "rank": 26, "score": 51821.109480782776 }, { "content": " Load::OPCODE, 1, 0, 100,\n\n JumpEqual::OPCODE, 30, 29, 28,\n\n Load::OPCODE, 2, 0, 100,\n\n Load::OPCODE, 3, 0, 100,\n\n Load::OPCODE, 4, 0, 100,\n\n Load::OPCODE, 5, 0, 100,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(30, 24).unwrap();\n\n vm.set_register(29, 200).unwrap();\n\n vm.set_register(28, 200).unwrap();\n\n\n\n vm.run(program);\n\n\n\n // Should set these\n\n assert_eq!(100, vm.register(0).unwrap());\n\n assert_eq!(100, vm.register(1).unwrap());\n\n\n\n // Should skip these\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 27, "score": 51821.02970729017 }, { "content": " Load::OPCODE, 4, 0, 100,\n\n Load::OPCODE, 5, 0, 100,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.run(program);\n\n\n\n // Should set these\n\n assert_eq!(100, vm.register(0).unwrap());\n\n assert_eq!(100, vm.register(1).unwrap());\n\n\n\n // Should skip these\n\n assert_eq!(0, vm.register(2).unwrap());\n\n assert_eq!(0, vm.register(3).unwrap());\n\n assert_eq!(0, vm.register(4).unwrap());\n\n\n\n // And hit this one at the end\n\n assert_eq!(100, vm.register(5).unwrap());\n\n\n\n // And check on the counter itself\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 28, "score": 51820.95079093093 }, { "content": " assert_eq!(0, vm.register(2).unwrap());\n\n assert_eq!(0, vm.register(3).unwrap());\n\n assert_eq!(0, vm.register(4).unwrap());\n\n\n\n // And hit this one at the end\n\n assert_eq!(100, vm.register(5).unwrap());\n\n\n\n // And check on the counter itself\n\n assert_eq!(28, vm.program_counter());\n\n }\n\n\n\n #[test]\n\n fn test_jump_forward() {\n\n let program = Program::from(vec![\n\n // A bunch of random load instructions\n\n Load::OPCODE, 0, 0, 100,\n\n Load::OPCODE, 1, 0, 100,\n\n JumpForward::OPCODE, 0, 0, 3,\n\n Load::OPCODE, 2, 0, 100,\n\n Load::OPCODE, 3, 0, 100,\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 29, "score": 51819.44903795288 }, { "content": " assert_eq!(0, vm.register(2).unwrap());\n\n assert_eq!(0, vm.register(3).unwrap());\n\n assert_eq!(0, vm.register(4).unwrap());\n\n\n\n // And hit this one at the end\n\n assert_eq!(100, vm.register(5).unwrap());\n\n\n\n // And check on the counter itself\n\n assert_eq!(28, vm.program_counter());\n\n }\n\n\n\n #[test]\n\n fn test_dont_jump_if_not_equal() {\n\n let program = Program::from(vec![\n\n // A bunch of random load instructions\n\n Load::OPCODE, 0, 0, 100,\n\n Load::OPCODE, 1, 0, 100,\n\n JumpEqual::OPCODE, 30, 29, 28,\n\n Load::OPCODE, 2, 0, 100,\n\n Load::OPCODE, 3, 0, 100,\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 30, "score": 51819.40830324337 }, { "content": " assert_eq!(28, vm.program_counter());\n\n }\n\n\n\n #[test]\n\n fn test_jump_backward() {\n\n let program = Program::from(vec![\n\n Load::OPCODE, 0, 0, 100, // Jump to here, execute\n\n\n\n Halt::OPCODE, 0, 0, 0, // Stop\n\n\n\n Load::OPCODE, 1, 0, 100,\n\n Load::OPCODE, 2, 0, 100, // Start here (12)\n\n Load::OPCODE, 3, 0, 100, // Execute\n\n\n\n JumpBackward::OPCODE, 0, 0, 5, // Jump\n\n\n\n Load::OPCODE, 4, 0, 100,\n\n Load::OPCODE, 5, 0, 100,\n\n ]);\n\n\n", "file_path": "kaylee/src/instructions/program.rs", "rank": 31, "score": 51817.19842627562 }, { "content": "enum SignatureState {\n\n Identifier,\n\n Operands,\n\n}\n\n\n", "file_path": "kaylee_derive/src/lib.rs", "rank": 32, "score": 46169.48695693795 }, { "content": "fn main() {\n\n let mut repl = Repl::new();\n\n repl.run();\n\n}\n", "file_path": "kaylee/src/main.rs", "rank": 33, "score": 39747.42800966529 }, { "content": " self.bytes.extend(iter)\n\n }\n\n}\n\n\n\nimpl Program {\n\n pub fn new() -> Self {\n\n Program {\n\n bytes: Vec::new()\n\n }\n\n }\n\n\n\n pub fn len(&self) -> usize {\n\n self.bytes.len()\n\n }\n\n\n\n pub fn bytes(&self) -> &Vec<u8> {\n\n &self.bytes\n\n }\n\n}\n\n\n", "file_path": "kaylee/src/program.rs", "rank": 34, "score": 28987.22215438373 }, { "content": "impl<'a> TryFrom<Parsed<'a>> for Program {\n\n type Error = AssemblerError;\n\n\n\n fn try_from(parsed: Parsed) -> Result<Self, Self::Error> {\n\n let assembler = Assembler::new();\n\n assembler.assemble_parsed_asm(parsed)\n\n }\n\n}\n\n\n\nimpl TryFrom<Source> for Program {\n\n type Error = AssemblerError;\n\n\n\n fn try_from(source: Source) -> Result<Self, Self::Error> {\n\n // let parsed = Parsed::try_from(source);\n\n let parsed = parse_asm(source.body.as_str());\n\n match parsed {\n\n Ok(success) => {\n\n success.1.try_into()\n\n }\n\n Err(_) => Err(AssemblerError::Other(String::from(\"Parsing error\")))\n\n }\n\n }\n\n}\n\n\n\n// impl IndexMut<ProgramIndex> for Program {\n\n// fn index_mut(&mut self, index: ProgramIndex) -> &mut Self::Output {\n\n// todo!()\n\n// }\n\n// }", "file_path": "kaylee/src/program.rs", "rank": 35, "score": 28986.833589014 }, { "content": "use std::ops::Index;\n\nuse std::vec::IntoIter;\n\n\n\nuse crate::asm::{Parsed, Source};\n\nuse crate::asm::assembler::{Assembler, AssemblerError};\n\nuse crate::asm::parser::parse_asm;\n\nuse crate::vm::Byte;\n\n\n\npub type ProgramIndex = usize;\n\n\n\n#[derive(PartialEq, Debug)]\n\npub struct Program {\n\n bytes: Vec<Byte>,\n\n}\n\n\n\nimpl Index<ProgramIndex> for Program {\n\n type Output = Byte;\n\n\n\n fn index(&self, index: ProgramIndex) -> &Self::Output {\n\n &self.bytes[index]\n", "file_path": "kaylee/src/program.rs", "rank": 36, "score": 28982.851991862455 }, { "content": " }\n\n}\n\n\n\nimpl IntoIterator for Program {\n\n type Item = u8;\n\n type IntoIter = IntoIter<Byte>;\n\n\n\n fn into_iter(self) -> Self::IntoIter {\n\n self.bytes.into_iter()\n\n }\n\n}\n\n\n\nimpl From<Vec<Byte>> for Program {\n\n fn from(bytes: Vec<Byte>) -> Self {\n\n Program { bytes }\n\n }\n\n}\n\n\n\nimpl Extend<Byte> for Program {\n\n fn extend<T: IntoIterator<Item=Byte>>(&mut self, iter: T) {\n", "file_path": "kaylee/src/program.rs", "rank": 37, "score": 28981.008979455553 }, { "content": "/// Decode a single operand from a Halfword in the Instruction Stream\n\nimpl TryFrom<HalfWord> for OperandValue {\n\n type Error = ();\n\n\n\n fn try_from(value: HalfWord) -> Result<Self, Self::Error> {\n\n Ok(OperandValue::HalfWord(value))\n\n }\n\n}\n\n\n\nimpl OperandValue {\n\n /// Get the OperandValue as a RegisterId\n\n // @todo: I tried to do these conversions using TryFrom and a generic `into<T>(&self) -> T` function, but neither worked.\n\n // @todo: There is certainly a more idiomatic way\n\n fn as_register_id(&self) -> RegisterId {\n\n match self {\n\n OperandValue::Byte(value) => *value as usize,\n\n OperandValue::HalfWord(value) => *value as usize,\n\n OperandValue::Word(value) => *value as usize,\n\n OperandValue::None => panic!(\"Did not receive a destination register\")\n\n }\n", "file_path": "kaylee/src/instructions.rs", "rank": 38, "score": 24939.74845596034 }, { "content": "mod misc;\n\n\n\n/// Type for the three operand slots allowed for each instruction\n\npub type RegisteredInstruction = (&'static str, u8, [OperandType; 3]);\n\n\n\n/// Data Repository for Registered Instructions. \n\n/// Not intended to be directly accessed. Use `InstructionRegistry` instead.\n\n#[distributed_slice]\n\npub static _INSTRUCTION_REGISTRY: [RegisteredInstruction] = [..];\n\n\n\n/// Link-time built registry of all allowed instructions, including signatures.\n\n/// Useful for parsing, listing, and examining instructions\n\npub struct InstructionRegistry {}\n\n\n\nimpl InstructionRegistry {\n\n /// Get a RegisteredInstruction from the InstructionRegistry if it exists\n\n pub fn get(operation: &str) -> Option<&RegisteredInstruction> {\n\n let mut item: Option<&RegisteredInstruction> = None;\n\n for registered_instruction in _INSTRUCTION_REGISTRY {\n\n if registered_instruction.0 == operation {\n", "file_path": "kaylee/src/instructions.rs", "rank": 39, "score": 24932.38506294413 }, { "content": "use std::fmt::Error;\n\n\n\nuse linkme::distributed_slice;\n\n\n\nuse crate::instructions::compare::{Equal, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEqual};\n\nuse crate::instructions::data::Load;\n\nuse crate::instructions::machine::Halt;\n\nuse crate::instructions::math::{Add, Divide, Multiply, Subtract};\n\nuse crate::instructions::program::{Jump, JumpBackward, JumpEqual, JumpForward};\n\nuse crate::program::{Program, ProgramIndex};\n\nuse crate::vm::{Byte, ExecutionResult, HalfWord, Kaylee, RegisterId, RegisterValue, Word};\n\n\n\nmod machine;\n\nmod data;\n\nmod math;\n\nmod program;\n\nmod compare;\n\nmod logical;\n\nmod system;\n\nmod library;\n", "file_path": "kaylee/src/instructions.rs", "rank": 40, "score": 24931.213034817247 }, { "content": " item = Some(registered_instruction);\n\n break;\n\n }\n\n }\n\n\n\n item\n\n }\n\n}\n\n\n\n/// Errors concerning decoding instruction bytecode\n\n#[derive(Debug)]\n\npub enum InstructionDecodeError {\n\n InvalidValueSize,\n\n IllegalOpcode,\n\n}\n\n\n\n/// Decode the next instruction in the Program stream\n", "file_path": "kaylee/src/instructions.rs", "rank": 41, "score": 24931.145004116748 }, { "content": " OperandValue::Byte(value) => value.to_string(),\n\n OperandValue::HalfWord(value) => value.to_string(),\n\n OperandValue::Word(value) => value.to_string(),\n\n OperandValue::None => panic!(\"Did not receive a destination register\")\n\n }\n\n }\n\n}\n\n\n\n/// Defines an Instruction's Signature\n\npub struct InstructionSignature {\n\n pub identifier: String,\n\n pub operands: [OperandType; 3],\n\n}\n\n\n\n/// Defines an Instruction's documentation\n\npub struct InstructionDocumentation {\n\n pub name: String,\n\n pub help: String,\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 42, "score": 24928.690527595598 }, { "content": " }\n\n\n\n /// Get the OperandValue as a Program Index Target\n\n fn as_program_index(&self) -> ProgramIndex {\n\n self.as_register_id() as ProgramIndex\n\n }\n\n\n\n /// Get the OperandValue as a constant literal value (integer)\n\n fn as_constant_value(&self) -> RegisterValue {\n\n match self {\n\n OperandValue::Byte(value) => *value as RegisterValue,\n\n OperandValue::HalfWord(value) => *value as RegisterValue,\n\n OperandValue::Word(value) => *value as RegisterValue,\n\n OperandValue::None => panic!(\"Did not receive a destination register\")\n\n }\n\n }\n\n\n\n /// Get the OperandValue as a string\n\n pub(crate) fn as_string(&self) -> String {\n\n match self {\n", "file_path": "kaylee/src/instructions.rs", "rank": 43, "score": 24928.038365970664 }, { "content": " let b = (instructions[*program_counter + 1] as Word) << 8;\n\n let c = instructions[*program_counter + 2] as Word;\n\n\n\n let value = (a | b | c) as u32;\n\n\n\n operand_values[index] = OperandValue::Word(value);\n\n\n\n *program_counter += 3;\n\n }\n\n };\n\n }\n\n\n\n if (original_pc + 3) != *program_counter {\n\n *program_counter = original_pc + 3;\n\n }\n\n Ok(operand_values)\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 44, "score": 24923.857164907342 }, { "content": " if index > 2 {\n\n return Err(\"Index Out Of Bounds\".to_string());\n\n }\n\n\n\n Ok(&self.operand_values()[index])\n\n }\n\n\n\n /// Get a concrete value from a register by looking at the target in an OperandValue\n\n fn get_register_value_for_operand(&self, operand_value_index: usize, vm: &mut Kaylee) -> Result<RegisterValue, ()> {\n\n let register = self.operand_values()[operand_value_index].as_register_id();\n\n vm.register(register)\n\n }\n\n}", "file_path": "kaylee/src/instructions.rs", "rank": 45, "score": 24923.427710254608 }, { "content": " JumpBackward::OPCODE => build::<JumpBackward>(instructions, program_counter),\n\n JumpEqual::OPCODE => build::<JumpEqual>(instructions, program_counter),\n\n\n\n Equal::OPCODE => build::<Equal>(instructions, program_counter),\n\n NotEqual::OPCODE => build::<NotEqual>(instructions, program_counter),\n\n GreaterThan::OPCODE => build::<GreaterThan>(instructions, program_counter),\n\n LessThan::OPCODE => build::<LessThan>(instructions, program_counter),\n\n GreaterThanOrEqual::OPCODE => build::<GreaterThanOrEqual>(instructions, program_counter),\n\n LessThanOrEqual::OPCODE => build::<LessThanOrEqual>(instructions, program_counter),\n\n\n\n _ => {\n\n Err(InstructionDecodeError::IllegalOpcode)\n\n }\n\n })\n\n}\n\n\n", "file_path": "kaylee/src/instructions.rs", "rank": 46, "score": 24923.265942781323 }, { "content": "//! Instructions for manipulating data (registers and memory)\n\n//! Opcodes reserved: 30 - 49\n\nuse std::fmt::Error;\n\n\n\nuse kaylee_derive::Instruction;\n\n\n\nuse crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues};\n\nuse crate::vm::{ExecutionResult, Kaylee};\n\n\n\n/// LOAD: Loads a value into a designated register\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `#2` | 2 Bytes | HalfWord | Literal value to be loaded\n\n/// - 2: NOT USED, given to Operand 1\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If register is out of bounds\n\n/// - `AssemblerError` or `ProgramPanic`: If Constant value is too large for 2 bytes\n\n///\n\n/// Examples\n", "file_path": "kaylee/src/instructions/data.rs", "rank": 47, "score": 23980.105988999192 }, { "content": "//! Instructions for arithmetic operations\n\n//! Opcodes reserved: 70 - 99\n\nuse std::fmt::Error;\n\n\n\nuse kaylee_derive::Instruction;\n\n\n\nuse crate::instructions;\n\nuse crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues};\n\nuse crate::vm::{ExecutionResult, Kaylee, RegisterValue};\n\n\n\n/// Add: Sums the value of two registers and loads the result into a third register\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n/// - `RuntimeError`: If the result is too large for a destination register\n\n///\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 48, "score": 23978.682959900067 }, { "content": "//! Instructions for controlling the Virtual Machine\n\n//! Opcodes reserved: 0 - 29\n\nuse std::fmt::Error;\n\n\n\nuse kaylee_derive::Instruction;\n\n\n\nuse crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues};\n\nuse crate::vm::{ExecutionResult, Kaylee};\n\n\n\n/// Halt: Gracefully ends the program and shuts down the process\n\n/// Operands:\n\n/// - None\n\n///\n\n/// Errors/ Panics\n\n/// - None\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// HALT // `01 00 00 00`\n\n/// ```\n", "file_path": "kaylee/src/instructions/machine.rs", "rank": 49, "score": 23978.655504052316 }, { "content": "//! Instructions for comparisons\n\n//! Opcodes reserved: 100 - 119\n\nuse std::fmt::Error;\n\n\n\nuse kaylee_derive::Instruction;\n\n\n\nuse crate::instructions;\n\nuse crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues};\n\nuse crate::vm::{ExecutionResult, Kaylee, RegisterValue};\n\n\n\n/// Equal: Stores a boolean in a destination with the comparison result from two register values\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n///\n\n/// Examples\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 50, "score": 23978.285491159357 }, { "content": "\n\nimpl Executable for LessThanOrEqual {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left <= right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n match result {\n\n 1 => Ok(ExecutionResult::Equality(true)),\n\n 0 => Ok(ExecutionResult::Equality(false)),\n\n _ => panic!(\"Equality returned something other than a 0 or 1\")\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::instructions::compare::{Equal, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEqual};\n\n use crate::program::Program;\n\n use crate::vm::Kaylee;\n\n\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 51, "score": 23977.90487120762 }, { "content": "#[derive(Instruction)]\n\n#[opcode = 1]\n\n#[signature = \"HALT\"]\n\npub struct Halt {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Halt {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n vm.halt();\n\n Ok(ExecutionResult::Halted)\n\n }\n\n}", "file_path": "kaylee/src/instructions/machine.rs", "rank": 52, "score": 23976.95146673089 }, { "content": " operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Subtract {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left - right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n Ok(ExecutionResult::Value(result))\n\n }\n\n}\n\n\n\n/// Multiply: Multiplies the values of two registers and loads the result into a third register\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 53, "score": 23975.940325585114 }, { "content": " }\n\n}\n\n\n\n/// Divide: Divides the values of two registers, loads the result into a third register, and saves the remainder\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n/// - `RuntimeError`: If the result is too large for a destination register\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// DIV $01 $10 $30 // `49 01 0A 1E` - Divides the values of registers 10 and 30 ($10 / $30), stores the result in register 1, with the remainder\n\n/// DIV $40 $01 $10 // `48 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 73]\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 54, "score": 23975.76683110912 }, { "content": " fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left > right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n match result {\n\n 1 => Ok(ExecutionResult::Equality(true)),\n\n 0 => Ok(ExecutionResult::Equality(false)),\n\n _ => panic!(\"Equality returned something other than a 0 or 1\")\n\n }\n\n }\n\n}\n\n\n\n/// LessThan: Stores a boolean in a destination with the comparison result from two register values\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 55, "score": 23975.766391764704 }, { "content": "///\n\n/// Examples\n\n/// ```asm\n\n/// LT $01 $10 $30 // `6E 01 0A 1E` - Loads true/false into register 1 based on comparison from values in registers 10 and 30\n\n/// LT $40 $01 $10 // `6E 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 113]\n\n#[signature = \"LT $D $L $R\"]\n\npub struct LessThan {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for LessThan {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left < right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n match result {\n\n 1 => Ok(ExecutionResult::Equality(true)),\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 56, "score": 23975.58810334726 }, { "content": "#[signature = \"DIV $D $L $R\"]\n\npub struct Divide {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Divide {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let destination = self.operand_values[0].as_register_id();\n\n\n\n let left = self.get_register_value_for_operand(1, vm).unwrap();\n\n let right = self.get_register_value_for_operand(2, vm).unwrap();\n\n\n\n let value = left / right;\n\n let remainder = (left % right) as u32;\n\n\n\n vm.set_register(destination, value).unwrap();\n\n vm.set_remainder(remainder);\n\n\n\n Ok(ExecutionResult::Value(value))\n\n }\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 57, "score": 23975.40939800515 }, { "content": "#[derive(Instruction)]\n\n#[opcode = 114]\n\n#[signature = \"GTE $D $L $R\"]\n\npub struct GreaterThanOrEqual {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for GreaterThanOrEqual {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left >= right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n match result {\n\n 1 => Ok(ExecutionResult::Equality(true)),\n\n 0 => Ok(ExecutionResult::Equality(false)),\n\n _ => panic!(\"Equality returned something other than a 0 or 1\")\n\n }\n\n }\n\n}\n\n\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 58, "score": 23975.368011362913 }, { "content": "/// ```asm\n\n/// EQ $01 $10 $30 // `6E 01 0A 1E` - Loads true/false into register 1 based on comparison from values in registers 10 and 30\n\n/// EQ $40 $01 $10 // `6E 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 110]\n\n#[signature = \"EQ $D $L $R\"]\n\npub struct Equal {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Equal {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left == right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n match result {\n\n 1 => Ok(ExecutionResult::Equality(true)),\n\n 0 => Ok(ExecutionResult::Equality(false)),\n\n _ => panic!(\"Equality returned something other than a 0 or 1\")\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 59, "score": 23975.0256083929 }, { "content": "/// - `RuntimeError`: If the result is too large for a destination register\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// MUL $01 $10 $30 // `48 01 0A 1E` - Multiplies the value of register 10 and the value of register 30 ($10 * $30), and stores the result in register 1\n\n/// MUL $40 $01 $10 // `48 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 72]\n\n#[signature = \"MUL $D $L $R\"]\n\npub struct Multiply {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Multiply {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left * right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n Ok(ExecutionResult::Value(result))\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 60, "score": 23974.566692891254 }, { "content": "#[signature = \"NEQ $D $L $R\"]\n\npub struct NotEqual {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for NotEqual {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left != right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n match result {\n\n 1 => Ok(ExecutionResult::Equality(true)),\n\n 0 => Ok(ExecutionResult::Equality(false)),\n\n _ => panic!(\"Equality returned something other than a 0 or 1\")\n\n }\n\n }\n\n}\n\n\n\n/// GreaterThan: Stores a boolean in a destination with the comparison result from two register values\n\n/// Operands:\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 61, "score": 23974.451194963065 }, { "content": "\n\n/// Subtract: Subtracts the values of two registers and loads the result into a third register\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n/// - `RuntimeError`: If the result is too large for a destination register\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// SUB $01 $10 $30 // `47 01 0A 1E` - Subtracts the value of register 30 from the value of register 10 ($10 - $30), and stores the result in register 1\n\n/// SUB $40 $01 $10 // `47 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 71]\n\n#[signature = \"SUB $D $L $R\"]\n\npub struct Subtract {\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 62, "score": 23974.43517777899 }, { "content": "/// Examples\n\n/// ```asm\n\n/// ADD $01 $10 $30 // `46 01 0A 1E` - Adds the value of register 10 to the value of register 30 ($10 + $30), and stores the result in register 1\n\n/// ADD $40 $01 $10 // `46 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 70]\n\n#[signature = \"ADD $D $L $R\"]\n\npub struct Add {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Add {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let callback = |left: RegisterValue, right: RegisterValue| { (left + right) as RegisterValue };\n\n\n\n let result = instructions::basic_register_execution(self, vm, callback);\n\n Ok(ExecutionResult::Value(result))\n\n }\n\n}\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 63, "score": 23974.434448518965 }, { "content": "/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// GT $01 $10 $30 // `6E 01 0A 1E` - Loads true/false into register 1 based on comparison from values in registers 10 and 30\n\n/// GT $40 $01 $10 // `6E 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 112]\n\n#[signature = \"GT $D $L $R\"]\n\npub struct GreaterThan {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for GreaterThan {\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 64, "score": 23973.410895185716 }, { "content": "/// LessThanOrEqual: Stores a boolean in a destination with the comparison result from two register values\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// LTE $01 $10 $30 // `6E 01 0A 1E` - Loads true/false into register 1 based on comparison from values in registers 10 and 30\n\n/// LTE $40 $01 $10 // `6E 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 115]\n\n#[signature = \"LTE $D $L $R\"]\n\npub struct LessThanOrEqual {\n\n operand_values: OperandValues,\n\n}\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 65, "score": 23972.71870017304 }, { "content": "/// ```asm\n\n/// LOAD $1 #500 // `1E 01 01 FF` - Loads 500 into Register 1\n\n/// LOAD $31 #01 // `1E 1F 00 01` - Loads 1 into Register 31\n\n/// LOAD $40 #10 // `1E 28 00 0A` - Assembler Error because 40 is not a valid register\n\n/// LOAD $15 #1,000,000 // `1E 0F 00 0A` - Assembler Error because constant value is out of bounds\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 30]\n\n#[signature = \"LOAD $D #2\"]\n\npub struct Load {\n\n operand_values: OperandValues,\n\n}\n\n\n\nimpl Executable for Load {\n\n fn execute(&self, vm: &mut Kaylee) -> Result<ExecutionResult, Error> {\n\n let destination = self.operand_value(0).unwrap().as_register_id();\n\n let value = self.operand_value(1).unwrap().as_constant_value();\n\n\n\n vm.set_register(destination, value).unwrap();\n\n Ok(ExecutionResult::Value(value))\n", "file_path": "kaylee/src/instructions/data.rs", "rank": 66, "score": 23972.7059726983 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::instructions::math::{Add, Divide, Multiply, Subtract};\n\n use crate::program::Program;\n\n use crate::vm::Kaylee;\n\n\n\n #[test]\n\n fn test_add() {\n\n let program = Program::from(vec![\n\n Add::OPCODE, 29, 0, 2,\n\n Add::OPCODE, 30, 1, 3,\n\n Add::OPCODE, 31, 29, 30,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(0, 12).unwrap();\n\n vm.set_register(1, 10).unwrap();\n\n vm.set_register(2, 500).unwrap();\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 67, "score": 23972.69494989976 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::instructions::data::Load;\n\n use crate::program::Program;\n\n use crate::vm::Kaylee;\n\n\n\n #[test]\n\n fn test_load() {\n\n let program = Program::from(vec![\n\n Load::OPCODE, 4, 1, 244, // LOAD $4 #500\n\n Load::OPCODE, 30, 0, 12, // LOAD $6 #12\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.run(program);\n\n\n\n assert_eq!(500, vm.register(4).unwrap());\n\n assert_eq!(12, vm.register(30).unwrap());\n\n }\n\n}", "file_path": "kaylee/src/instructions/data.rs", "rank": 68, "score": 23972.664963685223 }, { "content": " }\n\n }\n\n}\n\n\n\n/// NotEqual: Stores a boolean in a destination with the comparison result from two register values\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// NEQ $01 $10 $30 // `6E 01 0A 1E` - Loads true/false into register 1 based on comparison from values in registers 10 and 30\n\n/// NEQ $40 $01 $10 // `6E 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n\n#[derive(Instruction)]\n\n#[opcode = 111]\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 69, "score": 23972.017832959744 }, { "content": " assert_eq!(384, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_divide_no_remainder() {\n\n let program = Program::from(vec![\n\n Divide::OPCODE, 31, 0, 1,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(0, 16).unwrap();\n\n vm.set_register(1, 2).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(8, vm.register(31).unwrap());\n\n assert_eq!(0, vm.remainder());\n\n }\n\n\n\n #[test]\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 70, "score": 23971.37022858512 }, { "content": " fn test_divide_with_remainder() {\n\n let program = Program::from(vec![\n\n Divide::OPCODE, 31, 0, 1,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(0, 13).unwrap();\n\n vm.set_register(1, 5).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(2, vm.register(31).unwrap());\n\n assert_eq!(3, vm.remainder());\n\n }\n\n\n\n #[test]\n\n fn test_math() {\n\n let program = Program::from(vec![\n\n Add::OPCODE, 29, 0, 2,\n\n Add::OPCODE, 30, 29, 2,\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 71, "score": 23971.249440819156 }, { "content": " 0 => Ok(ExecutionResult::Equality(false)),\n\n _ => panic!(\"Equality returned something other than a 0 or 1\")\n\n }\n\n }\n\n}\n\n\n\n/// GreaterThanOrEqual: Stores a boolean in a destination with the comparison result from two register values\n\n/// Operands:\n\n/// - 0: `$D` | 1 Byte | RegisterId | RegisterId of the destination register (0-31)\n\n/// - 1: `$L` | 1 Byte | RegisterId | RegisterId of the left term\n\n/// - 2: `$R` | 1 Byte | RegisterId | RegisterId of the right term\n\n///\n\n/// Errors/ Panics\n\n/// - `AssemblerError` or `ProgramPanic`: If any register is out of bounds\n\n///\n\n/// Examples\n\n/// ```asm\n\n/// GTE $01 $10 $30 // `6E 01 0A 1E` - Loads true/false into register 1 based on comparison from values in registers 10 and 30\n\n/// GTE $40 $01 $10 // `6E 28 01 0A` - AssemblerError because 40 is not a valid register\n\n/// ```\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 72, "score": 23970.826119696696 }, { "content": " let program = Program::from(vec![\n\n GreaterThan::OPCODE, 30, 1, 2, // Pass\n\n GreaterThan::OPCODE, 31, 3, 4, // Fail\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(1, 300).unwrap();\n\n vm.set_register(2, 200).unwrap();\n\n vm.set_register(3, 200).unwrap();\n\n vm.set_register(4, 300).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(1, vm.register(30).unwrap());\n\n assert_eq!(0, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_less_than() {\n\n let program = Program::from(vec![\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 73, "score": 23968.381616061804 }, { "content": " let program = Program::from(vec![\n\n Multiply::OPCODE, 29, 0, 2,\n\n Multiply::OPCODE, 30, 1, 3,\n\n Multiply::OPCODE, 31, 29, 30,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(0, 2).unwrap();\n\n vm.set_register(1, 4).unwrap();\n\n vm.set_register(2, 6).unwrap();\n\n vm.set_register(3, 8).unwrap();\n\n\n\n // $29[12] = 2 * 6\n\n // $30[32] = 4 * 8\n\n // $31[384] = 12 * 32\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(12, vm.register(29).unwrap());\n\n assert_eq!(32, vm.register(30).unwrap());\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 74, "score": 23968.35941429425 }, { "content": " #[test]\n\n fn test_equal() {\n\n let program = Program::from(vec![\n\n Equal::OPCODE, 30, 1, 2, // Pass\n\n Equal::OPCODE, 31, 3, 4, // Fail\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(1, 100).unwrap();\n\n vm.set_register(2, 100).unwrap();\n\n vm.set_register(3, 200).unwrap();\n\n vm.set_register(4, 500).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(1, vm.register(30).unwrap());\n\n assert_eq!(0, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 75, "score": 23968.10859658204 }, { "content": " fn test_not_equal() {\n\n let program = Program::from(vec![\n\n NotEqual::OPCODE, 30, 1, 2, // Pass\n\n NotEqual::OPCODE, 31, 3, 4, // Fail\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(1, 100).unwrap();\n\n vm.set_register(2, 200).unwrap();\n\n vm.set_register(3, 300).unwrap();\n\n vm.set_register(4, 300).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(1, vm.register(30).unwrap());\n\n assert_eq!(0, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_greater_than() {\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 76, "score": 23968.04815087493 }, { "content": " LessThan::OPCODE, 30, 1, 2, // Pass\n\n LessThan::OPCODE, 31, 3, 4, // Fail\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(1, 100).unwrap();\n\n vm.set_register(2, 200).unwrap();\n\n vm.set_register(3, 400).unwrap();\n\n vm.set_register(4, 300).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(1, vm.register(30).unwrap());\n\n assert_eq!(0, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_greater_than_or_equal() {\n\n let program = Program::from(vec![\n\n GreaterThanOrEqual::OPCODE, 28, 1, 2, // Pass\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 77, "score": 23967.871891324045 }, { "content": "\n\n let mut vm = Kaylee::new();\n\n vm.set_register(0, 222).unwrap();\n\n vm.set_register(1, 14).unwrap();\n\n vm.set_register(2, 22).unwrap();\n\n vm.set_register(3, 3).unwrap();\n\n\n\n // $29[200] = 222 - 22\n\n // $30[11] = 14 - 3\n\n // $31[189] = 200 - 11\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(200, vm.register(29).unwrap());\n\n assert_eq!(11, vm.register(30).unwrap());\n\n assert_eq!(189, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_multiply() {\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 78, "score": 23967.45347382499 }, { "content": "\n\n #[test]\n\n fn test_less_than_or_equal() {\n\n let program = Program::from(vec![\n\n LessThanOrEqual::OPCODE, 28, 1, 2, // Pass\n\n LessThanOrEqual::OPCODE, 29, 3, 4, // Pass\n\n LessThanOrEqual::OPCODE, 30, 5, 6, // Fail\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(1, 100).unwrap();\n\n vm.set_register(2, 200).unwrap();\n\n\n\n vm.set_register(3, 200).unwrap();\n\n vm.set_register(4, 200).unwrap();\n\n\n\n vm.set_register(5, 400).unwrap();\n\n vm.set_register(6, 300).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(1, vm.register(28).unwrap());\n\n assert_eq!(1, vm.register(29).unwrap());\n\n assert_eq!(0, vm.register(30).unwrap());\n\n }\n\n}\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 79, "score": 23967.343251360566 }, { "content": " GreaterThanOrEqual::OPCODE, 29, 3, 4, // Pass\n\n GreaterThanOrEqual::OPCODE, 30, 5, 6, // Fail\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(1, 200).unwrap();\n\n vm.set_register(2, 100).unwrap();\n\n\n\n vm.set_register(3, 200).unwrap();\n\n vm.set_register(4, 200).unwrap();\n\n\n\n vm.set_register(5, 200).unwrap();\n\n vm.set_register(6, 300).unwrap();\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(1, vm.register(28).unwrap());\n\n assert_eq!(1, vm.register(29).unwrap());\n\n assert_eq!(0, vm.register(30).unwrap());\n\n }\n", "file_path": "kaylee/src/instructions/compare.rs", "rank": 80, "score": 23966.794349651373 }, { "content": " Subtract::OPCODE, 30, 29, 1,\n\n Add::OPCODE, 28, 3, 4,\n\n Multiply::OPCODE, 31, 3, 2,\n\n Divide::OPCODE, 3, 29, 30,\n\n Subtract::OPCODE, 4, 2, 30,\n\n Add::OPCODE, 0, 3, 28,\n\n Multiply::OPCODE, 1, 3, 4,\n\n Divide::OPCODE, 31, 28, 30,\n\n ]);\n\n\n\n let mut vm = Kaylee::new();\n\n vm.set_register(0, 2).unwrap();\n\n vm.set_register(1, 4).unwrap();\n\n vm.set_register(2, 6).unwrap();\n\n vm.set_register(3, 8).unwrap();\n\n vm.set_register(4, 9).unwrap();\n\n\n\n // 29[8] = 2 + 6\n\n // 30[14] = 8 + 6\n\n // 30[4] = 8 - 4\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 81, "score": 23965.429908181803 }, { "content": " // 28[17] = 8 + 9\n\n // 31[48] = 8 * 6\n\n // 3[2] = 8 / 4\n\n // 4[2] = 6 - 4\n\n // 0[19] = 2 + 17\n\n // 1[4] = 2 * 2\n\n // 31[4r1] = 17 / 4\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(19, vm.register(0).unwrap());\n\n assert_eq!(4, vm.register(1).unwrap());\n\n assert_eq!(6, vm.register(2).unwrap());\n\n assert_eq!(2, vm.register(3).unwrap());\n\n assert_eq!(2, vm.register(4).unwrap());\n\n assert_eq!(17, vm.register(28).unwrap());\n\n assert_eq!(8, vm.register(29).unwrap());\n\n assert_eq!(4, vm.register(30).unwrap());\n\n assert_eq!(4, vm.register(31).unwrap());\n\n assert_eq!(1, vm.remainder());\n\n }\n\n}\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 82, "score": 23965.105621070423 }, { "content": " vm.set_register(3, 7).unwrap();\n\n\n\n // $29[512] = 12 + 500\n\n // $30[17] = 10 + 7\n\n // $31[529] = 512 + 17\n\n\n\n vm.run(program);\n\n\n\n assert_eq!(512, vm.register(29).unwrap());\n\n assert_eq!(17, vm.register(30).unwrap());\n\n assert_eq!(529, vm.register(31).unwrap());\n\n }\n\n\n\n #[test]\n\n fn test_subtract() {\n\n let program = Program::from(vec![\n\n Subtract::OPCODE, 29, 0, 2,\n\n Subtract::OPCODE, 30, 1, 3,\n\n Subtract::OPCODE, 31, 29, 30,\n\n ]);\n", "file_path": "kaylee/src/instructions/math.rs", "rank": 83, "score": 23964.20709299001 }, { "content": "//! Instructions for Misc or overflow operations\n\n//! Opcodes reserved: 220 - 255", "file_path": "kaylee/src/instructions/misc.rs", "rank": 84, "score": 23960.751084176005 }, { "content": "//! Instructions for performing logical operations (shift, or, and, etc)\n\n//! Opcodes reserved: 120 - 129", "file_path": "kaylee/src/instructions/logical.rs", "rank": 85, "score": 23960.66804822069 }, { "content": "//! Instructions for the \"standard library\"\n\n//! @todo: This and system may be merged, there is a lot of overlap in my mind\n\n//! Opcodes reserved: 180 - 219", "file_path": "kaylee/src/instructions/library.rs", "rank": 86, "score": 23960.515498193075 }, { "content": "//! Instructions for interacting the the operating environment\n\n//! These will be things like file manipulation, environment variables, networking, etc\n\n//! Opcodes reserved: 130 - 179", "file_path": "kaylee/src/instructions/system.rs", "rank": 87, "score": 23960.41152881528 }, { "content": "use crate::instructions::{InstructionRegistry, OperandType};\n\nuse crate::program::Program;\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum AssemblerError {\n\n Other(String),\n\n}\n\n\n\npub struct Assembler {\n\n // There will be state needed eventually\n\n}\n\n\n\nimpl Assembler {\n\n pub fn new() -> Self {\n\n Assembler {}\n\n }\n\n\n\n /// @todo: This is awful. Absolutely no error checking\n\n pub fn assemble_parsed_asm(&self, parsed: Vec<Vec<&str>>) -> Result<Program, AssemblerError> {\n\n let mut bytes: Vec<u8> = Vec::new();\n", "file_path": "kaylee/src/asm/assembler.rs", "rank": 91, "score": 29.986326491324746 }, { "content": "\n\n for instruction in parsed {\n\n let item = InstructionRegistry::get(instruction[0]);\n\n\n\n // Push the opcode\n\n bytes.push(item.unwrap().1.clone());\n\n\n\n for i in 1..(instruction.len()) {\n\n if let Some(value) = instruction.get(i) {\n\n // this is an operand, so we have to break it into u8 chunks\n\n let number = value.parse::<i32>().unwrap();\n\n let operand_bytes = number.to_be_bytes();\n\n\n\n let spot: &OperandType = &item.unwrap().2[i - 1];\n\n\n\n let byte_count = match spot {\n\n OperandType::None => 0 as u8,\n\n OperandType::RegisterId => 1 as u8,\n\n OperandType::ConstantByte => 1 as u8,\n\n OperandType::ConstantHalfWord => 2 as u8,\n", "file_path": "kaylee/src/asm/assembler.rs", "rank": 93, "score": 24.624146696349133 }, { "content": " Ok(instruction) => println!(\"{}\", instruction.display()),\n\n Err(_error) => panic!(\"received an error\")\n\n };\n\n }\n\n\n\n println!(\"End of instructions\");\n\n }\n\n \".registers\" => {\n\n println!(\"Listing all registers and contents\");\n\n println!(\"{:#?}\", self.vm.all_registers());\n\n println!(\"End of register listing\");\n\n }\n\n _ => {\n\n match parse_asm(buffer) {\n\n Ok(parsed) => {\n\n let assembler = Assembler::new();\n\n let results = assembler.assemble_parsed_asm(parsed.1);\n\n match results {\n\n Ok(bytes) => {\n\n let _ = &program.extend(bytes);\n", "file_path": "kaylee/src/repl.rs", "rank": 95, "score": 22.865850299296625 }, { "content": " OperandType::ConstantWord => 3 as u8,\n\n };\n\n\n\n let start_slice = (4 - byte_count) as usize;\n\n\n\n bytes.extend(&operand_bytes[start_slice..]);\n\n }\n\n }\n\n }\n\n\n\n Ok(Program::from(bytes))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::asm::assembler::Assembler;\n\n use crate::program::Program;\n\n\n\n #[test]\n", "file_path": "kaylee/src/asm/assembler.rs", "rank": 96, "score": 19.303574495977692 }, { "content": " let buffer = buffer.trim();\n\n\n\n self.command_buffer.push(buffer.to_string());\n\n\n\n match buffer {\n\n \".quit\" => {\n\n println!(\"Have a great day!\");\n\n std::process::exit(0);\n\n }\n\n \".history\" => {\n\n for command in &self.command_buffer {\n\n println!(\"{command}\");\n\n }\n\n }\n\n \".program\" => {\n\n println!(\"Listing entire program instructions\");\n\n let mut pc: usize = 0;\n\n\n\n while let Some(result) = decode_next_instruction(&program, &mut pc) {\n\n match result {\n", "file_path": "kaylee/src/repl.rs", "rank": 97, "score": 18.521267556631543 }, { "content": "use std;\n\nuse std::io;\n\nuse std::io::Write;\n\n\n\nuse nom::IResult;\n\n\n\nuse crate::asm::assembler::Assembler;\n\nuse crate::asm::parser::{line, parse_asm};\n\nuse crate::instructions::decode_next_instruction;\n\nuse crate::program::Program;\n\nuse crate::shared::parse_hex;\n\nuse crate::vm::Kaylee;\n\n\n\n/// Core structure for the REPL for the Assembler\n\npub struct Repl {\n\n command_buffer: Vec<String>,\n\n vm: Kaylee,\n\n}\n\n\n\nimpl Repl {\n", "file_path": "kaylee/src/repl.rs", "rank": 98, "score": 16.015478173138675 } ]
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 reverse order so as to\n\n// maintain a pre-order traversal. As of the time of this\n\n// writing, the fact that the traversal is pre-order is not\n\n// known to be significant to any code, but it seems like the\n\n// natural order one would expect (basically, the order of the\n\n// types as they are written).\n\nfn push_subtypes<'tcx>(stack: &mut TypeWalkerStack<'tcx>, parent_ty: Ty<'tcx>) {\n\n match parent_ty.sty {\n\n ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) |\n\n ty::TyStr | ty::TyInfer(_) | ty::TyParam(_) | ty::TyNever | ty::TyError => {\n\n }\n\n ty::TyArray(ty, _) | ty::TySlice(ty) => {\n\n stack.push(ty);\n\n }\n\n ty::TyRawPtr(ref mt) | ty::TyRef(_, ref mt) => {\n\n stack.push(mt.ty);\n\n }\n\n ty::TyProjection(ref data) => {\n\n stack.extend(data.trait_ref.substs.types().rev());\n\n }\n\n ty::TyDynamic(ref obj, ..) => {\n\n stack.extend(obj.iter().rev().flat_map(|predicate| {\n\n let (substs, opt_ty) = match *predicate.skip_binder() {\n\n ty::ExistentialPredicate::Trait(tr) => (tr.substs, None),\n\n ty::ExistentialPredicate::Projection(p) =>\n\n (p.trait_ref.substs, Some(p.ty)),\n", "file_path": "src/librustc/ty/walk.rs", "rank": 1, "score": 501951.94737605785 }, { "content": "/// Order the predicates in `predicates` such that each parameter is\n\n/// constrained before it is used, if that is possible, and add the\n\n/// paramaters so constrained to `input_parameters`. For example,\n\n/// imagine the following impl:\n\n///\n\n/// impl<T: Debug, U: Iterator<Item=T>> Trait for U\n\n///\n\n/// The impl's predicates are collected from left to right. Ignoring\n\n/// the implicit `Sized` bounds, these are\n\n/// * T: Debug\n\n/// * U: Iterator\n\n/// * <U as Iterator>::Item = T -- a desugared ProjectionPredicate\n\n///\n\n/// When we, for example, try to go over the trait-reference\n\n/// `IntoIter<u32> as Trait`, we substitute the impl parameters with fresh\n\n/// variables and match them with the impl trait-ref, so we know that\n\n/// `$U = IntoIter<u32>`.\n\n///\n\n/// However, in order to process the `$T: Debug` predicate, we must first\n\n/// know the value of `$T` - which is only given by processing the\n\n/// projection. As we occasionally want to process predicates in a single\n\n/// pass, we want the projection to come first. In fact, as projections\n\n/// can (acyclically) depend on one another - see RFC447 for details - we\n\n/// need to topologically sort them.\n\n///\n\n/// We *do* have to be somewhat careful when projection targets contain\n\n/// projections themselves, for example in\n\n/// impl<S,U,V,W> Trait for U where\n\n/// /* 0 */ S: Iterator<Item=U>,\n\n/// /* - */ U: Iterator,\n\n/// /* 1 */ <U as Iterator>::Item: ToOwned<Owned=(W,<V as Iterator>::Item)>\n\n/// /* 2 */ W: Iterator<Item=V>\n\n/// /* 3 */ V: Debug\n\n/// we have to evaluate the projections in the order I wrote them:\n\n/// `V: Debug` requires `V` to be evaluated. The only projection that\n\n/// *determines* `V` is 2 (1 contains it, but *does not determine it*,\n\n/// as it is only contained within a projection), but that requires `W`\n\n/// which is determined by 1, which requires `U`, that is determined\n\n/// by 0. I should probably pick a less tangled example, but I can't\n\n/// think of any.\n\npub fn setup_constraining_predicates<'tcx>(predicates: &mut [ty::Predicate<'tcx>],\n\n impl_trait_ref: Option<ty::TraitRef<'tcx>>,\n\n input_parameters: &mut FxHashSet<Parameter>)\n\n{\n\n // The canonical way of doing the needed topological sort\n\n // would be a DFS, but getting the graph and its ownership\n\n // right is annoying, so I am using an in-place fixed-point iteration,\n\n // which is `O(nt)` where `t` is the depth of type-parameter constraints,\n\n // remembering that `t` should be less than 7 in practice.\n\n //\n\n // Basically, I iterate over all projections and swap every\n\n // \"ready\" projection to the start of the list, such that\n\n // all of the projections before `i` are topologically sorted\n\n // and constrain all the parameters in `input_parameters`.\n\n //\n\n // In the example, `input_parameters` starts by containing `U` - which\n\n // is constrained by the trait-ref - and so on the first pass we\n\n // observe that `<U as Iterator>::Item = T` is a \"ready\" projection that\n\n // constrains `T` and swap it to front. As it is the sole projection,\n\n // no more swaps can take place afterwards, with the result being\n", "file_path": "src/librustc_typeck/constrained_type_params.rs", "rank": 2, "score": 496580.9744713821 }, { "content": "fn push_region_constraints<'tcx>(out: &mut Vec<Component<'tcx>>, regions: Vec<&'tcx ty::Region>) {\n\n for r in regions {\n\n if !r.is_bound() {\n\n out.push(Component::Region(r));\n\n }\n\n }\n\n}\n", "file_path": "src/librustc/ty/outlives.rs", "rank": 3, "score": 487584.9606860689 }, { "content": "pub fn unsized_info_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type {\n\n let unsized_part = ccx.tcx().struct_tail(ty);\n\n match unsized_part.sty {\n\n ty::TyStr | ty::TyArray(..) | ty::TySlice(_) => {\n\n Type::uint_from_ty(ccx, ast::UintTy::Us)\n\n }\n\n ty::TyDynamic(..) => Type::vtable_ptr(ccx),\n\n _ => bug!(\"Unexpected tail in unsized_info_ty: {:?} for ty={:?}\",\n\n unsized_part, ty)\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/type_of.rs", "rank": 4, "score": 471953.001297887 }, { "content": "/// When we have an implied bound that `T: 'a`, we can further break\n\n/// this down to determine what relationships would have to hold for\n\n/// `T: 'a` to hold. We get to assume that the caller has validated\n\n/// those relationships.\n\nfn implied_bounds_from_components<'tcx>(sub_region: &'tcx ty::Region,\n\n sup_components: Vec<Component<'tcx>>)\n\n -> Vec<ImpliedBound<'tcx>>\n\n{\n\n sup_components\n\n .into_iter()\n\n .flat_map(|component| {\n\n match component {\n\n Component::Region(r) =>\n\n vec![ImpliedBound::RegionSubRegion(sub_region, r)],\n\n Component::Param(p) =>\n\n vec![ImpliedBound::RegionSubParam(sub_region, p)],\n\n Component::Projection(p) =>\n\n vec![ImpliedBound::RegionSubProjection(sub_region, p)],\n\n Component::EscapingProjection(_) =>\n\n // If the projection has escaping regions, don't\n\n // try to infer any implied bounds even for its\n\n // free components. This is conservative, because\n\n // the caller will still have to prove that those\n\n // free components outlive `sub_region`. But the\n", "file_path": "src/librustc/ty/wf.rs", "rank": 5, "score": 445176.74044775934 }, { "content": "fn push_sig_subtypes<'tcx>(stack: &mut TypeWalkerStack<'tcx>, sig: ty::PolyFnSig<'tcx>) {\n\n stack.push(sig.skip_binder().output());\n\n stack.extend(sig.skip_binder().inputs().iter().cloned().rev());\n\n}\n", "file_path": "src/librustc/ty/walk.rs", "rank": 6, "score": 441994.57254928467 }, { "content": "fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> String {\n\n let mut name = String::with_capacity(32);\n\n let printer = DefPathBasedNames::new(cx.tcx(), true, true);\n\n printer.push_type_name(ty, &mut name);\n\n name\n\n}\n", "file_path": "src/librustc_trans/type_of.rs", "rank": 7, "score": 439612.30754988565 }, { "content": "/// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`.\n\n/// This is the right LLVM type for an alloca containing a value of that type,\n\n/// and the pointee of an Lvalue Datum (which is always a LLVM pointer).\n\n/// For unsized types, the returned type is a fat pointer, thus the resulting\n\n/// LLVM type for a `Trait` Lvalue is `{ i8*, void(i8*)** }*`, which is a double\n\n/// indirection to the actual data, unlike a `i8` Lvalue, which is just `i8*`.\n\n/// This is needed due to the treatment of immediate values, as a fat pointer\n\n/// is too large for it to be placed in SSA value (by our rules).\n\n/// For the raw type without far pointer indirection, see `in_memory_type_of`.\n\npub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type {\n\n let ty = if !cx.shared().type_is_sized(ty) {\n\n cx.tcx().mk_imm_ptr(ty)\n\n } else {\n\n ty\n\n };\n\n in_memory_type_of(cx, ty)\n\n}\n\n\n", "file_path": "src/librustc_trans/type_of.rs", "rank": 8, "score": 434731.03277565376 }, { "content": "pub fn identify_constrained_type_params<'tcx>(predicates: &[ty::Predicate<'tcx>],\n\n impl_trait_ref: Option<ty::TraitRef<'tcx>>,\n\n input_parameters: &mut FxHashSet<Parameter>)\n\n{\n\n let mut predicates = predicates.to_owned();\n\n setup_constraining_predicates(&mut predicates, impl_trait_ref, input_parameters);\n\n}\n\n\n\n\n", "file_path": "src/librustc_typeck/constrained_type_params.rs", "rank": 9, "score": 425879.4072472617 }, { "content": "pub fn fat_ptr_base_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type {\n\n match ty.sty {\n\n ty::TyRef(_, ty::TypeAndMut { ty: t, .. }) |\n\n ty::TyRawPtr(ty::TypeAndMut { ty: t, .. }) if !ccx.shared().type_is_sized(t) => {\n\n in_memory_type_of(ccx, t).ptr_to()\n\n }\n\n ty::TyAdt(def, _) if def.is_box() => {\n\n in_memory_type_of(ccx, ty.boxed_ty()).ptr_to()\n\n }\n\n _ => bug!(\"expected fat ptr ty but got {:?}\", ty)\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/type_of.rs", "rank": 10, "score": 422280.21858324914 }, { "content": "/// Returns Some([a, b]) if the type has a pair of fields with types a and b.\n\npub fn type_pair_fields<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>)\n\n -> Option<[Ty<'tcx>; 2]> {\n\n match ty.sty {\n\n ty::TyAdt(adt, substs) => {\n\n assert_eq!(adt.variants.len(), 1);\n\n let fields = &adt.variants[0].fields;\n\n if fields.len() != 2 {\n\n return None;\n\n }\n\n Some([monomorphize::field_ty(ccx.tcx(), substs, &fields[0]),\n\n monomorphize::field_ty(ccx.tcx(), substs, &fields[1])])\n\n }\n\n ty::TyClosure(def_id, substs) => {\n\n let mut tys = substs.upvar_tys(def_id, ccx.tcx());\n\n tys.next().and_then(|first_ty| tys.next().and_then(|second_ty| {\n\n if tys.next().is_some() {\n\n None\n\n } else {\n\n Some([first_ty, second_ty])\n\n }\n", "file_path": "src/librustc_trans/common.rs", "rank": 11, "score": 421035.98646971653 }, { "content": "/// Return the set of parameters constrained by the impl header.\n\npub fn parameters_for_impl<'tcx>(impl_self_ty: Ty<'tcx>,\n\n impl_trait_ref: Option<ty::TraitRef<'tcx>>)\n\n -> FxHashSet<Parameter>\n\n{\n\n let vec = match impl_trait_ref {\n\n Some(tr) => parameters_for(&tr, false),\n\n None => parameters_for(&impl_self_ty, false),\n\n };\n\n vec.into_iter().collect()\n\n}\n\n\n", "file_path": "src/librustc_typeck/constrained_type_params.rs", "rank": 12, "score": 420355.56196312374 }, { "content": "fn compute_types<'tcx,'ast>(tcx: &mut TypeContext<'tcx,'ast>,\n\n ast: Ast<'ast>) -> Type<'tcx>\n\n{\n\n match ast.kind {\n\n ExprInt | ExprVar(_) => {\n\n let ty = tcx.add_type(TypeInt);\n\n tcx.set_type(ast.id, ty)\n\n }\n\n ExprLambda(ast) => {\n\n let arg_ty = tcx.add_type(TypeInt);\n\n let body_ty = compute_types(tcx, ast);\n\n let lambda_ty = tcx.add_type(TypeFunction(arg_ty, body_ty));\n\n tcx.set_type(ast.id, lambda_ty)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass-fulldeps/regions-mock-tcx.rs", "rank": 13, "score": 415823.6038472848 }, { "content": "/// Declare a global value.\n\n///\n\n/// If there’s a value with the same name already declared, the function will\n\n/// return its ValueRef instead.\n\npub fn declare_global(ccx: &CrateContext, name: &str, ty: Type) -> llvm::ValueRef {\n\n debug!(\"declare_global(name={:?})\", name);\n\n let namebuf = CString::new(name).unwrap_or_else(|_|{\n\n bug!(\"name {:?} contains an interior null byte\", name)\n\n });\n\n unsafe {\n\n llvm::LLVMRustGetOrInsertGlobal(ccx.llmod(), namebuf.as_ptr(), ty.to_ref())\n\n }\n\n}\n\n\n\n\n", "file_path": "src/librustc_trans/declare.rs", "rank": 14, "score": 410466.9228198077 }, { "content": "/// Declare a global with an intention to define it.\n\n///\n\n/// Use this function when you intend to define a global. This function will\n\n/// return None if the name already has a definition associated with it. In that\n\n/// case an error should be reported to the user, because it usually happens due\n\n/// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).\n\npub fn define_global(ccx: &CrateContext, name: &str, ty: Type) -> Option<ValueRef> {\n\n if get_defined_value(ccx, name).is_some() {\n\n None\n\n } else {\n\n Some(declare_global(ccx, name, ty))\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/declare.rs", "rank": 15, "score": 410457.2722993979 }, { "content": "pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {\n\n unsafe {\n\n llvm::LLVMConstPointerCast(val, ty.to_ref())\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/consts.rs", "rank": 16, "score": 408161.1587840512 }, { "content": "fn use_<'b>(c: Invariant<'b>) {\n\n\n\n // For this assignment to be legal, Invariant<'b> <: Invariant<'static>.\n\n // Since 'b <= 'static, this would be true if Invariant were covariant\n\n // with respect to its parameter 'a.\n\n\n\n let _: Invariant<'static> = c; //~ ERROR mismatched types\n\n}\n\n\n", "file_path": "src/test/compile-fail/regions-variance-invariant-use-covariant.rs", "rank": 17, "score": 407629.8186434139 }, { "content": "// Using this instead of Fn etc. to take HRTB out of the equation.\n\ntrait Trigger<B> { fn fire(&self, b: &mut B); }\n\nimpl<B: Button> Trigger<B> for () {\n\n fn fire(&self, b: &mut B) {\n\n b.push();\n\n }\n\n}\n\n\n", "file_path": "src/test/ui/span/issue-26656.rs", "rank": 18, "score": 404136.34431917476 }, { "content": "/// Declare a function.\n\n///\n\n/// If there’s a value with the same name already declared, the function will\n\n/// update the declaration and return existing ValueRef instead.\n\nfn declare_raw_fn(ccx: &CrateContext, name: &str, callconv: llvm::CallConv, ty: Type) -> ValueRef {\n\n debug!(\"declare_raw_fn(name={:?}, ty={:?})\", name, ty);\n\n let namebuf = CString::new(name).unwrap_or_else(|_|{\n\n bug!(\"name {:?} contains an interior null byte\", name)\n\n });\n\n let llfn = unsafe {\n\n llvm::LLVMRustGetOrInsertFunction(ccx.llmod(), namebuf.as_ptr(), ty.to_ref())\n\n };\n\n\n\n llvm::SetFunctionCallConv(llfn, callconv);\n\n // Function addresses in Rust are never significant, allowing functions to\n\n // be merged.\n\n llvm::SetUnnamedAddr(llfn, true);\n\n\n\n if ccx.tcx().sess.opts.cg.no_redzone\n\n .unwrap_or(ccx.tcx().sess.target.target.options.disable_redzone) {\n\n llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);\n\n }\n\n\n\n if let Some(ref sanitizer) = ccx.tcx().sess.opts.debugging_opts.sanitizer {\n", "file_path": "src/librustc_trans/declare.rs", "rank": 19, "score": 403744.3122665549 }, { "content": "/// Set the discriminant for a new value of the given case of the given\n\n/// representation.\n\npub fn trans_set_discr<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, val: ValueRef, to: Disr) {\n\n let l = bcx.ccx.layout_of(t);\n\n match *l {\n\n layout::CEnum{ discr, min, max, .. } => {\n\n assert_discr_in_range(Disr(min), Disr(max), to);\n\n bcx.store(C_integral(Type::from_integer(bcx.ccx, discr), to.0, true),\n\n val, None);\n\n }\n\n layout::General{ discr, .. } => {\n\n bcx.store(C_integral(Type::from_integer(bcx.ccx, discr), to.0, true),\n\n bcx.struct_gep(val, 0), None);\n\n }\n\n layout::Univariant { .. }\n\n | layout::UntaggedUnion { .. }\n\n | layout::Vector { .. } => {\n\n assert_eq!(to, Disr(0));\n\n }\n\n layout::RawNullablePointer { nndiscr, .. } => {\n\n if to.0 != nndiscr {\n\n let llptrty = val_ty(val).element_type();\n", "file_path": "src/librustc_trans/adt.rs", "rank": 20, "score": 403409.11617142364 }, { "content": "fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) {\n\n\n\n let closure = |x, y| {\n\n zzz(); // #break\n\n (y, x)\n\n };\n\n\n\n closure(a, b)\n\n}\n\n\n", "file_path": "src/test/debuginfo/closure-in-generic-function.rs", "rank": 21, "score": 402386.2801612811 }, { "content": "pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {\n\n unsafe {\n\n return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/common.rs", "rank": 22, "score": 401847.72285638447 }, { "content": "fn function<T1, T2>(_: T1, _: T2) {}\n\n\n", "file_path": "src/test/codegen-units/item-collection/function-as-argument.rs", "rank": 23, "score": 401374.2567957684 }, { "content": "/// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`.\n\n/// This is the right LLVM type for a field/array element of that type,\n\n/// and is the same as `type_of` for all Sized types.\n\n/// Unsized types, however, are represented by a \"minimal unit\", e.g.\n\n/// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this\n\n/// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.\n\n/// If the type is an unsized struct, the regular layout is generated,\n\n/// with the inner-most trailing unsized field using the \"minimal unit\"\n\n/// of that field's type - this is useful for taking the address of\n\n/// that field and ensuring the struct has the right alignment.\n\n/// For the LLVM type of a value as a whole, see `type_of`.\n\npub fn in_memory_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {\n\n // Check the cache.\n\n if let Some(&llty) = cx.lltypes().borrow().get(&t) {\n\n return llty;\n\n }\n\n\n\n debug!(\"type_of {:?}\", t);\n\n\n\n assert!(!t.has_escaping_regions(), \"{:?} has escaping regions\", t);\n\n\n\n // Replace any typedef'd types with their equivalent non-typedef\n\n // type. This ensures that all LLVM nominal types that contain\n\n // Rust types are defined as the same LLVM types. If we don't do\n\n // this then, e.g. `Option<{myfield: bool}>` would be a different\n\n // type than `Option<myrec>`.\n\n let t_norm = cx.tcx().erase_regions(&t);\n\n\n\n if t != t_norm {\n\n let llty = in_memory_type_of(cx, t_norm);\n\n debug!(\"--> normalized {:?} to {:?} llty={:?}\", t, t_norm, llty);\n", "file_path": "src/librustc_trans/type_of.rs", "rank": 24, "score": 399472.4831599846 }, { "content": "pub fn immediate_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {\n\n if t.is_bool() {\n\n Type::i1(cx)\n\n } else {\n\n type_of(cx, t)\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/type_of.rs", "rank": 25, "score": 399430.79671284585 }, { "content": "fn foo2<T1, T2>(a: T1, b: T2) -> (T1, T2) {\n\n (a, b)\n\n}\n\n\n", "file_path": "src/test/codegen-units/item-collection/generic-functions.rs", "rank": 26, "score": 399112.5248206336 }, { "content": "#[inline(always)]\n\nfn checked_mem_copy<T1, T2>(from: &[T1], to: &mut [T2], byte_count: usize) {\n\n let from_size = from.len() * mem::size_of::<T1>();\n\n let to_size = to.len() * mem::size_of::<T2>();\n\n assert!(from_size >= byte_count);\n\n assert!(to_size >= byte_count);\n\n let from_byte_ptr = from.as_ptr() as * const u8;\n\n let to_byte_ptr = to.as_mut_ptr() as * mut u8;\n\n unsafe {\n\n ::std::ptr::copy_nonoverlapping(from_byte_ptr, to_byte_ptr, byte_count);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_data_structures/blake2b.rs", "rank": 27, "score": 395178.86379430257 }, { "content": "/// LLVM-level types are a little complicated.\n\n///\n\n/// C-like enums need to be actual ints, not wrapped in a struct,\n\n/// because that changes the ABI on some platforms (see issue #10308).\n\n///\n\n/// For nominal types, in some cases, we need to use LLVM named structs\n\n/// and fill in the actual contents in a second pass to prevent\n\n/// unbounded recursion; see also the comments in `trans::type_of`.\n\npub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {\n\n generic_type_of(cx, t, None, false, false)\n\n}\n\n\n", "file_path": "src/librustc_trans/adt.rs", "rank": 28, "score": 394233.1451358802 }, { "content": "fn statement_scope_span(tcx: TyCtxt, region: &ty::Region) -> Option<Span> {\n\n match *region {\n\n ty::ReScope(scope) => {\n\n match tcx.hir.find(scope.node_id(&tcx.region_maps)) {\n\n Some(hir_map::NodeStmt(stmt)) => Some(stmt.span),\n\n _ => None\n\n }\n\n }\n\n _ => None\n\n }\n\n}\n\n\n\nimpl BitwiseOperator for LoanDataFlowOperator {\n\n #[inline]\n\n fn join(&self, succ: usize, pred: usize) -> usize {\n\n succ | pred // loans from both preds are in scope\n\n }\n\n}\n\n\n\nimpl DataFlowOperator for LoanDataFlowOperator {\n", "file_path": "src/librustc_borrowck/borrowck/mod.rs", "rank": 29, "score": 393442.74269444693 }, { "content": "fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,\n\n (item_def_id, def_id): (DefId, DefId))\n\n -> ty::GenericPredicates<'tcx> {\n\n use rustc::hir::map::*;\n\n use rustc::hir::*;\n\n\n\n // In the AST, bounds can derive from two places. Either\n\n // written inline like `<T:Foo>` or in a where clause like\n\n // `where T:Foo`.\n\n\n\n let param_id = tcx.hir.as_local_node_id(def_id).unwrap();\n\n let param_owner = tcx.hir.ty_param_owner(param_id);\n\n let param_owner_def_id = tcx.hir.local_def_id(param_owner);\n\n let generics = tcx.item_generics(param_owner_def_id);\n\n let index = generics.type_param_to_index[&def_id.index];\n\n let ty = tcx.mk_param(index, tcx.hir.ty_param_name(param_id));\n\n\n\n // Don't look for bounds where the type parameter isn't in scope.\n\n let parent = if item_def_id == param_owner_def_id {\n\n None\n", "file_path": "src/librustc_typeck/collect.rs", "rank": 30, "score": 392178.35767976585 }, { "content": "#[cfg(not(cfail1))]\n\n#[rustc_dirty(label=\"Hir\", cfg=\"cfail2\")]\n\n#[rustc_clean(label=\"Hir\", cfg=\"cfail3\")]\n\n#[rustc_metadata_clean(cfg=\"cfail3\")]\n\ntype AddTypeParam<T1, T2> = (T1, T2);\n\n\n\n\n\n\n\n// Add type param bound --------------------------------------------------------\n", "file_path": "src/test/incremental/hashes/type_defs.rs", "rank": 31, "score": 392123.5018344763 }, { "content": "/// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html\n\n/// The algorithm from the paper has been modified to correctly handle empty\n\n/// types. The changes are:\n\n/// (0) We don't exit early if the pattern matrix has zero rows. We just\n\n/// continue to recurse over columns.\n\n/// (1) all_constructors will only return constructors that are statically\n\n/// possible. eg. it will only return Ok for Result<T, !>\n\n///\n\n/// Whether a vector `v` of patterns is 'useful' in relation to a set of such\n\n/// vectors `m` is defined as there being a set of inputs that will match `v`\n\n/// but not any of the sets in `m`.\n\n///\n\n/// This is used both for reachability checking (if a pattern isn't useful in\n\n/// relation to preceding patterns, it is not reachable) and exhaustiveness\n\n/// checking (if a wildcard pattern is useful in relation to a matrix, the\n\n/// matrix isn't exhaustive).\n\npub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,\n\n matrix: &Matrix<'p, 'tcx>,\n\n v: &[&'p Pattern<'tcx>],\n\n witness: WitnessPreference)\n\n -> Usefulness<'tcx> {\n\n let &Matrix(ref rows) = matrix;\n\n debug!(\"is_useful({:?}, {:?})\", matrix, v);\n\n\n\n // The base case. We are pattern-matching on () and the return value is\n\n // based on whether our matrix has a row or not.\n\n // NOTE: This could potentially be optimized by checking rows.is_empty()\n\n // first and then, if v is non-empty, the return value is based on whether\n\n // the type of the tuple we're checking is inhabited or not.\n\n if v.is_empty() {\n\n return if rows.is_empty() {\n\n match witness {\n\n ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),\n\n LeaveOutWitness => Useful,\n\n }\n\n } else {\n", "file_path": "src/librustc_const_eval/_match.rs", "rank": 32, "score": 391229.97972933215 }, { "content": "pub fn walk_shallow<'tcx>(ty: Ty<'tcx>) -> AccIntoIter<TypeWalkerArray<'tcx>> {\n\n let mut stack = SmallVec::new();\n\n push_subtypes(&mut stack, ty);\n\n stack.into_iter()\n\n}\n\n\n", "file_path": "src/librustc/ty/walk.rs", "rank": 33, "score": 390752.29737773596 }, { "content": "fn register_region_obligation<'tcx>(t_a: Ty<'tcx>,\n\n r_b: &'tcx ty::Region,\n\n cause: ObligationCause<'tcx>,\n\n region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)\n\n{\n\n let region_obligation = RegionObligation { sup_type: t_a,\n\n sub_region: r_b,\n\n cause: cause };\n\n\n\n debug!(\"register_region_obligation({:?}, cause={:?})\",\n\n region_obligation, region_obligation.cause);\n\n\n\n region_obligations.entry(region_obligation.cause.body_id)\n\n .or_insert(vec![])\n\n .push(region_obligation);\n\n\n\n}\n\n\n\nimpl<'a, 'gcx, 'tcx> GlobalFulfilledPredicates<'gcx> {\n\n pub fn new(dep_graph: DepGraph) -> GlobalFulfilledPredicates<'gcx> {\n", "file_path": "src/librustc/traits/fulfill.rs", "rank": 34, "score": 389037.87755948555 }, { "content": "fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {\n\n if !tcx.sess.target.target.is_abi_supported(abi) {\n\n struct_span_err!(tcx.sess, span, E0570,\n\n \"The ABI `{}` is not supported for the current target\", abi).emit()\n\n }\n\n}\n\n\n", "file_path": "src/librustc_typeck/check/mod.rs", "rank": 35, "score": 388889.420784833 }, { "content": "/// Helper for loading values from memory. Does the necessary conversion if the in-memory type\n\n/// differs from the type used for SSA values. Also handles various special cases where the type\n\n/// gives us better information about what we are loading.\n\npub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,\n\n alignment: Alignment, t: Ty<'tcx>) -> ValueRef {\n\n let ccx = b.ccx;\n\n if type_is_zero_size(ccx, t) {\n\n return C_undef(type_of::type_of(ccx, t));\n\n }\n\n\n\n unsafe {\n\n let global = llvm::LLVMIsAGlobalVariable(ptr);\n\n if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {\n\n let val = llvm::LLVMGetInitializer(global);\n\n if !val.is_null() {\n\n if t.is_bool() {\n\n return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());\n\n }\n\n return val;\n\n }\n\n }\n\n }\n\n\n", "file_path": "src/librustc_trans/base.rs", "rank": 36, "score": 388814.98994373216 }, { "content": "fn f<ty>(_: ty) {} //~ ERROR type parameter `ty` should have a camel case name such as `Ty`\n\n\n", "file_path": "src/test/compile-fail/lint-non-camel-case-types.rs", "rank": 37, "score": 388764.9952136632 }, { "content": "fn resolve_fn<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>,\n\n kind: FnKind<'tcx>,\n\n decl: &'tcx hir::FnDecl,\n\n body_id: hir::BodyId,\n\n sp: Span,\n\n id: ast::NodeId) {\n\n debug!(\"region::resolve_fn(id={:?}, \\\n\n span={:?}, \\\n\n body.id={:?}, \\\n\n cx.parent={:?})\",\n\n id,\n\n visitor.sess.codemap().span_to_string(sp),\n\n body_id,\n\n visitor.cx.parent);\n\n\n\n visitor.cx.parent = visitor.new_code_extent(\n\n CodeExtentData::CallSiteScope { fn_id: id, body_id: body_id.node_id });\n\n\n\n let fn_decl_scope = visitor.new_code_extent(\n\n CodeExtentData::ParameterScope { fn_id: id, body_id: body_id.node_id });\n", "file_path": "src/librustc/middle/region.rs", "rank": 38, "score": 385995.25333823694 }, { "content": "fn take_fn_pointer<T1, T2>(f: fn(T1, T2), x: T1, y: T2) {\n\n (f)(x, y)\n\n}\n\n\n", "file_path": "src/test/codegen-units/item-collection/function-as-argument.rs", "rank": 39, "score": 385387.7668926849 }, { "content": "fn main() { let x: a = a::A; match x { b::B => { } } }\n", "file_path": "src/test/compile-fail/match-tag-nullary.rs", "rank": 40, "score": 385032.95999446395 }, { "content": "fn main() {}\n", "file_path": "src/test/compile-fail/match-ref-mut-let-invariance.rs", "rank": 41, "score": 384313.0048925752 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_arm.rs", "rank": 42, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() {\n\n continue;\n\n }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_msp430.rs", "rank": 43, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n let mut offset = if fty.ret.is_indirect() { 4 } else { 0 };\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg, &mut offset);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_sparc.rs", "rank": 44, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n let mut offset = if fty.ret.is_indirect() { 8 } else { 0 };\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg, &mut offset);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_mips64.rs", "rank": 45, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_sparc64.rs", "rank": 46, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n let mut offset = if fty.ret.is_indirect() { 4 } else { 0 };\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg, &mut offset);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_powerpc.rs", "rank": 47, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n let mut offset = if fty.ret.is_indirect() { 4 } else { 0 };\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg, &mut offset);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_mips.rs", "rank": 48, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_s390x.rs", "rank": 49, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_asmjs.rs", "rank": 50, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_powerpc64.rs", "rank": 51, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n let mut int_regs = 6; // RDI, RSI, RDX, RCX, R8, R9\n\n let mut sse_regs = 8; // XMM0-7\n\n\n\n let mut x86_64_ty = |arg: &mut ArgType<'tcx>, is_arg: bool| {\n\n let cls = classify_arg(ccx, arg);\n\n\n\n let mut needed_int = 0;\n\n let mut needed_sse = 0;\n\n let in_mem = match cls {\n\n Err(Memory) => true,\n\n Ok(ref cls) if is_arg => {\n\n for &c in cls {\n\n match c {\n\n Class::Int => needed_int += 1,\n\n Class::Sse => needed_sse += 1,\n\n _ => {}\n\n }\n\n }\n\n arg.layout.is_aggregate() &&\n", "file_path": "src/librustc_trans/cabi_x86_64.rs", "rank": 52, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() {\n\n continue;\n\n }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_nvptx.rs", "rank": 53, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() { continue; }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_aarch64.rs", "rank": 54, "score": 383245.7161781737 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n if !fty.ret.is_ignore() {\n\n classify_ret_ty(ccx, &mut fty.ret);\n\n }\n\n\n\n for arg in &mut fty.args {\n\n if arg.is_ignore() {\n\n continue;\n\n }\n\n classify_arg_ty(ccx, arg);\n\n }\n\n}\n", "file_path": "src/librustc_trans/cabi_nvptx64.rs", "rank": 55, "score": 383245.7161781737 }, { "content": "// Returns the width of a float TypeVariant\n\n// Returns None if the type is not a float\n\nfn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>)\n\n -> Option<u64> {\n\n use rustc::ty::TyFloat;\n\n match *sty {\n\n TyFloat(t) => Some(match t {\n\n ast::FloatTy::F32 => 32,\n\n ast::FloatTy::F64 => 64,\n\n }),\n\n _ => None,\n\n }\n\n}\n", "file_path": "src/librustc_trans/intrinsic.rs", "rank": 56, "score": 382193.3742250621 }, { "content": "fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,\n\n def_id: DefId)\n\n -> ty::ClosureKind {\n\n let node_id = tcx.hir.as_local_node_id(def_id).unwrap();\n\n tcx.item_tables(def_id).closure_kinds[&node_id]\n\n}\n\n\n", "file_path": "src/librustc_typeck/check/mod.rs", "rank": 57, "score": 381371.29529619496 }, { "content": "struct SomeGenericType<T1, T2>(T1, T2);\n\n\n\nmod mod1 {\n\n use super::{SomeType, SomeGenericType};\n\n\n\n // Even though the impl is in `mod1`, the methods should end up in the\n\n // parent module, since that is where their self-type is.\n\n impl SomeType {\n\n //~ TRANS_ITEM fn methods_are_with_self_type::mod1[0]::{{impl}}[0]::method[0] @@ methods_are_with_self_type[External]\n\n fn method(&self) {}\n\n\n\n //~ TRANS_ITEM fn methods_are_with_self_type::mod1[0]::{{impl}}[0]::associated_fn[0] @@ methods_are_with_self_type[External]\n\n fn associated_fn() {}\n\n }\n\n\n\n impl<T1, T2> SomeGenericType<T1, T2> {\n\n pub fn method(&self) {}\n\n pub fn associated_fn(_: T1, _: T2) {}\n\n }\n\n}\n\n\n", "file_path": "src/test/codegen-units/partitioning/methods-are-with-self-type.rs", "rank": 58, "score": 380924.04648385727 }, { "content": "fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,\n\n impl_m: &ty::AssociatedItem,\n\n impl_m_span: Span,\n\n trait_m: &ty::AssociatedItem,\n\n impl_trait_ref: ty::TraitRef<'tcx>)\n\n -> Result<(), ErrorReported>\n\n{\n\n // Try to give more informative error messages about self typing\n\n // mismatches. Note that any mismatch will also be detected\n\n // below, where we construct a canonical function type that\n\n // includes the self parameter as a normal parameter. It's just\n\n // that the error messages you get out of this code are a bit more\n\n // inscrutable, particularly for cases where one method has no\n\n // self.\n\n\n\n let self_string = |method: &ty::AssociatedItem| {\n\n let untransformed_self_ty = match method.container {\n\n ty::ImplContainer(_) => impl_trait_ref.self_ty(),\n\n ty::TraitContainer(_) => tcx.mk_self_type()\n\n };\n", "file_path": "src/librustc_typeck/check/compare_method.rs", "rank": 59, "score": 380230.6244907607 }, { "content": "pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) {\n\n let fixup = |a: &mut ArgType<'tcx>| {\n\n let size = a.layout.size(ccx);\n\n if a.layout.is_aggregate() {\n\n match size.bits() {\n\n 8 => a.cast_to(ccx, Reg::i8()),\n\n 16 => a.cast_to(ccx, Reg::i16()),\n\n 32 => a.cast_to(ccx, Reg::i32()),\n\n 64 => a.cast_to(ccx, Reg::i64()),\n\n _ => a.make_indirect(ccx)\n\n };\n\n } else {\n\n if let Layout::Vector { .. } = *a.layout {\n\n // FIXME(eddyb) there should be a size cap here\n\n // (probably what clang calls \"illegal vectors\").\n\n } else if size.bytes() > 8 {\n\n a.make_indirect(ccx);\n\n } else {\n\n a.extend_integer_width_to(32);\n\n }\n", "file_path": "src/librustc_trans/cabi_x86_win64.rs", "rank": 60, "score": 378453.7382715268 }, { "content": "fn require_c_abi_if_variadic(tcx: TyCtxt,\n\n decl: &hir::FnDecl,\n\n abi: Abi,\n\n span: Span) {\n\n if decl.variadic && abi != Abi::C {\n\n let mut err = struct_span_err!(tcx.sess, span, E0045,\n\n \"variadic function must have C calling convention\");\n\n err.span_label(span, &(\"variadics require C calling conventions\").to_string())\n\n .emit();\n\n }\n\n}\n\n\n", "file_path": "src/librustc_typeck/lib.rs", "rank": 61, "score": 375082.19236217753 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(32);\n\n } else {\n\n ret.make_indirect(ccx);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_mips.rs", "rank": 62, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(32);\n\n } else {\n\n ret.make_indirect(ccx);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_sparc.rs", "rank": 63, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if !arg.layout.is_aggregate() {\n\n arg.extend_integer_width_to(64);\n\n return;\n\n }\n\n\n\n if let Some(uniform) = is_homogenous_aggregate(ccx, arg) {\n\n arg.cast_to(ccx, uniform);\n\n return;\n\n }\n\n\n\n let total = arg.layout.size(ccx);\n\n arg.cast_to(ccx, Uniform {\n\n unit: Reg::i64(),\n\n total\n\n });\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_powerpc64.rs", "rank": 64, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(32);\n\n } else {\n\n ret.make_indirect(ccx);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_powerpc.rs", "rank": 65, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(64);\n\n return;\n\n }\n\n\n\n // The PowerPC64 big endian ABI doesn't return aggregates in registers\n\n if ccx.sess().target.target.target_endian == \"big\" {\n\n ret.make_indirect(ccx);\n\n }\n\n\n\n if let Some(uniform) = is_homogenous_aggregate(ccx, ret) {\n\n ret.cast_to(ccx, uniform);\n\n return;\n\n }\n\n let size = ret.layout.size(ccx);\n\n let bits = size.bits();\n\n if bits <= 128 {\n\n let unit = if bits <= 8 {\n\n Reg::i8()\n", "file_path": "src/librustc_trans/cabi_powerpc64.rs", "rank": 66, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() && ret.layout.size(ccx).bits() <= 64 {\n\n ret.extend_integer_width_to(64);\n\n } else {\n\n ret.make_indirect(ccx);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_s390x.rs", "rank": 67, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if !arg.layout.is_aggregate() {\n\n arg.extend_integer_width_to(32);\n\n return;\n\n }\n\n if let Some(uniform) = is_homogenous_aggregate(ccx, arg) {\n\n arg.cast_to(ccx, uniform);\n\n return;\n\n }\n\n let size = arg.layout.size(ccx);\n\n let bits = size.bits();\n\n if bits <= 128 {\n\n let unit = if bits <= 8 {\n\n Reg::i8()\n\n } else if bits <= 16 {\n\n Reg::i16()\n\n } else if bits <= 32 {\n\n Reg::i32()\n\n } else {\n\n Reg::i64()\n", "file_path": "src/librustc_trans/cabi_aarch64.rs", "rank": 68, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(32);\n\n return;\n\n }\n\n if let Some(uniform) = is_homogenous_aggregate(ccx, ret) {\n\n ret.cast_to(ccx, uniform);\n\n return;\n\n }\n\n let size = ret.layout.size(ccx);\n\n let bits = size.bits();\n\n if bits <= 128 {\n\n let unit = if bits <= 8 {\n\n Reg::i8()\n\n } else if bits <= 16 {\n\n Reg::i16()\n\n } else if bits <= 32 {\n\n Reg::i32()\n\n } else {\n\n Reg::i64()\n", "file_path": "src/librustc_trans/cabi_aarch64.rs", "rank": 69, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(32);\n\n return;\n\n }\n\n let size = ret.layout.size(ccx);\n\n let bits = size.bits();\n\n if bits <= 32 {\n\n let unit = if bits <= 8 {\n\n Reg::i8()\n\n } else if bits <= 16 {\n\n Reg::i16()\n\n } else {\n\n Reg::i32()\n\n };\n\n ret.cast_to(ccx, Uniform {\n\n unit,\n\n total: size\n\n });\n\n return;\n\n }\n\n ret.make_indirect(ccx);\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_arm.rs", "rank": 70, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if !arg.layout.is_aggregate() {\n\n arg.extend_integer_width_to(32);\n\n return;\n\n }\n\n let align = arg.layout.align(ccx).abi();\n\n let total = arg.layout.size(ccx);\n\n arg.cast_to(ccx, Uniform {\n\n unit: if align <= 4 { Reg::i32() } else { Reg::i64() },\n\n total\n\n });\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_arm.rs", "rank": 71, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if !arg.layout.is_aggregate() {\n\n arg.extend_integer_width_to(64);\n\n return;\n\n }\n\n\n\n if let Some(uniform) = is_homogenous_aggregate(ccx, arg) {\n\n arg.cast_to(ccx, uniform);\n\n return;\n\n }\n\n\n\n let total = arg.layout.size(ccx);\n\n arg.cast_to(ccx, Uniform {\n\n unit: Reg::i64(),\n\n total\n\n });\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_sparc64.rs", "rank": 72, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n let size = arg.layout.size(ccx);\n\n if !arg.layout.is_aggregate() && size.bits() <= 64 {\n\n arg.extend_integer_width_to(64);\n\n return;\n\n }\n\n\n\n if is_single_fp_element(ccx, arg.layout) {\n\n match size.bytes() {\n\n 4 => arg.cast_to(ccx, Reg::f32()),\n\n 8 => arg.cast_to(ccx, Reg::f64()),\n\n _ => arg.make_indirect(ccx)\n\n }\n\n } else {\n\n match size.bytes() {\n\n 1 => arg.cast_to(ccx, Reg::i8()),\n\n 2 => arg.cast_to(ccx, Reg::i16()),\n\n 4 => arg.cast_to(ccx, Reg::i32()),\n\n 8 => arg.cast_to(ccx, Reg::i64()),\n\n _ => arg.make_indirect(ccx)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_s390x.rs", "rank": 73, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(64);\n\n return;\n\n }\n\n\n\n if let Some(uniform) = is_homogenous_aggregate(ccx, ret) {\n\n ret.cast_to(ccx, uniform);\n\n return;\n\n }\n\n let size = ret.layout.size(ccx);\n\n let bits = size.bits();\n\n if bits <= 128 {\n\n let unit = if bits <= 8 {\n\n Reg::i8()\n\n } else if bits <= 16 {\n\n Reg::i16()\n\n } else if bits <= 32 {\n\n Reg::i32()\n\n } else {\n", "file_path": "src/librustc_trans/cabi_sparc64.rs", "rank": 74, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if arg.layout.is_aggregate() && arg.layout.size(ccx).bits() > 32 {\n\n arg.make_indirect(ccx);\n\n } else {\n\n arg.extend_integer_width_to(16);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_msp430.rs", "rank": 75, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if arg.layout.is_aggregate() && arg.layout.size(ccx).bits() > 32 {\n\n arg.make_indirect(ccx);\n\n } else {\n\n arg.extend_integer_width_to(32);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_nvptx.rs", "rank": 76, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if arg.layout.is_aggregate() && arg.layout.size(ccx).bits() > 64 {\n\n arg.make_indirect(ccx);\n\n } else {\n\n arg.extend_integer_width_to(64);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_nvptx64.rs", "rank": 77, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if ret.layout.is_aggregate() && ret.layout.size(ccx).bits() > 32 {\n\n ret.make_indirect(ccx);\n\n } else {\n\n ret.extend_integer_width_to(32);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_nvptx.rs", "rank": 78, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if ret.layout.is_aggregate() && ret.layout.size(ccx).bits() > 64 {\n\n ret.make_indirect(ccx);\n\n } else {\n\n ret.extend_integer_width_to(64);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_nvptx64.rs", "rank": 79, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if ret.layout.is_aggregate() {\n\n if let Some(unit) = ret.layout.homogenous_aggregate(ccx) {\n\n let size = ret.layout.size(ccx);\n\n if unit.size == size {\n\n ret.cast_to(ccx, Uniform {\n\n unit,\n\n total: size\n\n });\n\n return;\n\n }\n\n }\n\n\n\n ret.make_indirect(ccx);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_asmjs.rs", "rank": 80, "score": 374612.83939278394 }, { "content": "// 3.5 Structures or Unions Passed and Returned by Reference\n\n//\n\n// \"Structures (including classes) and unions larger than 32 bits are passed and\n\n// returned by reference. To pass a structure or union by reference, the caller\n\n// places its address in the appropriate location: either in a register or on\n\n// the stack, according to its position in the argument list. (..)\"\n\nfn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if ret.layout.is_aggregate() && ret.layout.size(ccx).bits() > 32 {\n\n ret.make_indirect(ccx);\n\n } else {\n\n ret.extend_integer_width_to(16);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_msp430.rs", "rank": 81, "score": 374612.83939278394 }, { "content": "fn classify_ret_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ret: &mut ArgType<'tcx>) {\n\n if !ret.layout.is_aggregate() {\n\n ret.extend_integer_width_to(64);\n\n } else {\n\n ret.make_indirect(ccx);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_mips64.rs", "rank": 82, "score": 374612.83939278394 }, { "content": "fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tcx>) {\n\n if arg.layout.is_aggregate() {\n\n arg.make_indirect(ccx);\n\n arg.attrs.set(ArgAttribute::ByVal);\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/cabi_asmjs.rs", "rank": 83, "score": 374612.83939278394 }, { "content": "/// Returns true if the type is represented as a pair of immediates.\n\npub fn type_is_imm_pair<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>)\n\n -> bool {\n\n match *ccx.layout_of(ty) {\n\n Layout::FatPointer { .. } => true,\n\n Layout::Univariant { ref variant, .. } => {\n\n // There must be only 2 fields.\n\n if variant.offsets.len() != 2 {\n\n return false;\n\n }\n\n\n\n match type_pair_fields(ccx, ty) {\n\n Some([a, b]) => {\n\n type_is_immediate(ccx, a) && type_is_immediate(ccx, b)\n\n }\n\n None => false\n\n }\n\n }\n\n _ => false\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/common.rs", "rank": 84, "score": 374278.9759526923 }, { "content": "fn copy_borrowed_ptr<'a, 'b, 'c>(p: &'a mut &'b mut &'c mut isize) -> &'b mut isize {\n\n &mut ***p //~ ERROR cannot infer\n\n}\n\n\n", "file_path": "src/test/compile-fail/regions-reborrow-from-shorter-mut-ref-mut-ref.rs", "rank": 85, "score": 372598.737878707 }, { "content": "fn main() { let x: a = a::A(0); match x { b::B(y) => { } } }\n", "file_path": "src/test/compile-fail/match-tag-unary.rs", "rank": 86, "score": 372221.4193211879 }, { "content": "fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {\n\n match t.sty {\n\n ty::TyInt(int_type) => const_to_opt_u128(value, true)\n\n .and_then(|input| ConstInt::new_signed(input as i128, int_type,\n\n tcx.sess.target.int_type)),\n\n ty::TyUint(uint_type) => const_to_opt_u128(value, false)\n\n .and_then(|input| ConstInt::new_unsigned(input, uint_type,\n\n tcx.sess.target.uint_type)),\n\n _ => None\n\n\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/mir/constant.rs", "rank": 87, "score": 372087.3231843605 }, { "content": "pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, info: ValueRef)\n\n -> (ValueRef, ValueRef) {\n\n debug!(\"calculate size of DST: {}; with lost info: {:?}\",\n\n t, Value(info));\n\n if bcx.ccx.shared().type_is_sized(t) {\n\n let size = bcx.ccx.size_of(t);\n\n let align = bcx.ccx.align_of(t);\n\n debug!(\"size_and_align_of_dst t={} info={:?} size: {} align: {}\",\n\n t, Value(info), size, align);\n\n let size = C_uint(bcx.ccx, size);\n\n let align = C_uint(bcx.ccx, align);\n\n return (size, align);\n\n }\n\n match t.sty {\n\n ty::TyAdt(def, substs) => {\n\n let ccx = bcx.ccx;\n\n // First get the size of all statically known fields.\n\n // Don't use size_of because it also rounds up to alignment, which we\n\n // want to avoid, as the unsized field's alignment could be smaller.\n\n assert!(!t.is_simd());\n", "file_path": "src/librustc_trans/glue.rs", "rank": 88, "score": 371544.88021213753 }, { "content": "/// Declare a C ABI function.\n\n///\n\n/// Only use this for foreign function ABIs and glue. For Rust functions use\n\n/// `declare_fn` instead.\n\n///\n\n/// If there’s a value with the same name already declared, the function will\n\n/// update the declaration and return existing ValueRef instead.\n\npub fn declare_cfn(ccx: &CrateContext, name: &str, fn_type: Type) -> ValueRef {\n\n declare_raw_fn(ccx, name, llvm::CCallConv, fn_type)\n\n}\n\n\n\n\n", "file_path": "src/librustc_trans/declare.rs", "rank": 89, "score": 371374.3544285789 }, { "content": "/// Returns the size of the type as an LLVM constant integer value.\n\npub fn llsize_of(cx: &CrateContext, ty: Type) -> ValueRef {\n\n // Once upon a time, this called LLVMSizeOf, which does a\n\n // getelementptr(1) on a null pointer and casts to an int, in\n\n // order to obtain the type size as a value without requiring the\n\n // target data layout. But we have the target data layout, so\n\n // there's no need for that contrivance. The instruction\n\n // selection DAG generator would flatten that GEP(1) node into a\n\n // constant of the type's alloc size, so let's save it some work.\n\n return C_uint(cx, llsize_of_alloc(cx, ty));\n\n}\n\n\n", "file_path": "src/librustc_trans/machine.rs", "rank": 90, "score": 371160.25809094915 }, { "content": "fn invariant_id<'a,'b>(t: &'b mut &'static ()) -> &'b mut &'a ()\n\n where 'a: 'static { t }\n", "file_path": "src/test/run-pass/regions-static-bound.rs", "rank": 91, "score": 370385.9500730298 }, { "content": "/// Return the set of type variables contained in a trait ref\n\nfn trait_ref_type_vars<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,\n\n t: ty::PolyTraitRef<'tcx>) -> Vec<Ty<'tcx>>\n\n{\n\n t.skip_binder() // ok b/c this check doesn't care about regions\n\n .input_types()\n\n .map(|t| selcx.infcx().resolve_type_vars_if_possible(&t))\n\n .filter(|t| t.has_infer_types())\n\n .flat_map(|t| t.walk())\n\n .filter(|t| match t.sty { ty::TyInfer(_) => true, _ => false })\n\n .collect()\n\n}\n\n\n", "file_path": "src/librustc/traits/fulfill.rs", "rank": 92, "score": 370185.49815543316 }, { "content": "fn use_slice_mut(_: &mut [u8]) {}\n\n\n", "file_path": "src/test/run-pass/coerce-overloaded-autoderef.rs", "rank": 93, "score": 369816.50633820513 }, { "content": "pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {\n\n let layout = ccx.layout_of(ty);\n\n match *layout {\n\n Layout::CEnum { .. } |\n\n Layout::Scalar { .. } |\n\n Layout::Vector { .. } => true,\n\n\n\n Layout::FatPointer { .. } => false,\n\n\n\n Layout::Array { .. } |\n\n Layout::Univariant { .. } |\n\n Layout::General { .. } |\n\n Layout::UntaggedUnion { .. } |\n\n Layout::RawNullablePointer { .. } |\n\n Layout::StructWrappedNullablePointer { .. } => {\n\n !layout.is_unsized() && layout.size(ccx).bytes() == 0\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/common.rs", "rank": 94, "score": 369521.6814073267 }, { "content": "fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>,\n\n local: &'tcx hir::Local) {\n\n debug!(\"resolve_local(local.id={:?},local.init={:?})\",\n\n local.id,local.init.is_some());\n\n\n\n // For convenience in trans, associate with the local-id the var\n\n // scope that will be used for any bindings declared in this\n\n // pattern.\n\n let blk_scope = visitor.cx.var_parent;\n\n assert!(blk_scope != ROOT_CODE_EXTENT); // locals must be within a block\n\n visitor.region_maps.record_var_scope(local.id, blk_scope);\n\n\n\n // As an exception to the normal rules governing temporary\n\n // lifetimes, initializers in a let have a temporary lifetime\n\n // of the enclosing block. This means that e.g. a program\n\n // like the following is legal:\n\n //\n\n // let ref x = HashMap::new();\n\n //\n\n // Because the hash map will be freed in the enclosing block.\n", "file_path": "src/librustc/middle/region.rs", "rank": 95, "score": 368095.5434744796 }, { "content": "/// Helper for storing values in memory. Does the necessary conversion if the in-memory type\n\n/// differs from the type used for SSA values.\n\npub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,\n\n dst_align: Alignment, t: Ty<'tcx>) {\n\n debug!(\"store_ty: {:?} : {:?} <- {:?}\", Value(dst), t, Value(v));\n\n\n\n if common::type_is_fat_ptr(cx.ccx, t) {\n\n let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);\n\n let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);\n\n store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);\n\n } else {\n\n cx.store(from_immediate(cx, v), dst, dst_align.to_align());\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/base.rs", "rank": 96, "score": 366018.6764912641 }, { "content": "/// This function is used to enforce the constraints on\n\n/// const/static items. It walks through the *value*\n\n/// of the item walking down the expression and evaluating\n\n/// every nested expression. If the expression is not part\n\n/// of a const/static item, it is qualified for promotion\n\n/// instead of producing errors.\n\nfn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {\n\n match node_ty.sty {\n\n ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {\n\n v.promotable = false;\n\n }\n\n _ => {}\n\n }\n\n\n\n let method_call = ty::MethodCall::expr(e.id);\n\n match e.node {\n\n hir::ExprUnary(..) |\n\n hir::ExprBinary(..) |\n\n hir::ExprIndex(..) if v.tables.method_map.contains_key(&method_call) => {\n\n v.promotable = false;\n\n }\n\n hir::ExprBox(_) => {\n\n v.promotable = false;\n\n }\n\n hir::ExprUnary(op, ref inner) => {\n\n match v.tables.node_id_to_type(inner.id).sty {\n", "file_path": "src/librustc_passes/consts.rs", "rank": 97, "score": 365955.1306567275 }, { "content": "/// Identify types which have size zero at runtime.\n\npub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {\n\n let layout = ccx.layout_of(ty);\n\n !layout.is_unsized() && layout.size(ccx).bytes() == 0\n\n}\n\n\n\n/*\n\n* A note on nomenclature of linking: \"extern\", \"foreign\", and \"upcall\".\n\n*\n\n* An \"extern\" is an LLVM symbol we wind up emitting an undefined external\n\n* reference to. This means \"we don't have the thing in this compilation unit,\n\n* please make sure you link it in at runtime\". This could be a reference to\n\n* C code found in a C library, or rust code found in a rust crate.\n\n*\n\n* Most \"externs\" are implicitly declared (automatically) as a result of a\n\n* user declaring an extern _module_ dependency; this causes the rust driver\n\n* to locate an extern crate, scan its compilation metadata, and emit extern\n\n* declarations for any symbols used by the declaring crate.\n\n*\n\n* A \"foreign\" is an extern that references C (or other non-rust ABI) code.\n\n* There is no metadata to scan for extern references so in these cases either\n", "file_path": "src/librustc_trans/common.rs", "rank": 98, "score": 365243.185095827 }, { "content": "pub fn type_is_fat_ptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {\n\n if let Layout::FatPointer { .. } = *ccx.layout_of(ty) {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/librustc_trans/common.rs", "rank": 99, "score": 365235.8512613906 } ]
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_api_response(mut rx: oneshot::Receiver<String>) -> Result<String, String> {\n\n // TODO timeout error\n\n loop {\n\n match rx.try_recv() {\n\n Ok(resp) => {\n\n return Ok(resp.into());\n\n },\n\n Err(oneshot::error::TryRecvError::Closed) => {\n\n return Err(\"Failed to reach API\".into());\n\n },\n\n _ => {},\n\n }\n\n }\n\n}\n\n\n\n\n\n/// Opens a warp server to host a media file at the specified path and port.\n\n/// A shutdown reciever is used to close the media server gracefully when requested.\n\n#[allow(dead_code)]\n\npub async fn host_media(file: &Path, port: u16, shutdown_rx: oneshot::Receiver<()>) {\n\n let route = warp::fs::file(file.to_path_buf());\n\n let addr = ([0,0,0,0], port);\n\n let (_, server) = warp::serve(route)\n\n .bind_with_graceful_shutdown(addr, async {\n\n shutdown_rx.await.ok();\n\n });\n\n \n\n server.await;\n\n}\n", "file_path": "src/server/mod.rs", "rank": 0, "score": 122105.55356757877 }, { "content": "#[allow(dead_code)]\n\npub fn is_chromecast_compatible(input: &str, _chromecast: Chromecast) -> bool {\n\n ffmpeg::init().unwrap();\n\n\n\n // TODO check if any of the media streams are compatible, not just best\n\n let ictx = format::input(&input).unwrap();\n\n let video_stream = ictx.streams().best(media::Type::Video).unwrap();\n\n let _audio_stream = ictx.streams().best(media::Type::Audio).unwrap();\n\n let _vcodec = video_stream.codec();\n\n \n\n todo!()\n\n}\n\n\n\n/// Extracts the video codec from the best video stream available\n\n/// #### Returns\n\n/// ffmpeg::codec::Id - The id of the video stream codec\n", "file_path": "src/video_encoding.rs", "rank": 2, "score": 88973.80564415299 }, { "content": "/// Convert a json input into a CastSignal\n\nfn json_to_signal() -> impl Filter<Extract = (api::CastSignal,), Error = warp::Rejection> + Clone {\n\n warp::body::content_length_limit(1024).and(warp::body::json())\n\n}\n\n\n\n/// Launches a warp server to host the web interface. This includes the webapp\n\n/// and the api.\n\npub async fn host_api(port: u16, \n\n shutdown_rx: oneshot::Receiver<()>,\n\n api_tx: mpsc::Sender<api::Request>) {\n\n \n\n let webapp = warp::get().and(\n\n warp::fs::dir(\"webapp/dist/mucast-frontend\") \n\n )\n\n .and(warp::path::end());\n\n\n\n let tx_filter = warp::any().map(move || api_tx.clone());\n\n let put_signals = warp::put()\n\n .and(warp::path(\"api\"))\n\n .and(warp::path(\"cast-signal\"))\n\n .and(warp::path::end())\n", "file_path": "src/server/mod.rs", "rank": 3, "score": 86695.10634142018 }, { "content": "#[allow(dead_code)]\n\npub fn remux(input: &str, output: &str) { \n\n //TODO Error handling/wrapping\n\n\n\n ffmpeg::init().unwrap();\n\n log::set_level(log::Level::Warning);\n\n\n\n let mut ictx = format::input(&input).unwrap();\n\n let mut octx = format::output(&output).unwrap();\n\n\n\n let mut stream_mapping = vec![0; ictx.nb_streams() as _];\n\n let mut ist_time_bases = vec![Rational(0, 1); ictx.nb_streams() as _];\n\n let mut ost_index = 0;\n\n for (ist_index, ist) in ictx.streams().enumerate() {\n\n let ist_medium = ist.codec().medium();\n\n if ist_medium != media::Type::Audio\n\n && ist_medium != media::Type::Video\n\n && ist_medium != media::Type::Subtitle\n\n {\n\n stream_mapping[ist_index] = -1;\n\n continue;\n", "file_path": "src/video_encoding.rs", "rank": 4, "score": 80781.76836594302 }, { "content": "#[allow(dead_code)]\n\npub fn get_video_codec(input: &str) -> ffmpeg::codec::Id {\n\n ffmpeg::init().unwrap();\n\n\n\n let ictx = format::input(&input).unwrap();\n\n let ist = ictx.streams().best(media::Type::Video).unwrap();\n\n ist.codec().id()\n\n}\n\n\n\n/// Move media streams from one container to another.\n\n///\n\n/// This is ripped straight from ffmpeg-next examples.\n\n/// https://github.com/zmwangx/rust-ffmpeg/blob/5ed41c84ff877dc9ae9bd76412c86ee03afb5282/examples/remux.rs\n\n/// Bless their soul for providing the multimedia voodoo code.\n\n///\n\n/// #### Usage\n\n/// `remux(\"media.mkv\", \"media.mp4\");`\n", "file_path": "src/video_encoding.rs", "rank": 5, "score": 63298.76728872725 }, { "content": "#[derive(Debug)]\n\npub enum CastError {\n\n RustCastError(rust_cast::errors::Error),\n\n IoError(std::io::Error),\n\n HyperError(warp::hyper::Error),\n\n MDNSError(mdns::Error),\n\n ServerError,\n\n CasterError(&'static str),\n\n}\n\nimpl From<rust_cast::errors::Error> for CastError {\n\n fn from(err: rust_cast::errors::Error) -> Self {\n\n CastError::RustCastError(err)\n\n }\n\n}\n\nimpl From<std::io::Error> for CastError {\n\n fn from(err: std::io::Error) -> Self {\n\n CastError::IoError(err)\n\n }\n\n}\n\nimpl From<warp::hyper::Error> for CastError {\n", "file_path": "src/cast/error.rs", "rank": 8, "score": 21414.254986750766 }, { "content": "use crate::cast;\n\n\n\n#[derive(Debug)]\n\npub enum ApiError {\n\n ApiError(String),\n\n CastError(cast::Error)\n\n}\n\n\n\n// ApiError from string\n\nimpl From<String> for ApiError {\n\n fn from(s: String) -> Self {\n\n Self::ApiError(s)\n\n }\n\n}\n\n\n\n// CastError\n\nimpl From<cast::Error> for ApiError {\n\n fn from(e: cast::Error) -> Self {\n\n Self::CastError(e)\n\n }\n\n}\n", "file_path": "src/api/error.rs", "rank": 9, "score": 21413.85261455301 }, { "content": " fn from(err: warp::hyper::Error) -> Self {\n\n CastError::HyperError(err)\n\n }\n\n}\n\nimpl From<mdns::Error> for CastError {\n\n fn from(err: mdns::Error) -> Self {\n\n CastError::MDNSError(err)\n\n }\n\n}\n", "file_path": "src/cast/error.rs", "rank": 10, "score": 21410.37626729767 }, { "content": "#[allow(dead_code)]\n\nimpl Api {\n\n pub fn new() -> Self {\n\n Self { caster: cast::Caster::new(), \n\n current_chromecast: None,\n\n discovered_chromecasts: Vec::new() }\n\n }\n\n \n\n /// Polls the network for mDNS devices to build a list of available chromecasts.\n\n /// The discovered devices are cached and can be returned with `get_discovered_chromecasts()`\n\n /// This function MUST be called on the tokio::runtimes' thread, otherwise, you will need to\n\n /// use the runtime's handle and replicate this function using that.\n\n /// # Returns\n\n /// `&Vec<(String, IpAddress)` - A vec containing all the found devices as (FriendlyName,\n\n /// IpAddress)\n\n /// `ApiError` - on failure\n\n pub fn discover_chromecasts(&mut self) -> Result<(), Error> {\n\n // Call find_chromecasts on tokio::runtime\n\n let (tx, mut rx) = oneshot::channel::<Result<Vec<(String, IpAddr)>, cast::Error>>();\n\n tokio::spawn( async move {\n", "file_path": "src/api/mod.rs", "rank": 20, "score": 15457.221097725982 }, { "content": " match signal {\n\n CastSignal::Begin(_) => todo!(),\n\n CastSignal::Stop => self.caster.stop().unwrap(),\n\n CastSignal::Pause => self.caster.pause().unwrap(),\n\n CastSignal::Play => self.caster.resume().unwrap(),\n\n CastSignal::Seek(seconds) => self.caster.seek(seconds).unwrap(),\n\n }\n\n }\n\n\n\n /// Handles Request::Get\n\n fn handle_get_request(&self, get_type: GetType, sender: oneshot::Sender<String>) {\n\n match get_type {\n\n\n\n GetType::MediaStatus => {\n\n // Grab MediaStatus from the caster, serialize to JSON and reply.\n\n let status = self.caster.status.lock().unwrap().clone();\n\n let _ = sender.send(serde_json::to_string(&status).unwrap());\n\n },\n\n \n\n GetType::Chromecasts => {\n", "file_path": "src/api/mod.rs", "rank": 21, "score": 15456.779551991543 }, { "content": " shutdown_rx.await.ok();\n\n });\n\n \n\n server.await;\n\n}\n\n\n\nasync fn get_media_status(mut api_tx: mpsc::Sender<api::Request>)\n\n -> Result<impl warp::Reply, warp::Rejection> {\n\n \n\n\n\n let (req_tx, req_rx) = oneshot::channel::<String>();\n\n let request = api::Request::Get(api::GetType::MediaStatus, req_tx);\n\n api_tx.send( request ).await.unwrap();\n\n \n\n match await_api_response(req_rx) {\n\n Ok(resp) => {\n\n Ok(Response::new(resp.into()))\n\n },\n\n Err(_) => Err(warp::reject::reject()),\n\n }\n", "file_path": "src/server/mod.rs", "rank": 30, "score": 15452.21388007876 }, { "content": "\n\n /// Returns a reference the cached Vec holding all the previously discovered chromecasts.\n\n /// Note, there is no guarantee that any of the devices are still available.\n\n pub fn get_discovered_chromecasts(&self) -> &Vec<(String, IpAddr)> {\n\n &self.discovered_chromecasts\n\n }\n\n \n\n /// Sets the selected chromecast to the passed reference. Note, the device MUST be present\n\n /// in discovered chromecasts, otherwise this will return an error.\n\n pub fn select_chromecast(&mut self, device: &(String, IpAddr)) -> Result<(), Error> {\n\n if self.discovered_chromecasts.contains(&device) {\n\n self.current_chromecast = Some(device.clone());\n\n self.caster.set_device_addr(&device.1.to_string());\n\n\n\n log::info!(\"[API] Selected chromecast: {:?}\", &device);\n\n }\n\n else{\n\n return Err(Error::ApiError(\"Device not found within discovered_chromecasts,try calling Api::discover_chromecasts() first.\".into()));\n\n }\n\n \n", "file_path": "src/api/mod.rs", "rank": 32, "score": 15451.992388857054 }, { "content": " tx.send(cast::find_chromecasts().await).unwrap();\n\n });\n\n \n\n // Wait for the thread to send the list of chromecasts\n\n let chromecasts;\n\n loop {\n\n if let Ok(msg) = rx.try_recv() {\n\n chromecasts = msg;\n\n break;\n\n }\n\n }\n\n \n\n // Either store the result or return the error\n\n match chromecasts {\n\n Ok(chromecasts) => self.discovered_chromecasts = chromecasts,\n\n Err(err) => return Err(err.into()),\n\n }\n\n\n\n Ok(())\n\n }\n", "file_path": "src/api/mod.rs", "rank": 35, "score": 15449.999713804014 }, { "content": "}\n\n\n\n\n\n/// Put request function to send a CastSignal request to the API\n\nasync fn put_cast_signal(\n\n signal: api::CastSignal,\n\n mut api_tx: mpsc::Sender<api::Request>) \n\n -> Result<impl warp::Reply, warp::Rejection> {\n\n \n\n let (req_tx, req_rx) = oneshot::channel::<String>();\n\n // Send the requested signal to the caster thread\n\n let request = api::Request::Put( api::PutType::Control(signal), req_tx);\n\n api_tx.send( request ).await.unwrap();\n\n \n\n match await_api_response(req_rx) {\n\n Ok(resp) => Ok(warp::reply::with_status( resp, warp::http::StatusCode::OK )),\n\n Err(_) => Err(warp::reject::reject()),\n\n }\n\n}\n\n\n", "file_path": "src/server/mod.rs", "rank": 36, "score": 15449.415285468778 }, { "content": " PutType::SelectChromecast(addr) => {\n\n log::info!(\"[API] Request recieved: select chromecast '{}'\", addr);\n\n // Try to match the chromecast with a discovered device\n\n if let Some(device) = &self.discovered_chromecasts\n\n .clone()\n\n .iter()\n\n .find(|x| x.1.to_string() == addr) {\n\n \n\n self.select_chromecast(&device.clone()).unwrap();\n\n let _ = sender.send(\"Success.\".into());\n\n } \n\n else {\n\n let _ = sender.send(\"Chromecast not found.\".into());\n\n }\n\n },\n\n }\n\n }\n\n\n\n // Handle Get requests\n\n Request::Get(get, sender) => self.handle_get_request(get, sender),\n", "file_path": "src/api/mod.rs", "rank": 37, "score": 15449.253791393261 }, { "content": "}\n\n\n\n#[derive(Debug, Clone, Copy, Serialize, Deserialize)]\n\npub enum GetType {\n\n MediaStatus,\n\n Chromecasts,\n\n}\n\n\n\n/// PutTypes are used to determine what Put request is being called.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum PutType {\n\n /// Used to transmit signals to the chromecast\n\n Control(CastSignal),\n\n SelectChromecast(String),\n\n DiscoverChromecasts,\n\n}\n\n\n\n/// CastSignals are used to send requests to the chromecast for playback\n\n/// These are essentially the remote control for the chromecast.\n\n#[derive(Debug, Clone, Copy, Serialize, Deserialize)]\n", "file_path": "src/api/mod.rs", "rank": 38, "score": 15449.117751520751 }, { "content": "pub mod error;\n\n\n\nuse crate::cast;\n\nuse std::net::IpAddr;\n\nuse serde::{Serialize, Deserialize};\n\nuse tokio::sync::oneshot;\n\n\n\npub type Error = error::ApiError;\n\n\n\n/// `Request` are the used as the main wrapper for API interaction\n\n/// They can be sent via channel and handled by the Api struct easily \n\n/// through `Api::handle_request()`.\n\n/// All variants of `Request` accept a tokio `oneshot::Sender` as part of their parameters.\n\n/// This is used to send JSON feedback to the API caller. If the reciever is dropped before\n\n/// a response is sent, the feedback will simply be discarded without an error.\n\n#[derive(Debug)]\n\n#[allow(dead_code)]\n\npub enum Request {\n\n Put(PutType, oneshot::Sender<String>),\n\n Get(GetType, oneshot::Sender<String>),\n", "file_path": "src/api/mod.rs", "rank": 39, "score": 15448.903564911298 }, { "content": " Ok(())\n\n }\n\n\n\n /// Handles API requests from a client.\n\n pub fn handle_request(&mut self, request: Request) {\n\n match request {\n\n // Handle Put requests\n\n Request::Put(put, sender) => {\n\n match put {\n\n // Forward CastSignal to handler\n\n PutType::Control(signal) => self.handle_cast_signal(signal, sender),\n\n \n\n // Perform mDNS discovery, this is blocking\n\n PutType::DiscoverChromecasts => {\n\n log::info!(\"[API] Request recieved: DiscoverChromecasts\");\n\n self.discover_chromecasts().unwrap();\n\n let _ = sender.send(\"Success.\".into());\n\n },\n\n \n\n // Attempt to select specific chromecast\n", "file_path": "src/api/mod.rs", "rank": 41, "score": 15445.040937024596 }, { "content": "pub enum CastSignal {\n\n /// CastSignal::Begin takes a u32 representing the index of the video file in the server's\n\n /// library. This will likely need to be retrieved with a Get before it can be determined.\n\n Begin(u32),\n\n Stop,\n\n Pause,\n\n Play,\n\n Seek(f32),\n\n}\n\n\n\n/// Api serves as an easily manipulated interface with a Caster.\n\n/// The intended purpose is to streamline interaction between a client program\n\n/// and this daemon.\n\npub struct Api {\n\n // TODO move caster to private, once appropriate control functions are in place\n\n pub caster: cast::Caster,\n\n current_chromecast: Option<(String, IpAddr)>,\n\n discovered_chromecasts: Vec<(String, IpAddr)>,\n\n}\n\n\n", "file_path": "src/api/mod.rs", "rank": 42, "score": 15444.394284623379 }, { "content": " // Build Vec<(String, String)> from &Vec<(String, IpAddr)>\n\n let chromecasts: Vec<(String, String)> = self.discovered_chromecasts\n\n .iter()\n\n .map(|x| (x.0.clone(), (x.1).to_string()))\n\n .collect();\n\n \n\n // Serialize to map in JSON and reply to API caller\n\n let _ = sender.send(serde_json::to_string(&chromecasts).unwrap());\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/api/mod.rs", "rank": 43, "score": 15441.935356601514 }, { "content": " .and(json_to_signal())\n\n .and(tx_filter.clone())\n\n .and_then(put_cast_signal);\n\n\n\n let get_media_status = warp::get()\n\n .and(warp::path(\"api\"))\n\n .and(warp::path(\"media-status\"))\n\n .and(warp::path::end())\n\n .and(tx_filter.clone())\n\n .and_then(get_media_status);\n\n\n\n let route = warp::any().and(\n\n webapp\n\n .or(put_signals)\n\n .or(get_media_status)\n\n );\n\n\n\n let addr = ([0,0,0,0], port);\n\n let (_, server) = warp::serve(route)\n\n .bind_with_graceful_shutdown(addr, async {\n", "file_path": "src/server/mod.rs", "rank": 44, "score": 15441.315275645627 }, { "content": " }\n\n }\n\n \n\n /// Handles Request::Put(Control(CastSignal)) requests.\n\n /// These are essentially the remote control signals that handle video\n\n /// playback.\n\n /// # Parameters\n\n /// `signal: CastSignal` - The signal to handle, this determines what to tell the chromecast to\n\n /// do.\n\n /// `sender: Sender<String>` - The feedback to return to the client.\n\n // TODO Only reply to client after chromecast has reacted to signal. This allows for a client to determine when the chromecast has ACTUALLY enacted its request.\n\n fn handle_cast_signal(&self, signal: CastSignal, sender: oneshot::Sender<String>) {\n\n let _ = sender.send(\"Request recieved.\".into());\n\n log::info!(\"[API] Request recieved: {:?}\", signal);\n\n \n\n if !self.caster.is_streaming() {\n\n log::info!(\"[API] Failed request. Chromecast is not streaming.\");\n\n return;\n\n }\n\n\n", "file_path": "src/api/mod.rs", "rank": 46, "score": 15437.216402466727 }, { "content": "use crate::api;\n\n\n\nuse std::path::Path;\n\nuse tokio::sync::{ oneshot, mpsc };\n\nuse warp::{reply::Response, Filter};\n\n\n\n/// Convert a json input into a CastSignal\n", "file_path": "src/server/mod.rs", "rank": 47, "score": 15434.850470497207 }, { "content": " // Spawn the casting thread\n\n // this will be where the API is interfaced\n\n let (cast_tx, mut cast_rx) = tokio::sync::mpsc::channel::<api::Request>(1024);\n\n\n\n // Spawn webapp/api server\n\n let handle = Handle::current();\n\n std::thread::spawn(move || {\n\n handle.spawn( async move {\n\n let (_shutdown_tx, shutdown_rx) = oneshot::channel::<()>();\n\n server::host_api(8008, shutdown_rx, cast_tx).await;\n\n });\n\n });\n\n\n\n let mut api = Api::new();\n\n api.discover_chromecasts().unwrap();\n\n let chromecasts = api.get_discovered_chromecasts().clone();\n\n if let Some(cast) = chromecasts.first() {\n\n api.select_chromecast(cast).unwrap(); \n\n }\n\n else {\n", "file_path": "src/main.rs", "rank": 48, "score": 11.815818719879843 }, { "content": " println!(\"No chromecasts found. Aborting.\");\n\n return;\n\n }\n\n\n\n let handle = Handle::current();\n\n std::thread::spawn( move || {\n\n handle.spawn( async move {\n\n let (_tx, rx) = tokio::sync::oneshot::channel::<()>();\n\n let path = PathBuf::from(\"sample.mp4\");\n\n server::host_media(&path, 8009, rx).await;\n\n });\n\n });\n\n\n\n api.caster.begin_cast(8009).unwrap();\n\n \n\n // API loop\n\n loop {\n\n if let Some(request) = cast_rx.recv().await {\n\n api.handle_request(request);\n\n }\n\n };\n\n}\n", "file_path": "src/main.rs", "rank": 49, "score": 10.868354432372165 }, { "content": "use std::path::PathBuf;\n\nuse tokio::runtime::Handle;\n\nuse tokio::sync::oneshot;\n\n\n\nextern crate ffmpeg_next as ffmpeg; \n\n\n\nmod cast;\n\nmod server;\n\nmod video_encoding;\n\nmod api;\n\n\n\nuse api::Api;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n fern::Dispatch::new()\n\n .level(log::LevelFilter::Info)\n\n .chain(std::io::stdout())\n\n .apply().unwrap();\n\n \n", "file_path": "src/main.rs", "rank": 50, "score": 10.199836092961192 }, { "content": "# Daemon\n\n - Complete API features:\n\n - Media Status\n\n - Discover/List/Select Chromecast\n\n - Queuing\n\n - Library\n\n \n\n - Implement correct control flow, that is, handle all control of the chromecast in API functionality.\n\n\n\n# Client\n\n - Not started\n\n\n\n# Web app\n\n - Complete Playback UI\n\n - Finish API service\n\n - Server dashboard\n\n - Video selection\n\n - Library display\n", "file_path": "TODO.md", "rank": 51, "score": 9.231501832296651 }, { "content": " }\n\n stream_mapping[ist_index] = ost_index;\n\n ist_time_bases[ist_index] = ist.time_base();\n\n ost_index += 1;\n\n let mut ost = octx.add_stream(encoder::find(codec::Id::None)).unwrap();\n\n ost.set_parameters(ist.parameters());\n\n // We need to set codec_tag to 0 lest we run into incompatible codec tag\n\n // issues when muxing into a different container format. Unfortunately\n\n // there's no high level API to do this (yet).\n\n unsafe {\n\n (*ost.parameters().as_mut_ptr()).codec_tag = 0;\n\n }\n\n }\n\n\n\n octx.set_metadata(ictx.metadata().to_owned());\n\n octx.write_header().unwrap();\n\n\n\n for (stream, mut packet) in ictx.packets() {\n\n let ist_index = stream.index();\n\n let ost_index = stream_mapping[ist_index];\n", "file_path": "src/video_encoding.rs", "rank": 52, "score": 6.703127903168898 }, { "content": "use ffmpeg::{\n\n codec, encoder, format, log, media, Rational,\n\n};\n\n\n\n#[allow(dead_code)]\n\n#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]\n\npub enum Chromecast {\n\n FirstAndSecond,\n\n Third,\n\n Ultra,\n\n GoogleTV,\n\n NestHub,\n\n}\n\n\n\n\n\n/// A list of valid codec pairs (video, audio), Note that these don't work\n\n/// for ALL chromecast generations, but ones not listed here are always \n\n/// non-compatible. Majority of these are untested and are just based off Google's\n\n/// supported media types list.\n\n#[allow(dead_code)]\n", "file_path": "src/video_encoding.rs", "rank": 53, "score": 6.054693125764516 }, { "content": " if ost_index < 0 {\n\n continue;\n\n }\n\n let ost = octx.stream(ost_index as _).unwrap();\n\n packet.rescale_ts(ist_time_bases[ist_index], ost.time_base());\n\n packet.set_position(-1);\n\n packet.set_stream(ost_index as _);\n\n packet.write_interleaved(&mut octx).unwrap();\n\n }\n\n\n\n octx.write_trailer().unwrap();\n\n}\n\n\n", "file_path": "src/video_encoding.rs", "rank": 54, "score": 5.930911714644921 }, { "content": "# μCaster \n\n(mucaster)\n\n\n\nOnce completed, μCaster is a cross-platform Chromecast controller that can play files directly from a host computer. This project is directly inspired by Gnomecast and Videostream while aiming to provide a more lightweight, terminal/webapp based, cross-platform alternative. The webapp merely serves as an interface and can be swapped/supplemented freely, provided a matching API is used.\n\n\n\nWindows and Linux are the only supported platforms. MacOS may work, however will never actively be tested or supported (by me). \n\n\n\n## Acknowledgments\n\n\n\n* This project would not be possible without [rust-cast](https://github.com/azasypkin/rust-cast). \n\n* File conversion is performed by the ubiquitous [ffmpeg](https://github.com/FFmpeg/FFmpeg) and supplied via [ffmpeg-next](https://github.com/zmwangx/rust-ffmpeg).\n\n* Finally, without inspiration from [Gnomecast](https://github.com/keredson/gnomecast) I would have never started this project. \n\n\n\n\n\n### Author\n\n\n\n[Jayden Dumouchel](mailto:[email protected])\n\n\n\n### License\n\n\n\nThis project is licensed under the MIT License - see the LICENSE.md file for details\n", "file_path": "README.md", "rank": 55, "score": 4.190474935690263 }, { "content": "const VALID_CODECS: [(codec::Id, codec::Id); 8] = [\n\n (codec::Id::H264, codec::Id::MP3),\n\n (codec::Id::H264, codec::Id::AAC),\n\n (codec::Id::HEVC, codec::Id::MP3),\n\n (codec::Id::HEVC, codec::Id::AAC),\n\n (codec::Id::H265, codec::Id::MP3),\n\n (codec::Id::H265, codec::Id::AAC),\n\n (codec::Id::VP8, codec::Id::VORBIS),\n\n (codec::Id::VP9, codec::Id::VORBIS),\n\n];\n\n\n\n// TODO convert from &str to Path/PathBuf\n\n// TODO perform error wrapping/handling\n\n/// Test if the video and audio codecs are compatible with specific chromecast\n\n#[allow(dead_code)]\n", "file_path": "src/video_encoding.rs", "rank": 56, "score": 3.598786158322818 }, { "content": "MIT License\n\n\n\nCopyright (c) 2020 Jayden Dumouchel\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", "file_path": "LICENSE.md", "rank": 57, "score": 2.830986156139805 } ]
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(&vm.interner.str(name));\n\n result\n\n}\n\n\n", "file_path": "dora/src/vm/namespaces.rs", "rank": 1, "score": 560323.911551744 }, { "content": "pub fn method_accessible_from(vm: &VM, fct_id: FctId, namespace_id: NamespaceId) -> bool {\n\n let fct = vm.fcts.idx(fct_id);\n\n let fct = fct.read();\n\n\n\n let element_pub = match fct.parent {\n\n FctParent::Class(cls_id) => {\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n\n\n cls.is_pub && fct.is_pub\n\n }\n\n\n\n FctParent::Extension(_) => fct.is_pub,\n\n FctParent::Impl(_) | FctParent::Trait(_) => {\n\n // TODO: This should probably be limited\n\n return true;\n\n }\n\n\n\n FctParent::Module(module_id) => {\n\n let module = vm.modules.idx(module_id);\n", "file_path": "dora/src/vm/classes.rs", "rank": 2, "score": 536125.5933143252 }, { "content": "pub fn trait_accessible_from(vm: &VM, trait_id: TraitId, namespace_id: NamespaceId) -> bool {\n\n let xtrait = vm.traits[trait_id].read();\n\n\n\n accessible_from(vm, xtrait.namespace_id, xtrait.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/traits.rs", "rank": 3, "score": 532571.0659403474 }, { "content": "fn find_trait(vm: &mut VM, namespace_id: NamespaceId, name: &str) -> TraitId {\n\n let iname = vm.interner.intern(name);\n\n let symtable = NestedSymTable::new(vm, namespace_id);\n\n symtable.get_trait(iname).expect(\"trait not found\")\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 4, "score": 514901.64251479926 }, { "content": "pub fn struct_accessible_from(vm: &VM, struct_id: StructId, namespace_id: NamespaceId) -> bool {\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n accessible_from(vm, xstruct.namespace_id, xstruct.is_pub, namespace_id)\n\n}\n\n\n", "file_path": "dora/src/vm/structs.rs", "rank": 5, "score": 503376.60220245284 }, { "content": "pub fn fct_accessible_from(vm: &VM, fct_id: FctId, namespace_id: NamespaceId) -> bool {\n\n let fct = vm.fcts.idx(fct_id);\n\n let fct = fct.read();\n\n\n\n accessible_from(vm, fct.namespace_id, fct.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/functions.rs", "rank": 6, "score": 494362.59092547616 }, { "content": "pub fn namespace_contains(vm: &VM, parent_id: NamespaceId, child_id: NamespaceId) -> bool {\n\n if parent_id == child_id {\n\n return true;\n\n }\n\n\n\n let namespace = &vm.namespaces[child_id.to_usize()];\n\n namespace.parents.contains(&parent_id)\n\n}\n\n\n", "file_path": "dora/src/vm/namespaces.rs", "rank": 8, "score": 448614.7631573996 }, { "content": "pub fn check(vm: &mut VM) -> bool {\n\n // add user defined fcts and classes to vm\n\n // this check does not look into fct or class bodies\n\n if let Err(_) = globaldef::check(vm) {\n\n return false;\n\n }\n\n return_on_error!(vm);\n\n\n\n // add internal annotations early\n\n stdlib::resolve_internal_annotations(vm);\n\n\n\n // define internal classes\n\n stdlib::resolve_internal_classes(vm);\n\n\n\n // discover all enum variants\n\n enumck::check_variants(vm);\n\n\n\n // fill prelude with important types and functions\n\n stdlib::fill_prelude(vm);\n\n\n", "file_path": "dora/src/semck.rs", "rank": 9, "score": 436322.2942558858 }, { "content": "pub fn global_accessible_from(vm: &VM, global_id: GlobalId, namespace_id: NamespaceId) -> bool {\n\n let global = vm.globals.idx(global_id);\n\n let global = global.read();\n\n\n\n accessible_from(vm, global.namespace_id, global.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/globals.rs", "rank": 10, "score": 436026.60322782316 }, { "content": "pub fn class_accessible_from(vm: &VM, cls_id: ClassId, namespace_id: NamespaceId) -> bool {\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n\n\n accessible_from(vm, cls.namespace_id, cls.is_pub, namespace_id)\n\n}\n\n\n", "file_path": "dora/src/vm/classes.rs", "rank": 11, "score": 436026.60322782316 }, { "content": "pub fn enum_accessible_from(vm: &VM, enum_id: EnumId, namespace_id: NamespaceId) -> bool {\n\n let xenum = vm.enums[enum_id].read();\n\n\n\n accessible_from(vm, xenum.namespace_id, xenum.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/enums.rs", "rank": 12, "score": 436026.60322782316 }, { "content": "pub fn const_accessible_from(vm: &VM, const_id: ConstId, namespace_id: NamespaceId) -> bool {\n\n let xconst = vm.consts.idx(const_id);\n\n let xconst = xconst.read();\n\n\n\n accessible_from(vm, xconst.namespace_id, xconst.is_pub, namespace_id)\n\n}\n", "file_path": "dora/src/vm/consts.rs", "rank": 13, "score": 436026.60322782316 }, { "content": "fn find_enum(vm: &mut VM, namespace_id: NamespaceId, name: &str) -> EnumId {\n\n let iname = vm.interner.intern(name);\n\n let symtable = NestedSymTable::new(vm, namespace_id);\n\n symtable.get_enum(iname).expect(\"enum not found\")\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 14, "score": 429103.73502807686 }, { "content": "fn find_static(vm: &VM, namespace_id: NamespaceId, container_name: &str, name: &str) -> FctId {\n\n let container_name = vm.interner.intern(container_name);\n\n\n\n let symtable = NestedSymTable::new(vm, namespace_id);\n\n let sym = symtable.get(container_name);\n\n let intern_name = vm.interner.intern(name);\n\n\n\n match sym {\n\n Some(Sym::Module(module_id)) => {\n\n let module = vm.modules.idx(module_id);\n\n let module = module.read();\n\n\n\n for &mid in &module.methods {\n\n let mtd = vm.fcts.idx(mid);\n\n let mtd = mtd.read();\n\n\n\n if mtd.name == intern_name {\n\n return mid;\n\n }\n\n }\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 15, "score": 428779.4801248413 }, { "content": "fn find_method(vm: &VM, namespace_id: NamespaceId, container_name: &str, name: &str) -> FctId {\n\n let container_name = vm.interner.intern(container_name);\n\n\n\n let cls_id = NestedSymTable::new(vm, namespace_id)\n\n .get_class(container_name)\n\n .expect(\"class not found\");\n\n\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n let intern_name = vm.interner.intern(name);\n\n\n\n for &mid in &cls.methods {\n\n let mtd = vm.fcts.idx(mid);\n\n let mtd = mtd.read();\n\n\n\n if mtd.name == intern_name {\n\n return mid;\n\n }\n\n }\n\n\n\n panic!(\"cannot find class method `{}`\", name)\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 16, "score": 428706.47594565235 }, { "content": "pub fn type_names(vm: &VM, types: &[SourceType]) -> String {\n\n let mut result = String::new();\n\n result.push('[');\n\n let mut first = true;\n\n for ty in types {\n\n if !first {\n\n result.push_str(\", \");\n\n }\n\n result.push_str(&ty.name(vm));\n\n first = false;\n\n }\n\n result.push(']');\n\n result\n\n}\n\n\n", "file_path": "dora/src/ty.rs", "rank": 17, "score": 428479.16183685476 }, { "content": "pub fn report_sym_shadow(vm: &VM, name: Name, file: FileId, pos: Position, sym: Sym) {\n\n let name = vm.interner.str(name).to_string();\n\n\n\n let msg = match sym {\n\n Sym::Class(_) => SemError::ShadowClass(name),\n\n Sym::Struct(_) => SemError::ShadowStruct(name),\n\n Sym::Trait(_) => SemError::ShadowTrait(name),\n\n Sym::Enum(_) => SemError::ShadowEnum(name),\n\n Sym::Fct(_) => SemError::ShadowFunction(name),\n\n Sym::Global(_) => SemError::ShadowGlobal(name),\n\n Sym::Const(_) => SemError::ShadowConst(name),\n\n Sym::Module(_) => SemError::ShadowModule(name),\n\n Sym::Var(_) => SemError::ShadowParam(name),\n\n Sym::Namespace(_) => SemError::ShadowNamespace(name),\n\n _ => unreachable!(),\n\n };\n\n\n\n vm.diag.lock().report(file, pos, msg);\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 18, "score": 424887.4704696149 }, { "content": "pub fn namespace_accessible_from(vm: &VM, target_id: NamespaceId, from_id: NamespaceId) -> bool {\n\n accessible_from(vm, target_id, true, from_id)\n\n}\n\n\n", "file_path": "dora/src/vm/namespaces.rs", "rank": 19, "score": 422759.24854890746 }, { "content": "pub fn parse_bundled_stdlib(vm: &mut VM, namespace_id: NamespaceId) -> Result<(), i32> {\n\n use crate::driver::start::STDLIB;\n\n\n\n for (filename, content) in STDLIB {\n\n parse_bundled_stdlib_file(vm, namespace_id, filename, content)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "dora/src/semck/globaldef.rs", "rank": 20, "score": 421190.28011374595 }, { "content": "fn intrinsic_fct(vm: &mut VM, namespace_id: NamespaceId, name: &str, intrinsic: Intrinsic) {\n\n common_fct(\n\n vm,\n\n namespace_id,\n\n name,\n\n FctImplementation::Intrinsic(intrinsic),\n\n );\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 21, "score": 414192.47685143305 }, { "content": "fn internal_class(vm: &VM, namespace_id: NamespaceId, name: &str) -> ClassId {\n\n let iname = vm.interner.intern(name);\n\n let symtable = NestedSymTable::new(vm, namespace_id);\n\n let clsid = symtable.get_class(iname).expect(\"class not found\");\n\n\n\n let cls = vm.classes.idx(clsid);\n\n let mut cls = cls.write();\n\n cls.internal_resolved = true;\n\n\n\n clsid\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 22, "score": 410990.32597664365 }, { "content": "fn common_fct(vm: &mut VM, namespace_id: NamespaceId, name: &str, kind: FctImplementation) {\n\n let name = vm.interner.intern(name);\n\n let fctid = NestedSymTable::new(vm, namespace_id)\n\n .get_fct(name)\n\n .expect(\"function not found\");\n\n\n\n let fct = vm.fcts.idx(fctid);\n\n let mut fct = fct.write();\n\n\n\n match kind {\n\n FctImplementation::Intrinsic(intrinsic) => fct.intrinsic = Some(intrinsic),\n\n FctImplementation::Native(address) => {\n\n fct.native_pointer = Some(address);\n\n }\n\n }\n\n fct.internal_resolved = true;\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 23, "score": 410566.76958718494 }, { "content": "fn native_fct(vm: &mut VM, namespace_id: NamespaceId, name: &str, fctptr: *const u8) {\n\n common_fct(\n\n vm,\n\n namespace_id,\n\n name,\n\n FctImplementation::Native(Address::from_ptr(fctptr)),\n\n );\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 24, "score": 403348.25509194867 }, { "content": "pub fn resolve_internal_annotations(vm: &mut VM) {\n\n let stdlib = vm.stdlib_namespace_id;\n\n vm.known.annotations.abstract_ =\n\n internal_annotation(vm, stdlib, \"abstract\", Modifier::Abstract);\n\n vm.known.annotations.final_ = internal_annotation(vm, stdlib, \"final\", Modifier::Final);\n\n vm.known.annotations.internal = internal_annotation(vm, stdlib, \"internal\", Modifier::Internal);\n\n vm.known.annotations.open = internal_annotation(vm, stdlib, \"open\", Modifier::Open);\n\n vm.known.annotations.override_ =\n\n internal_annotation(vm, stdlib, \"override\", Modifier::Override);\n\n vm.known.annotations.pub_ = internal_annotation(vm, stdlib, \"pub\", Modifier::Pub);\n\n vm.known.annotations.static_ = internal_annotation(vm, stdlib, \"static\", Modifier::Static);\n\n\n\n vm.known.annotations.test = internal_annotation(vm, stdlib, \"test\", Modifier::Test);\n\n\n\n vm.known.annotations.optimize_immediately = internal_annotation(\n\n vm,\n\n stdlib,\n\n \"optimizeImmediately\",\n\n Modifier::OptimizeImmediately,\n\n );\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 25, "score": 400433.46260823694 }, { "content": "pub fn resolve_internal_functions(vm: &mut VM) {\n\n let stdlib = vm.stdlib_namespace_id;\n\n native_fct(vm, stdlib, \"fatalError\", stdlib::fatal_error as *const u8);\n\n native_fct(vm, stdlib, \"abort\", stdlib::abort as *const u8);\n\n native_fct(vm, stdlib, \"exit\", stdlib::exit as *const u8);\n\n intrinsic_fct(vm, stdlib, \"unreachable\", Intrinsic::Unreachable);\n\n\n\n native_fct(vm, stdlib, \"print\", stdlib::print as *const u8);\n\n native_fct(vm, stdlib, \"println\", stdlib::println as *const u8);\n\n intrinsic_fct(vm, stdlib, \"assert\", Intrinsic::Assert);\n\n intrinsic_fct(vm, stdlib, \"debug\", Intrinsic::Debug);\n\n native_fct(vm, stdlib, \"argc\", stdlib::argc as *const u8);\n\n native_fct(vm, stdlib, \"argv\", stdlib::argv as *const u8);\n\n native_fct(vm, stdlib, \"forceCollect\", stdlib::gc_collect as *const u8);\n\n native_fct(vm, stdlib, \"timestamp\", stdlib::timestamp as *const u8);\n\n native_fct(\n\n vm,\n\n stdlib,\n\n \"forceMinorCollect\",\n\n stdlib::gc_minor_collect as *const u8,\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 26, "score": 400433.46260823694 }, { "content": "pub fn resolve_internal_classes(vm: &mut VM) {\n\n let stdlib = vm.stdlib_namespace_id;\n\n vm.known.structs.bool = internal_struct(vm, stdlib, \"Bool\", Some(SourceType::Bool));\n\n\n\n vm.known.structs.uint8 = internal_struct(vm, stdlib, \"UInt8\", Some(SourceType::UInt8));\n\n vm.known.structs.char = internal_struct(vm, stdlib, \"Char\", Some(SourceType::Char));\n\n vm.known.structs.int32 = internal_struct(vm, stdlib, \"Int32\", Some(SourceType::Int32));\n\n vm.known.structs.int64 = internal_struct(vm, stdlib, \"Int64\", Some(SourceType::Int64));\n\n\n\n vm.known.structs.float32 = internal_struct(vm, stdlib, \"Float32\", Some(SourceType::Float32));\n\n vm.known.structs.float64 = internal_struct(vm, stdlib, \"Float64\", Some(SourceType::Float64));\n\n\n\n vm.known.classes.object = Some(find_class(vm, stdlib, \"Object\"));\n\n vm.known.classes.string = Some(internal_class(vm, stdlib, \"String\"));\n\n\n\n vm.known.classes.string_buffer = Some(find_class(vm, stdlib, \"StringBuffer\"));\n\n\n\n vm.known.classes.atomic_int32 = Some(find_class(vm, stdlib, \"AtomicInt32\"));\n\n vm.known.classes.atomic_int64 = Some(find_class(vm, stdlib, \"AtomicInt64\"));\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 27, "score": 400433.46260823694 }, { "content": "pub fn discover_known_methods(vm: &mut VM) {\n\n let stdlib = vm.stdlib_namespace_id;\n\n vm.known.functions.string_buffer_empty = find_static(vm, stdlib, \"StringBuffer\", \"empty\");\n\n vm.known.functions.string_buffer_append = find_method(vm, stdlib, \"StringBuffer\", \"append\");\n\n vm.known.functions.string_buffer_to_string =\n\n find_method(vm, stdlib, \"StringBuffer\", \"toString\");\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 28, "score": 400339.11357729294 }, { "content": "pub fn namespace_package(vm: &VM, namespace_id: NamespaceId) -> NamespaceId {\n\n let namespace = &vm.namespaces[namespace_id.to_usize()];\n\n\n\n if let Some(&global_id) = namespace.parents.first() {\n\n global_id\n\n } else {\n\n namespace_id\n\n }\n\n}\n\n\n", "file_path": "dora/src/vm/namespaces.rs", "rank": 29, "score": 396692.5292372585 }, { "content": "fn ensure_display(vm: &VM, vtable: &mut VTableBox, parent_id: Option<ClassDefId>) -> usize {\n\n // if subtype_display[0] is set, vtable was already initialized\n\n assert!(vtable.subtype_display[0].is_null());\n\n\n\n if let Some(parent_id) = parent_id {\n\n let parent = vm.class_defs.idx(parent_id);\n\n\n\n let parent_vtable = parent.vtable.read();\n\n let parent_vtable = parent_vtable.as_ref().unwrap();\n\n assert!(!parent_vtable.subtype_display[0].is_null());\n\n\n\n let depth = 1 + parent_vtable.subtype_depth;\n\n\n\n let depth_fixed;\n\n\n\n if depth >= DISPLAY_SIZE {\n\n depth_fixed = DISPLAY_SIZE;\n\n\n\n vtable.allocate_overflow(depth as usize - DISPLAY_SIZE + 1);\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 30, "score": 388496.05016134714 }, { "content": "/// returns true if given size is gen aligned\n\npub fn gen_aligned(size: usize) -> bool {\n\n (size & (GEN_SIZE - 1)) == 0\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq, Eq)]\n\npub enum GcReason {\n\n PromotionFailure,\n\n AllocationFailure,\n\n ForceCollect,\n\n ForceMinorCollect,\n\n Stress,\n\n StressMinor,\n\n}\n\n\n\nimpl GcReason {\n\n fn message(&self) -> &'static str {\n\n match self {\n\n GcReason::PromotionFailure => \"promo failure\",\n\n GcReason::AllocationFailure => \"alloc failure\",\n\n GcReason::ForceCollect => \"force collect\",\n", "file_path": "dora/src/gc.rs", "rank": 31, "score": 386125.5748325896 }, { "content": "fn determine_vtable(vm: &VM, lens: &mut HashSet<ClassId>, cls: &mut Class) {\n\n if let Some(parent_class) = cls.parent_class.clone() {\n\n let parent_cls_id = parent_class.cls_id().expect(\"no class\");\n\n let parent = vm.classes.idx(parent_cls_id);\n\n if !lens.contains(&parent_cls_id) {\n\n let mut parent = parent.write();\n\n determine_vtable(vm, lens, &mut *parent)\n\n }\n\n\n\n let parent = parent.read();\n\n cls.virtual_fcts\n\n .extend_from_slice(parent.virtual_fcts.as_slice());\n\n }\n\n\n\n for &mid in &cls.methods {\n\n let fct = vm.fcts.idx(mid);\n\n let mut fct = fct.write();\n\n\n\n assert!(fct.vtable_index.is_none());\n\n\n", "file_path": "dora/src/semck/superck.rs", "rank": 32, "score": 385888.65015782806 }, { "content": "pub fn should_emit_debug(vm: &VM, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = vm.args.flag_emit_debug {\n\n fct_pattern_match(vm, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 33, "score": 381344.17828069587 }, { "content": "pub fn specialize_struct_id(vm: &VM, struct_id: StructId) -> StructDefId {\n\n let struc = vm.structs.idx(struct_id);\n\n let struc = struc.read();\n\n specialize_struct(vm, &*struc, SourceTypeArray::empty())\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 34, "score": 379279.813401755 }, { "content": "pub fn specialize_class_ty(vm: &VM, ty: SourceType) -> ClassDefId {\n\n match ty {\n\n SourceType::Class(cls_id, list_id) => {\n\n let params = vm.source_type_arrays.lock().get(list_id);\n\n specialize_class_id_params(vm, cls_id, &params)\n\n }\n\n\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 35, "score": 378757.88031044457 }, { "content": "pub fn always_returns(s: &ast::Stmt) -> bool {\n\n returnck::returns_value(s).is_ok()\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 36, "score": 378240.5749189691 }, { "content": "pub fn ensure_native_stub(vm: &VM, fct_id: Option<FctId>, internal_fct: NativeFct) -> Address {\n\n let mut native_stubs = vm.native_stubs.lock();\n\n let ptr = internal_fct.ptr;\n\n\n\n if let Some(jit_fct_id) = native_stubs.find_fct(ptr) {\n\n let jit_fct = vm.jit_fcts.idx(jit_fct_id);\n\n jit_fct.instruction_start()\n\n } else {\n\n let dbg = if let Some(fct_id) = fct_id {\n\n let fct = vm.fcts.idx(fct_id);\n\n let fct = fct.read();\n\n should_emit_debug(vm, &*fct)\n\n } else {\n\n false\n\n };\n\n\n\n let jit_fct_id = native_stub::generate(vm, internal_fct, dbg);\n\n let jit_fct = vm.jit_fcts.idx(jit_fct_id);\n\n\n\n let fct_ptr = jit_fct.instruction_start();\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 37, "score": 375312.6126432511 }, { "content": "pub fn walk_struct_field<V: Visitor>(v: &mut V, f: &StructField) {\n\n v.visit_type(&f.data_type);\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 38, "score": 373983.6367442864 }, { "content": "pub fn generate_fct(vm: &VM, id: FctId) -> BytecodeFunction {\n\n let fct = vm.fcts.idx(id);\n\n let fct = fct.read();\n\n let analysis = fct.analysis();\n\n\n\n generate(vm, &fct, analysis)\n\n}\n\n\n", "file_path": "dora/src/bytecode/generator.rs", "rank": 39, "score": 373883.3195102883 }, { "content": "pub fn expr_always_returns(e: &ast::Expr) -> bool {\n\n returnck::expr_returns_value(e).is_ok()\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 40, "score": 373057.17021150276 }, { "content": "fn find_class(vm: &VM, namespace_id: NamespaceId, name: &str) -> ClassId {\n\n let iname = vm.interner.intern(name);\n\n let symtable = NestedSymTable::new(vm, namespace_id);\n\n symtable.get_class(iname).expect(\"class not found\")\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 41, "score": 367588.33805935015 }, { "content": "pub fn get_vm() -> &'static VM {\n\n unsafe { &*(VM_GLOBAL as *const VM) }\n\n}\n\n\n", "file_path": "dora/src/vm.rs", "rank": 42, "score": 367052.1495107617 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn commit(size: usize, executable: bool) -> Address {\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n use winapi::um::memoryapi::VirtualAlloc;\n\n use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE};\n\n\n\n let prot = if executable {\n\n PAGE_EXECUTE_READWRITE\n\n } else {\n\n PAGE_READWRITE\n\n };\n\n\n\n let ptr = unsafe { VirtualAlloc(ptr::null_mut(), size, MEM_COMMIT | MEM_RESERVE, prot) };\n\n\n\n if ptr.is_null() {\n\n panic!(\"VirtualAlloc failed\");\n\n }\n\n\n\n Address::from_ptr(ptr)\n\n}\n\n\n", "file_path": "dora/src/os/allocator.rs", "rank": 43, "score": 361182.8649660852 }, { "content": "pub fn check(vm: &mut VM) {\n\n for ximpl in &vm.impls {\n\n let impl_for = {\n\n let ximpl = ximpl.read();\n\n let xtrait = vm.traits[ximpl.trait_id()].read();\n\n\n\n let all: HashSet<_> = xtrait.methods.iter().cloned().collect();\n\n let mut defined = HashSet::new();\n\n let mut impl_for = HashMap::new();\n\n\n\n for &method_id in &ximpl.methods {\n\n let method = vm.fcts.idx(method_id);\n\n let method = method.read();\n\n\n\n if let Some(fid) = xtrait.find_method_with_replace(\n\n vm,\n\n method.is_static,\n\n method.name,\n\n Some(ximpl.ty.clone()),\n\n method.params_without_self(),\n", "file_path": "dora/src/semck/implck.rs", "rank": 44, "score": 360284.11725778296 }, { "content": "pub fn check(vm: &mut VM) {\n\n cycle_detection(vm);\n\n\n\n if vm.diag.lock().has_errors() {\n\n return;\n\n }\n\n\n\n // determine_struct_sizes(vm);\n\n determine_vtables(vm);\n\n}\n\n\n", "file_path": "dora/src/semck/superck.rs", "rank": 45, "score": 360284.11725778296 }, { "content": "pub fn expr_block_always_returns(e: &ast::ExprBlockType) -> bool {\n\n returnck::expr_block_returns_value(e).is_ok()\n\n}\n\n\n", "file_path": "dora/src/semck.rs", "rank": 46, "score": 358732.11911056115 }, { "content": "fn determine_stack_entry(stacktrace: &mut NativeStacktrace, vm: &VM, pc: usize) -> bool {\n\n let code_map = vm.code_map.lock();\n\n let data = code_map.get(pc.into());\n\n\n\n match data {\n\n Some(CodeDescriptor::DoraFct(fct_id)) => {\n\n let jit_fct = vm.jit_fcts.idx(fct_id);\n\n\n\n let offset = pc - jit_fct.instruction_start().to_usize();\n\n let position = jit_fct\n\n .position_for_offset(offset as u32)\n\n .expect(\"position not found for program point\");\n\n\n\n stacktrace.push_entry(fct_id, position.line as i32);\n\n\n\n true\n\n }\n\n\n\n Some(CodeDescriptor::NativeStub(fct_id)) => {\n\n let jit_fct = vm.jit_fcts.idx(fct_id);\n", "file_path": "dora/src/stack.rs", "rank": 47, "score": 357279.30465496 }, { "content": "pub fn fill_prelude(vm: &mut VM) {\n\n let symbols = [\n\n \"Bool\",\n\n \"UInt8\",\n\n \"Char\",\n\n \"Int32\",\n\n \"Int64\",\n\n \"Float32\",\n\n \"Float64\",\n\n \"Object\",\n\n \"String\",\n\n \"Array\",\n\n \"Vec\",\n\n \"print\",\n\n \"println\",\n\n \"Option\",\n\n \"unimplemented\",\n\n \"unreachable\",\n\n \"assert\",\n\n \"Result\",\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 48, "score": 356358.5604473393 }, { "content": "pub fn walk_field<V: Visitor>(v: &mut V, f: &Field) {\n\n v.visit_type(&f.data_type);\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 49, "score": 353542.7897360879 }, { "content": "pub fn walk_struct<V: Visitor>(v: &mut V, s: &Struct) {\n\n for f in &s.fields {\n\n v.visit_struct_field(f);\n\n }\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 50, "score": 353251.7332650666 }, { "content": "#[cfg(target_os = \"linux\")]\n\npub fn register_with_perf(code: &Code, vm: &VM, name: Name) {\n\n use std::fs::OpenOptions;\n\n use std::io::prelude::*;\n\n\n\n let pid = unsafe { libc::getpid() };\n\n let fname = format!(\"/tmp/perf-{}.map\", pid);\n\n\n\n let mut options = OpenOptions::new();\n\n let mut file = options.create(true).append(true).open(&fname).unwrap();\n\n\n\n let code_start = code.ptr_start().to_usize();\n\n let code_end = code.ptr_end().to_usize();\n\n let name = vm.interner.str(name);\n\n\n\n let line = format!(\n\n \"{:x} {:x} dora::{}\\n\",\n\n code_start,\n\n code_end - code_start,\n\n name\n\n );\n\n file.write_all(line.as_bytes()).unwrap();\n\n}\n\n\n", "file_path": "dora/src/os/perf.rs", "rank": 51, "score": 351215.03257772 }, { "content": "pub fn generate(vm: &VM, id: FctId, type_params: &SourceTypeArray) -> Address {\n\n let fct = vm.fcts.idx(id);\n\n let fct = fct.read();\n\n generate_fct(vm, &fct, type_params)\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 52, "score": 349758.3734453977 }, { "content": "pub fn reserve_align(size: usize, align: usize, jitting: bool) -> Reservation {\n\n debug_assert!(mem::is_page_aligned(size));\n\n debug_assert!(mem::is_page_aligned(align));\n\n\n\n let align = if align == 0 { page_size() } else { align };\n\n let unaligned_size = size + align - page_size();\n\n\n\n let unaligned_start = reserve(unaligned_size, jitting);\n\n let aligned_start: Address = mem::align_usize(unaligned_start.to_usize(), align).into();\n\n\n\n let gap_start = aligned_start.offset_from(unaligned_start);\n\n let gap_end = unaligned_size - size - gap_start;\n\n\n\n if gap_start > 0 {\n\n uncommit(unaligned_start, gap_start);\n\n }\n\n\n\n if gap_end > 0 {\n\n uncommit(aligned_start.offset(size), gap_end);\n\n }\n", "file_path": "dora/src/os/allocator.rs", "rank": 53, "score": 349270.7926745431 }, { "content": "fn determine_rootset(rootset: &mut Vec<Slot>, vm: &VM, fp: usize, pc: usize) -> bool {\n\n let code_map = vm.code_map.lock();\n\n let data = code_map.get(pc.into());\n\n\n\n match data {\n\n Some(CodeDescriptor::DoraFct(fct_id)) => {\n\n let jit_fct = vm.jit_fcts.idx(fct_id);\n\n\n\n let offset = pc - jit_fct.instruction_start().to_usize();\n\n let gcpoint = jit_fct\n\n .gcpoint_for_offset(offset as u32)\n\n .expect(\"no gcpoint\");\n\n\n\n for &offset in &gcpoint.offsets {\n\n let addr = (fp as isize + offset as isize) as usize;\n\n rootset.push(Slot::at(addr.into()));\n\n }\n\n\n\n true\n\n }\n", "file_path": "dora/src/gc/root.rs", "rank": 54, "score": 349218.27131481085 }, { "content": "fn discover_type_params(vm: &VM, ty: SourceType, used_type_params: &mut FixedBitSet) {\n\n match ty {\n\n SourceType::Error\n\n | SourceType::Unit\n\n | SourceType::This\n\n | SourceType::Any\n\n | SourceType::Bool\n\n | SourceType::UInt8\n\n | SourceType::Char\n\n | SourceType::Int32\n\n | SourceType::Int64\n\n | SourceType::Float32\n\n | SourceType::Float64\n\n | SourceType::Module(_)\n\n | SourceType::Ptr\n\n | SourceType::Trait(_, _) => {}\n\n SourceType::Class(_, list_id)\n\n | SourceType::Enum(_, list_id)\n\n | SourceType::Struct(_, list_id) => {\n\n let params = vm.source_type_arrays.lock().get(list_id);\n", "file_path": "dora/src/semck/extensiondefck.rs", "rank": 55, "score": 348162.40816313925 }, { "content": "fn add_ref_fields(vm: &VM, ref_fields: &mut Vec<i32>, offset: i32, ty: SourceType) {\n\n if let Some(tuple_id) = ty.tuple_id() {\n\n let tuples = vm.tuples.lock();\n\n let tuple = tuples.get_tuple(tuple_id);\n\n\n\n for &ref_offset in tuple.references() {\n\n ref_fields.push(offset + ref_offset);\n\n }\n\n } else if let SourceType::Enum(enum_id, type_params_id) = ty.clone() {\n\n let type_params = vm.source_type_arrays.lock().get(type_params_id);\n\n let edef_id = specialize_enum_id_params(vm, enum_id, type_params);\n\n let edef = vm.enum_defs.idx(edef_id);\n\n\n\n match edef.layout {\n\n EnumLayout::Int => {}\n\n EnumLayout::Ptr | EnumLayout::Tagged => {\n\n ref_fields.push(offset);\n\n }\n\n }\n\n } else if let SourceType::Struct(struct_id, type_params_id) = ty.clone() {\n", "file_path": "dora/src/semck/specialize.rs", "rank": 56, "score": 346746.3207865667 }, { "content": "pub fn find_trait_impl(\n\n vm: &VM,\n\n fct_id: FctId,\n\n trait_id: TraitId,\n\n object_type: SourceType,\n\n) -> FctId {\n\n debug_assert!(!object_type.contains_type_param(vm));\n\n let impl_id = find_impl(vm, object_type, &[], trait_id)\n\n .expect(\"no impl found for generic trait method call\");\n\n\n\n let ximpl = vm.impls[impl_id].read();\n\n assert_eq!(ximpl.trait_id(), trait_id);\n\n\n\n ximpl\n\n .impl_for\n\n .get(&fct_id)\n\n .cloned()\n\n .expect(\"no impl method found for generic trait call\")\n\n}\n", "file_path": "dora/src/vm/impls.rs", "rank": 57, "score": 346370.8226820424 }, { "content": "pub fn struct_field_accessible_from(\n\n vm: &VM,\n\n struct_id: StructId,\n\n field_id: StructFieldId,\n\n namespace_id: NamespaceId,\n\n) -> bool {\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n let field = &xstruct.fields[field_id.to_usize()];\n\n\n\n accessible_from(\n\n vm,\n\n xstruct.namespace_id,\n\n xstruct.is_pub && field.is_pub,\n\n namespace_id,\n\n )\n\n}\n\n\n", "file_path": "dora/src/vm/structs.rs", "rank": 58, "score": 346322.5595014511 }, { "content": "pub fn find_methods_in_struct(\n\n vm: &VM,\n\n object_type: SourceType,\n\n type_param_defs: &[TypeParam],\n\n type_param_defs2: Option<&TypeParamDefinition>,\n\n name: Name,\n\n is_static: bool,\n\n) -> Vec<Candidate> {\n\n let struct_id = if object_type.is_primitive() {\n\n object_type\n\n .primitive_struct_id(vm)\n\n .expect(\"primitive expected\")\n\n } else {\n\n object_type.struct_id().expect(\"struct expected\")\n\n };\n\n\n\n let xstruct = vm.structs.idx(struct_id);\n\n let xstruct = xstruct.read();\n\n\n\n for &extension_id in &xstruct.extensions {\n", "file_path": "dora/src/vm/structs.rs", "rank": 59, "score": 346225.76878247864 }, { "content": "pub fn walk_impl<V: Visitor>(v: &mut V, i: &Arc<Impl>) {\n\n for m in &i.methods {\n\n v.visit_method(m);\n\n }\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 60, "score": 344143.11945635354 }, { "content": "pub fn walk_trait<V: Visitor>(v: &mut V, t: &Arc<Trait>) {\n\n for m in &t.methods {\n\n v.visit_method(m);\n\n }\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 61, "score": 343869.1681623742 }, { "content": "fn parse_dir(vm: &mut VM, dirname: &str, namespace_id: NamespaceId) -> Result<(), i32> {\n\n let path = Path::new(dirname);\n\n\n\n if path.is_dir() {\n\n for entry in fs::read_dir(path).unwrap() {\n\n let path = entry.unwrap().path();\n\n\n\n if should_file_be_parsed(&path) {\n\n let file = ParseFile {\n\n path: PathBuf::from(path),\n\n namespace_id,\n\n };\n\n parse_file(vm, file)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n } else {\n\n println!(\"directory `{}` does not exist.\", dirname);\n\n\n\n Err(1)\n\n }\n\n}\n\n\n", "file_path": "dora/src/semck/globaldef.rs", "rank": 62, "score": 343787.5625619563 }, { "content": "fn run_test(vm: &VM, fct: FctId) -> bool {\n\n let testing_class = vm.known.classes.testing();\n\n let testing_class = specialize_class_id(vm, testing_class);\n\n let testing = object::alloc(vm, testing_class).cast();\n\n vm.run_test(fct, testing);\n\n\n\n !testing.has_failed()\n\n}\n\n\n", "file_path": "dora/src/driver/start.rs", "rank": 63, "score": 342264.9476387349 }, { "content": "pub fn generate<'a>(vm: &'a VM, fct: NativeFct, dbg: bool) -> JitFctId {\n\n let fct_desc = fct.desc.clone();\n\n\n\n let ngen = NativeGen {\n\n vm,\n\n masm: MacroAssembler::new(),\n\n fct,\n\n dbg,\n\n };\n\n\n\n let jit_fct = ngen.generate();\n\n let jit_start = jit_fct.ptr_start();\n\n let jit_end = jit_fct.ptr_end();\n\n let jit_fct_id: JitFctId = vm.jit_fcts.push(JitFct::Compiled(jit_fct)).into();\n\n\n\n let code_desc = match fct_desc {\n\n NativeFctDescriptor::NativeStub(_) => CodeDescriptor::NativeStub(jit_fct_id),\n\n NativeFctDescriptor::TrapStub => CodeDescriptor::TrapStub,\n\n NativeFctDescriptor::VerifyStub => CodeDescriptor::VerifyStub,\n\n NativeFctDescriptor::AllocStub => CodeDescriptor::AllocStub,\n\n NativeFctDescriptor::GuardCheckStub => CodeDescriptor::GuardCheckStub,\n\n NativeFctDescriptor::SafepointStub => CodeDescriptor::SafepointStub,\n\n };\n\n\n\n vm.insert_code_map(jit_start, jit_end, code_desc);\n\n\n\n jit_fct_id\n\n}\n\n\n", "file_path": "dora/src/compiler/native_stub.rs", "rank": 64, "score": 338884.9728705435 }, { "content": "fn is_simple_enum(vm: &VM, ty: SourceType) -> bool {\n\n match ty {\n\n SourceType::Enum(enum_id, _) => {\n\n let xenum = vm.enums[enum_id].read();\n\n xenum.simple_enumeration\n\n }\n\n\n\n _ => false,\n\n }\n\n}\n", "file_path": "dora/src/semck/fctbodyck/body.rs", "rank": 65, "score": 338756.26278734085 }, { "content": "pub fn check(vm: &mut VM) -> Result<(), i32> {\n\n parse_initial_files(vm)?;\n\n\n\n let mut next_file = 0;\n\n\n\n loop {\n\n let (next, files_to_parse) = check_files(vm, next_file);\n\n next_file = next;\n\n\n\n if files_to_parse.is_empty() {\n\n break;\n\n }\n\n\n\n for file in files_to_parse {\n\n parse_file(vm, file)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "dora/src/semck/globaldef.rs", "rank": 66, "score": 338125.3679548603 }, { "content": "pub fn should_emit_asm(vm: &VM, fct: &Fct) -> bool {\n\n if !disassembler::supported() {\n\n return false;\n\n }\n\n\n\n if let Some(ref dbg_names) = vm.args.flag_emit_asm {\n\n fct_pattern_match(vm, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 67, "score": 334430.72492271976 }, { "content": "pub fn should_emit_bytecode(vm: &VM, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = vm.args.flag_emit_bytecode {\n\n fct_pattern_match(vm, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 68, "score": 334430.72492271976 }, { "content": "pub fn get_encoded_bytecode_function_by_name(vm: &VM, name: &str) -> Ref<Obj> {\n\n let fct_name = vm.interner.intern(name);\n\n let bc_fct_id = NestedSymTable::new(vm, vm.boots_namespace_id)\n\n .get_fct(fct_name)\n\n .expect(\"method not found\");\n\n\n\n let fct = vm.fcts.idx(bc_fct_id);\n\n let fct = fct.read();\n\n\n\n let bytecode_fct = fct.bytecode.as_ref().expect(\"bytecode missing\");\n\n\n\n if should_emit_bytecode(vm, &*fct) {\n\n bytecode::dump(vm, Some(&*fct), bytecode_fct);\n\n }\n\n\n\n allocate_encoded_bytecode_function(vm, bytecode_fct)\n\n}\n", "file_path": "dora/src/boots.rs", "rank": 69, "score": 332277.60697765753 }, { "content": "pub fn specialize_struct(vm: &VM, struc: &StructData, type_params: SourceTypeArray) -> StructDefId {\n\n if let Some(&id) = struc.specializations.read().get(&type_params) {\n\n return id;\n\n }\n\n\n\n create_specialized_struct(vm, struc, type_params)\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 70, "score": 330724.91292669706 }, { "content": "fn internal_free_classes(vm: &mut VM) {\n\n let free_object: ClassDefId;\n\n let free_array: ClassDefId;\n\n\n\n {\n\n let mut class_defs = vm.class_defs.lock();\n\n let next = class_defs.len();\n\n\n\n free_object = next.into();\n\n free_array = (next + 1).into();\n\n\n\n class_defs.push(Arc::new(ClassDef {\n\n id: free_object,\n\n cls_id: None,\n\n trait_object: None,\n\n type_params: SourceTypeArray::empty(),\n\n parent_id: None,\n\n size: InstanceSize::Fixed(Header::size()),\n\n fields: Vec::new(),\n\n ref_fields: Vec::new(),\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 71, "score": 327576.5142530503 }, { "content": "pub fn supported() -> bool {\n\n false\n\n}\n\n\n", "file_path": "dora/src/disassembler/none.rs", "rank": 72, "score": 322951.3908699464 }, { "content": "fn intrinsic_ctor(vm: &VM, namespace_id: NamespaceId, class_name: &str, intrinsic: Intrinsic) {\n\n let symtable = NestedSymTable::new(vm, namespace_id);\n\n let class_name_interned = vm.interner.intern(class_name);\n\n let cls_id = symtable\n\n .get_class(class_name_interned)\n\n .expect(\"class not expected\");\n\n\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n\n\n let ctor_id = cls.constructor.expect(\"no constructor\");\n\n let ctor = vm.fcts.idx(ctor_id);\n\n let mut ctor = ctor.write();\n\n ctor.intrinsic = Some(intrinsic);\n\n}\n\n\n", "file_path": "dora/src/semck/stdlib.rs", "rank": 73, "score": 321407.09734448313 }, { "content": "fn code_method_with_struct_name(code: &'static str, struct_name: &'static str) -> Vec<Bytecode> {\n\n test::parse(code, |vm| {\n\n let fct_id = vm\n\n .struct_method_by_name(struct_name, \"f\", false)\n\n .unwrap_or_else(|| panic!(\"no function `f` in Class `{}`.\", struct_name));\n\n let fct = bytecode::generate_fct(vm, fct_id);\n\n build(&fct)\n\n })\n\n}\n\n\n", "file_path": "dora/src/bytecode/generator_tests.rs", "rank": 74, "score": 317322.1251102395 }, { "content": "fn set_backtrace(vm: &VM, mut obj: Handle<Stacktrace>, via_retrieve: bool) {\n\n let stacktrace = stacktrace_from_last_dtn(vm);\n\n let mut skip = 0;\n\n\n\n let mut skip_retrieve_stack = false;\n\n let mut skip_constructor = false;\n\n\n\n // ignore every element until first not inside susubclass of Stacktrace (ctor of Exception)\n\n if via_retrieve {\n\n for elem in stacktrace.elems.iter() {\n\n let jit_fct_id = JitFctId::from(elem.fct_id.idx() as usize);\n\n let jit_fct = vm.jit_fcts.idx(jit_fct_id);\n\n let fct_id = jit_fct.fct_id();\n\n let fct = vm.fcts.idx(fct_id);\n\n let fct = fct.read();\n\n\n\n if !skip_retrieve_stack {\n\n let stacktrace_cls = vm.classes.idx(vm.known.classes.stacktrace());\n\n let stacktrace_cls = stacktrace_cls.read();\n\n let retrieve_stacktrace_fct_id = stacktrace_cls\n", "file_path": "dora/src/stack.rs", "rank": 75, "score": 316360.83369169844 }, { "content": "pub fn walk_module<V: Visitor>(v: &mut V, m: &Arc<Module>) {\n\n for f in &m.fields {\n\n v.visit_field(f);\n\n }\n\n\n\n if let Some(ctor) = &m.constructor {\n\n v.visit_ctor(ctor);\n\n }\n\n\n\n for m in &m.methods {\n\n v.visit_method(m);\n\n }\n\n}\n\n\n", "file_path": "dora-parser/src/ast/visit.rs", "rank": 76, "score": 316301.57218044496 }, { "content": "fn encode_source_type(vm: &VM, ty: SourceType, buffer: &mut ByteBuffer) {\n\n match ty {\n\n SourceType::Error | SourceType::Any | SourceType::Ptr | SourceType::This => unreachable!(),\n\n SourceType::Unit => {\n\n buffer.emit_u8(SourceTypeOpcode::Unit.to_int());\n\n }\n\n SourceType::Bool => {\n\n buffer.emit_u8(SourceTypeOpcode::Bool.to_int());\n\n }\n\n SourceType::Char => {\n\n buffer.emit_u8(SourceTypeOpcode::Char.to_int());\n\n }\n\n SourceType::UInt8 => {\n\n buffer.emit_u8(SourceTypeOpcode::UInt8.to_int());\n\n }\n\n SourceType::Int32 => {\n\n buffer.emit_u8(SourceTypeOpcode::Int32.to_int());\n\n }\n\n SourceType::Int64 => {\n\n buffer.emit_u8(SourceTypeOpcode::Int64.to_int());\n", "file_path": "dora/src/boots/serializer.rs", "rank": 77, "score": 315876.280807446 }, { "content": "fn encode_bytecode_type(vm: &VM, ty: &BytecodeType, buffer: &mut ByteBuffer) {\n\n match ty {\n\n BytecodeType::Bool => {\n\n buffer.emit_u8(BytecodeTypeKind::Bool as u8);\n\n }\n\n BytecodeType::Char => {\n\n buffer.emit_u8(BytecodeTypeKind::Char as u8);\n\n }\n\n BytecodeType::UInt8 => {\n\n buffer.emit_u8(BytecodeTypeKind::UInt8 as u8);\n\n }\n\n BytecodeType::Int32 => {\n\n buffer.emit_u8(BytecodeTypeKind::Int32 as u8);\n\n }\n\n BytecodeType::Int64 => {\n\n buffer.emit_u8(BytecodeTypeKind::Int64 as u8);\n\n }\n\n BytecodeType::Float32 => {\n\n buffer.emit_u8(BytecodeTypeKind::Float32 as u8);\n\n }\n", "file_path": "dora/src/boots/serializer.rs", "rank": 78, "score": 315876.280807446 }, { "content": "pub fn replace_type_self(vm: &VM, ty: SourceType, self_ty: SourceType) -> SourceType {\n\n match ty {\n\n SourceType::Class(cls_id, list_id) => {\n\n let params = vm.source_type_arrays.lock().get(list_id);\n\n\n\n let params = SourceTypeArray::with(\n\n params\n\n .iter()\n\n .map(|p| replace_type_self(vm, p, self_ty.clone()))\n\n .collect::<Vec<_>>(),\n\n );\n\n\n\n let list_id = vm.source_type_arrays.lock().insert(params);\n\n SourceType::Class(cls_id, list_id)\n\n }\n\n\n\n SourceType::Trait(trait_id, list_id) => {\n\n let old_type_params = vm.source_type_arrays.lock().get(list_id);\n\n\n\n let new_type_params = SourceTypeArray::with(\n", "file_path": "dora/src/semck/specialize.rs", "rank": 79, "score": 314944.6413859035 }, { "content": "fn frames_from_pc(stacktrace: &mut NativeStacktrace, vm: &VM, pc: usize, mut fp: usize) {\n\n if !determine_stack_entry(stacktrace, vm, pc) {\n\n return;\n\n }\n\n\n\n while fp != 0 {\n\n let ra = unsafe { *((fp + 8) as *const usize) };\n\n\n\n if !determine_stack_entry(stacktrace, vm, ra) {\n\n return;\n\n }\n\n\n\n fp = unsafe { *(fp as *const usize) };\n\n }\n\n}\n\n\n", "file_path": "dora/src/stack.rs", "rank": 80, "score": 313979.512007457 }, { "content": "pub fn write_int32(vm: &VM, obj: Ref<Obj>, cls_id: ClassDefId, fid: FieldId, value: i32) {\n\n let cls_def = vm.class_defs.idx(cls_id);\n\n let field = &cls_def.fields[fid.to_usize()];\n\n let slot = obj.address().offset(field.offset as usize);\n\n assert!(field.ty == SourceType::Int32);\n\n\n\n unsafe {\n\n *slot.to_mut_ptr::<i32>() = value;\n\n }\n\n}\n\n\n\npub struct Stacktrace {\n\n pub header: Header,\n\n pub backtrace: Ref<Int32Array>,\n\n pub elements: Ref<Obj>,\n\n}\n\n\n\npub struct StacktraceElement {\n\n pub header: Header,\n\n pub name: Ref<Str>,\n", "file_path": "dora/src/object.rs", "rank": 81, "score": 313958.67669174063 }, { "content": "fn check_against_methods(vm: &VM, fct: &Fct, methods: &[FctId]) {\n\n for &method in methods {\n\n if method == fct.id {\n\n continue;\n\n }\n\n\n\n let method = vm.fcts.idx(method);\n\n let method = method.read();\n\n\n\n if method.initialized && method.name == fct.name && method.is_static == fct.is_static {\n\n let method_name = vm.interner.str(method.name).to_string();\n\n\n\n let msg = SemError::MethodExists(method_name, method.pos);\n\n vm.diag.lock().report(fct.file_id, fct.ast.pos, msg);\n\n return;\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "dora/src/semck/fctdefck.rs", "rank": 82, "score": 313456.43127902993 }, { "content": "pub fn fct_pattern_match(vm: &VM, fct: &Fct, pattern: &str) -> bool {\n\n if pattern == \"all\" {\n\n return true;\n\n }\n\n\n\n let fct_name = fct.name_with_params(vm);\n\n\n\n for part in pattern.split(',') {\n\n if fct_name.contains(part) {\n\n return true;\n\n }\n\n }\n\n\n\n false\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\npub enum AnyReg {\n\n Reg(Reg),\n\n FReg(FReg),\n", "file_path": "dora/src/compiler/codegen.rs", "rank": 83, "score": 312429.6435341369 }, { "content": "pub fn specialize_class_id(vm: &VM, cls_id: ClassId) -> ClassDefId {\n\n let cls = vm.classes.idx(cls_id);\n\n let cls = cls.read();\n\n specialize_class(vm, &*cls, &SourceTypeArray::empty())\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 84, "score": 311439.3339960456 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\npub fn register_with_perf(_: &Code, _: &VM, _: Name) {\n\n // nothing to do\n\n}\n", "file_path": "dora/src/os/perf.rs", "rank": 85, "score": 310533.2427208068 }, { "content": "pub fn write_ref(vm: &VM, obj: Ref<Obj>, cls_id: ClassDefId, fid: FieldId, value: Ref<Obj>) {\n\n let cls_def = vm.class_defs.idx(cls_id);\n\n let field = &cls_def.fields[fid.to_usize()];\n\n let slot = obj.address().offset(field.offset as usize);\n\n assert!(field.ty.reference_type());\n\n\n\n unsafe {\n\n *slot.to_mut_ptr::<Address>() = value.address();\n\n }\n\n}\n\n\n", "file_path": "dora/src/object.rs", "rank": 86, "score": 308028.55593424896 }, { "content": "pub fn check_super<'a>(vm: &VM, cls: &Class, error: ErrorReporting) -> bool {\n\n let object_type = cls.parent_class.clone().expect(\"parent_class missing\");\n\n\n\n let super_cls_id = object_type.cls_id().expect(\"no class\");\n\n let super_cls = vm.classes.idx(super_cls_id);\n\n let super_cls = super_cls.read();\n\n\n\n let checker = TypeParamCheck {\n\n vm,\n\n caller_type_param_defs: &cls.type_params,\n\n callee_type_param_defs: &super_cls.type_params,\n\n error,\n\n };\n\n\n\n let params = object_type.type_params(vm);\n\n\n\n checker.check(&params)\n\n}\n\n\n", "file_path": "dora/src/semck/typeparamck.rs", "rank": 87, "score": 307260.745726437 }, { "content": "fn run_tests(vm: &VM, namespace_id: NamespaceId) -> i32 {\n\n let mut tests = 0;\n\n let mut passed = 0;\n\n\n\n execute_on_main(|| {\n\n for fct in vm.fcts.iter() {\n\n let fct = fct.read();\n\n\n\n if !namespace_contains(vm, namespace_id, fct.namespace_id)\n\n || !is_test_fct(vm, &*fct)\n\n || !test_filter_matches(vm, &*fct)\n\n {\n\n continue;\n\n }\n\n\n\n tests += 1;\n\n\n\n print!(\"test {} ... \", vm.interner.str(fct.name));\n\n\n\n if run_test(vm, fct.id) {\n", "file_path": "dora/src/driver/start.rs", "rank": 88, "score": 306680.97281524737 }, { "content": "pub fn walk_region_and_skip_garbage<F>(vm: &VM, region: Region, mut fct: F)\n\nwhere\n\n F: FnMut(&mut Obj, Address, usize) -> bool,\n\n{\n\n let mut scan = region.start;\n\n let mut garbage_start = Address::null();\n\n let mut garbage_objects = 0;\n\n\n\n while scan < region.end {\n\n let object = scan.to_mut_obj();\n\n\n\n if object.header().vtblptr().is_null() {\n\n scan = scan.add_ptr(1);\n\n continue;\n\n }\n\n\n\n let object_size = object.size();\n\n let marked = fct(object, scan, object_size);\n\n scan = scan.offset(object_size);\n\n\n", "file_path": "dora/src/gc/swiper.rs", "rank": 89, "score": 301122.2045730168 }, { "content": "pub fn dump_file(ast: &Arc<File>, interner: &Interner) {\n\n let mut dumper = AstDumper {\n\n interner,\n\n indent: 0,\n\n };\n\n\n\n dumper.dump_file(ast);\n\n}\n\n\n", "file_path": "dora-parser/src/ast/dump.rs", "rank": 90, "score": 301095.37773065164 }, { "content": "pub fn specialize_type(vm: &VM, ty: SourceType, type_params: &SourceTypeArray) -> SourceType {\n\n replace_type_param(vm, ty, type_params, None)\n\n}\n\n\n", "file_path": "dora/src/semck/specialize.rs", "rank": 91, "score": 300695.87037292187 }, { "content": "/// returns true if given value is a multiple of a page size.\n\npub fn is_page_aligned(val: usize) -> bool {\n\n let align = os::page_size_bits();\n\n\n\n // we can use shifts here since we know that\n\n // page size is power of 2\n\n val == ((val >> align) << align)\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 92, "score": 300168.61141134263 }, { "content": "pub fn impl_matches(\n\n vm: &VM,\n\n check_ty: SourceType,\n\n check_type_param_defs: &[TypeParam],\n\n check_type_param_defs2: Option<&TypeParamDefinition>,\n\n impl_id: ImplId,\n\n) -> Option<SourceTypeArray> {\n\n let ximpl = vm.impls[impl_id].read();\n\n extension_matches_ty(\n\n vm,\n\n check_ty,\n\n check_type_param_defs,\n\n check_type_param_defs2,\n\n ximpl.ty.clone(),\n\n &ximpl.type_params,\n\n )\n\n}\n\n\n", "file_path": "dora/src/vm/impls.rs", "rank": 93, "score": 299730.17453421245 }, { "content": "/// returns 'true' if th given `value` is already aligned\n\n/// to `align`.\n\npub fn is_aligned(value: usize, align: usize) -> bool {\n\n align_usize(value, align) == value\n\n}\n\n\n", "file_path": "dora/src/mem.rs", "rank": 94, "score": 298233.0138985403 }, { "content": "fn check_files(vm: &mut VM, start: usize) -> (usize, Vec<ParseFile>) {\n\n let files = vm.files.clone();\n\n let files = files.read();\n\n\n\n let mut files_to_parse = Vec::new();\n\n\n\n for file in &files[start..] {\n\n let mut gdef = GlobalDef {\n\n vm,\n\n file_id: file.id,\n\n namespace_id: file.namespace_id,\n\n files_to_parse: &mut files_to_parse,\n\n };\n\n\n\n gdef.visit_file(&file.ast);\n\n }\n\n\n\n (files.len(), files_to_parse)\n\n}\n\n\n", "file_path": "dora/src/semck/globaldef.rs", "rank": 95, "score": 298093.5567253255 }, { "content": "pub fn ensure_tuple(vm: &VM, args: Vec<SourceType>) -> TupleId {\n\n let args = Arc::new(args);\n\n\n\n if let Some(&tuple_id) = vm.tuples.lock().map.get(&args) {\n\n return tuple_id;\n\n }\n\n\n\n let concrete = determine_tuple_size(vm, &*args);\n\n\n\n let mut tuples = vm.tuples.lock();\n\n\n\n if let Some(&tuple_id) = tuples.map.get(&args) {\n\n return tuple_id;\n\n }\n\n\n\n tuples.all.push(Tuple {\n\n args: args.clone(),\n\n concrete,\n\n });\n\n\n\n let id = TupleId((tuples.all.len() - 1).try_into().unwrap());\n\n tuples.map.insert(args, id);\n\n\n\n id\n\n}\n\n\n", "file_path": "dora/src/vm/tuples.rs", "rank": 96, "score": 294447.1367514291 }, { "content": "pub fn alloc(vm: &VM, clsid: ClassDefId) -> Ref<Obj> {\n\n let cls_def = vm.class_defs.idx(clsid);\n\n\n\n let size = match cls_def.size {\n\n InstanceSize::Fixed(size) => size as usize,\n\n _ => panic!(\"alloc only supports fix-sized types\"),\n\n };\n\n\n\n let size = mem::align_usize(size, mem::ptr_width() as usize);\n\n\n\n let ptr = vm.gc.alloc(vm, size, false).to_usize();\n\n let vtable = cls_def.vtable.read();\n\n let vtable: &VTable = vtable.as_ref().unwrap();\n\n let mut handle: Ref<Obj> = ptr.into();\n\n handle.header_mut().set_vtblptr(Address::from_ptr(vtable));\n\n handle.header_mut().clear_fwdptr();\n\n\n\n handle\n\n}\n\n\n", "file_path": "dora/src/object.rs", "rank": 97, "score": 294344.42346061976 }, { "content": "pub fn set_vm(vm: &VM) {\n\n let ptr = vm as *const _ as *const u8;\n\n\n\n unsafe {\n\n VM_GLOBAL = ptr;\n\n }\n\n}\n\n\n", "file_path": "dora/src/vm.rs", "rank": 98, "score": 292731.17230591964 } ]
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 }, { "content": "// Convert from 4-bit samples to 32-bit floating point.\n\npub fn u4_to_f32(amplitude: u8) -> f32 {\n\n const MAX_AMP: f32 = 15.0;\n\n\n\n (amplitude as f32) / MAX_AMP\n\n}\n\n\n", "file_path": "src/audio/channels/mod.rs", "rank": 1, "score": 189128.31516370102 }, { "content": "pub fn get_freq_modulo(hi_reg: u8, lo_reg: u8) -> u32 {\n\n const HI_FREQ_MASK: u8 = bits![2, 1, 0];\n\n let hi = hi_reg & HI_FREQ_MASK;\n\n make_16!(hi, lo_reg) as u32\n\n}\n\n\n", "file_path": "src/audio/channels/mod.rs", "rank": 2, "score": 168899.48754384767 }, { "content": "// CGB/SGB palette lookup table.\n\npub fn lookup_sgb_palette(hash_in: u8, char_4_in: u8) -> SGBPalette {\n\n for (hash, char_4, palette) in SGB_PALETTE_TABLE {\n\n if (*hash == hash_in) && ((*char_4 == 0) || (*char_4 == char_4_in)) {\n\n return *palette;\n\n }\n\n }\n\n\n\n BW_PALETTE\n\n}\n\n\n\nconst SGB_PALETTE_TABLE: &[(u8, u8, SGBPalette)] = &[\n\n (0x14, 0x00, PKMN_RED),\n\n (0x15, 0x00, PKMN_YELLOW),\n\n (0x18, 0x4B, DK_LAND_2), // DK Land JP\n\n (0x46, 0x45, MARIO_LAND),\n\n (0x46, 0x52, METROID_2),\n\n (0x59, 0x00, WARIO_LAND),\n\n (0x61, 0x45, PKMN_BLUE),\n\n (0x6A, 0x4B, DK_LAND_2), // DK Land 2\n\n (0x6B, 0x00, DK_LAND_2), // DK Land 3\n", "file_path": "src/video/sgbpalettes.rs", "rank": 3, "score": 117886.82340802022 }, { "content": "pub trait Channel {\n\n // Clock the channel and recalculate the output if necessary.\n\n // Call this with individual CPU cycles.\n\n fn sample_clock(&mut self, cycles: u32);\n\n\n\n // Call at 256Hz, to decrement the length counter.\n\n fn length_clock(&mut self);\n\n\n\n // Call at 64Hz, for volume envelope.\n\n fn envelope_clock(&mut self);\n\n\n\n // Get the current output sample.\n\n fn get_sample(&self) -> f32;\n\n\n\n // Reset all internat timers and buffers.\n\n fn reset(&mut self);\n\n}\n\n\n\n#[derive(Clone, Copy)]\n\npub enum SquareDuty {\n", "file_path": "src/audio/channels/mod.rs", "rank": 4, "score": 102245.96753573549 }, { "content": "// Read in a duration and update time registers.\n\nfn update_times(time_diff: &Duration, microseconds: &mut usize, seconds: &mut u8, minutes: &mut u8, hours: &mut u8, days: &mut u16) {\n\n let new_microseconds = (*microseconds as i64) + time_diff.num_microseconds().unwrap_or(0);\n\n let new_seconds = (*seconds as i64) + (new_microseconds / 1_000_000);\n\n let new_minutes = (*minutes as i64) + (new_seconds / 60);\n\n let new_hours = (*hours as i64) + (new_minutes / 60);\n\n let new_days = ((*days & 0x1FF) as i64) + (new_hours / 24);\n\n\n\n *microseconds = (new_microseconds % 1_000_000) as usize;\n\n *seconds = (new_seconds % 60) as u8;\n\n *minutes = (new_minutes % 60) as u8;\n\n *hours = (new_hours % 24) as u8;\n\n *days = (new_days % 512) as u16;\n\n if new_days > 511 {\n\n *days |= 0x8000;\n\n }\n\n}", "file_path": "src/mem/cartridge/ram.rs", "rank": 5, "score": 93621.94800118126 }, { "content": "#[inline]\n\nfn write_pixel(output: &mut [u8], colour: Colour) {\n\n output[0] = colour.r;\n\n output[1] = colour.g;\n\n output[2] = colour.b;\n\n}", "file_path": "src/video/vram/drawing.rs", "rank": 6, "score": 73380.76770690353 }, { "content": "// TODO: replace this with an async stream?\n\nstruct Source {\n\n receiver: Receiver<super::SamplePacket>,\n\n\n\n current: super::SamplePacket,\n\n n: usize,\n\n}\n\n\n\nimpl Source {\n\n fn new(receiver: Receiver<super::SamplePacket>) -> Self {\n\n Source {\n\n receiver: receiver,\n\n\n\n current: Box::new([]),\n\n n: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Signal for Source {\n\n type Frame = Stereo<f32>;\n", "file_path": "src/audio/resampler.rs", "rank": 7, "score": 52010.56220371535 }, { "content": "// A palette with hard-coded colours.\n\nstruct StaticPalette {\n\n colours: PaletteColours,\n\n palette: PaletteColours,\n\n raw: u8\n\n}\n\n\n\nimpl StaticPalette {\n\n pub fn new(colours: PaletteColours) -> Self {\n\n StaticPalette {\n\n colours: colours,\n\n palette: [\n\n colours[0],\n\n colours[0],\n\n colours[0],\n\n colours[0]\n\n ],\n\n raw: 0\n\n }\n\n }\n\n\n", "file_path": "src/video/vram/palette/static.rs", "rank": 8, "score": 48303.43485613147 }, { "content": "#[derive(Clone)]\n\nstruct DynamicPalette {\n\n colours: PaletteColours,\n\n raw: [u8; 8],\n\n}\n\n\n\nimpl DynamicPalette {\n\n fn new() -> Self {\n\n DynamicPalette {\n\n colours: [Colour::zero(); 4],\n\n raw: [0; 8],\n\n }\n\n }\n\n}\n\n\n\nimpl MemDevice for DynamicPalette {\n\n fn read(&self, loc: u16) -> u8 {\n\n self.raw[(loc % 8) as usize]\n\n }\n\n\n\n fn write(&mut self, loc: u16, val: u8) {\n", "file_path": "src/video/vram/palette/dynamic.rs", "rank": 9, "score": 48303.43485613147 }, { "content": "pub trait ROM {\n\n fn read(&self, loc: u16) -> u8;\n\n fn set_bank(&mut self, bank: u16);\n\n}\n\n\n\n// A local file.\n\npub struct ROMFile {\n\n bank_0: [u8; 0x4000],\n\n bank_cache: HashMap<usize, Vec<u8>>,\n\n bank_offset: usize,\n\n\n\n file: BufReader<File>,\n\n}\n\n\n\nimpl ROMFile {\n\n pub fn new(file_name: &str) -> Result<Box<Self>, String> {\n\n let f = File::open(file_name).map_err(|e| e.to_string())?;\n\n\n\n let mut reader = BufReader::new(f);\n\n let mut buf = [0_u8; 0x4000];\n", "file_path": "src/mem/cartridge/rom.rs", "rank": 10, "score": 46237.84834095409 }, { "content": "pub trait MemDevice {\n\n fn read(&self, loc: u16) -> u8;\n\n fn write(&mut self, loc: u16, val: u8);\n\n}\n\n\n\npub struct WriteableMem {\n\n mem: Vec<u8>,\n\n}\n\n\n\nimpl WriteableMem {\n\n pub fn new(size: usize) -> WriteableMem {\n\n WriteableMem {mem: vec![0; size]}\n\n }\n\n}\n\n\n\nimpl MemDevice for WriteableMem {\n\n fn read(&self, loc: u16) -> u8 {\n\n self.mem[loc as usize]\n\n }\n\n\n\n fn write(&mut self, loc: u16, val: u8) {\n\n self.mem[loc as usize] = val;\n\n }\n\n}", "file_path": "src/mem/mod.rs", "rank": 11, "score": 46237.84834095409 }, { "content": "pub trait RAM: MemDevice {\n\n fn set_bank(&mut self, bank: u8, loc: u16);\n\n fn flush(&mut self) {}\n\n}\n\n\n\n// Banked RAM\n\npub struct BankedRAM {\n\n ram: Vec<u8>,\n\n offset: usize\n\n}\n\n\n\nimpl BankedRAM {\n\n pub fn new(ram_size: usize) -> Self {\n\n BankedRAM {\n\n ram: vec![0; ram_size],\n\n offset: 0\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/mem/cartridge/ram.rs", "rank": 12, "score": 42483.86571614352 }, { "content": "#[inline]\n\nfn get_tile_and_row(loc: usize) -> (usize, usize) {\n\n let row = (loc >> 1) & 0x7;\n\n let tile = loc >> 4;\n\n (tile, row)\n\n}", "file_path": "src/video/vram/patternmem.rs", "rank": 13, "score": 37548.69739762126 }, { "content": "pub const TILE_DATA_WIDTH: usize = 16; // Width of the tile data in tiles.\n\npub const TILE_DATA_HEIGHT_GB: usize = 24; // Height of the tile data in tiles for GB.\n\npub const TILE_DATA_HEIGHT_CGB: usize = 48; // Height of the tile data in tiles for GB Color.", "file_path": "src/video/vram/consts.rs", "rank": 14, "score": 32391.897524513868 }, { "content": " length_modulo: u8,\n\n\n\n freq_counter: u32,\n\n freq_modulo: u32,\n\n}\n\n\n\nimpl Square2 {\n\n pub fn new() -> Self {\n\n Self {\n\n duty_length_reg: 0,\n\n vol_envelope_reg: 0,\n\n freq_lo_reg: 0,\n\n freq_hi_reg: 0,\n\n\n\n enabled: false,\n\n duty_counter: DutyCycleCounter::new(0),\n\n\n\n volume: 0,\n\n volume_counter: None,\n\n volume_modulo: 0,\n", "file_path": "src/audio/channels/square2.rs", "rank": 15, "score": 31509.190118580096 }, { "content": " pub fn is_enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n pub fn write_wave(&mut self, loc: u16, val: u8) {\n\n self.wave_pattern[loc as usize] = val;\n\n }\n\n\n\n pub fn read_wave(&self, loc: u16) -> u8 {\n\n self.wave_pattern[loc as usize]\n\n }\n\n}\n\n\n\nimpl Channel for Wave {\n\n fn sample_clock(&mut self, cycles: u32) {\n\n self.freq_counter += cycles;\n\n if self.freq_counter >= self.freq_modulo {\n\n self.freq_counter -= self.freq_modulo;\n\n self.pattern_index = (self.pattern_index + 1) % 32;\n\n }\n", "file_path": "src/audio/channels/wave.rs", "rank": 16, "score": 31508.21631065824 }, { "content": "\n\n pub fn set_freq_hi_reg(&mut self, val: u8) {\n\n self.freq_hi_reg = val;\n\n // And trigger event...\n\n if test_bit!(val, 7) {\n\n self.trigger();\n\n }\n\n }\n\n\n\n pub fn is_enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n}\n\n\n\nimpl Channel for Square2 {\n\n fn sample_clock(&mut self, cycles: u32) {\n\n self.freq_counter += cycles;\n\n if self.freq_counter >= self.freq_modulo {\n\n self.freq_counter -= self.freq_modulo;\n\n self.duty_counter.step();\n", "file_path": "src/audio/channels/square2.rs", "rank": 19, "score": 31505.903711981417 }, { "content": " volume_counter: Option<u8>,\n\n volume_modulo: u8,\n\n\n\n length_counter: u8,\n\n length_modulo: u8,\n\n\n\n freq_counter: u32,\n\n freq_modulo: u32,\n\n}\n\n\n\nimpl Square1 {\n\n pub fn new() -> Self {\n\n Self {\n\n sweep_reg: 0,\n\n duty_length_reg: 0,\n\n vol_envelope_reg: 0,\n\n freq_lo_reg: 0,\n\n freq_hi_reg: 0,\n\n\n\n enabled: false,\n", "file_path": "src/audio/channels/square1.rs", "rank": 21, "score": 31504.201565741187 }, { "content": "use super::*;\n\n\n\nconst MAX_LEN: u8 = 64;\n\n\n\npub struct Square2 {\n\n // Public registers\n\n pub duty_length_reg: u8,\n\n pub vol_envelope_reg: u8,\n\n pub freq_lo_reg: u8,\n\n pub freq_hi_reg: u8,\n\n\n\n // Internal registers\n\n enabled: bool,\n\n duty_counter: DutyCycleCounter,\n\n\n\n volume: u8,\n\n volume_counter: Option<u8>,\n\n volume_modulo: u8,\n\n\n\n length_counter: u8,\n", "file_path": "src/audio/channels/square2.rs", "rank": 22, "score": 31503.972522741413 }, { "content": " },\n\n true if self.volume < MAX_VOL => {\n\n self.volume += 1;\n\n Some(0)\n\n },\n\n _ => None\n\n }\n\n } else {\n\n Some(new_count)\n\n };\n\n }\n\n }\n\n\n\n fn get_sample(&self) -> f32 {\n\n if self.enabled {\n\n match self.duty_counter.read() {\n\n SquareDuty::Lo => -u4_to_f32(self.volume),\n\n SquareDuty::Hi => u4_to_f32(self.volume),\n\n }\n\n } else {\n", "file_path": "src/audio/channels/square2.rs", "rank": 23, "score": 31502.445131269746 }, { "content": "use super::*;\n\n\n\nconst MAX_LEN: u8 = 64;\n\n\n\npub struct Square1 {\n\n // Public registers\n\n pub sweep_reg: u8,\n\n pub duty_length_reg: u8,\n\n pub vol_envelope_reg: u8,\n\n pub freq_lo_reg: u8,\n\n pub freq_hi_reg: u8,\n\n\n\n // Internal registers\n\n enabled: bool,\n\n duty_counter: DutyCycleCounter,\n\n\n\n freq_sweep_counter: Option<u8>,\n\n freq_sweep_modulo: u8,\n\n\n\n volume: u8,\n", "file_path": "src/audio/channels/square1.rs", "rank": 24, "score": 31501.814961007964 }, { "content": " duty_counter: DutyCycleCounter::new(0),\n\n\n\n freq_sweep_counter: None,\n\n freq_sweep_modulo: 0,\n\n\n\n volume: 0,\n\n volume_counter: None,\n\n volume_modulo: 0,\n\n\n\n length_counter: 0,\n\n length_modulo: MAX_LEN,\n\n\n\n freq_counter: 0,\n\n freq_modulo: 0,\n\n }\n\n }\n\n\n\n pub fn set_sweep_reg(&mut self, val: u8) {\n\n self.sweep_reg = val;\n\n }\n", "file_path": "src/audio/channels/square1.rs", "rank": 25, "score": 31501.744630917325 }, { "content": " if let Some(counter) = self.volume_counter {\n\n let new_count = counter + 1;\n\n self.volume_counter = if new_count >= self.volume_modulo {\n\n match test_bit!(self.vol_envelope_reg, 3) {\n\n false if self.volume > MIN_VOL => {\n\n self.volume -= 1;\n\n Some(0)\n\n },\n\n true if self.volume < MAX_VOL => {\n\n self.volume += 1;\n\n Some(0)\n\n },\n\n _ => None\n\n }\n\n } else {\n\n Some(new_count)\n\n };\n\n }\n\n }\n\n }\n", "file_path": "src/audio/channels/square1.rs", "rank": 27, "score": 31498.404737616685 }, { "content": " pattern_index: usize,\n\n\n\n shift_amount: ShiftAmount,\n\n\n\n length_counter: u16,\n\n length_modulo: u16,\n\n\n\n freq_counter: u32,\n\n freq_modulo: u32,\n\n\n\n}\n\n\n\nimpl Wave {\n\n pub fn new() -> Self {\n\n Self {\n\n playback_reg: 0,\n\n length_reg: 0,\n\n vol_reg: 0,\n\n freq_lo_reg: 0,\n\n freq_hi_reg: 0,\n", "file_path": "src/audio/channels/wave.rs", "rank": 28, "score": 31498.206761448535 }, { "content": "\n\n pub fn is_enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n pub fn sweep_clock(&mut self) {\n\n if self.enabled {\n\n if let Some(counter) = self.freq_sweep_counter {\n\n let new_count = counter + 1;\n\n self.freq_sweep_counter = if new_count >= self.freq_sweep_modulo {\n\n self.freq_sweep();\n\n Some(0)\n\n } else {\n\n Some(new_count)\n\n };\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/audio/channels/square1.rs", "rank": 30, "score": 31495.936950727046 }, { "content": "impl Channel for Square1 {\n\n fn sample_clock(&mut self, cycles: u32) {\n\n self.freq_counter += cycles;\n\n if self.freq_counter >= self.freq_modulo {\n\n self.freq_counter -= self.freq_modulo;\n\n self.duty_counter.step();\n\n }\n\n }\n\n\n\n fn length_clock(&mut self) {\n\n if self.enabled && test_bit!(self.freq_hi_reg, 6) {\n\n self.length_counter -= 1;\n\n if self.length_counter == self.length_modulo {\n\n self.enabled = false;\n\n }\n\n }\n\n }\n\n\n\n fn envelope_clock(&mut self) {\n\n if self.enabled {\n", "file_path": "src/audio/channels/square1.rs", "rank": 31, "score": 31495.736418330118 }, { "content": " }\n\n }\n\n\n\n fn length_clock(&mut self) {\n\n if self.enabled && test_bit!(self.freq_hi_reg, 6) {\n\n self.length_counter -= 1;\n\n if self.length_counter == self.length_modulo {\n\n self.enabled = false;\n\n }\n\n }\n\n }\n\n\n\n fn envelope_clock(&mut self) {\n\n if let Some(counter) = self.volume_counter {\n\n let new_count = counter + 1;\n\n self.volume_counter = if new_count >= self.volume_modulo {\n\n match test_bit!(self.vol_envelope_reg, 3) {\n\n false if self.volume > MIN_VOL => {\n\n self.volume -= 1;\n\n Some(0)\n", "file_path": "src/audio/channels/square2.rs", "rank": 33, "score": 31494.843671858634 }, { "content": "\n\n self.enabled = false;\n\n }\n\n}\n\n\n\nimpl Square1 {\n\n fn trigger(&mut self) {\n\n const FREQ_SWEEP_MASK: u8 = bits![6, 5, 4];\n\n const LEN_MASK: u8 = bits![5, 4, 3, 2, 1, 0];\n\n const VOL_MASK: u8 = bits![7, 6, 5, 4];\n\n const VOL_SWEEP_MASK: u8 = bits![2, 1, 0];\n\n\n\n self.freq_sweep_modulo = (self.sweep_reg & FREQ_SWEEP_MASK) >> 4;\n\n self.freq_sweep_counter = if self.freq_sweep_modulo == 0 {None} else {Some(0)};\n\n\n\n self.volume = (self.vol_envelope_reg & VOL_MASK) >> 4;\n\n self.volume_modulo = self.vol_envelope_reg & VOL_SWEEP_MASK;\n\n self.volume_counter = if self.volume_modulo == 0 {None} else {Some(0)};\n\n\n\n self.freq_counter = 0;\n", "file_path": "src/audio/channels/square1.rs", "rank": 34, "score": 31494.815036418062 }, { "content": " 1 => ShiftAmount::Full,\n\n 2 => ShiftAmount::Half,\n\n 3 => ShiftAmount::Quarter,\n\n _ => unreachable!()\n\n };\n\n\n\n self.freq_counter = 0;\n\n self.freq_modulo = (2048 - get_freq_modulo(self.freq_hi_reg, self.freq_lo_reg)) * 2;\n\n\n\n self.length_counter = MAX_LEN;\n\n self.length_modulo = self.length_reg as u16;\n\n\n\n self.enabled = true;\n\n }\n\n\n\n fn read_wave_pattern(&self) -> f32 {\n\n let u8_index = self.pattern_index / 2;\n\n let shift = 4 * ((self.pattern_index + 1) % 2);\n\n let raw_sample = (self.wave_pattern[u8_index] >> shift) & 0xF;\n\n\n\n match self.shift_amount {\n\n ShiftAmount::Mute => 0.0,\n\n ShiftAmount::Full => i4_to_f32(raw_sample),\n\n ShiftAmount::Half => i4_to_f32(raw_sample) * 0.5,\n\n ShiftAmount::Quarter => i4_to_f32(raw_sample) * 0.25,\n\n }\n\n }\n\n}\n", "file_path": "src/audio/channels/wave.rs", "rank": 35, "score": 31494.13446119449 }, { "content": "\n\n fn get_sample(&self) -> f32 {\n\n if self.enabled {\n\n match self.duty_counter.read() {\n\n SquareDuty::Lo => -u4_to_f32(self.volume),\n\n SquareDuty::Hi => u4_to_f32(self.volume),\n\n }\n\n } else {\n\n 0.0\n\n }\n\n }\n\n\n\n fn reset(&mut self) {\n\n self.duty_length_reg = 0;\n\n self.vol_envelope_reg = 0;\n\n self.freq_lo_reg = 0;\n\n self.freq_hi_reg = 0;\n\n\n\n self.freq_counter = 0;\n\n self.length_counter = MAX_LEN;\n", "file_path": "src/audio/channels/square1.rs", "rank": 36, "score": 31493.133324525734 }, { "content": "\n\n self.volume = (self.vol_envelope_reg & VOL_MASK) >> 4;\n\n self.volume_modulo = self.vol_envelope_reg & VOL_SWEEP_MASK;\n\n self.volume_counter = if self.volume_modulo == 0 {None} else {Some(0)};\n\n\n\n self.freq_counter = 0;\n\n self.freq_modulo = (2048 - get_freq_modulo(self.freq_hi_reg, self.freq_lo_reg)) * 4;\n\n\n\n self.length_counter = MAX_LEN;\n\n self.length_modulo = self.duty_length_reg & LEN_MASK;\n\n\n\n self.enabled = true;\n\n }\n\n}\n", "file_path": "src/audio/channels/square2.rs", "rank": 38, "score": 31491.905536443945 }, { "content": "\n\n wave_pattern: [0; 16],\n\n\n\n enabled: false,\n\n pattern_index: 0,\n\n\n\n shift_amount: ShiftAmount::Mute,\n\n\n\n length_counter: 0,\n\n length_modulo: MAX_LEN,\n\n\n\n freq_counter: 0,\n\n freq_modulo: 0,\n\n }\n\n }\n\n\n\n pub fn set_playback_reg(&mut self, val: u8) {\n\n self.playback_reg = val;\n\n }\n\n\n", "file_path": "src/audio/channels/wave.rs", "rank": 39, "score": 31491.830753311086 }, { "content": "\n\n length_counter: 0,\n\n length_modulo: MAX_LEN,\n\n\n\n freq_counter: 0,\n\n freq_modulo: 0,\n\n }\n\n }\n\n\n\n pub fn set_duty_length_reg(&mut self, val: u8) {\n\n self.duty_length_reg = val;\n\n }\n\n\n\n pub fn set_vol_envelope_reg(&mut self, val: u8) {\n\n self.vol_envelope_reg = val;\n\n }\n\n\n\n pub fn set_freq_lo_reg(&mut self, val: u8) {\n\n self.freq_lo_reg = val;\n\n }\n", "file_path": "src/audio/channels/square2.rs", "rank": 40, "score": 31491.573112011254 }, { "content": " }\n\n\n\n fn reset(&mut self) {\n\n self.pattern_index = 0;\n\n self.freq_lo_reg = 0;\n\n self.freq_hi_reg = 0;\n\n\n\n self.freq_counter = 0;\n\n self.length_counter = MAX_LEN;\n\n\n\n self.enabled = false;\n\n }\n\n}\n\n\n\nimpl Wave {\n\n fn trigger(&mut self) {\n\n const SHIFT_MASK: u8 = bits![6, 5];\n\n\n\n self.shift_amount = match (self.vol_reg & SHIFT_MASK) >> 5 {\n\n 0 => ShiftAmount::Mute,\n", "file_path": "src/audio/channels/wave.rs", "rank": 41, "score": 31490.384851996958 }, { "content": " Lo,\n\n Hi\n\n}\n\nconst DUTY_0: [SquareDuty; 8] = [SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Hi];\n\nconst DUTY_1: [SquareDuty; 8] = [SquareDuty::Hi, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Hi];\n\nconst DUTY_2: [SquareDuty; 8] = [SquareDuty::Hi, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Lo, SquareDuty::Hi, SquareDuty::Hi, SquareDuty::Hi];\n\nconst DUTY_3: [SquareDuty; 8] = [SquareDuty::Lo, SquareDuty::Hi, SquareDuty::Hi, SquareDuty::Hi, SquareDuty::Hi, SquareDuty::Hi, SquareDuty::Hi, SquareDuty::Lo];\n\n\n\npub struct DutyCycleCounter {\n\n pattern: &'static [SquareDuty; 8],\n\n index: usize\n\n}\n\n\n\nimpl DutyCycleCounter {\n\n pub fn new(duty: u8) -> Self {\n\n Self {\n\n pattern: match duty & 0x3 {\n\n 0 => &DUTY_0,\n\n 1 => &DUTY_1,\n\n 2 => &DUTY_2,\n", "file_path": "src/audio/channels/mod.rs", "rank": 42, "score": 31489.47182353877 }, { "content": " pub fn set_length_reg(&mut self, val: u8) {\n\n self.length_reg = val;\n\n }\n\n\n\n pub fn set_vol_reg(&mut self, val: u8) {\n\n self.vol_reg = val;\n\n }\n\n\n\n pub fn set_freq_lo_reg(&mut self, val: u8) {\n\n self.freq_lo_reg = val;\n\n }\n\n\n\n pub fn set_freq_hi_reg(&mut self, val: u8) {\n\n self.freq_hi_reg = val;\n\n // And trigger event...\n\n if test_bit!(val, 7) {\n\n self.trigger();\n\n }\n\n }\n\n\n", "file_path": "src/audio/channels/wave.rs", "rank": 43, "score": 31489.06749599172 }, { "content": "\n\n pub fn set_duty_length_reg(&mut self, val: u8) {\n\n self.duty_length_reg = val;\n\n }\n\n\n\n pub fn set_vol_envelope_reg(&mut self, val: u8) {\n\n self.vol_envelope_reg = val;\n\n }\n\n\n\n pub fn set_freq_lo_reg(&mut self, val: u8) {\n\n self.freq_lo_reg = val;\n\n }\n\n\n\n pub fn set_freq_hi_reg(&mut self, val: u8) {\n\n self.freq_hi_reg = val;\n\n // And trigger event...\n\n if test_bit!(val, 7) {\n\n self.trigger();\n\n }\n\n }\n", "file_path": "src/audio/channels/square1.rs", "rank": 44, "score": 31488.899178516618 }, { "content": "use super::*;\n\n\n\nconst MAX_LEN: u16 = 256;\n\n\n", "file_path": "src/audio/channels/wave.rs", "rank": 45, "score": 31488.73825403595 }, { "content": " self.freq_modulo = (2048 - get_freq_modulo(self.freq_hi_reg, self.freq_lo_reg)) * 4;\n\n\n\n self.length_counter = MAX_LEN;\n\n self.length_modulo = self.duty_length_reg & LEN_MASK;\n\n\n\n self.enabled = true;\n\n }\n\n\n\n fn freq_sweep(&mut self) {\n\n const SWEEP_SHIFT_MASK: u8 = bits![2, 1, 0];\n\n const MAX_FREQUENCY: u32 = 2047;\n\n\n\n let freq_modulo = 2048 - (self.freq_modulo / 4);\n\n let sweep_shift = self.sweep_reg & SWEEP_SHIFT_MASK;\n\n let freq_delta = freq_modulo >> sweep_shift;\n\n let new_modulo = if test_bit!(self.sweep_reg, 3) {\n\n freq_modulo - freq_delta\n\n } else {\n\n freq_modulo + freq_delta\n\n };\n", "file_path": "src/audio/channels/square1.rs", "rank": 46, "score": 31488.316954177328 }, { "content": "\n\n if new_modulo > MAX_FREQUENCY {\n\n self.enabled = false;\n\n }\n\n\n\n self.freq_modulo = (2048 - new_modulo) * 4;\n\n\n\n self.freq_counter = 0;\n\n }\n\n}\n", "file_path": "src/audio/channels/square1.rs", "rank": 47, "score": 31488.18205465542 }, { "content": " }\n\n\n\n fn length_clock(&mut self) {\n\n if self.enabled && test_bit!(self.freq_hi_reg, 6) {\n\n self.length_counter -= 1;\n\n if self.length_counter == self.length_modulo {\n\n self.enabled = false;\n\n }\n\n }\n\n }\n\n\n\n fn envelope_clock(&mut self) {\n\n }\n\n\n\n fn get_sample(&self) -> f32 {\n\n if self.enabled {\n\n self.read_wave_pattern()\n\n } else {\n\n 0.0\n\n }\n", "file_path": "src/audio/channels/wave.rs", "rank": 48, "score": 31487.81946989736 }, { "content": " 0.0\n\n }\n\n }\n\n\n\n fn reset(&mut self) {\n\n self.duty_length_reg = 0;\n\n self.vol_envelope_reg = 0;\n\n self.freq_lo_reg = 0;\n\n self.freq_hi_reg = 0;\n\n\n\n self.freq_counter = 0;\n\n self.length_counter = MAX_LEN;\n\n }\n\n}\n\n\n\nimpl Square2 {\n\n fn trigger(&mut self) {\n\n const LEN_MASK: u8 = bits![5, 4, 3, 2, 1, 0];\n\n const VOL_MASK: u8 = bits![7, 6, 5, 4];\n\n const VOL_SWEEP_MASK: u8 = bits![2, 1, 0];\n", "file_path": "src/audio/channels/square2.rs", "rank": 50, "score": 31486.58676880524 }, { "content": "// Audio channels.\n\npub mod square1;\n\npub mod square2;\n\npub mod wave;\n\npub mod noise;\n\n\n", "file_path": "src/audio/channels/mod.rs", "rank": 52, "score": 31484.932259263063 }, { "content": " 3 => &DUTY_3,\n\n _ => unreachable!()\n\n },\n\n index: 0\n\n }\n\n }\n\n\n\n pub fn step(&mut self) {\n\n self.index = (self.index + 1) % 8;\n\n }\n\n\n\n pub fn read(&self) -> SquareDuty {\n\n self.pattern[self.index]\n\n }\n\n}\n\n\n\npub const MAX_VOL: u8 = 15;\n\npub const MIN_VOL: u8 = 0;\n\n\n", "file_path": "src/audio/channels/mod.rs", "rank": 53, "score": 31484.867589254205 }, { "content": "# Super Rust Boy\n\n\n\nGame Boy and Game Boy Color emulator written in Rust.\n\n\n\nThis project features a library which can be used for external use, and a binary that can run the emulator locally (also for debugging purposes).\n\n\n\n### Debug Mode\n\nThe emulator library can be built in debug mode by enabling the `debug` feature at compile time: `cargo build --features debug`.\n\n\n\n### Making the Binary\n\nTo build a binary for use on Windows, macOS (with MoltenVK) and Linux, see [here](https://github.com/super-rust-boy/super-rust-boy-bin).\n\n\n\n### TODO video:\n\n* Separate video render calls to enable \"turbo\" mode.\n\n* Better cache invalidation detection.\n\n\n\n### TODO audio:\n\n* Noise wave high freq. higher precision.\n\n* Allow changing duty cycle mid-sound.\n\n\n\n### TODO other:\n\n* Optimisations in CPU (?)\n\n* Add ability to use preset ROM (internally - for testing)\n\n* MBC 6,7 bank swapping systems\n\n* Save states\n\n* Further cleanup\n\n* Link cables via network\n", "file_path": "README.md", "rank": 54, "score": 31013.351272492713 }, { "content": "MIT License\n\n\n\nCopyright (c) 2020 Simon Cooper\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n", "file_path": "LICENSE.md", "rank": 55, "score": 31006.41102851044 }, { "content": "enum ShiftAmount {\n\n Mute,\n\n Full,\n\n Half,\n\n Quarter\n\n}\n\n\n\npub struct Wave {\n\n // Public registers\n\n pub playback_reg: u8,\n\n pub length_reg: u8,\n\n pub vol_reg: u8,\n\n pub freq_lo_reg: u8,\n\n pub freq_hi_reg: u8,\n\n\n\n // Sample table\n\n pub wave_pattern: [u8; 16],\n\n\n\n // Internal registers\n\n enabled: bool,\n", "file_path": "src/audio/channels/wave.rs", "rank": 56, "score": 28976.511445717733 }, { "content": " frame_cycle_count: u32,\n\n frame_count: u8,\n\n}\n\n\n\nimpl AudioDevice {\n\n pub fn new() -> Self {\n\n AudioDevice {\n\n square_1: Square1::new(),\n\n square_2: Square2::new(),\n\n wave: Wave::new(),\n\n noise: Noise::new(),\n\n\n\n volume_control: VolumeControl::default(),\n\n channel_enables: ChannelEnables::default(),\n\n power_control: PowerControl::default(),\n\n\n\n sample_buffer: Vec::new(),\n\n sender: None,\n\n cycle_count: 0.0,\n\n cycles_per_sample: 0.0,\n", "file_path": "src/audio/mod.rs", "rank": 57, "score": 29.632497881883197 }, { "content": "pub struct Timer {\n\n divider: u16,\n\n timer_counter: u8,\n\n timer_modulo: u8,\n\n\n\n timer_enable: bool,\n\n clock_select: u8,\n\n\n\n trigger: bool,\n\n}\n\n\n\nimpl Timer {\n\n pub fn new() -> Self {\n\n Timer {\n\n divider: 0,\n\n timer_counter: 0,\n\n timer_modulo: 0,\n\n\n\n timer_enable: false,\n\n clock_select: 0,\n", "file_path": "src/timer.rs", "rank": 58, "score": 27.699737631327075 }, { "content": " match loc {\n\n 0xFF03 => self.divider = 0,\n\n 0xFF04 => self.divider = 0,\n\n 0xFF05 => self.timer_counter = val,\n\n 0xFF06 => self.timer_modulo = val,\n\n 0xFF07 => {\n\n self.timer_enable = test_bit!(val, 2);\n\n self.clock_select = val & 0b11;\n\n },\n\n _ => {},\n\n }\n\n }\n\n\n\n // Call this every cycle. Returns true if an interrupt is triggered (after 1 cycle delay).\n\n pub fn update(&mut self, cycles: u32) -> bool {\n\n let trigger = self.trigger;\n\n\n\n self.divider = (self.divider as u32 + cycles) as u16; // TODO: check this is ok for CGB.\n\n\n\n if self.timer_enable {\n", "file_path": "src/timer.rs", "rank": 59, "score": 26.749171537948744 }, { "content": "\n\n trigger: false,\n\n }\n\n }\n\n\n\n pub fn read(&self, loc: u16) -> u8 {\n\n match loc {\n\n 0xFF03 => (self.divider & 0xFF) as u8,\n\n 0xFF04 => (self.divider >> 8) as u8,\n\n 0xFF05 => self.timer_counter,\n\n 0xFF06 => self.timer_modulo,\n\n 0xFF07 => {\n\n let enable = if self.timer_enable {bit!(2)} else {0};\n\n enable | self.clock_select\n\n },\n\n _ => 0,\n\n }\n\n }\n\n\n\n pub fn write(&mut self, loc: u16, val: u8) {\n", "file_path": "src/timer.rs", "rank": 60, "score": 21.766792325127547 }, { "content": " self.ram.read(loc)\n\n } else {\n\n 0\n\n }\n\n }\n\n\n\n #[inline]\n\n fn write_ram(&mut self, loc: u16, val: u8) {\n\n if self.ram_enable {\n\n match self.mem_bank {\n\n MBC::_2 => self.ram.write(loc, val & 0xF),\n\n _ => self.ram.write(loc, val),\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl MemDevice for Cartridge {\n\n fn read(&self, loc: u16) -> u8 {\n\n match loc {\n", "file_path": "src/mem/cartridge/mod.rs", "rank": 61, "score": 21.44190040720596 }, { "content": " self.lcd_control.bits()\n\n }\n\n\n\n pub fn read_status(&self) -> u8 {\n\n self.lcd_status.read()\n\n }\n\n}\n\n\n\n// Writing\n\nimpl VideoRegs {\n\n\n\n // Returns true if cycle count should be reset\n\n pub fn write_lcd_control(&mut self, val: u8) -> bool {\n\n let was_display_enabled = self.is_display_enabled();\n\n self.lcd_control = LCDControl::from_bits_truncate(val);\n\n let is_display_enabled = self.is_display_enabled();\n\n\n\n // Has display been toggled on/off?\n\n if is_display_enabled && !was_display_enabled { // ON\n\n self.lcd_status.write_mode(Mode::_2);\n", "file_path": "src/video/regs.rs", "rank": 62, "score": 21.427896759956642 }, { "content": "\n\nuse std::sync::{\n\n Arc,\n\n Mutex\n\n};\n\n\n\npub use sgbpalettes::UserPalette;\n\n\n\n// Modes\n\n#[derive(PartialEq, Debug, Clone, Copy)]\n\npub enum Mode {\n\n _0 = 0, // H-blank\n\n _1 = 1, // V-blank\n\n _2 = 2, // Reading OAM\n\n _3 = 3 // Drawing\n\n}\n\n\n\nimpl From<u8> for Mode {\n\n fn from(val: u8) -> Self {\n\n match val & 0b11 {\n", "file_path": "src/video/mod.rs", "rank": 63, "score": 20.992709303017094 }, { "content": "\n\n dirty: bool,\n\n}\n\n\n\nimpl MapCache {\n\n pub fn new(cgb_mode: bool) -> Self {\n\n MapCache {\n\n texels: vec![vec![0; 256]; 256],\n\n attrs: if cgb_mode {vec![vec![TileAttributes::default(); 256]; 256]} else {Vec::new()},\n\n\n\n dirty: true,\n\n }\n\n }\n\n\n\n #[inline]\n\n pub fn get_texel(&self, x: usize, y: usize) -> u8 {\n\n self.texels[y][x]\n\n }\n\n\n\n #[inline]\n", "file_path": "src/video/vram/mapcache.rs", "rank": 64, "score": 19.820968719139028 }, { "content": "// Module that resamples from 32_000 to the output sample rate.\n\nuse crossbeam_channel::Receiver;\n\nuse dasp::{\n\n frame::{Frame, Stereo},\n\n interpolate::sinc::Sinc,\n\n ring_buffer::Fixed,\n\n signal::{\n\n interpolate::Converter,\n\n Signal,\n\n }\n\n};\n\n\n\npub struct Resampler {\n\n converter: Converter<Source, Sinc<[Stereo<f32>; 2]>>\n\n}\n\n\n\nimpl Resampler {\n\n pub fn new(receiver: Receiver<super::SamplePacket>, target_sample_rate: f64) -> Self {\n\n let sinc = Sinc::new(Fixed::from([Stereo::EQUILIBRIUM; 2]));\n\n Resampler {\n", "file_path": "src/audio/resampler.rs", "rank": 65, "score": 19.710297878990815 }, { "content": "pub struct CPUState {\n\n pub a: u8,\n\n pub b: u8,\n\n pub c: u8,\n\n pub d: u8,\n\n pub e: u8,\n\n\n\n pub h: u8,\n\n pub l: u8,\n\n\n\n pub flags: u8,\n\n\n\n pub pc: u16,\n\n pub sp: u16\n\n}\n\n\n\nimpl CPUState {\n\n pub fn to_string(&self) -> String {\n\n format!(\"a:{:02X} b:{:02X} c:{:02X} d:{:02X} e:{:02X} h:{:02X} l:{:02X}\\n\\\n\n znhc: {:08b}\\n\\\n\n pc: {:04X} sp: {:04X}\",\n\n self.a, self.b, self.c, self.d, self.e, self.h, self.l,\n\n self.flags,\n\n self.pc, self.sp)\n\n }\n\n}\n", "file_path": "src/debug.rs", "rank": 66, "score": 18.95311927270638 }, { "content": " buttons: Buttons::default(),\n\n directions: Directions::default(),\n\n\n\n selector: Select::None,\n\n change: false\n\n }\n\n }\n\n\n\n pub fn read(&self) -> u8 {\n\n match self.selector {\n\n Select::Direction => (!self.directions.bits() & 0xF),\n\n Select::Button => (!self.buttons.bits() & 0xF),\n\n Select::None => 0\n\n }\n\n }\n\n\n\n pub fn write(&mut self, val: u8) {\n\n self.selector = if !test_bit!(val, SELECT_BUTTONS) {\n\n Select::Button\n\n } else if !test_bit!(val, SELECT_DIRECTION) {\n", "file_path": "src/joypad.rs", "rank": 67, "score": 18.346532798684734 }, { "content": "\n\n let new_rom_bank = mb.get_rom_bank();\n\n let new_ram_bank = mb.get_ram_bank();\n\n\n\n if new_rom_bank != old_rom_bank {\n\n self.swap_rom_bank(new_rom_bank as u16);\n\n }\n\n if new_ram_bank != old_ram_bank {\n\n self.swap_ram_bank(new_ram_bank);\n\n }\n\n },\n\n MBC::_2 => match loc {\n\n 0x0000..=0x1FFF => self.ram_enable = (loc & 0x100) == 0,\n\n 0x2000..=0x3FFF if (loc & 0x100) != 0 => self.swap_rom_bank((val & 0xF) as u16),\n\n _ => {},\n\n },\n\n MBC::_3 => match (loc, val) {\n\n (0x0000..=0x1FFF, _) => self.ram_enable = (val & 0xF) == 0xA,\n\n (0x2000..=0x3FFF, 0) => self.swap_rom_bank(1),\n\n (0x2000..=0x3FFF, _) => self.swap_rom_bank((val & 0x7F) as u16),\n", "file_path": "src/mem/cartridge/mod.rs", "rank": 68, "score": 18.301232607795495 }, { "content": " self.days &= 0xFF00;\n\n self.days |= val as u16;\n\n },\n\n DH => {\n\n if (val & 0x40) != 0 {\n\n println!(\"Stop the clocks!\");\n\n }\n\n self.days &= 0xFF;\n\n self.days |= ((val & 1) as u16) << 8;\n\n },\n\n }\n\n\n\n self.dirty = true;\n\n }\n\n}\n\n\n\nimpl RAM for ClockRAM {\n\n fn set_bank(&mut self, bank: u8, loc: u16) {\n\n use RamMap::*;\n\n\n", "file_path": "src/mem/cartridge/ram.rs", "rank": 69, "score": 18.29596180333014 }, { "content": "#[derive(Clone, Copy)]\n\npub struct Sprite {\n\n pub y: u8,\n\n pub x: u8,\n\n pub tile_num: u8,\n\n pub flags: SpriteFlags\n\n}\n\n\n\nimpl Sprite {\n\n pub fn new() -> Self {\n\n Sprite {\n\n y: 0,\n\n x: 0,\n\n tile_num: 0,\n\n flags: SpriteFlags::default()\n\n }\n\n }\n\n\n\n pub fn is_above_bg(&self) -> bool {\n\n !self.flags.contains(SpriteFlags::PRIORITY)\n", "file_path": "src/video/vram/sprite.rs", "rank": 70, "score": 17.905684800757157 }, { "content": " self.exec_instruction();\n\n }\n\n\n\n return true;\n\n }\n\n\n\n pub fn frame_update(&mut self, frame: Arc<Mutex<[u8]>>) {\n\n self.mem.frame(frame);\n\n self.mem.flush_cart();\n\n }\n\n\n\n pub fn enable_audio(&mut self, sender: Sender<SamplePacket>) {\n\n self.mem.enable_audio(sender);\n\n }\n\n\n\n pub fn set_button(&mut self, button: Buttons, val: bool) {\n\n self.mem.set_button(button, val);\n\n }\n\n\n\n pub fn set_direction(&mut self, direction: Directions, val: bool) {\n", "file_path": "src/cpu.rs", "rank": 71, "score": 17.697760572035403 }, { "content": " pub fn set_lower(&mut self, val: u8) {\n\n match val & 0x1F {\n\n 0 => self.lower_select = 1,\n\n x => self.lower_select = x,\n\n }\n\n }\n\n\n\n pub fn set_upper(&mut self, val: u8) {\n\n self.upper_select = val & 0x03;\n\n }\n\n\n\n pub fn mem_type_select(&mut self, val: u8) {\n\n match val & 1 {\n\n 1 => self.banking_mode = BankingMode::RAM,\n\n _ => self.banking_mode = BankingMode::ROM,\n\n }\n\n }\n\n\n\n pub fn get_rom_bank(&self) -> u8 {\n\n match self.banking_mode {\n", "file_path": "src/mem/cartridge/mbc1.rs", "rank": 72, "score": 17.399879739215212 }, { "content": " data: Vec<u8>,\n\n bank_offset: usize,\n\n}\n\n\n\nimpl ROMData {\n\n pub fn new(data: &[u8]) -> Box<Self> {\n\n Box::new(ROMData {\n\n data: Vec::from(data),\n\n bank_offset: 0,\n\n })\n\n }\n\n}\n\n\n\nimpl ROM for ROMData {\n\n fn read(&self, loc: u16) -> u8 {\n\n match loc {\n\n 0x0..=0x3FFF => self.data[loc as usize],\n\n 0x4000..=0x7FFF => self.data[self.bank_offset + (loc - 0x4000) as usize],\n\n _ => unreachable!()\n\n }\n\n }\n\n\n\n fn set_bank(&mut self, bank: u16) {\n\n self.bank_offset = (bank as usize) * 0x4000;\n\n }\n\n}\n\n\n\n// TODO: remote loading.", "file_path": "src/mem/cartridge/rom.rs", "rank": 73, "score": 17.337575529509934 }, { "content": "\n\nimpl VideoRegs {\n\n pub fn new() -> Self {\n\n VideoRegs {\n\n lcd_control: LCDControl::ENABLE,\n\n lcd_status: LCDStatus::new(),\n\n lcdc_y: 0,\n\n ly_compare: 0,\n\n\n\n scroll_y: 0,\n\n scroll_x: 0,\n\n window_y: 0,\n\n window_x: 0,\n\n }\n\n }\n\n\n\n pub fn compare_ly_equal(&self) -> bool {\n\n self.lcdc_y == self.ly_compare\n\n }\n\n\n", "file_path": "src/video/regs.rs", "rank": 74, "score": 17.237050709534554 }, { "content": " }\n\n}\n\n\n\n// Expects a loc range from 0 -> 0x9F\n\nimpl MemDevice for ObjectMem {\n\n fn read(&self, loc: u16) -> u8 {\n\n let index = (loc / 4) as usize;\n\n\n\n match loc % 4 {\n\n 0 => self.objects[index].y,\n\n 1 => self.objects[index].x,\n\n 2 => self.objects[index].tile_num,\n\n _ => self.objects[index].flags.bits()\n\n }\n\n }\n\n\n\n fn write(&mut self, loc: u16, val: u8) {\n\n let index = (loc / 4) as usize;\n\n\n\n match loc % 4 {\n\n 0 => self.objects[index].y = val,\n\n 1 => self.objects[index].x = val,\n\n 2 => self.objects[index].tile_num = val,\n\n _ => self.objects[index].flags = SpriteFlags::from_bits_truncate(val)\n\n }\n\n }\n\n}", "file_path": "src/video/vram/sprite.rs", "rank": 75, "score": 17.214868285798484 }, { "content": "pub struct StaticPaletteMem {\n\n palettes: Vec<StaticPalette>\n\n}\n\n\n\nimpl StaticPaletteMem {\n\n pub fn new(colours: SGBPalette) -> Self {\n\n StaticPaletteMem {\n\n palettes: vec![\n\n StaticPalette::new(colours.bg),\n\n StaticPalette::new(colours.obj0),\n\n StaticPalette::new(colours.obj1)\n\n ]\n\n }\n\n }\n\n\n\n pub fn read(&self, which: usize) -> u8 {\n\n self.palettes[which].read()\n\n }\n\n\n\n pub fn write(&mut self, which: usize, val: u8) {\n\n self.palettes[which].write(val);\n\n }\n\n\n\n pub fn get_colour(&self, which: usize, texel: u8) -> Colour {\n\n self.palettes[which].palette[texel as usize]\n\n }\n\n}", "file_path": "src/video/vram/palette/static.rs", "rank": 76, "score": 17.197183063320562 }, { "content": " fn reset(&mut self) {\n\n self.square_1.reset();\n\n self.square_2.reset();\n\n self.wave.reset();\n\n self.noise.reset();\n\n\n\n self.volume_control = VolumeControl::default();\n\n self.channel_enables = ChannelEnables::default();\n\n }\n\n\n\n fn clock_channels(&mut self, cycles: u32) {\n\n const FRAME_MODULO: u32 = 8192; // Clock rate / 8192 = 512\n\n // Advance samples\n\n self.square_1.sample_clock(cycles);\n\n self.square_2.sample_clock(cycles);\n\n self.wave.sample_clock(cycles);\n\n self.noise.sample_clock(cycles);\n\n\n\n self.frame_cycle_count += cycles;\n\n // Clock length and sweeping at 512Hz\n", "file_path": "src/audio/mod.rs", "rank": 77, "score": 17.120159989366524 }, { "content": "#[derive(Clone, Copy, Debug)]\n\npub struct Colour {\n\n pub r: u8,\n\n pub g: u8,\n\n pub b: u8\n\n}\n\n\n\nimpl Colour {\n\n pub const fn new(r: u8, g: u8, b: u8) -> Self {\n\n Colour {\n\n r: r,\n\n g: g,\n\n b: b\n\n }\n\n }\n\n\n\n pub fn zero() -> Colour {\n\n Colour {\n\n r: 255,\n\n g: 255,\n\n b: 255\n\n }\n\n }\n\n}\n\n\n\npub type PaletteColours = [Colour; 4];", "file_path": "src/video/types.rs", "rank": 78, "score": 16.936712367003096 }, { "content": " square_1: Square1,\n\n square_2: Square2,\n\n wave: Wave,\n\n noise: Noise,\n\n\n\n // Control\n\n volume_control: VolumeControl,\n\n channel_enables: ChannelEnables,\n\n power_control: PowerControl,\n\n\n\n // Managing output of samples\n\n sample_buffer: Vec<Stereo<f32>>,\n\n sender: Option<Sender<SamplePacket>>,\n\n cycle_count: f64,\n\n cycles_per_sample: f64,\n\n\n\n vol_left: f32,\n\n vol_right: f32,\n\n\n\n // Managing clocking channels\n", "file_path": "src/audio/mod.rs", "rank": 79, "score": 16.84797755087685 }, { "content": "\n\nimpl Tile {\n\n pub fn new() -> Self {\n\n Tile {\n\n texels: vec![vec![0; TILE_WIDTH]; TILE_HEIGHT]\n\n }\n\n }\n\n\n\n #[inline]\n\n pub fn get_texel(&self, x: usize, y: usize) -> u8 {\n\n self.texels[y][x]\n\n }\n\n}\n\n\n\npub struct TileMem {\n\n tiles: Vec<Tile>\n\n}\n\n\n\nimpl TileMem {\n\n pub fn new(num_tiles: usize) -> Self {\n", "file_path": "src/video/vram/patternmem.rs", "rank": 80, "score": 16.598151292572247 }, { "content": " dirty: false\n\n })\n\n }\n\n}\n\n\n\nimpl MemDevice for BatteryRAM {\n\n fn read(&self, loc: u16) -> u8 {\n\n self.ram[self.offset + (loc as usize)]\n\n }\n\n\n\n fn write(&mut self, loc: u16, val: u8) {\n\n let pos = self.offset + (loc as usize);\n\n\n\n self.ram[pos] = val;\n\n\n\n self.dirty = true;\n\n }\n\n}\n\n\n\nimpl RAM for BatteryRAM {\n", "file_path": "src/mem/cartridge/ram.rs", "rank": 81, "score": 16.190917524679506 }, { "content": " return true;\n\n } else if !is_display_enabled && was_display_enabled { // OFF\n\n self.lcd_status.write_mode(Mode::_0);\n\n self.lcdc_y = 0;\n\n }\n\n\n\n false\n\n }\n\n\n\n pub fn write_status(&mut self, val: u8) {\n\n self.lcd_status.write(val);\n\n }\n\n}", "file_path": "src/video/regs.rs", "rank": 82, "score": 16.147709691726497 }, { "content": " }\n\n}\n\n\n\npub struct ObjectMem {\n\n objects: Vec<Sprite>,\n\n}\n\n\n\nimpl ObjectMem {\n\n pub fn new() -> Self {\n\n ObjectMem {\n\n objects: vec![Sprite::new(); 40],\n\n }\n\n }\n\n\n\n pub fn get_objects_for_line(&self, y: u8, large: bool) -> Vec<Sprite> {\n\n let y_upper = y + 16;\n\n let y_lower = y_upper - if large {SPRITE_LARGE_HEIGHT} else {SPRITE_SMALL_HEIGHT};\n\n self.objects.iter().filter(|o| {\n\n (o.y > y_lower) && (o.y <= y_upper)\n\n }).cloned().collect::<Vec<_>>()\n", "file_path": "src/video/vram/sprite.rs", "rank": 83, "score": 16.09574538041584 }, { "content": " dma_addr: u16,\n\n dma_active: bool,\n\n\n\n // CGB\n\n cgb_ram_offset: u16,\n\n cgb_dma_src: u16,\n\n cgb_dma_dst: u16,\n\n cgb_dma_len: u16,\n\n cgb_dma_hblank_len: Option<u16>,\n\n\n\n cgb_mode: bool\n\n}\n\n\n\nimpl MemBus {\n\n pub fn new(rom: ROMType, save_file: &str, user_palette: UserPalette) -> MemBus {\n\n let cart = match Cartridge::new(rom, save_file) {\n\n Ok(r) => r,\n\n Err(s) => panic!(\"Could not construct ROM: {}\", s),\n\n };\n\n\n", "file_path": "src/mem/bus.rs", "rank": 84, "score": 15.754420358188888 }, { "content": "\n\n if self.joypad.check_interrupt() {\n\n self.interrupt_flag.insert(InterruptFlags::JOYPAD);\n\n }\n\n }\n\n\n\n pub fn enable_audio(&mut self, sender: Sender<SamplePacket>) {\n\n self.audio_device.enable_audio(sender);\n\n }\n\n\n\n // Clock memory: update timer and DMA transfers.\n\n // Return true if CGB DMA is active.\n\n pub fn clock(&mut self, cycles: u32) -> bool {\n\n self.audio_device.clock(cycles);\n\n\n\n if self.timer.update(cycles) {\n\n self.interrupt_flag.insert(InterruptFlags::TIMER);\n\n }\n\n if self.dma_active {\n\n self.dma_tick();\n", "file_path": "src/mem/bus.rs", "rank": 85, "score": 15.563933029701413 }, { "content": " cycle_count: 0,\n\n }\n\n }\n\n\n\n // Drawing for a single frame.\n\n pub fn start_frame(&mut self, render_target: RenderTarget) {\n\n self.renderer.start_frame(render_target);\n\n }\n\n\n\n // Query to see if the video device is in H-Blank.\n\n pub fn is_in_hblank(&self) -> bool {\n\n self.regs.read_mode() == Mode::_0\n\n }\n\n\n\n // Set the current video mode based on the cycle count.\n\n // May trigger an interrupt.\n\n // Returns true if transitioned to V-Blank.\n\n pub fn video_mode(&mut self, cycles: u32) -> (bool, InterruptFlags) {\n\n use self::constants::*;\n\n //let mut mem = self.mem.lock().unwrap();\n", "file_path": "src/video/mod.rs", "rank": 86, "score": 15.461591842826245 }, { "content": " DH => (days >> 8) as u8,\n\n _ => unreachable!()\n\n }\n\n },\n\n }\n\n }\n\n\n\n fn write(&mut self, loc: u16, val: u8) {\n\n use RamMap::*;\n\n\n\n match self.ram_map {\n\n RAM => {\n\n let pos = self.offset + (loc as usize);\n\n\n\n self.ram[pos] = val;\n\n },\n\n S => self.seconds = val,\n\n M => self.minutes = val,\n\n H => self.hours = val,\n\n DL => {\n", "file_path": "src/mem/cartridge/ram.rs", "rank": 87, "score": 15.325535909228048 }, { "content": " e: u8,\n\n h: u8,\n\n l: u8,\n\n\n\n // Flags\n\n flags: CPUFlags,\n\n\n\n // Interrupts\n\n ime: bool,\n\n cont: bool,\n\n\n\n // Stack Pointer & PC\n\n sp: u16,\n\n pc: u16,\n\n\n\n // Memory Bus (ROM,RAM,Peripherals etc)\n\n mem: MemBus,\n\n\n\n // Internals\n\n step_cycles: u32,\n\n v_blank_latch: bool,\n\n double_speed_latch: bool,\n\n cgb_dma_active: bool\n\n}\n\n\n\n\n\n// Conditions for Jump\n\n#[derive(PartialEq)]\n", "file_path": "src/cpu.rs", "rank": 88, "score": 15.247875695212526 }, { "content": "impl MemDevice for BankedRAM {\n\n fn read(&self, loc: u16) -> u8 {\n\n self.ram[self.offset + (loc as usize)]\n\n }\n\n\n\n fn write(&mut self, loc: u16, val: u8) {\n\n self.ram[self.offset + (loc as usize)] = val;\n\n }\n\n}\n\n\n\nimpl RAM for BankedRAM {\n\n fn set_bank(&mut self, bank: u8, _: u16) {\n\n self.offset = (bank as usize) * 0x2000;\n\n }\n\n}\n\n\n\n// Battery backed RAM\n\npub struct BatteryRAM {\n\n save_file: String,\n\n offset: usize,\n", "file_path": "src/mem/cartridge/ram.rs", "rank": 89, "score": 15.229861216768157 }, { "content": " 0xFF1D => self.wave.set_freq_lo_reg(val),\n\n 0xFF1E => self.wave.set_freq_hi_reg(val),\n\n\n\n 0xFF20 => self.noise.set_length_reg(val),\n\n 0xFF21 => self.noise.set_vol_envelope_reg(val),\n\n 0xFF22 => self.noise.set_poly_counter_reg(val),\n\n 0xFF23 => self.noise.set_trigger_reg(val),\n\n\n\n 0xFF24 => {\n\n const REDUCTION_FACTOR: f32 = 1.0 / (4.0 * 7.0); // 4 channels, max vol = 7\n\n let vol_ctrl = VolumeControl::from_bits_truncate(val);\n\n self.vol_left = vol_ctrl.vol_left() * REDUCTION_FACTOR;\n\n self.vol_right = vol_ctrl.vol_right() * REDUCTION_FACTOR;\n\n self.volume_control = vol_ctrl;\n\n },\n\n 0xFF25 => self.channel_enables = ChannelEnables::from_bits_truncate(val),\n\n 0xFF26 => {\n\n let power_on = test_bit!(val, 7);\n\n if !power_on {\n\n self.power_control.remove(PowerControl::POWER);\n", "file_path": "src/audio/mod.rs", "rank": 90, "score": 15.115505231774524 }, { "content": " pub fn cgb_cart(&self) -> bool {\n\n let cgb_flag = self.read(0x143);\n\n test_bit!(cgb_flag, 7)\n\n }\n\n}\n\n\n\n// Internal swapping methods.\n\nimpl Cartridge {\n\n fn swap_rom_bank(&mut self, bank: u16) {\n\n self.rom.set_bank(bank);\n\n }\n\n\n\n #[inline]\n\n fn swap_ram_bank(&mut self, bank: u8) {\n\n self.ram.set_bank(bank, 0);\n\n }\n\n\n\n #[inline]\n\n fn read_ram(&self, loc: u16) -> u8 {\n\n if self.ram_enable {\n", "file_path": "src/mem/cartridge/mod.rs", "rank": 91, "score": 14.990259906324237 }, { "content": " const PLAYING_2 = bit!(1);\n\n const PLAYING_1 = bit!(0);\n\n }\n\n}\n\n\n\nimpl PowerControl {\n\n fn is_on(&self) -> bool {\n\n self.contains(PowerControl::POWER)\n\n }\n\n}\n\n\n\nconst SAMPLE_PACKET_SIZE: usize = 32;\n\nconst CYCLES_PER_SECOND: usize = 154 * 456 * 60;\n\nconst INPUT_SAMPLE_RATE: f64 = 131_072.0;\n\n\n\npub type SamplePacket = Box<[Stereo<f32>]>;\n\n\n\n// The structure that exists in memory. Sends data to the audio thread.\n\npub struct AudioDevice {\n\n // Raw channel data\n", "file_path": "src/audio/mod.rs", "rank": 92, "score": 14.862434327211162 }, { "content": "// Cache for storing tile maps.\n\nuse bitflags::bitflags;\n\n\n\nuse super::patternmem::TileMem;\n\nuse super::super::regs::VideoRegs;\n\n\n\nbitflags!{\n\n #[derive(Default)]\n\n pub struct TileAttributes: u8 {\n\n const PRIORITY = bit!(7);\n\n const Y_FLIP = bit!(6);\n\n const X_FLIP = bit!(5);\n\n const VRAM_BANK = bit!(3);\n\n const CGB_PAL = bit!(2) | bit!(1) | bit!(0);\n\n }\n\n}\n\n\n\npub struct MapCache {\n\n texels: Vec<Vec<u8>>,\n\n attrs: Vec<Vec<TileAttributes>>, // TODO: is this the best way of doing this?\n", "file_path": "src/video/vram/mapcache.rs", "rank": 93, "score": 14.695360546459177 }, { "content": "// Pixel renderer. Makes a texture of format R8G8B8A8Unorm\n\nuse super::vram::VRAM;\n\nuse super::regs::VideoRegs;\n\n\n\nuse std::sync::{\n\n Arc,\n\n Mutex\n\n};\n\n\n\nuse crossbeam_channel::{\n\n unbounded,\n\n Sender,\n\n Receiver\n\n};\n\n\n\npub type RenderTarget = Arc<Mutex<[u8]>>;\n\n\n\n// Messages to send to the render thread.\n", "file_path": "src/video/renderer_threads.rs", "rank": 94, "score": 14.503410424759242 }, { "content": " ret\n\n }\n\n}\n\n\n\n// Instructions\n\nimpl CPU {\n\n // Arithmetic\n\n fn add(&mut self, carry: bool, op: u8) {\n\n let c = if self.flags.contains(CPUFlags::CARRY) && carry {1_u8} else {0_u8};\n\n let result = (self.a as u16) + (op as u16) + (c as u16);\n\n self.flags = CPUFlags::default();\n\n self.flags.set(CPUFlags::ZERO, (result & 0xFF) == 0);\n\n self.flags.set(CPUFlags::HC, ((self.a & 0xF) + (op & 0xF) + c) > 0xF);\n\n self.flags.set(CPUFlags::CARRY, result > 0xFF);\n\n self.a = result as u8;\n\n }\n\n\n\n fn add_16(&mut self, op: u16) {\n\n self.clock_inc();\n\n let hl = self.get_16(Reg::HL);\n", "file_path": "src/cpu.rs", "rank": 95, "score": 14.468963039415112 }, { "content": "#[cfg(feature = \"debug\")]\n\nimpl RustBoy {\n\n pub fn step(&mut self) -> bool {\n\n self.cpu.step()\n\n }\n\n\n\n pub fn get_state(&self) -> debug::CPUState {\n\n self.cpu.get_state()\n\n }\n\n\n\n pub fn get_instr(&self) -> [u8; 3] {\n\n self.cpu.get_instr()\n\n }\n\n\n\n pub fn get_mem_at(&self, loc: u16) -> u8 {\n\n self.cpu.get_mem_at(loc)\n\n }\n\n}", "file_path": "src/lib.rs", "rank": 96, "score": 14.377123255105765 }, { "content": " self.lcd_control.contains(LCDControl::BG_TILE_MAP_SELECT)\n\n }\n\n\n\n pub fn window_tile_map_select(&self) -> bool {\n\n self.lcd_control.contains(LCDControl::WINDOW_TILE_MAP_SELECT)\n\n }\n\n\n\n pub fn display_sprites(&self) -> bool {\n\n self.lcd_control.contains(LCDControl::OBJ_DISPLAY_ENABLE)\n\n }\n\n}\n\n\n\n// Reading\n\nimpl VideoRegs {\n\n\n\n pub fn read_lcdc_y(&self) -> u8 {\n\n self.lcdc_y\n\n }\n\n\n\n pub fn read_lcd_control(&self) -> u8 {\n", "file_path": "src/video/regs.rs", "rank": 97, "score": 13.992551401986372 }, { "content": " pub fn read_bg_index(&self) -> u8 {\n\n (self.bg_palette_index as u8) | self.bg_auto_inc.bits()\n\n }\n\n\n\n pub fn write_bg_index(&mut self, val: u8) {\n\n self.bg_palette_index = (val & 0x3F) as usize;\n\n self.bg_auto_inc = PaletteIndex::from_bits_truncate(val);\n\n }\n\n\n\n pub fn read_obj_index(&self) -> u8 {\n\n (self.obj_palette_index as u8) | self.obj_auto_inc.bits()\n\n }\n\n\n\n pub fn write_obj_index(&mut self, val: u8) {\n\n self.obj_palette_index = (val & 0x3F) as usize;\n\n self.obj_auto_inc = PaletteIndex::from_bits_truncate(val);\n\n }\n\n\n\n pub fn read_bg(&self) -> u8 {\n\n let palette = self.bg_palette_index / 8;\n", "file_path": "src/video/vram/palette/dynamic.rs", "rank": 98, "score": 13.959454820090787 }, { "content": " Select::Direction\n\n } else {\n\n Select::None\n\n };\n\n }\n\n\n\n pub fn set_direction(&mut self, direction: Directions, val: bool) {\n\n self.directions.set(direction, val);\n\n self.change = self.change || val;\n\n }\n\n\n\n pub fn set_button(&mut self, button: Buttons, val: bool) {\n\n self.buttons.set(button, val);\n\n self.change = self.change || val;\n\n }\n\n\n\n pub fn check_interrupt(&mut self) -> bool {\n\n let trigger_interrupt = self.change;\n\n self.change = false;\n\n trigger_interrupt\n\n }\n\n}\n", "file_path": "src/joypad.rs", "rank": 99, "score": 13.870100192784566 } ]
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 // organisational/licenses:\n\n let texts_requested = (\n\n matches.is_present(ARG_LICENSE),\n\n matches.is_present(ARG_DEP_LICENSES),\n\n );\n\n\n\n match texts_requested {\n\n (true, false) => {\n\n builder = builder.show_license_text_of(SelectedLicenses::ThisSoftware);\n\n }\n\n (false, true) => {\n\n builder = builder.show_license_text_of(SelectedLicenses::Dependencies);\n\n }\n\n (true, true) => {\n\n builder = builder.show_license_text_of(SelectedLicenses::ThisSoftwarePlusDependencies);\n\n }\n\n (false, false) => (),\n", "file_path": "src/app/cli.rs", "rank": 2, "score": 205694.33800769082 }, { "content": "/// In and output path prefixes are pre-defined.\n\npub fn command(input: &str, output: &str, args: &str) -> Child {\n\n let input = setup_input_path(&input);\n\n let input = input.to_str().unwrap();\n\n let output = setup_output_path(&output);\n\n let output = output.to_str().unwrap();\n\n\n\n let mut command = Command::new(\"cargo\");\n\n\n\n let mut arguments = vec![\"run\", \"--\", \"-i\", input, \"-o\", output];\n\n let provided: Vec<&str> = args.split_whitespace().collect();\n\n arguments.extend(provided);\n\n\n\n command.args(arguments);\n\n command.spawn().expect(\"Couldn't spawn child process.\")\n\n}\n\n\n\npub const DEFAULT_IN: &str = \"rainbow_8x6.bmp\";\n\n\n\nmacro_rules! assert_not {\n\n ($e:expr) => {\n\n assert!(!$e)\n\n };\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 3, "score": 200065.04831809824 }, { "content": "/// Strictly speaking not necessary here since the responsible owners will validate the quality as well.\n\n/// However, by doing anyways it we can exit earlier.\n\npub fn validate_jpeg_quality(quality: u8) -> Result<u8, String> {\n\n fn within_range(v: u8) -> Result<u8, String> {\n\n // Upper bound is exclusive with .. syntax.\n\n // When the `range_contains` feature will be stabilised Range.contains(&v)\n\n // should be used instead.\n\n const ALLOWED_RANGE: std::ops::Range<u8> = 1..101;\n\n if ALLOWED_RANGE.contains(&v) {\n\n Ok(v)\n\n } else {\n\n Err(\"JPEG Encoding Settings error: JPEG quality requires a number between 1 and 100 (inclusive).\".to_string())\n\n }\n\n }\n\n\n\n within_range(quality)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use sic_image_engine::engine::Instruction;\n", "file_path": "src/app/config.rs", "rank": 4, "score": 198947.92013934298 }, { "content": "// enum variants on type aliases are currently experimental, so we use a function here instead.\n\npub fn use_stdout_bytes_as_export_method() -> ExportMethod<EmptyPath> {\n\n ExportMethod::StdoutBytes\n\n}\n\n\n\npub struct EmptyPath;\n\n\n\nimpl AsRef<Path> for EmptyPath {\n\n fn as_ref(&self) -> &Path {\n\n Path::new(\"\")\n\n }\n\n}\n", "file_path": "sic_io/src/save.rs", "rank": 5, "score": 198440.4872183341 }, { "content": "// by image header\n\nfn is_image_format(output_path: &str, hope: image::ImageFormat) -> bool {\n\n let mut file = std::fs::File::open(setup_output_path(output_path))\n\n .expect(\"Failed to find (produced) test image.\");\n\n\n\n let mut bytes = vec![];\n\n\n\n file.read_to_end(&mut bytes)\n\n .expect(\"Failed to read (produced) test image.\");\n\n\n\n hope == image::guess_format(&bytes).expect(\"Format could not be guessed.\")\n\n}\n\n\n\n// convert_to_X_by_extension\n\n// BMP, GIF, JPEG, PNG, ICO, PBM, PGM, PPM, PAM\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 6, "score": 195065.53673772517 }, { "content": "pub fn setup_input_path(test_image_path: &str) -> PathBuf {\n\n Path::new(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"resources\")\n\n .join(test_image_path)\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 7, "score": 192436.188702451 }, { "content": "/// Constructs a reader which reads from a file path.\n\npub fn file_reader<P: AsRef<Path>>(path: P) -> ImportResult<Box<dyn Read>> {\n\n Ok(Box::new(BufReader::new(File::open(path)?)))\n\n}\n\n\n", "file_path": "sic_io/src/load.rs", "rank": 8, "score": 191067.3167863571 }, { "content": "pub fn clean_up_output_path(test_output_path: &str) {\n\n std::fs::remove_file(setup_output_path(test_output_path))\n\n .expect(\"Unable to remove file after test.\");\n\n}\n\n\n", "file_path": "sic_testing/src/lib.rs", "rank": 10, "score": 184725.76706047577 }, { "content": "pub fn setup_output_path(test_output_path: &str) -> PathBuf {\n\n Path::new(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"target\")\n\n .join(test_output_path)\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 11, "score": 181707.3043036014 }, { "content": "pub fn setup_output_path(test_output_path: &str) -> PathBuf {\n\n Path::new(\"\").join(out_!(test_output_path))\n\n}\n\n\n", "file_path": "sic_testing/src/lib.rs", "rank": 12, "score": 177933.97451802914 }, { "content": "pub fn parse_script(script: &str) -> Result<Vec<Instruction>, String> {\n\n let parsed_script = SICParser::parse(PARSER_RULE, script);\n\n\n\n parsed_script\n\n .map_err(|err| format!(\"Unable to parse sic image operations script: {:?}\", err))\n\n .and_then(parse_image_operations)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use sic_image_engine::engine::Instruction;\n\n use sic_image_engine::ImgOp;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_too_many_args() {\n\n let input = \"blur 15 28;\";\n\n let parsed = SICParser::parse(Rule::main, input);\n\n\n", "file_path": "sic_parser/src/lib.rs", "rank": 13, "score": 171512.02572255486 }, { "content": "/// TODO{issue#128}: rework to provide flexibility and consistency, so all modules can use this;\n\npub fn setup_test_image(test_image_path: &str) -> PathBuf {\n\n Path::new(\"\").join(in_!(test_image_path))\n\n}\n\n\n", "file_path": "sic_testing/src/lib.rs", "rank": 14, "score": 170943.40430795462 }, { "content": "pub fn export<P: AsRef<Path>>(\n\n image: &image::DynamicImage,\n\n method: ExportMethod<P>,\n\n format: image::ImageOutputFormat,\n\n export_settings: ExportSettings,\n\n) -> Result<(), String> {\n\n let writer = ConversionWriter::new(image);\n\n writer.write(method, format, export_settings.adjust_color_type)\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ExportSettings {\n\n pub adjust_color_type: AutomaticColorTypeAdjustment,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ExportMethod<P: AsRef<Path>> {\n\n File(P),\n\n StdoutBytes,\n\n}\n\n\n", "file_path": "sic_io/src/save.rs", "rank": 15, "score": 165543.99966960744 }, { "content": "// copied from sic_lib::processor::mod_test_includes\n\n// I preferred to not make that module public (2018-11-28)\n\n// Originally named: setup_test_image.\n\nfn setup_input_path(test_image_path: &str) -> PathBuf {\n\n Path::new(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"resources\")\n\n .join(test_image_path)\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 16, "score": 161473.98548546853 }, { "content": "/// Constructs a reader which reads from the stdin.\n\npub fn stdin_reader() -> ImportResult<Box<dyn Read>> {\n\n Ok(Box::new(BufReader::new(std::io::stdin())))\n\n}\n\n\n", "file_path": "sic_io/src/load.rs", "rank": 17, "score": 155653.73305376456 }, { "content": "// copied from sic_lib::processor::mod_test_includes\n\n// I preferred to not make that module public (2018-11-28)\n\nfn clean_up_output_path(test_output_path: &str) {\n\n std::fs::remove_file(setup_output_path(test_output_path))\n\n .expect(\"Unable to remove file after test.\");\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 18, "score": 155292.62019105244 }, { "content": "/// Load an image using a reader.\n\n/// All images are currently loaded from memory.\n\npub fn load_image<R: Read>(\n\n reader: &mut R,\n\n config: &ImportConfig,\n\n) -> ImportResult<image::DynamicImage> {\n\n let buffer = load(reader)?;\n\n\n\n if starts_with_gif_magic_number(&buffer) {\n\n load_gif(&buffer, config.selected_frame)\n\n } else {\n\n image::load_from_memory(&buffer).map_err(From::from)\n\n }\n\n}\n\n\n", "file_path": "sic_io/src/load.rs", "rank": 19, "score": 152363.94231622614 }, { "content": "// Let the reader store the raw bytes into a buffer.\n\nfn load<R: Read>(reader: &mut R) -> ImportResult<Vec<u8>> {\n\n let mut buffer = Vec::new();\n\n let _size = reader.read_to_end(&mut buffer)?;\n\n Ok(buffer)\n\n}\n\n\n\n#[derive(Debug, Default)]\n\npub struct ImportConfig {\n\n /// For animated images; decides which frame will be used as static image.\n\n pub selected_frame: FrameIndex,\n\n}\n\n\n\n/// Zero-indexed frame index.\n\n#[derive(Clone, Copy, Debug)]\n\npub enum FrameIndex {\n\n First,\n\n Last,\n\n Nth(usize),\n\n}\n\n\n\nimpl Default for FrameIndex {\n\n fn default() -> Self {\n\n FrameIndex::First\n\n }\n\n}\n\n\n", "file_path": "sic_io/src/load.rs", "rank": 20, "score": 152339.1333117755 }, { "content": "// copied from sic_lib::processor::mod_test_includes\n\n// I preferred to not make that module public (2018-11-28)\n\nfn setup_output_path(test_output_path: &str) -> PathBuf {\n\n Path::new(env!(\"CARGO_MANIFEST_DIR\"))\n\n .join(\"target\")\n\n .join(test_output_path)\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 21, "score": 150028.8818811244 }, { "content": "fn main() -> Result<(), String> {\n\n let app = sic_lib::app::cli::cli();\n\n let matches = app.get_matches();\n\n\n\n let license_display = matches.is_present(\"license\") || matches.is_present(\"dep_licenses\");\n\n\n\n let configuration = build_app_config(&matches)?;\n\n\n\n if license_display {\n\n run_display_licenses(&configuration)\n\n } else {\n\n run(&matches, &configuration)\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 22, "score": 148990.42831464432 }, { "content": "// This function parses statements provided as a single 'script' to an image operations program.\n\n// An image operations program is currently a linear list of image operations which are applied\n\n// in a left-to-right order.\n\n// Operations are parsed from Pairs and Rules, which are provided by the Pest parser library.\n\n//\n\n// In the event of any parse failure, an error shall be returned.\n\n// The error currently usually contains into_inner(), to provide detailed information about the\n\n// origins of the parsing rejection.\n\n//\n\n// FIXME: When the user facing errors will be reworked, the providing of or the how to providing of-\n\n// the into_inner() parsing details should be reconsidered\n\npub fn parse_image_operations(pairs: Pairs<'_, Rule>) -> Result<Vec<Instruction>, String> {\n\n pairs\n\n .filter(|pair| pair.as_rule() != Rule::EOI)\n\n .map(|pair| match pair.as_rule() {\n\n Rule::blur => Blur(pair),\n\n Rule::brighten => Brighten(pair),\n\n Rule::contrast => Contrast(pair),\n\n Rule::crop => Crop(pair),\n\n Rule::filter3x3 => Filter3x3(pair),\n\n Rule::flip_horizontal => Ok(Instruction::Operation(ImgOp::FlipHorizontal)),\n\n Rule::flip_vertical => Ok(Instruction::Operation(ImgOp::FlipVertical)),\n\n Rule::grayscale => Ok(Instruction::Operation(ImgOp::GrayScale)),\n\n Rule::huerotate => HueRotate(pair),\n\n Rule::invert => Ok(Instruction::Operation(ImgOp::Invert)),\n\n Rule::resize => Resize(pair),\n\n Rule::rotate90 => Ok(Instruction::Operation(ImgOp::Rotate90)),\n\n Rule::rotate180 => Ok(Instruction::Operation(ImgOp::Rotate180)),\n\n Rule::rotate270 => Ok(Instruction::Operation(ImgOp::Rotate270)),\n\n Rule::unsharpen => Unsharpen(pair),\n\n Rule::setopt => parse_set_environment(pair.into_inner().next().ok_or_else(|| {\n", "file_path": "sic_parser/src/rule_parser.rs", "rank": 23, "score": 140836.27730110945 }, { "content": "fn load_gif(buffer: &[u8], frame: FrameIndex) -> Result<image::DynamicImage, ImportError> {\n\n let decoder = image::gif::Decoder::new(&buffer[..])?;\n\n let frames = decoder.into_frames();\n\n let vec = frames.collect::<Result<Vec<_>, image::ImageError>>()?;\n\n let amount_of_frames = vec.len();\n\n\n\n // The one-indexed selected frame picked by the user; stored as zero-indexed frames\n\n // in the import config.\n\n // There is no guarantee that the selected frame does exist at this point.\n\n let selected = match frame {\n\n FrameIndex::First => 0usize,\n\n FrameIndex::Nth(n) => n,\n\n FrameIndex::Last => {\n\n if vec.is_empty() {\n\n return Err(ImportError::NoSuchFrame(0, \"No frames found.\".to_string()));\n\n }\n\n\n\n amount_of_frames - 1\n\n }\n\n };\n", "file_path": "sic_io/src/load.rs", "rank": 24, "score": 138700.88659685763 }, { "content": "pub fn open_test_image<P: AsRef<Path>>(path: P) -> sic_core::image::DynamicImage {\n\n sic_core::image::open(path.as_ref()).unwrap()\n\n}\n", "file_path": "sic_testing/src/lib.rs", "rank": 25, "score": 137566.77753294702 }, { "content": "pub trait EncodingFormatByMethod {\n\n /// Determine the encoding format based on the method of exporting.\n\n fn by_method<P: AsRef<Path>>(\n\n &self,\n\n method: &ExportMethod<P>,\n\n ) -> Result<image::ImageOutputFormat, Box<dyn Error>>;\n\n}\n\n\n", "file_path": "sic_io/src/format.rs", "rank": 26, "score": 135627.9295897185 }, { "content": "fn ast_from_index_tree(tree: &mut IndexTree) -> Result<Vec<Instruction>, String> {\n\n tree.iter()\n\n .map(|(_index, op)| match op {\n\n Op::Bare(id) => {\n\n let empty: &[&str; 0] = &[];\n\n id.mk_statement(empty)\n\n }\n\n Op::WithValues(id, values) => id.mk_statement(values),\n\n })\n\n .collect::<Result<Vec<Instruction>, String>>()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use sic_image_engine::engine::Instruction;\n\n use sic_image_engine::ImgOp;\n\n use std::collections::BTreeMap;\n\n\n\n macro_rules! assert_match {\n", "file_path": "src/app/cli.rs", "rank": 28, "score": 134369.88260960535 }, { "content": "pub fn get_tool_name() -> &'static str {\n\n env!(\"CARGO_PKG_NAME\")\n\n}\n", "file_path": "src/lib.rs", "rank": 29, "score": 130944.22057144548 }, { "content": "fn read_file_to_bytes<P: AsRef<Path>>(path: P) -> Vec<u8> {\n\n let mut f = std::fs::File::open(path).unwrap();\n\n let mut buffer = Vec::new();\n\n\n\n // read the whole file\n\n f.read_to_end(&mut buffer).unwrap();\n\n\n\n buffer\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 30, "score": 128734.66394842575 }, { "content": "fn path_buf_str(pb: &PathBuf) -> &str {\n\n pb.to_str().unwrap()\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 31, "score": 127205.09681465893 }, { "content": "/// Chunk provided values and try to unify each chunk to a single [Op].\n\n/// Requires each chunk to be of the size of the `size` argument.\n\nfn unify_arguments_of_operation(nodes: IndexedOps, size: usize) -> Result<IndexedOps, String> {\n\n assert_ne!(size, 0);\n\n\n\n let chunks = nodes.chunks(size).clone();\n\n let mut vec: IndexedOps = Vec::new();\n\n\n\n for chunk in chunks {\n\n if chunk.len() != size {\n\n return Err(format!(\n\n \"Unification of multi valued argument(s) failed: arguments could't be \\\n\n partitioned in correct chunk sizes. Length of chunk: {}\",\n\n chunk.len()\n\n ));\n\n }\n\n\n\n let unified_chunk = unify_chunk(chunk, None, size);\n\n vec.push(unified_chunk?);\n\n }\n\n\n\n Ok(vec)\n\n}\n\n\n\nconst FAILED_UNIFICATION_MESSAGE: &str =\n\n \"Unification of multi valued argument(s) failed: \\\n\n When using an image operation cli argument which requires n values, \\\n\n all values should be provided at once. For example, `--crop` takes 4 values \\\n\n so, n=4. Now, `--crop 0 0 1 1` would be valid, but `--crop 0 0 --crop 1 1` would not.\";\n\n\n", "file_path": "src/app/operations.rs", "rank": 32, "score": 118155.26325155803 }, { "content": "#[test]\n\nfn only_o() {\n\n let kind = RunWithIOArg::OnlyO;\n\n let input = String::from(setup_input_path(\"palette_4x4.png\").to_str().unwrap());\n\n let output = String::from(setup_output_path(\"ooo.jpg\").to_str().unwrap());\n\n let result = kind.start(&input, &output).expect(\"process\").wait();\n\n\n\n assert!(result.is_ok());\n\n\n\n // expect a non zero exit status\n\n assert_not!(result.unwrap().success());\n\n}\n", "file_path": "tests/cli_input_output.rs", "rank": 33, "score": 117496.17178373931 }, { "content": "#[test]\n\nfn only_i() {\n\n let kind = RunWithIOArg::OnlyI;\n\n let input = String::from(setup_input_path(\"palette_4x4.png\").to_str().unwrap());\n\n let output = String::from(setup_output_path(\"iii.jpg\").to_str().unwrap());\n\n let result = kind.start(&input, &output).expect(\"process\").wait();\n\n\n\n assert!(result.is_ok());\n\n\n\n // expect a non zero exit status\n\n assert_not!(result.unwrap().success());\n\n}\n\n\n", "file_path": "tests/cli_input_output.rs", "rank": 34, "score": 117496.17178373931 }, { "content": "#[test]\n\nfn both_i_and_o_args() {\n\n let kind = RunWithIOArg::BothIO;\n\n let input = String::from(setup_input_path(\"palette_4x4.png\").to_str().unwrap());\n\n let output = String::from(setup_output_path(\"io.jpg\").to_str().unwrap());\n\n let result = kind.start(&input, &output).expect(\"process\").wait();\n\n\n\n assert!(result.is_ok());\n\n assert!(result.unwrap().success());\n\n}\n\n\n", "file_path": "tests/cli_input_output.rs", "rank": 35, "score": 112809.41627903841 }, { "content": "pub trait EncodingFormatJPEGQuality {\n\n /// Returns a validated jpeg quality value.\n\n /// If no such value exists, it will return an error instead.\n\n fn jpeg_quality(&self) -> Result<JPEGQuality, Box<dyn Error>>;\n\n}\n\n\n", "file_path": "sic_io/src/format.rs", "rank": 36, "score": 108591.59203174259 }, { "content": "#[test]\n\nfn neither_i_and_o_args() {\n\n let kind = RunWithIOArg::NeitherIO;\n\n let input = String::from(setup_input_path(\"palette_4x4.png\").to_str().unwrap());\n\n let output = String::from(setup_output_path(\"not_io.jpg\").to_str().unwrap());\n\n let result = kind.start(&input, &output).expect(\"process\").wait();\n\n\n\n assert!(result.is_ok());\n\n assert!(result.unwrap().success());\n\n}\n\n\n", "file_path": "tests/cli_input_output.rs", "rank": 37, "score": 108565.99070877646 }, { "content": "#[test]\n\nfn convert_jpeg_quality_different() {\n\n let which = \"jpeg\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let out1 = setup_output_path(\"out_02_jpeg_1.jpeg\");\n\n let out2 = setup_output_path(\"out_02_jpeg_2.jpeg\");\n\n\n\n let args1 = vec![\n\n \"sic\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&out1),\n\n ];\n\n\n\n let args2 = vec![\n\n \"sic\",\n\n \"--jpeg-encoding-quality\",\n\n \"81\",\n\n \"--output-format\",\n", "file_path": "tests/cli_convert.rs", "rank": 38, "score": 104962.51262667609 }, { "content": "fn parse_set_environment(pair: Pair<'_, Rule>) -> Result<Instruction, String> {\n\n let environment_item = match pair.as_rule() {\n\n Rule::set_resize_sampling_filter => parse_set_resize_sampling_filter(pair)?,\n\n Rule::set_resize_preserve_aspect_ratio => EnvironmentItem::PreserveAspectRatio,\n\n _ => {\n\n return Err(format!(\n\n \"Unable to parse `set` environment command. Error on element: {}\",\n\n pair\n\n ));\n\n }\n\n };\n\n\n\n Ok(Instruction::AddToEnv(environment_item))\n\n}\n\n\n", "file_path": "sic_parser/src/rule_parser.rs", "rank": 39, "score": 99914.57179157632 }, { "content": "fn parse_unset_environment(pair: Pair<'_, Rule>) -> Result<Instruction, String> {\n\n let environment_item = match pair.as_rule() {\n\n Rule::env_resize_sampling_filter_name => EnvironmentKind::CustomSamplingFilter,\n\n Rule::env_resize_preserve_aspect_ratio_name => EnvironmentKind::PreserveAspectRatio,\n\n _ => {\n\n return Err(format!(\n\n \"Unable to parse `del` environment command. Error on element: {}\",\n\n pair\n\n ));\n\n }\n\n };\n\n\n\n Ok(Instruction::RemoveFromEnv(environment_item))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::SICParser;\n\n use pest::Parser;\n\n use sic_core::image;\n", "file_path": "sic_parser/src/rule_parser.rs", "rank": 40, "score": 99914.57179157632 }, { "content": "fn mk_ops(op: OperationId, matches: &ArgMatches) -> Option<IndexedOps> {\n\n let argc = op.takes_number_of_arguments();\n\n match argc {\n\n 0 => op_valueless!(matches, op),\n\n _n => op_with_values!(matches, op),\n\n }\n\n}\n\n\n", "file_path": "src/app/cli.rs", "rank": 41, "score": 99216.14746735449 }, { "content": "fn run_license_command() -> Output {\n\n Command::new(\"cargo\")\n\n .args(&[\"run\", \"--\", \"--license\"])\n\n .output()\n\n .expect(\"Running test failed\")\n\n}\n\n\n\n// This test just ensures the license is included within the binary.\n", "file_path": "tests/cli_license.rs", "rank": 42, "score": 98042.01118323588 }, { "content": "fn parse_set_resize_sampling_filter(pair: Pair<'_, Rule>) -> Result<EnvironmentItem, String> {\n\n let mut inner = pair.into_inner();\n\n\n\n // skip over the compound atomic 'env_available' rule\n\n inner\n\n .next()\n\n .ok_or_else(|| \"Unable to parse the 'set_resize_sampling_filter' option. No options exist for the command. \")?;\n\n\n\n inner\n\n .next()\n\n .ok_or_else(|| {\n\n format!(\n\n \"Unable to parse the 'set_resize_sampling_filter' option. Error on element: {}\",\n\n inner\n\n )\n\n })\n\n .map(|val| val.as_str())\n\n .and_then(|val| {\n\n FilterTypeWrap::try_from_str(val).map_err(|err| format!(\"Unable to parse: {}\", err))\n\n })\n\n .map(EnvironmentItem::CustomSamplingFilter)\n\n}\n\n\n", "file_path": "sic_parser/src/rule_parser.rs", "rank": 43, "score": 94129.94621923837 }, { "content": "pub trait EncodingFormatByExtension {\n\n /// Determine the encoding format based on the extension of a file path.\n\n fn by_extension<P: AsRef<Path>>(\n\n &self,\n\n path: P,\n\n ) -> Result<image::ImageOutputFormat, Box<dyn Error>>;\n\n}\n\n\n", "file_path": "sic_io/src/format.rs", "rank": 44, "score": 85431.01462905915 }, { "content": "pub trait EncodingFormatByIdentifier {\n\n /// Determine the encoding format based on the method of exporting.\n\n /// Determine the encoding format based on a recognized given identifier.\n\n fn by_identifier(&self, identifier: &str) -> Result<image::ImageOutputFormat, Box<dyn Error>>;\n\n}\n\n\n", "file_path": "sic_io/src/format.rs", "rank": 45, "score": 85431.01462905915 }, { "content": "fn guess_is_ascii_encoded(input: &[u8]) -> bool {\n\n // The character P in ascii encoding\n\n let is_ascii_p = |c: u8| c == 0x50;\n\n\n\n // P1, P2, P3 are ascii\n\n // Checks for numbers 1, 2, 3, binary known as: 0x31, 0x32, 0x33 respectively\n\n let is_ascii_magic_number = |c| c == 0x31 || c == 0x32 || c == 0x33;\n\n\n\n let mut iter = input.iter();\n\n let first = iter.next().unwrap();\n\n let second = iter.next().unwrap();\n\n\n\n // check also to be sure that every character in the file can be ascii encoded\n\n is_ascii_p(*first) && is_ascii_magic_number(*second) && iter.all(|c| *c <= 0x7F)\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 46, "score": 84690.14525686923 }, { "content": "pub fn cli() -> App<'static, 'static> {\n\n App::new(get_tool_name())\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .about(ABOUT)\n\n .after_help(\"For more information, visit: https://github.com/foresterre/sic\")\n\n .author(\"Martijn Gribnau <[email protected]>\")\n\n\n\n // settings\n\n .global_setting(AppSettings::NextLineHelp)\n\n .global_setting(AppSettings::ColoredHelp)\n\n .global_setting(AppSettings::ColorAuto)\n\n .global_setting(AppSettings::DontCollapseArgsInUsage)\n\n .global_setting(AppSettings::UnifiedHelpMessage)\n\n .max_term_width(120)\n\n\n\n // cli arguments\n\n\n\n // organisational:\n\n .arg(Arg::with_name(ARG_LICENSE)\n\n .long(\"license\")\n", "file_path": "src/app/cli.rs", "rank": 47, "score": 82845.2679139399 }, { "content": "pub trait EncodingFormatPNMSampleEncoding {\n\n /// Returns a pnm sample encoding type.\n\n /// If no such value exists, it will return an error instead.\n\n fn pnm_encoding_type(&self) -> Result<image::pnm::SampleEncoding, Box<dyn Error>>;\n\n}\n\n\n\n/// This struct ensures no invalid JPEG qualities can be stored.\n\n/// Using this struct instead of `u8` directly should ensure no panics occur because of invalid\n\n/// quality values.\n\n#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]\n\npub struct JPEGQuality {\n\n quality: u8,\n\n}\n\n\n\nimpl Default for JPEGQuality {\n\n /// The default JPEG quality is `80`.\n\n fn default() -> Self {\n\n Self { quality: 80 }\n\n }\n\n}\n", "file_path": "sic_io/src/format.rs", "rank": 48, "score": 81287.34808607686 }, { "content": "fn starts_with_gif_magic_number(buffer: &[u8]) -> bool {\n\n buffer.starts_with(b\"GIF87a\") || buffer.starts_with(b\"GIF89a\")\n\n}\n\n\n", "file_path": "sic_io/src/load.rs", "rank": 49, "score": 80984.3455426103 }, { "content": "#[test]\n\nfn convert_to_bmp_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.bmp\");\n\n\n\n let args = vec![\n\n \"sic\",\n\n our_input.to_str().unwrap(),\n\n path_buf_str(&our_output),\n\n ];\n\n let matches = get_app().get_matches_from(args);\n\n\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::BMP\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 50, "score": 79925.8151070556 }, { "content": "#[test]\n\nfn convert_to_bmp_by_ff() {\n\n let which = \"bmp\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::BMP\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 51, "score": 79925.8151070556 }, { "content": "fn build_ast_from_matches(\n\n matches: &ArgMatches,\n\n tree: &mut IndexTree,\n\n) -> Result<Vec<Instruction>, String> {\n\n let operations = vec![\n\n // operations\n\n OperationId::Blur,\n\n OperationId::Brighten,\n\n OperationId::Contrast,\n\n OperationId::Crop,\n\n OperationId::Filter3x3,\n\n OperationId::FlipH,\n\n OperationId::FlipV,\n\n OperationId::Grayscale,\n\n OperationId::HueRotate,\n\n OperationId::Invert,\n\n OperationId::Resize,\n\n OperationId::Rotate90,\n\n OperationId::Rotate180,\n\n OperationId::Rotate270,\n", "file_path": "src/app/cli.rs", "rank": 52, "score": 79890.47165261599 }, { "content": "/// Result which is returned for operations within this module.\n\ntype ImportResult<T> = Result<T, ImportError>;\n\n\n", "file_path": "sic_io/src/load.rs", "rank": 53, "score": 73769.18903401318 }, { "content": "/// This iteration of the parse trait should help with unifying the\n\n/// Pest parsing and cli ops arguments directly from &str.\n\n///\n\n/// From Pest we receive iterators, but we can use as_str, to request &str values.\n\n/// We'll try to use this to map the received values as_str, and then we'll have\n\n/// a similar structure as the image operation arguments from the cli (we receive these\n\n/// eventually as Vec<&str>, thus iterable.\n\npub trait ParseInputsFromIter {\n\n type Error;\n\n\n\n fn parse<'a, T>(iterable: T) -> Result<Self, Self::Error>\n\n where\n\n T: IntoIterator,\n\n T::Item: Into<Describable<'a>> + std::fmt::Debug,\n\n Self: std::marker::Sized;\n\n}\n\n\n\nmacro_rules! parse_next {\n\n ($iter:expr, $ty:ty, $err_msg:expr) => {\n\n $iter\n\n .next()\n\n .ok_or_else(|| $err_msg.to_string())\n\n .and_then(|v| {\n\n let v: Describable = v.into();\n\n v.0.parse::<$ty>().map_err(|_| $err_msg.to_string())\n\n })?;\n\n };\n", "file_path": "sic_parser/src/value_parser.rs", "rank": 54, "score": 73204.18978128323 }, { "content": " fn only_i(&self, input: &str, output: &str) -> Command {\n\n let mut command = Command::new(\"cargo\");\n\n command.args(&[\"run\", \"--\", \"-i\", input, output]);\n\n command\n\n }\n\n\n\n fn only_o(&self, input: &str, output: &str) -> Command {\n\n let mut command = Command::new(\"cargo\");\n\n command.args(&[\"run\", \"--\", \"-o\", output, input]);\n\n command\n\n }\n\n\n\n fn start(&self, input: &str, output: &str) -> std::io::Result<Child> {\n\n match self {\n\n RunWithIOArg::BothIO => self.both(input, output).spawn(),\n\n RunWithIOArg::OnlyI => self.only_i(input, output).spawn(),\n\n RunWithIOArg::OnlyO => self.only_o(input, output).spawn(),\n\n RunWithIOArg::NeitherIO => self.neither(input, output).spawn(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/cli_input_output.rs", "rank": 55, "score": 63580.80091009469 }, { "content": "use std::process::{Child, Command};\n\n\n\n#[macro_use]\n\npub mod common;\n\n\n\nuse crate::common::*;\n\n\n\n#[derive(Copy, Clone)]\n", "file_path": "tests/cli_input_output.rs", "rank": 56, "score": 63568.71773962993 }, { "content": "fn main() {\n\n // Compress the thanks/dependency_licenses.txt file, because it's huge.\n\n let folder = env::var(\"OUT_DIR\").expect(\"OUT_DIR not set\");\n\n let path = Path::new(&folder).join(\"compressed_dep_licenses\");\n\n let file = File::create(&path).unwrap();\n\n\n\n let text = include_bytes!(concat!(\n\n env!(\"CARGO_MANIFEST_DIR\"),\n\n \"/thanks\",\n\n \"/dependency_licenses.txt\"\n\n ));\n\n\n\n let mut encoder = DeflateEncoder::new(file, Compression::default());\n\n encoder\n\n .write_all(text)\n\n .expect(\"Unable to compress dep licenses tet\");\n\n}\n", "file_path": "build.rs", "rank": 57, "score": 57534.14759522685 }, { "content": "#[derive(Copy, Clone)]\n\nenum RunWithIOArg {\n\n BothIO,\n\n NeitherIO,\n\n OnlyI,\n\n OnlyO,\n\n}\n\n\n\nimpl RunWithIOArg {\n\n fn both(&self, input: &str, output: &str) -> Command {\n\n let mut command = Command::new(\"cargo\");\n\n command.args(&[\"run\", \"--\", \"-i\", input, \"-o\", output]);\n\n command\n\n }\n\n\n\n fn neither(&self, input: &str, output: &str) -> Command {\n\n let mut command = Command::new(\"cargo\");\n\n command.args(&[\"run\", \"--\", input, output]);\n\n command\n\n }\n\n\n", "file_path": "tests/cli_input_output.rs", "rank": 58, "score": 54949.44927556644 }, { "content": "fn main() {\n\n let mut cli = sic_lib::app::cli::cli();\n\n\n\n let program_name = option_env!(\"SIC_COMPLETIONS_APP_NAME\").unwrap_or(\"sic\");\n\n\n\n let shell = match option_env!(\"SIC_COMPLETIONS_FOR_SHELL\").unwrap_or(\"zsh\") {\n\n \"bash\" => clap::Shell::Bash,\n\n \"elvish\" => clap::Shell::Elvish,\n\n \"fish\" => clap::Shell::Fish,\n\n \"powershell\" => clap::Shell::PowerShell,\n\n \"zsh\" => clap::Shell::Zsh,\n\n _ => clap::Shell::Zsh,\n\n };\n\n\n\n let or_out_dir = || {\n\n std::env::args_os().nth(1).unwrap_or(\n\n std::env::current_dir()\n\n .expect(\"Unable to receive current directory.\")\n\n .into_os_string(),\n\n )\n\n };\n\n\n\n let out = option_env!(\"SIC_COMPLETIONS_OUT_DIR\")\n\n .map(From::from)\n\n .unwrap_or_else(or_out_dir);\n\n\n\n cli.gen_completions(program_name, shell, out)\n\n}\n", "file_path": "examples/gen_completions.rs", "rank": 59, "score": 53935.49485444212 }, { "content": "// The `update_dep_licenses` script is no longer a build.rs, mandatory pre-build script.\n\n// To solve issues with `cargo install` (1) and ensure that the licenses of dependencies are\n\n// included in a release binary, the licenses will now always be included.\n\n// This will be done by including a `dependency_licenses.txt` file in the root of the repo.\n\n// Every release, this file needs to be updated, and there this script comes into play.\n\n//\n\n// This script updates the `dependency_licenses.txt` file by using cargo-bom to generate the\n\n// dependencies, this project relies on.\n\n//\n\n// Usage:\n\n// To update the `dependency_licenses.txt` file, run from the project root folder:\n\n// `cargo run --example update_dep_licenses`\n\n//\n\n// (1): https://github.com/foresterre/sic/issues/50\n\n//\n\n// >> The build script for `sic` primarily makes licenses of dependencies available to the installed\n\n// >> executable.\n\n// >> Previously we used cargo-make for this purpose, but in case `sic` is installed by running\n\n// >> `cargo install --force sic`, `cargo make release` is not invoked.\n\n// >> To fix that, we will now use this build script instead.\n\n// >> As a bonus, it should now work both on Windows and Linux out of the box; i.e. on Windows it\n\n// >> doesn't rely on some installed tools like which anymore.\n\nfn main() {\n\n println!(\"Starting the update process of the dependency licenses file.\");\n\n\n\n // Check if cargo-bom is available in our PATH.\n\n let cargo_bom_might_be_installed = if cfg!(windows) {\n\n Command::new(\"where.exe\")\n\n .args(&[\"cargo-bom\"])\n\n .output()\n\n .expect(\"`where.exe` unavailable.\")\n\n .stdout\n\n } else {\n\n Command::new(\"which\")\n\n .args(&[\"cargo-bom\"])\n\n .output()\n\n .expect(\"`which` unavailable.\")\n\n .stdout\n\n };\n\n\n\n // Convert to str\n\n let str_path = str::from_utf8(cargo_bom_might_be_installed.as_slice())\n", "file_path": "examples/update_dep_licenses.rs", "rank": 60, "score": 52409.952667874786 }, { "content": "/// Try to unify a chunk of values to a single value.\n\nfn unify_chunk(\n\n left: &[(usize, Op)],\n\n last: Option<(usize, Op)>,\n\n size: usize,\n\n) -> Result<(usize, Op), String> {\n\n // stop: complete unification of the chunk\n\n if left.is_empty() {\n\n match last {\n\n Some(ret) => Ok(ret),\n\n None => Err(FAILED_UNIFICATION_MESSAGE.to_string()),\n\n }\n\n } else {\n\n // continue (left.len() > 0):\n\n let current: (usize, Op) = left[0].clone();\n\n\n\n match last {\n\n Some(node) => {\n\n // is it incremental based on the last index <- (index, _) ?\n\n if (node.0 + 1) == current.0 {\n\n // Here we create an [IndexedOpNode] tuple.\n", "file_path": "src/app/operations.rs", "rank": 61, "score": 52404.14577424941 }, { "content": "/// This tree extension function should be used if an image operation cli arguments takes more than 1\n\n/// value.\n\n/// Clap provides all values for an argument as a linear container (like a vector with values).\n\n/// However, we don't want to allow --crop 0 0 --crop 1 1, but we do want --crop 0 0 1 1.\n\n/// The resulting value we get from Clap do not differ for the two examples above.\n\n/// Both will give a container along the lines of vec!(\"0\", \"0\", \"1\", \"1\").\n\n/// To ensure we only allow, for an image operation cli arguments which takes 4 values, 4 values\n\n/// all at once, we use the indices of the values (which Clap does provide) to check whether they\n\n/// are incrementally correct (i.e. index_{i+1} = index_{i} + 1).\n\n///\n\n/// Arguments:\n\n/// tree: The BTree which we will extend with nodes for an operation type.\n\n/// op_values: If the operation is not provided, we don't extend the tree. If it is,\n\n/// we'll use the separate nodes and try to unify them into nodes which contain\n\n/// each `size` values.\n\n/// size: The amount of values which an image operation requires.\n\n///\n\nfn tree_extend_unifiable(\n\n tree: &mut IndexTree,\n\n nodes: IndexedOps,\n\n size: usize,\n\n) -> Result<(), String> {\n\n let unified = unify_arguments_of_operation(nodes, size)?;\n\n tree.extend(unified);\n\n Ok(())\n\n}\n\n\n", "file_path": "src/app/operations.rs", "rank": 62, "score": 51035.073940622126 }, { "content": "#[test]\n\nfn convert_to_jpg_by_ff() {\n\n let which = \"jpg\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::JPEG\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 63, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_png_by_ff() {\n\n let which = \"png\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNG\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 64, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_pgm_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.pgm\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 65, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_pbm_by_ff() {\n\n let which = \"pbm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 66, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_jpeg_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.jpeg\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::JPEG\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 67, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_pgm_ascii() {\n\n let which = \"pgm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_02a_{}\", which));\n\n\n\n let args = vec![\n\n \"sic\",\n\n \"--pnm-encoding-ascii\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&our_output),\n\n ];\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n\n\n // read file contents\n\n let contents = read_file_to_bytes(path_buf_str(&our_output));\n\n\n\n // is it just ascii?\n\n assert!(guess_is_ascii_encoded(&contents));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 68, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn cli_license_starts_with() {\n\n let res = run_license_command();\n\n\n\n let begin_text = \"sic image tools license:\";\n\n\n\n assert!(res.status.success());\n\n assert!(std::str::from_utf8(&res.stdout)\n\n .unwrap()\n\n .starts_with(begin_text));\n\n}\n", "file_path": "tests/cli_license.rs", "rank": 69, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_pam_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.pam\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 70, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_gif_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.gif\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::GIF\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 71, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_png_by_extension() {\n\n let our_input = setup_input_path(\"rainbow_8x6.bmp\");\n\n let our_output = setup_output_path(\"out_01.png\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNG\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 72, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_gif_by_ff() {\n\n let which = \"gif\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::GIF\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 73, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_pam_by_ff() {\n\n let which = \"pam\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n\n// Try to determine that PBM, PGM, PPM in ascii mode (P1, P2, P3 resp.) are ascii encoded\n\n// and if they are 'binary' encoded (P4, P5, P6), they are obviously not ascii encoded.\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 74, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_pgm_not_ascii() {\n\n let which = \"pgm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_02b_{}\", which));\n\n\n\n let args = vec![\n\n \"sic\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&our_output),\n\n ];\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n\n\n // read file contents\n\n let contents = read_file_to_bytes(path_buf_str(&our_output));\n\n\n\n // is it just ascii?\n\n assert!(!guess_is_ascii_encoded(&contents));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 75, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_ppm_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.ppm\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 76, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_jpeg_by_ff() {\n\n let which = \"jpeg\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::JPEG\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 77, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_ico_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.ico\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::ICO\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 78, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_ico_by_ff() {\n\n let which = \"ico\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::ICO\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 79, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_pbm_ascii() {\n\n let which = \"pbm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_02a_{}\", which));\n\n\n\n let args = vec![\n\n \"sic\",\n\n \"--pnm-encoding-ascii\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&our_output),\n\n ];\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n\n\n // read file contents\n\n let contents = read_file_to_bytes(path_buf_str(&our_output));\n\n\n\n // is it just ascii?\n\n assert!(guess_is_ascii_encoded(&contents));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 80, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_pbm_not_ascii() {\n\n let which = \"pbm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_02b_{}\", which));\n\n\n\n let args = vec![\n\n \"sic\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&our_output),\n\n ];\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n\n\n // read file contents\n\n let contents = read_file_to_bytes(path_buf_str(&our_output));\n\n\n\n // is it just ascii?\n\n assert!(!guess_is_ascii_encoded(&contents));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 81, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_ppm_ascii() {\n\n let which = \"ppm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_02a_{}\", which));\n\n\n\n let args = vec![\n\n \"sic\",\n\n \"--pnm-encoding-ascii\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&our_output),\n\n ];\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n\n\n // read file contents\n\n let contents = read_file_to_bytes(path_buf_str(&our_output));\n\n\n\n // is it just ascii?\n\n assert!(guess_is_ascii_encoded(&contents));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 82, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_ppm_not_ascii() {\n\n let which = \"ppm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_02b_{}\", which));\n\n\n\n let args = vec![\n\n \"sic\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&our_input),\n\n path_buf_str(&our_output),\n\n ];\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 83, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_pbm_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.pbm\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 84, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_pgm_by_ff() {\n\n let which = \"pgm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 85, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_ppm_by_ff() {\n\n let which = \"ppm\";\n\n\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(&format!(\"out_01_{}\", which));\n\n\n\n let args = convert_to_x_by_ff_args(which, &our_input, &our_output);\n\n\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::PNM\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 86, "score": 51017.65018313758 }, { "content": "#[test]\n\nfn convert_to_jpg_by_extension() {\n\n let our_input = setup_input_path(\"palette_4x4.png\");\n\n let our_output = setup_output_path(\"out_01.jpg\");\n\n\n\n let args = vec![\"sic\", path_buf_str(&our_input), path_buf_str(&our_output)];\n\n let matches = get_app().get_matches_from(args);\n\n let complete = run(&matches, &build_app_config(&matches).unwrap());\n\n\n\n assert_eq!(Ok(()), complete);\n\n assert!(our_output.exists());\n\n assert!(is_image_format(\n\n path_buf_str(&our_output),\n\n image::ImageFormat::JPEG\n\n ));\n\n\n\n clean_up_output_path(path_buf_str(&our_output));\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 87, "score": 51017.65018313758 }, { "content": "fn convert_to_x_by_ff_args<'a>(\n\n which: &'a str,\n\n input: &'a PathBuf,\n\n output: &'a PathBuf,\n\n) -> Vec<&'a str> {\n\n vec![\n\n \"sic\",\n\n \"--output-format\",\n\n which,\n\n path_buf_str(&input),\n\n path_buf_str(&output),\n\n ]\n\n}\n\n\n", "file_path": "tests/cli_convert.rs", "rank": 88, "score": 48083.91006367678 }, { "content": "fn ast_extend_with_operation<T: IntoIterator<Item = OperationId>>(\n\n tree: &mut IndexTree,\n\n matches: &ArgMatches,\n\n operations: T,\n\n) -> Result<(), String> {\n\n for operation in operations {\n\n let argc = operation.takes_number_of_arguments();\n\n let ops = mk_ops(operation, matches);\n\n extend_index_tree_with_unification(tree, ops, argc)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/app/cli.rs", "rank": 89, "score": 37179.9217619595 }, { "content": "\n\n // config(out)\n\n pub fn pnm_format_type(mut self, use_ascii: bool) -> ConfigBuilder<'a> {\n\n self.settings.encoding_settings.pnm_use_ascii_format = use_ascii;\n\n self\n\n }\n\n\n\n // config(out)\n\n pub fn output_path(mut self, path: &'a str) -> ConfigBuilder<'a> {\n\n self.settings.output = Some(path);\n\n self\n\n }\n\n\n\n // image-operations\n\n pub fn image_operations_program(mut self, program: Vec<Instruction>) -> ConfigBuilder<'a> {\n\n self.settings.image_operations_program = program;\n\n self\n\n }\n\n\n\n pub fn build(self) -> Config<'a> {\n", "file_path": "src/app/config.rs", "rank": 90, "score": 33557.19258281993 }, { "content": " pub disable_automatic_color_type_adjustment: bool,\n\n\n\n // config(out)\n\n /// Format to which an image will be converted (enforced).\n\n pub forced_output_format: Option<&'a str>,\n\n\n\n // config(out)\n\n /// Encoding settings for specific output formats.\n\n pub encoding_settings: FormatEncodingSettings,\n\n\n\n // image-operations\n\n /// If a user wants to perform image operations on input image, they will need to provide\n\n /// the image operation commands.\n\n /// THe value set here should be presented as a [sic_image_engine::engine::Program].\n\n /// If no program is present, an empty vec should be provided.\n\n pub image_operations_program: Vec<Instruction>,\n\n}\n\n\n\nimpl Default for Config<'_> {\n\n fn default() -> Self {\n", "file_path": "src/app/config.rs", "rank": 91, "score": 33553.26863444866 }, { "content": "use sic_image_engine::engine::Instruction;\n\nuse sic_io::load::FrameIndex;\n\n\n\n#[derive(Debug)]\n\npub struct Config<'a> {\n\n pub tool_name: &'static str,\n\n\n\n // organisational\n\n /// Display license of this software or its dependencies.\n\n pub show_license_text_of: Option<SelectedLicenses>,\n\n\n\n // io(output)\n\n /// The image output path.\n\n pub output: Option<&'a str>,\n\n\n\n // config(in)\n\n pub selected_frame: FrameIndex,\n\n\n\n // config(out)\n\n /// Disable color type adjustments on save.\n", "file_path": "src/app/config.rs", "rank": 92, "score": 33551.823257448064 }, { "content": "\n\n #[test]\n\n fn jpeg_in_quality_range_upper_bound_outside() {\n\n let value: &str = \"101\";\n\n assert!(validate_jpeg_quality(u8::from_str(value).unwrap()).is_err())\n\n }\n\n\n\n #[test]\n\n fn config_builder_override_defaults() {\n\n let mut builder = ConfigBuilder::new();\n\n builder = builder.output_path(\"lalala\");\n\n builder = builder.image_operations_program(vec![Instruction::Operation(ImgOp::Blur(1.0))]);\n\n let config = builder.build();\n\n\n\n assert!(!config.image_operations_program.is_empty());\n\n assert_eq!(config.output.unwrap(), \"lalala\");\n\n }\n\n}\n", "file_path": "src/app/config.rs", "rank": 93, "score": 33551.82251448623 }, { "content": " /// Default format encoding settings.\n\n encoding_settings: FormatEncodingSettings {\n\n /// Default JPEG quality is set to 80.\n\n jpeg_quality: 80,\n\n\n\n /// Default encoding type of PNM files (excluding PAM) is set to binary.\n\n pnm_use_ascii_format: false,\n\n },\n\n\n\n /// Defaults to no provided image operations script.\n\n image_operations_program: Vec::new(),\n\n }\n\n }\n\n}\n\n\n\n/// Builder for [crate::app::config::Config]. Should be used with the Default implementation\n\n/// of [crate::app::config::Config].\n\n/// If the default trait is not used with this builder, some settings may be inaccessible.\n\n/// For example, `output_path` can be set to some value, but not unset.\n\n///\n", "file_path": "src/app/config.rs", "rank": 94, "score": 33551.49865913164 }, { "content": " Config {\n\n /// If using default, requires the `CARGO_PKG_NAME` to be set.\n\n tool_name: env!(\"CARGO_PKG_NAME\"),\n\n\n\n /// Defaults to no displayed license text.\n\n show_license_text_of: None,\n\n\n\n /// Default output path is None. The program may require an output to be set\n\n /// for most of its program behaviour.\n\n output: None,\n\n\n\n /// By default the first frame of a gif is used.\n\n selected_frame: FrameIndex::First,\n\n\n\n /// Defaults to using automatic color type adjustment where appropriate.\n\n disable_automatic_color_type_adjustment: false,\n\n\n\n /// Defaults to not forcing a specific image output format.\n\n forced_output_format: None,\n\n\n", "file_path": "src/app/config.rs", "rank": 95, "score": 33551.0989592256 }, { "content": " self\n\n }\n\n\n\n // config(out)\n\n pub fn forced_output_format(mut self, format: &'a str) -> ConfigBuilder<'a> {\n\n self.settings.forced_output_format = Some(format);\n\n self\n\n }\n\n\n\n // config(out)\n\n pub fn disable_automatic_color_type_adjustment(mut self, toggle: bool) -> ConfigBuilder<'a> {\n\n self.settings.disable_automatic_color_type_adjustment = toggle;\n\n self\n\n }\n\n\n\n // config(out)\n\n pub fn jpeg_quality(mut self, quality: u8) -> ConfigBuilder<'a> {\n\n self.settings.encoding_settings.jpeg_quality = quality;\n\n self\n\n }\n", "file_path": "src/app/config.rs", "rank": 96, "score": 33550.52721781055 }, { "content": " use sic_image_engine::ImgOp;\n\n use std::str::FromStr;\n\n\n\n #[test]\n\n fn jpeg_in_quality_range_lower_bound_inside() {\n\n let value: &str = \"1\";\n\n assert!(validate_jpeg_quality(u8::from_str(value).unwrap()).is_ok())\n\n }\n\n\n\n #[test]\n\n fn jpeg_in_quality_range_lower_bound_outside() {\n\n let value: &str = \"0\";\n\n assert!(validate_jpeg_quality(u8::from_str(value).unwrap()).is_err())\n\n }\n\n\n\n #[test]\n\n fn jpeg_in_quality_range_upper_bound_inside() {\n\n let value: &str = \"100\";\n\n assert!(validate_jpeg_quality(u8::from_str(value).unwrap()).is_ok())\n\n }\n", "file_path": "src/app/config.rs", "rank": 97, "score": 33543.02193440372 }, { "content": "/// Builder is consuming.\n\n#[derive(Debug, Default)]\n\npub struct ConfigBuilder<'a> {\n\n settings: Config<'a>,\n\n}\n\n\n\nimpl<'a> ConfigBuilder<'a> {\n\n pub fn new() -> Self {\n\n ConfigBuilder::default()\n\n }\n\n\n\n // organisational\n\n pub fn show_license_text_of(mut self, selection: SelectedLicenses) -> ConfigBuilder<'a> {\n\n self.settings.show_license_text_of = Some(selection);\n\n self\n\n }\n\n\n\n // config(in)\n\n pub fn select_frame(mut self, frame: FrameIndex) -> ConfigBuilder<'a> {\n\n self.settings.selected_frame = frame;\n", "file_path": "src/app/config.rs", "rank": 98, "score": 33539.68273881462 }, { "content": " self.settings\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub enum SelectedLicenses {\n\n ThisSoftware,\n\n Dependencies,\n\n // not optimal for combinations, but is that actually necessary?\n\n ThisSoftwarePlusDependencies,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct FormatEncodingSettings {\n\n pub jpeg_quality: u8,\n\n pub pnm_use_ascii_format: bool,\n\n}\n\n\n\n/// Strictly speaking not necessary here since the responsible owners will validate the quality as well.\n\n/// However, by doing anyways it we can exit earlier.\n", "file_path": "src/app/config.rs", "rank": 99, "score": 33538.19936995 } ]
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 v in values {\n\n let v_f32 = v.to_f32().unwrap();\n\n writer.write(&v_f32.to_ne_bytes())?;\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "splashsurf/src/io.rs", "rank": 0, "score": 334462.2767041529 }, { "content": "/// Writes particles positions to the given file path, automatically detects the file format\n\npub fn write_particle_positions<R: Real, P: AsRef<Path>>(\n\n particles: &[Vector3<R>],\n\n output_file: P,\n\n _format_params: &OutputFormatParameters,\n\n) -> Result<(), anyhow::Error> {\n\n let output_file = output_file.as_ref();\n\n info!(\n\n \"Writing {} particles to \\\"{}\\\"...\",\n\n particles.len(),\n\n output_file.display()\n\n );\n\n\n\n if let Some(extension) = output_file.extension() {\n\n profile!(\"writing particle positions\");\n\n\n\n let extension = extension\n\n .to_str()\n\n .ok_or(anyhow!(\"Invalid extension of output file\"))?;\n\n\n\n match extension.to_lowercase().as_str() {\n", "file_path": "splashsurf/src/io.rs", "rank": 4, "score": 301519.05293870217 }, { "content": "/// Loads particles positions from the given file path, automatically detects the file format\n\npub fn read_particle_positions<R: Real, P: AsRef<Path>>(\n\n input_file: P,\n\n _format_params: &InputFormatParameters,\n\n) -> Result<Vec<Vector3<R>>, anyhow::Error> {\n\n let input_file = input_file.as_ref();\n\n info!(\n\n \"Reading particle dataset from \\\"{}\\\"...\",\n\n input_file.display()\n\n );\n\n\n\n let particle_positions = if let Some(extension) = input_file.extension() {\n\n profile!(\"loading particle positions\");\n\n\n\n let extension = extension\n\n .to_str()\n\n .ok_or(anyhow!(\"Invalid extension of input file\"))?;\n\n\n\n match extension.to_lowercase().as_str() {\n\n \"vtk\" => vtk_format::particles_from_vtk(&input_file)?,\n\n \"xyz\" => xyz_format::particles_from_xyz(&input_file)?,\n", "file_path": "splashsurf/src/io.rs", "rank": 7, "score": 270321.3690290241 }, { "content": "/// Pretty print the collected profiling data of all thread local [`Profiler`]s to the given writer\n\npub fn write<W: io::Write>(out: &mut W) -> io::Result<()> {\n\n let mut merged_scopes = HashMap::<ScopeId, Scope>::new();\n\n let mut roots = HashSet::<ScopeId>::new();\n\n\n\n // Collect scopes over all threads\n\n for profiler in PROFILER.iter() {\n\n if let Ok(profiler) = profiler.read() {\n\n roots.extend(profiler.roots.iter());\n\n\n\n for (&id, scope) in &profiler.scopes {\n\n merged_scopes\n\n .entry(id)\n\n .and_modify(|s| s.merge(scope))\n\n .or_insert_with(|| scope.clone());\n\n }\n\n }\n\n }\n\n\n\n // Sort and filter root scopes\n\n let sorted_roots = {\n", "file_path": "splashsurf_lib/src/profiling.rs", "rank": 8, "score": 269416.72334364674 }, { "content": "/// Loads and parses a BGEO file to memory\n\npub fn load_bgeo_file<P: AsRef<Path>>(bgeo_file: P) -> Result<BgeoFile, anyhow::Error> {\n\n let mut buf = Vec::new();\n\n let mut is_compressed = false;\n\n\n\n // First check if the file is gzip compressed\n\n {\n\n let file = File::open(bgeo_file.as_ref()).context(\"Unable to open file for reading\")?;\n\n let mut gz = GzDecoder::new(file);\n\n if gz.header().is_some() {\n\n is_compressed = true;\n\n gz.read_to_end(&mut buf)\n\n .context(\"Error during gzip decompression\")?;\n\n }\n\n }\n\n\n\n // Otherwise just read the raw file\n\n if !is_compressed {\n\n // File has to be opened again because the Gz header check already reads parts of the file\n\n let mut file = File::open(bgeo_file).context(\"Unable to open file for reading\")?;\n\n file.read_to_end(&mut buf)\n", "file_path": "splashsurf/src/io/bgeo_format.rs", "rank": 10, "score": 263661.106030617 }, { "content": "/// Helper function that extracts vertex indices from the [`CellData`] for the triangle with the given edge indices\n\nfn get_triangle(cell_data: &CellData, edge_indices: [i32; 3]) -> Result<[usize; 3], anyhow::Error> {\n\n let [edge_idx_0, edge_idx_1, edge_idx_2] = edge_indices;\n\n\n\n Ok([\n\n cell_data\n\n .iso_surface_vertices\n\n .get(edge_idx_0 as usize)\n\n .with_context(|| \"Invalid edge index. This is a bug.\")?\n\n .with_context(|| {\n\n format!(\n\n \"Missing iso surface vertex at edge {}. This is a bug.\",\n\n edge_idx_0\n\n )\n\n })?,\n\n cell_data\n\n .iso_surface_vertices\n\n .get(edge_idx_1 as usize)\n\n .with_context(|| \"Invalid edge index. This is a bug.\")?\n\n .with_context(|| {\n\n format!(\n", "file_path": "splashsurf_lib/src/marching_cubes/triangulation.rs", "rank": 11, "score": 243664.9532511958 }, { "content": "pub fn particles_from_xyz<R: Real, P: AsRef<Path>>(\n\n xyz_file: P,\n\n) -> Result<Vec<Vector3<R>>, anyhow::Error> {\n\n let file = File::open(xyz_file).context(\"Unable to open XYZ file for reading\")?;\n\n let mut reader = BufReader::new(file);\n\n\n\n let mut buffer = [0u8; 3 * 4];\n\n\n\n let get_four_bytes = |buffer: &[u8], offset: usize| -> [u8; 4] {\n\n [\n\n buffer[offset + 0],\n\n buffer[offset + 1],\n\n buffer[offset + 2],\n\n buffer[offset + 3],\n\n ]\n\n };\n\n\n\n let mut particles = Vec::new();\n\n\n\n while let Ok(_) = reader.read_exact(&mut buffer) {\n", "file_path": "splashsurf/src/io/xyz_format.rs", "rank": 13, "score": 234936.3882609931 }, { "content": "pub fn particles_from_ply<R: Real, P: AsRef<Path>>(\n\n ply_file: P,\n\n) -> Result<Vec<Vector3<R>>, anyhow::Error> {\n\n let mut ply_file = std::fs::File::open(ply_file).unwrap();\n\n let parser = ply::parser::Parser::<ply::ply::DefaultElement>::new();\n\n\n\n let ply = parser\n\n .read_ply(&mut ply_file)\n\n .context(\"Failed to read PLY file\")?;\n\n let elements = ply\n\n .payload\n\n .get(\"vertex\")\n\n .ok_or(anyhow!(\"PLY file is missing a 'vertex' element\"))?;\n\n\n\n let particles = elements\n\n .into_iter()\n\n .map(|e| {\n\n let vertex = (\n\n e.get(\"x\").unwrap(),\n\n e.get(\"y\").unwrap(),\n", "file_path": "splashsurf/src/io/ply_format.rs", "rank": 14, "score": 234936.3882609931 }, { "content": "pub fn particles_from_bgeo<R: Real, P: AsRef<Path>>(\n\n bgeo_file: P,\n\n) -> Result<Vec<Vector3<R>>, anyhow::Error> {\n\n // Load positions from BGEO file\n\n let position_storage = {\n\n let mut bgeo_file = load_bgeo_file(bgeo_file).context(\"Error while loading BGEO file\")?;\n\n\n\n //println!(\"header: {:?}\", bgeo_file.header);\n\n //println!(\"attrs: {:?}\", bgeo_file.point_attributes);\n\n\n\n let storage = bgeo_file\n\n .points\n\n .remove(\"position\")\n\n .expect(\"Positions should always be in BGEO file\");\n\n\n\n if let AttributeStorage::Vector(dim, storage) = storage {\n\n assert_eq!(dim, 3);\n\n assert_eq!(storage.len() % dim, 0);\n\n storage\n\n } else {\n", "file_path": "splashsurf/src/io/bgeo_format.rs", "rank": 15, "score": 234936.3882609931 }, { "content": "pub fn particles_from_json<R: Real, P: AsRef<Path>>(\n\n json_file: P,\n\n) -> Result<Vec<Vector3<R>>, anyhow::Error> {\n\n let path = json_file.as_ref();\n\n let file = File::open(path).context(\"Cannot open file for JSON parsing\")?;\n\n let reader = BufReader::new(file);\n\n\n\n // Read the JSON contents of the file as an instance of `User`.\n\n let json =\n\n serde_json::from_reader(reader).context(\"Reading of file to JSON structure failed\")?;\n\n let particles = serde_json::from_value::<ParticleVecF32>(json)\n\n .context(\"Parsing of JSON structure as particle positions failed\")?;\n\n\n\n let particles = particles\n\n .into_iter()\n\n .map(|raw_particle| {\n\n Vector3::new(\n\n R::from_f32(raw_particle[0]).unwrap(),\n\n R::from_f32(raw_particle[1]).unwrap(),\n\n R::from_f32(raw_particle[2]).unwrap(),\n\n )\n\n })\n\n .collect();\n\n\n\n Ok(particles)\n\n}\n", "file_path": "splashsurf/src/io/json_format.rs", "rank": 16, "score": 234936.3882609931 }, { "content": "fn reconstruct_particles<P: AsRef<Path>>(particle_file: P) -> SurfaceReconstruction<i64, f32> {\n\n let particle_positions: &Vec<Vector3<f32>> = &particles_from_vtk(particle_file).unwrap();\n\n\n\n let particle_radius = 0.011;\n\n let compact_support_radius = 4.0 * particle_radius;\n\n let cube_size = 1.5 * particle_radius;\n\n\n\n let parameters = Parameters {\n\n particle_radius,\n\n rest_density: 1000.0,\n\n compact_support_radius: compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold: 0.6,\n\n domain_aabb: None,\n\n enable_multi_threading: true,\n\n spatial_decomposition: Some(SpatialDecompositionParameters {\n\n subdivision_criterion: SubdivisionCriterion::MaxParticleCountAuto,\n\n ghost_particle_safety_factor: None,\n\n enable_stitching: true,\n\n particle_density_computation: ParticleDensityComputationStrategy::SynchronizeSubdomains,\n\n }),\n\n };\n\n\n\n reconstruct_surface::<i64, _>(particle_positions.as_slice(), &parameters).unwrap()\n\n}\n\n\n", "file_path": "splashsurf_lib/benches/benches/bench_mesh.rs", "rank": 18, "score": 224748.4823703142 }, { "content": "/// Writes a mesh to the given file path, automatically detects the file format\n\npub fn write_mesh<R: Real, M: Mesh3d<R>, P: AsRef<Path>>(\n\n mesh: &MeshWithData<R, M>,\n\n output_file: P,\n\n _format_params: &OutputFormatParameters,\n\n) -> Result<(), anyhow::Error> {\n\n let output_file = output_file.as_ref();\n\n info!(\n\n \"Writing mesh with {} vertices and {} cells to \\\"{}\\\"...\",\n\n mesh.mesh.vertices().len(),\n\n mesh.mesh.cells().len(),\n\n output_file.display()\n\n );\n\n\n\n if let Some(extension) = output_file.extension() {\n\n profile!(\"writing mesh\");\n\n\n\n let extension = extension\n\n .to_str()\n\n .ok_or(anyhow!(\"Invalid extension of output file\"))?;\n\n\n", "file_path": "splashsurf/src/io.rs", "rank": 19, "score": 221141.22767394496 }, { "content": "#[allow(dead_code)]\n\nfn particles_to_file<P: AsRef<Path>, R: Real>(particles: Vec<Vector3<R>>, path: P) {\n\n let points = PointCloud3d { points: particles };\n\n io::vtk::write_vtk(\n\n UnstructuredGridPiece::from(&points),\n\n path.as_ref(),\n\n \"particles\",\n\n )\n\n .unwrap();\n\n}\n\n */\n\n\n", "file_path": "splashsurf_lib/tests/integration_tests/test_octree.rs", "rank": 20, "score": 209385.98950686314 }, { "content": "/// Loads a surface mesh from the given file path, automatically detects the file format\n\npub fn read_surface_mesh<R: Real, P: AsRef<Path>>(\n\n input_file: P,\n\n _format_params: &InputFormatParameters,\n\n) -> Result<MeshWithData<R, TriMesh3d<R>>, anyhow::Error> {\n\n let input_file = input_file.as_ref();\n\n info!(\"Reading mesh from \\\"{}\\\"...\", input_file.display());\n\n\n\n let mesh = if let Some(extension) = input_file.extension() {\n\n profile!(\"loading surface mesh\");\n\n\n\n let extension = extension\n\n .to_str()\n\n .ok_or(anyhow!(\"Invalid extension of input file\"))?;\n\n\n\n match extension.to_lowercase().as_str() {\n\n \"vtk\" => vtk_format::surface_mesh_from_vtk(&input_file)?,\n\n _ => {\n\n return Err(anyhow!(\n\n \"Unsupported file format extension \\\"{}\\\" for reading surface meshes\",\n\n extension\n", "file_path": "splashsurf/src/io.rs", "rank": 21, "score": 208007.35409983902 }, { "content": "#[allow(unused)]\n\n#[inline(never)]\n\nfn assert_cell_data_point_data_consistency<I: Index, R: Real>(\n\n density_map: &DensityMap<I, R>,\n\n cell_data: &MapType<I, CellData>,\n\n grid: &UniformGrid<I, R>,\n\n iso_surface_threshold: R,\n\n) {\n\n // Check for each cell that if it has a missing point value, then it is has no other\n\n // iso-surface crossing edges / vertices\n\n for (&flat_cell_index, cell_data) in cell_data {\n\n let mut has_missing_point_data = false;\n\n let mut has_point_data_above_threshold = false;\n\n\n\n let cell = grid.try_unflatten_cell_index(flat_cell_index).unwrap();\n\n for i in 0..8 {\n\n let point = cell.global_point_index_of(i).unwrap();\n\n let flat_point_index = grid.flatten_point_index(&point);\n\n if let Some(point_value) = density_map.get(flat_point_index) {\n\n if point_value > iso_surface_threshold {\n\n has_point_data_above_threshold = true;\n\n }\n", "file_path": "splashsurf_lib/src/marching_cubes.rs", "rank": 22, "score": 201009.5875281997 }, { "content": "pub fn aabb_from_points(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &particles_from_vtk(\"../data/hilbert_46843_particles.vtk\").unwrap();\n\n\n\n let mut group = c.benchmark_group(\"aabb\");\n\n group.sample_size(200);\n\n group.warm_up_time(Duration::from_secs(3));\n\n group.measurement_time(Duration::from_secs(5));\n\n\n\n group.bench_function(\"aabb_from_points\", move |b| {\n\n b.iter(|| AxisAlignedBoundingBox3d::from_points(particle_positions))\n\n });\n\n\n\n group.finish();\n\n}\n\n\n", "file_path": "splashsurf_lib/benches/benches/bench_aabb.rs", "rank": 23, "score": 196453.444071198 }, { "content": "/// Constructs the background grid for marching cubes based on the parameters supplied to the surface reconstruction\n\npub fn grid_for_reconstruction<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n particle_radius: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n domain_aabb: Option<&AxisAlignedBoundingBox3d<R>>,\n\n enable_multi_threading: bool,\n\n) -> Result<UniformGrid<I, R>, ReconstructionError<I, R>> {\n\n let domain_aabb = if let Some(domain_aabb) = domain_aabb {\n\n domain_aabb.clone()\n\n } else {\n\n profile!(\"compute minimum enclosing aabb\");\n\n\n\n let mut domain_aabb = {\n\n let mut aabb = if enable_multi_threading {\n\n AxisAlignedBoundingBox3d::par_from_points(particle_positions)\n\n } else {\n\n AxisAlignedBoundingBox3d::from_points(particle_positions)\n\n };\n\n aabb.grow_uniformly(particle_radius);\n", "file_path": "splashsurf_lib/src/lib.rs", "rank": 24, "score": 193567.07150106085 }, { "content": "pub fn aabb_from_points_par(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &particles_from_vtk(\"../data/hilbert_46843_particles.vtk\").unwrap();\n\n\n\n let mut group = c.benchmark_group(\"aabb\");\n\n group.sample_size(500);\n\n group.warm_up_time(Duration::from_secs(3));\n\n group.measurement_time(Duration::from_secs(5));\n\n\n\n group.bench_function(\"aabb_from_points_par\", move |b| {\n\n b.iter(|| AxisAlignedBoundingBox3d::par_from_points(particle_positions))\n\n });\n\n\n\n group.finish();\n\n}\n\n\n\ncriterion_group!(bench_aabb, aabb_from_points, aabb_from_points_par);\n", "file_path": "splashsurf_lib/benches/benches/bench_aabb.rs", "rank": 25, "score": 192945.6318793726 }, { "content": "#[inline(always)]\n\npub fn cubic_kernel_r_f64(r: f64, h: f64) -> f64 {\n\n let q = (2.0 * r) / h;\n\n 8.0 * cubic_function_f64(q) / (h * h * h)\n\n}\n\n\n\n/// Evaluates the cubic kernel with compact support radius `h` at the radius `r`, generic version\n", "file_path": "splashsurf_lib/src/kernel.rs", "rank": 26, "score": 191428.5732850506 }, { "content": "/// Returns the pretty printed output of the collected profiling data as a `String`\n\npub fn write_to_string() -> Result<String, Box<dyn Error>> {\n\n let mut buffer = Vec::new();\n\n write(&mut buffer)?;\n\n Ok(String::from_utf8(buffer)?)\n\n}\n\n\n", "file_path": "splashsurf_lib/src/profiling.rs", "rank": 27, "score": 186673.19319371693 }, { "content": "#[inline(never)]\n\npub fn compute_particle_densities<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n particle_neighbor_lists: &[Vec<usize>],\n\n compact_support_radius: R,\n\n particle_rest_mass: R,\n\n enable_multi_threading: bool,\n\n) -> Vec<R> {\n\n let mut densities = Vec::new();\n\n if enable_multi_threading {\n\n parallel_compute_particle_densities::<I, R>(\n\n particle_positions,\n\n particle_neighbor_lists,\n\n compact_support_radius,\n\n particle_rest_mass,\n\n &mut densities,\n\n )\n\n } else {\n\n sequential_compute_particle_densities::<I, R>(\n\n particle_positions,\n\n particle_neighbor_lists,\n\n compact_support_radius,\n\n particle_rest_mass,\n\n &mut densities,\n\n )\n\n }\n\n densities\n\n}\n\n\n\n/// Computes the individual densities of particles inplace using a standard SPH sum\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 28, "score": 186666.19610685686 }, { "content": "pub fn mesh_to_obj<R: Real, M: Mesh3d<R>, P: AsRef<Path>>(\n\n mesh: &MeshWithData<R, M>,\n\n filename: P,\n\n) -> Result<(), anyhow::Error> {\n\n let file = fs::OpenOptions::new()\n\n .read(true)\n\n .write(true)\n\n .create(true)\n\n .open(filename)\n\n .context(\"Failed to open file handle for writing OBJ file\")?;\n\n let mut writer = BufWriter::with_capacity(100000, file);\n\n\n\n let mesh = &mesh.mesh;\n\n for v in mesh.vertices() {\n\n write!(&mut writer, \"v {} {} {}\\n\", v.x, v.y, v.z)?;\n\n }\n\n\n\n for f in mesh.cells() {\n\n write!(writer, \"f\")?;\n\n f.try_for_each_vertex(|v| write!(writer, \" {}\", v + 1))?;\n\n write!(writer, \"\\n\")?;\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "splashsurf/src/io/obj_format.rs", "rank": 29, "score": 185765.05146090014 }, { "content": "#[inline(never)]\n\npub fn parallel_compute_particle_densities<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n particle_neighbor_lists: &[Vec<usize>],\n\n compact_support_radius: R,\n\n particle_rest_mass: R,\n\n particle_densities: &mut Vec<R>,\n\n) {\n\n profile!(\"parallel_compute_particle_densities\");\n\n\n\n init_density_storage(particle_densities, particle_positions.len());\n\n\n\n // Pre-compute the kernel which can be queried using squared distances\n\n let kernel = DiscreteSquaredDistanceCubicKernel::new(1000, compact_support_radius);\n\n\n\n particle_positions\n\n .par_iter()\n\n .with_min_len(8)\n\n .zip_eq(particle_neighbor_lists.par_iter())\n\n .zip_eq(particle_densities.par_iter_mut())\n\n .for_each(\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 30, "score": 183359.00060251378 }, { "content": "#[inline(never)]\n\npub fn sequential_compute_particle_densities<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n particle_neighbor_lists: &[Vec<usize>],\n\n compact_support_radius: R,\n\n particle_rest_mass: R,\n\n particle_densities: &mut Vec<R>,\n\n) {\n\n profile!(\"sequential_compute_particle_densities\");\n\n\n\n init_density_storage(particle_densities, particle_positions.len());\n\n\n\n // Pre-compute the kernel which can be queried using squared distances\n\n let kernel = DiscreteSquaredDistanceCubicKernel::new(1000, compact_support_radius);\n\n\n\n for (i, (particle_i_position, particle_i_neighbors)) in particle_positions\n\n .iter()\n\n .zip(particle_neighbor_lists.iter())\n\n .enumerate()\n\n {\n\n let mut particle_i_density = kernel.evaluate(R::zero());\n\n for particle_j_position in particle_i_neighbors.iter().map(|&j| &particle_positions[j]) {\n\n let r_squared = (particle_j_position - particle_i_position).norm_squared();\n\n particle_i_density += kernel.evaluate(r_squared);\n\n }\n\n particle_i_density *= particle_rest_mass;\n\n particle_densities[i] = particle_i_density;\n\n }\n\n}\n\n\n\n/// Computes the individual densities of particles using a standard SPH sum, multi-threaded implementation\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 31, "score": 183359.00060251378 }, { "content": "#[inline(never)]\n\npub fn compute_particle_densities_inplace<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n particle_neighbor_lists: &[Vec<usize>],\n\n compact_support_radius: R,\n\n particle_rest_mass: R,\n\n enable_multi_threading: bool,\n\n densities: &mut Vec<R>,\n\n) {\n\n if enable_multi_threading {\n\n parallel_compute_particle_densities::<I, R>(\n\n particle_positions,\n\n particle_neighbor_lists,\n\n compact_support_radius,\n\n particle_rest_mass,\n\n densities,\n\n )\n\n } else {\n\n sequential_compute_particle_densities::<I, R>(\n\n particle_positions,\n\n particle_neighbor_lists,\n\n compact_support_radius,\n\n particle_rest_mass,\n\n densities,\n\n )\n\n }\n\n}\n\n\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 32, "score": 183359.00060251378 }, { "content": "/// Initializes the global thread pool used by this library with the given parameters.\n\n///\n\n/// Initialization of the global thread pool happens exactly once.\n\n/// Therefore, if you call `initialize_thread_pool` a second time, it will return an error.\n\n/// An `Ok` result indicates that this is the first initialization of the thread pool.\n\npub fn initialize_thread_pool(num_threads: usize) -> Result<(), anyhow::Error> {\n\n rayon::ThreadPoolBuilder::new()\n\n .num_threads(num_threads)\n\n .build_global()?;\n\n Ok(())\n\n}\n\n\n\n/// Performs a marching cubes surface construction of the fluid represented by the given particle positions\n", "file_path": "splashsurf_lib/src/lib.rs", "rank": 33, "score": 180182.12008775305 }, { "content": "#[allow(dead_code)]\n\nfn octree_to_file<P: AsRef<Path>, I: Index, R: Real>(\n\n octree: &Octree<I, R>,\n\n grid: &UniformGrid<I, R>,\n\n path: P,\n\n) {\n\n let mesh = octree.hexmesh(&grid, false);\n\n io::vtk::write_vtk(mesh.to_unstructured_grid(), path.as_ref(), \"octree\").unwrap();\n\n}\n\n\n", "file_path": "splashsurf_lib/tests/integration_tests/test_octree.rs", "rank": 34, "score": 174766.11425746288 }, { "content": "fn init_density_storage<R: Real>(densities: &mut Vec<R>, new_len: usize) {\n\n // Ensure that length is correct\n\n densities.resize(new_len, R::zero());\n\n // Existing values don't have to be set to zero, as they are overwritten later anyway\n\n}\n\n\n\n/// Computes the individual densities of particles using a standard SPH sum, sequential implementation\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 35, "score": 166986.56814006777 }, { "content": "#[allow(unused)]\n\nfn check_mesh_with_cell_data<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n marching_cubes_data: &MarchingCubesInput<I>,\n\n mesh: &TriMesh3d<R>,\n\n) -> Result<(), String> {\n\n let boundary_edges = mesh.find_boundary_edges();\n\n\n\n if boundary_edges.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n let mut error_string = String::new();\n\n error_string += &format!(\"Mesh is not closed. It has {} boundary edges (edges that are connected to only one triangle):\", boundary_edges.len());\n\n for (edge, tri_idx, _) in boundary_edges {\n\n let v0 = mesh.vertices[edge[0]];\n\n let v1 = mesh.vertices[edge[1]];\n\n let center = (v0 + v1) / (R::one() + R::one());\n\n let cell = grid.enclosing_cell(&center);\n\n if let Some(cell_index) = grid.get_cell(cell) {\n\n let point_index = grid\n", "file_path": "splashsurf_lib/src/marching_cubes.rs", "rank": 36, "score": 166630.0265207243 }, { "content": "#[inline(never)]\n\nfn parallel_generate_cell_to_particle_map<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n particle_positions: &[Vector3<R>],\n\n) -> ParallelMapType<I, Vec<usize>> {\n\n profile!(\"parallel_generate_cell_to_particle_map\");\n\n let particles_per_cell = ParallelMapType::with_hasher(HashState::default());\n\n\n\n // Assign all particles to enclosing cells\n\n particle_positions\n\n .par_iter()\n\n .enumerate()\n\n .for_each(|(particle_i, particle)| {\n\n let cell_ijk = grid.enclosing_cell(particle);\n\n let cell = grid.get_cell(cell_ijk).unwrap();\n\n let flat_cell_index = grid.flatten_cell_index(&cell);\n\n\n\n particles_per_cell\n\n .entry(flat_cell_index)\n\n .or_insert_with(Vec::new)\n\n .push(particle_i);\n\n });\n\n\n\n particles_per_cell\n\n}\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 37, "score": 163215.36512401575 }, { "content": "#[inline(never)]\n\nfn sequential_generate_cell_to_particle_map<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n particle_positions: &[Vector3<R>],\n\n) -> MapType<I, Vec<usize>> {\n\n profile!(\"sequential_generate_cell_to_particle_map\");\n\n let mut particles_per_cell = new_map();\n\n\n\n // Compute average particle density for initial cell capacity\n\n let cell_dims = grid.cells_per_dim();\n\n let n_cells = cell_dims[0] * cell_dims[1] * cell_dims[2];\n\n let avg_density = particle_positions.len() / n_cells.to_usize().unwrap_or(1);\n\n\n\n // Assign all particles to enclosing cells\n\n for (particle_i, particle) in particle_positions.iter().enumerate() {\n\n let cell_ijk = grid.enclosing_cell(particle);\n\n let cell = grid.get_cell(cell_ijk).unwrap();\n\n let flat_cell_index = grid.flatten_cell_index(&cell);\n\n\n\n particles_per_cell\n\n .entry(flat_cell_index)\n\n .or_insert_with(|| Vec::with_capacity(avg_density))\n\n .push(particle_i);\n\n }\n\n\n\n particles_per_cell\n\n}\n\n\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 38, "score": 163215.36512401575 }, { "content": "pub fn subdivide_recursively_benchmark(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &particles_from_vtk(\"../data/hilbert_46843_particles.vtk\").unwrap();\n\n let particles_per_cell = 20000;\n\n\n\n let particle_radius = 0.011;\n\n let compact_support_radius = 4.0 * particle_radius;\n\n\n\n let cube_size = 1.5 * particle_radius;\n\n let grid: &UniformGrid<i64, _> = &grid_for_reconstruction(\n\n particle_positions.as_slice(),\n\n particle_radius,\n\n compact_support_radius,\n\n cube_size,\n\n None,\n\n true,\n\n )\n\n .unwrap();\n\n\n\n let mut group = c.benchmark_group(\"octree subdivision\");\n", "file_path": "splashsurf_lib/benches/benches/bench_octree.rs", "rank": 39, "score": 161754.32534754972 }, { "content": "pub fn surface_reconstruction_canyon(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &super::io::xyz::particles_from_xyz(\"../../canyon_13353401_particles.xyz\").unwrap();\n\n\n\n let particle_radius = 0.011;\n\n let compact_support_radius = 4.0 * particle_radius;\n\n let cube_size = 1.5 * particle_radius;\n\n\n\n let parameters = Parameters {\n\n particle_radius,\n\n rest_density: 1000.0,\n\n compact_support_radius: compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold: 0.6,\n\n domain_aabb: None,\n\n enable_multi_threading: true,\n\n spatial_decomposition: None,\n\n };\n\n\n\n let mut group = c.benchmark_group(\"full surface reconstruction\");\n", "file_path": "splashsurf_lib/benches/benches/bench_full.rs", "rank": 40, "score": 161754.32534754972 }, { "content": "pub fn mesh_vertex_normals(c: &mut Criterion) {\n\n //let reconstruction = reconstruct_particles(\"../../canyon_13353401_particles.vtk\");\n\n let reconstruction = reconstruct_particles(\"../data/hilbert_46843_particles.vtk\");\n\n let mesh = reconstruction.mesh();\n\n\n\n let mut group = c.benchmark_group(\"mesh\");\n\n group.sample_size(50);\n\n group.warm_up_time(Duration::from_secs(3));\n\n group.measurement_time(Duration::from_secs(10));\n\n\n\n group.bench_function(\"mesh_vertex_normals\", |b| {\n\n b.iter(|| {\n\n let normals = mesh.vertex_normals();\n\n criterion::black_box(normals)\n\n })\n\n });\n\n\n\n group.finish();\n\n}\n\n\n", "file_path": "splashsurf_lib/benches/benches/bench_mesh.rs", "rank": 41, "score": 161754.32534754972 }, { "content": "#[inline(never)]\n\npub fn reconstruct_surface<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n parameters: &Parameters<R>,\n\n) -> Result<SurfaceReconstruction<I, R>, ReconstructionError<I, R>> {\n\n let mut surface = SurfaceReconstruction::default();\n\n reconstruct_surface_inplace(particle_positions, parameters, &mut surface)?;\n\n Ok(surface)\n\n}\n\n\n", "file_path": "splashsurf_lib/src/lib.rs", "rank": 42, "score": 160961.720022109 }, { "content": "#[inline(never)]\n\npub fn search<I: Index, R: Real>(\n\n domain: &AxisAlignedBoundingBox3d<R>,\n\n particle_positions: &[Vector3<R>],\n\n search_radius: R,\n\n enable_multi_threading: bool,\n\n) -> Vec<Vec<usize>> {\n\n let mut particle_neighbor_lists = Vec::new();\n\n if enable_multi_threading {\n\n parallel_search::<I, R>(\n\n domain,\n\n particle_positions,\n\n search_radius,\n\n &mut particle_neighbor_lists,\n\n )\n\n } else {\n\n sequential_search::<I, R>(\n\n domain,\n\n particle_positions,\n\n search_radius,\n\n &mut particle_neighbor_lists,\n\n )\n\n }\n\n particle_neighbor_lists\n\n}\n\n\n\n/// Performs a neighborhood search inplace, stores the indices of all neighboring particles in the given search radius per particle in the given vector\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 43, "score": 160961.720022109 }, { "content": "pub fn surface_reconstruction_dam_break(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &particles_from_vtk(\"../data/dam_break_frame_23_24389_particles.vtk\").unwrap();\n\n\n\n let particle_radius = 0.025;\n\n let compact_support_radius = 4.0 * particle_radius;\n\n let cube_size = 0.3 * particle_radius;\n\n\n\n let parameters = Parameters {\n\n particle_radius,\n\n rest_density: 1000.0,\n\n compact_support_radius: compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold: 0.6,\n\n domain_aabb: None,\n\n enable_multi_threading: true,\n\n spatial_decomposition: None,\n\n };\n\n\n\n let mut group = c.benchmark_group(\"full surface reconstruction\");\n", "file_path": "splashsurf_lib/benches/benches/bench_full.rs", "rank": 44, "score": 159273.29129483196 }, { "content": "pub fn mesh_vertex_normals_parallel(c: &mut Criterion) {\n\n //let reconstruction = reconstruct_particles(\"../../canyon_13353401_particles.vtk\");\n\n let reconstruction = reconstruct_particles(\"../data/hilbert_46843_particles.vtk\");\n\n let mesh = reconstruction.mesh();\n\n\n\n let mut group = c.benchmark_group(\"mesh\");\n\n group.sample_size(50);\n\n group.warm_up_time(Duration::from_secs(3));\n\n group.measurement_time(Duration::from_secs(10));\n\n\n\n group.bench_function(\"mesh_vertex_normals_parallel\", |b| {\n\n b.iter(|| {\n\n let normals = mesh.par_vertex_normals();\n\n criterion::black_box(normals)\n\n })\n\n });\n\n\n\n group.finish();\n\n}\n\n\n\ncriterion_group!(\n\n bench_mesh,\n\n mesh_vertex_normals,\n\n mesh_vertex_normals_parallel\n\n);\n", "file_path": "splashsurf_lib/benches/benches/bench_mesh.rs", "rank": 45, "score": 159273.29129483196 }, { "content": "#[inline(never)]\n\npub fn sequential_search<I: Index, R: Real>(\n\n domain: &AxisAlignedBoundingBox3d<R>,\n\n particle_positions: &[Vector3<R>],\n\n search_radius: R,\n\n neighborhood_list: &mut Vec<Vec<usize>>,\n\n) {\n\n // TODO: Use ArrayStorage from femproto instead of Vec of Vecs?\n\n // FIXME: Replace unwraps?\n\n profile!(\"neighborhood_search\");\n\n\n\n assert!(\n\n search_radius > R::zero(),\n\n \"Search radius for neighborhood search has to be positive!\"\n\n );\n\n assert!(\n\n domain.is_consistent(),\n\n \"Domain for neighborhood search has to be consistent!\"\n\n );\n\n assert!(\n\n !domain.is_degenerate(),\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 46, "score": 158196.69470869476 }, { "content": "#[inline(never)]\n\npub fn search_inplace<I: Index, R: Real>(\n\n domain: &AxisAlignedBoundingBox3d<R>,\n\n particle_positions: &[Vector3<R>],\n\n search_radius: R,\n\n enable_multi_threading: bool,\n\n particle_neighbor_lists: &mut Vec<Vec<usize>>,\n\n) {\n\n if enable_multi_threading {\n\n parallel_search::<I, R>(\n\n domain,\n\n particle_positions,\n\n search_radius,\n\n particle_neighbor_lists,\n\n )\n\n } else {\n\n sequential_search::<I, R>(\n\n domain,\n\n particle_positions,\n\n search_radius,\n\n particle_neighbor_lists,\n\n )\n\n }\n\n}\n\n\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 47, "score": 158196.69470869476 }, { "content": "#[inline(never)]\n\npub fn parallel_search<I: Index, R: Real>(\n\n domain: &AxisAlignedBoundingBox3d<R>,\n\n particle_positions: &[Vector3<R>],\n\n search_radius: R,\n\n neighborhood_list: &mut Vec<Vec<usize>>,\n\n) {\n\n profile!(\"par_neighborhood_search\");\n\n\n\n assert!(\n\n search_radius > R::zero(),\n\n \"Search radius for neighborhood search has to be positive!\"\n\n );\n\n assert!(\n\n domain.is_consistent(),\n\n \"Domain for neighborhood search has to be consistent!\"\n\n );\n\n assert!(\n\n !domain.is_degenerate(),\n\n \"Domain for neighborhood search cannot be degenerate!\"\n\n );\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 48, "score": 158196.69470869476 }, { "content": "pub fn surface_reconstruction_double_dam_break(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &particles_from_vtk(\"../data/double_dam_break_frame_26_4732_particles.vtk\").unwrap();\n\n\n\n let particle_radius = 0.025;\n\n let compact_support_radius = 4.0 * particle_radius;\n\n let cube_size = 0.3 * particle_radius;\n\n\n\n let parameters = Parameters {\n\n particle_radius,\n\n rest_density: 1000.0,\n\n compact_support_radius: compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold: 0.6,\n\n domain_aabb: None,\n\n enable_multi_threading: true,\n\n spatial_decomposition: None,\n\n };\n\n\n\n let mut group = c.benchmark_group(\"full surface reconstruction\");\n", "file_path": "splashsurf_lib/benches/benches/bench_full.rs", "rank": 49, "score": 156922.11860822508 }, { "content": "/// Performs a marching cubes triangulation of a density map on the given background grid\n\npub fn triangulate_density_map<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n density_map: &DensityMap<I, R>,\n\n iso_surface_threshold: R,\n\n) -> Result<TriMesh3d<R>, MarchingCubesError> {\n\n profile!(\"triangulate_density_map\");\n\n\n\n let mut mesh = TriMesh3d::default();\n\n triangulate_density_map_append(grid, None, density_map, iso_surface_threshold, &mut mesh)?;\n\n Ok(mesh)\n\n}\n\n\n", "file_path": "splashsurf_lib/src/marching_cubes.rs", "rank": 50, "score": 155588.58763272688 }, { "content": "/// Checks the consistency of the mesh (currently only checks for holes) and returns a string with debug information in case of problems\n\npub fn check_mesh_consistency<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n mesh: &TriMesh3d<R>,\n\n) -> Result<(), String> {\n\n let boundary_edges = mesh.find_boundary_edges();\n\n\n\n if boundary_edges.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n let mut error_string = String::new();\n\n error_string += &format!(\"Mesh is not closed. It has {} boundary edges (edges that are connected to only one triangle):\", boundary_edges.len());\n\n for (edge, tri_idx, _) in boundary_edges {\n\n let v0 = mesh.vertices[edge[0]];\n\n let v1 = mesh.vertices[edge[1]];\n\n let center = (v0 + v1) / (R::one() + R::one());\n\n let cell = grid.enclosing_cell(&center);\n\n if let Some(cell_index) = grid.get_cell(cell) {\n\n let point_index = grid\n\n .get_point(*cell_index.index())\n", "file_path": "splashsurf_lib/src/marching_cubes.rs", "rank": 51, "score": 155584.38891544868 }, { "content": "/// Performs a marching cubes surface construction of the fluid represented by the given particle positions, inplace\n\npub fn reconstruct_surface_inplace<'a, I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n parameters: &Parameters<R>,\n\n output_surface: &'a mut SurfaceReconstruction<I, R>,\n\n) -> Result<(), ReconstructionError<I, R>> {\n\n // Clear the existing mesh\n\n output_surface.mesh.clear();\n\n\n\n // Initialize grid for the reconstruction\n\n output_surface.grid = grid_for_reconstruction(\n\n particle_positions,\n\n parameters.particle_radius,\n\n parameters.compact_support_radius,\n\n parameters.cube_size,\n\n parameters.domain_aabb.as_ref(),\n\n parameters.enable_multi_threading,\n\n )?;\n\n\n\n output_surface.grid.log_grid_info();\n\n\n", "file_path": "splashsurf_lib/src/lib.rs", "rank": 52, "score": 155378.50140227808 }, { "content": "pub fn surface_reconstruction_double_dam_break_inplace(c: &mut Criterion) {\n\n let particle_positions: &Vec<Vector3<f32>> =\n\n &particles_from_vtk(\"../data/double_dam_break_frame_26_4732_particles.vtk\").unwrap();\n\n\n\n let particle_radius = 0.025;\n\n let compact_support_radius = 4.0 * particle_radius;\n\n let cube_size = 0.3 * particle_radius;\n\n\n\n let parameters = Parameters {\n\n particle_radius,\n\n rest_density: 1000.0,\n\n compact_support_radius: compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold: 0.6,\n\n domain_aabb: None,\n\n enable_multi_threading: true,\n\n spatial_decomposition: None,\n\n };\n\n\n\n let mut group = c.benchmark_group(\"full surface reconstruction\");\n", "file_path": "splashsurf_lib/benches/benches/bench_full.rs", "rank": 53, "score": 154690.87157995714 }, { "content": "/// Performs a marching cubes triangulation of a density map on the given background grid, appends triangles to the given mesh\n\npub fn triangulate_density_map_append<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n subdomain: Option<&OwningSubdomainGrid<I, R>>,\n\n density_map: &DensityMap<I, R>,\n\n iso_surface_threshold: R,\n\n mesh: &mut TriMesh3d<R>,\n\n) -> Result<(), MarchingCubesError> {\n\n profile!(\"triangulate_density_map_append\");\n\n\n\n let marching_cubes_data = if let Some(subdomain) = subdomain {\n\n construct_mc_input(\n\n subdomain,\n\n &density_map,\n\n iso_surface_threshold,\n\n &mut mesh.vertices,\n\n )\n\n } else {\n\n let subdomain = DummySubdomain::new(grid);\n\n construct_mc_input(\n\n &subdomain,\n", "file_path": "splashsurf_lib/src/marching_cubes.rs", "rank": 54, "score": 153120.69150253644 }, { "content": "#[inline(never)]\n\npub fn generate_sparse_density_map<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n subdomain: Option<&OwningSubdomainGrid<I, R>>,\n\n particle_positions: &[Vector3<R>],\n\n particle_densities: &[R],\n\n active_particles: Option<&[usize]>,\n\n particle_rest_mass: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n allow_threading: bool,\n\n density_map: &mut DensityMap<I, R>,\n\n) -> Result<(), DensityMapError<R>> {\n\n trace!(\n\n \"Starting construction of sparse density map... (Input: {} particles)\",\n\n if let Some(active_particles) = active_particles {\n\n active_particles.len()\n\n } else {\n\n particle_positions.len()\n\n }\n\n );\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 55, "score": 153112.49002832675 }, { "content": "#[test]\n\nfn test_cube_local_point_coordinate_consistency() {\n\n for (local_point, coords) in CELL_LOCAL_POINT_COORDS.iter().enumerate() {\n\n let flattened = coords[0] + 2 * coords[1] + 4 * coords[2];\n\n assert_eq!(CELL_LOCAL_POINTS[flattened as usize], local_point);\n\n }\n\n}\n\n\n\n/// Maps from a local point in a cell and an axis direction originating from this point to the local edge index\n\n#[rustfmt::skip]\n\nconst CELL_LOCAL_EDGES_FROM_LOCAL_POINT: [[Option<usize>; 3]; 8] = [\n\n [Some(0), Some(3), Some(8) ], // vertex 0\n\n [None , Some(1), Some(9) ], // vertex 1\n\n [None , None , Some(10)], // vertex 2\n\n [Some(2), None , Some(11)], // vertex 3\n\n [Some(4), Some(7), None ], // vertex 4\n\n [None , Some(5), None ], // vertex 5\n\n [None , None , None ], // vertex 6\n\n [Some(6), None , None ], // vertex 7\n\n];\n\n\n", "file_path": "splashsurf_lib/src/uniform_grid.rs", "rank": 56, "score": 150807.1331419493 }, { "content": "#[inline(never)]\n\npub fn sparse_density_map_to_hex_mesh<I: Index, R: Real>(\n\n density_map: &DensityMap<I, R>,\n\n grid: &UniformGrid<I, R>,\n\n default_value: R,\n\n) -> MeshWithData<R, HexMesh3d<R>> {\n\n profile!(\"sparse_density_map_to_hex_mesh\");\n\n\n\n let mut mesh = HexMesh3d {\n\n vertices: Vec::new(),\n\n cells: Vec::new(),\n\n };\n\n let mut values = Vec::new();\n\n let mut cells = new_map();\n\n\n\n // Create vertices and cells for points with values\n\n density_map.for_each(|flat_point_index, point_value| {\n\n let point = grid.try_unflatten_point_index(flat_point_index).unwrap();\n\n let point_coords = grid.point_coordinates(&point);\n\n\n\n // Create vertex\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 57, "score": 150769.97435785912 }, { "content": "#[inline(never)]\n\npub fn sequential_generate_sparse_density_map<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n particle_positions: &[Vector3<R>],\n\n particle_densities: &[R],\n\n active_particles: Option<&[usize]>,\n\n particle_rest_mass: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n) -> Result<DensityMap<I, R>, DensityMapError<R>> {\n\n profile!(\"sequential_generate_sparse_density_map\");\n\n\n\n let mut sparse_densities = new_map();\n\n\n\n let density_map_generator = SparseDensityMapGenerator::try_new(\n\n grid,\n\n compact_support_radius,\n\n cube_size,\n\n particle_rest_mass,\n\n )?;\n\n\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 58, "score": 150769.97435785912 }, { "content": "#[inline(never)]\n\npub fn parallel_generate_sparse_density_map<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n particle_positions: &[Vector3<R>],\n\n particle_densities: &[R],\n\n active_particles: Option<&[usize]>,\n\n particle_rest_mass: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n) -> Result<DensityMap<I, R>, DensityMapError<R>> {\n\n profile!(\"parallel_generate_sparse_density_map\");\n\n\n\n // Each thread will write to its own local density map\n\n let sparse_densities: ThreadLocal<RefCell<MapType<I, R>>> = ThreadLocal::new();\n\n\n\n // Generate thread local density maps\n\n {\n\n let density_map_generator = SparseDensityMapGenerator::try_new(\n\n grid,\n\n compact_support_radius,\n\n cube_size,\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 59, "score": 150769.97435785912 }, { "content": "#[test]\n\nfn test_cube_cell_local_point_index() {\n\n let cube: CellIndex<i32> = CellIndex { index: [1, 1, 1] };\n\n\n\n assert_eq!(cube.local_point_index_of(&[1, 1, 1]), Some(0));\n\n assert_eq!(cube.local_point_index_of(&[2, 1, 1]), Some(1));\n\n assert_eq!(cube.local_point_index_of(&[2, 2, 1]), Some(2));\n\n assert_eq!(cube.local_point_index_of(&[1, 2, 1]), Some(3));\n\n assert_eq!(cube.local_point_index_of(&[1, 1, 2]), Some(4));\n\n assert_eq!(cube.local_point_index_of(&[2, 1, 2]), Some(5));\n\n assert_eq!(cube.local_point_index_of(&[2, 2, 2]), Some(6));\n\n assert_eq!(cube.local_point_index_of(&[1, 2, 2]), Some(7));\n\n assert_eq!(cube.local_point_index_of(&[0, 2, 2]), None);\n\n assert_eq!(cube.local_point_index_of(&[1, 2, 3]), None);\n\n}\n\n\n\n/// Maps from a flattened coordinate index inside of a cell to the corresponding local vertex\n\nconst CELL_LOCAL_POINTS: [usize; 8] = [0, 1, 3, 2, 4, 5, 7, 6];\n\n\n\n/// Maps from the local numbering of the cell vertices to their coordinates in the cell\n\nconst CELL_LOCAL_POINT_COORDS: [[i32; 3]; 8] = [\n\n [0, 0, 0], // vertex 0\n\n [1, 0, 0], // vertex 1\n\n [1, 1, 0], // vertex 2\n\n [0, 1, 0], // vertex 3\n\n [0, 0, 1], // vertex 4\n\n [1, 0, 1], // vertex 5\n\n [1, 1, 1], // vertex 6\n\n [0, 1, 1], // vertex 7\n\n];\n\n\n", "file_path": "splashsurf_lib/src/uniform_grid.rs", "rank": 60, "score": 150726.84895838893 }, { "content": "/// Executes the `convert` subcommand\n\npub fn convert_subcommand(cmd_args: &ConvertSubcommandArgs) -> Result<(), anyhow::Error> {\n\n // Check if file already exists\n\n overwrite_check(cmd_args)?;\n\n\n\n match (&cmd_args.input_particles, &cmd_args.input_mesh) {\n\n (Some(_), _) => convert_particles(cmd_args)?,\n\n (_, Some(_)) => convert_mesh(cmd_args)?,\n\n (_, _) => return Err(anyhow!(\n\n \"Aborting: No input file specified, either a particle or mesh input file has to be specified.\"))\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "splashsurf/src/convert.rs", "rank": 61, "score": 150634.84942000383 }, { "content": "/// Executes the `reconstruct` subcommand\n\npub fn reconstruct_subcommand(cmd_args: &ReconstructSubcommandArgs) -> Result<(), anyhow::Error> {\n\n let paths = ReconstructionRunnerPathCollection::try_from(cmd_args)\n\n .context(\"Failed parsing input file path(s) from command line\")?\n\n .collect();\n\n let args = ReconstructionRunnerArgs::try_from(cmd_args)\n\n .context(\"Failed processing parameters from command line\")?;\n\n\n\n let result = if cmd_args.parallelize_over_files.into_bool() {\n\n paths.par_iter().try_for_each(|path| {\n\n reconstruction_pipeline(path, &args)\n\n .with_context(|| {\n\n format!(\n\n \"Error while processing input file '{}' from a file sequence\",\n\n path.input_file.display()\n\n )\n\n })\n\n .map_err(|err| {\n\n // Already log the error in case there are multiple errors\n\n log_error(&err);\n\n err\n", "file_path": "splashsurf/src/reconstruction.rs", "rank": 62, "score": 150634.84942000383 }, { "content": "#[inline(never)]\n\npub fn sequential_generate_sparse_density_map_subdomain<I: Index, R: Real>(\n\n subdomain: &OwningSubdomainGrid<I, R>,\n\n particle_positions: &[Vector3<R>],\n\n particle_densities: &[R],\n\n active_particles: Option<&[usize]>,\n\n particle_rest_mass: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n density_map: &mut DensityMap<I, R>,\n\n) -> Result<(), DensityMapError<R>> {\n\n profile!(\"sequential_generate_sparse_density_map_subdomain\");\n\n\n\n let mut sparse_densities = density_map.standard_or_insert_mut();\n\n sparse_densities.clear();\n\n\n\n let density_map_generator = SparseDensityMapGenerator::try_new(\n\n &subdomain.global_grid(),\n\n compact_support_radius,\n\n cube_size,\n\n particle_rest_mass,\n", "file_path": "splashsurf_lib/src/density_map.rs", "rank": 63, "score": 148546.9427795428 }, { "content": "#[inline(always)]\n\npub fn cubic_kernel_r<R: Real>(r: R, h: R) -> R {\n\n let r = r.to_f64().unwrap();\n\n let h = h.to_f64().unwrap();\n\n\n\n R::from_f64(cubic_kernel_r_f64(r, h)).unwrap()\n\n}\n\n\n", "file_path": "splashsurf_lib/src/kernel.rs", "rank": 64, "score": 147796.99954203356 }, { "content": "#[inline(never)]\n\nfn interpolate_points_to_cell_data_generic<\n\n I: Index,\n\n R: Real,\n\n S: Subdomain<I, R>,\n\n F: DensityMapFilter<I, R, S>,\n\n>(\n\n subdomain: &S,\n\n density_map: &DensityMap<I, R>,\n\n iso_surface_threshold: R,\n\n vertices: &mut Vec<Vector3<R>>,\n\n marching_cubes_data: &mut MarchingCubesInput<I>,\n\n mut filter: F,\n\n) -> F {\n\n let grid = subdomain.global_grid();\n\n let subdomain_grid = subdomain.subdomain_grid();\n\n\n\n profile!(\"interpolate_points_to_cell_data_skip_boundary\");\n\n trace!(\"Starting interpolation of cell data for marching cubes (excluding boundary layer)... (Input: {} existing vertices)\", vertices.len());\n\n\n\n // Map from flat cell index to all data that is required per cell for the marching cubes triangulation\n", "file_path": "splashsurf_lib/src/marching_cubes/narrow_band_extraction.rs", "rank": 65, "score": 144263.8017139796 }, { "content": "/// Trait for subdomains of a global grid, providing mappings of indices between the grids\n\npub trait Subdomain<I: Index, R: Real> {\n\n /// Returns a reference to the global grid corresponding to the subdomain\n\n fn global_grid(&self) -> &UniformGrid<I, R>;\n\n /// Returns a reference to the subdomain grid\n\n fn subdomain_grid(&self) -> &UniformGrid<I, R>;\n\n /// Returns the offset of the subdomain grid relative to the global grid\n\n fn subdomain_offset(&self) -> &[I; 3];\n\n\n\n /// Returns the lower corner point index of the subdomain in the global grid\n\n fn min_point(&self) -> PointIndex<I> {\n\n self.global_grid()\n\n .get_point(self.subdomain_offset().clone())\n\n .expect(\"Invalid subdomain\")\n\n }\n\n\n\n /// Returns the upper corner point index of the subdomain in the global grid\n\n fn max_point(&self) -> PointIndex<I> {\n\n let max_point = Direction::Positive\n\n // Take `cells_per_dim` steps as this is equal to `points_per_dim - 1`\n\n .checked_apply_step_ijk(\n", "file_path": "splashsurf_lib/src/uniform_grid.rs", "rank": 66, "score": 143212.71534488685 }, { "content": "fn build_octree_par_consistency<I: Index, R: Real, P: AsRef<Path>>(\n\n file: P,\n\n parameters: TestParameters<R>,\n\n) {\n\n let particles = io::vtk::particles_from_vtk::<R, _>(file).unwrap();\n\n\n\n let grid = parameters.build_grid::<I>(particles.as_slice());\n\n\n\n let octree_seq = if parameters.compare_seq_par {\n\n let mut octree_seq = Octree::new(&grid, particles.as_slice().len());\n\n octree_seq.subdivide_recursively_margin(\n\n &grid,\n\n particles.as_slice(),\n\n parameters\n\n .max_particles_per_cell\n\n .map(|n| SubdivisionCriterion::MaxParticleCount(n))\n\n .unwrap_or(SubdivisionCriterion::MaxParticleCountAuto),\n\n parameters.margin.unwrap_or(R::zero()),\n\n false,\n\n );\n", "file_path": "splashsurf_lib/tests/integration_tests/test_octree.rs", "rank": 67, "score": 141811.05752680323 }, { "content": "/// Returns the [PointIndex] of the octree subdivision point for an [OctreeNode] with the given lower and upper points\n\nfn get_split_point<I: Index, R: Real>(\n\n grid: &UniformGrid<I, R>,\n\n lower: &PointIndex<I>,\n\n upper: &PointIndex<I>,\n\n) -> Option<PointIndex<I>> {\n\n let two = I::one() + I::one();\n\n\n\n let lower = lower.index();\n\n let upper = upper.index();\n\n\n\n let mid_indices = [\n\n (lower[0] + upper[0]) / two,\n\n (lower[1] + upper[1]) / two,\n\n (lower[2] + upper[2]) / two,\n\n ];\n\n\n\n grid.get_point(mid_indices)\n\n}\n\n\n\nmod split_criterion {\n", "file_path": "splashsurf_lib/src/octree.rs", "rank": 68, "score": 140898.28356093194 }, { "content": "#[inline(always)]\n\nfn cubic_function_f64(q: f64) -> f64 {\n\n if q < 1.0 {\n\n return ALPHA * (TWO_THIRDS - q * q + 0.5 * q * q * q);\n\n } else if q < 2.0 {\n\n let x = 2.0 - q;\n\n return ALPHA * ONE_SIXTH * x * x * x;\n\n } else {\n\n return 0.0;\n\n }\n\n}\n\n\n\n/// Evaluates the cubic kernel with compact support radius `h` at the radius `r`, `f64` version\n", "file_path": "splashsurf_lib/src/kernel.rs", "rank": 69, "score": 139901.9681070781 }, { "content": "/// Loops through all corner vertices in the given marching cubes input and updates the above/below threshold flags\n\nfn update_cell_data_threshold_flags<I: Index, R: Real, S: Subdomain<I, R>>(\n\n subdomain: &S,\n\n density_map: &DensityMap<I, R>,\n\n iso_surface_threshold: R,\n\n skip_points_above_threshold: bool,\n\n marching_cubes_input: &mut MarchingCubesInput<I>,\n\n) {\n\n // Cell corner points above the iso-surface threshold which are only surrounded by neighbors that\n\n // are also above the threshold were not marked as `corner_above_threshold = true` before, because they\n\n // don't have any adjacent edge crossing the iso-surface (and thus were never touched by the point data loop).\n\n // This can happen in a configuration where e.g. only one corner is below the threshold.\n\n //\n\n // Therefore, we have to loop over all corner points of all cells that were collected for marching cubes\n\n // and check their density value again.\n\n //\n\n // Note, that we would also have this problem if we flipped the default/initial value of corner_above_threshold\n\n // to false. In this case we could also move this into the point data loop (which might increase performance).\n\n // However, we would have to special case cells without point data, which are currently skipped.\n\n // Similarly, they have to be treated in a second pass because we don't want to initialize cells only\n\n // consisting of missing points and points below the surface.\n", "file_path": "splashsurf_lib/src/marching_cubes/narrow_band_extraction.rs", "rank": 70, "score": 139586.83949581336 }, { "content": "/// Merges boundary such that only density values and cell data in the result subdomain are part of the result\n\nfn merge_boundary_data<I: Index, R: Real>(\n\n target_subdomain: &OwningSubdomainGrid<I, R>,\n\n negative_subdomain: &OwningSubdomainGrid<I, R>,\n\n negative_data: BoundaryData<I, R>,\n\n negative_vertex_offset: Option<usize>,\n\n positive_subdomain: &OwningSubdomainGrid<I, R>,\n\n positive_data: BoundaryData<I, R>,\n\n positive_vertex_offset: Option<usize>,\n\n) -> BoundaryData<I, R> {\n\n trace!(\"Merging boundary data. Size of containers: (-) side (density map: {}, cell data map: {}), (+) side (density map: {}, cell data map: {})\", negative_data.boundary_density_map.len(), negative_data.boundary_cell_data.len(), positive_data.boundary_density_map.len(), positive_data.boundary_cell_data.len());\n\n\n\n let negative_len =\n\n negative_data.boundary_density_map.len() + negative_data.boundary_cell_data.len();\n\n let positive_len =\n\n positive_data.boundary_density_map.len() + positive_data.boundary_cell_data.len();\n\n\n\n let merged_boundary_data = if negative_len > positive_len {\n\n let merged_boundary_data = negative_data.map_to_domain(\n\n target_subdomain,\n\n negative_subdomain,\n", "file_path": "splashsurf_lib/src/marching_cubes/stitching.rs", "rank": 71, "score": 135495.046566062 }, { "content": "type ParticleVecF32 = Vec<[f32; 3]>;\n\n\n", "file_path": "splashsurf/src/io/json_format.rs", "rank": 72, "score": 134116.9086421686 }, { "content": "fn convert_particles(cmd_args: &ConvertSubcommandArgs) -> Result<(), anyhow::Error> {\n\n profile!(\"particle file conversion cli\");\n\n\n\n let io_params = io::FormatParameters::default();\n\n let input_file = cmd_args.input_particles.as_ref().unwrap();\n\n let output_file = &cmd_args.output_file;\n\n\n\n // Read particles\n\n let particle_positions: Vec<Vector3<f32>> =\n\n io::read_particle_positions(input_file.as_path(), &io_params.input).with_context(|| {\n\n format!(\n\n \"Failed to load particle positions from file \\\"{}\\\"\",\n\n input_file.as_path().display()\n\n )\n\n })?;\n\n\n\n // Filter particles by user specified domain\n\n let particle_positions = if let (Some(min), Some(max)) =\n\n (cmd_args.domain_min.clone(), cmd_args.domain_max.clone())\n\n {\n", "file_path": "splashsurf/src/convert.rs", "rank": 73, "score": 133707.03441389848 }, { "content": "/// Computes the [OwningSubdomainGrid] for the final combined domain of the two sides\n\nfn compute_stitching_result_domain<I: Index, R: Real>(\n\n stitching_axis: Axis,\n\n global_grid: &UniformGrid<I, R>,\n\n negative_subdomain: &OwningSubdomainGrid<I, R>,\n\n positive_subdomain: &OwningSubdomainGrid<I, R>,\n\n) -> OwningSubdomainGrid<I, R> {\n\n // Get the number of cells of the result domain by adding all cells in stitching direction\n\n let n_cells_per_dim = {\n\n let length_neg = negative_subdomain.subdomain_grid().cells_per_dim()[stitching_axis.dim()];\n\n let length_pos = positive_subdomain.subdomain_grid().cells_per_dim()[stitching_axis.dim()];\n\n\n\n let mut n_cells_per_dim = negative_subdomain.subdomain_grid().cells_per_dim().clone();\n\n n_cells_per_dim[stitching_axis.dim()] = length_neg + length_pos;\n\n\n\n n_cells_per_dim\n\n };\n\n\n\n // Construct the grid\n\n let subdomain_grid = UniformGrid::new(\n\n &negative_subdomain.subdomain_grid().aabb().min(),\n", "file_path": "splashsurf_lib/src/marching_cubes/stitching.rs", "rank": 74, "score": 132948.01397673954 }, { "content": "/// Allocates enough storage for the given number of particles and clears all existing neighborhood lists\n\nfn init_neighborhood_list(neighborhood_list: &mut Vec<Vec<usize>>, new_len: usize) {\n\n let old_len = neighborhood_list.len();\n\n // Reset all neighbor lists that won't be truncated\n\n for particle_list in neighborhood_list.iter_mut().take(old_len.min(new_len)) {\n\n particle_list.clear();\n\n }\n\n\n\n // Ensure that length is correct\n\n neighborhood_list.resize_with(new_len, || Vec::with_capacity(15));\n\n}\n\n\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 75, "score": 132784.35516180383 }, { "content": " #[cfg_attr(doc_cfg, doc(cfg(feature = \"vtk_extras\")))]\n\n pub trait HasVtkCellType {\n\n /// Returns the corresponding [`vtkio::model::CellType`](https://docs.rs/vtkio/0.6.*/vtkio/model/enum.CellType.html) of the cell\n\n fn vtk_cell_type() -> CellType;\n\n }\n\n\n\n #[cfg_attr(doc_cfg, doc(cfg(feature = \"vtk_extras\")))]\n\n impl HasVtkCellType for TriangleCell {\n\n fn vtk_cell_type() -> CellType {\n\n CellType::Triangle\n\n }\n\n }\n\n\n\n #[cfg_attr(doc_cfg, doc(cfg(feature = \"vtk_extras\")))]\n\n impl HasVtkCellType for HexCell {\n\n fn vtk_cell_type() -> CellType {\n\n CellType::Hexahedron\n\n }\n\n }\n\n\n\n #[cfg_attr(doc_cfg, doc(cfg(feature = \"vtk_extras\")))]\n", "file_path": "splashsurf_lib/src/mesh.rs", "rank": 76, "score": 132291.10543947818 }, { "content": "/// Extracts the triangle with the given index from the triangulation\n\nfn triangulation_to_triangle(triangulation: &[i32; 16], triangle_index: usize) -> Option<[i32; 3]> {\n\n let i = triangle_index;\n\n if triangulation[3 * i] == -1 {\n\n None\n\n } else {\n\n // Reverse the vertex index order to fix winding order (so that normals point outwards)\n\n Some([\n\n triangulation[3 * i + 2],\n\n triangulation[3 * i + 1],\n\n triangulation[3 * i + 0],\n\n ])\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(unused)]\n\nmod test_lut {\n\n use super::*;\n\n\n\n /// A dumb integer -> bit flags conversion using format!\n", "file_path": "splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs", "rank": 77, "score": 131571.9998390852 }, { "content": "/// Allocates enough storage for the given number of particles and clears all existing neighborhood lists in parallel\n\nfn par_init_neighborhood_list(neighborhood_list: &mut Vec<Vec<usize>>, new_len: usize) {\n\n let old_len = neighborhood_list.len();\n\n // Reset all neighbor lists that won't be truncated\n\n neighborhood_list\n\n .par_iter_mut()\n\n .with_min_len(8)\n\n .take(old_len.min(new_len))\n\n .for_each(|particle_list| {\n\n particle_list.clear();\n\n });\n\n\n\n // Ensure that length is correct\n\n neighborhood_list.resize_with(new_len, || Vec::with_capacity(15));\n\n}\n\n\n\n/// Performs a neighborhood search, returning the indices of all neighboring particles in the given search radius per particle, sequential implementation\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 78, "score": 130849.52249468127 }, { "content": "/// Returns a vector containing per particle how often it is a non-ghost particle in the octree\n\nfn count_non_ghost_particles<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n octree: &Octree<I, R>,\n\n) -> Vec<usize> {\n\n let mut non_ghost_particles = vec![0; particle_positions.len()];\n\n for node in octree.root().dfs_iter() {\n\n if let Some(particle_set) = node.data().particle_set() {\n\n for &idx in particle_set.particles.iter() {\n\n if node.aabb().contains_point(&particle_positions[idx]) {\n\n non_ghost_particles[idx] += 1;\n\n }\n\n }\n\n }\n\n }\n\n\n\n non_ghost_particles\n\n}\n\n\n", "file_path": "splashsurf_lib/tests/integration_tests/test_octree.rs", "rank": 79, "score": 130558.13772721609 }, { "content": "/// Asserts whether each particle has a unique octree node where it is not a ghost particle\n\nfn assert_unique_node_per_particle<I: Index, R: Real>(\n\n particle_positions: &[Vector3<R>],\n\n octree: &Octree<I, R>,\n\n) {\n\n let non_ghost_particles_counts = count_non_ghost_particles(particle_positions, octree);\n\n let no_unique_node_particles: Vec<_> = non_ghost_particles_counts\n\n .into_iter()\n\n .enumerate()\n\n .filter(|&(_, count)| count != 1)\n\n .collect();\n\n\n\n assert_eq!(\n\n no_unique_node_particles,\n\n vec![],\n\n \"There are nodes that don't have a unique octree node where they are not ghost particles!\"\n\n );\n\n}\n\n\n", "file_path": "splashsurf_lib/tests/integration_tests/test_octree.rs", "rank": 80, "score": 128322.8420864298 }, { "content": "fn write_recursively<W: io::Write>(\n\n out: &mut W,\n\n sorted_scopes: &[(ScopeId, Scope)],\n\n current: &(ScopeId, Scope),\n\n total_duration: Option<Duration>,\n\n depth: usize,\n\n) -> io::Result<()> {\n\n let (id, scope) = current;\n\n\n\n for _ in 0..depth {\n\n write!(out, \" \")?;\n\n }\n\n\n\n let duration_sum_secs = scope.duration_sum.as_secs_f64();\n\n let total_duration_secs = total_duration.map_or(duration_sum_secs, |t| t.as_secs_f64());\n\n let percent = duration_sum_secs / total_duration_secs * 100.0;\n\n\n\n writeln!(\n\n out,\n\n \"{}: {:3.2}%, {:>4.2}ms avg @ {:.2}Hz ({} {})\",\n", "file_path": "splashsurf_lib/src/profiling.rs", "rank": 81, "score": 126700.22528536963 }, { "content": "#[test]\n\nfn test_interpolate_cell_data() {\n\n use nalgebra::Vector3;\n\n let iso_surface_threshold = 0.25;\n\n //let default_value = 0.0;\n\n\n\n let mut trimesh = crate::TriMesh3d::default();\n\n let origin = Vector3::new(0.0, 0.0, 0.0);\n\n let n_cubes_per_dim = [1, 1, 1];\n\n let cube_size = 1.0;\n\n\n\n let grid = UniformGrid::<i32, f64>::new(&origin, &n_cubes_per_dim, cube_size).unwrap();\n\n\n\n assert_eq!(grid.aabb().max(), &Vector3::new(1.0, 1.0, 1.0));\n\n\n\n let mut sparse_data = new_map();\n\n\n\n let marching_cubes_data = {\n\n let subdomain = DummySubdomain::new(&grid);\n\n construct_mc_input(\n\n &subdomain,\n", "file_path": "splashsurf_lib/src/marching_cubes.rs", "rank": 82, "score": 124783.59389919802 }, { "content": "/// Resets the profiling data of all thread local [`Profiler`]s\n\n///\n\n/// Note that it should be ensure that this is called outside of any scopes. It's safe to also call\n\n/// this function from inside a scope but it can lead to inconsistent profiling data (if a new scope\n\n/// is created afterwards followed by dropping of an old scope).\n\npub fn reset() {\n\n for profiler in PROFILER.iter() {\n\n if let Ok(mut profiler) = profiler.write() {\n\n profiler.reset();\n\n }\n\n }\n\n}\n", "file_path": "splashsurf_lib/src/profiling.rs", "rank": 83, "score": 123321.11225656368 }, { "content": "/// Computes stats (avg. neighbors, histogram) of the given neighborhood list\n\npub fn compute_neigborhood_stats(neighborhood_list: &Vec<Vec<usize>>) -> NeighborhoodStats {\n\n let mut max_neighbors = 0;\n\n let mut total_neighbors = 0;\n\n let mut particles_with_neighbors = 0;\n\n let mut neighbor_histogram: Vec<usize> = vec![0; 1];\n\n\n\n for neighborhood in neighborhood_list.iter() {\n\n if !neighborhood.is_empty() {\n\n if neighbor_histogram.len() < neighborhood.len() + 1 {\n\n neighbor_histogram.resize(neighborhood.len() + 1, 0);\n\n }\n\n neighbor_histogram[neighborhood.len()] += 1;\n\n\n\n max_neighbors = max_neighbors.max(neighborhood.len());\n\n total_neighbors += neighborhood.len();\n\n particles_with_neighbors += 1;\n\n } else {\n\n neighbor_histogram[0] += 1;\n\n }\n\n }\n", "file_path": "splashsurf_lib/src/neighborhood_search.rs", "rank": 84, "score": 122041.56437309377 }, { "content": "/// Helper function that returns a formatted string to debug triangulation failures\n\nfn cell_debug_string<I: Index, R: Real, S: Subdomain<I, R>>(\n\n subdomain: &S,\n\n flat_cell_index: I,\n\n cell_data: &CellData,\n\n) -> String {\n\n let global_cell_index = subdomain\n\n .global_grid()\n\n .try_unflatten_cell_index(flat_cell_index)\n\n .expect(\"Failed to get cell index\");\n\n\n\n let point_index = subdomain\n\n .global_grid()\n\n .get_point(*global_cell_index.index())\n\n .expect(\"Unable to get point index of cell\");\n\n let cell_center = subdomain.global_grid().point_coordinates(&point_index)\n\n + &Vector3::repeat(subdomain.global_grid().cell_size().times_f64(0.5));\n\n\n\n format!(\n\n \"Unable to construct triangle for cell {:?}, with center coordinates {:?} and edge length {}.\\n{:?}\\nStitching domain: (offset: {:?}, cells_per_dim: {:?})\",\n\n global_cell_index.index(),\n\n cell_center,\n\n subdomain.global_grid().cell_size(),\n\n cell_data,\n\n subdomain.subdomain_offset(),\n\n subdomain.subdomain_grid().cells_per_dim(),\n\n )\n\n}\n", "file_path": "splashsurf_lib/src/marching_cubes/triangulation.rs", "rank": 85, "score": 121352.31040801873 }, { "content": "fn main() -> Result<(), anyhow::Error> {\n\n /*\n\n // Panic hook for easier debugging\n\n panic::set_hook(Box::new(|panic_info| {\n\n println!(\"Panic occurred: {}\", panic_info);\n\n println!(\"Add breakpoint here for debugging.\");\n\n }));\n\n */\n\n\n\n std::process::exit(match run_splashsurf() {\n\n Ok(_) => 0,\n\n Err(err) => {\n\n log_error(&err);\n\n 1\n\n }\n\n });\n\n}\n\n\n", "file_path": "splashsurf/src/main.rs", "rank": 87, "score": 119443.71132171432 }, { "content": "/// Basic functionality that is provided by all meshes of the library\n\n///\n\n/// Meshes consist of vertices and cells. Cells identify their associated vertices using indices\n\n/// into the mesh's slice of vertices.\n\npub trait Mesh3d<R: Real> {\n\n /// The cell connectivity type of the mesh\n\n type Cell: CellConnectivity;\n\n\n\n /// Returns a slice of all vertices of the mesh\n\n fn vertices(&self) -> &[Vector3<R>];\n\n /// Returns a slice of all cells of the mesh\n\n fn cells(&self) -> &[Self::Cell];\n\n}\n\n\n", "file_path": "splashsurf_lib/src/mesh.rs", "rank": 88, "score": 119327.47031215971 }, { "content": "fn run_splashsurf() -> Result<(), anyhow::Error> {\n\n let cmd_args = CommandlineArgs::from_args();\n\n\n\n let verbosity = VerbosityLevel::from(cmd_args.verbosity);\n\n let is_quiet = cmd_args.quiet;\n\n\n\n initialize_logging(verbosity, is_quiet).context(\"Failed to initialize logging\")?;\n\n log_program_info();\n\n\n\n // Delegate to subcommands\n\n match &cmd_args.subcommand {\n\n Subcommand::Reconstruct(cmd_args) => reconstruction::reconstruct_subcommand(cmd_args)?,\n\n Subcommand::Convert(cmd_args) => convert::convert_subcommand(cmd_args)?,\n\n }\n\n\n\n // Write coarse_prof stats using log::info\n\n info!(\"Timings:\");\n\n splashsurf_lib::profiling::write_to_string()\n\n .unwrap()\n\n .split(\"\\n\")\n", "file_path": "splashsurf/src/main.rs", "rank": 89, "score": 117226.28366586495 }, { "content": "/// Returns a reference into the marching cubes LUT to the case corresponding to the given vertex configuration\n\npub fn get_marching_cubes_triangulation_raw(vertices_inside: &[bool; 8]) -> &'static [i32; 16] {\n\n let index = flags_to_index(vertices_inside);\n\n &MARCHING_CUBES_TABLE[index]\n\n}\n\n\n", "file_path": "splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs", "rank": 90, "score": 114662.61099312827 }, { "content": "fn params<R: Real>(\n\n particle_radius: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n iso_surface_threshold: R,\n\n strategy: Strategy,\n\n) -> Parameters<R> {\n\n params_with_aabb(\n\n particle_radius,\n\n compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold,\n\n None,\n\n strategy,\n\n )\n\n}\n\n\n", "file_path": "splashsurf_lib/tests/integration_tests/test_full.rs", "rank": 91, "score": 112533.74929999572 }, { "content": "/// Trait that has to be implemented for types to be used as floating points values in the context of the library (e.g. for coordinates, density values)\n\npub trait Real: RealField + FromPrimitive + ToPrimitive + Debug + Default + ThreadSafe {\n\n fn try_convert<T: Real>(self) -> Option<T> {\n\n Some(T::from_f64(self.to_f64()?)?)\n\n }\n\n\n\n fn try_convert_vec_from<R, const D: usize>(vec: &SVector<R, D>) -> Option<SVector<Self, D>>\n\n where\n\n R: Real,\n\n {\n\n let mut converted = SVector::<Self, D>::zeros();\n\n for i in 0..D {\n\n converted[i] = vec[i].try_convert()?\n\n }\n\n Some(converted)\n\n }\n\n\n\n /// Converts the value to the specified [Index] type. If the value cannot be represented by the target type, `None` is returned.\n\n fn to_index<I: Index>(self) -> Option<I> {\n\n I::from_f64(self.to_f64()?)\n\n }\n", "file_path": "splashsurf_lib/src/traits.rs", "rank": 92, "score": 111088.97120397529 }, { "content": "fn params_with_aabb<R: Real>(\n\n particle_radius: R,\n\n compact_support_radius: R,\n\n cube_size: R,\n\n iso_surface_threshold: R,\n\n domain_aabb: Option<AxisAlignedBoundingBox3d<R>>,\n\n strategy: Strategy,\n\n) -> Parameters<R> {\n\n let compact_support_radius = particle_radius * compact_support_radius;\n\n let cube_size = particle_radius * cube_size;\n\n\n\n let mut parameters = Parameters {\n\n particle_radius,\n\n rest_density: R::from_f64(1000.0).unwrap(),\n\n compact_support_radius,\n\n cube_size,\n\n iso_surface_threshold,\n\n domain_aabb,\n\n enable_multi_threading: false,\n\n spatial_decomposition: None,\n", "file_path": "splashsurf_lib/tests/integration_tests/test_full.rs", "rank": 93, "score": 110693.15918998265 }, { "content": "/// Returns the marching cubes triangulation corresponding to the given vertex configuration\n\n///\n\n/// In the vertex configuration, a `true` value indicates that the given vertex is inside the\n\n/// iso-surface, i.e. above the iso-surface threshold value. The returned iterator yields\n\n/// at most 5 triangles defined by the indices of the edges of their corner vertices.\n\npub fn marching_cubes_triangulation_iter(\n\n vertices_inside: &[bool; 8],\n\n) -> impl Iterator<Item = [i32; 3]> {\n\n let triangulation = get_marching_cubes_triangulation_raw(vertices_inside);\n\n (0..5)\n\n .into_iter()\n\n .map(move |i| triangulation_to_triangle(triangulation, i))\n\n .flatten()\n\n}\n\n\n", "file_path": "splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs", "rank": 94, "score": 109528.09303000993 }, { "content": "/// Prints an anyhow error and its full error chain using the log::error macro\n\npub fn log_error(err: &anyhow::Error) {\n\n error!(\"Error occurred: {}\", err);\n\n err.chain()\n\n .skip(1)\n\n .for_each(|cause| error!(\" caused by: {}\", cause));\n\n}\n\n\n", "file_path": "splashsurf/src/main.rs", "rank": 95, "score": 109380.17310693966 }, { "content": "/// Computes the [OwningSubdomainGrid] for stitching region between the two sides that has to be triangulated\n\nfn compute_stitching_domain<I: Index, R: Real>(\n\n stitching_axis: Axis,\n\n global_grid: &UniformGrid<I, R>,\n\n negative_subdomain: &OwningSubdomainGrid<I, R>,\n\n positive_subdomain: &OwningSubdomainGrid<I, R>,\n\n) -> OwningSubdomainGrid<I, R> {\n\n // Ensure that global grids are equivalent\n\n assert_eq!(\n\n negative_subdomain.global_grid(),\n\n global_grid,\n\n \"The global grid of the two subdomains that should be stitched is not identical!\"\n\n );\n\n assert_eq!(\n\n positive_subdomain.global_grid(),\n\n global_grid,\n\n \"The global grid of the two subdomains that should be stitched is not identical!\"\n\n );\n\n\n\n // Check that the two domains actually meet\n\n {\n", "file_path": "splashsurf_lib/src/marching_cubes/stitching.rs", "rank": 96, "score": 104302.86051855367 }, { "content": "/// Returns an error if the file already exists but overwrite is disabled\n\nfn overwrite_check(cmd_args: &ConvertSubcommandArgs) -> Result<(), anyhow::Error> {\n\n if !cmd_args.overwrite {\n\n if cmd_args.output_file.exists() {\n\n return Err(anyhow!(\n\n \"Aborting: Output file \\\"{}\\\" already exists. Use overwrite flag to ignore this.\",\n\n cmd_args.output_file.display()\n\n ));\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "splashsurf/src/convert.rs", "rank": 97, "score": 103465.03279595978 }, { "content": "fn convert_mesh(cmd_args: &ConvertSubcommandArgs) -> Result<(), anyhow::Error> {\n\n profile!(\"mesh file conversion cli\");\n\n\n\n let io_params = io::FormatParameters::default();\n\n let input_file = cmd_args.input_mesh.as_ref().unwrap();\n\n let output_file = &cmd_args.output_file;\n\n\n\n // Try to load surface mesh\n\n let mesh: MeshWithData<f32, _> = io::read_surface_mesh(input_file.as_path(), &io_params.input)\n\n .with_context(|| {\n\n format!(\n\n \"Failed to load surface mesh from file \\\"{}\\\"\",\n\n input_file.as_path().display()\n\n )\n\n })?;\n\n\n\n // Write mesh\n\n io::write_mesh(&mesh, output_file.as_path(), &io_params.output)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "splashsurf/src/convert.rs", "rank": 98, "score": 103460.52383971142 }, { "content": "fn default_params<R: Real>() -> Parameters<R> {\n\n default_params_with(Strategy::Global)\n\n}\n\n\n", "file_path": "splashsurf_lib/tests/integration_tests/test_full.rs", "rank": 99, "score": 102653.19670462109 } ]
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: &mut (impl ?Sized + io::Write), args: I, cursor: u64) -> io::Result<()>\n\nwhere\n\n I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,\n\n{\n\n cmd.write_all(b\"*\")?;\n\n ::itoa::write(&mut *cmd, args.len())?;\n\n cmd.write_all(b\"\\r\\n\")?;\n\n\n\n let mut cursor_bytes = itoa::Buffer::new();\n\n for item in args {\n\n let bytes = match item {\n\n Arg::Cursor => cursor_bytes.format(cursor).as_bytes(),\n\n Arg::Simple(val) => val,\n\n };\n\n\n\n cmd.write_all(b\"$\")?;\n\n ::itoa::write(&mut *cmd, bytes.len())?;\n\n cmd.write_all(b\"\\r\\n\")?;\n\n\n\n cmd.write_all(bytes)?;\n\n cmd.write_all(b\"\\r\\n\")?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/cmd.rs", "rank": 3, "score": 162734.4534890242 }, { "content": "fn write_pipeline(rv: &mut Vec<u8>, cmds: &[Cmd], atomic: bool) {\n\n let cmds_len = cmds.iter().map(cmd_len).sum();\n\n\n\n if atomic {\n\n let multi = cmd(\"MULTI\");\n\n let exec = cmd(\"EXEC\");\n\n rv.reserve(cmd_len(&multi) + cmd_len(&exec) + cmds_len);\n\n\n\n multi.write_packed_command_preallocated(rv);\n\n for cmd in cmds {\n\n cmd.write_packed_command_preallocated(rv);\n\n }\n\n exec.write_packed_command_preallocated(rv);\n\n } else {\n\n rv.reserve(cmds_len);\n\n\n\n for cmd in cmds {\n\n cmd.write_packed_command_preallocated(rv);\n\n }\n\n }\n", "file_path": "src/cmd.rs", "rank": 4, "score": 159290.54749107646 }, { "content": "// Get slot data from connection.\n\nfn get_slots(connection: &mut Connection) -> RedisResult<Vec<Slot>> {\n\n let mut cmd = Cmd::new();\n\n cmd.arg(\"CLUSTER\").arg(\"SLOTS\");\n\n let packed_command = cmd.get_packed_command();\n\n let value = connection.req_packed_command(&packed_command)?;\n\n\n\n // Parse response.\n\n let mut result = Vec::with_capacity(2);\n\n\n\n if let Value::Bulk(items) = value {\n\n let mut iter = items.into_iter();\n\n while let Some(Value::Bulk(item)) = iter.next() {\n\n if item.len() < 3 {\n\n continue;\n\n }\n\n\n\n let start = if let Value::Int(start) = item[0] {\n\n start as u16\n\n } else {\n\n continue;\n", "file_path": "src/cluster.rs", "rank": 6, "score": 147874.11582363243 }, { "content": "fn test_error(con: &MultiplexedConnection) -> impl Future<Output = RedisResult<()>> {\n\n let mut con = con.clone();\n\n async move {\n\n redis::cmd(\"SET\")\n\n .query_async(&mut con)\n\n .map(|result| match result {\n\n Ok(()) => panic!(\"Expected redis to return an error\"),\n\n Err(_) => Ok(()),\n\n })\n\n .await\n\n }\n\n}\n\n\n", "file_path": "tests/test_async.rs", "rank": 7, "score": 142346.22946872632 }, { "content": "fn test_error(con: &MultiplexedConnection) -> impl Future<Output = RedisResult<()>> {\n\n let mut con = con.clone();\n\n async move {\n\n redis::cmd(\"SET\")\n\n .query_async(&mut con)\n\n .map(|result| match result {\n\n Ok(()) => panic!(\"Expected redis to return an error\"),\n\n Err(_) => Ok(()),\n\n })\n\n .await\n\n }\n\n}\n\n\n", "file_path": "tests/test_async_async_std.rs", "rank": 8, "score": 136334.41342169326 }, { "content": "/// Abstraction trait for redis command abstractions.\n\npub trait RedisWrite {\n\n /// Accepts a serialized redis command.\n\n fn write_arg(&mut self, arg: &[u8]);\n\n}\n\n\n\nimpl RedisWrite for Vec<Vec<u8>> {\n\n fn write_arg(&mut self, arg: &[u8]) {\n\n self.push(arg.to_owned());\n\n }\n\n}\n\n\n", "file_path": "src/types.rs", "rank": 9, "score": 135891.65147611906 }, { "content": "/// This is a pretty stupid example that demonstrates how to create a large\n\n/// set through a pipeline and how to iterate over it through implied\n\n/// cursors.\n\nfn do_show_scanning(con: &mut redis::Connection) -> redis::RedisResult<()> {\n\n // This makes a large pipeline of commands. Because the pipeline is\n\n // modified in place we can just ignore the return value upon the end\n\n // of each iteration.\n\n let mut pipe = redis::pipe();\n\n for num in 0..1000 {\n\n pipe.cmd(\"SADD\").arg(\"my_set\").arg(num).ignore();\n\n }\n\n\n\n // since we don't care about the return value of the pipeline we can\n\n // just cast it into the unit type.\n\n pipe.query(con)?;\n\n\n\n // since rust currently does not track temporaries for us, we need to\n\n // store it in a local variable.\n\n let mut cmd = redis::cmd(\"SSCAN\");\n\n cmd.arg(\"my_set\").cursor_arg(0);\n\n\n\n // as a simple exercise we just sum up the iterator. Since the fold\n\n // method carries an initial value we do not need to define the\n\n // type of the iterator, rust will figure \"int\" out for us.\n\n let sum: i32 = cmd.iter::<i32>(con)?.sum();\n\n\n\n println!(\"The sum of all numbers in the set 0-1000: {}\", sum);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/basic.rs", "rank": 10, "score": 135301.43679899647 }, { "content": "/// Demonstrates how to do an atomic increment with transaction support.\n\nfn do_atomic_increment(con: &mut redis::Connection) -> redis::RedisResult<()> {\n\n let key = \"the_key\";\n\n println!(\"Run high-level atomic increment:\");\n\n\n\n // set the initial value so we have something to test with.\n\n con.set(key, 42)?;\n\n\n\n // run the transaction block.\n\n let (new_val,): (isize,) = transaction(con, &[key], |con, pipe| {\n\n // load the old value, so we know what to increment.\n\n let val: isize = con.get(key)?;\n\n // increment\n\n pipe.set(key, val + 1).ignore().get(key).query(con)\n\n })?;\n\n\n\n // and print the result\n\n println!(\"New value: {}\", new_val);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/basic.rs", "rank": 11, "score": 135301.43679899647 }, { "content": "fn get_socket_addrs(host: &str, port: u16) -> RedisResult<SocketAddr> {\n\n let mut socket_addrs = (&host[..], port).to_socket_addrs()?;\n\n match socket_addrs.next() {\n\n Some(socket_addr) => Ok(socket_addr),\n\n None => Err(RedisError::from((\n\n ErrorKind::InvalidClientConfig,\n\n \"No address found for host\",\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "src/aio.rs", "rank": 12, "score": 132925.87248473385 }, { "content": "/// Demonstrates how to do an atomic increment in a very low level way.\n\nfn do_atomic_increment_lowlevel(con: &mut redis::Connection) -> redis::RedisResult<()> {\n\n let key = \"the_key\";\n\n println!(\"Run low-level atomic increment:\");\n\n\n\n // set the initial value so we have something to test with.\n\n redis::cmd(\"SET\").arg(key).arg(42).query(con)?;\n\n\n\n loop {\n\n // we need to start watching the key we care about, so that our\n\n // exec fails if the key changes.\n\n redis::cmd(\"WATCH\").arg(key).query(con)?;\n\n\n\n // load the old value, so we know what to increment.\n\n let val: isize = redis::cmd(\"GET\").arg(key).query(con)?;\n\n\n\n // at this point we can go into an atomic pipe (a multi block)\n\n // and set up the keys.\n\n let response: Option<(isize,)> = redis::pipe()\n\n .atomic()\n\n .cmd(\"SET\")\n", "file_path": "examples/basic.rs", "rank": 13, "score": 132862.0040490407 }, { "content": "/// Parses bytes into a redis value.\n\n///\n\n/// This is the most straightforward way to parse something into a low\n\n/// level redis value instead of having to use a whole parser.\n\npub fn parse_redis_value(bytes: &[u8]) -> RedisResult<Value> {\n\n let mut parser = Parser::new();\n\n parser.parse_value(bytes)\n\n}\n", "file_path": "src/parser.rs", "rank": 14, "score": 132049.7375595335 }, { "content": "fn test_cmd(con: &MultiplexedConnection, i: i32) -> impl Future<Output = RedisResult<()>> + Send {\n\n let mut con = con.clone();\n\n async move {\n\n let key = format!(\"key{}\", i);\n\n let key_2 = key.clone();\n\n let key2 = format!(\"key{}_2\", i);\n\n let key2_2 = key2.clone();\n\n\n\n let foo_val = format!(\"foo{}\", i);\n\n\n\n redis::cmd(\"SET\")\n\n .arg(&key[..])\n\n .arg(foo_val.as_bytes())\n\n .query_async(&mut con)\n\n .await?;\n\n redis::cmd(\"SET\")\n\n .arg(&[&key2, \"bar\"])\n\n .query_async(&mut con)\n\n .await?;\n\n redis::cmd(\"MGET\")\n\n .arg(&[&key_2, &key2_2])\n\n .query_async(&mut con)\n\n .map(|result| {\n\n assert_eq!(Ok((foo_val, b\"bar\".to_vec())), result);\n\n Ok(())\n\n })\n\n .await\n\n }\n\n}\n\n\n", "file_path": "tests/test_async.rs", "rank": 15, "score": 131179.19043797598 }, { "content": "/// A shortcut function to invoke `FromRedisValue::from_redis_value`\n\n/// to make the API slightly nicer.\n\npub fn from_redis_value<T: FromRedisValue>(v: &Value) -> RedisResult<T> {\n\n FromRedisValue::from_redis_value(v)\n\n}\n", "file_path": "src/types.rs", "rank": 16, "score": 131173.1090332047 }, { "content": "/// This function demonstrates how a return value can be coerced into a\n\n/// hashmap of tuples. This is particularly useful for responses like\n\n/// CONFIG GET or all most H functions which will return responses in\n\n/// such list of implied tuples.\n\nfn do_print_max_entry_limits(con: &mut redis::Connection) -> redis::RedisResult<()> {\n\n // since rust cannot know what format we actually want we need to be\n\n // explicit here and define the type of our response. In this case\n\n // String -> int fits all the items we query for.\n\n let config: HashMap<String, isize> = redis::cmd(\"CONFIG\")\n\n .arg(\"GET\")\n\n .arg(\"*-max-*-entries\")\n\n .query(con)?;\n\n\n\n println!(\"Max entry limits:\");\n\n\n\n println!(\n\n \" max-intset: {}\",\n\n config.get(\"set-max-intset-entries\").unwrap_or(&0)\n\n );\n\n println!(\n\n \" hash-max-ziplist: {}\",\n\n config.get(\"hash-max-ziplist-entries\").unwrap_or(&0)\n\n );\n\n println!(\n", "file_path": "examples/basic.rs", "rank": 17, "score": 130548.76875216435 }, { "content": "fn test_cmd(con: &MultiplexedConnection, i: i32) -> impl Future<Output = RedisResult<()>> + Send {\n\n let mut con = con.clone();\n\n async move {\n\n let key = format!(\"key{}\", i);\n\n let key_2 = key.clone();\n\n let key2 = format!(\"key{}_2\", i);\n\n let key2_2 = key2.clone();\n\n\n\n let foo_val = format!(\"foo{}\", i);\n\n\n\n redis::cmd(\"SET\")\n\n .arg(&key[..])\n\n .arg(foo_val.as_bytes())\n\n .query_async(&mut con)\n\n .await?;\n\n redis::cmd(\"SET\")\n\n .arg(&[&key2, \"bar\"])\n\n .query_async(&mut con)\n\n .await?;\n\n redis::cmd(\"MGET\")\n\n .arg(&[&key_2, &key2_2])\n\n .query_async(&mut con)\n\n .map(|result| {\n\n assert_eq!(Ok((foo_val, b\"bar\".to_vec())), result);\n\n Ok(())\n\n })\n\n .await\n\n }\n\n}\n\n\n", "file_path": "tests/test_async_async_std.rs", "rank": 19, "score": 125793.91123141143 }, { "content": "/// This function simplifies transaction management slightly. What it\n\n/// does is automatically watching keys and then going into a transaction\n\n/// loop util it succeeds. Once it goes through the results are\n\n/// returned.\n\n///\n\n/// To use the transaction two pieces of information are needed: a list\n\n/// of all the keys that need to be watched for modifications and a\n\n/// closure with the code that should be execute in the context of the\n\n/// transaction. The closure is invoked with a fresh pipeline in atomic\n\n/// mode. To use the transaction the function needs to return the result\n\n/// from querying the pipeline with the connection.\n\n///\n\n/// The end result of the transaction is then available as the return\n\n/// value from the function call.\n\n///\n\n/// Example:\n\n///\n\n/// ```rust,no_run\n\n/// use redis::Commands;\n\n/// # fn do_something() -> redis::RedisResult<()> {\n\n/// # let client = redis::Client::open(\"redis://127.0.0.1/\").unwrap();\n\n/// # let mut con = client.get_connection().unwrap();\n\n/// let key = \"the_key\";\n\n/// let (new_val,) : (isize,) = redis::transaction(&mut con, &[key], |con, pipe| {\n\n/// let old_val : isize = con.get(key)?;\n\n/// pipe\n\n/// .set(key, old_val + 1).ignore()\n\n/// .get(key).query(con)\n\n/// })?;\n\n/// println!(\"The incremented number is: {}\", new_val);\n\n/// # Ok(()) }\n\n/// ```\n\npub fn transaction<\n\n C: ConnectionLike,\n\n K: ToRedisArgs,\n\n T,\n\n F: FnMut(&mut C, &mut Pipeline) -> RedisResult<Option<T>>,\n\n>(\n\n con: &mut C,\n\n keys: &[K],\n\n func: F,\n\n) -> RedisResult<T> {\n\n let mut func = func;\n\n loop {\n\n cmd(\"WATCH\").arg(keys).query::<()>(con)?;\n\n let mut p = pipe();\n\n let response: Option<T> = func(con, p.atomic())?;\n\n match response {\n\n None => {\n\n continue;\n\n }\n\n Some(response) => {\n\n // make sure no watch is left in the connection, even if\n\n // someone forgot to use the pipeline.\n\n cmd(\"UNWATCH\").query::<()>(con)?;\n\n return Ok(response);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/connection.rs", "rank": 20, "score": 120399.11029976528 }, { "content": "pub fn connect(\n\n connection_info: &ConnectionInfo,\n\n timeout: Option<Duration>,\n\n) -> RedisResult<Connection> {\n\n let con = ActualConnection::new(&connection_info.addr, timeout)?;\n\n let mut rv = Connection {\n\n con,\n\n parser: Parser::new(),\n\n db: connection_info.db,\n\n pubsub: false,\n\n };\n\n\n\n if let Some(ref passwd) = connection_info.passwd {\n\n match cmd(\"AUTH\").arg(&**passwd).query::<Value>(&mut rv) {\n\n Ok(Value::Okay) => {}\n\n _ => {\n\n fail!((\n\n ErrorKind::AuthenticationFailed,\n\n \"Password authentication failed\"\n\n ));\n", "file_path": "src/connection.rs", "rank": 21, "score": 120381.76546367706 }, { "content": "#[test]\n\nfn test_use_coord_struct() {\n\n let ctx = TestContext::new();\n\n let mut con = ctx.connection();\n\n\n\n assert_eq!(\n\n con.geo_add(\n\n \"my_gis\",\n\n (Coord::lon_lat(13.361_389, 38.115_556), \"Palermo\")\n\n ),\n\n Ok(1)\n\n );\n\n\n\n let result: Vec<Coord<f64>> = con.geo_pos(\"my_gis\", \"Palermo\").unwrap();\n\n assert_eq!(result.len(), 1);\n\n\n\n assert_approx_eq!(result[0].longitude, 13.36138, 0.0001);\n\n assert_approx_eq!(result[0].latitude, 38.11555, 0.0001);\n\n}\n\n\n", "file_path": "tests/test_geospatial.rs", "rank": 22, "score": 120024.14183861922 }, { "content": "/// This function takes a redis URL string and parses it into a URL\n\n/// as used by rust-url. This is necessary as the default parser does\n\n/// not understand how redis URLs function.\n\npub fn parse_redis_url(input: &str) -> Result<url::Url, ()> {\n\n match url::Url::parse(input) {\n\n Ok(result) => match result.scheme() {\n\n \"redis\" | \"redis+tls\" | \"redis+unix\" | \"unix\" => Ok(result),\n\n _ => Err(()),\n\n },\n\n Err(_) => Err(()),\n\n }\n\n}\n\n\n\n/// Defines the connection address.\n\n///\n\n/// Not all connection addresses are supported on all platforms. For instance\n\n/// to connect to a unix socket you need to run this on an operating system\n\n/// that supports them.\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum ConnectionAddr {\n\n /// Format for this is `(host, port)`.\n\n Tcp(String, u16),\n\n /// Format for this is `(host, port)`.\n", "file_path": "src/connection.rs", "rank": 23, "score": 119142.26320966452 }, { "content": "/// Shortcut for creating a new pipeline.\n\npub fn pipe() -> Pipeline {\n\n Pipeline::new()\n\n}\n", "file_path": "src/cmd.rs", "rank": 24, "score": 113742.05006745258 }, { "content": "pub fn make_extension_error(code: &str, detail: Option<&str>) -> RedisError {\n\n RedisError {\n\n repr: ErrorRepr::ExtensionError(\n\n code.to_string(),\n\n match detail {\n\n Some(x) => x.to_string(),\n\n None => \"Unknown extension error encountered\".to_string(),\n\n },\n\n ),\n\n }\n\n}\n\n\n\n/// Library generic result type.\n\npub type RedisResult<T> = Result<T, RedisError>;\n\n\n\n/// Library generic future type.\n\n#[cfg(feature = \"aio\")]\n\npub type RedisFuture<'a, T> = futures_util::future::BoxFuture<'a, RedisResult<T>>;\n\n\n\n/// An info dictionary type.\n", "file_path": "src/types.rs", "rank": 25, "score": 112204.6693658367 }, { "content": "fn write_command_to_vec<'a, I>(cmd: &mut Vec<u8>, args: I, cursor: u64)\n\nwhere\n\n I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,\n\n{\n\n let totlen = args_len(args.clone(), cursor);\n\n\n\n cmd.reserve(totlen);\n\n\n\n write_command(cmd, args, cursor).unwrap()\n\n}\n\n\n", "file_path": "src/cmd.rs", "rank": 26, "score": 110179.69741060451 }, { "content": "#[derive(Debug)]\n\nstruct Slot {\n\n start: u16,\n\n end: u16,\n\n master: String,\n\n replicas: Vec<String>,\n\n}\n\n\n\nimpl Slot {\n\n pub fn start(&self) -> u16 {\n\n self.start\n\n }\n\n pub fn end(&self) -> u16 {\n\n self.end\n\n }\n\n pub fn master(&self) -> &str {\n\n &self.master\n\n }\n\n #[allow(dead_code)]\n\n pub fn replicas(&self) -> &Vec<String> {\n\n &self.replicas\n\n }\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 27, "score": 108793.9873775066 }, { "content": "#[cfg(unix)]\n\nstruct UnixConnection {\n\n sock: UnixStream,\n\n open: bool,\n\n}\n\n\n", "file_path": "src/connection.rs", "rank": 28, "score": 106342.65771036508 }, { "content": "struct TcpConnection {\n\n reader: TcpStream,\n\n open: bool,\n\n}\n\n\n", "file_path": "src/connection.rs", "rank": 29, "score": 106337.99314316227 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nenum RoutingInfo {\n\n AllNodes,\n\n AllMasters,\n\n Random,\n\n Slot(u16),\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 30, "score": 105996.25152149843 }, { "content": "fn bench_decode(c: &mut Criterion) {\n\n let value = Value::Bulk(vec![\n\n Value::Okay,\n\n Value::Status(\"testing\".to_string()),\n\n Value::Bulk(vec![]),\n\n Value::Nil,\n\n Value::Data(vec![b'a'; 10]),\n\n Value::Int(7512182390),\n\n ]);\n\n\n\n c.bench(\"decode\", {\n\n let mut input = Vec::new();\n\n support::encode_value(&value, &mut input).unwrap();\n\n assert_eq!(redis::parse_redis_value(&input).unwrap(), value);\n\n Benchmark::new(\"decode\", move |b| bench_decode_simple(b, &input))\n\n });\n\n}\n\n\n\ncriterion_group!(bench, bench_query, bench_encode, bench_decode);\n\ncriterion_main!(bench);\n", "file_path": "benches/bench_basic.rs", "rank": 31, "score": 105253.3708696746 }, { "content": "fn bench_query(c: &mut Criterion) {\n\n c.bench(\n\n \"query\",\n\n Benchmark::new(\"simple_getsetdel\", bench_simple_getsetdel)\n\n .with_function(\"simple_getsetdel_async\", bench_simple_getsetdel_async)\n\n .with_function(\"simple_getsetdel_pipeline\", bench_simple_getsetdel_pipeline)\n\n .with_function(\n\n \"simple_getsetdel_pipeline_precreated\",\n\n bench_simple_getsetdel_pipeline_precreated,\n\n ),\n\n );\n\n c.bench(\n\n \"query_pipeline\",\n\n Benchmark::new(\n\n \"multiplexed_async_implicit_pipeline\",\n\n bench_multiplexed_async_implicit_pipeline,\n\n )\n\n .with_function(\n\n \"multiplexed_async_long_pipeline\",\n\n bench_multiplexed_async_long_pipeline,\n\n )\n\n .with_function(\"async_long_pipeline\", bench_async_long_pipeline)\n\n .with_function(\"long_pipeline\", bench_long_pipeline)\n\n .throughput(Throughput::Elements(PIPELINE_QUERIES as u64)),\n\n );\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 32, "score": 105253.3708696746 }, { "content": "fn bench_encode(c: &mut Criterion) {\n\n c.bench(\n\n \"encode\",\n\n Benchmark::new(\"pipeline\", bench_encode_pipeline)\n\n .with_function(\"pipeline_nested\", bench_encode_pipeline_nested)\n\n .with_function(\"integer\", bench_encode_integer)\n\n .with_function(\"small\", bench_encode_small),\n\n );\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 33, "score": 105253.3708696746 }, { "content": "fn countdigits(mut v: usize) -> usize {\n\n let mut result = 1;\n\n loop {\n\n if v < 10 {\n\n return result;\n\n }\n\n if v < 100 {\n\n return result + 1;\n\n }\n\n if v < 1000 {\n\n return result + 2;\n\n }\n\n if v < 10000 {\n\n return result + 3;\n\n }\n\n\n\n v /= 10000;\n\n result += 4;\n\n }\n\n}\n\n\n", "file_path": "src/cmd.rs", "rank": 34, "score": 104843.81253773003 }, { "content": "#[cfg(feature = \"tls\")]\n\nstruct TcpTlsConnection {\n\n reader: TlsStream<TcpStream>,\n\n open: bool,\n\n}\n\n\n", "file_path": "src/connection.rs", "rank": 36, "score": 103496.81629180466 }, { "content": "fn bench_encode_small(b: &mut Bencher) {\n\n b.iter(|| {\n\n let mut cmd = redis::cmd(\"HSETX\");\n\n\n\n cmd.arg(\"ABC:1237897325302:878241asdyuxpioaswehqwu\")\n\n .arg(\"some hash key\")\n\n .arg(124757920);\n\n\n\n cmd.get_packed_command()\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 37, "score": 103024.53468979691 }, { "content": "fn bench_simple_getsetdel(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut con = client.get_connection().unwrap();\n\n\n\n b.iter(|| {\n\n let key = \"test_key\";\n\n redis::cmd(\"SET\").arg(key).arg(42).execute(&mut con);\n\n let _: isize = redis::cmd(\"GET\").arg(key).query(&mut con).unwrap();\n\n redis::cmd(\"DEL\").arg(key).execute(&mut con);\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 38, "score": 103024.53468979691 }, { "content": "fn bench_long_pipeline(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut con = client.get_connection().unwrap();\n\n\n\n let pipe = long_pipeline();\n\n\n\n b.iter(|| {\n\n let () = pipe.query(&mut con).unwrap();\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 39, "score": 103024.53468979691 }, { "content": "fn bench_encode_integer(b: &mut Bencher) {\n\n b.iter(|| {\n\n let mut pipe = redis::pipe();\n\n\n\n for _ in 0..1_000 {\n\n pipe.set(123, 45679123).ignore();\n\n }\n\n pipe.get_packed_pipeline()\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 40, "score": 103024.53468979691 }, { "content": "fn bench_encode_pipeline(b: &mut Bencher) {\n\n b.iter(|| {\n\n let mut pipe = redis::pipe();\n\n\n\n for _ in 0..1_000 {\n\n pipe.set(\"foo\", \"bar\").ignore();\n\n }\n\n pipe.get_packed_pipeline()\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 41, "score": 103024.53468979691 }, { "content": "/// Shortcut function to creating a command with a single argument.\n\n///\n\n/// The first argument of a redis command is always the name of the command\n\n/// which needs to be a string. This is the recommended way to start a\n\n/// command pipe.\n\n///\n\n/// ```rust\n\n/// redis::cmd(\"PING\");\n\n/// ```\n\npub fn cmd(name: &str) -> Cmd {\n\n let mut rv = Cmd::new();\n\n rv.arg(name);\n\n rv\n\n}\n\n\n", "file_path": "src/cmd.rs", "rank": 42, "score": 102686.1421666232 }, { "content": "fn bench_simple_getsetdel_pipeline(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut con = client.get_connection().unwrap();\n\n\n\n b.iter(|| {\n\n let key = \"test_key\";\n\n let _: (usize,) = redis::pipe()\n\n .cmd(\"SET\")\n\n .arg(key)\n\n .arg(42)\n\n .ignore()\n\n .cmd(\"GET\")\n\n .arg(key)\n\n .cmd(\"DEL\")\n\n .arg(key)\n\n .ignore()\n\n .query(&mut con)\n\n .unwrap();\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 43, "score": 100942.4229877993 }, { "content": "fn bench_async_long_pipeline(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut runtime = current_thread_runtime();\n\n let mut con = runtime.block_on(client.get_async_connection()).unwrap();\n\n\n\n let pipe = long_pipeline();\n\n\n\n b.iter(|| {\n\n let () = runtime\n\n .block_on(async { pipe.query_async(&mut con).await })\n\n .unwrap();\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 44, "score": 100942.4229877993 }, { "content": "fn bench_encode_pipeline_nested(b: &mut Bencher) {\n\n b.iter(|| {\n\n let mut pipe = redis::pipe();\n\n\n\n for _ in 0..200 {\n\n pipe.set(\n\n \"foo\",\n\n (\"bar\", 123, b\"1231279712\", &[\"test\", \"test\", \"test\"][..]),\n\n )\n\n .ignore();\n\n }\n\n pipe.get_packed_pipeline()\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 45, "score": 100942.4229877993 }, { "content": "fn bench_simple_getsetdel_async(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut runtime = current_thread_runtime();\n\n let con = client.get_async_connection();\n\n let mut con = runtime.block_on(con).unwrap();\n\n\n\n b.iter(|| {\n\n runtime\n\n .block_on(async {\n\n let key = \"test_key\";\n\n redis::cmd(\"SET\")\n\n .arg(key)\n\n .arg(42)\n\n .query_async(&mut con)\n\n .await?;\n\n let _: isize = redis::cmd(\"GET\").arg(key).query_async(&mut con).await?;\n\n redis::cmd(\"DEL\").arg(key).query_async(&mut con).await?;\n\n Ok(())\n\n })\n\n .map_err(|err: RedisError| err)\n\n .unwrap()\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 46, "score": 100942.4229877993 }, { "content": "fn bench_multiplexed_async_implicit_pipeline(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut runtime = current_thread_runtime();\n\n let con = runtime\n\n .block_on(client.get_multiplexed_tokio_connection())\n\n .unwrap();\n\n\n\n let cmds: Vec<_> = (0..PIPELINE_QUERIES)\n\n .map(|i| redis::cmd(\"SET\").arg(format!(\"foo{}\", i)).arg(i).clone())\n\n .collect();\n\n\n\n let mut connections = (0..PIPELINE_QUERIES)\n\n .map(|_| con.clone())\n\n .collect::<Vec<_>>();\n\n\n\n b.iter(|| {\n\n let () = runtime\n\n .block_on(async {\n\n cmds.iter()\n\n .zip(&mut connections)\n\n .map(|(cmd, con)| cmd.query_async(con))\n\n .collect::<stream::FuturesUnordered<_>>()\n\n .try_for_each(|()| async { Ok(()) })\n\n .await\n\n })\n\n .unwrap();\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 47, "score": 98993.00912360167 }, { "content": "fn bench_multiplexed_async_long_pipeline(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut runtime = current_thread_runtime();\n\n let mut con = runtime\n\n .block_on(client.get_multiplexed_tokio_connection())\n\n .unwrap();\n\n\n\n let pipe = long_pipeline();\n\n\n\n b.iter(|| {\n\n let () = runtime\n\n .block_on(async { pipe.query_async(&mut con).await })\n\n .unwrap();\n\n });\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 48, "score": 98993.00912360167 }, { "content": "fn bench_simple_getsetdel_pipeline_precreated(b: &mut Bencher) {\n\n let client = get_client();\n\n let mut con = client.get_connection().unwrap();\n\n let key = \"test_key\";\n\n let mut pipe = redis::pipe();\n\n pipe.cmd(\"SET\")\n\n .arg(key)\n\n .arg(42)\n\n .ignore()\n\n .cmd(\"GET\")\n\n .arg(key)\n\n .cmd(\"DEL\")\n\n .arg(key)\n\n .ignore();\n\n\n\n b.iter(|| {\n\n let _: (usize,) = pipe.query(&mut con).unwrap();\n\n });\n\n}\n\n\n\nconst PIPELINE_QUERIES: usize = 1_000;\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 49, "score": 98993.00912360167 }, { "content": "#[test]\n\nfn test_cluster_eval() {\n\n let cluster = TestClusterContext::new(3, 0);\n\n let mut con = cluster.connection();\n\n\n\n let rv = redis::cmd(\"EVAL\")\n\n .arg(\n\n r#\"\n\n redis.call(\"SET\", KEYS[1], \"1\");\n\n redis.call(\"SET\", KEYS[2], \"2\");\n\n return redis.call(\"MGET\", KEYS[1], KEYS[2]);\n\n \"#,\n\n )\n\n .arg(\"2\")\n\n .arg(\"{x}a\")\n\n .arg(\"{x}b\")\n\n .query(&mut con);\n\n\n\n assert_eq!(rv, Ok((\"1\".to_string(), \"2\".to_string())));\n\n}\n\n\n", "file_path": "tests/test_cluster.rs", "rank": 50, "score": 98479.22661407785 }, { "content": "#[test]\n\nfn test_cluster_pipeline() {\n\n let cluster = TestClusterContext::new(3, 0);\n\n let mut con = cluster.connection();\n\n\n\n let err = redis::pipe()\n\n .cmd(\"SET\")\n\n .arg(\"key_1\")\n\n .arg(42)\n\n .ignore()\n\n .query::<()>(&mut con)\n\n .unwrap_err();\n\n\n\n assert_eq!(\n\n err.to_string(),\n\n \"This connection does not support pipelining.\"\n\n );\n\n}\n", "file_path": "tests/test_cluster.rs", "rank": 51, "score": 98479.22661407785 }, { "content": "#[test]\n\n#[cfg(feature = \"script\")]\n\nfn test_cluster_script() {\n\n let cluster = TestClusterContext::new(3, 0);\n\n let mut con = cluster.connection();\n\n\n\n let script = redis::Script::new(\n\n r#\"\n\n redis.call(\"SET\", KEYS[1], \"1\");\n\n redis.call(\"SET\", KEYS[2], \"2\");\n\n return redis.call(\"MGET\", KEYS[1], KEYS[2]);\n\n \"#,\n\n );\n\n\n\n let rv = script.key(\"{x}a\").key(\"{x}b\").invoke(&mut con);\n\n assert_eq!(rv, Ok((\"1\".to_string(), \"2\".to_string())));\n\n}\n\n\n", "file_path": "tests/test_cluster.rs", "rank": 52, "score": 98479.22661407785 }, { "content": "#[test]\n\nfn test_cluster_basics() {\n\n let cluster = TestClusterContext::new(3, 0);\n\n let mut con = cluster.connection();\n\n\n\n redis::cmd(\"SET\")\n\n .arg(\"{x}key1\")\n\n .arg(b\"foo\")\n\n .execute(&mut con);\n\n redis::cmd(\"SET\").arg(&[\"{x}key2\", \"bar\"]).execute(&mut con);\n\n\n\n assert_eq!(\n\n redis::cmd(\"MGET\")\n\n .arg(&[\"{x}key1\", \"{x}key2\"])\n\n .query(&mut con),\n\n Ok((\"foo\".to_string(), b\"bar\".to_vec()))\n\n );\n\n}\n\n\n", "file_path": "tests/test_cluster.rs", "rank": 53, "score": 98479.22661407785 }, { "content": "#[cfg(not(unix))]\n\nfn url_to_unix_connection_info(_: url::Url) -> RedisResult<ConnectionInfo> {\n\n fail!((\n\n ErrorKind::InvalidClientConfig,\n\n \"Unix sockets are not available on this platform.\"\n\n ));\n\n}\n\n\n\nimpl IntoConnectionInfo for url::Url {\n\n fn into_connection_info(self) -> RedisResult<ConnectionInfo> {\n\n match self.scheme() {\n\n \"redis\" | \"redis+tls\" => url_to_tcp_connection_info(self),\n\n \"unix\" | \"redis+unix\" => url_to_unix_connection_info(self),\n\n _ => fail!((\n\n ErrorKind::InvalidClientConfig,\n\n \"URL provided is not a redis URL\"\n\n )),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/connection.rs", "rank": 54, "score": 98108.0264218847 }, { "content": "struct InFlight<O, E> {\n\n output: PipelineOutput<O, E>,\n\n response_count: usize,\n\n buffer: Vec<O>,\n\n}\n\n\n", "file_path": "src/aio.rs", "rank": 55, "score": 97662.07197710792 }, { "content": " #[cfg(feature = \"aio\")]\n\n pub trait AsyncCommands : crate::aio::ConnectionLike + Send + Sized {\n\n $(\n\n $(#[$attr])*\n\n #[inline]\n\n #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]\n\n fn $name<$lifetime, $($tyargs: $ty + Send + Sync + $lifetime,)* RV>(\n\n & $lifetime mut self\n\n $(, $argname: $argty)*\n\n ) -> crate::types::RedisFuture<'a, RV>\n\n where\n\n RV: FromRedisValue,\n\n {\n\n Box::pin(async move { ($body).query_async(self).await })\n\n }\n\n )*\n\n }\n\n\n\n /// Implements common redis commands for pipelines. Unlike the regular\n\n /// commands trait, this returns the pipeline rather than a result\n\n /// directly. Other than that it works the same however.\n", "file_path": "src/commands.rs", "rank": 56, "score": 97530.50743365627 }, { "content": "#[cfg(unix)]\n\nfn url_to_unix_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {\n\n Ok(ConnectionInfo {\n\n addr: Box::new(ConnectionAddr::Unix(unwrap_or!(\n\n url.to_file_path().ok(),\n\n fail!((ErrorKind::InvalidClientConfig, \"Missing path\"))\n\n ))),\n\n db: match url.query_pairs().find(|&(ref key, _)| key == \"db\") {\n\n Some((_, db)) => unwrap_or!(\n\n db.parse::<i64>().ok(),\n\n fail!((ErrorKind::InvalidClientConfig, \"Invalid database number\"))\n\n ),\n\n None => 0,\n\n },\n\n passwd: url.password().map(|pw| pw.to_string()),\n\n })\n\n}\n\n\n", "file_path": "src/connection.rs", "rank": 57, "score": 95660.99627294976 }, { "content": "fn url_to_tcp_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {\n\n let host = match url.host() {\n\n Some(host) => host.to_string(),\n\n None => fail!((ErrorKind::InvalidClientConfig, \"Missing hostname\")),\n\n };\n\n let port = url.port().unwrap_or(DEFAULT_PORT);\n\n let addr = if url.scheme() == \"redis+tls\" {\n\n #[cfg(feature = \"tls\")]\n\n {\n\n match url.fragment() {\n\n Some(\"insecure\") => ConnectionAddr::TcpTls {\n\n host,\n\n port,\n\n insecure: true,\n\n },\n\n Some(_) => fail!((\n\n ErrorKind::InvalidClientConfig,\n\n \"only #insecure is supported as URL fragment\"\n\n )),\n\n _ => ConnectionAddr::TcpTls {\n", "file_path": "src/connection.rs", "rank": 58, "score": 95656.33170574695 }, { "content": "/// Used to convert a value into one or multiple redis argument\n\n/// strings. Most values will produce exactly one item but in\n\n/// some cases it might make sense to produce more than one.\n\npub trait ToRedisArgs: Sized {\n\n /// This converts the value into a vector of bytes. Each item\n\n /// is a single argument. Most items generate a vector of a\n\n /// single item.\n\n ///\n\n /// The exception to this rule currently are vectors of items.\n\n fn to_redis_args(&self) -> Vec<Vec<u8>> {\n\n let mut out = Vec::new();\n\n self.write_redis_args(&mut out);\n\n out\n\n }\n\n\n\n /// This writes the value into a vector of bytes. Each item\n\n /// is a single argument. Most items generate a single item.\n\n ///\n\n /// The exception to this rule currently are vectors of items.\n\n fn write_redis_args<W>(&self, out: &mut W)\n\n where\n\n W: ?Sized + RedisWrite;\n\n\n", "file_path": "src/types.rs", "rank": 59, "score": 94885.21098344096 }, { "content": "/// This trait is used to convert a redis value into a more appropriate\n\n/// type. While a redis `Value` can represent any response that comes\n\n/// back from the redis server, usually you want to map this into something\n\n/// that works better in rust. For instance you might want to convert the\n\n/// return value into a `String` or an integer.\n\n///\n\n/// This trait is well supported throughout the library and you can\n\n/// implement it for your own types if you want.\n\n///\n\n/// In addition to what you can see from the docs, this is also implemented\n\n/// for tuples up to size 12 and for Vec<u8>.\n\npub trait FromRedisValue: Sized {\n\n /// Given a redis `Value` this attempts to convert it into the given\n\n /// destination type. If that fails because it's not compatible an\n\n /// appropriate error is generated.\n\n fn from_redis_value(v: &Value) -> RedisResult<Self>;\n\n\n\n /// Similar to `from_redis_value` but constructs a vector of objects\n\n /// from another vector of values. This primarily exists internally\n\n /// to customize the behavior for vectors of tuples.\n\n fn from_redis_values(items: &[Value]) -> RedisResult<Vec<Self>> {\n\n let mut rv = vec![];\n\n for item in items.iter() {\n\n if let Ok(val) = FromRedisValue::from_redis_value(item) {\n\n rv.push(val);\n\n }\n\n }\n\n Ok(rv)\n\n }\n\n\n\n /// This only exists internally as a workaround for the lack of\n", "file_path": "src/types.rs", "rank": 60, "score": 94885.04540389798 }, { "content": "/// An async abstraction over connections.\n\npub trait ConnectionLike: Sized {\n\n /// Sends an already encoded (packed) command into the TCP socket and\n\n /// reads the single response from it.\n\n fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, Value>;\n\n\n\n /// Sends multiple already encoded (packed) command into the TCP socket\n\n /// and reads `count` responses from it. This is used to implement\n\n /// pipelining.\n\n fn req_packed_commands<'a>(\n\n &'a mut self,\n\n cmd: &'a crate::Pipeline,\n\n offset: usize,\n\n count: usize,\n\n ) -> RedisFuture<'a, Vec<Value>>;\n\n\n\n /// Returns the database this connection is bound to. Note that this\n\n /// information might be unreliable because it's initially cached and\n\n /// also might be incorrect if the connection like object is not\n\n /// actually connected.\n\n fn get_db(&self) -> i64;\n", "file_path": "src/aio.rs", "rank": 61, "score": 94536.91687183654 }, { "content": "fn bench_decode_simple(b: &mut Bencher, input: &[u8]) {\n\n b.iter(|| redis::parse_redis_value(input).unwrap());\n\n}\n", "file_path": "benches/bench_basic.rs", "rank": 62, "score": 93759.28086154643 }, { "content": "// A single message sent through the pipeline\n\nstruct PipelineMessage<S, I, E> {\n\n input: S,\n\n output: PipelineOutput<I, E>,\n\n response_count: usize,\n\n}\n\n\n", "file_path": "src/aio.rs", "rank": 63, "score": 93065.33359586712 }, { "content": "fn encode_pipeline(cmds: &[Cmd], atomic: bool) -> Vec<u8> {\n\n let mut rv = vec![];\n\n write_pipeline(&mut rv, cmds, atomic);\n\n rv\n\n}\n\n\n", "file_path": "src/cmd.rs", "rank": 64, "score": 92458.27830571626 }, { "content": "/// Runs all the examples and propagates errors up.\n\nfn do_redis_code(url: &str) -> redis::RedisResult<()> {\n\n // general connection handling\n\n let client = redis::Client::open(url)?;\n\n let mut con = client.get_connection()?;\n\n\n\n // read some config and print it.\n\n do_print_max_entry_limits(&mut con)?;\n\n\n\n // demonstrate how scanning works.\n\n do_show_scanning(&mut con)?;\n\n\n\n // shows an atomic increment.\n\n do_atomic_increment_lowlevel(&mut con)?;\n\n do_atomic_increment(&mut con)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/basic.rs", "rank": 65, "score": 92014.9209994257 }, { "content": "/// Packs a bunch of commands into a request. This is generally a quite\n\n/// useless function as this functionality is nicely wrapped through the\n\n/// `Cmd` object, but in some cases it can be useful. The return value\n\n/// of this can then be send to the low level `ConnectionLike` methods.\n\n///\n\n/// Example:\n\n///\n\n/// ```rust\n\n/// # use redis::ToRedisArgs;\n\n/// let mut args = vec![];\n\n/// args.extend(\"SET\".to_redis_args());\n\n/// args.extend(\"my_key\".to_redis_args());\n\n/// args.extend(42.to_redis_args());\n\n/// let cmd = redis::pack_command(&args);\n\n/// assert_eq!(cmd, b\"*3\\r\\n$3\\r\\nSET\\r\\n$6\\r\\nmy_key\\r\\n$2\\r\\n42\\r\\n\".to_vec());\n\n/// ```\n\npub fn pack_command(args: &[Vec<u8>]) -> Vec<u8> {\n\n encode_command(args.iter().map(|x| Arg::Simple(&x[..])), 0)\n\n}\n\n\n", "file_path": "src/cmd.rs", "rank": 66, "score": 91844.79549207618 }, { "content": "#[test]\n\nfn test_bool() {\n\n use redis::{ErrorKind, FromRedisValue, Value};\n\n\n\n let v = FromRedisValue::from_redis_value(&Value::Status(\"1\".into()));\n\n assert_eq!(v, Ok(true));\n\n\n\n let v = FromRedisValue::from_redis_value(&Value::Status(\"0\".into()));\n\n assert_eq!(v, Ok(false));\n\n\n\n let v: Result<bool, _> = FromRedisValue::from_redis_value(&Value::Status(\"garbage\".into()));\n\n assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);\n\n\n\n let v = FromRedisValue::from_redis_value(&Value::Okay);\n\n assert_eq!(v, Ok(true));\n\n\n\n let v = FromRedisValue::from_redis_value(&Value::Nil);\n\n assert_eq!(v, Ok(false));\n\n\n\n let v = FromRedisValue::from_redis_value(&Value::Int(0));\n\n assert_eq!(v, Ok(false));\n\n\n\n let v = FromRedisValue::from_redis_value(&Value::Int(42));\n\n assert_eq!(v, Ok(true));\n\n}\n\n\n", "file_path": "tests/test_types.rs", "rank": 67, "score": 91507.37660372918 }, { "content": "#[cfg(not(feature = \"geospatial\"))]\n\nfn run() -> RedisResult<()> {\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/geospatial.rs", "rank": 68, "score": 89323.16151520041 }, { "content": "fn get_random_connection<'a>(\n\n connections: &'a mut HashMap<String, Connection>,\n\n excludes: Option<&'a HashSet<String>>,\n\n) -> (String, &'a mut Connection) {\n\n let mut rng = thread_rng();\n\n let addr = match excludes {\n\n Some(excludes) if excludes.len() < connections.len() => connections\n\n .keys()\n\n .filter(|key| !excludes.contains(*key))\n\n .choose(&mut rng)\n\n .unwrap()\n\n .to_string(),\n\n _ => connections.keys().choose(&mut rng).unwrap().to_string(),\n\n };\n\n\n\n let con = connections.get_mut(&addr).unwrap();\n\n (addr, con)\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 69, "score": 89086.10872928669 }, { "content": "#[test]\n\nfn test_redis_server_down() {\n\n let mut ctx = TestContext::new();\n\n let mut con = ctx.connection();\n\n\n\n let ping = redis::cmd(\"PING\").query::<String>(&mut con);\n\n assert_eq!(ping, Ok(\"PONG\".into()));\n\n\n\n ctx.stop_server();\n\n\n\n let ping = redis::cmd(\"PING\").query::<String>(&mut con);\n\n\n\n assert_eq!(ping.is_err(), true);\n\n assert_eq!(con.is_open(), false);\n\n}\n", "file_path": "tests/test_basic.rs", "rank": 70, "score": 88613.21868859115 }, { "content": "#[test]\n\nfn test_parse_redis_url() {\n\n let redis_url = \"redis://127.0.0.1:1234/0\".to_string();\n\n redis::parse_redis_url(&redis_url).unwrap();\n\n redis::parse_redis_url(\"unix:/var/run/redis/redis.sock\").unwrap();\n\n assert!(redis::parse_redis_url(\"127.0.0.1\").is_err());\n\n}\n\n\n", "file_path": "tests/test_basic.rs", "rank": 71, "score": 86224.6423830004 }, { "content": "#[test]\n\nfn test_types_to_redis_args() {\n\n use redis::ToRedisArgs;\n\n use std::collections::BTreeMap;\n\n use std::collections::BTreeSet;\n\n use std::collections::HashSet;\n\n\n\n assert!(!5i32.to_redis_args().is_empty());\n\n assert!(!\"abc\".to_redis_args().is_empty());\n\n assert!(!\"abc\".to_redis_args().is_empty());\n\n assert!(!String::from(\"x\").to_redis_args().is_empty());\n\n\n\n assert!(![5, 4]\n\n .iter()\n\n .cloned()\n\n .collect::<HashSet<_>>()\n\n .to_redis_args()\n\n .is_empty());\n\n\n\n assert!(![5, 4]\n\n .iter()\n", "file_path": "tests/test_types.rs", "rank": 72, "score": 86224.6423830004 }, { "content": "fn connect<T: IntoConnectionInfo>(\n\n info: T,\n\n readonly: bool,\n\n password: Option<String>,\n\n) -> RedisResult<Connection>\n\nwhere\n\n T: std::fmt::Debug,\n\n{\n\n let mut connection_info = info.into_connection_info()?;\n\n connection_info.passwd = password;\n\n let client = super::Client::open(connection_info)?;\n\n\n\n let mut con = client.get_connection()?;\n\n if readonly {\n\n cmd(\"READONLY\").query(&mut con)?;\n\n }\n\n Ok(con)\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 73, "score": 84970.35039760376 }, { "content": "fn get_client() -> redis::Client {\n\n redis::Client::open(\"redis://127.0.0.1:6379\").unwrap()\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 74, "score": 82810.16939054891 }, { "content": "fn long_pipeline() -> redis::Pipeline {\n\n let mut pipe = redis::pipe();\n\n\n\n for i in 0..PIPELINE_QUERIES {\n\n pipe.set(format!(\"foo{}\", i), \"bar\").ignore();\n\n }\n\n pipe\n\n}\n\n\n", "file_path": "benches/bench_basic.rs", "rank": 75, "score": 82810.16939054891 }, { "content": "fn arbitrary_value<G: ::quickcheck::Gen>(g: &mut G, recursive_size: usize) -> Value {\n\n use quickcheck::Arbitrary;\n\n if recursive_size == 0 {\n\n Value::Nil\n\n } else {\n\n match g.gen_range(0, 6) {\n\n 0 => Value::Nil,\n\n 1 => Value::Int(Arbitrary::arbitrary(g)),\n\n 2 => Value::Data(Arbitrary::arbitrary(g)),\n\n 3 => {\n\n let size = {\n\n let s = g.size();\n\n g.gen_range(0, s)\n\n };\n\n Value::Bulk(\n\n (0..size)\n\n .map(|_| arbitrary_value(g, recursive_size / size))\n\n .collect(),\n\n )\n\n }\n", "file_path": "tests/parser.rs", "rank": 76, "score": 81395.64451103586 }, { "content": "fn get_hashtag(key: &[u8]) -> Option<&[u8]> {\n\n let open = key.iter().position(|v| *v == b'{');\n\n let open = match open {\n\n Some(open) => open,\n\n None => return None,\n\n };\n\n\n\n let close = key[open..].iter().position(|v| *v == b'}');\n\n let close = match close {\n\n Some(close) => close,\n\n None => return None,\n\n };\n\n\n\n let rv = &key[open + 1..open + close];\n\n if rv.is_empty() {\n\n None\n\n } else {\n\n Some(rv)\n\n }\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 77, "score": 77918.91871369735 }, { "content": "fn get_arg(values: &[Value], idx: usize) -> Option<&[u8]> {\n\n match values.get(idx) {\n\n Some(Value::Data(ref data)) => Some(&data[..]),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 78, "score": 72059.36190423758 }, { "content": "/// Wrapper around a `Stream + Sink` where each item sent through the `Sink` results in one or more\n\n/// items being output by the `Stream` (the number is specified at time of sending). With the\n\n/// interface provided by `Pipeline` an easy interface of request to response, hiding the `Stream`\n\n/// and `Sink`.\n\nstruct Pipeline<SinkItem, I, E>(mpsc::Sender<PipelineMessage<SinkItem, I, E>>);\n\n\n\nimpl<SinkItem, I, E> Clone for Pipeline<SinkItem, I, E> {\n\n fn clone(&self) -> Self {\n\n Pipeline(self.0.clone())\n\n }\n\n}\n\n\n\npin_project! {\n\n struct PipelineSink<T, I, E> {\n\n #[pin]\n\n sink_stream: T,\n\n in_flight: VecDeque<InFlight<I, E>>,\n\n error: Option<E>,\n\n }\n\n}\n\n\n\nimpl<T, I, E> PipelineSink<T, I, E>\n\nwhere\n\n T: Stream<Item = Result<I, E>> + 'static,\n", "file_path": "src/aio.rs", "rank": 79, "score": 71475.14520994065 }, { "content": "fn get_u64_arg(values: &[Value], idx: usize) -> Option<u64> {\n\n get_arg(values, idx)\n\n .and_then(|x| std::str::from_utf8(x).ok())\n\n .and_then(|x| x.parse().ok())\n\n}\n\n\n\nimpl RoutingInfo {\n\n pub fn for_packed_command(cmd: &[u8]) -> Option<RoutingInfo> {\n\n parse_redis_value(cmd).ok().and_then(RoutingInfo::for_value)\n\n }\n\n\n\n pub fn for_value(value: Value) -> Option<RoutingInfo> {\n\n let args = match value {\n\n Value::Bulk(args) => args,\n\n _ => return None,\n\n };\n\n\n\n match &get_command_arg(&args, 0)?[..] {\n\n b\"FLUSHALL\" | b\"FLUSHDB\" | b\"SCRIPT\" => Some(RoutingInfo::AllMasters),\n\n b\"ECHO\" | b\"CONFIG\" | b\"CLIENT\" | b\"SLOWLOG\" | b\"DBSIZE\" | b\"LASTSAVE\" | b\"PING\"\n", "file_path": "src/cluster.rs", "rank": 80, "score": 70238.84639947915 }, { "content": "/// The PubSub trait allows subscribing to one or more channels\n\n/// and receiving a callback whenever a message arrives.\n\n///\n\n/// Each method handles subscribing to the list of keys, waiting for\n\n/// messages, and unsubscribing from the same list of channels once\n\n/// a ControlFlow::Break is encountered.\n\n///\n\n/// Once (p)subscribe returns Ok(U), the connection is again safe to use\n\n/// for calling other methods.\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust,no_run\n\n/// # fn do_something() -> redis::RedisResult<()> {\n\n/// use redis::{PubSubCommands, ControlFlow};\n\n/// let client = redis::Client::open(\"redis://127.0.0.1/\")?;\n\n/// let mut con = client.get_connection()?;\n\n/// let mut count = 0;\n\n/// con.subscribe(&[\"foo\"], |msg| {\n\n/// // do something with message\n\n/// assert_eq!(msg.get_channel(), Ok(String::from(\"foo\")));\n\n///\n\n/// // increment messages seen counter\n\n/// count += 1;\n\n/// match count {\n\n/// // stop after receiving 10 messages\n\n/// 10 => ControlFlow::Break(()),\n\n/// _ => ControlFlow::Continue,\n\n/// }\n\n/// });\n\n/// # Ok(()) }\n\n/// ```\n\n// TODO In the future, it would be nice to implement Try such that `?` will work\n\n// within the closure.\n\npub trait PubSubCommands: Sized {\n\n /// Subscribe to a list of channels using SUBSCRIBE and run the provided\n\n /// closure for each message received.\n\n ///\n\n /// For every `Msg` passed to the provided closure, either\n\n /// `ControlFlow::Break` or `ControlFlow::Continue` must be returned. This\n\n /// method will not return until `ControlFlow::Break` is observed.\n\n fn subscribe<C, F, U>(&mut self, _: C, _: F) -> RedisResult<U>\n\n where F: FnMut(Msg) -> ControlFlow<U>,\n\n C: ToRedisArgs;\n\n\n\n /// Subscribe to a list of channels using PSUBSCRIBE and run the provided\n\n /// closure for each message received.\n\n ///\n\n /// For every `Msg` passed to the provided closure, either\n\n /// `ControlFlow::Break` or `ControlFlow::Continue` must be returned. This\n\n /// method will not return until `ControlFlow::Break` is observed.\n\n fn psubscribe<P, F, U>(&mut self, _: P, _: F) -> RedisResult<U>\n\n where F: FnMut(Msg) -> ControlFlow<U>,\n\n P: ToRedisArgs;\n", "file_path": "src/commands.rs", "rank": 81, "score": 69611.98858663907 }, { "content": "#[derive(Debug)]\n\nenum ErrorRepr {\n\n WithDescription(ErrorKind, &'static str),\n\n WithDescriptionAndDetail(ErrorKind, &'static str, String),\n\n ExtensionError(String, String),\n\n IoError(io::Error),\n\n}\n\n\n\nimpl PartialEq for RedisError {\n\n fn eq(&self, other: &RedisError) -> bool {\n\n match (&self.repr, &other.repr) {\n\n (&ErrorRepr::WithDescription(kind_a, _), &ErrorRepr::WithDescription(kind_b, _)) => {\n\n kind_a == kind_b\n\n }\n\n (\n\n &ErrorRepr::WithDescriptionAndDetail(kind_a, _, _),\n\n &ErrorRepr::WithDescriptionAndDetail(kind_b, _, _),\n\n ) => kind_a == kind_b,\n\n (&ErrorRepr::ExtensionError(ref a, _), &ErrorRepr::ExtensionError(ref b, _)) => {\n\n *a == *b\n\n }\n", "file_path": "src/types.rs", "rank": 82, "score": 69072.93459090317 }, { "content": "enum ActualConnection {\n\n Tcp(TcpConnection),\n\n #[cfg(feature = \"tls\")]\n\n TcpTls(TcpTlsConnection),\n\n #[cfg(unix)]\n\n Unix(UnixConnection),\n\n}\n\n\n\n/// Represents a stateful redis TCP connection.\n\npub struct Connection {\n\n con: ActualConnection,\n\n parser: Parser,\n\n db: i64,\n\n\n\n /// Flag indicating whether the connection was left in the PubSub state after dropping `PubSub`.\n\n ///\n\n /// This flag is checked when attempting to send a command, and if it's raised, we attempt to\n\n /// exit the pubsub state before executing the new request.\n\n pubsub: bool,\n\n}\n", "file_path": "src/connection.rs", "rank": 83, "score": 69072.93459090317 }, { "content": "fn get_command_arg(values: &[Value], idx: usize) -> Option<Vec<u8>> {\n\n get_arg(values, idx).map(|x| x.to_ascii_uppercase())\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 84, "score": 67765.1138354403 }, { "content": "enum Mode {\n\n Default,\n\n Multiplexed,\n\n Reconnect,\n\n}\n\n\n\nasync fn run_single<C: ConnectionLike>(mut con: C) -> RedisResult<()> {\n\n let mut interval = interval(Duration::from_millis(100));\n\n loop {\n\n interval.tick().await;\n\n println!();\n\n println!(\"> PING\");\n\n let result: RedisResult<String> = redis::cmd(\"PING\").query_async(&mut con).await;\n\n println!(\"< {:?}\", result);\n\n }\n\n}\n\n\n\nasync fn run_multi<C: ConnectionLike + Clone>(mut con: C) -> RedisResult<()> {\n\n let mut interval = interval(Duration::from_millis(100));\n\n loop {\n", "file_path": "examples/async-connection-loss.rs", "rank": 85, "score": 67651.58840766623 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ArbitraryValue(Value);\n\nimpl ::quickcheck::Arbitrary for ArbitraryValue {\n\n fn arbitrary<G: ::quickcheck::Gen>(g: &mut G) -> Self {\n\n let size = g.size();\n\n ArbitraryValue(arbitrary_value(g, size))\n\n }\n\n fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {\n\n match self.0 {\n\n Value::Nil | Value::Okay => Box::new(None.into_iter()),\n\n Value::Int(i) => Box::new(i.shrink().map(Value::Int).map(ArbitraryValue)),\n\n Value::Data(ref xs) => Box::new(xs.shrink().map(Value::Data).map(ArbitraryValue)),\n\n Value::Bulk(ref xs) => {\n\n let ys = xs\n\n .iter()\n\n .map(|x| ArbitraryValue(x.clone()))\n\n .collect::<Vec<_>>();\n\n Box::new(\n\n ys.shrink()\n\n .map(|xs| xs.into_iter().map(|x| x.0).collect())\n\n .map(Value::Bulk)\n\n .map(ArbitraryValue),\n\n )\n\n }\n\n Value::Status(ref status) => {\n\n Box::new(status.shrink().map(Value::Status).map(ArbitraryValue))\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/parser.rs", "rank": 86, "score": 64598.71188640897 }, { "content": "/// Implements the \"stateless\" part of the connection interface that is used by the\n\n/// different objects in redis-rs. Primarily it obviously applies to `Connection`\n\n/// object but also some other objects implement the interface (for instance\n\n/// whole clients or certain redis results).\n\n///\n\n/// Generally clients and connections (as well as redis results of those) implement\n\n/// this trait. Actual connections provide more functionality which can be used\n\n/// to implement things like `PubSub` but they also can modify the intrinsic\n\n/// state of the TCP connection. This is not possible with `ConnectionLike`\n\n/// implementors because that functionality is not exposed.\n\npub trait ConnectionLike {\n\n /// Sends an already encoded (packed) command into the TCP socket and\n\n /// reads the single response from it.\n\n fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value>;\n\n\n\n /// Sends multiple already encoded (packed) command into the TCP socket\n\n /// and reads `count` responses from it. This is used to implement\n\n /// pipelining.\n\n fn req_packed_commands(\n\n &mut self,\n\n cmd: &[u8],\n\n offset: usize,\n\n count: usize,\n\n ) -> RedisResult<Vec<Value>>;\n\n\n\n /// Returns the database this connection is bound to. Note that this\n\n /// information might be unreliable because it's initially cached and\n\n /// also might be incorrect if the connection like object is not\n\n /// actually connected.\n\n fn get_db(&self) -> i64;\n", "file_path": "src/connection.rs", "rank": 87, "score": 64055.37512666065 }, { "content": "/// Converts an object into a connection info struct. This allows the\n\n/// constructor of the client to accept connection information in a\n\n/// range of different formats.\n\npub trait IntoConnectionInfo {\n\n /// Converts the object into a connection info object.\n\n fn into_connection_info(self) -> RedisResult<ConnectionInfo>;\n\n}\n\n\n\nimpl IntoConnectionInfo for ConnectionInfo {\n\n fn into_connection_info(self) -> RedisResult<ConnectionInfo> {\n\n Ok(self)\n\n }\n\n}\n\n\n\nimpl<'a> IntoConnectionInfo for &'a str {\n\n fn into_connection_info(self) -> RedisResult<ConnectionInfo> {\n\n match parse_redis_url(self) {\n\n Ok(u) => u.into_connection_info(),\n\n Err(_) => fail!((ErrorKind::InvalidClientConfig, \"Redis URL did not parse\")),\n\n }\n\n }\n\n}\n\n\n\nimpl IntoConnectionInfo for String {\n\n fn into_connection_info(self) -> RedisResult<ConnectionInfo> {\n\n match parse_redis_url(&self) {\n\n Ok(u) => u.into_connection_info(),\n\n Err(_) => fail!((ErrorKind::InvalidClientConfig, \"Redis URL did not parse\")),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/connection.rs", "rank": 88, "score": 64045.93824347366 }, { "content": "struct PartialAsyncRead<R> {\n\n inner: R,\n\n ops: Box<dyn Iterator<Item = PartialOp> + Send>,\n\n}\n\n\n\nimpl<R> AsyncRead for PartialAsyncRead<R>\n\nwhere\n\n R: AsyncRead + Unpin,\n\n{\n\n fn poll_read(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut task::Context,\n\n buf: &mut [u8],\n\n ) -> Poll<io::Result<usize>> {\n\n match self.ops.next() {\n\n Some(PartialOp::Limited(n)) => {\n\n let len = std::cmp::min(n, buf.len());\n\n Pin::new(&mut self.inner).poll_read(cx, &mut buf[..len])\n\n }\n\n Some(PartialOp::Err(err)) => {\n", "file_path": "tests/parser.rs", "rank": 89, "score": 63283.30350903257 }, { "content": "fn main() {\n\n // at this point the errors are fatal, let's just fail hard.\n\n let url = if env::args().nth(1) == Some(\"--tls\".into()) {\n\n \"redis+tls://127.0.0.1:6380/#insecure\"\n\n } else {\n\n \"redis://127.0.0.1:6379/\"\n\n };\n\n match do_redis_code(url) {\n\n Err(err) => {\n\n println!(\"Could not execute example:\");\n\n println!(\" {}: {}\", err.category(), err);\n\n }\n\n Ok(()) => {}\n\n }\n\n}\n", "file_path": "examples/basic.rs", "rank": 90, "score": 58260.330936585044 }, { "content": "fn main() {\n\n if let Err(e) = run() {\n\n println!(\"{:?}\", e);\n\n exit(1);\n\n }\n\n}\n", "file_path": "examples/geospatial.rs", "rank": 91, "score": 58260.330936585044 }, { "content": " /// Implements common redis commands for connection like objects. This\n\n /// allows you to send commands straight to a connection or client. It\n\n /// is also implemented for redis results of clients which makes for\n\n /// very convenient access in some basic cases.\n\n ///\n\n /// This allows you to use nicer syntax for some common operations.\n\n /// For instance this code:\n\n ///\n\n /// ```rust,no_run\n\n /// # fn do_something() -> redis::RedisResult<()> {\n\n /// let client = redis::Client::open(\"redis://127.0.0.1/\")?;\n\n /// let mut con = client.get_connection()?;\n\n /// redis::cmd(\"SET\").arg(\"my_key\").arg(42).execute(&mut con);\n\n /// assert_eq!(redis::cmd(\"GET\").arg(\"my_key\").query(&mut con), Ok(42));\n\n /// # Ok(()) }\n\n /// ```\n\n ///\n\n /// Will become this:\n\n ///\n\n /// ```rust,no_run\n\n /// # fn do_something() -> redis::RedisResult<()> {\n\n /// use redis::Commands;\n\n /// let client = redis::Client::open(\"redis://127.0.0.1/\")?;\n\n /// let mut con = client.get_connection()?;\n\n /// con.set(\"my_key\", 42)?;\n\n /// assert_eq!(con.get(\"my_key\"), Ok(42));\n\n /// # Ok(()) }\n\n /// ```\n\n pub trait Commands : ConnectionLike+Sized {\n\n $(\n\n $(#[$attr])*\n\n #[inline]\n\n #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]\n\n fn $name<$lifetime, $($tyargs: $ty, )* RV: FromRedisValue>(\n\n &mut self $(, $argname: $argty)*) -> RedisResult<RV>\n\n { Cmd::$name($($argname),*).query(self) }\n\n )*\n\n\n\n /// Incrementally iterate the keys space.\n\n #[inline]\n\n fn scan<RV: FromRedisValue>(&mut self) -> RedisResult<Iter<'_, RV>> {\n\n let mut c = cmd(\"SCAN\");\n\n c.cursor_arg(0);\n\n c.iter(self)\n\n }\n\n\n\n /// Incrementally iterate the keys space for keys matching a pattern.\n\n #[inline]\n", "file_path": "src/commands.rs", "rank": 92, "score": 57266.53811499008 }, { "content": "#[test]\n\nfn test_georadius() {\n\n let ctx = TestContext::new();\n\n let mut con = ctx.connection();\n\n\n\n assert_eq!(con.geo_add(\"my_gis\", &[PALERMO, CATANIA]), Ok(2));\n\n\n\n let mut geo_radius = |opts: RadiusOptions| -> Vec<RadiusSearchResult> {\n\n con.geo_radius(\"my_gis\", 15.0, 37.0, 200.0, Unit::Kilometers, opts)\n\n .unwrap()\n\n };\n\n\n\n // Simple request, without extra data\n\n let mut result = geo_radius(RadiusOptions::default());\n\n result.sort_by(|a, b| Ord::cmp(&a.name, &b.name));\n\n\n\n assert_eq!(result.len(), 2);\n\n\n\n assert_eq!(result[0].name.as_str(), \"Catania\");\n\n assert_eq!(result[0].coord, None);\n\n assert_eq!(result[0].dist, None);\n", "file_path": "tests/test_geospatial.rs", "rank": 93, "score": 55422.11144337323 }, { "content": "#[test]\n\n#[cfg(feature = \"script\")]\n\nfn test_script() {\n\n use redis::RedisError;\n\n\n\n // Note this test runs both scripts twice to test when they have already been loaded\n\n // into Redis and when they need to be loaded in\n\n let script1 = redis::Script::new(\"return redis.call('SET', KEYS[1], ARGV[1])\");\n\n let script2 = redis::Script::new(\"return redis.call('GET', KEYS[1])\");\n\n\n\n let ctx = TestContext::new();\n\n\n\n block_on_all(async move {\n\n let mut con = ctx.multiplexed_async_connection().await?;\n\n script1\n\n .key(\"key1\")\n\n .arg(\"foo\")\n\n .invoke_async(&mut con)\n\n .await?;\n\n let val: String = script2.key(\"key1\").invoke_async(&mut con).await?;\n\n assert_eq!(val, \"foo\");\n\n script1\n", "file_path": "tests/test_async.rs", "rank": 94, "score": 55422.11144337323 }, { "content": "#[test]\n\nfn test_args() {\n\n let ctx = TestContext::new();\n\n let connect = ctx.async_connection();\n\n\n\n block_on_all(connect.and_then(|mut con| async move {\n\n redis::cmd(\"SET\")\n\n .arg(\"key1\")\n\n .arg(b\"foo\")\n\n .query_async(&mut con)\n\n .await?;\n\n redis::cmd(\"SET\")\n\n .arg(&[\"key2\", \"bar\"])\n\n .query_async(&mut con)\n\n .await?;\n\n let result = redis::cmd(\"MGET\")\n\n .arg(&[\"key1\", \"key2\"])\n\n .query_async(&mut con)\n\n .await;\n\n assert_eq!(result, Ok((\"foo\".to_string(), b\"bar\".to_vec())));\n\n result\n\n }))\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/test_async.rs", "rank": 95, "score": 55422.11144337323 }, { "content": "#[test]\n\nfn test_args() {\n\n let ctx = TestContext::new();\n\n let mut con = ctx.connection();\n\n\n\n redis::cmd(\"SET\").arg(\"key1\").arg(b\"foo\").execute(&mut con);\n\n redis::cmd(\"SET\").arg(&[\"key2\", \"bar\"]).execute(&mut con);\n\n\n\n assert_eq!(\n\n redis::cmd(\"MGET\").arg(&[\"key1\", \"key2\"]).query(&mut con),\n\n Ok((\"foo\".to_string(), b\"bar\".to_vec()))\n\n );\n\n}\n\n\n", "file_path": "tests/test_basic.rs", "rank": 96, "score": 55422.11144337323 }, { "content": "#[test]\n\nfn test_geohash() {\n\n let ctx = TestContext::new();\n\n let mut con = ctx.connection();\n\n\n\n assert_eq!(con.geo_add(\"my_gis\", &[PALERMO, CATANIA]), Ok(2));\n\n let result: RedisResult<Vec<String>> = con.geo_hash(\"my_gis\", PALERMO.2);\n\n assert_eq!(result, Ok(vec![String::from(\"sqc8b49rny0\")]));\n\n\n\n let result: RedisResult<Vec<String>> = con.geo_hash(\"my_gis\", &[PALERMO.2, CATANIA.2]);\n\n assert_eq!(\n\n result,\n\n Ok(vec![\n\n String::from(\"sqc8b49rny0\"),\n\n String::from(\"sqdtr74hyu0\"),\n\n ])\n\n );\n\n}\n\n\n", "file_path": "tests/test_geospatial.rs", "rank": 97, "score": 55422.11144337323 }, { "content": "#[test]\n\nfn test_geopos() {\n\n let ctx = TestContext::new();\n\n let mut con = ctx.connection();\n\n\n\n assert_eq!(con.geo_add(\"my_gis\", &[PALERMO, CATANIA]), Ok(2));\n\n\n\n let result: Vec<Vec<f64>> = con.geo_pos(\"my_gis\", &[PALERMO.2]).unwrap();\n\n assert_eq!(result.len(), 1);\n\n\n\n assert_approx_eq!(result[0][0], 13.36138, 0.0001);\n\n assert_approx_eq!(result[0][1], 38.11555, 0.0001);\n\n\n\n // Using the Coord struct\n\n let result: Vec<Coord<f64>> = con.geo_pos(\"my_gis\", &[PALERMO.2, CATANIA.2]).unwrap();\n\n assert_eq!(result.len(), 2);\n\n\n\n assert_approx_eq!(result[0].longitude, 13.36138, 0.0001);\n\n assert_approx_eq!(result[0].latitude, 38.11555, 0.0001);\n\n\n\n assert_approx_eq!(result[1].longitude, 15.08726, 0.0001);\n\n assert_approx_eq!(result[1].latitude, 37.50266, 0.0001);\n\n}\n\n\n", "file_path": "tests/test_geospatial.rs", "rank": 98, "score": 55422.11144337323 } ]
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_height + base_height * (len / 1.0);\n\n let time = time_s(min_time + base_time * (len / 1.0));\n\n let up_and_down = up_and_down_move(view, sprite, height, time);\n\n let main_move = action::MoveBy::new(sprite, diff, time).boxed();\n\n seq([fork(main_move), up_and_down])\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 0, "score": 323311.1057474372 }, { "content": "fn action_set_z(layer: &zscene::Layer, sprite: &Sprite, z: f32) -> Box<dyn Action> {\n\n let sprite = sprite.clone();\n\n let mut layer = layer.clone();\n\n let closure = Box::new(move || {\n\n layer.set_z(&sprite, z);\n\n });\n\n action::Custom::new(closure).boxed()\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 1, "score": 312337.5389484856 }, { "content": "pub fn seq(actions: impl Into<Vec<Box<dyn Action>>>) -> Box<dyn Action> {\n\n action::Sequence::new(actions.into()).boxed()\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 2, "score": 301310.47665544174 }, { "content": "fn announce(view: &mut BattleView, text: &str, time: Duration) -> ZResult<Box<dyn Action>> {\n\n let height_text = 0.2;\n\n let height_bg = height_text * 5.0;\n\n let time_appear = time.mul_f32(0.25);\n\n let time_wait = time.mul_f32(0.5);\n\n let time_disappear = time.mul_f32(0.35);\n\n let action_show_and_hide = |sprite, color: Color| {\n\n let color_invisible = Color { a: 0.0, ..color };\n\n seq([\n\n action::SetColor::new(&sprite, color_invisible).boxed(),\n\n action::Show::new(&view.layers().text, &sprite).boxed(),\n\n action::ChangeColorTo::new(&sprite, color, time_appear).boxed(),\n\n action::Sleep::new(time_wait).boxed(),\n\n action::ChangeColorTo::new(&sprite, color_invisible, time_disappear).boxed(),\n\n action::Hide::new(&view.layers().text, &sprite).boxed(),\n\n ])\n\n };\n\n let actions_text = {\n\n let color = [0.0, 0.0, 0.0, 1.0].into();\n\n let font = assets::get().font;\n", "file_path": "src/screen/battle/visualize.rs", "rank": 3, "score": 292914.96006917104 }, { "content": "fn attack_message(view: &mut BattleView, pos: Vec2, text: &str) -> ZResult<Box<dyn Action>> {\n\n let visible = [0.0, 0.0, 0.0, 1.0].into();\n\n let invisible = [0.0, 0.0, 0.0, 0.0].into();\n\n let font = assets::get().font;\n\n let mut sprite = Sprite::from_text((text, font), 0.1);\n\n sprite.set_centered(true);\n\n let point = pos + Vec2::new(0.0, view.tile_size() * 0.5);\n\n sprite.set_pos(point);\n\n sprite.set_color(invisible);\n\n let action_show_hide = seq([\n\n action::Show::new(&view.layers().text, &sprite).boxed(),\n\n // TODO: read the time from Config:\n\n action::ChangeColorTo::new(&sprite, visible, time_s(0.3)).boxed(),\n\n action::ChangeColorTo::new(&sprite, invisible, time_s(0.3)).boxed(),\n\n action::Hide::new(&view.layers().text, &sprite).boxed(),\n\n ]);\n\n Ok(fork(action_show_hide))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 4, "score": 289136.47103781026 }, { "content": "pub fn message(view: &mut BattleView, pos: PosHex, text: &str) -> ZResult<Box<dyn Action>> {\n\n let visible = [0.0, 0.0, 0.0, 1.0].into();\n\n let invisible = Color::new(0.0, 0.0, 0.0, 0.0);\n\n let font = assets::get().font;\n\n let mut sprite = Sprite::from_text((text, font), 0.1);\n\n sprite.set_centered(true);\n\n let point = view.hex_to_point(pos);\n\n let point = point - Vec2::new(0.0, view.tile_size() * 1.5);\n\n sprite.set_pos(point);\n\n sprite.set_color(invisible);\n\n let action_show_hide = seq([\n\n action::Show::new(&view.layers().text, &sprite).boxed(),\n\n action::ChangeColorTo::new(&sprite, visible, time_s(0.4)).boxed(),\n\n action::Sleep::new(time_s(0.4)).boxed(),\n\n // TODO: read the time from Config:\n\n action::ChangeColorTo::new(&sprite, invisible, time_s(0.6)).boxed(),\n\n action::Hide::new(&view.layers().text, &sprite).boxed(),\n\n ]);\n\n let duration = action_show_hide.duration();\n\n let delta = -Vec2::new(0.0, 0.15);\n", "file_path": "src/screen/battle/visualize.rs", "rank": 5, "score": 279803.4798755328 }, { "content": "pub fn make_action_create_map(state: &State, view: &BattleView) -> ZResult<Box<dyn Action>> {\n\n let mut actions = Vec::new();\n\n for hex_pos in state.map().iter() {\n\n actions.push(make_action_show_tile(state, view, hex_pos)?);\n\n let is_free = state::is_tile_completely_free(state, hex_pos);\n\n let is_plain = state.map().tile(hex_pos) == TileType::Plain;\n\n if is_free && is_plain && roll_dice(0, 10) < 2 {\n\n actions.push(make_action_grass(view, hex_pos)?);\n\n }\n\n }\n\n Ok(visualize::seq(actions))\n\n}\n", "file_path": "src/screen/battle/view.rs", "rank": 6, "score": 276975.83439585974 }, { "content": "pub fn fork(action: Box<dyn Action>) -> Box<dyn Action> {\n\n action::Fork::new(action).boxed()\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 7, "score": 269572.74236689694 }, { "content": "fn make_gui(font: mq::text::Font) -> ui::Result<ui::Gui<Message>> {\n\n let mut gui = ui::Gui::new();\n\n let anchor = ui::Anchor(ui::HAnchor::Right, ui::VAnchor::Bottom);\n\n let text = ui::Drawable::text(\"Button\", font);\n\n let button = ui::Button::new(text, 0.2, gui.sender(), Message::Command)?;\n\n gui.add(&ui::pack(button), anchor);\n\n Ok(gui)\n\n}\n\n\n", "file_path": "zgui/examples/absolute_coordinates.rs", "rank": 8, "score": 259126.64347298708 }, { "content": "fn make_gui(font: mq::text::Font) -> ui::Result<ui::Gui<Message>> {\n\n let mut gui = ui::Gui::new();\n\n let anchor = ui::Anchor(ui::HAnchor::Right, ui::VAnchor::Bottom);\n\n let text = ui::Drawable::text(\"Button\", font);\n\n let button = ui::Button::new(text, 0.2, gui.sender(), Message::Command)?;\n\n gui.add(&ui::pack(button), anchor);\n\n Ok(gui)\n\n}\n\n\n", "file_path": "zgui/examples/pixel_coordinates.rs", "rank": 9, "score": 259126.64347298708 }, { "content": "fn visualize_post(state: &State, view: &mut BattleView, event: &Event) -> ZResult<Box<dyn Action>> {\n\n let mut actions = Vec::new();\n\n for &id in &event.actor_ids {\n\n actions.push(refresh_brief_agent_info(state, view, id)?);\n\n }\n\n for &(id, _) in &event.instant_effects {\n\n actions.push(refresh_brief_agent_info(state, view, id)?);\n\n }\n\n for &(id, _) in &event.timed_effects {\n\n actions.push(refresh_brief_agent_info(state, view, id)?);\n\n }\n\n Ok(seq(actions))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 10, "score": 256815.6041882246 }, { "content": "fn visualize_pre(state: &State, view: &mut BattleView, event: &Event) -> ZResult<Box<dyn Action>> {\n\n let mut actions = vec![visualize_event(state, view, &event.active_event)?];\n\n for &(id, ref effects) in &event.instant_effects {\n\n for effect in effects {\n\n actions.push(visualize_instant_effect(state, view, id, effect)?);\n\n }\n\n }\n\n for &(id, ref effects) in &event.timed_effects {\n\n for effect in effects {\n\n actions.push(visualize_lasting_effect(state, view, id, effect)?);\n\n }\n\n }\n\n Ok(seq(actions))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 11, "score": 256815.6041882246 }, { "content": "pub fn apply(state: &mut State, event: &Event) {\n\n trace!(\"event::apply: {:?}\", event);\n\n apply_event(state, event);\n\n for &(obj_id, ref effects) in &event.instant_effects {\n\n for effect in effects {\n\n apply_effect_instant(state, obj_id, effect);\n\n }\n\n }\n\n for &(obj_id, ref effects) in &event.timed_effects {\n\n for effect in effects {\n\n apply_effect_timed(state, obj_id, effect);\n\n }\n\n }\n\n for &(id, ref abilities) in &event.scheduled_abilities {\n\n for planned_ability in abilities {\n\n apply_scheduled_ability(state, id, planned_ability);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 12, "score": 249635.2993115281 }, { "content": "fn lunge(state: &State, view: &mut BattleView, id: Id, to: PosHex) -> ZResult<Box<dyn Action>> {\n\n let from = state.parts().pos.get(id).0;\n\n let diff = (view.hex_to_point(to) - view.hex_to_point(from)) / 2.0;\n\n let mut actions = Vec::new();\n\n if let Some(facing) = geom::Facing::from_positions(view.tile_size(), from, to) {\n\n let sprite = view.id_to_sprite(id).clone();\n\n actions.push(action::SetFacing::new(&sprite, facing.to_scene_facing()).boxed());\n\n }\n\n let time_to = time_s(TIME_LUNGE_TO);\n\n let time_from = time_s(TIME_LUNGE_FROM);\n\n actions.push(move_object_with_shadow(view, id, diff, time_to));\n\n actions.push(move_object_with_shadow(view, id, -diff, time_from));\n\n Ok(seq(actions))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 13, "score": 246551.68612433242 }, { "content": "fn vanish_with_duration(view: &mut BattleView, target_id: Id, time: Duration) -> Box<dyn Action> {\n\n trace!(\"vanish target_id={:?}\", target_id);\n\n let sprite = view.id_to_sprite(target_id).clone();\n\n let sprite_shadow = view.id_to_shadow_sprite(target_id).clone();\n\n view.remove_object(target_id);\n\n let dark = [0.1, 0.1, 0.1, 1.0].into();\n\n let invisible = [0.1, 0.1, 0.1, 0.0].into();\n\n let time_div_3 = time.div_f32(3.0);\n\n seq([\n\n action::ChangeColorTo::new(&sprite, dark, time_div_3).boxed(),\n\n action::ChangeColorTo::new(&sprite, invisible, time_div_3).boxed(),\n\n action::Hide::new(&view.layers().objects, &sprite).boxed(),\n\n action::ChangeColorTo::new(&sprite_shadow, invisible, time_div_3).boxed(),\n\n action::Hide::new(&view.layers().shadows, &sprite_shadow).boxed(),\n\n ])\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 14, "score": 246046.229524993 }, { "content": "fn visualize_effect_vanish(_: &State, view: &mut BattleView, target_id: Id) -> Box<dyn Action> {\n\n fork(vanish_with_duration(view, target_id, time_s(1.2)))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 15, "score": 243395.3646908718 }, { "content": "fn show_dust(view: &mut BattleView, at: Vec2, count: i32) -> ZResult<Box<dyn Action>> {\n\n let mut actions = Vec::new();\n\n for i in 0..count {\n\n let k = roll_dice(0.8, 1.2);\n\n let visible = [0.8 * k, 0.8 * k, 0.7 * k, 0.8 * k].into();\n\n let invisible = [0.8 * k, 0.8 * k, 0.7 * k, 0.0].into();\n\n let scale = roll_dice(0.2, 0.4);\n\n let size = view.tile_size() * 2.0 * scale;\n\n let vector = {\n\n let max = std::f32::consts::PI * 2.0;\n\n let rot = Mat2::from_angle((max / count as f32) * i as f32);\n\n let n = roll_dice(0.3, 0.6);\n\n let mut vector = rot * Vec2::new(view.tile_size() * n, 0.0);\n\n vector.y *= geom::FLATNESS_COEFFICIENT;\n\n vector\n\n };\n\n let point = at + vector;\n\n let sprite = {\n\n let mut sprite = Sprite::from_texture(textures().map.white_hex, size);\n\n sprite.set_centered(true);\n", "file_path": "src/screen/battle/visualize.rs", "rank": 16, "score": 241855.2488989725 }, { "content": "fn make_gui(font: mq::text::Font) -> ui::Result<ui::Gui<Message>> {\n\n let mut gui = ui::Gui::new();\n\n let anchor = ui::Anchor(ui::HAnchor::Right, ui::VAnchor::Bottom);\n\n let text = ui::Drawable::text(\"Button\", font);\n\n let button = ui::Button::new(text, 0.2, gui.sender(), Message::Command)?;\n\n gui.add(&ui::pack(button), anchor);\n\n Ok(gui)\n\n}\n\n\n\n#[mq::main(\"ZGui: Text Button Demo\")]\n\n#[macroquad(crate_rename = \"mq\")]\n\nasync fn main() {\n\n let assets = common::Assets::load().await.expect(\"Can't load assets\");\n\n let mut gui = make_gui(assets.font).expect(\"Can't create the gui\");\n\n loop {\n\n // Update the camera and the GUI.\n\n let aspect_ratio = common::aspect_ratio();\n\n let camera = common::make_and_set_camera(aspect_ratio);\n\n gui.resize_if_needed(aspect_ratio);\n\n // Handle cursor updates.\n", "file_path": "zgui/examples/text_button.rs", "rank": 17, "score": 241272.95133243658 }, { "content": "pub fn sort_agent_ids_by_distance_to_enemies(state: &State, ids: &mut [Id]) {\n\n ids.sort_unstable_by_key(|&id| {\n\n let agent_player_id = state.parts().belongs_to.get(id).0;\n\n let agent_pos = state.parts().pos.get(id).0;\n\n let mut min_distance = state.map().height();\n\n for enemy_id in enemy_agent_ids(state, agent_player_id) {\n\n let enemy_pos = state.parts().pos.get(enemy_id).0;\n\n let distance = map::distance_hex(agent_pos, enemy_pos);\n\n if distance < min_distance {\n\n min_distance = distance;\n\n }\n\n }\n\n min_distance\n\n });\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 18, "score": 240695.62276360948 }, { "content": "fn make_gui(font: mq::text::Font) -> ui::Result<ui::Gui<Message>> {\n\n let mut gui = ui::Gui::new();\n\n let anchor = ui::Anchor(ui::HAnchor::Right, ui::VAnchor::Bottom);\n\n let text = ui::Drawable::text(\"Button\", font);\n\n let button = ui::Button::new(text, 0.2, gui.sender(), Message::AddOrRemove)?;\n\n gui.add(&ui::pack(button), anchor);\n\n Ok(gui)\n\n}\n\n\n", "file_path": "zgui/examples/remove.rs", "rank": 19, "score": 232761.65572550427 }, { "content": "fn label(font: Font, text: &str) -> ZResult<Box<dyn ui::Widget>> {\n\n let text = ui::Drawable::text(text, font);\n\n Ok(Box::new(ui::Label::new(text, line_height())?))\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Campaign {\n\n state: State,\n\n receiver_battle_result: Option<Receiver<Option<BattleResult>>>,\n\n receiver_exit_confirmation: Option<Receiver<screen::confirm::Message>>,\n\n gui: Gui<Message>,\n\n layout: Option<ui::RcWidget>,\n\n label_central_message: Option<ui::RcWidget>,\n\n}\n\n\n\nimpl Campaign {\n\n pub fn new() -> ZResult<Self> {\n\n let campaign_plan = assets::get().campaign_plan.clone();\n\n let agent_campaign_info = assets::get().agent_campaign_info.clone();\n\n let state = State::new(campaign_plan, agent_campaign_info);\n", "file_path": "src/screen/campaign.rs", "rank": 20, "score": 232269.8563783319 }, { "content": "fn exec(state: &mut State, command: impl Into<Command>) -> Vec<Event> {\n\n try_exec(state, command).unwrap()\n\n}\n\n\n", "file_path": "src/core/battle/tests.rs", "rank": 21, "score": 230321.48786231928 }, { "content": "fn build_panel_actions(gui: &mut ui::Gui<Message>, state: &State) -> ZResult<Box<dyn ui::Widget>> {\n\n let font = assets::get().font;\n\n let h = line_height();\n\n let mut layout = Box::new(ui::VLayout::new().stretchable(true));\n\n layout.add(label(font, \"Actions:\")?);\n\n layout.add(Box::new(ui::Spacer::new_vertical(line_height_small())));\n\n for action in state.available_actions() {\n\n let mut line = ui::HLayout::new().stretchable(true);\n\n let action_cost = state.action_cost(action);\n\n let text = match action {\n\n Action::Recruit { agent_type } => {\n\n let title = agent_type.0.to_title_case();\n\n format!(\"Recruit {} for {}r\", title, action_cost.0)\n\n }\n\n Action::Upgrade { from, to } => {\n\n let from = from.0.to_title_case();\n\n let to = to.0.to_title_case();\n\n format!(\"Upgrade {} to {} for {}r\", from, to, action_cost.0)\n\n }\n\n };\n", "file_path": "src/screen/campaign.rs", "rank": 22, "score": 230298.69616352385 }, { "content": "fn exec_and_check(state: &mut State, command: impl Into<Command>, expected_events: &[Event]) {\n\n let events = exec(state, command);\n\n assert_eq!(events.as_slice(), expected_events);\n\n}\n\n\n", "file_path": "src/core/battle/tests.rs", "rank": 23, "score": 224301.3984311066 }, { "content": "/// <http://www.redblobgames.com/grids/hexagons/#pixel-to-hex>\n\npub fn point_to_hex(size: f32, mut point: Vec2) -> PosHex {\n\n point.y /= FLATNESS_COEFFICIENT;\n\n let q = (point.x * SQRT_OF_3 / 3.0 - point.y / 3.0) / size;\n\n let r = point.y * 2.0 / 3.0 / size;\n\n hex_round(PosHex { q, r })\n\n}\n\n\n", "file_path": "src/geom.rs", "rank": 24, "score": 222412.32737196912 }, { "content": "fn apply_event_use_ability(state: &mut State, event: &event::UseAbility) {\n\n let id = event.id;\n\n let parts = state.parts_mut();\n\n if let Some(abilities) = parts.abilities.get_opt_mut(id) {\n\n for r_ability in &mut abilities.0 {\n\n if r_ability.ability == event.ability {\n\n let cooldown = r_ability.ability.base_cooldown();\n\n assert_eq!(r_ability.status, ability::Status::Ready);\n\n if !cooldown.is_zero() {\n\n r_ability.status = ability::Status::Cooldown(cooldown);\n\n }\n\n }\n\n }\n\n }\n\n if let Some(agent) = parts.agent.get_opt_mut(id) {\n\n if agent.attacks.0 > 0 {\n\n agent.attacks.0 -= 1;\n\n } else if agent.jokers.0 > 0 {\n\n agent.jokers.0 -= 1;\n\n } else {\n", "file_path": "src/core/battle/state/apply.rs", "rank": 25, "score": 221616.94527858045 }, { "content": "fn make_action_show_tile(state: &State, view: &BattleView, at: PosHex) -> ZResult<Box<dyn Action>> {\n\n let screen_pos = hex_to_point(view.tile_size(), at);\n\n let texture = match state.map().tile(at) {\n\n TileType::Plain => textures().map.tile,\n\n TileType::Rocks => textures().map.tile_rocks,\n\n };\n\n let size = view.tile_size() * 2.0 * geom::FLATNESS_COEFFICIENT;\n\n let mut sprite = Sprite::from_texture(texture, size);\n\n sprite.set_centered(true);\n\n sprite.set_pos(screen_pos);\n\n Ok(action::Show::new(&view.layers().bg, &sprite).boxed())\n\n}\n\n\n", "file_path": "src/screen/battle/view.rs", "rank": 26, "score": 220169.79447815428 }, { "content": "fn apply_effect_timed(state: &mut State, id: Id, timed_effect: &effect::Timed) {\n\n trace!(\"effect::apply_timed: {:?}\", timed_effect);\n\n let effects = &mut state.parts_mut().effects;\n\n if effects.get_opt(id).is_none() {\n\n effects.insert(id, component::Effects(Vec::new()));\n\n }\n\n let effects = &mut effects.get_mut(id).0;\n\n if let Some(i) = effects.iter().position(|e| e.effect == timed_effect.effect) {\n\n effects[i] = timed_effect.clone();\n\n } else {\n\n effects.push(timed_effect.clone());\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 27, "score": 219697.45744815105 }, { "content": "pub fn execute(state: &mut State, command: &Command, cb: Cb) -> Result<(), Error> {\n\n trace!(\"Simulator: do_command: {:?}\", command);\n\n if let Err(err) = check(state, command) {\n\n error!(\"Check failed: {:?}\", err);\n\n return Err(err);\n\n }\n\n match *command {\n\n Command::Create(ref command) => execute_create(state, cb, command),\n\n Command::MoveTo(ref command) => execute_move_to(state, cb, command),\n\n Command::Attack(ref command) => execute_attack(state, cb, command),\n\n Command::EndTurn(ref command) => execute_end_turn(state, cb, command),\n\n Command::UseAbility(ref command) => execute_use_ability(state, cb, command),\n\n }\n\n execute_planned_abilities(state, cb);\n\n match *command {\n\n Command::Create(_) => {}\n\n _ => try_execute_end_battle(state, cb),\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 28, "score": 219633.4933771424 }, { "content": "pub fn add_bg(w: Box<dyn ui::Widget>) -> ZResult<ui::LayersLayout> {\n\n let bg = ui::ColoredRect::new(ui::SPRITE_COLOR_BG, w.rect()).stretchable(true);\n\n let mut layers = ui::LayersLayout::new();\n\n layers.add(Box::new(bg));\n\n layers.add(w);\n\n Ok(layers)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 29, "score": 213926.28711000577 }, { "content": "pub fn is_lasting_effect_over(state: &State, id: Id, timed_effect: &effect::Timed) -> bool {\n\n if let effect::Lasting::Poison = timed_effect.effect {\n\n let strength = state.parts().strength.get(id).strength;\n\n if strength <= Strength(1) {\n\n return true;\n\n }\n\n }\n\n timed_effect.duration.is_over()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 30, "score": 213767.49442113342 }, { "content": "fn execute_use_ability_vanish(state: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n assert!(state.parts().is_exist(command.id));\n\n let effects = vec![Effect::Vanish];\n\n context.instant_effects.push((command.id, effects));\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 31, "score": 209896.4559636694 }, { "content": "fn execute_use_ability_club(state: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n let id = state::blocker_id_at(state, command.pos);\n\n if state.parts().belongs_to.get_opt(id).is_some() {\n\n let owner = state.parts().belongs_to.get(id).0;\n\n let phase = Phase::from_player_id(owner);\n\n let effect = effect::Timed {\n\n duration: effect::Duration::Rounds(1.into()),\n\n phase,\n\n effect: effect::Lasting::Stun,\n\n };\n\n context.timed_effects.push((id, vec![effect]));\n\n extend_or_crate_sub_vec(&mut context.instant_effects, id, vec![Effect::Stun]);\n\n }\n\n context.actor_ids.push(id);\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 32, "score": 209896.4559636694 }, { "content": "fn execute_use_ability_summon(state: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n let max_summoned_count = state.parts().summoner.get(command.id).count;\n\n let available_typenames = &[\"imp\".into(), \"toxic_imp\".into(), \"imp_bomber\".into()];\n\n let existing_agents = existing_agent_typenames(state, state.player_id());\n\n let mut new_agents = Vec::new();\n\n for pos in state::free_neighbor_positions(state, command.pos, max_summoned_count as _) {\n\n let prototype = choose_who_to_summon(&existing_agents, &new_agents, available_typenames);\n\n let effect_create = effect_create_agent(state, &prototype, state.player_id(), pos);\n\n let id = state.alloc_id();\n\n let effects = vec![effect_create, Effect::Stun];\n\n new_agents.push(prototype);\n\n context.instant_effects.push((id, effects));\n\n context.moved_actor_ids.push(id);\n\n context.reaction_attack_targets.push(id);\n\n }\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 33, "score": 209896.4559636694 }, { "content": "fn execute_use_ability_poison(state: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n let id = state::blocker_id_at(state, command.pos);\n\n let owner = state.parts().belongs_to.get(id).0;\n\n let phase = Phase::from_player_id(owner);\n\n let effect = effect::Timed {\n\n duration: effect::Duration::Rounds(2.into()),\n\n phase,\n\n effect: effect::Lasting::Poison,\n\n };\n\n context.timed_effects.push((id, vec![effect]));\n\n context.actor_ids.push(id);\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 34, "score": 209896.4559636694 }, { "content": "pub fn get_world_mouse_pos(camera: &Camera2D) -> Vec2 {\n\n camera.screen_to_world(mq::input::mouse_position().into())\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 35, "score": 209815.159575301 }, { "content": "fn execute_use_ability(state: &mut State, cb: Cb, command: &command::UseAbility) {\n\n let mut context = match command.ability {\n\n Ability::Knockback => execute_use_ability_knockback(state, command),\n\n Ability::Club => execute_use_ability_club(state, command),\n\n Ability::Jump => execute_use_ability_jump(state, command),\n\n Ability::LongJump => execute_use_ability_long_jump(state, command),\n\n Ability::Dash => execute_use_ability_dash(state, command),\n\n Ability::Rage => execute_use_ability_rage(state, command),\n\n Ability::Heal => execute_use_ability_heal(state, command, Strength(2)),\n\n Ability::GreatHeal => execute_use_ability_heal(state, command, Strength(3)),\n\n Ability::Vanish => execute_use_ability_vanish(state, command),\n\n Ability::ExplodeFire => execute_use_ability_explode_fire(state, command),\n\n Ability::ExplodePoison => execute_use_ability_explode_poison(state, command),\n\n Ability::ExplodePush => execute_use_ability_explode_push(state, command),\n\n Ability::ExplodeDamage => execute_use_ability_explode_damage(state, command),\n\n Ability::Poison => execute_use_ability_poison(state, command),\n\n Ability::Bomb => execute_use_ability_bomb_damage(state, command),\n\n Ability::BombPush => execute_use_ability_bomb_push(state, command),\n\n Ability::BombFire => execute_use_ability_bomb_fire(state, command),\n\n Ability::BombPoison => execute_use_ability_bomb_poison(state, command),\n", "file_path": "src/core/battle/execute.rs", "rank": 36, "score": 209763.51724354114 }, { "content": "fn try_exec(state: &mut State, command: impl Into<Command>) -> Result<Vec<Event>, check::Error> {\n\n let mut events = Vec::new();\n\n execute(state, &command.into(), &mut |_state, event, phase| {\n\n if phase == ApplyPhase::Pre {\n\n events.push(event.clone());\n\n }\n\n })?;\n\n Ok(events)\n\n}\n\n\n", "file_path": "src/core/battle/tests.rs", "rank": 37, "score": 209292.5139060014 }, { "content": "pub fn add_offsets_and_bg_big(w: Box<dyn ui::Widget>) -> ZResult<ui::LayersLayout> {\n\n add_offsets_and_bg(w, OFFSET_BIG)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 38, "score": 206607.7122747925 }, { "content": "fn apply_event_use_passive_ability(_: &mut State, _: &event::UsePassiveAbility) {}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 39, "score": 206452.82047021505 }, { "content": "pub fn get_world_mouse_pos(camera: &Camera2D) -> Vec2 {\n\n camera.screen_to_world(mq::input::mouse_position().into())\n\n}\n\n\n\npub struct Assets {\n\n pub font: Font,\n\n pub texture: Texture2D,\n\n}\n\n\n\nimpl Assets {\n\n pub async fn load() -> Result<Self, Err> {\n\n let font = load_ttf_font(\"zgui/assets/Karla-Regular.ttf\").await?;\n\n let texture = texture::load_texture(\"zgui/assets/fire.png\").await?;\n\n Ok(Self { font, texture })\n\n }\n\n}\n", "file_path": "zgui/examples/common/mod.rs", "rank": 40, "score": 204726.21022128937 }, { "content": "pub fn can_agent_use_ability(state: &State, id: Id, ability: &Ability) -> bool {\n\n let parts = state.parts();\n\n let agent_player_id = parts.belongs_to.get(id).0;\n\n let agent = parts.agent.get(id);\n\n let has_actions = agent.attacks > battle::Attacks(0) || agent.jokers > battle::Jokers(0);\n\n let is_player_agent = agent_player_id == state.player_id();\n\n let abilities = &parts.abilities.get(id).0;\n\n let r_ability = abilities.iter().find(|r| &r.ability == ability).unwrap();\n\n let is_ready = r_ability.status == ability::Status::Ready;\n\n is_player_agent && is_ready && has_actions\n\n}\n", "file_path": "src/core/battle/state.rs", "rank": 41, "score": 204718.01888707856 }, { "content": "fn apply_lasting_effects(state: &mut State) {\n\n for id in state::players_agent_ids(state, state.player_id()) {\n\n if state.parts().effects.get_opt(id).is_some() {\n\n let effects = state.parts().effects.get(id).clone();\n\n for effect in &effects.0 {\n\n apply_lasting_effect(state, id, &effect.effect);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 42, "score": 203339.2456474424 }, { "content": "fn tick_planned_abilities(state: &mut State) {\n\n let phase = Phase::from_player_id(state.player_id());\n\n let ids = state.parts().schedule.ids_collected();\n\n for obj_id in ids {\n\n let schedule = state.parts_mut().schedule.get_mut(obj_id);\n\n for planned in &mut schedule.planned {\n\n if planned.phase == phase {\n\n planned.rounds.decrease();\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/core/battle/state/apply.rs", "rank": 43, "score": 203339.2456474424 }, { "content": "fn update_lasting_effects_duration(state: &mut State) {\n\n let phase = Phase::from_player_id(state.player_id());\n\n for id in state.parts().effects.ids_collected() {\n\n for effect in &mut state.parts_mut().effects.get_mut(id).0 {\n\n if effect.phase == phase {\n\n if let Duration::Rounds(ref mut rounds) = effect.duration {\n\n assert!(rounds.0 > 0);\n\n rounds.decrease();\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 44, "score": 200944.47837326833 }, { "content": "pub fn add_offsets_and_bg(w: Box<dyn ui::Widget>, offset: f32) -> ZResult<ui::LayersLayout> {\n\n add_bg(add_offsets(w, offset))\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 45, "score": 198375.75063885472 }, { "content": "pub fn remove_widget<M: Clone>(gui: &mut ui::Gui<M>, widget: &mut Option<ui::RcWidget>) -> ZResult {\n\n if let Some(w) = widget.take() {\n\n gui.remove(&w);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 46, "score": 198276.3653852567 }, { "content": "fn show_blood_spot(view: &mut BattleView, at: PosHex) -> ZResult<Box<dyn Action>> {\n\n let mut sprite = Sprite::from_texture(textures().map.blood, view.tile_size() * 2.0);\n\n sprite.set_centered(true);\n\n sprite.set_color([1.0, 1.0, 1.0, 0.0].into());\n\n sprite.set_pos(view.hex_to_point(at) + Vec2::new(0.0, view.tile_size() * 0.1));\n\n let color_final: Color = [1.0, 1.0, 1.0, 1.0].into();\n\n let time = time_s(0.6);\n\n let layer = view.layers().blood.clone();\n\n let duration = BLOOD_SPRITE_DURATION_TURNS;\n\n view.add_disappearing_sprite(&layer, &sprite, duration, color_final.a);\n\n Ok(seq([\n\n action::Show::new(&layer, &sprite).boxed(),\n\n action::ChangeColorTo::new(&sprite, color_final, time).boxed(),\n\n ]))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 47, "score": 197534.60454122996 }, { "content": "fn show_dust_at_pos(view: &mut BattleView, at: PosHex) -> ZResult<Box<dyn Action>> {\n\n let point = view.hex_to_point(at);\n\n let count = 9;\n\n show_dust(view, point, count)\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 48, "score": 197534.60454122996 }, { "content": "fn show_explosion_ground_mark(view: &mut BattleView, at: PosHex) -> ZResult<Box<dyn Action>> {\n\n let tex = textures().map.explosion_ground_mark;\n\n let mut sprite = Sprite::from_texture(tex, view.tile_size() * 2.0);\n\n sprite.set_centered(true);\n\n sprite.set_color([1.0, 1.0, 1.0, 1.0].into());\n\n sprite.set_pos(view.hex_to_point(at));\n\n let layer = view.layers().blood.clone();\n\n let duration = BLOOD_SPRITE_DURATION_TURNS;\n\n view.add_disappearing_sprite(&layer, &sprite, duration, sprite.color().a);\n\n Ok(action::Show::new(&layer, &sprite).boxed())\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 50, "score": 195085.63005218515 }, { "content": "fn remove_brief_agent_info(view: &mut BattleView, id: Id) -> ZResult<Box<dyn Action>> {\n\n let mut actions = Vec::new();\n\n let sprites = view.agent_info_get(id);\n\n for sprite in sprites {\n\n let color = sprite.color();\n\n let color = Color { a: 0.0, ..color };\n\n actions.push(fork(seq([\n\n action::ChangeColorTo::new(&sprite, color, time_s(0.4)).boxed(),\n\n action::Hide::new(&view.layers().dots, &sprite).boxed(),\n\n ])));\n\n }\n\n Ok(seq(actions))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 51, "score": 195085.63005218515 }, { "content": "fn execute_use_ability_rage(_: &mut State, _: &command::UseAbility) -> ExecuteContext {\n\n ExecuteContext::default()\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 52, "score": 194945.25941753696 }, { "content": "fn apply_event(state: &mut State, event: &Event) {\n\n match event.active_event {\n\n ActiveEvent::Create => {}\n\n ActiveEvent::MoveTo(ref ev) => apply_event_move_to(state, ev),\n\n ActiveEvent::Attack(ref ev) => apply_event_attack(state, ev),\n\n ActiveEvent::EndTurn(ref ev) => apply_event_end_turn(state, ev),\n\n ActiveEvent::EndBattle(ref ev) => apply_event_end_battle(state, ev),\n\n ActiveEvent::BeginTurn(ref ev) => apply_event_begin_turn(state, ev),\n\n ActiveEvent::UseAbility(ref ev) => apply_event_use_ability(state, ev),\n\n ActiveEvent::UsePassiveAbility(ref ev) => apply_event_use_passive_ability(state, ev),\n\n ActiveEvent::EffectTick(ref ev) => apply_event_effect_tick(state, ev),\n\n ActiveEvent::EffectEnd(ref ev) => apply_event_effect_end(state, ev),\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 53, "score": 193512.5078103525 }, { "content": "fn execute_use_ability_jump(_: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n context.moved_actor_ids.push(command.id);\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 54, "score": 192147.00805645762 }, { "content": "fn execute_use_ability_dash(_: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n context.moved_actor_ids.push(command.id);\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 55, "score": 192147.00805645762 }, { "content": "fn apply_effect_stun(state: &mut State, id: Id) {\n\n let parts = state.parts_mut();\n\n let agent = parts.agent.get_mut(id);\n\n agent.moves.0 = 0;\n\n agent.attacks.0 = 0;\n\n agent.jokers.0 = 0;\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 56, "score": 191228.32088297416 }, { "content": "fn apply_effect_vanish(state: &mut State, id: Id) {\n\n let parts = state.parts_mut();\n\n parts.remove(id);\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 57, "score": 191228.32088297416 }, { "content": "fn apply_effect_bloodlust(state: &mut State, id: Id) {\n\n let parts = state.parts_mut();\n\n let agent = parts.agent.get_mut(id);\n\n agent.jokers.0 += 3;\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 58, "score": 191228.32088297416 }, { "content": "fn update_cooldowns_for_object(state: &mut State, id: Id) {\n\n let parts = state.parts_mut();\n\n if let Some(abilities) = parts.abilities.get_opt_mut(id) {\n\n for ability in &mut abilities.0 {\n\n ability.status.update();\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 59, "score": 191228.32088297416 }, { "content": "pub fn get_armor(state: &State, id: Id) -> Strength {\n\n let parts = state.parts();\n\n let default = Strength(0);\n\n parts.armor.get_opt(id).map(|v| v.armor).unwrap_or(default)\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 60, "score": 190644.64175460028 }, { "content": "// TODO: simplify\n\n/// Ticks and kills all the lasting effects.\n\nfn execute_effects(state: &mut State, cb: Cb) {\n\n let phase = Phase::from_player_id(state.player_id());\n\n for id in state.parts().effects.ids_collected() {\n\n for effect in &state.parts().effects.get(id).0.clone() {\n\n if effect.phase != phase {\n\n continue;\n\n }\n\n assert!(state.parts().is_exist(id));\n\n {\n\n let active_event = event::EffectTick {\n\n id,\n\n effect: effect.effect,\n\n };\n\n let mut target_effects = Vec::new();\n\n match effect.effect {\n\n effect::Lasting::Poison => {\n\n let strength = state.parts().strength.get(id).strength;\n\n if strength > battle::Strength(1) {\n\n let damage = battle::Strength(1);\n\n target_effects.push(wound_or_kill(state, id, damage));\n", "file_path": "src/core/battle/execute.rs", "rank": 61, "score": 190355.79982290277 }, { "content": "fn execute_use_ability_long_jump(_: &mut State, command: &command::UseAbility) -> ExecuteContext {\n\n let mut context = ExecuteContext::default();\n\n context.moved_actor_ids.push(command.id);\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 62, "score": 189473.90584084712 }, { "content": "fn update_cooldowns(state: &mut State, player_id: PlayerId) {\n\n for id in state::players_agent_ids(state, player_id) {\n\n update_cooldowns_for_object(state, id);\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 63, "score": 189046.77678954322 }, { "content": "fn apply_lasting_effect_stun(state: &mut State, id: Id) {\n\n let parts = state.parts_mut();\n\n let agent = parts.agent.get_mut(id);\n\n agent.moves.0 = 0;\n\n agent.attacks.0 = 0;\n\n agent.jokers.0 = 0;\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 64, "score": 189046.77678954322 }, { "content": "fn show_flare(view: &mut BattleView, at: PosHex, color: Color) -> ZResult<Box<dyn Action>> {\n\n let scale = 1.0;\n\n show_flare_scale_time(view, at, color, scale, time_s(TIME_DEFAULT_FLARE))\n\n}\n\n\n", "file_path": "src/screen/battle/visualize.rs", "rank": 65, "score": 188404.76337042695 }, { "content": "pub fn blocker_id_at(state: &State, pos: PosHex) -> Id {\n\n blocker_id_at_opt(state, pos).unwrap()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 66, "score": 188357.5684985015 }, { "content": "pub fn is_tile_blocked(state: &State, pos: PosHex) -> bool {\n\n assert!(state.map().is_inboard(pos));\n\n for id in state.parts().blocker.ids() {\n\n if state.parts().pos.get(id).0 == pos {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 67, "score": 188357.5684985015 }, { "content": "fn execute_planned_abilities(state: &mut State, cb: Cb) {\n\n let mut ids = state.parts().schedule.ids_collected();\n\n ids.sort();\n\n for obj_id in ids {\n\n let pos = state.parts().pos.get(obj_id).0;\n\n let mut activated = Vec::new();\n\n {\n\n let schedule = state.parts().schedule.get(obj_id);\n\n for planned in &schedule.planned {\n\n if planned.rounds.0 <= 0 {\n\n trace!(\"planned ability: ready!\");\n\n let c = command::UseAbility {\n\n ability: planned.ability,\n\n id: obj_id,\n\n pos,\n\n };\n\n activated.push(c);\n\n }\n\n }\n\n }\n\n for command in activated {\n\n if state.parts().is_exist(obj_id) {\n\n execute_use_ability(state, cb, &command);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 68, "score": 187845.79131069296 }, { "content": "fn reset_moves_and_attacks(state: &mut State, player_id: PlayerId) {\n\n for id in state::players_agent_ids(state, player_id) {\n\n let agent = state.parts_mut().agent.get_mut(id);\n\n agent.moves = agent.base_moves;\n\n agent.attacks = agent.base_attacks;\n\n agent.jokers = agent.base_jokers;\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 69, "score": 186960.7067670088 }, { "content": "pub fn zrng() -> impl rand::Rng {\n\n QuadRand\n\n}\n\n\n", "file_path": "src/core/utils.rs", "rank": 70, "score": 186721.15499100933 }, { "content": "pub fn is_tile_completely_free(state: &State, pos: PosHex) -> bool {\n\n if !state.map().is_inboard(pos) {\n\n return false;\n\n }\n\n for id in state.parts().pos.ids() {\n\n if state.parts().pos.get(id).0 == pos {\n\n return false;\n\n }\n\n }\n\n true\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 71, "score": 186173.28837435215 }, { "content": "pub fn random_free_pos(state: &State) -> Option<PosHex> {\n\n assert!(!state.deterministic_mode());\n\n let attempts = 30;\n\n let radius = state.map().radius();\n\n for _ in 0..attempts {\n\n let pos = PosHex {\n\n q: roll_dice(-radius.0, radius.0),\n\n r: roll_dice(-radius.0, radius.0),\n\n };\n\n if state::is_tile_plain_and_completely_free(state, pos) {\n\n return Some(pos);\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/core/battle/scenario.rs", "rank": 72, "score": 185870.4122768071 }, { "content": "fn apply_event_move_to(state: &mut State, event: &event::MoveTo) {\n\n let parts = state.parts_mut();\n\n let agent = parts.agent.get_mut(event.id);\n\n let pos = parts.pos.get_mut(event.id);\n\n pos.0 = event.path.to();\n\n if agent.moves.0 > 0 {\n\n agent.moves.0 -= event.cost.0;\n\n } else {\n\n agent.jokers.0 -= event.cost.0;\n\n }\n\n assert!(agent.moves >= Moves(0));\n\n assert!(agent.jokers >= Jokers(0));\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 73, "score": 185776.00707412226 }, { "content": "fn apply_event_attack(state: &mut State, event: &event::Attack) {\n\n let parts = state.parts_mut();\n\n let agent = parts.agent.get_mut(event.attacker_id);\n\n if agent.attacks.0 > 0 {\n\n agent.attacks.0 -= 1;\n\n } else {\n\n agent.jokers.0 -= 1;\n\n }\n\n assert!(agent.attacks >= Attacks(0));\n\n assert!(agent.jokers >= Jokers(0));\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 74, "score": 185776.00707412226 }, { "content": "fn execute_event_end_turn(state: &mut State, cb: Cb) {\n\n let player_id_old = state.player_id();\n\n let active_event = event::EndTurn {\n\n player_id: player_id_old,\n\n }\n\n .into();\n\n let mut actor_ids = state::players_agent_ids(state, player_id_old);\n\n actor_ids.sort();\n\n let event = Event {\n\n active_event,\n\n actor_ids,\n\n instant_effects: Vec::new(),\n\n timed_effects: Vec::new(),\n\n scheduled_abilities: Vec::new(),\n\n };\n\n do_event(state, cb, &event);\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 75, "score": 185456.55529427045 }, { "content": "fn execute_event_begin_turn(state: &mut State, cb: Cb) {\n\n let player_id_new = state.next_player_id();\n\n let active_event = event::BeginTurn {\n\n player_id: player_id_new,\n\n }\n\n .into();\n\n let mut actor_ids = state::players_agent_ids(state, player_id_new);\n\n actor_ids.sort();\n\n let event = Event {\n\n active_event,\n\n actor_ids,\n\n instant_effects: Vec::new(),\n\n timed_effects: Vec::new(),\n\n scheduled_abilities: Vec::new(),\n\n };\n\n do_event(state, cb, &event);\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 76, "score": 185456.55529427045 }, { "content": "fn try_execute_end_battle(state: &mut State, cb: Cb) {\n\n for i in 0..state.scenario().players_count {\n\n let player_id = PlayerId(i);\n\n let enemies_count = state::enemy_agent_ids(state, player_id).len();\n\n if enemies_count == 0 {\n\n let result = BattleResult {\n\n winner_id: player_id,\n\n survivor_types: state::players_agent_types(state, PlayerId(0)),\n\n };\n\n let event = Event {\n\n active_event: event::EndBattle { result }.into(),\n\n actor_ids: Vec::new(),\n\n instant_effects: Vec::new(),\n\n timed_effects: Vec::new(),\n\n scheduled_abilities: Vec::new(),\n\n };\n\n do_event(state, cb, &event);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 77, "score": 185456.55529427045 }, { "content": "pub fn ids_at(state: &State, pos: PosHex) -> Vec<Id> {\n\n let i = state.parts().pos.ids();\n\n i.filter(|&id| state.parts().pos.get(id).0 == pos).collect()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 78, "score": 185324.07533965659 }, { "content": "pub fn is_tile_plain_and_completely_free(state: &State, pos: PosHex) -> bool {\n\n if !state.map().is_inboard(pos) || state.map().tile(pos) != TileType::Plain {\n\n return false;\n\n }\n\n for id in state.parts().pos.ids() {\n\n if state.parts().pos.get(id).0 == pos {\n\n return false;\n\n }\n\n }\n\n true\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 79, "score": 184084.62117743702 }, { "content": "pub fn blocker_ids_at(state: &State, pos: PosHex) -> Vec<Id> {\n\n let i = state.parts().blocker.ids();\n\n i.filter(|&id| state.parts().pos.get(id).0 == pos).collect()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 80, "score": 183139.79521550724 }, { "content": "pub fn agent_ids_at(state: &State, pos: PosHex) -> Vec<Id> {\n\n let i = state.parts().agent.ids();\n\n i.filter(|&id| state.parts().pos.get(id).0 == pos).collect()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 81, "score": 183139.79521550724 }, { "content": "fn add_components(state: &mut State, id: Id, components: &[Component]) {\n\n let parts = state.parts_mut();\n\n for component in components {\n\n add_component(parts, id, component.clone());\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 82, "score": 182755.16615549615 }, { "content": "pub fn check(state: &State, command: &Command) -> Result<(), Error> {\n\n trace!(\"check: {:?}\", command);\n\n if state.battle_result().is_some() {\n\n return Err(Error::BattleEnded);\n\n }\n\n match *command {\n\n Command::Create(ref command) => check_command_create(state, command),\n\n Command::MoveTo(ref command) => check_command_move_to(state, command),\n\n Command::Attack(ref command) => check_command_attack(state, command),\n\n Command::EndTurn(ref command) => check_command_end_turn(state, command),\n\n Command::UseAbility(ref command) => check_command_use_ability(state, command),\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq)]\n\npub enum Error {\n\n NotEnoughMovePoints,\n\n NotEnoughStrength,\n\n BadActorId,\n\n BadTargetId,\n", "file_path": "src/core/battle/check.rs", "rank": 83, "score": 181944.4320960958 }, { "content": "fn apply_event_end_turn(state: &mut State, event: &event::EndTurn) {\n\n // Update attacks\n\n {\n\n let parts = state.parts_mut();\n\n for id in parts.agent.ids_collected() {\n\n let agent = parts.agent.get_mut(id);\n\n let player_id = parts.belongs_to.get(id).0;\n\n if player_id == event.player_id {\n\n agent.attacks.0 += agent.reactive_attacks.0;\n\n }\n\n if let Some(effects) = parts.effects.get_opt(id) {\n\n for effect in &effects.0 {\n\n if let effect::Lasting::Stun = effect.effect {\n\n agent.attacks.0 = 0;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n // Remove outdated planned abilities\n", "file_path": "src/core/battle/state/apply.rs", "rank": 84, "score": 181692.8483678708 }, { "content": "fn apply_event_begin_turn(state: &mut State, event: &event::BeginTurn) {\n\n state.set_player_id(event.player_id);\n\n update_lasting_effects_duration(state);\n\n reset_moves_and_attacks(state, event.player_id);\n\n apply_lasting_effects(state);\n\n update_cooldowns(state, event.player_id);\n\n tick_planned_abilities(state);\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 85, "score": 181692.8483678708 }, { "content": "fn apply_event_end_battle(state: &mut State, event: &event::EndBattle) {\n\n state.set_battle_result(event.result.clone());\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 86, "score": 181692.8483678708 }, { "content": "fn do_event(state: &mut State, cb: Cb, event: &Event) {\n\n cb(state, event, ApplyPhase::Pre);\n\n state.apply(event);\n\n cb(state, event, ApplyPhase::Post);\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 87, "score": 181554.1806766459 }, { "content": "pub fn blocker_id_at_opt(state: &State, pos: PosHex) -> Option<Id> {\n\n let ids = blocker_ids_at(state, pos);\n\n if ids.len() == 1 {\n\n Some(ids[0])\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 88, "score": 181051.12801859208 }, { "content": "pub fn agent_id_at_opt(state: &State, pos: PosHex) -> Option<Id> {\n\n let ids = agent_ids_at(state, pos);\n\n if ids.len() == 1 {\n\n Some(ids[0])\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 89, "score": 181051.12801859208 }, { "content": "fn try_execute_passive_abilities_on_begin_turn(state: &mut State, cb: Cb) {\n\n for id in state::players_agent_ids(state, state.player_id()) {\n\n try_execute_passive_abilities_tick(state, cb, id);\n\n }\n\n\n\n // TODO: extract to some self-abilities-method?\n\n {\n\n let ids = state.parts().passive_abilities.ids_collected();\n\n for id in ids {\n\n assert!(state.parts().is_exist(id));\n\n let owner = match state.parts().belongs_to.get_opt(id) {\n\n Some(owner) => owner.0,\n\n None => continue,\n\n };\n\n if state.player_id() != owner {\n\n continue;\n\n }\n\n let abilities = state.parts().passive_abilities.get(id).clone();\n\n for &ability in &abilities.0 {\n\n assert!(state.parts().is_exist(id));\n", "file_path": "src/core/battle/execute.rs", "rank": 90, "score": 181006.32418905746 }, { "content": "fn apply_effect_instant(state: &mut State, id: Id, effect: &Effect) {\n\n trace!(\"effect::apply_instant: {:?} ({})\", effect, effect.to_str());\n\n match *effect {\n\n Effect::Create(ref effect) => apply_effect_create(state, id, effect),\n\n Effect::Kill(ref effect) => apply_effect_kill(state, id, effect),\n\n Effect::Vanish => apply_effect_vanish(state, id),\n\n Effect::Stun => apply_effect_stun(state, id),\n\n Effect::Heal(ref effect) => apply_effect_heal(state, id, effect),\n\n Effect::Wound(ref effect) => apply_effect_wound(state, id, effect),\n\n Effect::Knockback(ref effect) => apply_effect_knockback(state, id, effect),\n\n Effect::FlyOff(ref effect) => apply_effect_fly_off(state, id, effect),\n\n Effect::Throw(ref effect) => apply_effect_throw(state, id, effect),\n\n Effect::Dodge(_) => {}\n\n Effect::Bloodlust => apply_effect_bloodlust(state, id),\n\n }\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 91, "score": 180669.0961329617 }, { "content": "fn start_fire(state: &mut State, pos: PosHex) -> ExecuteContext {\n\n let vanish = component::PlannedAbility {\n\n rounds: 2.into(), // TODO: Replace this magic number\n\n phase: Phase::from_player_id(state.player_id()),\n\n ability: Ability::Vanish,\n\n };\n\n let mut context = ExecuteContext::default();\n\n if let Some(id) = state::obj_with_passive_ability_at(state, pos, PassiveAbility::Burn) {\n\n context.scheduled_abilities.push((id, vec![vanish]));\n\n } else {\n\n let effect_create = effect_create_object(state, &\"fire\".into(), pos);\n\n let id = state.alloc_id();\n\n context.instant_effects.push((id, vec![effect_create]));\n\n context.scheduled_abilities.push((id, vec![vanish]));\n\n for target_id in state::agent_ids_at(state, pos) {\n\n context.merge_with(try_execute_passive_ability_burn(state, target_id));\n\n }\n\n }\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 92, "score": 179908.59355586855 }, { "content": "fn window_conf() -> window::Conf {\n\n window::Conf {\n\n window_title: \"Zemeroth\".to_owned(),\n\n high_dpi: true,\n\n ..Default::default()\n\n }\n\n}\n\n\n\n#[mq::main(window_conf)]\n\n#[macroquad(crate_rename = \"mq\")]\n\nasync fn main() -> ZResult {\n\n // std::env isn't supported on WASM.\n\n #[cfg(not(target_arch = \"wasm32\"))]\n\n if std::env::var(\"RUST_BACKTRACE\").is_err() {\n\n std::env::set_var(\"RUST_BACKTRACE\", \"1\");\n\n }\n\n env_logger::init();\n\n quad_rand::srand(mq::miniquad::date::now() as _);\n\n mq::file::set_pc_assets_folder(\"assets\");\n\n assets::load().await.expect(\"Can't load assets\");\n\n let mut state = MainState::new().expect(\"Can't create the main state\");\n\n loop {\n\n state.tick().expect(\"Tick failed\");\n\n window::next_frame().await;\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 93, "score": 179561.91969230532 }, { "content": "pub fn enemy_agent_ids(state: &State, player_id: PlayerId) -> Vec<Id> {\n\n let i = state.parts().agent.ids();\n\n i.filter(|&id| !is_agent_belong_to(state, player_id, id))\n\n .collect()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 94, "score": 179051.5707077792 }, { "content": "pub fn players_agent_ids(state: &State, player_id: PlayerId) -> Vec<Id> {\n\n let i = state.parts().agent.ids();\n\n i.filter(|&id| is_agent_belong_to(state, player_id, id))\n\n .collect()\n\n}\n\n\n", "file_path": "src/core/battle/state.rs", "rank": 95, "score": 179051.5707077792 }, { "content": "fn build_panel_renown(state: &State) -> ZResult<Box<dyn ui::Widget>> {\n\n let font = assets::get().font;\n\n let mut layout = Box::new(ui::VLayout::new().stretchable(true));\n\n let renown_text = &format!(\"Your renown is: {}r\", state.renown().0);\n\n layout.add(label(font, renown_text)?);\n\n let layout = utils::add_offsets_and_bg_big(layout)?.stretchable(true);\n\n Ok(Box::new(layout))\n\n}\n\n\n", "file_path": "src/screen/campaign.rs", "rank": 96, "score": 178182.16167099867 }, { "content": "fn apply_effect_kill(state: &mut State, id: Id, _: &effect::Kill) {\n\n let parts = state.parts_mut();\n\n parts.remove(id);\n\n}\n\n\n", "file_path": "src/core/battle/state/apply.rs", "rank": 97, "score": 177869.84217573726 }, { "content": "fn create_poison_cloud(state: &mut State, pos: PosHex) -> ExecuteContext {\n\n let vanish = component::PlannedAbility {\n\n rounds: 2.into(), // TODO: Replace this magic number\n\n phase: Phase::from_player_id(state.player_id()),\n\n ability: Ability::Vanish,\n\n };\n\n let mut context = ExecuteContext::default();\n\n if let Some(id) = state::obj_with_passive_ability_at(state, pos, PassiveAbility::Poison) {\n\n context.scheduled_abilities.push((id, vec![vanish]));\n\n } else {\n\n let effect_create = effect_create_object(state, &\"poison_cloud\".into(), pos);\n\n let id = state.alloc_id();\n\n context.instant_effects.push((id, vec![effect_create]));\n\n context.scheduled_abilities.push((id, vec![vanish]));\n\n for target_id in state::agent_ids_at(state, pos) {\n\n context.merge_with(try_execute_passive_ability_poison(state, target_id));\n\n }\n\n }\n\n context\n\n}\n\n\n", "file_path": "src/core/battle/execute.rs", "rank": 98, "score": 177735.5544736365 }, { "content": "pub fn make_and_set_camera(aspect_ratio: f32) -> Camera2D {\n\n let camera = Camera2D::from_display_rect(Rect {\n\n x: -aspect_ratio,\n\n y: -1.0,\n\n w: aspect_ratio * 2.0,\n\n h: 2.0,\n\n });\n\n set_camera(&camera);\n\n camera\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 99, "score": 177208.0150949038 } ]
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>(a: &ArrayBase<SA, Ix2>, p: &[usize], b: &ArrayBase<SB, Ix1>) -> Array1<A>\n\nwhere\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: Data<Elem = A>,\n\n{\n\n assert_eq!(a.nrows(), p.len());\n\n assert_eq!(p.len(), b.len());\n\n assert!(a.ncols() >= p.len());\n\n unsafe {\n\n let mut x = b.to_owned();\n\n lapack::laswp(1, x.as_mut_ptr(), x.stride_of(Axis(0)), 1, 0, p);\n\n for (i, row) in a.lanes(Axis(1)).into_iter().enumerate() {\n\n for (k, a_elem) in row.iter().take(i).enumerate() {\n\n let prod = *a_elem * *x.uget(k);\n\n *x.uget_mut(i) -= prod;\n\n }\n\n }\n\n for i in (0..x.len()).rev() {\n\n for k in i + 1..x.len() {\n", "file_path": "src/lapack/getrs.rs", "rank": 0, "score": 231700.09248089785 }, { "content": "#[allow(dead_code)]\n\npub fn upper<A, SA, SB>(a: &ArrayBase<SA, Ix2>, b: &mut ArrayBase<SB, Ix2>)\n\nwhere\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: DataMut<Elem = A>,\n\n{\n\n let col_min = cmp::min(a.ncols(), b.ncols());\n\n for (i, (a_row, mut b_row)) in a\n\n .lanes(Axis(1))\n\n .into_iter()\n\n .zip(b.lanes_mut(Axis(1)).into_iter())\n\n .enumerate()\n\n .take(col_min)\n\n {\n\n for (a_v, b_v) in a_row\n\n .slice(s![i..])\n\n .iter()\n\n .zip(b_row.slice_mut(s![i..]).into_iter())\n\n {\n\n *b_v = *a_v;\n", "file_path": "src/lapack/lacpy.rs", "rank": 1, "score": 206593.98872179893 }, { "content": "#[allow(dead_code)]\n\npub fn lower<A, SA, SB>(a: &ArrayBase<SA, Ix2>, b: &mut ArrayBase<SB, Ix2>)\n\nwhere\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: DataMut<Elem = A>,\n\n{\n\n let ncols = cmp::min(a.ncols(), b.ncols());\n\n for (i, (a_row, mut b_row)) in a\n\n .lanes(Axis(1))\n\n .into_iter()\n\n .zip(b.lanes_mut(Axis(1)).into_iter())\n\n .enumerate()\n\n {\n\n let ncols = cmp::min(ncols, i + 1);\n\n for (a_v, b_v) in a_row\n\n .slice(s![..ncols])\n\n .iter()\n\n .zip(b_row.slice_mut(s![..ncols]).into_iter())\n\n {\n\n *b_v = *a_v;\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/lapack/lacpy.rs", "rank": 2, "score": 206593.98872179893 }, { "content": "/// Computes the QR factorization of a matrix.\n\npub fn geqrf<A, S>(a: &mut ArrayBase<S, Ix2>) -> Array1<A>\n\nwhere\n\n A: Scalar + Div<<A as Scalar>::Real, Output = A> + MulAssign<<A as Scalar>::Real>,\n\n S: DataMut<Elem = A>,\n\n{\n\n let min_dim = cmp::min(a.nrows(), a.ncols());\n\n let mut tau = Array1::<A>::zeros(min_dim);\n\n for i in 0..min_dim {\n\n let bottom = a.nrows();\n\n let (beta, _, t) = lapack::larfg(a[(i, i)], a.column_mut(i).slice_mut(s![i + 1..bottom]));\n\n tau[i] = t;\n\n if i < a.ncols() {\n\n a[(i, i)] = A::one();\n\n let v = a.column(i).slice(s![i..]).to_owned();\n\n lapack::larf::left(&v, t.conj(), &mut a.slice_mut(s![i.., i + 1..]));\n\n a[(i, i)] = beta.into();\n\n }\n\n }\n\n tau\n\n}\n", "file_path": "src/lapack/geqrf.rs", "rank": 3, "score": 180490.4455935692 }, { "content": "/// Generates an elementary reflector (Householder matrix).\n\npub fn larfg<A, S>(mut alpha: A, mut x: ArrayBase<S, Ix1>) -> (A::Real, ArrayBase<S, Ix1>, A)\n\nwhere\n\n A: Scalar + Div<<A as Scalar>::Real, Output = A> + MulAssign<<A as Scalar>::Real>,\n\n S: DataMut<Elem = A>,\n\n{\n\n let mut x_norm = blas::nrm2(&x);\n\n if x_norm == A::zero().re() && alpha.im() == A::zero().re() {\n\n return (alpha.re(), x, A::zero());\n\n }\n\n\n\n let mut beta = -lapack::lapy3(alpha.re(), alpha.im(), x_norm).copysign(alpha.re());\n\n let safe_min = A::Real::sfmin() / A::Real::eps();\n\n let mut knt = 0;\n\n if beta.abs() < safe_min {\n\n let safe_min_recip = safe_min.recip();\n\n loop {\n\n knt += 1;\n\n blas::scal(safe_min_recip, &mut x);\n\n beta *= safe_min_recip;\n\n alpha *= safe_min_recip;\n", "file_path": "src/lapack/larfg.rs", "rank": 4, "score": 177720.0045449945 }, { "content": "/// Performs `x` = `a` * `x` for an upper-triangular matrix `a` and a column\n\n/// vector `x`.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `a`'s number of columns is not equal to `x`'s number of elements.\n\npub fn upper_notrans<A, SA, SX>(a: &ArrayBase<SA, Ix2>, x: &mut ArrayBase<SX, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SX: DataMut<Elem = A>,\n\n{\n\n assert_eq!(a.ncols(), x.len());\n\n for (j, a_col) in a.lanes(Axis(0)).into_iter().enumerate() {\n\n let multiplier = *unsafe { x.uget(j) };\n\n if multiplier == A::zero() {\n\n continue;\n\n }\n\n for (i, a_elem) in a_col.iter().take(j).enumerate() {\n\n *unsafe { x.uget_mut(i) } += multiplier * *a_elem;\n\n }\n\n *unsafe { x.uget_mut(j) } *= a_col[j];\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/blas/trmv.rs", "rank": 5, "score": 155529.40043452638 }, { "content": "#[allow(dead_code)]\n\npub fn unglq<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n ungl2(a, tau)\n\n}\n\n\n", "file_path": "src/lapack/unglq.rs", "rank": 6, "score": 155526.32397491205 }, { "content": "#[allow(dead_code)]\n\npub fn p_square<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n if a.is_empty() {\n\n return;\n\n }\n\n\n\n assert_eq!(a.nrows(), a.ncols());\n\n assert_eq!(a.ncols(), tau.len());\n\n a.column_mut(0).fill(A::zero());\n\n a.row_mut(0)[0] = A::one();\n\n\n\n for (j, mut col) in a.lanes_mut(Axis(0)).into_iter().enumerate().skip(1) {\n\n for i in (1..j).rev() {\n\n col[i] = col[i - 1];\n\n }\n\n col[0] = A::zero();\n", "file_path": "src/lapack/ungbr.rs", "rank": 7, "score": 155526.32397491205 }, { "content": "#[allow(dead_code)]\n\npub fn ungrq<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n ungr2(a, tau)\n\n}\n\n\n", "file_path": "src/lapack/ungrq.rs", "rank": 8, "score": 155526.32397491205 }, { "content": "#[allow(dead_code)]\n\npub fn ungqr<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n ung2r(a, tau)\n\n}\n\n\n", "file_path": "src/lapack/ungqr.rs", "rank": 9, "score": 155526.32397491205 }, { "content": "#[allow(dead_code)]\n\npub fn q_tall<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n if a.is_empty() {\n\n return;\n\n }\n\n\n\n assert!(a.nrows() >= a.ncols());\n\n assert!(a.ncols() >= tau.len());\n\n lapack::ungqr(a, &tau);\n\n}\n\n\n", "file_path": "src/lapack/ungbr.rs", "rank": 10, "score": 155526.32397491205 }, { "content": "#[allow(dead_code)]\n\npub fn forward_columnwise<A, SV, ST>(v: &ArrayBase<SV, Ix2>, tau: &ArrayBase<ST, Ix1>) -> Array2<A>\n\nwhere\n\n A: Scalar,\n\n SV: Data<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n let mut triangular = Array2::zeros((v.ncols(), v.ncols()));\n\n if v.is_empty() {\n\n return triangular;\n\n }\n\n\n\n let mut prev_last_v = v.nrows();\n\n for (i, ((v_row_i, v_col_i), &tau_i)) in (v.rows().into_iter().zip(v.columns().into_iter()))\n\n .zip(tau.iter())\n\n .take(v.ncols())\n\n .enumerate()\n\n {\n\n if tau_i == A::zero() {\n\n continue;\n\n }\n", "file_path": "src/lapack/larft.rs", "rank": 11, "score": 153607.29571503156 }, { "content": "/// Computes `b` * `a` assuming `a` is a lower triangular matrix.\n\n///\n\n/// `UNIT` indicates whether to assume `a`'s diagonal elements are 1s.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `a` is not a square matrix, or `a`'s # of rows is different from\n\n/// `b`'s # of columns.\n\npub fn right_lower_notrans<A, SA, SB, const UNIT: bool>(\n\n a: &ArrayBase<SA, Ix2>,\n\n b: &mut ArrayBase<SB, Ix2>,\n\n) where\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: DataMut<Elem = A>,\n\n{\n\n assert!(a.is_square());\n\n assert_eq!(b.ncols(), a.nrows());\n\n for (j, a_col) in a.columns().into_iter().enumerate() {\n\n if !UNIT {\n\n b.column_mut(j).mul_assign(a_col[j]);\n\n }\n\n for k in j + 1..b.ncols() {\n\n let multiplier = a_col[k];\n\n if multiplier == A::zero() {\n\n continue;\n\n }\n\n\n\n for i in 0..b.nrows() {\n\n let b_i_k = b[(i, k)];\n\n b[(i, j)] += multiplier * b_i_k;\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/blas/trmm.rs", "rank": 12, "score": 152473.20903456357 }, { "content": "/// Computes `b` * `a^H` assuming `a` is a upper triangular matrix.\n\n///\n\n/// `UNIT` indicates whether to assume `a`'s diagonal elements are 1s.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `a` is not a square matrix, or `a`'s # of rows is different from\n\n/// `b`'s # of columns.\n\npub fn right_upper_conjtrans<A, SA, SB, const UNIT: bool>(\n\n a: &ArrayBase<SA, Ix2>,\n\n b: &mut ArrayBase<SB, Ix2>,\n\n) where\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: DataMut<Elem = A>,\n\n{\n\n assert!(a.is_square());\n\n assert_eq!(b.ncols(), a.nrows());\n\n for k in 0..a.ncols() {\n\n for j in 0..k {\n\n let multiplier = a[(j, k)].conj();\n\n if multiplier == A::zero() {\n\n continue;\n\n }\n\n\n\n for i in 0..b.nrows() {\n\n let b_i_k = b[(i, k)];\n\n b[(i, j)] += multiplier * b_i_k;\n", "file_path": "src/blas/trmm.rs", "rank": 13, "score": 152473.15821165324 }, { "content": "#[allow(dead_code)]\n\npub fn right_lower_conjtrans<A, SA, SB, const UNIT: bool>(\n\n a: &ArrayBase<SA, Ix2>,\n\n b: &mut ArrayBase<SB, Ix2>,\n\n) where\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: DataMut<Elem = A>,\n\n{\n\n assert!(a.is_square());\n\n assert_eq!(b.ncols(), a.nrows());\n\n for k in (0..a.ncols()).rev() {\n\n for j in k + 1..b.ncols() {\n\n let multiplier = a[(j, k)].conj();\n\n if multiplier == A::zero() {\n\n continue;\n\n }\n\n\n\n for i in 0..b.nrows() {\n\n let increase = multiplier * b[(i, k)];\n\n b[(i, j)] += increase;\n", "file_path": "src/blas/trmm.rs", "rank": 14, "score": 152470.41785665788 }, { "content": "/// Applies an elementary reflector to a matrix.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `v` is a zero vector, or `c` is a zero matrix.\n\npub fn right<A, SV, SC>(v: &ArrayBase<SV, Ix1>, tau: A, c: &mut ArrayBase<SC, Ix2>)\n\nwhere\n\n A: Scalar,\n\n SV: Data<Elem = A>,\n\n SC: DataMut<Elem = A>,\n\n{\n\n if tau == A::zero() {\n\n return;\n\n }\n\n let (last_v, _) = v\n\n .iter()\n\n .enumerate()\n\n .rev()\n\n .find(|(_, &elem)| elem != A::zero())\n\n .unwrap();\n\n let last_r = if let Some(last_r) = lapack::ilalr(&c.slice(s![.., 0..=last_v])) {\n\n last_r\n\n } else {\n\n return;\n\n };\n", "file_path": "src/lapack/larf.rs", "rank": 15, "score": 152068.44644500606 }, { "content": "/// Applies an elementary reflector to a matrix.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `v` is a zero vector, or `c` is a zero matrix.\n\npub fn left<A, SV, SC>(v: &ArrayBase<SV, Ix1>, tau: A, c: &mut ArrayBase<SC, Ix2>)\n\nwhere\n\n A: Scalar,\n\n SV: Data<Elem = A>,\n\n SC: DataMut<Elem = A>,\n\n{\n\n if tau == A::zero() {\n\n return;\n\n }\n\n let (last_v, _) = v\n\n .iter()\n\n .enumerate()\n\n .rev()\n\n .find(|(_, &elem)| elem != A::zero())\n\n .unwrap();\n\n let last_c = if let Some(last_c) = lapack::ilalc(&c.slice(s![0..=last_v, ..])) {\n\n last_c\n\n } else {\n\n return;\n\n };\n", "file_path": "src/lapack/larf.rs", "rank": 16, "score": 152068.4464450061 }, { "content": "#[allow(dead_code)]\n\npub fn maxabs<A, S>(a: &ArrayBase<S, Ix2>) -> A::Real\n\nwhere\n\n A: Scalar,\n\n S: Data<Elem = A>,\n\n{\n\n if a.is_empty() {\n\n return A::Real::zero();\n\n }\n\n\n\n a.into_iter()\n\n .map(|v| v.abs())\n\n .fold(A::Real::neg_infinity(), |max, v| {\n\n match max.partial_cmp(&v) {\n\n None => A::Real::nan(),\n\n Some(Ordering::Less) => v,\n\n Some(_) => max,\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/lapack/lange.rs", "rank": 17, "score": 149387.91901109298 }, { "content": "#[allow(dead_code)]\n\npub fn lower_zero<A, S>(a: &mut ArrayBase<S, Ix2>)\n\nwhere\n\n A: Scalar,\n\n S: DataMut<Elem = A>,\n\n{\n\n if a.ncols() == 0 {\n\n return;\n\n }\n\n\n\n let col_max = a.ncols() - 1;\n\n for (i, mut row) in a.lanes_mut(Axis(1)).into_iter().enumerate() {\n\n for v in row.slice_mut(s![..=cmp::min(i, col_max)]) {\n\n *v = A::zero();\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ndarray::{arr2, Array2};\n", "file_path": "src/lapack/laset.rs", "rank": 18, "score": 144903.58495442048 }, { "content": "/// Constructs a companion matrix.\n\n///\n\n/// # Errors\n\n///\n\n/// * [`InvalidInput::Shape`] if `a` contains less than two coefficients.\n\n/// * [`InvalidInput::Value`] if `a[0]` is zero.\n\n///\n\n/// [`InvalidInput::Shape`]: ../enum.InvalidInput.html#variant.Shape\n\n/// [`InvalidInput::Value`]: ../enum.InvalidInput.html#variant.Value\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use lair::matrix::companion;\n\n///\n\n/// let a = vec![1., -10., 31., -30.];\n\n/// let c = companion(&a).expect(\"valid input\");\n\n/// assert_eq!(c, ndarray::aview2(&[[10., -31., 30.], [1., 0., 0.], [0., 1., 0.]]));\n\n/// ```\n\npub fn companion<A>(a: &[A]) -> Result<Array2<A>, InvalidInput>\n\nwhere\n\n A: Scalar,\n\n{\n\n if a.len() < 2 {\n\n return Err(InvalidInput::Shape(format!(\n\n \"input polynomial has {} coefficient; expected at least two\",\n\n a.len()\n\n )));\n\n }\n\n if a[0] == A::zero() {\n\n return Err(InvalidInput::Value(format!(\n\n \"invalid first coefficient {}, expected a non-zero value\",\n\n a[0]\n\n )));\n\n }\n\n\n\n let mut matrix = Array2::<A>::zeros((a.len() - 1, a.len() - 1));\n\n for (mv, av) in matrix.row_mut(0).into_iter().zip(a.iter().skip(1)) {\n\n *mv = -*av / a[0];\n", "file_path": "src/matrix.rs", "rank": 19, "score": 142385.89951611508 }, { "content": "#[allow(dead_code)]\n\npub fn tall<A, S>(a: &mut ArrayBase<S, Ix2>) -> Bidiagonal<A>\n\nwhere\n\n A: Scalar + Div<<A as Scalar>::Real, Output = A> + MulAssign<<A as Scalar>::Real>,\n\n S: DataMut<Elem = A>,\n\n{\n\n unblocked_tall(a)\n\n}\n\n\n", "file_path": "src/lapack/gebrd.rs", "rank": 20, "score": 141348.8578030228 }, { "content": "/// Constructs a circulant matrix.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use lair::matrix::circulant;\n\n///\n\n/// let a = vec![1., 2., 3.];\n\n/// let c = circulant(&a);\n\n/// assert_eq!(c, ndarray::aview2(&[[1., 3., 2.], [2., 1., 3.], [3., 2., 1.]]));\n\n/// ```\n\npub fn circulant<A>(a: &[A]) -> Array2<A>\n\nwhere\n\n A: Copy,\n\n{\n\n let mut x = Array2::<A>::uninit((a.len(), a.len()));\n\n unsafe {\n\n for (i, a_elem) in a.iter().enumerate() {\n\n for j in 0..a.len() {\n\n *(x[[(i + j) % a.len(), j]].as_mut_ptr()) = *a_elem;\n\n }\n\n }\n\n x.assume_init()\n\n }\n\n}\n\n\n", "file_path": "src/matrix.rs", "rank": 21, "score": 137815.96185048946 }, { "content": "/// Solves a system of linear scalar equations.\n\n///\n\n/// # Errors\n\n///\n\n/// * [`InvalidInput::Shape`] if `a` is not a square matrix, or `a`'s number of\n\n/// rows and `b`'s length does not match.\n\n/// * [`InvalidInput::Value`] if `a` is a singular matrix.\n\n///\n\n/// [`InvalidInput::Shape`]: ../enum.InvalidInput.html#variant.Shape\n\n/// [`InvalidInput::Value`]: ../enum.InvalidInput.html#variant.Value\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use lair::equation::solve;\n\n///\n\n/// // Solve the system of equations:\n\n/// // 3 * x0 + x1 = 9\n\n/// // x0 + 2 * x1 = 8\n\n/// let a = ndarray::arr2(&[[3., 1.], [1., 2.]]);\n\n/// let b = ndarray::arr1(&[9., 8.]);\n\n/// let x = solve(&a, &b).expect(\"valid input\");\n\n/// assert_eq!(x, ndarray::aview1(&[2., 3.]));\n\n/// ```\n\npub fn solve<A, SA, SB>(\n\n a: &ArrayBase<SA, Ix2>,\n\n b: &ArrayBase<SB, Ix1>,\n\n) -> Result<Array1<A>, InvalidInput>\n\nwhere\n\n A: Scalar,\n\n A::Real: Real,\n\n SA: Data<Elem = A>,\n\n SB: Data<Elem = A>,\n\n{\n\n if !a.is_square() {\n\n return Err(InvalidInput::Shape(\n\n \"input matrix is not square\".to_string(),\n\n ));\n\n }\n\n if b.len() != a.nrows() {\n\n return Err(InvalidInput::Shape(format!(\n\n \"The number of elements in `b`, {}, must be the same as the number of rows in `a`, {}\",\n\n b.len(),\n\n a.nrows()\n\n )));\n\n }\n\n let factorized = lu::Factorized::from(a.to_owned());\n\n if factorized.is_singular() {\n\n Err(InvalidInput::Value(\"`a` is a singular matrix\".to_string()))\n\n } else {\n\n factorized.solve(b)\n\n }\n\n}\n", "file_path": "src/equation.rs", "rank": 22, "score": 136185.9592016922 }, { "content": "pub fn scal<TA, TX, S>(a: TA, x: &mut ArrayBase<S, Ix1>)\n\nwhere\n\n TA: Copy,\n\n TX: MulAssign<TA>,\n\n S: DataMut<Elem = TX>,\n\n{\n\n for elem in x.iter_mut() {\n\n *elem *= a;\n\n }\n\n}\n", "file_path": "src/blas/scal.rs", "rank": 23, "score": 134536.1906914358 }, { "content": "#[allow(dead_code)]\n\npub fn lapy2<A: Real>(x: A, y: A) -> A {\n\n (x * x + y * y).sqrt()\n\n}\n\n\n", "file_path": "src/lapack.rs", "rank": 24, "score": 134507.70288013757 }, { "content": "pub fn lapy3<A: Real>(x: A, y: A, z: A) -> A {\n\n (x * x + y * y + z * z).sqrt()\n\n}\n", "file_path": "src/lapack.rs", "rank": 25, "score": 131875.84154979914 }, { "content": "/// Generates all or part of the orthogonal matrix Q from a QR factorization.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `a` has more columns than rows, or has fewer columns than the\n\n/// number of elementary reflectors.\n\nfn ung2r<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n assert!(a.ncols() <= a.nrows(), \"too many columns in `a`\");\n\n assert!(tau.len() <= a.ncols(), \"too many reflectors\");\n\n\n\n if a.is_empty() {\n\n return;\n\n }\n\n\n\n a.slice_mut(s![.., tau.len()..]).fill(A::zero());\n\n for i in tau.len()..a.ncols() {\n\n *a.get_mut((i, i)).expect(\"valid index\") = A::one();\n\n }\n\n\n\n for (i, tau_i) in tau.iter().enumerate().rev() {\n\n if i < a.ncols() - 1 {\n", "file_path": "src/lapack/ungqr.rs", "rank": 26, "score": 131060.32227616507 }, { "content": "fn ungr2<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n assert!(a.ncols() >= a.nrows());\n\n assert!(a.nrows() >= tau.len());\n\n\n\n let a_nrows = a.nrows();\n\n let a_ncols = a.ncols();\n\n if tau.len() < a_nrows {\n\n for j in 0..a_ncols {\n\n for l in 0..a_nrows - tau.len() {\n\n a[(l, j)] = A::zero();\n\n }\n\n if j >= a_ncols - a_nrows && j < a_ncols - tau.len() {\n\n a[(j + a_nrows - a_ncols, j)] = A::one();\n\n }\n\n }\n", "file_path": "src/lapack/ungrq.rs", "rank": 27, "score": 131060.32227616507 }, { "content": "fn ungl2<A, SA, ST>(a: &mut ArrayBase<SA, Ix2>, tau: &ArrayBase<ST, Ix1>)\n\nwhere\n\n A: Scalar,\n\n SA: DataMut<Elem = A>,\n\n ST: Data<Elem = A>,\n\n{\n\n assert!(a.ncols() >= a.nrows());\n\n assert!(a.nrows() >= tau.len());\n\n\n\n let a_nrows = a.nrows();\n\n let a_ncols = a.ncols();\n\n if tau.len() < a_nrows {\n\n for j in 0..a_ncols {\n\n for l in tau.len()..a_nrows {\n\n a[(l, j)] = A::zero();\n\n }\n\n if j >= tau.len() && j < a_nrows {\n\n a[(j, j)] = A::one();\n\n }\n\n }\n", "file_path": "src/lapack/unglq.rs", "rank": 28, "score": 131060.32227616507 }, { "content": "/// Performs `c` += `alpha` * `a` * `b`.\n\npub fn gemm<A, SA, SB, SC>(\n\n alpha: A,\n\n a: &ArrayBase<SA, Ix2>,\n\n a_conjugate: bool,\n\n b: &ArrayBase<SB, Ix2>,\n\n b_conjugate: bool,\n\n c: &mut ArrayBase<SC, Ix2>,\n\n) where\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SB: Data<Elem = A>,\n\n SC: DataMut<Elem = A>,\n\n{\n\n for (a_row, c_row) in a.rows().into_iter().zip(c.rows_mut()) {\n\n for (b_col, c_elem) in b.columns().into_iter().zip(c_row.into_iter()) {\n\n let dot_product = a_row\n\n .iter()\n\n .zip(b_col)\n\n .fold(A::zero(), |sum, (a_elem, b_elem)| {\n\n let a_elem = if a_conjugate { a_elem.conj() } else { *a_elem };\n\n let b_elem = if b_conjugate { b_elem.conj() } else { *b_elem };\n\n sum + a_elem * b_elem\n\n });\n\n *c_elem += alpha * dot_product;\n\n }\n\n }\n\n}\n", "file_path": "src/blas/gemm.rs", "rank": 29, "score": 126690.71827075054 }, { "content": "/// A trait for real and complex numbers.\n\npub trait Scalar:\n\n Copy\n\n + Debug\n\n + Display\n\n + LowerExp\n\n + UpperExp\n\n + PartialEq\n\n + Neg<Output = Self>\n\n + NumAssign\n\n + FromPrimitive\n\n + Sum\n\n + Product\n\n + ScalarOperand\n\n{\n\n type Real: Real + Into<Self> + FromPrimitive;\n\n trait_scalar_body!();\n\n}\n\n\n\n#[cfg(not(feature = \"serde\"))]\n\nimpl<T> Scalar for T\n", "file_path": "src/scalar.rs", "rank": 30, "score": 122263.11751592072 }, { "content": "/// A trait for real numbers.\n\npub trait Real: Float + NumAssign + Sum {\n\n /// Returns a number composed of the magnitude of `self` and the sign of\n\n /// `sign`.\n\n fn copysign(self, sign: Self) -> Self;\n\n\n\n /// Relative machine precision.\n\n #[inline]\n\n #[must_use]\n\n fn eps() -> Self {\n\n Self::epsilon() / (Self::one() + Self::one())\n\n }\n\n\n\n /// Safe minimum, such that its reciprocal does not overflow.\n\n #[inline]\n\n #[must_use]\n\n fn sfmin() -> Self {\n\n Self::min_positive_value()\n\n }\n\n}\n\n\n", "file_path": "src/scalar.rs", "rank": 31, "score": 120043.43282771047 }, { "content": "fn unblocked_tall<A, S>(a: &mut ArrayBase<S, Ix2>) -> Bidiagonal<A>\n\nwhere\n\n A: Scalar + Div<<A as Scalar>::Real, Output = A> + MulAssign<<A as Scalar>::Real>,\n\n S: DataMut<Elem = A>,\n\n{\n\n assert!(a.nrows() >= a.ncols());\n\n if a.is_empty() {\n\n return (\n\n Array1::<A::Real>::zeros(0),\n\n Array1::<A::Real>::zeros(0),\n\n Array1::<A>::zeros(0),\n\n Array1::<A>::zeros(0),\n\n );\n\n }\n\n\n\n let (mut d, mut e, mut tau_q, mut tau_p) = unsafe {\n\n // Will be initialized in the following `for` loop.\n\n (\n\n Array1::<A::Real>::uninit(a.ncols()).assume_init(),\n\n Array1::<A::Real>::uninit(a.ncols() - 1).assume_init(),\n", "file_path": "src/lapack/gebrd.rs", "rank": 32, "score": 109964.2382053237 }, { "content": "#[inline]\n\npub fn dot<A, SX, SY>(x: &ArrayBase<SX, Ix1>, y: &ArrayBase<SY, Ix1>, n: usize) -> A\n\nwhere\n\n A: Copy + AddAssign + Mul<Output = A> + Sum<<A as Mul>::Output> + Zero,\n\n SX: Data<Elem = A>,\n\n SY: Data<Elem = A>,\n\n{\n\n assert!(x.len() >= n && y.len() >= n);\n\n\n\n let inc_x = x.stride_of(Axis(0));\n\n let inc_y = y.stride_of(Axis(0));\n\n unsafe { inner(n, x.as_ptr(), inc_x, y.as_ptr(), inc_y) }\n\n}\n\n\n\n/// Computes a dot product of two vectors.\n\n///\n\n/// # Safety\n\n///\n\n/// * `x` is the beginning address of an array of at least `n` elements with\n\n/// stride `inc_x`.\n\n/// * `y` is the beginning address of an array of at least `n` elements with\n", "file_path": "src/blas/dot.rs", "rank": 33, "score": 107542.66246401885 }, { "content": "/// Finds the last non-zero row in a matrix.\n\npub fn ilalr<A, S>(x: &ArrayBase<S, Ix2>) -> Option<usize>\n\nwhere\n\n A: Scalar,\n\n S: Data<Elem = A>,\n\n{\n\n if x.nrows() == 0 || x.ncols() == 0 {\n\n return None;\n\n }\n\n\n\n let last_row = x.nrows() - 1;\n\n if x[(last_row, x.ncols() - 1)] != A::zero() {\n\n return Some(last_row);\n\n }\n\n\n\n for row in (0..x.nrows()).rev() {\n\n if x.row(row).iter().any(|&elem| elem != A::zero()) {\n\n return Some(row);\n\n }\n\n }\n\n None\n", "file_path": "src/lapack/ilal.rs", "rank": 34, "score": 106560.73029875808 }, { "content": "/// Finds the last non-zero column in a matrix.\n\npub fn ilalc<A, S>(x: &ArrayBase<S, Ix2>) -> Option<usize>\n\nwhere\n\n A: Scalar,\n\n S: Data<Elem = A>,\n\n{\n\n if x.nrows() == 0 || x.ncols() == 0 {\n\n return None;\n\n }\n\n\n\n let last_col = x.ncols() - 1;\n\n if x[(x.nrows() - 1, last_col)] != A::zero() {\n\n return Some(last_col);\n\n }\n\n\n\n for col in (0..x.ncols()).rev() {\n\n if x.column(col).iter().any(|&elem| elem != A::zero()) {\n\n return Some(col);\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/lapack/ilal.rs", "rank": 35, "score": 106560.73029875808 }, { "content": "fn getrf_100(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"lu\");\n\n let mut rng = Isaac64Rng::seed_from_u64(0);\n\n let a_row_major = Array::random_using((100, 100), Uniform::new(0., 10.), &mut rng);\n\n let a_tmp = a_row_major.clone().reversed_axes();\n\n let a_col_major = a_tmp.as_standard_layout().reversed_axes();\n\n assert!(a_row_major.is_standard_layout());\n\n assert!(!a_col_major.is_standard_layout());\n\n assert_eq!(a_row_major, a_col_major);\n\n group.bench_function(\"row-major\", |bencher| {\n\n bencher.iter(|| {\n\n let a = a_row_major.clone();\n\n lu::Factorized::from(a);\n\n })\n\n });\n\n group.bench_function(\"col-major\", |bencher| {\n\n bencher.iter(|| {\n\n let a = a_col_major.clone();\n\n lu::Factorized::from(a);\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, getrf_100);\n\ncriterion_main!(benches);\n", "file_path": "benches/getrf.rs", "rank": 36, "score": 84456.23538033168 }, { "content": "fn geqrf_100(c: &mut Criterion) {\n\n let mut rng = Isaac64Rng::seed_from_u64(0);\n\n let a = Array::random_using((100, 100), Uniform::new(0., 10.), &mut rng);\n\n c.bench_function(\"geqrf\", |bencher| {\n\n bencher.iter(|| {\n\n let a = a.clone();\n\n qr::Factorized::from(a);\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, geqrf_100);\n\ncriterion_main!(benches);\n", "file_path": "benches/geqrf.rs", "rank": 37, "score": 84456.23538033168 }, { "content": "fn getrs_100(c: &mut Criterion) {\n\n let mut rng = Isaac64Rng::seed_from_u64(0);\n\n let a = Array::random_using((100, 100), Uniform::new(0., 10.), &mut rng);\n\n let b = Array::random_using(100, Uniform::new(0., 10.), &mut rng);\n\n let lu = lu::Factorized::from(a);\n\n c.bench_function(\"getrs\", |bencher| {\n\n bencher.iter(|| {\n\n lu.solve(&b).unwrap();\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, getrs_100);\n\ncriterion_main!(benches);\n", "file_path": "benches/getrs.rs", "rank": 38, "score": 84456.23538033168 }, { "content": "/// Performs `y` = `alpha` * `a.H` * `x` + `beta` * `y`.\n\n///\n\n/// # Safety\n\n///\n\n/// * `a` is a two-dimensional array array with `n_rows` rows and `n_cols`\n\n/// columns, with strides of `row_stride` and `col_stride`, respectively.\n\n/// * `x` is an array of `n_rows` elements with stride of `inc_x`.\n\n/// * `y` is an array of `n_cols` elements with stride of `inc_y`.\n\npub fn conjtrans<A, SA, SX, SY>(\n\n alpha: A,\n\n a: &ArrayBase<SA, Ix2>,\n\n x: &ArrayBase<SX, Ix1>,\n\n beta: A,\n\n y: &mut ArrayBase<SY, Ix1>,\n\n) where\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SX: Data<Elem = A>,\n\n SY: DataMut<Elem = A>,\n\n{\n\n if beta == A::zero() {\n\n y.fill(A::zero());\n\n } else if beta != A::one() {\n\n *y *= beta;\n\n }\n\n if alpha == A::zero() {\n\n return;\n\n }\n", "file_path": "src/blas/gemv.rs", "rank": 39, "score": 81291.10756619507 }, { "content": "/// Performs `y` = `alpha` * `a` * `x` + `beta` * `y`.\n\npub fn notrans<A, SA, SX, SY>(\n\n alpha: A,\n\n a: &ArrayBase<SA, Ix2>,\n\n x: &ArrayBase<SX, Ix1>,\n\n beta: A,\n\n y: &mut ArrayBase<SY, Ix1>,\n\n) where\n\n A: Scalar,\n\n SA: Data<Elem = A>,\n\n SX: Data<Elem = A>,\n\n SY: DataMut<Elem = A>,\n\n{\n\n if beta == A::zero() {\n\n y.fill(A::zero());\n\n } else if beta != A::one() {\n\n *y *= beta;\n\n }\n\n if alpha == A::zero() {\n\n return;\n\n }\n", "file_path": "src/blas/gemv.rs", "rank": 40, "score": 81287.85528981741 }, { "content": "fn lacgv<A, S, D>(x: &mut ArrayBase<S, D>)\n\nwhere\n\n A: Scalar,\n\n S: DataMut<Elem = A>,\n\n D: Dimension,\n\n{\n\n x.iter_mut().for_each(|x| *x = x.conj());\n\n}\n\n\n", "file_path": "src/lapack.rs", "rank": 41, "score": 77798.35179727455 }, { "content": "#[allow(dead_code)]\n\npub fn left_notrans_forward_columnwise<A, SV, ST, SC>(\n\n v: &ArrayBase<SV, Ix2>,\n\n t: &ArrayBase<ST, Ix2>,\n\n c: &mut ArrayBase<SC, Ix2>,\n\n) where\n\n A: Scalar,\n\n SV: Data<Elem = A>,\n\n ST: Data<Elem = A>,\n\n SC: DataMut<Elem = A>,\n\n{\n\n assert!(v.nrows() == c.nrows());\n\n assert!(v.ncols() == t.ncols());\n\n assert!(t.ncols() <= c.nrows());\n\n if c.is_empty() {\n\n return;\n\n }\n\n\n\n let c_nrows = c.nrows();\n\n let (c_upper, mut c_lower) = c.view_mut().split_at(Axis(0), t.ncols());\n\n let mut work = unsafe {\n", "file_path": "src/lapack/larfb.rs", "rank": 42, "score": 74733.3639687028 }, { "content": "pub fn getrf<A>(a: ArrayViewMut2<A>) -> (Vec<usize>, Option<usize>)\n\nwhere\n\n A: Scalar,\n\n A::Real: Real,\n\n{\n\n unsafe {\n\n let dim_min = cmp::min(a.nrows(), a.ncols());\n\n let mut pivots = (0..dim_min).collect::<Vec<_>>();\n\n let singular = if a.is_standard_layout() {\n\n getrf_row_major(a, &mut pivots)\n\n } else {\n\n getrf_col_major(a, &mut pivots)\n\n };\n\n (pivots, singular)\n\n }\n\n}\n\n\n\n#[allow(dead_code)]\n\npub(crate) fn getrf_recursive<A>(a: ArrayViewMut2<A>) -> Result<Vec<usize>, Singular>\n\nwhere\n", "file_path": "src/lapack/getrf.rs", "rank": 43, "score": 69675.73364665853 }, { "content": "#[allow(dead_code)]\n\nfn lasq6<A, const PP: usize>(i0: usize, n0: usize, z: &mut [A]) -> (A, A, A, A, A, A)\n\nwhere\n\n A: Float + MulAssign,\n\n{\n\n assert!(PP <= 1, \"`PP` must be either 0 or 1.\");\n\n assert_eq!(z.len(), (n0 + 1) * 4);\n\n assert!(i0 + 1 < n0);\n\n\n\n let mut j4 = 4 * i0 + PP;\n\n let mut e_min = z[j4 + 4];\n\n let mut d = z[j4];\n\n let mut d_min = d;\n\n\n\n if n0 >= 3 {\n\n for j4 in (4 * i0 + 3..=4 * (n0 - 3) + 3).step_by(4) {\n\n z[j4 - PP - 2] = d + z[j4 + PP - 1];\n\n if z[j4 - PP - 2] == A::zero() {\n\n z[j4 - PP] = A::zero();\n\n d = z[j4 + PP + 1];\n\n d_min = d;\n", "file_path": "src/lapack/lasq.rs", "rank": 44, "score": 68041.47055150372 }, { "content": "use ndarray::ScalarOperand;\n\nuse num_complex::Complex;\n\nuse num_traits::{Float, FromPrimitive, NumAssign};\n\n#[cfg(feature = \"serde\")]\n\nuse serde::{Deserialize, Serialize};\n\nuse std::fmt::{Debug, Display, LowerExp, UpperExp};\n\nuse std::iter::{Product, Sum};\n\nuse std::ops::Neg;\n\n\n\nmacro_rules! trait_scalar_body {\n\n () => {\n\n fn re(&self) -> Self::Real;\n\n fn im(&self) -> Self::Real;\n\n fn conj(&self) -> Self;\n\n fn abs(&self) -> Self::Real;\n\n fn square(&self) -> Self::Real;\n\n\n\n fn sqrt(self) -> Self;\n\n fn exp(self) -> Self;\n\n fn ln(self) -> Self;\n", "file_path": "src/scalar.rs", "rank": 45, "score": 46055.73630687901 }, { "content": "macro_rules! impl_scalar_complex_body {\n\n () => {\n\n #[inline]\n\n fn re(&self) -> Self::Real {\n\n self.re\n\n }\n\n\n\n #[inline]\n\n fn im(&self) -> Self::Real {\n\n self.im\n\n }\n\n\n\n #[inline]\n\n fn conj(&self) -> Self {\n\n self.conj()\n\n }\n\n\n\n #[inline]\n\n fn abs(&self) -> Self::Real {\n\n self.norm()\n", "file_path": "src/scalar.rs", "rank": 46, "score": 46051.38206037247 }, { "content": "where\n\n T: Debug\n\n + Display\n\n + LowerExp\n\n + UpperExp\n\n + NumAssign\n\n + FromPrimitive\n\n + Sum\n\n + Product\n\n + Real\n\n + ScalarOperand,\n\n{\n\n type Real = Self;\n\n\n\n impl_scalar_t_body!();\n\n}\n\n\n\n#[cfg(not(feature = \"serde\"))]\n\nimpl<T> Scalar for Complex<T>\n\nwhere\n", "file_path": "src/scalar.rs", "rank": 47, "score": 46050.243805773425 }, { "content": "\n\n fn sin(self) -> Self;\n\n fn cos(self) -> Self;\n\n fn tan(self) -> Self;\n\n fn sinh(self) -> Self;\n\n fn cosh(self) -> Self;\n\n fn tanh(self) -> Self;\n\n fn asin(self) -> Self;\n\n fn acos(self) -> Self;\n\n fn atan(self) -> Self;\n\n fn asinh(self) -> Self;\n\n fn acosh(self) -> Self;\n\n fn atanh(self) -> Self;\n\n };\n\n}\n\n\n\nmacro_rules! impl_scalar_t_body {\n\n () => {\n\n #[inline]\n\n fn re(&self) -> Self::Real {\n", "file_path": "src/scalar.rs", "rank": 48, "score": 46050.1283905481 }, { "content": "#[cfg(feature = \"serde\")]\n\nimpl<T> Scalar for T\n\nwhere\n\n T: Debug\n\n + Display\n\n + LowerExp\n\n + UpperExp\n\n + NumAssign\n\n + FromPrimitive\n\n + Sum\n\n + Product\n\n + Real\n\n + ScalarOperand\n\n + Serialize\n\n + for<'de> Deserialize<'de>,\n\n{\n\n type Real = Self;\n\n\n\n impl_scalar_t_body!();\n\n}\n", "file_path": "src/scalar.rs", "rank": 49, "score": 46049.94501069989 }, { "content": " *self\n\n }\n\n\n\n #[inline]\n\n fn im(&self) -> Self::Real {\n\n T::zero()\n\n }\n\n\n\n #[inline]\n\n fn conj(&self) -> Self {\n\n *self\n\n }\n\n\n\n #[inline]\n\n fn abs(&self) -> Self::Real {\n\n Self::abs(*self)\n\n }\n\n\n\n #[inline]\n\n fn square(&self) -> Self::Real {\n", "file_path": "src/scalar.rs", "rank": 50, "score": 46049.547479963505 }, { "content": "impl Real for f32 {\n\n #[inline]\n\n fn copysign(self, sign: Self) -> Self {\n\n self.copysign(sign)\n\n }\n\n}\n\n\n\nimpl Real for f64 {\n\n #[inline]\n\n fn copysign(self, sign: Self) -> Self {\n\n self.copysign(sign)\n\n }\n\n}\n", "file_path": "src/scalar.rs", "rank": 51, "score": 46048.84872396874 }, { "content": " }\n\n\n\n #[inline]\n\n fn square(&self) -> Self::Real {\n\n self.norm_sqr()\n\n }\n\n\n\n #[inline]\n\n fn sqrt(self) -> Self {\n\n self.sqrt()\n\n }\n\n\n\n #[inline]\n\n fn exp(self) -> Self {\n\n self.exp()\n\n }\n\n\n\n #[inline]\n\n fn ln(self) -> Self {\n\n self.ln()\n", "file_path": "src/scalar.rs", "rank": 52, "score": 46048.1141781848 }, { "content": " }\n\n\n\n #[inline]\n\n fn atan(self) -> Self {\n\n self.atan()\n\n }\n\n\n\n #[inline]\n\n fn asinh(self) -> Self {\n\n self.asinh()\n\n }\n\n\n\n #[inline]\n\n fn acosh(self) -> Self {\n\n self.acosh()\n\n }\n\n\n\n #[inline]\n\n fn atanh(self) -> Self {\n\n self.atanh()\n\n }\n\n };\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\n/// A trait for real and complex numbers.\n", "file_path": "src/scalar.rs", "rank": 53, "score": 46047.72597221481 }, { "content": " T: Copy\n\n + Debug\n\n + Display\n\n + LowerExp\n\n + UpperExp\n\n + Neg<Output = T>\n\n + NumAssign\n\n + FromPrimitive\n\n + Real,\n\n Complex<T>: ScalarOperand,\n\n{\n\n type Real = T;\n\n\n\n impl_scalar_complex_body!();\n\n}\n\n\n", "file_path": "src/scalar.rs", "rank": 54, "score": 46047.618070048586 }, { "content": "\n\n#[cfg(feature = \"serde\")]\n\nimpl<T> Scalar for Complex<T>\n\nwhere\n\n T: Copy\n\n + Debug\n\n + Display\n\n + LowerExp\n\n + UpperExp\n\n + Neg<Output = T>\n\n + NumAssign\n\n + FromPrimitive\n\n + Real\n\n + Serialize\n\n + for<'de> Deserialize<'de>,\n\n Complex<T>: ScalarOperand + Serialize + for<'de> Deserialize<'de>,\n\n{\n\n type Real = T;\n\n\n\n impl_scalar_complex_body!();\n\n}\n\n\n\n#[cfg(not(feature = \"serde\"))]\n", "file_path": "src/scalar.rs", "rank": 55, "score": 46046.96984084816 }, { "content": " *self * *self\n\n }\n\n\n\n #[inline]\n\n fn sqrt(self) -> Self {\n\n self.sqrt()\n\n }\n\n\n\n #[inline]\n\n fn exp(self) -> Self {\n\n self.exp()\n\n }\n\n\n\n #[inline]\n\n fn ln(self) -> Self {\n\n self.ln()\n\n }\n\n\n\n #[inline]\n\n fn sin(self) -> Self {\n", "file_path": "src/scalar.rs", "rank": 56, "score": 46045.46795452657 }, { "content": " }\n\n\n\n #[inline]\n\n fn sin(self) -> Self {\n\n self.sin()\n\n }\n\n\n\n #[inline]\n\n fn cos(self) -> Self {\n\n self.cos()\n\n }\n\n\n\n #[inline]\n\n fn tan(self) -> Self {\n\n self.tan()\n\n }\n\n\n\n #[inline]\n\n fn sinh(self) -> Self {\n\n self.sinh()\n", "file_path": "src/scalar.rs", "rank": 57, "score": 46045.4345566107 }, { "content": " self.cosh()\n\n }\n\n\n\n #[inline]\n\n fn tanh(self) -> Self {\n\n self.tanh()\n\n }\n\n\n\n #[inline]\n\n fn asin(self) -> Self {\n\n self.asin()\n\n }\n\n\n\n #[inline]\n\n fn acos(self) -> Self {\n\n self.acos()\n\n }\n\n\n\n #[inline]\n\n fn atan(self) -> Self {\n", "file_path": "src/scalar.rs", "rank": 58, "score": 46045.4345566107 }, { "content": " self.sin()\n\n }\n\n\n\n #[inline]\n\n fn cos(self) -> Self {\n\n self.cos()\n\n }\n\n\n\n #[inline]\n\n fn tan(self) -> Self {\n\n self.tan()\n\n }\n\n\n\n #[inline]\n\n fn sinh(self) -> Self {\n\n self.sinh()\n\n }\n\n\n\n #[inline]\n\n fn cosh(self) -> Self {\n", "file_path": "src/scalar.rs", "rank": 59, "score": 46045.4345566107 }, { "content": " }\n\n\n\n #[inline]\n\n fn cosh(self) -> Self {\n\n self.cosh()\n\n }\n\n\n\n #[inline]\n\n fn tanh(self) -> Self {\n\n self.tanh()\n\n }\n\n\n\n #[inline]\n\n fn asin(self) -> Self {\n\n self.asin()\n\n }\n\n\n\n #[inline]\n\n fn acos(self) -> Self {\n\n self.acos()\n", "file_path": "src/scalar.rs", "rank": 60, "score": 46045.4345566107 }, { "content": " self.atan()\n\n }\n\n\n\n #[inline]\n\n fn asinh(self) -> Self {\n\n self.asinh()\n\n }\n\n\n\n #[inline]\n\n fn acosh(self) -> Self {\n\n self.acosh()\n\n }\n\n\n\n #[inline]\n\n fn atanh(self) -> Self {\n\n self.atanh()\n\n }\n\n };\n\n}\n\n\n", "file_path": "src/scalar.rs", "rank": 61, "score": 46045.302765323664 }, { "content": "#[allow(dead_code)]\n\n#[allow(clippy::too_many_arguments, clippy::too_many_lines)]\n\nfn lasq4<A, const PP: usize>(\n\n i0: usize,\n\n n0: usize,\n\n z: &[A],\n\n n0_in: usize,\n\n d_min: A,\n\n d_min_1: A,\n\n d_min_2: A,\n\n d_n: A,\n\n d_n_1: A,\n\n d_n_2: A,\n\n mut g: A,\n\n mut ttype: isize,\n\n) -> (A, isize, A)\n\nwhere\n\n A: Float + AddAssign + MulAssign,\n\n{\n\n assert!(PP <= 1, \"`PP` must be either 0 or 1.\");\n\n\n\n if d_min <= A::zero() {\n", "file_path": "src/lapack/lasq.rs", "rank": 62, "score": 44595.283194584685 }, { "content": "#[allow(dead_code)]\n\nfn lasq5<A, const PP: usize>(\n\n i0: usize,\n\n n0: usize,\n\n z: &mut [A],\n\n mut tau: A,\n\n sigma: A,\n\n eps: A,\n\n) -> (A, A, A, A, A, A)\n\nwhere\n\n A: Float,\n\n{\n\n assert!(PP <= 1, \"`PP` must be either 0 or 1.\");\n\n assert!(n0 - i0 <= 1);\n\n\n\n let d_thresh = eps * (sigma + tau);\n\n if tau < d_thresh / (A::one() + A::one()) {\n\n tau = A::zero();\n\n }\n\n\n\n let mut j4 = 4 * i0 + PP - 3;\n", "file_path": "src/lapack/lasq.rs", "rank": 63, "score": 44595.283194584685 }, { "content": "#[allow(dead_code)]\n\nfn las2<T>(f: T, g: T, h: T) -> (T, T)\n\nwhere\n\n T: Float,\n\n{\n\n let f_abs = f.abs();\n\n let g_abs = g.abs();\n\n let h_abs = h.abs();\n\n let (f_h_min, f_h_max) = if f_abs < h_abs {\n\n (f_abs, h_abs)\n\n } else {\n\n (h_abs, f_abs)\n\n };\n\n if f_h_min == T::zero() {\n\n if f_h_max == T::zero() {\n\n (f_h_min, g_abs)\n\n } else {\n\n let f_h_g_max = if f_h_max > g_abs { f_h_max } else { g_abs };\n\n let smaller = if f_h_max < g_abs { f_h_max } else { g_abs };\n\n let ratio = smaller / f_h_g_max;\n\n (f_h_min, f_h_g_max * (T::one() + ratio * ratio).sqrt())\n", "file_path": "src/lapack/las2.rs", "rank": 80, "score": 38846.49220668691 }, { "content": "//! Matrix equation solvers.\n\n\n\nuse crate::decomposition::lu;\n\nuse crate::{InvalidInput, Real, Scalar};\n\nuse ndarray::{Array1, ArrayBase, Data, Ix1, Ix2};\n\n\n\n/// Solves a system of linear scalar equations.\n\n///\n\n/// # Errors\n\n///\n\n/// * [`InvalidInput::Shape`] if `a` is not a square matrix, or `a`'s number of\n\n/// rows and `b`'s length does not match.\n\n/// * [`InvalidInput::Value`] if `a` is a singular matrix.\n\n///\n\n/// [`InvalidInput::Shape`]: ../enum.InvalidInput.html#variant.Shape\n\n/// [`InvalidInput::Value`]: ../enum.InvalidInput.html#variant.Value\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n", "file_path": "src/equation.rs", "rank": 81, "score": 13631.916303920594 }, { "content": "use crate::{Real, Scalar};\n\nuse ndarray::{ArrayBase, DataMut, Dimension};\n\n\n\nmod gebrd;\n\nmod geqrf;\n\nmod getrf;\n\nmod getrs;\n\nmod ilal;\n\npub mod lacpy;\n\npub mod lange;\n\npub mod larf;\n\npub mod larfb;\n\nmod larfg;\n\npub mod larft;\n\nmod lartg;\n\nmod las2;\n\npub mod lascl;\n\npub mod laset;\n\nmod lasq;\n\nmod laswp;\n", "file_path": "src/lapack.rs", "rank": 82, "score": 13628.91995209814 }, { "content": "//! Lair implements linear algebra routines in pure Rust. It uses [ndarray] as\n\n//! its matrix representation.\n\n//!\n\n//! [ndarray]: https://docs.rs/ndarray/\n\n\n\nmod blas;\n\npub mod decomposition;\n\n// TODO: pub mod eigen;\n\npub mod equation;\n\nmod lapack;\n\npub mod matrix;\n\nmod scalar;\n\n\n\npub use scalar::{Real, Scalar};\n\n\n\n/// An error which can be returned when a function argument is invalid.\n\n#[derive(Debug, thiserror::Error)]\n\npub enum InvalidInput {\n\n #[error(\"shape error: {0}\")]\n\n Shape(String),\n\n #[error(\"value error: {0}\")]\n\n Value(String),\n\n}\n", "file_path": "src/lib.rs", "rank": 83, "score": 13627.317251200222 }, { "content": "//! Matrix functions and special matrices.\n\n\n\nuse crate::{InvalidInput, Scalar};\n\nuse ndarray::Array2;\n\n\n\n/// Constructs a circulant matrix.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use lair::matrix::circulant;\n\n///\n\n/// let a = vec![1., 2., 3.];\n\n/// let c = circulant(&a);\n\n/// assert_eq!(c, ndarray::aview2(&[[1., 3., 2.], [2., 1., 3.], [3., 2., 1.]]));\n\n/// ```\n", "file_path": "src/matrix.rs", "rank": 84, "score": 13625.78972900757 }, { "content": "mod ungbr;\n\nmod unglq;\n\nmod ungqr;\n\nmod ungrq;\n\n\n\npub use geqrf::geqrf;\n\npub use getrf::getrf;\n\npub use getrs::getrs;\n\npub use ilal::{ilalc, ilalr};\n\npub use larfg::larfg;\n\npub use laswp::laswp;\n\nuse unglq::unglq;\n\nuse ungqr::ungqr;\n\n\n", "file_path": "src/lapack.rs", "rank": 85, "score": 13622.586515325886 }, { "content": "mod copy;\n\nmod dot;\n\nmod gemm;\n\npub(crate) mod gemv;\n\nmod gerc;\n\nmod iamax;\n\nmod nrm2;\n\nmod scal;\n\npub mod trmm;\n\npub mod trmv;\n\nmod trsm;\n\n\n\npub(crate) use dot::dot;\n\npub(crate) use gemm::gemm;\n\npub(crate) use gerc::gerc;\n\npub(crate) use iamax::iamax;\n\npub(crate) use nrm2::nrm2;\n\npub(crate) use scal::scal;\n\npub(crate) use trsm::trsm;\n", "file_path": "src/blas.rs", "rank": 86, "score": 13622.33261058737 }, { "content": "//! Matrix decompositions.\n\n\n\npub mod lu;\n\npub mod qr;\n", "file_path": "src/decomposition.rs", "rank": 87, "score": 13621.716634993627 }, { "content": "/// use lair::equation::solve;\n\n///\n\n/// // Solve the system of equations:\n\n/// // 3 * x0 + x1 = 9\n\n/// // x0 + 2 * x1 = 8\n\n/// let a = ndarray::arr2(&[[3., 1.], [1., 2.]]);\n\n/// let b = ndarray::arr1(&[9., 8.]);\n\n/// let x = solve(&a, &b).expect(\"valid input\");\n\n/// assert_eq!(x, ndarray::aview1(&[2., 3.]));\n\n/// ```\n", "file_path": "src/equation.rs", "rank": 88, "score": 13620.330140954156 }, { "content": " }\n\n for i in 1..a.len() - 1 {\n\n matrix[[i, i - 1]] = A::one();\n\n }\n\n Ok(matrix)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ndarray::aview2;\n\n use num_complex::{Complex32, Complex64};\n\n\n\n #[test]\n\n fn circulant() {\n\n let a = Vec::<f32>::new();\n\n let c = super::circulant(&a);\n\n assert_eq!(c.shape(), [0, 0]);\n\n\n\n let a = vec![Complex32::new(1., 2.)];\n\n let c = super::circulant(&a);\n", "file_path": "src/matrix.rs", "rank": 89, "score": 13619.227294305962 }, { "content": "//! Eigenvalues and eigenvectors.\n", "file_path": "src/eigen.rs", "rank": 90, "score": 13614.114328848666 }, { "content": " assert_eq!(c, aview2(&[[Complex32::new(1., 2.)]]));\n\n\n\n let a = vec![1., 2., 4.];\n\n let c = super::circulant(&a);\n\n assert_eq!(c, aview2(&[[1., 4., 2.], [2., 1., 4.], [4., 2., 1.]]));\n\n }\n\n\n\n #[test]\n\n fn companion() {\n\n let a = Vec::<f32>::new();\n\n assert!(super::companion(&a).is_err());\n\n\n\n let a = vec![Complex64::new(1., 2.)];\n\n assert!(super::companion(&a).is_err());\n\n\n\n let a = vec![\n\n Complex32::new(0., 0.),\n\n Complex32::new(1., 1.),\n\n Complex32::new(2., 2.),\n\n ];\n", "file_path": "src/matrix.rs", "rank": 91, "score": 13614.114328848666 }, { "content": " assert!(super::companion(&a).is_err());\n\n\n\n let a = vec![Complex32::new(1., 2.), Complex32::new(3., 4.)];\n\n let c = super::companion(&a).expect(\"valid input\");\n\n assert_eq!(c, aview2(&[[Complex32::new(-2.2, 0.4)]]));\n\n\n\n let a = vec![2., -4., 8., -10.];\n\n let c = super::companion(&a).expect(\"valid input\");\n\n assert_eq!(\n\n c,\n\n aview2(&[[2.0, -4.0, 5.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])\n\n );\n\n }\n\n}\n", "file_path": "src/matrix.rs", "rank": 92, "score": 13614.114328848666 }, { "content": "use crate::{lapack, Scalar};\n\nuse ndarray::{s, Array1, ArrayBase, Axis, DataMut, Ix2};\n\nuse std::ops::{Div, MulAssign};\n\n\n\n/// An upper or lower bidiagonal matrix.\n\n///\n\n/// The bidiagonal matrix B is Q^H * `a` * P, and consists of four components:\n\n///\n\n/// 1. The diagonal elements\n\n/// 2. The off-diagonal elements\n\n/// 3. The scalar factors of the elementary reflectors representing Q\n\n/// 4. The scalar factors of the elementary reflectors representing P\n\npub type Bidiagonal<A> = (\n\n Array1<<A as Scalar>::Real>,\n\n Array1<<A as Scalar>::Real>,\n\n Array1<A>,\n\n Array1<A>,\n\n);\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/lapack/gebrd.rs", "rank": 93, "score": 12895.787143982512 }, { "content": "use crate::{Real, Scalar};\n\nuse ndarray::{ArrayBase, DataMut, Ix2};\n\nuse num_traits::{Float, One, Zero};\n\n\n\n/// Multiplies a full matrix by a real scalar `c_to / c_from`.\n\n#[allow(dead_code)]\n\npub(crate) fn full<A, S>(c_from: A::Real, c_to: A::Real, a: &mut ArrayBase<S, Ix2>)\n\nwhere\n\n A: Scalar,\n\n S: DataMut<Elem = A>,\n\n{\n\n let small_num = A::Real::sfmin();\n\n let large_num = A::Real::one() / small_num;\n\n\n\n let mut c_from = c_from;\n\n let mut c_to = c_to;\n\n\n\n loop {\n\n let (mul, done) = {\n\n let small_from = c_from * small_num;\n", "file_path": "src/lapack/lascl.rs", "rank": 94, "score": 12891.898996717604 }, { "content": "//! QR decomposition.\n\n\n\nuse crate::{blas, lapack, Real, Scalar};\n\nuse ndarray::{s, Array1, Array2, ArrayBase, Data, DataMut, Ix2};\n\nuse std::fmt;\n\nuse std::ops::{Div, MulAssign};\n\n\n\n/// QR decomposition factors.\n\n#[derive(Debug)]\n\npub struct Factorized<A, S>\n\nwhere\n\n A: fmt::Debug,\n\n S: Data<Elem = A>,\n\n{\n\n qr: ArrayBase<S, Ix2>,\n\n tau: Array1<A>,\n\n}\n\n\n\nimpl<A, S> Factorized<A, S>\n\nwhere\n", "file_path": "src/decomposition/qr.rs", "rank": 95, "score": 12891.290206969512 }, { "content": "use crate::Scalar;\n\nuse ndarray::{ArrayBase, Axis, Data, DataMut, Ix1, Ix2};\n\n\n\n/// Performs `y` = `alpha` * `a` * `x` + `beta` * `y`.\n", "file_path": "src/blas/gemv.rs", "rank": 96, "score": 12890.781071344096 }, { "content": "use crate::{lapack, Scalar};\n\nuse ndarray::{s, ArrayBase, Axis, Data, DataMut, Ix1, Ix2};\n\n\n\n#[allow(dead_code)]\n", "file_path": "src/lapack/ungbr.rs", "rank": 97, "score": 12890.426328269612 }, { "content": "use crate::{lapack, Scalar};\n\nuse ndarray::{Array1, ArrayBase, Axis, Data, Ix1, Ix2};\n\n\n\n/// 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", "file_path": "src/lapack/getrs.rs", "rank": 98, "score": 12890.345178729156 }, { "content": "use crate::{blas, lapack, Scalar};\n\nuse ndarray::{s, Array1, ArrayBase, Axis, Data, DataMut, Ix1, Ix2};\n\n\n\n/// Applies an elementary reflector to a matrix.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if `v` is a zero vector, or `c` is a zero matrix.\n", "file_path": "src/lapack/larf.rs", "rank": 99, "score": 20.658701934185764 } ]
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\n src: &'a str,\n\n start: usize,\n\n end: usize,\n\n pub line: u32,\n\n}\n\n\n\nimpl<'a> Lexer<'a> {\n\n pub fn new(s: &'a str) -> Self {\n\n Self {\n\n f: Self::begin,\n\n iter: s.char_indices(),\n\n src: s,\n\n start: 0,\n\n end: 0,\n\n line: 1,\n", "file_path": "lib/src/lexer.rs", "rank": 1, "score": 169483.70753673933 }, { "content": "pub fn run<W: Write>(writer: &mut W, src: &str) -> std::result::Result<String, WithContext> {\n\n let mut itp = Interpreter::new();\n\n\n\n match itp.run(writer, src) {\n\n Ok(val) => {\n\n let log = itp.get_log();\n\n\n\n if log.is_empty() {\n\n Ok(format!(\"{}\\n\", val))\n\n } else {\n\n Ok(log)\n\n }\n\n }\n\n Err(e) => Err(itp.get_context(e)),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::midi::tests::{bindiff, FILE0, FILE1};\n", "file_path": "lib/src/lib.rs", "rank": 2, "score": 146193.93826878708 }, { "content": "type OpFn = fn(Value, Value) -> Result<Value>;\n", "file_path": "lib/src/interpreter.rs", "rank": 3, "score": 134364.10269305122 }, { "content": "type UnOpFn = fn(Value) -> Result<Value>;\n", "file_path": "lib/src/interpreter.rs", "rank": 4, "score": 132457.3097620243 }, { "content": "type Lambda = (AstPtr, AstPtr);\n\n\n\npub struct Interpreter {\n\n parser: Parser,\n\n env: EnvStore,\n\n builtins: Vec<BuiltinFn<Self>>,\n\n paths: Vec<PathBuf>,\n\n lambdas: FnvIndexMap<Lambda, EnvId>,\n\n events: FnvIndexSet<Event>,\n\n tracks: Vec<Track>,\n\n c_path: Option<usize>,\n\n c_ident: Option<StrId>,\n\n log: FnvIndexMap<StrId, u32>,\n\n}\n\n\n\nimpl Interpreter {\n\n pub fn new() -> Self {\n\n let mut itp = Self {\n\n parser: Parser::new(),\n\n env: EnvStore::new(),\n", "file_path": "lib/src/interpreter.rs", "rank": 5, "score": 124350.84796622352 }, { "content": "fn call_midilisp(src: &str) -> WasmResult {\n\n let mut w = Cursor::new(Vec::new());\n\n\n\n match super::run(&mut w, src) {\n\n Ok(log) => {\n\n let vec = w.into_inner();\n\n\n\n if !vec.is_empty() {\n\n Ok(vec)\n\n } else {\n\n Err(log.into_bytes())\n\n }\n\n }\n\n Err(e) => Err(e.to_string().into_bytes()),\n\n }\n\n}\n", "file_path": "lib/src/wasm.rs", "rank": 6, "score": 107995.47860840154 }, { "content": "fn read_input(opts: &Opts) -> Result<String> {\n\n match &opts.in_path {\n\n Some(path) => Ok(fs::read_to_string(path)?),\n\n None => {\n\n let mut buf = String::new();\n\n io::stdin().read_to_string(&mut buf)?;\n\n Ok(buf)\n\n }\n\n }\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 7, "score": 99170.69542145048 }, { "content": "fn finish(opts: &Opts, log: String) -> Result<()> {\n\n match &opts.out_path {\n\n Some(out) => {\n\n let tmp = opts.tmp_path.as_ref().unwrap();\n\n let len = tmp.metadata()?.len();\n\n\n\n if len > 0 {\n\n fs::rename(&tmp, &out)?;\n\n eprintln!(\"{} bytes written to {}\", len, &out.to_string_lossy());\n\n } else {\n\n eprint!(\"{}\", log);\n\n fs::remove_file(&tmp)?;\n\n }\n\n }\n\n None => {}\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 8, "score": 96303.0297573132 }, { "content": "fn run() -> Result<()> {\n\n let opts = parse_args()?;\n\n let src = read_input(&opts)?;\n\n let mut writer = create_writer(&opts)?;\n\n let log = midilisp::run(&mut writer, &src)?;\n\n finish(&opts, log)\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 9, "score": 90418.102318083 }, { "content": "fn parse_args() -> Result<Opts> {\n\n let args: Vec<OsString> = env::args_os().collect();\n\n\n\n match args.len() {\n\n 1 | 2 | 3 => Ok(Opts::new(args.get(1), args.get(2))),\n\n _ => Err(CliError.into()),\n\n }\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 10, "score": 80095.83534094386 }, { "content": "type WasmResult = Result<Vec<u8>, Vec<u8>>;\n\n\n\n#[export_name = \"malloc\"]\n\npub unsafe extern \"C\" fn malloc(n: usize) -> *mut u8 {\n\n assert_ne!(n, 0);\n\n alloc(Layout::array::<u8>(n).expect(\"overflow\"))\n\n}\n\n\n\n#[export_name = \"getVecPtr\"]\n\npub unsafe extern \"C\" fn get_vec_ptr(ptr: *const Vec<u8>) -> *const u8 {\n\n ptr.as_ref().expect(\"null ptr\").as_ptr()\n\n}\n\n\n\n#[export_name = \"getVecLen\"]\n\npub unsafe extern \"C\" fn get_vec_len(ptr: *const Vec<u8>) -> usize {\n\n ptr.as_ref().expect(\"null ptr\").len()\n\n}\n\n\n\n#[export_name = \"isOk\"]\n\npub unsafe extern \"C\" fn is_ok(ptr: *const WasmResult) -> i32 {\n", "file_path": "lib/src/wasm.rs", "rank": 11, "score": 74406.510397506 }, { "content": "type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;\n\n\n\nconst USAGE: &str = \"\\nUsage: midilisp [INPUT] [OUTPUT]\";\n\n\n", "file_path": "cli/src/main.rs", "rank": 12, "score": 73792.3990271062 }, { "content": "fn create_writer(opts: &Opts) -> Result<Box<dyn Write>> {\n\n match &opts.tmp_path {\n\n Some(path) => Ok(Box::new(fs::File::create(path)?)),\n\n None => Ok(Box::new(io::stdout())),\n\n }\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 13, "score": 62065.28755248538 }, { "content": "struct Opts {\n\n in_path: Option<PathBuf>,\n\n out_path: Option<PathBuf>,\n\n tmp_path: Option<PathBuf>,\n\n}\n\n\n\nimpl Opts {\n\n fn new<P: Into<PathBuf>>(i: Option<P>, o: Option<P>) -> Self {\n\n let (op, tp) = match o {\n\n Some(p) => {\n\n let op: PathBuf = p.into();\n\n let mut tp = op.clone();\n\n tp.set_extension(\"tmp\");\n\n (Some(op), Some(tp))\n\n }\n\n None => (None, None),\n\n };\n\n\n\n Self {\n\n in_path: i.map(|p| p.into()),\n\n out_path: op,\n\n tmp_path: tp,\n\n }\n\n }\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 14, "score": 58248.22716379632 }, { "content": "fn main() {\n\n process::exit(match run() {\n\n Ok(()) => 0,\n\n Err(err) => {\n\n eprint!(\"{}\", err);\n\n 1\n\n }\n\n })\n\n}\n\n\n", "file_path": "cli/src/main.rs", "rank": 15, "score": 57350.825789670926 }, { "content": "#[derive(thiserror::Error, Copy, Clone, Debug)]\n\n#[error(\"invalid number of arguments{}\", USAGE)]\n\nstruct CliError;\n", "file_path": "cli/src/main.rs", "rank": 16, "score": 56157.819187384564 }, { "content": "pub trait WriteVarLen {\n\n fn write_var_len(&mut self, val: u32);\n\n}\n\n\n", "file_path": "lib/src/midi.rs", "rank": 17, "score": 49086.8303501615 }, { "content": "pub trait ReadVarLen {\n\n fn read_var_len(&mut self) -> u32;\n\n}\n\n\n\nimpl WriteVarLen for Vec<u8> {\n\n fn write_var_len(&mut self, val: u32) {\n\n let mut offset = match val {\n\n 0..=0x7f => 0,\n\n 0x80..=0x3fff => 1,\n\n 0x4000..=0x1fffff => 2,\n\n _ => 3,\n\n };\n\n\n\n while offset != 0 {\n\n let shift_by = offset * 7;\n\n let u7 = ((val >> shift_by) & 0x7f) as u8;\n\n self.push(u7 | 0x80);\n\n offset -= 1;\n\n }\n\n\n", "file_path": "lib/src/midi.rs", "rank": 18, "score": 49086.8303501615 }, { "content": "use std::cmp::PartialEq;\n\nuse std::str::CharIndices;\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\npub enum Token {\n\n Bin,\n\n Eof,\n\n Float,\n\n Hex,\n\n Ident,\n\n Int,\n\n LeftParen,\n\n NumError,\n\n RightParen,\n\n Str,\n\n StrError,\n\n}\n\n\n\nuse Token::*;\n\n\n", "file_path": "lib/src/lexer.rs", "rank": 30, "score": 42572.2432277428 }, { "content": " expect_s(&mut lex, Int, \"256\");\n\n expect_s(&mut lex, Hex, \"c0ffee\");\n\n expect_s(&mut lex, Bin, \"110101\");\n\n expect_s(&mut lex, Int, \"00000001903\");\n\n expect_s(&mut lex, Int, \"-99\");\n\n expect_s(&mut lex, Float, \"0.5\");\n\n expect_s(&mut lex, Float, \".5\");\n\n expect_s(&mut lex, Float, \"-9.234\");\n\n expect(&mut lex, NumError);\n\n assert_eq!(lex.next(), None);\n\n }\n\n\n\n #[test]\n\n fn comments() {\n\n let src = \";ignore this\n\n 123 456 ;and this\n\n 0xb;and this\";\n\n let mut lex = Lexer::new(src);\n\n expect_s(&mut lex, Int, \"123\");\n\n expect_s(&mut lex, Int, \"456\");\n", "file_path": "lib/src/lexer.rs", "rank": 31, "score": 42571.59608509069 }, { "content": " }\n\n\n\n fn eof(&mut self) -> Token {\n\n Eof\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{Lexer, Token};\n\n use Token::*;\n\n\n\n fn expect(lex: &mut Lexer, exp_tok: Token) {\n\n assert_eq!(exp_tok, lex.next().unwrap());\n\n }\n\n\n\n fn expect_s(lex: &mut Lexer, exp_tok: Token, exp_s: &str) {\n\n expect(lex, exp_tok);\n\n assert_eq!(exp_s, lex.get_str());\n\n }\n", "file_path": "lib/src/lexer.rs", "rank": 32, "score": 42571.4480610933 }, { "content": "\n\n if self.end == self.src.len() {\n\n self.ret(Self::eof, StrError)\n\n } else {\n\n self.ret(Self::begin, Str)\n\n }\n\n }\n\n\n\n fn zero(&mut self) -> Token {\n\n match self.advance() {\n\n Some('x') => self.hex(),\n\n Some('b') => self.bin(),\n\n Some('.') => self.float(),\n\n Some(c) if c.is_ascii_digit() => self.int(),\n\n opt => self.default_ret(opt, Int, NumError),\n\n }\n\n }\n\n\n\n fn minus(&mut self) -> Token {\n\n match self.advance() {\n", "file_path": "lib/src/lexer.rs", "rank": 33, "score": 42571.03309666818 }, { "content": " #[test]\n\n fn strings() {\n\n let src = \"\\\"\\\"\\\"foobar00\\\"029\\\"3#8(9;)49\\\"(\\\"Quux-029+Z\\\")\\\"s*fdkf\";\n\n let mut lex = Lexer::new(src);\n\n expect_s(&mut lex, Str, \"\");\n\n expect_s(&mut lex, Str, \"foobar00\");\n\n expect_s(&mut lex, Int, \"029\");\n\n expect_s(&mut lex, Str, \"3#8(9;)49\");\n\n expect(&mut lex, LeftParen);\n\n expect_s(&mut lex, Str, \"Quux-029+Z\");\n\n expect(&mut lex, RightParen);\n\n expect(&mut lex, StrError);\n\n assert_eq!(lex.next(), None);\n\n }\n\n}\n", "file_path": "lib/src/lexer.rs", "rank": 34, "score": 42568.731602441534 }, { "content": " Some(c) if c.is_ascii_digit() => self.int(),\n\n opt => match self.default_match(opt) {\n\n Some(f) => self.ret(f, Ident),\n\n None => self.ident(),\n\n },\n\n }\n\n }\n\n\n\n fn int(&mut self) -> Token {\n\n loop {\n\n match self.advance() {\n\n Some(c) if c.is_ascii_digit() => continue,\n\n Some('.') => break self.float(),\n\n opt => break self.default_ret(opt, Int, NumError),\n\n }\n\n }\n\n }\n\n\n\n fn float(&mut self) -> Token {\n\n loop {\n", "file_path": "lib/src/lexer.rs", "rank": 35, "score": 42567.918042048244 }, { "content": " None => Some(Self::eof),\n\n }\n\n }\n\n\n\n fn default_ret(&mut self, c: Option<char>, ok: Token, err: Token) -> Token {\n\n match self.default_match(c) {\n\n Some(f) => self.ret(f, ok),\n\n None => self.ret(Self::eof, err),\n\n }\n\n }\n\n\n\n fn ret(&mut self, f: LexFn<Self>, tok: Token) -> Token {\n\n self.f = f;\n\n tok\n\n }\n\n\n\n fn skip_to(&mut self, c: char) {\n\n self.end = self\n\n .iter\n\n .find(|t| t.1 == c)\n", "file_path": "lib/src/lexer.rs", "rank": 36, "score": 42567.52622033749 }, { "content": " expect_s(&mut lex, Hex, \"b\");\n\n assert_eq!(lex.next(), None);\n\n }\n\n\n\n #[test]\n\n fn idents() {\n\n let src = \"(foobar-01 🍔) + !/#¤=&* - 絵文字 🍓🍐\";\n\n let mut lex = Lexer::new(src);\n\n expect(&mut lex, LeftParen);\n\n expect_s(&mut lex, Ident, \"foobar-01\");\n\n expect_s(&mut lex, Ident, \"🍔\");\n\n expect(&mut lex, RightParen);\n\n expect_s(&mut lex, Ident, \"+\");\n\n expect_s(&mut lex, Ident, \"!/#¤=&*\");\n\n expect_s(&mut lex, Ident, \"-\");\n\n expect_s(&mut lex, Ident, \"絵文字\");\n\n expect_s(&mut lex, Ident, \"🍓🍐\");\n\n assert_eq!(lex.next(), None);\n\n }\n\n\n", "file_path": "lib/src/lexer.rs", "rank": 37, "score": 42567.45564332222 }, { "content": "\n\n #[test]\n\n fn parens() {\n\n let src = \"())(\";\n\n let mut lex = Lexer::new(src);\n\n expect(&mut lex, LeftParen);\n\n expect(&mut lex, RightParen);\n\n expect(&mut lex, RightParen);\n\n expect(&mut lex, LeftParen);\n\n assert_eq!(lex.next(), None);\n\n }\n\n\n\n #[test]\n\n fn numbers() {\n\n let src = \"(0) 1 256 0xc0ffee 0b110101 00000001903 -99 0.5 .5 -9.234 123a1\";\n\n let mut lex = Lexer::new(src);\n\n expect(&mut lex, LeftParen);\n\n expect_s(&mut lex, Int, \"0\");\n\n expect(&mut lex, RightParen);\n\n expect_s(&mut lex, Int, \"1\");\n", "file_path": "lib/src/lexer.rs", "rank": 38, "score": 42566.5211753701 }, { "content": " Some('(') => break self.lpar(),\n\n Some(')') => break self.rpar(),\n\n Some(';') => break self.comment(),\n\n Some('\"') => break self.string(),\n\n Some('-') => break self.minus(),\n\n Some(_) => break self.ident(),\n\n None => break self.ret(Self::eof, Eof),\n\n }\n\n }\n\n }\n\n\n\n fn default_match(&self, opt: Option<char>) -> Option<LexFn<Self>> {\n\n match opt {\n\n Some('(') => Some(Self::lpar),\n\n Some(')') => Some(Self::rpar),\n\n Some(';') => Some(Self::comment),\n\n Some('\"') => Some(Self::string),\n\n Some(c) if c.is_whitespace() => Some(Self::begin),\n\n Some(c) if c.is_control() => Some(Self::begin),\n\n Some(_) => None,\n", "file_path": "lib/src/lexer.rs", "rank": 39, "score": 42565.58268373696 }, { "content": " None => {\n\n self.end = self.src.len();\n\n None\n\n }\n\n }\n\n }\n\n\n\n fn begin(&mut self) -> Token {\n\n let mut opt;\n\n\n\n loop {\n\n opt = self.advance();\n\n self.start = self.end;\n\n\n\n match opt {\n\n Some('0') => break self.zero(),\n\n Some(c) if c.is_ascii_digit() => break self.int(),\n\n Some(c) if c.is_whitespace() => continue,\n\n Some(c) if c.is_control() => continue,\n\n Some('.') => break self.float(),\n", "file_path": "lib/src/lexer.rs", "rank": 40, "score": 42564.66000893189 }, { "content": "\n\n loop {\n\n match self.advance() {\n\n Some('0') | Some('1') => continue,\n\n opt => break self.default_ret(opt, Bin, NumError),\n\n }\n\n }\n\n }\n\n\n\n fn ident(&mut self) -> Token {\n\n let mut opt;\n\n\n\n loop {\n\n opt = self.advance();\n\n\n\n match self.default_match(opt) {\n\n None => continue,\n\n Some(f) => break self.ret(f, Ident),\n\n }\n\n }\n", "file_path": "lib/src/lexer.rs", "rank": 41, "score": 42563.64743653249 }, { "content": " .map(|t| t.0)\n\n .unwrap_or(self.src.len());\n\n }\n\n\n\n fn lpar(&mut self) -> Token {\n\n self.ret(Self::begin, LeftParen)\n\n }\n\n\n\n fn rpar(&mut self) -> Token {\n\n self.ret(Self::begin, RightParen)\n\n }\n\n\n\n fn comment(&mut self) -> Token {\n\n self.skip_to('\\n');\n\n self.begin()\n\n }\n\n\n\n fn string(&mut self) -> Token {\n\n self.start = self.end + 1;\n\n self.skip_to('\"');\n", "file_path": "lib/src/lexer.rs", "rank": 42, "score": 42563.4537894961 }, { "content": " }\n\n }\n\n\n\n pub fn next(&mut self) -> Option<Token> {\n\n Some((self.f)(self)).filter(|t| t != &Eof)\n\n }\n\n\n\n pub fn get_str(&self) -> &str {\n\n &self.src[self.start..self.end]\n\n }\n\n\n\n fn advance(&mut self) -> Option<char> {\n\n match self.iter.next() {\n\n Some((idx, chr)) => {\n\n if chr == '\\n' {\n\n self.line += 1;\n\n }\n\n self.end = idx;\n\n Some(chr)\n\n }\n", "file_path": "lib/src/lexer.rs", "rank": 43, "score": 42562.69174437142 }, { "content": " match self.advance() {\n\n Some(c) if c.is_ascii_digit() => continue,\n\n opt => break self.default_ret(opt, Float, NumError),\n\n }\n\n }\n\n }\n\n\n\n fn hex(&mut self) -> Token {\n\n self.start += 2;\n\n\n\n loop {\n\n match self.advance() {\n\n Some(c) if c.is_ascii_hexdigit() => continue,\n\n opt => break self.default_ret(opt, Hex, NumError),\n\n }\n\n }\n\n }\n\n\n\n fn bin(&mut self) -> Token {\n\n self.start += 2;\n", "file_path": "lib/src/lexer.rs", "rank": 44, "score": 42562.41756279837 }, { "content": " Quote(AstPtr),\n\n Str(StrId),\n\n U32(u32),\n\n}\n\n\n\nimpl Value {\n\n pub fn parse_int(s: &str) -> Result<Self> {\n\n i32::from_str(s).map(I32).map_err(|_| Error::ParseNum)\n\n }\n\n\n\n pub fn parse_float(s: &str) -> Result<Self> {\n\n f32::from_str(s).map(F32).map_err(|_| Error::ParseNum)\n\n }\n\n\n\n pub fn parse_hex(s: &str) -> Result<Self> {\n\n u32::from_str_radix(s, 16)\n\n .map(U32)\n\n .map_err(|_| Error::ParseNum)\n\n }\n\n\n", "file_path": "lib/src/value.rs", "rank": 45, "score": 42388.82611899027 }, { "content": "use crate::{\n\n error::{Error, Result},\n\n parser::{AstPtr, StrId},\n\n};\n\nuse std::convert::TryInto;\n\nuse std::fmt;\n\nuse std::ops::{Add, Div, Mul, Rem, Sub};\n\nuse std::str::FromStr;\n\nuse Value::*;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq)]\n\npub enum Value {\n\n Bool(bool),\n\n Builtin(u32),\n\n F32(f32),\n\n I32(i32),\n\n Ident(StrId),\n\n Lambda(u32),\n\n Midi(u32),\n\n Nil,\n", "file_path": "lib/src/value.rs", "rank": 46, "score": 42387.99524594776 }, { "content": " pub fn parse_bin(s: &str) -> Result<Self> {\n\n u32::from_str_radix(s, 2)\n\n .map(U32)\n\n .map_err(|_| Error::ParseNum)\n\n }\n\n\n\n pub fn to_u32(self) -> Result<Value> {\n\n match self {\n\n U32(_) => Ok(self),\n\n I32(v) => v.try_into().map(U32).map_err(|_| Error::Convert),\n\n F32(v) => Ok(v as u32).map(U32),\n\n Nil => Err(Error::NilArgument),\n\n _ => Err(Error::NotANumber),\n\n }\n\n }\n\n\n\n pub fn to_i32(self) -> Result<Value> {\n\n match self {\n\n I32(_) => Ok(self),\n\n U32(v) => v.try_into().map(I32).map_err(|_| Error::Convert),\n", "file_path": "lib/src/value.rs", "rank": 47, "score": 42381.29028085204 }, { "content": " Self::Quote(_) => write!(f, \"<quote>\"),\n\n Self::Str(_) => write!(f, \"<str>\"),\n\n Self::U32(n) => fmt::Display::fmt(&n, f),\n\n Self::I32(n) => fmt::Display::fmt(&n, f),\n\n Self::F32(n) => fmt::Display::fmt(&n, f),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::LowerHex for Value {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Self::U32(n) => fmt::LowerHex::fmt(&n, f),\n\n Self::I32(n) => fmt::LowerHex::fmt(&n, f),\n\n val => fmt::Display::fmt(&val, f),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Binary for Value {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Self::U32(n) => fmt::Binary::fmt(&n, f),\n\n Self::I32(n) => fmt::Binary::fmt(&n, f),\n\n val => fmt::Display::fmt(&val, f),\n\n }\n\n }\n\n}\n", "file_path": "lib/src/value.rs", "rank": 48, "score": 42379.77856323215 }, { "content": "\n\n pub fn le(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(Bool(lhs <= rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(Bool(lhs <= rhs)),\n\n (F32(lhs), F32(rhs)) => Ok(Bool(lhs <= rhs)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for Value {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Self::Bool(b) => fmt::Display::fmt(&b, f),\n\n Self::Builtin(_) => write!(f, \"<builtin>\"),\n\n Self::Ident(_) => write!(f, \"<ident>\"),\n\n Self::Lambda(_) => write!(f, \"<lambda>\"),\n\n Self::Midi(_) => write!(f, \"<midi event>\"),\n\n Self::Nil => write!(f, \"()\"),\n", "file_path": "lib/src/value.rs", "rank": 49, "score": 42376.60077948393 }, { "content": " _ => Err(Error::NotMidi),\n\n }\n\n }\n\n\n\n pub fn to_str(self) -> Result<StrId> {\n\n match self {\n\n Str(id) => Ok(id),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn clamp(self, max: u32) -> Result<Self> {\n\n match self {\n\n U32(v) => Ok(U32(v.min(max))),\n\n I32(v) => Ok(I32(v.max(0).min(max as i32))),\n\n F32(v) => Ok(F32(v.clamp(0.0, max as f32))),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n", "file_path": "lib/src/value.rs", "rank": 50, "score": 42376.35343678974 }, { "content": " .ok_or(Error::Overflow)\n\n }\n\n\n\n pub fn shl(self, other: Self) -> Result<Self> {\n\n match (self, other.to_u32()?) {\n\n (I32(lhs), U32(rhs)) => lhs.checked_shl(rhs).map(I32).ok_or(Error::Convert),\n\n (U32(lhs), U32(rhs)) => lhs.checked_shl(rhs).map(U32).ok_or(Error::Convert),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn shr(self, other: Self) -> Result<Self> {\n\n match (self, other.to_u32()?) {\n\n (I32(lhs), U32(rhs)) => lhs.checked_shr(rhs).map(I32).ok_or(Error::Convert),\n\n (U32(lhs), U32(rhs)) => lhs.checked_shr(rhs).map(U32).ok_or(Error::Convert),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn bitand(self, other: Self) -> Result<Self> {\n", "file_path": "lib/src/value.rs", "rank": 51, "score": 42373.800419040366 }, { "content": " F32(v) => Ok(v as i32).map(I32),\n\n Nil => Err(Error::NilArgument),\n\n _ => Err(Error::NotANumber),\n\n }\n\n }\n\n\n\n pub fn to_f32(self) -> Result<Value> {\n\n match self {\n\n F32(_) => Ok(self),\n\n U32(v) => Ok(v as f32).map(F32),\n\n I32(v) => Ok(v as f32).map(F32),\n\n Nil => Err(Error::NilArgument),\n\n _ => Err(Error::NotANumber),\n\n }\n\n }\n\n\n\n pub fn to_midi(self) -> Result<u32> {\n\n match self {\n\n Midi(e) => Ok(e),\n\n Nil => Err(Error::NilArgument),\n", "file_path": "lib/src/value.rs", "rank": 52, "score": 42373.035065502016 }, { "content": " U32(v) => Ok(v),\n\n _ => unreachable!(),\n\n }\n\n }\n\n\n\n pub fn abs(self) -> Result<Self> {\n\n match self {\n\n v @ U32(_) => Ok(v),\n\n I32(v) => Ok(I32(v.abs())),\n\n F32(v) => Ok(F32(v.abs())),\n\n _ => Err(Error::NotANumber),\n\n }\n\n }\n\n\n\n pub fn neg(self) -> Result<Self> {\n\n match self {\n\n I32(v) => Ok(I32(-v)),\n\n F32(v) => Ok(F32(-v)),\n\n _ => Err(Error::TypeErr),\n\n }\n", "file_path": "lib/src/value.rs", "rank": 53, "score": 42372.9452347699 }, { "content": "\n\n pub fn add(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => lhs.checked_add(rhs).map(I32),\n\n (U32(lhs), U32(rhs)) => lhs.checked_add(rhs).map(U32),\n\n (F32(lhs), F32(rhs)) => Some(lhs.add(rhs)).map(F32),\n\n _ => return Err(Error::TypeErr),\n\n }\n\n .ok_or(Error::Overflow)\n\n }\n\n\n\n pub fn sub(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => lhs.checked_sub(rhs).map(I32),\n\n (U32(lhs), U32(rhs)) => lhs.checked_sub(rhs).map(U32),\n\n (F32(lhs), F32(rhs)) => Some(lhs.sub(rhs)).map(F32),\n\n _ => return Err(Error::TypeErr),\n\n }\n\n .ok_or(Error::Overflow)\n\n }\n", "file_path": "lib/src/value.rs", "rank": 54, "score": 42372.23425859232 }, { "content": "\n\n pub fn rem(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => lhs.checked_rem(rhs).map(I32),\n\n (U32(lhs), U32(rhs)) => lhs.checked_rem(rhs).map(U32),\n\n (F32(lhs), F32(rhs)) => Some(lhs.rem(rhs)).map(F32),\n\n _ => return Err(Error::TypeErr),\n\n }\n\n .ok_or(Error::DivideByZero)\n\n }\n\n\n\n pub fn pow(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => lhs\n\n .checked_pow(rhs.try_into().map_err(|_| Error::Convert)?)\n\n .map(I32),\n\n (U32(lhs), U32(rhs)) => lhs.checked_pow(rhs).map(U32),\n\n (F32(lhs), F32(rhs)) => Some(lhs.powf(rhs)).map(F32),\n\n _ => return Err(Error::TypeErr),\n\n }\n", "file_path": "lib/src/value.rs", "rank": 55, "score": 42372.22435325558 }, { "content": "\n\n pub fn mul(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => lhs.checked_mul(rhs).map(I32),\n\n (U32(lhs), U32(rhs)) => lhs.checked_mul(rhs).map(U32),\n\n (F32(lhs), F32(rhs)) => Some(lhs.mul(rhs)).map(F32),\n\n _ => return Err(Error::TypeErr),\n\n }\n\n .ok_or(Error::Overflow)\n\n }\n\n\n\n pub fn div(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => lhs.checked_div(rhs).map(I32),\n\n (U32(lhs), U32(rhs)) => lhs.checked_div(rhs).map(U32),\n\n (F32(lhs), F32(rhs)) => Some(lhs.div(rhs)).map(F32),\n\n _ => return Err(Error::TypeErr),\n\n }\n\n .ok_or(Error::DivideByZero)\n\n }\n", "file_path": "lib/src/value.rs", "rank": 56, "score": 42372.16082259879 }, { "content": " }\n\n\n\n pub fn not(self) -> Result<Self> {\n\n match self {\n\n U32(v) => Ok(U32(!v)),\n\n I32(v) => Ok(I32(!v)),\n\n Bool(v) => Ok(Bool(!v)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn convert(self, other: Self) -> Result<(Self, Self)> {\n\n Ok(match (self, other) {\n\n (I32(_), U32(_)) => (self, other.to_i32()?),\n\n (U32(_), I32(_)) => (self, other.to_u32()?),\n\n (F32(_), rhs) => (self, rhs.to_f32()?),\n\n (lhs, F32(_)) => (lhs.to_f32()?, other),\n\n _ => (self, other),\n\n })\n\n }\n", "file_path": "lib/src/value.rs", "rank": 57, "score": 42371.64025974653 }, { "content": " match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(I32(lhs & rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(U32(lhs & rhs)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn bitor(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(I32(lhs | rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(U32(lhs | rhs)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn bitxor(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(I32(lhs ^ rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(U32(lhs ^ rhs)),\n\n _ => Err(Error::TypeErr),\n", "file_path": "lib/src/value.rs", "rank": 58, "score": 42370.61317852311 }, { "content": " pub fn _to_u7(self) -> Result<u8> {\n\n Ok(match self.clamp(0x7f)? {\n\n U32(v) => v as u8,\n\n I32(v) => v as u8,\n\n F32(v) => v as u8,\n\n _ => unreachable!(),\n\n })\n\n }\n\n\n\n pub fn _to_u16(self) -> Result<u16> {\n\n Ok(match self.clamp(0xffff)? {\n\n U32(v) => v as u16,\n\n I32(v) => v as u16,\n\n F32(v) => v as u16,\n\n _ => unreachable!(),\n\n })\n\n }\n\n\n\n pub fn _to_u32(self) -> Result<u32> {\n\n match self.to_u32()? {\n", "file_path": "lib/src/value.rs", "rank": 59, "score": 42370.26196823723 }, { "content": " pub fn eq(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (lhs, rhs) if lhs == rhs => Ok(Bool(true)),\n\n _ => Ok(Bool(false)),\n\n }\n\n }\n\n\n\n pub fn ne(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (lhs, rhs) if lhs != rhs => Ok(Bool(true)),\n\n _ => Ok(Bool(false)),\n\n }\n\n }\n\n\n\n pub fn gt(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(Bool(lhs > rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(Bool(lhs > rhs)),\n\n (F32(lhs), F32(rhs)) => Ok(Bool(lhs > rhs)),\n\n _ => Err(Error::TypeErr),\n", "file_path": "lib/src/value.rs", "rank": 60, "score": 42369.68007396875 }, { "content": " }\n\n }\n\n\n\n pub fn lt(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(Bool(lhs < rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(Bool(lhs < rhs)),\n\n (F32(lhs), F32(rhs)) => Ok(Bool(lhs < rhs)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn ge(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (I32(lhs), I32(rhs)) => Ok(Bool(lhs >= rhs)),\n\n (U32(lhs), U32(rhs)) => Ok(Bool(lhs >= rhs)),\n\n (F32(lhs), F32(rhs)) => Ok(Bool(lhs >= rhs)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n", "file_path": "lib/src/value.rs", "rank": 61, "score": 42369.46489558363 }, { "content": " }\n\n }\n\n\n\n pub fn and(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (Bool(true), Bool(true)) => Ok(Bool(true)),\n\n (Bool(_), Bool(_)) => Ok(Bool(false)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n\n pub fn or(self, other: Self) -> Result<Self> {\n\n match self.convert(other)? {\n\n (Bool(true), Bool(_)) => Ok(Bool(true)),\n\n (Bool(_), Bool(true)) => Ok(Bool(true)),\n\n (Bool(_), Bool(_)) => Ok(Bool(false)),\n\n _ => Err(Error::TypeErr),\n\n }\n\n }\n\n\n", "file_path": "lib/src/value.rs", "rank": 62, "score": 42367.85517117964 }, { "content": " exportString(str) {\n\n const bytes = new TextEncoder(\"utf-8\").encode(str);\n\n return this.exportBytes(bytes);\n", "file_path": "web/midilisp.js", "rank": 63, "score": 21548.3759705891 }, { "content": " importString(ptr) {\n\n const bytes = this.importBytes(ptr);\n\n return new TextDecoder(\"utf-8\").decode(bytes);\n", "file_path": "web/midilisp.js", "rank": 64, "score": 21548.3759705891 }, { "content": " fn expect_arg(&mut self, expr: AstPtr) -> Result<(Value, AstPtr)> {\n\n let (car, cdr) = self.expect_cons(expr)?;\n\n Ok((self.eval(car)?, cdr))\n\n }\n\n\n\n fn expect_cons(&self, expr: AstPtr) -> Result<(AstPtr, AstPtr)> {\n\n match self.parser.get(expr) {\n\n Expr::Cons(car, cdr) => Ok((car, cdr)),\n\n _ => Err(Error::NilArgument),\n\n }\n\n }\n\n\n\n fn expect_ident(&self, expr: AstPtr) -> Result<StrId> {\n\n match self.parser.get(expr) {\n\n Expr::Atom(Value::Ident(i)) => Ok(i),\n\n _ => Err(Error::NotAnIdent),\n\n }\n\n }\n\n\n\n fn expect_midi(&mut self, expr: AstPtr) -> Result<(u32, AstPtr)> {\n", "file_path": "lib/src/interpreter.rs", "rank": 65, "score": 15237.217491672898 }, { "content": " }\n\n\n\n fn define(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (car, cdr) = self.expect_cons(expr)?;\n\n let id = self.expect_ident(car)?;\n\n let (expr, nil) = self.expect_cons(cdr)?;\n\n self.expect_nil(nil)?;\n\n let val = self.eval(expr)?;\n\n self.env.extend(self.env.current, id, val);\n\n Ok(Value::Nil)\n\n }\n\n\n\n fn eval(&mut self, expr: AstPtr) -> Result<Value> {\n\n match self.parser.get(expr) {\n\n Expr::Cons(car, cdr) => {\n\n let val = self.eval(car)?;\n\n self.apply(val, cdr)\n\n }\n\n Expr::Atom(Value::Ident(id)) => self.get(id),\n\n Expr::Atom(val) => Ok(val),\n", "file_path": "lib/src/interpreter.rs", "rank": 66, "score": 15236.881343337598 }, { "content": " let (car, cdr) = self.expect_cons(expr)?;\n\n Ok((self.eval(car)?._to_u32()?, cdr))\n\n }\n\n\n\n fn expect_u7(&mut self, expr: AstPtr) -> Result<(u8, AstPtr)> {\n\n let (car, cdr) = self.expect_cons(expr)?;\n\n Ok((self.eval(car)?._to_u7()?, cdr))\n\n }\n\n\n\n fn get(&mut self, id: StrId) -> Result<Value> {\n\n self.c_ident = Some(id);\n\n self.env.get(id).ok_or(Error::Undefined)\n\n }\n\n\n\n fn get_event(&self, id: u32) -> Event {\n\n *self\n\n .events\n\n .get_index(id as usize)\n\n .expect(\"BUG: Invalid event id\")\n\n }\n", "file_path": "lib/src/interpreter.rs", "rank": 67, "score": 15232.898313853857 }, { "content": " } else {\n\n self.log.insert(id, 1);\n\n }\n\n }\n\n\n\n fn _log(&mut self, expr: AstPtr, fmt: char) -> Result<Value> {\n\n let (val, nil) = self.expect_arg(expr)?;\n\n self.expect_nil(nil)?;\n\n\n\n match (val, fmt) {\n\n (Value::Str(id), _) => self.log_str_id(id),\n\n (val, 'x') => self.log_str(&format!(\"{:#x}\", val)),\n\n (val, 'b') => self.log_str(&format!(\"{:#b}\", val)),\n\n (val, _) => self.log_str(&val.to_string()),\n\n }\n\n\n\n Ok(Value::Nil)\n\n }\n\n\n\n fn log(&mut self, expr: AstPtr) -> Result<Value> {\n", "file_path": "lib/src/interpreter.rs", "rank": 68, "score": 15229.60189910071 }, { "content": "\n\n fn get_track(&mut self, id: u32) -> &mut Track {\n\n let trk = id as usize;\n\n\n\n if trk >= self.tracks.len() {\n\n self.tracks.resize_with(trk + 1, Track::new);\n\n }\n\n\n\n self.tracks.get_mut(trk).unwrap()\n\n }\n\n\n\n fn if_(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (cond, next) = self.expect_arg(expr)?;\n\n let (car, cdr) = self.expect_cons(next)?;\n\n\n\n if let Ok((_, nil)) = self.expect_cons(cdr) {\n\n self.expect_nil(nil)?;\n\n }\n\n\n\n if cond == Value::Bool(true) {\n", "file_path": "lib/src/interpreter.rs", "rank": 69, "score": 15228.453348068873 }, { "content": "use crate::parser::StrId;\n\nuse crate::value::Value;\n\nuse crate::FnvIndexMap;\n\n\n\npub type EnvId = u32;\n\n\n\npub struct EnvStore {\n\n count: u32,\n\n pub current: EnvId,\n\n pub capture: bool,\n\n parents: FnvIndexMap<EnvId, EnvId>,\n\n values: FnvIndexMap<(EnvId, StrId), Value>,\n\n}\n\n\n\nimpl EnvStore {\n\n pub fn new() -> Self {\n\n Self {\n\n count: 0,\n\n current: 0,\n\n capture: false,\n", "file_path": "lib/src/env.rs", "rank": 70, "score": 15228.39617480236 }, { "content": " fn adv_clock(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (trk, next) = self.expect_u32(expr)?;\n\n let (dur, next) = self.expect_u32(next)?;\n\n self.expect_nil(next)?;\n\n self.get_track(trk).advance(dur)?;\n\n Ok(Value::Nil)\n\n }\n\n\n\n fn apply(&mut self, val: Value, cdr: AstPtr) -> Result<Value> {\n\n match val {\n\n Value::Builtin(i) => self.builtins[i as usize](self, cdr),\n\n Value::Lambda(i) => self.call(i, cdr),\n\n val if cdr == NIL => Ok(val),\n\n Value::I32(n) => self.repeat(n, cdr),\n\n _ => Err(Error::CannotApply),\n\n }\n\n }\n\n\n\n fn assert(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (val, nil) = self.expect_arg(expr)?;\n", "file_path": "lib/src/interpreter.rs", "rank": 71, "score": 15228.38204566984 }, { "content": " let (car, cdr) = self.expect_cons(expr)?;\n\n Ok((self.eval(car)?.to_midi()?, cdr))\n\n }\n\n\n\n fn expect_nil(&mut self, expr: AstPtr) -> Result<()> {\n\n if expr == NIL {\n\n Ok(())\n\n } else {\n\n Err(Error::ExtraArgument)\n\n }\n\n }\n\n\n\n fn expect_quote(&mut self, expr: AstPtr) -> Result<AstPtr> {\n\n match self.eval(expr)? {\n\n Value::Quote(i) => Ok(i),\n\n _ => Err(Error::NotAQuote),\n\n }\n\n }\n\n\n\n fn expect_u32(&mut self, expr: AstPtr) -> Result<(u32, AstPtr)> {\n", "file_path": "lib/src/interpreter.rs", "rank": 72, "score": 15228.335237974308 }, { "content": " self.eval(car)\n\n } else if cond == Value::Bool(false) {\n\n self.eval(cdr)\n\n } else {\n\n Err(Error::TypeErr)\n\n }\n\n }\n\n\n\n fn include(&mut self, expr: AstPtr) -> Result<Value> {\n\n let mut args = expr;\n\n\n\n while args != NIL {\n\n let (arg, more) = self.expect_cons(args)?;\n\n let id = self.eval(arg)?.to_str()?;\n\n self._include(id)?;\n\n args = more;\n\n }\n\n\n\n Ok(Value::Nil)\n\n }\n", "file_path": "lib/src/interpreter.rs", "rank": 73, "score": 15227.449381071492 }, { "content": " arg_vals = vcdr;\n\n }\n\n\n\n if arg_vals != NIL {\n\n return Err(Error::ExtraArgument);\n\n }\n\n\n\n self.eval_body(body, lambda_env)\n\n }\n\n\n\n fn car(&mut self, expr: AstPtr) -> Result<Value> {\n\n let q = self.expect_quote(expr)?;\n\n let (car, _) = self.expect_cons(q)?;\n\n self.quote(car)\n\n }\n\n\n\n fn cdr(&mut self, expr: AstPtr) -> Result<Value> {\n\n let q = self.expect_quote(expr)?;\n\n let (_, cdr) = self.expect_cons(q)?;\n\n self.quote(cdr)\n", "file_path": "lib/src/interpreter.rs", "rank": 74, "score": 15226.616363526196 }, { "content": " let (car, cdr) = self.expect_cons(expr)?;\n\n let id = self.expect_ident(car)?;\n\n let (expr, nil) = self.expect_cons(cdr)?;\n\n self.expect_nil(nil)?;\n\n let val = self.eval(expr)?;\n\n\n\n if self.env.set(id, val) {\n\n Ok(Value::Nil)\n\n } else {\n\n Err(Error::Undefined)\n\n }\n\n }\n\n\n\n fn note_off(&mut self, next: AstPtr) -> Result<Value> {\n\n let (chn, next) = self.expect_u7(next)?;\n\n let (num, next) = self.expect_u7(next)?;\n\n let (vel, next) = self.expect_u7(next)?;\n\n self.expect_nil(next)?;\n\n self.add_event(Event::NoteOff(chn, num, vel))\n\n }\n", "file_path": "lib/src/interpreter.rs", "rank": 75, "score": 15225.590653485438 }, { "content": "\n\n fn lambda(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (args, body) = self.expect_cons(expr)?;\n\n let mut m_args = args;\n\n\n\n while m_args != NIL {\n\n let (arg, more) = self.expect_cons(m_args)?;\n\n self.expect_ident(arg)?;\n\n m_args = more;\n\n }\n\n\n\n self.env.capture = true;\n\n let id = self.lambdas.insert_full((args, body), self.env.current).0;\n\n Ok(Value::Lambda(id as u32))\n\n }\n\n\n\n fn let_(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (mut args, body) = self.expect_cons(expr)?;\n\n let new_env = self.env.create(self.env.current);\n\n\n", "file_path": "lib/src/interpreter.rs", "rank": 76, "score": 15224.749287489281 }, { "content": " while args != NIL {\n\n let (arg, more) = self.expect_cons(args)?;\n\n let (car, cdr) = self.expect_cons(arg)?;\n\n let id = self.expect_ident(car)?;\n\n let val = self.eval(cdr)?;\n\n self.env.extend(new_env, id, val);\n\n args = more;\n\n }\n\n\n\n self.eval_body(body, new_env)\n\n }\n\n\n\n fn log_str(&mut self, s: &str) {\n\n let id = self.parser.add_str(s);\n\n self.log_str_id(id);\n\n }\n\n\n\n fn log_str_id(&mut self, id: StrId) {\n\n if let Some(count) = self.log.get_mut(&id) {\n\n *count += 1;\n", "file_path": "lib/src/interpreter.rs", "rank": 77, "score": 15224.656609939088 }, { "content": "\n\n fn call(&mut self, lambda: u32, mut arg_vals: AstPtr) -> Result<Value> {\n\n let (mut arg_ids, body, par_env) = self\n\n .lambdas\n\n .get_index(lambda as usize)\n\n .map(|((a, b), e)| (*a, *b, *e))\n\n .expect(\"BUG: invalid lambda id\");\n\n let lambda_env = self.env.create(par_env);\n\n\n\n while arg_ids != NIL {\n\n let (icar, icdr) = self.expect_cons(arg_ids)?;\n\n let (vcar, vcdr) = self.expect_cons(arg_vals).map_err(|_| Error::NilArgument)?;\n\n let id = self.expect_ident(icar).unwrap();\n\n let val = self.eval(vcar)?;\n\n\n\n if !self.env.extend(lambda_env, id, val) {\n\n return Err(Error::DuplicateArg);\n\n }\n\n\n\n arg_ids = icdr;\n", "file_path": "lib/src/interpreter.rs", "rank": 78, "score": 15224.466100131578 }, { "content": " self._log(expr, 'd')\n\n }\n\n\n\n fn logx(&mut self, expr: AstPtr) -> Result<Value> {\n\n self._log(expr, 'x')\n\n }\n\n\n\n fn logb(&mut self, expr: AstPtr) -> Result<Value> {\n\n self._log(expr, 'b')\n\n }\n\n\n\n fn bitnot(&mut self, expr: AstPtr) -> Result<Value> {\n\n let (lhs, next) = self.expect_u32(expr)?;\n\n self.expect_nil(next)?;\n\n Ok(Value::U32(!lhs))\n\n }\n\n\n\n fn quote(&mut self, expr: AstPtr) -> Result<Value> {\n\n match self.parser.get(expr) {\n\n Expr::Atom(v @ Value::U32(_)) => Ok(v),\n", "file_path": "lib/src/interpreter.rs", "rank": 79, "score": 15224.02876423659 }, { "content": "use crate::{\n\n env::{EnvId, EnvStore},\n\n error::{Error, Result, WithContext},\n\n midi::{Event, Header, Track},\n\n parser::{AstPtr, Expr, Parser, StrId, NIL},\n\n value::Value,\n\n FnvIndexMap, FnvIndexSet,\n\n};\n\nuse std::convert::TryInto;\n\nuse std::io::Write;\n\nuse std::path::PathBuf;\n\n\n\nconst INCLUDE_PATH: &str = \"./include\";\n\n\n", "file_path": "lib/src/interpreter.rs", "rank": 80, "score": 15223.590775089731 }, { "content": " builtins: Vec::with_capacity(40),\n\n paths: Vec::new(),\n\n lambdas: Default::default(),\n\n events: Default::default(),\n\n tracks: Vec::new(),\n\n c_path: None,\n\n c_ident: None,\n\n log: Default::default(),\n\n };\n\n itp._define_builtins();\n\n itp\n\n }\n\n\n\n pub fn run<W: Write>(&mut self, writer: &mut W, src: &str) -> Result<Value> {\n\n let exprs = self.parser.parse(src)?;\n\n let mut retval = Value::Nil;\n\n\n\n for expr in exprs.iter() {\n\n retval = self.eval(*expr)?;\n\n }\n", "file_path": "lib/src/interpreter.rs", "rank": 81, "score": 15223.29677569357 }, { "content": " }\n\n\n\n Ok(())\n\n }\n\n\n\n fn _define(&mut self, s: &'static str, val: Value) {\n\n let id = self.parser.add_str(s);\n\n self.env.extend(0, id, val);\n\n }\n\n\n\n fn _builtin(&mut self, s: &'static str, f: fn(&mut Self, AstPtr) -> Result<Value>) {\n\n self.builtins.push(f);\n\n self._define(s, Value::Builtin((self.builtins.len() - 1) as u32));\n\n }\n\n\n\n fn _define_builtins(&mut self) {\n\n self._define(\"fmt\", Value::U32(0));\n\n self._define(\"div\", Value::U32(96));\n\n self._define(\"true\", Value::Bool(true));\n\n self._define(\"false\", Value::Bool(false));\n", "file_path": "lib/src/interpreter.rs", "rank": 82, "score": 15222.629776687349 }, { "content": " fn _include(&mut self, id: StrId) -> Result<()> {\n\n use crate::wasm;\n\n let s = self.parser.get_str(id);\n\n let name = s.strip_suffix(\".midilisp\").unwrap_or(s);\n\n\n\n let src = match name {\n\n \"default\" => wasm::DEFAULT,\n\n _ => return Err(Error::InvalidPath),\n\n };\n\n\n\n let path = PathBuf::from(name);\n\n\n\n if !self.paths.contains(&path) {\n\n let exprs = self.parser.parse(&src)?;\n\n\n\n for expr in exprs.iter() {\n\n self.eval(*expr)?;\n\n }\n\n\n\n self.paths.push(path);\n", "file_path": "lib/src/interpreter.rs", "rank": 83, "score": 15221.957701786465 }, { "content": " }\n\n\n\n fn var_op(&mut self, expr: AstPtr, f: OpFn) -> Result<Value> {\n\n let (mut acc, next) = self.expect_arg(expr)?;\n\n let (mut rhs, mut next) = self.expect_arg(next)?;\n\n\n\n loop {\n\n acc = f(acc, rhs)?;\n\n\n\n if let Ok((val, cdr)) = self.expect_arg(next) {\n\n rhs = val;\n\n next = cdr;\n\n } else {\n\n break;\n\n }\n\n }\n\n\n\n self.expect_nil(next)?;\n\n Ok(acc)\n\n }\n", "file_path": "lib/src/interpreter.rs", "rank": 84, "score": 15221.675285864943 }, { "content": " Expr::Atom(v @ Value::I32(_)) => Ok(v),\n\n Expr::Atom(v @ Value::F32(_)) => Ok(v),\n\n Expr::Atom(v @ Value::Str(_)) => Ok(v),\n\n Expr::Atom(v @ Value::Nil) => Ok(v),\n\n Expr::Atom(Value::Ident(id)) => self.get(id),\n\n _ => Ok(Value::Quote(expr)),\n\n }\n\n }\n\n\n\n fn repeat(&mut self, times: i32, expr: AstPtr) -> Result<Value> {\n\n let mut retval = Value::Nil;\n\n\n\n for _ in 0..times.abs() {\n\n retval = self.eval_body(expr, self.env.current)?;\n\n }\n\n\n\n Ok(retval)\n\n }\n\n\n\n fn set(&mut self, expr: AstPtr) -> Result<Value> {\n", "file_path": "lib/src/interpreter.rs", "rank": 85, "score": 15221.541004025701 }, { "content": " self.expect_nil(nil)?;\n\n\n\n if val != Value::Bool(true) {\n\n return Err(Error::Assert);\n\n }\n\n\n\n Ok(Value::Nil)\n\n }\n\n\n\n fn un_op(&mut self, expr: AstPtr, f: UnOpFn) -> Result<Value> {\n\n let (lhs, next) = self.expect_arg(expr)?;\n\n self.expect_nil(next)?;\n\n f(lhs)\n\n }\n\n\n\n fn bin_op(&mut self, expr: AstPtr, f: OpFn) -> Result<Value> {\n\n let (lhs, next) = self.expect_arg(expr)?;\n\n let (rhs, next) = self.expect_arg(next)?;\n\n self.expect_nil(next)?;\n\n f(lhs, rhs)\n", "file_path": "lib/src/interpreter.rs", "rank": 86, "score": 15221.532386424333 }, { "content": " loop {\n\n match self.values.get(&(env, id)) {\n\n None if env > 0 => env = self.parent(env),\n\n opt => return opt.copied(),\n\n }\n\n }\n\n }\n\n\n\n pub fn set(&mut self, id: StrId, val: Value) -> bool {\n\n let mut env = self.current;\n\n\n\n loop {\n\n if let Some(refer) = self.values.get_mut(&(env, id)) {\n\n *refer = val;\n\n return true;\n\n } else if env > 0 {\n\n env = self.parent(env);\n\n } else {\n\n return false;\n\n }\n\n }\n\n }\n\n}\n", "file_path": "lib/src/env.rs", "rank": 87, "score": 15221.453628824585 }, { "content": " self._builtin(\"program-change\", Self::program_change);\n\n self._builtin(\"set-tempo\", Self::set_tempo);\n\n self._builtin(\"time-signature\", Self::time_signature);\n\n self._builtin(\"pitch-bend\", Self::pitch_bend);\n\n self._builtin(\"put-event\", Self::put_event);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{Interpreter, Value};\n\n use crate::error::Error;\n\n\n\n #[test]\n\n fn assert() {\n\n let src = \"(assert true)\n\n (assert (&& true true))\n\n (assert (|| false false))\";\n\n let mut itp = Interpreter::new();\n\n let exprs = itp.parser.parse(src).unwrap();\n", "file_path": "lib/src/interpreter.rs", "rank": 88, "score": 15218.75913184404 }, { "content": " let mut log = String::new();\n\n\n\n for (id, count) in self.log.iter() {\n\n log.push_str(self.parser.get_str(*id));\n\n\n\n if *count > 1 {\n\n log.push_str(&format!(\" ({})\", count));\n\n }\n\n\n\n log.push('\\n');\n\n }\n\n\n\n log\n\n }\n\n\n\n fn write_out<W: Write>(&mut self, writer: &mut W) -> Result<()> {\n\n let fmt: u16 = self.get(0).map(|v| v._to_u16().unwrap_or(0))?;\n\n let div: u16 = self.get(1).map(|v| v._to_u16().unwrap_or(96))?;\n\n self.c_ident = None;\n\n let ntrks: u16 = self\n", "file_path": "lib/src/interpreter.rs", "rank": 89, "score": 15218.627506653744 }, { "content": " #[error(\"unclosed parenthesis\")]\n\n UnclosedParen,\n\n #[error(\"unclosed string literal\")]\n\n UnclosedStr,\n\n}\n\n\n\n#[derive(thiserror::Error, Clone, Debug)]\n\npub struct WithContext {\n\n pub path: Option<OsString>,\n\n pub line: Option<u32>,\n\n pub ident: Option<String>,\n\n pub source: Error,\n\n pub log: String,\n\n}\n\n\n\nimpl fmt::Display for WithContext {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n let path = self\n\n .path\n\n .as_ref()\n", "file_path": "lib/src/error.rs", "rank": 90, "score": 15217.829399412944 }, { "content": " }\n\n }\n\n\n\n fn eval_body(&mut self, mut next: AstPtr, lambda_env: u32) -> Result<Value> {\n\n let mut retval = Value::Nil;\n\n let real_env = self.env.current;\n\n self.env.current = lambda_env;\n\n self.env.capture = false;\n\n\n\n while next != NIL {\n\n let (expr, more) = self.expect_cons(next)?;\n\n retval = self.eval(expr)?;\n\n next = more;\n\n }\n\n\n\n self.env.current = real_env;\n\n self.env.pop(lambda_env);\n\n Ok(retval)\n\n }\n\n\n", "file_path": "lib/src/interpreter.rs", "rank": 91, "score": 15215.957855430841 }, { "content": "#![allow(dead_code)]\n\n\n\nmod env;\n\nmod error;\n\nmod interpreter;\n\nmod lexer;\n\nmod midi;\n\nmod parser;\n\nmod value;\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\npub mod wasm;\n\n\n\nuse error::WithContext;\n\nuse fnv::FnvBuildHasher;\n\nuse indexmap::{IndexMap, IndexSet};\n\nuse interpreter::Interpreter;\n\nuse std::io::Write;\n\n\n\npub(crate) type FnvIndexMap<K, V> = IndexMap<K, V, FnvBuildHasher>;\n\npub(crate) type FnvIndexSet<T> = IndexSet<T, FnvBuildHasher>;\n\n\n", "file_path": "lib/src/lib.rs", "rank": 92, "score": 15215.802901770176 }, { "content": "\n\n self.write_out(writer)?;\n\n Ok(retval)\n\n }\n\n\n\n pub fn get_context(&self, err: Error) -> WithContext {\n\n WithContext {\n\n path: self\n\n .c_path\n\n .map(|i| &self.paths[i])\n\n .and_then(|p| p.file_name())\n\n .map(|p| p.to_owned()),\n\n line: self.parser.line,\n\n ident: self.c_ident.map(|i| self.parser.get_str(i).to_string()),\n\n source: err,\n\n log: self.get_log(),\n\n }\n\n }\n\n\n\n pub fn get_log(&self) -> String {\n", "file_path": "lib/src/interpreter.rs", "rank": 93, "score": 15215.726657077068 }, { "content": " ptr.as_ref().expect(\"null ptr\").is_ok() as i32\n\n}\n\n\n\n#[export_name = \"unwrap\"]\n\npub unsafe extern \"C\" fn unwrap(ptr: *const WasmResult) -> *const Vec<u8> {\n\n match ptr.as_ref().expect(\"null ptr\") {\n\n Ok(v) => v,\n\n Err(v) => v,\n\n }\n\n}\n\n\n\n#[export_name = \"run\"]\n\npub extern \"C\" fn run(ptr: *const u8, len: usize) -> *const WasmResult {\n\n assert!(!ptr.is_null());\n\n assert_ne!(len, 0);\n\n assert!(len <= isize::MAX as usize);\n\n\n\n let slice = unsafe { std::slice::from_raw_parts(ptr, len) };\n\n\n\n let result = match std::str::from_utf8(slice) {\n\n Ok(src) => call_midilisp(src),\n\n Err(e) => Err(e.to_string().into_bytes()),\n\n };\n\n\n\n Box::into_raw(Box::new(result))\n\n}\n\n\n", "file_path": "lib/src/wasm.rs", "rank": 94, "score": 15215.717040693886 }, { "content": " (car (cdr (car (cdr b))))\";\n\n let mut itp = Interpreter::new();\n\n let exprs = itp.parser.parse(src).unwrap();\n\n itp.eval(exprs[0]).unwrap();\n\n itp.eval(exprs[1]).unwrap();\n\n assert_eq!(Value::I32(1), itp.eval(exprs[2]).unwrap());\n\n assert_eq!(Value::I32(2), itp.eval(exprs[3]).unwrap());\n\n assert_eq!(Value::I32(3), itp.eval(exprs[4]).unwrap());\n\n assert_eq!(Value::I32(1), itp.eval(exprs[5]).unwrap());\n\n assert_eq!(Value::I32(4), itp.eval(exprs[6]).unwrap());\n\n }\n\n\n\n #[test]\n\n fn errors() {\n\n let src = \"(define foo\n\n (lambda (a b 123)\n\n (+ a b 123)))\n\n (define foo\n\n (lambda (a a c)\n\n (+ a a c)))\n", "file_path": "lib/src/interpreter.rs", "rank": 95, "score": 15215.687266444667 }, { "content": " .and_then(|p| p.to_str())\n\n .map(|s| format!(\" in {}\", s))\n\n .unwrap_or_else(String::new);\n\n let line = self\n\n .line\n\n .map(|l| format!(\" on line {}\", l))\n\n .unwrap_or_else(String::new);\n\n let ident = self\n\n .ident\n\n .as_ref()\n\n .map(|i| format!(\" at '{}'\", i))\n\n .unwrap_or_else(String::new);\n\n writeln!(\n\n f,\n\n \"{}Error{}{}{}: {}\",\n\n self.log, path, line, ident, self.source\n\n )\n\n }\n\n}\n", "file_path": "lib/src/error.rs", "rank": 96, "score": 15215.260955998818 }, { "content": " assert_eq!(Value::Nil, itp.eval(exprs[0]).unwrap());\n\n assert_eq!(Value::Nil, itp.eval(exprs[1]).unwrap());\n\n assert_eq!(Error::Assert, itp.eval(exprs[2]).unwrap_err());\n\n }\n\n\n\n #[test]\n\n fn arithmetic() {\n\n let src = \"(+ (+ 1 (+ 4 3)) (+ (+ 4 5 7) 96))\n\n (- (- 100 2) (- (- 20 10 3) 3))\n\n (* (* 2 (* 2 3)) (* 4 5))\n\n (/ (/ 64 2) (/ 8 4))\n\n (% (% 10 6) (% 10 7))\n\n (** (** 2 2) (** 2 3))\n\n (abs -0)\n\n (abs -6)\n\n (abs -12.5)\n\n (neg 6.0)\n\n (neg -12)\";\n\n let mut itp = Interpreter::new();\n\n let exprs = itp.parser.parse(src).unwrap();\n", "file_path": "lib/src/interpreter.rs", "rank": 97, "score": 15214.940250251237 }, { "content": "\n\n fn note_on(&mut self, next: AstPtr) -> Result<Value> {\n\n let (chn, next) = self.expect_u7(next)?;\n\n let (num, next) = self.expect_u7(next)?;\n\n let (vel, next) = self.expect_u7(next)?;\n\n self.expect_nil(next)?;\n\n self.add_event(Event::NoteOn(chn, num, vel))\n\n }\n\n\n\n fn control_change(&mut self, next: AstPtr) -> Result<Value> {\n\n let (chn, next) = self.expect_u7(next)?;\n\n let (id, next) = self.expect_u7(next)?;\n\n let (val, next) = self.expect_u7(next)?;\n\n self.expect_nil(next)?;\n\n self.add_event(Event::ControlChange(chn, id, val))\n\n }\n\n\n\n fn program_change(&mut self, next: AstPtr) -> Result<Value> {\n\n let (chn, next) = self.expect_u7(next)?;\n\n let (prg, next) = self.expect_u7(next)?;\n", "file_path": "lib/src/interpreter.rs", "rank": 98, "score": 15214.867423759895 }, { "content": " self.values.insert((env, id), val).is_none()\n\n }\n\n\n\n pub fn pop(&mut self, env: EnvId) {\n\n if !self.capture && env != self.current {\n\n while let Some((key, _)) = self.values.last() {\n\n if key.0 == env {\n\n self.values.pop().unwrap();\n\n } else {\n\n break;\n\n }\n\n }\n\n\n\n self.parents.remove(&env);\n\n }\n\n }\n\n\n\n pub fn get(&mut self, id: StrId) -> Option<Value> {\n\n let mut env = self.current;\n\n\n", "file_path": "lib/src/env.rs", "rank": 99, "score": 15214.590823283943 } ]
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(|()| NatError::AsymmetricDecipherFailed)\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 145537.84113431777 }, { "content": "/// Utility function to encrypt messages to peer\n\npub fn msg_to_send(plain_text: &[u8], key: &box_::PrecomputedKey) -> ::Res<Vec<u8>> {\n\n let nonce = box_::gen_nonce();\n\n let handshake = CryptMsg {\n\n nonce: nonce.0,\n\n cipher_text: box_::seal_precomputed(plain_text, &nonce, key),\n\n };\n\n\n\n Ok(serialize(&handshake, Infinite)?)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 1, "score": 142917.53196956968 }, { "content": "fn start_chatting(el: &El, token: Token, rx: mpsc::Receiver<()>) {\n\n println!(\"Waiting for a UDT connection...\");\n\n unwrap!(rx.recv());\n\n println!(\"Begin chatting with peer (type \\\"quit\\\" to quit)\");\n\n\n\n loop {\n\n let mut input = String::new();\n\n let _ = unwrap!(io::stdin().read_line(&mut input));\n\n input = input.trim().to_owned();\n\n\n\n if input == \"quit\" {\n\n break;\n\n }\n\n\n\n unwrap!(el.core_tx.send(CoreMsg::new(move |core, poll| {\n\n let chat_engine = unwrap!(core.peer_state(token));\n\n chat_engine.borrow_mut().write(core, poll, input);\n\n })));\n\n }\n\n}\n\n\n", "file_path": "examples/peer.rs", "rank": 2, "score": 138911.12820233323 }, { "content": "pub fn spawn_event_loop() -> El {\n\n let (core_tx, core_rx) = channel::channel::<CoreMsg>();\n\n let (nat_tx, nat_rx) = channel::channel();\n\n let nat_tx_cloned = nat_tx.clone();\n\n let core_tx_cloned = core_tx.clone();\n\n\n\n let joiner = thread::spawn(move || {\n\n const TIMER_TOKEN: usize = 0;\n\n const CORE_RX_TOKEN: usize = TIMER_TOKEN + 1;\n\n const NAT_RX_TOKEN: usize = CORE_RX_TOKEN + 1;\n\n\n\n let poll = unwrap!(Poll::new());\n\n\n\n let mut file = unwrap!(File::open(\"./sample-config\"));\n\n let mut content = String::new();\n\n unwrap!(file.read_to_string(&mut content));\n\n let config = unwrap!(serde_json::from_str(&content));\n\n\n\n let (enc_pk, enc_sk) = box_::gen_keypair();\n\n let timer = Timer::default();\n", "file_path": "examples/event_loop/mod.rs", "rank": 3, "score": 137008.1356728218 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct TcpEchoResp(pub Vec<u8>);\n\n\n", "file_path": "src/tcp/mod.rs", "rank": 5, "score": 117471.21227663915 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct TcpEchoReq(pub [u8; PUBLICKEYBYTES]);\n", "file_path": "src/tcp/mod.rs", "rank": 6, "score": 117471.21227663915 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct UdpEchoResp(pub Vec<u8>);\n", "file_path": "src/udp/mod.rs", "rank": 7, "score": 117471.21227663915 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct UdpEchoReq(pub [u8; PUBLICKEYBYTES]);\n", "file_path": "src/udp/mod.rs", "rank": 8, "score": 117471.21227663915 }, { "content": "pub fn spawn_event_loop(config_path: String) -> El {\n\n let (core_tx, core_rx) = channel::channel::<CoreMsg>();\n\n let (nat_tx, nat_rx) = channel::channel();\n\n let nat_tx_cloned = nat_tx.clone();\n\n let core_tx_cloned = core_tx.clone();\n\n\n\n let j = thread::named(\"Event-Loop\", move || {\n\n const TIMER_TOKEN: usize = 0;\n\n const CORE_RX_TOKEN: usize = TIMER_TOKEN + 1;\n\n const NAT_RX_TOKEN: usize = CORE_RX_TOKEN + 1;\n\n\n\n let poll = unwrap!(Poll::new());\n\n\n\n let mut file = unwrap!(File::open(&config_path));\n\n let mut content = String::new();\n\n unwrap!(file.read_to_string(&mut content));\n\n let config = unwrap!(serde_json::from_str(&content));\n\n\n\n let (enc_pk, enc_sk) = box_::gen_keypair();\n\n let timer = Timer::default();\n", "file_path": "tests/nat_traversal.rs", "rank": 9, "score": 116642.49194430077 }, { "content": "enum State {\n\n None,\n\n Rendezvous {\n\n info: RendezvousInfo,\n\n nat_info: NatInfo,\n\n timeout: Timeout,\n\n f: GetInfo,\n\n },\n\n ReadyToHolePunch,\n\n HolePunching {\n\n info: HolePunchInfo,\n\n timeout: Timeout,\n\n f: HolePunchFinsih,\n\n },\n\n}\n\n\n\nimpl Debug for State {\n\n fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n\n match *self {\n\n State::None => write!(f, \"State::None\"),\n", "file_path": "src/hole_punch.rs", "rank": 10, "score": 100912.74207636612 }, { "content": "pub trait CoreState {\n\n fn ready(&mut self, &mut Core, &Poll, Ready);\n\n fn terminate(&mut self, &mut Core, &Poll);\n\n fn write(&mut self, &mut Core, &Poll, String);\n\n}\n\n\n\npub struct CoreMsg(Option<Box<FnMut(&mut Core, &Poll) + Send + 'static>>);\n\nimpl CoreMsg {\n\n #[allow(unused)]\n\n pub fn new<F: FnOnce(&mut Core, &Poll) + Send + 'static>(f: F) -> Self {\n\n let mut f = Some(f);\n\n CoreMsg(Some(Box::new(move |core: &mut Core, poll: &Poll| {\n\n if let Some(f) = f.take() {\n\n f(core, poll);\n\n }\n\n })))\n\n }\n\n}\n\n\n\npub struct Notify(Sender<CoreMsg>);\n", "file_path": "examples/event_loop/mod.rs", "rank": 11, "score": 96763.24651669944 }, { "content": "enum State {\n\n None,\n\n Rendezvous {\n\n children: HashSet<Token>,\n\n info: (SocketAddr, Vec<SocketAddr>),\n\n f: RendezvousFinsih,\n\n },\n\n ReadyToHolePunch(SocketAddr),\n\n HolePunching {\n\n children: HashSet<Token>,\n\n f: HolePunchFinsih,\n\n },\n\n}\n\nimpl Debug for State {\n\n fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n\n match *self {\n\n State::None => write!(f, \"State::None\"),\n\n State::Rendezvous { .. } => write!(f, \"State::Rendezvous\"),\n\n State::ReadyToHolePunch(..) => write!(f, \"State::ReadyToHolePunch\"),\n\n State::HolePunching { .. } => write!(f, \"State::HolePunching\"),\n", "file_path": "src/tcp/hole_punch/mod.rs", "rank": 12, "score": 95799.25702160112 }, { "content": "enum State {\n\n None,\n\n Rendezvous {\n\n children: HashSet<Token>,\n\n info: (Vec<(UdpSock, Token)>, Vec<SocketAddr>),\n\n nat_type: NatType,\n\n f: RendezvousFinsih,\n\n },\n\n ReadyToHolePunch(Vec<(UdpSock, Token)>),\n\n HolePunching {\n\n children: HashSet<Token>,\n\n f: HolePunchFinsih,\n\n },\n\n}\n\nimpl Debug for State {\n\n fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n\n match *self {\n\n State::None => write!(f, \"State::None\"),\n\n State::Rendezvous { .. } => write!(f, \"State::Rendezvous\"),\n\n State::ReadyToHolePunch(..) => write!(f, \"State::ReadyToHolePunch\"),\n", "file_path": "src/udp/hole_punch/mod.rs", "rank": 13, "score": 95799.25702160112 }, { "content": "fn start_rendezvous_servers() -> Vec<El> {\n\n const NUM_RENDEZVOUS_SERVERS: usize = 3;\n\n\n\n let mut els = Vec::new();\n\n\n\n for i in 0..NUM_RENDEZVOUS_SERVERS {\n\n let el = spawn_event_loop(format!(\n\n \"./tests/nat-traversal-test-resources/config-rendezvous-server-{}\",\n\n i,\n\n ));\n\n\n\n let (tx, rx) = mpsc::channel();\n\n unwrap!(el.nat_tx.send(NatMsg::new(move |ifc, poll| {\n\n let udp_server_token = unwrap!(UdpRendezvousServer::start(ifc, poll));\n\n let tcp_server_token = unwrap!(TcpRendezvousServer::start(ifc, poll));\n\n unwrap!(tx.send((udp_server_token, tcp_server_token)));\n\n })));\n\n\n\n let (_udp_server_token, _tcp_server_token) = unwrap!(rx.recv());\n\n\n\n els.push(el);\n\n }\n\n\n\n els\n\n}\n\n\n", "file_path": "tests/nat_traversal.rs", "rank": 14, "score": 91513.32142442721 }, { "content": "pub fn new_reusably_bound_tcp_sockets(\n\n local_addr: &SocketAddr,\n\n n: usize,\n\n) -> ::Res<(Vec<TcpBuilder>, SocketAddr)> {\n\n if n < 1 {\n\n return Ok((vec![], *local_addr));\n\n }\n\n\n\n let mut v = Vec::with_capacity(n);\n\n\n\n let sock = match local_addr.ip() {\n\n IpAddr::V4(..) => TcpBuilder::new_v4()?,\n\n IpAddr::V6(..) => TcpBuilder::new_v6()?,\n\n };\n\n let _ = sock.reuse_address(true)?;\n\n enable_so_reuseport(&sock)?;\n\n let _ = sock.bind(local_addr)?;\n\n\n\n let addr = sock.local_addr()?;\n\n\n", "file_path": "src/tcp/mod.rs", "rank": 15, "score": 80369.0533057522 }, { "content": "#[cfg(target_family = \"unix\")]\n\nfn enable_so_reuseport(sock: &TcpBuilder) -> ::Res<()> {\n\n use net2::unix::UnixTcpBuilderExt;\n\n let _ = sock.reuse_port(true)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/tcp/mod.rs", "rank": 16, "score": 77787.81975587076 }, { "content": "/// The main trait that our users should implement.\n\n///\n\n/// We enlist our _expectations_ from the user code using this trait. This trait object is passed\n\n/// ubiquitously in this crate and also passed back to the user via various callbacks we take to\n\n/// communicate results back to them.\n\npub trait Interface {\n\n /// We call this when we want our state to be held before we go back to the event loop. The\n\n /// callee is expected to store this some place (e.g. `HashMap<Token, Rc<RefCell<NatState>>>`)\n\n /// to be retrieved when `mio` poll indicates some event associated with the `token` has\n\n /// occurred. In that case call `NatState::ready`.\n\n fn insert_state(\n\n &mut self,\n\n token: Token,\n\n state: Rc<RefCell<NatState>>,\n\n ) -> Result<(), (Rc<RefCell<NatState>>, String)>;\n\n /// Remove the state that was previously stored against the `token` and return it if\n\n /// successfully retrieved.\n\n fn remove_state(&mut self, token: Token) -> Option<Rc<RefCell<NatState>>>;\n\n /// Return the state (without removing - just a query) associated with the `token`\n\n fn state(&mut self, token: Token) -> Option<Rc<RefCell<NatState>>>;\n\n /// Set timeout. User code is expected to have a `mio::timer::Timer<NatTimer>` on which the\n\n /// timeout can be set.\n\n fn set_timeout(\n\n &mut self,\n\n duration: Duration,\n", "file_path": "src/lib.rs", "rank": 17, "score": 77273.02516981645 }, { "content": "#[derive(Debug, Eq, PartialEq)]\n\nenum Sending {\n\n Syn,\n\n SynAck,\n\n Ack,\n\n AckAck,\n\n}\n\n\n\npub struct Puncher {\n\n token: Token,\n\n sock: UdpSock,\n\n peer: SocketAddr,\n\n peer_enc_pk: box_::PublicKey,\n\n key: box_::PrecomputedKey,\n\n connection_chooser: bool,\n\n os_ttl: u32,\n\n starting_ttl: u32,\n\n current_ttl: u32,\n\n ttl_on_being_reached: u32,\n\n ttl_inc_interval_ms: u64,\n\n timeout: Timeout,\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 18, "score": 75308.85969867601 }, { "content": "/// The main trait that we implement.\n\n///\n\n/// All our registered states essentially implement this trait so that the user code can call us\n\n/// and indicate what event was fired for us in poll.\n\npub trait NatState {\n\n /// To be called when readiness event has fired\n\n fn ready(&mut self, &mut Interface, &Poll, Ready) {}\n\n /// To be called when user wants to actively terminate this state. It will do all the necessary\n\n /// clean ups and resource (file/socket descriptors) cleaning freeing so merely calling this is\n\n /// sufficient.\n\n fn terminate(&mut self, &mut Interface, &Poll) {}\n\n /// To be called when timeout has been fired and the user has retrieved the state using the\n\n /// token stored inside the `NatTimer::associated_nat_state`.\n\n fn timeout(&mut self, &mut Interface, &Poll, u8) {}\n\n /// This is for internal use for the crate and is rarely needed.\n\n fn as_any(&mut self) -> &mut Any;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 19, "score": 74515.68108388795 }, { "content": "fn get_rendezvous_info(el: &El) -> Res<(Handle, RendezvousInfo)> {\n\n let (tx, rx) = mpsc::channel();\n\n unwrap!(el.nat_tx.send(NatMsg::new(move |ifc, poll| {\n\n let get_info = move |_: &mut Interface, _: &Poll, _nat_info, res| {\n\n unwrap!(tx.send(res));\n\n };\n\n unwrap!(HolePunchMediator::start(ifc, poll, Box::new(get_info)));\n\n })));\n\n\n\n unwrap!(rx.recv())\n\n}\n\n\n", "file_path": "examples/peer.rs", "rank": 20, "score": 66601.9877790435 }, { "content": "#[cfg(target_family = \"windows\")]\n\nfn enable_so_reuseport(_sock: &TcpBuilder) -> ::Res<()> {\n\n Ok(())\n\n}\n", "file_path": "src/tcp/mod.rs", "rank": 21, "score": 62429.981002188506 }, { "content": "fn get_rendezvous_info(el: &El) -> mpsc::Receiver<(NatInfo, Res<(Handle, RendezvousInfo)>)> {\n\n let (tx, rx) = mpsc::channel();\n\n unwrap!(el.nat_tx.send(NatMsg::new(move |ifc, poll| {\n\n let handler = move |_: &mut Interface, _: &Poll, nat_info, res| {\n\n unwrap!(tx.send((nat_info, res)));\n\n };\n\n unwrap!(HolePunchMediator::start(ifc, poll, Box::new(handler)));\n\n })));\n\n\n\n rx\n\n}\n\n\n", "file_path": "tests/nat_traversal.rs", "rank": 22, "score": 57825.40476806148 }, { "content": "struct ChatEngine {\n\n token: Token,\n\n write_queue: VecDeque<Vec<u8>>,\n\n read_buf: [u8; 1024],\n\n // sock: UdtSock,\n\n sock: UdpSock,\n\n peer: SocketAddr,\n\n key: box_::PrecomputedKey,\n\n waiting_for_connect: bool,\n\n tx: mpsc::Sender<()>,\n\n}\n\n\n\nimpl ChatEngine {\n\n fn start(\n\n core: &mut Core,\n\n poll: &Poll,\n\n token: Token,\n\n mut sock: UdpSock,\n\n peer: SocketAddr,\n\n peer_enc_pk: &box_::PublicKey,\n", "file_path": "examples/peer.rs", "rank": 23, "score": 50219.59895930839 }, { "content": "fn main() {\n\n unwrap!(maidsafe_utilities::log::init(true));\n\n let el = spawn_event_loop();\n\n unwrap!(el.nat_tx.send(NatMsg::new(move |ifc, poll| {\n\n let _token_udp = unwrap!(UdpRendezvousServer::start(ifc, poll));\n\n let _token_tcp = unwrap!(TcpRendezvousServer::start(ifc, poll));\n\n })));\n\n\n\n let (_tx, rx) = mpsc::channel();\n\n println!(\"Server started. Blocking main thread indefinitely\");\n\n unwrap!(rx.recv())\n\n}\n", "file_path": "examples/server.rs", "rank": 24, "score": 48346.56062538964 }, { "content": "fn main() {\n\n unwrap!(maidsafe_utilities::log::init(true));\n\n\n\n let el = spawn_event_loop();\n\n let (handle, rendezvous_info) = match get_rendezvous_info(&el) {\n\n Ok((h, r)) => (h, r),\n\n Err(e) => {\n\n println!(\"Could not obtain rendezvous info: {:?}\", e);\n\n println!(\n\n \"[Check if the rendezvous server addresses are correct and publicly \\\n\n reachable and that they are running].\"\n\n );\n\n return;\n\n }\n\n };\n\n\n\n let our_info = unwrap!(serde_json::to_string(&rendezvous_info));\n\n\n\n #[cfg(target_family = \"unix\")]\n\n copy_to_clipboard(&our_info);\n", "file_path": "examples/peer.rs", "rank": 25, "score": 48346.56062538964 }, { "content": "#[test]\n\nfn nat_traverse_among_3_peers() {\n\n unwrap!(maidsafe_utilities::log::init(true));\n\n\n\n let _els_rendezvous_servers = start_rendezvous_servers();\n\n\n\n let peer_config_path = \"./tests/nat-traversal-test-resources/config-peers\".to_string();\n\n let el_peer0 = spawn_event_loop(peer_config_path.clone());\n\n let el_peer1 = spawn_event_loop(peer_config_path.clone());\n\n let el_peer2 = spawn_event_loop(peer_config_path);\n\n\n\n // Get `RendezvousInfo` in parallel\n\n let rendezvous_rx01 = get_rendezvous_info(&el_peer0);\n\n let rendezvous_rx02 = get_rendezvous_info(&el_peer0);\n\n let rendezvous_rx10 = get_rendezvous_info(&el_peer1);\n\n let rendezvous_rx12 = get_rendezvous_info(&el_peer1);\n\n let rendezvous_rx20 = get_rendezvous_info(&el_peer2);\n\n let rendezvous_rx21 = get_rendezvous_info(&el_peer2);\n\n\n\n let (nat_info01, (handle01, rendezvous_info01)) = {\n\n let (nat_info, res) = unwrap!(rendezvous_rx01.recv());\n", "file_path": "tests/nat_traversal.rs", "rank": 26, "score": 43243.47008738181 }, { "content": "#[cfg(target_family = \"unix\")]\n\nfn copy_to_clipboard(our_info: &str) {\n\n let xclip = format!(\"xclip -i -selection clipboard <<< '{}'\", our_info);\n\n if let Ok(mut cmd) = Command::new(\"sh\").arg(\"-c\").arg(xclip).spawn() {\n\n let _ = cmd.wait();\n\n }\n\n}\n\n\n", "file_path": "examples/peer.rs", "rank": 27, "score": 41450.75074733331 }, { "content": " }\n\n }\n\n\n\n fn handle_readiness(&mut self, poll: &Poll, token: Token, kind: Ready) {\n\n if let Some(nat_state) = self.state(token) {\n\n return nat_state.borrow_mut().ready(self, poll, kind);\n\n }\n\n if let Some(peer_state) = self.peer_states.get(&token).cloned() {\n\n return peer_state.borrow_mut().ready(self, poll, kind);\n\n }\n\n }\n\n}\n\n\n\nimpl Interface for Core {\n\n fn insert_state(\n\n &mut self,\n\n token: Token,\n\n state: Rc<RefCell<NatState>>,\n\n ) -> Result<(), (Rc<RefCell<NatState>>, String)> {\n\n if let Entry::Vacant(ve) = self.nat_states.entry(token) {\n", "file_path": "examples/event_loop/mod.rs", "rank": 28, "score": 30621.341976200627 }, { "content": "use mio::channel::{self, Sender};\n\nuse mio::timer::{Timeout, Timer, TimerError};\n\nuse mio::{Event, Events, Poll, PollOpt, Ready, Token};\n\nuse p2p::{Config, Interface, NatMsg, NatState, NatTimer};\n\nuse serde_json;\n\n// use socket_collection::{EpollLoop, Handle, Notifier};\n\nuse sodium::crypto::box_;\n\nuse std::cell::RefCell;\n\nuse std::collections::hash_map::Entry;\n\nuse std::collections::HashMap;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::rc::Rc;\n\nuse std::thread::{self, JoinHandle};\n\nuse std::time::Duration;\n\n\n\npub struct Core {\n\n nat_states: HashMap<Token, Rc<RefCell<NatState>>>,\n\n peer_states: HashMap<Token, Rc<RefCell<CoreState>>>,\n\n timer: Timer<NatTimer>,\n", "file_path": "examples/event_loop/mod.rs", "rank": 29, "score": 30619.12472630143 }, { "content": "// impl Notifier for Notify {\n\n// fn notify(&self, event: Event) {\n\n// unwrap!(self.0.send(CoreMsg::new(move |core, poll| {\n\n// core.handle_readiness(poll, event.token(), event.kind());\n\n// })));\n\n// }\n\n// }\n\n\n\npub struct El {\n\n pub nat_tx: Sender<NatMsg>,\n\n pub core_tx: Sender<CoreMsg>,\n\n joiner: Option<JoinHandle<()>>,\n\n}\n\n\n\nimpl Drop for El {\n\n fn drop(&mut self) {\n\n let _ = self.core_tx.send(CoreMsg(None));\n\n let joiner = unwrap!(self.joiner.take());\n\n unwrap!(joiner.join());\n\n println!(\"Gracefully shut down mio event loop\");\n\n }\n\n}\n\n\n", "file_path": "examples/event_loop/mod.rs", "rank": 30, "score": 30618.93722336347 }, { "content": " ve.insert(state);\n\n Ok(())\n\n } else {\n\n Err((state, \"Token is already mapped\".to_string()))\n\n }\n\n }\n\n\n\n fn remove_state(&mut self, token: Token) -> Option<Rc<RefCell<NatState>>> {\n\n self.nat_states.remove(&token)\n\n }\n\n\n\n fn state(&mut self, token: Token) -> Option<Rc<RefCell<NatState>>> {\n\n self.nat_states.get(&token).cloned()\n\n }\n\n\n\n fn set_timeout(\n\n &mut self,\n\n duration: Duration,\n\n timer_detail: NatTimer,\n\n ) -> Result<Timeout, TimerError> {\n", "file_path": "examples/event_loop/mod.rs", "rank": 31, "score": 30618.69517837508 }, { "content": " token: usize,\n\n config: Config,\n\n enc_pk: box_::PublicKey,\n\n enc_sk: box_::SecretKey,\n\n tx: Sender<NatMsg>,\n\n // udt_epoll_handle: Handle,\n\n}\n\n\n\nimpl Core {\n\n #[allow(unused)]\n\n pub fn insert_peer_state(\n\n &mut self,\n\n token: Token,\n\n state: Rc<RefCell<CoreState>>,\n\n ) -> Result<(), (Rc<RefCell<CoreState>>, String)> {\n\n if let Entry::Vacant(ve) = self.peer_states.entry(token) {\n\n ve.insert(state);\n\n Ok(())\n\n } else {\n\n Err((state, \"Token is already mapped\".to_string()))\n", "file_path": "examples/event_loop/mod.rs", "rank": 32, "score": 30618.58153402975 }, { "content": " // let notifier = Notify(core_tx);\n\n // let epoll_loop = unwrap!(EpollLoop::start_event_loop(notifier));\n\n // let udt_epoll_handle = epoll_loop.handle();\n\n\n\n let mut core = Core {\n\n nat_states: HashMap::with_capacity(10),\n\n peer_states: HashMap::with_capacity(5),\n\n timer: timer,\n\n token: NAT_RX_TOKEN + 1,\n\n config: config,\n\n enc_pk: enc_pk,\n\n enc_sk: enc_sk,\n\n tx: nat_tx,\n\n // udt_epoll_handle,\n\n };\n\n\n\n let mut events = Events::with_capacity(1024);\n\n\n\n 'event_loop: loop {\n\n unwrap!(poll.poll(&mut events, None));\n", "file_path": "examples/event_loop/mod.rs", "rank": 33, "score": 30615.651217353778 }, { "content": " }\n\n }\n\n\n\n // pub fn udt_epoll_handle(&self) -> Handle {\n\n // unreachable!(\"For later\");\n\n // //self.udt_epoll_handle.clone()\n\n // }\n\n\n\n #[allow(unused)]\n\n pub fn peer_state(&mut self, token: Token) -> Option<Rc<RefCell<CoreState>>> {\n\n self.peer_states.get(&token).cloned()\n\n }\n\n\n\n fn handle_nat_timer(&mut self, poll: &Poll) {\n\n while let Some(nat_timer) = self.timer.poll() {\n\n if let Some(nat_state) = self.state(nat_timer.associated_nat_state) {\n\n nat_state\n\n .borrow_mut()\n\n .timeout(self, poll, nat_timer.timer_id);\n\n }\n", "file_path": "examples/event_loop/mod.rs", "rank": 34, "score": 30615.04553682701 }, { "content": "\n\n for event in events.iter() {\n\n match event.token() {\n\n Token(t) if t == TIMER_TOKEN => {\n\n assert!(event.kind().is_readable());\n\n core.handle_nat_timer(&poll);\n\n }\n\n Token(t) if t == CORE_RX_TOKEN => {\n\n assert!(event.kind().is_readable());\n\n while let Ok(f) = core_rx.try_recv() {\n\n if let Some(mut f) = f.0 {\n\n f(&mut core, &poll);\n\n } else {\n\n break 'event_loop;\n\n }\n\n }\n\n }\n\n Token(t) if t == NAT_RX_TOKEN => {\n\n assert!(event.kind().is_readable());\n\n while let Ok(f) = nat_rx.try_recv() {\n", "file_path": "examples/event_loop/mod.rs", "rank": 35, "score": 30613.661775828765 }, { "content": " self.timer.set_timeout(duration, timer_detail)\n\n }\n\n\n\n fn cancel_timeout(&mut self, timeout: &Timeout) -> Option<NatTimer> {\n\n self.timer.cancel_timeout(timeout)\n\n }\n\n\n\n fn new_token(&mut self) -> Token {\n\n self.token += 1;\n\n Token(self.token)\n\n }\n\n\n\n fn config(&self) -> &Config {\n\n &self.config\n\n }\n\n\n\n fn enc_pk(&self) -> &box_::PublicKey {\n\n &self.enc_pk\n\n }\n\n\n\n fn enc_sk(&self) -> &box_::SecretKey {\n\n &self.enc_sk\n\n }\n\n\n\n fn sender(&self) -> &Sender<NatMsg> {\n\n &self.tx\n\n }\n\n}\n\n\n", "file_path": "examples/event_loop/mod.rs", "rank": 36, "score": 30612.845580623627 }, { "content": " f.invoke(&mut core, &poll);\n\n }\n\n }\n\n t => core.handle_readiness(&poll, t, event.kind()),\n\n }\n\n }\n\n }\n\n });\n\n\n\n El {\n\n nat_tx: nat_tx_cloned,\n\n core_tx: core_tx_cloned,\n\n joiner: Some(joiner),\n\n }\n\n}\n", "file_path": "examples/event_loop/mod.rs", "rank": 37, "score": 30607.61391224283 }, { "content": "\n\n unwrap!(poll.register(\n\n &timer,\n\n Token(TIMER_TOKEN),\n\n Ready::readable() | Ready::error() | Ready::hup(),\n\n PollOpt::edge(),\n\n ));\n\n unwrap!(poll.register(\n\n &core_rx,\n\n Token(CORE_RX_TOKEN),\n\n Ready::readable() | Ready::error() | Ready::hup(),\n\n PollOpt::edge(),\n\n ));\n\n unwrap!(poll.register(\n\n &nat_rx,\n\n Token(NAT_RX_TOKEN),\n\n Ready::readable() | Ready::error() | Ready::hup(),\n\n PollOpt::edge(),\n\n ));\n\n\n", "file_path": "examples/event_loop/mod.rs", "rank": 38, "score": 30607.484048239352 }, { "content": " sending: Sending,\n\n num_acks_transmitted: u8,\n\n commenced_at: Instant,\n\n f: Finish,\n\n}\n\n\n\nimpl Puncher {\n\n pub fn start(\n\n ifc: &mut Interface,\n\n poll: &Poll,\n\n token: Token,\n\n mut sock: UdpSock,\n\n starting_ttl: u8,\n\n ttl_inc_interval_ms: u64,\n\n peer: SocketAddr,\n\n peer_enc_pk: &box_::PublicKey,\n\n f: Finish,\n\n ) -> ::Res<()> {\n\n let os_ttl = sock.ttl()?;\n\n let starting_ttl = starting_ttl as u32;\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 40, "score": 28884.621921411708 }, { "content": "use mio::timer::Timeout;\n\nuse mio::{Poll, PollOpt, Ready, Token};\n\nuse socket_collection::UdpSock;\n\nuse sodium::crypto::box_;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::net::SocketAddr;\n\nuse std::rc::Rc;\n\nuse std::time::{Duration, Instant};\n\nuse std::{fmt, mem};\n\nuse {Interface, NatError, NatState, NatTimer};\n\n\n\n// Result of (UdpSock, peer, starting_ttl, ttl_on_being_reached, duration-of-hole-punch)\n\npub type Finish =\n\n Box<FnMut(&mut Interface, &Poll, Token, ::Res<(UdpSock, SocketAddr, u32, u32, Duration)>)>;\n\n\n\nconst TIMER_ID: u8 = 0;\n\nconst SYN: &[u8] = b\"SYN\";\n\nconst SYN_ACK: &[u8] = b\"SYN-ACK\";\n\nconst ACK: &[u8] = b\"ACK\";\n\nconst ACK_ACK: &[u8] = b\"ACK_ACK\"; // Fire and forget optimistic case to release ACK-sender\n\nconst MAX_ACK_RETRANSMISSIONS: u8 = 3;\n\n\n\n#[derive(Debug, Eq, PartialEq)]\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 43, "score": 28880.97314379546 }, { "content": " ttl_inc_interval_ms,\n\n timeout,\n\n sending: Sending::Syn,\n\n num_acks_transmitted: 0,\n\n commenced_at: Instant::now(),\n\n f,\n\n }));\n\n\n\n if let Err((nat_state, e)) = ifc.insert_state(token, puncher) {\n\n debug!(\"Error inserting state: {:?}\", e);\n\n nat_state.borrow_mut().terminate(ifc, poll);\n\n return Err(NatError::UdpHolePunchFailed);\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn read(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let mut cipher_text = Vec::new();\n\n loop {\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 46, "score": 28874.570398849475 }, { "content": " poll,\n\n self.token,\n\n Ok((\n\n s,\n\n self.peer,\n\n self.starting_ttl,\n\n self.ttl_on_being_reached,\n\n self.commenced_at.elapsed(),\n\n )),\n\n );\n\n }\n\n\n\n fn handle_err(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n self.terminate(ifc, poll);\n\n (*self.f)(ifc, poll, self.token, Err(NatError::UdpHolePunchFailed));\n\n }\n\n}\n\n\n\nimpl NatState for Puncher {\n\n fn ready(&mut self, ifc: &mut Interface, poll: &Poll, event: Ready) {\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 47, "score": 28874.39748887292 }, { "content": " sock.set_ttl(starting_ttl)?;\n\n sock.connect(&peer).map_err(|e| {\n\n debug!(\"Error: Failed to connect UDP Puncher: {:?}\", e);\n\n e\n\n })?;\n\n\n\n let timeout = match ifc.set_timeout(\n\n Duration::from_millis(ttl_inc_interval_ms),\n\n NatTimer::new(token, TIMER_ID),\n\n ) {\n\n Ok(timeout) => timeout,\n\n Err(e) => {\n\n debug!(\"Error: UdpPuncher errored in setting timeout: {:?}\", e);\n\n let _ = poll.deregister(&sock);\n\n return Err(From::from(e));\n\n }\n\n };\n\n\n\n if let Err(e) = poll.reregister(\n\n &sock,\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 49, "score": 28873.298673109097 }, { "content": " token,\n\n Ready::readable() | Ready::writable(),\n\n PollOpt::edge(),\n\n ) {\n\n debug!(\"Error: UdpPuncher errored in registeration: {:?}\", e);\n\n let _ = poll.deregister(&sock);\n\n return Err(From::from(e));\n\n }\n\n\n\n let puncher = Rc::new(RefCell::new(Puncher {\n\n token: token,\n\n sock,\n\n peer,\n\n peer_enc_pk: *peer_enc_pk,\n\n key: box_::precompute(peer_enc_pk, ifc.enc_sk()),\n\n connection_chooser: ifc.enc_pk() > peer_enc_pk,\n\n os_ttl,\n\n starting_ttl,\n\n current_ttl: starting_ttl,\n\n ttl_on_being_reached: 0,\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 51, "score": 28869.811432951876 }, { "content": " if event.is_readable() {\n\n self.read(ifc, poll)\n\n } else if event.is_writable() {\n\n self.write(ifc, poll, None)\n\n } else {\n\n warn!(\n\n \"{} Investigate: Ignoring unknown event kind: {:?}\",\n\n self, event\n\n );\n\n }\n\n }\n\n\n\n fn timeout(&mut self, ifc: &mut Interface, poll: &Poll, timer_id: u8) {\n\n if timer_id != TIMER_ID {\n\n warn!(\"{} Invalid Timer ID: {}\", self, timer_id);\n\n }\n\n\n\n self.timeout = match ifc.set_timeout(\n\n Duration::from_millis(self.ttl_inc_interval_ms),\n\n NatTimer::new(self.token, TIMER_ID),\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 54, "score": 28868.072180618994 }, { "content": " fn on_successful_send(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n match self.sending {\n\n Sending::Ack => if self.num_acks_transmitted == MAX_ACK_RETRANSMISSIONS {\n\n trace!(\"{} Sent all ACKs - we are done\", self);\n\n self.done(ifc, poll);\n\n },\n\n Sending::AckAck => {\n\n trace!(\"{} Sent ACK_ACK - we are done\", self);\n\n self.done(ifc, poll);\n\n }\n\n _ => (),\n\n }\n\n }\n\n\n\n fn done(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let _ = ifc.remove_state(self.token);\n\n let _ = ifc.cancel_timeout(&self.timeout);\n\n let s = mem::replace(&mut self.sock, Default::default());\n\n (*self.f)(\n\n ifc,\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 56, "score": 28866.47558671816 }, { "content": " debug!(\"{} Error setting ttl: {:?}\", self, e);\n\n return self.handle_err(ifc, poll);\n\n }\n\n }\n\n\n\n self.continue_handshake(ifc, poll)\n\n }\n\n\n\n fn terminate(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let _ = ifc.remove_state(self.token);\n\n let _ = ifc.cancel_timeout(&self.timeout);\n\n let _ = poll.deregister(&self.sock);\n\n\n\n trace!(\"{} terminated\", self);\n\n }\n\n\n\n fn as_any(&mut self) -> &mut Any {\n\n self\n\n }\n\n}\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 58, "score": 28865.713433913872 }, { "content": " // Since we have read something, revert back to OS default TTL\n\n if self.current_ttl != self.os_ttl {\n\n if let Err(e) = self.sock.set_ttl(self.os_ttl) {\n\n debug!(\"{} Error: Could not set OS Default TTL: {:?}\", self, e);\n\n return self.handle_err(ifc, poll);\n\n } else {\n\n self.ttl_on_being_reached = self.current_ttl;\n\n self.current_ttl = self.os_ttl;\n\n }\n\n }\n\n\n\n // Do a premature-handshake since we have received something. This will hasten things up.\n\n self.continue_handshake(ifc, poll);\n\n }\n\n\n\n fn write(&mut self, ifc: &mut Interface, poll: &Poll, m: Option<Vec<u8>>) {\n\n match self.sock.write(m.map(|m| (m, 0))) {\n\n Ok(true) => self.on_successful_send(ifc, poll),\n\n Ok(false) => (),\n\n Err(e) => trace!(\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 60, "score": 28864.123697318206 }, { "content": "\n\nimpl fmt::Display for Puncher {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let ttl_on_being_reached = if self.ttl_on_being_reached == 0 {\n\n \"N/A\".to_string()\n\n } else {\n\n format!(\"{}\", self.ttl_on_being_reached)\n\n };\n\n write!(\n\n f,\n\n \"UdpPuncher [peer=({:02x}{:02x}{:02x}../{}) ;; os_ttl={}, starting_ttl={}, current_ttl={}\n\n , ttl_on_being_reached={} ;; state={:?} ;; chooser={}]\",\n\n self.peer_enc_pk.0[0],\n\n self.peer_enc_pk.0[1],\n\n self.peer_enc_pk.0[2],\n\n self.peer,\n\n self.os_ttl,\n\n self.starting_ttl,\n\n self.current_ttl,\n\n ttl_on_being_reached,\n\n self.sending,\n\n self.connection_chooser\n\n )\n\n }\n\n}\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 61, "score": 28862.646908488074 }, { "content": " ACK\n\n }\n\n Sending::AckAck => {\n\n let _ = ifc.cancel_timeout(&self.timeout);\n\n ACK_ACK\n\n }\n\n };\n\n\n\n match ::msg_to_send(m, &self.key) {\n\n Ok(m) => m,\n\n Err(e) => {\n\n debug!(\"{} Error: while encrypting: {:?}\", self, e);\n\n return self.handle_err(ifc, poll);\n\n }\n\n }\n\n };\n\n\n\n self.write(ifc, poll, Some(msg));\n\n }\n\n\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 62, "score": 28859.362588898595 }, { "content": "\n\n let msg = match ::msg_to_read(&cipher_text, &self.key) {\n\n Ok(m) => m,\n\n Err(e) => {\n\n debug!(\"{} Errored while deciphering incoming data: {:?}\", self, e);\n\n return self.handle_err(ifc, poll);\n\n }\n\n };\n\n\n\n if msg == SYN {\n\n if let Sending::Syn = self.sending {\n\n self.sending = Sending::SynAck;\n\n }\n\n } else if msg == SYN_ACK {\n\n if self.connection_chooser {\n\n self.sending = Sending::Ack\n\n } else if let Sending::Syn = self.sending {\n\n self.sending = Sending::SynAck;\n\n }\n\n } else if msg == ACK {\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 63, "score": 28858.559155083665 }, { "content": " match self.sock.read() {\n\n Ok(Some(m)) => cipher_text = m,\n\n Ok(None) => if cipher_text.is_empty() {\n\n return;\n\n } else {\n\n break;\n\n },\n\n Err(e) => {\n\n trace!(\n\n \"{} Ignoring Error Read: {:?} - These are likely caused by ICMP errors for \\\n\n timeout/ttl-drops or unreachable-peer/port. Continue with ttl-runners.\",\n\n self, e);\n\n if cipher_text.is_empty() {\n\n return;\n\n } else {\n\n break;\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 64, "score": 28857.82202698957 }, { "content": " \"{} Ignoring Error in Write: {:?} - These are likely caused by ICMP errors for \\\n\n timeout/ttl-drops or unreachable-peer/port. Continue with ttl-runners.\",\n\n self,\n\n e\n\n ),\n\n }\n\n }\n\n\n\n fn continue_handshake(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let msg = {\n\n let m = match self.sending {\n\n Sending::Syn => SYN,\n\n Sending::SynAck => SYN_ACK,\n\n Sending::Ack => {\n\n if self.num_acks_transmitted < MAX_ACK_RETRANSMISSIONS {\n\n self.num_acks_transmitted += 1;\n\n }\n\n if self.num_acks_transmitted == MAX_ACK_RETRANSMISSIONS {\n\n let _ = ifc.cancel_timeout(&self.timeout);\n\n }\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 65, "score": 28857.205019051784 }, { "content": " if self.connection_chooser {\n\n info!(\n\n \"{} No tolerance for a non chooser giving us an ACK - terminating\",\n\n self\n\n );\n\n return self.handle_err(ifc, poll);\n\n }\n\n self.sending = Sending::AckAck;\n\n } else if msg == ACK_ACK {\n\n if !self.connection_chooser {\n\n info!(\n\n \"{} No tolerance for a chooser giving us an ACK_ACK - terminating\",\n\n self\n\n );\n\n return self.handle_err(ifc, poll);\n\n }\n\n trace!(\"{} Rxd ACK_ACK - we are done\", self);\n\n return self.done(ifc, poll);\n\n }\n\n\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 66, "score": 28854.278772601367 }, { "content": " ) {\n\n Ok(t) => t,\n\n Err(e) => {\n\n debug!(\"{} Error in setting timeout: {:?}\", self, e);\n\n return self.handle_err(ifc, poll);\n\n }\n\n };\n\n\n\n // If we have got an incoming message we would have had set current to the os value so\n\n // keep it at that, else do the usual incrementing.\n\n if self.current_ttl < self.os_ttl {\n\n self.current_ttl += 1;\n\n if self.current_ttl == self.os_ttl {\n\n debug!(\n\n \"{} OS TTL reached and still peer did not reach us - giving up\",\n\n self\n\n );\n\n return self.handle_err(ifc, poll);\n\n }\n\n if let Err(e) = self.sock.set_ttl(self.current_ttl) {\n", "file_path": "src/udp/hole_punch/puncher.rs", "rank": 68, "score": 28853.380809785023 }, { "content": "use super::puncher::{Finish, Puncher, Via};\n\nuse mio::tcp::TcpListener;\n\nuse mio::{Poll, PollOpt, Ready, Token};\n\nuse socket_collection::TcpSock;\n\nuse sodium::crypto::box_;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\nuse std::time::Instant;\n\nuse {Interface, NatError, NatState};\n\n\n\npub struct Listener {\n\n token: Token,\n\n listener: TcpListener,\n\n peer_enc_key: box_::PublicKey,\n\n commenced_at: Instant,\n\n f: Option<Finish>,\n\n}\n\n\n\nimpl Listener {\n", "file_path": "src/tcp/hole_punch/listener.rs", "rank": 69, "score": 39.18214749278001 }, { "content": " token,\n\n sock,\n\n peer,\n\n timeout,\n\n }));\n\n\n\n if ifc.insert_state(token, exchg_msg.clone()).is_err() {\n\n debug!(\"Unable to start TCP rendezvous exchanger!\");\n\n exchg_msg.borrow_mut().terminate(ifc, poll);\n\n Err(NatError::TcpRendezvousExchangerStartFailed)\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n\n\n fn read(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let mut pk = None;\n\n loop {\n\n match self.sock.read() {\n\n Ok(Some(TcpEchoReq(raw))) => pk = Some(box_::PublicKey(raw)),\n", "file_path": "src/tcp/rendezvous_server/exchange_msg.rs", "rank": 70, "score": 39.08748824418074 }, { "content": " };\n\n let sock = TcpSock::wrap(s);\n\n let via = Via::Accept(sock, self.token, self.commenced_at);\n\n if let Err(e) = Puncher::start(ifc, poll, via, &self.peer_enc_key, f) {\n\n debug!(\"Error accepting direct puncher connection: {:?}\", e);\n\n }\n\n }\n\n Err(e) => debug!(\"Failed to accept new socket: {:?}\", e),\n\n }\n\n }\n\n\n\n fn handle_err(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n self.terminate(ifc, poll);\n\n if let Some(ref mut f) = self.f {\n\n f(ifc, poll, self.token, Err(NatError::TcpHolePunchFailed));\n\n }\n\n }\n\n}\n\n\n\nimpl NatState for Listener {\n", "file_path": "src/tcp/hole_punch/listener.rs", "rank": 71, "score": 35.70128398452976 }, { "content": " peer: peer,\n\n key: box_::precompute(peer_enc_pk, core.enc_sk()),\n\n waiting_for_connect: true,\n\n tx,\n\n }));\n\n\n\n if let Err(e) = core.insert_peer_state(token, engine) {\n\n panic!(\"{}\", e.1);\n\n }\n\n token\n\n }\n\n\n\n fn read(&mut self, core: &mut Core, poll: &Poll) {\n\n loop {\n\n match self.sock.read::<Vec<u8>>() {\n\n Ok(Some(cipher_text)) => {\n\n let msg = unwrap!(String::from_utf8(unwrap!(p2p::msg_to_read(\n\n &cipher_text,\n\n &self.key\n\n ))));\n", "file_path": "examples/peer.rs", "rank": 72, "score": 35.11257907953176 }, { "content": "impl TcpRendezvousClient {\n\n pub fn start(ifc: &mut Interface, poll: &Poll, sock: TcpSock, f: Finish) -> ::Res<Token> {\n\n let token = ifc.new_token();\n\n\n\n poll.register(\n\n &sock,\n\n token,\n\n Ready::readable() | Ready::writable(),\n\n PollOpt::edge(),\n\n )?;\n\n\n\n let client = Rc::new(RefCell::new(TcpRendezvousClient {\n\n token,\n\n sock,\n\n req: Some(TcpEchoReq(ifc.enc_pk().0)),\n\n f,\n\n }));\n\n\n\n if ifc.insert_state(token, client.clone()).is_err() {\n\n debug!(\"Unable to insert TcpRendezvousClient State!\");\n", "file_path": "src/tcp/hole_punch/rendezvous_client.rs", "rank": 73, "score": 34.78829030257174 }, { "content": " commenced_at: Instant::now(),\n\n f: Some(f),\n\n }));\n\n\n\n if ifc.insert_state(token, listener.clone()).is_err() {\n\n warn!(\"Unable to start Listener!\");\n\n listener.borrow_mut().terminate(ifc, poll);\n\n Err(NatError::TcpHolePunchFailed)\n\n } else {\n\n Ok(token)\n\n }\n\n }\n\n\n\n fn accept(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n match self.listener.accept() {\n\n Ok((s, _)) => {\n\n self.terminate(ifc, poll);\n\n let f = match self.f.take() {\n\n Some(f) => f,\n\n None => return,\n", "file_path": "src/tcp/hole_punch/listener.rs", "rank": 74, "score": 33.34371897381885 }, { "content": "use mio::{Poll, PollOpt, Ready, Token};\n\nuse rand::{self, Rng};\n\nuse socket_collection::UdpSock;\n\nuse sodium::crypto::sealedbox;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::mem;\n\nuse std::net::SocketAddr;\n\nuse std::rc::Rc;\n\nuse std::str::{self, FromStr};\n\nuse udp::{UdpEchoReq, UdpEchoResp};\n\nuse {Interface, NatError, NatState, NatType};\n\n\n\npub type Finish = Box<FnMut(&mut Interface, &Poll, Token, NatType, ::Res<(UdpSock, SocketAddr)>)>;\n\n\n\npub struct UdpRendezvousClient {\n\n sock: UdpSock,\n\n token: Token,\n\n servers: Vec<SocketAddr>,\n\n on_first_write_triggered: Option<SocketAddr>,\n", "file_path": "src/udp/hole_punch/rendezvous_client.rs", "rank": 75, "score": 32.917366043384376 }, { "content": " timeout: Timeout,\n\n}\n\n\n\nimpl ExchangeMsg {\n\n pub fn start(ifc: &mut Interface, poll: &Poll, peer: SocketAddr, sock: TcpSock) -> ::Res<()> {\n\n let token = ifc.new_token();\n\n\n\n let timeout = ifc.set_timeout(\n\n Duration::from_secs(RENDEZVOUS_EXCHG_TIMEOUT_SEC),\n\n NatTimer::new(token, TIMER_ID),\n\n )?;\n\n\n\n poll.register(\n\n &sock,\n\n token,\n\n Ready::readable() | Ready::writable(),\n\n PollOpt::edge(),\n\n )?;\n\n\n\n let exchg_msg = Rc::new(RefCell::new(ExchangeMsg {\n", "file_path": "src/tcp/rendezvous_server/exchange_msg.rs", "rank": 76, "score": 32.63872537883276 }, { "content": "/// A message that can be sent to the event loop to perform an action.\n\n///\n\n/// This can be used to send actions from a thread outside the event loop too if sent via\n\n/// [`mio::channel::Sender`][0].\n\n///\n\n/// [0]: http://rust-doc.s3-website-us-east-1.amazonaws.com/mio/master/mio/channel\n\npub struct NatMsg(Box<FnMut(&mut Interface, &Poll) + Send + 'static>);\n\nimpl NatMsg {\n\n /// Construct a new message indicating the action via a function/functor.\n\n pub fn new<F>(f: F) -> Self\n\n where\n\n F: FnOnce(&mut Interface, &Poll) + Send + 'static,\n\n {\n\n let mut f = Some(f);\n\n NatMsg(Box::new(move |ifc: &mut Interface, poll: &Poll| {\n\n if let Some(f) = f.take() {\n\n f(ifc, poll)\n\n }\n\n }))\n\n }\n", "file_path": "src/lib.rs", "rank": 77, "score": 32.62153031798711 }, { "content": "use self::listener::Listener;\n\nuse self::puncher::{Puncher, Via};\n\nuse self::rendezvous_client::TcpRendezvousClient;\n\nuse mio::tcp::{TcpListener, TcpStream};\n\nuse mio::Poll;\n\nuse mio::Token;\n\nuse rand::{self, Rng};\n\nuse socket_collection::TcpSock;\n\nuse sodium::crypto::box_;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::collections::HashSet;\n\nuse std::fmt::{self, Debug, Formatter};\n\nuse std::mem;\n\nuse std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};\n\nuse std::rc::{Rc, Weak};\n\nuse std::time::Duration;\n\nuse tcp::new_reusably_bound_tcp_sockets;\n\nuse {Interface, NatError, NatState, NatType, TcpHolePunchInfo};\n\n\n\nmod listener;\n\nmod puncher;\n\nmod rendezvous_client;\n\n\n\npub type RendezvousFinsih = Box<FnMut(&mut Interface, &Poll, NatType, ::Res<SocketAddr>)>;\n\npub type HolePunchFinsih = Box<FnMut(&mut Interface, &Poll, ::Res<TcpHolePunchInfo>)>;\n\n\n\nconst LISTENER_BACKLOG: i32 = 100;\n\n\n", "file_path": "src/tcp/hole_punch/mod.rs", "rank": 78, "score": 32.480360759306464 }, { "content": "use mio::{Poll, PollOpt, Ready, Token};\n\nuse socket_collection::{self, TcpSock};\n\nuse sodium::crypto::sealedbox;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::net::SocketAddr;\n\nuse std::rc::Rc;\n\nuse std::str::{self, FromStr};\n\nuse tcp::{TcpEchoReq, TcpEchoResp};\n\nuse {Interface, NatError, NatState};\n\n\n\npub type Finish = Box<FnMut(&mut Interface, &Poll, Token, ::Res<SocketAddr>)>;\n\n\n\npub struct TcpRendezvousClient {\n\n token: Token,\n\n sock: TcpSock,\n\n req: Option<TcpEchoReq>,\n\n f: Finish,\n\n}\n\n\n", "file_path": "src/tcp/hole_punch/rendezvous_client.rs", "rank": 79, "score": 32.424837365489445 }, { "content": " f,\n\n }));\n\n\n\n if ifc.insert_state(token, client.clone()).is_err() {\n\n debug!(\"Unable to insert UdpRendezvousClient State!\");\n\n client.borrow_mut().terminate(ifc, poll);\n\n Err(NatError::UdpRendezvousFailed)\n\n } else {\n\n Ok(token)\n\n }\n\n }\n\n\n\n fn read(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let mut cipher_text = Vec::with_capacity(64);\n\n loop {\n\n match self.sock.read() {\n\n Ok(Some(UdpEchoResp(cipher))) => cipher_text = cipher,\n\n Ok(None) => if cipher_text.is_empty() {\n\n return;\n\n } else {\n", "file_path": "src/udp/hole_punch/rendezvous_client.rs", "rank": 80, "score": 32.292499944916145 }, { "content": "use self::puncher::Puncher;\n\nuse self::rendezvous_client::UdpRendezvousClient;\n\nuse mio::Poll;\n\nuse mio::Token;\n\nuse socket_collection::UdpSock;\n\nuse sodium::crypto::box_;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::collections::HashSet;\n\nuse std::fmt::{self, Debug, Formatter};\n\nuse std::mem;\n\nuse std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};\n\nuse std::rc::{Rc, Weak};\n\nuse std::time::Duration;\n\nuse {Interface, NatError, NatState, NatType, UdpHolePunchInfo};\n\n\n\nmod puncher;\n\nmod rendezvous_client;\n\n\n\npub type RendezvousFinsih = Box<FnMut(&mut Interface, &Poll, NatType, ::Res<Vec<SocketAddr>>)>;\n\npub type HolePunchFinsih = Box<FnMut(&mut Interface, &Poll, ::Res<UdpHolePunchInfo>)>;\n\n\n", "file_path": "src/udp/hole_punch/mod.rs", "rank": 81, "score": 31.48154317458669 }, { "content": "use super::{TcpEchoReq, TcpEchoResp};\n\nuse mio::timer::Timeout;\n\nuse mio::{Poll, PollOpt, Ready, Token};\n\nuse socket_collection::{SocketError, TcpSock};\n\nuse sodium::crypto::box_;\n\nuse sodium::crypto::sealedbox;\n\nuse std::any::Any;\n\nuse std::cell::RefCell;\n\nuse std::net::SocketAddr;\n\nuse std::rc::Rc;\n\nuse std::time::Duration;\n\nuse {Interface, NatError, NatState, NatTimer};\n\n\n\nconst TIMER_ID: u8 = 0;\n\nconst RENDEZVOUS_EXCHG_TIMEOUT_SEC: u64 = 5;\n\n\n\npub struct ExchangeMsg {\n\n token: Token,\n\n sock: TcpSock,\n\n peer: SocketAddr,\n", "file_path": "src/tcp/rendezvous_server/exchange_msg.rs", "rank": 82, "score": 31.081550895116543 }, { "content": " return self.terminate(ifc, poll);\n\n }\n\n }\n\n\n\n fn write(&mut self, ifc: &mut Interface, poll: &Poll, m: Option<TcpEchoResp>) {\n\n match self.sock.write(m.map(|m| (m, 0))) {\n\n Ok(true) => (),\n\n Ok(false) => return,\n\n Err(e) => {\n\n debug!(\"Error in write for tcp exchanger: {:?}\", e);\n\n self.terminate(ifc, poll);\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl NatState for ExchangeMsg {\n\n fn ready(&mut self, ifc: &mut Interface, poll: &Poll, event: Ready) {\n\n if event.is_readable() {\n\n self.read(ifc, poll)\n", "file_path": "src/tcp/rendezvous_server/exchange_msg.rs", "rank": 83, "score": 30.710480842302857 }, { "content": "impl HolePunchMediator {\n\n /// Start the mediator engine. This will prepare it for the rendezvous. Once rendezvous\n\n /// information is obtained via the given callback, the user is expected to exchange it out of\n\n /// band with the peer and begin hole punching by giving the peer's rendezvous information.\n\n pub fn start(ifc: &mut Interface, poll: &Poll, f: GetInfo) -> ::Res<()> {\n\n let token = ifc.new_token();\n\n let dur = ifc\n\n .config()\n\n .rendezvous_timeout_sec\n\n .unwrap_or(RENDEZVOUS_TIMEOUT_SEC);\n\n let timeout = ifc.set_timeout(Duration::from_secs(dur), NatTimer::new(token, TIMER_ID))?;\n\n\n\n let mediator = Rc::new(RefCell::new(HolePunchMediator {\n\n token,\n\n state: State::None,\n\n udp_child: None,\n\n tcp_child: None,\n\n self_weak: Weak::new(),\n\n }));\n\n let weak = Rc::downgrade(&mediator);\n", "file_path": "src/hole_punch.rs", "rank": 84, "score": 30.312383749426292 }, { "content": " if let Ok(ext_addr) = res {\n\n info.tcp = Some(ext_addr);\n\n } else {\n\n self.tcp_child = None;\n\n }\n\n nat_info.nat_type_for_tcp = nat_type;\n\n }\n\n\n\n self.handle_rendezvous_impl(ifc, poll);\n\n }\n\n\n\n fn handle_rendezvous_impl(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let r = match self.state {\n\n State::Rendezvous {\n\n ref mut info,\n\n ref mut nat_info,\n\n ref mut f,\n\n ref timeout,\n\n } => {\n\n if (self.udp_child.is_none() || !info.udp.is_empty())\n", "file_path": "src/hole_punch.rs", "rank": 85, "score": 30.28259837766283 }, { "content": " }\n\n\n\n fn handle_hole_punch(\n\n &mut self,\n\n ifc: &mut Interface,\n\n poll: &Poll,\n\n child: Token,\n\n res: ::Res<(TcpSock, Duration)>,\n\n ) {\n\n let r = match self.state {\n\n State::HolePunching {\n\n ref mut children,\n\n ref mut f,\n\n } => {\n\n let _ = children.remove(&child);\n\n if let Ok((sock, dur)) = res {\n\n f(ifc, poll, Ok(TcpHolePunchInfo::new(sock, child, dur)));\n\n Ok(true)\n\n } else if children.is_empty() {\n\n f(ifc, poll, Err(NatError::TcpHolePunchFailed));\n", "file_path": "src/tcp/hole_punch/mod.rs", "rank": 86, "score": 29.620902488959615 }, { "content": " while let Some(nat_timer) = self.timer.poll() {\n\n if let Some(nat_state) = self.state(nat_timer.associated_nat_state) {\n\n nat_state\n\n .borrow_mut()\n\n .timeout(self, poll, nat_timer.timer_id);\n\n }\n\n }\n\n }\n\n\n\n fn handle_readiness(&mut self, poll: &Poll, token: Token, kind: Ready) {\n\n if let Some(nat_state) = self.state(token) {\n\n return nat_state.borrow_mut().ready(self, poll, kind);\n\n }\n\n }\n\n}\n\n\n\nimpl Interface for StateMachine {\n\n fn insert_state(\n\n &mut self,\n\n token: Token,\n", "file_path": "tests/nat_traversal.rs", "rank": 87, "score": 29.45861949486897 }, { "content": " let weak = self.self_weak.clone();\n\n let handler = move |ifc: &mut Interface, poll: &Poll, token, res| {\n\n if let Some(mediator) = weak.upgrade() {\n\n mediator\n\n .borrow_mut()\n\n .handle_hole_punch(ifc, poll, token, res);\n\n }\n\n };\n\n let via = Via::Connect {\n\n our_addr: our_addr,\n\n peer_addr: peer,\n\n };\n\n if let Ok(child) = Puncher::start(ifc, poll, via, peer_enc_pk, Box::new(handler)) {\n\n let _ = children.insert(child);\n\n }\n\n\n\n let weak = self.self_weak.clone();\n\n let handler = move |ifc: &mut Interface, poll: &Poll, token, res| {\n\n if let Some(mediator) = weak.upgrade() {\n\n mediator\n", "file_path": "src/tcp/hole_punch/mod.rs", "rank": 88, "score": 29.132578472732394 }, { "content": " pub fn start(\n\n ifc: &mut Interface,\n\n poll: &Poll,\n\n l: TcpListener,\n\n peer_enc_key: &box_::PublicKey,\n\n f: Finish,\n\n ) -> ::Res<Token> {\n\n let token = ifc.new_token();\n\n\n\n poll.register(\n\n &l,\n\n token,\n\n Ready::readable() | Ready::error() | Ready::hup(),\n\n PollOpt::edge(),\n\n )?;\n\n\n\n let listener = Rc::new(RefCell::new(Listener {\n\n token: token,\n\n listener: l,\n\n peer_enc_key: *peer_enc_key,\n", "file_path": "src/tcp/hole_punch/listener.rs", "rank": 89, "score": 28.296595786654454 }, { "content": " &self.enc_pk\n\n }\n\n\n\n fn enc_sk(&self) -> &box_::SecretKey {\n\n &self.enc_sk\n\n }\n\n\n\n fn sender(&self) -> &Sender<NatMsg> {\n\n &self.tx\n\n }\n\n}\n\n\n\npub struct CoreMsg(Option<Box<FnMut(&mut StateMachine, &Poll) + Send + 'static>>);\n\nimpl CoreMsg {\n\n #[allow(unused)]\n\n pub fn new<F: FnOnce(&mut StateMachine, &Poll) + Send + 'static>(f: F) -> Self {\n\n let mut f = Some(f);\n\n CoreMsg(Some(Box::new(move |sm: &mut StateMachine, poll: &Poll| {\n\n if let Some(f) = f.take() {\n\n f(sm, poll);\n", "file_path": "tests/nat_traversal.rs", "rank": 90, "score": 28.088718049417977 }, { "content": " Err(NatError::TcpRendezvousServerStartFailed)\n\n } else {\n\n Ok(token)\n\n }\n\n }\n\n\n\n fn accept(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n loop {\n\n match self.listener.accept() {\n\n Ok((socket, peer)) => {\n\n if let Err(e) = ExchangeMsg::start(ifc, poll, peer, TcpSock::wrap(socket)) {\n\n debug!(\"Error accepting direct connection: {:?}\", e);\n\n }\n\n }\n\n Err(ref e)\n\n if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::Interrupted =>\n\n {\n\n return;\n\n }\n\n Err(e) => {\n", "file_path": "src/tcp/rendezvous_server/mod.rs", "rank": 91, "score": 28.074281641445396 }, { "content": " State::HolePunching { .. } => write!(f, \"State::HolePunching\"),\n\n }\n\n }\n\n}\n\n\n\npub struct UdpHolePunchMediator {\n\n state: State,\n\n self_weak: Weak<RefCell<UdpHolePunchMediator>>,\n\n}\n\n\n\nimpl UdpHolePunchMediator {\n\n pub fn start(\n\n ifc: &mut Interface,\n\n poll: &Poll,\n\n f: RendezvousFinsih,\n\n ) -> ::Res<Rc<RefCell<Self>>> {\n\n let mut socks = Vec::with_capacity(ifc.config().udp_hole_punchers.len());\n\n let addr_any = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0));\n\n for _ in 0..ifc.config().udp_hole_punchers.len() {\n\n socks.push(UdpSock::bind(&addr_any)?);\n", "file_path": "src/udp/hole_punch/mod.rs", "rank": 92, "score": 27.449202498494593 }, { "content": " self.state = State::HolePunching {\n\n children: children,\n\n f,\n\n };\n\n\n\n Ok(())\n\n }\n\n\n\n fn handle_hole_punch(\n\n &mut self,\n\n ifc: &mut Interface,\n\n poll: &Poll,\n\n child: Token,\n\n res: ::Res<(UdpSock, SocketAddr, u32, u32, Duration)>,\n\n ) {\n\n let r = match self.state {\n\n State::HolePunching {\n\n ref mut children,\n\n ref mut f,\n\n } => {\n", "file_path": "src/udp/hole_punch/mod.rs", "rank": 93, "score": 27.362753466398694 }, { "content": " );\n\n true\n\n }\n\n };\n\n\n\n if terminate {\n\n self.terminate(ifc, poll);\n\n }\n\n }\n\n\n\n fn terminate(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let _ = ifc.remove_state(self.token);\n\n match self.state {\n\n State::Rendezvous { ref timeout, .. } => {\n\n let _ = ifc.cancel_timeout(timeout);\n\n }\n\n State::HolePunching {\n\n ref mut info,\n\n ref timeout,\n\n ..\n", "file_path": "src/hole_punch.rs", "rank": 94, "score": 27.204148482570677 }, { "content": " // Errored while writting\n\n if self.terminated {\n\n break;\n\n }\n\n }\n\n }\n\n\n\n fn write_to(&mut self, ifc: &mut Interface, poll: &Poll, m: Option<(UdpEchoResp, SocketAddr)>) {\n\n match self.sock.write_to(m.map(|(m, s)| (m, s, 0))) {\n\n Ok(_) => (),\n\n Err(e) => {\n\n warn!(\"Udp Rendezvous Server has errored out in write: {:?}\", e);\n\n self.terminate(ifc, poll);\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl NatState for UdpRendezvousServer {\n\n fn ready(&mut self, ifc: &mut Interface, poll: &Poll, event: Ready) {\n", "file_path": "src/udp/rendezvous_server.rs", "rank": 95, "score": 27.136508080584452 }, { "content": " } else if event.is_writable() {\n\n self.write(ifc, poll, None)\n\n } else {\n\n warn!(\"Investigate: Ignoring unknown event kind: {:?}\", event);\n\n }\n\n }\n\n\n\n fn timeout(&mut self, ifc: &mut Interface, poll: &Poll, timer_id: u8) {\n\n if timer_id != TIMER_ID {\n\n debug!(\"Invalid Timer ID: {}\", timer_id);\n\n }\n\n debug!(\"Timeout in tcp rendezvous exchanger. Terminating session.\");\n\n self.terminate(ifc, poll)\n\n }\n\n\n\n fn terminate(&mut self, ifc: &mut Interface, poll: &Poll) {\n\n let _ = ifc.cancel_timeout(&self.timeout);\n\n let _ = ifc.remove_state(self.token);\n\n let _ = poll.deregister(&self.sock);\n\n }\n\n\n\n fn as_any(&mut self) -> &mut Any {\n\n self\n\n }\n\n}\n", "file_path": "src/tcp/rendezvous_server/exchange_msg.rs", "rank": 96, "score": 26.510380778014426 }, { "content": " f(ifc, poll, nat_type, Ok(ext_addrs));\n\n Ok(Some(socks))\n\n }\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n ref x => {\n\n warn!(\n\n \"Logic Error in state book-keeping - Pls report this as a bug. Expected \\\n\n state: State::Rendezvous ;; Found: {:?}\",\n\n x\n\n );\n\n Err(NatError::InvalidState)\n\n }\n\n };\n\n\n\n match r {\n\n Ok(Some(socks)) => self.state = State::ReadyToHolePunch(socks),\n\n Ok(None) => (),\n", "file_path": "src/udp/hole_punch/mod.rs", "rank": 97, "score": 26.30130316993226 }, { "content": " token,\n\n Ready::readable() | Ready::writable(),\n\n PollOpt::edge(),\n\n )?;\n\n\n\n let server = Rc::new(RefCell::new(UdpRendezvousServer {\n\n sock,\n\n token,\n\n terminated: false,\n\n }));\n\n\n\n if ifc.insert_state(token, server.clone()).is_err() {\n\n warn!(\"Unable to start UdpRendezvousServer!\");\n\n server.borrow_mut().terminate(ifc, poll);\n\n Err(NatError::UdpRendezvousServerStartFailed)\n\n } else {\n\n Ok(token)\n\n }\n\n }\n\n\n", "file_path": "src/udp/rendezvous_server.rs", "rank": 98, "score": 25.978201103219313 }, { "content": " );\n\n }\n\n}\n\n\n\nimpl NatState for UdpRendezvousClient {\n\n fn ready(&mut self, ifc: &mut Interface, poll: &Poll, event: Ready) {\n\n if event.is_readable() {\n\n self.read(ifc, poll)\n\n } else if event.is_writable() {\n\n if let Some(server) = self.on_first_write_triggered.take() {\n\n if let Err(e) = self.sock.connect(&server) {\n\n debug!(\n\n \"Error: Udp Rendezvous Client could not connect to server: {:?}\",\n\n e\n\n );\n\n return self.handle_err(ifc, poll, None);\n\n }\n\n let pk = ifc.enc_pk().0;\n\n self.write(ifc, poll, Some(UdpEchoReq(pk)));\n\n } else {\n", "file_path": "src/udp/hole_punch/rendezvous_client.rs", "rank": 99, "score": 25.97450026571023 } ]
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 ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/settings.svg\")\n\n .build_widget(ctx, \"settings\"),\n\n ]))\n\n .aligned(HorizontalAlignment::Left, VerticalAlignment::BottomAboveOSD)\n\n .build(ctx)\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 0, "score": 481276.33606234903 }, { "content": "/// Creates the top row for any layer panel.\n\npub fn header(ctx: &mut EventCtx, name: &str) -> Widget {\n\n Widget::row(vec![\n\n Widget::draw_svg(ctx, \"system/assets/tools/layers.svg\").centered_vert(),\n\n name.draw_text(ctx).centered_vert(),\n\n ctx.style().btn_close_widget(ctx),\n\n ])\n\n}\n", "file_path": "game/src/layer/mod.rs", "rank": 1, "score": 448456.1256075818 }, { "content": "fn make_controls(ctx: &mut EventCtx) -> Panel {\n\n let btn = ctx.style();\n\n Panel::new(Widget::col(vec![\n\n Text::from_multiline(vec![\n\n Line(\"widgetry demo\").big_heading_styled(),\n\n Line(\"Click and drag the background to pan, use touchpad or scroll wheel to zoom\"),\n\n ])\n\n .draw(ctx),\n\n // Button Style Gallery\n\n // TODO might be nice to have this in separate tabs or something.\n\n Text::from(Line(\"Buttons\").big_heading_styled().size(18)).draw(ctx),\n\n Widget::row(vec![\n\n Widget::col(vec![\n\n Text::from(Line(\"Neutral Dark\")).bg(Color::CLEAR).draw(ctx),\n\n btn.btn_solid_dark_text(\"Primary\")\n\n .build_widget(ctx, \"btn_solid_dark_text\"),\n\n Widget::row(vec![\n\n btn.btn_solid_dark_icon(\"system/assets/tools/map.svg\")\n\n .build_widget(ctx, \"btn_solid_dark_icon_1\"),\n\n btn.btn_solid_dark_icon(\"system/assets/tools/layers.svg\")\n", "file_path": "widgetry_demo/src/lib.rs", "rank": 2, "score": 441856.81817141944 }, { "content": "fn make_top_panel(ctx: &mut EventCtx, app: &App, can_undo: bool, can_redo: bool) -> Panel {\n\n let row = vec![\n\n ctx.style()\n\n .btn_solid_dark_text(\"Finish\")\n\n .hotkey(Key::Enter)\n\n .build_def(ctx),\n\n ctx.style()\n\n .btn_solid_dark_text(\"Preview\")\n\n .hotkey(lctrl(Key::P))\n\n .build_def(ctx),\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/undo.svg\")\n\n .disabled(!can_undo)\n\n .hotkey(lctrl(Key::Z))\n\n .build_widget(ctx, \"undo\"),\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/redo.svg\")\n\n .disabled(!can_redo)\n\n // TODO ctrl+shift+Z!\n\n .hotkey(lctrl(Key::Y))\n", "file_path": "game/src/edit/traffic_signals/mod.rs", "rank": 3, "score": 437985.4204259449 }, { "content": "fn make_panel(ctx: &mut EventCtx, story: &StoryMap, mode: &Mode, dirty: bool) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Widget::row(vec![\n\n Line(\"Story map editor\").small_heading().draw(ctx),\n\n Widget::vert_separator(ctx, 30.0),\n\n ctx.style()\n\n .btn_outline_light_popup(&story.name)\n\n .hotkey(lctrl(Key::L))\n\n .build_widget(ctx, \"load\"),\n\n ctx.style()\n\n .btn_solid_light_icon(\"system/assets/tools/save.svg\")\n\n .hotkey(lctrl(Key::S))\n\n .disabled(!dirty)\n\n .build_widget(ctx, \"save\"),\n\n ctx.style().btn_close_widget(ctx),\n\n ]),\n\n Widget::row(vec![\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/timeline/goal_pos.svg\")\n\n .disabled(matches!(mode, Mode::PlacingMarker))\n", "file_path": "game/src/devtools/story.rs", "rank": 4, "score": 425890.5125074807 }, { "content": "pub fn execute(ctx: &mut EventCtx, app: &mut App, id: ID, action: &str) -> Transition {\n\n match (id, action.as_ref()) {\n\n (ID::Building(b), \"start a trip here\") => Transition::Push(AgentSpawner::new(ctx, Some(b))),\n\n (ID::Intersection(id), \"spawn agents here\") => {\n\n spawn_agents_around(id, app);\n\n Transition::Keep\n\n }\n\n _ => unreachable!(),\n\n }\n\n}\n", "file_path": "game/src/sandbox/gameplay/freeform.rs", "rank": 5, "score": 420769.3162410866 }, { "content": "pub fn execute(ctx: &mut EventCtx, app: &mut App, id: ID, action: &str) -> Transition {\n\n let mut tut = app.session.tutorial.as_mut().unwrap();\n\n let response = match (id, action.as_ref()) {\n\n (ID::Car(c), \"draw WASH ME\") => {\n\n let is_parked = app\n\n .primary\n\n .sim\n\n .agent_to_trip(AgentID::Car(ESCORT))\n\n .is_none();\n\n if c == ESCORT {\n\n if is_parked {\n\n tut.prank_done = true;\n\n PopupMsg::new(\n\n ctx,\n\n \"Prank in progress\",\n\n vec![\"You quickly scribble on the window...\"],\n\n )\n\n } else {\n\n PopupMsg::new(\n\n ctx,\n", "file_path": "game/src/sandbox/gameplay/tutorial.rs", "rank": 6, "score": 420769.3162410866 }, { "content": "fn make_btn(ctx: &EventCtx, label: &str, tooltip: &str, is_persisten_split: bool) -> Button {\n\n // If we want to make Dropdown configurable, pass in or expose its button builder?\n\n let mut builder = ctx.style().btn_solid_dark_dropdown();\n\n if is_persisten_split {\n\n // Quick hacks to make PersistentSplit's dropdown look a little better.\n\n // It's not ideal, but we only use one persistent split in the whole app\n\n // and it's front and center - we'll notice if something breaks.\n\n builder = builder\n\n .padding(EdgeInsets {\n\n top: 15.0,\n\n bottom: 15.0,\n\n left: 8.0,\n\n right: 8.0,\n\n })\n\n .corner_rounding(CornerRounding::CornerRadii(CornerRadii {\n\n top_left: 0.0,\n\n bottom_left: 0.0,\n\n bottom_right: 2.0,\n\n top_right: 2.0,\n\n }))\n\n .outline(0.0, Color::CLEAR, ControlState::Default);\n\n } else {\n\n builder = builder.label_text(label);\n\n }\n\n\n\n builder.build(ctx, tooltip)\n\n}\n", "file_path": "widgetry/src/widgets/dropdown.rs", "rank": 7, "score": 412836.815586796 }, { "content": "fn make_vehicle_panel(ctx: &mut EventCtx, app: &App) -> Panel {\n\n let mut buttons = Vec::new();\n\n for name in &app.session.vehicles_unlocked {\n\n let vehicle = Vehicle::get(name);\n\n let batch = vehicle\n\n .animate(ctx.prerender, Time::START_OF_DAY)\n\n .scale(10.0);\n\n\n\n buttons.push(\n\n if name == &app.session.current_vehicle {\n\n Widget::draw_batch(ctx, batch)\n\n .container()\n\n .padding(5)\n\n .outline(2.0, Color::WHITE)\n\n } else {\n\n let normal = batch.clone().color(RewriteColor::MakeGrayscale);\n\n let hovered = batch;\n\n ButtonBuilder::new()\n\n .custom_batch(normal, ControlState::Default)\n\n .custom_batch(hovered, ControlState::Hovered)\n", "file_path": "santa/src/before_level.rs", "rank": 8, "score": 388167.22940741316 }, { "content": "fn link(ctx: &mut EventCtx, label: &str, url: &str) -> Widget {\n\n ctx.style()\n\n .btn_plain_light_text(label)\n\n .build_widget(ctx, &format!(\"open {}\", url))\n\n}\n\n\n\nimpl SimpleState<App> for Credits {\n\n fn on_click(&mut self, _: &mut EventCtx, _: &mut App, x: &str, _: &Panel) -> Transition {\n\n match x {\n\n \"close\" | \"Back\" => Transition::Pop,\n\n x => {\n\n if let Some(url) = x.strip_prefix(\"open \") {\n\n open_browser(url);\n\n return Transition::Keep;\n\n }\n\n\n\n unreachable!()\n\n }\n\n }\n\n }\n", "file_path": "santa/src/title.rs", "rank": 9, "score": 387538.44423425384 }, { "content": "fn make_panel(ctx: &mut EventCtx, app: &App) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Widget::row(vec![\n\n Line(\"Commute map by block\").small_heading().draw(ctx),\n\n ctx.style().btn_close_widget(ctx),\n\n ]),\n\n Checkbox::toggle(ctx, \"from / to this block\", \"from\", \"to\", Key::Space, true),\n\n Checkbox::switch(ctx, \"include borders\", None, true),\n\n Widget::row(vec![\n\n \"Departing from:\".draw_text(ctx).margin_right(20),\n\n Slider::area(ctx, 0.15 * ctx.canvas.window_width, 0.0).named(\"depart from\"),\n\n ]),\n\n Widget::row(vec![\n\n \"Departing until:\".draw_text(ctx).margin_right(20),\n\n Slider::area(ctx, 0.15 * ctx.canvas.window_width, 1.0).named(\"depart until\"),\n\n ]),\n\n checkbox_per_mode(ctx, app, &TripMode::all().into_iter().collect()),\n\n ColorLegend::gradient(ctx, &app.cs.good_to_bad_red, vec![\"0\", \"0\"]).named(\"scale\"),\n\n \"None selected\".draw_text(ctx).named(\"current\"),\n\n ]))\n\n .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)\n\n .build(ctx)\n\n}\n", "file_path": "game/src/sandbox/dashboards/commuter.rs", "rank": 10, "score": 384870.8102741135 }, { "content": "fn make_select_panel(ctx: &mut EventCtx, selector: &RoadSelector) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Line(\"Edit many roads\").small_heading().draw(ctx),\n\n selector.make_controls(ctx),\n\n Widget::row(vec![\n\n ctx.style()\n\n .btn_outline_light_text(&format!(\"Edit {} roads\", selector.roads.len()))\n\n .disabled(selector.roads.is_empty())\n\n .hotkey(hotkeys(vec![Key::E, Key::Enter]))\n\n .build_widget(ctx, \"edit roads\"),\n\n ctx.style()\n\n .btn_outline_light_text(&format!(\n\n \"Export {} roads to shared-row\",\n\n selector.roads.len()\n\n ))\n\n .build_widget(ctx, \"export roads to shared-row\"),\n\n ctx.style()\n\n .btn_outline_light_text(\"export one road to Streetmix\")\n\n .build_def(ctx),\n\n ctx.style()\n", "file_path": "game/src/edit/bulk.rs", "rank": 11, "score": 381680.78856638743 }, { "content": "pub fn maybe_exit_sandbox(ctx: &mut EventCtx) -> Transition {\n\n Transition::Push(ChooseSomething::new(\n\n ctx,\n\n \"Are you ready to leave this mode?\",\n\n vec![\n\n Choice::string(\"keep playing\"),\n\n Choice::string(\"quit to main screen\").key(Key::Q),\n\n ],\n\n Box::new(|resp, ctx, app| {\n\n if resp == \"keep playing\" {\n\n return Transition::Pop;\n\n }\n\n\n\n if app.primary.map.unsaved_edits() {\n\n return Transition::Multi(vec![\n\n Transition::Push(Box::new(BackToMainMenu)),\n\n Transition::Push(SaveEdits::new(\n\n ctx,\n\n app,\n\n \"Do you want to save your proposal first?\",\n", "file_path": "game/src/sandbox/mod.rs", "rank": 12, "score": 378631.8499965816 }, { "content": "fn make_changelist(ctx: &mut EventCtx, app: &App) -> Panel {\n\n // TODO Support redo. Bit harder here to reset the redo_stack when the edits\n\n // change, because nested other places modify it too.\n\n let edits = app.primary.map.get_edits();\n\n let mut col = vec![\n\n Widget::row(vec![\n\n ctx.style()\n\n .btn_outline_light_popup(&edits.edits_name)\n\n .hotkey(lctrl(Key::P))\n\n .build_widget(ctx, \"manage proposals\"),\n\n \"autosaved\"\n\n .draw_text(ctx)\n\n .container()\n\n .padding(10)\n\n .bg(Color::hex(\"#5D9630\")),\n\n ]),\n\n ColorLegend::row(\n\n ctx,\n\n app.cs.edits_layer,\n\n format!(\n", "file_path": "game/src/edit/mod.rs", "rank": 13, "score": 374452.86304195446 }, { "content": "fn make_topcenter(ctx: &mut EventCtx, app: &App) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Line(\"Editing map\")\n\n .small_heading()\n\n .draw(ctx)\n\n .centered_horiz(),\n\n ctx.style()\n\n .btn_solid_dark_text(&format!(\n\n \"Finish & resume from {}\",\n\n app.primary\n\n .suspended_sim\n\n .as_ref()\n\n .unwrap()\n\n .time()\n\n .ampm_tostring()\n\n ))\n\n .hotkey(Key::Escape)\n\n .build_widget(ctx, \"finish editing\"),\n\n ]))\n\n .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)\n\n .build(ctx)\n\n}\n\n\n", "file_path": "game/src/edit/mod.rs", "rank": 14, "score": 374452.86304195446 }, { "content": "fn search_osm(filter: String, ctx: &mut EventCtx, app: &mut App) -> Transition {\n\n let mut num_matches = 0;\n\n let mut batch = GeomBatch::new();\n\n\n\n // TODO Case insensitive\n\n let map = &app.primary.map;\n\n let color = Color::RED.alpha(0.8);\n\n for r in map.all_roads() {\n\n if r.osm_tags\n\n .inner()\n\n .iter()\n\n .any(|(k, v)| format!(\"{} = {}\", k, v).contains(&filter))\n\n {\n\n num_matches += 1;\n\n batch.push(color, r.get_thick_polygon(map));\n\n }\n\n }\n\n for a in map.all_areas() {\n\n if a.osm_tags\n\n .inner()\n", "file_path": "game/src/debug/mod.rs", "rank": 15, "score": 372406.3467820876 }, { "content": "fn challenge_header(ctx: &mut EventCtx, title: &str) -> Widget {\n\n Widget::row(vec![\n\n Line(title).small_heading().draw(ctx).centered_vert(),\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/info.svg\")\n\n .build_widget(ctx, \"instructions\")\n\n .centered_vert(),\n\n Widget::vert_separator(ctx, 50.0),\n\n ctx.style()\n\n .btn_outline_light_icon_text(\"system/assets/tools/pencil.svg\", \"Edit map\")\n\n .hotkey(lctrl(Key::E))\n\n .build_widget(ctx, \"edit map\")\n\n .centered_vert(),\n\n ])\n\n .padding(5)\n\n}\n\n\n\npub struct FinalScore {\n\n panel: Panel,\n\n retry: GameplayMode,\n", "file_path": "game/src/sandbox/gameplay/mod.rs", "rank": 16, "score": 370857.1679745058 }, { "content": "fn make_upzone_panel(ctx: &mut EventCtx, app: &App, num_picked: usize) -> Panel {\n\n // Don't overwhelm players on the very first level.\n\n if app.session.upzones_unlocked == 0 {\n\n return Panel::new(\n\n ctx.style()\n\n .btn_solid_dark_text(\"Start game\")\n\n .hotkey(Key::Enter)\n\n .build_def(ctx)\n\n .container(),\n\n )\n\n .aligned(\n\n HorizontalAlignment::RightInset,\n\n VerticalAlignment::BottomInset,\n\n )\n\n .build(ctx);\n\n }\n\n\n\n Panel::new(Widget::col(vec![\n\n Widget::row(vec![\n\n Line(\"Upzoning\").small_heading().draw(ctx),\n", "file_path": "santa/src/before_level.rs", "rank": 17, "score": 367200.1502417316 }, { "content": "pub fn apply_map_edits(ctx: &mut EventCtx, app: &mut App, edits: MapEdits) {\n\n let mut timer = Timer::new(\"apply map edits\");\n\n\n\n let (roads_changed, turns_deleted, turns_added, mut modified_intersections) =\n\n app.primary.map.must_apply_edits(edits);\n\n\n\n if !roads_changed.is_empty() || !modified_intersections.is_empty() {\n\n app.primary\n\n .draw_map\n\n .draw_all_unzoomed_roads_and_intersections =\n\n DrawMap::regenerate_unzoomed_layer(&app.primary.map, &app.cs, ctx, &mut timer);\n\n }\n\n\n\n for r in roads_changed {\n\n let road = app.primary.map.get_r(r);\n\n app.primary.draw_map.roads[r.0].clear_rendering();\n\n\n\n // An edit to one lane potentially affects markings in all lanes in the same road, because\n\n // of one-way markings, driving lines, etc.\n\n for l in road.all_lanes() {\n", "file_path": "game/src/edit/mod.rs", "rank": 18, "score": 365041.4454566748 }, { "content": "fn warp_to_id(ctx: &mut EventCtx, app: &mut App, line: &str) -> Option<Transition> {\n\n if line.is_empty() {\n\n return None;\n\n }\n\n if line == \"j\" {\n\n if let Some((pt, zoom)) = app.primary.last_warped_from {\n\n return Some(Transition::Replace(Warping::new(\n\n ctx,\n\n pt,\n\n Some(zoom),\n\n None,\n\n &mut app.primary,\n\n )));\n\n }\n\n return None;\n\n }\n\n\n\n let id = match usize::from_str_radix(&line[1..line.len()], 10) {\n\n Ok(idx) => match line.chars().next().unwrap() {\n\n 'r' => {\n", "file_path": "game/src/common/warp.rs", "rank": 19, "score": 364917.20884463063 }, { "content": "fn build_panel(ctx: &mut EventCtx, app: &App, start: &Building, isochrone: &Isochrone) -> Panel {\n\n let mut rows = Vec::new();\n\n\n\n rows.push(\n\n Line(\"15-minute neighborhood explorer\")\n\n .small_heading()\n\n .draw(ctx),\n\n );\n\n\n\n rows.push(\n\n ctx.style()\n\n .btn_light_popup_icon_text(\n\n \"system/assets/tools/map.svg\",\n\n nice_map_name(app.map.get_name()),\n\n )\n\n .hotkey(lctrl(Key::L))\n\n .build_widget(ctx, \"change map\"),\n\n );\n\n\n\n rows.push(\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 20, "score": 354184.6080984768 }, { "content": "// This prepares a bunch of geometry (colored polygons) and uploads it to the GPU once. Then it can\n\n// be redrawn cheaply later.\n\nfn setup_scrollable_canvas(ctx: &mut EventCtx) -> Drawable {\n\n let mut batch = GeomBatch::new();\n\n batch.push(\n\n Color::hex(\"#4E30A6\"),\n\n Polygon::rounded_rectangle(5000.0, 5000.0, 25.0),\n\n );\n\n // SVG support using lyon and usvg. Map-space means don't scale for high DPI monitors.\n\n batch\n\n .append(GeomBatch::load_svg(ctx, \"system/assets/pregame/logo.svg\").translate(300.0, 300.0));\n\n // Text rendering also goes through lyon and usvg.\n\n batch.append(\n\n Text::from(Line(\"Awesome vector text thanks to usvg and lyon\").fg(Color::hex(\"#DF8C3D\")))\n\n .render_autocropped(ctx)\n\n .scale(2.0)\n\n .centered_on(Pt2D::new(600.0, 500.0))\n\n .rotate(Angle::degrees(-30.0)),\n\n );\n\n\n\n let mut rng = if cfg!(target_arch = \"wasm32\") {\n\n XorShiftRng::seed_from_u64(0)\n", "file_path": "widgetry_demo/src/lib.rs", "rank": 21, "score": 350257.900685337 }, { "content": "pub fn parent_path(path: &str) -> String {\n\n format!(\"{}\", std::path::Path::new(path).parent().unwrap().display())\n\n}\n", "file_path": "abstutil/src/utils.rs", "rank": 22, "score": 348733.9529259198 }, { "content": "pub fn info(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BuildingID) -> Vec<Widget> {\n\n let mut rows = header(ctx, app, details, id, Tab::BldgInfo(id));\n\n let b = app.primary.map.get_b(id);\n\n\n\n let mut kv = Vec::new();\n\n\n\n kv.push((\"Address\", b.address.clone()));\n\n if let Some(ref names) = b.name {\n\n kv.push((\"Name\", names.get(app.opts.language.as_ref()).to_string()));\n\n }\n\n if app.opts.dev {\n\n kv.push((\"OSM ID\", format!(\"{}\", b.orig_id.inner())));\n\n }\n\n\n\n let num_spots = b.num_parking_spots();\n\n if app.primary.sim.infinite_parking() {\n\n kv.push((\n\n \"Parking\",\n\n format!(\n\n \"Unlimited, currently {} cars inside\",\n", "file_path": "game/src/info/building.rs", "rank": 23, "score": 342180.6996093578 }, { "content": "pub fn people(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BuildingID) -> Vec<Widget> {\n\n let mut rows = header(ctx, app, details, id, Tab::BldgPeople(id));\n\n\n\n // Two caveats about these counts:\n\n // 1) A person might use multiple modes through the day, but this just picks a single category.\n\n // 2) Only people currently in the building currently are counted, whether or not that's their\n\n // home.\n\n let mut drivers = 0;\n\n let mut cyclists = 0;\n\n let mut others = 0;\n\n\n\n let mut ppl: Vec<(Time, Widget)> = Vec::new();\n\n for p in app.primary.sim.bldg_to_people(id) {\n\n let person = app.primary.sim.get_person(p);\n\n\n\n let mut has_car = false;\n\n let mut has_bike = false;\n\n for vehicle in &person.vehicles {\n\n if vehicle.vehicle_type == VehicleType::Car {\n\n has_car = true;\n", "file_path": "game/src/info/building.rs", "rank": 24, "score": 342180.6996093578 }, { "content": "fn make_panel(ctx: &mut EventCtx, app: &App, table: &Table<App, Entry, Filters>) -> Panel {\n\n let mut col = vec![DashTab::ParkingOverhead.picker(ctx, app)];\n\n col.push(\n\n Widget::row(vec![\n\n Text::from_multiline(vec![\n\n Line(\n\n \"Trips taken by car also include time to walk between the building and \\\n\n parking spot, as well as the time to find parking.\",\n\n ),\n\n Line(\"Overhead is 1 - driving time / total time\"),\n\n Line(\"Ideally, overhead is 0% -- the entire trip is just spent driving.\"),\n\n Line(\"\"),\n\n Line(\"High overhead could mean:\"),\n\n Line(\"- the car burned more resources and caused more traffic looking for parking\"),\n\n Line(\"- somebody with impaired movement had to walk far to reach their vehicle\"),\n\n Line(\"- the person was inconvenienced\"),\n\n Line(\"\"),\n\n Line(\n\n \"Note: Trips beginning/ending outside the map have an artifically high \\\n\n overhead,\",\n", "file_path": "game/src/sandbox/dashboards/parking_overhead.rs", "rank": 25, "score": 341166.4033075396 }, { "content": "pub fn route(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BusRouteID) -> Vec<Widget> {\n\n let map = &app.primary.map;\n\n let route = map.get_br(id);\n\n let mut rows = vec![];\n\n\n\n rows.push(Widget::row(vec![\n\n Line(format!(\"Route {}\", route.short_name))\n\n .small_heading()\n\n .draw(ctx),\n\n header_btns(ctx),\n\n ]));\n\n rows.push(\n\n Text::from(Line(&route.full_name))\n\n .wrap_to_pct(ctx, 20)\n\n .draw(ctx),\n\n );\n\n\n\n if app.opts.dev {\n\n rows.push(\n\n ctx.style()\n", "file_path": "game/src/info/bus.rs", "rank": 26, "score": 339532.89291502826 }, { "content": "pub fn stop(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BusStopID) -> Vec<Widget> {\n\n let bs = app.primary.map.get_bs(id);\n\n let mut rows = vec![];\n\n\n\n let sim = &app.primary.sim;\n\n\n\n rows.push(Widget::row(vec![\n\n Line(\"Bus stop\").small_heading().draw(ctx),\n\n header_btns(ctx),\n\n ]));\n\n rows.push(Line(&bs.name).draw(ctx));\n\n\n\n let all_arrivals = &sim.get_analytics().bus_arrivals;\n\n for r in app.primary.map.get_routes_serving_stop(id) {\n\n // Full names can overlap, so include the ID\n\n let label = format!(\"{} ({})\", r.full_name, r.id);\n\n rows.push(\n\n ctx.style()\n\n .btn_outline_light_text(&format!(\"Route {}\", r.short_name))\n\n .build_widget(ctx, &label),\n", "file_path": "game/src/info/bus.rs", "rank": 27, "score": 339532.89291502826 }, { "content": "pub fn bus_status(ctx: &mut EventCtx, app: &App, details: &mut Details, id: CarID) -> Vec<Widget> {\n\n let mut rows = bus_header(ctx, app, details, id, Tab::BusStatus(id));\n\n\n\n let route = app\n\n .primary\n\n .map\n\n .get_br(app.primary.sim.bus_route_id(id).unwrap());\n\n\n\n rows.push(\n\n ctx.style()\n\n .btn_outline_light_text(&format!(\"Serves route {}\", route.short_name))\n\n .build_def(ctx),\n\n );\n\n details.hyperlinks.insert(\n\n format!(\"Serves route {}\", route.short_name),\n\n Tab::BusRoute(route.id),\n\n );\n\n\n\n rows.push(\n\n Line(format!(\n\n \"Currently has {} passengers\",\n\n app.primary.sim.num_transit_passengers(id),\n\n ))\n\n .draw(ctx),\n\n );\n\n\n\n rows\n\n}\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 28, "score": 339532.89291502826 }, { "content": "pub fn path_save(name: &MapName, edits_name: &str, run_name: &str, time: String) -> String {\n\n path(format!(\n\n \"player/saves/{}/{}/{}/{}_{}/{}.bin\",\n\n name.city.country, name.city.city, name.map, edits_name, run_name, time\n\n ))\n\n}\n", "file_path": "abstio/src/abst_paths.rs", "rank": 29, "score": 337223.8442460896 }, { "content": "pub fn info(ctx: &mut EventCtx, app: &App, details: &mut Details, id: ParkingLotID) -> Vec<Widget> {\n\n let mut rows = header(ctx, details, id, Tab::ParkingLot(id));\n\n let pl = app.primary.map.get_pl(id);\n\n let capacity = pl.capacity();\n\n\n\n rows.push(\n\n format!(\n\n \"{} / {} spots available\",\n\n prettyprint_usize(app.primary.sim.get_free_lot_spots(pl.id).len()),\n\n prettyprint_usize(capacity)\n\n )\n\n .draw_text(ctx),\n\n );\n\n\n\n let mut series = vec![Series {\n\n label: format!(\"After \\\"{}\\\"\", app.primary.map.get_edits().edits_name),\n\n color: app.cs.after_changes,\n\n pts: app.primary.sim.get_analytics().parking_lot_availability(\n\n app.primary.sim.time(),\n\n pl.id,\n", "file_path": "game/src/info/parking_lot.rs", "rank": 30, "score": 336960.9836262632 }, { "content": "fn preview_trip(g: &mut GfxCtx, app: &App, panel: &Panel) {\n\n let inner_rect = panel.rect_of(\"preview\").clone();\n\n let map_bounds = app.primary.map.get_bounds().clone();\n\n let zoom = 0.15 * g.canvas.window_width / map_bounds.width().max(map_bounds.height());\n\n g.fork(\n\n Pt2D::new(map_bounds.min_x, map_bounds.min_y),\n\n ScreenPt::new(inner_rect.x1, inner_rect.y1),\n\n zoom,\n\n None,\n\n );\n\n g.enable_clipping(inner_rect);\n\n\n\n g.redraw(&app.primary.draw_map.boundary_polygon);\n\n g.redraw(&app.primary.draw_map.draw_all_areas);\n\n g.redraw(\n\n &app.primary\n\n .draw_map\n\n .draw_all_unzoomed_roads_and_intersections,\n\n );\n\n\n", "file_path": "game/src/sandbox/dashboards/generic_trip_table.rs", "rank": 31, "score": 334137.4619283782 }, { "content": "fn make_tool_panel(ctx: &mut EventCtx, app: &App) -> Widget {\n\n let buttons = ctx\n\n .style()\n\n .btn_solid_light()\n\n .image_dims(ScreenDims::square(20.0))\n\n // the default transparent button background is jarring for these buttons which are floating\n\n // in a transparent panel.\n\n .bg_color(app.cs.inner_panel, ControlState::Default)\n\n .padding(8);\n\n\n\n Widget::col(vec![\n\n (if ctx.canvas.cam_zoom >= app.opts.min_zoom_for_detail {\n\n buttons\n\n .clone()\n\n .image_path(\"system/assets/minimap/zoom_out_fully.svg\")\n\n .build_widget(ctx, \"zoom out fully\")\n\n } else {\n\n buttons\n\n .clone()\n\n .image_path(\"system/assets/minimap/zoom_in_fully.svg\")\n", "file_path": "game/src/common/minimap.rs", "rank": 32, "score": 333584.70801693725 }, { "content": "fn make_controls(ctx: &mut EventCtx, app: &App, opts: &Options, legend: Option<Widget>) -> Panel {\n\n let (total_ppl, ppl_in_bldg, ppl_off_map) = app.primary.sim.num_ppl();\n\n\n\n let mut col = vec![\n\n header(\n\n ctx,\n\n &format!(\"Population: {}\", prettyprint_usize(total_ppl)),\n\n ),\n\n Widget::row(vec![\n\n Widget::row(vec![\n\n Widget::draw_svg(ctx, \"system/assets/tools/home.svg\"),\n\n Line(prettyprint_usize(ppl_in_bldg)).small().draw(ctx),\n\n ]),\n\n Line(format!(\"Off-map: {}\", prettyprint_usize(ppl_off_map)))\n\n .small()\n\n .draw(ctx),\n\n ])\n\n .centered(),\n\n ];\n\n\n", "file_path": "game/src/layer/population.rs", "rank": 33, "score": 332463.3754090907 }, { "content": "fn make_controls(ctx: &mut EventCtx, app: &App, opts: &Options, legend: Option<Widget>) -> Panel {\n\n let model = app.primary.sim.get_pandemic_model().unwrap();\n\n let pct = 100.0 / (model.count_total() as f64);\n\n\n\n let mut col = vec![\n\n header(ctx, \"Pandemic model\"),\n\n Text::from_multiline(vec![\n\n Line(format!(\n\n \"{} Sane ({:.1}%)\",\n\n prettyprint_usize(model.count_sane()),\n\n (model.count_sane() as f64) * pct\n\n )),\n\n Line(format!(\n\n \"{} Exposed ({:.1}%)\",\n\n prettyprint_usize(model.count_exposed()),\n\n (model.count_exposed() as f64) * pct\n\n )),\n\n Line(format!(\n\n \"{} Infected ({:.1}%)\",\n\n prettyprint_usize(model.count_infected()),\n", "file_path": "game/src/layer/pandemic.rs", "rank": 34, "score": 332463.3754090907 }, { "content": "pub fn make_bar(ctx: &mut EventCtx, filled_color: Color, value: usize, max: usize) -> Widget {\n\n let pct_full = if max == 0 {\n\n 0.0\n\n } else {\n\n (value as f64) / (max as f64)\n\n };\n\n let txt = Text::from(Line(format!(\n\n \"{} / {}\",\n\n prettyprint_usize(value),\n\n prettyprint_usize(max)\n\n )));\n\n custom_bar(ctx, filled_color, pct_full, txt)\n\n}\n", "file_path": "santa/src/meters.rs", "rank": 35, "score": 330695.4737613811 }, { "content": "pub fn file_exists<I: Into<String>>(path: I) -> bool {\n\n Path::new(&path.into()).exists()\n\n}\n\n\n", "file_path": "abstio/src/io_native.rs", "rank": 36, "score": 329774.4971635154 }, { "content": "pub fn file_exists<I: Into<String>>(path: I) -> bool {\n\n // TODO Handle player data in local storage\n\n let path = path.into();\n\n SYSTEM_DATA\n\n .get_file(path.trim_start_matches(\"../data/system/\"))\n\n .is_some()\n\n || Manifest::load()\n\n .entries\n\n .contains_key(path.trim_start_matches(\"../\"))\n\n}\n\n\n", "file_path": "abstio/src/io_web.rs", "rank": 37, "score": 329774.4971635154 }, { "content": "fn make_meter(ctx: &mut EventCtx, app: &App, worst: Option<(IntersectionID, Duration)>) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Widget::horiz_separator(ctx, 0.2),\n\n if let Some((_, delay)) = worst {\n\n Widget::row(vec![\n\n Text::from_all(vec![\n\n Line(\"Worst delay: \"),\n\n Line(delay.to_string(&app.opts.units)).fg(if delay < Duration::minutes(5) {\n\n Color::hex(\"#F9EC51\")\n\n } else if delay < Duration::minutes(15) {\n\n Color::hex(\"#EE702E\")\n\n } else {\n\n Color::hex(\"#EB3223\")\n\n }),\n\n ])\n\n .draw(ctx),\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/location.svg\")\n\n .build_widget(ctx, \"go to slowest intersection\")\n\n .align_right(),\n", "file_path": "game/src/sandbox/gameplay/fix_traffic_signals.rs", "rank": 38, "score": 328660.2269729285 }, { "content": "pub fn custom_bar(ctx: &mut EventCtx, filled_color: Color, pct_full: f64, txt: Text) -> Widget {\n\n let total_width = 300.0;\n\n let height = 32.0;\n\n let radius = 4.0;\n\n\n\n let mut batch = GeomBatch::new();\n\n // Background\n\n batch.push(\n\n Color::hex(\"#666666\"),\n\n Polygon::rounded_rectangle(total_width, height, radius),\n\n );\n\n // Foreground\n\n if let Some(poly) = Polygon::maybe_rounded_rectangle(pct_full * total_width, height, radius) {\n\n batch.push(filled_color, poly);\n\n }\n\n // Text\n\n let label = txt.render_autocropped(ctx);\n\n let dims = label.get_dims();\n\n batch.append(label.translate(10.0, height / 2.0 - dims.height / 2.0));\n\n Widget::draw_batch(ctx, batch)\n\n}\n\n\n", "file_path": "santa/src/meters.rs", "rank": 39, "score": 327815.13081194006 }, { "content": "/// Extract the map and scenario name from a path. Crashes if the input is strange.\n\npub fn parse_scenario_path(path: &str) -> (MapName, String) {\n\n // TODO regex\n\n let parts = path.split(\"/\").collect::<Vec<_>>();\n\n let country = parts[parts.len() - 5];\n\n let city = parts[parts.len() - 4];\n\n let map = parts[parts.len() - 2];\n\n let scenario = basename(parts[parts.len() - 1]);\n\n let map_name = MapName::new(country, city, map);\n\n (map_name, scenario)\n\n}\n\n\n\n// Player data (Players edit this)\n\n\n", "file_path": "abstio/src/abst_paths.rs", "rank": 40, "score": 327616.9545463269 }, { "content": "pub fn area(ctx: &EventCtx, app: &App, _: &mut Details, id: AreaID) -> Vec<Widget> {\n\n let mut rows = vec![];\n\n\n\n rows.push(Widget::row(vec![\n\n Line(id.to_string()).small_heading().draw(ctx),\n\n header_btns(ctx),\n\n ]));\n\n\n\n let area = app.primary.map.get_a(id);\n\n\n\n if let Some(osm_id) = area.osm_id {\n\n rows.push(\n\n ctx.style()\n\n .btn_solid_dark_text(\"Open in OSM\")\n\n .build_widget(ctx, &format!(\"open {}\", osm_id)),\n\n );\n\n }\n\n\n\n rows.extend(make_table(\n\n ctx,\n\n area.osm_tags\n\n .inner()\n\n .iter()\n\n .map(|(k, v)| (k.to_string(), v.to_string()))\n\n .collect(),\n\n ));\n\n\n\n rows\n\n}\n", "file_path": "game/src/info/debug.rs", "rank": 41, "score": 326426.27610258193 }, { "content": "pub fn path_all_saves(name: &MapName, edits_name: &str, run_name: &str) -> String {\n\n path(format!(\n\n \"player/saves/{}/{}/{}/{}_{}\",\n\n name.city.country, name.city.city, name.map, edits_name, run_name\n\n ))\n\n}\n\n\n\n// Input data (For developers to build maps, not needed at runtime)\n\n\n", "file_path": "abstio/src/abst_paths.rs", "rank": 42, "score": 325316.1249809446 }, { "content": "pub fn info(ctx: &EventCtx, app: &App, details: &mut Details, id: LaneID) -> Vec<Widget> {\n\n let mut rows = header(ctx, app, details, id, Tab::LaneInfo(id));\n\n let map = &app.primary.map;\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n let mut kv = Vec::new();\n\n\n\n if !l.is_walkable() {\n\n kv.push((\"Type\", l.lane_type.describe().to_string()));\n\n }\n\n if r.is_private() {\n\n let mut ban = Vec::new();\n\n for p in PathConstraints::all() {\n\n if !r.access_restrictions.allow_through_traffic.contains(p) {\n\n ban.push(format!(\"{:?}\", p).to_ascii_lowercase());\n\n }\n\n }\n\n if !ban.is_empty() {\n\n kv.push((\"No through-traffic for\", ban.join(\", \")));\n", "file_path": "game/src/info/lane.rs", "rank": 43, "score": 323545.93315314094 }, { "content": "pub fn info(ctx: &EventCtx, app: &App, details: &mut Details, id: IntersectionID) -> Vec<Widget> {\n\n let mut rows = header(ctx, app, details, id, Tab::IntersectionInfo(id));\n\n let i = app.primary.map.get_i(id);\n\n\n\n let mut txt = Text::from(Line(\"Connecting\"));\n\n let mut road_names = BTreeSet::new();\n\n for r in &i.roads {\n\n road_names.insert(\n\n app.primary\n\n .map\n\n .get_r(*r)\n\n .get_name(app.opts.language.as_ref()),\n\n );\n\n }\n\n for r in road_names {\n\n txt.add(Line(format!(\" {}\", r)));\n\n }\n\n rows.push(txt.draw(ctx));\n\n\n\n if app.opts.dev {\n\n rows.push(\n\n ctx.style()\n\n .btn_solid_dark_text(\"Open OSM node\")\n\n .build_widget(ctx, &format!(\"open {}\", i.orig_id)),\n\n );\n\n }\n\n\n\n rows\n\n}\n\n\n", "file_path": "game/src/info/intersection.rs", "rank": 44, "score": 323545.93315314094 }, { "content": "pub fn debug(ctx: &EventCtx, app: &App, details: &mut Details, id: LaneID) -> Vec<Widget> {\n\n let mut rows = header(ctx, app, details, id, Tab::LaneDebug(id));\n\n let map = &app.primary.map;\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n let mut kv = Vec::new();\n\n\n\n kv.push((\"Parent\".to_string(), r.id.to_string()));\n\n\n\n if l.lane_type.is_for_moving_vehicles() {\n\n kv.push((\n\n \"Driving blackhole\".to_string(),\n\n l.driving_blackhole.to_string(),\n\n ));\n\n kv.push((\n\n \"Biking blackhole\".to_string(),\n\n l.biking_blackhole.to_string(),\n\n ));\n\n }\n", "file_path": "game/src/info/lane.rs", "rank": 45, "score": 323545.93315314094 }, { "content": "// Recursively walks the entire JSON object. Will call transform on all of the map objects. If the\n\n// callback returns true, won't recurse into that map.\n\nfn walk<F: Fn(&mut serde_json::Map<String, Value>) -> bool>(value: &mut Value, transform: &F) {\n\n match value {\n\n Value::Array(list) => {\n\n for x in list {\n\n walk(x, transform);\n\n }\n\n }\n\n Value::Object(map) => {\n\n if !(transform)(map) {\n\n for x in map.values_mut() {\n\n walk(x, transform);\n\n }\n\n }\n\n }\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "map_model/src/edits/compat.rs", "rank": 46, "score": 323043.17546219355 }, { "content": "/// If the output file doesn't already exist, downloads the URL into that location. Automatically\n\n/// uncompresses .zip and .gz files. Assumes a proper path is passed in (including data/).\n\npub fn download(config: &ImporterConfiguration, output: String, url: &str) {\n\n if Path::new(&output).exists() {\n\n println!(\"- {} already exists\", output);\n\n return;\n\n }\n\n // Create the directory\n\n std::fs::create_dir_all(Path::new(&output).parent().unwrap())\n\n .expect(\"Creating parent dir failed\");\n\n\n\n let tmp = \"tmp_output\";\n\n println!(\"- Missing {}, so downloading {}\", output, url);\n\n must_run_cmd(\n\n Command::new(\"curl\")\n\n .arg(\"--fail\")\n\n .arg(\"-L\")\n\n .arg(\"-o\")\n\n .arg(tmp)\n\n .arg(url),\n\n );\n\n\n", "file_path": "importer/src/utils.rs", "rank": 47, "score": 321740.8806711311 }, { "content": "fn make_pagination(ctx: &mut EventCtx, total: usize, skip: usize) -> Widget {\n\n let next = ctx\n\n .style()\n\n .btn_next()\n\n .disabled(skip + 1 + ROWS >= total)\n\n .hotkey(Key::RightArrow);\n\n let prev = ctx\n\n .style()\n\n .btn_prev()\n\n .disabled(skip == 0)\n\n .hotkey(Key::LeftArrow);\n\n\n\n Widget::row(vec![\n\n prev.build_widget(ctx, \"previous\"),\n\n format!(\n\n \"{}-{} of {}\",\n\n if total > 0 {\n\n prettyprint_usize(skip + 1)\n\n } else {\n\n \"0\".to_string()\n\n },\n\n prettyprint_usize((skip + 1 + ROWS).min(total)),\n\n prettyprint_usize(total)\n\n )\n\n .draw_text(ctx)\n\n .centered_vert(),\n\n next.build_widget(ctx, \"next\"),\n\n ])\n\n}\n\n\n", "file_path": "widgetry/src/widgets/table.rs", "rank": 48, "score": 320678.4085589547 }, { "content": "pub fn path_edits(name: &MapName, edits_name: &str) -> String {\n\n path(format!(\n\n \"player/edits/{}/{}/{}/{}.json\",\n\n name.city.country, name.city.city, name.map, edits_name\n\n ))\n\n}\n", "file_path": "abstio/src/abst_paths.rs", "rank": 49, "score": 319097.20970091154 }, { "content": "pub fn path_scenario(name: &MapName, scenario_name: &str) -> String {\n\n // TODO Getting complicated. Sometimes we're trying to load, so we should look for .bin, then\n\n // .json. But when we're writing a custom scenario, we actually want to write a .bin.\n\n let bin = path(format!(\n\n \"system/{}/{}/scenarios/{}/{}.bin\",\n\n name.city.country, name.city.city, name.map, scenario_name\n\n ));\n\n let json = path(format!(\n\n \"system/{}/{}/scenarios/{}/{}.json\",\n\n name.city.country, name.city.city, name.map, scenario_name\n\n ));\n\n if file_exists(&bin) {\n\n return bin;\n\n }\n\n if file_exists(&json) {\n\n return json;\n\n }\n\n bin\n\n}\n", "file_path": "abstio/src/abst_paths.rs", "rank": 50, "score": 319097.20970091154 }, { "content": "pub fn path_prebaked_results(name: &MapName, scenario_name: &str) -> String {\n\n path(format!(\n\n \"system/{}/{}/prebaked_results/{}/{}.bin\",\n\n name.city.country, name.city.city, name.map, scenario_name\n\n ))\n\n}\n\n\n", "file_path": "abstio/src/abst_paths.rs", "rank": 51, "score": 315669.9869282355 }, { "content": "fn setup_texture_demo(ctx: &mut EventCtx, bg_texture: Texture, fg_texture: Texture) -> Drawable {\n\n let mut batch = GeomBatch::new();\n\n\n\n let mut rect = Polygon::rectangle(100.0, 100.0);\n\n rect = rect.translate(200.0, 900.0);\n\n // Texture::NOOP should always be pure white, since all \"non-textured\" colors are multiplied by\n\n // Texture::NOOP (Texture::NOOP.0 == 0)\n\n batch.push(Texture::NOOP, rect);\n\n\n\n let triangle = geom::Triangle {\n\n pt1: Pt2D::new(0.0, 100.0),\n\n pt2: Pt2D::new(50.0, 0.0),\n\n pt3: Pt2D::new(100.0, 100.0),\n\n };\n\n let mut triangle_poly = Polygon::from_triangle(&triangle);\n\n triangle_poly = triangle_poly.translate(400.0, 900.0);\n\n batch.push(bg_texture, triangle_poly);\n\n\n\n let circle = geom::Circle::new(Pt2D::new(50.0, 50.0), geom::Distance::meters(50.0));\n\n let mut circle_poly = circle.to_polygon();\n\n circle_poly = circle_poly.translate(600.0, 900.0);\n\n batch.push(\n\n Fill::ColoredTexture(Color::RED, bg_texture),\n\n circle_poly.clone(),\n\n );\n\n batch.push(fg_texture, circle_poly.clone());\n\n\n\n batch.upload(ctx)\n\n}\n\n\n", "file_path": "widgetry_demo/src/lib.rs", "rank": 52, "score": 311449.23429008294 }, { "content": "/// Make it clear the map can't be interacted with right now.\n\npub fn grey_out_map(g: &mut GfxCtx, app: &dyn AppLike) {\n\n g.fork_screenspace();\n\n // TODO - OSD height\n\n g.draw_polygon(\n\n app.cs().fade_map_dark,\n\n Polygon::rectangle(g.canvas.window_width, g.canvas.window_height),\n\n );\n\n g.unfork();\n\n}\n\n\n", "file_path": "map_gui/src/tools/mod.rs", "rank": 53, "score": 310583.28694146127 }, { "content": "fn mouseover_unzoomed_agent_circle(ctx: &mut EventCtx, app: &mut App) {\n\n let cursor = if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {\n\n pt\n\n } else {\n\n return;\n\n };\n\n\n\n for (id, _, _) in app\n\n .primary\n\n .agents\n\n .borrow_mut()\n\n .calculate_unzoomed_agents(ctx, app)\n\n .query(\n\n Circle::new(cursor, Distance::meters(3.0))\n\n .get_bounds()\n\n .as_bbox(),\n\n )\n\n {\n\n if let Some(pt) = app\n\n .primary\n\n .sim\n\n .canonical_pt_for_agent(*id, &app.primary.map)\n\n {\n\n if Circle::new(pt, unzoomed_agent_radius(id.to_vehicle_type())).contains_pt(cursor) {\n\n app.primary.current_selection = Some(ID::from_agent(*id));\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "game/src/sandbox/mod.rs", "rank": 54, "score": 310429.79906642623 }, { "content": "fn explain_upzoning(ctx: &mut EventCtx) -> Transition {\n\n Transition::Push(PopupMsg::new(\n\n ctx,\n\n \"Upzoning power unlocked\",\n\n vec![\n\n \"It's hard to deliver to houses far away from shops, isn't it?\",\n\n \"You've gained the power to change the zoning code for a residential building.\",\n\n \"You can now transform a single-family house into a multi-use building,\",\n\n \"with shops on the ground floor, and people living above.\",\n\n \"\",\n\n \"Where should you place the new store?\",\n\n ],\n\n ))\n\n}\n", "file_path": "santa/src/before_level.rs", "rank": 55, "score": 309680.91035423934 }, { "content": "pub fn osm_to_raw(name: &str, timer: &mut Timer, config: &ImporterConfiguration) {\n\n let city = CityName::new(\"us\", \"seattle\");\n\n\n\n input(config, timer);\n\n osmconvert(\n\n city.input_path(\"osm/washington-latest.osm.pbf\"),\n\n format!(\"importer/config/us/seattle/{}.poly\", name),\n\n city.input_path(format!(\"osm/{}.osm\", name)),\n\n config,\n\n );\n\n\n\n let map = convert_osm::convert(\n\n convert_osm::Options {\n\n osm_input: city.input_path(format!(\"osm/{}.osm\", name)),\n\n name: MapName::seattle(name),\n\n\n\n clip: Some(format!(\"importer/config/us/seattle/{}.poly\", name)),\n\n map_config: map_model::MapConfig {\n\n driving_side: map_model::DrivingSide::Right,\n\n bikes_can_use_bus_lanes: true,\n", "file_path": "importer/src/seattle.rs", "rank": 56, "score": 309478.37128844217 }, { "content": "pub fn retain_btreeset<K: Ord + Clone, F: FnMut(&K) -> bool>(set: &mut BTreeSet<K>, mut keep: F) {\n\n let mut remove: Vec<K> = Vec::new();\n\n for k in set.iter() {\n\n if !keep(k) {\n\n remove.push(k.clone());\n\n }\n\n }\n\n for k in remove {\n\n set.remove(&k);\n\n }\n\n}\n\n\n", "file_path": "abstutil/src/collections.rs", "rank": 57, "score": 306528.6127007365 }, { "content": "/// Match OSM buildings to parcels, scraping the number of housing units.\n\n// TODO It's expensive to load the huge zoning_parcels.bin file for every map.\n\npub fn match_parcels_to_buildings(map: &mut Map, timer: &mut Timer) {\n\n let shapes: ExtraShapes = abstio::read_binary(\n\n CityName::new(\"us\", \"seattle\").input_path(\"zoning_parcels.bin\"),\n\n timer,\n\n );\n\n let mut parcels_with_housing: Vec<(Polygon, usize)> = Vec::new();\n\n // TODO We should refactor something like FindClosest, but for polygon containment\n\n // The quadtree's ID is just an index into parcels_with_housing.\n\n let mut quadtree: QuadTree<usize> = QuadTree::default(map.get_bounds().as_bbox());\n\n timer.start_iter(\"index all parcels\", shapes.shapes.len());\n\n for shape in shapes.shapes {\n\n timer.next();\n\n if let Some(units) = shape\n\n .attributes\n\n .get(\"EXIST_UNITS\")\n\n .and_then(|x| x.parse::<usize>().ok())\n\n {\n\n if let Some(ring) = map\n\n .get_gps_bounds()\n\n .try_convert(&shape.points)\n", "file_path": "importer/src/seattle.rs", "rank": 58, "score": 305556.0180985706 }, { "content": "pub fn read_binary<T: DeserializeOwned>(path: String, timer: &mut Timer) -> T {\n\n match maybe_read_binary(path.clone(), timer) {\n\n Ok(obj) => obj,\n\n Err(err) => panic!(\"Couldn't read_binary({}): {}\", path, err),\n\n }\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 59, "score": 301759.71351466264 }, { "content": "pub fn read_json<T: DeserializeOwned>(path: String, timer: &mut Timer) -> T {\n\n match maybe_read_json(path.clone(), timer) {\n\n Ok(obj) => obj,\n\n Err(err) => panic!(\"Couldn't read_json({}): {}\", path, err),\n\n }\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 60, "score": 301759.71351466264 }, { "content": "fn export_for_leaflet(ctx: &mut EventCtx, app: &App) {\n\n let name = app.primary.map.get_name();\n\n let bounds = app.primary.map.get_bounds();\n\n let map_length = bounds.width().max(bounds.height());\n\n\n\n // At zoom level N, the entire map fits into (N + 1) * (N + 1) tiles\n\n for zoom_level in 0..=25 {\n\n let num_tiles = zoom_level + 1;\n\n // How do we fit the entire map_length into this many tiles?\n\n let zoom = 256.0 * (num_tiles as f64) / map_length;\n\n ctx.request_update(UpdateType::ScreenCaptureEverything {\n\n dir: format!(\n\n \"screenshots/{}/{}/{}/{}\",\n\n name.city.country, name.city.city, name.map, zoom_level\n\n ),\n\n zoom,\n\n dims: ScreenDims::new(256.0, 256.0),\n\n leaflet_naming: true,\n\n });\n\n }\n\n}\n", "file_path": "game/src/debug/mod.rs", "rank": 61, "score": 298786.1678156906 }, { "content": "/// May be a JSON or binary file. Panics on failure.\n\npub fn must_read_object<T: DeserializeOwned>(path: String, timer: &mut Timer) -> T {\n\n match read_object(path.clone(), timer) {\n\n Ok(obj) => obj,\n\n Err(err) => panic!(\"Couldn't read_object({}): {}\", path, err),\n\n }\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 62, "score": 298463.5399659474 }, { "content": "pub fn angle_from_arrow_keys(ctx: &EventCtx) -> Option<Angle> {\n\n let mut x: f64 = 0.0;\n\n let mut y: f64 = 0.0;\n\n if ctx.is_key_down(Key::LeftArrow) || ctx.is_key_down(Key::A) {\n\n x -= 1.0;\n\n }\n\n if ctx.is_key_down(Key::RightArrow) || ctx.is_key_down(Key::D) {\n\n x += 1.0;\n\n }\n\n if ctx.is_key_down(Key::UpArrow) || ctx.is_key_down(Key::W) {\n\n y -= 1.0;\n\n }\n\n if ctx.is_key_down(Key::DownArrow) || ctx.is_key_down(Key::S) {\n\n y += 1.0;\n\n }\n\n\n\n if x == 0.0 && y == 0.0 {\n\n return None;\n\n }\n\n Some(Angle::new_rads(y.atan2(x)))\n\n}\n", "file_path": "santa/src/controls.rs", "rank": 63, "score": 297831.30434566934 }, { "content": "fn use_elevation(map: &mut RawMap, path: &str, timer: &mut Timer) {\n\n timer.start(\"apply elevation data to intersections\");\n\n let elevation = srtm::Elevation::load(path).unwrap();\n\n for i in map.intersections.values_mut() {\n\n // TODO Not sure why, but I've seen nodes from South Carolina wind up in the updated\n\n // Seattle extract. And I think there's a bug with clipping, because they survive to this\n\n // point. O_O\n\n if map.boundary_polygon.contains_pt(i.point) {\n\n i.elevation = elevation.get(i.point.to_gps(&map.gps_bounds));\n\n }\n\n }\n\n timer.stop(\"apply elevation data to intersections\");\n\n}\n\n\n", "file_path": "convert_osm/src/lib.rs", "rank": 64, "score": 297592.0664002249 }, { "content": "// TODO Can we automatically transform text and SVG colors?\n\nfn cutscene_pt1_task(ctx: &mut EventCtx) -> Widget {\n\n Widget::custom_col(vec![\n\n Text::from_multiline(vec![\n\n Line(format!(\n\n \"Don't let anyone be delayed by one traffic signal more than {}!\",\n\n THRESHOLD\n\n ))\n\n .fg(Color::BLACK),\n\n Line(\"Survive as long as possible through 24 hours of a busy weekday.\")\n\n .fg(Color::BLACK),\n\n ])\n\n .draw(ctx)\n\n .margin_below(30),\n\n Widget::custom_row(vec![\n\n Widget::col(vec![\n\n Line(\"Time\").fg(Color::BLACK).draw(ctx),\n\n Widget::draw_svg_transform(\n\n ctx,\n\n \"system/assets/tools/time.svg\",\n\n RewriteColor::ChangeAll(Color::BLACK),\n", "file_path": "game/src/sandbox/gameplay/fix_traffic_signals.rs", "rank": 65, "score": 296515.4011339387 }, { "content": "/// May be a JSON or binary file\n\npub fn read_object<T: DeserializeOwned>(path: String, timer: &mut Timer) -> Result<T> {\n\n if path.ends_with(\".bin\") {\n\n maybe_read_binary(path, timer)\n\n } else {\n\n maybe_read_json(path, timer)\n\n }\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 66, "score": 294666.32690765685 }, { "content": "fn use_parking_hints(map: &mut RawMap, path: String, timer: &mut Timer) {\n\n timer.start(\"apply parking hints\");\n\n let shapes: ExtraShapes = abstio::read_binary(path, timer);\n\n\n\n // Match shapes with the nearest road + direction (true for forwards)\n\n let mut closest: FindClosest<(OriginalRoad, bool)> =\n\n FindClosest::new(&map.gps_bounds.to_bounds());\n\n for (id, r) in &map.roads {\n\n if r.is_light_rail() || r.is_footway() || r.is_service() {\n\n continue;\n\n }\n\n let center = PolyLine::must_new(r.center_points.clone());\n\n closest.add(\n\n (*id, true),\n\n center.must_shift_right(DIRECTED_ROAD_THICKNESS).points(),\n\n );\n\n closest.add(\n\n (*id, false),\n\n center.must_shift_left(DIRECTED_ROAD_THICKNESS).points(),\n\n );\n", "file_path": "convert_osm/src/parking.rs", "rank": 67, "score": 294143.104104002 }, { "content": "fn use_offstreet_parking(map: &mut RawMap, path: String, timer: &mut Timer) {\n\n timer.start(\"match offstreet parking points\");\n\n let shapes: ExtraShapes = abstio::read_binary(path, timer);\n\n\n\n let mut closest: FindClosest<osm::OsmID> = FindClosest::new(&map.gps_bounds.to_bounds());\n\n for (id, b) in &map.buildings {\n\n closest.add(*id, b.polygon.points());\n\n }\n\n\n\n // TODO Another function just to use ?. Try blocks would rock.\n\n let mut handle_shape: Box<dyn FnMut(kml::ExtraShape) -> Option<()>> = Box::new(|s| {\n\n assert_eq!(s.points.len(), 1);\n\n let pt = s.points[0].to_pt(&map.gps_bounds);\n\n let (id, _) = closest.closest_pt(pt, Distance::meters(50.0))?;\n\n // TODO Handle parking lots.\n\n if !map.buildings[&id].polygon.contains_pt(pt) {\n\n return None;\n\n }\n\n let name = s.attributes.get(\"DEA_FACILITY_NAME\")?.to_string();\n\n let num_stalls = s.attributes.get(\"DEA_STALLS\")?.parse::<usize>().ok()?;\n", "file_path": "convert_osm/src/parking.rs", "rank": 68, "score": 294143.104104002 }, { "content": "pub fn maybe_read_json<T: DeserializeOwned>(path: String, timer: &mut Timer) -> Result<T> {\n\n if !path.ends_with(\".json\") && !path.ends_with(\".geojson\") {\n\n panic!(\"read_json needs {} to end with .json or .geojson\", path);\n\n }\n\n\n\n timer.start(format!(\"parse {}\", path));\n\n // TODO timer.read_file isn't working here. And we need to call stop() if there's no file.\n\n let result: Result<T> =\n\n slurp_file(&path).and_then(|raw| serde_json::from_slice(&raw).map_err(|err| err.into()));\n\n timer.stop(format!(\"parse {}\", path));\n\n result\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 69, "score": 291491.7813566987 }, { "content": "pub fn maybe_read_binary<T: DeserializeOwned>(path: String, _: &mut Timer) -> Result<T> {\n\n if let Some(raw) = SYSTEM_DATA.get_file(path.trim_start_matches(\"../data/system/\")) {\n\n bincode::deserialize(raw.contents()).map_err(|err| err.into())\n\n } else {\n\n bail!(\"Can't maybe_read_binary {}, it doesn't exist\", path)\n\n }\n\n}\n\n\n", "file_path": "abstio/src/io_web.rs", "rank": 70, "score": 291491.78135669866 }, { "content": "fn make_table<I: Into<String>>(ctx: &EventCtx, rows: Vec<(I, String)>) -> Vec<Widget> {\n\n rows.into_iter()\n\n .map(|(k, v)| {\n\n Widget::row(vec![\n\n Line(k).secondary().draw(ctx),\n\n // TODO not quite...\n\n v.draw_text(ctx).centered_vert().align_right(),\n\n ])\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "game/src/info/mod.rs", "rank": 71, "score": 291418.23183287284 }, { "content": "fn draw_star(ctx: &mut EventCtx, b: &Building) -> GeomBatch {\n\n GeomBatch::load_svg(ctx, \"system/assets/tools/star.svg\")\n\n .centered_on(b.polygon.center())\n\n .color(RewriteColor::ChangeAll(Color::BLACK))\n\n}\n\n\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 72, "score": 291181.87186654564 }, { "content": "fn options_to_controls(ctx: &mut EventCtx, opts: &Options) -> Widget {\n\n let mut rows = vec![Checkbox::toggle(\n\n ctx,\n\n \"walking / biking\",\n\n \"walking\",\n\n \"biking\",\n\n None,\n\n match opts {\n\n Options::Walking(_) => true,\n\n Options::Biking => false,\n\n },\n\n )];\n\n match opts {\n\n Options::Walking(ref opts) => {\n\n rows.push(Checkbox::switch(\n\n ctx,\n\n \"Allow walking on the shoulder of the road without a sidewalk\",\n\n None,\n\n opts.allow_shoulders,\n\n ));\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 73, "score": 291181.87186654564 }, { "content": "#[allow(non_snake_case)]\n\npub fn Line<S: Into<String>>(text: S) -> TextSpan {\n\n TextSpan {\n\n text: text.into(),\n\n fg_color: DEFAULT_FG_COLOR,\n\n size: DEFAULT_FONT_SIZE,\n\n font: DEFAULT_FONT,\n\n underlined: false,\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Text {\n\n // The bg_color will cover the entire block, but some lines can have extra highlighting.\n\n lines: Vec<(Option<Color>, Vec<TextSpan>)>,\n\n // TODO Stop using this as much as possible.\n\n bg_color: Option<Color>,\n\n}\n\n\n\nimpl Text {\n\n pub fn new() -> Text {\n", "file_path": "widgetry/src/text.rs", "rank": 74, "score": 288912.5816162314 }, { "content": "pub fn read(path: &str, input_gps_bounds: &GPSBounds, timer: &mut Timer) -> Result<Document> {\n\n timer.start(format!(\"read {}\", path));\n\n let bytes = slurp_file(path)?;\n\n let raw_string = std::str::from_utf8(&bytes)?;\n\n let tree = roxmltree::Document::parse(raw_string)?;\n\n timer.stop(format!(\"read {}\", path));\n\n\n\n let mut doc = Document {\n\n gps_bounds: input_gps_bounds.clone(),\n\n nodes: BTreeMap::new(),\n\n ways: BTreeMap::new(),\n\n relations: BTreeMap::new(),\n\n };\n\n\n\n timer.start(\"scrape objects\");\n\n for obj in tree.descendants() {\n\n if !obj.is_element() {\n\n continue;\n\n }\n\n match obj.tag_name().name() {\n", "file_path": "convert_osm/src/reader.rs", "rank": 75, "score": 288670.351620857 }, { "content": "fn make_btn(ctx: &mut EventCtx, num: usize) -> Widget {\n\n let title = match num {\n\n 0 => \"Record 0 intersections\".to_string(),\n\n 1 => \"Record 1 intersection\".to_string(),\n\n _ => format!(\"Record {} intersections\", num),\n\n };\n\n ctx.style()\n\n .btn_solid_dark_text(&title)\n\n .disabled(num == 0)\n\n .hotkey(Key::Enter)\n\n .build_widget(ctx, \"record\")\n\n}\n", "file_path": "game/src/sandbox/misc_tools.rs", "rank": 76, "score": 288646.17325782566 }, { "content": "pub fn maybe_read_binary<T: DeserializeOwned>(path: String, timer: &mut Timer) -> Result<T> {\n\n if !path.ends_with(\".bin\") {\n\n panic!(\"read_binary needs {} to end with .bin\", path);\n\n }\n\n\n\n timer.read_file(&path)?;\n\n bincode::deserialize_from(timer).map_err(|err| err.into())\n\n}\n\n\n", "file_path": "abstio/src/io_native.rs", "rank": 77, "score": 288432.2536941533 }, { "content": "pub fn list_names<F: Fn(TextSpan) -> TextSpan>(txt: &mut Text, styler: F, names: BTreeSet<String>) {\n\n let len = names.len();\n\n for (idx, n) in names.into_iter().enumerate() {\n\n if idx != 0 {\n\n if idx == len - 1 {\n\n if len == 2 {\n\n txt.append(Line(\" and \"));\n\n } else {\n\n txt.append(Line(\", and \"));\n\n }\n\n } else {\n\n txt.append(Line(\", \"));\n\n }\n\n }\n\n txt.append(styler(Line(n)));\n\n }\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 78, "score": 288075.34368212824 }, { "content": "fn make_btn(ctx: &mut EventCtx, num: usize) -> Widget {\n\n let title = match num {\n\n 0 => \"Edit 0 signals\".to_string(),\n\n 1 => \"Edit 1 signal\".to_string(),\n\n _ => format!(\"Edit {} signals\", num),\n\n };\n\n ctx.style()\n\n .btn_solid_dark_text(&title)\n\n .disabled(num == 0)\n\n .hotkey(hotkeys(vec![Key::Enter, Key::E]))\n\n .build_widget(ctx, \"edit\")\n\n}\n", "file_path": "game/src/edit/traffic_signals/picker.rs", "rank": 79, "score": 286197.6809861625 }, { "content": "fn calc_all_routes(ctx: &EventCtx, app: &mut App) -> (usize, Drawable) {\n\n let agents = app.primary.sim.active_agents();\n\n let mut batch = GeomBatch::new();\n\n let mut cnt = 0;\n\n let sim = &app.primary.sim;\n\n let map = &app.primary.map;\n\n for maybe_trace in Timer::new(\"calculate all routes\").parallelize(\n\n \"route to geometry\",\n\n Parallelism::Fastest,\n\n agents,\n\n |id| {\n\n sim.trace_route(id, map)\n\n .map(|trace| trace.make_polygons(NORMAL_LANE_THICKNESS))\n\n },\n\n ) {\n\n if let Some(t) = maybe_trace {\n\n cnt += 1;\n\n batch.push(app.cs.route, t);\n\n }\n\n }\n\n (cnt, ctx.upload(batch))\n\n}\n\n\n", "file_path": "game/src/debug/mod.rs", "rank": 80, "score": 283998.2996347357 }, { "content": "pub fn load_svg(prerender: &Prerender, filename: &str) -> (GeomBatch, Bounds) {\n\n let cache_key = format!(\"file://{}\", filename);\n\n if let Some(pair) = prerender.assets.get_cached_svg(&cache_key) {\n\n return pair;\n\n }\n\n\n\n let bytes = (prerender.assets.read_svg)(filename);\n\n load_svg_from_bytes_uncached(&bytes)\n\n .map(|(batch, bounds)| {\n\n prerender\n\n .assets\n\n .cache_svg(cache_key, batch.clone(), bounds.clone());\n\n (batch, bounds)\n\n })\n\n .expect(&format!(\"error loading svg: {}\", filename))\n\n}\n\n\n", "file_path": "widgetry/src/svg.rs", "rank": 81, "score": 281629.4116159361 }, { "content": "fn intro_story(ctx: &mut EventCtx) -> Box<dyn State<App>> {\n\n CutsceneBuilder::new(\"Introduction\")\n\n .boss(\n\n \"Argh, the mayor's on my case again about the West Seattle bridge. This day couldn't \\\n\n get any worse.\",\n\n )\n\n .player(\"Er, hello? Boss? I'm --\")\n\n .boss(\"Yet somehow it did.. You're the new recruit. Yeah, yeah. Come in.\")\n\n .boss(\n\n \"Due to budget cuts, we couldn't hire a real traffic engineer, so we just called some \\\n\n know-it-all from Reddit who seems to think they can fix Seattle traffic.\",\n\n )\n\n .player(\"Yes, hi, my name is --\")\n\n .boss(\"We can't afford name-tags, didn't you hear, budget cuts? Your name doesn't matter.\")\n\n .player(\"What about my Insta handle?\")\n\n .boss(\"-glare-\")\n\n .boss(\n\n \"Look, you think fixing traffic is easy? Hah! You can't fix one intersection without \\\n\n breaking ten more.\",\n\n )\n", "file_path": "game/src/sandbox/gameplay/tutorial.rs", "rank": 82, "score": 281549.80736307247 }, { "content": "pub fn retain_btreemap<K: Ord + Clone, V, F: FnMut(&K, &V) -> bool>(\n\n map: &mut BTreeMap<K, V>,\n\n mut keep: F,\n\n) {\n\n let mut remove_keys: Vec<K> = Vec::new();\n\n for (k, v) in map.iter() {\n\n if !keep(k, v) {\n\n remove_keys.push(k.clone());\n\n }\n\n }\n\n for k in remove_keys {\n\n map.remove(&k);\n\n }\n\n}\n\n\n", "file_path": "abstutil/src/collections.rs", "rank": 83, "score": 276874.2908238615 }, { "content": "/// Just list all things from a directory, return sorted by name, with file extension removed.\n\npub fn list_all_objects(dir: String) -> Vec<String> {\n\n list_dir(dir).into_iter().map(basename).collect()\n\n}\n", "file_path": "abstio/src/io.rs", "rank": 84, "score": 275301.3407820455 }, { "content": "fn draw_unwalkable_roads(ctx: &mut EventCtx, app: &App, opts: &Options) -> Drawable {\n\n let allow_shoulders = match opts {\n\n Options::Walking(ref opts) => opts.allow_shoulders,\n\n Options::Biking => {\n\n return Drawable::empty(ctx);\n\n }\n\n };\n\n\n\n let mut batch = GeomBatch::new();\n\n 'ROADS: for road in app.map.all_roads() {\n\n if road.is_light_rail() {\n\n continue;\n\n }\n\n for (_, _, lt) in road.lanes_ltr() {\n\n if lt == LaneType::Sidewalk || (lt == LaneType::Shoulder && allow_shoulders) {\n\n continue 'ROADS;\n\n }\n\n }\n\n // TODO Skip highways\n\n batch.push(Color::BLUE.alpha(0.5), road.get_thick_polygon(&app.map));\n\n }\n\n ctx.upload(batch)\n\n}\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 85, "score": 274833.2008347599 }, { "content": "fn scatter_plot(ctx: &mut EventCtx, app: &App, filter: &Filter) -> Widget {\n\n if app.has_prebaked().is_none() {\n\n return Widget::nothing();\n\n }\n\n\n\n let points = filter.get_trips(app);\n\n if points.is_empty() {\n\n return Widget::nothing();\n\n }\n\n\n\n Widget::col(vec![\n\n Line(\"Trip time before and after\").small_heading().draw(ctx),\n\n CompareTimes::new(\n\n ctx,\n\n format!(\n\n \"Trip time before \\\"{}\\\"\",\n\n app.primary.map.get_edits().edits_name\n\n ),\n\n format!(\n\n \"Trip time after \\\"{}\\\"\",\n\n app.primary.map.get_edits().edits_name\n\n ),\n\n points,\n\n ),\n\n ])\n\n .padding(16)\n\n .outline(2.0, Color::WHITE)\n\n}\n\n\n", "file_path": "game/src/sandbox/dashboards/summaries.rs", "rank": 86, "score": 274833.20083475986 }, { "content": "fn summary_boxes(ctx: &mut EventCtx, app: &App, filter: &Filter) -> Widget {\n\n if app.has_prebaked().is_none() {\n\n return Widget::nothing();\n\n }\n\n\n\n let mut num_same = 0;\n\n let mut num_faster = 0;\n\n let mut num_slower = 0;\n\n let mut sum_faster = Duration::ZERO;\n\n let mut sum_slower = Duration::ZERO;\n\n for (_, b, a, mode) in app\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .both_finished_trips(app.primary.sim.time(), app.prebaked())\n\n {\n\n if !filter.modes.contains(&mode) {\n\n continue;\n\n }\n\n let same = if let Some(pct) = filter.changes_pct {\n", "file_path": "game/src/sandbox/dashboards/summaries.rs", "rank": 87, "score": 274833.20083475986 }, { "content": "fn contingency_table(ctx: &mut EventCtx, app: &App, filter: &Filter) -> Widget {\n\n if app.has_prebaked().is_none() {\n\n return Widget::nothing();\n\n }\n\n\n\n let total_width = 500.0;\n\n let total_height = 300.0;\n\n\n\n let points = filter.get_trips(app);\n\n if points.is_empty() {\n\n return Widget::nothing();\n\n }\n\n let num_buckets = 10;\n\n let (_, endpts) = points\n\n .iter()\n\n .map(|(b, a)| a.max(b))\n\n .max()\n\n .unwrap()\n\n .make_intervals_for_max(num_buckets);\n\n\n", "file_path": "game/src/sandbox/dashboards/summaries.rs", "rank": 88, "score": 274833.20083475986 }, { "content": "pub fn path<I: Into<String>>(p: I) -> String {\n\n let p = p.into();\n\n if p.starts_with(\"player/\") {\n\n format!(\"{}/{}\", *ROOT_PLAYER_DIR, p)\n\n } else {\n\n format!(\"{}/{}\", *ROOT_DIR, p)\n\n }\n\n}\n\n\n\n/// A single city is identified using this.\n\n#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]\n\npub struct CityName {\n\n /// A two letter lowercase country code, from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2.\n\n /// To represent imaginary/test cities, use the code `zz`.\n\n pub country: String,\n\n /// The name of the city, in filename-friendly form -- for example, \"tel_aviv\".\n\n pub city: String,\n\n}\n\n\n\nimpl CityName {\n", "file_path": "abstio/src/abst_paths.rs", "rank": 89, "score": 274701.2679019951 }, { "content": "pub fn basename<I: Into<String>>(path: I) -> String {\n\n std::path::Path::new(&path.into())\n\n .file_stem()\n\n .unwrap()\n\n .to_os_string()\n\n .into_string()\n\n .unwrap()\n\n}\n\n\n", "file_path": "abstutil/src/utils.rs", "rank": 90, "score": 274701.2679019951 }, { "content": "fn make_instructions(ctx: &mut EventCtx, allow_through_traffic: &BTreeSet<TripMode>) -> Widget {\n\n if allow_through_traffic == &TripMode::all().into_iter().collect() {\n\n Text::from(Line(\n\n \"Through-traffic is allowed for everyone, meaning this is just a normal public road. \\\n\n Would you like to restrict it?\",\n\n ))\n\n .wrap_to_pct(ctx, 30)\n\n .draw(ctx)\n\n } else {\n\n Line(\"Trips may start or end in this zone, but through-traffic is only allowed for:\")\n\n .draw(ctx)\n\n }\n\n}\n", "file_path": "game/src/edit/zones.rs", "rank": 91, "score": 274683.6036920305 }, { "content": "pub fn nice_country_name(code: &str) -> &str {\n\n // If you add something here, please also add the flag to data/system/assets/flags.\n\n // https://github.com/hampusborgos/country-flags/tree/master/svg\n\n match code {\n\n \"at\" => \"Austria\",\n\n \"ca\" => \"Canada\",\n\n \"de\" => \"Germany\",\n\n \"fr\" => \"France\",\n\n \"gb\" => \"Great Britain\",\n\n \"il\" => \"Israel\",\n\n \"pl\" => \"Poland\",\n\n \"us\" => \"United States of America\",\n\n _ => code,\n\n }\n\n}\n\n\n", "file_path": "map_gui/src/tools/mod.rs", "rank": 92, "score": 273724.8286608793 }, { "content": "fn params_to_controls(ctx: &mut EventCtx, mode: TripMode, params: &RoutingParams) -> Widget {\n\n let mut rows = vec![Widget::custom_row(vec![\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/meters/bike.svg\")\n\n .disabled(mode == TripMode::Bike)\n\n .build_widget(ctx, \"bikes\"),\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/meters/car.svg\")\n\n .disabled(mode == TripMode::Drive)\n\n .build_widget(ctx, \"cars\"),\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/meters/pedestrian.svg\")\n\n .disabled(mode == TripMode::Walk)\n\n .build_widget(ctx, \"pedestrians\"),\n\n ])\n\n .evenly_spaced()];\n\n if mode == TripMode::Bike {\n\n // TODO Spinners that natively understand a floating point range with a given precision\n\n rows.push(Widget::row(vec![\n\n \"Bike lane penalty:\".draw_text(ctx).margin_right(20),\n", "file_path": "game/src/debug/routes.rs", "rank": 93, "score": 272545.78091671725 }, { "content": "/// Keeps file extensions\n\npub fn find_prev_file(orig: String) -> Option<String> {\n\n let mut files = list_dir(parent_path(&orig));\n\n files.reverse();\n\n files.into_iter().find(|f| *f < orig)\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 94, "score": 272474.97148498334 }, { "content": "/// Returns full paths\n\npub fn list_dir(path: String) -> Vec<String> {\n\n let mut files: Vec<String> = Vec::new();\n\n match std::fs::read_dir(&path) {\n\n Ok(iter) => {\n\n for entry in iter {\n\n files.push(entry.unwrap().path().to_str().unwrap().to_string());\n\n }\n\n }\n\n Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {}\n\n Err(e) => panic!(\"Couldn't read_dir {:?}: {}\", path, e),\n\n };\n\n files.sort();\n\n files\n\n}\n\n\n", "file_path": "abstio/src/io_native.rs", "rank": 95, "score": 272474.97148498334 }, { "content": "pub fn find_next_file(orig: String) -> Option<String> {\n\n let files = list_dir(parent_path(&orig));\n\n files.into_iter().find(|f| *f > orig)\n\n}\n\n\n", "file_path": "abstio/src/io.rs", "rank": 96, "score": 272474.97148498334 }, { "content": "pub fn list_dir(dir: String) -> Vec<String> {\n\n // TODO Handle player data in local storage\n\n let mut results = BTreeSet::new();\n\n if dir == \"../data/system\" {\n\n for f in SYSTEM_DATA.files() {\n\n results.insert(format!(\"../data/system/{}\", f.path().display()));\n\n }\n\n } else if let Some(dir) = SYSTEM_DATA.get_dir(dir.trim_start_matches(\"../data/system/\")) {\n\n for f in dir.files() {\n\n results.insert(format!(\"../data/system/{}\", f.path().display()));\n\n }\n\n } else {\n\n warn!(\"list_dir({}): not in SYSTEM_DATA, maybe it's remote\", dir);\n\n }\n\n\n\n // Merge with remote files. Duplicates handled by BTreeSet.\n\n let mut dir = dir.trim_start_matches(\"../\").to_string();\n\n if !dir.ends_with(\"/\") {\n\n dir = format!(\"{}/\", dir);\n\n }\n\n for f in Manifest::load().entries.keys() {\n\n if let Some(path) = f.strip_prefix(&dir) {\n\n // Just list the things immediately in this directory; don't recurse arbitrarily\n\n results.insert(format!(\"../{}{}\", dir, path.split(\"/\").next().unwrap()));\n\n }\n\n }\n\n\n\n results.into_iter().collect()\n\n}\n\n\n", "file_path": "abstio/src/io_web.rs", "rank": 97, "score": 272474.97148498334 }, { "content": "pub fn path_player<I: Into<String>>(p: I) -> String {\n\n path(format!(\"player/{}\", p.into()))\n\n}\n\n\n", "file_path": "abstio/src/abst_paths.rs", "rank": 98, "score": 271649.8215185663 }, { "content": "pub fn path_popdat() -> String {\n\n path(\"input/us/seattle/popdat.bin\")\n\n}\n\n\n", "file_path": "abstio/src/abst_paths.rs", "rank": 99, "score": 270949.1584323668 } ]
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\n transport.blocked() == Some(Blocked::Read)\n\n self.interest() == Reg::Write\n\n\n\n Should call `scope.register(EventSet::read())`, not with write\n\n\n\n #[test]\n\n fn test_conn_register_when_transport_blocked() {\n\n\n\n }\n\n */\n\n}\n", "file_path": "src/http/conn.rs", "rank": 0, "score": 370613.77446519054 }, { "content": "pub trait MessageHandlerFactory<K: Key, T: Transport> {\n\n type Output: MessageHandler<T>;\n\n\n\n fn create(&mut self, seed: Seed<K>) -> Option<Self::Output>;\n\n\n\n fn keep_alive_interest(&self) -> Next;\n\n}\n\n\n", "file_path": "src/http/conn.rs", "rank": 1, "score": 259224.16882977297 }, { "content": "/// An Authorization scheme to be used in the header.\n\npub trait Scheme: FromStr + fmt::Debug + Clone + Send + Sync {\n\n /// An optional Scheme name.\n\n ///\n\n /// Will be replaced with an associated constant once available.\n\n fn scheme() -> Option<&'static str>;\n\n /// Format the Scheme data into a header value.\n\n fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result;\n\n}\n\n\n\nimpl Scheme for String {\n\n fn scheme() -> Option<&'static str> {\n\n None\n\n }\n\n\n\n fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n Display::fmt(self, f)\n\n }\n\n}\n\n\n\n/// Credential holder for Basic Authentication\n", "file_path": "src/header/common/authorization.rs", "rank": 4, "score": 246680.01152257546 }, { "content": "/// A trait to react to client events that happen for each message.\n\n///\n\n/// Each event handler returns it's desired `Next` action.\n\npub trait Handler<T: Transport>: Send + 'static {\n\n /// This event occurs first, triggering when a `Request` head can be written..\n\n fn on_request(&mut self, request: &mut Request) -> http::Next;\n\n /// This event occurs each time the `Request` is ready to be written to.\n\n fn on_request_writable(&mut self, request: &mut http::Encoder<T>) -> http::Next;\n\n /// This event occurs after the first time this handler signals `Next::read()`,\n\n /// and a Response has been parsed.\n\n fn on_response(&mut self, response: Response) -> http::Next;\n\n /// This event occurs each time the `Response` is ready to be read from.\n\n fn on_response_readable(&mut self, response: &mut http::Decoder<T>) -> http::Next;\n\n\n\n /// This event occurs whenever an `Error` occurs outside of the other events.\n\n ///\n\n /// This could IO errors while waiting for events, or a timeout, etc.\n\n fn on_error(&mut self, err: ::Error) -> http::Next {\n\n debug!(\"default Handler.on_error({:?})\", err);\n\n http::Next::remove()\n\n }\n\n\n\n /// This event occurs when this Handler has requested to remove the Transport.\n\n fn on_remove(self, _transport: T) where Self: Sized {\n\n debug!(\"default Handler.on_remove\");\n\n }\n\n\n\n /// Receive a `Control` to manage waiting for this request.\n\n fn on_control(&mut self, _: http::Control) {\n\n debug!(\"default Handler.on_control()\");\n\n }\n\n}\n\n\n", "file_path": "src/client/mod.rs", "rank": 5, "score": 230958.94778652187 }, { "content": "pub trait MessageHandler<T: Transport> {\n\n type Message: Http1Message;\n\n fn on_incoming(&mut self, head: http::MessageHead<<Self::Message as Http1Message>::Incoming>, transport: &T) -> Next;\n\n fn on_outgoing(&mut self, head: &mut http::MessageHead<<Self::Message as Http1Message>::Outgoing>) -> Next;\n\n fn on_decode(&mut self, &mut http::Decoder<T>) -> Next;\n\n fn on_encode(&mut self, &mut http::Encoder<T>) -> Next;\n\n fn on_error(&mut self, err: ::Error) -> Next;\n\n\n\n fn on_remove(self, T) where Self: Sized;\n\n}\n\n\n\npub struct Seed<'a, K: Key + 'a>(&'a K, &'a channel::Sender<Next>);\n\n\n\nimpl<'a, K: Key + 'a> Seed<'a, K> {\n\n pub fn control(&self) -> Control {\n\n Control {\n\n tx: self.1.clone(),\n\n }\n\n }\n\n\n\n pub fn key(&self) -> &K {\n\n self.0\n\n }\n\n}\n\n\n\n\n", "file_path": "src/http/conn.rs", "rank": 6, "score": 223551.44429916405 }, { "content": "/// A trait alias representing all types that are both `NetworkStream` and `Clone`.\n\npub trait CloneableStream: NetworkStream + Clone {}\n\nimpl<S: NetworkStream + Clone> CloneableStream for S {}\n\n\n\n/// A newtype wrapping any `CloneableStream` in order to provide an implementation of a\n\n/// `TransportSream` trait for all types that are a `CloneableStream`.\n", "file_path": "src/http/h2/mod.rs", "rank": 8, "score": 216426.31955583696 }, { "content": "/// Deprecated\n\n///\n\n/// Use `SslClient` and `SslServer` instead.\n\npub trait Ssl {\n\n /// The protected stream.\n\n type Stream: Transport;\n\n /// Wrap a client stream with SSL.\n\n fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>;\n\n /// Wrap a server stream with SSL.\n\n fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>;\n\n}\n\n\n", "file_path": "src/net.rs", "rank": 9, "score": 212877.01483092504 }, { "content": "/// An abstraction to allow any SSL implementation to be used with client-side `HttpsStream`s.\n\npub trait SslClient {\n\n /// The protected stream.\n\n type Stream: Transport;\n\n /// Wrap a client stream with SSL.\n\n fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>;\n\n}\n\n\n", "file_path": "src/net.rs", "rank": 10, "score": 209303.98806237543 }, { "content": "/// Creates a new Response that can be used to write to a network stream.\n\npub fn new(head: &mut http::MessageHead<StatusCode>) -> Response {\n\n Response {\n\n head: head\n\n }\n\n}\n", "file_path": "src/server/response.rs", "rank": 11, "score": 204631.87842408652 }, { "content": "#[inline]\n\npub fn new_protocol() -> Http2Protocol<HttpConnector, HttpStream> {\n\n Http2Protocol::with_connector(HttpConnector)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{Http2Protocol, prepare_headers, parse_headers, parse_response};\n\n\n\n use std::io::{Read};\n\n\n\n use mock::{MockHttp2Connector, MockStream};\n\n use http::{RequestHead, ResponseHead, Protocol};\n\n\n\n use header::Headers;\n\n use header;\n\n use url::Url;\n\n use method;\n\n use cookie;\n\n use version;\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 12, "score": 201786.95606212472 }, { "content": "/// `ConnInner` contains all of a connections state which Conn proxies for in a way\n\n/// that allows Conn to maintain convenient move and self consuming method call\n\n/// semantics but avoiding many costly memcpy calls.\n\nstruct ConnInner<K: Key, T: Transport, H: MessageHandler<T>> {\n\n buf: Buffer,\n\n ctrl: (channel::Sender<Next>, channel::Receiver<Next>),\n\n keep_alive_enabled: bool,\n\n key: K,\n\n state: State<H, T>,\n\n transport: T,\n\n}\n\n\n\nimpl<K: Key, T: Transport, H: MessageHandler<T>> fmt::Debug for ConnInner<K, T, H> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"Conn\")\n\n .field(\"keep_alive_enabled\", &self.keep_alive_enabled)\n\n .field(\"state\", &self.state)\n\n .field(\"buf\", &self.buf)\n\n .finish()\n\n }\n\n}\n\n\n\nimpl<K: Key, T: Transport, H: MessageHandler<T>> fmt::Debug for Conn<K, T, H> {\n", "file_path": "src/http/conn.rs", "rank": 13, "score": 189788.0410464748 }, { "content": "/// A trait to react to server events that happen for each message.\n\n///\n\n/// Each event handler returns its desired `Next` action.\n\npub trait Handler<T: Transport> {\n\n /// This event occurs first, triggering when a `Request` has been parsed.\n\n fn on_request(&mut self, request: Request<T>) -> Next;\n\n /// This event occurs each time the `Request` is ready to be read from.\n\n fn on_request_readable(&mut self, request: &mut http::Decoder<T>) -> Next;\n\n /// This event occurs after the first time this handled signals `Next::write()`.\n\n fn on_response(&mut self, response: &mut Response) -> Next;\n\n /// This event occurs each time the `Response` is ready to be written to.\n\n fn on_response_writable(&mut self, response: &mut http::Encoder<T>) -> Next;\n\n\n\n /// This event occurs whenever an `Error` occurs outside of the other events.\n\n ///\n\n /// This could IO errors while waiting for events, or a timeout, etc.\n\n fn on_error(&mut self, err: ::Error) -> Next where Self: Sized {\n\n debug!(\"default Handler.on_error({:?})\", err);\n\n http::Next::remove()\n\n }\n\n\n\n /// This event occurs when this Handler has requested to remove the Transport.\n\n fn on_remove(self, _transport: T) where Self: Sized {\n\n debug!(\"default Handler.on_remove\");\n\n }\n\n}\n\n\n\n\n", "file_path": "src/server/mod.rs", "rank": 14, "score": 188498.90290865372 }, { "content": "/// Used to create a `Handler` when a new message is received by the server.\n\npub trait HandlerFactory<T: Transport> {\n\n /// The `Handler` to use for the incoming message.\n\n type Output: Handler<T>;\n\n /// Creates the associated `Handler`.\n\n fn create(&mut self, ctrl: http::Control) -> Self::Output;\n\n}\n\n\n\nimpl<F, H, T> HandlerFactory<T> for F\n\nwhere F: FnMut(http::Control) -> H, H: Handler<T>, T: Transport {\n\n type Output = H;\n\n fn create(&mut self, ctrl: http::Control) -> H {\n\n self(ctrl)\n\n }\n\n}\n", "file_path": "src/server/mod.rs", "rank": 15, "score": 185456.3901995345 }, { "content": "#[cfg(windows)]\n\npub trait Transport: Read + Write + Evented {\n\n /// Takes a socket error when event polling notices an `events.is_error()`.\n\n fn take_socket_error(&mut self) -> io::Result<()>;\n\n\n\n /// Returns if the this transport is blocked on read or write.\n\n ///\n\n /// By default, the user will declare whether they wish to wait on read\n\n /// or write events. However, some transports, such as those protected by\n\n /// TLS, may be blocked on reading before it can write, or vice versa.\n\n fn blocked(&self) -> Option<Blocked> {\n\n None\n\n }\n\n}\n\n\n\n/// Declares when a transport is blocked from any further action, until the\n\n/// corresponding event has occured.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum Blocked {\n\n /// Blocked on reading\n\n Read,\n\n /// blocked on writing\n\n Write,\n\n}\n\n\n\n\n", "file_path": "src/net.rs", "rank": 16, "score": 183219.689924385 }, { "content": "/// A trait for any object that will represent a header field and value.\n\n///\n\n/// This trait represents the construction and identification of headers,\n\n/// and contains trait-object unsafe methods.\n\npub trait Header: HeaderClone + Any + GetType + Send + Sync {\n\n /// Returns the name of the header field this belongs to.\n\n ///\n\n /// This will become an associated constant once available.\n\n fn header_name() -> &'static str where Self: Sized;\n\n /// Parse a header from a raw stream of bytes.\n\n ///\n\n /// It's possible that a request can include a header field more than once,\n\n /// and in that case, the slice will have a length greater than 1. However,\n\n /// it's not necessarily the case that a Header is *allowed* to have more\n\n /// than one field value. If that's the case, you **should** return `None`\n\n /// if `raw.len() > 1`.\n\n fn parse_header(raw: &Raw) -> ::Result<Self> where Self: Sized;\n\n /// Format a header to be output into a TcpStream.\n\n ///\n\n /// This method is not allowed to introduce an Err not produced\n\n /// by the passed-in Formatter.\n\n fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result;\n\n}\n\n\n", "file_path": "src/header/mod.rs", "rank": 17, "score": 181886.6273346141 }, { "content": "/// An abstraction to allow any SSL implementation to be used with server-side `HttpsStream`s.\n\npub trait SslServer {\n\n /// The protected stream.\n\n type Stream: Transport;\n\n /// Wrap a server stream with SSL.\n\n fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>;\n\n}\n\n\n\nimpl<S: Ssl> SslClient for S {\n\n type Stream = <S as Ssl>::Stream;\n\n\n\n fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> {\n\n Ssl::wrap_client(self, stream, host)\n\n }\n\n}\n\n\n\nimpl<S: Ssl> SslServer for S {\n\n type Stream = <S as Ssl>::Stream;\n\n\n\n fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> {\n\n Ssl::wrap_server(self, stream)\n", "file_path": "src/net.rs", "rank": 18, "score": 181414.9321138211 }, { "content": "#[doc(hidden)]\n\npub trait HeaderClone {\n\n fn clone_box(&self) -> Box<Header + Send + Sync>;\n\n}\n\n\n\nimpl<T: Header + Clone> HeaderClone for T {\n\n #[inline]\n\n fn clone_box(&self) -> Box<Header + Send + Sync> {\n\n Box::new(self.clone())\n\n }\n\n}\n\n\n\nimpl Header + Send + Sync {\n\n // A trait object looks like this:\n\n //\n\n // TraitObject { data: *mut (), vtable: *mut () }\n\n //\n\n // So, we transmute &Trait into a (*mut (), *mut ()). This depends on the\n\n // order the compiler has chosen to represent a TraitObject.\n\n //\n\n // It has been assured that this order will be stable.\n", "file_path": "src/header/mod.rs", "rank": 19, "score": 178009.94010469507 }, { "content": "pub trait Http1Message {\n\n type Incoming;\n\n type Outgoing: Default;\n\n fn parse(bytes: &[u8]) -> ParseResult<Self::Incoming>;\n\n fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<h1::Decoder>;\n\n fn encode(head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> h1::Encoder;\n\n}\n\n\n\n/// Used to signal desired events when working with asynchronous IO.\n\n#[must_use]\n\n#[derive(Clone)]\n\npub struct Next {\n\n interest: Next_,\n\n timeout: Option<Duration>,\n\n}\n\n\n\nimpl fmt::Debug for Next {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n try!(write!(f, \"Next::{:?}\", &self.interest));\n\n match self.timeout {\n\n Some(ref d) => write!(f, \"({:?})\", d),\n\n None => Ok(())\n\n }\n\n }\n\n}\n\n\n\n// Internal enum for `Next`\n", "file_path": "src/http/mod.rs", "rank": 20, "score": 176683.1842573696 }, { "content": " pub trait AtomicWrite {\n\n fn write_atomic(&mut self, data: &[&[u8]]) -> io::Result<usize>;\n\n }\n\n\n\n #[cfg(not(windows))]\n\n impl<T: Write + ::vecio::Writev> AtomicWrite for T {\n\n\n\n fn write_atomic(&mut self, bufs: &[&[u8]]) -> io::Result<usize> {\n\n self.writev(bufs)\n\n }\n\n\n\n }\n\n\n\n #[cfg(windows)]\n\n impl<T: Write> AtomicWrite for T {\n\n fn write_atomic(&mut self, bufs: &[&[u8]]) -> io::Result<usize> {\n\n let vec = bufs.concat();\n\n self.write(&vec)\n\n }\n\n }\n", "file_path": "src/http/mod.rs", "rank": 21, "score": 176683.1842573696 }, { "content": "#[inline]\n\nfn header_name<T: Header>() -> &'static str {\n\n <T as Header>::header_name()\n\n}\n\n\n\n/// A map of header fields on requests and responses.\n\n#[derive(Clone)]\n\npub struct Headers {\n\n data: VecMap<HeaderName, Item>,\n\n}\n\n\n\nimpl Default for Headers {\n\n fn default() -> Headers {\n\n Headers::new()\n\n }\n\n}\n\n\n\nmacro_rules! literals {\n\n ($($len:expr => $($header:path),+;)+) => (\n\n fn maybe_literal(s: &str) -> Cow<'static, str> {\n\n match s.len() {\n", "file_path": "src/header/mod.rs", "rank": 22, "score": 176226.39902229168 }, { "content": "#[derive(Clone, Debug)]\n\nstruct HeaderName(UniCase<Cow<'static, str>>);\n\n\n\nimpl fmt::Display for HeaderName {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n fmt::Display::fmt(&self.0, f)\n\n }\n\n}\n\n\n\nimpl AsRef<str> for HeaderName {\n\n fn as_ref(&self) -> &str {\n\n ((self.0).0).as_ref()\n\n }\n\n}\n\n\n\nimpl PartialEq for HeaderName {\n\n fn eq(&self, other: &HeaderName) -> bool {\n\n let s = self.as_ref();\n\n let k = other.as_ref();\n\n if s.len() == k.len() && s.as_ptr() == k.as_ptr() {\n\n true\n", "file_path": "src/header/mod.rs", "rank": 23, "score": 175528.9626289801 }, { "content": "#[doc(hidden)]\n\npub trait GetType: Any {\n\n #[inline(always)]\n\n fn get_type(&self) -> TypeId {\n\n TypeId::of::<Self>()\n\n }\n\n}\n\n\n\nimpl<T: Any> GetType for T {}\n\n\n", "file_path": "src/header/mod.rs", "rank": 24, "score": 173001.1749907864 }, { "content": "#[cfg(not(windows))]\n\npub trait Transport: Read + Write + Evented + ::vecio::Writev {\n\n /// Takes a socket error when event polling notices an `events.is_error()`.\n\n fn take_socket_error(&mut self) -> io::Result<()>;\n\n\n\n /// Returns if the this transport is blocked on read or write.\n\n ///\n\n /// By default, the user will declare whether they wish to wait on read\n\n /// or write events. However, some transports, such as those protected by\n\n /// TLS, may be blocked on reading before it can write, or vice versa.\n\n fn blocked(&self) -> Option<Blocked> {\n\n None\n\n }\n\n}\n\n\n\n/// A trait representing a socket transport that can be used in a Client or Server.\n", "file_path": "src/net.rs", "rank": 25, "score": 168872.16429157046 }, { "content": "pub fn new(head: &mut RequestHead) -> Request {\n\n Request { head: head }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n /*\n\n use std::io::Write;\n\n use std::str::from_utf8;\n\n use url::Url;\n\n use method::Method::{Get, Head, Post};\n\n use mock::{MockStream, MockConnector};\n\n use net::Fresh;\n\n use header::{ContentLength,TransferEncoding,Encoding};\n\n use url::form_urlencoded;\n\n use super::Request;\n\n use http::h1::Http11Message;\n\n\n\n fn run_request(req: Request<Fresh>) -> Vec<u8> {\n\n let req = req.start().unwrap();\n", "file_path": "src/client/request.rs", "rank": 26, "score": 168093.85117807583 }, { "content": "/// Reads a raw string into a value.\n\npub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> {\n\n let s = try!(str::from_utf8(raw));\n\n T::from_str(s).or(Err(::Error::Header))\n\n}\n\n\n\n/// Reads a comma-delimited raw header into a Vec.\n", "file_path": "src/header/parsing.rs", "rank": 27, "score": 167411.2695528919 }, { "content": "pub fn new(incoming: http::ResponseHead) -> Response {\n\n trace!(\"Response::new\");\n\n let status = status::StatusCode::from_u16(incoming.subject.0);\n\n debug!(\"version={:?}, status={:?}\", incoming.version, status);\n\n debug!(\"headers={:?}\", incoming.headers);\n\n\n\n Response {\n\n status: status,\n\n version: incoming.version,\n\n headers: incoming.headers,\n\n status_raw: incoming.subject,\n\n }\n\n\n\n}\n\n\n\n/// A response for a client request to a remote server.\n\n#[derive(Debug)]\n\npub struct Response {\n\n status: status::StatusCode,\n\n headers: header::Headers,\n", "file_path": "src/client/response.rs", "rank": 28, "score": 167020.58138042188 }, { "content": "/// Reads a single raw string when parsing a header.\n\npub fn from_one_raw_str<T: str::FromStr>(raw: &Raw) -> ::Result<T> {\n\n if let Some(line) = raw.one() {\n\n if !line.is_empty() {\n\n return from_raw_str(line)\n\n }\n\n }\n\n Err(::Error::Header)\n\n}\n\n\n", "file_path": "src/header/parsing.rs", "rank": 29, "score": 165326.48917860974 }, { "content": "/// Parses extended header parameter values (`ext-value`), as defined in\n\n/// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).\n\n///\n\n/// Extended values are denoted by parameter names that end with `*`.\n\n///\n\n/// ## ABNF\n\n/// ```plain\n\n/// ext-value = charset \"'\" [ language ] \"'\" value-chars\n\n/// ; like RFC 2231's <extended-initial-value>\n\n/// ; (see [RFC2231], Section 7)\n\n///\n\n/// charset = \"UTF-8\" / \"ISO-8859-1\" / mime-charset\n\n///\n\n/// mime-charset = 1*mime-charsetc\n\n/// mime-charsetc = ALPHA / DIGIT\n\n/// / \"!\" / \"#\" / \"$\" / \"%\" / \"&\"\n\n/// / \"+\" / \"-\" / \"^\" / \"_\" / \"`\"\n\n/// / \"{\" / \"}\" / \"~\"\n\n/// ; as <mime-charset> in Section 2.3 of [RFC2978]\n\n/// ; except that the single quote is not included\n\n/// ; SHOULD be registered in the IANA charset registry\n\n///\n\n/// language = <Language-Tag, defined in [RFC5646], Section 2.1>\n\n///\n\n/// value-chars = *( pct-encoded / attr-char )\n\n///\n\n/// pct-encoded = \"%\" HEXDIG HEXDIG\n\n/// ; see [RFC3986], Section 2.1\n\n///\n\n/// attr-char = ALPHA / DIGIT\n\n/// / \"!\" / \"#\" / \"$\" / \"&\" / \"+\" / \"-\" / \".\"\n\n/// / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n\n/// ; token except ( \"*\" / \"'\" / \"%\" )\n\n/// ```\n\npub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {\n\n\n\n // Break into three pieces separated by the single-quote character\n\n let mut parts = val.splitn(3,'\\'');\n\n\n\n // Interpret the first piece as a Charset\n\n let charset: Charset = match parts.next() {\n\n None => return Err(::Error::Header),\n\n Some(n) => try!(FromStr::from_str(n)),\n\n };\n\n\n\n // Interpret the second piece as a language tag\n\n let lang: Option<LanguageTag> = match parts.next() {\n\n None => return Err(::Error::Header),\n\n Some(\"\") => None,\n\n Some(s) => match s.parse() {\n\n Ok(lt) => Some(lt),\n\n Err(_) => return Err(::Error::Header),\n\n }\n\n };\n", "file_path": "src/header/parsing.rs", "rank": 30, "score": 162915.95496429768 }, { "content": "#[inline]\n\npub fn from_comma_delimited<T: str::FromStr>(raw: &Raw) -> ::Result<Vec<T>> {\n\n let mut result = Vec::new();\n\n for s in raw {\n\n let s = try!(str::from_utf8(s.as_ref()));\n\n result.extend(s.split(',')\n\n .filter_map(|x| match x.trim() {\n\n \"\" => None,\n\n y => Some(y)\n\n })\n\n .filter_map(|x| x.parse().ok()))\n\n }\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/header/parsing.rs", "rank": 31, "score": 157032.20827639796 }, { "content": "struct FastWrite<'a>(&'a mut Vec<u8>);\n\n\n\nimpl<'a> fmt::Write for FastWrite<'a> {\n\n fn write_str(&mut self, s: &str) -> fmt::Result {\n\n extend(self.0, s.as_bytes());\n\n Ok(())\n\n }\n\n\n\n fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result {\n\n fmt::write(self, args)\n\n }\n\n}\n\n\n", "file_path": "src/http/h1/parse.rs", "rank": 33, "score": 152774.74347290894 }, { "content": "/// Format an array into a comma-delimited string.\n\npub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {\n\n for (i, part) in parts.iter().enumerate() {\n\n if i != 0 {\n\n try!(f.write_str(\", \"));\n\n }\n\n try!(Display::fmt(part, f));\n\n }\n\n Ok(())\n\n}\n\n\n\n/// An extended header parameter value (i.e., tagged with a character set and optionally,\n\n/// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct ExtendedValue {\n\n /// The character set that is used to encode the `value` to a string.\n\n pub charset: Charset,\n\n /// The human language details of the `value`, if available.\n\n pub language_tag: Option<LanguageTag>,\n\n /// The parameter value, as expressed in octets.\n\n pub value: Vec<u8>,\n\n}\n\n\n", "file_path": "src/header/parsing.rs", "rank": 34, "score": 150811.4404350898 }, { "content": "#[inline]\n\npub fn should_keep_alive(version: HttpVersion, headers: &Headers) -> bool {\n\n let ret = match (version, headers.get::<Connection>()) {\n\n (Http10, None) => false,\n\n (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,\n\n (Http11, Some(conn)) if conn.contains(&Close) => false,\n\n _ => true\n\n };\n\n trace!(\"should_keep_alive(version={:?}, header={:?}) = {:?}\", version, headers.get::<Connection>(), ret);\n\n ret\n\n}\n\n\n\npub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>;\n\n\n", "file_path": "src/http/mod.rs", "rank": 35, "score": 150547.86047366637 }, { "content": "struct Worker {\n\n rx: Option<spmc::Receiver<String>>,\n\n notify: Option<channel::Sender<Answer>>,\n\n shutdown: bool,\n\n}\n\n\n\nimpl Worker {\n\n fn new(rx: spmc::Receiver<String>, notify: channel::Sender<Answer>) -> Worker {\n\n Worker {\n\n rx: Some(rx),\n\n notify: Some(notify),\n\n shutdown: false,\n\n }\n\n }\n\n}\n\n\n\nimpl Drop for Worker {\n\n fn drop(&mut self) {\n\n if !self.shutdown {\n\n trace!(\"Worker.drop panicked, restarting\");\n\n work(self.rx.take().expect(\"Worker lost rx\"),\n\n self.notify.take().expect(\"Worker lost notify\"));\n\n } else {\n\n trace!(\"Worker.drop shutdown, closing\");\n\n }\n\n }\n\n}\n", "file_path": "src/client/dns.rs", "rank": 36, "score": 148628.03490223543 }, { "content": "fn should_have_response_body(method: &Method, status: u16) -> bool {\n\n trace!(\"should_have_response_body({:?}, {})\", method, status);\n\n match (method, status) {\n\n (&Method::Head, _) |\n\n (_, 100...199) |\n\n (_, 204) |\n\n (_, 304) |\n\n (&Method::Connect, 200...299) => false,\n\n _ => true\n\n }\n\n}\n\n*/\n\n/*\n\nconst MAX_INVALID_RESPONSE_BYTES: usize = 1024 * 128;\n\nimpl HttpMessage for Http11Message {\n\n\n\n fn get_incoming(&mut self) -> ::Result<ResponseHead> {\n\n unimplemented!();\n\n /*\n\n try!(self.flush_outgoing());\n", "file_path": "src/http/h1/mod.rs", "rank": 37, "score": 145688.78800313958 }, { "content": "pub fn new<'a, T>(incoming: RequestHead, transport: &'a T) -> Request<'a, T> {\n\n let MessageHead { version, subject: RequestLine(method, uri), headers } = incoming;\n\n debug!(\"Request Line: {:?} {:?} {:?}\", method, uri, version);\n\n debug!(\"{:#?}\", headers);\n\n\n\n Request {\n\n method: method,\n\n uri: uri,\n\n headers: headers,\n\n version: version,\n\n transport: transport,\n\n }\n\n}\n\n\n\n/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`.\n\npub struct Request<'a, T: 'a> {\n\n method: Method,\n\n uri: RequestUri,\n\n version: HttpVersion,\n\n headers: Headers,\n", "file_path": "src/server/request.rs", "rank": 38, "score": 143423.3704255013 }, { "content": "/// A helper function that prepares the headers that should be sent in an HTTP/2 message.\n\n///\n\n/// Adapts the `Headers` into a list of octet string pairs.\n\nfn prepare_headers(mut headers: Headers) -> Vec<Http2Header> {\n\n if headers.remove::<header::Connection>() {\n\n warn!(\"The `Connection` header is not valid for an HTTP/2 connection.\");\n\n }\n\n let mut http2_headers: Vec<_> = headers.iter().filter_map(|h| {\n\n if h.is::<header::SetCookie>() {\n\n None\n\n } else {\n\n // HTTP/2 header names MUST be lowercase.\n\n Some((h.name().to_ascii_lowercase().into_bytes(), h.value_string().into_bytes()))\n\n }\n\n }).collect();\n\n\n\n // Now separately add the cookies, as `hyper` considers `Set-Cookie` to be only a single\n\n // header, even in the face of multiple cookies being set.\n\n if let Some(set_cookie) = headers.get::<header::SetCookie>() {\n\n for cookie in set_cookie.iter() {\n\n http2_headers.push((b\"set-cookie\".to_vec(), cookie.to_string().into_bytes()));\n\n }\n\n }\n\n\n\n http2_headers\n\n}\n\n\n\n/// A helper function that prepares the body for sending in an HTTP/2 request.\n", "file_path": "src/http/h2/mod.rs", "rank": 39, "score": 143055.84556147194 }, { "content": "fn extend(dst: &mut Vec<u8>, data: &[u8]) {\n\n use std::ptr;\n\n dst.reserve(data.len());\n\n let prev = dst.len();\n\n unsafe {\n\n ptr::copy_nonoverlapping(data.as_ptr(),\n\n dst.as_mut_ptr().offset(prev as isize),\n\n data.len());\n\n dst.set_len(prev + data.len());\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use http;\n\n use super::{parse};\n\n\n\n #[test]\n\n fn test_parse_request() {\n\n let raw = b\"GET /echo HTTP/1.1\\r\\nHost: hyper.rs\\r\\n\\r\\n\";\n", "file_path": "src/http/h1/parse.rs", "rank": 40, "score": 143008.39292045045 }, { "content": "#[derive(Debug)]\n\nenum EncoderImpl<'a, T: Transport + 'a> {\n\n H1(&'a mut h1::Encoder, &'a mut T),\n\n}\n\n\n\nimpl<'a, T: Read> Decoder<'a, T> {\n\n fn h1(decoder: &'a mut h1::Decoder, transport: Trans<'a, T>) -> Decoder<'a, T> {\n\n Decoder(DecoderImpl::H1(decoder, transport))\n\n }\n\n\n\n /// Read from the `Transport`.\n\n #[inline]\n\n pub fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n match self.0 {\n\n DecoderImpl::H1(ref mut decoder, ref mut transport) => {\n\n decoder.decode(transport, buf)\n\n }\n\n }\n\n }\n\n\n\n /// Try to read from the `Transport`.\n", "file_path": "src/http/mod.rs", "rank": 41, "score": 140880.23598497536 }, { "content": "struct Context<F> {\n\n factory: F,\n\n idle_timeout: Option<Duration>,\n\n keep_alive: bool,\n\n}\n\n\n\nimpl<F: HandlerFactory<T>, T: Transport> http::MessageHandlerFactory<(), T> for Context<F> {\n\n type Output = message::Message<F::Output, T>;\n\n\n\n fn create(&mut self, seed: http::Seed<()>) -> Option<Self::Output> {\n\n Some(message::Message::new(self.factory.create(seed.control())))\n\n }\n\n\n\n fn keep_alive_interest(&self) -> Next {\n\n if let Some(dur) = self.idle_timeout {\n\n Next::read().timeout(dur)\n\n } else {\n\n Next::read()\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/server/mod.rs", "rank": 42, "score": 139942.78004318677 }, { "content": "/// Convenience function to create a `Quality` from a float.\n\npub fn q(f: f32) -> Quality {\n\n assert!(f >= 0f32 && f <= 1f32, \"q value must be between 0.0 and 1.0\");\n\n from_f32(f)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use super::super::encoding::*;\n\n\n\n #[test]\n\n fn test_quality_item_show1() {\n\n let x = qitem(Chunked);\n\n assert_eq!(format!(\"{}\", x), \"chunked\");\n\n }\n\n #[test]\n\n fn test_quality_item_show2() {\n\n let x = QualityItem::new(Chunked, Quality(1));\n\n assert_eq!(format!(\"{}\", x), \"chunked; q=0.001\");\n\n }\n", "file_path": "src/header/shared/quality_item.rs", "rank": 43, "score": 138860.94334609862 }, { "content": "#[derive(Debug)]\n\nstruct Http2ConnectError(io::Error);\n\n\n\nimpl ::std::fmt::Display for Http2ConnectError {\n\n fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n write!(fmt, \"HTTP/2 connect error: {}\", (self as &::std::error::Error).description())\n\n }\n\n}\n\n\n\nimpl ::std::error::Error for Http2ConnectError {\n\n fn description(&self) -> &str {\n\n self.0.description()\n\n }\n\n\n\n fn cause(&self) -> Option<&::std::error::Error> {\n\n self.0.cause()\n\n }\n\n}\n\n\n\nimpl HttpConnectError for Http2ConnectError {}\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 44, "score": 138334.90964772284 }, { "content": "/// Accepts sockets asynchronously.\n\npub trait Accept: Evented {\n\n /// The transport type that is accepted.\n\n type Output: Transport;\n\n /// Accept a socket from the listener, if it doesn not block.\n\n fn accept(&self) -> io::Result<Option<Self::Output>>;\n\n /// Return the local `SocketAddr` of this listener.\n\n fn local_addr(&self) -> io::Result<SocketAddr>;\n\n}\n\n\n\n/// An alias to `mio::tcp::TcpStream`.\n\n#[derive(Debug)]\n\npub struct HttpStream(pub TcpStream);\n\n\n\nimpl Transport for HttpStream {\n\n fn take_socket_error(&mut self) -> io::Result<()> {\n\n self.0.take_socket_error()\n\n }\n\n}\n\n\n\nimpl Read for HttpStream {\n", "file_path": "src/net.rs", "rank": 45, "score": 133838.3638329184 }, { "content": "fn split_in_two(s: &str, separator: char) -> Option<(&str, &str)> {\n\n let mut iter = s.splitn(2, separator);\n\n match (iter.next(), iter.next()) {\n\n (Some(a), Some(b)) => Some((a, b)),\n\n _ => None\n\n }\n\n}\n\n\n\nimpl FromStr for ContentRangeSpec {\n\n type Err = ::Error;\n\n\n\n fn from_str(s: &str) -> ::Result<Self> {\n\n let res = match split_in_two(s, ' ') {\n\n Some((\"bytes\", resp)) => {\n\n let (range, instance_length) = try!(split_in_two(resp, '/').ok_or(::Error::Header));\n\n\n\n let instance_length = if instance_length == \"*\" {\n\n None\n\n } else {\n\n Some(try!(instance_length.parse().map_err(|_| ::Error::Header)))\n", "file_path": "src/header/common/content_range.rs", "rank": 46, "score": 132724.37712773203 }, { "content": "pub fn new<T>(notify: rotor::Notifier) -> (Sender<T>, Receiver<T>) {\n\n let b = Arc::new(AtomicBool::new(false));\n\n let (tx, rx) = mpsc::channel();\n\n (Sender {\n\n awake: b.clone(),\n\n notify: notify,\n\n tx: tx,\n\n },\n\n Receiver {\n\n awake: b,\n\n rx: rx,\n\n })\n\n}\n\n\n", "file_path": "src/http/channel.rs", "rank": 47, "score": 131592.08108442996 }, { "content": "pub fn parse<T: Http1Message<Incoming=I>, I>(rdr: &[u8]) -> ParseResult<I> {\n\n h1::parse::<T, I>(rdr)\n\n}\n\n\n\n// These 2 enums are not actually dead_code. They are used in the server and\n\n// and client modules, respectively. However, their being used as associated\n\n// types doesn't mark them as used, so the dead_code linter complains.\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug)]\n\npub enum ServerMessage {}\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug)]\n\npub enum ClientMessage {}\n\n\n", "file_path": "src/http/mod.rs", "rank": 48, "score": 130083.7852565281 }, { "content": "pub fn share<T, U>(other: &Sender<U>) -> (Sender<T>, Receiver<T>) {\n\n let (tx, rx) = mpsc::channel();\n\n let notify = other.notify.clone();\n\n let b = other.awake.clone();\n\n (Sender {\n\n awake: b.clone(),\n\n notify: notify,\n\n tx: tx,\n\n },\n\n Receiver {\n\n awake: b,\n\n rx: rx,\n\n })\n\n}\n\n\n\npub struct Sender<T> {\n\n awake: Arc<AtomicBool>,\n\n notify: rotor::Notifier,\n\n tx: mpsc::Sender<T>,\n\n}\n", "file_path": "src/http/channel.rs", "rank": 49, "score": 130083.7852565281 }, { "content": "fn eat<R: Read>(rdr: &mut R, bytes: &[u8]) -> io::Result<()> {\n\n let mut buf = [0];\n\n for &b in bytes.iter() {\n\n match try!(rdr.read(&mut buf)) {\n\n 1 if buf[0] == b => (),\n\n _ => return Err(io::Error::new(io::ErrorKind::InvalidInput,\n\n \"Invalid characters found\")),\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/http/h1/decode.rs", "rank": 50, "score": 130050.32494969746 }, { "content": "/// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk.\n\nfn read_chunk_size<R: Read>(rdr: &mut R) -> io::Result<u64> {\n\n macro_rules! byte (\n\n ($rdr:ident) => ({\n\n let mut buf = [0];\n\n match try!($rdr.read(&mut buf)) {\n\n 1 => buf[0],\n\n _ => return Err(io::Error::new(io::ErrorKind::InvalidInput,\n\n \"Invalid chunk size line\")),\n\n\n\n }\n\n })\n\n );\n\n let mut size = 0u64;\n\n let radix = 16;\n\n let mut in_ext = false;\n\n let mut in_chunk_size = true;\n\n loop {\n\n match byte!(rdr) {\n\n b@b'0'...b'9' if in_chunk_size => {\n\n size *= radix;\n", "file_path": "src/http/h1/decode.rs", "rank": 51, "score": 129605.4219442365 }, { "content": "fn s(bytes: &[u8]) -> &str {\n\n ::std::str::from_utf8(bytes.as_ref()).unwrap()\n\n}\n\n\n", "file_path": "tests/client.rs", "rank": 52, "score": 128225.6741832743 }, { "content": "pub fn parse<T: Http1Message<Incoming=I>, I>(buf: &[u8]) -> ParseResult<I> {\n\n if buf.len() == 0 {\n\n return Ok(None);\n\n }\n\n trace!(\"parse({:?})\", buf);\n\n <T as Http1Message>::parse(buf)\n\n}\n\n\n\n\n\n\n\nimpl Http1Message for ServerMessage {\n\n type Incoming = RequestLine;\n\n type Outgoing = StatusCode;\n\n\n\n fn parse(buf: &[u8]) -> ParseResult<RequestLine> {\n\n let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS];\n\n trace!(\"Request.parse([Header; {}], [u8; {}])\", headers.len(), buf.len());\n\n let mut req = httparse::Request::new(&mut headers);\n\n Ok(match try!(req.parse(buf)) {\n\n httparse::Status::Complete(len) => {\n", "file_path": "src/http/h1/parse.rs", "rank": 53, "score": 127825.61373816589 }, { "content": "type Line = Cow<'static, [u8]>;\n\n\n", "file_path": "src/header/raw.rs", "rank": 54, "score": 126971.42214584668 }, { "content": "fn from_comma_delimited<T: FromStr>(s: &str) -> Vec<T> {\n\n s.split(',')\n\n .filter_map(|x| match x.trim() {\n\n \"\" => None,\n\n y => Some(y)\n\n })\n\n .filter_map(|x| x.parse().ok())\n\n .collect()\n\n}\n\n\n\nimpl Header for Range {\n\n\n\n fn header_name() -> &'static str {\n\n static NAME: &'static str = \"Range\";\n\n NAME\n\n }\n\n\n\n fn parse_header(raw: &Raw) -> ::Result<Range> {\n\n from_one_raw_str(raw)\n\n }\n\n\n\n fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n Display::fmt(self, f)\n\n }\n\n\n\n}\n\n\n", "file_path": "src/header/common/range.rs", "rank": 55, "score": 118602.99284455099 }, { "content": "// check that each char in the slice is either:\n\n// 1. %x21, or\n\n// 2. in the range %x23 to %x7E, or\n\n// 3. above %x80\n\nfn check_slice_validity(slice: &str) -> bool {\n\n slice.bytes().all(|c|\n\n c == b'\\x21' || (c >= b'\\x23' && c <= b'\\x7e') | (c >= b'\\x80'))\n\n}\n\n\n\n/// An entity tag, defined in [RFC7232](https://tools.ietf.org/html/rfc7232#section-2.3)\n\n///\n\n/// An entity tag consists of a string enclosed by two literal double quotes.\n\n/// Preceding the first double quote is an optional weakness indicator,\n\n/// which always looks like `W/`. Examples for valid tags are `\"xyzzy\"` and `W/\"xyzzy\"`.\n\n///\n\n/// # ABNF\n\n/// ```plain\n\n/// entity-tag = [ weak ] opaque-tag\n\n/// weak = %x57.2F ; \"W/\", case-sensitive\n\n/// opaque-tag = DQUOTE *etagc DQUOTE\n\n/// etagc = %x21 / %x23-7E / obs-text\n\n/// ; VCHAR except double quotes, plus obs-text\n\n/// ```\n\n///\n", "file_path": "src/header/shared/entity.rs", "rank": 56, "score": 118075.32630767048 }, { "content": "pub fn parsed(val: &[u8]) -> Raw {\n\n Raw(Lines::One(maybe_literal(val.into())))\n\n}\n\n\n\nimpl fmt::Debug for Raw {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self.0 {\n\n Lines::One(ref line) => fmt::Debug::fmt(&[line], f),\n\n Lines::Many(ref lines) => fmt::Debug::fmt(lines, f)\n\n }\n\n }\n\n}\n\n\n\nimpl ::std::ops::Index<usize> for Raw {\n\n type Output = [u8];\n\n fn index(&self, idx: usize) -> &[u8] {\n\n match self.0 {\n\n Lines::One(ref line) => if idx == 0 {\n\n line.as_ref()\n\n } else {\n", "file_path": "src/header/raw.rs", "rank": 57, "score": 117546.14261424489 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nenum Reg {\n\n Read,\n\n Write,\n\n ReadWrite,\n\n Wait,\n\n Remove\n\n}\n\n\n\n/// A notifier to wakeup a socket after having used `Next::wait()`\n\n#[derive(Debug, Clone)]\n\npub struct Control {\n\n tx: self::channel::Sender<Next>,\n\n}\n\n\n\nimpl Control {\n\n /// Wakeup a waiting socket to listen for a certain event.\n\n pub fn ready(&self, next: Next) -> Result<(), ControlError> {\n\n //TODO: assert!( next.interest != Next_::Wait ) ?\n\n self.tx.send(next).map_err(|_| ControlError(()))\n\n }\n", "file_path": "src/http/mod.rs", "rank": 58, "score": 117225.38564662945 }, { "content": "#[derive(Debug)]\n\nstruct Chunk {\n\n buf: Cow<'static, [u8]>,\n\n pos: usize,\n\n next: (h1::Encoder, Next),\n\n}\n\n\n\nimpl Chunk {\n\n fn is_written(&self) -> bool {\n\n self.pos >= self.buf.len()\n\n }\n\n}\n\n\n", "file_path": "src/http/conn.rs", "rank": 59, "score": 116160.85859498518 }, { "content": "struct Message<H: Handler<T>, T: Transport> {\n\n handler: H,\n\n url: Option<Url>,\n\n _marker: PhantomData<T>,\n\n}\n\n\n\nimpl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> {\n\n type Message = http::ClientMessage;\n\n\n\n fn on_outgoing(&mut self, head: &mut RequestHead) -> Next {\n\n let url = self.url.take().expect(\"Message.url is missing\");\n\n if let Some(host) = url.host_str() {\n\n head.headers.set(Host {\n\n hostname: host.to_owned(),\n\n port: url.port(),\n\n });\n\n }\n\n head.subject.1 = RequestUri::AbsolutePath {\n\n path: url.path().to_owned(),\n\n query: url.query().map(|q| q.to_owned()),\n", "file_path": "src/client/mod.rs", "rank": 60, "score": 115427.9090658706 }, { "content": "fn _assert_transport() {\n\n fn _assert<T: Transport>() {}\n\n _assert::<HttpsStream<HttpStream>>();\n\n}\n\n\n\n/*\n\n#[cfg(all(not(feature = \"openssl\"), not(feature = \"security-framework\")))]\n\n#[doc(hidden)]\n\npub type DefaultConnector = HttpConnector;\n\n\n\n#[cfg(feature = \"openssl\")]\n\n#[doc(hidden)]\n\npub type DefaultConnector = HttpsConnector<self::openssl::OpensslClient>;\n\n\n\n#[cfg(all(feature = \"security-framework\", not(feature = \"openssl\")))]\n\npub type DefaultConnector = HttpsConnector<self::security_framework::ClientWrapper>;\n\n\n\n#[doc(hidden)]\n\npub type DefaultTransport = <DefaultConnector as Connect>::Output;\n\n*/\n", "file_path": "src/net.rs", "rank": 61, "score": 114556.88922373737 }, { "content": "#[derive(Clone, Debug)]\n\nstruct Http2Request {\n\n head: RequestHead,\n\n body: Vec<u8>,\n\n}\n\n\n\n/// Represents an HTTP/2 response.\n\n/// A convenience struct only in use by the `Http2Message`.\n", "file_path": "src/http/h2/mod.rs", "rank": 62, "score": 111600.28522637516 }, { "content": "#[derive(Clone, Debug)]\n\nstruct Http2Response {\n\n body: Cursor<Vec<u8>>,\n\n}\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 63, "score": 111600.28522637516 }, { "content": "#[derive(Clone, Copy)]\n\nstruct ChunkSize {\n\n bytes: [u8; CHUNK_SIZE_MAX_BYTES],\n\n pos: u8,\n\n len: u8,\n\n}\n\n\n\nimpl ChunkSize {\n\n fn update(&mut self, n: usize) -> usize {\n\n let diff = (self.len - self.pos).into();\n\n if n >= diff {\n\n self.pos = 0;\n\n self.len = 0;\n\n n - diff\n\n } else {\n\n self.pos += n as u8; // just verified it was a small usize\n\n 0\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/http/h1/encode.rs", "rank": 64, "score": 111600.28522637516 }, { "content": "#[test]\n\nfn test_get_type() {\n\n use ::header::{ContentLength, UserAgent};\n\n\n\n let len = ContentLength(5);\n\n let agent = UserAgent(\"hyper\".to_owned());\n\n\n\n assert_eq!(TypeId::of::<ContentLength>(), len.get_type());\n\n assert_eq!(TypeId::of::<UserAgent>(), agent.get_type());\n\n\n\n let len: Box<Header + Send + Sync> = Box::new(len);\n\n let agent: Box<Header + Send + Sync> = Box::new(agent);\n\n\n\n assert_eq!(TypeId::of::<ContentLength>(), (*len).get_type());\n\n assert_eq!(TypeId::of::<UserAgent>(), (*agent).get_type());\n\n}\n\n\n", "file_path": "src/header/mod.rs", "rank": 65, "score": 110023.07276027706 }, { "content": "#[test]\n\nfn test_should_keep_alive() {\n\n let mut headers = Headers::new();\n\n\n\n assert!(!should_keep_alive(Http10, &headers));\n\n assert!(should_keep_alive(Http11, &headers));\n\n\n\n headers.set(Connection::close());\n\n assert!(!should_keep_alive(Http10, &headers));\n\n assert!(!should_keep_alive(Http11, &headers));\n\n\n\n headers.set(Connection::keep_alive());\n\n assert!(should_keep_alive(Http10, &headers));\n\n assert!(should_keep_alive(Http11, &headers));\n\n}\n", "file_path": "src/http/mod.rs", "rank": 66, "score": 108735.58686938044 }, { "content": "#[test]\n\nfn cookie_jar() {\n\n let jar = CookieJar::new(b\"secret\");\n\n let cookie = CookiePair::new(\"foo\".to_owned(), \"bar\".to_owned());\n\n jar.add(cookie);\n\n\n\n let cookies = SetCookie::from_cookie_jar(&jar);\n\n\n\n let mut new_jar = CookieJar::new(b\"secret\");\n\n cookies.apply_to_cookie_jar(&mut new_jar);\n\n\n\n assert_eq!(jar.find(\"foo\"), new_jar.find(\"foo\"));\n\n assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>());\n\n}\n", "file_path": "src/header/common/set_cookie.rs", "rank": 67, "score": 107899.9696371894 }, { "content": "#[test]\n\nfn test_fmt() {\n\n use header::Headers;\n\n\n\n let mut cookie = CookiePair::new(\"foo\".to_owned(), \"bar\".to_owned());\n\n cookie.httponly = true;\n\n cookie.path = Some(\"/p\".to_owned());\n\n let cookies = SetCookie(vec![cookie, CookiePair::new(\"baz\".to_owned(), \"quux\".to_owned())]);\n\n let mut headers = Headers::new();\n\n headers.set(cookies);\n\n\n\n assert_eq!(\n\n &headers.to_string()[..],\n\n \"Set-Cookie: foo=bar; HttpOnly; Path=/p\\r\\nSet-Cookie: baz=quux\\r\\n\");\n\n}\n\n\n", "file_path": "src/header/common/set_cookie.rs", "rank": 68, "score": 107899.9696371894 }, { "content": "#[test]\n\nfn test_parse() {\n\n let h = Header::parse_header(&\"foo=bar; HttpOnly\".into());\n\n let mut c1 = CookiePair::new(\"foo\".to_owned(), \"bar\".to_owned());\n\n c1.httponly = true;\n\n\n\n assert_eq!(h.ok(), Some(SetCookie(vec![c1])));\n\n}\n\n\n", "file_path": "src/header/common/set_cookie.rs", "rank": 69, "score": 107899.9696371894 }, { "content": "/// Parses the response, as returned by `solicit`, into a `ResponseHead` and the full response\n\n/// body.\n\n///\n\n/// Returns them as a two-tuple.\n\nfn parse_response(response: ::solicit::http::Response) -> ::Result<(ResponseHead, Vec<u8>)> {\n\n let status = try!(response.status_code());\n\n let headers = try!(parse_headers(response.headers));\n\n Ok((ResponseHead {\n\n headers: headers,\n\n raw_status: RawStatus(status, \"\".into()),\n\n version: version::HttpVersion::Http20,\n\n }, response.body))\n\n}\n\n\n\nimpl<S> HttpMessage for Http2Message<S> where S: CloneableStream {\n\n fn set_outgoing(&mut self, head: RequestHead) -> ::Result<RequestHead> {\n\n match self.state {\n\n MessageState::Writing(_) | MessageState::Reading(_) => {\n\n return Err(From::from(Http2Error::from(\n\n io::Error::new(io::ErrorKind::Other,\n\n \"An outoging has already been set\"))));\n\n },\n\n MessageState::Idle => {},\n\n };\n", "file_path": "src/http/h2/mod.rs", "rank": 70, "score": 107368.43091633476 }, { "content": "struct Http1<H, T> {\n\n handler: H,\n\n reading: Reading,\n\n writing: Writing,\n\n keep_alive: bool,\n\n timeout: Option<Duration>,\n\n _marker: PhantomData<T>,\n\n}\n\n\n\nimpl<H, T> fmt::Debug for Http1<H, T> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"Http1\")\n\n .field(\"reading\", &self.reading)\n\n .field(\"writing\", &self.writing)\n\n .field(\"keep_alive\", &self.keep_alive)\n\n .field(\"timeout\", &self.timeout)\n\n .finish()\n\n }\n\n}\n\n\n", "file_path": "src/http/conn.rs", "rank": 71, "score": 106041.97785009128 }, { "content": "/// Convinience function to wrap a value in a `QualityItem`\n\n/// Sets `q` to the default 1.0\n\npub fn qitem<T>(item: T) -> QualityItem<T> {\n\n QualityItem::new(item, Default::default())\n\n}\n\n\n", "file_path": "src/header/shared/quality_item.rs", "rank": 72, "score": 103504.47498049925 }, { "content": "fn work(rx: spmc::Receiver<String>, notify: channel::Sender<Answer>) {\n\n thread::spawn(move || {\n\n let mut worker = Worker::new(rx, notify);\n\n let rx = worker.rx.as_ref().expect(\"Worker lost rx\");\n\n let notify = worker.notify.as_ref().expect(\"Worker lost notify\");\n\n while let Ok(host) = rx.recv() {\n\n debug!(\"resolve {:?}\", host);\n\n let res = match (&*host, 80).to_socket_addrs().map(|i| IpAddrs{ iter: i }) {\n\n Ok(addrs) => (host, Ok(addrs)),\n\n Err(e) => (host, Err(e))\n\n };\n\n\n\n if let Err(_) = notify.send(res) {\n\n break;\n\n }\n\n }\n\n worker.shutdown = true;\n\n });\n\n}\n\n\n", "file_path": "src/client/dns.rs", "rank": 73, "score": 101924.32323947467 }, { "content": "fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool {\n\n if a.len() != b.len() {\n\n false\n\n } else {\n\n for (a, b) in a.iter().zip(b.iter()) {\n\n if a.as_ref() != b.as_ref() {\n\n return false\n\n }\n\n }\n\n true\n\n }\n\n}\n\n\n\nimpl PartialEq<[Vec<u8>]> for Raw {\n\n fn eq(&self, bytes: &[Vec<u8>]) -> bool {\n\n match self.0 {\n\n Lines::One(ref line) => eq(&[line], bytes),\n\n Lines::Many(ref lines) => eq(lines, bytes)\n\n }\n\n }\n", "file_path": "src/header/raw.rs", "rank": 74, "score": 98933.70220324757 }, { "content": "#[derive(Clone)]\n\nstruct Http2Stream<S: CloneableStream>(S);\n\n\n\nimpl<S> Write for Http2Stream<S> where S: CloneableStream {\n\n #[inline]\n\n fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n\n self.0.write(buf)\n\n }\n\n #[inline]\n\n fn flush(&mut self) -> io::Result<()> {\n\n self.0.flush()\n\n }\n\n}\n\n\n\nimpl<S> Read for Http2Stream<S> where S: CloneableStream {\n\n #[inline]\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.0.read(buf)\n\n }\n\n}\n\n\n\nimpl<S> TransportStream for Http2Stream<S> where S: CloneableStream {\n\n fn try_split(&self) -> Result<Http2Stream<S>, io::Error> {\n\n Ok(self.clone())\n\n }\n\n\n\n fn close(&mut self) -> Result<(), io::Error> {\n\n self.0.close(Shutdown::Both)\n\n }\n\n}\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 75, "score": 96156.19215621175 }, { "content": "/// A helper struct that implements the `HttpConnect` trait from the `solicit` crate.\n\n///\n\n/// This is used by the `Http2Protocol` when it needs to create a new `SimpleClient`.\n\nstruct Http2Connector<S> where S: CloneableStream {\n\n stream: S,\n\n scheme: HttpScheme,\n\n host: String,\n\n}\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 76, "score": 94425.9733356118 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Prefix(Option<WriteBuf<Vec<u8>>>);\n\n\n\nimpl Prefix {\n\n fn update(&mut self, n: usize) -> usize {\n\n if let Some(mut buf) = self.0.take() {\n\n if buf.bytes.len() - buf.pos > n {\n\n buf.pos += n;\n\n self.0 = Some(buf);\n\n 0\n\n } else {\n\n let nbuf = buf.bytes.len() - buf.pos;\n\n n - nbuf\n\n }\n\n } else {\n\n n\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/http/h1/encode.rs", "rank": 77, "score": 94404.50488069507 }, { "content": "enum State<H: MessageHandler<T>, T: Transport> {\n\n Init {\n\n interest: Next_,\n\n timeout: Option<Duration>,\n\n },\n\n /// Http1 will only ever use a connection to send and receive a single\n\n /// message at a time. Once a H1 status has been determined, we will either\n\n /// be reading or writing an H1 message, and optionally multiple if\n\n /// keep-alive is true.\n\n Http1(Http1<H, T>),\n\n /// Http2 allows multiplexing streams over a single connection. So even\n\n /// when we've identified a certain message, we must always parse frame\n\n /// head to determine if the incoming frame is part of a current message,\n\n /// or a new one. This also means we could have multiple messages at once.\n\n //Http2 {},\n\n Closed,\n\n}\n\n\n\n\n\nimpl<H: MessageHandler<T>, T: Transport> State<H, T> {\n", "file_path": "src/http/conn.rs", "rank": 78, "score": 93242.24886812537 }, { "content": "#[inline]\n\nfn prepare_body(body: Vec<u8>) -> Option<Vec<u8>> {\n\n if body.is_empty() {\n\n None\n\n } else {\n\n Some(body)\n\n }\n\n}\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 79, "score": 86428.94157165443 }, { "content": "/// Parses a set of HTTP/2 headers into a `hyper::header::Headers` struct.\n\nfn parse_headers(http2_headers: Vec<Http2Header>) -> ::Result<Headers> {\n\n // Adapt the header name from `Vec<u8>` to `String`, without making any copies.\n\n let mut headers = Vec::new();\n\n for (name, value) in http2_headers.into_iter() {\n\n let name = match String::from_utf8(name) {\n\n Ok(name) => name,\n\n Err(_) => return Err(From::from(Http2Error::MalformedResponse)),\n\n };\n\n headers.push((name, value));\n\n }\n\n\n\n let mut raw_headers = Vec::new();\n\n for &(ref name, ref value) in &headers {\n\n raw_headers.push(httparse::Header { name: &name, value: &value });\n\n }\n\n\n\n Headers::from_raw(&raw_headers)\n\n}\n\n\n", "file_path": "src/http/h2/mod.rs", "rank": 80, "score": 86067.61216300596 }, { "content": "mod tests {\n\n use super::IfNoneMatch;\n\n use header::Header;\n\n use header::EntityTag;\n\n\n\n #[test]\n\n fn test_if_none_match() {\n\n let mut if_none_match: ::Result<IfNoneMatch>;\n\n\n\n if_none_match = Header::parse_header(&b\"*\".as_ref().into());\n\n assert_eq!(if_none_match.ok(), Some(IfNoneMatch::Any));\n\n\n\n if_none_match = Header::parse_header(&b\"\\\"foobar\\\", W/\\\"weak-etag\\\"\".as_ref().into());\n\n let mut entities: Vec<EntityTag> = Vec::new();\n\n let foobar_etag = EntityTag::new(false, \"foobar\".to_owned());\n\n let weak_etag = EntityTag::new(true, \"weak-etag\".to_owned());\n\n entities.push(foobar_etag);\n\n entities.push(weak_etag);\n\n assert_eq!(if_none_match.ok(), Some(IfNoneMatch::Items(entities)));\n\n }\n\n}\n\n\n\nbench_header!(bench, IfNoneMatch, { vec![b\"W/\\\"nonemptytag\\\"\".to_vec()] });\n", "file_path": "src/header/common/if_none_match.rs", "rank": 81, "score": 85177.9701221259 }, { "content": " /// ```\n\n ///\n\n /// # Example values\n\n /// * `\"xyzzy\"`\n\n /// * `W/\"xyzzy\"`\n\n /// * `\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"`\n\n /// * `W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\"`\n\n /// * `*`\n\n ///\n\n /// # Examples\n\n /// ```\n\n /// use hyper::header::{Headers, IfNoneMatch};\n\n ///\n\n /// let mut headers = Headers::new();\n\n /// headers.set(IfNoneMatch::Any);\n\n /// ```\n\n /// ```\n\n /// use hyper::header::{Headers, IfNoneMatch, EntityTag};\n\n ///\n\n /// let mut headers = Headers::new();\n", "file_path": "src/header/common/if_none_match.rs", "rank": 82, "score": 85177.76132533276 }, { "content": "use header::EntityTag;\n\n\n\nheader! {\n\n /// `If-None-Match` header, defined in\n\n /// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2)\n\n ///\n\n /// The `If-None-Match` header field makes the request method conditional\n\n /// on a recipient cache or origin server either not having any current\n\n /// representation of the target resource, when the field-value is \"*\",\n\n /// or having a selected representation with an entity-tag that does not\n\n /// match any of those listed in the field-value.\n\n ///\n\n /// A recipient MUST use the weak comparison function when comparing\n\n /// entity-tags for If-None-Match (Section 2.3.2), since weak entity-tags\n\n /// can be used for cache validation even if there have been changes to\n\n /// the representation data.\n\n ///\n\n /// # ABNF\n\n /// ```plain\n\n /// If-None-Match = \"*\" / 1#entity-tag\n", "file_path": "src/header/common/if_none_match.rs", "rank": 83, "score": 85172.7024011545 }, { "content": " /// headers.set(\n\n /// IfNoneMatch::Items(vec![\n\n /// EntityTag::new(false, \"xyzzy\".to_owned()),\n\n /// EntityTag::new(false, \"foobar\".to_owned()),\n\n /// EntityTag::new(false, \"bazquux\".to_owned()),\n\n /// ])\n\n /// );\n\n /// ```\n\n (IfNoneMatch, \"If-None-Match\") => {Any / (EntityTag)+}\n\n\n\n test_if_none_match {\n\n test_header!(test1, vec![b\"\\\"xyzzy\\\"\"]);\n\n test_header!(test2, vec![b\"W/\\\"xyzzy\\\"\"]);\n\n test_header!(test3, vec![b\"\\\"xyzzy\\\", \\\"r2d2xxxx\\\", \\\"c3piozzzz\\\"\"]);\n\n test_header!(test4, vec![b\"W/\\\"xyzzy\\\", W/\\\"r2d2xxxx\\\", W/\\\"c3piozzzz\\\"\"]);\n\n test_header!(test5, vec![b\"*\"]);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/header/common/if_none_match.rs", "rank": 84, "score": 85168.14997687307 }, { "content": "fn from_f32(f: f32) -> Quality {\n\n // this function is only used internally. A check that `f` is within range\n\n // should be done before calling this method. Just in case, this\n\n // debug_assert should catch if we were forgetful\n\n debug_assert!(f >= 0f32 && f <= 1f32, \"q value must be between 0.0 and 1.0\");\n\n Quality((f * 1000f32) as u16)\n\n}\n\n\n", "file_path": "src/header/shared/quality_item.rs", "rank": 85, "score": 82653.75534112289 }, { "content": "#[derive(Debug)]\n\nenum DecoderImpl<'a, T: Read + 'a> {\n\n H1(&'a mut h1::Decoder, Trans<'a, T>),\n\n}\n\n\n", "file_path": "src/http/mod.rs", "rank": 86, "score": 79491.39810466628 }, { "content": "struct Client {\n\n client: Option<hyper::Client<TestHandler>>,\n\n}\n\n\n", "file_path": "tests/client.rs", "rank": 87, "score": 75042.45929092816 }, { "content": "struct Echo {\n\n buf: Vec<u8>,\n\n read_pos: usize,\n\n write_pos: usize,\n\n eof: bool,\n\n route: Route,\n\n}\n\n\n", "file_path": "examples/server.rs", "rank": 88, "score": 75042.45929092816 }, { "content": "struct Serve {\n\n listening: Option<hyper::server::Listening>,\n\n msg_rx: mpsc::Receiver<Msg>,\n\n reply_tx: mpsc::Sender<Reply>,\n\n}\n\n\n\nimpl Serve {\n\n fn addrs(&self) -> &[SocketAddr] {\n\n self.listening.as_ref().unwrap().addrs()\n\n }\n\n\n\n fn addr(&self) -> &SocketAddr {\n\n let addrs = self.addrs();\n\n assert!(addrs.len() == 1);\n\n &addrs[0]\n\n }\n\n\n\n /*\n\n fn head(&self) -> Request {\n\n unimplemented!()\n", "file_path": "tests/server.rs", "rank": 89, "score": 75042.45929092816 }, { "content": "struct Hello;\n\n\n\nimpl Handler<HttpStream> for Hello {\n\n fn on_request(&mut self, _: Request<HttpStream>) -> Next {\n\n Next::write()\n\n }\n\n fn on_request_readable(&mut self, _: &mut Decoder<HttpStream>) -> Next {\n\n Next::write()\n\n }\n\n fn on_response(&mut self, response: &mut Response) -> Next {\n\n use hyper::header::ContentLength;\n\n response.headers_mut().set(ContentLength(PHRASE.len() as u64));\n\n Next::write()\n\n }\n\n fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next {\n\n let n = encoder.write(PHRASE).unwrap();\n\n debug_assert_eq!(n, PHRASE.len());\n\n Next::end()\n\n }\n\n}\n\n\n", "file_path": "examples/hello.rs", "rank": 90, "score": 75042.45929092816 }, { "content": "#[derive(Debug)]\n\nstruct Opts {\n\n body: Option<&'static [u8]>,\n\n method: Method,\n\n headers: Headers,\n\n read_timeout: Option<Duration>,\n\n}\n\n\n\nimpl Default for Opts {\n\n fn default() -> Opts {\n\n Opts {\n\n body: None,\n\n method: Method::Get,\n\n headers: Headers::new(),\n\n read_timeout: None,\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/client.rs", "rank": 91, "score": 75042.45929092816 }, { "content": "struct TestHandler {\n\n tx: mpsc::Sender<Msg>,\n\n reply: Vec<Reply>,\n\n peeked: Option<Vec<u8>>,\n\n timeout: Option<Duration>,\n\n}\n\n\n", "file_path": "tests/server.rs", "rank": 92, "score": 73784.2233520713 }, { "content": "#[derive(Debug)]\n\nstruct TestHandler {\n\n opts: Opts,\n\n tx: mpsc::Sender<Msg>\n\n}\n\n\n\nimpl TestHandler {\n\n fn new(opts: Opts) -> (TestHandler, mpsc::Receiver<Msg>) {\n\n let (tx, rx) = mpsc::channel();\n\n (TestHandler {\n\n opts: opts,\n\n tx: tx\n\n }, rx)\n\n }\n\n}\n\n\n", "file_path": "tests/client.rs", "rank": 93, "score": 73784.2233520713 }, { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n\n\n let url = match env::args().nth(1) {\n\n Some(url) => url,\n\n None => {\n\n println!(\"Usage: client <url>\");\n\n return;\n\n }\n\n };\n\n\n\n let (tx, rx) = mpsc::channel();\n\n let client = Client::new().expect(\"Failed to create a Client\");\n\n client.request(url.parse().unwrap(), Dump(tx)).unwrap();\n\n\n\n // wait till done\n\n let _ = rx.recv();\n\n client.close();\n\n}\n", "file_path": "examples/client.rs", "rank": 94, "score": 72150.8544978623 }, { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n let server = Server::http(&\"127.0.0.1:1337\".parse().unwrap()).unwrap();\n\n let (listening, server) = server.handle(|_| Echo::new()).unwrap();\n\n println!(\"Listening on http://{}\", listening);\n\n server.run();\n\n}\n", "file_path": "examples/server.rs", "rank": 95, "score": 72150.8544978623 }, { "content": "fn main() {\n\n env_logger::init().unwrap();\n\n \n\n let listener = HttpListener::bind(&\"127.0.0.1:3000\".parse().unwrap()).unwrap();\n\n let mut handles = Vec::new();\n\n\n\n for _ in 0..num_cpus::get() {\n\n let listener = listener.try_clone().unwrap();\n\n handles.push(::std::thread::spawn(move || {\n\n Server::new(listener)\n\n .handle(|_| Hello).unwrap();\n\n }));\n\n }\n\n println!(\"Listening on http://127.0.0.1:3000\");\n\n\n\n for handle in handles {\n\n handle.join().unwrap();\n\n }\n\n}\n", "file_path": "examples/hello.rs", "rank": 96, "score": 72150.8544978623 }, { "content": "struct ReplyBuilder<'a> {\n\n tx: &'a mpsc::Sender<Reply>,\n\n}\n\n\n\nimpl<'a> ReplyBuilder<'a> {\n\n fn status(self, status: hyper::StatusCode) -> Self {\n\n self.tx.send(Reply::Status(status)).unwrap();\n\n self\n\n }\n\n\n\n fn header<H: hyper::header::Header>(self, header: H) -> Self {\n\n let mut headers = hyper::Headers::new();\n\n headers.set(header);\n\n self.tx.send(Reply::Headers(headers)).unwrap();\n\n self\n\n }\n\n\n\n fn body<T: AsRef<[u8]>>(self, body: T) {\n\n self.tx.send(Reply::Body(body.as_ref().into())).unwrap();\n\n }\n\n}\n\n\n\nimpl Drop for Serve {\n\n fn drop(&mut self) {\n\n self.listening.take().unwrap().close();\n\n }\n\n}\n\n\n", "file_path": "tests/server.rs", "rank": 97, "score": 70725.92948888458 }, { "content": "#[test]\n\nfn server_get_with_body() {\n\n let server = serve();\n\n let mut req = TcpStream::connect(server.addr()).unwrap();\n\n req.write_all(b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n Host: example.domain\\r\\n\\\n\n Content-Length: 19\\r\\n\\\n\n \\r\\n\\\n\n I'm a good request.\\r\\n\\\n\n \").unwrap();\n\n req.read(&mut [0; 256]).unwrap();\n\n\n\n // note: doesnt include trailing \\r\\n, cause Content-Length wasn't 21\n\n assert_eq!(server.body(), b\"I'm a good request.\");\n\n}\n\n\n", "file_path": "tests/server.rs", "rank": 98, "score": 69724.83535647171 }, { "content": "#[test]\n\nfn server_empty_response() {\n\n let server = serve();\n\n server.reply()\n\n .status(hyper::Ok);\n\n let mut req = TcpStream::connect(server.addr()).unwrap();\n\n req.write_all(b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n Host: example.domain\\r\\n\\\n\n Connection: close\\r\\n\n\n \\r\\n\\\n\n \").unwrap();\n\n\n\n let mut response = String::new();\n\n req.read_to_string(&mut response).unwrap();\n\n\n\n assert_eq!(response, \"foo\");\n\n assert!(!response.contains(\"Transfer-Encoding: chunked\\r\\n\"));\n\n\n\n let mut lines = response.lines();\n\n assert_eq!(lines.next(), Some(\"HTTP/1.1 200 OK\"));\n\n\n\n let mut lines = lines.skip_while(|line| !line.is_empty());\n\n assert_eq!(lines.next(), Some(\"\"));\n\n assert_eq!(lines.next(), None);\n\n}\n\n*/\n\n\n", "file_path": "tests/server.rs", "rank": 99, "score": 69724.83535647171 } ]
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(Error::new(Span::call_site(), err)),\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Attrs<A> {\n\n pub paren: syn::token::Paren,\n\n pub attrs: Punctuated<A, syn::token::Comma>,\n\n}\n\n\n\nimpl<A: Parse> Parse for Attrs<A> {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n let content;\n\n let paren = syn::parenthesized!(content in input);\n\n let attrs = content.parse_terminated(A::parse)?;\n\n Ok(Self { paren, attrs })\n", "file_path": "derive/src/utils.rs", "rank": 3, "score": 117226.02043714165 }, { "content": "fn bench_digest(c: &mut Criterion) {\n\n let mut rng = rand::thread_rng();\n\n let data: Vec<u8> = (0..1024).map(|_| rng.gen()).collect();\n\n group_digest!(c,\n\n \"sha1\" => Sha1, &data\n\n \"sha2_256\" => Sha2_256, &data\n\n \"sha2_512\" => Sha2_512, &data\n\n \"sha3_224\" => Sha3_224, &data\n\n \"sha3_256\" => Sha3_256, &data\n\n \"sha3_384\" => Sha3_384, &data\n\n \"sha3_512\" => Sha3_512, &data\n\n \"keccak_224\" => Keccak224, &data\n\n \"keccak_256\" => Keccak256, &data\n\n \"keccak_384\" => Keccak384, &data\n\n \"keccak_512\" => Keccak512, &data\n\n \"blake2b_256\" => Blake2b256, &data\n\n \"blake2b_512\" => Blake2b512, &data\n\n \"blake2s_128\" => Blake2s128, &data\n\n \"blake2s_256\" => Blake2s256, &data\n\n \"blake3_256\" => Blake3_256, &data\n\n \"strobe_256\" => Strobe256, &data\n\n \"strobe_512\" => Strobe512, &data\n\n );\n\n}\n\n\n", "file_path": "benches/multihash.rs", "rank": 4, "score": 103354.99507813528 }, { "content": "pub fn multihash(s: Structure) -> TokenStream {\n\n let mh_crate = match utils::use_crate(\"multihash\") {\n\n Ok(ident) => ident,\n\n Err(e) => {\n\n let err = syn::Error::new(Span::call_site(), e).to_compile_error();\n\n return quote!(#err);\n\n }\n\n };\n\n let code_enum = &s.ast().ident;\n\n let alloc_size = parse_code_enum_attrs(s.ast());\n\n let hashes: Vec<_> = s.variants().iter().map(Hash::from).collect();\n\n\n\n error_code_duplicates(&hashes);\n\n\n\n let params = Params {\n\n code_enum: code_enum.clone(),\n\n };\n\n\n\n let code_into_u64 = hashes.iter().map(|h| h.code_into_u64(&params));\n\n let code_from_u64 = hashes.iter().map(|h| h.code_from_u64());\n", "file_path": "derive/src/multihash.rs", "rank": 5, "score": 94457.59356619185 }, { "content": "/// Testing the public interface of `Multihash` and coversions to it\n\nfn multihash_methods<H>(code: Code, prefix: &str, digest_str: &str)\n\nwhere\n\n H: Hasher + Default,\n\n{\n\n let digest = hex::decode(digest_str).unwrap();\n\n let expected_bytes = hex::decode(&format!(\"{}{}\", prefix, digest_str)).unwrap();\n\n let mut expected_cursor = Cursor::new(&expected_bytes);\n\n let multihash = code.digest(b\"hello world\");\n\n\n\n assert_eq!(Multihash::wrap(code.into(), &digest).unwrap(), multihash);\n\n assert_eq!(multihash.code(), u64::from(code));\n\n assert_eq!(multihash.size() as usize, digest.len());\n\n assert_eq!(multihash.digest(), digest);\n\n assert_eq!(Multihash::read(&mut expected_cursor).unwrap(), multihash);\n\n assert_eq!(Multihash::from_bytes(&expected_bytes).unwrap(), multihash);\n\n let mut written_buf = Vec::new();\n\n multihash.write(&mut written_buf).unwrap();\n\n assert_eq!(written_buf, expected_bytes);\n\n assert_eq!(multihash.to_bytes(), expected_bytes);\n\n\n\n // Test from hasher digest conversion\n\n let mut hasher = H::default();\n\n hasher.update(b\"hello world\");\n\n let multihash_from_digest = code.wrap(hasher.finalize()).unwrap();\n\n assert_eq!(multihash_from_digest.code(), u64::from(code));\n\n assert_eq!(multihash_from_digest.size() as usize, digest.len());\n\n assert_eq!(multihash_from_digest.digest(), digest);\n\n}\n\n\n", "file_path": "tests/lib.rs", "rank": 6, "score": 91807.36371862858 }, { "content": "/// Return an error if the same code is used several times.\n\n///\n\n/// This only checks for string equality, though this should still catch most errors caused by\n\n/// copy and pasting.\n\nfn error_code_duplicates(hashes: &[Hash]) {\n\n // Use a temporary store to determine whether a certain value is unique or not\n\n let mut uniq = HashSet::new();\n\n\n\n hashes.iter().for_each(|hash| {\n\n let code = &hash.code;\n\n let msg = format!(\n\n \"the #mh(code) attribute `{}` is defined multiple times\",\n\n quote!(#code)\n\n );\n\n\n\n // It's a duplicate\n\n if !uniq.insert(code) {\n\n #[cfg(test)]\n\n panic!(\"{}\", msg);\n\n #[cfg(not(test))]\n\n {\n\n let already_defined = uniq.get(code).unwrap();\n\n let line = already_defined.to_token_stream().span().start().line;\n\n proc_macro_error::emit_error!(\n\n &hash.code, msg;\n\n note = \"previous definition of `{}` at line {}\", quote!(#code), line;\n\n );\n\n }\n\n }\n\n });\n\n}\n\n\n\n/// An error that contains a span in order to produce nice error messages.\n", "file_path": "derive/src/multihash.rs", "rank": 7, "score": 82737.57387997584 }, { "content": "/// Chunks the data into 256-byte slices.\n\nfn bench_stream(c: &mut Criterion) {\n\n let mut rng = rand::thread_rng();\n\n let data: Vec<u8> = (0..1024).map(|_| rng.gen()).collect();\n\n group_stream!(c,\n\n \"sha1\" => Sha1, &data\n\n \"sha2_256\" => Sha2_256, &data\n\n \"sha2_512\" => Sha2_512, &data\n\n \"sha3_224\" => Sha3_224, &data\n\n \"sha3_256\" => Sha3_256, &data\n\n \"sha3_384\" => Sha3_384, &data\n\n \"sha3_512\" => Sha3_512, &data\n\n \"keccak_224\" => Keccak224, &data\n\n \"keccak_256\" => Keccak256, &data\n\n \"keccak_384\" => Keccak384, &data\n\n \"keccak_512\" => Keccak512, &data\n\n \"blake2b_256\" => Blake2b256, &data\n\n \"blake2b_512\" => Blake2b512, &data\n\n \"blake2s_128\" => Blake2s128, &data\n\n \"blake2s_256\" => Blake2s256, &data\n\n \"blake3_256\" => Blake3_256, &data\n\n \"strobe_256\" => Strobe256, &data\n\n \"strobe_512\" => Strobe512, &data\n\n );\n\n}\n\n\n\ncriterion_group!(benches, bench_digest, bench_stream);\n\ncriterion_main!(benches);\n", "file_path": "benches/multihash.rs", "rank": 8, "score": 82470.83236281651 }, { "content": "/// Trait implemented by a hash function implementation.\n\npub trait Hasher {\n\n /// Consume input and update internal state.\n\n fn update(&mut self, input: &[u8]);\n\n\n\n /// Returns the final digest.\n\n fn finalize(&mut self) -> &[u8];\n\n\n\n /// Reset the internal hasher state.\n\n fn reset(&mut self);\n\n}\n", "file_path": "src/hasher.rs", "rank": 9, "score": 79780.4711610111 }, { "content": "#[test]\n\nfn multihash_errors() {\n\n assert!(\n\n Multihash::from_bytes(&[]).is_err(),\n\n \"Should error on empty data\"\n\n );\n\n assert!(\n\n Multihash::from_bytes(&[1, 2, 3]).is_err(),\n\n \"Should error on invalid multihash\"\n\n );\n\n assert!(\n\n Multihash::from_bytes(&[1, 2, 3]).is_err(),\n\n \"Should error on invalid prefix\"\n\n );\n\n assert!(\n\n Multihash::from_bytes(&[0x12, 0x20, 0xff]).is_err(),\n\n \"Should error on correct prefix with wrong digest\"\n\n );\n\n let identity_code: u8 = 0x00;\n\n let identity_length = 3;\n\n assert!(\n\n Multihash::from_bytes(&[identity_code, identity_length, 1, 2, 3, 4]).is_err(),\n\n \"Should error on wrong hash length\"\n\n );\n\n}\n", "file_path": "tests/lib.rs", "rank": 10, "score": 78615.68872750134 }, { "content": "#[derive(Debug)]\n\nstruct ParseError(Span);\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 11, "score": 76121.91228936217 }, { "content": "/// Parse top-level enum [#mh()] attributes.\n\n///\n\n/// Returns the `alloc_size` and whether errors regarding to `alloc_size` should be reported or not.\n\nfn parse_code_enum_attrs(ast: &syn::DeriveInput) -> syn::LitInt {\n\n let mut alloc_size = None;\n\n\n\n for attr in &ast.attrs {\n\n let derive_attrs: Result<utils::Attrs<DeriveAttr>, _> = syn::parse2(attr.tokens.clone());\n\n if let Ok(derive_attrs) = derive_attrs {\n\n for derive_attr in derive_attrs.attrs {\n\n match derive_attr {\n\n DeriveAttr::AllocSize(alloc_size_attr) => {\n\n alloc_size = Some(alloc_size_attr.value)\n\n }\n\n }\n\n }\n\n }\n\n }\n\n match alloc_size {\n\n Some(alloc_size) => alloc_size,\n\n None => {\n\n let msg = \"enum is missing `alloc_size` attribute: e.g. #[mh(alloc_size = 64)]\";\n\n #[cfg(test)]\n\n panic!(\"{}\", msg);\n\n #[cfg(not(test))]\n\n proc_macro_error::abort!(&ast.ident, msg);\n\n }\n\n }\n\n}\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 12, "score": 64751.296548034865 }, { "content": "#[derive(Debug)]\n\nstruct Hash {\n\n ident: syn::Ident,\n\n code: syn::Expr,\n\n hasher: Box<syn::Type>,\n\n}\n\n\n\nimpl Hash {\n\n fn code_into_u64(&self, params: &Params) -> TokenStream {\n\n let ident = &self.ident;\n\n let code_enum = &params.code_enum;\n\n let code = &self.code;\n\n quote!(#code_enum::#ident => #code)\n\n }\n\n\n\n fn code_from_u64(&self) -> TokenStream {\n\n let ident = &self.ident;\n\n let code = &self.code;\n\n quote!(#code => Ok(Self::#ident))\n\n }\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 13, "score": 61854.81372273536 }, { "content": "struct Params {\n\n code_enum: syn::Ident,\n\n}\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 14, "score": 61851.53435420485 }, { "content": "fn multihash(s: Structure) -> TokenStream {\n\n multihash::multihash(s).into()\n\n}\n", "file_path": "derive/src/lib.rs", "rank": 15, "score": 60096.58410889763 }, { "content": "#[allow(clippy::cognitive_complexity)]\n\n#[test]\n\nfn multihash_encode() {\n\n assert_encode! {\n\n Identity256, Code::Identity, b\"beep boop\", \"00096265657020626f6f70\";\n\n Sha1, Code::Sha1, b\"beep boop\", \"11147c8357577f51d4f0a8d393aa1aaafb28863d9421\";\n\n Sha2_256, Code::Sha2_256, b\"helloworld\", \"1220936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\";\n\n Sha2_256, Code::Sha2_256, b\"beep boop\", \"122090ea688e275d580567325032492b597bc77221c62493e76330b85ddda191ef7c\";\n\n Sha2_512, Code::Sha2_512, b\"hello world\", \"1340309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f\";\n\n Sha3_224, Code::Sha3_224, b\"hello world\", \"171Cdfb7f18c77e928bb56faeb2da27291bd790bc1045cde45f3210bb6c5\";\n\n Sha3_256, Code::Sha3_256, b\"hello world\", \"1620644bcc7e564373040999aac89e7622f3ca71fba1d972fd94a31c3bfbf24e3938\";\n\n Sha3_384, Code::Sha3_384, b\"hello world\", \"153083bff28dde1b1bf5810071c6643c08e5b05bdb836effd70b403ea8ea0a634dc4997eb1053aa3593f590f9c63630dd90b\";\n\n Sha3_512, Code::Sha3_512, b\"hello world\", \"1440840006653e9ac9e95117a15c915caab81662918e925de9e004f774ff82d7079a40d4d27b1b372657c61d46d470304c88c788b3a4527ad074d1dccbee5dbaa99a\";\n\n Keccak224, Code::Keccak224, b\"hello world\", \"1A1C25f3ecfebabe99686282f57f5c9e1f18244cfee2813d33f955aae568\";\n\n Keccak256, Code::Keccak256, b\"hello world\", \"1B2047173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad\";\n\n Keccak384, Code::Keccak384, b\"hello world\", \"1C3065fc99339a2a40e99d3c40d695b22f278853ca0f925cde4254bcae5e22ece47e6441f91b6568425adc9d95b0072eb49f\";\n\n Keccak512, Code::Keccak512, b\"hello world\", \"1D403ee2b40047b8060f68c67242175660f4174d0af5c01d47168ec20ed619b0b7c42181f40aa1046f39e2ef9efc6910782a998e0013d172458957957fac9405b67d\";\n\n Blake2b512, Code::Blake2b512, b\"hello world\", \"c0e40240021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbcc05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0\";\n\n Blake2s256, Code::Blake2s256, b\"hello world\", \"e0e402209aec6806794561107e594b1f6a8a6b0c92a0cba9acf5e5e93cca06f781813b0b\";\n\n Blake2b256, Code::Blake2b256, b\"hello world\", \"a0e40220256c83b297114d201b30179f3f0ef0cace9783622da5974326b436178aeef610\";\n\n Blake2s128, Code::Blake2s128, b\"hello world\", \"d0e4021037deae0226c30da2ab424a7b8ee14e83\";\n\n Blake3_256, Code::Blake3_256, b\"hello world\", \"1e20d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24\";\n", "file_path": "tests/lib.rs", "rank": 16, "score": 55536.109147238676 }, { "content": "#[test]\n\nfn test_multihash_methods() {\n\n multihash_methods::<Identity256>(Code::Identity, \"000b\", \"68656c6c6f20776f726c64\");\n\n multihash_methods::<Sha1>(\n\n Code::Sha1,\n\n \"1114\",\n\n \"2aae6c35c94fcfb415dbe95f408b9ce91ee846ed\",\n\n );\n\n multihash_methods::<Sha2_256>(\n\n Code::Sha2_256,\n\n \"1220\",\n\n \"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9\",\n\n );\n\n multihash_methods::<Sha2_512, >(\n\n Code::Sha2_512,\n\n \"1340\",\n\n \"309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f\");\n\n multihash_methods::<Sha3_224>(\n\n Code::Sha3_224,\n\n \"171C\",\n\n \"dfb7f18c77e928bb56faeb2da27291bd790bc1045cde45f3210bb6c5\",\n", "file_path": "tests/lib.rs", "rank": 17, "score": 53198.01711915467 }, { "content": "fn main() {\n\n // Create new hashes from some input data. This is done through the `Code` enum we derived\n\n // Multihash from.\n\n let blake_hash = Code::Blake2b200.digest(b\"hello world!\");\n\n println!(\"{:02x?}\", blake_hash);\n\n let truncated_sha2_hash = Code::Sha2_256Truncated20.digest(b\"hello world!\");\n\n println!(\"{:02x?}\", truncated_sha2_hash);\n\n\n\n // Sometimes you might not need to hash new data, you just want to get the information about\n\n // a Multihash.\n\n let truncated_sha2_bytes = truncated_sha2_hash.to_bytes();\n\n let unknown_hash = Multihash::from_bytes(&truncated_sha2_bytes).unwrap();\n\n println!(\"SHA2 256-bit hash truncated to 160 bits:\");\n\n println!(\" code: {:x?}\", unknown_hash.code());\n\n println!(\" size: {}\", unknown_hash.size());\n\n println!(\" digest: {:02x?}\", unknown_hash.digest());\n\n\n\n // Though you might want to hash something new, with the same hasher that some other Multihash\n\n // used.\n\n Code::try_from(unknown_hash.code())\n\n .unwrap()\n\n .digest(b\"hashing something new\");\n\n}\n", "file_path": "examples/custom_table.rs", "rank": 18, "score": 35777.894108326276 }, { "content": "#[test]\n\nfn assert_decode() {\n\n assert_decode! {\n\n Code::Identity, \"000a68656c6c6f776f726c64\";\n\n Code::Sha1, \"11147c8357577f51d4f0a8d393aa1aaafb28863d9421\";\n\n Code::Sha2_256, \"1220936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\";\n\n Code::Sha2_256, \"122090ea688e275d580567325032492b597bc77221c62493e76330b85ddda191ef7c\";\n\n Code::Sha2_512, \"1340309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f\";\n\n Code::Sha3_224, \"171Cdfb7f18c77e928bb56faeb2da27291bd790bc1045cde45f3210bb6c5\";\n\n Code::Sha3_256, \"1620644bcc7e564373040999aac89e7622f3ca71fba1d972fd94a31c3bfbf24e3938\";\n\n Code::Sha3_384, \"153083bff28dde1b1bf5810071c6643c08e5b05bdb836effd70b403ea8ea0a634dc4997eb1053aa3593f590f9c63630dd90b\";\n\n Code::Sha3_512, \"1440840006653e9ac9e95117a15c915caab81662918e925de9e004f774ff82d7079a40d4d27b1b372657c61d46d470304c88c788b3a4527ad074d1dccbee5dbaa99a\";\n\n Code::Keccak224, \"1A1C25f3ecfebabe99686282f57f5c9e1f18244cfee2813d33f955aae568\";\n\n Code::Keccak256, \"1B2047173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad\";\n\n Code::Keccak384, \"1C3065fc99339a2a40e99d3c40d695b22f278853ca0f925cde4254bcae5e22ece47e6441f91b6568425adc9d95b0072eb49f\";\n\n Code::Keccak512, \"1D403ee2b40047b8060f68c67242175660f4174d0af5c01d47168ec20ed619b0b7c42181f40aa1046f39e2ef9efc6910782a998e0013d172458957957fac9405b67d\";\n\n Code::Blake2b512, \"c0e40240021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbcc05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0\";\n\n Code::Blake2s256, \"e0e402209aec6806794561107e594b1f6a8a6b0c92a0cba9acf5e5e93cca06f781813b0b\";\n\n Code::Blake2b256, \"a0e40220256c83b297114d201b30179f3f0ef0cace9783622da5974326b436178aeef610\";\n\n Code::Blake2s128, \"d0e4021037deae0226c30da2ab424a7b8ee14e83\";\n\n Code::Blake3_256, \"1e20d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24\";\n", "file_path": "tests/lib.rs", "rank": 19, "score": 35777.894108326276 }, { "content": "#[allow(clippy::cognitive_complexity)]\n\n#[test]\n\nfn assert_roundtrip() {\n\n assert_roundtrip!(\n\n Code::Identity, Identity256;\n\n Code::Sha1, Sha1;\n\n Code::Sha2_256, Sha2_256;\n\n Code::Sha2_512, Sha2_512;\n\n Code::Sha3_224, Sha3_224;\n\n Code::Sha3_256, Sha3_256;\n\n Code::Sha3_384, Sha3_384;\n\n Code::Sha3_512, Sha3_512;\n\n Code::Keccak224, Keccak224;\n\n Code::Keccak256, Keccak256;\n\n Code::Keccak384, Keccak384;\n\n Code::Keccak512, Keccak512;\n\n Code::Blake2b512, Blake2b512;\n\n Code::Blake2s256, Blake2s256;\n\n Code::Blake3_256, Blake3_256;\n\n );\n\n}\n\n\n", "file_path": "tests/lib.rs", "rank": 20, "score": 35777.894108326276 }, { "content": "#[test]\n\n#[should_panic]\n\nfn test_long_identity_hash() {\n\n // The identity hash allocates if the input size is bigger than the maximum size\n\n let input = b\"abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz\";\n\n Code::Identity.digest(input);\n\n}\n\n\n", "file_path": "tests/lib.rs", "rank": 21, "score": 33410.05116633998 }, { "content": "#[cfg(not(feature = \"std\"))]\n\nuse core2::{error::Error as StdError, io::Error as IoError};\n\n#[cfg(feature = \"std\")]\n\nuse std::{error::Error as StdError, io::Error as IoError};\n\n\n\nuse unsigned_varint::decode::Error as DecodeError;\n\n#[cfg(feature = \"std\")]\n\nuse unsigned_varint::io::ReadError;\n\n\n\n/// Multihash error.\n\n#[derive(Debug)]\n\npub enum Error {\n\n /// Io error.\n\n Io(IoError),\n\n /// Unsupported multihash code.\n\n UnsupportedCode(u64),\n\n /// Invalid multihash size.\n\n InvalidSize(u64),\n\n /// Invalid varint.\n\n Varint(DecodeError),\n", "file_path": "src/error.rs", "rank": 22, "score": 26148.136807445404 }, { "content": "}\n\n\n\nimpl core::fmt::Display for Error {\n\n fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {\n\n match self {\n\n Self::Io(err) => write!(f, \"{}\", err),\n\n Self::UnsupportedCode(code) => write!(f, \"Unsupported multihash code {}.\", code),\n\n Self::InvalidSize(size) => write!(f, \"Invalid multihash size {}.\", size),\n\n Self::Varint(err) => write!(f, \"{}\", err),\n\n }\n\n }\n\n}\n\n\n\nimpl StdError for Error {}\n\n\n\nimpl From<IoError> for Error {\n\n fn from(err: IoError) -> Self {\n\n Self::Io(err)\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 23, "score": 26146.129811674607 }, { "content": "\n\n#[cfg(feature = \"std\")]\n\nimpl From<ReadError> for Error {\n\n fn from(err: ReadError) -> Self {\n\n match err {\n\n ReadError::Io(err) => Self::Io(err),\n\n ReadError::Decode(err) => Self::Varint(err),\n\n _ => unreachable!(),\n\n }\n\n }\n\n}\n\n\n\n/// Multihash result.\n\npub type Result<T> = core::result::Result<T, Error>;\n", "file_path": "src/error.rs", "rank": 24, "score": 26142.709639779314 }, { "content": "use criterion::{black_box, criterion_group, criterion_main, Criterion};\n\nuse rand::Rng;\n\n\n\nuse multihash::{\n\n Blake2b256, Blake2b512, Blake2s128, Blake2s256, Blake3_256, Hasher, Keccak224, Keccak256,\n\n Keccak384, Keccak512, Sha1, Sha2_256, Sha2_512, Sha3_224, Sha3_256, Sha3_384, Sha3_512,\n\n Strobe256, Strobe512,\n\n};\n\n\n\nmacro_rules! group_digest {\n\n ($criterion:ident, $( $id:expr => $hash:ident, $input:expr)* ) => {{\n\n let mut group = $criterion.benchmark_group(\"digest\");\n\n $(\n\n group.bench_function($id, |b| {\n\n b.iter(|| {\n\n let mut hasher = $hash::default();\n\n hasher.update(black_box($input));\n\n let _ = black_box(hasher.finalize());\n\n })\n\n });\n", "file_path": "benches/multihash.rs", "rank": 43, "score": 22377.171663754183 }, { "content": " )*\n\n group.finish();\n\n }};\n\n}\n\n\n\nmacro_rules! group_stream {\n\n ($criterion:ident, $( $id:expr => $hash:ident, $input:expr)* ) => {{\n\n let mut group = $criterion.benchmark_group(\"stream\");\n\n $(\n\n group.bench_function($id, |b| {\n\n b.iter(|| {\n\n let input = black_box($input);\n\n let mut hasher = <$hash>::default();\n\n for i in 0..3 {\n\n let start = i * 256;\n\n hasher.update(&input[start..(start + 256)]);\n\n }\n\n let _ = black_box(hasher.finalize());\n\n })\n\n });\n\n )*\n\n group.finish();\n\n }};\n\n}\n\n\n", "file_path": "benches/multihash.rs", "rank": 44, "score": 22373.011605835025 }, { "content": " let code_digest = hashes.iter().map(|h| h.code_digest());\n\n\n\n quote! {\n\n /// A Multihash with the same allocated size as the Multihashes produces by this derive.\n\n pub type Multihash = #mh_crate::MultihashGeneric<#alloc_size>;\n\n\n\n impl #mh_crate::MultihashDigest<#alloc_size> for #code_enum {\n\n fn digest(&self, input: &[u8]) -> Multihash {\n\n use #mh_crate::Hasher;\n\n match self {\n\n #(#code_digest,)*\n\n _ => unreachable!(),\n\n }\n\n }\n\n\n\n fn wrap(&self, digest: &[u8]) -> Result<Multihash, #mh_crate::Error> {\n\n Multihash::wrap((*self).into(), digest)\n\n }\n\n }\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 45, "score": 21006.569160335795 }, { "content": "\n\n fn wrap(&self, digest: &[u8]) -> Result<Multihash, multihash::Error> {\n\n Multihash::wrap((*self).into(), digest)\n\n }\n\n }\n\n\n\n impl From<Code> for u64 {\n\n fn from(code: Code) -> Self {\n\n match code {\n\n Code::Identity256 => multihash::IDENTITY,\n\n Code::Strobe256 => 0x38b64f,\n\n _ => unreachable!(),\n\n }\n\n }\n\n }\n\n\n\n impl core::convert::TryFrom<u64> for Code {\n\n type Error = multihash::Error;\n\n\n\n fn try_from(code: u64) -> Result<Self, Self::Error> {\n", "file_path": "derive/src/multihash.rs", "rank": 46, "score": 21004.296506074148 }, { "content": " /// A Multihash with the same allocated size as the Multihashes produces by this derive.\n\n pub type Multihash = multihash::MultihashGeneric<32>;\n\n\n\n impl multihash::MultihashDigest<32> for Code {\n\n fn digest(&self, input: &[u8]) -> Multihash {\n\n use multihash::Hasher;\n\n match self {\n\n Self::Identity256 => {\n\n let mut hasher = multihash::Identity256::default();\n\n hasher.update(input);\n\n Multihash::wrap(multihash::IDENTITY, hasher.finalize()).unwrap()\n\n },\n\n Self::Strobe256 => {\n\n let mut hasher = multihash::Strobe256::default();\n\n hasher.update(input);\n\n Multihash::wrap(0x38b64f, hasher.finalize()).unwrap()\n\n },\n\n _ => unreachable!(),\n\n }\n\n }\n", "file_path": "derive/src/multihash.rs", "rank": 47, "score": 21003.35243317892 }, { "content": "pub use multihash_derive::Multihash;\n\n\n\n/// Default (cryptographically secure) Multihash implementation.\n\n///\n\n/// This is a default set of hashing algorithms. Usually applications would use their own subset of\n\n/// algorithms. See the [`Multihash` derive] for more information.\n\n///\n\n/// [`Multihash` derive]: crate::derive\n\n#[cfg_attr(feature = \"serde-codec\", derive(serde::Deserialize))]\n\n#[cfg_attr(feature = \"serde-codec\", derive(serde::Serialize))]\n\n#[derive(Copy, Clone, Debug, Eq, Multihash, PartialEq)]\n\n#[mh(alloc_size = 64)]\n\npub enum Code {\n\n /// SHA-256 (32-byte hash size)\n\n #[cfg(feature = \"sha2\")]\n\n #[mh(code = 0x12, hasher = crate::Sha2_256)]\n\n Sha2_256,\n\n /// SHA-512 (64-byte hash size)\n\n #[cfg(feature = \"sha2\")]\n\n #[mh(code = 0x13, hasher = crate::Sha2_512)]\n", "file_path": "src/multihash_impl.rs", "rank": 48, "score": 21001.550961017558 }, { "content": "\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::hasher::Hasher;\n\n use crate::hasher_impl::sha3::{Sha3_256, Sha3_512};\n\n use crate::multihash::MultihashDigest;\n\n\n\n #[test]\n\n fn test_hasher_256() {\n\n let mut hasher = Sha3_256::default();\n\n hasher.update(b\"hello world\");\n\n let digest = hasher.finalize();\n\n let hash = Code::Sha3_256.wrap(digest).unwrap();\n\n let hash2 = Code::Sha3_256.digest(b\"hello world\");\n\n assert_eq!(hash.code(), u64::from(Code::Sha3_256));\n\n assert_eq!(hash.size(), 32);\n\n assert_eq!(hash.digest(), digest);\n\n assert_eq!(hash, hash2);\n\n }\n", "file_path": "src/multihash_impl.rs", "rank": 49, "score": 20999.079301554582 }, { "content": " #[derive(Clone, Multihash)]\n\n #[mh(alloc_size = 64)]\n\n pub enum Multihash {\n\n #[mh(code = multihash::SHA2_256, hasher = multihash::Sha2_256)]\n\n Identity256,\n\n #[mh(code = multihash::SHA2_256, hasher = multihash::Sha2_256)]\n\n Identity256,\n\n }\n\n };\n\n let derive_input = syn::parse2(input).unwrap();\n\n let s = Structure::new(&derive_input);\n\n multihash(s);\n\n }\n\n\n\n #[test]\n\n #[should_panic(expected = \"the #mh(code) attribute `0x14` is defined multiple times\")]\n\n fn test_multihash_error_code_duplicates_numbers() {\n\n let input = quote! {\n\n #[derive(Clone, Multihash)]\n\n #[mh(alloc_size = 32)]\n", "file_path": "derive/src/multihash.rs", "rank": 50, "score": 20998.046846324054 }, { "content": " match code {\n\n multihash::IDENTITY => Ok(Self::Identity256),\n\n 0x38b64f => Ok(Self::Strobe256),\n\n _ => Err(multihash::Error::UnsupportedCode(code))\n\n }\n\n }\n\n }\n\n };\n\n let derive_input = syn::parse2(input).unwrap();\n\n let s = Structure::new(&derive_input);\n\n let result = multihash(s);\n\n utils::assert_proc_macro(result, expected);\n\n }\n\n\n\n #[test]\n\n #[should_panic(\n\n expected = \"the #mh(code) attribute `multihash :: SHA2_256` is defined multiple times\"\n\n )]\n\n fn test_multihash_error_code_duplicates() {\n\n let input = quote! {\n", "file_path": "derive/src/multihash.rs", "rank": 51, "score": 20997.751348412832 }, { "content": " impl From<#code_enum> for u64 {\n\n fn from(code: #code_enum) -> Self {\n\n match code {\n\n #(#code_into_u64,)*\n\n _ => unreachable!(),\n\n }\n\n }\n\n }\n\n\n\n impl core::convert::TryFrom<u64> for #code_enum {\n\n type Error = #mh_crate::Error;\n\n\n\n fn try_from(code: u64) -> Result<Self, Self::Error> {\n\n match code {\n\n #(#code_from_u64,)*\n\n _ => Err(#mh_crate::Error::UnsupportedCode(code))\n\n }\n\n }\n\n }\n\n }\n", "file_path": "derive/src/multihash.rs", "rank": 52, "score": 20996.951120056634 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_multihash_derive() {\n\n let input = quote! {\n\n #[derive(Clone, Multihash)]\n\n #[mh(alloc_size = 32)]\n\n pub enum Code {\n\n #[mh(code = multihash::IDENTITY, hasher = multihash::Identity256)]\n\n Identity256,\n\n /// Multihash array for hash function.\n\n #[mh(code = 0x38b64f, hasher = multihash::Strobe256)]\n\n Strobe256,\n\n }\n\n };\n\n let expected = quote! {\n", "file_path": "derive/src/multihash.rs", "rank": 53, "score": 20996.552808012246 }, { "content": "\n\n #[test]\n\n fn test_hasher_512() {\n\n let mut hasher = Sha3_512::default();\n\n hasher.update(b\"hello world\");\n\n let digest = hasher.finalize();\n\n let hash = Code::Sha3_512.wrap(digest).unwrap();\n\n let hash2 = Code::Sha3_512.digest(b\"hello world\");\n\n assert_eq!(hash.code(), u64::from(Code::Sha3_512));\n\n assert_eq!(hash.size(), 64);\n\n assert_eq!(hash.digest(), digest);\n\n assert_eq!(hash, hash2);\n\n }\n\n}\n", "file_path": "src/multihash_impl.rs", "rank": 54, "score": 20996.16504322837 }, { "content": " fn code_digest(&self) -> TokenStream {\n\n let ident = &self.ident;\n\n let hasher = &self.hasher;\n\n let code = &self.code;\n\n quote!(Self::#ident => {\n\n let mut hasher = #hasher::default();\n\n hasher.update(input);\n\n Multihash::wrap(#code, hasher.finalize()).unwrap()\n\n })\n\n }\n\n}\n\n\n\nimpl<'a> From<&'a VariantInfo<'a>> for Hash {\n\n fn from(bi: &'a VariantInfo<'a>) -> Self {\n\n let mut code = None;\n\n let mut hasher = None;\n\n for attr in bi.ast().attrs {\n\n let attr: Result<utils::Attrs<MhAttr>, _> = syn::parse2(attr.tokens.clone());\n\n if let Ok(attr) = attr {\n\n for attr in attr.attrs {\n", "file_path": "derive/src/multihash.rs", "rank": 55, "score": 20995.185950152485 }, { "content": " pub enum Code {\n\n #[mh(code = 0x14, hasher = multihash::Sha2_256)]\n\n Identity256,\n\n #[mh(code = 0x14, hasher = multihash::Sha2_256)]\n\n Identity256,\n\n }\n\n };\n\n let derive_input = syn::parse2(input).unwrap();\n\n let s = Structure::new(&derive_input);\n\n multihash(s);\n\n }\n\n}\n", "file_path": "derive/src/multihash.rs", "rank": 56, "score": 20993.038024959194 }, { "content": "use std::collections::HashSet;\n\n\n\nuse crate::utils;\n\nuse proc_macro2::{Span, TokenStream};\n\nuse quote::quote;\n\n#[cfg(not(test))]\n\nuse quote::ToTokens;\n\nuse syn::parse::{Parse, ParseStream};\n\n#[cfg(not(test))]\n\nuse syn::spanned::Spanned;\n\nuse synstructure::{Structure, VariantInfo};\n\n\n\nmod kw {\n\n use syn::custom_keyword;\n\n\n\n custom_keyword!(code);\n\n custom_keyword!(hasher);\n\n custom_keyword!(mh);\n\n custom_keyword!(alloc_size);\n\n}\n\n\n\n/// Attributes for the enum items.\n\n#[derive(Debug)]\n\n#[allow(clippy::large_enum_variant)]\n", "file_path": "derive/src/multihash.rs", "rank": 57, "score": 20992.26893866446 }, { "content": " Sha2_512,\n\n /// SHA3-224 (28-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x17, hasher = crate::Sha3_224)]\n\n Sha3_224,\n\n /// SHA3-256 (32-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x16, hasher = crate::Sha3_256)]\n\n Sha3_256,\n\n /// SHA3-384 (48-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x15, hasher = crate::Sha3_384)]\n\n Sha3_384,\n\n /// SHA3-512 (64-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x14, hasher = crate::Sha3_512)]\n\n Sha3_512,\n\n /// Keccak-224 (28-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x1a, hasher = crate::Keccak224)]\n", "file_path": "src/multihash_impl.rs", "rank": 58, "score": 20990.577410114445 }, { "content": " Keccak224,\n\n /// Keccak-256 (32-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x1b, hasher = crate::Keccak256)]\n\n Keccak256,\n\n /// Keccak-384 (48-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x1c, hasher = crate::Keccak384)]\n\n Keccak384,\n\n /// Keccak-512 (64-byte hash size)\n\n #[cfg(feature = \"sha3\")]\n\n #[mh(code = 0x1d, hasher = crate::Keccak512)]\n\n Keccak512,\n\n /// BLAKE2b-256 (32-byte hash size)\n\n #[cfg(feature = \"blake2b\")]\n\n #[mh(code = 0xb220, hasher = crate::Blake2b256)]\n\n Blake2b256,\n\n /// BLAKE2b-512 (64-byte hash size)\n\n #[cfg(feature = \"blake2b\")]\n\n #[mh(code = 0xb240, hasher = crate::Blake2b512)]\n", "file_path": "src/multihash_impl.rs", "rank": 59, "score": 20990.577410114445 }, { "content": " Blake2b512,\n\n /// BLAKE2s-128 (16-byte hash size)\n\n #[cfg(feature = \"blake2s\")]\n\n #[mh(code = 0xb250, hasher = crate::Blake2s128)]\n\n Blake2s128,\n\n /// BLAKE2s-256 (32-byte hash size)\n\n #[cfg(feature = \"blake2s\")]\n\n #[mh(code = 0xb260, hasher = crate::Blake2s256)]\n\n Blake2s256,\n\n /// BLAKE3-256 (32-byte hash size)\n\n #[cfg(feature = \"blake3\")]\n\n #[mh(code = 0x1e, hasher = crate::Blake3_256)]\n\n Blake3_256,\n\n\n\n // The following hashes are not cryptographically secure hashes and are not enabled by default\n\n /// Identity hash (max. 64 bytes)\n\n #[cfg(feature = \"identity\")]\n\n #[mh(code = 0x00, hasher = crate::IdentityHasher::<64>)]\n\n Identity,\n\n}\n", "file_path": "src/multihash_impl.rs", "rank": 60, "score": 20989.86738342867 }, { "content": " #[cfg(not(test))]\n\n proc_macro_error::abort!(ident, msg);\n\n });\n\n Self {\n\n ident,\n\n code,\n\n hasher,\n\n }\n\n }\n\n}\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 61, "score": 20989.744580210958 }, { "content": " match attr {\n\n MhAttr::Code(attr) => code = Some(attr.value),\n\n MhAttr::Hasher(attr) => hasher = Some(attr.value),\n\n }\n\n }\n\n }\n\n }\n\n\n\n let ident = bi.ast().ident.clone();\n\n let code = code.unwrap_or_else(|| {\n\n let msg = \"Missing code attribute: e.g. #[mh(code = multihash::SHA3_256)]\";\n\n #[cfg(test)]\n\n panic!(\"{}\", msg);\n\n #[cfg(not(test))]\n\n proc_macro_error::abort!(ident, msg);\n\n });\n\n let hasher = hasher.unwrap_or_else(|| {\n\n let msg = \"Missing hasher attribute: e.g. #[mh(hasher = multihash::Sha2_256)]\";\n\n #[cfg(test)]\n\n panic!(\"{}\", msg);\n", "file_path": "derive/src/multihash.rs", "rank": 62, "score": 20988.30373453861 }, { "content": "#[derive(Debug)]\n\nenum DeriveAttr {\n\n AllocSize(utils::Attr<kw::alloc_size, syn::LitInt>),\n\n}\n\n\n\nimpl Parse for DeriveAttr {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n if input.peek(kw::alloc_size) {\n\n Ok(Self::AllocSize(input.parse()?))\n\n } else {\n\n Err(syn::Error::new(input.span(), \"unknown attribute\"))\n\n }\n\n }\n\n}\n\n\n", "file_path": "derive/src/multihash.rs", "rank": 63, "score": 18672.57255614104 }, { "content": "#[derive(Debug)]\n\n#[allow(clippy::large_enum_variant)]\n\nenum MhAttr {\n\n Code(utils::Attr<kw::code, syn::Expr>),\n\n Hasher(utils::Attr<kw::hasher, Box<syn::Type>>),\n\n}\n\n\n\nimpl Parse for MhAttr {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n if input.peek(kw::code) {\n\n Ok(MhAttr::Code(input.parse()?))\n\n } else if input.peek(kw::hasher) {\n\n Ok(MhAttr::Hasher(input.parse()?))\n\n } else {\n\n Err(syn::Error::new(input.span(), \"unknown attribute\"))\n\n }\n\n }\n\n}\n\n\n\n/// Attributes of the top-level derive.\n", "file_path": "derive/src/multihash.rs", "rank": 64, "score": 18672.27130010816 }, { "content": "### Using a custom code table\n\n\n\nYou can derive your own application specific code table:\n\n\n\n```rust\n\nuse multihash::derive::Multihash;\n\nuse multihash::MultihashCode;\n\n\n\n#[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]\n\n#[mh(alloc_size = 64)]\n\npub enum Code {\n\n #[mh(code = 0x01, hasher = multihash::Sha2_256)]\n\n Foo,\n\n #[mh(code = 0x02, hasher = multihash::Sha2_512)]\n\n Bar,\n\n}\n\n\n\nfn main() {\n\n let hash = Code::Foo.digest(b\"my hash\");\n\n println!(\"{:02x?}\", hash);\n\n}\n\n```\n\n\n\n## Supported Hash Types\n\n\n\n* `SHA1`\n\n* `SHA2-256`\n\n* `SHA2-512`\n\n* `SHA3`/`Keccak`\n\n* `Blake2b-256`/`Blake2b-512`/`Blake2s-128`/`Blake2s-256`\n\n* `Blake3`\n\n* `Strobe`\n\n\n\n## Maintainers\n\n\n\nCaptain: [@dignifiedquire](https://github.com/dignifiedquire).\n\n\n\n## Contribute\n\n\n\nContributions welcome. Please check out [the issues](https://github.com/multiformats/rust-multihash/issues).\n\n\n\nCheck out our [contributing document](https://github.com/multiformats/multiformats/blob/master/contributing.md) for more information on how we work, and about contributing in general. Please be aware that all interactions related to multiformats are subject to the IPFS [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md).\n\n\n\nSmall note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.\n\n\n\n\n\n## License\n\n\n\n[MIT](LICENSE)\n", "file_path": "README.md", "rank": 65, "score": 12971.610097740595 }, { "content": "# rust-multihash\n\n\n\n[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io)\n\n[![](https://img.shields.io/badge/project-multiformats-blue.svg?style=flat-square)](https://github.com/multiformats/multiformats)\n\n[![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](https://webchat.freenode.net/?channels=%23ipfs)\n\n[![](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme)\n\n\n\n[![Build Status](https://github.com/multiformats/rust-multihash/workflows/build/badge.svg)](https://github.com/multiformats/rust-multihash/actions)\n\n[![Crates.io](https://img.shields.io/crates/v/multihash?style=flat-square)](https://crates.io/crates/multihash)\n\n[![License](https://img.shields.io/crates/l/multihash?style=flat-square)](LICENSE)\n\n[![Documentation](https://docs.rs/multihash/badge.svg?style=flat-square)](https://docs.rs/multihash)\n\n[![Dependency Status](https://deps.rs/repo/github/multiformats/rust-multihash/status.svg)](https://deps.rs/repo/github/multiformats/rust-multihash)\n\n[![Coverage Status]( https://img.shields.io/codecov/c/github/multiformats/rust-multihash?style=flat-square)](https://codecov.io/gh/multiformats/rust-multihash)\n\n\n\n> [multihash](https://github.com/multiformats/multihash) implementation in Rust.\n\n\n\n## Table of Contents\n\n - [Install](#install)\n\n - [Usage](#usage)\n\n - [Supported Hash Types](#supported-hash-types)\n\n - [Maintainers](#maintainers)\n\n - [Contribute](#contribute)\n\n - [License](#license)\n\n\n\n## Install\n\n\n\nFirst add this to your `Cargo.toml`\n\n\n\n```toml\n\n[dependencies]\n\nmultihash = \"*\"\n\n```\n\n\n\nThen run `cargo build`.\n\n\n\nMSRV 1.51.0 due to use of const generics\n\n\n\n## Usage\n\n\n\n```rust\n\nuse multihash::{Code, MultihashDigest};\n\n\n\nfn main() {\n\n let hash = Code::Sha2_256.digest(b\"my hash\");\n\n println!(\"{:?}\", hash);\n\n}\n\n```\n\n\n", "file_path": "README.md", "rank": 66, "score": 12964.050660692426 }, { "content": "}\n\n\n\npub mod identity {\n\n use super::*;\n\n\n\n /// Identity hasher with a maximum size.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if the input is bigger than the maximum size.\n\n #[derive(Debug)]\n\n pub struct IdentityHasher<const S: usize> {\n\n i: usize,\n\n bytes: [u8; S],\n\n }\n\n\n\n impl<const S: usize> Default for IdentityHasher<S> {\n\n fn default() -> Self {\n\n Self {\n\n i: 0,\n", "file_path": "src/hasher_impl.rs", "rank": 67, "score": 25.15466020871331 }, { "content": "use std::convert::TryFrom;\n\n\n\nuse multihash::derive::Multihash;\n\nuse multihash::{Error, Hasher, MultihashDigest, MultihashGeneric, Sha2_256};\n\n\n\n// You can implement a custom hasher. This is a SHA2 256-bit hasher that returns a hash that is\n\n// truncated to 160 bits.\n\n#[derive(Default, Debug)]\n\npub struct Sha2_256Truncated20(Sha2_256);\n\nimpl Hasher for Sha2_256Truncated20 {\n\n fn update(&mut self, input: &[u8]) {\n\n self.0.update(input)\n\n }\n\n fn finalize(&mut self) -> &[u8] {\n\n &self.0.finalize()[..20]\n\n }\n\n fn reset(&mut self) {\n\n self.0.reset();\n\n }\n\n}\n", "file_path": "examples/custom_table.rs", "rank": 68, "score": 22.673527319285142 }, { "content": "macro_rules! derive_hasher_sha {\n\n ($module:ty, $name:ident, $size:expr) => {\n\n /// Multihash hasher.\n\n #[derive(Debug)]\n\n pub struct $name {\n\n state: $module,\n\n digest: [u8; $size],\n\n }\n\n\n\n impl Default for $name {\n\n fn default() -> Self {\n\n $name {\n\n state: Default::default(),\n\n digest: [0; $size],\n\n }\n\n }\n\n }\n\n\n\n impl $crate::hasher::Hasher for $name {\n\n fn update(&mut self, input: &[u8]) {\n", "file_path": "src/hasher_impl.rs", "rank": 69, "score": 21.135857178604518 }, { "content": "//! use multihash::derive::Multihash;\n\n//! use multihash::MultihashDigest;\n\n//!\n\n//! #[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]\n\n//! #[mh(alloc_size = 64)]\n\n//! pub enum Code {\n\n//! #[mh(code = 0x01, hasher = multihash::Sha2_256)]\n\n//! Foo,\n\n//! #[mh(code = 0x02, hasher = multihash::Sha2_512)]\n\n//! Bar,\n\n//! }\n\n//!\n\n//! let hash = Code::Foo.digest(b\"hello world!\");\n\n//! println!(\"{:02x?}\", hash);\n\n//! ```\n\nextern crate proc_macro;\n\n\n\nmod multihash;\n\nmod utils;\n\n\n\nuse proc_macro::TokenStream;\n\nuse proc_macro_error::proc_macro_error;\n\nuse synstructure::{decl_derive, Structure};\n\n\n\ndecl_derive!([Multihash, attributes(mh)] => #[proc_macro_error] multihash);\n", "file_path": "derive/src/lib.rs", "rank": 70, "score": 20.98886685257439 }, { "content": " }\n\n }\n\n }\n\n\n\n impl<const S: usize> Hasher for $name<S> {\n\n fn update(&mut self, input: &[u8]) {\n\n self.state.update(input);\n\n }\n\n\n\n fn finalize(&mut self) -> &[u8] {\n\n let digest = self.state.finalize();\n\n let digest_bytes = digest.as_bytes();\n\n let digest_out = &mut self.digest[..digest_bytes.len().max(S)];\n\n digest_out.copy_from_slice(digest_bytes);\n\n digest_out\n\n }\n\n\n\n fn reset(&mut self) {\n\n let Self { state, .. } = Self::default();\n\n self.state = state;\n", "file_path": "src/hasher_impl.rs", "rank": 71, "score": 20.672629454517153 }, { "content": "\n\n#[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]\n\n#[mh(alloc_size = 64)]\n\npub enum Code {\n\n /// Example for using a custom hasher which returns truncated hashes\n\n #[mh(code = 0x12, hasher = Sha2_256Truncated20)]\n\n Sha2_256Truncated20,\n\n /// Example for using a hasher with a bit size that is not exported by default\n\n #[mh(code = 0xb219, hasher = multihash::Blake2bHasher::<25>)]\n\n Blake2b200,\n\n}\n\n\n", "file_path": "examples/custom_table.rs", "rank": 72, "score": 19.40589368505279 }, { "content": " use digest::Digest;\n\n self.state.update(input)\n\n }\n\n\n\n fn finalize(&mut self) -> &[u8] {\n\n use digest::Digest;\n\n let digest = self.state.clone().finalize();\n\n let digest_bytes = digest.as_slice();\n\n let digest_out = &mut self.digest[..digest_bytes.len().max($size)];\n\n digest_out.copy_from_slice(digest_bytes);\n\n digest_out\n\n }\n\n\n\n fn reset(&mut self) {\n\n use digest::Digest;\n\n self.state.reset();\n\n }\n\n }\n\n\n\n impl io::Write for $name {\n", "file_path": "src/hasher_impl.rs", "rank": 73, "score": 19.078432621879063 }, { "content": "use std::io::{Cursor, Write};\n\n\n\nuse multihash::{\n\n derive::Multihash, Blake2b256, Blake2b512, Blake2s128, Blake2s256, Blake3_256, Hasher,\n\n Identity256, Keccak224, Keccak256, Keccak384, Keccak512, MultihashDigest, Sha1, Sha2_256,\n\n Sha2_512, Sha3_224, Sha3_256, Sha3_384, Sha3_512, Strobe256, Strobe512,\n\n};\n\n\n\n#[derive(Clone, Copy, Debug, Eq, Multihash, PartialEq)]\n\n#[mh(alloc_size = 64)]\n\npub enum Code {\n\n #[mh(code = 0x00, hasher = Identity256)]\n\n Identity,\n\n #[mh(code = 0x11, hasher = Sha1)]\n\n Sha1,\n\n #[mh(code = 0x12, hasher = Sha2_256)]\n\n Sha2_256,\n\n #[mh(code = 0x13, hasher = Sha2_512)]\n\n Sha2_512,\n\n #[mh(code = 0x17, hasher = Sha3_224)]\n", "file_path": "tests/lib.rs", "rank": 74, "score": 18.44535898398371 }, { "content": " };\n\n}\n\n\n\n#[cfg(any(feature = \"blake2b\", feature = \"blake2s\"))]\n\nmacro_rules! derive_hasher_blake {\n\n ($module:ident, $name:ident) => {\n\n /// Multihash hasher.\n\n #[derive(Debug)]\n\n pub struct $name<const S: usize> {\n\n state: $module::State,\n\n digest: [u8; S],\n\n }\n\n\n\n impl<const S: usize> Default for $name<S> {\n\n fn default() -> Self {\n\n let mut params = $module::Params::new();\n\n params.hash_length(S);\n\n Self {\n\n state: params.to_state(),\n\n digest: [0; S],\n", "file_path": "src/hasher_impl.rs", "rank": 75, "score": 16.95241164546638 }, { "content": " hasher: ::blake3::Hasher,\n\n digest: [u8; S],\n\n }\n\n\n\n impl<const S: usize> Default for Blake3Hasher<S> {\n\n fn default() -> Self {\n\n let hasher = ::blake3::Hasher::new();\n\n\n\n Self {\n\n hasher,\n\n digest: [0; S],\n\n }\n\n }\n\n }\n\n\n\n impl<const S: usize> Hasher for Blake3Hasher<S> {\n\n fn update(&mut self, input: &[u8]) {\n\n self.hasher.update(input);\n\n }\n\n\n", "file_path": "src/hasher_impl.rs", "rank": 76, "score": 16.866292960266495 }, { "content": " bytes: [0u8; S],\n\n }\n\n }\n\n }\n\n\n\n impl<const S: usize> Hasher for IdentityHasher<S> {\n\n fn update(&mut self, input: &[u8]) {\n\n let start = self.i.min(self.bytes.len());\n\n let end = (self.i + input.len()).min(self.bytes.len());\n\n self.bytes[start..end].copy_from_slice(input);\n\n self.i = end;\n\n }\n\n\n\n fn finalize(&mut self) -> &[u8] {\n\n &self.bytes[..self.i]\n\n }\n\n\n\n fn reset(&mut self) {\n\n self.i = 0\n\n }\n", "file_path": "src/hasher_impl.rs", "rank": 77, "score": 16.65987102835913 }, { "content": "//! This proc macro derives a custom Multihash code table from a list of hashers. It also\n\n//! generates a public type called `Multihash` which corresponds to the specified `alloc_size`.\n\n//!\n\n//! The digests are stack allocated with a fixed size. That size needs to be big enough to hold any\n\n//! of the specified hash digests. This cannot be determined reliably on compile-time, hence it\n\n//! needs to set manually via the `alloc_size` attribute. Also you might want to set it to bigger\n\n//! sizes then necessarily needed for backwards/forward compatibility.\n\n//!\n\n//! If you set `#mh(alloc_size = …)` to a too low value, you will get compiler errors. Please note\n\n//! the the sizes are checked only on a syntactic level and *not* on the type level. This means\n\n//! that digest need to have a size const generic, which is a valid `usize`, for example `32` or\n\n//! `64`.\n\n//!\n\n//! You can disable those compiler errors with setting the `no_alloc_size_errors` attribute. This\n\n//! can be useful if you e.g. have specified type aliases for your hash digests and you are sure\n\n//! you use the correct value for `alloc_size`.\n\n//!\n\n//! # Example\n\n//!\n\n//! ```\n", "file_path": "derive/src/lib.rs", "rank": 78, "score": 15.861245262528033 }, { "content": " initialized: bool,\n\n digest: [u8; S],\n\n }\n\n\n\n impl<const S: usize> Default for StrobeHasher<S> {\n\n fn default() -> Self {\n\n Self {\n\n strobe: Strobe::new(b\"StrobeHash\", SecParam::B128),\n\n initialized: false,\n\n digest: [0; S],\n\n }\n\n }\n\n }\n\n\n\n impl<const S: usize> Hasher for StrobeHasher<S> {\n\n fn update(&mut self, input: &[u8]) {\n\n self.strobe.ad(input, self.initialized);\n\n self.initialized = true;\n\n }\n\n\n", "file_path": "src/hasher_impl.rs", "rank": 79, "score": 15.860383772891696 }, { "content": " 4 => g.gen_range(u64::pow(2, 28), u64::pow(2, 35)),\n\n 5 => g.gen_range(u64::pow(2, 35), u64::pow(2, 42)),\n\n 6 => g.gen_range(u64::pow(2, 42), u64::pow(2, 49)),\n\n 7 => g.gen_range(u64::pow(2, 56), u64::pow(2, 63)),\n\n _ => unreachable!(),\n\n };\n\n\n\n // Maximum size is S byte due to the generic.\n\n let size = g.gen_range(0, S);\n\n let mut data = [0; S];\n\n g.fill_bytes(&mut data);\n\n MultihashGeneric::wrap(code, &data[..size]).unwrap()\n\n }\n\n}\n", "file_path": "src/arb.rs", "rank": 80, "score": 15.760904428458819 }, { "content": " }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Attr<K, V> {\n\n pub key: K,\n\n pub eq: syn::token::Eq,\n\n pub value: V,\n\n}\n\n\n\nimpl<K: Parse, V: Parse> Parse for Attr<K, V> {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n Ok(Self {\n\n key: input.parse()?,\n\n eq: input.parse()?,\n\n value: input.parse()?,\n\n })\n\n }\n\n}\n\n\n", "file_path": "derive/src/utils.rs", "rank": 81, "score": 15.23840078264042 }, { "content": " fn finalize(&mut self) -> &[u8] {\n\n let digest = self.hasher.finalize(); //default is 32 bytes anyway\n\n let digest_bytes = digest.as_bytes();\n\n let digest_out = &mut self.digest[..digest_bytes.len().max(S)];\n\n digest_out.copy_from_slice(digest_bytes);\n\n digest_out\n\n }\n\n\n\n fn reset(&mut self) {\n\n self.hasher.reset();\n\n }\n\n }\n\n\n\n derive_write!(Blake3Hasher);\n\n\n\n /// blake3-256 hasher.\n\n pub type Blake3_256 = Blake3Hasher<32>;\n\n}\n\n\n\n#[cfg(feature = \"digest\")]\n", "file_path": "src/hasher_impl.rs", "rank": 82, "score": 14.976466435867504 }, { "content": "use crate::hasher::Hasher;\n\n\n\n#[cfg(feature = \"std\")]\n\nuse std::io;\n\n\n\n#[cfg(not(feature = \"std\"))]\n\nuse core2::io;\n\n\n\nmacro_rules! derive_write {\n\n ($name:ident) => {\n\n impl<const S: usize> io::Write for $name<S> {\n\n fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n\n self.update(buf);\n\n Ok(buf.len())\n\n }\n\n\n\n fn flush(&mut self) -> io::Result<()> {\n\n Ok(())\n\n }\n\n }\n", "file_path": "src/hasher_impl.rs", "rank": 83, "score": 14.801215656046216 }, { "content": "mod hasher;\n\nmod hasher_impl;\n\nmod multihash;\n\n#[cfg(feature = \"multihash-impl\")]\n\nmod multihash_impl;\n\n\n\npub use crate::error::{Error, Result};\n\npub use crate::hasher::Hasher;\n\npub use crate::multihash::{Multihash as MultihashGeneric, MultihashDigest};\n\n#[cfg(feature = \"derive\")]\n\npub use multihash_derive as derive;\n\n\n\n#[cfg(feature = \"multihash-impl\")]\n\npub use crate::multihash_impl::{Code, Multihash};\n\n\n\n#[cfg(feature = \"blake2b\")]\n\npub use crate::hasher_impl::blake2b::{Blake2b256, Blake2b512, Blake2bHasher};\n\n#[cfg(feature = \"blake2s\")]\n\npub use crate::hasher_impl::blake2s::{Blake2s128, Blake2s256, Blake2sHasher};\n\n#[cfg(feature = \"blake3\")]\n", "file_path": "src/lib.rs", "rank": 84, "score": 14.699554611864004 }, { "content": "use quickcheck::{Arbitrary, Gen};\n\nuse rand::{\n\n distributions::{weighted::WeightedIndex, Distribution},\n\n Rng,\n\n};\n\n\n\nuse crate::MultihashGeneric;\n\n\n\n/// Generates a random valid multihash.\n\nimpl<const S: usize> Arbitrary for MultihashGeneric<S> {\n\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n\n // In real world lower multihash codes are more likely to happen, hence distribute them\n\n // with bias towards smaller values.\n\n let weights = [128, 64, 32, 16, 8, 4, 2, 1];\n\n let dist = WeightedIndex::new(weights.iter()).unwrap();\n\n let code = match dist.sample(g) {\n\n 0 => g.gen_range(0, u64::pow(2, 7)),\n\n 1 => g.gen_range(u64::pow(2, 7), u64::pow(2, 14)),\n\n 2 => g.gen_range(u64::pow(2, 14), u64::pow(2, 21)),\n\n 3 => g.gen_range(u64::pow(2, 21), u64::pow(2, 28)),\n", "file_path": "src/arb.rs", "rank": 85, "score": 13.418588886657957 }, { "content": " fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n\n self.update(buf);\n\n Ok(buf.len())\n\n }\n\n\n\n fn flush(&mut self) -> io::Result<()> {\n\n Ok(())\n\n }\n\n }\n\n };\n\n}\n\n\n\n#[cfg(feature = \"sha1\")]\n\npub mod sha1 {\n\n use super::*;\n\n\n\n derive_hasher_sha!(::sha1::Sha1, Sha1, 20);\n\n}\n\n\n\n#[cfg(feature = \"sha2\")]\n", "file_path": "src/hasher_impl.rs", "rank": 86, "score": 13.074688164171786 }, { "content": " }\n\n}\n\n\n\nmacro_rules! assert_roundtrip {\n\n ($( $code:expr, $alg:ident; )*) => {\n\n $(\n\n // Hashing with one call\n\n {\n\n let hash = $code.digest(b\"helloworld\");\n\n assert_eq!(\n\n Multihash::from_bytes(&hash.to_bytes()).unwrap().code(),\n\n hash.code()\n\n );\n\n }\n\n // Hashing incrementally\n\n {\n\n let mut hasher = <$alg>::default();\n\n hasher.update(b\"helloworld\");\n\n let hash = $code.wrap(hasher.finalize()).unwrap();\n\n assert_eq!(\n", "file_path": "tests/lib.rs", "rank": 87, "score": 13.027345691226714 }, { "content": " Multihash::from_bytes(&hash.to_bytes()).unwrap().code(),\n\n hash.code()\n\n );\n\n }\n\n // Hashing as `Write` implementation\n\n {\n\n let mut hasher = <$alg>::default();\n\n hasher.write_all(b\"helloworld\").unwrap();\n\n let hash = $code.wrap(hasher.finalize()).unwrap();\n\n assert_eq!(\n\n Multihash::from_bytes(&hash.to_bytes()).unwrap().code(),\n\n hash.code()\n\n );\n\n }\n\n )*\n\n }\n\n}\n\n\n", "file_path": "tests/lib.rs", "rank": 88, "score": 12.539096307482337 }, { "content": " fn finalize(&mut self) -> &[u8] {\n\n self.strobe.clone().prf(&mut self.digest, false);\n\n &self.digest\n\n }\n\n\n\n fn reset(&mut self) {\n\n let Self { strobe, .. } = Self::default();\n\n self.strobe = strobe;\n\n self.initialized = false;\n\n }\n\n }\n\n\n\n derive_write!(StrobeHasher);\n\n\n\n /// 256 bit strobe hasher.\n\n pub type Strobe256 = StrobeHasher<32>;\n\n\n\n /// 512 bit strobe hasher.\n\n pub type Strobe512 = StrobeHasher<64>;\n\n}\n", "file_path": "src/hasher_impl.rs", "rank": 89, "score": 12.408046482059179 }, { "content": " }\n\n\n\n derive_write!(IdentityHasher);\n\n\n\n /// 32 byte Identity hasher (constrained to 32 bytes).\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if the input is bigger than 32 bytes.\n\n pub type Identity256 = IdentityHasher<32>;\n\n}\n\n\n\n#[cfg(feature = \"strobe\")]\n\npub mod strobe {\n\n use super::*;\n\n use strobe_rs::{SecParam, Strobe};\n\n\n\n /// Strobe hasher.\n\n pub struct StrobeHasher<const S: usize> {\n\n strobe: Strobe,\n", "file_path": "src/hasher_impl.rs", "rank": 90, "score": 11.90837681313159 }, { "content": " }\n\n}\n\n\n\nmacro_rules! assert_decode {\n\n {$( $code:expr, $hash:expr; )*} => {\n\n $(\n\n let hash = hex::decode($hash).unwrap();\n\n assert_eq!(\n\n Multihash::from_bytes(&hash).unwrap().code(),\n\n u64::from($code),\n\n \"{:?} decodes correctly\", stringify!($code)\n\n );\n\n )*\n\n }\n\n}\n\n\n", "file_path": "tests/lib.rs", "rank": 91, "score": 11.55942633929294 }, { "content": " Blake2s128,\n\n #[mh(code = 0xb260, hasher = Blake2s256)]\n\n Blake2s256,\n\n #[mh(code = 0x1e, hasher = Blake3_256)]\n\n Blake3_256,\n\n #[mh(code = 0x3312e7, hasher = Strobe256)]\n\n Strobe256,\n\n #[mh(code = 0x3312e8, hasher = Strobe512)]\n\n Strobe512,\n\n}\n\n\n\nmacro_rules! assert_encode {\n\n // Mutlihash enum member, Multihash code, input, Multihash as hex\n\n {$( $alg:ty, $code:expr, $data:expr, $expect:expr; )*} => {\n\n $(\n\n let expected = hex::decode($expect).unwrap();\n\n\n\n // From code\n\n assert_eq!(\n\n $code.digest($data).to_bytes(),\n", "file_path": "tests/lib.rs", "rank": 92, "score": 11.211304388831675 }, { "content": "#[cfg(feature = \"blake2s\")]\n\npub mod blake2s {\n\n use super::*;\n\n\n\n derive_hasher_blake!(blake2s_simd, Blake2sHasher);\n\n\n\n /// 256 bit blake2b hasher.\n\n pub type Blake2s128 = Blake2sHasher<16>;\n\n\n\n /// 512 bit blake2b hasher.\n\n pub type Blake2s256 = Blake2sHasher<32>;\n\n}\n\n\n\n#[cfg(feature = \"blake3\")]\n\npub mod blake3 {\n\n use super::*;\n\n\n\n /// Multihash hasher.\n\n #[derive(Debug)]\n\n pub struct Blake3Hasher<const S: usize> {\n", "file_path": "src/hasher_impl.rs", "rank": 93, "score": 10.544160522369708 }, { "content": "//! In order to enable all cryptographically secure hashers, you can set the `secure-hashes`\n\n//! feature flag (enabled by default).\n\n//!\n\n//! The library has support for `no_std`, if you disable the `std` feature flag.\n\n//!\n\n//! The `multihash-impl` feature flag (enabled by default) enables a default Multihash\n\n//! implementation that contains some of the bundled hashers. If you want a different set of hash\n\n//! algorithms you can change this with enabled the corresponding features.\n\n//!\n\n//! For example if you only need SHA2 hasher, you could set the features in the `multihash`\n\n//! dependency like this:\n\n//!\n\n//! ```toml\n\n//! multihash = { version = …, default-features = false, features = [\"std\", \"multihash-impl\", \"sha2\"] }\n\n//! ```\n\n//!\n\n//! If you want to customize your code table even more, for example you want only one specific hash\n\n//! digest size and not whole family, you would only enable the `derive` feature (enabled by\n\n//! default), which enables the [`Multihash` derive], together with the hashers you want.\n\n//!\n", "file_path": "src/lib.rs", "rank": 94, "score": 8.272169097974952 }, { "content": " expected,\n\n \"{:?} encodes correctly (from code)\", stringify!($alg)\n\n );\n\n\n\n // From incremental hashing\n\n let mut hasher = <$alg>::default();\n\n hasher.update($data);\n\n assert_eq!(\n\n $code.wrap(hasher.finalize()).unwrap().to_bytes(),\n\n expected,\n\n \"{:?} encodes correctly (from hasher)\", stringify!($alg)\n\n );\n\n )*\n\n }\n\n}\n\n\n\n#[allow(clippy::cognitive_complexity)]\n\n#[test]\n", "file_path": "tests/lib.rs", "rank": 95, "score": 8.199551660969966 }, { "content": "//! The `arb` feature flag enables the quickcheck arbitrary implementation for property based\n\n//! testing.\n\n//!\n\n//! For serializing the multihash there is support for [Serde] via the `serde-codec` feature and\n\n//! the [SCALE Codec] via the `scale-codec` feature.\n\n//!\n\n//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section\n\n//! [`Multihash` derive]: crate::derive\n\n//! [Serde]: https://serde.rs\n\n//! [SCALE Codec]: https://github.com/paritytech/parity-scale-codec\n\n\n\n#![deny(missing_docs, unsafe_code)]\n\n#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\n#[cfg(feature = \"alloc\")]\n\nextern crate alloc;\n\n\n\n#[cfg(any(test, feature = \"arb\"))]\n\nmod arb;\n\nmod error;\n", "file_path": "src/lib.rs", "rank": 96, "score": 8.195305051736941 }, { "content": "#[cfg(test)]\n\npub(crate) fn assert_proc_macro(\n\n result: proc_macro2::TokenStream,\n\n expected: proc_macro2::TokenStream,\n\n) {\n\n let result = result.to_string();\n\n let expected = expected.to_string();\n\n pretty_assertions::assert_eq!(result, expected);\n\n}\n", "file_path": "derive/src/utils.rs", "rank": 97, "score": 7.618911097305235 }, { "content": "//! Multihash implementation.\n\n//!\n\n//! Feature Flags\n\n//! -------------\n\n//!\n\n//! Multihash has lots of [feature flags], by default a table with cryptographically secure hashers\n\n//! is created.\n\n//!\n\n//! Some of the features are about specific hash functions, these are (\"default\" marks the hashers\n\n//! that are enabled by default):\n\n//!\n\n//! - `blake2b`: (default) Enable Blake2b hashers\n\n//! - `blake2s`: (default) Enable Blake2s hashers\n\n//! - `identity`: Enable the Identity hashers (using it is discouraged as it's not a hash function\n\n//! in the sense that it produces a fixed sized output independent of the input size)\n\n//! - `sha1`: Enable SHA-1 hasher\n\n//! - `sha2`: (default) Enable SHA-2 hashers\n\n//! - `sha3`: (default) Enable SHA-3 hashers\n\n//! - `strobe`: Enable Strobe hashers\n\n//!\n", "file_path": "src/lib.rs", "rank": 98, "score": 6.582522079419394 }, { "content": "pub use crate::hasher_impl::blake3::{Blake3Hasher, Blake3_256};\n\npub use crate::hasher_impl::identity::{Identity256, IdentityHasher};\n\n#[cfg(feature = \"sha1\")]\n\npub use crate::hasher_impl::sha1::Sha1;\n\n#[cfg(feature = \"sha2\")]\n\npub use crate::hasher_impl::sha2::{Sha2_256, Sha2_512};\n\n#[cfg(feature = \"sha3\")]\n\npub use crate::hasher_impl::sha3::{Keccak224, Keccak256, Keccak384, Keccak512};\n\n#[cfg(feature = \"sha3\")]\n\npub use crate::hasher_impl::sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512};\n\n#[cfg(feature = \"strobe\")]\n\npub use crate::hasher_impl::strobe::{Strobe256, Strobe512, StrobeHasher};\n", "file_path": "src/lib.rs", "rank": 99, "score": 6.270221790687117 } ]
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_perspective(\n\n &context,\n\n window.viewport().unwrap(),\n\n vec3(0.0, 30.0, 150.0),\n\n vec3(0.0, 30.0, 0.0),\n\n vec3(0.0, 1.0, 0.0),\n\n degrees(45.0),\n\n 0.1,\n\n 1000.0,\n\n )\n\n .unwrap();\n", "file_path": "examples/fireworks/src/main.rs", "rank": 0, "score": 247610.26764734992 }, { "content": "pub fn main() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Shapes 2D!\".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 rectangle = Rectangle::new_with_material(\n\n &context,\n\n vec2(200.0, 200.0),\n\n degrees(45.0),\n\n 100.0,\n\n 200.0,\n\n ColorMaterial {\n\n color: Color::RED,\n\n ..Default::default()\n\n },\n\n )\n", "file_path": "examples/shapes2d/src/main.rs", "rank": 1, "score": 213281.32752009697 }, { "content": "pub fn main() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Screen!\".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_perspective(\n\n &context,\n\n window.viewport().unwrap(),\n\n vec3(0.0, 0.0, 1.3),\n\n vec3(0.0, 0.0, 0.0),\n\n vec3(0.0, 1.0, 0.0),\n\n degrees(45.0),\n\n 0.1,\n\n 10.0,\n\n )\n\n .unwrap();\n", "file_path": "examples/screen/src/main.rs", "rank": 2, "score": 213281.32752009697 }, { "content": "pub fn main() {\n\n // Create a window (a canvas on web)\n\n let window = Window::new(WindowSettings {\n\n title: \"Triangle!\".to_string(),\n\n max_size: Some((1280, 720)),\n\n ..Default::default()\n\n })\n\n .unwrap();\n\n\n\n // Get the graphics context from the window\n\n let context = window.gl().unwrap();\n\n\n\n // Create a camera\n\n let mut camera = Camera::new_perspective(\n\n &context,\n\n window.viewport().unwrap(),\n\n vec3(0.0, 0.0, 2.0),\n\n vec3(0.0, 0.0, 0.0),\n\n vec3(0.0, 1.0, 0.0),\n\n degrees(45.0),\n", "file_path": "examples/triangle/src/main.rs", "rank": 3, "score": 213281.32752009697 }, { "content": "pub fn main() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Shapes!\".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_perspective(\n\n &context,\n\n window.viewport().unwrap(),\n\n vec3(5.0, 2.0, 2.5),\n\n vec3(0.0, 0.0, -0.5),\n\n vec3(0.0, 1.0, 0.0),\n\n degrees(45.0),\n\n 0.1,\n\n 1000.0,\n\n )\n\n .unwrap();\n", "file_path": "examples/shapes/src/main.rs", "rank": 4, "score": 213281.32752009697 }, { "content": "pub fn main() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Mandelbrot!\".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 // Renderer\n\n let mut camera = Camera::new_orthographic(\n\n &context,\n\n window.viewport().unwrap(),\n\n vec3(0.0, 0.0, 1.0),\n\n vec3(0.0, 0.0, 0.0),\n\n vec3(0.0, 1.0, 0.0),\n\n 2.5,\n\n 0.0,\n\n 10.0,\n\n )\n", "file_path": "examples/mandelbrot/src/main.rs", "rank": 5, "score": 213281.32752009697 }, { "content": "#[cfg(not(target_arch = \"wasm32\"))]\n\nfn load_from_disk(mut paths: Vec<PathBuf>, loaded: &mut Loaded) -> ThreeDResult<()> {\n\n let mut handles = Vec::new();\n\n for path in paths.drain(..) {\n\n handles.push((\n\n path.clone(),\n\n std::thread::spawn(move || std::fs::read(path)),\n\n ));\n\n }\n\n\n\n for (path, handle) in handles.drain(..) {\n\n let bytes = handle\n\n .join()\n\n .unwrap()\n\n .map_err(|e| IOError::FailedLoading(path.to_str().unwrap().to_string(), e))?;\n\n loaded.loaded.insert(path, bytes);\n\n }\n\n Ok(())\n\n}\n\n\n\n#[cfg(feature = \"reqwest\")]\n", "file_path": "src/io/loader.rs", "rank": 6, "score": 173105.57079795323 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\nfn build_context<T1: ContextCurrentState>(\n\n cb: ContextBuilder<T1>,\n\n) -> Result<(glutin::Context<NotCurrent>, EventLoop<()>), CreationError> {\n\n let el = EventLoop::new();\n\n build_context_headless(cb.clone(), &el).map(|ctx| (ctx, el))\n\n}\n", "file_path": "src/window/headless.rs", "rank": 7, "score": 152981.44107650506 }, { "content": "#[cfg(not(target_arch = \"wasm32\"))]\n\nfn main() {\n\n run();\n\n}\n\n\n", "file_path": "examples/fireworks/src/main.rs", "rank": 8, "score": 151767.8530924433 }, { "content": "fn main() {\n\n let viewport = Viewport::new_at_origo(1280, 720);\n\n\n\n // Create a headless graphics context\n\n let context = Context::new().unwrap();\n\n\n\n // Create a camera\n\n let camera = Camera::new_perspective(\n\n &context,\n\n viewport,\n\n vec3(0.0, 0.0, 2.0),\n\n vec3(0.0, 0.0, 0.0),\n\n vec3(0.0, 1.0, 0.0),\n\n degrees(60.0),\n\n 0.1,\n\n 10.0,\n\n )\n\n .unwrap();\n\n\n\n // Create the scene - a single colored triangle\n", "file_path": "examples/headless/src/main.rs", "rank": 9, "score": 151762.72214499553 }, { "content": "#[cfg(target_os = \"linux\")]\n\nfn build_context_osmesa<T1: ContextCurrentState>(\n\n cb: ContextBuilder<T1>,\n\n) -> Result<glutin::Context<NotCurrent>, CreationError> {\n\n use glutin::platform::unix::HeadlessContextExt;\n\n let size_one = PhysicalSize::new(1, 1);\n\n cb.build_osmesa(size_one)\n\n}\n\n\n", "file_path": "src/window/headless.rs", "rank": 10, "score": 150577.69753503526 }, { "content": "fn build_context_surfaceless<T1: ContextCurrentState>(\n\n cb: ContextBuilder<T1>,\n\n el: &EventLoop<()>,\n\n) -> Result<glutin::Context<NotCurrent>, CreationError> {\n\n use glutin::platform::unix::HeadlessContextExt;\n\n cb.build_surfaceless(&el)\n\n}*/\n\n\n", "file_path": "src/window/headless.rs", "rank": 11, "score": 150577.69753503526 }, { "content": "fn build_context_headless<T1: ContextCurrentState>(\n\n cb: ContextBuilder<T1>,\n\n el: &EventLoop<()>,\n\n) -> Result<glutin::Context<NotCurrent>, CreationError> {\n\n let size_one = PhysicalSize::new(1, 1);\n\n cb.build_headless(&el, size_one)\n\n}\n\n\n", "file_path": "src/window/headless.rs", "rank": 12, "score": 150577.69753503526 }, { "content": "use crate::core::*;\n\nuse crate::window::*;\n\n\n\n///\n\n/// A set of possible actions to apply to a camera when recieving input.\n\n///\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum CameraAction {\n\n /// No action.\n\n None,\n\n /// Rotate the camera around the horizontal axis as seen from the camera.\n\n Pitch {\n\n /// The speed of the rotation.\n\n speed: f32,\n\n },\n\n /// Orbits around the given target in the up direction as seen from the camera.\n\n OrbitUp {\n\n /// The target of the rotation.\n\n target: Vec3,\n\n /// The speed of the rotation.\n", "file_path": "src/window/control/camera_control.rs", "rank": 13, "score": 143443.73612160998 }, { "content": " *handled |= self.handle_action(camera, self.scroll_vertical, delta.1)?;\n\n change |= *handled;\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n Ok(change)\n\n }\n\n\n\n fn handle_action(\n\n &mut self,\n\n camera: &mut Camera,\n\n control_type: CameraAction,\n\n x: f64,\n\n ) -> ThreeDResult<bool> {\n\n match control_type {\n\n CameraAction::Pitch { speed } => {\n\n camera.pitch(radians(speed * x as f32))?;\n\n }\n", "file_path": "src/window/control/camera_control.rs", "rank": 14, "score": 143441.98841937253 }, { "content": " pub left_drag_horizontal: CameraAction,\n\n /// Specifies what happens when dragging vertically with the left mouse button.\n\n pub left_drag_vertical: CameraAction,\n\n /// Specifies what happens when dragging horizontally with the middle mouse button.\n\n pub middle_drag_horizontal: CameraAction,\n\n /// Specifies what happens when dragging vertically with the middle mouse button.\n\n pub middle_drag_vertical: CameraAction,\n\n /// Specifies what happens when dragging horizontally with the right mouse button.\n\n pub right_drag_horizontal: CameraAction,\n\n /// Specifies what happens when dragging vertically with the right mouse button.\n\n pub right_drag_vertical: CameraAction,\n\n /// Specifies what happens when scrolling horizontally.\n\n pub scroll_horizontal: CameraAction,\n\n /// Specifies what happens when scrolling vertically.\n\n pub scroll_vertical: CameraAction,\n\n}\n\n\n\nimpl CameraControl {\n\n /// Creates a new default CameraControl.\n\n pub fn new() -> Self {\n", "file_path": "src/window/control/camera_control.rs", "rank": 15, "score": 143441.60444645263 }, { "content": " Self::default()\n\n }\n\n\n\n /// Handles the events. Must be called each frame.\n\n pub fn handle_events(\n\n &mut self,\n\n camera: &mut Camera,\n\n events: &mut [Event],\n\n ) -> ThreeDResult<bool> {\n\n let mut change = false;\n\n for event in events.iter_mut() {\n\n match event {\n\n Event::MouseMotion {\n\n delta,\n\n button,\n\n handled,\n\n ..\n\n } => {\n\n if !*handled && button.is_some() {\n\n if let Some(b) = button {\n", "file_path": "src/window/control/camera_control.rs", "rank": 16, "score": 143440.44081796825 }, { "content": " /// The minimum distance to the target.\n\n min: f32,\n\n /// The maximum distance to the target.\n\n max: f32,\n\n },\n\n}\n\n\n\nimpl std::default::Default for CameraAction {\n\n fn default() -> Self {\n\n Self::None\n\n }\n\n}\n\n\n\n///\n\n/// A customizable controller for the camera.\n\n/// It is possible to specify a [CameraAction] for each of the input events.\n\n///\n\n#[derive(Clone, Copy, Debug, Default)]\n\npub struct CameraControl {\n\n /// Specifies what happens when dragging horizontally with the left mouse button.\n", "file_path": "src/window/control/camera_control.rs", "rank": 17, "score": 143440.2794390773 }, { "content": " let (control_horizontal, control_vertical) = match b {\n\n MouseButton::Left => {\n\n (self.left_drag_horizontal, self.left_drag_vertical)\n\n }\n\n MouseButton::Middle => {\n\n (self.middle_drag_horizontal, self.middle_drag_vertical)\n\n }\n\n MouseButton::Right => {\n\n (self.right_drag_horizontal, self.right_drag_vertical)\n\n }\n\n };\n\n *handled = self.handle_action(camera, control_horizontal, delta.0)?;\n\n *handled |= self.handle_action(camera, control_vertical, delta.1)?;\n\n change |= *handled;\n\n }\n\n }\n\n }\n\n Event::MouseWheel { delta, handled, .. } => {\n\n if !*handled {\n\n *handled = self.handle_action(camera, self.scroll_horizontal, delta.0)?;\n", "file_path": "src/window/control/camera_control.rs", "rank": 18, "score": 143436.6810255197 }, { "content": " camera.translate(&change)?;\n\n }\n\n CameraAction::Forward { speed } => {\n\n let change = camera.view_direction() * speed * x as f32;\n\n camera.translate(&change)?;\n\n }\n\n CameraAction::Zoom {\n\n target,\n\n speed,\n\n min,\n\n max,\n\n } => {\n\n camera.zoom_towards(&target, speed * x as f32, min, max)?;\n\n }\n\n CameraAction::None => {}\n\n }\n\n Ok(control_type != CameraAction::None)\n\n }\n\n}\n", "file_path": "src/window/control/camera_control.rs", "rank": 19, "score": 143436.14370291814 }, { "content": " CameraAction::OrbitUp { speed, target } => {\n\n camera.rotate_around_with_fixed_up(&target, 0.0, speed * x as f32)?;\n\n }\n\n CameraAction::Yaw { speed } => {\n\n camera.yaw(radians(speed * x as f32))?;\n\n }\n\n CameraAction::OrbitLeft { speed, target } => {\n\n camera.rotate_around_with_fixed_up(&target, speed * x as f32, 0.0)?;\n\n }\n\n CameraAction::Roll { speed } => {\n\n camera.roll(radians(speed * x as f32))?;\n\n }\n\n CameraAction::Left { speed } => {\n\n let change = -camera.right_direction() * x as f32 * speed;\n\n camera.translate(&change)?;\n\n }\n\n CameraAction::Up { speed } => {\n\n let right = camera.right_direction();\n\n let up = right.cross(camera.view_direction());\n\n let change = up * x as f32 * speed;\n", "file_path": "src/window/control/camera_control.rs", "rank": 20, "score": 143432.16506271024 }, { "content": " speed: f32,\n\n },\n\n /// Rotate the camera around the vertical axis as seen from the camera.\n\n Yaw {\n\n /// The speed of the rotation.\n\n speed: f32,\n\n },\n\n /// Orbits around the given target in the left direction as seen from the camera.\n\n OrbitLeft {\n\n /// The target of the rotation.\n\n target: Vec3,\n\n /// The speed of the rotation.\n\n speed: f32,\n\n },\n\n /// Rotate the camera around the forward axis as seen from the camera.\n\n Roll {\n\n /// The speed of the rotation.\n\n speed: f32,\n\n },\n\n /// Moves the camera to the left.\n", "file_path": "src/window/control/camera_control.rs", "rank": 21, "score": 143431.85453482077 }, { "content": " Left {\n\n /// The speed of the translation.\n\n speed: f32,\n\n },\n\n /// Moves the camera up.\n\n Up {\n\n /// The speed of the translation.\n\n speed: f32,\n\n },\n\n /// Moves the camera forward.\n\n Forward {\n\n /// The speed of the translation.\n\n speed: f32,\n\n },\n\n /// Zooms towards the given target.\n\n Zoom {\n\n /// The target of the zoom.\n\n target: Vec3,\n\n /// The speed of the zoom.\n\n speed: f32,\n", "file_path": "src/window/control/camera_control.rs", "rank": 22, "score": 143431.03081402727 }, { "content": "fn shadow_matrix(camera: &Camera) -> Mat4 {\n\n let bias_matrix = crate::Mat4::new(\n\n 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0,\n\n );\n\n bias_matrix * camera.projection() * camera.view()\n\n}\n\n\n", "file_path": "src/renderer/light.rs", "rank": 23, "score": 143289.48161996555 }, { "content": "fn update_modifiers(modifiers: &mut Modifiers, event: &web_sys::KeyboardEvent) -> bool {\n\n let old = modifiers.clone();\n\n *modifiers = Modifiers {\n\n alt: event.alt_key(),\n\n ctrl: event.ctrl_key(),\n\n shift: event.shift_key(),\n\n command: event.ctrl_key() || event.meta_key(),\n\n };\n\n old.alt != modifiers.alt\n\n || old.ctrl != modifiers.ctrl\n\n || old.shift != modifiers.shift\n\n || old.command != modifiers.command\n\n}\n\n\n", "file_path": "src/window/canvas.rs", "rank": 24, "score": 141562.1787145617 }, { "content": "fn generate(context: &Context) -> ThreeDResult<crate::context::Texture> {\n\n unsafe {\n\n Ok(context\n\n .create_texture()\n\n .map_err(|e| CoreError::TextureCreation(e))?)\n\n }\n\n}\n\n\n", "file_path": "src/core/texture.rs", "rank": 25, "score": 139215.10691051398 }, { "content": "///\n\n/// Finds the closest intersection between a ray from the given camera in the given pixel coordinate and the given geometries.\n\n/// The pixel coordinate must be in physical pixels, where (viewport.x, viewport.y) indicate the bottom left corner of the viewport\n\n/// and (viewport.x + viewport.width, viewport.y + viewport.height) indicate the top right corner.\n\n/// Returns ```None``` if no geometry was hit between the near (`z_near`) and far (`z_far`) plane for this camera.\n\n///\n\npub fn pick(\n\n context: &Context,\n\n camera: &Camera,\n\n pixel: (f32, f32),\n\n geometries: &[&dyn Geometry],\n\n) -> ThreeDResult<Option<Vec3>> {\n\n let pos = camera.position_at_pixel(pixel);\n\n let dir = camera.view_direction_at_pixel(pixel);\n\n ray_intersect(\n\n context,\n\n pos + dir * camera.z_near(),\n\n dir,\n\n camera.z_far() - camera.z_near(),\n\n geometries,\n\n )\n\n}\n\n\n", "file_path": "src/renderer.rs", "rank": 26, "score": 138410.86719628845 }, { "content": "///\n\n/// Render the objects using the given camera and lights. If the objects materials doesn't require lighting, you can use `&[]` as the `lights` argument.\n\n/// Also, objects outside the camera frustum are not rendered and the objects are rendered in the order given by [cmp_render_order].\n\n/// Must be called in the callback given as input to a [RenderTarget], [ColorTarget] or [DepthTarget] write method.\n\n///\n\npub fn render_pass(\n\n camera: &Camera,\n\n objects: &[&dyn Object],\n\n lights: &[&dyn Light],\n\n) -> ThreeDResult<()> {\n\n let mut culled_objects = objects\n\n .iter()\n\n .filter(|o| camera.in_frustum(&o.aabb()))\n\n .collect::<Vec<_>>();\n\n culled_objects.sort_by(|a, b| cmp_render_order(camera, a, b));\n\n for object in culled_objects {\n\n object.render(camera, lights)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/renderer.rs", "rank": 27, "score": 136257.55277572662 }, { "content": "///\n\n/// Finds the closest intersection between a ray starting at the given position in the given direction and the given geometries.\n\n/// Returns ```None``` if no geometry was hit before the given maximum depth.\n\n///\n\npub fn ray_intersect(\n\n context: &Context,\n\n position: Vec3,\n\n direction: Vec3,\n\n max_depth: f32,\n\n geometries: &[&dyn Geometry],\n\n) -> ThreeDResult<Option<Vec3>> {\n\n use crate::core::*;\n\n let viewport = Viewport::new_at_origo(1, 1);\n\n let up = if direction.dot(vec3(1.0, 0.0, 0.0)).abs() > 0.99 {\n\n direction.cross(vec3(0.0, 1.0, 0.0))\n\n } else {\n\n direction.cross(vec3(1.0, 0.0, 0.0))\n\n };\n\n let camera = Camera::new_orthographic(\n\n context,\n\n viewport,\n\n position,\n\n position + direction * max_depth,\n\n up,\n", "file_path": "src/renderer.rs", "rank": 28, "score": 136247.7297644581 }, { "content": "///\n\n/// Compare function for sorting objects based on distance from the camera.\n\n/// The order is opaque objects from nearest to farthest away from the camera,\n\n/// then transparent objects from farthest away to closest to the camera.\n\n///\n\npub fn cmp_render_order(\n\n camera: &Camera,\n\n obj0: impl Object,\n\n obj1: impl Object,\n\n) -> std::cmp::Ordering {\n\n if obj0.is_transparent() == obj1.is_transparent() {\n\n let distance_a = camera.position().distance2(obj0.aabb().center());\n\n let distance_b = camera.position().distance2(obj1.aabb().center());\n\n if obj0.is_transparent() {\n\n distance_b.partial_cmp(&distance_a).unwrap()\n\n } else {\n\n distance_a.partial_cmp(&distance_b).unwrap()\n\n }\n\n } else {\n\n if obj0.is_transparent() {\n\n std::cmp::Ordering::Greater\n\n } else {\n\n std::cmp::Ordering::Less\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/renderer.rs", "rank": 29, "score": 134194.99812218468 }, { "content": "fn clear(context: &Context, clear_state: &ClearState) {\n\n context.set_write_mask(WriteMask {\n\n red: clear_state.red.is_some(),\n\n green: clear_state.green.is_some(),\n\n blue: clear_state.blue.is_some(),\n\n alpha: clear_state.alpha.is_some(),\n\n depth: clear_state.depth.is_some(),\n\n });\n\n let clear_color = clear_state.red.is_some()\n\n || clear_state.green.is_some()\n\n || clear_state.blue.is_some()\n\n || clear_state.alpha.is_some();\n\n unsafe {\n\n if clear_color {\n\n context.clear_color(\n\n clear_state.red.unwrap_or(0.0),\n\n clear_state.green.unwrap_or(0.0),\n\n clear_state.blue.unwrap_or(0.0),\n\n clear_state.alpha.unwrap_or(1.0),\n\n );\n", "file_path": "src/core/render_target/render_target2d_array.rs", "rank": 30, "score": 131421.1131973483 }, { "content": "///\n\n/// Deserialize the 6 images given as byte arrays into a [CpuTextureCube] using\n\n/// the [image](https://crates.io/crates/image/main.rs) crate.\n\n/// The CpuTextureCube can then be used to create a [TextureCubeMap].\n\n///\n\npub fn cube_image_from_bytes(\n\n right_bytes: &[u8],\n\n left_bytes: &[u8],\n\n top_bytes: &[u8],\n\n bottom_bytes: &[u8],\n\n front_bytes: &[u8],\n\n back_bytes: &[u8],\n\n) -> ThreeDResult<CpuTextureCube> {\n\n let right = image_from_bytes(right_bytes)?;\n\n let left = image_from_bytes(left_bytes)?;\n\n let top = image_from_bytes(top_bytes)?;\n\n let bottom = image_from_bytes(bottom_bytes)?;\n\n let front = image_from_bytes(front_bytes)?;\n\n let back = image_from_bytes(back_bytes)?;\n\n let data = match right.data {\n\n TextureData::RU8(right) => {\n\n let left = if let TextureData::RU8(data) = left.data {\n\n data\n\n } else {\n\n unreachable!()\n", "file_path": "src/io/parser/img.rs", "rank": 31, "score": 130354.26641417338 }, { "content": "fn clear(context: &Context, clear_state: &ClearState) {\n\n context.set_write_mask(WriteMask {\n\n red: clear_state.red.is_some(),\n\n green: clear_state.green.is_some(),\n\n blue: clear_state.blue.is_some(),\n\n alpha: clear_state.alpha.is_some(),\n\n depth: clear_state.depth.is_some(),\n\n });\n\n let clear_color = clear_state.red.is_some()\n\n || clear_state.green.is_some()\n\n || clear_state.blue.is_some()\n\n || clear_state.alpha.is_some();\n\n unsafe {\n\n if clear_color {\n\n context.clear_color(\n\n clear_state.red.unwrap_or(0.0),\n\n clear_state.green.unwrap_or(0.0),\n\n clear_state.blue.unwrap_or(0.0),\n\n clear_state.alpha.unwrap_or(1.0),\n\n );\n", "file_path": "src/core/render_target/render_target_cube_map.rs", "rank": 32, "score": 130113.5960614844 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n main::main();\n\n Ok(())\n\n}\n", "file_path": "examples/triangle/src/lib.rs", "rank": 33, "score": 121155.22023810685 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n Ok(())\n\n}\n", "file_path": "examples/headless/src/lib.rs", "rank": 34, "score": 121155.22023810685 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n main::main();\n\n Ok(())\n\n}\n", "file_path": "examples/shapes2d/src/lib.rs", "rank": 35, "score": 121155.22023810685 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n main::main();\n\n Ok(())\n\n}\n", "file_path": "examples/shapes/src/lib.rs", "rank": 36, "score": 121155.22023810685 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n main::run();\n\n Ok(())\n\n}\n", "file_path": "examples/fireworks/src/lib.rs", "rank": 37, "score": 121155.22023810685 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n main::main();\n\n Ok(())\n\n}\n", "file_path": "examples/mandelbrot/src/lib.rs", "rank": 38, "score": 121155.22023810685 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_log::init_with_level(log::Level::Debug).unwrap();\n\n\n\n use log::info;\n\n info!(\"Logging works!\");\n\n\n\n std::panic::set_hook(Box::new(console_error_panic_hook::hook));\n\n main::main();\n\n Ok(())\n\n}\n", "file_path": "examples/screen/src/lib.rs", "rank": 39, "score": 121155.22023810685 }, { "content": "fn is_printable_char(chr: char) -> bool {\n\n let is_in_private_use_area = '\\u{e000}' <= chr && chr <= '\\u{f8ff}'\n\n || '\\u{f0000}' <= chr && chr <= '\\u{ffffd}'\n\n || '\\u{100000}' <= chr && chr <= '\\u{10fffd}';\n\n\n\n !is_in_private_use_area && !chr.is_ascii_control()\n\n}\n\n\n", "file_path": "src/window/glutin_window.rs", "rank": 40, "score": 110441.42280258781 }, { "content": "fn construct_input_state(frame_input: &mut FrameInput) -> egui::RawInput {\n\n let mut scroll_delta = egui::Vec2::ZERO;\n\n let mut egui_modifiers = egui::Modifiers::default();\n\n let mut egui_events = Vec::new();\n\n for event in frame_input.events.iter() {\n\n match event {\n\n Event::KeyPress {\n\n kind,\n\n modifiers,\n\n handled,\n\n } => {\n\n if !handled {\n\n egui_events.push(egui::Event::Key {\n\n key: translate_to_egui_key_code(kind),\n\n pressed: true,\n\n modifiers: map_modifiers(modifiers),\n\n });\n\n }\n\n }\n\n Event::KeyRelease {\n", "file_path": "src/gui/egui_gui.rs", "rank": 41, "score": 107971.06131786518 }, { "content": "///\n\n/// Deserialize the given bytes representing an image into a [CpuTexture] using\n\n/// the [image](https://crates.io/crates/image/main.rs) crate.\n\n/// The CpuTexture can then be used to create a [Texture2D].\n\n/// Supported formats: PNG, JPEG, GIF, WebP, pnm (pbm, pgm, ppm and pam), TIFF, DDS, BMP, ICO, HDR, farbfeld.\n\n/// **Note:** If the image contains and you want to load high dynamic range (hdr) information, use [hdr_image_from_bytes] instead.\n\n///\n\npub fn image_from_bytes(bytes: &[u8]) -> ThreeDResult<CpuTexture> {\n\n use image::DynamicImage;\n\n use image::GenericImageView as _;\n\n let img = image::load_from_memory(bytes)?;\n\n let width = img.width();\n\n let height = img.height();\n\n let data = match img {\n\n DynamicImage::ImageLuma8(_) => TextureData::RU8(img.into_bytes()),\n\n DynamicImage::ImageLumaA8(_) => {\n\n let bytes = img.as_bytes();\n\n let mut data = Vec::new();\n\n for i in 0..bytes.len() / 2 {\n\n data.push([bytes[i * 2], bytes[i * 2 + 1]]);\n\n }\n\n TextureData::RgU8(data)\n\n }\n\n DynamicImage::ImageRgb8(_) => {\n\n let bytes = img.as_bytes();\n\n let mut data = Vec::new();\n\n for i in 0..bytes.len() / 3 {\n", "file_path": "src/io/parser/img.rs", "rank": 42, "score": 107836.49179683218 }, { "content": "///\n\n/// Deserialize the given bytes representing a hdr image into a [CpuTexture] using\n\n/// the [image](https://crates.io/crates/image/main.rs) crate.\n\n/// The CpuTexture can then be used to create a [Texture2D] or a [TextureCubeMap] using the `new_from_equirectangular` method.\n\n/// Supported formats: HDR.\n\n///\n\npub fn hdr_image_from_bytes(bytes: &[u8]) -> ThreeDResult<CpuTexture> {\n\n use image::codecs::hdr::*;\n\n use image::*;\n\n let decoder = HdrDecoder::new(bytes)?;\n\n let metadata = decoder.metadata();\n\n let img = decoder.read_image_native()?;\n\n Ok(CpuTexture {\n\n data: TextureData::RgbF32(\n\n img.iter()\n\n .map(|rgbe| {\n\n let Rgb(values) = rgbe.to_hdr();\n\n [values[0], values[1], values[2]]\n\n })\n\n .collect::<Vec<_>>(),\n\n ),\n\n width: metadata.width,\n\n height: metadata.height,\n\n ..Default::default()\n\n })\n\n}\n\n\n", "file_path": "src/io/parser/img.rs", "rank": 43, "score": 106428.20743354034 }, { "content": "pub fn rotation_matrix_from_dir_to_dir(source_dir: Vec3, target_dir: Vec3) -> Mat4 {\n\n Mat4::from(Mat3::from(Basis3::between_vectors(source_dir, target_dir)))\n\n}\n", "file_path": "src/core/math.rs", "rank": 44, "score": 104237.93385311599 }, { "content": "fn flip_y<T: TextureDataType>(pixels: &mut [T], width: usize, height: usize) {\n\n for row in 0..height / 2 {\n\n for col in 0..width {\n\n let index0 = width * row + col;\n\n let index1 = width * (height - row - 1) + col;\n\n pixels.swap(index0, index1);\n\n }\n\n }\n\n}\n", "file_path": "src/core.rs", "rank": 45, "score": 101758.62609548308 }, { "content": "fn should_ignore_key(key: &str) -> bool {\n\n let is_function_key = key.starts_with('F') && key.len() > 1;\n\n is_function_key\n\n || matches!(\n\n key,\n\n \"Alt\"\n\n | \"ArrowDown\"\n\n | \"ArrowLeft\"\n\n | \"ArrowRight\"\n\n | \"ArrowUp\"\n\n | \"Backspace\"\n\n | \"CapsLock\"\n\n | \"ContextMenu\"\n\n | \"Control\"\n\n | \"Delete\"\n\n | \"End\"\n\n | \"Enter\"\n\n | \"Esc\"\n\n | \"Escape\"\n\n | \"Help\"\n", "file_path": "src/window/canvas.rs", "rank": 46, "score": 101704.42655404234 }, { "content": "use crate::core::*;\n\nuse crate::window::*;\n\n\n\n///\n\n/// A control that makes the camera fly through the 3D scene.\n\n///\n\npub struct FlyControl {\n\n control: CameraControl,\n\n}\n\n\n\nimpl FlyControl {\n\n /// Creates a new fly control with the given speed of movements.\n\n pub fn new(speed: f32) -> Self {\n\n Self {\n\n control: CameraControl {\n\n left_drag_horizontal: CameraAction::Yaw {\n\n speed: std::f32::consts::PI / 1800.0,\n\n },\n\n left_drag_vertical: CameraAction::Pitch {\n\n speed: std::f32::consts::PI / 1800.0,\n", "file_path": "src/window/control/fly_control.rs", "rank": 47, "score": 98792.49160646017 }, { "content": "use crate::core::*;\n\nuse crate::window::*;\n\n\n\n///\n\n/// A control that makes the camera orbit around a target.\n\n///\n\npub struct OrbitControl {\n\n control: CameraControl,\n\n}\n\n\n\nimpl OrbitControl {\n\n /// Creates a new orbit control with the given target and minimum and maximum distance to the target.\n\n pub fn new(target: Vec3, min_distance: f32, max_distance: f32) -> Self {\n\n Self {\n\n control: CameraControl {\n\n left_drag_horizontal: CameraAction::OrbitLeft { target, speed: 0.5 },\n\n left_drag_vertical: CameraAction::OrbitUp { target, speed: 0.5 },\n\n scroll_vertical: CameraAction::Zoom {\n\n min: min_distance,\n\n max: max_distance,\n", "file_path": "src/window/control/orbit_control.rs", "rank": 48, "score": 98791.5753518331 }, { "content": " speed: 0.1,\n\n target,\n\n },\n\n ..Default::default()\n\n },\n\n }\n\n }\n\n\n\n /// Handles the events. Must be called each frame.\n\n pub fn handle_events(\n\n &mut self,\n\n camera: &mut Camera,\n\n events: &mut [Event],\n\n ) -> ThreeDResult<bool> {\n\n if let CameraAction::Zoom { speed, target, .. } = &mut self.control.scroll_horizontal {\n\n *speed = 0.1 / target.distance(*camera.position());\n\n }\n\n self.control.handle_events(camera, events)\n\n }\n\n}\n", "file_path": "src/window/control/orbit_control.rs", "rank": 49, "score": 98788.02354046235 }, { "content": " },\n\n scroll_vertical: CameraAction::Forward { speed },\n\n right_drag_horizontal: CameraAction::Left { speed },\n\n right_drag_vertical: CameraAction::Up { speed },\n\n ..Default::default()\n\n },\n\n }\n\n }\n\n\n\n /// Handles the events. Must be called each frame.\n\n pub fn handle_events(\n\n &mut self,\n\n camera: &mut Camera,\n\n events: &mut [Event],\n\n ) -> ThreeDResult<bool> {\n\n self.control.handle_events(camera, events)\n\n }\n\n}\n", "file_path": "src/window/control/fly_control.rs", "rank": 50, "score": 98786.62914354209 }, { "content": "fn translate_key(key: &str) -> Option<Key> {\n\n use Key::*;\n\n Some(match key {\n\n \"ArrowDown\" => ArrowDown,\n\n \"ArrowLeft\" => ArrowLeft,\n\n \"ArrowRight\" => ArrowRight,\n\n \"ArrowUp\" => ArrowUp,\n\n\n\n \"Esc\" | \"Escape\" => Escape,\n\n \"Tab\" => Tab,\n\n \"Backspace\" => Backspace,\n\n \"Enter\" => Enter,\n\n \"Space\" => Space,\n\n\n\n \"Help\" | \"Insert\" => Insert,\n\n \"Delete\" => Delete,\n\n \"Home\" => Home,\n\n \"End\" => End,\n\n \"PageUp\" => PageUp,\n\n \"PageDown\" => PageDown,\n", "file_path": "src/window/canvas.rs", "rank": 51, "score": 98540.70999864132 }, { "content": "fn translate_virtual_key_code(key: event::VirtualKeyCode) -> Option<crate::Key> {\n\n use event::VirtualKeyCode::*;\n\n\n\n Some(match key {\n\n Down => Key::ArrowDown,\n\n Left => Key::ArrowLeft,\n\n Right => Key::ArrowRight,\n\n Up => Key::ArrowUp,\n\n\n\n Escape => Key::Escape,\n\n Tab => Key::Tab,\n\n Back => Key::Backspace,\n\n Return => Key::Enter,\n\n Space => Key::Space,\n\n\n\n Insert => Key::Insert,\n\n Delete => Key::Delete,\n\n Home => Key::Home,\n\n End => Key::End,\n\n PageUp => Key::PageUp,\n", "file_path": "src/window/glutin_window.rs", "rank": 52, "score": 97074.22679633359 }, { "content": "use crate::renderer::*;\n\nuse crate::window::*;\n\n\n\n///\n\n/// A control that makes the camera move like it is a person on the ground.\n\n///\n\npub struct FirstPersonControl {\n\n control: CameraControl,\n\n}\n\n\n\nimpl FirstPersonControl {\n\n /// Creates a new first person control with the given speed of movements.\n\n pub fn new(speed: f32) -> Self {\n\n Self {\n\n control: CameraControl {\n\n left_drag_horizontal: CameraAction::Yaw {\n\n speed: std::f32::consts::PI / 1800.0,\n\n },\n\n scroll_vertical: CameraAction::Forward { speed },\n\n ..Default::default()\n", "file_path": "src/window/control/first_person_control.rs", "rank": 53, "score": 96997.35157863263 }, { "content": " },\n\n }\n\n }\n\n\n\n /// Handles the events. Must be called each frame.\n\n pub fn handle_events(\n\n &mut self,\n\n camera: &mut Camera,\n\n events: &mut [Event],\n\n ) -> ThreeDResult<bool> {\n\n self.control.handle_events(camera, events)\n\n }\n\n}\n", "file_path": "src/window/control/first_person_control.rs", "rank": 54, "score": 96992.66643589323 }, { "content": "fn vertex_transformations(cpu_mesh: &CpuMesh) -> Instances {\n\n Instances {\n\n translations: cpu_mesh.positions.to_f32(),\n\n ..Default::default()\n\n }\n\n}\n\n\n", "file_path": "examples/wireframe/src/main.rs", "rank": 55, "score": 96248.20806245683 }, { "content": "fn edge_transformations(cpu_mesh: &CpuMesh) -> Instances {\n\n let indices = cpu_mesh.indices.as_ref().unwrap().to_u32();\n\n let positions = cpu_mesh.positions.to_f32();\n\n let mut translations = Vec::new();\n\n let mut rotations = Vec::new();\n\n let mut scales = Vec::new();\n\n let mut keys = Vec::new();\n\n for f in 0..indices.len() / 3 {\n\n let mut fun = |i1, i2| {\n\n let key = if i1 < i2 { (i1, i2) } else { (i2, i1) };\n\n if !keys.contains(&key) {\n\n keys.push(key);\n\n let p1: Vec3 = positions[i1];\n\n let p2: Vec3 = positions[i2];\n\n translations.push(p1);\n\n scales.push(vec3((p1 - p2).magnitude(), 1.0, 1.0));\n\n rotations.push(Quat::from_arc(\n\n vec3(1.0, 0.0, 0.0),\n\n (p2 - p1).normalize(),\n\n None,\n", "file_path": "examples/wireframe/src/main.rs", "rank": 56, "score": 96248.20806245683 }, { "content": "fn zoom(zoom: f32, viewport: Viewport) -> Viewport {\n\n let width = (viewport.width as f32 * zoom) as u32;\n\n let height = (viewport.height as f32 * zoom) as u32;\n\n Viewport {\n\n x: ((viewport.width - width) / 2 + viewport.x as u32) as i32,\n\n y: ((viewport.height - height) / 2 + viewport.y as u32) as i32,\n\n width,\n\n height,\n\n }\n\n}\n", "file_path": "examples/screen/src/main.rs", "rank": 57, "score": 95319.40456120363 }, { "content": "//!\n\n//! Contain a [CameraControl] struct that can be easily customized as well as a set of default camera controls.\n\n//!\n\n\n\nmod camera_control;\n\n#[doc(inline)]\n\npub use camera_control::*;\n\n\n\nmod orbit_control;\n\n#[doc(inline)]\n\npub use orbit_control::*;\n\n\n\nmod first_person_control;\n\n#[doc(inline)]\n\npub use first_person_control::*;\n\n\n\nmod fly_control;\n\n#[doc(inline)]\n\npub use fly_control::*;\n", "file_path": "src/window/control.rs", "rank": 58, "score": 93438.32750987815 }, { "content": "#[derive(Serialize)]\n\nstruct ContextOptions {\n\n antialias: bool,\n\n}\n\n\n", "file_path": "src/window/canvas.rs", "rank": 59, "score": 88878.45503063627 }, { "content": "#[derive(Debug, Eq, PartialEq, Copy, Clone)]\n\nenum CameraType {\n\n Primary,\n\n Secondary,\n\n}\n\n\n\nuse three_d::*;\n\n\n\npub async fn run() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Statues!\".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 primary_camera = Camera::new_perspective(\n\n &context,\n\n window.viewport().unwrap(),\n\n vec3(-300.0, 250.0, 200.0),\n", "file_path": "examples/statues/src/main.rs", "rank": 60, "score": 86458.8619686864 }, { "content": "///\n\n/// Represents a material that, together with a [geometry], can be rendered using [Geometry::render_with_material].\n\n/// Alternatively, a geometry and a material can be combined in a [Gm],\n\n/// thereby creating an [Object] which can be used in a render call, for example [render_pass].\n\n///\n\n/// The material can use an attribute by adding the folowing to the fragment shader source code.\n\n/// - position (in world space): `in vec3 pos;`\n\n/// - normal: `in vec3 nor;`,\n\n/// - tangent: `in vec3 tang;`\n\n/// - bitangent: `in vec3 bitang;`\n\n/// - uv coordinates: `in vec2 uvs;`\n\n/// - color: `in vec4 col;`\n\n/// The rendering will fail if the material requires one of these attributes and the [geometry] does not provide it.\n\n///\n\npub trait Material {\n\n /// Returns the fragment shader source for this material. Should output the final fragment color.\n\n fn fragment_shader_source(&self, use_vertex_colors: bool, lights: &[&dyn Light]) -> String;\n\n /// Sends the uniform data needed for this material to the fragment shader.\n\n fn use_uniforms(\n\n &self,\n\n program: &Program,\n\n camera: &Camera,\n\n lights: &[&dyn Light],\n\n ) -> ThreeDResult<()>;\n\n /// Returns the render states needed to render with this material.\n\n fn render_states(&self) -> RenderStates;\n\n /// Returns whether or not this material is transparent.\n\n fn is_transparent(&self) -> bool;\n\n}\n\n\n\nimpl<T: Material + ?Sized> Material for &T {\n\n fn fragment_shader_source(&self, use_vertex_colors: bool, lights: &[&dyn Light]) -> String {\n\n (*self).fragment_shader_source(use_vertex_colors, lights)\n\n }\n", "file_path": "src/renderer/material.rs", "rank": 61, "score": 69358.53941312562 }, { "content": "///\n\n/// Represents a 3D geometry that, together with a [material], can be rendered using [Geometry::render_with_material].\n\n/// Alternatively, a geometry and a material can be combined in a [Gm],\n\n/// thereby creating an [Object] which can be used in a render call, for example [render_pass].\n\n///\n\n/// If requested by the material, the geometry has to support the following attributes in the vertex shader source code.\n\n/// - position: `out vec3 pos;` (must be in world space)\n\n/// - normal: `out vec3 nor;`\n\n/// - tangent: `out vec3 tang;`\n\n/// - bitangent: `out vec3 bitang;`\n\n/// - uv coordinates: `out vec2 uvs;` (must be flipped in v compared to standard uv coordinates, ie. do `uvs = vec2(uvs.x, 1.0 - uvs.y);` in the vertex shader or do the flip before constructing the uv coordinates vertex buffer)\n\n/// - color: `out vec4 col;`\n\n///\n\npub trait Geometry {\n\n ///\n\n /// Render the geometry with the given material.\n\n /// Must be called in the callback given as input to a [RenderTarget], [ColorTarget] or [DepthTarget] write method.\n\n /// Use an empty array for the `lights` argument, if the objects does not require lights to be rendered.\n\n ///\n\n fn render_with_material(\n\n &self,\n\n material: &dyn Material,\n\n camera: &Camera,\n\n lights: &[&dyn Light],\n\n ) -> ThreeDResult<()>;\n\n\n\n ///\n\n /// Returns the [AxisAlignedBoundingBox] for this geometry in the global coordinate system.\n\n ///\n\n fn aabb(&self) -> AxisAlignedBoundingBox;\n\n}\n\n\n\nimpl<T: Geometry + ?Sized> Geometry for &T {\n", "file_path": "src/renderer/geometry.rs", "rank": 62, "score": 69357.83961260311 }, { "content": "/// Represents a light source.\n\npub trait Light {\n\n /// The fragment shader source for calculating this lights contribution to the color in a fragment.\n\n /// It should contain a function with this signature\n\n /// `vec3 calculate_lighting{}(vec3 surface_color, vec3 position, vec3 normal, vec3 view_direction, float metallic, float roughness, float occlusion)`\n\n /// Where `{}` is replaced with the number i given as input.\n\n /// This function should return the color contribution for this light on the surface with the given surface parameters.\n\n fn shader_source(&self, i: u32) -> String;\n\n /// Should bind the uniforms that is needed for calculating this lights contribution to the color in [Light::shader_source].\n\n fn use_uniforms(&self, program: &Program, i: u32) -> ThreeDResult<()>;\n\n}\n\n\n\nimpl<T: Light + ?Sized> Light for &T {\n\n fn shader_source(&self, i: u32) -> String {\n\n (*self).shader_source(i)\n\n }\n\n fn use_uniforms(&self, program: &Program, i: u32) -> ThreeDResult<()> {\n\n (*self).use_uniforms(program, i)\n\n }\n\n}\n\n\n", "file_path": "src/renderer/light.rs", "rank": 63, "score": 69353.5640345683 }, { "content": "fn set_parameters(\n\n context: &Context,\n\n target: u32,\n\n min_filter: Interpolation,\n\n mag_filter: Interpolation,\n\n mip_map_filter: Option<Interpolation>,\n\n wrap_s: Wrapping,\n\n wrap_t: Wrapping,\n\n wrap_r: Option<Wrapping>,\n\n) -> ThreeDResult<()> {\n\n unsafe {\n\n match mip_map_filter {\n\n None => context.tex_parameter_i32(\n\n target,\n\n crate::context::TEXTURE_MIN_FILTER,\n\n interpolation_from(min_filter),\n\n ),\n\n Some(Interpolation::Nearest) => {\n\n if min_filter == Interpolation::Nearest {\n\n context.tex_parameter_i32(\n", "file_path": "src/core/texture.rs", "rank": 64, "score": 69196.18365972128 }, { "content": "fn copy_from(\n\n context: &Context,\n\n color_texture: Option<&Texture2D>,\n\n depth_texture: Option<&DepthTargetTexture2D>,\n\n viewport: Viewport,\n\n write_mask: WriteMask,\n\n) -> ThreeDResult<()> {\n\n if color_texture.is_some() || depth_texture.is_some() {\n\n let fragment_shader_source = if color_texture.is_some() && depth_texture.is_some() {\n\n \"\n\n uniform sampler2D colorMap;\n\n uniform sampler2D depthMap;\n\n in vec2 uv;\n\n layout (location = 0) out vec4 color;\n\n void main()\n\n {\n\n color = texture(colorMap, uv);\n\n gl_FragDepth = texture(depthMap, uv).r;\n\n }\"\n\n } else if color_texture.is_some() {\n", "file_path": "src/core/render_target.rs", "rank": 65, "score": 69196.18365972128 }, { "content": "pub trait Mat4Ext {\n\n fn as_array(&self) -> [f32; 16];\n\n}\n\n\n\nimpl Mat4Ext for Mat4 {\n\n fn as_array(&self) -> [f32; 16] {\n\n [\n\n self.x.x, self.x.y, self.x.z, self.x.w, self.y.x, self.y.y, self.y.z, self.y.w,\n\n self.z.x, self.z.y, self.z.z, self.z.w, self.w.x, self.w.y, self.w.z, self.w.w,\n\n ]\n\n }\n\n}\n\n\n\npub const fn degrees(v: f32) -> Degrees {\n\n Deg(v)\n\n}\n\npub const fn radians(v: f32) -> Radians {\n\n Rad(v)\n\n}\n\n\n", "file_path": "src/core/math.rs", "rank": 66, "score": 68322.2322200676 }, { "content": "///\n\n/// Represents a 2D geometry that is possible to render with a [Material].\n\n///\n\npub trait Geometry2D {\n\n ///\n\n /// Render the object with the given material.\n\n /// Must be called in the callback given as input to a [RenderTarget], [ColorTarget] or [DepthTarget] write method.\n\n ///\n\n fn render_with_material(&self, material: &dyn Material, viewport: Viewport)\n\n -> ThreeDResult<()>;\n\n}\n\n\n\nimpl<T: Geometry2D + ?Sized> Geometry2D for &T {\n\n fn render_with_material(\n\n &self,\n\n material: &dyn Material,\n\n viewport: Viewport,\n\n ) -> ThreeDResult<()> {\n\n (*self).render_with_material(material, viewport)\n\n }\n\n}\n\n\n\nimpl<T: Geometry2D + ?Sized> Geometry2D for &mut T {\n", "file_path": "src/renderer/geometry.rs", "rank": 67, "score": 68322.2322200676 }, { "content": "pub trait Vec3Ext {\n\n fn as_array(&self) -> [f32; 3];\n\n}\n\n\n\nimpl Vec3Ext for Vec3 {\n\n fn as_array(&self) -> [f32; 3] {\n\n (*self).into()\n\n }\n\n}\n\n\n", "file_path": "src/core/math.rs", "rank": 68, "score": 68322.2322200676 }, { "content": "pub trait Vec4Ext {\n\n fn as_array(&self) -> [f32; 4];\n\n}\n\n\n\nimpl Vec4Ext for Vec4 {\n\n fn as_array(&self) -> [f32; 4] {\n\n (*self).into()\n\n }\n\n}\n\n\n\nimpl Vec4Ext for Quat {\n\n fn as_array(&self) -> [f32; 4] {\n\n [self.v.x, self.v.y, self.v.z, self.s]\n\n }\n\n}\n\n\n", "file_path": "src/core/math.rs", "rank": 69, "score": 68322.2322200676 }, { "content": "pub trait Mat3Ext {\n\n fn as_array(&self) -> [f32; 9];\n\n}\n\n\n\nimpl Mat3Ext for Mat3 {\n\n fn as_array(&self) -> [f32; 9] {\n\n [\n\n self.x.x, self.x.y, self.x.z, self.y.x, self.y.y, self.y.z, self.z.x, self.z.y,\n\n self.z.z,\n\n ]\n\n }\n\n}\n\n\n", "file_path": "src/core/math.rs", "rank": 70, "score": 68322.2322200676 }, { "content": "pub trait Vec2Ext {\n\n fn as_array(&self) -> [f32; 2];\n\n}\n\nimpl Vec2Ext for Vec2 {\n\n fn as_array(&self) -> [f32; 2] {\n\n (*self).into()\n\n }\n\n}\n\n\n", "file_path": "src/core/math.rs", "rank": 71, "score": 68322.2322200676 }, { "content": "pub trait Mat2Ext {\n\n fn as_array(&self) -> [f32; 4];\n\n}\n\n\n\nimpl Mat2Ext for Mat2 {\n\n fn as_array(&self) -> [f32; 4] {\n\n [self.x.x, self.x.y, self.y.x, self.y.y]\n\n }\n\n}\n\n\n", "file_path": "src/core/math.rs", "rank": 72, "score": 68322.2322200676 }, { "content": "fn index_buffer_from_mesh(\n\n context: &Context,\n\n cpu_mesh: &CpuMesh,\n\n) -> ThreeDResult<Option<ElementBuffer>> {\n\n Ok(if let Some(ref indices) = cpu_mesh.indices {\n\n Some(match indices {\n\n Indices::U8(ind) => ElementBuffer::new_with_data(context, ind)?,\n\n Indices::U16(ind) => ElementBuffer::new_with_data(context, ind)?,\n\n Indices::U32(ind) => ElementBuffer::new_with_data(context, ind)?,\n\n })\n\n } else {\n\n None\n\n })\n\n}\n", "file_path": "src/renderer/geometry.rs", "rank": 73, "score": 68169.00021739541 }, { "content": "fn vertex_buffers_from_mesh(\n\n context: &Context,\n\n cpu_mesh: &CpuMesh,\n\n) -> ThreeDResult<HashMap<String, VertexBuffer>> {\n\n #[cfg(debug_assertions)]\n\n cpu_mesh.validate()?;\n\n\n\n let mut buffers = HashMap::new();\n\n buffers.insert(\n\n \"position\".to_string(),\n\n VertexBuffer::new_with_data(context, &cpu_mesh.positions.to_f32())?,\n\n );\n\n if let Some(ref normals) = cpu_mesh.normals {\n\n buffers.insert(\n\n \"normal\".to_string(),\n\n VertexBuffer::new_with_data(context, normals)?,\n\n );\n\n };\n\n if let Some(ref tangents) = cpu_mesh.tangents {\n\n buffers.insert(\n", "file_path": "src/renderer/geometry.rs", "rank": 74, "score": 68169.00021739541 }, { "content": "fn copy_from_array(\n\n context: &Context,\n\n color_texture: Option<(&Texture2DArray, u32)>,\n\n depth_texture: Option<(&DepthTargetTexture2DArray, u32)>,\n\n viewport: Viewport,\n\n write_mask: WriteMask,\n\n) -> ThreeDResult<()> {\n\n if color_texture.is_some() || depth_texture.is_some() {\n\n let fragment_shader_source = if color_texture.is_some() && depth_texture.is_some() {\n\n \"\n\n uniform sampler2DArray colorMap;\n\n uniform sampler2DArray depthMap;\n\n uniform int colorLayer;\n\n uniform int depthLayer;\n\n in vec2 uv;\n\n layout (location = 0) out vec4 color;\n\n void main()\n\n {\n\n color = texture(colorMap, vec3(uv, colorLayer));\n\n gl_FragDepth = texture(depthMap, vec3(uv, depthLayer)).r;\n", "file_path": "src/core/render_target.rs", "rank": 75, "score": 68169.00021739541 }, { "content": "fn calculate_number_of_mip_maps(\n\n mip_map_filter: Option<Interpolation>,\n\n width: u32,\n\n height: u32,\n\n depth: Option<u32>,\n\n) -> u32 {\n\n if mip_map_filter.is_some()\n\n && width == height\n\n && depth.map(|d| d == width).unwrap_or(true)\n\n && width.is_power_of_two()\n\n {\n\n (width as f64).log2() as u32 + 1\n\n } else {\n\n 1\n\n }\n\n}\n\n\n", "file_path": "src/core/texture.rs", "rank": 76, "score": 67188.18308857233 }, { "content": "///\n\n/// Represents a 3D object which can be rendered directly or used in a render call, for example [render_pass].\n\n///\n\npub trait Object: Geometry {\n\n ///\n\n /// Render the object.\n\n /// Use an empty array for the `lights` argument, if the objects does not require lights to be rendered.\n\n /// Must be called in the callback given as input to a [RenderTarget], [ColorTarget] or [DepthTarget] write method.\n\n ///\n\n fn render(&self, camera: &Camera, lights: &[&dyn Light]) -> ThreeDResult<()>;\n\n\n\n ///\n\n /// Returns whether or not this object should be considered transparent.\n\n ///\n\n fn is_transparent(&self) -> bool;\n\n}\n\n\n\nimpl<T: Object + ?Sized> Object for &T {\n\n fn render(&self, camera: &Camera, lights: &[&dyn Light]) -> ThreeDResult<()> {\n\n (*self).render(camera, lights)\n\n }\n\n\n\n fn is_transparent(&self) -> bool {\n", "file_path": "src/renderer/object.rs", "rank": 77, "score": 66222.88863454049 }, { "content": "fn parse_texture<'a>(\n\n loaded: &mut Loaded,\n\n path: &Path,\n\n buffers: &[::gltf::buffer::Data],\n\n gltf_texture: ::gltf::texture::Texture,\n\n) -> ThreeDResult<CpuTexture> {\n\n let gltf_image = gltf_texture.source();\n\n let gltf_source = gltf_image.source();\n\n let tex = match gltf_source {\n\n ::gltf::image::Source::Uri { uri, .. } => loaded.image(path.join(Path::new(uri)))?,\n\n ::gltf::image::Source::View { view, .. } => {\n\n if view.stride() != None {\n\n unimplemented!();\n\n }\n\n let buffer = &buffers[view.buffer().index()];\n\n image_from_bytes(&buffer[view.offset()..view.offset() + view.length()])?\n\n }\n\n };\n\n // TODO: Parse sampling parameters\n\n Ok(tex)\n\n}\n\n\n", "file_path": "src/io/parser/gltf.rs", "rank": 78, "score": 65866.98228756394 }, { "content": "fn parse_tree<'a>(\n\n parent_transform: &Mat4,\n\n node: &::gltf::Node,\n\n loaded: &mut Loaded,\n\n path: &Path,\n\n buffers: &[::gltf::buffer::Data],\n\n cpu_meshes: &mut Vec<CpuMesh>,\n\n cpu_materials: &mut Vec<CpuMaterial>,\n\n) -> ThreeDResult<()> {\n\n let node_transform = parse_transform(node.transform());\n\n if node_transform.determinant() == 0.0 {\n\n return Ok(()); // glTF say that if the scale is all zeroes, the node should be ignored.\n\n }\n\n let transform = parent_transform * node_transform;\n\n\n\n if let Some(mesh) = node.mesh() {\n\n let name: String = mesh\n\n .name()\n\n .map(|s| s.to_string())\n\n .unwrap_or(format!(\"index {}\", mesh.index()));\n", "file_path": "src/io/parser/gltf.rs", "rank": 79, "score": 65866.98228756394 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\nfn base_path() -> PathBuf {\n\n let base_url = web_sys::window()\n\n .unwrap()\n\n .document()\n\n .unwrap()\n\n .url()\n\n .unwrap();\n\n if !base_url.ends_with('/') {\n\n PathBuf::from(base_url).parent().unwrap().to_path_buf()\n\n } else {\n\n PathBuf::from(base_url)\n\n }\n\n}\n", "file_path": "src/io/loader.rs", "rank": 80, "score": 64891.296106188674 }, { "content": "///\n\n/// Represents a 2D object which can be rendered.\n\n///\n\npub trait Object2D: Geometry2D {\n\n ///\n\n /// Render the object.\n\n /// Must be called in the callback given as input to a [RenderTarget], [ColorTarget] or [DepthTarget] write method.\n\n ///\n\n fn render(&self, viewport: Viewport) -> ThreeDResult<()>;\n\n\n\n ///\n\n /// Returns whether or not this object should be considered transparent.\n\n ///\n\n fn is_transparent(&self) -> bool;\n\n}\n\n\n\nimpl<T: Object2D + ?Sized> Object2D for &T {\n\n fn render(&self, viewport: Viewport) -> ThreeDResult<()> {\n\n (*self).render(viewport)\n\n }\n\n\n\n fn is_transparent(&self) -> bool {\n\n (*self).is_transparent()\n", "file_path": "src/renderer/object.rs", "rank": 81, "score": 64292.197747135724 }, { "content": "/// The basic data type used for each channel of each pixel in a texture.\n\npub trait TextureDataType: DataType {}\n\nimpl TextureDataType for u8 {}\n\nimpl TextureDataType for f16 {}\n\nimpl TextureDataType for f32 {}\n\n\n\nimpl<T: TextureDataType + PrimitiveDataType> TextureDataType for Vector2<T> {}\n\nimpl<T: TextureDataType + PrimitiveDataType> TextureDataType for Vector3<T> {}\n\nimpl<T: TextureDataType + PrimitiveDataType> TextureDataType for Vector4<T> {}\n\nimpl<T: TextureDataType + PrimitiveDataType> TextureDataType for [T; 2] {}\n\nimpl<T: TextureDataType + PrimitiveDataType> TextureDataType for [T; 3] {}\n\nimpl<T: TextureDataType + PrimitiveDataType> TextureDataType for [T; 4] {}\n\n\n\nimpl TextureDataType for Color {}\n\nimpl TextureDataType for Quat {}\n\n\n\nimpl<T: TextureDataType + ?Sized> TextureDataType for &T {}\n\n\n\n///\n\n/// The pixel/texel data for a [CpuTexture].\n\n///\n", "file_path": "src/core/texture.rs", "rank": 82, "score": 63396.31546749142 }, { "content": "/// The basic data type used for each element in a [VertexBuffer] or [InstanceBuffer].\n\npub trait BufferDataType: DataType {}\n\nimpl BufferDataType for u8 {}\n\nimpl BufferDataType for u16 {}\n\nimpl BufferDataType for u32 {}\n\nimpl BufferDataType for i8 {}\n\nimpl BufferDataType for i16 {}\n\nimpl BufferDataType for i32 {}\n\nimpl BufferDataType for f16 {}\n\nimpl BufferDataType for f32 {}\n\n\n\nimpl<T: BufferDataType + PrimitiveDataType> BufferDataType for Vector2<T> {}\n\nimpl<T: BufferDataType + PrimitiveDataType> BufferDataType for Vector3<T> {}\n\nimpl<T: BufferDataType + PrimitiveDataType> BufferDataType for Vector4<T> {}\n\nimpl<T: BufferDataType + PrimitiveDataType> BufferDataType for [T; 2] {}\n\nimpl<T: BufferDataType + PrimitiveDataType> BufferDataType for [T; 3] {}\n\nimpl<T: BufferDataType + PrimitiveDataType> BufferDataType for [T; 4] {}\n\n\n\nimpl BufferDataType for Color {}\n\nimpl BufferDataType for Quat {}\n\n\n\nimpl<T: BufferDataType + ?Sized> BufferDataType for &T {}\n\n\n", "file_path": "src/core/buffer.rs", "rank": 83, "score": 63396.24820138682 }, { "content": "///\n\n/// Possible types that can be send as a uniform to a shader (a variable that is uniformly available when processing all vertices and fragments).\n\n///\n\npub trait UniformDataType: DataType {}\n\n\n\nimpl UniformDataType for u8 {}\n\nimpl UniformDataType for u16 {}\n\nimpl UniformDataType for u32 {}\n\nimpl UniformDataType for i8 {}\n\nimpl UniformDataType for i16 {}\n\nimpl UniformDataType for i32 {}\n\nimpl UniformDataType for f16 {}\n\nimpl UniformDataType for f32 {}\n\n\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for Vector2<T> {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for Vector3<T> {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for Vector4<T> {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for [T; 2] {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for [T; 3] {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for [T; 4] {}\n\n\n\nimpl UniformDataType for Color {}\n\nimpl UniformDataType for Quat {}\n\n\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for Matrix2<T> {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for Matrix3<T> {}\n\nimpl<T: UniformDataType + PrimitiveDataType> UniformDataType for Matrix4<T> {}\n\n\n\nimpl<T: UniformDataType + ?Sized> UniformDataType for &T {}\n", "file_path": "src/core/uniform.rs", "rank": 84, "score": 63391.54534315871 }, { "content": "fn wrapping_from(wrapping: Wrapping) -> i32 {\n\n (match wrapping {\n\n Wrapping::Repeat => crate::context::REPEAT,\n\n Wrapping::MirroredRepeat => crate::context::MIRRORED_REPEAT,\n\n Wrapping::ClampToEdge => crate::context::CLAMP_TO_EDGE,\n\n }) as i32\n\n}\n\n\n", "file_path": "src/core/texture.rs", "rank": 85, "score": 61366.72767074632 }, { "content": "fn interpolation_from(interpolation: Interpolation) -> i32 {\n\n (match interpolation {\n\n Interpolation::Nearest => crate::context::NEAREST,\n\n Interpolation::Linear => crate::context::LINEAR,\n\n }) as i32\n\n}\n\n\n", "file_path": "src/core/texture.rs", "rank": 86, "score": 61366.72767074632 }, { "content": "fn is_absolute_url(path: &str) -> bool {\n\n path.find(\"://\").map(|i| i > 0).unwrap_or(false)\n\n || path.find(\"//\").map(|i| i == 0).unwrap_or(false)\n\n}\n\n\n", "file_path": "src/io/loader.rs", "rank": 87, "score": 60429.20673443725 }, { "content": "fn compute_up_direction(direction: Vec3) -> Vec3 {\n\n if vec3(1.0, 0.0, 0.0).dot(direction).abs() > 0.9 {\n\n (vec3(0.0, 1.0, 0.0).cross(direction)).normalize()\n\n } else {\n\n (vec3(1.0, 0.0, 0.0).cross(direction)).normalize()\n\n }\n\n}\n\n\n\npub(crate) fn lighting_model_shader(lighting_model: LightingModel) -> &'static str {\n\n match lighting_model {\n\n LightingModel::Phong => \"#define PHONG\",\n\n LightingModel::Blinn => \"#define BLINN\",\n\n LightingModel::Cook(normal, _) => match normal {\n\n NormalDistributionFunction::Blinn => \"#define COOK\\n#define COOK_BLINN\\n\",\n\n NormalDistributionFunction::Beckmann => \"#define COOK\\n#define COOK_BECKMANN\\n\",\n\n NormalDistributionFunction::TrowbridgeReitzGGX => \"#define COOK\\n#define COOK_GGX\\n\",\n\n },\n\n }\n\n}\n", "file_path": "src/renderer/light.rs", "rank": 88, "score": 60429.20673443725 }, { "content": "fn check_data_length<T: TextureDataType>(\n\n width: u32,\n\n height: u32,\n\n depth: u32,\n\n data_byte_size: usize,\n\n data: &[T],\n\n) -> ThreeDResult<()> {\n\n let expected_bytes = width as usize * height as usize * depth as usize * data_byte_size;\n\n let actual_bytes = data.len() * std::mem::size_of::<T>();\n\n if expected_bytes != actual_bytes {\n\n Err(CoreError::InvalidTextureLength(\n\n actual_bytes,\n\n expected_bytes,\n\n ))?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/core/texture.rs", "rank": 89, "score": 60282.83194102772 }, { "content": "fn format_from_data_type<T: DataType>() -> u32 {\n\n match T::size() {\n\n 1 => crate::context::RED,\n\n 2 => crate::context::RG,\n\n 3 => crate::context::RGB,\n\n 4 => crate::context::RGBA,\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/core.rs", "rank": 90, "score": 59532.17706498594 }, { "content": "fn is_transparent(cpu_material: &CpuMaterial) -> bool {\n\n cpu_material.albedo.a != 255\n\n || cpu_material\n\n .albedo_texture\n\n .as_ref()\n\n .map(|t| match &t.data {\n\n TextureData::RgbaU8(data) => data.iter().any(|d| d[3] != 255),\n\n TextureData::RgbaF16(data) => data.iter().any(|d| d[3] < f16::from_f32(0.99)),\n\n TextureData::RgbaF32(data) => data.iter().any(|d| d[3] < 0.99),\n\n _ => false,\n\n })\n\n .unwrap_or(false)\n\n}\n", "file_path": "src/renderer/material.rs", "rank": 91, "score": 59532.17706498594 }, { "content": "fn internal_format_from_depth(format: DepthFormat) -> u32 {\n\n match format {\n\n DepthFormat::Depth16 => crate::context::DEPTH_COMPONENT16,\n\n DepthFormat::Depth24 => crate::context::DEPTH_COMPONENT24,\n\n DepthFormat::Depth32F => crate::context::DEPTH_COMPONENT32F,\n\n }\n\n}\n\n\n", "file_path": "src/core/texture.rs", "rank": 92, "score": 58673.07090307053 }, { "content": "/// The basic data type used for each index in an element buffer.\n\npub trait ElementBufferDataType: data_type::DataType {\n\n ///\n\n /// Converts the index to `u32`.\n\n ///\n\n fn as_u32(&self) -> u32;\n\n}\n\nimpl ElementBufferDataType for u8 {\n\n fn as_u32(&self) -> u32 {\n\n *self as u32\n\n }\n\n}\n\nimpl ElementBufferDataType for u16 {\n\n fn as_u32(&self) -> u32 {\n\n *self as u32\n\n }\n\n}\n\nimpl ElementBufferDataType for u32 {\n\n fn as_u32(&self) -> u32 {\n\n *self\n\n }\n", "file_path": "src/core/buffer/element_buffer.rs", "rank": 93, "score": 57646.152627757154 }, { "content": "pub trait PrimitiveDataType: DataType + Copy + Default {\n\n fn send_uniform_with_type(\n\n context: &Context,\n\n location: &UniformLocation,\n\n data: &[Self],\n\n type_: UniformType,\n\n );\n\n fn internal_format_with_size(size: u32) -> u32;\n\n}\n\n\n\nimpl PrimitiveDataType for u8 {\n\n fn internal_format_with_size(size: u32) -> u32 {\n\n match size {\n\n 1 => crate::context::R8,\n\n 2 => crate::context::RG8,\n\n 3 => crate::context::RGB8,\n\n 4 => crate::context::RGBA8,\n\n _ => unreachable!(),\n\n }\n\n }\n", "file_path": "src/core/data_type.rs", "rank": 94, "score": 57619.98836827876 }, { "content": "fn map_modifiers(modifiers: &Modifiers) -> egui::Modifiers {\n\n egui::Modifiers {\n\n alt: modifiers.alt,\n\n ctrl: modifiers.ctrl,\n\n shift: modifiers.shift,\n\n command: modifiers.command,\n\n mac_cmd: cfg!(target_os = \"macos\") && modifiers.command,\n\n }\n\n}\n", "file_path": "src/gui/egui_gui.rs", "rank": 95, "score": 57297.71661333363 }, { "content": "pub trait DataType: std::fmt::Debug + Clone {\n\n fn internal_format() -> u32;\n\n fn data_type() -> u32;\n\n fn size() -> u32;\n\n fn send_uniform(context: &Context, location: &UniformLocation, data: &[Self]);\n\n}\n\n\n\nimpl<T: DataType + ?Sized> DataType for &T {\n\n fn internal_format() -> u32 {\n\n T::internal_format()\n\n }\n\n fn data_type() -> u32 {\n\n T::data_type()\n\n }\n\n fn size() -> u32 {\n\n T::size()\n\n }\n\n\n\n fn send_uniform(context: &Context, location: &UniformLocation, data: &[Self]) {\n\n T::send_uniform(\n", "file_path": "src/core/data_type.rs", "rank": 96, "score": 57103.71570140321 }, { "content": "fn get_sprite_transform(aabb: AxisAlignedBoundingBox) -> Mat4 {\n\n if aabb.is_empty() {\n\n Mat4::identity()\n\n } else {\n\n let (min, max) = (aabb.min(), aabb.max());\n\n let width = f32::sqrt(f32::powi(max.x - min.x, 2) + f32::powi(max.z - min.z, 2));\n\n let height = max.y - min.y;\n\n let center = 0.5 * min + 0.5 * max;\n\n Mat4::from_translation(center) * Mat4::from_nonuniform_scale(0.5 * width, 0.5 * height, 0.0)\n\n }\n\n}\n\n\n\nimpl Geometry for Imposters {\n\n fn render_with_material(\n\n &self,\n\n material: &dyn Material,\n\n camera: &Camera,\n\n lights: &[&dyn Light],\n\n ) -> ThreeDResult<()> {\n\n self.sprites.render_with_material(material, camera, lights)\n", "file_path": "src/renderer/object/imposters.rs", "rank": 97, "score": 56300.678357500554 }, { "content": "fn parse_transform(transform: gltf::scene::Transform) -> Mat4 {\n\n let [c0, c1, c2, c3] = transform.matrix();\n\n Mat4::from_cols(c0.into(), c1.into(), c2.into(), c3.into())\n\n}\n", "file_path": "src/io/parser/gltf.rs", "rank": 98, "score": 55285.50604004221 } ]
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},\n\n std::io::{Read, Write},\n\n };\n\n\n\n macro impl_fn {\n\n (read, $typ:ident, $read:ident, $value:expr) => {\n\n pub fn $read<R: Read>(reader: &mut R) -> Result<$typ, Error> {\n\n io::assert_byte(reader, Value::STRING)?;\n\n\n", "file_path": "aloene/src/io.rs", "rank": 5, "score": 182502.97030609567 }, { "content": "pub fn command(arg: &str) -> Command {\n\n let shell = if cfg!(target_os = \"windows\") {\n\n \"cmd\"\n\n } else {\n\n \"sh\"\n\n };\n\n\n\n let mut cmd = Command::new(shell);\n\n\n\n if cfg!(target_os = \"windows\") {\n\n cmd.args(&[\"/C\", arg]);\n\n } else {\n\n cmd.args(&[arg]);\n\n }\n\n\n\n cmd\n\n}\n\n\n\npub struct FileIter(fs::ReadDir);\n\n\n", "file_path": "varela/common/src/utils.rs", "rank": 7, "score": 169912.9670685036 }, { "content": "pub fn derive(enum_name: syn::Ident, data_enum: syn::DataEnum) -> proc_macro2::TokenStream {\n\n let fn_variant_names = enum_variant_name(&enum_name, &data_enum);\n\n\n\n let variants = data_enum\n\n .variants\n\n .iter()\n\n .map(|variant| variant.ident.to_string());\n\n\n\n let de_match = data_enum.variants.iter().map(de_variant);\n\n let se_match = data_enum.variants.iter().map(se_variant);\n\n\n\n quote::quote! {\n\n impl ::aloene::Aloene for #enum_name {\n\n fn deserialize<R: ::std::io::Read>(reader: &mut R) -> ::std::result::Result<Self, ::aloene::Error> {\n\n ::aloene::io::assert_byte(reader, ::aloene::bytes::Container::VARIANT)?;\n\n\n\n ::aloene::io::assert_byte(reader, ::aloene::bytes::Value::STRING)?;\n\n\n\n let variant = ::aloene::io::read_string(reader)?;\n\n\n", "file_path": "aloene/macros/src/enumeration.rs", "rank": 9, "score": 158313.18320296874 }, { "content": "#[inline(never)]\n\npub fn run(mut args: common::Args) -> Result<()> {\n\n // let stop = Arc::new(AtomicBool::new(false));\n\n\n\n // ctrlc::set_handler({\n\n // let stop = Arc::clone(&stop);\n\n\n\n // move || {\n\n // stop.store(true, Ordering::SeqCst);\n\n // }\n\n // })?;\n\n\n\n if args.peek().map(|a| a == \"--help\").unwrap_or_default() {\n\n println!(\"Usage:\");\n\n println!(\" varela serve <ARGS>\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Arguments:\");\n\n println!(\" host sets the server's bound IP address [default: 0.0.0.0]\");\n", "file_path": "varela/command/serve/src/lib.rs", "rank": 10, "score": 154067.31860598078 }, { "content": "pub fn run(mut args: common::Args) -> Result<()> {\n\n match args.next().as_deref() {\n\n Some(\"--help\") => {\n\n println!(\"Usage:\");\n\n println!(\" varela config <COMMAND> [<ARGS>]\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Commands:\");\n\n println!(\" get get and prints a configuration key\");\n\n println!(\" set set a configuration key\");\n\n println!(\" push add a entry onto a configuration list key\");\n\n println!(\" pop remove an entry onto a configuration list key\");\n\n }\n\n Some(\"get\") => {\n\n run_get(args)?;\n\n }\n\n Some(\"set\") => {\n\n run_set(args)?;\n", "file_path": "varela/command/config/src/lib.rs", "rank": 11, "score": 154062.8565174773 }, { "content": "pub fn write_length<W: Write>(writer: &mut W, mut length: usize) -> Result<(), Error> {\n\n loop {\n\n let write = (length & 0x7F) as u8;\n\n\n\n length >>= 7;\n\n\n\n if length == 0 {\n\n write_u8(writer, write)?;\n\n\n\n return Ok(());\n\n } else {\n\n write_u8(writer, write | 0x80)?;\n\n }\n\n }\n\n}\n\n\n", "file_path": "aloene/src/io.rs", "rank": 12, "score": 150854.626272115 }, { "content": "pub fn search(database: &Database, text: &str) -> Vec<Id> {\n\n let bounds = parse(text);\n\n\n\n let mut stories = Vec::new();\n\n\n\n let mut bounds_iter = bounds.into_iter();\n\n\n\n if let Some(bound) = bounds_iter.next() {\n\n let story_iter = database.index().stories.iter();\n\n\n\n let (include, iter) = match bound {\n\n Bound::Author { include, text } => (\n\n include,\n\n help!(bound; database, story_iter, text, Author, authors),\n\n ),\n\n Bound::Origin { include, text } => (\n\n include,\n\n help!(bound; database, story_iter, text, Origin, origins),\n\n ),\n\n Bound::Pairing { include, text } => (\n", "file_path": "varela/command/serve/src/search.rs", "rank": 13, "score": 148646.0245404187 }, { "content": "pub fn parse_html(text: &str) -> Result<(ParsedInfo, ParsedMeta, ParsedChapters)> {\n\n let doc = Document::try_from(text)?;\n\n\n\n let info = html::parse_info(&doc);\n\n let meta = html::parse_meta(&doc);\n\n let chapters = html::parse_chapters(&doc)?;\n\n\n\n Ok((info, meta, chapters))\n\n}\n", "file_path": "varela/format/ao3/src/lib.rs", "rank": 17, "score": 140893.96711544087 }, { "content": "pub fn read_string<R: Read>(reader: &mut R) -> Result<String, Error> {\n\n let length = read_length(reader)?;\n\n\n\n let mut buffer = Vec::with_capacity(length);\n\n\n\n for _ in 0..length {\n\n buffer.push(read_u8(reader)?);\n\n }\n\n\n\n Ok(String::from_utf8(buffer)?)\n\n}\n\n\n", "file_path": "aloene/src/io.rs", "rank": 18, "score": 140509.85372330312 }, { "content": "pub fn read_length<R: Read>(reader: &mut R) -> Result<usize, Error> {\n\n let mut number: u64 = 0;\n\n let mut count = 0;\n\n\n\n loop {\n\n let byte = read_u8(reader)?;\n\n\n\n number |= ((byte & 0x7F) as u64) << (7 * count);\n\n\n\n if byte & 0x80 == 0 {\n\n return Ok(number as usize);\n\n }\n\n\n\n count += 1;\n\n }\n\n}\n\n\n", "file_path": "aloene/src/io.rs", "rank": 19, "score": 140509.85372330312 }, { "content": "enum BoundIter<I, A, O, P, C, G>\n\nwhere\n\n A: Iterator<Item = I>,\n\n O: Iterator<Item = I>,\n\n P: Iterator<Item = I>,\n\n C: Iterator<Item = I>,\n\n G: Iterator<Item = I>,\n\n{\n\n Author(A),\n\n Origin(O),\n\n Pairing(P),\n\n Character(C),\n\n General(G),\n\n}\n\n\n\nimpl<I, A, O, P, C, G> Iterator for BoundIter<I, A, O, P, C, G>\n\nwhere\n\n A: Iterator<Item = I>,\n\n O: Iterator<Item = I>,\n\n P: Iterator<Item = I>,\n", "file_path": "varela/command/serve/src/search.rs", "rank": 20, "score": 140059.50517922908 }, { "content": "pub fn style(header: web::OptionalHeader<\"If-None-Match\">) -> HttpResponse {\n\n utils::wrap(|| {\n\n static CSS: &str = include_str!(\"../../assets/dist/index.css\");\n\n // RELEASE: change anytime theres a release and the style gets updated\n\n static CSS_TAG: &str = \"f621e1d55cbee8397c906c7d72d0fb9a4520a06be6218abeccff1ffcf75f00b3\";\n\n\n\n let mut res = HttpResponse::ok().header(CONTENT_TYPE, \"text/css; charset=utf-8\");\n\n\n\n if !cfg!(debug_assertions) {\n\n res = res\n\n .header(CACHE_CONTROL, \"public; max-age=31536000\")\n\n .header(ETAG, CSS_TAG);\n\n }\n\n\n\n if let Some(header) = header.as_deref() {\n\n if header == CSS_TAG {\n\n return Ok(res.status(http::StatusCode(304)).finish());\n\n }\n\n }\n\n\n\n Ok(res.body(CSS))\n\n })\n\n}\n", "file_path": "varela/command/serve/src/handlers/mod.rs", "rank": 21, "score": 139796.33136618434 }, { "content": "#[proc_macro_derive(Aloene, attributes(aloene))]\n\npub fn aloene_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let derive = syn::parse_macro_input!(input as syn::DeriveInput);\n\n\n\n let stream = match derive.data {\n\n syn::Data::Enum(data_enum) => enumeration::derive(derive.ident, data_enum),\n\n syn::Data::Struct(data_struct) => {\n\n structure::derive(derive.ident, data_struct, derive.generics)\n\n }\n\n _ => {\n\n syn_err!(derive, \"Aloene can not be used on `union`s\")\n\n }\n\n };\n\n\n\n if false {\n\n eprintln!(\"{}\", stream.to_string())\n\n }\n\n\n\n proc_macro::TokenStream::from(stream)\n\n}\n", "file_path": "aloene/macros/src/lib.rs", "rank": 22, "score": 136227.34118741908 }, { "content": "#[proc_macro_derive(Template, attributes(template))]\n\npub fn template_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let derive = syn::parse_macro_input!(input as syn::DeriveInput);\n\n\n\n let root_dir = match std::env::var(\"CARGO_MANIFEST_DIR\") {\n\n Ok(dir) => std::path::PathBuf::from(dir),\n\n Err(err) => {\n\n return proc_macro::TokenStream::from(\n\n syn::Error::new_spanned(derive, err).to_compile_error(),\n\n )\n\n }\n\n };\n\n\n\n let path = derive\n\n .attrs\n\n .iter()\n\n .find(|attr| attr.path.is_ident(\"template\"))\n\n .map(|attr| attr.parse_args::<Pair>())\n\n .transpose();\n\n\n\n let path = match path {\n", "file_path": "opal/macros/src/lib.rs", "rank": 23, "score": 136227.34118741908 }, { "content": "fn write_render(tokens: &[Stage4]) -> Result<proc_macro2::TokenStream, proc_macro2::LexError> {\n\n let mut stream = quote::quote! {};\n\n\n\n for token in tokens {\n\n match token {\n\n Stage4::Expr(expr) => {\n\n let expr = proc_macro2::TokenStream::from_str(\n\n &expr.replace('{', \"{{\").replace('}', \"}}\"),\n\n )?;\n\n\n\n stream = quote::quote! {\n\n #stream\n\n\n\n write!(writer, \"{}\", #expr)?;\n\n };\n\n }\n\n Stage4::ExprAssign(expr) => {\n\n let expr = proc_macro2::TokenStream::from_str(expr.trim())?;\n\n\n\n stream = quote::quote! {\n", "file_path": "opal/macros/src/lib.rs", "rank": 24, "score": 133258.6208536078 }, { "content": "fn write_size_hint(tokens: &[Stage4]) -> Result<proc_macro2::TokenStream, proc_macro2::LexError> {\n\n let mut stream = quote::quote! {};\n\n\n\n for token in tokens {\n\n match token {\n\n Stage4::Expr(expr) => {\n\n if expr.trim() == \"count\" {\n\n continue;\n\n }\n\n\n\n if !(expr.contains('+') || expr.contains('-') || expr.contains(\"len\")) {\n\n let v = proc_macro2::TokenStream::from_str(expr.trim())?;\n\n\n\n stream = quote::quote! {\n\n #stream\n\n\n\n hint += #v.len();\n\n };\n\n }\n\n }\n", "file_path": "opal/macros/src/lib.rs", "rank": 25, "score": 131548.16770055675 }, { "content": "pub fn de_field(field: &syn::Field) -> proc_macro2::TokenStream {\n\n let (field_name, ident) = match field_help(field) {\n\n Ok(pair) => pair,\n\n Err(err) => return err,\n\n };\n\n\n\n let typ = BUILTIN_TYPES.iter().find(|typ| ident == **typ);\n\n\n\n if let Some(typ) = typ {\n\n let function = quote::format_ident!(\"read_{}\", typ);\n\n\n\n quote::quote! {\n\n let #field_name = ::aloene::io::structure::#function(reader)?;\n\n }\n\n } else {\n\n quote::quote! {\n\n ::aloene::io::assert_byte(reader, ::aloene::bytes::Value::STRING)?;\n\n\n\n let _field = ::aloene::io::read_string(reader)?;\n\n\n\n ::aloene::io::assert_byte(reader, ::aloene::bytes::Container::VALUE)?;\n\n let #field_name = ::aloene::Aloene::deserialize(reader)?;\n\n }\n\n }\n\n}\n\n\n", "file_path": "aloene/macros/src/structure.rs", "rank": 26, "score": 129623.22084472592 }, { "content": "pub fn derive(\n\n struct_name: syn::Ident,\n\n data_struct: syn::DataStruct,\n\n generics: syn::Generics,\n\n) -> proc_macro2::TokenStream {\n\n let field_iter = data_struct.fields.iter().map(|field| {\n\n let ident = field.ident.as_ref().unwrap();\n\n\n\n quote::quote! { #ident }\n\n });\n\n\n\n let de_iter = data_struct.fields.iter().map(de_field);\n\n let se_iter = data_struct.fields.iter().map(se_field);\n\n\n\n let syn::Generics {\n\n lt_token,\n\n params,\n\n gt_token,\n\n where_clause,\n\n } = generics;\n", "file_path": "aloene/macros/src/structure.rs", "rank": 27, "score": 129528.6678688825 }, { "content": "#[proc_macro_attribute]\n\npub fn selector(\n\n _: proc_macro::TokenStream,\n\n input: proc_macro::TokenStream,\n\n) -> proc_macro::TokenStream {\n\n let mut dec = syn::parse_macro_input!(input as ItemStatic);\n\n\n\n let raw_selector = {\n\n let expr_lit = if let Expr::Lit(expr_lit) = &*dec.expr {\n\n expr_lit\n\n } else {\n\n return syn_err!(dec.expr, \"Selector can only be a string literal\");\n\n };\n\n\n\n let lit_str = if let Lit::Str(lit_str) = &expr_lit.lit {\n\n lit_str\n\n } else {\n\n return syn_err!(dec.expr, \"Selector can only be a string literal\");\n\n };\n\n\n\n Selector::from(lit_str.value())\n", "file_path": "query/macros/src/lib.rs", "rank": 28, "score": 129528.6678688825 }, { "content": "pub fn assert_byte<R: std::io::Read>(reader: &mut R, expected: u8) -> Result<(), Error> {\n\n let got = read_u8(reader)?;\n\n\n\n if got != expected {\n\n return Err(Error::InvalidByte { expected, got });\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "aloene/src/io.rs", "rank": 29, "score": 128063.08853978911 }, { "content": "pub fn story(\n\n db: web::Data<Database>,\n\n id: web::ParseParam<\"id\", Id>,\n\n index: web::Param<\"chapter\">,\n\n) -> HttpResponse {\n\n utils::wrap(|| {\n\n let index: usize = index.parse().map_err(anyhow::Error::from)?;\n\n\n\n let story = utils::get_story_full(&*db, &id)?;\n\n let chapter = db.get_chapter_body(&id, index)?;\n\n\n\n let body = Layout::new(\n\n Width::Slim,\n\n db.settings().theme,\n\n story.info.title.clone(),\n\n None,\n\n pages::Chapter::new(\n\n partials::StoryPartial::new(&id, story, None)?,\n\n &chapter,\n\n index,\n\n ),\n\n );\n\n\n\n Ok(crate::res!(200; body))\n\n })\n\n}\n", "file_path": "varela/command/serve/src/handlers/story.rs", "rank": 30, "score": 125777.63056932413 }, { "content": "pub fn catalog(\n\n db: web::Data<Database>,\n\n ext: web::ParseParam<\"ext\", CatalogFormat>,\n\n) -> HttpResponse {\n\n utils::wrap(|| {\n\n let mut stories = db\n\n .index()\n\n .stories\n\n .iter()\n\n .filter(|(_, s)| s.info.kind == FileKind::Epub)\n\n .map(|(id, _)| {\n\n utils::get_story_full(&db, id).map(|story| Existing::new(id.clone(), story))\n\n })\n\n .collect::<Result<Vec<_>>>()?;\n\n\n\n stories.sort_by(|a, b| a.info.updated.cmp(&b.info.updated));\n\n\n\n let updated = stories\n\n .first()\n\n .map(|story| story.info.updated.clone())\n\n .unwrap_or_else(|| humantime::format_rfc3339(std::time::SystemTime::now()).to_string());\n\n\n\n Ok(HttpResponse::ok()\n\n .header(CONTENT_TYPE, \"application/atom+xml\")\n\n .body(::opal::Template::render_into_string(OpdsFeed::new(\n\n updated, stories,\n\n ))?))\n\n })\n\n}\n", "file_path": "varela/command/serve/src/handlers/opds.rs", "rank": 31, "score": 125777.63056932413 }, { "content": "pub fn search(\n\n db: web::Data<Database>,\n\n search: web::Query<\"search\">,\n\n query: web::RawQuery,\n\n) -> HttpResponse {\n\n utils::wrap(|| {\n\n let ids = search::search(&*db, &search);\n\n\n\n let query = rebuild_query(&query);\n\n\n\n let mut stories = ids\n\n .iter()\n\n .map(|id| {\n\n utils::get_story_full(&*db, id)\n\n .and_then(|story| partials::StoryPartial::new(id, story, Some(query.clone())))\n\n })\n\n .collect::<Result<Vec<_>>>()?;\n\n\n\n stories.sort_by(|a, b| a.title().cmp(b.title()));\n\n\n", "file_path": "varela/command/serve/src/handlers/search.rs", "rank": 32, "score": 125777.63056932413 }, { "content": "pub fn init() -> Result<()> {\n\n let bypass = env::var(\"VARELA_LOG_ALL\").is_ok();\n\n let level = if bypass {\n\n LevelFilter::Trace\n\n } else {\n\n LevelFilter::Info\n\n };\n\n\n\n log::set_boxed_logger(Box::new(Logger {\n\n bypass,\n\n out: io::stdout(),\n\n level,\n\n }))?;\n\n log::set_max_level(level);\n\n\n\n Ok(())\n\n}\n\n\n\npub struct Logger {\n\n bypass: bool,\n", "file_path": "varela/common/src/logger.rs", "rank": 33, "score": 122874.9187386584 }, { "content": "pub fn new_id() -> Id {\n\n static ALPHABET: [char; LEN] = [\n\n '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n\n 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',\n\n 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n\n ];\n\n\n\n let mut id = String::new();\n\n\n\n loop {\n\n fastrand::seed({\n\n let mut buf = [0; std::mem::size_of::<u64>()];\n\n\n\n let _ = getrandom::getrandom(&mut buf);\n\n\n\n u64::from_le_bytes(buf)\n\n });\n\n\n\n let mut bytes = [0_u8; STEP];\n\n\n", "file_path": "varela/common/src/utils.rs", "rank": 34, "score": 121048.52453591308 }, { "content": "pub fn search_v2<'s>(\n\n query: &[(Cow<'s, str>, Cow<'s, str>)],\n\n stories: &mut Vec<(&'s Id, &'s Story)>,\n\n) -> Stats<'s> {\n\n // modified version of [`Iterator::partition`] to remove [`Default`] bounds\n\n #[inline]\n\n fn partition<I, B, F>(iter: I, f: F) -> (Vec<B>, Vec<B>)\n\n where\n\n I: Iterator<Item = B>,\n\n F: FnMut(&I::Item) -> bool,\n\n {\n\n #[inline]\n\n fn extend<'a, T, B: Extend<T>>(\n\n mut f: impl FnMut(&T) -> bool + 'a,\n\n left: &'a mut B,\n\n right: &'a mut B,\n\n ) -> impl FnMut((), T) + 'a {\n\n move |(), x| {\n\n if f(&x) {\n\n left.extend(Some(x));\n", "file_path": "varela/command/serve/src/search.rs", "rank": 35, "score": 121048.52453591308 }, { "content": "pub fn favicon() -> HttpResponse {\n\n HttpResponse::ok()\n\n .header(CONTENT_TYPE, \"image/x-icon\")\n\n .body(Vec::from(\n\n &include_bytes!(\"../../../../assets/noel.ico\")[..],\n\n ))\n\n}\n", "file_path": "varela/command/serve/src/handlers/index.rs", "rank": 36, "score": 117661.85198538724 }, { "content": "fn enum_variant_name(ident: &syn::Ident, data_enum: &syn::DataEnum) -> proc_macro2::TokenStream {\n\n let variant_idents = data_enum.variants.iter().map(|variant| &variant.ident);\n\n let variant_kind_idents = data_enum.variants.iter().map(|variant| &variant.ident);\n\n\n\n let variant_kind = data_enum\n\n .variants\n\n .iter()\n\n .map(|variant| match &variant.fields {\n\n syn::Fields::Named(_) => quote::quote! { { .. } },\n\n syn::Fields::Unnamed(unnamed) => {\n\n let fields = unnamed.unnamed.len();\n\n\n\n let blanks = (0..fields).map(|_| quote::quote! { _ });\n\n\n\n quote::quote! { ( #( #blanks ),* ) }\n\n }\n\n syn::Fields::Unit => quote::quote! {},\n\n });\n\n\n\n quote::quote! {\n\n fn get_name(enumeration: &#ident) -> &'static str {\n\n match enumeration {\n\n #( #ident::#variant_kind_idents #variant_kind => stringify!(#variant_idents), )*\n\n }\n\n }\n\n }\n\n}\n", "file_path": "aloene/macros/src/enumeration.rs", "rank": 37, "score": 115220.79876638178 }, { "content": "#[allow(clippy::needless_collect)] // clippy doesn't detect that the keys are being removed\n\n#[inline(never)]\n\npub fn run(_args: common::Args) -> Result<()> {\n\n debug!(\"building index\");\n\n\n\n let mut database = Database::open()?;\n\n\n\n let mut known_ids = Vec::new();\n\n\n\n debug!(\n\n \"checking `{}` for files\",\n\n database.data_path.display().bright_purple()\n\n );\n\n\n\n for entry in FileIter::new(fs::read_dir(&database.data_path)?) {\n\n handle_entry(&mut database, &mut known_ids, entry?)?;\n\n }\n\n\n\n let index = database.index_mut();\n\n\n\n let index_keys = index.stories.keys().cloned().collect::<Vec<_>>();\n\n\n", "file_path": "varela/command/index/src/lib.rs", "rank": 38, "score": 105726.4958710095 }, { "content": "#[inline(never)]\n\nfn run_pop(mut args: common::Args) -> Result<()> {\n\n let mut database = Database::open()?;\n\n let settings = database.settings_mut();\n\n\n\n if args.peek().map(|a| a == \"--help\").unwrap_or_default() {\n\n println!(\"Usage:\");\n\n println!(\" varela config pop <KEY>\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Arguments:\");\n\n println!(\" key the list item to remove\");\n\n\n\n return Ok(());\n\n }\n\n\n\n let key = args\n\n .next()\n\n .ok_or_else(|| anyhow::anyhow!(\"`config pop` is missing `key` value\"))?;\n", "file_path": "varela/command/config/src/lib.rs", "rank": 39, "score": 105138.40465246487 }, { "content": "#[inline(never)]\n\nfn run_get(mut args: common::Args) -> Result<()> {\n\n let database = Database::open()?;\n\n let settings = database.settings();\n\n\n\n if args.peek().map(|a| a == \"--help\").unwrap_or_default() {\n\n println!(\"Usage:\");\n\n println!(\" varela config get <KEY>\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Arguments:\");\n\n println!(\" key the key to get\");\n\n\n\n return Ok(());\n\n }\n\n\n\n let key = args\n\n .next()\n\n .ok_or_else(|| anyhow::anyhow!(\"`config get` is missing `key` value\"))?;\n", "file_path": "varela/command/config/src/lib.rs", "rank": 40, "score": 105138.40465246487 }, { "content": "#[inline(never)]\n\nfn run_set(mut args: common::Args) -> Result<()> {\n\n let mut database = Database::open()?;\n\n\n\n if args.peek().map(|a| a == \"--help\").unwrap_or_default() {\n\n println!(\"Usage:\");\n\n println!(\" varela config set <KEY> <VALUE>\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Arguments:\");\n\n println!(\" key the key to set\");\n\n println!(\" value the value to set the key to\");\n\n\n\n return Ok(());\n\n }\n\n\n\n let key = args\n\n .next()\n\n .ok_or_else(|| anyhow::anyhow!(\"`config set` is missing `key` value\"))?;\n", "file_path": "varela/command/config/src/lib.rs", "rank": 41, "score": 105138.40465246487 }, { "content": "#[inline(never)]\n\nfn run_push(mut args: common::Args) -> Result<()> {\n\n let mut database = Database::open()?;\n\n let settings = database.settings_mut();\n\n\n\n if args.peek().map(|a| a == \"--help\").unwrap_or_default() {\n\n println!(\"Usage:\");\n\n println!(\" varela config push <KEY> <VALUE>\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Arguments:\");\n\n println!(\" key the list to add to\");\n\n println!(\" value the value to add to the list\");\n\n\n\n return Ok(());\n\n }\n\n\n\n let key = args\n\n .next()\n", "file_path": "varela/command/config/src/lib.rs", "rank": 42, "score": 105138.40465246487 }, { "content": "fn handle_entry(db: &mut Database, known_ids: &mut Vec<Id>, entry: DirEntry) -> Result<()> {\n\n let path = entry.path();\n\n let ext = path.extension().and_then(OsStr::to_str);\n\n\n\n let name = path\n\n .file_name()\n\n .and_then(OsStr::to_str)\n\n .ok_or_else(|| anyhow!(\"File `{}` does not have a file name\", path.display()))?;\n\n\n\n let file_kind = match ext {\n\n // Some(\"epub\") => Some(FileKind::Epub),\n\n Some(\"epub\") => return Ok(()),\n\n Some(\"html\") => Some(FileKind::Html),\n\n _ => None,\n\n };\n\n\n\n if let Some(kind) = file_kind {\n\n let details = handle_file(db, known_ids, &path, name)\n\n .with_context(|| format!(\"While reading file {}\", name))?;\n\n\n", "file_path": "varela/command/index/src/lib.rs", "rank": 43, "score": 104995.87837638153 }, { "content": "pub fn parse_info(doc: &Document<'_>) -> ParsedInfo {\n\n #[query::selector]\n\n static META_TITLE: &str = \"html > body > #preface > .meta > h1\";\n\n\n\n /// Selects the `byline` to get the story authors\n\n #[query::selector]\n\n static META_BYLINE: &str = \"html > body > #preface > .meta > .byline > a[rel=author]\";\n\n\n\n /// Selects the stories summary and notes\n\n #[query::selector]\n\n static META_SUMMARY: &str = \"html > body > #preface > .meta > blockquote.userstuff\";\n\n\n\n let title = doc\n\n .select(&META_TITLE)\n\n .and_then(Node::into_text)\n\n .unwrap_or(\"\")\n\n .to_string();\n\n\n\n let summary = doc\n\n .select(&META_SUMMARY)\n", "file_path": "varela/format/ao3/src/html.rs", "rank": 44, "score": 104222.66220909765 }, { "content": "pub fn parse_meta(doc: &Document<'_>) -> ParsedMeta {\n\n #[query::selector]\n\n static META_TAGS_DT: &str = \"html > body > #preface > .meta > .tags > dt\";\n\n\n\n #[query::selector]\n\n static META_TAGS_DF: &str = \"html > body > #preface > .meta > .tags > dd\";\n\n\n\n let detail_names = doc.select_all(&META_TAGS_DT);\n\n let detail_definitions = doc.select_all(&META_TAGS_DF);\n\n\n\n let mut rating = Rating::Unknown;\n\n\n\n let mut categories = Vec::new();\n\n\n\n let mut origins = Vec::new();\n\n\n\n let mut warnings = Vec::new();\n\n let mut pairings = Vec::new();\n\n let mut characters = Vec::new();\n\n let mut generals = Vec::new();\n", "file_path": "varela/format/ao3/src/html.rs", "rank": 45, "score": 104222.66220909765 }, { "content": "pub fn wrap<F>(fun: F) -> HttpResponse\n\nwhere\n\n F: FnOnce() -> Result<HttpResponse>,\n\n{\n\n match fun() {\n\n Ok(res) => res,\n\n Err(err) => {\n\n error!(\"handler error: {}\", err);\n\n\n\n HttpResponse::internal_server_error().finish()\n\n }\n\n }\n\n}\n\n\n\npub mod http {\n\n use {\n\n common::prelude::*,\n\n std::{fs, path::Path},\n\n };\n\n\n", "file_path": "varela/command/serve/src/utils.rs", "rank": 46, "score": 104222.66220909765 }, { "content": "#[test]\n\nfn test_unit() {\n\n se_de(EnumUnit::Yes);\n\n se_de(EnumUnit::No);\n\n}\n", "file_path": "aloene/tests/se_de_enum.rs", "rank": 47, "score": 102012.8379740194 }, { "content": "pub fn parse_chapters(doc: &Document<'_>) -> Result<ParsedChapters> {\n\n /// Selects the `toc-heading` that is present on single chapter stories\n\n #[query::selector]\n\n static CHAPTERS: &str = \"html > body > #chapters\";\n\n\n\n let chapter_node = doc\n\n .select(&CHAPTERS)\n\n .ok_or_else(|| anyhow!(\"BUG: There this no chapters block\"))?;\n\n\n\n let chapters = match chapter_node.get_child_by_tag(\"h2\") {\n\n Some(title_node) => parse_chapter_single(doc, title_node)\n\n .context(\"Story detected as having a single chapter\")?,\n\n None => parse_chapters_multi(doc, chapter_node)\n\n .context(\"Story detected as having multiple chapters\")?,\n\n };\n\n Ok(ParsedChapters { chapters })\n\n}\n\n\n", "file_path": "varela/format/ao3/src/html.rs", "rank": 48, "score": 100207.04783069756 }, { "content": "pub fn index(db: web::Data<Database>) -> HttpResponse {\n\n utils::wrap(|| {\n\n let mut stories = db\n\n .index()\n\n .stories\n\n .keys()\n\n .map(|id| {\n\n utils::get_story_full(&*db, id)\n\n .and_then(|story| partials::StoryPartial::new(id, story, None))\n\n })\n\n .collect::<Result<Vec<partials::StoryPartial<'_>>>>()?;\n\n\n\n stories.sort_by(|a, b| a.title().cmp(b.title()));\n\n\n\n let body = Layout::new(\n\n Width::Slim,\n\n db.settings().theme,\n\n \"home\",\n\n None,\n\n pages::Index::new(stories),\n\n );\n\n\n\n Ok(crate::res!(200; body))\n\n })\n\n}\n\n\n", "file_path": "varela/command/serve/src/handlers/index.rs", "rank": 49, "score": 98838.31180347697 }, { "content": "pub fn download_get(db: web::Data<Database>) -> HttpResponse {\n\n utils::wrap(|| {\n\n let body = Layout::new(\n\n Width::Slim,\n\n db.settings().theme,\n\n \"downloads\",\n\n None,\n\n pages::Download::new(),\n\n );\n\n\n\n Ok(crate::res!(200; body))\n\n })\n\n}\n\n\n", "file_path": "varela/command/serve/src/handlers/download.rs", "rank": 50, "score": 97528.85545782108 }, { "content": "fn rebuild_query(raw_query: &web::RawQuery) -> Cow<'static, str> {\n\n if raw_query.is_empty() {\n\n Cow::from(String::new())\n\n } else {\n\n let mut parsed = QString::from(raw_query.as_str()).into_pairs();\n\n\n\n parsed.retain(|(k, _)| k != \"search\");\n\n\n\n Cow::from(format!(\"?{}\", QString::new(parsed)))\n\n }\n\n}\n\n\n", "file_path": "varela/command/serve/src/handlers/search.rs", "rank": 51, "score": 97347.42511134889 }, { "content": "#[allow(clippy::ptr_arg)]\n\npub fn get_story_full(db: &Database, id: &Id) -> Result<ResolvedStory> {\n\n if let Some(story) = STORY_CACHE\n\n .read()\n\n .map_err(|err| anyhow!(\"unable to get lock on cache: {}\", err))?\n\n .get(id)\n\n .cloned()\n\n {\n\n return Ok(story);\n\n }\n\n\n\n enum Kind {\n\n Categories,\n\n Authors,\n\n Origins,\n\n Warnings,\n\n Pairings,\n\n Characters,\n\n Generals,\n\n }\n\n\n", "file_path": "varela/command/serve/src/utils.rs", "rank": 52, "score": 93998.04322472379 }, { "content": "fn matcher_to_stmt_tokens(matcher: &Matcher) -> proc_macro2::TokenStream {\n\n let tags = matcher.tag.len();\n\n let classes = matcher.class.len();\n\n let ids = matcher.id.len();\n\n let attributes = matcher.attribute.len();\n\n\n\n quote::quote! {\n\n ::query::compile_time::StaticMatcher<#tags, #classes, #ids, #attributes>\n\n }\n\n}\n\n\n", "file_path": "query/macros/src/lib.rs", "rank": 53, "score": 93828.01193009247 }, { "content": "fn matcher_to_expr_tokens(matcher: &Matcher) -> proc_macro2::TokenStream {\n\n let tags = matcher.tag.iter().map(|i| quote::quote! { #i });\n\n let classes = matcher.class.iter().map(|i| quote::quote! { #i });\n\n let ids = matcher.id.iter().map(|i| quote::quote! { #i });\n\n\n\n let attributes = matcher.attribute.iter().map(|(key, value)| {\n\n let value = match value {\n\n AttributeSpec::Present => {\n\n quote::quote! { ::query::compile_time::StaticAttributeSpec::Present }\n\n }\n\n AttributeSpec::Exact(t) => {\n\n quote::quote! { ::query::compile_time::StaticAttributeSpec::Exact(#t) }\n\n }\n\n AttributeSpec::Starts(t) => {\n\n quote::quote! { ::query::compile_time::StaticAttributeSpec::Starts(#t) }\n\n }\n\n AttributeSpec::Ends(t) => {\n\n quote::quote! { ::query::compile_time::StaticAttributeSpec::Ends(#t) }\n\n }\n\n AttributeSpec::Contains(t) => {\n", "file_path": "query/macros/src/lib.rs", "rank": 54, "score": 93828.01193009247 }, { "content": "pub fn parse_epub(path: &Path) -> Result<(ParsedInfo, ParsedMeta, ParsedChapters)> {\n\n todo!()\n\n}\n\n\n", "file_path": "varela/format/ao3/src/lib.rs", "rank": 55, "score": 92796.15081922131 }, { "content": "pub fn percent_encode<B: AsRef<[u8]>>(bytes: B) -> PercentEncode<B> {\n\n PercentEncode(bytes)\n\n}\n\n\n\npub struct PercentEncode<B>(B);\n\n\n\nimpl<B: AsRef<[u8]>> Template for PercentEncode<B> {\n\n fn render<W>(&self, writer: &mut W) -> io::Result<()>\n\n where\n\n W: Write,\n\n {\n\n write!(\n\n writer,\n\n \"{}\",\n\n percent_encoding::percent_encode(self.0.as_ref(), percent_encoding::CONTROLS)\n\n )?;\n\n\n\n Ok(())\n\n }\n\n\n\n fn size_hint(&self) -> usize {\n\n let len = self.0.as_ref().len();\n\n\n\n len + (len / 2)\n\n }\n\n}\n", "file_path": "varela/command/serve/src/filters.rs", "rank": 56, "score": 91976.2641275967 }, { "content": "fn any_by_text(full: &HashMap<Id, Entity>, refs: &[Id], text: &str) -> bool {\n\n refs.iter().map(|id| full.get(id)).any(|a| match a {\n\n Some(entity) => entity.text.to_lowercase() == text.to_lowercase(),\n\n None => false,\n\n })\n\n}\n\n\n\n#[allow(clippy::while_let_on_iterator)]\n\npub(self) fn parse(text: &str) -> Vec<Bound> {\n\n let cleaned = text.trim();\n\n let mut parts = cleaned.split(',').map(str::trim);\n\n\n\n let mut bounds = Vec::with_capacity(parts.size_hint().0);\n\n\n\n while let Some(mut part) = parts.next() {\n\n let included = !part.starts_with('-');\n\n\n\n if !included {\n\n part = part.trim_start_matches('-');\n\n }\n", "file_path": "varela/command/serve/src/search.rs", "rank": 57, "score": 91127.9349010603 }, { "content": "/// This function abstracts the formatting of errors away from the core logic inside parser,\n\n/// so that the file is easier to read.\n\npub fn error_msg<'input>(error: PestError<Rule>) -> Result<super::Dom<'input>> {\n\n let message = error.renamed_rules(|rule| match *rule {\n\n Rule::EOI => \"end of input\".to_string(),\n\n Rule::doctype_html | Rule::doctype_xml => \"doctype element\".to_string(),\n\n Rule::node_text => \"text node\".to_string(),\n\n Rule::node_element => \"element node\".to_string(),\n\n Rule::el_void => \"void element\".to_string(),\n\n Rule::el_void_xml => \"void element with xml ending (/>)\".to_string(),\n\n Rule::el_process_instruct => \"xml processing instruction\".to_string(),\n\n Rule::el_raw_text => \"element with raw text (style or script)\".to_string(),\n\n Rule::el_normal => \"normal element\".to_string(),\n\n Rule::el_dangling => \"\".to_string(),\n\n Rule::attr => \"attribute (key=\\\"value\\\")\".to_string(),\n\n Rule::attr_key => \"attribute key\".to_string(),\n\n Rule::attr_value => \"attribute value\".to_string(),\n\n Rule::el_name => \"element name\".to_string(),\n\n Rule::el_void_name_html => \"void element name\".to_string(),\n\n // TODO: Continue with this\n\n x => format!(\"{:?} \", x),\n\n });\n\n\n\n Err(Error::Parsing(message.to_string()))\n\n}\n", "file_path": "html-parser/src/dom/formatting.rs", "rank": 58, "score": 88967.08585710618 }, { "content": "pub fn download_post(db: web::Data<Database>, body: web::Body) -> HttpResponse {\n\n utils::wrap(|| {\n\n let mut parse = form_urlencoded::parse(&body);\n\n\n\n if let Some((_, url)) = parse.find(|(key, _)| key == \"download\") {\n\n fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {\n\n haystack\n\n .windows(needle.len())\n\n .position(|window| window == needle)\n\n }\n\n\n\n let bytes = utils::http::get(&db.temp_path, &url)?;\n\n\n\n static TARGET_START: &[u8; 7] = b\"<title>\";\n\n static TARGET_END: &[u8; 8] = b\"</title>\";\n\n\n\n let start = find_subsequence(&bytes[..], &TARGET_START[..])\n\n .ok_or_else(|| anyhow!(\"Unable to find start of page title\"))?;\n\n let end = find_subsequence(&bytes[..], &TARGET_END[..])\n\n .ok_or_else(|| anyhow!(\"Unable to find end of page title\"))?;\n", "file_path": "varela/command/serve/src/handlers/download.rs", "rank": 59, "score": 87814.07180224992 }, { "content": "fn values_to_keys(vec: Vec<String>, map: &mut HashMap<Id, Entity>) -> Vec<Id> {\n\n vec.into_iter()\n\n .map(|name| Database::get_default(map, name, new_id))\n\n .collect()\n\n}\n\n\n", "file_path": "varela/command/index/src/lib.rs", "rank": 60, "score": 86910.53710260103 }, { "content": "pub fn search_v2(db: web::Data<Database>, query: web::RawQuery) -> HttpResponse {\n\n utils::wrap(|| {\n\n let mut stories = db.index().stories.iter().collect::<Vec<_>>();\n\n\n\n let parsed_query =\n\n form_urlencoded::parse(query.trim_start_matches('?').as_bytes()).collect::<Vec<_>>();\n\n\n\n let stats = search::search_v2(&parsed_query[..], &mut stories)\n\n .fill(db.index())\n\n .ok_or_else(|| {\n\n anyhow!(\"Unable to fill out stats, an entity does not exist somewhere\")\n\n })?;\n\n\n\n let query = rebuild_query(&query);\n\n\n\n let mut stories = stories\n\n .into_iter()\n\n .map(|(id, _)| {\n\n utils::get_story_full(&*db, id)\n\n .and_then(|story| partials::StoryPartial::new(id, story, Some(query.clone())))\n", "file_path": "varela/command/serve/src/handlers/search.rs", "rank": 61, "score": 86707.01385433445 }, { "content": "fn first_push<'d, I>(include: bool, database: &Database, stories: &mut Vec<Id>, ids: I)\n\nwhere\n\n I: Iterator<Item = (&'d Id, &'d Story)>,\n\n{\n\n if include {\n\n for id in ids.map(|(id, _)| id) {\n\n if !stories.contains(id) {\n\n stories.push(id.clone());\n\n }\n\n }\n\n } else {\n\n let mut ids = ids.map(|(id, _)| id);\n\n\n\n for id in database.index().stories.iter().map(|(id, _)| id) {\n\n if !ids.any(|i| i == id) {\n\n stories.push(id.clone());\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "varela/command/serve/src/search.rs", "rank": 62, "score": 86431.36279825942 }, { "content": "#[derive(Debug, PartialEq, Aloene)]\n\nenum EnumUnit {\n\n Yes,\n\n No,\n\n}\n\n\n", "file_path": "aloene/tests/se_de_enum.rs", "rank": 63, "score": 83011.78918995801 }, { "content": "pub fn entity(db: web::Data<Database>, id: web::ParseParam<\"id\", Id>) -> HttpResponse {\n\n utils::wrap(|| {\n\n if let Some(kind) = db.get_entity_from_id(&*id) {\n\n let entity = {\n\n let entities = match kind {\n\n EntityKind::Author => &db.index().authors,\n\n EntityKind::Warning => &db.index().warnings,\n\n EntityKind::Origin => &db.index().origins,\n\n EntityKind::Pairing => &db.index().pairings,\n\n EntityKind::Character => &db.index().characters,\n\n EntityKind::General => &db.index().generals,\n\n };\n\n\n\n unsafe { entities.get(&*id).unwrap_unchecked() }\n\n };\n\n\n\n let mut stories = db\n\n .index()\n\n .stories\n\n .iter()\n", "file_path": "varela/command/serve/src/handlers/entity.rs", "rank": 64, "score": 82548.68674593426 }, { "content": "fn se_variant(variant: &syn::Variant) -> proc_macro2::TokenStream {\n\n let variant_ident = &variant.ident;\n\n\n\n let handler = match &variant.fields {\n\n syn::Fields::Named(_named) => syn_err!(\n\n variant,\n\n \"Aloene does not yet support enums with struct like variants\"\n\n ),\n\n syn::Fields::Unnamed(_unnamed) => syn_err!(\n\n variant,\n\n \"Aloene does not yet support enums with tuple like variants\"\n\n ),\n\n syn::Fields::Unit => {\n\n quote::quote! {\n\n ::aloene::io::write_u8(writer, ::aloene::bytes::Value::STRING)?;\n\n\n\n ::aloene::io::write_string(writer, stringify!(#variant_ident))?;\n\n\n\n ::aloene::io::write_u8(writer, ::aloene::bytes::Container::UNIT)?;\n\n }\n\n }\n\n };\n\n\n\n quote::quote! {\n\n #variant_ident => { #handler },\n\n }\n\n}\n\n\n", "file_path": "aloene/macros/src/enumeration.rs", "rank": 65, "score": 82118.1562937657 }, { "content": "fn de_variant(variant: &syn::Variant) -> proc_macro2::TokenStream {\n\n let variant_ident = &variant.ident;\n\n\n\n let handler = match &variant.fields {\n\n syn::Fields::Named(_named) => {\n\n // let field_idents = named.named.iter().map(|field| {\n\n // let ident = field.ident.as_ref().unwrap();\n\n\n\n // quote::quote! { #ident }\n\n // });\n\n\n\n // let fields = named.named.iter().map(super::structure::de_field);\n\n\n\n // quote::quote! {\n\n // ::aloene::io::assert_byte(reader, ::aloene::bytes::Container::STRUCT)?;\n\n\n\n // #( #fields )*\n\n\n\n // Ok(Self::#variant_ident { #( #field_idents , )* })\n\n // }\n", "file_path": "aloene/macros/src/enumeration.rs", "rank": 66, "score": 82118.1562937657 }, { "content": "fn se_field(field: &syn::Field) -> proc_macro2::TokenStream {\n\n let (field_name, ident) = match field_help(field) {\n\n Ok(pair) => pair,\n\n Err(err) => return err,\n\n };\n\n\n\n let typ = BUILTIN_TYPES.iter().find(|typ| ident == **typ);\n\n\n\n if let Some(typ) = typ {\n\n let function = quote::format_ident!(\"write_{}\", typ);\n\n\n\n quote::quote! {\n\n ::aloene::io::structure::#function(writer, stringify!(#field_name), self . #field_name)?;\n\n }\n\n } else {\n\n quote::quote! {\n\n ::aloene::io::write_u8(writer, ::aloene::bytes::Value::STRING)?;\n\n\n\n ::aloene::io::write_string(writer, stringify!(#field_name))?;\n\n\n\n ::aloene::io::write_u8(writer, ::aloene::bytes::Container::VALUE)?;\n\n ::aloene::Aloene::serialize(&self . #field_name, writer)?;\n\n }\n\n }\n\n}\n", "file_path": "aloene/macros/src/structure.rs", "rank": 67, "score": 82118.1562937657 }, { "content": "#[derive(Debug, PartialEq, Aloene)]\n\nenum EnumUnit {\n\n Yes,\n\n No,\n\n}\n\n\n", "file_path": "aloene/tests/se_de.rs", "rank": 68, "score": 79436.09852193603 }, { "content": "fn field_help(field: &syn::Field) -> Result<(&syn::Ident, &syn::Ident), proc_macro2::TokenStream> {\n\n let field_name = match &field.ident {\n\n Some(ident) => ident,\n\n None => {\n\n return Err(syn_err!(field, \"Invalid field\"));\n\n }\n\n };\n\n\n\n let field_path = match &field.ty {\n\n syn::Type::Path(field_path) => field_path,\n\n _ => {\n\n return Err(syn_err!(field, \"Invalid field\"));\n\n }\n\n };\n\n\n\n let path_segments = &field_path.path.segments;\n\n\n\n let first_segment = match path_segments.iter().next() {\n\n Some(first_segment) => first_segment,\n\n None => {\n", "file_path": "aloene/macros/src/structure.rs", "rank": 69, "score": 70773.00439690598 }, { "content": "#[derive(Debug, PartialEq, Clone)]\n\nenum AttributeSpec {\n\n Present,\n\n Exact(String),\n\n Starts(String),\n\n Ends(String),\n\n Contains(String),\n\n}\n", "file_path": "query/macros/src/lib.rs", "rank": 70, "score": 70192.03751767105 }, { "content": "fn main() {\n\n embed_resource::compile(\"assets/manifest.rc\");\n\n}\n", "file_path": "varela/build.rs", "rank": 71, "score": 69739.45357145366 }, { "content": "#[derive(Debug, PartialEq)]\n\nenum Pager {\n\n Num(bool, u32),\n\n Ellipse,\n\n}\n\n\n", "file_path": "varela/command/serve/src/templates/partials/pagination.rs", "rank": 72, "score": 68282.38477671772 }, { "content": "#[derive(Debug, PartialEq)]\n\nenum LinkState {\n\n Normal,\n\n Active,\n\n Disabled,\n\n}\n", "file_path": "varela/command/serve/src/templates/partials/pagination.rs", "rank": 73, "score": 67398.8514786334 }, { "content": "pub trait Selector {\n\n fn elements<'input>(elements: Vec<Node<'input>>) -> Vec<Node<'input>> {\n\n elements\n\n .iter()\n\n .flat_map(|node| node.children.clone())\n\n .collect::<Vec<Node<'input>>>()\n\n }\n\n\n\n fn find<'input>(&self, elements: &[Node<'input>]) -> Vec<Node<'input>>;\n\n}\n\n\n", "file_path": "query/src/lib.rs", "rank": 74, "score": 66784.32050971859 }, { "content": "pub trait Matcher {\n\n fn matches<'input>(&self, name: &str, attrs: &Attributes<'input>) -> bool;\n\n}\n\n\n\npub mod runtime {\n\n use {\n\n super::{Attributes, Element, Matcher, Node, NodeData, Selector},\n\n std::collections::HashMap,\n\n };\n\n\n\n #[derive(Debug, PartialEq)]\n\n pub struct DynamicSelector {\n\n matchers: Vec<DynamicMatcher>,\n\n }\n\n\n\n impl DynamicSelector {\n\n fn find_nodes<'input>(\n\n &self,\n\n matcher: &DynamicMatcher,\n\n elements: &[Node<'input>],\n", "file_path": "query/src/lib.rs", "rank": 75, "score": 66784.32050971859 }, { "content": "pub trait Template {\n\n fn size_hint(&self) -> usize;\n\n\n\n fn render<W>(&self, writer: &mut W) -> Result<()>\n\n where\n\n W: Write;\n\n\n\n fn render_as_string(&self) -> Result<String>\n\n where\n\n Self: Sized,\n\n {\n\n let mut buf = Vec::with_capacity(self.size_hint());\n\n\n\n self.render(&mut buf)?;\n\n\n\n // SAFETY: The buffer is built using `write` calls, and everything is already a Rust string\n\n Ok(unsafe { String::from_utf8_unchecked(buf) })\n\n }\n\n\n\n fn render_into_string(self) -> Result<String>\n\n where\n\n Self: Sized,\n\n {\n\n self.render_as_string()\n\n }\n\n}\n", "file_path": "opal/src/lib.rs", "rank": 76, "score": 66784.32050971859 }, { "content": "#[test]\n\nfn test_childless_unit() {\n\n se_de(Childless {\n\n field1: \"Hello, World! How are you?\".into(),\n\n field2: EnumUnit::Yes,\n\n field3: true,\n\n });\n\n\n\n se_de(Childless {\n\n field1: \"Hello, World! How are you?\".into(),\n\n field2: EnumUnit::No,\n\n field3: true,\n\n });\n\n}\n", "file_path": "aloene/tests/se_de.rs", "rank": 77, "score": 65583.60146275186 }, { "content": "#[test]\n\nfn test_optional() {\n\n se_de(Optional {\n\n field1: false,\n\n field2: 5432.2,\n\n field3: Some(Childless {\n\n field1: \"Hello, World! How are you?\".into(),\n\n field2: 6543,\n\n field3: true,\n\n }),\n\n });\n\n\n\n se_de(Optional {\n\n field1: false,\n\n field2: 5432.2,\n\n field3: None,\n\n });\n\n}\n", "file_path": "aloene/tests/se_de_struct.rs", "rank": 78, "score": 65583.60146275186 }, { "content": "#[allow(clippy::too_many_arguments)]\n\nfn add_to_index(\n\n db: &mut Database,\n\n name: &str,\n\n hash: u64,\n\n updating: bool,\n\n id: Id,\n\n kind: FileKind,\n\n site: Site,\n\n parsed: (ParsedInfo, ParsedMeta, ParsedChapters),\n\n) {\n\n let (info, meta, chapters) = parsed;\n\n\n\n let created = if updating {\n\n if let Some(created) = db.index().stories.get(&id).map(|story| &story.info.created) {\n\n created.clone()\n\n } else {\n\n humantime::format_rfc3339(SystemTime::now()).to_string()\n\n }\n\n } else {\n\n humantime::format_rfc3339(SystemTime::now()).to_string()\n", "file_path": "varela/command/index/src/lib.rs", "rank": 79, "score": 65583.60146275186 }, { "content": "#[test]\n\nfn test_children() {\n\n se_de(Children {\n\n field1: false,\n\n field2: 5432.2,\n\n field3: Childless {\n\n field1: \"Hello, World! How are you?\".into(),\n\n field2: 6543,\n\n field3: true,\n\n },\n\n });\n\n}\n\n\n", "file_path": "aloene/tests/se_de_struct.rs", "rank": 80, "score": 65583.60146275186 }, { "content": "#[test]\n\nfn test_childless() {\n\n se_de(Childless {\n\n field1: \"Hello, World! How are you?\".into(),\n\n field2: 6543,\n\n field3: true,\n\n });\n\n}\n\n\n", "file_path": "aloene/tests/se_de_struct.rs", "rank": 81, "score": 65583.60146275186 }, { "content": "fn main() -> Result<()> {\n\n common::logger::init()?;\n\n\n\n let mut args: common::Args = env::args().skip(1).peekable();\n\n\n\n match args.next().as_deref() {\n\n Some(\"--help\") => {\n\n println!(\"Usage:\");\n\n println!(\" varela\");\n\n println!(\" varela <COMMAND> [<ARGS>]\");\n\n println!();\n\n println!(\"Options:\");\n\n println!(\" --help\");\n\n println!();\n\n println!(\"Commands:\");\n\n println!(\" config access and change the config\");\n\n println!(\" index builds or updates the index\");\n\n println!(\" serve run the internal web server [default]\");\n\n }\n\n Some(\"config\") => {\n", "file_path": "varela/src/main.rs", "rank": 82, "score": 64775.38626625254 }, { "content": "pub trait Aloene: Sized {\n\n fn deserialize<R: std::io::Read>(reader: &mut R) -> Result<Self>;\n\n\n\n fn serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<()>;\n\n}\n\n\n\npub mod test_utils {\n\n use crate::Aloene;\n\n\n\n #[track_caller]\n\n pub fn se_de<T: Aloene + std::fmt::Debug + PartialEq>(data: T) {\n\n let original = data;\n\n\n\n let mut bytes = Vec::new();\n\n\n\n original.serialize(&mut bytes).unwrap();\n\n\n\n let got = T::deserialize(&mut std::io::Cursor::new(bytes)).unwrap();\n\n\n\n assert_eq!(original, got);\n\n }\n\n}\n", "file_path": "aloene/src/lib.rs", "rank": 83, "score": 63335.71702426154 }, { "content": "#[test]\n\nfn test_parse_meta_multiple() {\n\n let doc = Document::try_from(DATA_MULTIPLE).expect(\"BUG: This file should always be parsable\");\n\n\n\n let left = ParsedMeta {\n\n rating: Rating::Teen,\n\n categories: vec![],\n\n origins: vec![\"Testing\".to_string()],\n\n warnings: vec![\"No Archive Warnings Apply\".to_string()],\n\n pairings: vec![],\n\n characters: vec![],\n\n generals: vec![],\n\n };\n\n let right = parse_meta(&doc);\n\n\n\n assert_eq!(left, right);\n\n}\n\n\n", "file_path": "varela/format/ao3/src/tests/html.rs", "rank": 84, "score": 62996.55192431701 }, { "content": "#[test]\n\nfn test_parse_info_multiple() {\n\n let doc = Document::try_from(DATA_MULTIPLE).expect(\"BUG: This file should always be parsable\");\n\n\n\n let left = ParsedInfo {\n\n title: \"Disrupt\".to_string(),\n\n authors: vec![\"testy\".to_string()],\n\n summary: \"<p>Unicorn et Retro adipisicing yr, nulla disrupt laboris austin.</p>\\n<p> </p>\\n<p> <b>Please do not delete! We may need this for further download testing.</b></p>\".to_string(),\n\n };\n\n let right = parse_info(&doc);\n\n\n\n assert_eq!(left, right);\n\n}\n\n\n", "file_path": "varela/format/ao3/src/tests/html.rs", "rank": 85, "score": 62996.55192431701 }, { "content": "#[test]\n\nfn test_parse_chapters_single() {\n\n let doc = Document::try_from(DATA_SINGLE).expect(\"BUG: This file should always be parsable\");\n\n\n\n let left = ParsedChapters {\n\n chapters: vec![ParsedChapter {\n\n title: \"A Work To Test Downloads Again\".to_string(),\n\n summary: None,\n\n start_notes: None,\n\n content: 2265..18822,\n\n end_notes: None,\n\n }],\n\n };\n\n let right = parse_chapters(&doc).unwrap();\n\n\n\n assert_eq!(left, right);\n\n}\n", "file_path": "varela/format/ao3/src/tests/html.rs", "rank": 86, "score": 62996.55192431701 }, { "content": "#[test]\n\nfn test_parse_chapters_multiple() {\n\n let doc = Document::try_from(DATA_MULTIPLE).expect(\"BUG: This file should always be parsable\");\n\n\n\n let left = ParsedChapters { chapters: vec![\n\n ParsedChapter {\n\n title: \"Small Batch Hashtag\".to_string(),\n\n summary: Some(\"<p>Trust fund hot chicken elit blog, williamsburg semiotics asymmetrical franzen church-key portland. Meh keytar iceland semiotics, portland asymmetrical cray godard venmo forage qui consectetur cillum adipisicing</p>\".to_string()),\n\n start_notes: Some(3112..3349),\n\n content: 3541..19287,\n\n end_notes: Some(19419..19430),\n\n },\n\n ParsedChapter {\n\n title: \"Try-hard Brunch\".to_string(),\n\n summary: Some(\"<p>Helvetica bread everyday.</p>\".to_string()),\n\n start_notes: None,\n\n content: 19837..41637,\n\n end_notes: Some(41769..41905),\n\n },\n\n ] };\n\n let right = parse_chapters(&doc).unwrap();\n\n\n\n assert_eq!(left, right);\n\n}\n\n\n\nstatic DATA_SINGLE: &str = include_str!(\"./A Work To Test Downloads.html\");\n\n\n", "file_path": "varela/format/ao3/src/tests/html.rs", "rank": 87, "score": 62996.55192431701 }, { "content": "#[test]\n\nfn test_parse_info_single() {\n\n let doc = Document::try_from(DATA_SINGLE).expect(\"BUG: This file should always be parsable\");\n\n\n\n let left = ParsedInfo {\n\n title: \"A Work To Test Downloads Again\".to_string(),\n\n authors: vec![\"testy\".to_string()],\n\n summary: \"<p>This is a new work for a test.</p>\".to_string(),\n\n };\n\n let right = parse_info(&doc);\n\n\n\n assert_eq!(left, right);\n\n}\n\n\n", "file_path": "varela/format/ao3/src/tests/html.rs", "rank": 88, "score": 62996.55192431701 }, { "content": "#[test]\n\nfn test_parse_meta_single() {\n\n let doc = Document::try_from(DATA_SINGLE).expect(\"BUG: This file should always be parsable\");\n\n\n\n let left = ParsedMeta {\n\n rating: Rating::General,\n\n categories: vec![],\n\n origins: vec![\"Testing\".to_string()],\n\n warnings: vec![\"No Archive Warnings Apply\".to_string()],\n\n pairings: vec![],\n\n characters: vec![],\n\n generals: vec![],\n\n };\n\n let right = parse_meta(&doc);\n\n\n\n assert_eq!(left, right);\n\n}\n\n\n", "file_path": "varela/format/ao3/src/tests/html.rs", "rank": 89, "score": 62996.55192431701 }, { "content": "fn parse_prefixed<B>(\n\n prefixes: [&str; 2],\n\n builder: B,\n\n bounds: &mut Vec<Bound>,\n\n included: bool,\n\n part: &mut &str,\n\n) -> bool\n\nwhere\n\n B: FnOnce(bool, String) -> Bound,\n\n{\n\n let [short, long] = prefixes;\n\n\n\n if part.starts_with(short) || part.starts_with(long) {\n\n let part = part\n\n .trim_start_matches(short)\n\n .trim_start_matches(long)\n\n .to_owned();\n\n\n\n bounds.push(builder(included, part));\n\n\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "varela/command/serve/src/search.rs", "rank": 90, "score": 61905.95867409387 }, { "content": "fn handle_file<P>(\n\n db: &mut Database,\n\n known_ids: &mut Vec<Id>,\n\n path: P,\n\n name: &str,\n\n) -> Result<Option<(Id, u64, bool)>>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let bytes = fs::read(&path)?;\n\n\n\n let hash = {\n\n let mut hasher = crc32fast::Hasher::default();\n\n\n\n hasher.write(&bytes[..]);\n\n\n\n hasher.finish()\n\n };\n\n\n\n let index = db.index();\n", "file_path": "varela/command/index/src/lib.rs", "rank": 91, "score": 61905.95867409387 }, { "content": "#[inline]\n\nfn parse_chapter_single<'input>(\n\n doc: &Document<'input>,\n\n title_node: &Node<'input>,\n\n) -> Result<Vec<ParsedChapter>> {\n\n /// Selects the single chapter next to the `toc-heading`\n\n #[query::selector]\n\n static CHAPTER: &str = \"html > body > #chapters > div.userstuff\";\n\n\n\n match doc.select(&CHAPTER) {\n\n Some(chapter) => {\n\n // TODO: Do people have single chapter stories that have chapter summaries\n\n // let summary = toc_heading\n\n // .get_child_by_tag(\"div\")\n\n // .and_then(|node| node.get_span_of_children(doc.input()))\n\n // .map(|span| span.as_str());\n\n\n\n Ok(vec![ParsedChapter {\n\n title: title_node.get_text().map(String::from).ok_or_else(|| {\n\n anyhow!(\n\n \"Story detected as having a single chapter, unable to find story title.\"\n", "file_path": "varela/format/ao3/src/html.rs", "rank": 92, "score": 61049.2559535822 }, { "content": "#[inline]\n\nfn parse_chapters_multi<'input>(\n\n doc: &Document<'input>,\n\n chapter_node: Node<'input>,\n\n) -> Result<Vec<ParsedChapter>> {\n\n let (mut chapters, mut state) = chapter_node\n\n .children\n\n .iter()\n\n .filter(|n| n.is_element())\n\n .try_fold(\n\n (Vec::new(), MultiState::default()),\n\n |(mut chapters, mut state), node| -> Result<(_, _)> {\n\n let element = match node.get_element() {\n\n Some(e) => e,\n\n None => unreachable!(),\n\n };\n\n\n\n let classes = element\n\n .get_attr(\"class\")\n\n .ok_or_else(|| anyhow!(\"Missing node classes, they should be there\"))?;\n\n\n", "file_path": "varela/format/ao3/src/html.rs", "rank": 93, "score": 61049.2559535822 }, { "content": "fn parse_group<'i, I>(\n\n symbols: [&str; 3],\n\n bounds: &mut Vec<Bound>,\n\n parts: &mut I,\n\n included: bool,\n\n part: &mut &str,\n\n) -> bool\n\nwhere\n\n I: Iterator<Item = &'i str>,\n\n{\n\n let [open, close, sep] = symbols;\n\n\n\n if part.starts_with(open) {\n\n let mut part = part.trim_start_matches(open).to_owned();\n\n\n\n part.push_str(sep);\n\n\n\n for mut inner in parts {\n\n if inner.ends_with(close) {\n\n inner = inner.trim_end_matches(close);\n", "file_path": "varela/command/serve/src/search.rs", "rank": 94, "score": 60508.71661682459 }, { "content": "pub trait IntoReadable: std::fmt::Display + Sized {\n\n fn into_readable(self) -> Readable<Self> {\n\n Readable { inner: self }\n\n }\n\n}\n\n\n\nimpl IntoReadable for usize {}\n\nimpl IntoReadable for isize {}\n\n\n\nimpl IntoReadable for u32 {}\n\nimpl IntoReadable for u64 {}\n\n\n\nimpl IntoReadable for i32 {}\n\nimpl IntoReadable for i64 {}\n", "file_path": "varela/command/serve/src/utils.rs", "rank": 95, "score": 53631.15113942929 }, { "content": "#[inline]\n\nfn span_as_range(span: Span<'_>) -> Range<usize> {\n\n let start = span.start();\n\n let end = span.end();\n\n\n\n Range { start, end }\n\n}\n", "file_path": "varela/format/ao3/src/html.rs", "rank": 96, "score": 52096.10450873723 }, { "content": "fn new_id<V>(map: &HashMap<Id, V>) -> Id {\n\n loop {\n\n let id = utils::new_id();\n\n\n\n if !map.contains_key(&id) {\n\n return id;\n\n }\n\n }\n\n}\n", "file_path": "varela/command/index/src/lib.rs", "rank": 97, "score": 48698.72262905983 }, { "content": "use aloene::{test_utils::se_de, Aloene};\n\n\n\n#[derive(Debug, PartialEq, Aloene)]\n", "file_path": "aloene/tests/se_de_enum.rs", "rank": 98, "score": 38443.07385220256 }, { "content": "\n\n class_match = self\n\n .class\n\n .iter()\n\n .all(|class| el_classes.iter().any(|eclass| eclass == class))\n\n }\n\n\n\n let mut attr_match = true;\n\n for (k, v) in &self.attribute {\n\n if let Some(value) = attrs.get(k.as_str()).copied().flatten() {\n\n if !v.matches(value) {\n\n attr_match = false;\n\n break;\n\n }\n\n }\n\n }\n\n\n\n let name = name.to_string();\n\n let tag_match = self.tag.is_empty() || self.tag.iter().any(|tag| &name == tag);\n\n\n", "file_path": "query/src/lib.rs", "rank": 99, "score": 19.447639665866735 } ]
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 remove breakpoints and detach from the debugger\n\nunsafe extern \"system\" fn ctrl_c_handler(_ctrl_type: u32) -> i32 {\n\n // Store that an exit was requested\n\n EXIT_REQUESTED.store(true, Ordering::SeqCst);\n\n\n\n // Sleep forever\n\n loop {\n\n std::thread::sleep(Duration::from_secs(100));\n\n }\n\n}\n\n\n\n/// Different types of breakpoints\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\npub enum BreakpointType {\n\n /// Keep the breakpoint in place and keep track of how many times it was\n\n /// hit\n\n Freq,\n\n\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 2, "score": 135912.1900162992 }, { "content": "/// Callback function for `EnumWindows()`\n\ntype EnumWindowsProc = extern \"C\" fn (hwnd: usize, lparam: usize) -> bool;\n\n\n\n#[link(name=\"User32\")]\n\nextern \"system\" {\n\n fn FindWindowW(lpClassName: *mut u16, lpWindowName: *mut u16) -> usize;\n\n fn EnumChildWindows(hwnd: usize, func: EnumChildProc,\n\n lparam: usize) -> bool;\n\n fn GetWindowTextW(hwnd: usize, string: *mut u16, chars: i32) -> i32;\n\n fn GetWindowTextLengthW(hwnd: usize) -> i32;\n\n fn PostMessageW(hwnd: usize, msg: u32, wparam: usize, lparam: usize)\n\n -> bool;\n\n fn GetMenu(hwnd: usize) -> usize;\n\n fn GetSubMenu(hwnd: usize, pos: i32) -> usize;\n\n fn GetMenuItemID(menu: usize, pos: i32) -> u32;\n\n fn GetMenuItemCount(menu: usize) -> i32;\n\n fn EnumWindows(func: EnumWindowsProc, lparam: usize) -> bool;\n\n fn GetWindowThreadProcessId(hwnd: usize, pid: *mut u32) -> u32;\n\n}\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 4, "score": 122190.01075365135 }, { "content": "/// Callback function for `EnumChildWindows()`\n\ntype EnumChildProc = extern \"C\" fn(hwnd: usize, lparam: usize) -> bool;\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 5, "score": 122189.95500614279 }, { "content": "#[repr(u32)]\n\nenum MessageType {\n\n /// Left mouse button down event\n\n LButtonDown = 0x0201,\n\n\n\n /// Left mouse button up event\n\n LButtonUp = 0x0202,\n\n\n\n /// Sends a key down event to the window\n\n KeyDown = 0x0100,\n\n\n\n /// Sends a key up event to the window\n\n KeyUp = 0x0101,\n\n\n\n /// Sends a command to a window, typically sent when a button is pressed\n\n /// or a menu item is used\n\n Command = 0x0111,\n\n\n\n /// Sends a graceful exit to the window\n\n Close = 0x0010,\n\n}\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 6, "score": 103102.68003899498 }, { "content": "fn worker(stats: Arc<Mutex<Statistics>>) {\n\n // Local stats database\n\n let mut local_stats = Statistics::default();\n\n\n\n // Create an RNG for this thread\n\n let rng = Rng::new();\n\n\n\n loop {\n\n // Delete all state invoked with the calc.exe process\n\n Command::new(\"reg.exe\").args(&[\n\n \"delete\",\n\n r\"HKEY_CURRENT_USER\\Software\\Microsoft\\Calc\",\n\n \"/f\",\n\n ]).output().unwrap();\n\n\n\n std::thread::sleep(Duration::from_millis(rng.rand() as u64 % 500));\n\n\n\n // Create a new calc instance\n\n let mut dbg = Debugger::spawn_proc(&[\"calc.exe\".into()], false);\n\n\n", "file_path": "mesos/src/main.rs", "rank": 7, "score": 97249.87101895502 }, { "content": "/// Create a full minidump of a given process\n\npub fn dump(filename: &str, pid: u32, tid: u32, process: HANDLE,\n\n exception: &mut EXCEPTION_RECORD, context: &mut CONTEXT) {\n\n // Don't overwrite existing dumps\n\n if Path::new(filename).is_file() {\n\n print!(\"Ignoring duplicate crash {}\\n\", filename);\n\n return;\n\n }\n\n\n\n unsafe {\n\n let filename = win32_string(filename);\n\n\n\n let ep = EXCEPTION_POINTERS {\n\n ExceptionRecord: exception,\n\n ContextRecord: context,\n\n };\n\n \n\n // Create the minidump file\n\n let fd = CreateFileW(filename.as_ptr(),\n\n GENERIC_READ | GENERIC_WRITE, 0,\n\n std::ptr::null_mut(), CREATE_NEW, 0, std::ptr::null_mut());\n", "file_path": "mesos/libs/debugger/src/minidump.rs", "rank": 8, "score": 95933.92189240252 }, { "content": "/// Enable SeDebugPrivilege so we can debug system services\n\npub fn sedebug() {\n\n unsafe {\n\n let mut token: HANDLE = std::ptr::null_mut();\n\n let mut tkp: TOKEN_PRIVILEGES = std::mem::zeroed();\n\n\n\n // Get the token for the current process\n\n assert!(OpenProcessToken(GetCurrentProcess(), \n\n TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &mut token) != 0);\n\n \n\n // Wrap up the handle so it'll get Dropped correctly\n\n let token = Handle::new(token)\n\n .expect(\"Failed to get valid handle for token\");\n\n\n\n // Lookup SeDebugPrivilege\n\n let privname = win32_string(\"SeDebugPrivilege\");\n\n assert!(LookupPrivilegeValueW(std::ptr::null(),\n\n privname.as_ptr(), &mut tkp.Privileges[0].Luid) != 0);\n\n\n\n tkp.PrivilegeCount = 1;\n\n tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\n\n\n\n // Set the privilege\n\n assert!(AdjustTokenPrivileges(token.raw(), 0, &mut tkp, 0,\n\n std::ptr::null_mut(), std::ptr::null_mut()) != 0);\n\n }\n\n}\n", "file_path": "mesos/libs/debugger/src/sedebug.rs", "rank": 9, "score": 86797.41963436933 }, { "content": "/// Function invoked on debug events\n\ntype DebugEventFunc = Box<dyn Fn(&mut Debugger, &DEBUG_EVENT)>;\n\n\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 10, "score": 85792.6067966681 }, { "content": "/// Grab a native-endianness u32 from a slice of u8s\n\nfn u32_from_slice(val: &[u8]) -> u32 {\n\n let mut tmp = [0u8; 4];\n\n tmp.copy_from_slice(&val[..4]);\n\n u32::from_ne_bytes(tmp)\n\n}\n\n\n", "file_path": "mesos/src/mesofile.rs", "rank": 11, "score": 85026.10544703635 }, { "content": "fn main() -> io::Result<()> {\n\n let window = Window::attach(\"Calculator\")?;\n\n\n\n assert!(unsafe { SetForegroundWindow(window.hwnd) });\n\n\n\n let mut rect = Rect::default();\n\n unsafe {\n\n assert!(GetWindowRect(window.hwnd, &mut rect));\n\n }\n\n\n\n print!(\"{:?}\\n\", rect);\n\n\n\n unsafe {\n\n loop {\n\n std::thread::sleep_ms(50);\n\n PostMessageW(window.hwnd, 0x0200, 0, ((window.rand() % 1000) << 16) | (window.rand() % 1000));\n\n }\n\n }\n\n\n\n /*\n", "file_path": "fuzzer/src/main.rs", "rank": 12, "score": 84309.07087701719 }, { "content": "fn scoop() -> io::Result<()> {\n\n let args: Vec<String> = std::env::args().collect();\n\n\n\n if args.len() != 2 {\n\n print!(\"usage: cargo run <window title to fuzz on>\\n\");\n\n return Ok(());\n\n }\n\n\n\n 'reconnect: loop {\n\n //std::thread::sleep_ms(5);\n\n\n\n let window = Window::attach(&args[1]);\n\n if window.is_err() {\n\n print!(\"could not attach to window\\n\");\n\n continue;\n\n }\n\n\n\n let window = window.unwrap();\n\n print!(\"Opened a handle to calc!\\n\");\n\n \n", "file_path": "fuzzer/src/main.rs", "rank": 13, "score": 84309.07087701719 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy, Debug, Default)]\n\nstruct Rect {\n\n left: i32,\n\n top: i32,\n\n right: i32,\n\n bottom: i32,\n\n}\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 14, "score": 78544.66719055876 }, { "content": "/// Function invoked on module loads\n\n/// (debugger, module filename, module base)\n\ntype ModloadFunc = Box<dyn Fn(&mut Debugger, &str, usize)>;\n\n\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 15, "score": 77020.51544017595 }, { "content": "#[repr(u8)]\n\nenum KeyCode {\n\n Back = 0x08,\n\n Tab = 0x09,\n\n Return = 0x0d,\n\n Shift = 0x10,\n\n Control = 0x11,\n\n Alt = 0x12,\n\n Left = 0x25,\n\n Up = 0x26,\n\n Right = 0x27,\n\n Down = 0x28,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 16, "score": 76918.97011514426 }, { "content": "#[repr(u32)]\n\nenum MsgType {\n\n LeftButtonDown = 0x0201,\n\n LeftButtonUp = 0x0202,\n\n KeyDown = 0x0100,\n\n KeyUp = 0x0101,\n\n}\n\n\n\n/// Different types of states for the `WPARAM` field on \n", "file_path": "fuzzer/src/main.rs", "rank": 17, "score": 76703.07411953807 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nenum InputType {\n\n Mouse = 0,\n\n Keyboard = 1,\n\n Hardware = 2,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 18, "score": 76702.97777232599 }, { "content": "#[repr(C)]\n\n#[derive(Debug, Default)]\n\nstruct MenuItemInfo {\n\n size: u32,\n\n mask: u32,\n\n typ: u32,\n\n state: u32,\n\n id: u32,\n\n sub_menu: usize,\n\n bmp_checked: usize,\n\n bmp_unchecked: usize,\n\n item_data: usize,\n\n type_data: usize,\n\n cch: u32,\n\n bmp_item: usize,\n\n}\n\n\n\nimpl Window {\n\n /// Find a window with `title`, and return a new `Window` object\n\n pub fn attach(title: &str) -> io::Result<Self> {\n\n // Convert the title to UTF-16\n\n let mut title = str_to_utf16(title); \n", "file_path": "guifuzz/src/winbindings.rs", "rank": 19, "score": 73676.78807394757 }, { "content": "/// Convert rust string to null-terminated UTF-16 Windows API string\n\npub fn win32_string(value: &str) -> Vec<u16> {\n\n OsStr::new(value).encode_wide().chain(once(0)).collect()\n\n}\n", "file_path": "mesos/libs/debugger/src/ffi_helpers.rs", "rank": 20, "score": 62770.68914404954 }, { "content": "/// Load a meso file based on `meso_path` and apply breakpoints as requested to\n\n/// the `Debugger` specified by `dbg`\n\npub fn load_meso(dbg: &mut Debugger, meso_path: &Path) {\n\n // Do nothing if the file doesn't exist\n\n if !meso_path.is_file() {\n\n return;\n\n }\n\n\n\n // Read the file\n\n let meso: Vec<u8> = std::fs::read(meso_path).expect(\"Failed to read meso\");\n\n\n\n // Current module name we are processing\n\n let mut cur_modname: Option<Arc<String>> = None;\n\n\n\n // Pointer to the remainder of the file\n\n let mut ptr = &meso[..];\n\n\n\n // Read a `$ty` from the mesofile\n\n macro_rules! read {\n\n ($ty:ty) => {{\n\n let mut array = [0; std::mem::size_of::<$ty>()];\n\n array.copy_from_slice(&ptr[..std::mem::size_of::<$ty>()]);\n", "file_path": "mesos/src/mesofile.rs", "rank": 21, "score": 62092.11693126585 }, { "content": "/// Computes the path to the cached meso filename for a given module loaded\n\n/// at `base`\n\npub fn compute_cached_meso_name(dbg: &mut Debugger, filename: &str,\n\n base: usize) -> PathBuf { \n\n let mut image_header = [0u8; 4096];\n\n\n\n // Read the image header at `base`\n\n assert!(dbg.read_mem(base, &mut image_header) ==\n\n std::mem::size_of_val(&image_header),\n\n \"Failed to read PE image header from target\");\n\n\n\n // Validate this is a PE\n\n assert!(&image_header[0..2] == b\"MZ\", \"File was not MZ\");\n\n let pe_ptr = u32_from_slice(&image_header[0x3c..0x40]) as usize;\n\n assert!(&image_header[pe_ptr..pe_ptr+4] == b\"PE\\0\\0\");\n\n\n\n // Get TimeDateStamp and ImageSize from the PE header\n\n let timestamp = u32_from_slice(&image_header[pe_ptr+8..pe_ptr+0xc]);\n\n let imagesz =\n\n u32_from_slice(&image_header[pe_ptr+0x50..pe_ptr+0x54]);\n\n\n\n // Compute the meso name\n\n format!(\"cache\\\\{}_{:x}_{:x}.meso\", filename, timestamp, imagesz).into()\n\n}\n\n\n", "file_path": "mesos/src/mesofile.rs", "rank": 22, "score": 60741.119547335205 }, { "content": "/// Convert a Rust UTF-8 `string` into a NUL-terminated UTF-16 vector\n\nfn str_to_utf16(string: &str) -> Vec<u16> {\n\n let mut ret: Vec<u16> = string.encode_utf16().collect();\n\n ret.push(0);\n\n ret\n\n}\n\n\n\n/// An active handle to a window\n\n#[derive(Clone, Copy)]\n\npub struct Window {\n\n /// Handle to the window which we have opened\n\n hwnd: usize,\n\n}\n\n\n\nimpl fmt::Debug for Window {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"Window {{ hwnd: {:#x}, title: \\\"{}\\\" }}\",\n\n self.hwnd, self.window_text().unwrap())\n\n }\n\n}\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 23, "score": 57536.98568469327 }, { "content": "fn record_input(fuzz_input: FuzzInput) {\n\n let mut hasher = DefaultHasher::new();\n\n fuzz_input.hash(&mut hasher);\n\n\n\n let _ = std::fs::create_dir(\"inputs\");\n\n std::fs::write(format!(\"inputs/{:016x}.input\", hasher.finish()),\n\n format!(\"{:#?}\", fuzz_input)).expect(\"Failed to save input to disk\");\n\n}\n\n\n", "file_path": "mesos/src/main.rs", "rank": 24, "score": 55568.607198681544 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy, Default, Debug)]\n\nstruct Rect {\n\n left: i32,\n\n top: i32,\n\n right: i32,\n\n bottom: i32,\n\n}\n\n\n\n/// Different types of inpust for the `typ` field on `Input`\n", "file_path": "fuzzer/src/main.rs", "rank": 25, "score": 50885.942342069065 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nstruct Input {\n\n typ: InputType,\n\n union: InputUnion,\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nunion InputUnion {\n\n mouse: MouseInput,\n\n keyboard: KeyboardInput,\n\n hardware: HardwareInput,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 26, "score": 50882.73366335887 }, { "content": "/// An active handle to a window\n\nstruct Window {\n\n /// Handle to the window which we have opened\n\n hwnd: usize,\n\n\n\n /// Seed for an RNG\n\n seed: Cell<u64>,\n\n\n\n /// Keys which seem interesting\n\n interesting_keys: Vec<u8>,\n\n}\n\n\n\nimpl Window {\n\n /// Find a window with `title`, and return a new `Window` object\n\n fn attach(title: &str) -> io::Result<Self> {\n\n // Convert the title to UTF-16\n\n let mut title = str_to_utf16(title); \n\n\n\n // Finds the window with `title`\n\n let ret = unsafe {\n\n FindWindowW(std::ptr::null_mut(), title.as_mut_ptr())\n", "file_path": "fuzzer/src/main.rs", "rank": 27, "score": 50879.195253808415 }, { "content": "fn main() {\n\n // Global statistics\n\n let stats = Arc::new(Mutex::new(Statistics::default()));\n\n\n\n // Open a log file\n\n let mut log = File::create(\"fuzz_stats.txt\").unwrap();\n\n\n\n // Save the current time\n\n let start_time = Instant::now();\n\n\n\n for _ in 0..10 {\n\n // Spawn threads\n\n let stats = stats.clone();\n\n let _ = std::thread::spawn(move || {\n\n worker(stats);\n\n });\n\n }\n\n\n\n loop {\n\n std::thread::sleep(Duration::from_millis(1000));\n", "file_path": "mesos/src/main.rs", "rank": 28, "score": 49621.44448597728 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nstruct HardwareInput {\n\n msg: u32,\n\n lparam: u16,\n\n hparam: u16,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 29, "score": 49598.85290948412 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nstruct KeyboardInput {\n\n vk: u16,\n\n scan_code: u16,\n\n flags: u32,\n\n time: u32,\n\n extra_info: usize,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 30, "score": 49598.85290948412 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nstruct MouseInput {\n\n dx: i32,\n\n dy: i32,\n\n mouse_data: u32,\n\n flags: u32,\n\n time: u32,\n\n extra_info: usize,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 31, "score": 49598.85290948412 }, { "content": "#[repr(usize)]\n\nenum WparamMousePress {\n\n Left = 0x0001,\n\n Right = 0x0002,\n\n Shift = 0x0004,\n\n Control = 0x0008,\n\n Middle = 0x0010,\n\n Xbutton1 = 0x0020,\n\n Xbutton2 = 0x0040,\n\n}\n\n\n", "file_path": "fuzzer/src/main.rs", "rank": 32, "score": 48610.74572746877 }, { "content": "/// Get elapsed time in seconds\n\nfn elapsed_from(start: &Instant) -> f64 {\n\n let dur = start.elapsed();\n\n dur.as_secs() as f64 + dur.subsec_nanos() as f64 / 1_000_000_000.0\n\n}\n\n\n\n// Mesos print with uptime prefix\n\nmacro_rules! mprint {\n\n ($x:ident, $($arg:tt)*) => {\n\n format!(\"[{:14.6}] \", elapsed_from(&$x.start_time));\n\n format!($($arg)*);\n\n }\n\n}\n\n\n\nimpl<'a> Debugger<'a> {\n\n /// Create a new debugger and attach to `pid`\n\n pub fn attach(pid: u32) -> Debugger<'a> {\n\n Debugger::attach_internal(pid, false)\n\n }\n\n\n\n /// Create a new process argv[0], with arguments argv[1..] and attach to it\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 33, "score": 36686.09141006908 }, { "content": "/// Convert a Rust UTF-8 `string` into a NUL-terminated UTF-16 vector\n\nfn str_to_utf16(string: &str) -> Vec<u16> {\n\n let mut ret: Vec<u16> = string.encode_utf16().collect();\n\n ret.push(0);\n\n ret\n\n}\n\n\n\n/// Different types of messages for `SendMessage()`\n", "file_path": "fuzzer/src/main.rs", "rank": 34, "score": 35204.061474864764 }, { "content": " }\n\n\n\n /// Created a RNG with a fixed `seed` value\n\n pub fn seeded(seed: u64) -> Self {\n\n Rng {\n\n seed: Cell::new(seed),\n\n }\n\n }\n\n\n\n /// Get a random 64-bit number using xorshift\n\n pub fn rand(&self) -> usize {\n\n let mut seed = self.seed.get();\n\n seed ^= seed << 13;\n\n seed ^= seed >> 17;\n\n seed ^= seed << 43;\n\n self.seed.set(seed);\n\n seed as usize\n\n }\n\n}\n\n\n", "file_path": "guifuzz/src/rng.rs", "rank": 35, "score": 29833.513669242075 }, { "content": "use std::cell::Cell;\n\n\n\n/// Random number generator implementation using xorshift64\n\npub struct Rng {\n\n /// Interal xorshift seed\n\n seed: Cell<u64>,\n\n}\n\n\n\nimpl Rng {\n\n /// Create a new, TSC-seeded random number generator\n\n pub fn new() -> Self {\n\n let ret = Rng {\n\n seed: Cell::new(unsafe { core::arch::x86_64::_rdtsc() }),\n\n };\n\n\n\n for _ in 0..1000 {\n\n let _ = ret.rand();\n\n }\n\n\n\n ret\n", "file_path": "guifuzz/src/rng.rs", "rank": 36, "score": 29831.443717104696 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n /// Presses a key down and releases it\n\n pub fn press_key(&self, key: usize) -> io::Result<()> {\n\n unsafe {\n\n if !PostMessageW(self.hwnd, MessageType::KeyDown as u32, key, 0) {\n\n // PostMessageW() failed\n\n return Err(io::Error::last_os_error());\n\n }\n\n\n\n if !PostMessageW(self.hwnd, MessageType::KeyUp as u32, key,\n\n 3 << 30) {\n\n // PostMessageW() failed\n\n return Err(io::Error::last_os_error());\n\n }\n\n }\n\n \n\n Ok(())\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 37, "score": 29063.293914830923 }, { "content": " unsafe {\n\n if PostMessageW(self.hwnd, MessageType::Command as u32,\n\n menu_id.try_into().unwrap(), 0) {\n\n // Success!\n\n Ok(())\n\n } else {\n\n // PostMessageW() error\n\n Err(io::Error::last_os_error())\n\n }\n\n }\n\n }\n\n\n\n /// Attempts to gracefully close the applications\n\n pub fn close(&self) -> io::Result<()> {\n\n unsafe {\n\n if PostMessageW(self.hwnd, MessageType::Close as u32, 0, 0) {\n\n // Success!\n\n Ok(())\n\n } else {\n\n // PostMessageW() error\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 38, "score": 29061.243196569925 }, { "content": " }\n\n }\n\n\n\n // Keep enumerating\n\n true\n\n } else {\n\n // Keep enumerating\n\n true\n\n }\n\n }\n\n\n\n /// Return a `Window` object for the `pid`s main window\n\n pub fn attach_pid(pid: u32, window_title: &str) -> io::Result<Self> {\n\n let mut context: (u32, Option<usize>, String) =\n\n (pid, None, window_title.into());\n\n\n\n unsafe {\n\n if !EnumWindows(Self::enum_windows_handler,\n\n &mut context as *mut _ as usize) {\n\n // EnumWindows() failed, return out the corresponding error\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 39, "score": 29059.097546006873 }, { "content": " pub fn enum_menus(&self) -> io::Result<BTreeSet<u32>> {\n\n // Get the window's main menu\n\n let menu = unsafe { GetMenu(self.hwnd) };\n\n if menu == 0 {\n\n // GetMenu() error\n\n return Err(io::Error::last_os_error());\n\n }\n\n\n\n // Create the empty hash set\n\n let mut menu_ids = BTreeSet::new();\n\n\n\n // Recursively search through the menu\n\n self.recurse_menu(&mut menu_ids, menu)?;\n\n\n\n Ok(menu_ids)\n\n }\n\n\n\n /// Send a message to the window, indicating that `menu_id` was clicked.\n\n /// To get a valid `menu_id`, use the `enum_menus` member function.\n\n pub fn use_menu_id(&self, menu_id: u32) -> io::Result<()> {\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 40, "score": 29058.65190987279 }, { "content": " /// Does a left click of the current window\n\n pub fn left_click(&self, state: Option<KeyMouseState>) -> io::Result<()> {\n\n // Get the state, or create a new, empty state\n\n let mut state = state.unwrap_or_default();\n\n\n\n unsafe {\n\n state.left_mouse = true;\n\n if !PostMessageW(self.hwnd, MessageType::LButtonDown as u32,\n\n state.into(), 0) {\n\n // PostMessageW() failed\n\n return Err(io::Error::last_os_error());\n\n }\n\n\n\n state.left_mouse = false;\n\n if !PostMessageW(self.hwnd, MessageType::LButtonUp as u32,\n\n state.into(), 0) {\n\n // PostMessageW() failed\n\n return Err(io::Error::last_os_error());\n\n }\n\n }\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 41, "score": 29057.335392291763 }, { "content": " Err(io::Error::last_os_error())\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Holds the state of some of the special keyboard and mouse buttons during\n\n/// certain mouse events\n\n#[derive(Default, Debug, Clone, Copy)]\n\npub struct KeyMouseState {\n\n /// Left mouse button is down\n\n pub left_mouse: bool,\n\n\n\n /// Middle mouse button is down\n\n pub middle_mouse: bool,\n\n\n\n /// Right mouse button is down\n\n pub right_mouse: bool,\n\n\n\n /// Shift key is down\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 42, "score": 29057.33041291968 }, { "content": " return Err(io::Error::last_os_error());\n\n }\n\n }\n\n\n\n if let Some(hwnd) = context.1 {\n\n // Create the window object\n\n Ok(Window { hwnd })\n\n } else {\n\n // Could not find a HWND\n\n Err(io::Error::new(io::ErrorKind::Other,\n\n \"Could not find HWND for pid\"))\n\n }\n\n }\n\n\n\n /// Internal callback for `EnumChildWindows()` used from the\n\n /// `enumerate_subwindows()` member function\n\n extern \"C\" fn enum_child_window_callback(hwnd: usize, lparam: usize)\n\n -> bool {\n\n // Get the parameter we passed in\n\n let listing: &mut WindowListing = unsafe {\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 43, "score": 29054.313996081204 }, { "content": "use std::io;\n\nuse std::fmt;\n\nuse std::error::Error;\n\nuse std::convert::TryInto;\n\nuse std::ops::Deref;\n\nuse std::collections::BTreeSet;\n\n\n\n/// Callback function for `EnumChildWindows()`\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 44, "score": 29054.091142735393 }, { "content": " pub shift: bool,\n\n\n\n /// First x button is down\n\n pub xbutton1: bool,\n\n\n\n /// Second x button is down\n\n pub xbutton2: bool,\n\n\n\n /// Control key is down\n\n pub control: bool,\n\n}\n\n\n\n\n\nimpl Into<usize> for KeyMouseState {\n\n fn into(self) -> usize {\n\n (if self.left_mouse { 0x0001 } else { 0 }) |\n\n (if self.middle_mouse { 0x0010 } else { 0 }) |\n\n (if self.right_mouse { 0x0002 } else { 0 }) |\n\n (if self.shift { 0x0004 } else { 0 }) |\n\n (if self.xbutton1 { 0x0020 } else { 0 }) |\n\n (if self.xbutton2 { 0x0040 } else { 0 }) |\n\n (if self.control { 0x0008 } else { 0 })\n\n }\n\n}\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 45, "score": 29053.520408158853 }, { "content": " // Child windows successfully enumerated\n\n Ok(listing)\n\n } else {\n\n // Failure during call to `EnumChildWindows()`\n\n Err(io::Error::last_os_error())\n\n }\n\n }\n\n }\n\n\n\n /// Gets the title for the window, or in the case of a control field, gets\n\n /// the text on the object\n\n pub fn window_text(&self) -> Result<String, Box<dyn Error>> {\n\n let text_len = unsafe { GetWindowTextLengthW(self.hwnd) };\n\n\n\n // Return an empty string if the window text length was reported as\n\n // zero\n\n if text_len == 0 {\n\n return Ok(String::new());\n\n }\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 46, "score": 29053.168322362955 }, { "content": "\n\n/// Different types of virtual key codes\n\n#[repr(usize)]\n\npub enum VirtualKeyCode {\n\n Left = 0x25,\n\n Up = 0x26,\n\n Right = 0x27,\n\n Down = 0x28,\n\n F10 = 0x79,\n\n}\n\n\n\n/// Rust implementation of `MENUITEMINFOW`\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 47, "score": 29052.925668376505 }, { "content": "\n\n // Finds the window with `title`\n\n let ret = unsafe {\n\n FindWindowW(std::ptr::null_mut(), title.as_mut_ptr())\n\n };\n\n\n\n if ret != 0 {\n\n // Successfully got a handle to the window\n\n return Ok(Window {\n\n hwnd: ret,\n\n });\n\n } else {\n\n // FindWindow() failed, return out the corresponding error\n\n Err(io::Error::last_os_error())\n\n }\n\n }\n\n\n\n extern \"C\" fn enum_windows_handler(hwnd: usize, lparam: usize) -> bool {\n\n let param = unsafe {\n\n &mut *(lparam as *mut (u32, Option<usize>, String))\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 48, "score": 29052.441172598905 }, { "content": " &mut *(lparam as *mut WindowListing)\n\n };\n\n\n\n // Add this window handle to the listing\n\n listing.windows.push(Window { hwnd });\n\n\n\n // Continue the search\n\n true\n\n }\n\n\n\n /// Enumerate all of the sub-windows belonging to `Self` recursively\n\n pub fn enumerate_subwindows(&self) -> io::Result<WindowListing> {\n\n // Create a new, empty window listing\n\n let mut listing = WindowListing::default();\n\n\n\n unsafe {\n\n // Enumerate all the child windows\n\n if EnumChildWindows(self.hwnd, \n\n Self::enum_child_window_callback,\n\n &mut listing as *mut WindowListing as usize) {\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 49, "score": 29051.591517944293 }, { "content": " }\n\n\n\n /// Recurse into a menu listing, looking for sub menus\n\n fn recurse_menu(&self, menu_ids: &mut BTreeSet<u32>, menu_handle: usize)\n\n -> io::Result<()> {\n\n unsafe {\n\n // Get the number of menu items\n\n let menu_count = GetMenuItemCount(menu_handle);\n\n if menu_count == -1 {\n\n // GetMenuItemCount() failed\n\n return Err(io::Error::last_os_error());\n\n }\n\n\n\n // Go through each item in the menu\n\n for menu_index in 0..menu_count {\n\n // Get the menu ID\n\n let menu_id = GetMenuItemID(menu_handle, menu_index);\n\n\n\n if menu_id == !0 {\n\n // Menu is a sub menu, get the sub menu handle\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 50, "score": 29051.432077440753 }, { "content": " let sub_menu = GetSubMenu(menu_handle, menu_index);\n\n if sub_menu == 0 {\n\n // GetSubMenu() failed\n\n return Err(io::Error::last_os_error());\n\n }\n\n\n\n // Recurse into the sub-menu\n\n self.recurse_menu(menu_ids, sub_menu)?;\n\n } else {\n\n // This is a menu identifier, add it to the set\n\n menu_ids.insert(menu_id);\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n }\n\n\n\n /// Enumerate all window menus, return a set of the menu IDs which can\n\n /// be used with a `WM_COMMAND` message\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 51, "score": 29048.84708065388 }, { "content": "/// Structure which contains a listing of all child windows\n\n#[derive(Default, Debug)]\n\npub struct WindowListing {\n\n /// List of all window HWNDs\n\n windows: Vec<Window>,\n\n}\n\n\n\nimpl Deref for WindowListing {\n\n type Target = [Window];\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.windows\n\n }\n\n}\n\n\n\n/// Different message types to be sent to `PostMessage()` and `SendMessage()`\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 52, "score": 29048.642541340472 }, { "content": " // Allocate a buffer to hold `text_len` wide characters\n\n let text_len: usize = text_len.try_into().unwrap();\n\n let alc_len = text_len.checked_add(1).unwrap();\n\n let mut wchar_buffer: Vec<u16> = Vec::with_capacity(alc_len);\n\n\n\n unsafe {\n\n // Get the window text\n\n let ret = GetWindowTextW(self.hwnd, wchar_buffer.as_mut_ptr(),\n\n alc_len.try_into().unwrap());\n\n\n\n // Set the length of the vector\n\n wchar_buffer.set_len(ret.try_into().unwrap());\n\n }\n\n\n\n // Convert the UTF-16 string into a Rust UTF-8 `String`\n\n String::from_utf16(wchar_buffer.as_slice()).map_err(|x| {\n\n x.into()\n\n })\n\n }\n\n\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 53, "score": 29045.66543209171 }, { "content": " };\n\n\n\n let mut pid = 0;\n\n let tid = unsafe{\n\n GetWindowThreadProcessId(hwnd, &mut pid)\n\n };\n\n if pid == 0 || tid == 0 {\n\n return true;\n\n }\n\n\n\n if param.0 == pid {\n\n // Create a window for this window we are enumerating\n\n let tmpwin = Window { hwnd };\n\n \n\n // Get the title for the window\n\n if let Ok(title) = tmpwin.window_text() {\n\n // Check if the title matches what we are searching for\n\n if &title == &param.2 {\n\n // Match!\n\n param.1 = Some(hwnd);\n", "file_path": "guifuzz/src/winbindings.rs", "rank": 54, "score": 29043.965477396672 }, { "content": " def ida_error():\n\n # Validate it worked!\n\n assert os.path.exists(PROBENAME), \\\n\n \"idat64.exe is not in your PATH or it's not functioning. \\\n", "file_path": "mesos/generate_mesos.py", "rank": 55, "score": 23847.808897120627 }, { "content": " /// Handle to the process, given by the first create process event so it\n\n /// is not present until `run()` is used\n\n process_handle: Option<HANDLE>,\n\n\n\n /// List of callbacks to invoke when a module is loaded\n\n module_load_callbacks: Option<Vec<ModloadFunc>>,\n\n\n\n /// List of callbacks to invoke when a debug event is fired\n\n debug_event_callbacks: Option<Vec<DebugEventFunc>>,\n\n\n\n /// Thread ID to handle map\n\n thread_handles: HashMap<u32, HANDLE>,\n\n\n\n /// List of all PCs we hit during execution\n\n /// Keyed by PC\n\n /// Tuple is (module, offset, symbol+offset, frequency)\n\n pub coverage: HashMap<usize, (Arc<String>, usize, String, u64)>,\n\n\n\n /// Set of DLL names and the corresponding DLL base\n\n modules: HashSet<(String, usize)>,\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 58, "score": 18.321265525756118 }, { "content": " /// Delete the breakpoint after it has been hit once\n\n Single,\n\n}\n\n\n\n/// Different types of ways the `Debugger::run()` routine can return\n\n#[derive(Clone, Debug, PartialEq, Eq)]\n\npub enum ExitType {\n\n /// Program exited gracefully with a given exit code\n\n ExitCode(i32),\n\n\n\n /// Program crashed\n\n Crash(String),\n\n}\n\n\n\n/// Structure to represent breakpoints\n\n#[derive(Clone)]\n\npub struct Breakpoint {\n\n /// Offset from module base\n\n offset: usize,\n\n\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 60, "score": 15.661397590733385 }, { "content": "use std::io;\n\nuse std::io::Error;\n\nuse std::cell::Cell;\n\nuse std::collections::HashSet;\n\nuse std::convert::TryInto;\n\n\n\n#[link(name=\"User32\")]\n\nextern \"system\" {\n\n fn FindWindowW(lpClassName: *mut u16, lpWindowName: *mut u16) -> usize;\n\n fn PostMessageW(hWnd: usize, msg: u32, wParam: usize, lParam: usize)\n\n -> usize;\n\n fn GetForegroundWindow() -> usize;\n\n fn SendInput(cInputs: u32, pInputs: *mut Input, cbSize: i32) -> u32;\n\n fn SetForegroundWindow(hwnd: usize) -> bool;\n\n fn GetClientRect(hwnd: usize, rect: *mut Rect) -> bool;\n\n fn GetWindowRect(hwnd: usize, rect: *mut Rect) -> bool;\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Clone, Copy, Default, Debug)]\n", "file_path": "fuzzer/src/main.rs", "rank": 61, "score": 15.47099999523634 }, { "content": "extern crate debugger;\n\nextern crate guifuzz;\n\n\n\npub mod mesofile;\n\n\n\nuse std::path::Path;\n\nuse std::process::Command;\n\nuse std::collections::{HashMap};\n\nuse std::sync::{Arc, Mutex};\n\nuse std::fs::File;\n\nuse std::io::Write;\n\nuse std::time::{Instant, Duration};\n\nuse std::collections::hash_map::DefaultHasher;\n\nuse std::hash::{Hash, Hasher};\n\nuse debugger::{ExitType, Debugger};\n\nuse guifuzz::*;\n\n\n", "file_path": "mesos/src/main.rs", "rank": 62, "score": 15.452913217763633 }, { "content": "mod debugger;\n\nmod minidump;\n\nmod sedebug;\n\nmod ffi_helpers;\n\nmod handles;\n\n\n\n// Make some things public\n\npub use debugger::{Debugger, ExitType, BreakpointType};\n", "file_path": "mesos/libs/debugger/src/lib.rs", "rank": 63, "score": 13.443141200389402 }, { "content": " MiniDumpWithModuleHeaders = 0x00080000,\n\n MiniDumpFilterTriage = 0x00100000,\n\n MiniDumpWithAvxXStateContext = 0x00200000,\n\n MiniDumpWithIptTrace = 0x00400000,\n\n MiniDumpValidTypeFlags = 0x007fffff,\n\n}\n\n\n\n#[link(name = \"dbghelp\")]\n\nextern \"system\" {\n\n pub fn MiniDumpWriteDump(hProcess: HANDLE, processId: u32,\n\n hFile: HANDLE, DumpType: u32,\n\n exception: *const MinidumpExceptionInformation,\n\n userstreamparam: usize,\n\n callbackParam: usize) -> i32;\n\n}\n\n\n\n#[repr(C, packed)]\n\n#[derive(Clone, Copy, Debug)]\n\npub struct MinidumpExceptionInformation {\n\n thread_id: u32,\n\n exception: *const EXCEPTION_POINTERS,\n\n client_pointers: u32,\n\n}\n\n\n\n/// Create a full minidump of a given process\n", "file_path": "mesos/libs/debugger/src/minidump.rs", "rank": 64, "score": 13.407594187031638 }, { "content": " /// `name` and `nameoff` are completely user controlled and are used to\n\n /// give this breakpoint a unique name. Often if used from mesos `name`\n\n /// will correspond to the function name and `nameoff` will be the offset\n\n /// into the function. However these can be whatever you like. It's only\n\n /// for readability of the coverage data\n\n pub fn register_breakpoint(&mut self, module: Arc<String>, offset: usize,\n\n name: Arc<String>, nameoff: usize, typ: BreakpointType,\n\n callback: Option<BreakpointCallback>) {\n\n // Create a new entry if none exists\n\n if !self.target_breakpoints.contains_key(&**module) {\n\n self.target_breakpoints.insert(module.to_string(), Vec::new());\n\n }\n\n\n\n if !self.minmax_breakpoint.contains_key(&**module) {\n\n self.minmax_breakpoint.insert(module.to_string(), (!0, 0));\n\n }\n\n\n\n let mmbp = self.minmax_breakpoint.get_mut(&**module).unwrap();\n\n mmbp.0 = std::cmp::min(mmbp.0, offset as usize);\n\n mmbp.1 = std::cmp::max(mmbp.1, offset as usize);\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 66, "score": 12.786233536604707 }, { "content": "use std::path::{Path, PathBuf};\n\nuse std::sync::Arc;\n\nuse debugger::{Debugger, BreakpointType};\n\n\n\n/// Grab a native-endianness u32 from a slice of u8s\n", "file_path": "mesos/src/mesofile.rs", "rank": 67, "score": 12.282540077467832 }, { "content": " callback: Option<BreakpointCallback>,\n\n\n\n /// Number of times this breakpoint has been hit\n\n freq: u64,\n\n}\n\n\n\n/// Debugger for a single process\n\npub struct Debugger<'a> {\n\n /// List of breakpoints we want to apply, keyed by module\n\n /// This is not the _active_ list of breakpoints, it only refers to things\n\n /// we would like to apply if we see this module show up\n\n target_breakpoints: HashMap<String, Vec<Breakpoint>>,\n\n\n\n /// List of potentially active breakpoints, keyed by linear address\n\n /// They may be optionally disabled via `Breakpoint.enabled`\n\n breakpoints: HashMap<usize, Breakpoint>,\n\n\n\n /// Tracks the minimum and maximum addresses for breakpoints per module\n\n minmax_breakpoint: HashMap<String, (usize, usize)>,\n\n\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 68, "score": 12.27250119513033 }, { "content": " win_inputs.as_mut_ptr(),\n\n std::mem::size_of::<Input>().try_into().unwrap())\n\n };\n\n\n\n if (res as usize) != inputs.len() {\n\n Err(Error::last_os_error())\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n\n\n fn press(&self, key: u16) -> io::Result<()> {\n\n self.keystream(&[\n\n KeyboardInput {\n\n vk: key,\n\n scan_code: 0,\n\n flags: 0,\n\n time: 0,\n\n extra_info: 0,\n\n },\n", "file_path": "fuzzer/src/main.rs", "rank": 70, "score": 11.076078052775479 }, { "content": " // Current module name state\n\n let module: &Arc<String> = cur_modname.as_ref().unwrap();\n\n\n\n // Function record\n\n let funcname_len = read!(u16);\n\n\n\n // Convert name to Rust str\n\n let funcname: Arc<String> =\n\n Arc::new(std::str::from_utf8(&ptr[..funcname_len as usize])\n\n .expect(\"Function name was not valid UTF-8\")\n\n .to_string());\n\n ptr = &ptr[funcname_len as usize..];\n\n\n\n // Get function offset from module base\n\n let funcoff = read!(u64) as usize;\n\n\n\n // Get number of basic blocks\n\n let num_blocks = read!(u32) as usize;\n\n\n\n // Iterate over all block offsets\n", "file_path": "mesos/src/mesofile.rs", "rank": 71, "score": 10.364343540900048 }, { "content": "\n\n /// TIDs actively single stepping mapped to the PC they stepped from\n\n single_step: HashMap<u32, usize>,\n\n\n\n /// Always do frequency tracking. Disables printing to screen and updates\n\n /// the coverage database on an interval to decrease I/O\n\n always_freq: bool,\n\n\n\n /// Last time we saved the coverage database\n\n last_db_save: Instant,\n\n\n\n /// Prints some more status information during runtime\n\n verbose: bool,\n\n\n\n /// Process ID of the process we're debugging\n\n pub pid: u32,\n\n\n\n /// Time we attached to the target at\n\n start_time: Instant,\n\n\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 72, "score": 10.298172964023257 }, { "content": " // FindWindow() failed, return out the corresponding error\n\n Err(Error::last_os_error())\n\n }\n\n }\n\n\n\n /// Get a random 64-bit number using xorshift\n\n fn rand(&self) -> usize {\n\n let mut seed = self.seed.get();\n\n seed ^= seed << 13;\n\n seed ^= seed >> 17;\n\n seed ^= seed << 43;\n\n self.seed.set(seed);\n\n seed as usize\n\n }\n\n\n\n fn keystream(&self, inputs: &[KeyboardInput]) -> io::Result<()> {\n\n // Generate an array to pass directly to `SendInput()`\n\n let mut win_inputs = Vec::new();\n\n\n\n // Create inputs based on each keyboard input\n", "file_path": "fuzzer/src/main.rs", "rank": 73, "score": 9.895106525807888 }, { "content": " buf.len() - offset, &mut bread) == 0 {\n\n // Return out on error\n\n return offset;\n\n }\n\n assert!(bread > 0);\n\n }\n\n\n\n offset += bread;\n\n }\n\n\n\n offset\n\n }\n\n\n\n /// Writes `buf` to `addr` in the process we're debugging\n\n /// Returns number of bytes written\n\n pub fn write_mem(&self, addr: usize, buf: &[u8]) -> usize {\n\n let mut offset = 0;\n\n\n\n // Write until complete\n\n while offset < buf.len() {\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 74, "score": 9.85927014020806 }, { "content": "use winapi::um::winnt::EXCEPTION_RECORD;\n\nuse winapi::um::errhandlingapi::GetLastError;\n\nuse winapi::um::minwinbase::CREATE_PROCESS_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::CREATE_THREAD_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::EXCEPTION_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::LOAD_DLL_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::EXIT_THREAD_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::EXIT_PROCESS_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::UNLOAD_DLL_DEBUG_EVENT;\n\nuse winapi::um::minwinbase::OUTPUT_DEBUG_STRING_EVENT;\n\nuse winapi::um::minwinbase::RIP_EVENT;\n\nuse winapi::shared::winerror::ERROR_SEM_TIMEOUT;\n\nuse winapi::um::debugapi::WaitForDebugEvent;\n\nuse winapi::um::debugapi::DebugActiveProcessStop;\n\nuse winapi::um::debugapi::DebugActiveProcess;\n\nuse winapi::um::debugapi::ContinueDebugEvent;\n\nuse winapi::um::processthreadsapi::GetProcessId;\n\nuse winapi::um::processthreadsapi::GetCurrentProcess;\n\nuse winapi::um::processthreadsapi::SetThreadContext;\n\nuse winapi::um::processthreadsapi::GetThreadContext;\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 75, "score": 9.63944029529771 }, { "content": " /// Kill the process via `TerminateProcess()`\n\n pub fn kill(&mut self) -> io::Result<()> {\n\n unsafe {\n\n if TerminateProcess(self.process_handle.unwrap(), 0) == 0 {\n\n Err(io::Error::last_os_error())\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n }\n\n\n\n /// Run the process forever\n\n pub fn run(&mut self) -> ExitType {\n\n let mut event = unsafe { std::mem::zeroed() };\n\n\n\n let mut hit_initial_break = false;\n\n\n\n unsafe { loop {\n\n // Flush the coverage database on an intervals\n\n if Instant::now().duration_since(self.last_db_save) >=\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 76, "score": 9.521228929188563 }, { "content": " coverage: HashMap::new(),\n\n minmax_breakpoint: HashMap::new(),\n\n modules: HashSet::new(),\n\n single_step: HashMap::new(),\n\n module_load_callbacks: Some(Vec::new()),\n\n debug_event_callbacks: Some(Vec::new()),\n\n always_freq: false,\n\n kill_requested: false,\n\n last_db_save: Instant::now(),\n\n verbose: false,\n\n bp_print: false,\n\n pid, start_time,\n\n\n\n context,\n\n _context_backing: context_backing, \n\n }\n\n }\n\n\n\n /// Get a list of all thread IDs currently active on this process\n\n pub fn get_thread_list(&self) -> Vec<u32> {\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 77, "score": 8.955090689595112 }, { "content": "/// Module containing utilities to create full minidumps of processes\n\n\n\nuse winapi::um::winnt::EXCEPTION_POINTERS;\n\nuse winapi::um::winnt::GENERIC_READ;\n\nuse winapi::um::winnt::GENERIC_WRITE;\n\nuse winapi::um::winnt::EXCEPTION_RECORD;\n\nuse winapi::um::fileapi::CREATE_NEW;\n\nuse winapi::um::winnt::HANDLE;\n\nuse winapi::um::fileapi::CreateFileW;\n\nuse winapi::um::handleapi::INVALID_HANDLE_VALUE;\n\nuse winapi::um::errhandlingapi::GetLastError;\n\nuse winapi::um::winnt::CONTEXT;\n\n\n\nuse std::path::Path;\n\nuse crate::handles::Handle;\n\nuse crate::ffi_helpers::win32_string;\n\n\n\n#[repr(C)]\n\n#[allow(dead_code)]\n\npub enum MinidumpType {\n", "file_path": "mesos/libs/debugger/src/minidump.rs", "rank": 78, "score": 8.612732329984231 }, { "content": " }\n\n\n\n pub fn set_always_freq(&mut self, val: bool) { self.always_freq = val; }\n\n pub fn set_verbose(&mut self, val: bool) { self.verbose = val; }\n\n pub fn set_bp_print(&mut self, val: bool) { self.bp_print = val; }\n\n\n\n /// Resolves the file name of a given memory mapped file in the target\n\n /// process\n\n fn filename_from_module_base(&self, base: usize) -> String {\n\n // Use GetMappedFileNameW() to get the mapped file name\n\n let mut buf = [0u16; 4096];\n\n let fnlen = unsafe {\n\n GetMappedFileNameW(self.process_handle(),\n\n base as *mut _, buf.as_mut_ptr(), buf.len() as u32)\n\n };\n\n assert!(fnlen != 0 && (fnlen as usize) < buf.len(),\n\n \"GetMappedFileNameW() failed\");\n\n\n\n // Convert the name to utf-8 and lowercase it\n\n let path = String::from_utf16(&buf[..fnlen as usize]).unwrap()\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 79, "score": 8.186144598207775 }, { "content": "/// High performance debugger for fuzzing and gathering code coverage on\n\n/// Windows\n\n\n\nuse std::io;\n\nuse std::time::{Duration, Instant};\n\nuse std::collections::{HashSet, HashMap};\n\nuse std::path::Path;\n\nuse std::sync::Arc;\n\nuse std::fs::File;\n\nuse std::ffi::CString;\n\nuse std::io::Write;\n\nuse std::io::BufWriter;\n\nuse std::sync::atomic::{AtomicBool, Ordering};\n\n\n\nuse winapi::um::memoryapi::ReadProcessMemory;\n\nuse winapi::um::memoryapi::WriteProcessMemory;\n\nuse winapi::um::winnt::CONTEXT;\n\nuse winapi::um::winnt::CONTEXT_ALL;\n\nuse winapi::um::winnt::DBG_CONTINUE;\n\nuse winapi::um::winnt::DBG_EXCEPTION_NOT_HANDLED;\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 80, "score": 8.028531737367747 }, { "content": " self.thread_handles.keys().cloned().collect()\n\n }\n\n\n\n /// Register a function to be invoked on module loads\n\n pub fn register_modload_callback(&mut self, func: ModloadFunc) {\n\n self.module_load_callbacks.as_mut()\n\n .expect(\"Cannot add callback during callback\").push(func);\n\n }\n\n\n\n /// Register a function to be invoked on debug events\n\n pub fn register_debug_event_callback(&mut self, func: DebugEventFunc) {\n\n self.debug_event_callbacks.as_mut()\n\n .expect(\"Cannot add callback during callback\").push(func);\n\n }\n\n\n\n /// Registers a breakpoint for a specific file\n\n /// `module` is the name of the module we want to apply the breakpoint to,\n\n /// for example \"notepad.exe\", `offset` is the byte offset in this module\n\n /// to apply the breakpoint to\n\n /// \n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 81, "score": 7.8476188351029155 }, { "content": "/// Crate to provide a Drop wrapper for HANDLEs\n\n\n\nuse winapi::um::winnt::HANDLE;\n\nuse winapi::um::handleapi::CloseHandle;\n\n\n\n/// Wrapper on a HANDLE to provide Drop support to clean up handles\n\npub struct Handle(HANDLE);\n\n\n\nimpl Handle {\n\n /// Wrap up a HANDLE\n\n pub fn new(handle: HANDLE) -> Option<Handle> {\n\n // Return None if the handle is null\n\n if handle == std::ptr::null_mut() { return None; }\n\n\n\n Some(Handle(handle))\n\n }\n\n\n\n /// Gets the raw HANDLE value this `Handle` represents\n\n pub fn raw(&self) -> HANDLE {\n\n self.0\n", "file_path": "mesos/libs/debugger/src/handles.rs", "rank": 82, "score": 7.844238537127424 }, { "content": " // Save coverage to global coverage database\n\n stats.coverage_db.insert(key.clone(), fuzz_input.clone());\n\n }\n\n }\n\n }\n\n\n\n // Get access to global stats\n\n let mut stats = stats.lock().unwrap();\n\n\n\n // Update fuzz case count\n\n local_stats.fuzz_cases += 1;\n\n stats.fuzz_cases += 1;\n\n\n\n // Check if this case ended due to a crash\n\n if let ExitType::Crash(crashname) = exit_state {\n\n // Update crash information\n\n local_stats.crashes += 1;\n\n stats.crashes += 1;\n\n\n\n // Add the crashing input to the input databases\n", "file_path": "mesos/src/main.rs", "rank": 83, "score": 7.781000108066641 }, { "content": " assert!(fd != INVALID_HANDLE_VALUE, \"Failed to create dump file\");\n\n\n\n // Wrap up the HANDLE for drop tracking\n\n let fd = Handle::new(fd).expect(\"Failed to get handle to minidump\");\n\n\n\n let mei = MinidumpExceptionInformation {\n\n thread_id: tid,\n\n exception: &ep,\n\n client_pointers: 0,\n\n };\n\n\n\n // Take a minidump!\n\n let res = MiniDumpWriteDump(process, pid, fd.raw(), \n\n MinidumpType::MiniDumpWithFullMemory as u32 |\n\n MinidumpType::MiniDumpWithHandleData as u32,\n\n &mei, 0, 0);\n\n assert!(res != 0, \"MiniDumpWriteDump error: {}\\n\", GetLastError());\n\n }\n\n}\n", "file_path": "mesos/libs/debugger/src/minidump.rs", "rank": 84, "score": 7.738810125348477 }, { "content": " for &input in inputs.iter() {\n\n win_inputs.push(Input {\n\n typ: InputType::Keyboard,\n\n union: InputUnion {\n\n keyboard: input\n\n }\n\n });\n\n }\n\n\n\n let res = unsafe {\n\n SendInput(\n\n win_inputs.len().try_into().unwrap(),\n\n win_inputs.as_mut_ptr(),\n\n std::mem::size_of::<Input>().try_into().unwrap())\n\n };\n\n\n\n if (res as usize) != inputs.len() {\n\n Err(Error::last_os_error())\n\n } else {\n\n Ok(())\n", "file_path": "fuzzer/src/main.rs", "rank": 85, "score": 7.342714077477596 }, { "content": " local_stats.input_db.insert(fuzz_input.clone());\n\n if stats.input_db.insert(fuzz_input.clone()) {\n\n stats.input_list.push(fuzz_input.clone());\n\n\n\n record_input(fuzz_input.clone());\n\n\n\n // Update the action database with known-feasible\n\n // actions\n\n for &action in fuzz_input.iter() {\n\n if stats.unique_action_set.insert(action) {\n\n stats.unique_actions.push(action);\n\n }\n\n }\n\n }\n\n\n\n // Add the crash name and corresponding fuzz input to the crash\n\n // database\n\n local_stats.crash_db.insert(crashname.clone(), fuzz_input.clone());\n\n stats.crash_db.insert(crashname, fuzz_input.clone());\n\n }\n\n }\n\n}\n\n\n", "file_path": "mesos/src/main.rs", "rank": 86, "score": 7.3081763606158106 }, { "content": " /// Tracks if this breakpoint is currently active\n\n enabled: bool,\n\n\n\n /// Original byte that was at this location, only set if breakpoint was\n\n /// ever applied\n\n orig_byte: Option<u8>,\n\n\n\n /// Tracks if this breakpoint should stick around after it's hit once\n\n typ: BreakpointType,\n\n\n\n /// Name of the function this breakpoint is in\n\n funcname: Arc<String>,\n\n\n\n /// Offset into the function that this breakpoint addresses\n\n funcoff: usize,\n\n\n\n /// Module name\n\n modname: Arc<String>,\n\n\n\n /// Callback to invoke if this breakpoint is hit\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 87, "score": 7.281112761408915 }, { "content": " let der = WaitForDebugEvent(&mut event, 10);\n\n if der == 0 {\n\n if GetLastError() == ERROR_SEM_TIMEOUT {\n\n // Just drop timeouts\n\n continue;\n\n }\n\n\n\n panic!(\"WaitForDebugEvent() returned error : {}\",\n\n GetLastError());\n\n }\n\n\n\n let decs = self.debug_event_callbacks.take()\n\n .expect(\"Event without callbacks present\");\n\n // Invoke callbacks\n\n for de in decs.iter() {\n\n de(self, &event);\n\n }\n\n self.debug_event_callbacks = Some(decs);\n\n\n\n // Get the PID and TID for the event\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 88, "score": 7.183777152728178 }, { "content": " fuzz_input.clone());\n\n\n\n // Get access to global stats\n\n let mut stats = stats.lock().unwrap();\n\n if !stats.coverage_db.contains_key(&key) {\n\n // Save input to global input database\n\n if stats.input_db.insert(fuzz_input.clone()) {\n\n stats.input_list.push(fuzz_input.clone());\n\n \n\n record_input(fuzz_input.clone());\n\n\n\n // Update the action database with known-feasible\n\n // actions\n\n for &action in fuzz_input.iter() {\n\n if stats.unique_action_set.insert(action) {\n\n stats.unique_actions.push(action);\n\n }\n\n }\n\n }\n\n \n", "file_path": "mesos/src/main.rs", "rank": 90, "score": 6.6867031679713875 }, { "content": "use winapi::um::processthreadsapi::FlushInstructionCache;\n\nuse winapi::um::processthreadsapi::TerminateProcess;\n\nuse winapi::um::processthreadsapi::OpenProcess;\n\nuse winapi::um::processthreadsapi::CreateProcessA;\n\nuse winapi::um::wow64apiset::IsWow64Process;\n\nuse winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION;\n\nuse winapi::um::psapi::GetMappedFileNameW;\n\nuse winapi::um::winnt::HANDLE;\n\nuse winapi::um::minwinbase::DEBUG_EVENT;\n\nuse winapi::um::winbase::DEBUG_PROCESS;\n\nuse winapi::um::winbase::DEBUG_ONLY_THIS_PROCESS;\n\nuse winapi::um::consoleapi::SetConsoleCtrlHandler;\n\n\n\nuse crate::minidump::dump;\n\nuse crate::handles::Handle;\n\n\n\n/// Tracks if an exit has been requested via the Ctrl+C/Ctrl+Break handler\n\nstatic EXIT_REQUESTED: AtomicBool = AtomicBool::new(false);\n\n\n\n/// Function invoked on module loads\n\n/// (debugger, module filename, module base)\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 91, "score": 6.574477571853684 }, { "content": "\n\n KeyboardInput {\n\n vk: key,\n\n scan_code: 0,\n\n flags: KEYEVENTF_KEYUP,\n\n time: 0,\n\n extra_info: 0,\n\n },\n\n ])\n\n }\n\n\n\n fn alt_press(&self, key: u16) -> io::Result<()> {\n\n if key == KeyCode::Tab as u16 || key == b' ' as u16 {\n\n return Ok(());\n\n }\n\n\n\n self.keystream(&[\n\n KeyboardInput {\n\n vk: KeyCode::Alt as u16,\n\n scan_code: 0,\n", "file_path": "fuzzer/src/main.rs", "rank": 92, "score": 6.499128558364147 }, { "content": "use winapi::um::winnt::HANDLE;\n\nuse winapi::um::winnt::TOKEN_PRIVILEGES;\n\nuse winapi::um::winnt::TOKEN_ADJUST_PRIVILEGES;\n\nuse winapi::um::winnt::TOKEN_QUERY;\n\nuse winapi::um::winnt::SE_PRIVILEGE_ENABLED;\n\nuse winapi::um::processthreadsapi::OpenProcessToken;\n\nuse winapi::um::processthreadsapi::GetCurrentProcess;\n\nuse winapi::um::securitybaseapi::AdjustTokenPrivileges;\n\nuse winapi::um::winbase::LookupPrivilegeValueW;\n\nuse crate::ffi_helpers::win32_string;\n\nuse crate::handles::Handle;\n\n\n\n/// Enable SeDebugPrivilege so we can debug system services\n", "file_path": "mesos/libs/debugger/src/sedebug.rs", "rank": 93, "score": 6.498408972055326 }, { "content": " .to_lowercase();\n\n\n\n // Get the filename from the path\n\n Path::new(&path).file_name().unwrap().to_str().unwrap().into()\n\n }\n\n\n\n /// Reads from `addr` in the process we're debugging into `buf`\n\n /// Returns number of bytes read\n\n pub fn read_mem(&self, addr: usize, buf: &mut [u8]) -> usize {\n\n let mut offset = 0;\n\n\n\n // Read until complete\n\n while offset < buf.len() {\n\n let mut bread = 0;\n\n\n\n unsafe {\n\n // Issue a read\n\n if ReadProcessMemory(\n\n self.process_handle(), (addr + offset) as *mut _,\n\n buf.as_mut_ptr().offset(offset as isize) as *mut _,\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 94, "score": 6.416547043258152 }, { "content": "\n\n KeyboardInput {\n\n vk: KeyCode::Alt as u16,\n\n scan_code: 0,\n\n flags: KEYEVENTF_KEYUP,\n\n time: 0,\n\n extra_info: 0,\n\n },\n\n ])\n\n }\n\n\n\n fn ctrl_press(&self, key: u16) -> io::Result<()> {\n\n if key == 0x1B {\n\n return Ok(());\n\n }\n\n\n\n self.keystream(&[\n\n KeyboardInput {\n\n vk: KeyCode::Control as u16,\n\n scan_code: 0,\n", "file_path": "fuzzer/src/main.rs", "rank": 97, "score": 6.248544315887965 }, { "content": " }\n\n })\n\n };\n\n\n\n // Debug forever\n\n let exit_state = dbg.run();\n\n\n\n // Extra-kill the debuggee\n\n let _ = dbg.kill();\n\n\n\n // Swap coverage with the debugger and drop it so that the debugger\n\n // disconnects its resources from the debuggee so it can exit\n\n let mut coverage = HashMap::new();\n\n std::mem::swap(&mut dbg.coverage, &mut coverage);\n\n std::mem::drop(dbg);\n\n\n\n // Connect to the fuzzer thread and get the result\n\n let genres = thr.join();\n\n if genres.is_err() {\n\n continue;\n", "file_path": "mesos/src/main.rs", "rank": 98, "score": 6.239071576223962 }, { "content": " {:>20}+0x{:08x} | {}\\n\",\n\n self.coverage.len(), self.breakpoints.len(),\n\n freq,\n\n addr, bp.modname, bp.offset, funcoff);\n\n }\n\n\n\n self.get_context(tid);\n\n\n\n // Back up so we re-execute where the breakpoint was\n\n\n\n #[cfg(target_pointer_width = \"64\")]\n\n { self.context.Rip = addr as u64; }\n\n\n\n #[cfg(target_pointer_width = \"32\")]\n\n { self.context.Eip = addr as u32; }\n\n\n\n // Single step if this is a frequency instruction\n\n if self.always_freq || bp.typ == BreakpointType::Freq {\n\n // Set the trap flag\n\n self.context.EFlags |= 1 << 8;\n", "file_path": "mesos/libs/debugger/src/debugger.rs", "rank": 99, "score": 6.202414621586599 } ]
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// -------------------------------------------------------------------------------------------------\n\n// FFI\n\n// -------------------------------------------------------------------------------------------------\n\npub mod ffi {\n\n use libc::{c_char, c_int, c_short, c_uchar, c_uint, c_ushort, c_void};\n\n extern {\n\n pub fn eglGetProcAddress(proc_name: *const c_char) -> *const c_void;\n\n }\n\n}\n\n\n", "file_path": "src/egl.rs", "rank": 0, "score": 85045.84386228042 }, { "content": "fn he() {\n\n let xx = HH{ActiveTePtr: get_proc_address(\"glActiveTexture\") };\n\n}", "file_path": "src/egl.rs", "rank": 1, "score": 44237.31691414488 }, { "content": "fn missin() -> ! {\n\n panic!(\"\")\n\n}\n\n\n\nimpl HH {\n\n pub fn new() -> HH {\n\n HH {\n\n ActiveTePtr: 0 as *const c_void,\n\n }\n\n }\n\n}\n\n\n\n\n\n\n", "file_path": "src/egl.rs", "rank": 2, "score": 42214.19955579366 }, { "content": "\n\npub enum __GLsync {}\n\npub type GLsync = *const __GLsync;\n\n\n\npub type GLDEBUGPROC = extern \"system\" fn(\n\n source: GLenum,\n\n gl_type: GLenum,\n\n id: GLuint,\n\n severity: GLenum,\n\n length: GLsizei,\n\n message: *const GLchar,\n\n user_param: *mut c_void,\n\n);\n\npub type GLDEBUGPROCARB = extern \"system\" fn(\n\n source: GLenum,\n\n gl_type: GLenum,\n\n id: GLuint,\n\n severity: GLenum,\n\n length: GLsizei,\n\n message: *const GLchar,\n", "file_path": "src/types.rs", "rank": 3, "score": 36066.16808571352 }, { "content": " user_param: *mut c_void,\n\n);\n\npub type GLDEBUGPROCKHR = extern \"system\" fn(\n\n source: GLenum,\n\n gl_type: GLenum,\n\n id: GLuint,\n\n severity: GLenum,\n\n length: GLsizei,\n\n message: *const GLchar,\n\n user_param: *mut c_void,\n\n);\n\n\n\n// Vendor extension types\n\npub type GLDEBUGPROCAMD = extern \"system\" fn(\n\n id: GLuint,\n\n category: GLenum,\n\n severity: GLenum,\n\n length: GLsizei,\n\n message: *const GLchar,\n\n user_param: *mut c_void,\n\n);\n\npub type GLhalfNV = c_ushort;\n\npub type GLvdpauSurfaceNV = GLintptr;\n", "file_path": "src/types.rs", "rank": 4, "score": 36060.16602620013 }, { "content": "use libc::{c_char, c_int, c_short, c_uchar, c_uint, c_ushort, c_void, c_float};\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n// TYPES\n\n// -------------------------------------------------------------------------------------------------\n\npub type GLbitfield = c_uint;\n\npub type GLboolean = c_uchar;\n\npub type GLbyte = c_char;\n\npub type GLchar = c_char;\n\npub type GLclampf = c_float;\n\npub type GLenum = c_uint;\n\npub type GLfloat = c_float;\n\npub type GLint = c_int;\n\npub type GLshort = c_short;\n\npub type GLsizei = c_int;\n\npub type GLubyte = c_uchar;\n\npub type GLuint = c_uint;\n\npub type GLushort = c_ushort;\n\npub type GLvoid = c_void;\n\npub type GLcharARB = c_char;\n", "file_path": "src/types.rs", "rank": 5, "score": 36043.77840598519 }, { "content": "\n\n#[cfg(target_os = \"macos\")]\n\npub type GLhandleARB = *const c_void;\n\n#[cfg(not(target_os = \"macos\"))]\n\npub type GLhandleARB = c_uint;\n\n\n\npub type GLhalfARB = c_ushort;\n\npub type GLhalf = c_ushort;\n\n\n\n// Must be 32 bits\n\npub type GLfixed = GLint;\n\n\n\npub type GLintptr = isize;\n\npub type GLsizeiptr = isize;\n\npub type GLint64 = i64;\n\npub type GLuint64 = u64;\n\npub type GLintptrARB = isize;\n\npub type GLsizeiptrARB = isize;\n\npub type GLint64EXT = i64;\n\npub type GLuint64EXT = u64;\n", "file_path": "src/types.rs", "rank": 6, "score": 36039.26320420058 }, { "content": "pub const GL_DEBUG_SEVERITY_HIGH: types::GLenum = 0x9146;\n\npub const GL_DEBUG_SEVERITY_LOW: types::GLenum = 0x9148;\n\npub const GL_DEBUG_SEVERITY_MEDIUM: types::GLenum = 0x9147;\n\npub const GL_DEBUG_SEVERITY_NOTIFICATION: types::GLenum = 0x826B;\n\npub const GL_DEBUG_SOURCE_API: types::GLenum = 0x8246;\n\npub const GL_DEBUG_SOURCE_APPLICATION: types::GLenum = 0x824A;\n\npub const GL_DEBUG_SOURCE_OTHER: types::GLenum = 0x824B;\n\npub const GL_DEBUG_SOURCE_SHADER_COMPILER: types::GLenum = 0x8248;\n\npub const GL_DEBUG_SOURCE_THIRD_PARTY: types::GLenum = 0x8249;\n\npub const GL_DEBUG_SOURCE_WINDOW_SYSTEM: types::GLenum = 0x8247;\n\npub const GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: types::GLenum = 0x824D;\n\npub const GL_DEBUG_TYPE_ERROR: types::GLenum = 0x824C;\n\npub const GL_DEBUG_TYPE_MARKER: types::GLenum = 0x8268;\n\npub const GL_DEBUG_TYPE_OTHER: types::GLenum = 0x8251;\n\npub const GL_DEBUG_TYPE_PERFORMANCE: types::GLenum = 0x8250;\n\npub const GL_DEBUG_TYPE_POP_GROUP: types::GLenum = 0x826A;\n\npub const GL_DEBUG_TYPE_PORTABILITY: types::GLenum = 0x824F;\n\npub const GL_DEBUG_TYPE_PUSH_GROUP: types::GLenum = 0x8269;\n\npub const GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: types::GLenum = 0x824E;\n\npub const GL_DECR: types::GLenum = 0x1E03;\n", "file_path": "src/consts.rs", "rank": 7, "score": 35428.60200052613 }, { "content": "pub const GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90DB;\n\npub const GL_MAX_COMPUTE_SHARED_MEMORY_SIZE: types::GLenum = 0x8262;\n\npub const GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS: types::GLenum = 0x91BC;\n\npub const GL_MAX_COMPUTE_UNIFORM_BLOCKS: types::GLenum = 0x91BB;\n\npub const GL_MAX_COMPUTE_UNIFORM_COMPONENTS: types::GLenum = 0x8263;\n\npub const GL_MAX_COMPUTE_WORK_GROUP_COUNT: types::GLenum = 0x91BE;\n\npub const GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS: types::GLenum = 0x90EB;\n\npub const GL_MAX_COMPUTE_WORK_GROUP_SIZE: types::GLenum = 0x91BF;\n\npub const GL_MAX_CUBE_MAP_TEXTURE_SIZE: types::GLenum = 0x851C;\n\npub const GL_MAX_DEBUG_GROUP_STACK_DEPTH: types::GLenum = 0x826C;\n\npub const GL_MAX_DEBUG_LOGGED_MESSAGES: types::GLenum = 0x9144;\n\npub const GL_MAX_DEBUG_MESSAGE_LENGTH: types::GLenum = 0x9143;\n\npub const GL_MAX_DEPTH_TEXTURE_SAMPLES: types::GLenum = 0x910F;\n\npub const GL_MAX_DRAW_BUFFERS: types::GLenum = 0x8824;\n\npub const GL_MAX_ELEMENTS_INDICES: types::GLenum = 0x80E9;\n\npub const GL_MAX_ELEMENTS_VERTICES: types::GLenum = 0x80E8;\n\npub const GL_MAX_ELEMENT_INDEX: types::GLenum = 0x8D6B;\n\npub const GL_MAX_FRAGMENT_ATOMIC_COUNTERS: types::GLenum = 0x92D6;\n\npub const GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92D0;\n\npub const GL_MAX_FRAGMENT_IMAGE_UNIFORMS: types::GLenum = 0x90CE;\n", "file_path": "src/consts.rs", "rank": 8, "score": 35422.18160932218 }, { "content": "#![allow(\n\nnon_camel_case_types, non_snake_case, non_upper_case_globals, dead_code,\n\nmissing_copy_implementations, unused_imports\n\n)]\n\n\n\nuse types;\n\n\n\npub const GL_ACTIVE_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92D9;\n\npub const GL_ACTIVE_ATTRIBUTES: types::GLenum = 0x8B89;\n\npub const GL_ACTIVE_ATTRIBUTE_MAX_LENGTH: types::GLenum = 0x8B8A;\n\npub const GL_ACTIVE_PROGRAM: types::GLenum = 0x8259;\n\npub const GL_ACTIVE_RESOURCES: types::GLenum = 0x92F5;\n\npub const GL_ACTIVE_TEXTURE: types::GLenum = 0x84E0;\n\npub const GL_ACTIVE_UNIFORMS: types::GLenum = 0x8B86;\n\npub const GL_ACTIVE_UNIFORM_BLOCKS: types::GLenum = 0x8A36;\n\npub const GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH: types::GLenum = 0x8A35;\n\npub const GL_ACTIVE_UNIFORM_MAX_LENGTH: types::GLenum = 0x8B87;\n\npub const GL_ACTIVE_VARIABLES: types::GLenum = 0x9305;\n\npub const GL_ALIASED_LINE_WIDTH_RANGE: types::GLenum = 0x846E;\n\npub const GL_ALIASED_POINT_SIZE_RANGE: types::GLenum = 0x846D;\n", "file_path": "src/consts.rs", "rank": 9, "score": 35421.94220079713 }, { "content": "pub const GL_IMAGE_BINDING_ACCESS: types::GLenum = 0x8F3E;\n\npub const GL_IMAGE_BINDING_FORMAT: types::GLenum = 0x906E;\n\npub const GL_IMAGE_BINDING_LAYER: types::GLenum = 0x8F3D;\n\npub const GL_IMAGE_BINDING_LAYERED: types::GLenum = 0x8F3C;\n\npub const GL_IMAGE_BINDING_LEVEL: types::GLenum = 0x8F3B;\n\npub const GL_IMAGE_BINDING_NAME: types::GLenum = 0x8F3A;\n\npub const GL_IMAGE_BUFFER: types::GLenum = 0x9051;\n\npub const GL_IMAGE_CUBE: types::GLenum = 0x9050;\n\npub const GL_IMAGE_CUBE_MAP_ARRAY: types::GLenum = 0x9054;\n\npub const GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS: types::GLenum = 0x90C9;\n\npub const GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE: types::GLenum = 0x90C8;\n\npub const GL_IMAGE_FORMAT_COMPATIBILITY_TYPE: types::GLenum = 0x90C7;\n\npub const GL_IMPLEMENTATION_COLOR_READ_FORMAT: types::GLenum = 0x8B9B;\n\npub const GL_IMPLEMENTATION_COLOR_READ_TYPE: types::GLenum = 0x8B9A;\n\npub const GL_INCR: types::GLenum = 0x1E02;\n\npub const GL_INCR_WRAP: types::GLenum = 0x8507;\n\npub const GL_INFO_LOG_LENGTH: types::GLenum = 0x8B84;\n\npub const GL_INNOCENT_CONTEXT_RESET: types::GLenum = 0x8254;\n\npub const GL_INT: types::GLenum = 0x1404;\n\npub const GL_INTERLEAVED_ATTRIBS: types::GLenum = 0x8C8C;\n", "file_path": "src/consts.rs", "rank": 10, "score": 35421.41041874237 }, { "content": "pub const GL_SAMPLE_POSITION: types::GLenum = 0x8E50;\n\npub const GL_SAMPLE_SHADING: types::GLenum = 0x8C36;\n\npub const GL_SCISSOR_BOX: types::GLenum = 0x0C10;\n\npub const GL_SCISSOR_TEST: types::GLenum = 0x0C11;\n\npub const GL_SCREEN: types::GLenum = 0x9295;\n\npub const GL_SEPARATE_ATTRIBS: types::GLenum = 0x8C8D;\n\npub const GL_SHADER: types::GLenum = 0x82E1;\n\npub const GL_SHADER_BINARY_FORMATS: types::GLenum = 0x8DF8;\n\npub const GL_SHADER_COMPILER: types::GLenum = 0x8DFA;\n\npub const GL_SHADER_IMAGE_ACCESS_BARRIER_BIT: types::GLenum = 0x00000020;\n\npub const GL_SHADER_SOURCE_LENGTH: types::GLenum = 0x8B88;\n\npub const GL_SHADER_STORAGE_BARRIER_BIT: types::GLenum = 0x00002000;\n\npub const GL_SHADER_STORAGE_BLOCK: types::GLenum = 0x92E6;\n\npub const GL_SHADER_STORAGE_BUFFER: types::GLenum = 0x90D2;\n\npub const GL_SHADER_STORAGE_BUFFER_BINDING: types::GLenum = 0x90D3;\n\npub const GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT: types::GLenum = 0x90DF;\n\npub const GL_SHADER_STORAGE_BUFFER_SIZE: types::GLenum = 0x90D5;\n\npub const GL_SHADER_STORAGE_BUFFER_START: types::GLenum = 0x90D4;\n\npub const GL_SHADER_TYPE: types::GLenum = 0x8B4F;\n\npub const GL_SHADING_LANGUAGE_VERSION: types::GLenum = 0x8B8C;\n", "file_path": "src/consts.rs", "rank": 11, "score": 35421.073532951625 }, { "content": "pub const GL_MAX_GEOMETRY_UNIFORM_BLOCKS: types::GLenum = 0x8A2C;\n\npub const GL_MAX_GEOMETRY_UNIFORM_COMPONENTS: types::GLenum = 0x8DDF;\n\npub const GL_MAX_IMAGE_UNITS: types::GLenum = 0x8F38;\n\npub const GL_MAX_INTEGER_SAMPLES: types::GLenum = 0x9110;\n\npub const GL_MAX_LABEL_LENGTH: types::GLenum = 0x82E8;\n\npub const GL_MAX_NAME_LENGTH: types::GLenum = 0x92F6;\n\npub const GL_MAX_NUM_ACTIVE_VARIABLES: types::GLenum = 0x92F7;\n\npub const GL_MAX_PATCH_VERTICES: types::GLenum = 0x8E7D;\n\npub const GL_MAX_PROGRAM_TEXEL_OFFSET: types::GLenum = 0x8905;\n\npub const GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET: types::GLenum = 0x8E5F;\n\npub const GL_MAX_RENDERBUFFER_SIZE: types::GLenum = 0x84E8;\n\npub const GL_MAX_SAMPLES: types::GLenum = 0x8D57;\n\npub const GL_MAX_SAMPLE_MASK_WORDS: types::GLenum = 0x8E59;\n\npub const GL_MAX_SERVER_WAIT_TIMEOUT: types::GLenum = 0x9111;\n\npub const GL_MAX_SHADER_STORAGE_BLOCK_SIZE: types::GLenum = 0x90DE;\n\npub const GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS: types::GLenum = 0x90DD;\n\npub const GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS: types::GLenum = 0x92D3;\n\npub const GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92CD;\n\npub const GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS: types::GLenum = 0x90CB;\n\npub const GL_MAX_TESS_CONTROL_INPUT_COMPONENTS: types::GLenum = 0x886C;\n", "file_path": "src/consts.rs", "rank": 12, "score": 35419.819782082486 }, { "content": "pub const GL_TRANSFORM_FEEDBACK_ACTIVE: types::GLenum = 0x8E24;\n\npub const GL_TRANSFORM_FEEDBACK_BARRIER_BIT: types::GLenum = 0x00000800;\n\npub const GL_TRANSFORM_FEEDBACK_BINDING: types::GLenum = 0x8E25;\n\npub const GL_TRANSFORM_FEEDBACK_BUFFER: types::GLenum = 0x8C8E;\n\npub const GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: types::GLenum = 0x8C8F;\n\npub const GL_TRANSFORM_FEEDBACK_BUFFER_MODE: types::GLenum = 0x8C7F;\n\npub const GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: types::GLenum = 0x8C85;\n\npub const GL_TRANSFORM_FEEDBACK_BUFFER_START: types::GLenum = 0x8C84;\n\npub const GL_TRANSFORM_FEEDBACK_PAUSED: types::GLenum = 0x8E23;\n\npub const GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: types::GLenum = 0x8C88;\n\npub const GL_TRANSFORM_FEEDBACK_VARYING: types::GLenum = 0x92F4;\n\npub const GL_TRANSFORM_FEEDBACK_VARYINGS: types::GLenum = 0x8C83;\n\npub const GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH: types::GLenum = 0x8C76;\n\npub const GL_TRIANGLES: types::GLenum = 0x0004;\n\npub const GL_TRIANGLES_ADJACENCY: types::GLenum = 0x000C;\n\npub const GL_TRIANGLE_FAN: types::GLenum = 0x0006;\n\npub const GL_TRIANGLE_STRIP: types::GLenum = 0x0005;\n\npub const GL_TRIANGLE_STRIP_ADJACENCY: types::GLenum = 0x000D;\n\npub const GL_TRUE: types::GLboolean = 1;\n\npub const GL_TYPE: types::GLenum = 0x92FA;\n", "file_path": "src/consts.rs", "rank": 13, "score": 35419.79610748845 }, { "content": "pub const GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT: types::GLenum = 0x00000004;\n\npub const GL_CONTEXT_LOST: types::GLenum = 0x0507;\n\npub const GL_COPY_READ_BUFFER: types::GLenum = 0x8F36;\n\npub const GL_COPY_READ_BUFFER_BINDING: types::GLenum = 0x8F36;\n\npub const GL_COPY_WRITE_BUFFER: types::GLenum = 0x8F37;\n\npub const GL_COPY_WRITE_BUFFER_BINDING: types::GLenum = 0x8F37;\n\npub const GL_CULL_FACE: types::GLenum = 0x0B44;\n\npub const GL_CULL_FACE_MODE: types::GLenum = 0x0B45;\n\npub const GL_CURRENT_PROGRAM: types::GLenum = 0x8B8D;\n\npub const GL_CURRENT_QUERY: types::GLenum = 0x8865;\n\npub const GL_CURRENT_VERTEX_ATTRIB: types::GLenum = 0x8626;\n\npub const GL_CW: types::GLenum = 0x0900;\n\npub const GL_DARKEN: types::GLenum = 0x9297;\n\npub const GL_DEBUG_CALLBACK_FUNCTION: types::GLenum = 0x8244;\n\npub const GL_DEBUG_CALLBACK_USER_PARAM: types::GLenum = 0x8245;\n\npub const GL_DEBUG_GROUP_STACK_DEPTH: types::GLenum = 0x826D;\n\npub const GL_DEBUG_LOGGED_MESSAGES: types::GLenum = 0x9145;\n\npub const GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH: types::GLenum = 0x8243;\n\npub const GL_DEBUG_OUTPUT: types::GLenum = 0x92E0;\n\npub const GL_DEBUG_OUTPUT_SYNCHRONOUS: types::GLenum = 0x8242;\n", "file_path": "src/consts.rs", "rank": 14, "score": 35419.49446797806 }, { "content": "pub const GL_TEXTURE_MIN_LOD: types::GLenum = 0x813A;\n\npub const GL_TEXTURE_RED_SIZE: types::GLenum = 0x805C;\n\npub const GL_TEXTURE_RED_TYPE: types::GLenum = 0x8C10;\n\npub const GL_TEXTURE_SAMPLES: types::GLenum = 0x9106;\n\npub const GL_TEXTURE_SHARED_SIZE: types::GLenum = 0x8C3F;\n\npub const GL_TEXTURE_STENCIL_SIZE: types::GLenum = 0x88F1;\n\npub const GL_TEXTURE_SWIZZLE_A: types::GLenum = 0x8E45;\n\npub const GL_TEXTURE_SWIZZLE_B: types::GLenum = 0x8E44;\n\npub const GL_TEXTURE_SWIZZLE_G: types::GLenum = 0x8E43;\n\npub const GL_TEXTURE_SWIZZLE_R: types::GLenum = 0x8E42;\n\npub const GL_TEXTURE_UPDATE_BARRIER_BIT: types::GLenum = 0x00000100;\n\npub const GL_TEXTURE_WIDTH: types::GLenum = 0x1000;\n\npub const GL_TEXTURE_WRAP_R: types::GLenum = 0x8072;\n\npub const GL_TEXTURE_WRAP_S: types::GLenum = 0x2802;\n\npub const GL_TEXTURE_WRAP_T: types::GLenum = 0x2803;\n\npub const GL_TIMEOUT_EXPIRED: types::GLenum = 0x911B;\n\npub const GL_TIMEOUT_IGNORED: types::GLuint64 = 0xFFFFFFFFFFFFFFFF;\n\npub const GL_TOP_LEVEL_ARRAY_SIZE: types::GLenum = 0x930C;\n\npub const GL_TOP_LEVEL_ARRAY_STRIDE: types::GLenum = 0x930D;\n\npub const GL_TRANSFORM_FEEDBACK: types::GLenum = 0x8E22;\n", "file_path": "src/consts.rs", "rank": 15, "score": 35419.447410834066 }, { "content": "pub const GL_UNIFORM_NAME_LENGTH: types::GLenum = 0x8A39;\n\npub const GL_UNIFORM_OFFSET: types::GLenum = 0x8A3B;\n\npub const GL_UNIFORM_SIZE: types::GLenum = 0x8A38;\n\npub const GL_UNIFORM_TYPE: types::GLenum = 0x8A37;\n\npub const GL_UNKNOWN_CONTEXT_RESET: types::GLenum = 0x8255;\n\npub const GL_UNPACK_ALIGNMENT: types::GLenum = 0x0CF5;\n\npub const GL_UNPACK_IMAGE_HEIGHT: types::GLenum = 0x806E;\n\npub const GL_UNPACK_ROW_LENGTH: types::GLenum = 0x0CF2;\n\npub const GL_UNPACK_SKIP_IMAGES: types::GLenum = 0x806D;\n\npub const GL_UNPACK_SKIP_PIXELS: types::GLenum = 0x0CF4;\n\npub const GL_UNPACK_SKIP_ROWS: types::GLenum = 0x0CF3;\n\npub const GL_UNSIGNALED: types::GLenum = 0x9118;\n\npub const GL_UNSIGNED_BYTE: types::GLenum = 0x1401;\n\npub const GL_UNSIGNED_INT: types::GLenum = 0x1405;\n\npub const GL_UNSIGNED_INT_10F_11F_11F_REV: types::GLenum = 0x8C3B;\n\npub const GL_UNSIGNED_INT_24_8: types::GLenum = 0x84FA;\n\npub const GL_UNSIGNED_INT_2_10_10_10_REV: types::GLenum = 0x8368;\n\npub const GL_UNSIGNED_INT_5_9_9_9_REV: types::GLenum = 0x8C3E;\n\npub const GL_UNSIGNED_INT_ATOMIC_COUNTER: types::GLenum = 0x92DB;\n\npub const GL_UNSIGNED_INT_IMAGE_2D: types::GLenum = 0x9063;\n", "file_path": "src/consts.rs", "rank": 16, "score": 35419.37578239739 }, { "content": "pub const GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY: types::GLenum = 0x9105;\n\npub const GL_TEXTURE_BINDING_3D: types::GLenum = 0x806A;\n\npub const GL_TEXTURE_BINDING_BUFFER: types::GLenum = 0x8C2C;\n\npub const GL_TEXTURE_BINDING_CUBE_MAP: types::GLenum = 0x8514;\n\npub const GL_TEXTURE_BINDING_CUBE_MAP_ARRAY: types::GLenum = 0x900A;\n\npub const GL_TEXTURE_BLUE_SIZE: types::GLenum = 0x805E;\n\npub const GL_TEXTURE_BLUE_TYPE: types::GLenum = 0x8C12;\n\npub const GL_TEXTURE_BORDER_COLOR: types::GLenum = 0x1004;\n\npub const GL_TEXTURE_BUFFER: types::GLenum = 0x8C2A;\n\npub const GL_TEXTURE_BUFFER_BINDING: types::GLenum = 0x8C2A;\n\npub const GL_TEXTURE_BUFFER_DATA_STORE_BINDING: types::GLenum = 0x8C2D;\n\npub const GL_TEXTURE_BUFFER_OFFSET: types::GLenum = 0x919D;\n\npub const GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT: types::GLenum = 0x919F;\n\npub const GL_TEXTURE_BUFFER_SIZE: types::GLenum = 0x919E;\n\npub const GL_TEXTURE_COMPARE_FUNC: types::GLenum = 0x884D;\n\npub const GL_TEXTURE_COMPARE_MODE: types::GLenum = 0x884C;\n\npub const GL_TEXTURE_COMPRESSED: types::GLenum = 0x86A1;\n\npub const GL_TEXTURE_CUBE_MAP: types::GLenum = 0x8513;\n\npub const GL_TEXTURE_CUBE_MAP_ARRAY: types::GLenum = 0x9009;\n\npub const GL_TEXTURE_CUBE_MAP_NEGATIVE_X: types::GLenum = 0x8516;\n", "file_path": "src/consts.rs", "rank": 17, "score": 35419.25746250971 }, { "content": "pub const GL_NICEST: types::GLenum = 0x1102;\n\npub const GL_NONE: types::GLenum = 0;\n\npub const GL_NOTEQUAL: types::GLenum = 0x0205;\n\npub const GL_NO_ERROR: types::GLenum = 0;\n\npub const GL_NO_RESET_NOTIFICATION: types::GLenum = 0x8261;\n\npub const GL_NUM_ACTIVE_VARIABLES: types::GLenum = 0x9304;\n\npub const GL_NUM_COMPRESSED_TEXTURE_FORMATS: types::GLenum = 0x86A2;\n\npub const GL_NUM_EXTENSIONS: types::GLenum = 0x821D;\n\npub const GL_NUM_PROGRAM_BINARY_FORMATS: types::GLenum = 0x87FE;\n\npub const GL_NUM_SAMPLE_COUNTS: types::GLenum = 0x9380;\n\npub const GL_NUM_SHADER_BINARY_FORMATS: types::GLenum = 0x8DF9;\n\npub const GL_OBJECT_TYPE: types::GLenum = 0x9112;\n\npub const GL_OFFSET: types::GLenum = 0x92FC;\n\npub const GL_ONE: types::GLenum = 1;\n\npub const GL_ONE_MINUS_CONSTANT_ALPHA: types::GLenum = 0x8004;\n\npub const GL_ONE_MINUS_CONSTANT_COLOR: types::GLenum = 0x8002;\n\npub const GL_ONE_MINUS_DST_ALPHA: types::GLenum = 0x0305;\n\npub const GL_ONE_MINUS_DST_COLOR: types::GLenum = 0x0307;\n\npub const GL_ONE_MINUS_SRC_ALPHA: types::GLenum = 0x0303;\n\npub const GL_ONE_MINUS_SRC_COLOR: types::GLenum = 0x0301;\n", "file_path": "src/consts.rs", "rank": 18, "score": 35418.77305706194 }, { "content": "pub const GL_TEXTURE3: types::GLenum = 0x84C3;\n\npub const GL_TEXTURE30: types::GLenum = 0x84DE;\n\npub const GL_TEXTURE31: types::GLenum = 0x84DF;\n\npub const GL_TEXTURE4: types::GLenum = 0x84C4;\n\npub const GL_TEXTURE5: types::GLenum = 0x84C5;\n\npub const GL_TEXTURE6: types::GLenum = 0x84C6;\n\npub const GL_TEXTURE7: types::GLenum = 0x84C7;\n\npub const GL_TEXTURE8: types::GLenum = 0x84C8;\n\npub const GL_TEXTURE9: types::GLenum = 0x84C9;\n\npub const GL_TEXTURE_2D: types::GLenum = 0x0DE1;\n\npub const GL_TEXTURE_2D_ARRAY: types::GLenum = 0x8C1A;\n\npub const GL_TEXTURE_2D_MULTISAMPLE: types::GLenum = 0x9100;\n\npub const GL_TEXTURE_2D_MULTISAMPLE_ARRAY: types::GLenum = 0x9102;\n\npub const GL_TEXTURE_3D: types::GLenum = 0x806F;\n\npub const GL_TEXTURE_ALPHA_SIZE: types::GLenum = 0x805F;\n\npub const GL_TEXTURE_ALPHA_TYPE: types::GLenum = 0x8C13;\n\npub const GL_TEXTURE_BASE_LEVEL: types::GLenum = 0x813C;\n\npub const GL_TEXTURE_BINDING_2D: types::GLenum = 0x8069;\n\npub const GL_TEXTURE_BINDING_2D_ARRAY: types::GLenum = 0x8C1D;\n\npub const GL_TEXTURE_BINDING_2D_MULTISAMPLE: types::GLenum = 0x9104;\n", "file_path": "src/consts.rs", "rank": 19, "score": 35418.738084500095 }, { "content": "pub const GL_MAX_VERTEX_UNIFORM_COMPONENTS: types::GLenum = 0x8B4A;\n\npub const GL_MAX_VERTEX_UNIFORM_VECTORS: types::GLenum = 0x8DFB;\n\npub const GL_MAX_VIEWPORT_DIMS: types::GLenum = 0x0D3A;\n\npub const GL_MEDIUM_FLOAT: types::GLenum = 0x8DF1;\n\npub const GL_MEDIUM_INT: types::GLenum = 0x8DF4;\n\npub const GL_MIN: types::GLenum = 0x8007;\n\npub const GL_MINOR_VERSION: types::GLenum = 0x821C;\n\npub const GL_MIN_FRAGMENT_INTERPOLATION_OFFSET: types::GLenum = 0x8E5B;\n\npub const GL_MIN_PROGRAM_TEXEL_OFFSET: types::GLenum = 0x8904;\n\npub const GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET: types::GLenum = 0x8E5E;\n\npub const GL_MIN_SAMPLE_SHADING_VALUE: types::GLenum = 0x8C37;\n\npub const GL_MIRRORED_REPEAT: types::GLenum = 0x8370;\n\npub const GL_MULTIPLY: types::GLenum = 0x9294;\n\npub const GL_MULTISAMPLE_LINE_WIDTH_GRANULARITY: types::GLenum = 0x9382;\n\npub const GL_MULTISAMPLE_LINE_WIDTH_RANGE: types::GLenum = 0x9381;\n\npub const GL_NAME_LENGTH: types::GLenum = 0x92F9;\n\npub const GL_NEAREST: types::GLenum = 0x2600;\n\npub const GL_NEAREST_MIPMAP_LINEAR: types::GLenum = 0x2702;\n\npub const GL_NEAREST_MIPMAP_NEAREST: types::GLenum = 0x2700;\n\npub const GL_NEVER: types::GLenum = 0x0200;\n", "file_path": "src/consts.rs", "rank": 20, "score": 35418.633625726696 }, { "content": "pub const GL_UNDEFINED_VERTEX: types::GLenum = 0x8260;\n\npub const GL_UNIFORM: types::GLenum = 0x92E1;\n\npub const GL_UNIFORM_ARRAY_STRIDE: types::GLenum = 0x8A3C;\n\npub const GL_UNIFORM_BARRIER_BIT: types::GLenum = 0x00000004;\n\npub const GL_UNIFORM_BLOCK: types::GLenum = 0x92E2;\n\npub const GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS: types::GLenum = 0x8A42;\n\npub const GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES: types::GLenum = 0x8A43;\n\npub const GL_UNIFORM_BLOCK_BINDING: types::GLenum = 0x8A3F;\n\npub const GL_UNIFORM_BLOCK_DATA_SIZE: types::GLenum = 0x8A40;\n\npub const GL_UNIFORM_BLOCK_INDEX: types::GLenum = 0x8A3A;\n\npub const GL_UNIFORM_BLOCK_NAME_LENGTH: types::GLenum = 0x8A41;\n\npub const GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER: types::GLenum = 0x8A46;\n\npub const GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER: types::GLenum = 0x8A44;\n\npub const GL_UNIFORM_BUFFER: types::GLenum = 0x8A11;\n\npub const GL_UNIFORM_BUFFER_BINDING: types::GLenum = 0x8A28;\n\npub const GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: types::GLenum = 0x8A34;\n\npub const GL_UNIFORM_BUFFER_SIZE: types::GLenum = 0x8A2A;\n\npub const GL_UNIFORM_BUFFER_START: types::GLenum = 0x8A29;\n\npub const GL_UNIFORM_IS_ROW_MAJOR: types::GLenum = 0x8A3E;\n\npub const GL_UNIFORM_MATRIX_STRIDE: types::GLenum = 0x8A3D;\n", "file_path": "src/consts.rs", "rank": 21, "score": 35418.39297934993 }, { "content": "pub const GL_SHORT: types::GLenum = 0x1402;\n\npub const GL_SIGNALED: types::GLenum = 0x9119;\n\npub const GL_SIGNED_NORMALIZED: types::GLenum = 0x8F9C;\n\npub const GL_SOFTLIGHT: types::GLenum = 0x929C;\n\npub const GL_SRC_ALPHA: types::GLenum = 0x0302;\n\npub const GL_SRC_ALPHA_SATURATE: types::GLenum = 0x0308;\n\npub const GL_SRC_COLOR: types::GLenum = 0x0300;\n\npub const GL_SRGB: types::GLenum = 0x8C40;\n\npub const GL_SRGB8: types::GLenum = 0x8C41;\n\npub const GL_SRGB8_ALPHA8: types::GLenum = 0x8C43;\n\npub const GL_STACK_OVERFLOW: types::GLenum = 0x0503;\n\npub const GL_STACK_UNDERFLOW: types::GLenum = 0x0504;\n\npub const GL_STATIC_COPY: types::GLenum = 0x88E6;\n\npub const GL_STATIC_DRAW: types::GLenum = 0x88E4;\n\npub const GL_STATIC_READ: types::GLenum = 0x88E5;\n\npub const GL_STENCIL: types::GLenum = 0x1802;\n\npub const GL_STENCIL_ATTACHMENT: types::GLenum = 0x8D20;\n\npub const GL_STENCIL_BACK_FAIL: types::GLenum = 0x8801;\n\npub const GL_STENCIL_BACK_FUNC: types::GLenum = 0x8800;\n\npub const GL_STENCIL_BACK_PASS_DEPTH_FAIL: types::GLenum = 0x8802;\n", "file_path": "src/consts.rs", "rank": 22, "score": 35418.35498090757 }, { "content": "pub const GL_FRAMEBUFFER_DEFAULT_HEIGHT: types::GLenum = 0x9311;\n\npub const GL_FRAMEBUFFER_DEFAULT_LAYERS: types::GLenum = 0x9312;\n\npub const GL_FRAMEBUFFER_DEFAULT_SAMPLES: types::GLenum = 0x9313;\n\npub const GL_FRAMEBUFFER_DEFAULT_WIDTH: types::GLenum = 0x9310;\n\npub const GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: types::GLenum = 0x8CD6;\n\npub const GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: types::GLenum = 0x8CD9;\n\npub const GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: types::GLenum = 0x8DA8;\n\npub const GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: types::GLenum = 0x8CD7;\n\npub const GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: types::GLenum = 0x8D56;\n\npub const GL_FRAMEBUFFER_UNDEFINED: types::GLenum = 0x8219;\n\npub const GL_FRAMEBUFFER_UNSUPPORTED: types::GLenum = 0x8CDD;\n\npub const GL_FRONT: types::GLenum = 0x0404;\n\npub const GL_FRONT_AND_BACK: types::GLenum = 0x0408;\n\npub const GL_FRONT_FACE: types::GLenum = 0x0B46;\n\npub const GL_FUNC_ADD: types::GLenum = 0x8006;\n\npub const GL_FUNC_REVERSE_SUBTRACT: types::GLenum = 0x800B;\n\npub const GL_FUNC_SUBTRACT: types::GLenum = 0x800A;\n\npub const GL_GENERATE_MIPMAP_HINT: types::GLenum = 0x8192;\n\npub const GL_GEOMETRY_INPUT_TYPE: types::GLenum = 0x8917;\n\npub const GL_GEOMETRY_OUTPUT_TYPE: types::GLenum = 0x8918;\n", "file_path": "src/consts.rs", "rank": 23, "score": 35418.188738171164 }, { "content": "pub const GL_FLOAT: types::GLenum = 0x1406;\n\npub const GL_FLOAT_32_UNSIGNED_INT_24_8_REV: types::GLenum = 0x8DAD;\n\npub const GL_FLOAT_MAT2: types::GLenum = 0x8B5A;\n\npub const GL_FLOAT_MAT2x3: types::GLenum = 0x8B65;\n\npub const GL_FLOAT_MAT2x4: types::GLenum = 0x8B66;\n\npub const GL_FLOAT_MAT3: types::GLenum = 0x8B5B;\n\npub const GL_FLOAT_MAT3x2: types::GLenum = 0x8B67;\n\npub const GL_FLOAT_MAT3x4: types::GLenum = 0x8B68;\n\npub const GL_FLOAT_MAT4: types::GLenum = 0x8B5C;\n\npub const GL_FLOAT_MAT4x2: types::GLenum = 0x8B69;\n\npub const GL_FLOAT_MAT4x3: types::GLenum = 0x8B6A;\n\npub const GL_FLOAT_VEC2: types::GLenum = 0x8B50;\n\npub const GL_FLOAT_VEC3: types::GLenum = 0x8B51;\n\npub const GL_FLOAT_VEC4: types::GLenum = 0x8B52;\n\npub const GL_FRACTIONAL_EVEN: types::GLenum = 0x8E7C;\n\npub const GL_FRACTIONAL_ODD: types::GLenum = 0x8E7B;\n\npub const GL_FRAGMENT_INTERPOLATION_OFFSET_BITS: types::GLenum = 0x8E5D;\n\npub const GL_FRAGMENT_SHADER: types::GLenum = 0x8B30;\n\npub const GL_FRAGMENT_SHADER_BIT: types::GLenum = 0x00000002;\n\npub const GL_FRAGMENT_SHADER_DERIVATIVE_HINT: types::GLenum = 0x8B8B;\n", "file_path": "src/consts.rs", "rank": 24, "score": 35418.09002539128 }, { "content": "pub const GL_INT_2_10_10_10_REV: types::GLenum = 0x8D9F;\n\npub const GL_INT_IMAGE_2D: types::GLenum = 0x9058;\n\npub const GL_INT_IMAGE_2D_ARRAY: types::GLenum = 0x905E;\n\npub const GL_INT_IMAGE_3D: types::GLenum = 0x9059;\n\npub const GL_INT_IMAGE_BUFFER: types::GLenum = 0x905C;\n\npub const GL_INT_IMAGE_CUBE: types::GLenum = 0x905B;\n\npub const GL_INT_IMAGE_CUBE_MAP_ARRAY: types::GLenum = 0x905F;\n\npub const GL_INT_SAMPLER_2D: types::GLenum = 0x8DCA;\n\npub const GL_INT_SAMPLER_2D_ARRAY: types::GLenum = 0x8DCF;\n\npub const GL_INT_SAMPLER_2D_MULTISAMPLE: types::GLenum = 0x9109;\n\npub const GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: types::GLenum = 0x910C;\n\npub const GL_INT_SAMPLER_3D: types::GLenum = 0x8DCB;\n\npub const GL_INT_SAMPLER_BUFFER: types::GLenum = 0x8DD0;\n\npub const GL_INT_SAMPLER_CUBE: types::GLenum = 0x8DCC;\n\npub const GL_INT_SAMPLER_CUBE_MAP_ARRAY: types::GLenum = 0x900E;\n\npub const GL_INT_VEC2: types::GLenum = 0x8B53;\n\npub const GL_INT_VEC3: types::GLenum = 0x8B54;\n\npub const GL_INT_VEC4: types::GLenum = 0x8B55;\n\npub const GL_INVALID_ENUM: types::GLenum = 0x0500;\n\npub const GL_INVALID_FRAMEBUFFER_OPERATION: types::GLenum = 0x0506;\n", "file_path": "src/consts.rs", "rank": 25, "score": 35418.0526433924 }, { "content": "pub const GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: types::GLenum = 0x8518;\n\npub const GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: types::GLenum = 0x851A;\n\npub const GL_TEXTURE_CUBE_MAP_POSITIVE_X: types::GLenum = 0x8515;\n\npub const GL_TEXTURE_CUBE_MAP_POSITIVE_Y: types::GLenum = 0x8517;\n\npub const GL_TEXTURE_CUBE_MAP_POSITIVE_Z: types::GLenum = 0x8519;\n\npub const GL_TEXTURE_DEPTH: types::GLenum = 0x8071;\n\npub const GL_TEXTURE_DEPTH_SIZE: types::GLenum = 0x884A;\n\npub const GL_TEXTURE_DEPTH_TYPE: types::GLenum = 0x8C16;\n\npub const GL_TEXTURE_FETCH_BARRIER_BIT: types::GLenum = 0x00000008;\n\npub const GL_TEXTURE_FIXED_SAMPLE_LOCATIONS: types::GLenum = 0x9107;\n\npub const GL_TEXTURE_GREEN_SIZE: types::GLenum = 0x805D;\n\npub const GL_TEXTURE_GREEN_TYPE: types::GLenum = 0x8C11;\n\npub const GL_TEXTURE_HEIGHT: types::GLenum = 0x1001;\n\npub const GL_TEXTURE_IMMUTABLE_FORMAT: types::GLenum = 0x912F;\n\npub const GL_TEXTURE_IMMUTABLE_LEVELS: types::GLenum = 0x82DF;\n\npub const GL_TEXTURE_INTERNAL_FORMAT: types::GLenum = 0x1003;\n\npub const GL_TEXTURE_MAG_FILTER: types::GLenum = 0x2800;\n\npub const GL_TEXTURE_MAX_LEVEL: types::GLenum = 0x813D;\n\npub const GL_TEXTURE_MAX_LOD: types::GLenum = 0x813B;\n\npub const GL_TEXTURE_MIN_FILTER: types::GLenum = 0x2801;\n", "file_path": "src/consts.rs", "rank": 26, "score": 35418.04363504113 }, { "content": "pub const GL_UNSIGNED_SHORT_5_6_5: types::GLenum = 0x8363;\n\npub const GL_VALIDATE_STATUS: types::GLenum = 0x8B83;\n\npub const GL_VENDOR: types::GLenum = 0x1F00;\n\npub const GL_VERSION: types::GLenum = 0x1F02;\n\npub const GL_VERTEX_ARRAY: types::GLenum = 0x8074;\n\npub const GL_VERTEX_ARRAY_BINDING: types::GLenum = 0x85B5;\n\npub const GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT: types::GLenum = 0x00000001;\n\npub const GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: types::GLenum = 0x889F;\n\npub const GL_VERTEX_ATTRIB_ARRAY_DIVISOR: types::GLenum = 0x88FE;\n\npub const GL_VERTEX_ATTRIB_ARRAY_ENABLED: types::GLenum = 0x8622;\n\npub const GL_VERTEX_ATTRIB_ARRAY_INTEGER: types::GLenum = 0x88FD;\n\npub const GL_VERTEX_ATTRIB_ARRAY_NORMALIZED: types::GLenum = 0x886A;\n\npub const GL_VERTEX_ATTRIB_ARRAY_POINTER: types::GLenum = 0x8645;\n\npub const GL_VERTEX_ATTRIB_ARRAY_SIZE: types::GLenum = 0x8623;\n\npub const GL_VERTEX_ATTRIB_ARRAY_STRIDE: types::GLenum = 0x8624;\n\npub const GL_VERTEX_ATTRIB_ARRAY_TYPE: types::GLenum = 0x8625;\n\npub const GL_VERTEX_ATTRIB_BINDING: types::GLenum = 0x82D4;\n\npub const GL_VERTEX_ATTRIB_RELATIVE_OFFSET: types::GLenum = 0x82D5;\n\npub const GL_VERTEX_BINDING_BUFFER: types::GLenum = 0x8F4F;\n\npub const GL_VERTEX_BINDING_DIVISOR: types::GLenum = 0x82D6;\n\npub const GL_VERTEX_BINDING_OFFSET: types::GLenum = 0x82D7;\n\npub const GL_VERTEX_BINDING_STRIDE: types::GLenum = 0x82D8;\n\npub const GL_VERTEX_SHADER: types::GLenum = 0x8B31;\n\npub const GL_VERTEX_SHADER_BIT: types::GLenum = 0x00000001;\n\npub const GL_VIEWPORT: types::GLenum = 0x0BA2;\n\npub const GL_WAIT_FAILED: types::GLenum = 0x911D;\n\npub const GL_WRITE_ONLY: types::GLenum = 0x88B9;\n\npub const GL_ZERO: types::GLenum = 0;\n", "file_path": "src/consts.rs", "rank": 27, "score": 35418.03085873881 }, { "content": "pub const GL_FRAMEBUFFER: types::GLenum = 0x8D40;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: types::GLenum = 0x8215;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: types::GLenum = 0x8214;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: types::GLenum = 0x8210;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: types::GLenum = 0x8211;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: types::GLenum = 0x8216;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: types::GLenum = 0x8213;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_LAYERED: types::GLenum = 0x8DA7;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: types::GLenum = 0x8CD1;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: types::GLenum = 0x8CD0;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE: types::GLenum = 0x8212;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: types::GLenum = 0x8217;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: types::GLenum = 0x8CD3;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: types::GLenum = 0x8CD4;\n\npub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: types::GLenum = 0x8CD2;\n\npub const GL_FRAMEBUFFER_BARRIER_BIT: types::GLenum = 0x00000400;\n\npub const GL_FRAMEBUFFER_BINDING: types::GLenum = 0x8CA6;\n\npub const GL_FRAMEBUFFER_COMPLETE: types::GLenum = 0x8CD5;\n\npub const GL_FRAMEBUFFER_DEFAULT: types::GLenum = 0x8218;\n\npub const GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS: types::GLenum = 0x9314;\n", "file_path": "src/consts.rs", "rank": 28, "score": 35418.006949045586 }, { "content": "pub const GL_RG32F: types::GLenum = 0x8230;\n\npub const GL_RG32I: types::GLenum = 0x823B;\n\npub const GL_RG32UI: types::GLenum = 0x823C;\n\npub const GL_RG8: types::GLenum = 0x822B;\n\npub const GL_RG8I: types::GLenum = 0x8237;\n\npub const GL_RG8UI: types::GLenum = 0x8238;\n\npub const GL_RG8_SNORM: types::GLenum = 0x8F95;\n\npub const GL_RGB: types::GLenum = 0x1907;\n\npub const GL_RGB10_A2: types::GLenum = 0x8059;\n\npub const GL_RGB10_A2UI: types::GLenum = 0x906F;\n\npub const GL_RGB16F: types::GLenum = 0x881B;\n\npub const GL_RGB16I: types::GLenum = 0x8D89;\n\npub const GL_RGB16UI: types::GLenum = 0x8D77;\n\npub const GL_RGB32F: types::GLenum = 0x8815;\n\npub const GL_RGB32I: types::GLenum = 0x8D83;\n\npub const GL_RGB32UI: types::GLenum = 0x8D71;\n\npub const GL_RGB565: types::GLenum = 0x8D62;\n\npub const GL_RGB5_A1: types::GLenum = 0x8057;\n\npub const GL_RGB8: types::GLenum = 0x8051;\n\npub const GL_RGB8I: types::GLenum = 0x8D8F;\n", "file_path": "src/consts.rs", "rank": 29, "score": 35417.58091707966 }, { "content": "pub const GL_RGB8UI: types::GLenum = 0x8D7D;\n\npub const GL_RGB8_SNORM: types::GLenum = 0x8F96;\n\npub const GL_RGB9_E5: types::GLenum = 0x8C3D;\n\npub const GL_RGBA: types::GLenum = 0x1908;\n\npub const GL_RGBA16F: types::GLenum = 0x881A;\n\npub const GL_RGBA16I: types::GLenum = 0x8D88;\n\npub const GL_RGBA16UI: types::GLenum = 0x8D76;\n\npub const GL_RGBA32F: types::GLenum = 0x8814;\n\npub const GL_RGBA32I: types::GLenum = 0x8D82;\n\npub const GL_RGBA32UI: types::GLenum = 0x8D70;\n\npub const GL_RGBA4: types::GLenum = 0x8056;\n\npub const GL_RGBA8: types::GLenum = 0x8058;\n\npub const GL_RGBA8I: types::GLenum = 0x8D8E;\n\npub const GL_RGBA8UI: types::GLenum = 0x8D7C;\n\npub const GL_RGBA8_SNORM: types::GLenum = 0x8F97;\n\npub const GL_RGBA_INTEGER: types::GLenum = 0x8D99;\n\npub const GL_RGB_INTEGER: types::GLenum = 0x8D98;\n\npub const GL_RG_INTEGER: types::GLenum = 0x8228;\n\npub const GL_SAMPLER: types::GLenum = 0x82E6;\n\npub const GL_SAMPLER_2D: types::GLenum = 0x8B5E;\n", "file_path": "src/consts.rs", "rank": 30, "score": 35417.50457527392 }, { "content": "pub const GL_DIFFERENCE: types::GLenum = 0x929E;\n\npub const GL_DISPATCH_INDIRECT_BUFFER: types::GLenum = 0x90EE;\n\npub const GL_DISPATCH_INDIRECT_BUFFER_BINDING: types::GLenum = 0x90EF;\n\npub const GL_DITHER: types::GLenum = 0x0BD0;\n\npub const GL_DONT_CARE: types::GLenum = 0x1100;\n\npub const GL_DRAW_BUFFER0: types::GLenum = 0x8825;\n\npub const GL_DRAW_BUFFER1: types::GLenum = 0x8826;\n\npub const GL_DRAW_BUFFER10: types::GLenum = 0x882F;\n\npub const GL_DRAW_BUFFER11: types::GLenum = 0x8830;\n\npub const GL_DRAW_BUFFER12: types::GLenum = 0x8831;\n\npub const GL_DRAW_BUFFER13: types::GLenum = 0x8832;\n\npub const GL_DRAW_BUFFER14: types::GLenum = 0x8833;\n\npub const GL_DRAW_BUFFER15: types::GLenum = 0x8834;\n\npub const GL_DRAW_BUFFER2: types::GLenum = 0x8827;\n\npub const GL_DRAW_BUFFER3: types::GLenum = 0x8828;\n\npub const GL_DRAW_BUFFER4: types::GLenum = 0x8829;\n\npub const GL_DRAW_BUFFER5: types::GLenum = 0x882A;\n\npub const GL_DRAW_BUFFER6: types::GLenum = 0x882B;\n\npub const GL_DRAW_BUFFER7: types::GLenum = 0x882C;\n\npub const GL_DRAW_BUFFER8: types::GLenum = 0x882D;\n", "file_path": "src/consts.rs", "rank": 31, "score": 35417.477102174766 }, { "content": "pub const GL_BUFFER_MAPPED: types::GLenum = 0x88BC;\n\npub const GL_BUFFER_MAP_LENGTH: types::GLenum = 0x9120;\n\npub const GL_BUFFER_MAP_OFFSET: types::GLenum = 0x9121;\n\npub const GL_BUFFER_MAP_POINTER: types::GLenum = 0x88BD;\n\npub const GL_BUFFER_SIZE: types::GLenum = 0x8764;\n\npub const GL_BUFFER_UPDATE_BARRIER_BIT: types::GLenum = 0x00000200;\n\npub const GL_BUFFER_USAGE: types::GLenum = 0x8765;\n\npub const GL_BUFFER_VARIABLE: types::GLenum = 0x92E5;\n\npub const GL_BYTE: types::GLenum = 0x1400;\n\npub const GL_CCW: types::GLenum = 0x0901;\n\npub const GL_CLAMP_TO_BORDER: types::GLenum = 0x812D;\n\npub const GL_CLAMP_TO_EDGE: types::GLenum = 0x812F;\n\npub const GL_COLOR: types::GLenum = 0x1800;\n\npub const GL_COLORBURN: types::GLenum = 0x929A;\n\npub const GL_COLORDODGE: types::GLenum = 0x9299;\n\npub const GL_COLOR_ATTACHMENT0: types::GLenum = 0x8CE0;\n\npub const GL_COLOR_ATTACHMENT1: types::GLenum = 0x8CE1;\n\npub const GL_COLOR_ATTACHMENT10: types::GLenum = 0x8CEA;\n\npub const GL_COLOR_ATTACHMENT11: types::GLenum = 0x8CEB;\n\npub const GL_COLOR_ATTACHMENT12: types::GLenum = 0x8CEC;\n", "file_path": "src/consts.rs", "rank": 32, "score": 35417.45035417395 }, { "content": "pub const GL_DRAW_BUFFER9: types::GLenum = 0x882E;\n\npub const GL_DRAW_FRAMEBUFFER: types::GLenum = 0x8CA9;\n\npub const GL_DRAW_FRAMEBUFFER_BINDING: types::GLenum = 0x8CA6;\n\npub const GL_DRAW_INDIRECT_BUFFER: types::GLenum = 0x8F3F;\n\npub const GL_DRAW_INDIRECT_BUFFER_BINDING: types::GLenum = 0x8F43;\n\npub const GL_DST_ALPHA: types::GLenum = 0x0304;\n\npub const GL_DST_COLOR: types::GLenum = 0x0306;\n\npub const GL_DYNAMIC_COPY: types::GLenum = 0x88EA;\n\npub const GL_DYNAMIC_DRAW: types::GLenum = 0x88E8;\n\npub const GL_DYNAMIC_READ: types::GLenum = 0x88E9;\n\npub const GL_ELEMENT_ARRAY_BARRIER_BIT: types::GLenum = 0x00000002;\n\npub const GL_ELEMENT_ARRAY_BUFFER: types::GLenum = 0x8893;\n\npub const GL_ELEMENT_ARRAY_BUFFER_BINDING: types::GLenum = 0x8895;\n\npub const GL_EQUAL: types::GLenum = 0x0202;\n\npub const GL_EXCLUSION: types::GLenum = 0x92A0;\n\npub const GL_EXTENSIONS: types::GLenum = 0x1F03;\n\npub const GL_FALSE: types::GLboolean = 0;\n\npub const GL_FASTEST: types::GLenum = 0x1101;\n\npub const GL_FIRST_VERTEX_CONVENTION: types::GLenum = 0x8E4D;\n\npub const GL_FIXED: types::GLenum = 0x140C;\n", "file_path": "src/consts.rs", "rank": 33, "score": 35417.406672300946 }, { "content": "pub const GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED: types::GLenum = 0x8221;\n\npub const GL_PROGRAM: types::GLenum = 0x82E2;\n\npub const GL_PROGRAM_BINARY_FORMATS: types::GLenum = 0x87FF;\n\npub const GL_PROGRAM_BINARY_LENGTH: types::GLenum = 0x8741;\n\npub const GL_PROGRAM_BINARY_RETRIEVABLE_HINT: types::GLenum = 0x8257;\n\npub const GL_PROGRAM_INPUT: types::GLenum = 0x92E3;\n\npub const GL_PROGRAM_OUTPUT: types::GLenum = 0x92E4;\n\npub const GL_PROGRAM_PIPELINE: types::GLenum = 0x82E4;\n\npub const GL_PROGRAM_PIPELINE_BINDING: types::GLenum = 0x825A;\n\npub const GL_PROGRAM_SEPARABLE: types::GLenum = 0x8258;\n\npub const GL_QUADS: types::GLenum = 0x0007;\n\npub const GL_QUERY: types::GLenum = 0x82E3;\n\npub const GL_QUERY_RESULT: types::GLenum = 0x8866;\n\npub const GL_QUERY_RESULT_AVAILABLE: types::GLenum = 0x8867;\n\npub const GL_R11F_G11F_B10F: types::GLenum = 0x8C3A;\n\npub const GL_R16F: types::GLenum = 0x822D;\n\npub const GL_R16I: types::GLenum = 0x8233;\n\npub const GL_R16UI: types::GLenum = 0x8234;\n\npub const GL_R32F: types::GLenum = 0x822E;\n\npub const GL_R32I: types::GLenum = 0x8235;\n", "file_path": "src/consts.rs", "rank": 34, "score": 35417.398012848076 }, { "content": "pub const GL_OUT_OF_MEMORY: types::GLenum = 0x0505;\n\npub const GL_OVERLAY: types::GLenum = 0x9296;\n\npub const GL_PACK_ALIGNMENT: types::GLenum = 0x0D05;\n\npub const GL_PACK_ROW_LENGTH: types::GLenum = 0x0D02;\n\npub const GL_PACK_SKIP_PIXELS: types::GLenum = 0x0D04;\n\npub const GL_PACK_SKIP_ROWS: types::GLenum = 0x0D03;\n\npub const GL_PATCHES: types::GLenum = 0x000E;\n\npub const GL_PATCH_VERTICES: types::GLenum = 0x8E72;\n\npub const GL_PIXEL_BUFFER_BARRIER_BIT: types::GLenum = 0x00000080;\n\npub const GL_PIXEL_PACK_BUFFER: types::GLenum = 0x88EB;\n\npub const GL_PIXEL_PACK_BUFFER_BINDING: types::GLenum = 0x88ED;\n\npub const GL_PIXEL_UNPACK_BUFFER: types::GLenum = 0x88EC;\n\npub const GL_PIXEL_UNPACK_BUFFER_BINDING: types::GLenum = 0x88EF;\n\npub const GL_POINTS: types::GLenum = 0x0000;\n\npub const GL_POLYGON_OFFSET_FACTOR: types::GLenum = 0x8038;\n\npub const GL_POLYGON_OFFSET_FILL: types::GLenum = 0x8037;\n\npub const GL_POLYGON_OFFSET_UNITS: types::GLenum = 0x2A00;\n\npub const GL_PRIMITIVES_GENERATED: types::GLenum = 0x8C87;\n\npub const GL_PRIMITIVE_BOUNDING_BOX: types::GLenum = 0x92BE;\n\npub const GL_PRIMITIVE_RESTART_FIXED_INDEX: types::GLenum = 0x8D69;\n", "file_path": "src/consts.rs", "rank": 35, "score": 35417.31545191085 }, { "content": "pub const GL_SAMPLER_2D_ARRAY: types::GLenum = 0x8DC1;\n\npub const GL_SAMPLER_2D_ARRAY_SHADOW: types::GLenum = 0x8DC4;\n\npub const GL_SAMPLER_2D_MULTISAMPLE: types::GLenum = 0x9108;\n\npub const GL_SAMPLER_2D_MULTISAMPLE_ARRAY: types::GLenum = 0x910B;\n\npub const GL_SAMPLER_2D_SHADOW: types::GLenum = 0x8B62;\n\npub const GL_SAMPLER_3D: types::GLenum = 0x8B5F;\n\npub const GL_SAMPLER_BINDING: types::GLenum = 0x8919;\n\npub const GL_SAMPLER_BUFFER: types::GLenum = 0x8DC2;\n\npub const GL_SAMPLER_CUBE: types::GLenum = 0x8B60;\n\npub const GL_SAMPLER_CUBE_MAP_ARRAY: types::GLenum = 0x900C;\n\npub const GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW: types::GLenum = 0x900D;\n\npub const GL_SAMPLER_CUBE_SHADOW: types::GLenum = 0x8DC5;\n\npub const GL_SAMPLES: types::GLenum = 0x80A9;\n\npub const GL_SAMPLE_ALPHA_TO_COVERAGE: types::GLenum = 0x809E;\n\npub const GL_SAMPLE_BUFFERS: types::GLenum = 0x80A8;\n\npub const GL_SAMPLE_COVERAGE: types::GLenum = 0x80A0;\n\npub const GL_SAMPLE_COVERAGE_INVERT: types::GLenum = 0x80AB;\n\npub const GL_SAMPLE_COVERAGE_VALUE: types::GLenum = 0x80AA;\n\npub const GL_SAMPLE_MASK: types::GLenum = 0x8E51;\n\npub const GL_SAMPLE_MASK_VALUE: types::GLenum = 0x8E52;\n", "file_path": "src/consts.rs", "rank": 36, "score": 35417.26155253755 }, { "content": "pub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4: types::GLenum = 0x93D0;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4: types::GLenum = 0x93D1;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5: types::GLenum = 0x93D2;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5: types::GLenum = 0x93D3;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6: types::GLenum = 0x93D4;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5: types::GLenum = 0x93D5;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6: types::GLenum = 0x93D6;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8: types::GLenum = 0x93D7;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: types::GLenum = 0x9279;\n\npub const GL_COMPRESSED_SRGB8_ETC2: types::GLenum = 0x9275;\n\npub const GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: types::GLenum = 0x9277;\n\npub const GL_COMPRESSED_TEXTURE_FORMATS: types::GLenum = 0x86A3;\n\npub const GL_COMPUTE_SHADER: types::GLenum = 0x91B9;\n\npub const GL_COMPUTE_SHADER_BIT: types::GLenum = 0x00000020;\n\npub const GL_COMPUTE_WORK_GROUP_SIZE: types::GLenum = 0x8267;\n\npub const GL_CONDITION_SATISFIED: types::GLenum = 0x911C;\n\npub const GL_CONSTANT_ALPHA: types::GLenum = 0x8003;\n\npub const GL_CONSTANT_COLOR: types::GLenum = 0x8001;\n\npub const GL_CONTEXT_FLAGS: types::GLenum = 0x821E;\n\npub const GL_CONTEXT_FLAG_DEBUG_BIT: types::GLenum = 0x00000002;\n", "file_path": "src/consts.rs", "rank": 37, "score": 35417.15957294135 }, { "content": "pub const GL_MAX_FRAGMENT_INPUT_COMPONENTS: types::GLenum = 0x9125;\n\npub const GL_MAX_FRAGMENT_INTERPOLATION_OFFSET: types::GLenum = 0x8E5C;\n\npub const GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90DA;\n\npub const GL_MAX_FRAGMENT_UNIFORM_BLOCKS: types::GLenum = 0x8A2D;\n\npub const GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: types::GLenum = 0x8B49;\n\npub const GL_MAX_FRAGMENT_UNIFORM_VECTORS: types::GLenum = 0x8DFD;\n\npub const GL_MAX_FRAMEBUFFER_HEIGHT: types::GLenum = 0x9316;\n\npub const GL_MAX_FRAMEBUFFER_LAYERS: types::GLenum = 0x9317;\n\npub const GL_MAX_FRAMEBUFFER_SAMPLES: types::GLenum = 0x9318;\n\npub const GL_MAX_FRAMEBUFFER_WIDTH: types::GLenum = 0x9315;\n\npub const GL_MAX_GEOMETRY_ATOMIC_COUNTERS: types::GLenum = 0x92D5;\n\npub const GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92CF;\n\npub const GL_MAX_GEOMETRY_IMAGE_UNIFORMS: types::GLenum = 0x90CD;\n\npub const GL_MAX_GEOMETRY_INPUT_COMPONENTS: types::GLenum = 0x9123;\n\npub const GL_MAX_GEOMETRY_OUTPUT_COMPONENTS: types::GLenum = 0x9124;\n\npub const GL_MAX_GEOMETRY_OUTPUT_VERTICES: types::GLenum = 0x8DE0;\n\npub const GL_MAX_GEOMETRY_SHADER_INVOCATIONS: types::GLenum = 0x8E5A;\n\npub const GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90D7;\n\npub const GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS: types::GLenum = 0x8C29;\n\npub const GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS: types::GLenum = 0x8DE1;\n", "file_path": "src/consts.rs", "rank": 38, "score": 35417.11165988576 }, { "content": "pub const GL_MAX_TEXTURE_SIZE: types::GLenum = 0x0D33;\n\npub const GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: types::GLenum = 0x8C8A;\n\npub const GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: types::GLenum = 0x8C8B;\n\npub const GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: types::GLenum = 0x8C80;\n\npub const GL_MAX_UNIFORM_BLOCK_SIZE: types::GLenum = 0x8A30;\n\npub const GL_MAX_UNIFORM_BUFFER_BINDINGS: types::GLenum = 0x8A2F;\n\npub const GL_MAX_UNIFORM_LOCATIONS: types::GLenum = 0x826E;\n\npub const GL_MAX_VARYING_COMPONENTS: types::GLenum = 0x8B4B;\n\npub const GL_MAX_VARYING_VECTORS: types::GLenum = 0x8DFC;\n\npub const GL_MAX_VERTEX_ATOMIC_COUNTERS: types::GLenum = 0x92D2;\n\npub const GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92CC;\n\npub const GL_MAX_VERTEX_ATTRIBS: types::GLenum = 0x8869;\n\npub const GL_MAX_VERTEX_ATTRIB_BINDINGS: types::GLenum = 0x82DA;\n\npub const GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET: types::GLenum = 0x82D9;\n\npub const GL_MAX_VERTEX_ATTRIB_STRIDE: types::GLenum = 0x82E5;\n\npub const GL_MAX_VERTEX_IMAGE_UNIFORMS: types::GLenum = 0x90CA;\n\npub const GL_MAX_VERTEX_OUTPUT_COMPONENTS: types::GLenum = 0x9122;\n\npub const GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90D6;\n\npub const GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: types::GLenum = 0x8B4C;\n\npub const GL_MAX_VERTEX_UNIFORM_BLOCKS: types::GLenum = 0x8A2B;\n", "file_path": "src/consts.rs", "rank": 39, "score": 35417.05276189904 }, { "content": "pub const GL_TEXTURE11: types::GLenum = 0x84CB;\n\npub const GL_TEXTURE12: types::GLenum = 0x84CC;\n\npub const GL_TEXTURE13: types::GLenum = 0x84CD;\n\npub const GL_TEXTURE14: types::GLenum = 0x84CE;\n\npub const GL_TEXTURE15: types::GLenum = 0x84CF;\n\npub const GL_TEXTURE16: types::GLenum = 0x84D0;\n\npub const GL_TEXTURE17: types::GLenum = 0x84D1;\n\npub const GL_TEXTURE18: types::GLenum = 0x84D2;\n\npub const GL_TEXTURE19: types::GLenum = 0x84D3;\n\npub const GL_TEXTURE2: types::GLenum = 0x84C2;\n\npub const GL_TEXTURE20: types::GLenum = 0x84D4;\n\npub const GL_TEXTURE21: types::GLenum = 0x84D5;\n\npub const GL_TEXTURE22: types::GLenum = 0x84D6;\n\npub const GL_TEXTURE23: types::GLenum = 0x84D7;\n\npub const GL_TEXTURE24: types::GLenum = 0x84D8;\n\npub const GL_TEXTURE25: types::GLenum = 0x84D9;\n\npub const GL_TEXTURE26: types::GLenum = 0x84DA;\n\npub const GL_TEXTURE27: types::GLenum = 0x84DB;\n\npub const GL_TEXTURE28: types::GLenum = 0x84DC;\n\npub const GL_TEXTURE29: types::GLenum = 0x84DD;\n", "file_path": "src/consts.rs", "rank": 40, "score": 35416.0474844022 }, { "content": "pub const GL_INVALID_INDEX: types::GLuint = 0xFFFFFFFF;\n\npub const GL_INVALID_OPERATION: types::GLenum = 0x0502;\n\npub const GL_INVALID_VALUE: types::GLenum = 0x0501;\n\npub const GL_INVERT: types::GLenum = 0x150A;\n\npub const GL_ISOLINES: types::GLenum = 0x8E7A;\n\npub const GL_IS_PER_PATCH: types::GLenum = 0x92E7;\n\npub const GL_IS_ROW_MAJOR: types::GLenum = 0x9300;\n\npub const GL_KEEP: types::GLenum = 0x1E00;\n\npub const GL_LAST_VERTEX_CONVENTION: types::GLenum = 0x8E4E;\n\npub const GL_LAYER_PROVOKING_VERTEX: types::GLenum = 0x825E;\n\npub const GL_LEQUAL: types::GLenum = 0x0203;\n\npub const GL_LESS: types::GLenum = 0x0201;\n\npub const GL_LIGHTEN: types::GLenum = 0x9298;\n\npub const GL_LINEAR: types::GLenum = 0x2601;\n\npub const GL_LINEAR_MIPMAP_LINEAR: types::GLenum = 0x2703;\n\npub const GL_LINEAR_MIPMAP_NEAREST: types::GLenum = 0x2701;\n\npub const GL_LINES: types::GLenum = 0x0001;\n\npub const GL_LINES_ADJACENCY: types::GLenum = 0x000A;\n\npub const GL_LINE_LOOP: types::GLenum = 0x0002;\n\npub const GL_LINE_STRIP: types::GLenum = 0x0003;\n", "file_path": "src/consts.rs", "rank": 41, "score": 35416.0426999266 }, { "content": "pub const GL_GEOMETRY_SHADER: types::GLenum = 0x8DD9;\n\npub const GL_GEOMETRY_SHADER_BIT: types::GLenum = 0x00000004;\n\npub const GL_GEOMETRY_SHADER_INVOCATIONS: types::GLenum = 0x887F;\n\npub const GL_GEOMETRY_VERTICES_OUT: types::GLenum = 0x8916;\n\npub const GL_GEQUAL: types::GLenum = 0x0206;\n\npub const GL_GREATER: types::GLenum = 0x0204;\n\npub const GL_GREEN: types::GLenum = 0x1904;\n\npub const GL_GREEN_BITS: types::GLenum = 0x0D53;\n\npub const GL_GUILTY_CONTEXT_RESET: types::GLenum = 0x8253;\n\npub const GL_HALF_FLOAT: types::GLenum = 0x140B;\n\npub const GL_HARDLIGHT: types::GLenum = 0x929B;\n\npub const GL_HIGH_FLOAT: types::GLenum = 0x8DF2;\n\npub const GL_HIGH_INT: types::GLenum = 0x8DF5;\n\npub const GL_HSL_COLOR: types::GLenum = 0x92AF;\n\npub const GL_HSL_HUE: types::GLenum = 0x92AD;\n\npub const GL_HSL_LUMINOSITY: types::GLenum = 0x92B0;\n\npub const GL_HSL_SATURATION: types::GLenum = 0x92AE;\n\npub const GL_IMAGE_2D: types::GLenum = 0x904D;\n\npub const GL_IMAGE_2D_ARRAY: types::GLenum = 0x9053;\n\npub const GL_IMAGE_3D: types::GLenum = 0x904E;\n", "file_path": "src/consts.rs", "rank": 42, "score": 35416.01666813206 }, { "content": "pub const GL_RENDERBUFFER: types::GLenum = 0x8D41;\n\npub const GL_RENDERBUFFER_ALPHA_SIZE: types::GLenum = 0x8D53;\n\npub const GL_RENDERBUFFER_BINDING: types::GLenum = 0x8CA7;\n\npub const GL_RENDERBUFFER_BLUE_SIZE: types::GLenum = 0x8D52;\n\npub const GL_RENDERBUFFER_DEPTH_SIZE: types::GLenum = 0x8D54;\n\npub const GL_RENDERBUFFER_GREEN_SIZE: types::GLenum = 0x8D51;\n\npub const GL_RENDERBUFFER_HEIGHT: types::GLenum = 0x8D43;\n\npub const GL_RENDERBUFFER_INTERNAL_FORMAT: types::GLenum = 0x8D44;\n\npub const GL_RENDERBUFFER_RED_SIZE: types::GLenum = 0x8D50;\n\npub const GL_RENDERBUFFER_SAMPLES: types::GLenum = 0x8CAB;\n\npub const GL_RENDERBUFFER_STENCIL_SIZE: types::GLenum = 0x8D55;\n\npub const GL_RENDERBUFFER_WIDTH: types::GLenum = 0x8D42;\n\npub const GL_RENDERER: types::GLenum = 0x1F01;\n\npub const GL_REPEAT: types::GLenum = 0x2901;\n\npub const GL_REPLACE: types::GLenum = 0x1E01;\n\npub const GL_RESET_NOTIFICATION_STRATEGY: types::GLenum = 0x8256;\n\npub const GL_RG: types::GLenum = 0x8227;\n\npub const GL_RG16F: types::GLenum = 0x822F;\n\npub const GL_RG16I: types::GLenum = 0x8239;\n\npub const GL_RG16UI: types::GLenum = 0x823A;\n", "file_path": "src/consts.rs", "rank": 43, "score": 35416.011985863915 }, { "content": "pub const GL_R32UI: types::GLenum = 0x8236;\n\npub const GL_R8: types::GLenum = 0x8229;\n\npub const GL_R8I: types::GLenum = 0x8231;\n\npub const GL_R8UI: types::GLenum = 0x8232;\n\npub const GL_R8_SNORM: types::GLenum = 0x8F94;\n\npub const GL_RASTERIZER_DISCARD: types::GLenum = 0x8C89;\n\npub const GL_READ_BUFFER: types::GLenum = 0x0C02;\n\npub const GL_READ_FRAMEBUFFER: types::GLenum = 0x8CA8;\n\npub const GL_READ_FRAMEBUFFER_BINDING: types::GLenum = 0x8CAA;\n\npub const GL_READ_ONLY: types::GLenum = 0x88B8;\n\npub const GL_READ_WRITE: types::GLenum = 0x88BA;\n\npub const GL_RED: types::GLenum = 0x1903;\n\npub const GL_RED_BITS: types::GLenum = 0x0D52;\n\npub const GL_RED_INTEGER: types::GLenum = 0x8D94;\n\npub const GL_REFERENCED_BY_COMPUTE_SHADER: types::GLenum = 0x930B;\n\npub const GL_REFERENCED_BY_FRAGMENT_SHADER: types::GLenum = 0x930A;\n\npub const GL_REFERENCED_BY_GEOMETRY_SHADER: types::GLenum = 0x9309;\n\npub const GL_REFERENCED_BY_TESS_CONTROL_SHADER: types::GLenum = 0x9307;\n\npub const GL_REFERENCED_BY_TESS_EVALUATION_SHADER: types::GLenum = 0x9308;\n\npub const GL_REFERENCED_BY_VERTEX_SHADER: types::GLenum = 0x9306;\n", "file_path": "src/consts.rs", "rank": 44, "score": 35416.011985863915 }, { "content": "pub const GL_BLEND: types::GLenum = 0x0BE2;\n\npub const GL_BLEND_COLOR: types::GLenum = 0x8005;\n\npub const GL_BLEND_DST_ALPHA: types::GLenum = 0x80CA;\n\npub const GL_BLEND_DST_RGB: types::GLenum = 0x80C8;\n\npub const GL_BLEND_EQUATION: types::GLenum = 0x8009;\n\npub const GL_BLEND_EQUATION_ALPHA: types::GLenum = 0x883D;\n\npub const GL_BLEND_EQUATION_RGB: types::GLenum = 0x8009;\n\npub const GL_BLEND_SRC_ALPHA: types::GLenum = 0x80CB;\n\npub const GL_BLEND_SRC_RGB: types::GLenum = 0x80C9;\n\npub const GL_BLOCK_INDEX: types::GLenum = 0x92FD;\n\npub const GL_BLUE: types::GLenum = 0x1905;\n\npub const GL_BLUE_BITS: types::GLenum = 0x0D54;\n\npub const GL_BOOL: types::GLenum = 0x8B56;\n\npub const GL_BOOL_VEC2: types::GLenum = 0x8B57;\n\npub const GL_BOOL_VEC3: types::GLenum = 0x8B58;\n\npub const GL_BOOL_VEC4: types::GLenum = 0x8B59;\n\npub const GL_BUFFER: types::GLenum = 0x82E0;\n\npub const GL_BUFFER_ACCESS_FLAGS: types::GLenum = 0x911F;\n\npub const GL_BUFFER_BINDING: types::GLenum = 0x9302;\n\npub const GL_BUFFER_DATA_SIZE: types::GLenum = 0x9303;\n", "file_path": "src/consts.rs", "rank": 45, "score": 35416.004991375004 }, { "content": "pub const GL_DECR_WRAP: types::GLenum = 0x8508;\n\npub const GL_DELETE_STATUS: types::GLenum = 0x8B80;\n\npub const GL_DEPTH: types::GLenum = 0x1801;\n\npub const GL_DEPTH24_STENCIL8: types::GLenum = 0x88F0;\n\npub const GL_DEPTH32F_STENCIL8: types::GLenum = 0x8CAD;\n\npub const GL_DEPTH_ATTACHMENT: types::GLenum = 0x8D00;\n\npub const GL_DEPTH_BITS: types::GLenum = 0x0D56;\n\npub const GL_DEPTH_BUFFER_BIT: types::GLenum = 0x00000100;\n\npub const GL_DEPTH_CLEAR_VALUE: types::GLenum = 0x0B73;\n\npub const GL_DEPTH_COMPONENT: types::GLenum = 0x1902;\n\npub const GL_DEPTH_COMPONENT16: types::GLenum = 0x81A5;\n\npub const GL_DEPTH_COMPONENT24: types::GLenum = 0x81A6;\n\npub const GL_DEPTH_COMPONENT32F: types::GLenum = 0x8CAC;\n\npub const GL_DEPTH_FUNC: types::GLenum = 0x0B74;\n\npub const GL_DEPTH_RANGE: types::GLenum = 0x0B70;\n\npub const GL_DEPTH_STENCIL: types::GLenum = 0x84F9;\n\npub const GL_DEPTH_STENCIL_ATTACHMENT: types::GLenum = 0x821A;\n\npub const GL_DEPTH_STENCIL_TEXTURE_MODE: types::GLenum = 0x90EA;\n\npub const GL_DEPTH_TEST: types::GLenum = 0x0B71;\n\npub const GL_DEPTH_WRITEMASK: types::GLenum = 0x0B72;\n", "file_path": "src/consts.rs", "rank": 46, "score": 35416.002667550856 }, { "content": "pub const GL_COLOR_ATTACHMENT13: types::GLenum = 0x8CED;\n\npub const GL_COLOR_ATTACHMENT14: types::GLenum = 0x8CEE;\n\npub const GL_COLOR_ATTACHMENT15: types::GLenum = 0x8CEF;\n\npub const GL_COLOR_ATTACHMENT16: types::GLenum = 0x8CF0;\n\npub const GL_COLOR_ATTACHMENT17: types::GLenum = 0x8CF1;\n\npub const GL_COLOR_ATTACHMENT18: types::GLenum = 0x8CF2;\n\npub const GL_COLOR_ATTACHMENT19: types::GLenum = 0x8CF3;\n\npub const GL_COLOR_ATTACHMENT2: types::GLenum = 0x8CE2;\n\npub const GL_COLOR_ATTACHMENT20: types::GLenum = 0x8CF4;\n\npub const GL_COLOR_ATTACHMENT21: types::GLenum = 0x8CF5;\n\npub const GL_COLOR_ATTACHMENT22: types::GLenum = 0x8CF6;\n\npub const GL_COLOR_ATTACHMENT23: types::GLenum = 0x8CF7;\n\npub const GL_COLOR_ATTACHMENT24: types::GLenum = 0x8CF8;\n\npub const GL_COLOR_ATTACHMENT25: types::GLenum = 0x8CF9;\n\npub const GL_COLOR_ATTACHMENT26: types::GLenum = 0x8CFA;\n\npub const GL_COLOR_ATTACHMENT27: types::GLenum = 0x8CFB;\n\npub const GL_COLOR_ATTACHMENT28: types::GLenum = 0x8CFC;\n\npub const GL_COLOR_ATTACHMENT29: types::GLenum = 0x8CFD;\n\npub const GL_COLOR_ATTACHMENT3: types::GLenum = 0x8CE3;\n\npub const GL_COLOR_ATTACHMENT30: types::GLenum = 0x8CFE;\n", "file_path": "src/consts.rs", "rank": 47, "score": 35416.000347547015 }, { "content": "pub const GL_ALL_BARRIER_BITS: types::GLenum = 0xFFFFFFFF;\n\npub const GL_ALL_SHADER_BITS: types::GLenum = 0xFFFFFFFF;\n\npub const GL_ALPHA: types::GLenum = 0x1906;\n\npub const GL_ALPHA_BITS: types::GLenum = 0x0D55;\n\npub const GL_ALREADY_SIGNALED: types::GLenum = 0x911A;\n\npub const GL_ALWAYS: types::GLenum = 0x0207;\n\npub const GL_ANY_SAMPLES_PASSED: types::GLenum = 0x8C2F;\n\npub const GL_ANY_SAMPLES_PASSED_CONSERVATIVE: types::GLenum = 0x8D6A;\n\npub const GL_ARRAY_BUFFER: types::GLenum = 0x8892;\n\npub const GL_ARRAY_BUFFER_BINDING: types::GLenum = 0x8894;\n\npub const GL_ARRAY_SIZE: types::GLenum = 0x92FB;\n\npub const GL_ARRAY_STRIDE: types::GLenum = 0x92FE;\n\npub const GL_ATOMIC_COUNTER_BARRIER_BIT: types::GLenum = 0x00001000;\n\npub const GL_ATOMIC_COUNTER_BUFFER: types::GLenum = 0x92C0;\n\npub const GL_ATOMIC_COUNTER_BUFFER_BINDING: types::GLenum = 0x92C1;\n\npub const GL_ATOMIC_COUNTER_BUFFER_INDEX: types::GLenum = 0x9301;\n\npub const GL_ATOMIC_COUNTER_BUFFER_SIZE: types::GLenum = 0x92C3;\n\npub const GL_ATOMIC_COUNTER_BUFFER_START: types::GLenum = 0x92C2;\n\npub const GL_ATTACHED_SHADERS: types::GLenum = 0x8B85;\n\npub const GL_BACK: types::GLenum = 0x0405;\n", "file_path": "src/consts.rs", "rank": 48, "score": 35415.99803135408 }, { "content": "pub const GL_LINE_STRIP_ADJACENCY: types::GLenum = 0x000B;\n\npub const GL_LINE_WIDTH: types::GLenum = 0x0B21;\n\npub const GL_LINK_STATUS: types::GLenum = 0x8B82;\n\npub const GL_LOCATION: types::GLenum = 0x930E;\n\npub const GL_LOSE_CONTEXT_ON_RESET: types::GLenum = 0x8252;\n\npub const GL_LOW_FLOAT: types::GLenum = 0x8DF0;\n\npub const GL_LOW_INT: types::GLenum = 0x8DF3;\n\npub const GL_LUMINANCE: types::GLenum = 0x1909;\n\npub const GL_LUMINANCE_ALPHA: types::GLenum = 0x190A;\n\npub const GL_MAJOR_VERSION: types::GLenum = 0x821B;\n\npub const GL_MAP_FLUSH_EXPLICIT_BIT: types::GLenum = 0x0010;\n\npub const GL_MAP_INVALIDATE_BUFFER_BIT: types::GLenum = 0x0008;\n\npub const GL_MAP_INVALIDATE_RANGE_BIT: types::GLenum = 0x0004;\n\npub const GL_MAP_READ_BIT: types::GLenum = 0x0001;\n\npub const GL_MAP_UNSYNCHRONIZED_BIT: types::GLenum = 0x0020;\n\npub const GL_MAP_WRITE_BIT: types::GLenum = 0x0002;\n\npub const GL_MATRIX_STRIDE: types::GLenum = 0x92FF;\n\npub const GL_MAX: types::GLenum = 0x8008;\n\npub const GL_MAX_3D_TEXTURE_SIZE: types::GLenum = 0x8073;\n\npub const GL_MAX_ARRAY_TEXTURE_LAYERS: types::GLenum = 0x88FF;\n", "file_path": "src/consts.rs", "rank": 49, "score": 35415.99803135408 }, { "content": "pub const GL_SUBPIXEL_BITS: types::GLenum = 0x0D50;\n\npub const GL_SYNC_CONDITION: types::GLenum = 0x9113;\n\npub const GL_SYNC_FENCE: types::GLenum = 0x9116;\n\npub const GL_SYNC_FLAGS: types::GLenum = 0x9115;\n\npub const GL_SYNC_FLUSH_COMMANDS_BIT: types::GLenum = 0x00000001;\n\npub const GL_SYNC_GPU_COMMANDS_COMPLETE: types::GLenum = 0x9117;\n\npub const GL_SYNC_STATUS: types::GLenum = 0x9114;\n\npub const GL_TESS_CONTROL_OUTPUT_VERTICES: types::GLenum = 0x8E75;\n\npub const GL_TESS_CONTROL_SHADER: types::GLenum = 0x8E88;\n\npub const GL_TESS_CONTROL_SHADER_BIT: types::GLenum = 0x00000008;\n\npub const GL_TESS_EVALUATION_SHADER: types::GLenum = 0x8E87;\n\npub const GL_TESS_EVALUATION_SHADER_BIT: types::GLenum = 0x00000010;\n\npub const GL_TESS_GEN_MODE: types::GLenum = 0x8E76;\n\npub const GL_TESS_GEN_POINT_MODE: types::GLenum = 0x8E79;\n\npub const GL_TESS_GEN_SPACING: types::GLenum = 0x8E77;\n\npub const GL_TESS_GEN_VERTEX_ORDER: types::GLenum = 0x8E78;\n\npub const GL_TEXTURE: types::GLenum = 0x1702;\n\npub const GL_TEXTURE0: types::GLenum = 0x84C0;\n\npub const GL_TEXTURE1: types::GLenum = 0x84C1;\n\npub const GL_TEXTURE10: types::GLenum = 0x84CA;\n", "file_path": "src/consts.rs", "rank": 50, "score": 35415.98880450414 }, { "content": "pub const GL_COLOR_ATTACHMENT31: types::GLenum = 0x8CFF;\n\npub const GL_COLOR_ATTACHMENT4: types::GLenum = 0x8CE4;\n\npub const GL_COLOR_ATTACHMENT5: types::GLenum = 0x8CE5;\n\npub const GL_COLOR_ATTACHMENT6: types::GLenum = 0x8CE6;\n\npub const GL_COLOR_ATTACHMENT7: types::GLenum = 0x8CE7;\n\npub const GL_COLOR_ATTACHMENT8: types::GLenum = 0x8CE8;\n\npub const GL_COLOR_ATTACHMENT9: types::GLenum = 0x8CE9;\n\npub const GL_COLOR_BUFFER_BIT: types::GLenum = 0x00004000;\n\npub const GL_COLOR_CLEAR_VALUE: types::GLenum = 0x0C22;\n\npub const GL_COLOR_WRITEMASK: types::GLenum = 0x0C23;\n\npub const GL_COMMAND_BARRIER_BIT: types::GLenum = 0x00000040;\n\npub const GL_COMPARE_REF_TO_TEXTURE: types::GLenum = 0x884E;\n\npub const GL_COMPILE_STATUS: types::GLenum = 0x8B81;\n\npub const GL_COMPRESSED_R11_EAC: types::GLenum = 0x9270;\n\npub const GL_COMPRESSED_RG11_EAC: types::GLenum = 0x9272;\n\npub const GL_COMPRESSED_RGB8_ETC2: types::GLenum = 0x9274;\n\npub const GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: types::GLenum = 0x9276;\n\npub const GL_COMPRESSED_RGBA8_ETC2_EAC: types::GLenum = 0x9278;\n\npub const GL_COMPRESSED_RGBA_ASTC_10x10: types::GLenum = 0x93BB;\n\npub const GL_COMPRESSED_RGBA_ASTC_10x5: types::GLenum = 0x93B8;\n", "file_path": "src/consts.rs", "rank": 51, "score": 35415.979637883516 }, { "content": "pub const GL_STENCIL_BACK_PASS_DEPTH_PASS: types::GLenum = 0x8803;\n\npub const GL_STENCIL_BACK_REF: types::GLenum = 0x8CA3;\n\npub const GL_STENCIL_BACK_VALUE_MASK: types::GLenum = 0x8CA4;\n\npub const GL_STENCIL_BACK_WRITEMASK: types::GLenum = 0x8CA5;\n\npub const GL_STENCIL_BITS: types::GLenum = 0x0D57;\n\npub const GL_STENCIL_BUFFER_BIT: types::GLenum = 0x00000400;\n\npub const GL_STENCIL_CLEAR_VALUE: types::GLenum = 0x0B91;\n\npub const GL_STENCIL_FAIL: types::GLenum = 0x0B94;\n\npub const GL_STENCIL_FUNC: types::GLenum = 0x0B92;\n\npub const GL_STENCIL_INDEX: types::GLenum = 0x1901;\n\npub const GL_STENCIL_INDEX8: types::GLenum = 0x8D48;\n\npub const GL_STENCIL_PASS_DEPTH_FAIL: types::GLenum = 0x0B95;\n\npub const GL_STENCIL_PASS_DEPTH_PASS: types::GLenum = 0x0B96;\n\npub const GL_STENCIL_REF: types::GLenum = 0x0B97;\n\npub const GL_STENCIL_TEST: types::GLenum = 0x0B90;\n\npub const GL_STENCIL_VALUE_MASK: types::GLenum = 0x0B93;\n\npub const GL_STENCIL_WRITEMASK: types::GLenum = 0x0B98;\n\npub const GL_STREAM_COPY: types::GLenum = 0x88E2;\n\npub const GL_STREAM_DRAW: types::GLenum = 0x88E0;\n\npub const GL_STREAM_READ: types::GLenum = 0x88E1;\n", "file_path": "src/consts.rs", "rank": 52, "score": 35415.97507697521 }, { "content": "pub const GL_UNSIGNED_INT_IMAGE_2D_ARRAY: types::GLenum = 0x9069;\n\npub const GL_UNSIGNED_INT_IMAGE_3D: types::GLenum = 0x9064;\n\npub const GL_UNSIGNED_INT_IMAGE_BUFFER: types::GLenum = 0x9067;\n\npub const GL_UNSIGNED_INT_IMAGE_CUBE: types::GLenum = 0x9066;\n\npub const GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: types::GLenum = 0x906A;\n\npub const GL_UNSIGNED_INT_SAMPLER_2D: types::GLenum = 0x8DD2;\n\npub const GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: types::GLenum = 0x8DD7;\n\npub const GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: types::GLenum = 0x910A;\n\npub const GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: types::GLenum = 0x910D;\n\npub const GL_UNSIGNED_INT_SAMPLER_3D: types::GLenum = 0x8DD3;\n\npub const GL_UNSIGNED_INT_SAMPLER_BUFFER: types::GLenum = 0x8DD8;\n\npub const GL_UNSIGNED_INT_SAMPLER_CUBE: types::GLenum = 0x8DD4;\n\npub const GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: types::GLenum = 0x900F;\n\npub const GL_UNSIGNED_INT_VEC2: types::GLenum = 0x8DC6;\n\npub const GL_UNSIGNED_INT_VEC3: types::GLenum = 0x8DC7;\n\npub const GL_UNSIGNED_INT_VEC4: types::GLenum = 0x8DC8;\n\npub const GL_UNSIGNED_NORMALIZED: types::GLenum = 0x8C17;\n\npub const GL_UNSIGNED_SHORT: types::GLenum = 0x1403;\n\npub const GL_UNSIGNED_SHORT_4_4_4_4: types::GLenum = 0x8033;\n\npub const GL_UNSIGNED_SHORT_5_5_5_1: types::GLenum = 0x8034;\n", "file_path": "src/consts.rs", "rank": 53, "score": 35415.9346879111 }, { "content": "pub const GL_COMPRESSED_RGBA_ASTC_10x6: types::GLenum = 0x93B9;\n\npub const GL_COMPRESSED_RGBA_ASTC_10x8: types::GLenum = 0x93BA;\n\npub const GL_COMPRESSED_RGBA_ASTC_12x10: types::GLenum = 0x93BC;\n\npub const GL_COMPRESSED_RGBA_ASTC_12x12: types::GLenum = 0x93BD;\n\npub const GL_COMPRESSED_RGBA_ASTC_4x4: types::GLenum = 0x93B0;\n\npub const GL_COMPRESSED_RGBA_ASTC_5x4: types::GLenum = 0x93B1;\n\npub const GL_COMPRESSED_RGBA_ASTC_5x5: types::GLenum = 0x93B2;\n\npub const GL_COMPRESSED_RGBA_ASTC_6x5: types::GLenum = 0x93B3;\n\npub const GL_COMPRESSED_RGBA_ASTC_6x6: types::GLenum = 0x93B4;\n\npub const GL_COMPRESSED_RGBA_ASTC_8x5: types::GLenum = 0x93B5;\n\npub const GL_COMPRESSED_RGBA_ASTC_8x6: types::GLenum = 0x93B6;\n\npub const GL_COMPRESSED_RGBA_ASTC_8x8: types::GLenum = 0x93B7;\n\npub const GL_COMPRESSED_SIGNED_R11_EAC: types::GLenum = 0x9271;\n\npub const GL_COMPRESSED_SIGNED_RG11_EAC: types::GLenum = 0x9273;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10: types::GLenum = 0x93DB;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5: types::GLenum = 0x93D8;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6: types::GLenum = 0x93D9;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8: types::GLenum = 0x93DA;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10: types::GLenum = 0x93DC;\n\npub const GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12: types::GLenum = 0x93DD;\n", "file_path": "src/consts.rs", "rank": 54, "score": 35415.90191147168 }, { "content": "pub const GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS: types::GLenum = 0x92DC;\n\npub const GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE: types::GLenum = 0x92D8;\n\npub const GL_MAX_COLOR_ATTACHMENTS: types::GLenum = 0x8CDF;\n\npub const GL_MAX_COLOR_TEXTURE_SAMPLES: types::GLenum = 0x910E;\n\npub const GL_MAX_COMBINED_ATOMIC_COUNTERS: types::GLenum = 0x92D7;\n\npub const GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92D1;\n\npub const GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS: types::GLenum = 0x8266;\n\npub const GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: types::GLenum = 0x8A33;\n\npub const GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS: types::GLenum = 0x8A32;\n\npub const GL_MAX_COMBINED_IMAGE_UNIFORMS: types::GLenum = 0x90CF;\n\npub const GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES: types::GLenum = 0x8F39;\n\npub const GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90DC;\n\npub const GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS: types::GLenum = 0x8E1E;\n\npub const GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS: types::GLenum = 0x8E1F;\n\npub const GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: types::GLenum = 0x8B4D;\n\npub const GL_MAX_COMBINED_UNIFORM_BLOCKS: types::GLenum = 0x8A2E;\n\npub const GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: types::GLenum = 0x8A31;\n\npub const GL_MAX_COMPUTE_ATOMIC_COUNTERS: types::GLenum = 0x8265;\n\npub const GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x8264;\n\npub const GL_MAX_COMPUTE_IMAGE_UNIFORMS: types::GLenum = 0x91BD;\n", "file_path": "src/consts.rs", "rank": 55, "score": 35415.878366888166 }, { "content": "pub const GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS: types::GLenum = 0x8E83;\n\npub const GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90D8;\n\npub const GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS: types::GLenum = 0x8E81;\n\npub const GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS: types::GLenum = 0x8E85;\n\npub const GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS: types::GLenum = 0x8E89;\n\npub const GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS: types::GLenum = 0x8E7F;\n\npub const GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS: types::GLenum = 0x92D4;\n\npub const GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS: types::GLenum = 0x92CE;\n\npub const GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS: types::GLenum = 0x90CC;\n\npub const GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS: types::GLenum = 0x886D;\n\npub const GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS: types::GLenum = 0x8E86;\n\npub const GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS: types::GLenum = 0x90D9;\n\npub const GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS: types::GLenum = 0x8E82;\n\npub const GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS: types::GLenum = 0x8E8A;\n\npub const GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS: types::GLenum = 0x8E80;\n\npub const GL_MAX_TESS_GEN_LEVEL: types::GLenum = 0x8E7E;\n\npub const GL_MAX_TESS_PATCH_COMPONENTS: types::GLenum = 0x8E84;\n\npub const GL_MAX_TEXTURE_BUFFER_SIZE: types::GLenum = 0x8C2B;\n\npub const GL_MAX_TEXTURE_IMAGE_UNITS: types::GLenum = 0x8872;\n\npub const GL_MAX_TEXTURE_LOD_BIAS: types::GLenum = 0x84FD;\n", "file_path": "src/consts.rs", "rank": 56, "score": 35415.86149781609 }, { "content": "\n\n pub fn gl_debug_message_insert(\n\n &mut self,\n\n source: GLenum,\n\n type_: GLenum,\n\n id: GLuint,\n\n severity: GLenum,\n\n length: GLsizei,\n\n buf: *const GLchar,\n\n ) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glDebugMessageInsert(source, type_, id, severity, length, buf);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_debug_message_callback(\n\n &mut self,\n\n callback: GLDEBUGPROC,\n\n userParam: *const GLvoid,\n", "file_path": "src/es32/wrapper.rs", "rank": 59, "score": 26.5143554470668 }, { "content": " dst_X, dst_Y, dst_Z, src_Width, src_Height, src_Depth,\n\n );\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_debug_message_control(\n\n &mut self,\n\n source: GLenum,\n\n type_: GLenum,\n\n severity: GLenum,\n\n count: GLsizei,\n\n ids: *const GLuint,\n\n enabled: GLboolean,\n\n ) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glDebugMessageControl(source, type_, severity, count, ids, enabled);\n\n }\n\n Ok(())\n\n }\n", "file_path": "src/es32/wrapper.rs", "rank": 60, "score": 26.254374105395957 }, { "content": " count,\n\n bufSize,\n\n sources,\n\n types,\n\n ids,\n\n severities,\n\n lengths,\n\n message_log,\n\n );\n\n Ok(result as u32)\n\n }\n\n }\n\n\n\n pub fn gl_push_debug_group(\n\n &mut self,\n\n source: GLenum,\n\n id: GLuint,\n\n length: GLsizei,\n\n message: *const GLchar,\n\n ) -> Result<(), Error> {\n", "file_path": "src/es32/wrapper.rs", "rank": 61, "score": 24.662568039407446 }, { "content": " ) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glDebugMessageCallback(callback, userParam);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_get_debug_message_Log(\n\n &mut self,\n\n count: GLuint,\n\n bufSize: GLsizei,\n\n sources: *mut GLenum,\n\n types: *mut GLenum,\n\n ids: *mut GLuint,\n\n severities: *mut GLenum,\n\n lengths: *mut GLsizei,\n\n message_log: *mut GLchar,\n\n ) -> Result<u32, Error> {\n\n unsafe {\n\n let result = ffi::glGetDebugMessageLog(\n", "file_path": "src/es32/wrapper.rs", "rank": 62, "score": 21.184562788020898 }, { "content": " source.as_mut_vec().as_mut_ptr() as *mut GLchar,\n\n );\n\n\n\n if length > 0 {\n\n source.as_mut_vec().set_len(length as usize);\n\n source.truncate(length as usize);\n\n\n\n Ok(source)\n\n } else {\n\n Ok(\"\".to_string())\n\n }\n\n }\n\n }\n\n\n\n pub fn gl_get_string(&mut self, name: ConstantType) -> Result<String, Error> {\n\n unsafe {\n\n let c_str = ffi::glGetString(name as GLenum);\n\n //todo : can't guarantee the lifetime, because the memory is allocated by C\n\n if !c_str.is_null() {\n\n match from_utf8(CStr::from_ptr(c_str as *const c_char).to_bytes()) {\n", "file_path": "src/es20/wrapper.rs", "rank": 63, "score": 17.89073305111534 }, { "content": " unsafe {\n\n ffi::glPushDebugGroup(source, id, length, message);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_pop_debug_group(&mut self) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glPopDebugGroup();\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_object_label(\n\n &mut self,\n\n identifier: GLenum,\n\n name: GLuint,\n\n length: GLsizei,\n\n label: *const GLchar,\n\n ) -> Result<(), Error> {\n", "file_path": "src/es32/wrapper.rs", "rank": 64, "score": 17.77930465053533 }, { "content": " name.truncate(length as usize);\n\n\n\n let type_ = DataType::from(uniform_data_type);\n\n\n\n Ok(Active {\n\n name,\n\n size,\n\n type_,\n\n length,\n\n })\n\n } else {\n\n // TODO: error desc\n\n Err(Error{})\n\n }\n\n }\n\n }\n\n\n\n pub fn gl_get_attached_shaders(&mut self, program: u32, max_count: i32) -> Result<Vec<u32>, Error> {\n\n unsafe {\n\n let mut count: GLsizei = 0;\n", "file_path": "src/es20/wrapper.rs", "rank": 66, "score": 15.992533905810772 }, { "content": "use enums::HintBehaviorType;\n\nuse enums::PackParamType;\n\nuse enums::PixelFormat;\n\nuse enums::PixelDataType;\n\nuse enums::ActionType;\n\nuse enums::DataType;\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n// STRUCTS\n\n// -------------------------------------------------------------------------------------------------\n\n\n\npub struct Active {\n\n pub name: String,\n\n pub size: i32,\n\n pub type_: DataType,\n\n pub length: i32,\n\n}\n\n\n\npub struct ShaderPrecisionFormat {\n\n pub precision: i32,\n", "file_path": "src/es20/wrapper.rs", "rank": 67, "score": 15.76131469131672 }, { "content": " let length: GLsizei = source.len() as GLsizei;\n\n\n\n ffi::glShaderSource(shader as GLuint, 1,\n\n &(source.as_ptr() as *const GLchar), &length)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_stencil_func(&mut self, func: FuncType, ref_: i32, mask: u32) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glStencilFunc(func as GLenum, ref_ as GLint, mask as GLuint)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_stencil_func_separate(&mut self, face: FaceMode, func: FuncType,\n\n ref_: i32, mask: u32) -> Result<(), Error> {\n\n unsafe {\n", "file_path": "src/es20/wrapper.rs", "rank": 68, "score": 15.678195855762558 }, { "content": "pub const GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH: GLuint = 33347;\n\npub const GL_DEBUG_CALLBACK_FUNCTION: GLuint = 33348;\n\npub const GL_DEBUG_CALLBACK_USER_PARAM: GLuint = 33349;\n\npub const GL_DEBUG_SOURCE_API: GLuint = 33350;\n\npub const GL_DEBUG_SOURCE_WINDOW_SYSTEM: GLuint = 33351;\n\npub const GL_DEBUG_SOURCE_SHADER_COMPILER: GLuint = 33352;\n\npub const GL_DEBUG_SOURCE_THIRD_PARTY: GLuint = 33353;\n\npub const GL_DEBUG_SOURCE_APPLICATION: GLuint = 33354;\n\npub const GL_DEBUG_SOURCE_OTHER: GLuint = 33355;\n\npub const GL_DEBUG_TYPE_ERROR: GLuint = 33356;\n\npub const GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: GLuint = 33357;\n\npub const GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: GLuint = 33358;\n\npub const GL_DEBUG_TYPE_PORTABILITY: GLuint = 33359;\n\npub const GL_DEBUG_TYPE_PERFORMANCE: GLuint = 33360;\n\npub const GL_DEBUG_TYPE_OTHER: GLuint = 33361;\n\npub const GL_DEBUG_TYPE_MARKER: GLuint = 33384;\n\npub const GL_DEBUG_TYPE_PUSH_GROUP: GLuint = 33385;\n\npub const GL_DEBUG_TYPE_POP_GROUP: GLuint = 33386;\n\npub const GL_DEBUG_SEVERITY_NOTIFICATION: GLuint = 33387;\n\npub const GL_MAX_DEBUG_GROUP_STACK_DEPTH: GLuint = 33388;\n", "file_path": "src/es32/data_struct.rs", "rank": 69, "score": 15.556531251139635 }, { "content": " size,\n\n type_: DataType::BOOL,\n\n length,\n\n })\n\n } else {\n\n Err(Error {})\n\n }\n\n }\n\n }\n\n\n\n pub fn gl_bind_transform_feedback(\n\n &mut self,\n\n target: TransformFeedbackObjectTarget,\n\n id: u32,\n\n ) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glBindTransformFeedback(target as GLenum, id as GLuint);\n\n }\n\n Ok(())\n\n }\n", "file_path": "src/es30/wrapper.rs", "rank": 70, "score": 14.593078348559885 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n // TODO: type_ & T is reasonable ?\n\n pub fn gl_draw_elements<T>(&mut self, mode: BeginMode, count: i32, type_: GLenum, indices: &[T]) -> Result<(), Error> where T: std::fmt::Debug + Clone {\n\n unsafe {\n\n ffi::glDrawElements(mode as GLenum, count as GLsizei,\n\n type_, indices.as_ptr() as *const GLvoid)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_enable(&mut self, feature: FeatureType) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glEnable(feature as GLenum)\n\n }\n\n\n\n Ok(())\n", "file_path": "src/es20/wrapper.rs", "rank": 71, "score": 14.581763884839713 }, { "content": "#![allow(\n\n non_camel_case_types, non_snake_case, non_upper_case_globals, dead_code,\n\n missing_copy_implementations, unused_imports\n\n)]\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n// DEPENDENCIES\n\n// -------------------------------------------------------------------------------------------------\n\nextern crate libc;\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n// DEPENDENCIES\n\n// -------------------------------------------------------------------------------------------------\n\n\n\nuse std::ffi::CStr;\n\nuse std::ffi::CString;\n\nuse std::mem::size_of;\n\nuse std::str::from_utf8;\n\n\n\nuse libc::{c_char, c_int, c_short, c_uchar, c_uint, c_ushort, c_void};\n", "file_path": "src/lib.rs", "rank": 72, "score": 13.813716148734892 }, { "content": "use std::result::Result;\n\n\n\nuse super::ffi;\n\nuse super::ffi::GLDEBUGPROC;\n\nuse consts::GL_TRUE;\n\nuse es20::wrapper::Error;\n\nuse types::*;\n\n\n\npub struct Wrapper {}\n\n\n\nimpl Wrapper {\n\n pub fn gl_blend_barrier(&mut self) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glBlendBarrier();\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_copy_image_sub_data(\n", "file_path": "src/es32/wrapper.rs", "rank": 73, "score": 13.05965678429569 }, { "content": "use types::*;\n\n\n\nextern \"C\" {\n\n pub fn glReadBuffer(mode: GLenum);\n\n\n\n pub fn glDrawRangeElements(\n\n mode: GLenum,\n\n start: GLuint,\n\n end: GLuint,\n\n count: GLsizei,\n\n type_: GLenum,\n\n indices: *const GLvoid,\n\n );\n\n\n\n pub fn glTexImage3D(\n\n target: GLenum,\n\n level: GLint,\n\n internalformat: GLint,\n\n width: GLsizei,\n\n height: GLsizei,\n", "file_path": "src/es30/ffi.rs", "rank": 74, "score": 12.918407742947087 }, { "content": " range.as_mut_ptr(),\n\n &mut precision,\n\n );\n\n }\n\n\n\n Ok(ShaderPrecisionFormat {\n\n precision: precision,\n\n range: range,\n\n })\n\n }\n\n\n\n pub fn gl_get_shader_source(&mut self, shader: u32, max_length: i32) -> Result<String, Error> {\n\n unsafe {\n\n let mut length: GLsizei = 0;\n\n let mut source = String::with_capacity(max_length as usize);\n\n\n\n ffi::glGetShaderSource(\n\n shader as GLuint,\n\n max_length as GLsizei,\n\n &mut length,\n", "file_path": "src/es20/wrapper.rs", "rank": 75, "score": 12.744418603464476 }, { "content": " }\n\n\n\n pub fn gl_create_shader(&mut self, type_: ShaderType) -> Result<u32, Error> {\n\n unsafe {\n\n let shader_id = ffi::glCreateShader(type_ as GLenum);\n\n\n\n Ok(shader_id as u32)\n\n }\n\n }\n\n\n\n pub fn gl_cull_face(&mut self, mode: FaceMode) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glCullFace(mode as GLenum)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_delete_buffers(&mut self, buffers: &[u32]) -> Result<(), Error> {\n\n unsafe {\n", "file_path": "src/es20/wrapper.rs", "rank": 76, "score": 12.412899378434403 }, { "content": "\n\n // TODO: data_format\n\n // TODO: length's unit should be byte or T ?\n\n pub fn gl_shader_binary<T>(&mut self, shaders: &[u32], data_format: GLenum,\n\n data: &[T], length: i32) -> Result<(), Error> where T: std::fmt::Debug + Clone {\n\n unsafe {\n\n ffi::glShaderBinary(\n\n shaders.len() as GLsizei,\n\n shaders.as_ptr(),\n\n data_format,\n\n data.as_ptr() as *const GLvoid,\n\n length as GLsizei,\n\n )\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_shader_source(&mut self, shader: u32, source: &str) -> Result<(), Error> {\n\n unsafe {\n", "file_path": "src/es20/wrapper.rs", "rank": 77, "score": 12.384061352604114 }, { "content": " pub fn gl_is_enabled(&mut self, feature: FeatureType) -> Result<bool, Error> {\n\n let mut res = false;\n\n\n\n unsafe {\n\n res = ffi::glIsEnabled(feature as GLenum) == GL_TRUE;\n\n }\n\n\n\n Ok(res)\n\n }\n\n\n\n pub fn gl_is_framebuffer(&mut self, framebuffer: u32) -> Result<bool, Error> {\n\n let mut res = false;\n\n\n\n unsafe {\n\n res = ffi::glIsFramebuffer(framebuffer as GLuint) == GL_TRUE;\n\n }\n\n\n\n Ok(res)\n\n }\n\n\n", "file_path": "src/es20/wrapper.rs", "rank": 78, "score": 11.845426966751244 }, { "content": "pub const GL_DEBUG_GROUP_STACK_DEPTH: GLuint = 33389;\n\npub const GL_BUFFER: GLuint = 33504;\n\npub const GL_SHADER: GLuint = 33505;\n\npub const GL_PROGRAM: GLuint = 33506;\n\npub const GL_VERTEX_ARRAY: GLuint = 32884;\n\npub const GL_QUERY: GLuint = 33507;\n\npub const GL_PROGRAM_PIPELINE: GLuint = 33508;\n\npub const GL_SAMPLER: GLuint = 33510;\n\npub const GL_MAX_LABEL_LENGTH: GLuint = 33512;\n\npub const GL_MAX_DEBUG_MESSAGE_LENGTH: GLuint = 37187;\n\npub const GL_MAX_DEBUG_LOGGED_MESSAGES: GLuint = 37188;\n\npub const GL_DEBUG_LOGGED_MESSAGES: GLuint = 37189;\n\npub const GL_DEBUG_SEVERITY_HIGH: GLuint = 37190;\n\npub const GL_DEBUG_SEVERITY_MEDIUM: GLuint = 37191;\n\npub const GL_DEBUG_SEVERITY_LOW: GLuint = 37192;\n\npub const GL_DEBUG_OUTPUT: GLuint = 37600;\n\npub const GL_CONTEXT_FLAG_DEBUG_BIT: GLuint = 2;\n\npub const GL_STACK_OVERFLOW: GLuint = 1283;\n\npub const GL_STACK_UNDERFLOW: GLuint = 1284;\n\npub const GL_GEOMETRY_SHADER: GLuint = 36313;\n", "file_path": "src/es32/data_struct.rs", "rank": 79, "score": 11.770422274849544 }, { "content": " INFO_LOG_LENGTH = GL_INFO_LOG_LENGTH as isize,\n\n SHADER_SOURCE_LENGTH = GL_SHADER_SOURCE_LENGTH as isize\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\npub enum ShaderPrecisionType {\n\n LOW_FLOAT = GL_LOW_FLOAT as isize,\n\n MEDIUM_FLOAT = GL_MEDIUM_FLOAT as isize,\n\n HIGH_FLOAT = GL_HIGH_FLOAT as isize,\n\n LOW_INT = GL_LOW_INT as isize,\n\n MEDIUM_INT = GL_MEDIUM_INT as isize,\n\n HIGH_INT = GL_HIGH_INT as isize,\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\npub enum ConstantType {\n\n VENDOR = GL_VENDOR as isize,\n\n RENDERER = GL_RENDERER as isize,\n\n VERSION = GL_VERSION as isize,\n\n SHADING_LANGUAGE_VERSION = GL_SHADING_LANGUAGE_VERSION as isize,\n", "file_path": "src/enums.rs", "rank": 80, "score": 11.513962496504915 }, { "content": "pub const GL_FLOAT_MAT4: GLuint = 0x8B5C;\n\npub const GL_SAMPLER_2D: GLuint = 0x8B5E;\n\npub const GL_SAMPLER_CUBE: GLuint = 0x8B60;\n\n\n\n// Vertex Arrays\n\npub const GL_VERTEX_ATTRIB_ARRAY_ENABLED: GLuint = 0x8622;\n\npub const GL_VERTEX_ATTRIB_ARRAY_SIZE: GLuint = 0x8623;\n\npub const GL_VERTEX_ATTRIB_ARRAY_STRIDE: GLuint = 0x8624;\n\npub const GL_VERTEX_ATTRIB_ARRAY_TYPE: GLuint = 0x8625;\n\npub const GL_VERTEX_ATTRIB_ARRAY_NORMALIZED: GLuint = 0x886A;\n\npub const GL_VERTEX_ATTRIB_ARRAY_POINTER: GLuint = 0x8645;\n\npub const GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLuint = 0x889F;\n\n\n\n// Read Format\n\npub const GL_IMPLEMENTATION_COLOR_READ_TYPE: GLuint = 0x8B9A;\n\npub const GL_IMPLEMENTATION_COLOR_READ_FORMAT: GLuint = 0x8B9B;\n\n\n\n// Shader Source\n\npub const GL_COMPILE_STATUS: GLuint = 0x8B81;\n\npub const GL_INFO_LOG_LENGTH: GLuint = 0x8B84;\n", "file_path": "src/es20/data_struct.rs", "rank": 81, "score": 11.374219058826618 }, { "content": " pub fn gl_disable(&mut self, feature: FeatureType) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glDisable(feature as GLenum)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_disable_vertex_attrib_array(&mut self, index: u32) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glDisableVertexAttribArray(index as GLuint)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_draw_arrays(&mut self, mode: BeginMode, first: i32, count: i32) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glDrawArrays(mode as GLenum, first as GLint, count as GLsizei)\n\n }\n", "file_path": "src/es20/wrapper.rs", "rank": 82, "score": 11.356164853997594 }, { "content": " unsafe {\n\n ffi::glUseProgramStages(pipeline, stages, program);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_active_shader_program(&mut self, pipeline: GLuint, program: GLuint) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glActiveShaderProgram(pipeline, program);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_create_shader_program_v(\n\n &mut self,\n\n type_: GLenum,\n\n count: GLsizei,\n\n strings: *const *const GLchar,\n\n ) -> Result<u32, Error> {\n\n unsafe {\n", "file_path": "src/es31/wrapper.rs", "rank": 83, "score": 11.135319360324642 }, { "content": " pub fn gl_transform_feedback_varyings(\n\n &mut self,\n\n program: u32,\n\n count: i32,\n\n varyings: &Vec<String>,\n\n buffer_mode: TransformFeedbackMode,\n\n ) -> Result<(), Error> {\n\n unsafe {\n\n let mut names: Vec<CString> = Vec::with_capacity(count as usize);\n\n let mut index = 0 as usize;\n\n while index < count as usize {\n\n names.push(CString::new(&(varyings[index])[..]).unwrap());\n\n index = index + 1;\n\n }\n\n index = 0;\n\n let ptr = names[index].as_ptr();\n\n let mut names_ptr: Vec<usize> = Vec::with_capacity(count as usize);\n\n\n\n while index < count as usize {\n\n names_ptr.push(names[index].as_ptr() as usize);\n", "file_path": "src/es30/wrapper.rs", "rank": 84, "score": 11.108562190636702 }, { "content": " pub fn gl_get_active_uniform(&mut self, program: u32, index: u32) -> Result<Active, Error> {\n\n unsafe {\n\n let mut length: GLsizei = 0;\n\n let mut size: GLint = 0;\n\n let mut uniform_data_type: GLenum = 0;\n\n\n\n let mut name = String::with_capacity(256);\n\n\n\n ffi::glGetActiveUniform(\n\n program as GLuint,\n\n index as GLuint,\n\n 256,\n\n &mut length,\n\n &mut size,\n\n &mut uniform_data_type,\n\n name.as_mut_vec().as_mut_ptr() as *mut GLchar,\n\n );\n\n\n\n if length > 0 {\n\n name.as_mut_vec().set_len(length as usize);\n", "file_path": "src/es20/wrapper.rs", "rank": 85, "score": 10.978658841340184 }, { "content": "use enums::TextureTarget;\n\nuse enums::ShaderType;\n\nuse enums::FaceMode;\n\nuse enums::FuncType;\n\nuse enums::FeatureType;\n\nuse enums::BeginMode;\n\nuse enums::FrameBufferAttachmentType;\n\nuse enums::FrontFaceDirection;\n\nuse enums::StateType;\n\nuse enums::BufferParamName;\n\nuse enums::ErrorType;\n\nuse enums::FrameBufferAttachmentParamType;\n\nuse enums::ProgramParamType;\n\nuse enums::RenderBufferParamType;\n\nuse enums::ShaderParamType;\n\nuse enums::ShaderPrecisionType;\n\nuse enums::ConstantType;\n\nuse enums::TextureParamType;\n\nuse enums::VertexAttributeParamType;\n\nuse enums::HintTargetType;\n", "file_path": "src/es20/wrapper.rs", "rank": 86, "score": 10.899765018594358 }, { "content": " pub fn gl_get_uniform_indices(\n\n &mut self,\n\n program: u32,\n\n uniform_count: i32,\n\n uniform_names: &Vec<String>,\n\n ) -> Result<Vec<GLuint>, Error> {\n\n unsafe {\n\n let mut names: Vec<CString> = Vec::with_capacity(uniform_count as usize);\n\n let mut index = 0 as usize;\n\n while index < uniform_count as usize {\n\n names.push(CString::new(&(uniform_names[index])[..]).unwrap());\n\n index = index + 1;\n\n }\n\n index = 0;\n\n let ptr = names[index].as_ptr();\n\n let mut names_ptr: Vec<usize> = Vec::with_capacity(uniform_count as usize);\n\n\n\n while index < uniform_count as usize {\n\n names_ptr.push(names[index].as_ptr() as usize);\n\n index = index + 1;\n", "file_path": "src/es30/wrapper.rs", "rank": 87, "score": 10.74107892133442 }, { "content": "use std;\n\nuse std::ffi::CStr;\n\nuse std::ffi::CString;\n\nuse std::mem;\n\nuse std::mem::size_of;\n\nuse std::ptr;\n\nuse std::slice;\n\nuse std::str::from_utf8;\n\n\n\nuse libc::c_char;\n\n\n\nuse super::data_struct::ProgramBinary;\n\nuse super::ffi;\n\nuse consts::*;\n\nuse enums::*;\n\nuse es20::wrapper::{Active, Error};\n\nuse types::*;\n\n\n\npub struct Wrapper {}\n\n\n", "file_path": "src/es30/wrapper.rs", "rank": 88, "score": 10.73086114577086 }, { "content": " }\n\n }\n\n\n\n pub fn gl_get_active_attrib(&mut self, program: u32, index: u32) -> Result<Active, Error> {\n\n unsafe {\n\n let mut length: GLsizei = 0;\n\n let mut size: GLint = 0;\n\n let mut attrib_type: GLenum = 0;\n\n\n\n let mut name = String::with_capacity(256);\n\n\n\n ffi::glGetActiveAttrib(\n\n program as GLuint,\n\n index as GLuint,\n\n 256,\n\n &mut length,\n\n &mut size,\n\n &mut attrib_type,\n\n name.as_mut_vec().as_mut_ptr() as *mut GLchar,\n\n );\n", "file_path": "src/es20/wrapper.rs", "rank": 89, "score": 10.681805101862272 }, { "content": " name as GLenum, &mut value);\n\n }\n\n\n\n Ok(value as i32)\n\n }\n\n\n\n pub fn gl_get_shaderiv(&mut self, shader: u32, name: ShaderParamType) -> Result<i32, Error> {\n\n let mut value: GLint = 0;\n\n\n\n unsafe {\n\n ffi::glGetShaderiv(shader as GLuint, name as GLenum, &mut value);\n\n }\n\n\n\n Ok(value as i32)\n\n }\n\n\n\n #[warn(unused_variables)]\n\n pub fn gl_get_shader_info_log(&mut self, shader: u32, max_length: i32) -> Result<String, Error> {\n\n unsafe {\n\n let mut length: GLsizei = 0;\n", "file_path": "src/es20/wrapper.rs", "rank": 90, "score": 10.646176922704187 }, { "content": " //todo : reference to program binary\n\n pub fn gl_map_buffer_range<'a, T>(\n\n &mut self,\n\n target: BufferObjectTarget,\n\n offset: GLintptr,\n\n length: GLsizeiptr,\n\n access: MappingBit,\n\n ) -> Result<&'a [T], Error> where T: std::fmt::Debug + Clone {\n\n unsafe {\n\n let ptr = ffi::glMapBufferRange(target as GLenum, offset, length, access as GLenum);\n\n\n\n let count = length as usize / std::mem::size_of::<T>();\n\n Ok(slice::from_raw_parts_mut(ptr as *mut T, count as usize))\n\n }\n\n }\n\n\n\n pub fn gl_flush_mapped_buffer_range(\n\n &mut self,\n\n target: BufferObjectTarget,\n\n offset: i32,\n", "file_path": "src/es30/wrapper.rs", "rank": 91, "score": 10.61027963168497 }, { "content": " }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_is_query(&mut self, id: u32) -> Result<GLboolean, Error> {\n\n unsafe {\n\n let result = ffi::glIsQuery(id as GLuint);\n\n Ok(result)\n\n }\n\n }\n\n\n\n pub fn gl_begin_query(&mut self, target: GLenum, id: u32) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glBeginQuery(target as GLenum, id as GLuint);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_end_query(&mut self, target: GLenum) -> Result<(), Error> {\n\n unsafe {\n", "file_path": "src/es30/wrapper.rs", "rank": 92, "score": 10.563898136139805 }, { "content": "\n\n// -------------------------------------------------------------------------------------------------\n\n// LINKING\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n#[cfg(target_os = \"android\")]\n\n#[link(name = \"GLESv2\")]\n\n#[link(name = \"EGL\")]\n\nextern \"C\" {}\n\n\n\n#[cfg(target_os = \"ios\")]\n\n#[link(name = \"OpenGLES\")]\n\nextern \"C\" {}\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n// MODULES\n\n// -------------------------------------------------------------------------------------------------\n\n\n\npub mod es20;\n\npub mod es30;\n\npub mod es31;\n\npub mod es32;\n\n\n\npub mod consts;\n\npub mod egl;\n\npub mod enums;\n\npub mod types;\n", "file_path": "src/lib.rs", "rank": 93, "score": 10.512881585145717 }, { "content": " }\n\n\n\n pub fn gl_enable_vertex_attrib_array(&mut self, index: u32) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glEnableVertexAttribArray(index as GLuint)\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_finish(&mut self) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glFinish()\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn gl_flush(&mut self) -> Result<(), Error> {\n\n unsafe {\n", "file_path": "src/es20/wrapper.rs", "rank": 94, "score": 10.4685264624489 }, { "content": " pub fn glSampleCoverage(value: GLclampf, invert: GLboolean);\n\n\n\n pub fn glScissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei);\n\n\n\n pub fn glShaderBinary(\n\n n: GLsizei,\n\n shaders: *const GLuint,\n\n binaryformat: GLenum,\n\n binary: *const GLvoid,\n\n length: GLsizei,\n\n );\n\n\n\n pub fn glShaderSource(\n\n shader: GLuint,\n\n count: GLsizei,\n\n string: *const *const GLchar,\n\n length: *const GLint,\n\n );\n\n\n\n pub fn glStencilFunc(func: GLenum, ref_: GLint, mask: GLuint);\n", "file_path": "src/es20/ffi.rs", "rank": 95, "score": 10.359551212834042 }, { "content": " log.as_mut_vec().as_mut_ptr() as *mut GLchar,\n\n );\n\n\n\n if length > 0 {\n\n log.as_mut_vec().set_len(length as usize);\n\n log.truncate(length as usize);\n\n\n\n Ok(log)\n\n } else {\n\n Ok(\"\".to_string())\n\n }\n\n }\n\n }\n\n\n\n pub fn gl_get_renderbuffer_parameteriv(&mut self, target: RenderBufferTarget,\n\n name: RenderBufferParamType) -> Result<i32, Error> {\n\n let mut value: GLint = 0;\n\n\n\n unsafe {\n\n ffi::glGetRenderbufferParameteriv(target as GLenum,\n", "file_path": "src/es20/wrapper.rs", "rank": 96, "score": 10.357566623470301 }, { "content": "\n\n pub fn gl_delete_transform_feedbacks(&mut self, ids: &[GLuint]) -> Result<(), Error> {\n\n unsafe {\n\n let n = ids.len() as i32;\n\n ffi::glDeleteTransformFeedbacks(n, ids.as_ptr() as *const GLuint);\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn gl_gen_transform_feedbacks(&mut self, size: i32) -> Result<Vec<GLuint>, Error> {\n\n unsafe {\n\n let mut ids: Vec<GLuint> = Vec::with_capacity(size as usize);\n\n ffi::glGenTransformFeedbacks(size as GLsizei, ids.as_mut_ptr() as *mut GLuint);\n\n Ok(ids)\n\n }\n\n }\n\n\n\n pub fn gl_is_transform_feedback(&mut self, id: u32) -> Result<bool, Error> {\n\n unsafe {\n\n let result = ffi::glIsTransformFeedback(id as GLuint);\n", "file_path": "src/es30/wrapper.rs", "rank": 97, "score": 10.317933340531104 }, { "content": " index: GLuint,\n\n propCount: GLsizei,\n\n props: *const GLenum,\n\n buf_size: GLsizei,\n\n length: *mut GLsizei,\n\n params: *mut GLint,\n\n ) -> Result<(), Error> {\n\n unsafe {\n\n ffi::glGetProgramResourceiv(\n\n program,\n\n program_interface,\n\n index,\n\n propCount,\n\n props,\n\n buf_size,\n\n length,\n\n params,\n\n );\n\n }\n\n Ok(())\n", "file_path": "src/es31/wrapper.rs", "rank": 98, "score": 10.273378042425557 }, { "content": " let mut vec: Vec<u32> = Vec::with_capacity(max_count as usize);\n\n\n\n ffi::glGetAttachedShaders(program as GLuint,\n\n max_count as GLsizei, &mut count,\n\n vec.as_mut_ptr());\n\n\n\n vec.set_len(count as usize);\n\n vec.truncate(count as usize);\n\n Ok(vec)\n\n }\n\n }\n\n\n\n pub fn gl_get_attrib_location(&mut self, program: u32, name: &str) -> Result<i32, Error> {\n\n unsafe {\n\n let c_str = CString::new(name).unwrap();\n\n\n\n let loc = ffi::glGetAttribLocation(program as GLuint, c_str.as_ptr() as *const GLchar);\n\n\n\n Ok(loc as i32)\n\n }\n", "file_path": "src/es20/wrapper.rs", "rank": 99, "score": 9.919886995824543 } ]
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 function for the field\n\n/// (e.g., `mean`, `sum`, `median`, `min`, `max`, `count`).\n\n///\n\n/// __Default value:__ `undefined` (None)\n\n///\n\n/// __See also:__ [`aggregate`](https://vega.github.io/vega-lite/docs/aggregate.html)\n\n/// documentation.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Aggregate {\n\n ArgmDef(ArgmDef),\n\n Enum(AggregateOp),\n", "file_path": "src/schema.rs", "rank": 8, "score": 55368.073404973155 }, { "content": "fn iter_to_data_inline_dataset<T>(v: impl Iterator<Item = T>) -> UrlDataInlineDataset\n\nwhere\n\n T: Serialize,\n\n{\n\n let values = v\n\n .map(serde_json::to_value)\n\n .collect::<Result<Vec<_>, _>>()\n\n .expect(\"TODO manage error in iter_to_dataInlineDataSet\");\n\n UrlDataInlineDataset::UnionArray(values)\n\n}\n\n\n\nimpl<T> From<&[T]> for UrlData\n\nwhere\n\n T: Serialize,\n\n{\n\n fn from(v: &[T]) -> Self {\n\n iter_to_data(v.iter())\n\n }\n\n}\n\nimpl<T> From<&[T]> for RemovableValue<UrlData>\n", "file_path": "src/data.rs", "rank": 9, "score": 54726.85138639403 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // input data: a CSV serialized to a `Vec<Item>`\n\n let mut rdr = csv::Reader::from_path(Path::new(\"examples/res/data/clustered_data.csv\"))?;\n\n let values = rdr\n\n .deserialize()\n\n .into_iter()\n\n .collect::<Result<Vec<Item>, csv::Error>>()?;\n\n\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Clusters\")\n\n .description(\"Dots colored by their cluster.\")\n\n .data(&values)\n\n .mark(Mark::Point)\n\n .encoding(\n\n EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .field(\"x\")\n\n .def_type(StandardType::Quantitative)\n\n .build()?)\n", "file_path": "examples/scatterplot.rs", "rank": 10, "score": 53418.28467629362 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // input data: a random ndarray\n\n let values: Array2<f64> = Array::random((100, 2), StandardNormal);\n\n\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Random points\")\n\n .data(values)\n\n .mark(Mark::Point)\n\n .encoding(\n\n EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .field(\"data.0\")\n\n .def_type(StandardType::Quantitative)\n\n .build()?)\n\n .y(YClassBuilder::default()\n\n .field(\"data.1\")\n\n .def_type(StandardType::Quantitative)\n\n .build()?)\n\n .build()?,\n", "file_path": "examples/from_ndarray.rs", "rank": 11, "score": 53418.28467629362 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Stock price\")\n\n .description(\"Google's stock price over time.\")\n\n .data(UrlDataBuilder::default().url(\n\n \"https://raw.githubusercontent.com/davidB/vega_lite_3.rs/master/examples/res/data/stocks.csv\"\n\n ).build()?)\n\n .transform(vec![\n\n TransformBuilder::default().filter(\"datum.symbol==='GOOG'\")\n\n .build()?])\n\n .mark(Mark::Line)\n\n .encoding(EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .field(\"date\")\n\n .def_type(StandardType::Temporal)\n\n .build()?)\n\n .y(YClassBuilder::default()\n\n .field(\"price\")\n\n .def_type(StandardType::Quantitative)\n", "file_path": "examples/from_url.rs", "rank": 12, "score": 53418.28467629362 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // input data: a CSV reader\n\n let rdr = csv::Reader::from_path(Path::new(\"examples/res/data/stocks.csv\"))?;\n\n\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Stock price\")\n\n .description(\"Google's stock price over time.\")\n\n .data(rdr)\n\n .transform(vec![TransformBuilder::default()\n\n .filter(\"datum[0]==='GOOG'\")\n\n .build()?])\n\n .mark(Mark::Line)\n\n .encoding(\n\n EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .field(\"1\")\n\n .def_type(StandardType::Temporal)\n\n .axis(AxisBuilder::default().title(\"date\").build()?)\n\n .build()?)\n", "file_path": "examples/from_csv.rs", "rank": 13, "score": 53418.28467629362 }, { "content": "/// Helper method turning an iterator over a `Serialize`-able type into a data that can't be used in a graph.\n\npub fn iter_to_data<T>(v: impl Iterator<Item = T>) -> UrlData\n\nwhere\n\n T: Serialize,\n\n{\n\n UrlDataBuilder::default()\n\n .values(iter_to_data_inline_dataset(v))\n\n .build()\n\n .unwrap()\n\n}\n\n\n", "file_path": "src/data.rs", "rank": 14, "score": 52692.54404899954 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Line Chart with Confidence Interval Band\")\n\n .autosize(AutosizeType::Fit)\n\n //.height(200)\n\n //.width(300)\n\n .data(\n\n UrlDataBuilder::default()\n\n .url(\"https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json\")\n\n .build()?,\n\n )\n\n .mark(Mark::Line)\n\n .encoding(\n\n EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .field(\"Year\")\n\n .def_type(StandardType::Temporal)\n\n .time_unit(TimeUnit::Year)\n\n .build()?)\n", "file_path": "examples/line_with_interval.rs", "rank": 15, "score": 51104.09849018997 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Choropleth of Unemployment Rate per County\")\n\n .data(\n\n UrlDataBuilder::default()\n\n .url(\"https://raw.githubusercontent.com/vega/vega-datasets/master/data/us-10m.json\")\n\n .format(\n\n DataFormatBuilder::default()\n\n .data_format_type(DataFormatType::Topojson)\n\n .feature(\"counties\")\n\n .build()?,\n\n )\n\n .build()?,\n\n )\n\n .mark(Mark::Geoshape)\n\n .transform(vec![TransformBuilder::default()\n\n .lookup(\"id\")\n\n .from(LookupDataBuilder::default()\n\n .data(DataBuilder::default()\n", "file_path": "examples/cloropleth_unemployment.rs", "rank": 16, "score": 51104.09849018997 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // the chart\n\n let chart = Vegalite {\n\n title: Some(Title::String(\"Stock price\".to_string())),\n\n description: Some(\"Google's stock price over time.\".to_string()),\n\n data: RemovableValue::Specified(UrlData {\n\n url: Some(\"https://raw.githubusercontent.com/davidB/vega_lite_3.rs/master/examples/res/data/stocks.csv\".to_string()),\n\n ..Default::default()\n\n }),\n\n transform: Some(vec![Transform {\n\n filter: Some(PurpleLogicalOperandPredicate::String(\"datum.symbol==='GOOG'\".to_string())),\n\n ..Default::default()\n\n }]),\n\n mark: Some(AnyMark::Enum(Mark::Line)),\n\n encoding: Some(\n\n Encoding {\n\n x: Some(XClass {\n\n field: Some(Field::String(\"date\".to_string())),\n\n def_type: Some(StandardType::Temporal),\n\n ..Default::default()\n", "file_path": "examples/without_builders.rs", "rank": 17, "score": 51104.09849018997 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // {\n\n // \"$schema\": \"https://vega.github.io/schema/vega-lite/v3.json\",\n\n // \"description\": \"Google's stock price over time.\",\n\n // \"data\": {\"url\": \"data/stocks.csv\"},\n\n // \"transform\": [{\"filter\": \"datum.symbol==='GOOG'\"}],\n\n // \"mark\": \"line\",\n\n // \"encoding\": {\n\n // \"x\": {\"field\": \"date\", \"type\": \"temporal\"},\n\n // \"y\": {\"field\": \"price\", \"type\": \"quantitative\"}\n\n // }\n\n // }\n\n\n\n // input data: a CSV serialized to a `Vec<Item>`\n\n let mut rdr = csv::Reader::from_path(Path::new(\"examples/res/data/stocks.csv\"))?;\n\n let values = rdr\n\n .deserialize()\n\n .into_iter()\n\n .collect::<Result<Vec<Item>, csv::Error>>()?;\n\n\n", "file_path": "examples/stock_graph.rs", "rank": 18, "score": 51104.09849018997 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let spec = r##\"\n\n{\n\n \"$schema\": \"https://vega.github.io/schema/vega-lite/v4.json\",\n\n \"description\": \"A population pyramid for the US in 2000, created using stack. See https://vega.github.io/vega-lite/examples/concat_population_pyramid.html for a variant of this created using concat.\",\n\n \"data\": { \"url\": \"https://raw.githubusercontent.com/vega/vega-datasets/master/data/population.json\"},\n\n \"transform\": [\n\n {\"filter\": \"datum.year == 2000\"},\n\n {\"calculate\": \"datum.sex == 2 ? 'Female' : 'Male'\", \"as\": \"gender\"},\n\n {\"calculate\": \"datum.sex == 2 ? -datum.people : datum.people\", \"as\": \"signed_people\"}\n\n ],\n\n \"width\": 300,\n\n \"height\": 200,\n\n \"mark\": \"bar\",\n\n \"encoding\": {\n\n \"y\": {\n\n \"field\": \"age\", \"type\": \"ordinal\",\n\n \"axis\": null, \"sort\": \"descending\"\n\n },\n\n \"x\": {\n", "file_path": "examples/from_json_spec.rs", "rank": 19, "score": 51104.09849018997 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .title(\"Weather in Seattle\")\n\n .data(\n\n UrlDataBuilder::default()\n\n .url(\"https://raw.githubusercontent.com/vega/vega-datasets/master/data/seattle-weather.csv\")\n\n .build()?\n\n )\n\n .mark(Mark::Bar)\n\n .encoding(\n\n EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .field(\"date\")\n\n .time_unit(TimeUnit::Month)\n\n .def_type(StandardType::Ordinal)\n\n .title(\"Month of the year\")\n\n .build()?)\n\n .y(YClassBuilder::default()\n\n .aggregate(AggregateOp::Count)\n", "file_path": "examples/stacked_bar_chart.rs", "rank": 20, "score": 49001.61333756922 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let spec = r##\"{\n\n \"$schema\": \"https://vega.github.io/schema/vega-lite/v3.4.0.json\",\n\n \"encoding\": {\n\n \"x\": {\n\n \"field\": \"data.0\",\n\n \"type\": \"quantitative\"\n\n },\n\n \"y\": {\n\n \"field\": \"data.1\",\n\n \"type\": \"quantitative\"\n\n }\n\n },\n\n \"mark\": \"point\",\n\n \"title\": \"Random points\"\n\n}\"##;\n\n let values: Array2<f64> = Array::random((100, 2), Uniform::new(0., 1000.));\n\n let mut chart: Vegalite = serde_json::from_str(spec)?;\n\n chart.data = values.into();\n\n // display the chart using `showata`\n\n chart.show()?;\n\n\n\n // print the vega lite spec\n\n eprintln!(\"{}\", chart.to_string()?);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/from_mixed_json_rust.rs", "rank": 21, "score": 49001.61333756922 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // the chart\n\n let chart = VegaliteBuilder::default()\n\n .description(\"A population pyramid for the US in 2000.\")\n\n .data(UrlDataBuilder::default().url(\n\n \"https://raw.githubusercontent.com/vega/vega-datasets/master/data/population.json\"\n\n ).build()?)\n\n .height(200)\n\n .width(300)\n\n .transform(vec![\n\n TransformBuilder::default().filter(\"datum.year == 2000\").build()?,\n\n TransformBuilder::default().calculate(\"datum.sex == 2 ? 'Female' : 'Male'\").transform_as(\"gender\").build()?,\n\n TransformBuilder::default().calculate(\"datum.sex == 2 ? -datum.people : datum.people\").transform_as(\"signed_people\").build()?,\n\n ])\n\n .mark(Mark::Bar)\n\n .encoding(EncodingBuilder::default()\n\n .x(XClassBuilder::default()\n\n .aggregate(AggregateOp::Sum)\n\n .field(\"signed_people\")\n\n .def_type(StandardType::Quantitative)\n", "file_path": "examples/diverging_stacked_bar_chart.rs", "rank": 22, "score": 47082.72332721991 }, { "content": "// serde_json::from_str(s)\n\n// }\n\n// }\n\n\n\nimpl Vegalite {\n\n /// Render the json for a graph\n\n pub fn to_string(&self) -> Result<String, serde_json::Error> {\n\n serde_json::to_string(self)\n\n }\n\n}\n\n\n\n// impl TryFrom<&Vegalite> for String {\n\n// type Error = serde_json::Error;\n\n// fn try_from(v: &Vegalite) -> Result<Self, Self::Error> {\n\n// v.to_string()\n\n// }\n\n// }\n\n\n\n// for every enum with String(String)\n\nmacro_rules! from_into_string{\n", "file_path": "src/string.rs", "rank": 23, "score": 32044.65086980414 }, { "content": "// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// https://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\nuse crate::schema::*;\n\n// use std::str::FromStr;\n\n// use std::convert::TryFrom;\n\nuse serde_json;\n\n\n\n// impl FromStr for Vegalite {\n\n// type Err = serde_json::Error;\n\n\n\n// fn from_str(s: &str) -> Result<Self, Self::Err> {\n", "file_path": "src/string.rs", "rank": 24, "score": 32038.07555660537 }, { "content": " ( $( $x:ident ),* $(,)? ) => {\n\n $(\n\n impl From<&str> for $x\n\n {\n\n fn from(v: &str) -> Self {\n\n $x::String(v.into())\n\n }\n\n }\n\n )*\n\n };\n\n}\n\n\n\nfrom_into_string!(\n\n Title,\n\n SelectionOperandElement,\n\n PurpleSelectionOperand,\n\n LogicalOperandPredicateElement,\n\n PurpleLogicalOperandPredicate,\n\n EqualUnion,\n\n Day,\n", "file_path": "src/string.rs", "rank": 25, "score": 32035.21323185765 }, { "content": " Month,\n\n Lt,\n\n SelectionInitIntervalElement,\n\n Value,\n\n Field,\n\n ScaleRange,\n\n RangeRange,\n\n Scheme,\n\n TooltipUnion,\n\n Style,\n\n BindValue,\n\n InitSelectionInitMapping,\n\n Translate,\n\n InlineDatasetValue,\n\n UrlDataInlineDataset,\n\n);\n\n\n\n// #[cfg(test)]\n\n// mod tests {\n\n// use super::*;\n", "file_path": "src/string.rs", "rank": 26, "score": 32033.57001465322 }, { "content": "\n\n// #[test]\n\n// fn test_from_string_to_string() {\n\n// let json1 = r#\"\n\n// {\n\n// \"$schema\": \"https://vega.github.io/schema/vega-lite/v3.json\",\n\n// \"description\": \"Google's stock price over time.\",\n\n// \"data\": {\"url\": \"data/stocks.csv\"},\n\n// \"transform\": [{\"filter\": \"datum.symbol==='GOOG'\"}],\n\n// \"mark\": \"line\",\n\n// \"encoding\": {\n\n// \"x\": {\"field\": \"date\", \"type\": \"temporal\"},\n\n// \"y\": {\"field\": \"price\", \"type\": \"quantitative\"}\n\n// }\n\n// }\n\n// \"#;\n\n// let vega1 = Vegalite::from_str(json1).unwrap();\n\n// //dbg!(vega1);\n\n// //let json2 = vega1.to_string().unwrap();\n\n// //let vega2 = Vegalite::from_str(json2).unwrap();\n\n// //assert_eq!(json1, json2);\n\n// //assert_eq!(vega1, vega2);\n\n// }\n\n// }\n", "file_path": "src/string.rs", "rank": 27, "score": 32025.75743335915 }, { "content": " Bool(bool),\n\n MarkConfig(MarkConfig),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum TooltipUnion {\n\n Bool(bool),\n\n Double(f64),\n\n String(String),\n\n TooltipContent(TooltipContent),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum BoxPlotDefExtent {\n\n Double(f64),\n\n Enum(ExtentExtent),\n", "file_path": "src/schema.rs", "rank": 28, "score": 49.22867978834412 }, { "content": "/// __Default value:__ `true` for axis of a continuous x-scale. Otherwise, `false`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Label {\n\n Bool(bool),\n\n Double(f64),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Keyvals {\n\n AnythingArray(Vec<Option<serde_json::Value>>),\n\n ImputeSequence(ImputeSequence),\n\n}\n\n\n\n/// Type of stacking offset if the field should be stacked.\n\n/// `stack` is only applicable for `x` and `y` channels with continuous domains.\n\n/// For example, `stack` of `y` can be used to customize stacking for a vertical bar chart.\n", "file_path": "src/schema.rs", "rank": 29, "score": 48.18565464538432 }, { "content": "/// `\"pad\"`, `\"fit\"` or `\"none\"`.\n\n/// Object values can additionally specify parameters for content sizing and automatic\n\n/// resizing.\n\n/// `\"fit\"` is only supported for single and layered views that don't use `rangeStep`.\n\n///\n\n/// __Default value__: `pad`\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Autosize {\n\n AutoSizeParams(AutoSizeParams),\n\n Enum(AutosizeType),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum VegaliteCenter {\n\n Bool(bool),\n\n RowColBoolean(RowColBoolean),\n", "file_path": "src/schema.rs", "rank": 30, "score": 45.38542953500913 }, { "content": "}\n\n\n\n/// An object indicating bin properties, or simply `true` for using default bin parameters.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum PurpleBin {\n\n BinParams(BinParams),\n\n Bool(bool),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum ColorCondition {\n\n ConditionalPredicateStringValueDefClass(ConditionalPredicateStringValueDefClass),\n\n ConditionalStringValueDefArray(Vec<ConditionalStringValueDef>),\n\n}\n\n\n\n/// Filter using a selection name.\n", "file_path": "src/schema.rs", "rank": 31, "score": 45.17731917215839 }, { "content": " StringArray(Vec<String>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum PointUnion {\n\n Bool(bool),\n\n Enum(PointEnum),\n\n OverlayMarkDef(OverlayMarkDef),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum SelectionDefBind {\n\n Enum(BindEnum),\n\n UnionMap(HashMap<String, BindValue>),\n\n}\n\n\n", "file_path": "src/schema.rs", "rank": 32, "score": 43.3378794955545 }, { "content": "/// used. The `flush` setting can be useful when attempting to place sub-plots without axes\n\n/// or legends into a uniform grid structure.\n\n///\n\n/// __Default value:__ `\"full\"`\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum BoundsEnum {\n\n #[serde(rename = \"flush\")]\n\n Flush,\n\n #[serde(rename = \"full\")]\n\n Full,\n\n}\n\n\n\n/// Type of input data: `\"json\"`, `\"csv\"`, `\"tsv\"`, `\"dsv\"`.\n\n///\n\n/// __Default value:__ The default format type is determined by the extension of the file\n\n/// URL.\n\n/// If no extension is detected, `\"json\"` will be used by default.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum DataFormatType {\n\n #[serde(rename = \"csv\")]\n", "file_path": "src/schema.rs", "rank": 33, "score": 43.32575805815893 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Stack {\n\n Bool(bool),\n\n Enum(StackOffset),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum XUnion {\n\n Double(f64),\n\n Enum(XEnum),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum YUnion {\n", "file_path": "src/schema.rs", "rank": 34, "score": 42.30221302368177 }, { "content": "/// - Secondary channels (e.g., `x2`, `y2`, `xError`, `yError`) do not have `type` as they\n\n/// have exactly the same type as their primary channels (e.g., `x`, `y`).\n\n///\n\n/// __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum TypeForShape {\n\n #[serde(rename = \"geojson\")]\n\n Geojson,\n\n #[serde(rename = \"nominal\")]\n\n Nominal,\n\n #[serde(rename = \"ordinal\")]\n\n Ordinal,\n\n}\n\n\n\n/// The imputation method to use for the field value of imputed data objects.\n\n/// One of `value`, `mean`, `median`, `max` or `min`.\n\n///\n\n/// __Default value:__ `\"value\"`\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum ImputeMethod {\n", "file_path": "src/schema.rs", "rank": 35, "score": 41.95730373592299 }, { "content": " TypedFieldDef(TypedFieldDef),\n\n TypedFieldDefArray(Vec<TypedFieldDef>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum FluffyBin {\n\n BinParams(BinParams),\n\n Bool(bool),\n\n Enum(BinEnum),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum FillOpacityCondition {\n\n ConditionalNumberValueDefArray(Vec<ConditionalNumberValueDef>),\n\n ConditionalPredicateNumberValueDefClass(ConditionalPredicateNumberValueDefClass),\n\n}\n", "file_path": "src/schema.rs", "rank": 36, "score": 41.81736616574394 }, { "content": "\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum HrefCondition {\n\n ConditionalPredicateValueDefClass(ConditionalPredicateValueDefClass),\n\n ConditionalValueDefArray(Vec<ConditionalValueDef>),\n\n}\n\n\n\n/// A constant value in visual domain (e.g., `\"red\"` / \"#0099ff\" for color, values between\n\n/// `0` to `1` for opacity).\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Value {\n\n Bool(bool),\n\n Double(f64),\n\n String(String),\n\n}\n\n\n", "file_path": "src/schema.rs", "rank": 37, "score": 41.637924756102144 }, { "content": "/// to the largest data within the range _[Q1 - k * IQR, Q3 + k * IQR]_ where _Q1_ and _Q3_\n\n/// are the first and third quartiles while _IQR_ is the interquartile range (_Q3-Q1_).\n\n///\n\n/// __Default value:__ `1.5`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum BoxplotExtent {\n\n Double(f64),\n\n Enum(ExtentEnum),\n\n}\n\n\n\n/// The bounds calculation to use for legend orient group layout.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum LayoutBounds {\n\n Enum(BoundsEnum),\n\n SignalRef(SignalRef),\n\n}\n", "file_path": "src/schema.rs", "rank": 38, "score": 41.61823402917234 }, { "content": " #[serde(rename = \"stdev\")]\n\n Stdev,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum PointEnum {\n\n #[serde(rename = \"transparent\")]\n\n Transparent,\n\n}\n\n\n\n/// The cartographic projection to use. This value is case-insensitive, for example\n\n/// `\"albers\"` and `\"Albers\"` indicate the same projection type. You can find all valid\n\n/// projection types [in the\n\n/// documentation](https://vega.github.io/vega-lite/docs/projection.html#projection-types).\n\n///\n\n/// __Default value:__ `mercator`\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum ProjectionType {\n\n #[serde(rename = \"albers\")]\n\n Albers,\n", "file_path": "src/schema.rs", "rank": 39, "score": 41.37654674008424 }, { "content": " Double(f64),\n\n String(String),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum SelectionInitIntervalElement {\n\n Bool(bool),\n\n DateTime(DateTime),\n\n Double(f64),\n\n String(String),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum RangeElement {\n\n DateTime(DateTime),\n\n Double(f64),\n", "file_path": "src/schema.rs", "rank": 40, "score": 40.670146170291986 }, { "content": "/// performed, removing any label that overlaps with the last visible label (this often works\n\n/// better for log-scaled axes).\n\n///\n\n/// __Default value:__ `true`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum LabelOverlap {\n\n Bool(bool),\n\n Enum(LabelOverlapEnum),\n\n}\n\n\n\n/// Customized domain values.\n\n///\n\n/// For _quantitative_ fields, `domain` can take the form of a two-element array with minimum\n\n/// and maximum values. [Piecewise\n\n/// scales](https://vega.github.io/vega-lite/docs/scale.html#piecewise) can be created by\n\n/// providing a `domain` with more than two entries.\n\n/// If the input field is aggregated, `domain` can also be a string value `\"unaggregated\"`,\n\n/// indicating that the domain should include the raw data values prior to the aggregation.\n", "file_path": "src/schema.rs", "rank": 41, "score": 40.58341640844042 }, { "content": "/// the values can be the month or day names (case insensitive) or their 3-letter initials\n\n/// (e.g., `\"Mon\"`, `\"Tue\"`).\n\n/// - `null` indicating no sort.\n\n///\n\n/// __Default value:__ `\"ascending\"`\n\n///\n\n/// __Note:__ `null` is not supported for `row` and `column`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum SortArray {\n\n Enum(SortOrder),\n\n SortEncodingSortField(SortEncodingSortField),\n\n UnionArray(Vec<SelectionInitIntervalElement>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Detail {\n", "file_path": "src/schema.rs", "rank": 42, "score": 39.91984950412336 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum InlineDatasetValue {\n\n AnythingMap(HashMap<String, Option<serde_json::Value>>),\n\n String(String),\n\n UnionArray(Vec<serde_json::value::Value>),\n\n}\n\n\n\n/// The alignment to apply to symbol legends rows and columns. The supported string values\n\n/// are `\"all\"`, `\"each\"` (the default), and `none`. For more information, see the [grid\n\n/// layout documentation](https://vega.github.io/vega/docs/layout).\n\n///\n\n/// __Default value:__ `\"each\"`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum LayoutAlign {\n\n #[serde(rename = \"all\")]\n\n All,\n\n #[serde(rename = \"each\")]\n\n Each,\n", "file_path": "src/schema.rs", "rank": 43, "score": 39.156855640544215 }, { "content": "\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum EqualUnion {\n\n Bool(bool),\n\n DateTime(DateTime),\n\n Double(f64),\n\n String(String),\n\n}\n\n\n\n/// Value representing the day of a week. This can be one of: (1) integer value -- `1`\n\n/// represents Monday; (2) case-insensitive day name (e.g., `\"Monday\"`); (3)\n\n/// case-insensitive, 3-character short day name (e.g., `\"Mon\"`). <br/> **Warning:** A\n\n/// DateTime definition object with `day`** should not be combined with `year`, `quarter`,\n\n/// `month`, or `date`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Day {\n", "file_path": "src/schema.rs", "rank": 44, "score": 39.127133587559456 }, { "content": " #[builder(default)]\n\n pub nice: Option<bool>,\n\n /// An exact step size to use between bins.\n\n ///\n\n /// __Note:__ If provided, options such as maxbins will be ignored.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub step: Option<f64>,\n\n /// An array of allowable step sizes to choose from.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub steps: Option<Vec<f64>>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct ConditionalStringValueDef {\n\n /// Predicate for triggering the condition\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n", "file_path": "src/schema.rs", "rank": 45, "score": 38.96701817861125 }, { "content": "}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct NiceClass {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub interval: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub step: Option<f64>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct SchemeParams {\n\n /// The number of colors to use in the scheme. This can be useful for scale types such as\n\n /// `\"quantize\"`, which use the length of the scale range to determine the number of discrete\n\n /// bins for the scale domain.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/schema.rs", "rank": 46, "score": 38.95779558609886 }, { "content": " #[builder(default)]\n\n pub field: Option<String>,\n\n /// Whether to sort the field in ascending or descending order. One of `\"ascending\"`\n\n /// (default), `\"descending\"`, or `null` (no not sort).\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub order: RemovableValue<SortOrder>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct WindowFieldDef {\n\n /// The output name for the window operation.\n\n #[serde(rename = \"as\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub window_field_def_as: Option<String>,\n\n /// The data field for which to compute the aggregate or window function. This can be omitted\n\n /// for window functions that do not operate over a field such as `count`, `rank`,\n\n /// `dense_rank`.\n", "file_path": "src/schema.rs", "rank": 47, "score": 38.71104315057872 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Order {\n\n OrderFieldDefArray(Vec<OrderFieldDef>),\n\n OrderFieldDefClass(OrderFieldDefClass),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum ConditionUnion {\n\n Conditional(Conditional),\n\n ConditionalStringValueDefArray(Vec<ConditionalStringValueDef>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Tooltip {\n", "file_path": "src/schema.rs", "rank": 48, "score": 38.40702137152082 }, { "content": " /// calculate count `distinct` of a categorical field `\"cat\"` using `{\"aggregate\":\n\n /// \"distinct\", \"field\": \"cat\", \"type\": \"quantitative\"}`. The `\"type\"` of the aggregate\n\n /// output is `\"quantitative\"`.\n\n /// - Secondary channels (e.g., `x2`, `y2`, `xError`, `yError`) do not have `type` as they\n\n /// have exactly the same type as their primary channels (e.g., `x`, `y`).\n\n ///\n\n /// __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub def_with_condition_mark_prop_field_def_number_type: Option<StandardType>,\n\n /// A constant value in visual domain (e.g., `\"red\"` / \"#0099ff\" for color, values between\n\n /// `0` to `1` for opacity).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub value: Option<f64>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n", "file_path": "src/schema.rs", "rank": 49, "score": 38.40095145922824 }, { "content": " /// [`fieldTitle` function via the `compile` function's\n\n /// options](https://vega.github.io/vega-lite/docs/compile.html#field-title).\n\n ///\n\n /// 2) If both field definition's `title` and axis, header, or legend `title` are defined,\n\n /// axis/header/legend title will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub title: RemovableValue<String>,\n\n /// A constant value in visual domain (e.g., `\"red\"` / \"#0099ff\" for color, values between\n\n /// `0` to `1` for opacity).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub value: Option<f64>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct OrderFieldDef {\n\n /// Aggregation function for the field\n\n /// (e.g., `mean`, `sum`, `median`, `min`, `max`, `count`).\n", "file_path": "src/schema.rs", "rank": 50, "score": 38.29455791001661 }, { "content": " /// axis/header/legend title will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub title: RemovableValue<String>,\n\n /// A constant value in visual domain (e.g., `\"red\"` / \"#0099ff\" for color, values between\n\n /// `0` to `1` for opacity).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub value: Option<XUnion>,\n\n}\n\n\n\n/// Y coordinates of the marks, or height of vertical `\"bar\"` and `\"area\"` without specified\n\n/// `y2` or `height`.\n\n///\n\n/// The `value` of this channel can be a number or a string `\"height\"` for the height of the\n\n/// plot.\n\n///\n\n/// Definition object for a constant value of an encoding channel.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n", "file_path": "src/schema.rs", "rank": 51, "score": 38.2651563518742 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum BindValue {\n\n AnythingArray(Vec<Option<serde_json::Value>>),\n\n Binding(Binding),\n\n Double(f64),\n\n String(String),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum SelectionDefInit {\n\n UnionMap(HashMap<String, InitSelectionInitMapping>),\n\n UnionMapArray(Vec<HashMap<String, SelectionInitIntervalElement>>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n", "file_path": "src/schema.rs", "rank": 52, "score": 38.12113212887138 }, { "content": " #[builder(default)]\n\n pub count: Option<f64>,\n\n /// The extent of the color range to use. For example `[0.2, 1]` will rescale the color\n\n /// scheme such that color values in the range _[0, 0.2)_ are excluded from the scheme.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub extent: Option<Vec<f64>>,\n\n /// A color scheme name for ordinal scales (e.g., `\"category10\"` or `\"blues\"`).\n\n ///\n\n /// For the full list of supported schemes, please refer to the [Vega\n\n /// Scheme](https://vega.github.io/vega/docs/schemes/#reference) reference.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub name: Option<String>,\n\n}\n\n\n\n/// A sort definition for sorting a discrete scale in an encoding field definition.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct EncodingSortField {\n", "file_path": "src/schema.rs", "rank": 53, "score": 37.47375845124013 }, { "content": " Double(f64),\n\n String(String),\n\n}\n\n\n\n/// One of: (1) integer value representing the month from `1`-`12`. `1` represents January;\n\n/// (2) case-insensitive month name (e.g., `\"January\"`); (3) case-insensitive, 3-character\n\n/// short month name (e.g., `\"Jan\"`).\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Month {\n\n Double(f64),\n\n String(String),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Lt {\n\n DateTime(DateTime),\n", "file_path": "src/schema.rs", "rank": 54, "score": 37.351533189353816 }, { "content": "/// The full data set, included inline. This can be an array of objects or primitive values,\n\n/// an object, or a string.\n\n/// Arrays of primitive values are ingested as objects with a `data` property. Strings are\n\n/// parsed according to the specified format type.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum UrlDataInlineDataset {\n\n AnythingMap(HashMap<String, Option<serde_json::Value>>),\n\n String(String),\n\n UnionArray(Vec<serde_json::value::Value>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\n#[allow(unused)]\n", "file_path": "src/schema.rs", "rank": 55, "score": 37.30816664856859 }, { "content": " #[serde(rename = \"normalize\")]\n\n Normalize,\n\n #[serde(rename = \"zero\")]\n\n Zero,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum XEnum {\n\n #[serde(rename = \"width\")]\n\n Width,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum YEnum {\n\n #[serde(rename = \"height\")]\n\n Height,\n\n}\n\n\n\n/// The mouse cursor used over the mark. Any valid [CSS cursor\n\n/// type](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values) can be used.\n", "file_path": "src/schema.rs", "rank": 56, "score": 36.86384898563103 }, { "content": " pub legend_type: Option<LegendType>,\n\n /// Explicitly set the visible legend values.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub values: Option<Vec<SelectionInitIntervalElement>>,\n\n /// A non-negative integer indicating the z-index of the legend.\n\n /// If zindex is 0, legend should be drawn behind all chart elements.\n\n /// To put them in front, use zindex = 1.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub zindex: Option<f64>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct Scale {\n\n /// The alignment of the steps within the scale range.\n\n ///\n\n /// This value must lie in the range `[0,1]`. A value of `0.5` indicates that the steps\n\n /// should be centered within the range. A value of `0` or `1` may be used to shift the bands\n", "file_path": "src/schema.rs", "rank": 57, "score": 36.49931344507223 }, { "content": "\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum BottomCenter {\n\n Bool(bool),\n\n SignalRef(SignalRef),\n\n}\n\n\n\n/// The layout direction for legend orient group layout.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Direction {\n\n Enum(Orientation),\n\n SignalRef(SignalRef),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n", "file_path": "src/schema.rs", "rank": 58, "score": 36.32658722892069 }, { "content": " /// calculate count `distinct` of a categorical field `\"cat\"` using `{\"aggregate\":\n\n /// \"distinct\", \"field\": \"cat\", \"type\": \"quantitative\"}`. The `\"type\"` of the aggregate\n\n /// output is `\"quantitative\"`.\n\n /// - Secondary channels (e.g., `x2`, `y2`, `xError`, `yError`) do not have `type` as they\n\n /// have exactly the same type as their primary channels (e.g., `x`, `y`).\n\n ///\n\n /// __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub def_type: Option<StandardType>,\n\n /// A constant value in visual domain (e.g., `\"red\"` / \"#0099ff\" for color, values between\n\n /// `0` to `1` for opacity).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub value: Option<XUnion>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n", "file_path": "src/schema.rs", "rank": 59, "score": 36.261668807289155 }, { "content": "\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct ArgmDef {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub argmax: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub argmin: Option<String>,\n\n}\n\n\n\n/// Binning properties or boolean flag for determining whether to bin data or not.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct BinParams {\n\n /// A value in the binned domain at which to anchor the bins, shifting the bin boundaries if\n\n /// necessary to ensure that a boundary aligns with the anchor value.\n\n ///\n\n /// __Default Value:__ the minimum bin extent value\n", "file_path": "src/schema.rs", "rank": 60, "score": 36.22190525563661 }, { "content": " #[builder(default)]\n\n pub row: Option<Vec<String>>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct RowColNumber {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub column: Option<f64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub row: Option<f64>,\n\n}\n\n\n\n/// Vega-Lite configuration object. This property can only be defined at the top-level of a\n\n/// specification.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct Config {\n", "file_path": "src/schema.rs", "rank": 61, "score": 36.213169818626454 }, { "content": " #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub theta: Option<f64>,\n\n /// Thickness of the tick mark.\n\n ///\n\n /// __Default value:__ `1`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub thickness: Option<f64>,\n\n /// The tooltip text string to show upon mouse hover or an object defining which fields\n\n /// should the tooltip be derived from.\n\n ///\n\n /// - If `tooltip` is `{\"content\": \"encoding\"}`, then all fields from `encoding` will be\n\n /// used.\n\n /// - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted\n\n /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n", "file_path": "src/schema.rs", "rank": 62, "score": 36.18794271365488 }, { "content": "/// }\n\n/// Reference to a repeated value.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct RepeatRef {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub repeat: Option<RepeatEnum>,\n\n}\n\n\n\n/// Properties of a legend or boolean flag for determining whether to show it.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct Legend {\n\n /// The height in pixels to clip symbol legend entries and limit their size.\n\n #[serde(rename = \"clipHeight\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub clip_height: Option<f64>,\n\n /// The horizontal padding in pixels between symbol legend entries.\n", "file_path": "src/schema.rs", "rank": 63, "score": 36.167871711175884 }, { "content": " /// - the general (wrappable) `concat` operator (not `hconcat`/`vconcat`)\n\n /// - the `facet` and `repeat` operator with one field/repetition definition (without\n\n /// row/column nesting)\n\n ///\n\n /// 2) Setting the `columns` to `1` is equivalent to `vconcat` (for `concat`) and to using\n\n /// the `row` channel (for `facet` and `repeat`).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub columns: Option<f64>,\n\n /// The default spacing in pixels between composed sub-views.\n\n ///\n\n /// __Default value__: `20`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub spacing: Option<f64>,\n\n}\n\n\n\n/// ErrorBand Config\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n", "file_path": "src/schema.rs", "rank": 64, "score": 36.04480280647445 }, { "content": "///\n\n/// __Default value:__ none (transparent)\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct ViewBackground {\n\n /// The radius in pixels of rounded rectangle corners.\n\n ///\n\n /// __Default value:__ `0`\n\n #[serde(rename = \"cornerRadius\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub corner_radius: Option<f64>,\n\n /// The fill color.\n\n ///\n\n /// __Default value:__ `undefined`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub fill: Option<String>,\n\n /// The fill opacity (value between [0,1]).\n\n ///\n", "file_path": "src/schema.rs", "rank": 65, "score": 35.9771844949788 }, { "content": " Double(f64),\n\n Enum(YEnum),\n\n}\n\n\n\n/// A string describing the mark type (one of `\"bar\"`, `\"circle\"`, `\"square\"`, `\"tick\"`,\n\n/// `\"line\"`,\n\n/// `\"area\"`, `\"point\"`, `\"rule\"`, `\"geoshape\"`, and `\"text\"`) or a [mark definition\n\n/// object](https://vega.github.io/vega-lite/docs/mark.html#mark-def).\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum AnyMark {\n\n MarkDefClass(MarkDefClass),\n\n Enum(Mark),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum DefBox {\n", "file_path": "src/schema.rs", "rank": 66, "score": 35.74464208605736 }, { "content": " pub text: Option<String>,\n\n /// The integer z-index indicating the layering of the title group relative to other axis,\n\n /// mark and legend groups.\n\n ///\n\n /// __Default value:__ `0`.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub zindex: Option<f64>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct Transform {\n\n /// Array of objects that define fields to aggregate.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub aggregate: Option<Vec<AggregatedFieldDef>>,\n\n /// The data fields to group by. If not specified, a single group containing all data objects\n\n /// will be used.\n\n ///\n", "file_path": "src/schema.rs", "rank": 67, "score": 35.69981610738351 }, { "content": " #[builder(default)]\n\n pub selection: Option<String>,\n\n /// The encoding channel to extract selected values for, when a selection is\n\n /// [projected](https://vega.github.io/vega-lite/docs/project.html)\n\n /// over multiple fields or encodings.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub encoding: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct ScaleInterpolateParams {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub gamma: Option<f64>,\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub scale_interpolate_params_type: Option<ScaleInterpolateParamsType>,\n", "file_path": "src/schema.rs", "rank": 68, "score": 35.695911501305034 }, { "content": "/// documentation.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct BrushConfig {\n\n /// The fill color of the interval mark.\n\n ///\n\n /// __Default value:__ `#333333`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub fill: Option<String>,\n\n /// The fill opacity of the interval mark (a value between 0 and 1).\n\n ///\n\n /// __Default value:__ `0.125`\n\n #[serde(rename = \"fillOpacity\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub fill_opacity: Option<f64>,\n\n /// The stroke color of the interval mark.\n\n ///\n\n /// __Default value:__ `#ffffff`\n", "file_path": "src/schema.rs", "rank": 69, "score": 35.68529462821671 }, { "content": " /// One of `value`, `mean`, `median`, `max` or `min`.\n\n ///\n\n /// __Default value:__ `\"value\"`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub method: Option<ImputeMethod>,\n\n /// The field value to use when the imputation `method` is `\"value\"`.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub value: Option<serde_json::Value>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct ImputeSequence {\n\n /// The starting value of the sequence.\n\n /// __Default value:__ `0`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub start: Option<f64>,\n", "file_path": "src/schema.rs", "rank": 70, "score": 35.379910948462694 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum RangeValue {\n\n SchemeConfig(SchemeConfig),\n\n UnionArray(Vec<RangeRange>),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum MultiInit {\n\n UnionMap(HashMap<String, SelectionInitIntervalElement>),\n\n UnionMapArray(Vec<HashMap<String, SelectionInitIntervalElement>>),\n\n}\n\n\n\n/// The full data set, included inline. This can be an array of objects or primitive values,\n\n/// an object, or a string.\n\n/// Arrays of primitive values are ingested as objects with a `data` property. Strings are\n\n/// parsed according to the specified format type.\n", "file_path": "src/schema.rs", "rank": 71, "score": 35.157701501133126 }, { "content": " /// __Default value:__ `true` for x and y channels if the quantitative field is not binned\n\n /// and no custom `domain` is provided; `false` otherwise.\n\n ///\n\n /// __Note:__ Log, time, and utc scales do not support `zero`.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub zero: Option<bool>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct DomainClass {\n\n /// The field name to extract selected values for, when a selection is\n\n /// [projected](https://vega.github.io/vega-lite/docs/project.html)\n\n /// over multiple fields or encodings.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub field: Option<String>,\n\n /// The name of a selection.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/schema.rs", "rank": 72, "score": 35.10630519706322 }, { "content": " ///\n\n /// __Default value__: `false`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub resize: Option<bool>,\n\n /// The sizing format type. One of `\"pad\"`, `\"fit\"` or `\"none\"`. See the [autosize\n\n /// type](https://vega.github.io/vega-lite/docs/size.html#autosize) documentation for\n\n /// descriptions of each.\n\n ///\n\n /// __Default value__: `\"pad\"`\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub auto_size_params_type: Option<AutosizeType>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct RowColBoolean {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/schema.rs", "rank": 73, "score": 34.948474015355835 }, { "content": " /// The minor step angles of the graticule.\n\n ///\n\n /// __Default value:__ `[10, 10]`\n\n #[serde(rename = \"stepMinor\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub step_minor: Option<Vec<f64>>,\n\n}\n\n\n\n/// Generate a sequence of numbers.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct SequenceParams {\n\n /// The name of the generated sequence field.\n\n ///\n\n /// __Default value:__ `\"data\"`\n\n #[serde(rename = \"as\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub sequence_params_as: Option<String>,\n", "file_path": "src/schema.rs", "rank": 74, "score": 34.87797481182685 }, { "content": " /// have exactly the same type as their primary channels (e.g., `x`, `y`).\n\n ///\n\n /// __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub def_with_condition_mark_prop_field_def_type_for_shape_string_null_type:\n\n Option<TypeForShape>,\n\n /// A constant value in visual domain (e.g., `\"red\"` / \"#0099ff\" for color, values between\n\n /// `0` to `1` for opacity).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub value: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct Conditional {\n\n /// Predicate for triggering the condition\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/schema.rs", "rank": 75, "score": 34.65023885337812 }, { "content": "/// one after the other.\n\n/// - For `\"each\"`, subviews will be aligned into a clean grid structure, but each row or\n\n/// column may be of variable size.\n\n/// - For `\"all\"`, subviews will be aligned and each row or column will be sized identically\n\n/// based on the maximum observed size. String values for this property will be applied to\n\n/// both grid rows and columns.\n\n///\n\n/// Alternatively, an object value of the form `{\"row\": string, \"column\": string}` can be\n\n/// used to supply different alignments for rows and columns.\n\n///\n\n/// __Default value:__ `\"all\"`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum AlignUnion {\n\n Enum(LayoutAlign),\n\n RowColLayoutAlign(RowColLayoutAlign),\n\n}\n\n\n\n/// Sets how the visualization size should be determined. If a string, should be one of\n", "file_path": "src/schema.rs", "rank": 76, "score": 34.52084808176074 }, { "content": " /// calculate count `distinct` of a categorical field `\"cat\"` using `{\"aggregate\":\n\n /// \"distinct\", \"field\": \"cat\", \"type\": \"quantitative\"}`. The `\"type\"` of the aggregate\n\n /// output is `\"quantitative\"`.\n\n /// - Secondary channels (e.g., `x2`, `y2`, `xError`, `yError`) do not have `type` as they\n\n /// have exactly the same type as their primary channels (e.g., `x`, `y`).\n\n ///\n\n /// __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.\n\n #[serde(rename = \"type\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub conditional_def_type: Option<StandardType>,\n\n}\n\n\n\n/// Latitude position of geographically projected marks.\n\n///\n\n/// Longitude position of geographically projected marks.\n\n///\n\n/// Definition object for a constant value of an encoding channel.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n", "file_path": "src/schema.rs", "rank": 77, "score": 34.27908062429624 }, { "content": " /// The sort order. One of `\"ascending\"` (default), `\"descending\"`, or `null` (no not sort).\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub order: RemovableValue<SortOrder>,\n\n /// The [encoding channel](https://vega.github.io/vega-lite/docs/encoding.html#channels) to\n\n /// sort by (e.g., `\"x\"`, `\"y\"`)\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub encoding: Option<SingleDefUnitChannel>,\n\n}\n\n\n\n/// A field definition for the horizontal facet of trellis plots.\n\n///\n\n/// A field definition for the (flexible) facet of trellis plots.\n\n///\n\n/// If either `row` or `column` is specified, this channel will be ignored.\n\n///\n\n/// A field definition for the vertical facet of trellis plots.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n", "file_path": "src/schema.rs", "rank": 78, "score": 34.15614414644589 }, { "content": " /// values only. This setting only affects those operations that depend on the window frame,\n\n /// namely aggregation operations and the first_value, last_value, and nth_value window\n\n /// operations.\n\n ///\n\n /// __Default value:__ `false`\n\n #[serde(rename = \"ignorePeers\")]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub ignore_peers: Option<bool>,\n\n /// The definition of the fields in the window, and what calculations to use.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub window: Option<Vec<WindowFieldDef>>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct AggregatedFieldDef {\n\n /// The output field names to use for each aggregated field.\n\n #[serde(rename = \"as\")]\n", "file_path": "src/schema.rs", "rank": 79, "score": 34.09857221629902 }, { "content": "///\n\n/// Base interface for a repeat specification.\n\n///\n\n/// Base interface for a generalized concatenation specification.\n\n///\n\n/// Base interface for a vertical concatenation specification.\n\n///\n\n/// Base interface for a horizontal concatenation specification.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct SpecClass {\n\n /// An object describing the data source. Set to `null` to ignore the parent's data source.\n\n /// If no data is set, it is derived from the parent.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub data: RemovableValue<UrlData>,\n\n /// Description of this mark for commenting purpose.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub description: Option<String>,\n", "file_path": "src/schema.rs", "rank": 80, "score": 34.0608878507023 }, { "content": " #[builder(default)]\n\n pub theta: Option<f64>,\n\n /// The tooltip text string to show upon mouse hover or an object defining which fields\n\n /// should the tooltip be derived from.\n\n ///\n\n /// - If `tooltip` is `{\"content\": \"encoding\"}`, then all fields from `encoding` will be\n\n /// used.\n\n /// - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted\n\n /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n\n /// Width of the marks.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub width: Option<f64>,\n\n /// X coordinates of the marks, or width of horizontal `\"bar\"` and `\"area\"` without specified\n\n /// `x2` or `width`.\n\n ///\n", "file_path": "src/schema.rs", "rank": 81, "score": 34.041833146483334 }, { "content": " /// The starting value of the sequence (inclusive).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub start: Option<f64>,\n\n /// The step value between sequence entries.\n\n ///\n\n /// __Default value:__ `1`\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub step: Option<f64>,\n\n /// The ending value of the sequence (exclusive).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub stop: Option<f64>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct SphereClass {}\n\n\n", "file_path": "src/schema.rs", "rank": 82, "score": 33.95216238733798 }, { "content": "/// The interpolation method for range values. By default, a general interpolator for\n\n/// numbers, dates, strings and colors (in HCL space) is used. For color ranges, this\n\n/// property allows interpolation in alternative color spaces. Legal values include `rgb`,\n\n/// `hsl`, `hsl-long`, `lab`, `hcl`, `hcl-long`, `cubehelix` and `cubehelix-long` ('-long'\n\n/// variants use longer paths in polar coordinate spaces). If object-valued, this property\n\n/// accepts an object with a string-valued _type_ property and an optional numeric _gamma_\n\n/// property applicable to rgb and cubehelix interpolators. For more, see the [d3-interpolate\n\n/// documentation](https://github.com/d3/d3-interpolate).\n\n///\n\n/// * __Default value:__ `hcl`\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum InterpolateUnion {\n\n Enum(ScaleInterpolate),\n\n ScaleInterpolateParams(ScaleInterpolateParams),\n\n}\n\n\n\n/// Extending the domain so that it starts and ends on nice round values. This method\n\n/// typically modifies the scale’s domain, and may only extend the bounds to the nearest\n", "file_path": "src/schema.rs", "rank": 83, "score": 33.86159706515016 }, { "content": " #[builder(default)]\n\n pub interpolate: Option<Interpolate>,\n\n /// The tension parameter for the interpolation type of the error band.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub tension: Option<f64>,\n\n}\n\n\n\n/// ErrorBar Config\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct ErrorBarConfig {\n\n /// The extent of the rule. Available options include:\n\n /// - `\"ci\"`: Extend the rule to the confidence interval of the mean.\n\n /// - `\"stderr\"`: The size of rule are set to the value of standard error, extending from the\n\n /// mean.\n\n /// - `\"stdev\"`: The size of rule are set to the value of standard deviation, extending from\n\n /// the mean.\n\n /// - `\"iqr\"`: Extend the rule to the q1 and q3.\n\n ///\n", "file_path": "src/schema.rs", "rank": 84, "score": 33.467276337668736 }, { "content": " /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n\n /// Width of the marks.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub width: Option<f64>,\n\n /// X coordinates of the marks, or width of horizontal `\"bar\"` and `\"area\"` without specified\n\n /// `x2` or `width`.\n\n ///\n\n /// The `value` of this channel can be a number or a string `\"width\"` for the width of the\n\n /// plot.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub x: Option<XUnion>,\n\n /// X2 coordinates for ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n\n ///\n\n /// The `value` of this channel can be a number or a string `\"width\"` for the width of the\n", "file_path": "src/schema.rs", "rank": 85, "score": 33.389693547313115 }, { "content": "#[derive(From)]\n\npub enum Translate {\n\n Bool(bool),\n\n String(String),\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum Title {\n\n String(String),\n\n TitleParams(TitleParams),\n\n}\n\n\n\n/// Definition for fields to be repeated. One of:\n\n/// 1) An array of fields to be repeated. If `\"repeat\"` is an array, the field can be\n\n/// referred using `{\"repeat\": \"repeat\"}`\n\n/// 2) An object that mapped `\"row\"` and/or `\"column\"` to the listed of fields to be repeated\n\n/// along the particular orientations. The objects `{\"repeat\": \"row\"}` and `{\"repeat\":\n\n/// \"column\"}` can be used to refer to the repeated field respectively.\n", "file_path": "src/schema.rs", "rank": 86, "score": 33.37762474713447 }, { "content": " pub text: Option<String>,\n\n /// Polar coordinate angle, in radians, of the text label from the origin determined by the\n\n /// `x` and `y` properties. Values for `theta` follow the same convention of `arc` mark\n\n /// `startAngle` and `endAngle` properties: angles are measured in radians, with `0`\n\n /// indicating \"north\".\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub theta: Option<f64>,\n\n /// The tooltip text string to show upon mouse hover or an object defining which fields\n\n /// should the tooltip be derived from.\n\n ///\n\n /// - If `tooltip` is `{\"content\": \"encoding\"}`, then all fields from `encoding` will be\n\n /// used.\n\n /// - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted\n\n /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n\n /// Width of the marks.\n", "file_path": "src/schema.rs", "rank": 87, "score": 33.36670526255514 }, { "content": " pub text: Option<String>,\n\n /// Polar coordinate angle, in radians, of the text label from the origin determined by the\n\n /// `x` and `y` properties. Values for `theta` follow the same convention of `arc` mark\n\n /// `startAngle` and `endAngle` properties: angles are measured in radians, with `0`\n\n /// indicating \"north\".\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub theta: Option<f64>,\n\n /// The tooltip text string to show upon mouse hover or an object defining which fields\n\n /// should the tooltip be derived from.\n\n ///\n\n /// - If `tooltip` is `{\"content\": \"encoding\"}`, then all fields from `encoding` will be\n\n /// used.\n\n /// - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted\n\n /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n\n /// Width of the marks.\n", "file_path": "src/schema.rs", "rank": 88, "score": 33.36670526255514 }, { "content": " ///\n\n /// - If `tooltip` is `{\"content\": \"encoding\"}`, then all fields from `encoding` will be\n\n /// used.\n\n /// - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted\n\n /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n\n /// Width of the marks.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub width: Option<f64>,\n\n /// X coordinates of the marks, or width of horizontal `\"bar\"` and `\"area\"` without specified\n\n /// `x2` or `width`.\n\n ///\n\n /// The `value` of this channel can be a number or a string `\"width\"` for the width of the\n\n /// plot.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n", "file_path": "src/schema.rs", "rank": 89, "score": 33.33606019701408 }, { "content": "/// updated, the key value will be used to match data elements to existing mark instances.\n\n/// Use a key channel to enable object constancy for transitions over dynamic data.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct TypedFieldDef {\n\n /// Aggregation function for the field\n\n /// (e.g., `mean`, `sum`, `median`, `min`, `max`, `count`).\n\n ///\n\n /// __Default value:__ `undefined` (None)\n\n ///\n\n /// __See also:__ [`aggregate`](https://vega.github.io/vega-lite/docs/aggregate.html)\n\n /// documentation.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub aggregate: Option<Aggregate>,\n\n /// A flag for binning a `quantitative` field, [an object defining binning\n\n /// parameters](https://vega.github.io/vega-lite/docs/bin.html#params), or indicating that\n\n /// the data for `x` or `y` channel are binned before they are imported into Vega-Lite\n\n /// (`\"binned\"`).\n\n ///\n", "file_path": "src/schema.rs", "rank": 90, "score": 33.119398604365614 }, { "content": "/// Orientation of the legend title.\n\n///\n\n/// The orientation of the axis. One of `\"top\"`, `\"bottom\"`, `\"left\"` or `\"right\"`. The\n\n/// orientation can be used to further specialize the axis type (e.g., a y-axis oriented\n\n/// towards the right edge of the chart).\n\n///\n\n/// __Default value:__ `\"bottom\"` for x-axes and `\"left\"` for y-axes.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum Orient {\n\n #[serde(rename = \"bottom\")]\n\n Bottom,\n\n #[serde(rename = \"left\")]\n\n Left,\n\n #[serde(rename = \"right\")]\n\n Right,\n\n #[serde(rename = \"top\")]\n\n Top,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n", "file_path": "src/schema.rs", "rank": 91, "score": 33.0118946825345 }, { "content": " /// Y2 coordinates for ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n\n ///\n\n /// The `value` of this channel can be a number or a string `\"height\"` for the height of the\n\n /// plot.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub y2: Option<XUnion>,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct PaddingClass {\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub bottom: Option<f64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub left: Option<f64>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n", "file_path": "src/schema.rs", "rank": 92, "score": 32.964317740547145 }, { "content": " pub signal: Option<String>,\n\n}\n\n\n\n/// Line-Specific Config\n\n///\n\n/// Trail-Specific Config\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct LineConfig {\n\n /// The horizontal alignment of the text. One of `\"left\"`, `\"right\"`, `\"center\"`.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub align: Option<Align>,\n\n /// The rotation angle of the text, in degrees.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub angle: Option<f64>,\n\n /// The vertical alignment of the text. One of `\"top\"`, `\"middle\"`, `\"bottom\"`.\n\n ///\n\n /// __Default value:__ `\"middle\"`\n", "file_path": "src/schema.rs", "rank": 93, "score": 32.891626560839036 }, { "content": "\n\n/// The sort order. One of `\"ascending\"` (default) or `\"descending\"`.\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum SortOrder {\n\n #[serde(rename = \"ascending\")]\n\n Ascending,\n\n #[serde(rename = \"descending\")]\n\n Descending,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum BinEnum {\n\n #[serde(rename = \"binned\")]\n\n Binned,\n\n}\n\n\n\n/// The encoded field's type of measurement (`\"quantitative\"`, `\"temporal\"`, `\"ordinal\"`, or\n\n/// `\"nominal\"`).\n\n/// It can also be a `\"geojson\"` type for encoding\n\n/// ['geoshape'](https://vega.github.io/vega-lite/docs/geoshape.html).\n", "file_path": "src/schema.rs", "rank": 94, "score": 32.85686666622888 }, { "content": " /// `x` and `y` properties. Values for `theta` follow the same convention of `arc` mark\n\n /// `startAngle` and `endAngle` properties: angles are measured in radians, with `0`\n\n /// indicating \"north\".\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub theta: Option<f64>,\n\n /// The tooltip text string to show upon mouse hover or an object defining which fields\n\n /// should the tooltip be derived from.\n\n ///\n\n /// - If `tooltip` is `{\"content\": \"encoding\"}`, then all fields from `encoding` will be\n\n /// used.\n\n /// - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted\n\n /// data point will be used.\n\n /// - If set to `null`, then no tooltip will be used.\n\n #[serde(default, skip_serializing_if = \"RemovableValue::is_default\")]\n\n #[builder(default)]\n\n pub tooltip: RemovableValue<TooltipUnion>,\n\n /// Width of the marks.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n", "file_path": "src/schema.rs", "rank": 95, "score": 32.80651404617766 }, { "content": " #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub title_padding: Option<f64>,\n\n}\n\n\n\n/// A sort definition for sorting a discrete scale in an encoding field definition.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct SortEncodingSortField {\n\n /// The data [field](https://vega.github.io/vega-lite/docs/field.html) to sort by.\n\n ///\n\n /// __Default value:__ If unspecified, defaults to the field specified in the outer data\n\n /// reference.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub field: Option<Field>,\n\n /// An [aggregate operation](https://vega.github.io/vega-lite/docs/aggregate.html#ops) to\n\n /// perform on the field prior to sorting (e.g., `\"count\"`, `\"mean\"` and `\"median\"`).\n\n /// An aggregation is required when there are multiple values of the sort field for each\n\n /// encoded data field.\n", "file_path": "src/schema.rs", "rank": 96, "score": 32.77199641409912 }, { "content": "use csv;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::path::Path;\n\nuse vega_lite_3::*;\n\n\n\n#[derive(Serialize, Deserialize)]\n\npub struct Item {\n\n pub symbol: String,\n\n pub date: String,\n\n pub price: f64,\n\n}\n\n\n", "file_path": "examples/stock_graph.rs", "rank": 97, "score": 32.124835029730484 }, { "content": "/// This can be either a string (e.g `\"bold\"`, `\"normal\"`) or a number (`100`, `200`, `300`,\n\n/// ..., `900` where `\"normal\"` = `400` and `\"bold\"` = `700`).\n\n///\n\n/// The font weight of legend label.\n\n///\n\n/// The font weight of the legend title.\n\n/// This can be either a string (e.g `\"bold\"`, `\"normal\"`) or a number (`100`, `200`, `300`,\n\n/// ..., `900` where `\"normal\"` = `400` and `\"bold\"` = `700`).\n\n///\n\n/// Font weight for title text.\n\n/// This can be either a string (e.g `\"bold\"`, `\"normal\"`) or a number (`100`, `200`, `300`,\n\n/// ..., `900` where `\"normal\"` = `400` and `\"bold\"` = `700`).\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\npub enum FontWeight {\n\n Double(f64),\n\n Enum(FontWeightEnum),\n\n}\n\n\n", "file_path": "src/schema.rs", "rank": 98, "score": 31.92239080637357 }, { "content": " /// [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN).\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub valid: Option<bool>,\n\n /// Filter using a selection name.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n\n pub selection: Option<Box<PurpleSelectionOperand>>,\n\n}\n\n\n\n/// Object for defining datetime in Vega-Lite Filter.\n\n/// If both month and quarter are provided, month has higher precedence.\n\n/// `day` cannot be combined with other date.\n\n/// We accept string for month and day names.\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, Builder)]\n\n#[builder(setter(into, strip_option))]\n\npub struct DateTime {\n\n /// Integer value representing the date from 1-31.\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n #[builder(default)]\n", "file_path": "src/schema.rs", "rank": 99, "score": 31.71827735039384 } ]
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// application to properly build the events DAG of a room.\n\nfn build_filter() -> String {\n\n let filter = serde_json::json!({\n\n \"event_fields\": [\n\n \"room_id\",\n\n \"sender\",\n\n \"origin\",\n\n \"origin_server_ts\",\n\n \"type\",\n\n \"state_key\",\n\n \"content\",\n\n \"prev_events\",\n\n \"depth\",\n\n \"auth_events\",\n\n \"redacts\",\n\n \"unsigned\",\n\n \"event_id\",\n\n \"hashes\",\n\n \"signatures\",\n\n ],\n\n \"event_format\": \"federation\",\n\n });\n\n\n\n percent_encoding::utf8_percent_encode(\n\n &serde_json::to_string(&filter).unwrap(),\n\n percent_encoding::USERINFO_ENCODE_SET,\n\n )\n\n .to_string()\n\n}\n", "file_path": "src/cs_backend/backend.rs", "rank": 0, "score": 75867.25495939772 }, { "content": "// Parses a list of events encoded as JSON values.\n\nfn parse_events(json_events: &[JsonValue]) -> Vec<Event> {\n\n json_events\n\n .iter()\n\n .map(|ev| {\n\n serde_json::from_value(ev.clone()).unwrap_or_else(|_| {\n\n panic!(\n\n \"Failed to parse event:\\n{}\",\n\n serde_json::to_string_pretty(&ev).expect(\"Failed to fail...\")\n\n )\n\n })\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/model/dag.rs", "rank": 1, "score": 57432.5860386018 }, { "content": "fn main() {\n\n yew::start_app::<matrix_visualisations::Model>();\n\n}\n", "file_path": "src/main.rs", "rank": 2, "score": 34321.356102735 }, { "content": "#[derive(Clone, Copy, Serialize)]\n\nstruct ViewId {\n\n id: usize,\n\n}\n\n\n\nimpl VisJsService {\n\n pub fn new(bk_type: Arc<RwLock<BackendChoice>>) -> Self {\n\n let lib = js! {\n\n return vis;\n\n };\n\n\n\n VisJsService {\n\n lib: Some(lib),\n\n network: None,\n\n bk_type,\n\n data: None,\n\n earliest_events: Vec::new(),\n\n latest_events: Vec::new(),\n\n orphan_events: Vec::new(),\n\n }\n\n }\n", "file_path": "src/visjs.rs", "rank": 3, "score": 34187.620234684524 }, { "content": "// This defines which fields of the event body will be displayed in the nodes of the displayed DAG.\n\nstruct FieldsChoice {\n\n sender: bool,\n\n origin: bool,\n\n origin_server_ts: bool,\n\n etype: bool,\n\n state_key: bool,\n\n prev_events: bool,\n\n depth: bool,\n\n redacts: bool,\n\n event_id: bool,\n\n\n\n fields: HashSet<Field>,\n\n}\n\n\n\npub enum Msg {\n\n UI(UIEvent),\n\n UICmd(UICommand),\n\n BkCmd(BkCommand),\n\n BkRes(BkResponse),\n\n}\n", "file_path": "src/lib.rs", "rank": 4, "score": 34186.58983343161 }, { "content": "fn new_nodes_edges(\n\n dag: &Graph<Event, ()>,\n\n from_indices: HashSet<NodeIndex>,\n\n) -> (HashSet<NodeIndex>, HashSet<(NodeIndex, NodeIndex)>) {\n\n let mut node_indices: HashSet<NodeIndex> = HashSet::from_iter(from_indices.iter().cloned());\n\n\n\n for &from_idx in from_indices.iter() {\n\n let mut bfs = Bfs::new(&dag, from_idx);\n\n\n\n while let Some(idx) = bfs.next(&dag) {\n\n node_indices.insert(idx);\n\n }\n\n }\n\n\n\n let new_node_indices: HashSet<NodeIndex> =\n\n node_indices.difference(&from_indices).cloned().collect();\n\n\n\n let mut new_edges: HashSet<(NodeIndex, NodeIndex)> = HashSet::new();\n\n\n\n for edges in new_node_indices\n", "file_path": "src/model/dag.rs", "rank": 5, "score": 29786.115106649602 }, { "content": "use std::collections::HashSet;\n\n\n\nuse serde_derive::{Deserialize, Serialize};\n\nuse serde_json::Value as JsonValue;\n\n\n\nuse super::dag::{DataSetNode, NodeColor};\n\n\n\n/// The internal representation of an event in the DAG.\n\n#[derive(Default, Clone, Deserialize, Serialize)]\n\npub struct Event {\n\n room_id: String, // Room identifier\n\n sender: String, // The ID of the user who has sent this event\n\n origin: String, // The `server_name` of the homeserver which created this event\n\n origin_server_ts: i64, // Timestamp in milliseconds on origin homeserver when this event was created\n\n #[serde(rename = \"type\")]\n\n etype: String, // Event type\n\n state_key: Option<String>, // Indicate whether this event is a state event\n\n content: JsonValue, // The content of the event\n\n prev_events: Vec<JsonValue>, // Event IDs for the most recent events in the room that the homeserver was aware of when it made this event\n\n pub depth: i64, // The maximum depth of the `prev_events`, plus one\n", "file_path": "src/model/event.rs", "rank": 6, "score": 24810.336829548498 }, { "content": " }\n\n\n\n if fields.contains(&Field::Redacts) {\n\n if let Some(redacts) = &self.redacts {\n\n label.push_str(&format!(\"Redacts: {}\\n\", redacts));\n\n }\n\n }\n\n\n\n if fields.contains(&Field::EventID) {\n\n label.push_str(&format!(\"Event ID: {}\\n\", self.event_id));\n\n }\n\n\n\n label.trim_end().to_string()\n\n }\n\n}\n\n\n\nimpl PartialEq for Event {\n\n fn eq(&self, other: &Event) -> bool {\n\n self.event_id == other.event_id\n\n }\n\n}\n\n\n\nimpl Eq for Event {}\n", "file_path": "src/model/event.rs", "rank": 7, "score": 24804.69007407753 }, { "content": "}\n\n\n\nimpl Event {\n\n /// This function is needed because the content of a the `prev_events` field can change\n\n /// across the versions of rooms.\n\n pub fn get_prev_events(&self) -> Vec<&str> {\n\n self.prev_events\n\n .iter()\n\n .map(|prev_ev| {\n\n if prev_ev.is_array() {\n\n prev_ev[0].as_str().unwrap()\n\n } else {\n\n prev_ev.as_str().unwrap()\n\n }\n\n })\n\n .collect()\n\n }\n\n\n\n /// Convert an event in a format usable by vis.js.\n\n /// `server_name` must be the HS from which the DAG was retrieved for coloring the node.\n", "file_path": "src/model/event.rs", "rank": 8, "score": 24803.344579178975 }, { "content": "\n\n if fields.contains(&Field::StateKey) {\n\n if let Some(state_key) = &self.state_key {\n\n label.push_str(&format!(\"State key: {}\\n\", state_key));\n\n }\n\n }\n\n\n\n if fields.contains(&Field::PrevEvents) {\n\n label.push_str(\"Previous events:\");\n\n\n\n for prev_ev in self.get_prev_events() {\n\n label.push(' ');\n\n label.push_str(prev_ev);\n\n }\n\n\n\n label.push('\\n');\n\n }\n\n\n\n if fields.contains(&Field::Depth) {\n\n label.push_str(&format!(\"Depth: {}\\n\", self.depth));\n", "file_path": "src/model/event.rs", "rank": 9, "score": 24803.254883883576 }, { "content": " /// `fields` is a set of events fields to include in the label.\n\n pub fn to_data_set_node(&self, server_name: &str, fields: &HashSet<Field>) -> DataSetNode {\n\n let (border_color, background_color) = if self.origin == server_name {\n\n (\"#006633\".to_string(), \"#009900\".to_string())\n\n } else {\n\n (\"#990000\".to_string(), \"#ff6600\".to_string())\n\n };\n\n\n\n DataSetNode {\n\n id: self.event_id.clone(),\n\n label: self.label(&fields),\n\n level: self.depth,\n\n color: NodeColor {\n\n border: border_color,\n\n background: background_color,\n\n },\n\n }\n\n }\n\n\n\n fn label(&self, fields: &HashSet<Field>) -> String {\n", "file_path": "src/model/event.rs", "rank": 10, "score": 24802.51026462729 }, { "content": " auth_events: Vec<JsonValue>, // Event IDs and reference hashes for the authorization events that would allow this event to be in the room\n\n redacts: Option<String>, // For redaction events, the ID of the event being redacted\n\n unsigned: Option<JsonValue>, // Additional data added by the origin server but not covered by the `signatures`\n\n pub event_id: String, // The event ID\n\n hashes: JsonValue, // Content hashes of the PDU, following the algorithm specified in `Signing Events`\n\n signatures: JsonValue, // Signatures for the PDU, following the algorithm specified in `Signing Events`\n\n}\n\n\n\n/// Defines the fields of the events which will be included in the labels of the DAG's nodes.\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\n\npub enum Field {\n\n Sender,\n\n Origin,\n\n OriginServerTS,\n\n Type,\n\n StateKey,\n\n PrevEvents,\n\n Depth,\n\n Redacts,\n\n EventID,\n", "file_path": "src/model/event.rs", "rank": 11, "score": 24802.118650316002 }, { "content": " let mut label = String::new();\n\n\n\n if fields.contains(&Field::Sender) {\n\n label.push_str(&format!(\"Sender: {}\\n\", self.sender));\n\n }\n\n\n\n if fields.contains(&Field::Origin) {\n\n label.push_str(&format!(\"Origin: {}\\n\", self.origin));\n\n }\n\n\n\n if fields.contains(&Field::OriginServerTS) {\n\n label.push_str(&format!(\n\n \"Origin server time stamp: {}\\n\",\n\n self.origin_server_ts\n\n ));\n\n }\n\n\n\n if fields.contains(&Field::Type) {\n\n label.push_str(&format!(\"Type: {}\\n\", self.etype));\n\n }\n", "file_path": "src/model/event.rs", "rank": 12, "score": 24800.60823167716 }, { "content": "#[derive(Clone, Debug)]\n\npub struct Session {\n\n pub server_name: String,\n\n pub room_id: String,\n\n pub connected: bool,\n\n}\n\n\n\nimpl Session {\n\n pub fn empty() -> Self {\n\n Session {\n\n server_name: String::new(),\n\n room_id: String::new(),\n\n connected: false,\n\n }\n\n }\n\n}\n", "file_path": "src/mv_backend/session.rs", "rank": 13, "score": 23230.94998114278 }, { "content": "/// Holds every informations allowing the application to communicate with the homeserver and\n\n/// retrieve the events of the room to observe.\n\n#[derive(Clone, Debug)]\n\npub struct Session {\n\n pub server_name: String,\n\n pub room_id: String,\n\n\n\n pub username: String,\n\n pub user_id: String,\n\n pub password: String,\n\n pub access_token: Option<String>,\n\n\n\n pub device_id: Option<String>,\n\n pub filter_id: Option<String>,\n\n pub next_batch_token: Option<String>,\n\n pub prev_batch_token: Option<String>,\n\n}\n\n\n\nimpl Session {\n\n pub fn empty() -> Self {\n", "file_path": "src/cs_backend/session.rs", "rank": 14, "score": 23230.186135644384 }, { "content": " Session {\n\n server_name: String::new(),\n\n room_id: String::new(),\n\n\n\n username: String::new(),\n\n user_id: String::new(),\n\n password: String::new(),\n\n\n\n access_token: None,\n\n\n\n device_id: None,\n\n filter_id: None,\n\n next_batch_token: None,\n\n prev_batch_token: None,\n\n }\n\n }\n\n}\n", "file_path": "src/cs_backend/session.rs", "rank": 15, "score": 23221.185340393877 }, { "content": "#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n\npub struct ContextResponse {\n\n pub start: String,\n\n pub end: String,\n\n pub events_before: Vec<JsonValue>,\n\n pub event: JsonValue,\n\n pub events_after: Vec<JsonValue>,\n\n pub state: Vec<JsonValue>,\n\n}\n\n\n\nimpl CSBackend {\n\n /// Creates a new CS backend linked to the given `session`.\n\n pub fn with_session(session: Arc<RwLock<Session>>) -> Self {\n\n CSBackend {\n\n fetch: FetchService::new(),\n\n session,\n\n }\n\n }\n\n\n\n /// Sends a login request to the homeserver and then calls `callback` when it gets the\n", "file_path": "src/cs_backend/backend.rs", "rank": 23, "score": 25.831873117021765 }, { "content": " .header(\"Authorization\", format!(\"Bearer {}\", access_token.unwrap()))\n\n .body(Nothing)\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Nothing>| {\n\n let (meta, _) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n\n callback.emit(Ok(()))\n\n } else {\n\n callback.emit(Err(format_err!(\"{}: error joining the room\", meta.status)))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n\n }\n\n\n\n /// Sends a request to the homeserver for making the initial sync or receiving new events and\n\n /// then calls `callback` when it gets the response.\n\n pub fn sync(\n", "file_path": "src/cs_backend/backend.rs", "rank": 24, "score": 25.559902882428027 }, { "content": " ancestors_task: Option<FetchTask>,\n\n\n\n stop_callback: Callback<Result<(), Error>>,\n\n stop_task: Option<FetchTask>,\n\n\n\n descendants_callback: Callback<Result<EventsResponse, Error>>,\n\n descendants_task: Option<FetchTask>,\n\n descendants_timeout_task: Option<TimeoutTask>,\n\n\n\n state_callback: Callback<Result<EventsResponse, Error>>,\n\n state_task: Option<FetchTask>,\n\n\n\n session: Arc<RwLock<MVSession>>,\n\n backend: MatrixVisualisationsBackend,\n\n events_dag: Option<Arc<RwLock<RoomEvents>>>,\n\n}\n\n\n\nimpl MVView {\n\n pub fn new(id: ViewIndex, link: &mut ComponentLink<Model>) -> MVView {\n\n let session = Arc::new(RwLock::new(MVSession::empty()));\n", "file_path": "src/lib.rs", "rank": 25, "score": 24.315725422660666 }, { "content": " let request = Request::get(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\"Authorization\", format!(\"Bearer {}\", access_token.unwrap()))\n\n .body(Nothing)\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Json<Result<MessagesResponse, Error>>>| {\n\n let (meta, Json(data)) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n\n callback.emit(data)\n\n } else {\n\n callback.emit(Err(format_err!(\n\n \"{}: error retrieving previous messages\",\n\n meta.status\n\n )))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n", "file_path": "src/cs_backend/backend.rs", "rank": 27, "score": 23.901353091719677 }, { "content": " let uri = format!(\"https://{}/_matrix/client/r0/logout\", server_name);\n\n\n\n let request = Request::post(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\n\n \"Authorization\",\n\n format!(\"Bearer {}\", access_token.expect(\"No access token\")),\n\n )\n\n .body(Nothing)\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Nothing>| {\n\n let (meta, _) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n\n callback.emit(Ok(()))\n\n } else {\n\n callback.emit(Err(format_err!(\"{}: error disconnecting\", meta.status)))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n\n }\n\n}\n\n\n\n// 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// application to properly build the events DAG of a room.\n", "file_path": "src/cs_backend/backend.rs", "rank": 28, "score": 23.84950021791036 }, { "content": " let uri = Uri::builder()\n\n .scheme(\"https\")\n\n .authority(server_name.as_str())\n\n .path_and_query(query_params.as_str())\n\n .build()\n\n .expect(\"Failed to build URI.\");\n\n\n\n let request = Request::get(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\"Authorization\", format!(\"Bearer {}\", access_token.unwrap()))\n\n .body(Nothing)\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Json<Result<SyncResponse, Error>>>| {\n\n let (meta, Json(data)) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n\n callback.emit(data)\n\n } else {\n\n callback.emit(Err(format_err!(\"{}: error syncing\", meta.status)))\n", "file_path": "src/cs_backend/backend.rs", "rank": 29, "score": 23.753688968223713 }, { "content": "\n\n if meta.status.is_success() {\n\n callback.emit(Ok(()))\n\n } else {\n\n callback.emit(Err(format_err!(\"{}: error leaving the room\", meta.status)))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n\n }\n\n\n\n /// Sends a request to the homeserver to logout and then calls `callback` when it gets the\n\n /// response.\n\n pub fn disconnect(&mut self, callback: Callback<Result<(), Error>>) -> FetchTask {\n\n let (server_name, access_token) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (session.server_name.clone(), session.access_token.clone())\n\n };\n\n\n", "file_path": "src/cs_backend/backend.rs", "rank": 30, "score": 23.334455853166773 }, { "content": "use std::collections::HashMap;\n\nuse std::sync::{Arc, RwLock};\n\n\n\nuse failure::{format_err, Error};\n\nuse serde_derive::{Deserialize, Serialize};\n\nuse serde_json::Value as JsonValue;\n\nuse yew::callback::Callback;\n\nuse yew::format::{Json, Nothing};\n\nuse yew::services::fetch::{FetchService, FetchTask, Request, Response, Uri};\n\n\n\nuse super::session::Session;\n\n\n\n/// Represents the backend used to communicate with a homeserver via the Client-Server HTTP REST\n\n/// API.\n\npub struct CSBackend {\n\n fetch: FetchService,\n\n session: Arc<RwLock<Session>>,\n\n}\n\n\n\n/// Represents the JSON body of a `POST /_matrix/client/r0/login` request.\n", "file_path": "src/cs_backend/backend.rs", "rank": 31, "score": 23.09362505630052 }, { "content": " }\n\n\n\n pub fn room_state(\n\n &mut self,\n\n callback: Callback<Result<ContextResponse, Error>>,\n\n event_id: &str,\n\n ) -> FetchTask {\n\n let (server_name, access_token, room_id) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (\n\n session.server_name.clone(),\n\n session.access_token.clone(),\n\n session.room_id.clone(),\n\n )\n\n };\n\n\n\n let uri = Uri::builder()\n\n .scheme(\"https\")\n\n .authority(server_name.as_str())\n", "file_path": "src/cs_backend/backend.rs", "rank": 32, "score": 23.093223416208797 }, { "content": " };\n\n\n\n let uri = format!(\"https://{}/_matrix/client/r0/login\", server_name);\n\n\n\n let request = Request::post(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .body(Json(&body))\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Json<Result<ConnectionResponse, Error>>>| {\n\n let (meta, Json(data)) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n\n callback.emit(data)\n\n } else {\n\n callback.emit(Err(format_err!(\"{}: error connecting\", meta.status)))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n", "file_path": "src/cs_backend/backend.rs", "rank": 33, "score": 22.80591495367773 }, { "content": " pub fn join_room(&mut self, callback: Callback<Result<(), Error>>) -> FetchTask {\n\n let (server_name, access_token, room_id) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (\n\n session.server_name.clone(),\n\n session.access_token.clone(),\n\n session.room_id.clone(),\n\n )\n\n };\n\n\n\n let uri = Uri::builder()\n\n .scheme(\"https\")\n\n .authority(server_name.as_str())\n\n .path_and_query(format!(\"/_matrix/client/r0/rooms/{}/join\", room_id).as_str())\n\n .build()\n\n .expect(\"Failed to build URI.\");\n\n\n\n let request = Request::post(uri)\n\n .header(\"Content-Type\", \"application/json\")\n", "file_path": "src/cs_backend/backend.rs", "rank": 34, "score": 22.622468341563412 }, { "content": " callback.emit(data)\n\n } else {\n\n callback.emit(Err(format_err!(\n\n \"{}: error retrieving previous messages\",\n\n meta.status\n\n )))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n\n }\n\n\n\n /// Sends a request to the homeserver to leave the room which was observed and then calls\n\n /// `callback` when it gets the response.\n\n pub fn leave_room(&mut self, callback: Callback<Result<(), Error>>) -> FetchTask {\n\n let (server_name, access_token, room_id) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (\n\n session.server_name.clone(),\n", "file_path": "src/cs_backend/backend.rs", "rank": 35, "score": 22.32502560441317 }, { "content": " session.access_token.clone(),\n\n session.room_id.clone(),\n\n )\n\n };\n\n\n\n let uri = Uri::builder()\n\n .scheme(\"https\")\n\n .authority(server_name.as_str())\n\n .path_and_query(format!(\"/_matrix/client/r0/rooms/{}/leave\", room_id).as_str())\n\n .build()\n\n .expect(\"Failed to build URI.\");\n\n\n\n let request = Request::post(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\"Authorization\", format!(\"Bearer {}\", access_token.unwrap()))\n\n .body(Nothing)\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Nothing>| {\n\n let (meta, _) = response.into_parts();\n", "file_path": "src/cs_backend/backend.rs", "rank": 36, "score": 21.822262144960263 }, { "content": " .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Json<Result<JoinedRooms, Error>>>| {\n\n let (meta, Json(data)) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n\n callback.emit(data)\n\n } else {\n\n callback.emit(Err(format_err!(\n\n \"{}: error listing joined rooms\",\n\n meta.status\n\n )))\n\n }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n\n }\n\n\n\n /// Sends a request to the homeserver to join the room to observe and then calls `callback`\n\n /// when it gets the response.\n", "file_path": "src/cs_backend/backend.rs", "rank": 37, "score": 21.682806033800407 }, { "content": " .path_and_query(\n\n format!(\n\n \"/_matrix/client/r0/rooms/{}/context/{}?limit=0\",\n\n room_id, event_id,\n\n )\n\n .as_str(),\n\n )\n\n .build()\n\n .expect(\"Failed to build URI.\");\n\n\n\n let request = Request::get(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\"Authorization\", format!(\"Bearer {}\", access_token.unwrap()))\n\n .body(Nothing)\n\n .expect(\"Failed to build request.\");\n\n\n\n let handler = move |response: Response<Json<Result<ContextResponse, Error>>>| {\n\n let (meta, Json(data)) = response.into_parts();\n\n\n\n if meta.status.is_success() {\n", "file_path": "src/cs_backend/backend.rs", "rank": 38, "score": 21.5038825807629 }, { "content": " }\n\n };\n\n\n\n self.fetch.fetch(request, handler.into())\n\n }\n\n\n\n /// Sends a request to the homeserver to get earlier events from the room to observe and then\n\n /// calls `callback` when it gets the response.\n\n pub fn get_prev_messages(\n\n &mut self,\n\n callback: Callback<Result<MessagesResponse, Error>>,\n\n ) -> FetchTask {\n\n let (server_name, access_token, room_id, prev_batch_token) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (\n\n session.server_name.clone(),\n\n session.access_token.clone(),\n\n session.room_id.clone(),\n\n session.prev_batch_token.clone(),\n", "file_path": "src/cs_backend/backend.rs", "rank": 40, "score": 20.2031249605221 }, { "content": " },\n\n ),\n\n disconnection_task: None,\n\n\n\n session: session.clone(),\n\n backend: CSBackend::with_session(session),\n\n events_dag: None,\n\n }\n\n }\n\n}\n\n\n\n// This contains every informations needed for the observation of a room from a given HS by using\n\n// the Matrix Visualisations' backend.\n\npub struct MVView {\n\n id: ViewIndex,\n\n\n\n deepest_callback: Callback<Result<EventsResponse, Error>>,\n\n deepest_task: Option<FetchTask>,\n\n\n\n ancestors_callback: Callback<Result<EventsResponse, Error>>,\n", "file_path": "src/lib.rs", "rank": 41, "score": 19.375646460728593 }, { "content": " }\n\n\n\n /// Sends a request to the homeserver in order to get the list of the rooms currently joined\n\n /// by the user and then calls `callback` when it gets the response.\n\n pub fn list_rooms(&mut self, callback: Callback<Result<JoinedRooms, Error>>) -> FetchTask {\n\n let (server_name, access_token) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (session.server_name.clone(), session.access_token.clone())\n\n };\n\n\n\n let uri = format!(\"https://{}/_matrix/client/r0/joined_rooms\", server_name);\n\n\n\n let request = Request::get(uri)\n\n .header(\"Content-Type\", \"application/json\")\n\n .header(\n\n \"Authorization\",\n\n format!(\"Bearer {}\", access_token.expect(\"No access token\")),\n\n )\n\n .body(Nothing)\n", "file_path": "src/cs_backend/backend.rs", "rank": 42, "score": 18.516487127445522 }, { "content": " /// response.\n\n pub fn connect(&mut self, callback: Callback<Result<ConnectionResponse, Error>>) -> FetchTask {\n\n let (server_name, username, password) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (\n\n session.server_name.clone(),\n\n session.username.clone(),\n\n session.password.clone(),\n\n )\n\n };\n\n\n\n let body = ConnectionRequest {\n\n typo: String::from(\"m.login.password\"),\n\n identifier: Identifier {\n\n typo: String::from(\"m.id.user\"),\n\n user: username,\n\n },\n\n password,\n\n initial_device_display_name: String::from(\"Matrix visualisations\"),\n", "file_path": "src/cs_backend/backend.rs", "rank": 43, "score": 18.13264811634621 }, { "content": " leaving_room_task: Option<FetchTask>,\n\n\n\n disconnection_callback: Callback<Result<(), Error>>,\n\n disconnection_task: Option<FetchTask>,\n\n\n\n session: Arc<RwLock<CSSession>>,\n\n backend: CSBackend,\n\n events_dag: Option<Arc<RwLock<RoomEvents>>>,\n\n}\n\n\n\nimpl CSView {\n\n pub fn new(id: ViewIndex, link: &mut ComponentLink<Model>) -> CSView {\n\n let session = Arc::new(RwLock::new(CSSession::empty()));\n\n\n\n CSView {\n\n id,\n\n\n\n connection_callback: link.send_back(\n\n move |response: Result<ConnectionResponse, Error>| match response {\n\n Ok(res) => Msg::BkRes(BkResponse::Connected(id, res)),\n", "file_path": "src/lib.rs", "rank": 44, "score": 17.097491326222727 }, { "content": "/// application must build for the observed room.\n\n#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n\npub struct Timeline {\n\n #[serde(default)]\n\n pub limited: bool,\n\n pub prev_batch: Option<String>,\n\n // TODO: Implement RoomEvent\n\n #[serde(default)]\n\n pub events: Vec<JsonValue>,\n\n}\n\n\n\n/// Represents the JSON body of a response to a `GET /_matrix/client/r0/rooms/{roomId}/messages`\n\n/// request.\n\n#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n\npub struct MessagesResponse {\n\n pub start: String,\n\n pub end: String,\n\n pub chunk: Vec<JsonValue>,\n\n}\n\n\n", "file_path": "src/cs_backend/backend.rs", "rank": 45, "score": 16.83208314272504 }, { "content": " &mut self,\n\n callback: Callback<Result<SyncResponse, Error>>,\n\n next_batch_token: Option<String>,\n\n ) -> FetchTask {\n\n let (server_name, access_token) = {\n\n let session = self.session.read().unwrap();\n\n\n\n (session.server_name.clone(), session.access_token.clone())\n\n };\n\n\n\n let filter = build_filter();\n\n let mut query_params = format!(\n\n \"/_matrix/client/r0/sync?filter={}&set_presence=offline&timeout=5000\",\n\n filter\n\n );\n\n if let Some(next_batch_token) = next_batch_token {\n\n query_params.push_str(\"&since=\");\n\n query_params.push_str(&next_batch_token);\n\n }\n\n\n", "file_path": "src/cs_backend/backend.rs", "rank": 46, "score": 16.776612911479713 }, { "content": "#[derive(Debug, Deserialize, Serialize)]\n\npub struct ConnectionRequest {\n\n #[serde(rename = \"type\")]\n\n typo: String,\n\n identifier: Identifier,\n\n password: String,\n\n initial_device_display_name: String,\n\n}\n\n\n\n/// Represents the `identifier` field in `ConnectionRequest`.\n\n#[derive(Debug, Deserialize, Serialize)]\n\npub struct Identifier {\n\n #[serde(rename = \"type\")]\n\n typo: String,\n\n user: String,\n\n}\n\n\n\n/// Represents the JSON body of a response to a `POST /_matrix/client/r0/login` request.\n\n#[derive(Debug, Deserialize)]\n\npub struct ConnectionResponse {\n", "file_path": "src/cs_backend/backend.rs", "rank": 47, "score": 15.769701017385081 }, { "content": " DeepestEvents(ViewIndex, EventsResponse),\n\n Ancestors(ViewIndex, EventsResponse),\n\n Descendants(ViewIndex, EventsResponse),\n\n State(ViewIndex, EventsResponse),\n\n\n\n DeepestRqFailed(ViewIndex),\n\n AncestorsRqFailed(ViewIndex),\n\n DescendantsRqFailed(ViewIndex),\n\n StateRqFailed(ViewIndex),\n\n}\n\n\n\nimpl Component for Model {\n\n type Message = Msg;\n\n type Properties = ();\n\n\n\n fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {\n\n let bk_type = Arc::new(RwLock::new(BackendChoice::CS));\n\n let default_view = vec![View::CS(CSView::new(0, &mut link))];\n\n\n\n let default_fields_choice = FieldsChoice {\n", "file_path": "src/lib.rs", "rank": 48, "score": 15.608238885532497 }, { "content": "use failure::Error;\n\nuse stdweb::unstable::TryInto;\n\nuse stdweb::web;\n\nuse stdweb::web::IParentNode;\n\nuse yew::services::fetch::FetchTask;\n\nuse yew::services::timeout::TimeoutTask;\n\nuse yew::services::{ConsoleService, TimeoutService};\n\nuse yew::{html, Callback, Component, ComponentLink, Html, Renderable, ShouldRender};\n\n\n\nuse cs_backend::backend::{\n\n CSBackend, ConnectionResponse, ContextResponse, JoinedRooms, MessagesResponse, SyncResponse,\n\n};\n\nuse cs_backend::session::Session as CSSession;\n\nuse model::dag::RoomEvents;\n\nuse model::event::Field;\n\nuse mv_backend::backend::{EventsResponse, MatrixVisualisationsBackend};\n\nuse mv_backend::session::Session as MVSession;\n\nuse visjs::VisJsService;\n\n\n\npub type ViewIndex = usize;\n", "file_path": "src/lib.rs", "rank": 49, "score": 14.912662575761027 }, { "content": " descendants_callback: link.send_back(move |response: Result<EventsResponse, Error>| {\n\n match response {\n\n Ok(res) => Msg::BkRes(BkResponse::Descendants(id, res)),\n\n Err(_) => Msg::BkRes(BkResponse::DescendantsRqFailed(id)),\n\n }\n\n }),\n\n descendants_task: None,\n\n descendants_timeout_task: None,\n\n\n\n state_callback: link.send_back(move |response: Result<EventsResponse, Error>| {\n\n match response {\n\n Ok(res) => Msg::BkRes(BkResponse::State(id, res)),\n\n Err(_) => Msg::BkRes(BkResponse::StateRqFailed(id)),\n\n }\n\n }),\n\n state_task: None,\n\n\n\n stop_callback: link.send_back(move |response: Result<(), Error>| match response {\n\n Ok(_) => Msg::BkRes(BkResponse::Disconnected(id)),\n\n Err(_) => Msg::BkRes(BkResponse::DisconnectionFailed(id)),\n", "file_path": "src/lib.rs", "rank": 50, "score": 14.704377328580504 }, { "content": " view.ancestors_task = None;\n\n }\n\n }\n\n BkResponse::DescendantsRqFailed(view_id) => {\n\n self.console\n\n .log(\"Could not retrieve the events' descendants\");\n\n\n\n if let View::MV(view) = &mut self.views[view_id] {\n\n view.descendants_task = None;\n\n }\n\n }\n\n BkResponse::StateRqFailed(view_id) => {\n\n self.console.log(\"Could not fetch the state of the room\");\n\n\n\n if let View::MV(view) = &mut self.views[view_id] {\n\n view.state_task = None;\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/lib.rs", "rank": 51, "score": 14.187988091818585 }, { "content": " pub user_id: String,\n\n pub access_token: String,\n\n pub device_id: String,\n\n}\n\n\n\n/// Represents the JSON body of a response to a `GET /_matrix/client/r0/joined_rooms` request.\n\n#[derive(Debug, Deserialize)]\n\npub struct JoinedRooms {\n\n pub joined_rooms: Vec<String>,\n\n}\n\n\n\n/// Represents the JSON body of a response to a `GET /_matrix/client/r0/sync` request.\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\n\npub struct SyncResponse {\n\n pub next_batch: String,\n\n #[serde(default)]\n\n pub rooms: Rooms,\n\n presence: Option<JsonValue>,\n\n #[serde(default)]\n\n account_data: JsonValue,\n", "file_path": "src/cs_backend/backend.rs", "rank": 52, "score": 13.482620291749424 }, { "content": "\n\n connection_callback: Callback<Result<ConnectionResponse, Error>>,\n\n connection_task: Option<FetchTask>,\n\n\n\n listing_rooms_callback: Callback<Result<JoinedRooms, Error>>,\n\n listing_rooms_task: Option<FetchTask>,\n\n\n\n joining_room_callback: Callback<Result<(), Error>>,\n\n joining_room_task: Option<FetchTask>,\n\n\n\n sync_callback: Callback<Result<SyncResponse, Error>>,\n\n sync_task: Option<FetchTask>,\n\n\n\n more_msg_callback: Callback<Result<MessagesResponse, Error>>,\n\n more_msg_task: Option<FetchTask>,\n\n\n\n state_callback: Callback<Result<ContextResponse, Error>>,\n\n state_task: Option<FetchTask>,\n\n\n\n leaving_room_callback: Callback<Result<(), Error>>,\n", "file_path": "src/lib.rs", "rank": 53, "score": 13.43425492054755 }, { "content": " #[serde(default)]\n\n pub unread_notifications: JsonValue,\n\n #[serde(default)]\n\n pub timeline: Timeline,\n\n #[serde(default)]\n\n pub state: State,\n\n #[serde(default)]\n\n pub account_data: JsonValue,\n\n #[serde(default)]\n\n pub ephemeral: JsonValue,\n\n}\n\n\n\n#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n\npub struct State {\n\n // TODO: Implement StateEvent\n\n #[serde(default)]\n\n pub events: Vec<JsonValue>,\n\n}\n\n\n\n/// Represents the timeline of a room in `SyncResponse`. These are the events of the DAG the\n", "file_path": "src/cs_backend/backend.rs", "rank": 54, "score": 13.217351121352698 }, { "content": " to: String,\n\n}\n\n\n\nimpl RoomEvents {\n\n /// Creates an event DAG from the initial `SyncResponse`.\n\n pub fn from_sync_response(\n\n room_id: &str,\n\n server_name: &str,\n\n fields: &HashSet<Field>,\n\n res: SyncResponse,\n\n ) -> Option<RoomEvents> {\n\n match res.rooms.join.get(room_id) {\n\n Some(room) => {\n\n let timeline = parse_events(&room.timeline.events);\n\n\n\n let mut dag = RoomEvents {\n\n server_name: server_name.to_string(),\n\n fields: fields.clone(),\n\n\n\n dag: Graph::new(),\n", "file_path": "src/model/dag.rs", "rank": 55, "score": 13.19353813698424 }, { "content": "\n\n MVView {\n\n id,\n\n\n\n deepest_callback: link.send_back(move |response: Result<EventsResponse, Error>| {\n\n match response {\n\n Ok(res) => Msg::BkRes(BkResponse::DeepestEvents(id, res)),\n\n Err(_) => Msg::BkRes(BkResponse::DeepestRqFailed(id)),\n\n }\n\n }),\n\n deepest_task: None,\n\n\n\n ancestors_callback: link.send_back(move |response: Result<EventsResponse, Error>| {\n\n match response {\n\n Ok(res) => Msg::BkRes(BkResponse::Ancestors(id, res)),\n\n Err(_) => Msg::BkRes(BkResponse::AncestorsRqFailed(id)),\n\n }\n\n }),\n\n ancestors_task: None,\n\n\n", "file_path": "src/lib.rs", "rank": 56, "score": 12.170332322434545 }, { "content": " state_callback: link.send_back(move |response: Result<ContextResponse, Error>| {\n\n match response {\n\n Ok(res) => Msg::BkRes(BkResponse::StateFetched(id, res)),\n\n Err(_) => Msg::BkRes(BkResponse::FetchStateFailed(id)),\n\n }\n\n }),\n\n state_task: None,\n\n\n\n leaving_room_callback: link.send_back(\n\n move |response: Result<(), Error>| match response {\n\n Ok(_) => Msg::BkRes(BkResponse::RoomLeft(id)),\n\n Err(_) => Msg::BkRes(BkResponse::LeavingRoomFailed(id)),\n\n },\n\n ),\n\n leaving_room_task: None,\n\n\n\n disconnection_callback: link.send_back(\n\n move |response: Result<(), Error>| match response {\n\n Ok(_) => Msg::BkRes(BkResponse::Disconnected(id)),\n\n Err(_) => Msg::BkRes(BkResponse::DisconnectionFailed(id)),\n", "file_path": "src/lib.rs", "rank": 57, "score": 12.146776001386492 }, { "content": " edges: Vec<DataSetEdge>,\n\n}\n\n\n\nimpl DataSet {\n\n /// Adds a prefix `pref` to the events in the `DataSet` so that they can be associated with\n\n /// a certain view identified in `pref`.\n\n pub fn add_prefix(&mut self, pref: &str) {\n\n for n in &mut self.nodes {\n\n n.id.insert_str(0, pref);\n\n }\n\n\n\n for e in &mut self.edges {\n\n e.id.insert_str(0, pref);\n\n e.from.insert_str(0, pref);\n\n e.to.insert_str(0, pref);\n\n }\n\n }\n\n}\n\n\n\n/// A node of the vis.js data set.\n", "file_path": "src/model/dag.rs", "rank": 58, "score": 12.001220711240803 }, { "content": " self.console.log(\"Disconnected\");\n\n\n\n view.sync_task = None; // If a `/sync` request was in progress, cancel it\n\n view.disconnection_task = None;\n\n\n\n let mut session = view.session.write().unwrap();\n\n\n\n // Erase the current session data so they won't be erroneously used if the user\n\n // logs in again\n\n session.access_token = None;\n\n session.device_id = None;\n\n session.filter_id = None;\n\n session.next_batch_token = None;\n\n session.prev_batch_token = None;\n\n\n\n view.events_dag = None;\n\n self.vis.remove_dag(view_id);\n\n\n\n self.event_body = None;\n\n self.room_state = None;\n", "file_path": "src/lib.rs", "rank": 59, "score": 11.99911821824005 }, { "content": "\n\n self.room_state = match serde_json::to_string_pretty(&res) {\n\n Ok(state) => Some(state),\n\n Err(_) => None,\n\n };\n\n }\n\n }\n\n\n\n BkResponse::DeepestRqFailed(view_id) => {\n\n self.console\n\n .log(\"Could not retrieve the room's deepest events\");\n\n\n\n if let View::MV(view) = &mut self.views[view_id] {\n\n view.deepest_task = None;\n\n }\n\n }\n\n BkResponse::AncestorsRqFailed(view_id) => {\n\n self.console.log(\"Could not retrieve the events' ancestors\");\n\n\n\n if let View::MV(view) = &mut self.views[view_id] {\n", "file_path": "src/lib.rs", "rank": 60, "score": 11.943154170491246 }, { "content": " dag: Graph<Event, (), Directed>, // The DAG of the events\n\n events_map: HashMap<String, NodeIndex>, // Allows to quickly locate an event in the DAG with its ID\n\n depth_map: HashMap<i64, Vec<NodeIndex>>, // Allows to quickly locate events at a given depth in the DAG\n\n pub latest_events: Vec<String>, // The ID of the latest events in the DAG\n\n pub earliest_events: Vec<String>, // The ID of the earliest events in the DAG\n\n pub orphan_events: Vec<OrphanInfo>, // The ID and depth of events with missing ancestors in the DAG\n\n max_depth: i64, // Minimal depth of the events in the DAG\n\n min_depth: i64, // Maximal depth of the events in the DAG\n\n}\n\n\n\n#[derive(Clone, Debug, Serialize)]\n\npub struct OrphanInfo {\n\n id: String,\n\n depth: i64,\n\n}\n\n\n\n/// The data set containing events which will be added to the vis.js network.\n\n#[derive(Debug, Default, Serialize)]\n\npub struct DataSet {\n\n nodes: Vec<DataSetNode>,\n", "file_path": "src/model/dag.rs", "rank": 61, "score": 11.893691252446501 }, { "content": "pub struct VisJsService {\n\n lib: Option<Value>,\n\n network: Option<Value>,\n\n bk_type: Arc<RwLock<BackendChoice>>,\n\n data: Option<Value>,\n\n earliest_events: Vec<Vec<String>>,\n\n latest_events: Vec<Vec<String>>,\n\n orphan_events: Vec<Vec<OrphanInfo>>,\n\n}\n\n\n\n// This enables the serialization of the ID of a view, so it can be used within the `js!`\n\n// macro.\n\n#[derive(Clone, Copy, Serialize)]\n", "file_path": "src/visjs.rs", "rank": 62, "score": 11.82935346323441 }, { "content": " .expect(\"Couldn't get document element\")\n\n .expect(\"Couldn't get document element\")\n\n .try_into()\n\n .unwrap();\n\n let event_id = event_id_input.raw_value();\n\n\n\n match &mut self.views[view_id] {\n\n View::CS(view) => match view.state_task {\n\n None => {\n\n view.state_task = Some(\n\n view.backend\n\n .room_state(view.state_callback.clone(), &event_id),\n\n )\n\n }\n\n Some(_) => self.console.log(\"Already fetching the state of the room\"),\n\n },\n\n View::MV(view) => match view.state_task {\n\n None => {\n\n view.state_task =\n\n Some(view.backend.state(view.state_callback.clone(), &event_id))\n", "file_path": "src/lib.rs", "rank": 63, "score": 11.78704858526788 }, { "content": "\n\n /// Creates and initialises the vis.js network as well as its parameters and callback\n\n /// functions for interacting with it.\n\n pub fn init(\n\n &mut self,\n\n container_id: &str,\n\n targeted_view_input_id: &str,\n\n more_ev_btn_id: &str,\n\n selected_event_input_id: &str,\n\n display_body_btn_id: &str,\n\n ancestors_input_id: &str,\n\n ancestors_btn_id: &str,\n\n ) {\n\n let lib = self.lib.as_ref().expect(\"vis library object lost\");\n\n\n\n let container = web::document()\n\n .query_selector(container_id)\n\n .expect(\"Couldn't get document element\")\n\n .expect(\"Couldn't get document element\");\n\n let targeted_view_input = web::document()\n", "file_path": "src/visjs.rs", "rank": 64, "score": 11.750081291665271 }, { "content": " }\n\n View::MV(view) => {\n\n self.console.log(\"Backend stopped\");\n\n\n\n view.stop_task = None;\n\n\n\n let mut session = view.session.write().unwrap();\n\n\n\n session.connected = false;\n\n view.descendants_timeout_task = None;\n\n view.events_dag = None;\n\n self.vis.remove_dag(view_id);\n\n\n\n self.event_body = None;\n\n self.room_state = None;\n\n }\n\n }\n\n }\n\n\n\n BkResponse::ConnectionFailed(view_id) => {\n", "file_path": "src/lib.rs", "rank": 65, "score": 11.140456825019466 }, { "content": "#[derive(Debug, Serialize)]\n\npub struct DataSetNode {\n\n pub id: String,\n\n pub label: String,\n\n pub level: i64,\n\n pub color: NodeColor,\n\n}\n\n\n\n/// The colors of the data set's node.\n\n#[derive(Debug, Serialize)]\n\npub struct NodeColor {\n\n pub border: String,\n\n pub background: String,\n\n}\n\n\n\n/// An edge of the vis.js data set.\n\n#[derive(Debug, Serialize)]\n\npub struct DataSetEdge {\n\n id: String,\n\n from: String,\n", "file_path": "src/model/dag.rs", "rank": 66, "score": 11.114967093803951 }, { "content": " match view.events_dag.clone() {\n\n // Add earlier event to the DAG and display them\n\n Some(dag) => {\n\n dag.write().unwrap().add_events(res.chunk);\n\n\n\n self.vis.update_dag(dag, view_id);\n\n }\n\n None => self.console.log(\"There was no DAG\"),\n\n }\n\n }\n\n }\n\n BkResponse::StateFetched(view_id, res) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.state_task = None;\n\n\n\n let event_bodies = res.state.clone();\n\n\n\n let object = json!({ \"events\": event_bodies });\n\n\n\n self.room_state = match serde_json::to_string_pretty(&object) {\n", "file_path": "src/lib.rs", "rank": 67, "score": 11.113124375138142 }, { "content": " dag.write().unwrap().add_events(res.events);\n\n\n\n self.vis.update_dag(dag, view_id);\n\n\n\n if view.session.read().unwrap().connected {\n\n view.descendants_timeout_task = Some(self.timeout.spawn(\n\n std::time::Duration::new(5, 0),\n\n self.link.send_back(move |_: ()| {\n\n Msg::BkCmd(BkCommand::Sync(view_id))\n\n }),\n\n ));\n\n }\n\n }\n\n None => self.console.log(\"There was no DAG\"),\n\n }\n\n }\n\n }\n\n BkResponse::State(view_id, res) => {\n\n if let View::MV(view) = &mut self.views[view_id] {\n\n view.state_task = None;\n", "file_path": "src/lib.rs", "rank": 68, "score": 11.098624321165186 }, { "content": " ToggleRedacts,\n\n ToggleEventID,\n\n}\n\n\n\npub enum UICommand {\n\n DisplayEventBody,\n\n}\n\n\n\n/// These messages are used by the frontend to send commands to the backend.\n\npub enum BkCommand {\n\n Connect(ViewIndex),\n\n ListRooms(ViewIndex),\n\n JoinRoom(ViewIndex),\n\n Sync(ViewIndex),\n\n MoreMsg,\n\n FetchState,\n\n LeaveRoom(ViewIndex),\n\n Disconnect(ViewIndex),\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 69, "score": 10.94865500559207 }, { "content": " }\n\n }\n\n BkCommand::Sync(view_id) => match &mut self.views[view_id] {\n\n View::CS(view) => {\n\n let next_batch_token = view.session.read().unwrap().next_batch_token.clone();\n\n\n\n view.sync_task = Some(\n\n view.backend\n\n .sync(view.sync_callback.clone(), next_batch_token),\n\n )\n\n }\n\n View::MV(view) => {\n\n if let Some(dag) = &view.events_dag {\n\n let from = &dag.read().unwrap().latest_events;\n\n\n\n view.descendants_task = Some(\n\n view.backend\n\n .descendants(view.descendants_callback.clone(), from),\n\n );\n\n }\n", "file_path": "src/lib.rs", "rank": 70, "score": 10.88466708389021 }, { "content": "use std::collections::{HashMap, HashSet};\n\nuse std::iter::FromIterator;\n\n\n\nuse petgraph::graph::{Graph, NodeIndex};\n\nuse petgraph::visit::{Bfs, EdgeRef};\n\nuse petgraph::{Directed, Direction};\n\nuse serde_derive::Serialize;\n\nuse serde_json::Value as JsonValue;\n\n\n\nuse crate::cs_backend::backend::SyncResponse;\n\nuse crate::mv_backend::backend::EventsResponse;\n\n\n\nuse super::event::{Event, Field};\n\n\n\n/// The internal representation of the events DAG of the room being observed as well as various\n\n/// informations and `HashMap`s which makes easier to locate the events.\n\npub struct RoomEvents {\n\n server_name: String, // The name of the server this DAG was retrieved from\n\n fields: HashSet<Field>, // Events fields which will be included in the labels on the nodes of the vis.js network\n\n\n", "file_path": "src/model/dag.rs", "rank": 71, "score": 10.638747648851334 }, { "content": " to_device: Option<JsonValue>,\n\n device_lists: Option<JsonValue>,\n\n #[serde(default)]\n\n device_one_time_keys_count: HashMap<String, u64>,\n\n}\n\n\n\n/// Represents the list of rooms in `SyncResponse`.\n\n#[derive(Clone, Debug, Default, Deserialize, Serialize)]\n\npub struct Rooms {\n\n #[serde(default)]\n\n leave: HashMap<String, JsonValue>,\n\n #[serde(default)]\n\n pub join: HashMap<String, JoinedRoom>,\n\n #[serde(default)]\n\n invite: HashMap<String, JsonValue>,\n\n}\n\n\n\n/// Represents the list of rooms joined by the user in `SyncResponse`.\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\n\npub struct JoinedRoom {\n", "file_path": "src/cs_backend/backend.rs", "rank": 72, "score": 10.615286030815552 }, { "content": "\n\npub struct Model {\n\n console: ConsoleService,\n\n timeout: TimeoutService,\n\n vis: VisJsService,\n\n link: ComponentLink<Self>,\n\n\n\n bk_type: Arc<RwLock<BackendChoice>>,\n\n view_idx: ViewIndex,\n\n views: Vec<View>,\n\n event_body: Option<String>,\n\n room_state: Option<String>,\n\n fields_choice: FieldsChoice,\n\n}\n\n\n\npub enum View {\n\n CS(CSView),\n\n MV(MVView),\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 73, "score": 10.578013780436004 }, { "content": "\n\n if let Some(dag) = self.views[view_id].get_events_dag() {\n\n self.event_body = dag\n\n .read()\n\n .unwrap()\n\n .get_event(&event_id)\n\n .map(|ev| serde_json::to_string_pretty(ev).unwrap());\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn process_bk_command(&mut self, cmd: BkCommand) {\n\n let console_msg = match cmd {\n\n BkCommand::Connect(_) => \"Connecting...\",\n\n BkCommand::ListRooms(_) => \"Listing joined rooms...\",\n\n BkCommand::JoinRoom(_) => \"Joining the room...\",\n\n BkCommand::Sync(_) => \"Syncing...\",\n\n BkCommand::MoreMsg => \"Retrieving previous messages...\",\n\n BkCommand::FetchState => \"Fetching the state of the room...\",\n", "file_path": "src/lib.rs", "rank": 74, "score": 10.28641512590157 }, { "content": "\n\nimpl Model {\n\n fn process_ui_event(&mut self, event: UIEvent) {\n\n // Change the informations of the session whenever their corresponding entries in the UI\n\n // are changed\n\n match event {\n\n UIEvent::ChooseCSBackend => {\n\n *self.bk_type.write().unwrap() = BackendChoice::CS;\n\n\n\n let mut new_views: Vec<CSView> = (0..self.views.len())\n\n .map(|id| CSView::new(id, &mut self.link))\n\n .collect();\n\n\n\n for (old_view, new_view) in self.views.iter().zip(new_views.iter_mut()) {\n\n if let View::MV(old_view) = old_view {\n\n let mv_session = old_view.session.read().unwrap();\n\n let mut new_session = new_view.session.write().unwrap();\n\n\n\n new_session.server_name = mv_session.server_name.clone();\n\n new_session.room_id = mv_session.room_id.clone();\n", "file_path": "src/lib.rs", "rank": 75, "score": 10.274475420512886 }, { "content": " }),\n\n stop_task: None,\n\n\n\n session: session.clone(),\n\n backend: MatrixVisualisationsBackend::with_session(session),\n\n events_dag: None,\n\n }\n\n }\n\n}\n\n\n\n// This defines which backend is used by the application for the retrieval of the events DAG.\n\n#[derive(Clone, Copy, Eq, PartialEq)]\n\npub enum BackendChoice {\n\n CS,\n\n MV,\n\n}\n\n\n\n// This defines which fields of the event body will be displayed in the nodes of the displayed DAG.\n", "file_path": "src/lib.rs", "rank": 76, "score": 10.233637703223774 }, { "content": " if let View::MV(view) = &mut self.views[view_id] {\n\n view.ancestors_task = None;\n\n\n\n match view.events_dag.clone() {\n\n // Add ancestors to the DAG and display them\n\n Some(dag) => {\n\n dag.write().unwrap().add_events(res.events);\n\n\n\n self.vis.update_dag(dag, view_id);\n\n }\n\n None => self.console.log(\"There was no DAG\"),\n\n }\n\n }\n\n }\n\n BkResponse::Descendants(view_id, res) => {\n\n if let View::MV(view) = &mut self.views[view_id] {\n\n view.descendants_task = None;\n\n\n\n match view.events_dag.clone() {\n\n Some(dag) => {\n", "file_path": "src/lib.rs", "rank": 77, "score": 10.10237473394937 }, { "content": " )\n\n };\n\n\n\n let filter = build_filter();\n\n\n\n let uri = Uri::builder()\n\n .scheme(\"https\")\n\n .authority(server_name.as_str())\n\n .path_and_query(\n\n format!(\n\n \"/_matrix/client/r0/rooms/{}/messages?from={}&dir=b&filter={}\",\n\n room_id,\n\n prev_batch_token.clone().unwrap_or_default(),\n\n filter,\n\n )\n\n .as_str(),\n\n )\n\n .build()\n\n .expect(\"Failed to build URI.\");\n\n\n", "file_path": "src/cs_backend/backend.rs", "rank": 78, "score": 10.050096837489217 }, { "content": "impl View {\n\n pub fn get_id(&self) -> ViewIndex {\n\n match self {\n\n View::CS(v) => v.id,\n\n View::MV(v) => v.id,\n\n }\n\n }\n\n\n\n pub fn get_events_dag(&self) -> &Option<Arc<RwLock<RoomEvents>>> {\n\n match self {\n\n View::CS(v) => &v.events_dag,\n\n View::MV(v) => &v.events_dag,\n\n }\n\n }\n\n}\n\n\n\n// This contains every informations needed for the observation of a room from a given HS by using\n\n// the CS API.\n\npub struct CSView {\n\n id: ViewIndex,\n", "file_path": "src/lib.rs", "rank": 79, "score": 9.672261945544285 }, { "content": " }\n\n None => self.console.log(\"There is no DAG\"),\n\n },\n\n }\n\n\n\n session.next_batch_token = Some(next_batch_token);\n\n\n\n // Request for futur new events\n\n self.link\n\n .send_back(move |_: ()| Msg::BkCmd(BkCommand::Sync(view_id)))\n\n .emit(());\n\n }\n\n }\n\n BkResponse::MsgGot(view_id, res) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.more_msg_task = None;\n\n\n\n // Save the prev batch token for the next `/messages` request\n\n view.session.write().unwrap().prev_batch_token = Some(res.end);\n\n\n", "file_path": "src/lib.rs", "rank": 80, "score": 9.53514877998801 }, { "content": " \"#ancestors-id\",\n\n \"#ancestors-target\",\n\n );\n\n }\n\n\n\n self.vis.add_dag(dag, view_id);\n\n }\n\n None => self.console.log(\"Failed to build the DAG\"),\n\n }\n\n\n\n view.descendants_timeout_task = Some(\n\n self.timeout.spawn(\n\n std::time::Duration::new(5, 0),\n\n self.link\n\n .send_back(move |_: ()| Msg::BkCmd(BkCommand::Sync(view_id))),\n\n ),\n\n );\n\n }\n\n }\n\n BkResponse::Ancestors(view_id, res) => {\n", "file_path": "src/lib.rs", "rank": 81, "score": 9.426688693518575 }, { "content": " self.console.log(\"You were not connected\");\n\n }\n\n }\n\n },\n\n }\n\n }\n\n\n\n fn process_bk_response(&mut self, res: BkResponse) {\n\n match res {\n\n BkResponse::Connected(view_id, res) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.connection_task = None;\n\n\n\n let mut session = view.session.write().unwrap();\n\n\n\n // Save the informations given by the homeserver when connecting to it. The access\n\n // token will be used for authenticating subsequent requests.\n\n session.user_id = res.user_id;\n\n session.access_token = Some(res.access_token);\n\n session.device_id = Some(res.device_id);\n", "file_path": "src/lib.rs", "rank": 82, "score": 9.401548936237589 }, { "content": " \"#display-body-target\",\n\n \"#ancestors-id\",\n\n \"#ancestors-target\",\n\n );\n\n }\n\n\n\n self.vis.add_dag(dag, view_id);\n\n }\n\n None => self.console.log(\"Failed to build the DAG\"),\n\n }\n\n }\n\n Some(_) => match view.events_dag.clone() {\n\n // Add new events to the DAG\n\n Some(dag) => {\n\n if let Some(room) = res.rooms.join.get(&session.room_id) {\n\n dag.write()\n\n .unwrap()\n\n .add_events(room.timeline.events.clone());\n\n self.vis.update_dag(dag, view_id);\n\n }\n", "file_path": "src/lib.rs", "rank": 83, "score": 9.11653493288374 }, { "content": "\n\n <button id=\"more-ev-target\", onclick=|_| Msg::BkCmd(BkCommand::MoreMsg),>{ \"More events\" }</button>\n\n <input type=\"text\", id=\"selected-event\",/>\n\n <button id=\"display-body-target\", onclick=|_| Msg::UICmd(UICommand::DisplayEventBody),>{ \"Display body\" }</button>\n\n\n\n <input type=\"text\", id=\"ancestors-id\",/>\n\n <button id=\"ancestors-target\", onclick=|_| Msg::BkCmd(BkCommand::MoreMsg),>{ \"Ancestors\" }</button>\n\n </section>\n\n\n\n <div class=\"view\",>\n\n <section id=\"dag-vis\",>\n\n </section>\n\n\n\n <section id=\"event-body\",>\n\n { self.display_body() }\n\n </section>\n\n </div>\n\n\n\n <section class=\"state\",>\n\n <button onclick=|_| Msg::BkCmd(BkCommand::FetchState), disabled=self.event_body.is_none(),>\n", "file_path": "src/lib.rs", "rank": 84, "score": 8.835472229031273 }, { "content": " None => match view.deepest_task {\n\n None => {\n\n view.deepest_task =\n\n Some(view.backend.deepest(view.deepest_callback.clone()))\n\n }\n\n Some(_) => self.console.log(\"Already fetching deepest events\"),\n\n },\n\n Some(_) => self.console.log(\"Deepest events already fetched\"),\n\n },\n\n },\n\n BkCommand::ListRooms(view_id) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.listing_rooms_task =\n\n Some(view.backend.list_rooms(view.listing_rooms_callback.clone()))\n\n }\n\n }\n\n BkCommand::JoinRoom(view_id) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.joining_room_task =\n\n Some(view.backend.join_room(view.joining_room_callback.clone()))\n", "file_path": "src/lib.rs", "rank": 85, "score": 8.680887159584264 }, { "content": " );\n\n }\n\n Some(_) => self.console.log(\"Already fetching previous messages\"),\n\n },\n\n View::MV(view) => match view.ancestors_task {\n\n None => match &view.events_dag {\n\n Some(_) => {\n\n let input: web::html_element::InputElement = web::document()\n\n .query_selector(\"#ancestors-id\")\n\n .expect(\"Couldn't get document element\")\n\n .expect(\"Couldn't get document element\")\n\n .try_into()\n\n .unwrap();\n\n let from = vec![input.raw_value()];\n\n\n\n view.ancestors_task = Some(\n\n view.backend\n\n .ancestors(view.ancestors_callback.clone(), &from),\n\n );\n\n }\n", "file_path": "src/lib.rs", "rank": 86, "score": 8.614489217339443 }, { "content": " }\n\n Some(_) => self.console.log(\"Already fetching the state of the room\"),\n\n },\n\n }\n\n }\n\n BkCommand::LeaveRoom(view_id) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n match view.leaving_room_task {\n\n None => {\n\n view.leaving_room_task =\n\n Some(view.backend.leave_room(view.leaving_room_callback.clone()))\n\n }\n\n Some(_) => self.console.log(\"Already leaving the room\"),\n\n }\n\n }\n\n }\n\n BkCommand::Disconnect(view_id) => match &mut self.views[view_id] {\n\n View::CS(view) => match view.session.read().unwrap().access_token {\n\n None => {\n\n self.console.log(\"You were not connected\");\n", "file_path": "src/lib.rs", "rank": 87, "score": 8.486701059385242 }, { "content": "\n\n events_dag.change_fields(&fc.fields);\n\n }\n\n\n\n if self.vis.is_active() {\n\n if let Some(events_dag) = view.get_events_dag() {\n\n self.vis.update_labels(events_dag.clone(), view.get_id());\n\n }\n\n }\n\n }\n\n }\n\n UIEvent::ToggleStateKey => {\n\n let fc = &mut self.fields_choice;\n\n\n\n fc.state_key = !fc.state_key;\n\n\n\n if fc.state_key {\n\n fc.fields.insert(Field::StateKey);\n\n } else {\n\n fc.fields.remove(&Field::StateKey);\n", "file_path": "src/lib.rs", "rank": 88, "score": 8.427212347803898 }, { "content": " let mut session = view.session.write().unwrap();\n\n session.connected = true;\n\n\n\n view.events_dag = Some(Arc::new(RwLock::new(\n\n model::dag::RoomEvents::from_deepest_events(\n\n &session.server_name,\n\n &self.fields_choice.fields,\n\n res,\n\n ),\n\n )));\n\n\n\n match view.events_dag.clone() {\n\n Some(dag) => {\n\n if !self.vis.is_active() {\n\n self.vis.init(\n\n \"#dag-vis\",\n\n \"#targeted-view\",\n\n \"#more-ev-target\",\n\n \"#selected-event\",\n\n \"#display-body-target\",\n", "file_path": "src/lib.rs", "rank": 89, "score": 8.057021907261754 }, { "content": "use std::sync::{Arc, RwLock};\n\n\n\nuse serde_derive::Serialize;\n\nuse stdweb::web;\n\nuse stdweb::web::IParentNode;\n\nuse stdweb::Value;\n\n\n\nuse crate::model::dag::RoomEvents;\n\nuse crate::model::dag::{DataSet, OrphanInfo};\n\nuse crate::BackendChoice;\n\n\n\n/// This struct contains the DAG displayed by the application.\n\n///\n\n/// `data` contains every nodes of every views of the DAG, so they are displayed side-by-side\n\n/// within the same vis.js network. Each node stored there has a prefix of the form \"subdag_X_\"\n\n/// which means that this node belongs to the view X.\n\n///\n\n/// Each of `earliest_events`, `latest_events` and `orphan_events` variables contains a list of\n\n/// lists of the earliest/latest/orphan events' IDs currently displayed for each views. So\n\n/// `*_events[X]` corresponds with the view X.\n", "file_path": "src/visjs.rs", "rank": 90, "score": 7.841694845374382 }, { "content": "\n\n // Make the initial sync as soon as the user has joined the room\n\n self.link\n\n .send_back(move |_: ()| Msg::BkCmd(BkCommand::Sync(view_id)))\n\n .emit(());\n\n }\n\n }\n\n BkResponse::Synced(view_id, res) => {\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.sync_task = None;\n\n\n\n let mut session = view.session.write().unwrap();\n\n let next_batch_token = res.next_batch.clone(); // Save the next batch token to get new events later\n\n\n\n match session.next_batch_token {\n\n None => {\n\n // Initialise the prev batch token on the initial sync\n\n if let Some(room) = res.rooms.join.get(&session.room_id) {\n\n session.prev_batch_token = room.timeline.prev_batch.clone();\n\n }\n", "file_path": "src/lib.rs", "rank": 91, "score": 7.56581349219447 }, { "content": " BkResponse::SyncFailed(view_id) => {\n\n self.console.log(\"Could not sync\");\n\n\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.sync_task = None;\n\n }\n\n }\n\n BkResponse::MoreMsgFailed(view_id) => {\n\n self.console.log(\"Could not retrieve previous messages\");\n\n\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.more_msg_task = None;\n\n }\n\n }\n\n BkResponse::FetchStateFailed(view_id) => {\n\n self.console.log(\"Could not fetch the state of the room\");\n\n\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.more_msg_task = None;\n\n }\n", "file_path": "src/lib.rs", "rank": 92, "score": 7.549264200391166 }, { "content": " None => self.console.log(\"There was no DAG\"),\n\n },\n\n Some(_) => self.console.log(\"Already fetching ancestors\"),\n\n },\n\n }\n\n }\n\n BkCommand::FetchState => {\n\n let view_selection_input: web::html_element::InputElement = web::document()\n\n .query_selector(\"#targeted-view\")\n\n .expect(\"Couldn't get document element\")\n\n .expect(\"Couldn't get document element\")\n\n .try_into()\n\n .unwrap();\n\n let view_id: ViewIndex = view_selection_input\n\n .raw_value()\n\n .parse()\n\n .expect(\"Failed to parse view_id\");\n\n\n\n let event_id_input: web::html_element::InputElement = web::document()\n\n .query_selector(\"#selected-event\")\n", "file_path": "src/lib.rs", "rank": 93, "score": 7.493031197078901 }, { "content": " dag.update_event_edges();\n\n\n\n dag\n\n }\n\n\n\n /// Adds `events` to the DAG.\n\n pub fn add_events(&mut self, events: Vec<JsonValue>) {\n\n let events = parse_events(&events);\n\n\n\n self.add_event_nodes(events);\n\n self.update_event_edges();\n\n }\n\n\n\n fn add_event_nodes(&mut self, events: Vec<Event>) {\n\n for event in events.iter() {\n\n let id = &event.event_id;\n\n let depth = event.depth;\n\n let index = self.dag.add_node(event.clone()); // Add each event as a node in the DAG\n\n\n\n self.events_map.insert(id.clone(), index); // Update the events map\n", "file_path": "src/model/dag.rs", "rank": 94, "score": 7.492445248211775 }, { "content": " <pre><code>{ room_state }</code></pre>\n\n }\n\n }\n\n None => {\n\n html! {\n\n <p>{ \"No room state to show yet\" }</p>\n\n }\n\n }\n\n }\n\n }\n\n\n\n fn display_backend_choice(&self) -> Html<Self> {\n\n let bk_type = *self.bk_type.read().unwrap();\n\n\n\n let connected = self.views.iter().any(|view| match view {\n\n View::CS(view) => view.session.read().unwrap().access_token.is_some(),\n\n View::MV(view) => view.session.read().unwrap().connected,\n\n });\n\n\n\n if !connected {\n", "file_path": "src/lib.rs", "rank": 95, "score": 7.423728983981025 }, { "content": " view.session.write().unwrap().username = u;\n\n }\n\n }\n\n }\n\n UIEvent::Password(p) => {\n\n if let html::ChangeData::Value(p) = p {\n\n if let View::CS(view) = &mut self.views[self.view_idx] {\n\n view.session.write().unwrap().password = p;\n\n }\n\n }\n\n }\n\n UIEvent::ToggleSender => {\n\n let fc = &mut self.fields_choice;\n\n\n\n fc.sender = !fc.sender;\n\n\n\n if fc.sender {\n\n fc.fields.insert(Field::Sender);\n\n } else {\n\n fc.fields.remove(&Field::Sender);\n", "file_path": "src/lib.rs", "rank": 96, "score": 7.420080682070386 }, { "content": "\n\n self.console.log(&format!(\n\n \"Connected with token: {} and as {}\",\n\n session.access_token.as_ref().unwrap(),\n\n session.device_id.as_ref().unwrap()\n\n ));\n\n\n\n // Request the list of the rooms joined by the user as soon as we are connected\n\n self.link\n\n .send_back(move |_: ()| Msg::BkCmd(BkCommand::ListRooms(view_id)))\n\n .emit(());\n\n }\n\n }\n\n BkResponse::RoomsList(view_id, res) => {\n\n self.console.log(\"Looking up in joined rooms\");\n\n\n\n if let View::CS(view) = &mut self.views[view_id] {\n\n view.listing_rooms_task = None;\n\n\n\n if res\n", "file_path": "src/lib.rs", "rank": 97, "score": 7.365832065371422 }, { "content": " }\n\n }\n\n\n\n let new_views = new_views.into_iter().map(|view| View::CS(view)).collect();\n\n\n\n self.views = new_views;\n\n }\n\n UIEvent::ChooseMVBackend => {\n\n *self.bk_type.write().unwrap() = BackendChoice::MV;\n\n\n\n let mut new_views: Vec<MVView> = (0..self.views.len())\n\n .map(|id| MVView::new(id, &mut self.link))\n\n .collect();\n\n\n\n for (old_view, new_view) in self.views.iter().zip(new_views.iter_mut()) {\n\n if let View::CS(old_view) = old_view {\n\n let cs_session = old_view.session.read().unwrap();\n\n let mut new_session = new_view.session.write().unwrap();\n\n\n\n new_session.server_name = cs_session.server_name.clone();\n", "file_path": "src/lib.rs", "rank": 98, "score": 7.264448122274937 }, { "content": " .collect();\n\n\n\n DataSet { nodes, edges }\n\n }\n\n\n\n /// Adds to `data_set` every events in the DAG which are earlier than the events which IDs are\n\n /// in `from`.\n\n pub fn add_earlier_events_to_data_set(&self, data_set: &mut DataSet, from: Vec<String>) {\n\n let from_indices: HashSet<NodeIndex> = from.iter().map(|id| self.events_map[id]).collect();\n\n\n\n let (new_node_indices, new_edges) = new_nodes_edges(&self.dag, from_indices);\n\n\n\n new_node_indices\n\n .iter()\n\n .map(|idx| {\n\n self.dag\n\n .node_weight(*idx)\n\n .unwrap()\n\n .to_data_set_node(&self.server_name, &self.fields)\n\n })\n", "file_path": "src/model/dag.rs", "rank": 99, "score": 7.234045021951916 } ]
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 let len: usize = s.len();\n\n // ELEMENTS: 8->14\n\n if len < 14 {\n\n return Err(Error::InvalidLength);\n\n }\n\n\n\n // Split at separator and check for two pieces\n\n let (raw_hrp, raw_data) = match s.rfind(\"1\") {\n\n None => return Err(Error::MissingSeparator),\n\n Some(sep) => {\n\n let (hrp, data) = s.split_at(sep);\n\n (hrp, &data[1..])\n\n }\n\n };\n\n // ELEMENTS: 6->12\n\n if raw_hrp.len() < 1 || raw_data.len() < 12 || raw_hrp.len() > 83 {\n\n return Err(Error::InvalidLength);\n\n }\n", "file_path": "src/blech32.rs", "rank": 0, "score": 107995.1444902755 }, { "content": "/// Encode a bech32 payload to an [fmt::Formatter].\n\npub fn encode_to_fmt<T: AsRef<[u5]>>(fmt: &mut fmt::Formatter, hrp: &str, data: T) -> fmt::Result {\n\n let hrp_bytes: &[u8] = hrp.as_bytes();\n\n let checksum = create_checksum(hrp_bytes, data.as_ref());\n\n let data_part = data.as_ref().iter().chain(checksum.iter());\n\n\n\n write!(\n\n fmt,\n\n \"{}{}{}\",\n\n hrp,\n\n SEP,\n\n data_part\n\n .map(|p| CHARSET[*p.as_ref() as usize])\n\n .collect::<String>()\n\n )\n\n}\n\n\n", "file_path": "src/blech32.rs", "rank": 1, "score": 106783.09259207928 }, { "content": "/// Extract the bech32 prefix.\n\n/// Returns the same slice when no prefix is found.\n\nfn find_prefix(bech32: &str) -> &str {\n\n // Split at the last occurrence of the separator character '1'.\n\n match bech32.rfind(\"1\") {\n\n None => bech32,\n\n Some(sep) => bech32.split_at(sep).0,\n\n }\n\n}\n\n\n", "file_path": "src/address.rs", "rank": 2, "score": 77905.73241284865 }, { "content": "/// Checks if both prefixes match, regardless of case.\n\n/// The first prefix can be mixed case, but the second one is expected in\n\n/// lower case.\n\nfn match_prefix(prefix_mixed: &str, prefix_lower: &str) -> bool {\n\n if prefix_lower.len() != prefix_mixed.len() {\n\n false\n\n } else {\n\n prefix_lower\n\n .chars()\n\n .zip(prefix_mixed.chars())\n\n .all(|(char_lower, char_mixed)| char_lower == char_mixed.to_ascii_lowercase())\n\n }\n\n}\n\n\n\nimpl FromStr for Address {\n\n type Err = AddressError;\n\n\n\n fn from_str(s: &str) -> Result<Address, AddressError> {\n\n // shorthands\n\n let liq = &AddressParams::LIQUID;\n\n let ele = &AddressParams::ELEMENTS;\n\n\n\n // Bech32.\n", "file_path": "src/address.rs", "rank": 5, "score": 64143.89164307623 }, { "content": "/// Compute the Merkle root of the give hashes using mid-state only.\n\n/// The inputs must be byte slices of length 32.\n\n/// Note that the merkle root calculated with this method is not the same as the\n\n/// one computed by a normal SHA256(d) merkle root.\n\npub fn fast_merkle_root(leaves: &[[u8; 32]]) -> sha256::Midstate {\n\n let mut result_hash = Default::default();\n\n // Implementation based on ComputeFastMerkleRoot method in Elements Core.\n\n if leaves.is_empty() {\n\n return result_hash;\n\n }\n\n\n\n // inner is an array of eagerly computed subtree hashes, indexed by tree\n\n // level (0 being the leaves).\n\n // For example, when count is 25 (11001 in binary), inner[4] is the hash of\n\n // the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to\n\n // the last leaf. The other inner entries are undefined.\n\n //\n\n // First process all leaves into 'inner' values.\n\n let mut inner: [sha256::Midstate; 32] = Default::default();\n\n let mut count: u32 = 0;\n\n while (count as usize) < leaves.len() {\n\n let mut temp_hash = sha256::Midstate::from_inner(leaves[count as usize]);\n\n count += 1;\n\n // For each of the lower bits in count that are 0, do 1 step. Each\n", "file_path": "src/fast_merkle_root.rs", "rank": 7, "score": 46042.33271127277 }, { "content": "#[cfg(feature = \"honggfuzz\")]\n\n#[macro_use] extern crate honggfuzz;\n\n#[cfg(feature = \"honggfuzz\")]\n\nfn main() {\n\n loop {\n\n fuzz!(|data| {\n\n do_test(data);\n\n });\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {\n\n let mut b = 0;\n\n for (idx, c) in hex.as_bytes().iter().enumerate() {\n\n b <<= 4;\n\n match *c {\n\n b'A'...b'F' => b |= c - b'A' + 10,\n\n b'a'...b'f' => b |= c - b'a' + 10,\n\n b'0'...b'9' => b |= c - b'0',\n\n _ => panic!(\"Bad hex\"),\n\n }\n", "file_path": "fuzz/fuzz_targets/deserialize_output.rs", "rank": 10, "score": 39352.95246305986 }, { "content": "#[cfg(feature = \"honggfuzz\")]\n\n#[macro_use] extern crate honggfuzz;\n\n#[cfg(feature = \"honggfuzz\")]\n\nfn main() {\n\n loop {\n\n fuzz!(|data| {\n\n do_test(data);\n\n });\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {\n\n let mut b = 0;\n\n for (idx, c) in hex.as_bytes().iter().enumerate() {\n\n b <<= 4;\n\n match *c {\n\n b'A'...b'F' => b |= c - b'A' + 10,\n\n b'a'...b'f' => b |= c - b'a' + 10,\n\n b'0'...b'9' => b |= c - b'0',\n\n _ => panic!(\"Bad hex\"),\n\n }\n", "file_path": "fuzz/fuzz_targets/deserialize_block.rs", "rank": 11, "score": 39352.95246305986 }, { "content": "#[cfg(feature = \"honggfuzz\")]\n\n#[macro_use] extern crate honggfuzz;\n\n#[cfg(feature = \"honggfuzz\")]\n\nfn main() {\n\n loop {\n\n fuzz!(|data| {\n\n do_test(data);\n\n });\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {\n\n let mut b = 0;\n\n for (idx, c) in hex.as_bytes().iter().enumerate() {\n\n b <<= 4;\n\n match *c {\n\n b'A'...b'F' => b |= c - b'A' + 10,\n\n b'a'...b'f' => b |= c - b'a' + 10,\n\n b'0'...b'9' => b |= c - b'0',\n\n _ => panic!(\"Bad hex\"),\n\n }\n", "file_path": "fuzz/fuzz_targets/deserialize_transaction.rs", "rank": 12, "score": 39352.95246305986 }, { "content": "fn polymod(values: &[u5]) -> u64 {\n\n let mut chk: u64 = 1;\n\n let mut b: u8;\n\n for v in values {\n\n b = (chk >> 55) as u8; // ELEMENTS: 25->55\n\n chk = (chk & 0x7fffffffffffff) << 5 ^ (u64::from(*v.as_ref())); // ELEMENTS 0x1ffffff->0x7fffffffffffff\n\n for i in 0..5 {\n\n if (b >> i) & 1 == 1 {\n\n chk ^= GEN[i]\n\n }\n\n }\n\n }\n\n chk\n\n}\n\n\n\n/// Human-readable part and data part separator\n\nconst SEP: char = '1';\n\n\n\n/// Encoding character set. Maps data value -> char\n\nconst CHARSET: [char; 32] = [\n", "file_path": "src/blech32.rs", "rank": 14, "score": 31724.33525380501 }, { "content": "fn do_test(data: &[u8]) {\n\n let result: Result<elements::TxOut, _> = elements::encode::deserialize(data);\n\n match result {\n\n Err(_) => {},\n\n Ok(output) => {\n\n let reser = elements::encode::serialize(&output);\n\n assert_eq!(data, &reser[..]);\n\n\n\n output.is_null_data();\n\n output.is_pegout();\n\n output.pegout_data();\n\n output.is_fee();\n\n output.minimum_value();\n\n },\n\n }\n\n}\n\n\n\n#[cfg(feature = \"afl\")]\n\nextern crate afl;\n", "file_path": "fuzz/fuzz_targets/deserialize_output.rs", "rank": 15, "score": 31064.965365045835 }, { "content": "fn do_test(data: &[u8]) {\n\n let tx_result: Result<elements::Transaction, _> = elements::encode::deserialize(data);\n\n match tx_result {\n\n Err(_) => {},\n\n Ok(mut tx) => {\n\n let reser = elements::encode::serialize(&tx);\n\n assert_eq!(data, &reser[..]);\n\n let len = reser.len();\n\n let calculated_weight = tx.get_weight();\n\n for input in &mut tx.input {\n\n input.witness = elements::TxInWitness::default();\n\n }\n\n for output in &mut tx.output {\n\n output.witness = elements::TxOutWitness::default();\n\n }\n\n assert_eq!(tx.has_witness(), false);\n\n let no_witness_len = elements::encode::serialize(&tx).len();\n\n assert_eq!(no_witness_len * 3 + len, calculated_weight);\n\n\n\n for output in &tx.output {\n", "file_path": "fuzz/fuzz_targets/deserialize_transaction.rs", "rank": 16, "score": 31064.965365045835 }, { "content": "fn do_test(data: &[u8]) {\n\n let block_result: Result<elements::Block, _> = elements::encode::deserialize(data);\n\n match block_result {\n\n Err(_) => {},\n\n Ok(block) => {\n\n let reser = elements::encode::serialize(&block);\n\n assert_eq!(data, &reser[..]);\n\n },\n\n }\n\n}\n\n\n\n#[cfg(feature = \"afl\")]\n\nextern crate afl;\n", "file_path": "fuzz/fuzz_targets/deserialize_block.rs", "rank": 17, "score": 31064.965365045835 }, { "content": "fn hrp_expand(hrp: &[u8]) -> Vec<u5> {\n\n let mut v: Vec<u5> = Vec::new();\n\n for b in hrp {\n\n v.push(u5::try_from_u8(*b >> 5).expect(\"can't be out of range, max. 7\"));\n\n }\n\n v.push(u5::try_from_u8(0).unwrap());\n\n for b in hrp {\n\n v.push(u5::try_from_u8(*b & 0x1f).expect(\"can't be out of range, max. 31\"));\n\n }\n\n v\n\n}\n\n\n", "file_path": "src/blech32.rs", "rank": 18, "score": 28080.23278330008 }, { "content": "fn verify_checksum(hrp: &[u8], data: &[u5]) -> bool {\n\n let mut exp = hrp_expand(hrp);\n\n exp.extend_from_slice(data);\n\n polymod(&exp) == 1u64\n\n}\n\n\n", "file_path": "src/blech32.rs", "rank": 19, "score": 26085.778750848716 }, { "content": "fn create_checksum(hrp: &[u8], data: &[u5]) -> Vec<u5> {\n\n let mut values: Vec<u5> = hrp_expand(hrp);\n\n values.extend_from_slice(data);\n\n // Pad with 12 zeros\n\n values.extend_from_slice(&[u5::try_from_u8(0).unwrap(); 12]); // ELEMENTS: 6->12\n\n let plm: u64 = polymod(&values) ^ 1;\n\n let mut checksum: Vec<u5> = Vec::new();\n\n // ELEMENTS: 6->12\n\n for p in 0..12 {\n\n checksum.push(u5::try_from_u8(((plm >> (5 * (11 - p))) & 0x1f) as u8).unwrap()); // ELEMENTS: 5->11\n\n }\n\n checksum\n\n}\n\n\n", "file_path": "src/blech32.rs", "rank": 20, "score": 24388.80124401106 }, { "content": "#[inline]\n\nfn sha256midstate(left: &[u8], right: &[u8]) -> sha256::Midstate {\n\n let mut engine = sha256::Hash::engine();\n\n engine.input(left);\n\n engine.input(right);\n\n engine.midstate()\n\n}\n\n\n", "file_path": "src/fast_merkle_root.rs", "rank": 21, "score": 23576.898272587794 }, { "content": "\n\n impl fmt::Display for $name {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n $name::Null => f.write_str(\"null\"),\n\n $name::Explicit(n) => write!(f, \"{}\", n),\n\n $name::Confidential(prefix, bytes) => {\n\n write!(f, \"{:02x}\", prefix)?;\n\n for b in bytes.iter() {\n\n write!(f, \"{:02x}\", b)?;\n\n }\n\n Ok(())\n\n }\n\n }\n\n }\n\n }\n\n\n\n impl Encodable for $name {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n match *self {\n", "file_path": "src/confidential.rs", "rank": 24, "score": 19.59348441957214 }, { "content": " fn deserialize<D>(deserializer: D) -> Result<$name, D::Error>\n\n where\n\n D: $crate::serde::de::Deserializer<'de>,\n\n {\n\n use $crate::std::fmt::{self, Formatter};\n\n use $crate::serde::de::IgnoredAny;\n\n\n\n #[allow(non_camel_case_types)]\n\n enum Enum { Unknown__Field, $($fe),* }\n\n\n\n struct EnumVisitor;\n\n impl<'de> $crate::serde::de::Visitor<'de> for EnumVisitor {\n\n type Value = Enum;\n\n\n\n fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {\n\n formatter.write_str(\"a field name\")\n\n }\n\n\n\n fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>\n\n where\n", "file_path": "src/internal_macros.rs", "rank": 26, "score": 18.2810728439636 }, { "content": " struct Visitor;\n\n\n\n impl<'de> $crate::serde::de::Visitor<'de> for Visitor {\n\n type Value = $name;\n\n\n\n fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {\n\n formatter.write_str(\"a struct\")\n\n }\n\n\n\n fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>\n\n where\n\n A: $crate::serde::de::MapAccess<'de>,\n\n {\n\n use $crate::serde::de::Error;\n\n\n\n $(let mut $fe = None;)*\n\n\n\n loop {\n\n match map.next_key::<Enum>()? {\n\n Some(Enum::Unknown__Field) => {\n", "file_path": "src/internal_macros.rs", "rank": 27, "score": 18.16572530896915 }, { "content": " /// Scriptpubkey\n\n pub script_pubkey: Script,\n\n /// Witness data - not deserialized/serialized as part of a `TxIn` object\n\n /// (rather as part of its containing transaction, if any) but is logically\n\n /// part of the txin.\n\n pub witness: TxOutWitness,\n\n}\n\nserde_struct_impl!(TxOut, asset, value, nonce, script_pubkey, witness);\n\n\n\nimpl Encodable for TxOut {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n Ok(self.asset.consensus_encode(&mut s)? +\n\n self.value.consensus_encode(&mut s)? +\n\n self.nonce.consensus_encode(&mut s)? +\n\n self.script_pubkey.consensus_encode(&mut s)?)\n\n }\n\n}\n\n\n\nimpl Decodable for TxOut {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<TxOut, encode::Error> {\n", "file_path": "src/transaction.rs", "rank": 28, "score": 18.152160729190943 }, { "content": " \"extension_space\" => Ok(Enum::ExtSpace),\n\n _ => Ok(Enum::Unknown),\n\n }\n\n }\n\n }\n\n\n\n impl<'de> Deserialize<'de> for Enum {\n\n fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {\n\n d.deserialize_str(EnumVisitor)\n\n }\n\n }\n\n\n\n struct Visitor;\n\n impl<'de> de::Visitor<'de> for Visitor {\n\n type Value = Params;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"block header extra data\")\n\n }\n\n\n", "file_path": "src/dynafed.rs", "rank": 29, "score": 17.747456817769088 }, { "content": "\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"a field name\")\n\n }\n\n\n\n fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {\n\n match v {\n\n \"challenge\" => Ok(Enum::Challenge),\n\n \"solution\" => Ok(Enum::Solution),\n\n \"current\" => Ok(Enum::Current),\n\n \"proposed\" => Ok(Enum::Proposed),\n\n \"signblock_witness\" => Ok(Enum::Witness),\n\n _ => Ok(Enum::Unknown),\n\n }\n\n }\n\n }\n\n\n\n impl<'de> Deserialize<'de> for Enum {\n\n fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {\n\n d.deserialize_str(EnumVisitor)\n", "file_path": "src/block.rs", "rank": 30, "score": 17.645823574397042 }, { "content": "impl BitcoinHash for OutPoint {\n\n fn bitcoin_hash(&self) -> sha256d::Hash {\n\n let mut enc = sha256d::Hash::engine();\n\n self.consensus_encode(&mut enc).unwrap();\n\n sha256d::Hash::from_engine(enc)\n\n }\n\n}\n\n\n\nimpl fmt::Display for OutPoint {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"[elements]\")?;\n\n write!(f, \"{}:{}\", self.txid, self.vout)\n\n }\n\n}\n\n\n\nimpl ::std::str::FromStr for OutPoint {\n\n type Err = bitcoin::blockdata::transaction::ParseOutPointError;\n\n fn from_str(mut s: &str) -> Result<Self, Self::Err> {\n\n if s.starts_with(\"[elements]\") {\n\n s = &s[10..];\n", "file_path": "src/transaction.rs", "rank": 31, "score": 16.877470266599325 }, { "content": " pub asset_issuance: AssetIssuance,\n\n /// Witness data - not deserialized/serialized as part of a `TxIn` object\n\n /// (rather as part of its containing transaction, if any) but is logically\n\n /// part of the txin.\n\n pub witness: TxInWitness,\n\n}\n\nserde_struct_impl!(TxIn, previous_output, is_pegin, has_issuance, script_sig, sequence, asset_issuance, witness);\n\n\n\nimpl Encodable for TxIn {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n let mut ret = 0;\n\n let mut vout = self.previous_output.vout;\n\n if self.is_pegin {\n\n vout |= 1 << 30;\n\n }\n\n if self.has_issuance {\n\n vout |= 1 << 31;\n\n }\n\n ret += self.previous_output.txid.consensus_encode(&mut s)?;\n\n ret += vout.consensus_encode(&mut s)?;\n", "file_path": "src/transaction.rs", "rank": 32, "score": 16.14297736292535 }, { "content": " SignblockWitnessLimit,\n\n FedpegProgram,\n\n FedpegScript,\n\n ExtSpace,\n\n }\n\n struct EnumVisitor;\n\n\n\n impl<'de> de::Visitor<'de> for EnumVisitor {\n\n type Value = Enum;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"a field name\")\n\n }\n\n\n\n fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {\n\n match v {\n\n \"signblockscript\" => Ok(Enum::SignblockScript),\n\n \"signblock_witness_limit\" => Ok(Enum::SignblockWitnessLimit),\n\n \"fedpeg_program\" => Ok(Enum::FedpegProgram),\n\n \"fedpegscript\" => Ok(Enum::FedpegScript),\n", "file_path": "src/dynafed.rs", "rank": 33, "score": 16.101191226165064 }, { "content": "impl ::std::fmt::Debug for AssetId {\n\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n ::std::fmt::Display::fmt(&self, f)\n\n }\n\n}\n\n\n\nimpl ::std::fmt::LowerHex for AssetId {\n\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n ::std::fmt::LowerHex::fmt(&self.0, f)\n\n }\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\nimpl ::serde::Serialize for AssetId {\n\n fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {\n\n use bitcoin::hashes::hex::ToHex;\n\n if s.is_human_readable() {\n\n s.serialize_str(&self.to_hex())\n\n } else {\n\n s.serialize_bytes(&self.0[..])\n", "file_path": "src/issuance.rs", "rank": 34, "score": 16.090814513012944 }, { "content": " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let desc = error::Error::description;\n\n match *self {\n\n AddressError::Base58(ref e) => fmt::Display::fmt(e, f),\n\n AddressError::Bech32(ref e) => write!(f, \"bech32 error: {}\", e),\n\n AddressError::Blech32(ref e) => write!(f, \"blech32 error: {}\", e),\n\n AddressError::InvalidAddress(ref a) => write!(f, \"{}: {}\", desc(self), a),\n\n AddressError::UnsupportedWitnessVersion(ref wver) => {\n\n write!(f, \"{}: {}\", desc(self), wver)\n\n }\n\n AddressError::InvalidBlindingPubKey(ref e) => write!(f, \"{}: {}\", desc(self), e),\n\n _ => f.write_str(desc(self)),\n\n }\n\n }\n\n}\n\n\n\nimpl error::Error for AddressError {\n\n fn cause(&self) -> Option<&error::Error> {\n\n match *self {\n\n AddressError::Base58(ref e) => Some(e),\n", "file_path": "src/address.rs", "rank": 35, "score": 15.382191409514299 }, { "content": "}\n\n\n\nimpl Encodable for OutPoint {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n Ok(self.txid.consensus_encode(&mut s)? +\n\n self.vout.consensus_encode(&mut s)?)\n\n }\n\n}\n\n\n\nimpl Decodable for OutPoint {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<OutPoint, encode::Error> {\n\n let txid = sha256d::Hash::consensus_decode(&mut d)?;\n\n let vout = u32::consensus_decode(&mut d)?;\n\n Ok(OutPoint {\n\n txid: txid,\n\n vout: vout,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/transaction.rs", "rank": 36, "score": 15.212601117940167 }, { "content": " D: serde::Deserializer<'de>,\n\n {\n\n use std::fmt::Formatter;\n\n\n\n struct Visitor;\n\n impl<'de> serde::de::Visitor<'de> for Visitor {\n\n type Value = Address;\n\n\n\n fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {\n\n formatter.write_str(\"a Bitcoin address\")\n\n }\n\n\n\n fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n Address::from_str(v).map_err(E::custom)\n\n }\n\n\n\n fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>\n", "file_path": "src/address.rs", "rank": 37, "score": 15.179299426066283 }, { "content": "\n\n impl <'de> Visitor<'de> for CommitVisitor {\n\n type Value = $name;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"a committed value\")\n\n }\n\n\n\n fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {\n\n let prefix: u8 = if let Some(x) = access.next_element()? {\n\n x\n\n } else {\n\n return Err(A::Error::custom(\"missing prefix\"));\n\n };\n\n\n\n match prefix {\n\n 0 => Ok($name::Null),\n\n 1 => {\n\n // Apply $explicit_fn to allow `Value` to swap the amount bytes\n\n match access.next_element()? {\n", "file_path": "src/confidential.rs", "rank": 38, "score": 14.943042796415549 }, { "content": "impl BitcoinHash for Transaction {\n\n /// To get a transaction's txid, which is usually what you want, use the `txid` method.\n\n fn bitcoin_hash(&self) -> sha256d::Hash {\n\n let mut enc = sha256d::Hash::engine();\n\n self.consensus_encode(&mut enc).unwrap();\n\n sha256d::Hash::from_engine(enc)\n\n }\n\n}\n\n\n\nimpl Encodable for Transaction {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n let mut ret = 0;\n\n ret += self.version.consensus_encode(&mut s)?;\n\n\n\n let wit_flag = self.has_witness();\n\n if wit_flag {\n\n ret += 1u8.consensus_encode(&mut s)?;\n\n } else {\n\n ret += 0u8.consensus_encode(&mut s)?;\n\n }\n", "file_path": "src/transaction.rs", "rank": 41, "score": 14.377028805541972 }, { "content": " }\n\n }\n\n\n\n struct Visitor;\n\n impl<'de> de::Visitor<'de> for Visitor {\n\n type Value = ExtData;\n\n\n\n fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(\"block header extra data\")\n\n }\n\n\n\n fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>\n\n where\n\n A: de::MapAccess<'de>,\n\n {\n\n let mut challenge = None;\n\n let mut solution = None;\n\n let mut current = None;\n\n let mut proposed = None;\n\n let mut witness = None;\n", "file_path": "src/block.rs", "rank": 42, "score": 13.964314497666189 }, { "content": " }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\nimpl<'de> ::serde::Deserialize<'de> for AssetId {\n\n fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<AssetId, D::Error> {\n\n use bitcoin::hashes::hex::FromHex;\n\n\n\n if d.is_human_readable() {\n\n struct HexVisitor;\n\n\n\n impl<'de> ::serde::de::Visitor<'de> for HexVisitor {\n\n type Value = AssetId;\n\n\n\n fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n formatter.write_str(\"an ASCII hex string\")\n\n }\n\n\n\n fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>\n", "file_path": "src/issuance.rs", "rank": 43, "score": 13.130144227934299 }, { "content": "use serde::{Deserialize, Deserializer, Serialize, Serializer};\n\n\n\nuse std::{io, fmt};\n\n\n\nuse bitcoin::hashes::sha256d;\n\n\n\nuse encode::{self, Encodable, Decodable};\n\n\n\n// Helper macro to implement various things for the various confidential\n\n// commitment types\n\nmacro_rules! impl_confidential_commitment {\n\n ($name:ident, $prefixA:expr, $prefixB:expr) => (\n\n impl_confidential_commitment!($name, $prefixA, $prefixB, |x|x);\n\n );\n\n ($name:ident, $prefixA:expr, $prefixB:expr, $explicit_fn:expr) => (\n\n impl Default for $name {\n\n fn default() -> Self {\n\n $name::Null\n\n }\n\n }\n", "file_path": "src/confidential.rs", "rank": 44, "score": 12.947638412377351 }, { "content": " $name::Null => 0u8.consensus_encode(s),\n\n $name::Explicit(n) => {\n\n 1u8.consensus_encode(&mut s)?;\n\n // Apply $explicit_fn to allow `Value` to swap the amount bytes\n\n Ok(1 + $explicit_fn(n).consensus_encode(&mut s)?)\n\n }\n\n $name::Confidential(prefix, bytes) => {\n\n Ok(prefix.consensus_encode(&mut s)? + bytes.consensus_encode(&mut s)?)\n\n }\n\n }\n\n }\n\n }\n\n\n\n impl Decodable for $name {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<$name, encode::Error> {\n\n let prefix = u8::consensus_decode(&mut d)?;\n\n match prefix {\n\n 0 => Ok($name::Null),\n\n 1 => {\n\n // Apply $explicit_fn to allow `Value` to swap the amount bytes\n", "file_path": "src/confidential.rs", "rank": 45, "score": 12.702201273842656 }, { "content": " Some(::fast_merkle_root::fast_merkle_root(&leaves[..]))\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Encodable for BlockHeader {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n let version = if let ExtData::Dynafed { .. } = self.ext {\n\n self.version | 0x8000_0000\n\n } else {\n\n self.version\n\n };\n\n\n\n Ok(version.consensus_encode(&mut s)? +\n\n self.prev_blockhash.consensus_encode(&mut s)? +\n\n self.merkle_root.consensus_encode(&mut s)? +\n\n self.time.consensus_encode(&mut s)? +\n\n self.height.consensus_encode(&mut s)? +\n\n self.ext.consensus_encode(&mut s)?)\n", "file_path": "src/block.rs", "rank": 47, "score": 12.337875033387757 }, { "content": " E: $crate::serde::de::Error,\n\n {\n\n match v {\n\n $(\n\n stringify!($fe) => Ok(Enum::$fe)\n\n ),*,\n\n _ => Ok(Enum::Unknown__Field)\n\n }\n\n }\n\n }\n\n\n\n impl<'de> $crate::serde::Deserialize<'de> for Enum {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: ::serde::de::Deserializer<'de>,\n\n {\n\n deserializer.deserialize_str(EnumVisitor)\n\n }\n\n }\n\n\n", "file_path": "src/internal_macros.rs", "rank": 48, "score": 12.184022232790443 }, { "content": " let explicit = $explicit_fn(Decodable::consensus_decode(&mut d)?);\n\n Ok($name::Explicit(explicit))\n\n }\n\n x => {\n\n let commitment = <[u8; 32]>::consensus_decode(&mut d)?;\n\n Ok($name::Confidential(x, commitment))\n\n }\n\n }\n\n }\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n impl Serialize for $name {\n\n fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {\n\n use serde::ser::SerializeSeq;\n\n\n\n let seq_len = if *self == $name::Null { 1 } else { 2 };\n\n let mut seq = s.serialize_seq(Some(seq_len))?;\n\n\n\n match *self {\n", "file_path": "src/confidential.rs", "rank": 49, "score": 12.003346989534432 }, { "content": " };\n\n AssetId(fast_merkle_root(&[entropy.into_inner(), second]))\n\n }\n\n}\n\n\n\nimpl hex::FromHex for AssetId {\n\n fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>\n\n where\n\n I: Iterator<Item = Result<u8, hex::Error>> + ExactSizeIterator + DoubleEndedIterator,\n\n {\n\n sha256::Midstate::from_byte_iter(iter).map(AssetId)\n\n }\n\n}\n\n\n\nimpl ::std::fmt::Display for AssetId {\n\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n ::std::fmt::Display::fmt(&self.0, f)\n\n }\n\n}\n\n\n", "file_path": "src/issuance.rs", "rank": 50, "score": 11.939464360382683 }, { "content": " Confidential(u8, [u8; 32]),\n\n}\n\nimpl_confidential_commitment!(Nonce, 0x02, 0x03);\n\n\n\nimpl Nonce {\n\n /// Serialized length, in bytes\n\n pub fn encoded_length(&self) -> usize {\n\n match *self {\n\n Nonce::Null => 1,\n\n Nonce::Explicit(..) => 33,\n\n Nonce::Confidential(..) => 33,\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use bitcoin::hashes::Hash;\n\n use super::*;\n\n\n", "file_path": "src/confidential.rs", "rank": 51, "score": 11.854030035843543 }, { "content": " struct BytesVisitor;\n\n\n\n impl<'de> ::serde::de::Visitor<'de> for BytesVisitor {\n\n type Value = AssetId;\n\n\n\n fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n formatter.write_str(\"a bytestring\")\n\n }\n\n\n\n fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>\n\n where\n\n E: ::serde::de::Error,\n\n {\n\n if v.len() != 32 {\n\n Err(E::invalid_length(v.len(), &stringify!($len)))\n\n } else {\n\n let mut ret = [0; 32];\n\n ret.copy_from_slice(v);\n\n Ok(AssetId(sha256::Midstate::from_inner(ret)))\n\n }\n", "file_path": "src/issuance.rs", "rank": 52, "score": 11.759500166007271 }, { "content": "\n\n#[doc(hidden)]\n\nimpl From<base58::Error> for AddressError {\n\n fn from(e: base58::Error) -> AddressError {\n\n AddressError::Base58(e)\n\n }\n\n}\n\n\n\n/// The parameters to derive addresses.\n\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub struct AddressParams {\n\n /// The base58 prefix for p2pkh addresses.\n\n pub p2pkh_prefix: u8,\n\n /// The base58 prefix for p2sh addresses.\n\n pub p2sh_prefix: u8,\n\n /// The base58 prefix for blinded addresses.\n\n pub blinded_prefix: u8,\n\n /// The bech32 HRP for unblinded segwit addresses.\n\n pub bech_hrp: &'static str,\n\n /// The bech32 HRP for blinded segwit addresses.\n", "file_path": "src/address.rs", "rank": 53, "score": 11.303158686465974 }, { "content": " if b32_ex || b32_bl {\n\n return Address::from_bech32(s, b32_bl, params);\n\n }\n\n\n\n // Base58.\n\n if s.len() > 150 {\n\n return Err(base58::Error::InvalidLength(s.len() * 11 / 15))?;\n\n }\n\n let data = base58::from_check(s)?;\n\n Address::from_base58(&data, params)\n\n }\n\n}\n\n\n\nimpl fmt::Display for Address {\n\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n\n match self.payload {\n\n Payload::PubkeyHash(ref hash) => {\n\n if let Some(ref blinder) = self.blinding_pubkey {\n\n let mut prefixed = [0; 55]; // 1 + 1 + 33 + 20\n\n prefixed[0] = self.params.blinded_prefix;\n", "file_path": "src/address.rs", "rank": 54, "score": 11.290554301222674 }, { "content": "// Rust Elements Library\n\n// Written by\n\n// The Elements developers\n\n//\n\n// To the extent possible under law, the author(s) have dedicated all\n\n// copyright and related and neighboring rights to this software to\n\n// the public domain worldwide. This software is distributed without\n\n// any warranty.\n\n//\n\n// You should have received a copy of the CC0 Public Domain Dedication\n\n// along with this software.\n\n// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n\n//\n\n\n\n//! # Addresses\n\n//!\n\n\n\nuse std::error;\n\nuse std::fmt;\n\nuse std::str::FromStr;\n", "file_path": "src/address.rs", "rank": 55, "score": 11.21997313537004 }, { "content": " return Err(base58::Error::InvalidVersion(vec![prefix]))?;\n\n };\n\n\n\n Ok(Address {\n\n params: params,\n\n payload: payload,\n\n blinding_pubkey: blinding_pubkey,\n\n })\n\n }\n\n\n\n /// Parse the address using the given parameters.\n\n /// When using the built-in parameters, you can use [FromStr].\n\n pub fn parse_with_params(\n\n s: &str,\n\n params: &'static AddressParams,\n\n ) -> Result<Address, AddressError> {\n\n // Bech32.\n\n let prefix = find_prefix(s);\n\n let b32_ex = match_prefix(prefix, params.bech_hrp);\n\n let b32_bl = match_prefix(prefix, params.blech_hrp);\n", "file_path": "src/address.rs", "rank": 56, "score": 11.058516824142478 }, { "content": " $( ret += self.$field.consensus_encode(&mut s)?; )+\n\n Ok(ret)\n\n }\n\n }\n\n\n\n impl $crate::encode::Decodable for $thing {\n\n #[inline]\n\n fn consensus_decode<D: $crate::std::io::Read>(mut d: D) -> Result<$thing, $crate::encode::Error> {\n\n Ok($thing {\n\n $( $field: $crate::encode::Decodable::consensus_decode(&mut d)?, )+\n\n })\n\n }\n\n }\n\n );\n\n}\n\n\n\nmacro_rules! serde_struct_impl {\n\n ($name:ident, $($fe:ident),*) => (\n\n #[cfg(feature = \"serde\")]\n\n impl<'de> $crate::serde::Deserialize<'de> for $name {\n", "file_path": "src/internal_macros.rs", "rank": 57, "score": 10.968332041961084 }, { "content": " st.end()\n\n },\n\n ExtData::Dynafed { ref current, ref proposed, ref signblock_witness } => {\n\n let mut st = s.serialize_struct(\"ExtData\", 3)?;\n\n st.serialize_field(\"current\", current)?;\n\n st.serialize_field(\"proposed\", proposed)?;\n\n st.serialize_field(\"signblock_witness\", signblock_witness)?;\n\n st.end()\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl Encodable for ExtData {\n\n fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n Ok(match *self {\n\n ExtData::Proof {\n\n ref challenge,\n\n ref solution,\n\n } => {\n", "file_path": "src/block.rs", "rank": 58, "score": 10.771278541532848 }, { "content": "// Rust Bitcoin Library\n\n// Written in 2014 by\n\n// Andrew Poelstra <[email protected]>\n\n//\n\n// To the extent possible under law, the author(s) have dedicated all\n\n// copyright and related and neighboring rights to this software to\n\n// the public domain worldwide. This software is distributed without\n\n// any warranty.\n\n//\n\n// You should have received a copy of the CC0 Public Domain Dedication\n\n// along with this software.\n\n// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n\n//\n\n\n\nmacro_rules! impl_consensus_encoding {\n\n ($thing:ident, $($field:ident),+) => (\n\n impl $crate::encode::Encodable for $thing {\n\n #[inline]\n\n fn consensus_encode<S: $crate::std::io::Write>(&self, mut s: S) -> Result<usize, $crate::encode::Error> {\n\n let mut ret = 0;\n", "file_path": "src/internal_macros.rs", "rank": 59, "score": 10.76384260727336 }, { "content": " ret += self.input.consensus_encode(&mut s)?;\n\n ret += self.output.consensus_encode(&mut s)?;\n\n ret += self.lock_time.consensus_encode(&mut s)?;\n\n\n\n if wit_flag {\n\n for i in &self.input {\n\n ret += i.witness.consensus_encode(&mut s)?;\n\n }\n\n for o in &self.output {\n\n ret += o.witness.consensus_encode(&mut s)?;\n\n }\n\n }\n\n Ok(ret)\n\n }\n\n}\n\n\n\nimpl Decodable for Transaction {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<Transaction, encode::Error> {\n\n let version = u32::consensus_decode(&mut d)?;\n\n let wit_flag = u8::consensus_decode(&mut d)?;\n", "file_path": "src/transaction.rs", "rank": 61, "score": 10.381539534766944 }, { "content": " Dynafed {\n\n /// Current dynamic federation parameters\n\n current: dynafed::Params,\n\n /// Proposed dynamic federation parameters\n\n proposed: dynafed::Params,\n\n /// Witness satisfying the current blocksigning script\n\n signblock_witness: Vec<Vec<u8>>,\n\n },\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\nimpl<'de> Deserialize<'de> for ExtData {\n\n fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {\n\n use serde::de;\n\n\n\n enum Enum { Unknown, Challenge, Solution, Current, Proposed, Witness }\n\n struct EnumVisitor;\n\n\n\n impl<'de> de::Visitor<'de> for EnumVisitor {\n\n type Value = Enum;\n", "file_path": "src/block.rs", "rank": 62, "score": 10.295536142095473 }, { "content": " }\n\n}\n\n\n\nimpl Decodable for BlockHeader {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {\n\n let mut version: u32 = Decodable::consensus_decode(&mut d)?;\n\n let is_dyna = if version >> 31 == 1 {\n\n version &= 0x7fff_ffff;\n\n true\n\n } else {\n\n false\n\n };\n\n\n\n Ok(BlockHeader {\n\n version: version,\n\n prev_blockhash: Decodable::consensus_decode(&mut d)?,\n\n merkle_root: Decodable::consensus_decode(&mut d)?,\n\n time: Decodable::consensus_decode(&mut d)?,\n\n height: Decodable::consensus_decode(&mut d)?,\n\n ext: if is_dyna {\n", "file_path": "src/block.rs", "rank": 63, "score": 10.210851777284848 }, { "content": " data.extend_from_slice(&witprog);\n\n let mut b32_data = vec![witver];\n\n b32_data.extend_from_slice(&data.to_base32());\n\n blech32::encode_to_fmt(fmt, &hrp, &b32_data)\n\n } else {\n\n let mut bech32_writer = bech32::Bech32Writer::new(hrp, fmt)?;\n\n bech32::WriteBase32::write_u5(&mut bech32_writer, witver)?;\n\n bech32::ToBase32::write_base32(&witprog, &mut bech32_writer)\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Address {\n\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n\n fmt::Display::fmt(self, fmt)\n\n }\n\n}\n\n\n\n/// Extract the bech32 prefix.\n\n/// Returns the same slice when no prefix is found.\n", "file_path": "src/address.rs", "rank": 64, "score": 10.195563831991638 }, { "content": "mod fast_merkle_root;\n\npub mod issuance;\n\nmod transaction;\n\n\n\n// export everything at the top level so it can be used as `elements::Transaction` etc.\n\npub use address::{Address, AddressParams, AddressError};\n\npub use transaction::{OutPoint, PeginData, PegoutData, TxIn, TxOut, TxInWitness, TxOutWitness, Transaction, AssetIssuance};\n\npub use block::{BlockHeader, Block};\n\npub use block::ExtData as BlockExtData;\n\npub use ::bitcoin::consensus::encode::VarInt;\n\npub use fast_merkle_root::fast_merkle_root;\n\npub use issuance::AssetId;\n\n\n", "file_path": "src/lib.rs", "rank": 65, "score": 10.138608889432234 }, { "content": " where\n\n E: serde::de::Error,\n\n {\n\n self.visit_str(v)\n\n }\n\n\n\n fn visit_string<E>(self, v: String) -> Result<Self::Value, E>\n\n where\n\n E: serde::de::Error,\n\n {\n\n self.visit_str(&v)\n\n }\n\n }\n\n\n\n deserializer.deserialize_str(Visitor)\n\n }\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\nimpl serde::Serialize for Address {\n", "file_path": "src/address.rs", "rank": 66, "score": 10.079154079612412 }, { "content": "// Original documentation is left untouched, so it corresponds to bech32.\n\n\n\nuse std::fmt;\n\n\n\n// AsciiExt is needed until for Rust 1.26 but not for newer versions\n\n#[allow(unused_imports, deprecated)]\n\nuse std::ascii::AsciiExt;\n\n\n\nuse bitcoin::bech32::{u5, Error};\n\n\n\n/// Encode a bech32 payload to an [fmt::Formatter].\n", "file_path": "src/blech32.rs", "rank": 67, "score": 9.897489060178378 }, { "content": " Base58(base58::Error),\n\n /// Bech32 encoding error\n\n Bech32(bech32::Error),\n\n /// Blech32 encoding error\n\n Blech32(bech32::Error),\n\n /// Was unable to parse the address.\n\n InvalidAddress(String),\n\n /// Script version must be 0 to 16 inclusive\n\n InvalidWitnessVersion,\n\n /// Unsupported witness version\n\n UnsupportedWitnessVersion(u8),\n\n /// An invalid blinding pubkey was encountered.\n\n InvalidBlindingPubKey(secp256k1::Error),\n\n /// Given the program version, the length is invalid\n\n ///\n\n /// Version 0 scripts must be either 20 or 32 bytes\n\n InvalidWitnessProgramLength,\n\n}\n\n\n\nimpl fmt::Display for AddressError {\n", "file_path": "src/address.rs", "rank": 68, "score": 9.837385906682616 }, { "content": " fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>\n\n where\n\n A: de::MapAccess<'de>,\n\n {\n\n let mut signblockscript = None;\n\n let mut signblock_witness_limit = None;\n\n let mut fedpeg_program = None;\n\n let mut fedpegscript = None;\n\n let mut extension_space = None;\n\n\n\n loop {\n\n match map.next_key::<Enum>()? {\n\n Some(Enum::Unknown) => {\n\n map.next_value::<de::IgnoredAny>()?;\n\n },\n\n Some(Enum::SignblockScript) => {\n\n signblockscript = Some(map.next_value()?);\n\n },\n\n Some(Enum::SignblockWitnessLimit) => {\n\n signblock_witness_limit = Some(map.next_value()?);\n", "file_path": "src/dynafed.rs", "rank": 69, "score": 9.823694741963159 }, { "content": " 4 + // version\n\n 4 + // locktime\n\n VarInt(self.input.len() as u64).len() as usize +\n\n VarInt(self.output.len() as u64).len() as usize +\n\n 1 // segwit flag byte (note this is *not* witness data in Elements)\n\n ) + input_weight + output_weight\n\n }\n\n\n\n /// The txid of the transaction. To get its hash, use `BitcoinHash::bitcoin_hash()`.\n\n pub fn txid(&self) -> sha256d::Hash {\n\n let mut enc = sha256d::Hash::engine();\n\n self.version.consensus_encode(&mut enc).unwrap();\n\n 0u8.consensus_encode(&mut enc).unwrap();\n\n self.input.consensus_encode(&mut enc).unwrap();\n\n self.output.consensus_encode(&mut enc).unwrap();\n\n self.lock_time.consensus_encode(&mut enc).unwrap();\n\n sha256d::Hash::from_engine(enc)\n\n }\n\n}\n\n\n", "file_path": "src/transaction.rs", "rank": 70, "score": 9.783849346624084 }, { "content": "\n\n// AsciiExt is needed until for Rust 1.26 but not for newer versions\n\n#[allow(unused_imports, deprecated)]\n\nuse std::ascii::AsciiExt;\n\n\n\nuse bitcoin::bech32::{self, u5, FromBase32, ToBase32};\n\nuse bitcoin::blockdata::{opcodes, script};\n\nuse bitcoin::util::base58;\n\nuse bitcoin::PublicKey;\n\nuse bitcoin::hashes::{hash160, Hash};\n\nuse bitcoin::secp256k1;\n\n#[cfg(feature = \"serde\")]\n\nuse serde;\n\n\n\nuse blech32;\n\n\n\n/// Encoding error\n\n#[derive(Debug, PartialEq)]\n\npub enum AddressError {\n\n /// Base58 encoding error\n", "file_path": "src/address.rs", "rank": 71, "score": 9.720000425507193 }, { "content": " signblock_witness_limit: Decodable::consensus_decode(&mut d)?,\n\n fedpeg_program: Decodable::consensus_decode(&mut d)?,\n\n fedpegscript: Decodable::consensus_decode(&mut d)?,\n\n extension_space: Decodable::consensus_decode(&mut d)?,\n\n }),\n\n _ => Err(encode::Error::ParseFailed(\n\n \"bad serialize type for dynafed parameters\"\n\n )),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use bitcoin;\n\n use bitcoin::hashes::hex::ToHex;\n\n\n\n #[test]\n", "file_path": "src/dynafed.rs", "rank": 72, "score": 9.683938829149028 }, { "content": " ret += self.script_sig.consensus_encode(&mut s)?;\n\n ret += self.sequence.consensus_encode(&mut s)?;\n\n if self.has_issuance() {\n\n ret += self.asset_issuance.consensus_encode(&mut s)?;\n\n }\n\n Ok(ret)\n\n }\n\n}\n\n\n\nimpl Decodable for TxIn {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<TxIn, encode::Error> {\n\n let mut outp = OutPoint::consensus_decode(&mut d)?;\n\n let script_sig = Script::consensus_decode(&mut d)?;\n\n let sequence = u32::consensus_decode(&mut d)?;\n\n let issuance;\n\n let is_pegin;\n\n let has_issuance;\n\n // Pegin/issuance flags are encoded into the high bits of `vout`, *except*\n\n // if vout is all 1's; this indicates a coinbase transaction\n\n if outp.vout == 0xffffffff {\n", "file_path": "src/transaction.rs", "rank": 73, "score": 9.668815828601199 }, { "content": " fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {\n\n Ok(match *self {\n\n Params::Null => Encodable::consensus_encode(&0u8, &mut s)?,\n\n Params::Compact {\n\n ref signblockscript,\n\n ref signblock_witness_limit,\n\n } => {\n\n Encodable::consensus_encode(&1u8, &mut s)? +\n\n Encodable::consensus_encode(signblockscript, &mut s)? +\n\n Encodable::consensus_encode(signblock_witness_limit, &mut s)?\n\n },\n\n Params::Full {\n\n ref signblockscript,\n\n ref signblock_witness_limit,\n\n ref fedpeg_program,\n\n ref fedpegscript,\n\n ref extension_space,\n\n } => {\n\n Encodable::consensus_encode(&2u8, &mut s)? +\n\n Encodable::consensus_encode(signblockscript, &mut s)? +\n", "file_path": "src/dynafed.rs", "rank": 74, "score": 9.512889275882795 }, { "content": " Encodable::consensus_encode(signblock_witness_limit, &mut s)? +\n\n Encodable::consensus_encode(fedpeg_program, &mut s)? +\n\n Encodable::consensus_encode(fedpegscript, &mut s)? +\n\n Encodable::consensus_encode(extension_space, &mut s)?\n\n },\n\n })\n\n }\n\n}\n\n\n\nimpl Decodable for Params {\n\n fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {\n\n let ser_type: u8 = Decodable::consensus_decode(&mut d)?;\n\n match ser_type {\n\n 0 => Ok(Params::Null),\n\n 1 => Ok(Params::Compact {\n\n signblockscript: Decodable::consensus_decode(&mut d)?,\n\n signblock_witness_limit: Decodable::consensus_decode(&mut d)?,\n\n }),\n\n 2 => Ok(Params::Full {\n\n signblockscript: Decodable::consensus_decode(&mut d)?,\n", "file_path": "src/dynafed.rs", "rank": 75, "score": 9.50477393126085 }, { "content": " $name::Null => seq.serialize_element(&0u8)?,\n\n $name::Explicit(n) => {\n\n seq.serialize_element(&1u8)?;\n\n // Apply $explicit_fn to allow `Value` to swap the amount bytes\n\n seq.serialize_element(&$explicit_fn(n))?;\n\n }\n\n $name::Confidential(prefix, bytes) => {\n\n seq.serialize_element(&prefix)?;\n\n seq.serialize_element(&bytes)?;\n\n }\n\n }\n\n seq.end()\n\n }\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n impl<'de> Deserialize<'de> for $name {\n\n fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {\n\n use serde::de::{Error, Visitor, SeqAccess};\n\n struct CommitVisitor;\n", "file_path": "src/confidential.rs", "rank": 76, "score": 9.390742620212528 }, { "content": " fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: serde::Serializer,\n\n {\n\n serializer.serialize_str(&self.to_string())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use bitcoin::util::key;\n\n use bitcoin::Script;\n\n use bitcoin::secp256k1::{PublicKey, Secp256k1};\n\n #[cfg(feature = \"serde\")]\n\n use serde_json;\n\n\n\n fn roundtrips(addr: &Address) {\n\n assert_eq!(\n\n Address::from_str(&addr.to_string()).ok().as_ref(),\n", "file_path": "src/address.rs", "rank": 77, "score": 9.220381230775157 }, { "content": " };\n\n\n\n Ok(ret)\n\n }\n\n }\n\n // end type defs\n\n\n\n static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*];\n\n\n\n deserializer.deserialize_struct(stringify!($name), FIELDS, Visitor)\n\n }\n\n }\n\n\n\n #[cfg(feature = \"serde\")]\n\n impl $crate::serde::Serialize for $name {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: $crate::serde::Serializer,\n\n {\n\n use $crate::serde::ser::SerializeStruct;\n", "file_path": "src/internal_macros.rs", "rank": 78, "score": 9.151681726066242 }, { "content": " Ok(TxOut {\n\n asset: Decodable::consensus_decode(&mut d)?,\n\n value: Decodable::consensus_decode(&mut d)?,\n\n nonce: Decodable::consensus_decode(&mut d)?,\n\n script_pubkey: Decodable::consensus_decode(&mut d)?,\n\n witness: TxOutWitness::default(),\n\n })\n\n }\n\n}\n\n\n\nimpl TxOut {\n\n /// Whether this data represents nulldata (OP_RETURN followed by pushes,\n\n /// not necessarily minimal)\n\n pub fn is_null_data(&self) -> bool {\n\n let mut iter = self.script_pubkey.iter(false);\n\n if iter.next() == Some(Instruction::Op(opcodes::all::OP_RETURN)) {\n\n for push in iter {\n\n match push {\n\n Instruction::Op(op) if op.into_u8() > opcodes::all::OP_PUSHNUM_16.into_u8() => return false,\n\n Instruction::Error(_) => return false,\n", "file_path": "src/transaction.rs", "rank": 79, "score": 8.947815529367617 }, { "content": "use bitcoin::blockdata::opcodes;\n\nuse bitcoin::blockdata::script::{Script, Instruction};\n\nuse bitcoin::hashes::{Hash, sha256d};\n\n\n\nuse confidential;\n\nuse encode::{self, Encodable, Decodable};\n\n\n\n/// Description of an asset issuance in a transaction input\n\n#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]\n\npub struct AssetIssuance {\n\n /// Zero for a new asset issuance; otherwise a blinding factor for the input\n\n pub asset_blinding_nonce: [u8; 32],\n\n /// Freeform entropy field\n\n pub asset_entropy: [u8; 32],\n\n /// Amount of asset to issue\n\n pub amount: confidential::Value,\n\n /// Amount of inflation keys to issue\n\n pub inflation_keys: confidential::Value,\n\n}\n\nserde_struct_impl!(AssetIssuance, asset_blinding_nonce, asset_entropy, amount, inflation_keys);\n", "file_path": "src/transaction.rs", "rank": 80, "score": 8.703103457775168 }, { "content": " AddressError::Bech32(ref e) => Some(e),\n\n AddressError::Blech32(ref e) => Some(e),\n\n AddressError::InvalidBlindingPubKey(ref e) => Some(e),\n\n _ => None,\n\n }\n\n }\n\n\n\n fn description(&self) -> &str {\n\n match *self {\n\n AddressError::Base58(ref e) => e.description(),\n\n AddressError::Bech32(ref e) => e.description(),\n\n AddressError::Blech32(ref e) => e.description(),\n\n AddressError::InvalidAddress(..) => \"was unable to parse the address\",\n\n AddressError::UnsupportedWitnessVersion(..) => \"unsupported witness version\",\n\n AddressError::InvalidBlindingPubKey(..) => \"an invalid blinding pubkey was encountered\",\n\n AddressError::InvalidWitnessProgramLength => \"program length incompatible with version\",\n\n AddressError::InvalidWitnessVersion => \"invalid witness script version\",\n\n }\n\n }\n\n}\n", "file_path": "src/address.rs", "rank": 81, "score": 8.66169275397817 }, { "content": "\n\n // Only used to get the struct length.\n\n static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*];\n\n\n\n let mut st = serializer.serialize_struct(stringify!($name), FIELDS.len())?;\n\n\n\n $(\n\n st.serialize_field(stringify!($fe), &self.$fe)?;\n\n )*\n\n\n\n st.end()\n\n }\n\n }\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\nmacro_rules! hex_deserialize(\n\n ($e:expr) => ({\n\n use $crate::encode::deserialize;\n", "file_path": "src/internal_macros.rs", "rank": 82, "score": 8.262198490063165 }, { "content": " Full {\n\n /// \"scriptPubKey\" used for block signing\n\n signblockscript: bitcoin::Script,\n\n /// Maximum, in bytes, of the size of a blocksigning witness\n\n signblock_witness_limit: u32,\n\n /// Untweaked `scriptPubKey` used for pegins\n\n fedpeg_program: bitcoin::Script,\n\n /// For v0 fedpeg programs, the witness script of the untweaked\n\n /// pegin address. For future versions, this data has no defined\n\n /// meaning and will be considered \"anyone can spend\".\n\n fedpegscript: Vec<u8>,\n\n /// \"Extension space\" used by Liquid for PAK key entries\n\n extension_space: Vec<Vec<u8>>,\n\n },\n\n}\n\n\n\nimpl Params {\n\n /// Check whether this is [Params::Null].\n\n pub fn is_null(&self) -> bool {\n\n match *self {\n", "file_path": "src/dynafed.rs", "rank": 83, "score": 8.133326719912077 }, { "content": " }\n\n }\n\n\n\n d.deserialize_bytes(BytesVisitor)\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use std::str::FromStr;\n\n\n\n use bitcoin::hashes::hex::FromHex;\n\n use bitcoin::hashes::sha256;\n\n\n\n #[test]\n\n fn example_elements_core() {\n\n // example test data from Elements Core 0.17\n\n let prevout_str = \"05a047c98e82a848dee94efcf32462b065198bebf2404d201ba2e06db30b28f4:0\";\n", "file_path": "src/issuance.rs", "rank": 84, "score": 8.116521000773798 }, { "content": "#[cfg(feature = \"serde\")] use serde::{Deserialize, Deserializer, Serialize, Serializer};\n\n#[cfg(feature = \"serde\")] use std::fmt;\n\n\n\nuse encode::{self, Encodable, Decodable};\n\n\n\n/// Dynamic federations paramaters, as encoded in a block header\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub enum Params {\n\n /// Null entry, used to signal \"no vote\" as a proposal\n\n Null,\n\n /// Compact params where the fedpeg data and extension space\n\n /// are not included, and are assumed to be equal to the values\n\n /// from the previous block\n\n Compact {\n\n /// \"scriptPubKey\" used for block signing\n\n signblockscript: bitcoin::Script,\n\n /// Maximum, in bytes, of the size of a blocksigning witness\n\n signblock_witness_limit: u32,\n\n },\n\n /// Full dynamic federations parameters\n", "file_path": "src/dynafed.rs", "rank": 85, "score": 8.102104719351711 }, { "content": "\n\n#[cfg(feature = \"serde\")]\n\nimpl Serialize for Params {\n\n fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {\n\n use serde::ser::SerializeStruct;\n\n\n\n match *self {\n\n Params::Null => {\n\n let st = s.serialize_struct(\"Params\", 0)?;\n\n st.end()\n\n },\n\n Params::Compact {\n\n ref signblockscript,\n\n ref signblock_witness_limit,\n\n } => {\n\n let mut st = s.serialize_struct(\"Params\", 2)?;\n\n st.serialize_field(\"signblockscript\", signblockscript)?;\n\n st.serialize_field(\"signblock_witness_limit\", signblock_witness_limit)?;\n\n st.end()\n\n },\n", "file_path": "src/dynafed.rs", "rank": 86, "score": 8.008993186687546 }, { "content": "use bitcoin::BitcoinHash;\n\nuse bitcoin::hashes::{Hash, sha256d, sha256};\n\n#[cfg(feature = \"serde\")] use serde::{Deserialize, Deserializer, Serialize, Serializer};\n\n#[cfg(feature = \"serde\")] use std::fmt;\n\n\n\nuse dynafed;\n\nuse Transaction;\n\nuse encode::{self, Encodable, Decodable};\n\n\n\n/// Data related to block signatures\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub enum ExtData {\n\n /// Liquid v1-style static `signblockscript` and witness\n\n Proof {\n\n /// Block \"public key\"\n\n challenge: Script,\n\n /// Satisfying witness to the above challenge, or nothing\n\n solution: Script,\n\n },\n\n /// Dynamic federations\n", "file_path": "src/block.rs", "rank": 87, "score": 7.970849671162508 }, { "content": " \"challenge\",\n\n \"solution\",\n\n \"current\",\n\n \"proposed\",\n\n \"signblock_witness\",\n\n ];\n\n d.deserialize_struct(\"ExtData\", FIELDS, Visitor)\n\n }\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\nimpl Serialize for ExtData {\n\n fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {\n\n use serde::ser::SerializeStruct;\n\n\n\n match *self {\n\n ExtData::Proof { ref challenge, ref solution } => {\n\n let mut st = s.serialize_struct(\"ExtData\", 2)?;\n\n st.serialize_field(\"challenge\", challenge)?;\n\n st.serialize_field(\"solution\", solution)?;\n", "file_path": "src/block.rs", "rank": 88, "score": 7.93688486853317 }, { "content": "// Coding conventions\n\n#![deny(non_upper_case_globals)]\n\n#![deny(non_camel_case_types)]\n\n#![deny(non_snake_case)]\n\n#![deny(unused_mut)]\n\n#![deny(missing_docs)]\n\n\n\npub extern crate bitcoin;\n\n#[cfg(feature = \"serde\")] extern crate serde;\n\n\n\n#[cfg(test)] extern crate rand;\n\n#[cfg(test)] extern crate serde_json;\n\n\n\n#[macro_use] mod internal_macros;\n\npub mod address;\n\npub mod blech32;\n\nmod block;\n\npub mod confidential;\n\npub mod dynafed;\n\npub mod encode;\n", "file_path": "src/lib.rs", "rank": 89, "score": 7.79854206581876 }, { "content": " pub blech_hrp: &'static str,\n\n}\n\n\n\nimpl AddressParams {\n\n /// The Liquid network address parameters.\n\n pub const LIQUID: AddressParams = AddressParams {\n\n p2pkh_prefix: 57,\n\n p2sh_prefix: 39,\n\n blinded_prefix: 12,\n\n bech_hrp: \"ex\",\n\n blech_hrp: \"lq\",\n\n };\n\n\n\n /// The default Elements network address parameters.\n\n pub const ELEMENTS: AddressParams = AddressParams {\n\n p2pkh_prefix: 235,\n\n p2sh_prefix: 75,\n\n blinded_prefix: 4,\n\n bech_hrp: \"ert\",\n\n blech_hrp: \"el\",\n", "file_path": "src/address.rs", "rank": 90, "score": 7.6808743971579325 }, { "content": "\n\n use confidential;\n\n use super::*;\n\n\n\n #[test]\n\n fn outpoint() {\n\n let txid = \"d0a5c455ea7221dead9513596d2f97c09943bad81a386fe61a14a6cda060e422\";\n\n let s = format!(\"{}:42\", txid);\n\n let expected = OutPoint {\n\n txid: sha256d::Hash::from_hex(&txid).unwrap(),\n\n vout: 42,\n\n };\n\n let op = ::std::str::FromStr::from_str(&s).ok();\n\n assert_eq!(op, Some(expected));\n\n // roundtrip with elements prefix\n\n let op = ::std::str::FromStr::from_str(&expected.to_string()).ok();\n\n assert_eq!(op, Some(expected));\n\n }\n\n\n\n #[test]\n", "file_path": "src/transaction.rs", "rank": 91, "score": 7.597676216745057 }, { "content": "// Rust Elements Library\n\n// Written in 2018 by\n\n// Andrew Poelstra <[email protected]>\n\n//\n\n// To the extent possible under law, the author(s) have dedicated all\n\n// copyright and related and neighboring rights to this software to\n\n// the public domain worldwide. This software is distributed without\n\n// any warranty.\n\n//\n\n// You should have received a copy of the CC0 Public Domain Dedication\n\n// along with this software.\n\n// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.\n\n//\n\n\n\n//! # Transactions\n\n//!\n\n\n\nuse std::{io, fmt};\n\n\n\nuse bitcoin::{self, BitcoinHash, VarInt};\n", "file_path": "src/transaction.rs", "rank": 92, "score": 7.447393189723726 }, { "content": "\n\n let leaves = [\n\n serialize_hash(self.signblockscript().unwrap()).into_inner(),\n\n serialize_hash(&self.signblock_witness_limit().unwrap()).into_inner(),\n\n serialize_hash(self.fedpeg_program().unwrap_or(&bitcoin::Script::new())).into_inner(),\n\n serialize_hash(self.fedpegscript().unwrap_or(&Vec::new())).into_inner(),\n\n serialize_hash(self.extension_space().unwrap_or(&Vec::new())).into_inner(),\n\n ];\n\n ::fast_merkle_root::fast_merkle_root(&leaves[..])\n\n }\n\n}\n\n\n\n#[cfg(feature = \"serde\")]\n\nimpl<'de> Deserialize<'de> for Params {\n\n fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {\n\n use serde::de;\n\n\n\n enum Enum {\n\n Unknown,\n\n SignblockScript,\n", "file_path": "src/dynafed.rs", "rank": 93, "score": 7.309635799591048 }, { "content": " /// Get the extension_space. Is [None] for non-[Full] params.\n\n pub fn extension_space(&self) -> Option<&Vec<Vec<u8>>> {\n\n match *self {\n\n Params::Null => None,\n\n Params::Compact { .. } => None,\n\n Params::Full { ref extension_space, ..} => Some(extension_space),\n\n }\n\n }\n\n\n\n /// Calculate the root of this [Params].\n\n pub fn calculate_root(&self) -> sha256::Midstate {\n\n fn serialize_hash<E: Encodable>(obj: &E) -> sha256d::Hash {\n\n let mut engine = sha256d::Hash::engine();\n\n obj.consensus_encode(&mut engine).expect(\"engines don't error\");\n\n sha256d::Hash::from_engine(engine)\n\n }\n\n\n\n if self.is_null() {\n\n return sha256::Midstate::from_inner([0u8; 32]);\n\n }\n", "file_path": "src/dynafed.rs", "rank": 94, "score": 7.289287862030681 }, { "content": "/// A CT commitment to an amount\n\n#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]\n\npub enum Value {\n\n /// No value\n\n Null,\n\n /// Value is explicitly encoded\n\n Explicit(u64),\n\n // Split commitments into a 1-byte prefix and 32-byte commitment, because\n\n // they're easy enough to separate and Rust stdlib treats 32-byte arrays\n\n // much much better than 33-byte arrays.\n\n /// Value is committed\n\n Confidential(u8, [u8; 32]),\n\n}\n\nimpl_confidential_commitment!(Value, 0x08, 0x09, u64::swap_bytes);\n\n\n\nimpl Value {\n\n /// Serialized length, in bytes\n\n pub fn encoded_length(&self) -> usize {\n\n match *self {\n\n Value::Null => 1,\n", "file_path": "src/confidential.rs", "rank": 95, "score": 7.238457271039963 }, { "content": "pub struct TxOutWitness {\n\n /// Surjection proof showing that the asset commitment is legitimate\n\n pub surjection_proof: Vec<u8>,\n\n /// Rangeproof showing that the value commitment is legitimate\n\n pub rangeproof: Vec<u8>,\n\n}\n\nserde_struct_impl!(TxOutWitness, surjection_proof, rangeproof);\n\nimpl_consensus_encoding!(TxOutWitness, surjection_proof, rangeproof);\n\n\n\nimpl TxOutWitness {\n\n /// Whether this witness is null\n\n pub fn is_empty(&self) -> bool {\n\n self.surjection_proof.is_empty() && self.rangeproof.is_empty()\n\n }\n\n}\n\n\n\n/// Information about a pegout\n\n#[derive(Clone, Default, PartialEq, Eq, Debug, Hash)]\n\npub struct PegoutData<'txo> {\n\n /// Amount to peg out\n", "file_path": "src/transaction.rs", "rank": 96, "score": 7.047198276296399 }, { "content": " where\n\n E: ::serde::de::Error,\n\n {\n\n if let Ok(hex) = ::std::str::from_utf8(v) {\n\n AssetId::from_hex(hex).map_err(E::custom)\n\n } else {\n\n return Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self));\n\n }\n\n }\n\n\n\n fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>\n\n where\n\n E: ::serde::de::Error,\n\n {\n\n AssetId::from_hex(v).map_err(E::custom)\n\n }\n\n }\n\n\n\n d.deserialize_str(HexVisitor)\n\n } else {\n", "file_path": "src/issuance.rs", "rank": 97, "score": 7.035874802621891 }, { "content": "/// Elements transaction\n\n#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]\n\npub struct Transaction {\n\n /// Transaction version field (should always be 2)\n\n pub version: u32,\n\n /// Transaction locktime\n\n pub lock_time: u32,\n\n /// Vector of inputs\n\n pub input: Vec<TxIn>,\n\n /// Vector of outputs\n\n pub output: Vec<TxOut>,\n\n}\n\nserde_struct_impl!(Transaction, version, lock_time, input, output);\n\n\n\nimpl Transaction {\n\n /// Whether the transaction is a coinbase tx\n\n pub fn is_coinbase(&self) -> bool {\n\n self.input.len() == 1 && self.input[0].is_coinbase()\n\n }\n\n\n", "file_path": "src/transaction.rs", "rank": 98, "score": 7.006271548970659 }, { "content": " sha256d::Hash::from_engine(enc)\n\n }\n\n}\n\n\n\n/// Elements block\n\n#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]\n\npub struct Block {\n\n /// Header of the block\n\n pub header: BlockHeader,\n\n /// Complete list of transaction in the block\n\n pub txdata: Vec<Transaction>,\n\n}\n\nserde_struct_impl!(Block, header, txdata);\n\nimpl_consensus_encoding!(Block, header, txdata);\n\n\n\nimpl BitcoinHash for Block {\n\n fn bitcoin_hash(&self) -> sha256d::Hash {\n\n self.header.bitcoin_hash()\n\n }\n\n}\n", "file_path": "src/block.rs", "rank": 99, "score": 6.9817269523071275 } ]
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/rp -- \\\n\n -r /foo:http://localhost:3000/foo \\\n\n -r /bar:http://localhost:3001/bar\n\n~~~~\n\n\n\n## Use a config file\n\n\n\nYou can use a config file instead of specified settings to arguments.\n\n\n\n(1) ./conf.yaml\n\n\n\n~~~~yaml\n\nreverse_proxy:\n\n - path: /foo\n\n url: http://localhost:3000/foo\n\n - path: /bar\n\n url: http://localhost:3001/bar\n\n~~~~\n\n\n\n(2) run\n\n\n\n~~~~shell\n\ndocker --rm -it --network host -v $PWD/conf.yaml:/conf/conf.yaml sifyfy/rp\n\n~~~~\n\n\n\n## Build\n\n\n\n### Build docker image\n\n\n\n~~~~shell\n\ngit clone https://github.com/sifyfy/docker-rp.git\n\ncd docker-rp\n\nmake\n\n~~~~\n\n\n\n### Build the generating nginx conf command\n\n\n\nRequirements: Rust 1.30+ (Recommend latest stable)\n\n\n\n~~~~shell\n\ngit clone https://github.com/sifyfy/docker-rp.git\n\ncd docker-rp\n\ncargo build\n\n~~~~\n\n\n\nor install `generate-simple-reverse-proxy-conf-to-nginx`\n\n\n\n~~~~shell\n\ncargo install --git https://github.com/sifyfy/docker-rp.git\n\n~~~~\n", "file_path": "README.md", "rank": 15, "score": 9.578734779616065 } ]
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 ::prost_build::Config::new()\n\n .out_dir(\"./src\")\n\n .type_attribute(\".\", \"#[derive(::serde::Serialize, ::serde::Deserialize)]\")\n\n .type_attribute(\".\", \"#[serde(rename_all = \\\"camelCase\\\")]\")\n\n .type_attribute(\n\n \"entities.Exchanges\",\n\n \"#[derive(::num_derive::FromPrimitive, ::clap::Parser)]\",\n\n )\n\n .type_attribute(\"entities.Exchanges\", \"#[serde(tag = \\\"exchange\\\")]\")\n\n .type_attribute(\n\n \"entities.BackTestPriceBase\",\n\n \"#[derive(::num_derive::FromPrimitive, ::clap::Parser)]\",\n", "file_path": "backend/libs/rpc/build.rs", "rank": 0, "score": 128170.71327965078 }, { "content": "pub fn build_debug() -> Logger {\n\n let dec = ::slog_term::TermDecorator::new().build();\n\n let drain = ::slog_term::FullFormat::new(dec).build().fuse();\n\n return new_root_logger(Mutex::new(drain).fuse());\n\n}\n\n\n", "file_path": "backend/libs/slog_builder/src/lib.rs", "rank": 1, "score": 106467.25999142969 }, { "content": "pub fn build_json() -> Logger {\n\n let drain = ::slog_json::Json::new(::std::io::stdout())\n\n .add_default_keys()\n\n .build()\n\n .fuse();\n\n return new_root_logger(Mutex::new(drain).fuse());\n\n}\n", "file_path": "backend/libs/slog_builder/src/lib.rs", "rank": 2, "score": 106467.25999142969 }, { "content": "fn new_root_logger<T>(drain: T) -> Logger\n\nwhere\n\n T: SendSyncRefUnwindSafeDrain<Ok = (), Err = Never> + UnwindSafe + 'static,\n\n{\n\n return Logger::root(drain, o!(\"version\" => env!(\"CARGO_PKG_VERSION\")));\n\n}\n\n\n", "file_path": "backend/libs/slog_builder/src/lib.rs", "rank": 3, "score": 105009.9943223704 }, { "content": "fn handle_websocket(\n\n exchange: impl TradeObserverTrait + Send + Sync + 'static,\n\n ws: ::warp::ws::Ws,\n\n) -> impl Reply {\n\n return ws.on_upgrade(|mut socket: ::warp::ws::WebSocket| async move {\n\n let mut book_tickers: HashMap<String, BookTicker> = HashMap::new();\n\n let mut publish_interval = interval(Duration::from_millis(50));\n\n let mut sub = match exchange.subscribe().await {\n\n Ok(sub) => sub,\n\n Err(e) => {\n\n let _ = socket\n\n .send(Message::close_with(1001 as u16, format!(\"{}\", e)))\n\n .await;\n\n let _ = socket.close().await;\n\n return;\n\n }\n\n };\n\n let mut needs_flush = false;\n\n loop {\n\n select! {\n", "file_path": "backend/services/observer/src/main.rs", "rank": 4, "score": 101971.07515384222 }, { "content": "pub fn construct(db: &Database, cli: Client) -> BoxedFilter<(impl Reply,)> {\n\n let writer = BotInfoRecorder::new(db);\n\n let register = ::warp::post()\n\n .and(::warp::filters::body::json())\n\n .map(move |bot: RPCBot| (bot, cli.clone(), writer.clone()))\n\n .untuple_one()\n\n .and_then(\n\n |bot: RPCBot, cli: Client, writer: BotInfoRecorder| async move {\n\n let bot = Bot::try_from(bot);\n\n if let Err(e) = bot {\n\n let code = StatusCode::EXPECTATION_FAILED;\n\n let status = Status::new(code.clone(), e.to_string());\n\n return Err(::warp::reject::custom(status));\n\n }\n\n let transpiler = Transpiler::new(cli);\n\n let bot = transpiler.transpile(&bot.unwrap()).await;\n\n if let Err(e) = bot {\n\n let code = StatusCode::INTERNAL_SERVER_ERROR;\n\n let status = Status::new(code.clone(), e.to_string());\n\n return Err(::warp::reject::custom(status));\n", "file_path": "backend/services/bot/src/routing.rs", "rank": 5, "score": 84813.77608865123 }, { "content": "use ::clap::Parser;\n\n\n\nuse super::constants::DEFAULT_CONFIG_PATH;\n\n\n\n#[derive(Parser)]\n\n#[clap(author = \"Hiroaki Yamamoto\")]\n\npub struct CmdArgs {\n\n #[clap(short, long, default_value = DEFAULT_CONFIG_PATH)]\n\n pub config: String,\n\n}\n", "file_path": "backend/libs/config/src/cmdargs.rs", "rank": 6, "score": 83274.09816373404 }, { "content": " private deleteKeyPair(index: number) {\n\n return (accepted: boolean) => {\n\n if (!accepted) { return; }\n\n this.keychain.delete(index).subscribe();\n\n };\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 7, "score": 83154.08007070684 }, { "content": " private editKeyPair() {\n\n return (result: EditDialogData) => {\n\n if (result === undefined || result === null) {\n\n return;\n\n }\n\n switch (result.type) {\n\n case RespType.POST:\n\n if (result.index >= 0) {\n\n this.keychain.rename(result.index, result.data.label).subscribe();\n\n } else {\n\n const key = new APIKey();\n\n key.setExchange(result.data.exchange);\n\n key.setLabel(result.data.label);\n\n key.setPubKey(result.data.pubKey);\n\n key.setPrvKey(result.data.prvKey);\n\n const payload = key.toObject();\n\n this.keychain.add(payload).subscribe();\n\n }\n\n break;\n\n case RespType.DELETE:\n\n const dialog = this.dialogOpener.open(DeleteWarnComponent, {\n\n width: '50vw',\n\n data: {\n\n index: result.index,\n\n data: this.keychain.keys[result.index],\n\n }\n\n });\n\n dialog.afterClosed().subscribe(this.deleteKeyPair(result.index));\n\n break;\n\n case RespType.CANCEL:\n\n break;\n\n }\n\n };\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 8, "score": 83154.08007070684 }, { "content": "use ::std::fmt::{Display, Error, Formatter, Result as FmtResult};\n\n\n\nuse ::serde::{Deserialize, Serialize};\n\nuse ::serde_json::to_string;\n\nuse ::warp::reject::Reject;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct CSRFCheckFailed {\n\n pub reason: String,\n\n pub cookie_value: String,\n\n pub header_value: String,\n\n}\n\n\n\nimpl CSRFCheckFailed {\n\n pub fn new(\n\n reason: String,\n\n cookie_value: String,\n\n header_value: String,\n\n ) -> Self {\n\n return Self {\n", "file_path": "backend/libs/csrf/src/errors.rs", "rank": 9, "score": 83057.0006521538 }, { "content": " reason,\n\n cookie_value,\n\n header_value,\n\n };\n\n }\n\n}\n\n\n\nimpl Display for CSRFCheckFailed {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {\n\n let json = to_string(self).map_err(|_| Error {})?;\n\n return write!(f, \"{}\", json);\n\n }\n\n}\n\n\n\nimpl Reject for CSRFCheckFailed {}\n", "file_path": "backend/libs/csrf/src/errors.rs", "rank": 10, "score": 83055.87468644076 }, { "content": "pub fn cast_i64(fld_name: &str, value: &Value) -> StdResult<i64, ParseError> {\n\n return match value.as_i64() {\n\n Some(n) => Ok(n),\n\n None => {\n\n return Err(ParseError::new(Some(fld_name), Some(value.to_string())))\n\n }\n\n };\n\n}\n", "file_path": "backend/libs/types/src/casting.rs", "rank": 19, "score": 73087.81233132893 }, { "content": "pub fn cast_f64(fld_name: &str, value: &Value) -> StdResult<f64, ParseError> {\n\n let err = ParseError::new(Some(fld_name), Some(value.to_string()));\n\n return match value.as_str() {\n\n Some(s) => Ok(s.parse().map_err(|_| err))?,\n\n None => return Err(err),\n\n };\n\n}\n\n\n", "file_path": "backend/libs/types/src/casting.rs", "rank": 20, "score": 73087.81233132893 }, { "content": "pub fn to_stream_raw(\n\n sub: Subscription,\n\n) -> impl Stream<Item = Message> + Send + Sync {\n\n let (sender, receiver) = unbounded_channel();\n\n let _ = sub.with_handler(move |msg| {\n\n return sender\n\n .send(msg)\n\n .map_err(|e| IOError::new(ErrorKind::Other, e));\n\n });\n\n let stream = UnboundedReceiverStream::new(receiver);\n\n return stream;\n\n}\n\n\n", "file_path": "backend/libs/subscribe/src/streams.rs", "rank": 21, "score": 57491.23720820331 }, { "content": "pub fn cast_datetime(\n\n fld_name: &str,\n\n value: &Value,\n\n) -> StdResult<DateTime, ParseError> {\n\n return match value.as_i64() {\n\n Some(n) => Ok(cast_datetime_from_i64(n)),\n\n None => Err(ParseError::new(Some(fld_name), Some(value.to_string()))),\n\n };\n\n}\n\n\n", "file_path": "backend/libs/types/src/casting.rs", "rank": 22, "score": 57491.23720820331 }, { "content": "pub fn to_stream<T>(\n\n sub: Subscription,\n\n) -> impl Stream<Item = (T, Message)> + Send + Sync\n\nwhere\n\n T: DeserializeOwned + Send + Sync,\n\n{\n\n let stream = to_stream_raw(sub);\n\n let stream = stream\n\n .map(|msg| from_msgpack::<T>(&msg.data).map(|d| (d, msg)))\n\n .filter_map(|res| async { res.ok() });\n\n return stream;\n\n}\n", "file_path": "backend/libs/subscribe/src/streams.rs", "rank": 23, "score": 54628.492302884166 }, { "content": " pub prv_key: String,\n\n pub cert: String,\n\n pub ca: String,\n\n pub root: String,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct ServiceAddresses {\n\n pub historical: String,\n\n pub symbol: String,\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct Config {\n\n pub host: String,\n\n #[serde(rename = \"dbURL\")]\n\n pub db_url: String,\n\n #[serde(rename = \"brokerURL\")]\n\n pub broker_url: String,\n", "file_path": "backend/libs/config/src/config.rs", "rank": 24, "score": 50292.28103068608 }, { "content": " #[serde(rename = \"redisURL\", deserialize_with = \"Config::redis_client\")]\n\n pub redis: RedisClient,\n\n #[serde(default)]\n\n pub debug: bool,\n\n pub tls: TLS,\n\n}\n\n\n\nimpl Config {\n\n fn redis_client<'de, D>(de: D) -> Result<RedisClient, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n let url: String = Deserialize::deserialize(de)?;\n\n return ::redis::Client::open(url).map_err(|e| SerdeError::custom(e));\n\n }\n\n pub fn redis(&self, logger: &Logger) -> ThreadSafeResult<Connection> {\n\n for _ in 0..10 {\n\n match self\n\n .redis\n\n .get_connection_with_timeout(Duration::from_secs(1))\n", "file_path": "backend/libs/config/src/config.rs", "rank": 25, "score": 50291.802433519115 }, { "content": " }\n\n\n\n pub fn from_fpath(path: Option<String>) -> GenericResult<Self> {\n\n let path = match path {\n\n None => String::from(super::constants::DEFAULT_CONFIG_PATH),\n\n Some(p) => p,\n\n };\n\n let f = File::open(path)?;\n\n return Ok(Self::from_stream(f)?);\n\n }\n\n\n\n pub fn build_slog(&self) -> Logger {\n\n return match self.debug {\n\n true => build_debug(),\n\n false => build_json(),\n\n };\n\n }\n\n\n\n pub fn build_rest_client(&self) -> GenericResult<Client> {\n\n let ca = Certificate::from_pem(read_to_string(&self.tls.ca)?.as_bytes())?;\n\n return Ok(Client::builder().add_root_certificate(ca).build()?);\n\n }\n\n}\n", "file_path": "backend/libs/config/src/config.rs", "rank": 26, "score": 50290.554800989514 }, { "content": "use ::std::fs::{read_to_string, File};\n\nuse ::std::io::Read;\n\nuse ::std::time::Duration;\n\n\n\nuse ::reqwest::{Certificate, Client};\n\nuse ::serde::de::Error as SerdeError;\n\nuse ::serde::{Deserialize, Deserializer};\n\nuse ::serde_yaml::Result as YaMLResult;\n\nuse ::slog::Logger;\n\nuse ::slog_builder::{build_debug, build_json};\n\n\n\nuse ::types::{GenericResult, ThreadSafeResult};\n\n\n\nuse ::errors::MaximumAttemptExceeded;\n\nuse ::redis::{Client as RedisClient, Connection};\n\n\n\n#[derive(Debug, Clone, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct TLS {\n\n #[serde(rename = \"privateKey\")]\n", "file_path": "backend/libs/config/src/config.rs", "rank": 27, "score": 50289.99087611336 }, { "content": " {\n\n Ok(o) => return Ok(o),\n\n Err(e) => {\n\n ::slog::warn!(\n\n logger,\n\n \"Failed to estanblish the connection to redis. Retrying.\\\n\n (Reason: {:?})\",\n\n e\n\n );\n\n continue;\n\n }\n\n }\n\n }\n\n return Err(Box::new(MaximumAttemptExceeded::default()));\n\n }\n\n pub fn from_stream<T>(st: T) -> YaMLResult<Self>\n\n where\n\n T: Read,\n\n {\n\n return ::serde_yaml::from_reader::<_, Self>(st);\n", "file_path": "backend/libs/config/src/config.rs", "rank": 28, "score": 50285.734786288645 }, { "content": "@Component({\n\n selector: 'app-keychain',\n\n templateUrl: './keychain.component.html',\n\n styleUrls: ['./keychain.component.scss']\n\n})\n\nexport class KeychainComponent implements OnInit {\n\n\n\n constructor(\n\n private dialogOpener: MatDialog,\n\n public keychain: KeychainService,\n\n ) { }\n\n\n\n ngOnInit(): void {}\n\n\n\n openEditDialog(index?: number): void {\n\n const dialog = this.dialogOpener.open(EditDialogComponent, {\n\n width: '50vw',\n\n data: {index},\n\n });\n\n dialog.afterClosed().subscribe(this.editKeyPair());\n\n }\n\n\n\n private editKeyPair() {\n\n return (result: EditDialogData) => {\n\n if (result === undefined || result === null) {\n\n return;\n\n }\n\n switch (result.type) {\n\n case RespType.POST:\n\n if (result.index >= 0) {\n\n this.keychain.rename(result.index, result.data.label).subscribe();\n\n } else {\n\n const key = new APIKey();\n\n key.setExchange(result.data.exchange);\n\n key.setLabel(result.data.label);\n\n key.setPubKey(result.data.pubKey);\n\n key.setPrvKey(result.data.prvKey);\n\n const payload = key.toObject();\n\n this.keychain.add(payload).subscribe();\n\n }\n\n break;\n\n case RespType.DELETE:\n\n const dialog = this.dialogOpener.open(DeleteWarnComponent, {\n\n width: '50vw',\n\n data: {\n\n index: result.index,\n\n data: this.keychain.keys[result.index],\n\n }\n\n });\n\n dialog.afterClosed().subscribe(this.deleteKeyPair(result.index));\n\n break;\n\n case RespType.CANCEL:\n\n break;\n\n }\n\n };\n\n }\n\n\n\n private deleteKeyPair(index: number) {\n\n return (accepted: boolean) => {\n\n if (!accepted) { return; }\n\n this.keychain.delete(index).subscribe();\n\n };\n\n }\n\n\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 29, "score": 50091.088351987244 }, { "content": " constructor(\n\n private dialogOpener: MatDialog,\n\n public keychain: KeychainService,\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 30, "score": 49660.637322050396 }, { "content": " ngOnInit(): void {}\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 31, "score": 49237.52130571132 }, { "content": " openEditDialog(index?: number): void {\n\n const dialog = this.dialogOpener.open(EditDialogComponent, {\n\n width: '50vw',\n\n data: {index},\n\n });\n\n dialog.afterClosed().subscribe(this.editKeyPair());\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 32, "score": 48821.55440066482 }, { "content": "pub fn cast_datetime_from_i64(value: i64) -> DateTime {\n\n return DateTime::from_millis(value);\n\n}\n\n\n", "file_path": "backend/libs/types/src/casting.rs", "rank": 33, "score": 47383.38869330945 }, { "content": "@Injectable({\n\n providedIn: 'root'\n\n})\n\nexport class KeychainService {\n\n private readonly endpoint = '/keychain';\n\n public keys: APIKey.AsObject[] = [];\n\n\n\n constructor(private http: HttpClient) { }\n\n\n\n fetch(): Observable<APIKey.AsObject[]> {\n\n return this.http\n\n .get(`${this.endpoint}/`)\n\n .pipe(\n\n map((value: APIKeyList.AsObject) => value.keysList),\n\n tap((value: APIKey.AsObject[]) => {\n\n this.keys = value;\n\n })\n\n );\n\n }\n\n\n\n add(payload: APIKey.AsObject) {\n\n return this.http\n\n .post(`${this.endpoint}/`, payload)\n\n .pipe(tap((res: InsertOneResult.AsObject) => {\n\n let api = {...payload};\n\n api.prvKey = ('*').repeat(16);\n\n api.id = res.id;\n\n this.keys.push(api);\n\n }));\n\n }\n\n\n\n rename(index: number, label: string) {\n\n const payload: APIRename.AsObject = {label}\n\n return this.http\n\n .patch(`${this.endpoint}/${this.keys[index].id}`, payload)\n\n .pipe(tap(() => {\n\n this.keys[index].label = label;\n\n }));\n\n }\n\n\n\n delete(index: number) {\n\n const target = this.keys.splice(index, 1)[0];\n\n return this.http\n\n .delete(`${this.endpoint}/${target.id}`)\n\n .pipe(catchError((e) => {\n\n this.keys.splice(index, 0, target);\n\n throw e;\n\n }));\n\n }\n", "file_path": "frontend/src/app/resources/keychain.service.ts", "rank": 34, "score": 45511.96562529803 }, { "content": " constructor(private http: HttpClient) { }\n", "file_path": "frontend/src/app/resources/keychain.service.ts", "rank": 35, "score": 44980.60044175374 }, { "content": " delete(index: number) {\n\n const target = this.keys.splice(index, 1)[0];\n\n return this.http\n\n .delete(`${this.endpoint}/${target.id}`)\n\n .pipe(catchError((e) => {\n\n this.keys.splice(index, 0, target);\n\n throw e;\n\n }));\n", "file_path": "frontend/src/app/resources/keychain.service.ts", "rank": 36, "score": 44980.60044175374 }, { "content": " add(payload: APIKey.AsObject) {\n\n return this.http\n\n .post(`${this.endpoint}/`, payload)\n\n .pipe(tap((res: InsertOneResult.AsObject) => {\n\n let api = {...payload};\n\n api.prvKey = ('*').repeat(16);\n\n api.id = res.id;\n\n this.keys.push(api);\n\n }));\n", "file_path": "frontend/src/app/resources/keychain.service.ts", "rank": 37, "score": 44980.60044175374 }, { "content": " fetch(): Observable<APIKey.AsObject[]> {\n\n return this.http\n\n .get(`${this.endpoint}/`)\n\n .pipe(\n\n map((value: APIKeyList.AsObject) => value.keysList),\n\n tap((value: APIKey.AsObject[]) => {\n\n this.keys = value;\n\n })\n\n );\n", "file_path": "frontend/src/app/resources/keychain.service.ts", "rank": 38, "score": 44980.60044175374 }, { "content": " rename(index: number, label: string) {\n\n const payload: APIRename.AsObject = {label}\n\n return this.http\n\n .patch(`${this.endpoint}/${this.keys[index].id}`, payload)\n\n .pipe(tap(() => {\n\n this.keys[index].label = label;\n\n }));\n", "file_path": "frontend/src/app/resources/keychain.service.ts", "rank": 39, "score": 44980.60044175374 }, { "content": "import { Component, OnInit } from '@angular/core';\n\n\n\nimport { MatDialog } from '@angular/material/dialog';\n\n\n\nimport { EditDialogComponent } from './edit-dialog/edit-dialog.component';\n\nimport { DeleteWarnComponent } from './delete-warn/delete-warn.component';\n\nimport { RespType, EditDialogData } from './edit-dialog/edit-dialog-data'\n\n\n\nimport { KeychainService } from '../resources/keychain.service';\n\nimport { APIKey } from '../rpc/keychain_pb';\n\n\n\n@Component({\n\n selector: 'app-keychain',\n\n templateUrl: './keychain.component.html',\n\n styleUrls: ['./keychain.component.scss']\n\n})\n\nexport class KeychainComponent implements OnInit {\n\n\n\n constructor(\n\n private dialogOpener: MatDialog,\n\n public keychain: KeychainService,\n\n ) { }\n\n\n\n ngOnInit(): void {}\n\n\n\n openEditDialog(index?: number): void {\n\n const dialog = this.dialogOpener.open(EditDialogComponent, {\n\n width: '50vw',\n\n data: {index},\n\n });\n\n dialog.afterClosed().subscribe(this.editKeyPair());\n\n }\n\n\n\n private editKeyPair() {\n\n return (result: EditDialogData) => {\n\n if (result === undefined || result === null) {\n\n return;\n\n }\n\n switch (result.type) {\n\n case RespType.POST:\n\n if (result.index >= 0) {\n\n this.keychain.rename(result.index, result.data.label).subscribe();\n\n } else {\n\n const key = new APIKey();\n\n key.setExchange(result.data.exchange);\n\n key.setLabel(result.data.label);\n\n key.setPubKey(result.data.pubKey);\n\n key.setPrvKey(result.data.prvKey);\n\n const payload = key.toObject();\n\n this.keychain.add(payload).subscribe();\n\n }\n\n break;\n\n case RespType.DELETE:\n\n const dialog = this.dialogOpener.open(DeleteWarnComponent, {\n\n width: '50vw',\n\n data: {\n\n index: result.index,\n\n data: this.keychain.keys[result.index],\n\n }\n\n });\n\n dialog.afterClosed().subscribe(this.deleteKeyPair(result.index));\n\n break;\n\n case RespType.CANCEL:\n\n break;\n\n }\n\n };\n\n }\n\n\n\n private deleteKeyPair(index: number) {\n\n return (accepted: boolean) => {\n\n if (!accepted) { return; }\n\n this.keychain.delete(index).subscribe();\n\n };\n\n }\n\n\n\n}\n", "file_path": "frontend/src/app/keychain/keychain.component.ts", "rank": 40, "score": 42499.62424907525 }, { "content": "import { ComponentFixture, TestBed } from '@angular/core/testing';\n\n\n\nimport { KeychainComponent } from './keychain.component';\n\n\n\ndescribe('KeychainComponent', () => {\n\n let component: KeychainComponent;\n\n let fixture: ComponentFixture<KeychainComponent>;\n\n\n\n beforeEach(async () => {\n\n await TestBed.configureTestingModule({\n\n declarations: [ KeychainComponent ]\n\n })\n\n .compileComponents();\n\n });\n\n\n\n beforeEach(() => {\n\n fixture = TestBed.createComponent(KeychainComponent);\n\n component = fixture.componentInstance;\n\n fixture.detectChanges();\n\n });\n\n\n\n it('should create', () => {\n\n expect(component).toBeTruthy();\n\n });\n\n});\n", "file_path": "frontend/src/app/keychain/keychain.component.spec.ts", "rank": 41, "score": 42035.912791913644 }, { "content": "\n\nimpl TryFrom<RPCAPIKey> for APIKey {\n\n type Error = ParseError;\n\n fn try_from(value: RPCAPIKey) -> Result<Self, Self::Error> {\n\n let exchange: Exchanges =\n\n FromPrimitive::from_i32(value.exchange).ok_or(ParseError::new::<\n\n String,\n\n String,\n\n >(\n\n None,\n\n Some(value.exchange.to_string()),\n\n ))?;\n\n let exchange: APIKey = match exchange {\n\n Exchanges::Binance => APIKey::Binance(APIKeyInner {\n\n id: ObjectId::parse_str(&value.id).ok(),\n\n label: value.label,\n\n pub_key: value.pub_key,\n\n prv_key: value.prv_key,\n\n }),\n\n };\n", "file_path": "backend/libs/entities/src/apikey.rs", "rank": 42, "score": 41642.91681843304 }, { "content": "use ::std::convert::TryFrom;\n\n\n\nuse ::bson::oid::ObjectId;\n\nuse ::num_traits::FromPrimitive;\n\nuse ::serde::{Deserialize, Serialize};\n\n\n\nuse ::errors::ParseError;\n\n\n\nuse ::rpc::entities::Exchanges;\n\nuse ::rpc::keychain::ApiKey as RPCAPIKey;\n\n\n\n#[derive(Debug, Clone, Default, Serialize, Deserialize)]\n\npub struct APIKeyInner {\n\n #[serde(default, rename = \"_id\", skip_serializing_if = \"Option::is_none\")]\n\n pub id: Option<ObjectId>,\n\n pub label: String,\n\n pub pub_key: String,\n\n pub prv_key: String,\n\n}\n\n\n", "file_path": "backend/libs/entities/src/apikey.rs", "rank": 43, "score": 41642.83869889992 }, { "content": " fn from(v: APIKey) -> Self {\n\n match v {\n\n APIKey::Binance(_) => Self::Binance,\n\n }\n\n }\n\n}\n\n\n\nimpl From<APIKey> for Result<RPCAPIKey, String> {\n\n fn from(value: APIKey) -> Self {\n\n let inner = value.inner().clone();\n\n let exchange: Exchanges = value.into();\n\n return Ok(RPCAPIKey {\n\n id: inner.id.map(|oid| oid.to_hex()).unwrap_or(String::from(\"\")),\n\n exchange: exchange.into(),\n\n label: inner.label,\n\n pub_key: inner.pub_key,\n\n prv_key: inner.prv_key,\n\n });\n\n }\n\n}\n", "file_path": "backend/libs/entities/src/apikey.rs", "rank": 44, "score": 41638.052603118 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(tag = \"exchange\", rename_all = \"camelCase\")]\n\npub enum APIKey {\n\n Binance(APIKeyInner),\n\n}\n\n\n\nimpl APIKey {\n\n pub fn inner(&self) -> &APIKeyInner {\n\n match self {\n\n APIKey::Binance(inner) => inner,\n\n }\n\n }\n\n pub fn inner_mut(&mut self) -> &mut APIKeyInner {\n\n match self {\n\n APIKey::Binance(inner) => inner,\n\n }\n\n }\n\n}\n\n\n\nimpl From<APIKey> for Exchanges {\n", "file_path": "backend/libs/entities/src/apikey.rs", "rank": 45, "score": 41633.205188881795 }, { "content": " return Ok(exchange);\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(tag = \"type\")]\n\npub enum APIKeyEvent {\n\n Add(APIKey),\n\n Remove(APIKey),\n\n}\n", "file_path": "backend/libs/entities/src/apikey.rs", "rank": 46, "score": 41632.76361043693 }, { "content": "mod cmdargs;\n\nmod config;\n\nmod constants;\n\n\n\npub use self::constants::{\n\n CHAN_BUF_SIZE, DEFAULT_CONFIG_PATH, DEFAULT_RECONNECT_INTERVAL,\n\n NUM_OBJECTS_TO_FETCH,\n\n};\n\n\n\npub use self::cmdargs::CmdArgs;\n\npub use self::config::Config;\n\npub use ::redis;\n", "file_path": "backend/libs/config/src/lib.rs", "rank": 47, "score": 41603.61051797711 }, { "content": "pub const CHAN_BUF_SIZE: usize = 1024;\n\npub const DEFAULT_RECONNECT_INTERVAL: i64 = 30;\n\npub const NUM_OBJECTS_TO_FETCH: usize = 1000;\n\npub const DEFAULT_CONFIG_PATH: &str = \"/etc/midas/config.yml\";\n", "file_path": "backend/libs/config/src/constants.rs", "rank": 48, "score": 41594.421360299704 }, { "content": " if cookie.is_none() || header.is_none() {\n\n return Err(::warp::reject::custom(CSRFCheckFailed::new(\n\n \"Either cookie or header is none.\".to_string(),\n\n format!(\"{:?}\", cookie),\n\n format!(\"{:?}\", header),\n\n )));\n\n }\n\n let (cookie, header) = (cookie.unwrap(), header.unwrap());\n\n if cookie == header {\n\n return Ok(());\n\n }\n\n return Err(::warp::reject::custom(CSRFCheckFailed::new(\n\n \"CSRF Token Mismatch\".to_string(),\n\n cookie,\n\n header,\n\n )));\n\n },\n\n )\n\n .and_then(|res: Result<(), Rejection>| async { return res })\n\n .untuple_one();\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 49, "score": 41571.885611297024 }, { "content": " return Self { opt };\n\n }\n\n pub fn protect(\n\n &self,\n\n ) -> impl Filter<Extract = (), Error = ::warp::Rejection>\n\n + Clone\n\n + Send\n\n + Sync\n\n + 'static {\n\n let verify_methods = self.opt.verify_methods.clone();\n\n return ::warp::method()\n\n .and(::warp::filters::cookie::optional(self.opt.cookie_name))\n\n .and(::warp::filters::header::optional(self.opt.header_name))\n\n .map(\n\n move |method: Method,\n\n cookie: Option<String>,\n\n header: Option<String>| {\n\n if !verify_methods.contains(&method) {\n\n return Ok(());\n\n }\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 50, "score": 41571.33555922052 }, { "content": "mod errors;\n\n\n\nuse ::cookie::CookieBuilder;\n\nuse ::hyper::header::SET_COOKIE;\n\nuse ::rand::distributions::Alphanumeric;\n\nuse ::rand::{thread_rng, Rng};\n\nuse ::time::Duration as TimeDuration;\n\nuse ::warp::http::Method;\n\nuse ::warp::reply;\n\nuse ::warp::{Filter, Rejection, Reply};\n\n\n\npub use self::errors::CSRFCheckFailed;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct CSRFOption {\n\n cookie_name: &'static str,\n\n header_name: &'static str,\n\n verify_methods: Vec<Method>,\n\n}\n\n\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 51, "score": 41567.292128959525 }, { "content": " move |resp: Resp, req_cookie: Option<String>| {\n\n let value: Vec<u8> =\n\n thread_rng().sample_iter(&Alphanumeric).take(50).collect();\n\n let cookie = CookieBuilder::new(\n\n cookie_name,\n\n String::from_utf8_lossy(value.as_ref()),\n\n )\n\n .max_age(TimeDuration::new(3600, 0))\n\n .http_only(false)\n\n .secure(true)\n\n .path(\"/\")\n\n .finish();\n\n match req_cookie {\n\n None => {\n\n return reply::with_header(\n\n resp,\n\n SET_COOKIE.as_str(),\n\n cookie.to_string(),\n\n )\n\n .into_response();\n\n }\n\n Some(_) => return resp.into_response(),\n\n };\n\n },\n\n );\n\n }\n\n}\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 52, "score": 41564.6765974021 }, { "content": " self.cookie_name = cookie_name;\n\n return self;\n\n }\n\n pub fn header_name(mut self, header_name: &'static str) -> Self {\n\n self.header_name = header_name;\n\n return self;\n\n }\n\n pub fn verify_methods(mut self, methods: Vec<Method>) -> Self {\n\n self.verify_methods = methods;\n\n return self;\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct CSRF {\n\n opt: CSRFOption,\n\n}\n\n\n\nimpl CSRF {\n\n pub fn new(opt: CSRFOption) -> Self {\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 53, "score": 41564.163242235794 }, { "content": " }\n\n\n\n pub fn generate_cookie<F, Resp>(\n\n &self,\n\n filter: F,\n\n ) -> impl Filter<Extract = (impl Reply,), Error = ::warp::Rejection>\n\n + Clone\n\n + Send\n\n + Sync\n\n + 'static\n\n where\n\n F: Filter<Extract = (Resp,), Error = ::warp::Rejection>\n\n + Clone\n\n + Send\n\n + Sync\n\n + 'static,\n\n Resp: Reply,\n\n {\n\n let cookie_name = self.opt.cookie_name.clone();\n\n return filter.and(::warp::cookie::optional(&cookie_name)).map(\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 54, "score": 41562.09606162459 }, { "content": "impl Default for CSRFOption {\n\n fn default() -> Self {\n\n return Self {\n\n cookie_name: \"XSRF-TOKEN\",\n\n header_name: \"X-XSRF-TOKEN\",\n\n verify_methods: vec![\n\n Method::POST,\n\n Method::PUT,\n\n Method::PATCH,\n\n Method::DELETE,\n\n ],\n\n };\n\n }\n\n}\n\n\n\nimpl CSRFOption {\n\n pub fn builder() -> Self {\n\n return Self::default();\n\n }\n\n pub fn cookie_name(mut self, cookie_name: &'static str) -> Self {\n", "file_path": "backend/libs/csrf/src/lib.rs", "rank": 55, "score": 41559.50535920217 }, { "content": "use ::err_derive::Error;\n\n\n\n#[derive(Debug, Clone, Error)]\n\n#[error(display = \"Field {} is required, but it's empty\", field)]\n\npub struct EmptyError {\n\n pub field: String,\n\n}\n", "file_path": "backend/libs/errors/src/empty.rs", "rank": 56, "score": 41501.50584336335 }, { "content": "use ::err_derive::Error;\n\n\n\n#[derive(Debug, Clone, Error)]\n\n#[error(display = \"Unknown Exchange: {}\", exchange)]\n\npub struct UnknownExchangeError {\n\n exchange: String,\n\n}\n\n\n\nimpl UnknownExchangeError {\n\n pub fn new(exchange: String) -> Self {\n\n return Self { exchange };\n\n }\n\n}\n", "file_path": "backend/libs/errors/src/unknown.rs", "rank": 57, "score": 41501.3713765959 }, { "content": "use ::err_derive::Error;\n\n\n\nuse ::serde::Serialize;\n\nuse ::slog_derive::KV;\n\n\n\n#[derive(Debug, Clone, Serialize, Default, KV, Error)]\n\n#[error(display = \"Websocket Error (status: {:?}, msg: {:?})\", status, msg)]\n\npub struct WebsocketError {\n\n pub status: Option<u16>,\n\n pub msg: Option<String>,\n\n}\n", "file_path": "backend/libs/errors/src/websocket.rs", "rank": 58, "score": 41501.16012811143 }, { "content": "use ::err_derive::Error;\n\n\n\n#[derive(Debug, Clone, Error)]\n\n#[error(display = \"Entity {} Not Found\", entity)]\n\npub struct ObjectNotFound {\n\n entity: String,\n\n}\n\n\n\nimpl ObjectNotFound {\n\n pub fn new(entity: String) -> Self {\n\n return Self { entity };\n\n }\n\n}\n", "file_path": "backend/libs/errors/src/object.rs", "rank": 59, "score": 41501.15711349241 }, { "content": "use ::std::fmt::Debug;\n\n\n\nuse ::err_derive::Error;\n\n\n\n#[derive(Debug, Default, Clone, Error)]\n\n#[error(display = \"Failed to parse: (field: {:?}, input: {:?})\", field, input)]\n\npub struct ParseError {\n\n pub field: Option<String>,\n\n pub input: Option<String>,\n\n}\n\n\n\nimpl ParseError {\n\n pub fn new<S, T>(field: Option<S>, input: Option<T>) -> Self\n\n where\n\n S: AsRef<str>,\n\n T: AsRef<str>,\n\n {\n\n return Self {\n\n field: field.map(|s| s.as_ref().to_string()),\n\n input: input.map(|s| s.as_ref().to_string()),\n\n };\n\n }\n\n}\n", "file_path": "backend/libs/errors/src/parse.rs", "rank": 60, "score": 41500.513208692464 }, { "content": "use ::err_derive::Error;\n\n\n\n#[derive(Debug, Clone, Error)]\n\n#[error(display = \"Trade Execution Failed. Reason: {}\", reason)]\n\npub struct ExecutionFailed {\n\n pub reason: String,\n\n}\n\n\n\nimpl ExecutionFailed {\n\n pub fn new<T>(reason: T) -> Self\n\n where\n\n T: AsRef<str>,\n\n {\n\n return Self {\n\n reason: String::from(reason.as_ref()),\n\n };\n\n }\n\n}\n", "file_path": "backend/libs/errors/src/execution.rs", "rank": 61, "score": 41500.11497538309 }, { "content": "use ::err_derive::Error;\n\nuse ::url::Url;\n\nuse ::warp::reject::Reject;\n\n\n\n#[derive(Debug, Clone, Error)]\n\n#[error(\n\n display = \"Status Failue (code: {}, text: {}, url: {:?})\",\n\n code,\n\n text,\n\n url\n\n)]\n\npub struct StatusFailure {\n\n pub url: Option<Url>,\n\n pub code: u16,\n\n pub text: String,\n\n}\n\n\n\nimpl StatusFailure {\n\n pub fn new(url: Option<Url>, code: u16, text: String) -> Self {\n\n return Self { url, code, text };\n\n }\n\n}\n\n\n\nimpl Reject for StatusFailure {}\n", "file_path": "backend/libs/errors/src/status.rs", "rank": 62, "score": 41499.865547096146 }, { "content": "mod attempt;\n\nmod empty;\n\nmod execution;\n\nmod initialize;\n\nmod object;\n\nmod parse;\n\nmod status;\n\nmod unknown;\n\nmod vec_elem;\n\nmod websocket;\n\n\n\npub use attempt::MaximumAttemptExceeded;\n\npub use empty::EmptyError;\n\npub use execution::ExecutionFailed;\n\npub use initialize::InitError;\n\npub use object::ObjectNotFound;\n\npub use parse::ParseError;\n\npub use status::StatusFailure;\n\npub use unknown::UnknownExchangeError;\n\npub use vec_elem::{RawVecElemErrs, VecElementErr, VecElementErrs};\n\npub use websocket::WebsocketError;\n", "file_path": "backend/libs/errors/src/lib.rs", "rank": 63, "score": 41499.044650412405 }, { "content": "use ::err_derive::Error;\n\n\n\n#[derive(Debug, Clone, Default, Error)]\n\n#[error(display = \"Maximum retrieving count exceeded.\")]\n\npub struct MaximumAttemptExceeded;\n", "file_path": "backend/libs/errors/src/attempt.rs", "rank": 64, "score": 41498.04580928122 }, { "content": "use std::fmt::Debug;\n\n\n\nuse ::err_derive::Error;\n\n\n\n#[derive(Debug, Clone, Error)]\n\n#[error(display = \"Initialization Failed: {:?}\", message)]\n\npub struct InitError<T>\n\nwhere\n\n T: AsRef<str> + Clone + Debug,\n\n{\n\n message: Option<T>,\n\n}\n\n\n\nimpl<T> InitError<T>\n\nwhere\n\n T: AsRef<str> + Clone + Debug,\n\n{\n\n pub fn new(msg: Option<T>) -> Self {\n\n return Self { message: msg };\n\n }\n\n}\n", "file_path": "backend/libs/errors/src/initialize.rs", "rank": 65, "score": 41497.217564806524 }, { "content": "async fn main() {\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let args: CmdArgs = CmdArgs::parse();\n\n let cfg = Config::from_fpath(Some(args.config)).unwrap();\n\n let logger = cfg.build_slog();\n\n let db = DBCli::with_options(DBCliOpt::parse(&cfg.db_url).await.unwrap())\n\n .unwrap()\n\n .database(\"midas\");\n\n let broker = connect_broker(&cfg.broker_url).unwrap();\n\n let host: SocketAddr = cfg.host.parse().unwrap();\n\n let svc =\n\n Service::new(&db, broker, logger.new(o!(\"scope\" => \"SymbolService\"))).await;\n\n let csrf = CSRF::new(CSRFOption::builder());\n\n let router = csrf.protect().and(svc.route().await);\n\n\n\n info!(logger, \"Opened REST server on {}\", host);\n\n let (_, svr) = ::warp::serve(router)\n\n .tls()\n\n .cert_path(&cfg.tls.cert)\n", "file_path": "backend/services/symbol/src/main.rs", "rank": 66, "score": 41247.66075415029 }, { "content": "use ::clap::Parser;\n\nuse ::futures::future::{select, Either};\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::nats::connect as new_broker;\n\nuse ::tokio::signal::unix as signal;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::notification::binance;\n\nuse ::notification::traits::UserStream as UserStreamTrait;\n\n\n\n#[::tokio::main]\n\nasync fn main() {\n\n let args: CmdArgs = CmdArgs::parse();\n\n let config = Config::from_fpath(Some(args.config)).unwrap();\n\n let logger = config.build_slog();\n\n let broker = new_broker(config.broker_url.as_str()).unwrap();\n\n let binance = binance::UserStream::new(broker, logger);\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let sig = Box::pin(sig.recv());\n\n let jobs = binance.start();\n\n match select(jobs, sig).await {\n\n Either::Left((v, _)) => v,\n\n Either::Right(_) => Ok(()),\n\n }\n\n .unwrap();\n\n}\n", "file_path": "backend/workers/notify/src/main.rs", "rank": 67, "score": 41247.58488886957 }, { "content": " let logger = cfg.build_slog();\n\n let route_logger = logger.clone();\n\n let csrf = CSRF::new(CSRFOption::builder());\n\n let route = csrf\n\n .protect()\n\n .and(warp::path::param())\n\n .map(move |exchange: String| {\n\n return (exchange, broker.clone(), route_logger.clone());\n\n })\n\n .untuple_one()\n\n .and_then(\n\n |exchange: String, broker: NatsCon, logger: Logger| async move {\n\n let exchange: Exchanges =\n\n exchange.parse().map_err(|_| ::warp::reject::not_found())?;\n\n let observer = match exchange {\n\n Exchanges::Binance => get_exchange(exchange, broker, logger).await,\n\n };\n\n return match observer {\n\n None => Err(::warp::reject::not_found()),\n\n Some(o) => Ok(o),\n", "file_path": "backend/services/observer/src/main.rs", "rank": 68, "score": 41247.11787884236 }, { "content": "mod entities;\n\nmod service;\n\n\n\nuse ::std::net::SocketAddr;\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::FutureExt;\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::mongodb::{options::ClientOptions as DBCliOpt, Client as DBCli};\n\nuse ::nats::connect as connect_broker;\n\nuse ::slog::{info, o};\n\nuse ::tokio::signal::unix as signal;\n\nuse ::warp::Filter;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::csrf::{CSRFOption, CSRF};\n\n\n\nuse self::service::Service;\n\n\n\n#[tokio::main]\n", "file_path": "backend/services/symbol/src/main.rs", "rank": 69, "score": 41243.7316145676 }, { "content": " let cfg = Config::from_fpath(Some(args.config)).unwrap();\n\n let logger = cfg.build_slog();\n\n info!(logger, \"Historical Kline Service\");\n\n let broker = ::nats::connect(&cfg.broker_url).unwrap();\n\n let redis = cfg.redis;\n\n let host: SocketAddr = cfg.host.parse().unwrap();\n\n let svc = Service::new(&broker, &redis).await.unwrap();\n\n let csrf = CSRF::new(CSRFOption::builder());\n\n let route = csrf.protect().and(svc.route()).recover(handle_rejection);\n\n\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let host = host.clone();\n\n info!(logger, \"Opened REST server on {}\", host);\n\n let (_, ws_svr) = ::warp::serve(route)\n\n .tls()\n\n .cert_path(&cfg.tls.cert)\n\n .key_path(&cfg.tls.prv_key)\n\n .bind_with_graceful_shutdown(host, async move {\n\n sig.recv().await;\n\n });\n\n let svr = ws_svr.then(|_| async {\n\n warn!(logger, \"REST Server is shutting down! Bye! Bye!\");\n\n });\n\n svr.await;\n\n}\n", "file_path": "backend/services/historical/src/main.rs", "rank": 70, "score": 41243.636935653114 }, { "content": "use ::std::net::SocketAddr;\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::FutureExt;\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::slog::info;\n\nuse ::tokio::signal::unix as signal;\n\nuse ::warp::reply;\n\nuse ::warp::Filter;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::csrf::{CSRFOption, CSRF};\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let args: CmdArgs = CmdArgs::parse();\n\n let cfg = Config::from_fpath(Some(args.config)).unwrap();\n\n let logger = cfg.build_slog();\n", "file_path": "backend/services/token/src/main.rs", "rank": 71, "score": 41243.309341175474 }, { "content": "async fn main() {\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let args: CmdArgs = CmdArgs::parse();\n\n let cfg = Config::from_fpath(Some(args.config)).unwrap();\n\n let logger = cfg.build_slog();\n\n let db =\n\n DBCli::with_options(MongoDBCliOpt::parse(&cfg.db_url).await.unwrap())\n\n .unwrap()\n\n .database(\"midas\");\n\n let http_cli = cfg.build_rest_client().unwrap();\n\n let host: SocketAddr = cfg.host.parse().unwrap();\n\n let csrf = CSRF::new(CSRFOption::builder());\n\n let route = construct(&db, http_cli);\n\n let route = csrf.protect().and(route).recover(handle_rejection);\n\n\n\n info!(logger, \"Opened REST server on {}\", host);\n\n let (_, svr) = ::warp::serve(route)\n\n .tls()\n\n .cert_path(&cfg.tls.cert)\n", "file_path": "backend/services/bot/src/main.rs", "rank": 72, "score": 41242.17130848072 }, { "content": "mod routing;\n\n\n\nuse ::std::net::SocketAddr;\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::FutureExt;\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::mongodb::options::ClientOptions as MongoDBCliOpt;\n\nuse ::mongodb::Client as DBCli;\n\nuse ::slog::info;\n\nuse ::tokio::signal::unix as signal;\n\nuse ::warp::Filter;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::csrf::{CSRFOption, CSRF};\n\nuse ::rpc::rejection_handler::handle_rejection;\n\n\n\nuse self::routing::construct;\n\n\n\n#[tokio::main]\n", "file_path": "backend/services/bot/src/main.rs", "rank": 73, "score": 41241.114717888886 }, { "content": " binance::TradeObserver::new(\n\n Some(db),\n\n broker,\n\n logger.new(o!(\"scope\" => \"Trade Observer\")),\n\n )\n\n .await,\n\n ),\n\n };\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let sig = Box::pin(sig.recv());\n\n match select(exchange.start(), sig).await {\n\n Either::Left((v, _)) => v,\n\n Either::Right(_) => Ok(()),\n\n }\n\n .unwrap();\n\n}\n", "file_path": "backend/workers/observer/src/main.rs", "rank": 74, "score": 41240.44462039291 }, { "content": "mod service;\n\n\n\nuse ::std::net::SocketAddr;\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::FutureExt;\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::slog::{info, warn};\n\nuse ::tokio::signal::unix as signal;\n\nuse ::warp::Filter;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::csrf::{CSRFOption, CSRF};\n\nuse ::rpc::rejection_handler::handle_rejection;\n\n\n\nuse crate::service::Service;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let args: CmdArgs = CmdArgs::parse();\n", "file_path": "backend/services/historical/src/main.rs", "rank": 75, "score": 41239.02466401222 }, { "content": "use ::std::collections::HashMap;\n\nuse ::std::net::SocketAddr;\n\nuse ::std::time::Duration;\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::{FutureExt, SinkExt, StreamExt};\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::nats::{connect as broker_con, Connection as NatsCon};\n\nuse ::rpc::entities::Status;\n\nuse ::serde_json::to_string;\n\nuse ::slog::{o, Logger};\n\nuse ::tokio::select;\n\nuse ::tokio::signal::unix as signal;\n\nuse ::tokio::time::interval;\n\nuse ::warp::ws::Message;\n\nuse ::warp::{Filter, Reply};\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::csrf::{CSRFOption, CSRF};\n\nuse ::observers::binance;\n", "file_path": "backend/services/observer/src/main.rs", "rank": 76, "score": 41238.05820749055 }, { "content": "use ::clap::Parser;\n\nuse ::futures::future::{select, Either};\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::mongodb::options::ClientOptions as MongoDBCliOpt;\n\nuse ::mongodb::Client as DBCli;\n\nuse ::nats::connect as new_broker;\n\nuse ::slog::o;\n\nuse ::tokio::signal::unix as signal;\n\n\n\nuse ::config::{Config, DEFAULT_CONFIG_PATH};\n\nuse ::observers::binance;\n\nuse ::observers::traits::TradeObserver as TradeObserverTrait;\n\nuse ::rpc::entities::Exchanges;\n\n\n\n#[derive(Debug, Parser)]\n\n#[clap(author = \"Hiroaki Yamamoto\")]\n", "file_path": "backend/workers/observer/src/main.rs", "rank": 77, "score": 41237.42312778361 }, { "content": " };\n\n },\n\n )\n\n .and(::warp::ws())\n\n .map(handle_websocket);\n\n let mut sig =\n\n signal::signal(signal::SignalKind::from_raw(SIGTERM | SIGINT)).unwrap();\n\n let host: SocketAddr = cfg.host.parse().unwrap();\n\n let (_, ws_svr) = ::warp::serve(route)\n\n .tls()\n\n .cert_path(&cfg.tls.cert)\n\n .key_path(&cfg.tls.prv_key)\n\n .bind_with_graceful_shutdown(host, async move {\n\n sig.recv().await;\n\n });\n\n ::slog::info!(\n\n &logger,\n\n \"Starting Trade Observer Websocket Server\";\n\n o!(\"addr\" => host.to_string()),\n\n );\n\n let ws_svr = ws_svr.then(|_| async {\n\n ::slog::warn!(\n\n &logger,\n\n \"Trade Observer Websocket Server is shutting down! Bye! Bye!\"\n\n );\n\n });\n\n ws_svr.await;\n\n}\n", "file_path": "backend/services/observer/src/main.rs", "rank": 78, "score": 41237.39705801241 }, { "content": "use ::observers::traits::TradeObserver as TradeObserverTrait;\n\nuse ::rpc::bookticker::BookTicker;\n\nuse ::rpc::entities::Exchanges;\n\n\n\nasync fn get_exchange(\n\n exchange: Exchanges,\n\n broker: NatsCon,\n\n logger: Logger,\n\n) -> Option<impl TradeObserverTrait> {\n\n return match exchange {\n\n Exchanges::Binance => {\n\n Some(binance::TradeObserver::new(None, broker, logger).await)\n\n }\n\n };\n\n}\n\n\n", "file_path": "backend/services/observer/src/main.rs", "rank": 79, "score": 41235.045714885804 }, { "content": " let host: SocketAddr = cfg.host.parse().unwrap();\n\n let csrf = CSRF::new(CSRFOption::builder());\n\n let route = ::warp::get()\n\n .or(::warp::head())\n\n .or(::warp::options())\n\n .and(::warp::path(\"csrf\"))\n\n .map(|_| reply::reply());\n\n let route = csrf.generate_cookie(route);\n\n\n\n info!(logger, \"Opened REST server on {}\", host);\n\n let (_, svr) = ::warp::serve(route)\n\n .tls()\n\n .cert_path(&cfg.tls.cert)\n\n .key_path(&cfg.tls.prv_key)\n\n .bind_with_graceful_shutdown(host, async move {\n\n sig.recv().await;\n\n });\n\n let svr = svr.then(|_| async {\n\n ::slog::warn!(logger, \"REST Server is shutting down! Bye! Bye!\");\n\n });\n\n svr.await;\n\n}\n", "file_path": "backend/services/token/src/main.rs", "rank": 80, "score": 41233.79551927208 }, { "content": " .key_path(&cfg.tls.prv_key)\n\n .bind_with_graceful_shutdown(host, async move {\n\n sig.recv().await;\n\n });\n\n let svr = svr.then(|_| async {\n\n ::slog::warn!(logger, \"REST Server is shutting down! Bye! Bye!\");\n\n });\n\n svr.await;\n\n}\n", "file_path": "backend/services/bot/src/main.rs", "rank": 81, "score": 41233.347943578825 }, { "content": " .key_path(&cfg.tls.prv_key)\n\n .bind_with_graceful_shutdown(host, async move {\n\n sig.recv().await;\n\n });\n\n let svr = svr.then(|_| async {\n\n ::slog::warn!(logger, \"REST Server is shutting down! Bye! Bye!\");\n\n });\n\n svr.await;\n\n return;\n\n}\n", "file_path": "backend/services/symbol/src/main.rs", "rank": 82, "score": 41233.347943578825 }, { "content": " let msg = msg.unwrap_or(::warp::filters::ws::Message::close());\n\n if msg.is_close() {\n\n break;\n\n }\n\n continue;\n\n },\n\n else => {\n\n break;\n\n }\n\n }\n\n }\n\n let _ = socket.close().await;\n\n });\n\n}\n\n\n\n#[::tokio::main]\n\nasync fn main() {\n\n let cmd: CmdArgs = CmdArgs::parse();\n\n let cfg = Config::from_fpath(Some(cmd.config)).unwrap();\n\n let broker = broker_con(cfg.broker_url.as_str()).unwrap();\n", "file_path": "backend/services/observer/src/main.rs", "rank": 83, "score": 41232.57236760353 }, { "content": " Some(best_price) = sub.next() => {\n\n let best_price: BookTicker = best_price.into();\n\n book_tickers.insert(best_price.symbol.to_owned(), best_price);\n\n needs_flush = true;\n\n },\n\n _ = publish_interval.tick() => {\n\n if needs_flush {\n\n let msg: String = to_string(&book_tickers).unwrap_or_else(|e| {\n\n return to_string(&Status::new_int(0, format!(\"{}\", e).as_str()))\n\n .unwrap_or_else(\n\n |e| format!(\"Failed to encode the bookticker data: {}\", e)\n\n );\n\n });\n\n book_tickers.clear();\n\n let _ = socket.send(Message::text(msg)).await;\n\n let _ = socket.flush().await;\n\n needs_flush = false;\n\n }\n\n }\n\n Some(msg) = socket.next() => {\n", "file_path": "backend/services/observer/src/main.rs", "rank": 84, "score": 41221.79606211763 }, { "content": "\n\n#[derive(Debug, Clone)]\n\npub struct KeyChain {\n\n pubsub: APIKeyPubSub,\n\n db: Database,\n\n col: Collection<APIKey>,\n\n}\n\n\n\nimpl KeyChain {\n\n pub async fn new(broker: NatsCon, db: Database) -> Self {\n\n let col = db.collection(\"apiKeyChains\");\n\n let ret = Self {\n\n pubsub: APIKeyPubSub::new(broker),\n\n db,\n\n col,\n\n };\n\n ret.update_indices(&[\"exchange\"]).await;\n\n return ret;\n\n }\n\n\n", "file_path": "backend/libs/keychain/src/lib.rs", "rank": 85, "score": 41061.75359960281 }, { "content": "\n\n pub async fn get(\n\n &self,\n\n exchange: Exchanges,\n\n id: ObjectId,\n\n ) -> Result<Option<APIKey>> {\n\n let key = self\n\n .col\n\n .find_one(\n\n doc! {\n\n \"_id\": id,\n\n \"exchange\": exchange.as_string()\n\n },\n\n None,\n\n )\n\n .await?;\n\n return Ok(key);\n\n }\n\n\n\n pub async fn delete(&self, id: ObjectId) -> GenericResult<()> {\n", "file_path": "backend/libs/keychain/src/lib.rs", "rank": 86, "score": 41061.06615037583 }, { "content": " \"$set\": doc! {\"label\": label},\n\n }]),\n\n None,\n\n )\n\n .await?;\n\n return Ok(());\n\n }\n\n\n\n pub async fn list(\n\n &self,\n\n filter: Document,\n\n ) -> ThreadSafeResult<BoxStream<'_, APIKey>> {\n\n let stream = self\n\n .col\n\n .find(filter, None)\n\n .await?\n\n .filter_map(|res| async { res.ok() })\n\n .boxed();\n\n return Ok(stream);\n\n }\n", "file_path": "backend/libs/keychain/src/lib.rs", "rank": 87, "score": 41059.074146310115 }, { "content": " if let Some(doc) =\n\n self.col.find_one_and_delete(doc! {\"_id\": id}, None).await?\n\n {\n\n let api_key: APIKey = doc;\n\n let event = APIKeyEvent::Remove(api_key);\n\n let _ = self.pubsub.publish(&event)?;\n\n }\n\n return Ok(());\n\n }\n\n}\n\n\n\nimpl DBWriterTrait for KeyChain {\n\n fn get_database(&self) -> &Database {\n\n return &self.db;\n\n }\n\n\n\n fn get_col_name(&self) -> &str {\n\n return self.col.name();\n\n }\n\n}\n", "file_path": "backend/libs/keychain/src/lib.rs", "rank": 88, "score": 41058.202206562506 }, { "content": "pub mod pubsub;\n\n\n\nuse ::futures::stream::BoxStream;\n\nuse ::futures::StreamExt;\n\nuse ::mongodb::bson::oid::ObjectId;\n\nuse ::mongodb::bson::{doc, Document};\n\nuse ::mongodb::error::Result;\n\nuse ::mongodb::options::UpdateModifications;\n\nuse ::mongodb::{Collection, Database};\n\nuse ::nats::Connection as NatsCon;\n\nuse ::subscribe::PubSub;\n\n\n\nuse ::rpc::entities::Exchanges;\n\nuse ::types::{GenericResult, ThreadSafeResult};\n\n\n\npub use ::entities::APIKey;\n\nuse ::entities::APIKeyEvent;\n\nuse ::writers::DatabaseWriter as DBWriterTrait;\n\n\n\nuse self::pubsub::APIKeyPubSub;\n", "file_path": "backend/libs/keychain/src/lib.rs", "rank": 89, "score": 41056.755891678404 }, { "content": "use ::entities::APIKeyEvent;\n\nuse ::subscribe::pubsub;\n\n\n\npubsub!(pub, APIKeyPubSub, APIKeyEvent, \"apikey\");\n", "file_path": "backend/libs/keychain/src/pubsub.rs", "rank": 90, "score": 41056.556469524556 }, { "content": " pub async fn push(&self, api_key: APIKey) -> GenericResult<Option<ObjectId>> {\n\n let result = self.col.insert_one(&api_key, None).await?;\n\n let id = result.inserted_id.as_object_id();\n\n let mut api_key = api_key.clone();\n\n api_key.inner_mut().id = id.clone();\n\n let event = APIKeyEvent::Add(api_key);\n\n let _ = self.pubsub.publish(&event)?;\n\n return Ok(id.clone());\n\n }\n\n\n\n pub async fn rename_label(\n\n &self,\n\n id: ObjectId,\n\n label: &str,\n\n ) -> GenericResult<()> {\n\n let _ = self\n\n .col\n\n .update_one(\n\n doc! { \"_id\": id },\n\n UpdateModifications::Pipeline(vec![doc! {\n", "file_path": "backend/libs/keychain/src/lib.rs", "rank": 91, "score": 41056.085388289386 }, { "content": "#[derive(::serde::Serialize, ::serde::Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct ApiKey {\n\n #[prost(string, tag=\"1\")]\n\n pub id: ::prost::alloc::string::String,\n\n #[prost(enumeration=\"super::entities::Exchanges\", tag=\"2\")]\n\n pub exchange: i32,\n\n #[prost(string, tag=\"3\")]\n\n pub label: ::prost::alloc::string::String,\n\n #[prost(string, tag=\"4\")]\n\n pub pub_key: ::prost::alloc::string::String,\n\n #[prost(string, tag=\"5\")]\n\n pub prv_key: ::prost::alloc::string::String,\n\n}\n\n#[derive(::serde::Serialize, ::serde::Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct ApiKeyList {\n\n #[prost(message, repeated, tag=\"1\")]\n", "file_path": "backend/libs/rpc/src/keychain.rs", "rank": 92, "score": 41052.550583601405 }, { "content": " #[serde(rename = \"keysList\")]\n\n pub keys: ::prost::alloc::vec::Vec<ApiKey>,\n\n}\n\n#[derive(::serde::Serialize, ::serde::Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\n#[derive(Clone, PartialEq, ::prost::Message)]\n\npub struct ApiRename {\n\n #[prost(string, tag=\"1\")]\n\n pub label: ::prost::alloc::string::String,\n\n}\n", "file_path": "backend/libs/rpc/src/keychain.rs", "rank": 93, "score": 41052.32225898857 }, { "content": "use ::std::error::Error as ErrTrait;\n\n\n\nuse ::err_derive::Error;\n\n\n\nuse ::serde::Serialize;\n\n\n\n#[derive(Debug, Clone, Serialize, Error)]\n\n#[error(display = \"Error (index: {}, err: {:?}\", index, err)]\n\npub struct VecElementErr<T>\n\nwhere\n\n T: ErrTrait,\n\n{\n\n pub index: usize,\n\n pub err: T,\n\n}\n\n\n\nimpl<T> VecElementErr<T>\n\nwhere\n\n T: ErrTrait,\n\n{\n", "file_path": "backend/libs/errors/src/vec_elem.rs", "rank": 94, "score": 40634.83695974566 }, { "content": " pub fn new(index: usize, err: T) -> Self {\n\n return Self { index, err };\n\n }\n\n}\n\n\n\npub type RawVecElemErrs<T> = Vec<VecElementErr<T>>;\n\n\n\n#[derive(Debug, Clone, Serialize, Error)]\n\n#[error(display = \"Multiple Errors: {:?}\", errors)]\n\npub struct VecElementErrs<T>\n\nwhere\n\n T: ErrTrait,\n\n{\n\n pub errors: Vec<VecElementErr<T>>,\n\n}\n\n\n\nimpl<T> From<RawVecElemErrs<T>> for VecElementErrs<T>\n\nwhere\n\n T: ErrTrait,\n\n{\n\n fn from(v: Vec<VecElementErr<T>>) -> Self {\n\n return Self { errors: v };\n\n }\n\n}\n", "file_path": "backend/libs/errors/src/vec_elem.rs", "rank": 95, "score": 40630.547542709974 }, { "content": "use ::history::pubsub::{FetchStatusEventPubSub, HistChartPubSub};\n\nuse ::history::traits::{\n\n HistoryFetcher as HistoryFetcherTrait, HistoryWriter as HistoryWriterTrait,\n\n Store as StoreTrait,\n\n};\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let args: CmdArgs = CmdArgs::parse();\n\n let cfg = Config::from_fpath(Some(args.config)).unwrap();\n\n let logger = cfg.build_slog();\n\n info!(logger, \"Kline fetch worker\");\n\n let broker = connect(&cfg.broker_url).unwrap();\n\n let db =\n\n DBCli::with_options(MongoDBCliOpt::parse(&cfg.db_url).await.unwrap())\n\n .unwrap()\n\n .database(\"midas\");\n\n let redis = cfg.redis(&logger).unwrap();\n\n let mut cur_prog_kvs = CurrentSyncProgressStore::new(redis);\n\n\n", "file_path": "backend/workers/historical/src/main_fetcher.rs", "rank": 96, "score": 40379.83893900736 }, { "content": " error!(logger, \"Failed to fetch klines: {}\", e);\n\n continue;\n\n },\n\n Ok(k) => k\n\n }\n\n },\n\n None => {\n\n error!(logger, \"Unknown Exchange: {}\", req.exchange.as_string());\n\n continue;\n\n }\n\n };\n\n if let Err(e) = writer.write(klines).await {\n\n error!(logger, \"Failed to write the klines: {}\", e);\n\n continue;\n\n }\n\n if let Err(e) = cur_prog_kvs.incr(\n\n req.exchange.as_string(),\n\n req.symbol.clone(), 1\n\n ) {\n\n error!(logger, \"Failed to report the progress: {}\", e);\n", "file_path": "backend/workers/historical/src/main_fetcher.rs", "rank": 97, "score": 40376.72788834791 }, { "content": "use ::std::collections::HashMap;\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::StreamExt;\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::mongodb::options::ClientOptions as MongoDBCliOpt;\n\nuse ::mongodb::Client as DBCli;\n\nuse ::nats::connect;\n\nuse ::slog::{error, info};\n\nuse ::subscribe::PubSub;\n\nuse ::tokio::select;\n\nuse ::tokio::signal::unix as signal;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::rpc::entities::Exchanges;\n\n\n\nuse ::history::binance::fetcher::HistoryFetcher;\n\nuse ::history::binance::writer::HistoryWriter;\n\nuse ::history::entities::FetchStatusChanged;\n\nuse ::history::kvs::CurrentSyncProgressStore;\n", "file_path": "backend/workers/historical/src/main_fetcher.rs", "rank": 98, "score": 40375.40199053249 }, { "content": "use ::std::time::{Duration, UNIX_EPOCH};\n\n\n\nuse ::clap::Parser;\n\nuse ::futures::StreamExt;\n\nuse ::libc::{SIGINT, SIGTERM};\n\nuse ::nats::connect as con_nats;\n\nuse ::slog::error;\n\nuse ::tokio::select;\n\nuse ::tokio::signal::unix as signal;\n\n\n\nuse ::config::{CmdArgs, Config};\n\nuse ::date_splitter::DateSplitter;\n\nuse ::history::kvs::{CurrentSyncProgressStore, NumObjectsToFetchStore};\n\nuse ::history::pubsub::{HistChartPubSub, RawHistChartPubSub};\n\nuse ::history::traits::Store as StoreTrait;\n\nuse ::rpc::entities::Exchanges;\n\nuse ::subscribe::PubSub;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n", "file_path": "backend/workers/historical/src/main_splitter.rs", "rank": 99, "score": 40375.17558458364 } ]
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 that reads from a `flate2::read::GzDecoder` into a `BytesMut` and emits the results\n\n/// as a `Chunk`.\n\nstruct Gzip {\n\n inner: Box<GzDecoder<ReadableChunks<Body>>>,\n\n buf: BytesMut,\n\n}\n\n\n\nimpl fmt::Debug for Decoder {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"Decoder\")\n\n .finish()\n\n }\n\n}\n\n\n\nimpl Decoder {\n\n /// An empty decoder.\n\n ///\n\n /// This decoder will produce a single 0 byte chunk.\n\n #[inline]\n\n pub fn empty() -> Decoder {\n\n Decoder {\n\n inner: Inner::PlainText(Body::empty())\n", "file_path": "src/async_impl/decoder.rs", "rank": 2, "score": 90912.15898475621 }, { "content": "struct Config {\n\n gzip: bool,\n\n headers: HeaderMap,\n\n #[cfg(feature = \"default-tls\")]\n\n hostname_verification: bool,\n\n #[cfg(feature = \"tls\")]\n\n certs_verification: bool,\n\n connect_timeout: Option<Duration>,\n\n max_idle_per_host: usize,\n\n #[cfg(feature = \"tls\")]\n\n identity: Option<Identity>,\n\n proxies: Vec<Proxy>,\n\n redirect_policy: RedirectPolicy,\n\n referer: bool,\n\n timeout: Option<Duration>,\n\n #[cfg(feature = \"tls\")]\n\n root_certs: Vec<Certificate>,\n\n #[cfg(feature = \"tls\")]\n\n tls: TlsBackend,\n\n http2_only: bool,\n", "file_path": "src/async_impl/client.rs", "rank": 3, "score": 90912.15898475621 }, { "content": "fn fetch() -> impl Future<Item=(), Error=()> {\n\n Client::new()\n\n .get(\"https://hyper.rs\")\n\n .send()\n\n .and_then(|mut res| {\n\n println!(\"{}\", res.status());\n\n\n\n let body = mem::replace(res.body_mut(), Decoder::empty());\n\n body.concat2()\n\n })\n\n .map_err(|err| println!(\"request error: {}\", err))\n\n .map(|body| {\n\n let mut body = Cursor::new(body);\n\n let _ = io::copy(&mut body, &mut io::stdout())\n\n .map_err(|err| {\n\n println!(\"stdout error: {}\", err);\n\n });\n\n })\n\n}\n\n\n", "file_path": "examples/async.rs", "rank": 4, "score": 90869.08442592359 }, { "content": "fn _assert_impls() {\n\n fn assert_send<T: Send>() {}\n\n fn assert_sync<T: Sync>() {}\n\n fn assert_clone<T: Clone>() {}\n\n\n\n assert_send::<Client>();\n\n assert_sync::<Client>();\n\n assert_clone::<Client>();\n\n\n\n assert_send::<Request>();\n\n assert_send::<RequestBuilder>();\n\n\n\n assert_send::<Response>();\n\n\n\n assert_send::<Error>();\n\n assert_sync::<Error>();\n\n}\n", "file_path": "src/lib.rs", "rank": 5, "score": 89569.87028959172 }, { "content": "struct PendingRequest {\n\n method: Method,\n\n url: Url,\n\n headers: HeaderMap,\n\n body: Option<Option<Bytes>>,\n\n\n\n urls: Vec<Url>,\n\n\n\n client: Arc<ClientRef>,\n\n\n\n in_flight: ResponseFuture,\n\n timeout: Option<Delay>,\n\n}\n\n\n\nimpl Pending {\n\n pub(super) fn new_err(err: ::Error) -> Pending {\n\n Pending {\n\n inner: PendingInner::Error(Some(err)),\n\n }\n\n }\n", "file_path": "src/async_impl/client.rs", "rank": 6, "score": 87967.02643971099 }, { "content": "struct ClientRef {\n\n cookie_store: Option<RwLock<cookie::CookieStore>>,\n\n gzip: bool,\n\n headers: HeaderMap,\n\n hyper: HyperClient,\n\n redirect_policy: RedirectPolicy,\n\n referer: bool,\n\n request_timeout: Option<Duration>,\n\n proxies: Arc<Vec<Proxy>>,\n\n proxies_maybe_http_auth: bool,\n\n}\n\n\n\npub(super) struct Pending {\n\n inner: PendingInner,\n\n}\n\n\n", "file_path": "src/async_impl/client.rs", "rank": 7, "score": 87967.02643971099 }, { "content": "fn fetch() -> impl Future<Item=(), Error=()> {\n\n let client = Client::new();\n\n\n\n let json = |mut res : Response | {\n\n res.json::<SlideshowContainer>()\n\n };\n\n\n\n let request1 =\n\n client\n\n .get(\"https://httpbin.org/json\")\n\n .send()\n\n .and_then(json);\n\n\n\n let request2 =\n\n client\n\n .get(\"https://httpbin.org/json\")\n\n .send()\n\n .and_then(json);\n\n\n\n request1.join(request2)\n\n .map(|(res1, res2)|{\n\n println!(\"{:?}\", res1);\n\n println!(\"{:?}\", res2);\n\n })\n\n .map_err(|err| {\n\n println!(\"stdout error: {}\", err);\n\n })\n\n}\n\n\n", "file_path": "examples/async_multiple_requests.rs", "rank": 8, "score": 86183.41969361203 }, { "content": "#[test]\n\nfn write_timeout_large_body() {\n\n let _ = env_logger::try_init();\n\n let body = String::from_utf8(vec![b'x'; 20_000]).unwrap();\n\n let len = 8192;\n\n\n\n // Make Client drop *after* the Server, so the background doesn't\n\n // close too early.\n\n let client = reqwest::Client::builder()\n\n .timeout(Duration::from_millis(500))\n\n .build()\n\n .unwrap();\n\n\n\n let server = server! {\n\n request: format!(\"\\\n\n POST /write-timeout HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n content-length: {}\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n", "file_path": "tests/timeouts.rs", "rank": 9, "score": 84888.62414702807 }, { "content": "#[cfg(feature = \"tls\")]\n\n#[test]\n\nfn test_badssl_self_signed() {\n\n let text = reqwest::Client::builder()\n\n .danger_accept_invalid_certs(true)\n\n .build().unwrap()\n\n .get(\"https://self-signed.badssl.com/\")\n\n .send().unwrap()\n\n .text().unwrap();\n\n\n\n assert!(text.contains(\"<title>self-signed.badssl.com</title>\"));\n\n}\n\n\n", "file_path": "tests/badssl.rs", "rank": 10, "score": 84888.62414702807 }, { "content": "#[derive(Debug, Clone, PartialEq)]\n\nstruct ResponseUrl(Url);\n\n\n", "file_path": "src/async_impl/response.rs", "rank": 11, "score": 82135.15859863008 }, { "content": "/// Extension trait for http::response::Builder objects\n\n///\n\n/// Allows the user to add a `Url` to the http::Response\n\npub trait ResponseBuilderExt {\n\n /// A builder method for the `http::response::Builder` type that allows the user to add a `Url`\n\n /// to the `http::Response`\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # extern crate url;\n\n /// # extern crate http;\n\n /// # extern crate reqwest;\n\n /// # use std::error::Error;\n\n /// use url::Url;\n\n /// use http::response::Builder;\n\n /// use reqwest::async::ResponseBuilderExt;\n\n /// # fn main() -> Result<(), Box<Error>> {\n\n /// let response = Builder::new()\n\n /// .status(200)\n\n /// .url(Url::parse(\"http://example.com\")?)\n\n /// .body(())?;\n\n ///\n", "file_path": "src/async_impl/response.rs", "rank": 12, "score": 80177.62810947455 }, { "content": "fn fmt_request_fields<'a, 'b>(f: &'a mut fmt::DebugStruct<'a, 'b>, req: &Request) -> &'a mut fmt::DebugStruct<'a, 'b> {\n\n f.field(\"method\", &req.method)\n\n .field(\"url\", &req.url)\n\n .field(\"headers\", &req.headers)\n\n}\n\n\n\npub(crate) fn replace_headers(dst: &mut HeaderMap, src: HeaderMap) {\n\n\n\n // IntoIter of HeaderMap yields (Option<HeaderName>, HeaderValue).\n\n // The first time a name is yielded, it will be Some(name), and if\n\n // there are more values with the same name, the next yield will be\n\n // None.\n\n //\n\n // TODO: a complex exercise would be to optimize this to only\n\n // require 1 hash/lookup of the key, but doing something fancy\n\n // with header::Entry...\n\n\n\n let mut prev_name = None;\n\n for (key, value) in src {\n\n match key {\n", "file_path": "src/async_impl/request.rs", "rank": 13, "score": 78663.65380067371 }, { "content": "/// Shortcut method to quickly make a `GET` request.\n\n///\n\n/// See also the methods on the [`reqwest::Response`](./struct.Response.html)\n\n/// type.\n\n///\n\n/// **NOTE**: This function creates a new internal `Client` on each call,\n\n/// and so should not be used if making many requests. Create a\n\n/// [`Client`](./struct.Client.html) instead.\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust\n\n/// # fn run() -> Result<(), reqwest::Error> {\n\n/// let body = reqwest::get(\"https://www.rust-lang.org\")?\n\n/// .text()?;\n\n/// # Ok(())\n\n/// # }\n\n/// # fn main() { }\n\n/// ```\n\n///\n\n/// # Errors\n\n///\n\n/// This function fails if:\n\n///\n\n/// - native TLS backend cannot be initialized\n\n/// - supplied `Url` cannot be parsed\n\n/// - there was an error while sending request\n\n/// - redirect loop was detected\n\n/// - redirect limit was exhausted\n\npub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {\n\n Client::builder()\n\n .build()?\n\n .get(url)\n\n .send()\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 14, "score": 78353.6823898942 }, { "content": "struct Inner {\n\n background: Mutex<Option<Background>>,\n\n once: Once,\n\n resolver: ErasedResolver,\n\n}\n\n\n\nimpl TrustDnsResolver {\n\n pub(crate) fn new() -> io::Result<Self> {\n\n let (conf, opts) = system_conf::read_system_conf()?;\n\n let (resolver, bg) = AsyncResolver::new(conf, opts);\n\n\n\n let resolver: ErasedResolver = Box::new(move |name| {\n\n resolver.lookup_ip(name.as_str())\n\n });\n\n let background = Mutex::new(Some(Box::new(bg) as Background));\n\n let once = Once::new();\n\n\n\n Ok(TrustDnsResolver {\n\n inner: Arc::new(Inner {\n\n background,\n", "file_path": "src/dns.rs", "rank": 15, "score": 63020.962637750265 }, { "content": "#[derive(Clone)]\n\nstruct Custom {\n\n // This auth only applies if the returned ProxyScheme doesn't have an auth...\n\n auth: Option<HeaderValue>,\n\n func: Arc<dyn Fn(&Url) -> Option<::Result<ProxyScheme>> + Send + Sync + 'static>,\n\n}\n\n\n\nimpl Custom {\n\n fn call<D: Dst>(&self, uri: &D) -> Option<ProxyScheme> {\n\n let url = format!(\n\n \"{}://{}{}{}\",\n\n uri.scheme(),\n\n uri.host(),\n\n uri.port().map(|_| \":\").unwrap_or(\"\"),\n\n uri.port().map(|p| p.to_string()).unwrap_or(String::new())\n\n )\n\n .parse()\n\n .expect(\"should be valid Url\");\n\n\n\n (self.func)(&url)\n\n .and_then(|result| result.ok())\n", "file_path": "src/proxy.rs", "rank": 16, "score": 63020.962637750265 }, { "content": "struct Inner {\n\n kind: Kind,\n\n url: Option<Url>,\n\n}\n\n\n\n\n\n/// A `Result` alias where the `Err` case is `reqwest::Error`.\n\npub type Result<T> = ::std::result::Result<T, Error>;\n\n\n\nimpl Error {\n\n fn new(kind: Kind, url: Option<Url>) -> Error {\n\n Error {\n\n inner: Box::new(Inner {\n\n kind,\n\n url,\n\n }),\n\n }\n\n }\n\n\n\n /// Returns a possible URL related to this error.\n", "file_path": "src/error.rs", "rank": 17, "score": 63020.962637750265 }, { "content": "fn fmt_request_fields<'a, 'b>(f: &'a mut fmt::DebugStruct<'a, 'b>, req: &Request) -> &'a mut fmt::DebugStruct<'a, 'b> {\n\n f.field(\"method\", req.method())\n\n .field(\"url\", req.url())\n\n .field(\"headers\", req.headers())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use {body, Client, Method};\n\n use header::{ACCEPT, HOST, HeaderMap, HeaderValue, CONTENT_TYPE};\n\n use std::collections::{BTreeMap, HashMap};\n\n use serde::Serialize;\n\n use serde_json;\n\n use serde_urlencoded;\n\n\n\n #[test]\n\n fn basic_get_request() {\n\n let client = Client::new();\n\n let some_url = \"https://google.com/\";\n\n let r = client.get(some_url).build().unwrap();\n", "file_path": "src/request.rs", "rank": 18, "score": 61619.01215948333 }, { "content": "struct WaitBody {\n\n inner: wait::WaitStream<async_impl::Decoder>\n\n}\n\n\n\nimpl Stream for WaitBody {\n\n type Item = <async_impl::Decoder as Stream>::Item;\n\n type Error = <async_impl::Decoder as Stream>::Error;\n\n\n\n fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {\n\n match self.inner.next() {\n\n Some(Ok(chunk)) => Ok(Async::Ready(Some(chunk))),\n\n Some(Err(e)) => {\n\n let req_err = match e {\n\n wait::Waited::TimedOut => ::error::timedout(None),\n\n wait::Waited::Executor(e) => ::error::from(e),\n\n wait::Waited::Inner(e) => e,\n\n };\n\n\n\n Err(req_err)\n\n },\n", "file_path": "src/response.rs", "rank": 19, "score": 61188.542386976114 }, { "content": "struct ThreadNotify {\n\n thread: thread::Thread,\n\n}\n\n\n\nimpl Notify for ThreadNotify {\n\n fn notify(&self, _id: usize) {\n\n self.thread.unpark();\n\n }\n\n}\n\n\n", "file_path": "src/wait.rs", "rank": 20, "score": 61188.542386976114 }, { "content": "#[derive(Clone)]\n\nstruct ClientHandle {\n\n timeout: Timeout,\n\n inner: Arc<InnerClientHandle>\n\n}\n\n\n", "file_path": "src/client.rs", "rank": 21, "score": 61188.542386976114 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct Post {\n\n id: Option<i32>,\n\n title: String,\n\n body: String,\n\n #[serde(rename = \"userId\")]\n\n user_id: i32,\n\n}\n\n\n", "file_path": "examples/json_typed.rs", "rank": 22, "score": 61188.542386976114 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct Slideshow {\n\n title: String,\n\n author: String,\n\n}\n\n\n", "file_path": "examples/async_multiple_requests.rs", "rank": 23, "score": 59532.550965935574 }, { "content": "struct InnerClientHandle {\n\n tx: Option<ThreadSender>,\n\n thread: Option<thread::JoinHandle<()>>\n\n}\n\n\n\nimpl Drop for InnerClientHandle {\n\n fn drop(&mut self) {\n\n self.tx.take();\n\n self.thread.take().map(|h| h.join());\n\n }\n\n}\n\n\n\nimpl ClientHandle {\n\n fn new(builder: ClientBuilder) -> ::Result<ClientHandle> {\n\n let timeout = builder.timeout;\n\n let builder = builder.inner;\n\n let (tx, rx) = mpsc::unbounded();\n\n let (spawn_tx, spawn_rx) = oneshot::channel::<::Result<()>>();\n\n let handle = try_!(thread::Builder::new().name(\"reqwest-internal-sync-runtime\".into()).spawn(move || {\n\n use tokio::runtime::current_thread::Runtime;\n", "file_path": "src/client.rs", "rank": 24, "score": 59532.550965935574 }, { "content": "fn make_referer(next: &Url, previous: &Url) -> Option<HeaderValue> {\n\n if next.scheme() == \"http\" && previous.scheme() == \"https\" {\n\n return None;\n\n }\n\n\n\n let mut referer = previous.clone();\n\n let _ = referer.set_username(\"\");\n\n let _ = referer.set_password(None);\n\n referer.set_fragment(None);\n\n referer.as_str().parse().ok()\n\n}\n\n\n", "file_path": "src/async_impl/client.rs", "rank": 25, "score": 58573.36178444692 }, { "content": " pub trait Sealed {}\n\n }\n\n\n\n impl<S: Read + Write> Read for TlsStream<S> {\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.inner.read(buf)\n\n }\n\n }\n\n\n\n impl<S: Read + Write> Write for TlsStream<S> {\n\n fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n\n self.inner.write(buf)\n\n }\n\n\n\n fn flush(&mut self) -> io::Result<()> {\n\n self.inner.flush()\n\n }\n\n }\n\n\n\n\n", "file_path": "src/connect.rs", "rank": 26, "score": 58563.56674912968 }, { "content": "pub trait Redirect {\n\n fn redirect(&self, next: &Url, previous: &[Url]) -> ::Result<bool>;\n\n}\n\n\n\nimpl<F> Redirect for F\n\nwhere F: Fn(&Url, &[Url]) -> ::Result<bool> {\n\n fn redirect(&self, next: &Url, previous: &[Url]) -> ::Result<bool> {\n\n self(next, previous)\n\n }\n\n}\n\n*/\n\n\n", "file_path": "src/redirect.rs", "rank": 27, "score": 58563.56674912968 }, { "content": "fn main() {\n\n reqwest::Client::new()\n\n .post(\"http://www.baidu.com\")\n\n .form(&[(\"one\", \"1\")])\n\n .send()\n\n .unwrap();\n\n}\n", "file_path": "examples/form.rs", "rank": 28, "score": 58407.82102417371 }, { "content": "fn main() {\n\n tokio::run(fetch());\n\n}\n", "file_path": "examples/async.rs", "rank": 29, "score": 58407.82102417371 }, { "content": "#[test]\n\nfn file() {\n\n let _ = env_logger::try_init();\n\n\n\n let form = reqwest::multipart::Form::new()\n\n .file(\"foo\", \"Cargo.lock\").unwrap();\n\n\n\n let fcontents = ::std::fs::read_to_string(\"Cargo.lock\").unwrap();\n\n\n\n let expected_body = format!(\"\\\n\n --{0}\\r\\n\\\n\n Content-Disposition: form-data; name=\\\"foo\\\"; filename=\\\"Cargo.lock\\\"\\r\\n\\\n\n Content-Type: application/octet-stream\\r\\n\\r\\n\\\n\n {1}\\r\\n\\\n\n --{0}--\\r\\n\\\n\n \", form.boundary(), fcontents);\n\n\n\n let server = server! {\n\n request: format!(\"\\\n\n POST /multipart/2 HTTP/1.1\\r\\n\\\n\n content-type: multipart/form-data; boundary={}\\r\\n\\\n", "file_path": "tests/multipart.rs", "rank": 30, "score": 58407.82102417371 }, { "content": "#[test]\n\nfn multipart() {\n\n let _ = env_logger::try_init();\n\n\n\n let stream = futures::stream::once::<_, hyper::Error>(Ok(hyper::Chunk::from(\"part1 part2\".to_owned())));\n\n let part = Part::stream(stream);\n\n\n\n let form = Form::new()\n\n .text(\"foo\", \"bar\")\n\n .part(\"part_stream\", part);\n\n\n\n let expected_body = format!(\"\\\n\n 24\\r\\n\\\n\n --{0}\\r\\n\\r\\n\\\n\n 2E\\r\\n\\\n\n Content-Disposition: form-data; name=\\\"foo\\\"\\r\\n\\r\\n\\r\\n\\\n\n 3\\r\\n\\\n\n bar\\r\\n\\\n\n 2\\r\\n\\\n\n \\r\\n\\r\\n\\\n\n 24\\r\\n\\\n", "file_path": "tests/async.rs", "rank": 31, "score": 58407.82102417371 }, { "content": "#[cfg(feature = \"tls\")]\n\nstruct Tunnel<T> {\n\n buf: io::Cursor<Vec<u8>>,\n\n conn: Option<T>,\n\n state: TunnelState,\n\n}\n\n\n", "file_path": "src/connect.rs", "rank": 32, "score": 58043.148392596944 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct SlideshowContainer {\n\n slideshow: Slideshow,\n\n}\n\n\n", "file_path": "examples/async_multiple_requests.rs", "rank": 33, "score": 58028.67833858846 }, { "content": "/// Trait used for converting into a proxy scheme. This trait supports\n\n/// parsing from a URL-like type, whilst also supporting proxy schemes\n\n/// built directly using the factory methods.\n\npub trait IntoProxyScheme {\n\n fn into_proxy_scheme(self) -> ::Result<ProxyScheme>;\n\n}\n\n\n\nimpl<T: IntoUrl> IntoProxyScheme for T {\n\n fn into_proxy_scheme(self) -> ::Result<ProxyScheme> {\n\n ProxyScheme::parse(self.into_url()?)\n\n }\n\n}\n\n\n\nimpl IntoProxyScheme for ProxyScheme {\n\n fn into_proxy_scheme(self) -> ::Result<ProxyScheme> {\n\n Ok(self)\n\n }\n\n}\n\n\n\nimpl Proxy {\n\n /// Proxy all HTTP traffic to the passed URL.\n\n ///\n\n /// # Example\n", "file_path": "src/proxy.rs", "rank": 34, "score": 56907.02059514444 }, { "content": "pub trait PolyfillTryInto {\n\n // Besides parsing as a valid `Url`, the `Url` must be a valid\n\n // `http::Uri`, in that it makes sense to use in a network request.\n\n fn into_url(self) -> ::Result<Url>;\n\n}\n\n\n\nimpl PolyfillTryInto for Url {\n\n fn into_url(self) -> ::Result<Url> {\n\n if self.has_host() {\n\n Ok(self)\n\n } else {\n\n Err(::error::url_bad_scheme(self))\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> PolyfillTryInto for &'a str {\n\n fn into_url(self) -> ::Result<Url> {\n\n try_!(Url::parse(self))\n\n .into_url()\n", "file_path": "src/into_url.rs", "rank": 35, "score": 56902.57084435107 }, { "content": "#[test]\n\nfn test_post() {\n\n let server = server! {\n\n request: b\"\\\n\n POST /2 HTTP/1.1\\r\\n\\\n\n content-length: 5\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: post\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n", "file_path": "tests/client.rs", "rank": 36, "score": 56603.21692145322 }, { "content": "#[test]\n\nfn http_proxy() {\n\n let server = server! {\n\n request: b\"\\\n\n GET http://hyper.rs/prox HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: hyper.rs\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: proxied\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let proxy = format!(\"http://{}\", server.addr());\n\n\n", "file_path": "tests/proxy.rs", "rank": 37, "score": 56603.21692145322 }, { "content": "#[test]\n\nfn gzip_response() {\n\n gzip_case(10_000, 4096);\n\n}\n\n\n", "file_path": "tests/async.rs", "rank": 38, "score": 56603.21692145322 }, { "content": "#[test]\n\nfn test_get() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /1 HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/1\", server.addr());\n\n let mut res = reqwest::get(&url).unwrap();\n", "file_path": "tests/client.rs", "rank": 39, "score": 56603.21692145322 }, { "content": "#[test]\n\nfn response_timeout() {\n\n let _ = env_logger::try_init();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET /slow HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Content-Length: 5\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \",\n\n write_timeout: Duration::from_secs(2)\n\n };\n", "file_path": "tests/async.rs", "rank": 40, "score": 56603.21692145322 }, { "content": "#[test]\n\nfn text_part() {\n\n let _ = env_logger::try_init();\n\n\n\n let form = reqwest::multipart::Form::new()\n\n .text(\"foo\", \"bar\");\n\n\n\n let expected_body = format!(\"\\\n\n --{0}\\r\\n\\\n\n Content-Disposition: form-data; name=\\\"foo\\\"\\r\\n\\r\\n\\\n\n bar\\r\\n\\\n\n --{0}--\\r\\n\\\n\n \", form.boundary());\n\n\n\n let server = server! {\n\n request: format!(\"\\\n\n POST /multipart/1 HTTP/1.1\\r\\n\\\n\n content-type: multipart/form-data; boundary={}\\r\\n\\\n\n content-length: 125\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n", "file_path": "tests/multipart.rs", "rank": 41, "score": 56603.21692145322 }, { "content": "#[test]\n\nfn request_timeout() {\n\n let _ = env_logger::try_init();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET /slow HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Content-Length: 5\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \",\n\n read_timeout: Duration::from_secs(2)\n\n };\n", "file_path": "tests/async.rs", "rank": 42, "score": 56603.21692145322 }, { "content": "#[cfg(feature = \"tls\")]\n\n#[test]\n\nfn test_badssl_modern() {\n\n let text = reqwest::get(\"https://mozilla-modern.badssl.com/\").unwrap()\n\n .text().unwrap();\n\n\n\n assert!(text.contains(\"<title>mozilla-modern.badssl.com</title>\"));\n\n}\n\n\n", "file_path": "tests/badssl.rs", "rank": 44, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn cookie_store_simple() {\n\n let mut rt = tokio::runtime::current_thread::Runtime::new().expect(\"new rt\");\n\n let client = reqwest::async::Client::builder().cookie_store(true).build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Set-Cookie: key=val; HttpOnly\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/cookie.rs", "rank": 45, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_post_form() {\n\n let server = server! {\n\n request: b\"\\\n\n POST /form HTTP/1.1\\r\\n\\\n\n content-type: application/x-www-form-urlencoded\\r\\n\\\n\n content-length: 24\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n hello=world&sean=monstar\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: post-form\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/client.rs", "rank": 46, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_gzip_response() {\n\n let content: String = (0..50).into_iter().map(|i| format!(\"test {}\", i)).collect();\n\n let chunk_size = content.len() / 3;\n\n let mut encoder = ::libflate::gzip::Encoder::new(Vec::new()).unwrap();\n\n match encoder.write(content.as_bytes()) {\n\n Ok(n) => assert!(n > 0, \"Failed to write to encoder.\"),\n\n _ => panic!(\"Failed to gzip encode string.\"),\n\n };\n\n\n\n let gzipped_content = encoder.finish().into_result().unwrap();\n\n\n\n let mut response = format!(\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test-accept\\r\\n\\\n\n Content-Encoding: gzip\\r\\n\\\n\n Content-Length: {}\\r\\n\\\n\n \\r\\n\", &gzipped_content.len())\n\n .into_bytes();\n\n response.extend(&gzipped_content);\n\n\n", "file_path": "tests/gzip.rs", "rank": 47, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_default_headers() {\n\n use reqwest::header;\n\n let mut headers = header::HeaderMap::with_capacity(1);\n\n headers.insert(header::COOKIE, header::HeaderValue::from_static(\"a=b;c=d\"));\n\n let client = reqwest::Client::builder()\n\n .default_headers(headers)\n\n .build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET /1 HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n cookie: a=b;c=d\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n", "file_path": "tests/client.rs", "rank": 48, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_response_text() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /text HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 5\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/text\", server.addr());\n\n let mut res = reqwest::get(&url).unwrap();\n\n assert_eq!(res.url().as_str(), &url);\n\n assert_eq!(res.status(), reqwest::StatusCode::OK);\n\n assert_eq!(res.headers().get(reqwest::header::SERVER).unwrap(), &\"test\");\n\n assert_eq!(res.headers().get(reqwest::header::CONTENT_LENGTH).unwrap(), &\"5\");\n\n\n\n let body = res.text().unwrap();\n\n assert_eq!(b\"Hello\", body.as_bytes());\n\n}\n\n\n", "file_path": "tests/client.rs", "rank": 49, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_response_timeout() {\n\n let _ = env_logger::try_init();\n\n let server = server! {\n\n request: b\"\\\n\n GET /response-timeout HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \",\n\n response_timeout: Duration::from_secs(1)\n\n };\n\n\n\n let url = format!(\"http://{}/response-timeout\", server.addr());\n\n let err = reqwest::Client::builder()\n", "file_path": "tests/timeouts.rs", "rank": 50, "score": 54972.36345799843 }, { "content": "fn main() {\n\n tokio::run(fetch());\n\n}\n", "file_path": "examples/async_multiple_requests.rs", "rank": 51, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn cookie_store_expires() {\n\n let mut rt = tokio::runtime::current_thread::Runtime::new().expect(\"new rt\");\n\n let client = reqwest::async::Client::builder().cookie_store(true).build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Set-Cookie: key=val; Expires=Wed, 21 Oct 2015 07:28:00 GMT\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/cookie.rs", "rank": 52, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn timeout_closes_connection() {\n\n let _ = env_logger::try_init();\n\n\n\n // Make Client drop *after* the Server, so the background doesn't\n\n // close too early.\n\n let client = reqwest::Client::builder()\n\n .timeout(Duration::from_millis(500))\n\n .build()\n\n .unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET /closes HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n", "file_path": "tests/timeouts.rs", "rank": 53, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn cookie_store_path() {\n\n let mut rt = tokio::runtime::current_thread::Runtime::new().expect(\"new rt\");\n\n let client = reqwest::async::Client::builder().cookie_store(true).build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Set-Cookie: key=val; Path=/subpath\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/cookie.rs", "rank": 54, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn cookie_response_accessor() {\n\n let mut rt = tokio::runtime::current_thread::Runtime::new().expect(\"new rt\");\n\n let client = reqwest::async::Client::new();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Set-Cookie: key=val\\r\\n\\\n\n Set-Cookie: expires=1; Expires=Wed, 21 Oct 2015 07:28:00 GMT\\r\\n\\\n\n Set-Cookie: path=1; Path=/the-path\\r\\n\\\n\n Set-Cookie: maxage=1; Max-Age=100\\r\\n\\\n\n Set-Cookie: domain=1; Domain=mydomain\\r\\n\\\n", "file_path": "tests/cookie.rs", "rank": 55, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_read_timeout() {\n\n let _ = env_logger::try_init();\n\n let server = server! {\n\n request: b\"\\\n\n GET /read-timeout HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Content-Length: 5\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \",\n\n write_timeout: Duration::from_secs(1)\n\n };\n\n\n", "file_path": "tests/timeouts.rs", "rank": 56, "score": 54972.36345799843 }, { "content": "#[test]\n\nfn test_response_copy_to() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /1 HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 5\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/1\", server.addr());\n", "file_path": "tests/client.rs", "rank": 57, "score": 54972.36345799843 }, { "content": "#[cold]\n\n#[inline(never)]\n\nfn event_loop_panicked() -> ! {\n\n // The only possible reason there would be a Canceled error\n\n // is if the thread running the event loop panicked. We could return\n\n // an Err here, like a BrokenPipe, but the Client is not\n\n // recoverable. Additionally, the panic in the other thread\n\n // is not normal, and should likely be propagated.\n\n panic!(\"event loop thread panicked\");\n\n}\n", "file_path": "src/client.rs", "rank": 58, "score": 54972.36345799843 }, { "content": "#[derive(Clone, Copy)]\n\nstruct Timeout(Option<Duration>);\n\n\n\nimpl Default for Timeout {\n\n fn default() -> Timeout {\n\n // default mentioned in ClientBuilder::timeout() doc comment\n\n Timeout(Some(Duration::from_secs(30)))\n\n }\n\n}\n\n\n\npub(crate) struct KeepCoreThreadAlive(Option<Arc<InnerClientHandle>>);\n\n\n\nimpl KeepCoreThreadAlive {\n\n pub(crate) fn empty() -> KeepCoreThreadAlive {\n\n KeepCoreThreadAlive(None)\n\n }\n\n}\n\n\n", "file_path": "src/client.rs", "rank": 59, "score": 53902.75957325728 }, { "content": "#[test]\n\nfn cookie_store_max_age() {\n\n let mut rt = tokio::runtime::current_thread::Runtime::new().expect(\"new rt\");\n\n let client = reqwest::async::Client::builder().cookie_store(true).build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Set-Cookie: key=val; Max-Age=0\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/cookie.rs", "rank": 60, "score": 53491.31962423097 }, { "content": "#[cfg(feature = \"default-tls\")]\n\n#[test]\n\nfn test_badssl_wrong_host() {\n\n let text = reqwest::Client::builder()\n\n .danger_accept_invalid_hostnames(true)\n\n .build().unwrap()\n\n .get(\"https://wrong.host.badssl.com/\")\n\n .send().unwrap()\n\n .text().unwrap();\n\n\n\n assert!(text.contains(\"<title>wrong.host.badssl.com</title>\"));\n\n\n\n\n\n let result = reqwest::Client::builder()\n\n .danger_accept_invalid_hostnames(true)\n\n .build().unwrap()\n\n .get(\"https://self-signed.badssl.com/\")\n\n .send();\n\n\n\n assert!(result.is_err());\n\n}\n", "file_path": "tests/badssl.rs", "rank": 61, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_gzip_empty_body() {\n\n let server = server! {\n\n request: b\"\\\n\n HEAD /gzip HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test-accept\\r\\n\\\n\n Content-Encoding: gzip\\r\\n\\\n\n Content-Length: 100\\r\\n\\\n\n \\r\\n\"\n\n };\n\n\n\n let client = reqwest::Client::new();\n\n let mut res = client\n\n .head(&format!(\"http://{}/gzip\", server.addr()))\n\n .send()\n\n .unwrap();\n\n\n\n let mut body = ::std::string::String::new();\n\n res.read_to_string(&mut body).unwrap();\n\n\n\n assert_eq!(body, \"\");\n\n}\n\n\n", "file_path": "tests/gzip.rs", "rank": 62, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_redirect_policy_limit() {\n\n let policy = RedirectPolicy::default();\n\n let next = Url::parse(\"http://x.y/z\").unwrap();\n\n let mut previous = (0..9)\n\n .map(|i| Url::parse(&format!(\"http://a.b/c/{}\", i)).unwrap())\n\n .collect::<Vec<_>>();\n\n\n\n assert_eq!(\n\n policy.check(StatusCode::FOUND, &next, &previous),\n\n Action::Follow\n\n );\n\n\n\n previous.push(Url::parse(\"http://a.b.d/e/33\").unwrap());\n\n\n\n assert_eq!(\n\n policy.check(StatusCode::FOUND, &next, &previous),\n\n Action::TooManyRedirects\n\n );\n\n}\n\n\n", "file_path": "src/redirect.rs", "rank": 63, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_error_for_status_4xx() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /1 HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 400 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/1\", server.addr());\n\n let res = reqwest::get(&url).unwrap();\n\n\n\n let err = res.error_for_status().err().unwrap();\n\n assert!(err.is_client_error());\n\n assert_eq!(err.status(), Some(reqwest::StatusCode::BAD_REQUEST));\n\n}\n\n\n\n/// Calling `Response::error_for_status`` on a response with status in 5xx\n\n/// returns a error.\n", "file_path": "tests/client.rs", "rank": 64, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_redirect_307_and_308_tries_to_get_again() {\n\n let client = reqwest::Client::new();\n\n let codes = [307, 308];\n\n for code in codes.iter() {\n\n let redirect = server! {\n\n request: format!(\"\\\n\n GET /{} HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \", code),\n\n response: format!(\"\\\n\n HTTP/1.1 {} reason\\r\\n\\\n\n Server: test-redirect\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n Location: /dst\\r\\n\\\n\n Connection: close\\r\\n\\\n\n \\r\\n\\\n", "file_path": "tests/redirect.rs", "rank": 65, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_referer_is_not_set_if_disabled() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /no-refer HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 302 Found\\r\\n\\\n\n Server: test-no-referer\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n Location: /dst\\r\\n\\\n\n Connection: close\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n ;\n\n\n", "file_path": "tests/redirect.rs", "rank": 66, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_gzip_invalid_body() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /gzip HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test-accept\\r\\n\\\n\n Content-Encoding: gzip\\r\\n\\\n\n Content-Length: 100\\r\\n\\\n\n \\r\\n\\\n\n 0\"\n\n };\n\n\n\n let mut res = reqwest::get(&format!(\"http://{}/gzip\", server.addr())).unwrap();\n\n // this tests that the request.send() didn't error, but that the error\n\n // is in reading the body\n\n\n\n let mut body = ::std::string::String::new();\n\n res.read_to_string(&mut body).unwrap_err();\n\n}\n\n\n", "file_path": "tests/gzip.rs", "rank": 67, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_override_default_headers() {\n\n use reqwest::header;\n\n let mut headers = header::HeaderMap::with_capacity(1);\n\n headers.insert(header::AUTHORIZATION, header::HeaderValue::from_static(\"iamatoken\"));\n\n let client = reqwest::Client::builder()\n\n .default_headers(headers)\n\n .build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET /3 HTTP/1.1\\r\\n\\\n\n authorization: secret\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n", "file_path": "tests/client.rs", "rank": 68, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_redirect_policy_custom() {\n\n let policy = RedirectPolicy::custom(|attempt| {\n\n if attempt.url().host_str() == Some(\"foo\") {\n\n attempt.stop()\n\n } else {\n\n attempt.follow()\n\n }\n\n });\n\n\n\n let next = Url::parse(\"http://bar/baz\").unwrap();\n\n assert_eq!(\n\n policy.check(StatusCode::FOUND, &next, &[]),\n\n Action::Follow\n\n );\n\n\n\n let next = Url::parse(\"http://foo/baz\").unwrap();\n\n assert_eq!(\n\n policy.check(StatusCode::FOUND, &next, &[]),\n\n Action::Stop\n\n );\n\n}\n\n\n", "file_path": "src/redirect.rs", "rank": 69, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn http_proxy_basic_auth() {\n\n let server = server! {\n\n request: b\"\\\n\n GET http://hyper.rs/prox HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n proxy-authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\r\\n\\\n\n host: hyper.rs\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: proxied\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let proxy = format!(\"http://{}\", server.addr());\n", "file_path": "tests/proxy.rs", "rank": 70, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn cookie_store_overwrite_existing() {\n\n let mut rt = tokio::runtime::current_thread::Runtime::new().expect(\"new rt\");\n\n let client = reqwest::async::Client::builder().cookie_store(true).build().unwrap();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET / HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Set-Cookie: key=val\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/cookie.rs", "rank": 71, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_appended_headers_not_overwritten() {\n\n let client = reqwest::Client::new();\n\n\n\n let server = server! {\n\n request: b\"\\\n\n GET /4 HTTP/1.1\\r\\n\\\n\n accept: application/json\\r\\n\\\n\n accept: application/json+hal\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n", "file_path": "tests/client.rs", "rank": 72, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_error_for_status_5xx() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /1 HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 500 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/1\", server.addr());\n\n let res = reqwest::get(&url).unwrap();\n\n\n\n let err = res.error_for_status().err().unwrap();\n\n assert!(err.is_server_error());\n\n assert_eq!(err.status(), Some(reqwest::StatusCode::INTERNAL_SERVER_ERROR));\n\n}\n\n\n", "file_path": "tests/client.rs", "rank": 73, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_remove_sensitive_headers() {\n\n use hyper::header::{ACCEPT, AUTHORIZATION, COOKIE, HeaderValue};\n\n\n\n let mut headers = HeaderMap::new();\n\n headers.insert(ACCEPT, HeaderValue::from_static(\"*/*\"));\n\n headers.insert(AUTHORIZATION, HeaderValue::from_static(\"let me in\"));\n\n headers.insert(COOKIE, HeaderValue::from_static(\"foo=bar\"));\n\n\n\n let next = Url::parse(\"http://initial-domain.com/path\").unwrap();\n\n let mut prev = vec![Url::parse(\"http://initial-domain.com/new_path\").unwrap()];\n\n let mut filtered_headers = headers.clone();\n\n\n\n remove_sensitive_headers(&mut headers, &next, &prev);\n\n assert_eq!(headers, filtered_headers);\n\n\n\n prev.push(Url::parse(\"http://new-domain.com/path\").unwrap());\n\n filtered_headers.remove(AUTHORIZATION);\n\n filtered_headers.remove(COOKIE);\n\n\n\n remove_sensitive_headers(&mut headers, &next, &prev);\n\n assert_eq!(headers, filtered_headers);\n\n}\n", "file_path": "src/redirect.rs", "rank": 74, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn gzip_single_byte_chunks() {\n\n gzip_case(10, 1);\n\n}\n\n\n", "file_path": "tests/async.rs", "rank": 75, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_redirect_302_with_set_cookies() {\n\n let code = 302;\n\n let client = reqwest::ClientBuilder::new().cookie_store(true).build().unwrap();\n\n let server = server! {\n\n request: format!(\"\\\n\n GET /{} HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \", code),\n\n response: format!(\"\\\n\n HTTP/1.1 {} reason\\r\\n\\\n\n Server: test-redirect\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n Location: /dst\\r\\n\\\n\n Connection: close\\r\\n\\\n\n Set-Cookie: key=value\\r\\n\\\n\n \\r\\n\\\n", "file_path": "tests/redirect.rs", "rank": 76, "score": 53491.31962423097 }, { "content": "#[test]\n\nfn test_redirect_307_and_308_tries_to_post_again() {\n\n let client = reqwest::Client::new();\n\n let codes = [307, 308];\n\n for code in codes.iter() {\n\n let redirect = server! {\n\n request: format!(\"\\\n\n POST /{} HTTP/1.1\\r\\n\\\n\n content-length: 5\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n Hello\\\n\n \", code),\n\n response: format!(\"\\\n\n HTTP/1.1 {} reason\\r\\n\\\n\n Server: test-redirect\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n Location: /dst\\r\\n\\\n", "file_path": "tests/redirect.rs", "rank": 77, "score": 53491.31962423097 }, { "content": "/// A trait to try to convert some type into a `Url`.\n\n///\n\n/// This trait is \"sealed\", such that only types within reqwest can\n\n/// implement it. The reason is that it will eventually be deprecated\n\n/// and removed, when `std::convert::TryFrom` is stabilized.\n\npub trait IntoUrl: PolyfillTryInto {}\n\n\n\nimpl<T: PolyfillTryInto> IntoUrl for T {}\n\n\n", "file_path": "src/into_url.rs", "rank": 78, "score": 52865.996669862696 }, { "content": "#[test]\n\nfn http_proxy_basic_auth_parsed() {\n\n let server = server! {\n\n request: b\"\\\n\n GET http://hyper.rs/prox HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n proxy-authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\\r\\n\\\n\n host: hyper.rs\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: proxied\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let proxy = format!(\"http://Aladdin:open sesame@{}\", server.addr());\n", "file_path": "tests/proxy.rs", "rank": 79, "score": 52140.34968845375 }, { "content": "#[test]\n\nfn test_redirect_307_does_not_try_if_reader_cannot_reset() {\n\n let client = reqwest::Client::new();\n\n let codes = [307, 308];\n\n for &code in codes.iter() {\n\n let redirect = server! {\n\n request: format!(\"\\\n\n POST /{} HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n transfer-encoding: chunked\\r\\n\\\n\n \\r\\n\\\n\n 5\\r\\n\\\n\n Hello\\r\\n\\\n\n 0\\r\\n\\r\\n\\\n\n \", code),\n\n response: format!(\"\\\n\n HTTP/1.1 {} reason\\r\\n\\\n\n Server: test-redirect\\r\\n\\\n", "file_path": "tests/redirect.rs", "rank": 80, "score": 52140.34968845375 }, { "content": "#[test]\n\nfn test_response_non_utf_8_text() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /text HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 4\\r\\n\\\n\n Content-Type: text/plain; charset=gbk\\r\\n\\\n\n \\r\\n\\\n\n \\xc4\\xe3\\xba\\xc3\\\n\n \"\n\n };\n\n\n", "file_path": "tests/client.rs", "rank": 81, "score": 52140.34968845375 }, { "content": "#[test]\n\nfn test_redirect_removes_sensitive_headers() {\n\n let end_server = server! {\n\n request: b\"\\\n\n GET /otherhost HTTP/1.1\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let mid_server = server! {\n\n request: b\"\\\n", "file_path": "tests/redirect.rs", "rank": 82, "score": 52140.34968845375 }, { "content": "#[test]\n\nfn test_redirect_301_and_302_and_303_changes_post_to_get() {\n\n let client = reqwest::Client::new();\n\n let codes = [301, 302, 303];\n\n\n\n for code in codes.iter() {\n\n let redirect = server! {\n\n request: format!(\"\\\n\n POST /{} HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \", code),\n\n response: format!(\"\\\n\n HTTP/1.1 {} reason\\r\\n\\\n\n Server: test-redirect\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n Location: /dst\\r\\n\\\n\n Connection: close\\r\\n\\\n", "file_path": "tests/redirect.rs", "rank": 83, "score": 52140.34968845375 }, { "content": "#[test]\n\nfn test_accept_header_is_not_changed_if_set() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /accept HTTP/1.1\\r\\n\\\n\n accept: application/json\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test-accept\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n let client = reqwest::Client::new();\n\n\n\n let res = client\n\n .get(&format!(\"http://{}/accept\", server.addr()))\n\n .header(reqwest::header::ACCEPT, reqwest::header::HeaderValue::from_static(\"application/json\"))\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(res.status(), reqwest::StatusCode::OK);\n\n}\n\n\n", "file_path": "tests/gzip.rs", "rank": 84, "score": 52140.34968845375 }, { "content": "#[test]\n\nfn test_accept_encoding_header_is_not_changed_if_set() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /accept-encoding HTTP/1.1\\r\\n\\\n\n accept-encoding: identity\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test-accept-encoding\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n let client = reqwest::Client::new();\n\n\n\n let res = client.get(&format!(\"http://{}/accept-encoding\", server.addr()))\n\n .header(reqwest::header::ACCEPT_ENCODING, reqwest::header::HeaderValue::from_static(\"identity\"))\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(res.status(), reqwest::StatusCode::OK);\n\n}\n", "file_path": "tests/gzip.rs", "rank": 85, "score": 50903.038707353 }, { "content": "#[test]\n\nfn test_redirect_policy_can_return_errors() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /loop HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 302 Found\\r\\n\\\n\n Server: test\\r\\n\\\n\n Location: /loop\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let err = reqwest::get(&format!(\"http://{}/loop\", server.addr())).unwrap_err();\n\n assert!(err.is_redirect());\n\n}\n\n\n", "file_path": "tests/redirect.rs", "rank": 86, "score": 50903.038707353 }, { "content": "#[test]\n\nfn test_invalid_location_stops_redirect_gh484() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /yikes HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 302 Found\\r\\n\\\n\n Server: test-yikes\\r\\n\\\n\n Location: http://www.yikes{KABOOM}\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/yikes\", server.addr());\n\n\n\n let res = reqwest::get(&url).unwrap();\n\n\n\n assert_eq!(res.url().as_str(), url);\n\n assert_eq!(res.status(), reqwest::StatusCode::FOUND);\n\n assert_eq!(res.headers().get(reqwest::header::SERVER).unwrap(), &\"test-yikes\");\n\n}\n\n\n", "file_path": "tests/redirect.rs", "rank": 87, "score": 50903.038707353 }, { "content": "fn add_cookie_header(headers: &mut HeaderMap, cookie_store: &cookie::CookieStore, url: &Url) {\n\n let header = cookie_store\n\n .0\n\n .get_request_cookies(url)\n\n .map(|c| format!(\"{}={}\", c.name(), c.value()))\n\n .collect::<Vec<_>>()\n\n .join(\"; \");\n\n if !header.is_empty() {\n\n headers.insert(\n\n ::header::COOKIE,\n\n HeaderValue::from_bytes(header.as_bytes()).unwrap()\n\n );\n\n }\n\n}\n", "file_path": "src/async_impl/client.rs", "rank": 88, "score": 50143.72849205363 }, { "content": "struct DebugLength<'a>(&'a Option<u64>);\n\n\n\nimpl<'a> fmt::Debug for DebugLength<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self.0 {\n\n Some(ref len) => fmt::Debug::fmt(len, f),\n\n None => f.write_str(\"Unknown\"),\n\n }\n\n }\n\n}\n\n\n\npub(crate) enum Reader {\n\n Reader(Box<dyn Read + Send>),\n\n Bytes(Cursor<Bytes>),\n\n}\n\n\n\nimpl Read for Reader {\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n match *self {\n\n Reader::Reader(ref mut rdr) => rdr.read(buf),\n", "file_path": "src/body.rs", "rank": 89, "score": 48724.372006745834 }, { "content": "#[test]\n\nfn test_redirect_policy_can_stop_redirects_without_an_error() {\n\n let server = server! {\n\n request: b\"\\\n\n GET /no-redirect HTTP/1.1\\r\\n\\\n\n user-agent: $USERAGENT\\r\\n\\\n\n accept: */*\\r\\n\\\n\n accept-encoding: gzip\\r\\n\\\n\n host: $HOST\\r\\n\\\n\n \\r\\n\\\n\n \",\n\n response: b\"\\\n\n HTTP/1.1 302 Found\\r\\n\\\n\n Server: test-dont\\r\\n\\\n\n Location: /dont\\r\\n\\\n\n Content-Length: 0\\r\\n\\\n\n \\r\\n\\\n\n \"\n\n };\n\n\n\n let url = format!(\"http://{}/no-redirect\", server.addr());\n", "file_path": "tests/redirect.rs", "rank": 90, "score": 48716.47225253276 }, { "content": "fn io_timeout() -> io::Error {\n\n io::Error::new(io::ErrorKind::TimedOut, \"timed out\")\n\n}\n\n\n\n#[allow(missing_debug_implementations)]\n\npub(crate) struct InternalFrom<T>(pub T, pub Option<Url>);\n\n\n\n#[doc(hidden)] // https://github.com/rust-lang/rust/issues/42323\n\nimpl From<InternalFrom<Error>> for Error {\n\n #[inline]\n\n fn from(other: InternalFrom<Error>) -> Error {\n\n other.0\n\n }\n\n}\n\n\n\n#[doc(hidden)] // https://github.com/rust-lang/rust/issues/42323\n\nimpl<T> From<InternalFrom<T>> for Error\n\nwhere\n\n T: Into<Kind>,\n\n{\n", "file_path": "src/error.rs", "rank": 91, "score": 48715.3891717106 }, { "content": "#[cfg(feature = \"tls\")]\n\n#[inline]\n\nfn tunnel_eof() -> io::Error {\n\n io::Error::new(\n\n io::ErrorKind::UnexpectedEof,\n\n \"unexpected eof while tunneling\"\n\n )\n\n}\n\n\n\n#[cfg(feature = \"default-tls\")]\n\nmod native_tls_async {\n\n use std::io::{self, Read, Write};\n\n\n\n use futures::{Poll, Future, Async};\n\n use native_tls::{self, HandshakeError, Error, TlsConnector};\n\n use tokio_io::{AsyncRead, AsyncWrite};\n\n\n\n /// A wrapper around an underlying raw stream which implements the TLS or SSL\n\n /// protocol.\n\n ///\n\n /// A `TlsStream<S>` represents a handshake that has been completed successfully\n\n /// and both the server and the client are ready for receiving and sending\n", "file_path": "src/connect.rs", "rank": 92, "score": 48715.3891717106 }, { "content": " /// Extension trait for the `TlsConnector` type in the `native_tls` crate.\n\n pub trait TlsConnectorExt: sealed::Sealed {\n\n /// Connects the provided stream with this connector, assuming the provided\n\n /// domain.\n\n ///\n\n /// This function will internally call `TlsConnector::connect` to connect\n\n /// the stream and returns a future representing the resolution of the\n\n /// connection operation. The returned future will resolve to either\n\n /// `TlsStream<S>` or `Error` depending if it's successful or not.\n\n ///\n\n /// This is typically used for clients who have already established, for\n\n /// example, a TCP connection to a remote server. That stream is then\n\n /// provided here to perform the client half of a connection to a\n\n /// TLS-powered server.\n\n ///\n\n /// # Compatibility notes\n\n ///\n\n /// Note that this method currently requires `S: Read + Write` but it's\n\n /// highly recommended to ensure that the object implements the `AsyncRead`\n\n /// and `AsyncWrite` traits as well, otherwise this function will not work\n\n /// properly.\n\n fn connect_async<S>(&self, domain: &str, stream: S) -> ConnectAsync<S>\n\n where S: Read + Write; // TODO: change to AsyncRead + AsyncWrite\n\n }\n\n\n\n mod sealed {\n", "file_path": "src/connect.rs", "rank": 93, "score": 48182.4902787759 }, { "content": "#[cfg(not(feature = \"trust-dns\"))]\n\nfn http_connector() -> ::Result<HttpConnector> {\n\n Ok(HttpConnector::new(4))\n\n}\n\n\n\nimpl Connect for Connector {\n\n type Transport = Conn;\n\n type Error = io::Error;\n\n type Future = Connecting;\n\n\n\n fn connect(&self, dst: Destination) -> Self::Future {\n\n #[cfg(feature = \"tls\")]\n\n let nodelay = self.nodelay;\n\n\n\n macro_rules! timeout {\n\n ($future:expr) => {\n\n if let Some(dur) = self.timeout {\n\n Box::new(Timeout::new($future, dur).map_err(|err| {\n\n if err.is_inner() {\n\n err.into_inner().expect(\"is_inner\")\n\n } else if err.is_elapsed() {\n", "file_path": "src/connect.rs", "rank": 94, "score": 47364.41923593338 }, { "content": "fn main() -> Result<(), reqwest::Error> {\n\n let echo_json: serde_json::Value = reqwest::Client::new()\n\n .post(\"https://jsonplaceholder.typicode.com/posts\")\n\n .json(\n\n &json!({\n\n \"title\": \"Reqwest.rs\",\n\n \"body\": \"https://docs.rs/reqwest\",\n\n \"userId\": 1\n\n })\n\n )\n\n .send()?\n\n .json()?;\n\n\n\n println!(\"{:#?}\", echo_json);\n\n // Object(\n\n // {\n\n // \"body\": String(\n\n // \"https://docs.rs/reqwest\"\n\n // ),\n\n // \"id\": Number(\n", "file_path": "examples/json_dynamic.rs", "rank": 95, "score": 45657.618766802465 }, { "content": "fn main() -> Result<(), reqwest::Error> {\n\n let new_post = Post {\n\n id: None,\n\n title: \"Reqwest.rs\".into(),\n\n body: \"https://docs.rs/reqwest\".into(),\n\n user_id: 1\n\n };\n\n let new_post: Post = reqwest::Client::new()\n\n .post(\"https://jsonplaceholder.typicode.com/posts\")\n\n .json(&new_post)\n\n .send()?\n\n .json()?;\n\n\n\n println!(\"{:#?}\", new_post);\n\n // Post {\n\n // id: Some(\n\n // 101\n\n // ),\n\n // title: \"Reqwest.rs\",\n\n // body: \"https://docs.rs/reqwest\",\n\n // user_id: 1\n\n // }\n\n Ok(())\n\n}\n", "file_path": "examples/json_typed.rs", "rank": 96, "score": 45657.618766802465 }, { "content": "/// Convert a time::Tm time to SystemTime.\n\nfn tm_to_systemtime(tm: ::time::Tm) -> SystemTime {\n\n let seconds = tm.to_timespec().sec;\n\n let duration = std::time::Duration::from_secs(seconds.abs() as u64);\n\n if seconds > 0 {\n\n SystemTime::UNIX_EPOCH + duration\n\n } else {\n\n SystemTime::UNIX_EPOCH - duration\n\n }\n\n}\n\n\n\n/// Error representing a parse failure of a 'Set-Cookie' header.\n\npub struct CookieParseError(cookie::ParseError);\n\n\n\nimpl<'a> fmt::Debug for CookieParseError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n self.0.fmt(f)\n\n }\n\n}\n\n\n\nimpl<'a> fmt::Display for CookieParseError {\n", "file_path": "src/cookie.rs", "rank": 97, "score": 41872.48434006379 }, { "content": "fn gzip_case(response_size: usize, chunk_size: usize) {\n\n let content: String = (0..response_size).into_iter().map(|i| format!(\"test {}\", i)).collect();\n\n let mut encoder = ::libflate::gzip::Encoder::new(Vec::new()).unwrap();\n\n match encoder.write(content.as_bytes()) {\n\n Ok(n) => assert!(n > 0, \"Failed to write to encoder.\"),\n\n _ => panic!(\"Failed to gzip encode string.\"),\n\n };\n\n\n\n let gzipped_content = encoder.finish().into_result().unwrap();\n\n\n\n let mut response = format!(\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n Server: test-accept\\r\\n\\\n\n Content-Encoding: gzip\\r\\n\\\n\n Content-Length: {}\\r\\n\\\n\n \\r\\n\", &gzipped_content.len())\n\n .into_bytes();\n\n response.extend(&gzipped_content);\n\n\n\n let server = server! {\n", "file_path": "tests/async.rs", "rank": 98, "score": 40823.334327810284 } ]
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.55038871255 }, { "content": "/// Returns all the breakpoints set for a given chunk of code.\n\npub fn breakpoints_in_code(db: &dyn crate::Db, code: Code) -> Vec<syntax::Expr> {\n\n let filename = code.body_tokens.filename(db);\n\n let locations = breakpoint_locations(db, filename);\n\n locations\n\n .iter()\n\n .flat_map(|l| crate::breakpoint::find(db, filename, *l))\n\n .filter(|bp| bp.code == code)\n\n .map(|bp| bp.expr)\n\n .collect()\n\n}\n", "file_path": "components/dada-breakpoint/src/locations.rs", "rank": 1, "score": 366406.4449649055 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn keywords(db: &dyn crate::Db) -> Map<Word, Keyword> {\n\n Keyword::all().map(|kw| (kw.word(db), kw)).collect()\n\n}\n", "file_path": "components/dada-ir/src/kw.rs", "rank": 2, "score": 317136.56731591705 }, { "content": "#[salsa::memoized(in crate::Jar)]\n\npub fn brew(db: &dyn crate::Db, validated_tree: validated::Tree) -> bir::Bir {\n\n let function = validated_tree.origin(db);\n\n let code = function.code(db);\n\n let breakpoints = dada_breakpoint::locations::breakpoints_in_code(db, code);\n\n let mut tables = bir::Tables::default();\n\n let mut origins = bir::Origins::default();\n\n let brewery = &mut Brewery::new(\n\n db,\n\n code,\n\n &breakpoints,\n\n validated_tree,\n\n &mut tables,\n\n &mut origins,\n\n );\n\n let num_parameters = validated_tree.data(db).num_parameters;\n\n\n\n // Compile the root expression and -- assuming it doesn't diverse --\n\n // return the resulting value.\n\n let root_expr = validated_tree.data(db).root_expr;\n\n let root_expr_origin = validated_tree.origins(db)[root_expr];\n", "file_path": "components/dada-brew/src/brew.rs", "rank": 3, "score": 306511.30424097285 }, { "content": "/// Locates the syntax expression that the cursor is \"on\".\n\n/// This is used to in the time-travelling debugger.\n\n///\n\n/// The idea is that executions stops at the \"cusp\" of the returned expression E:\n\n/// that is, the moment when all of E's children have been\n\n/// evaluated, but E has not yet taken effect itself.\n\n///\n\n/// Assumes: the offset is somewhere in this syntax tree.\n\n///\n\n/// Returns None if the cursor does not lie in the syntax tree at all.\n\nfn find_syntax_expr(db: &dyn crate::Db, syntax_tree: syntax::Tree, offset: Offset) -> syntax::Expr {\n\n let spans = syntax_tree.spans(db);\n\n let data = syntax_tree.data(db);\n\n let traversal = TreeTraversal {\n\n spans,\n\n tables: &data.tables,\n\n offset,\n\n };\n\n traversal.find(data.root_expr).unwrap_or(data.root_expr)\n\n}\n\n\n", "file_path": "components/dada-breakpoint/src/breakpoint.rs", "rank": 4, "score": 304461.7918757956 }, { "content": "#[salsa::memoized(in crate::Jar)]\n\n#[tracing::instrument(level = \"debug\", skip(db))]\n\npub fn validate_function(db: &dyn crate::Db, function: Function) -> validated::Tree {\n\n let code = function.code(db);\n\n let syntax_tree = code.syntax_tree(db);\n\n\n\n let mut tables = validated::Tables::default();\n\n let mut origins = validated::Origins::default();\n\n let root_definitions = root_definitions(db, code.filename(db));\n\n let scope = Scope::root(db, root_definitions);\n\n\n\n let mut validator = validator::Validator::new(\n\n db,\n\n code,\n\n syntax_tree,\n\n &mut tables,\n\n &mut origins,\n\n scope,\n\n |_| function.effect_span(db),\n\n );\n\n\n\n for parameter in &syntax_tree.data(db).parameter_decls {\n", "file_path": "components/dada-validate/src/validate.rs", "rank": 5, "score": 303609.8343896365 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn class_field_names(db: &dyn crate::Db, class: Class) -> Vec<Word> {\n\n class.fields(db).iter().map(|p| p.name(db)).collect()\n\n}\n", "file_path": "components/dada-execute/src/ext.rs", "rank": 6, "score": 299745.12905258604 }, { "content": "pub fn lex_file(db: &dyn crate::Db, filename: Filename) -> TokenTree {\n\n let source_text = dada_ir::manifest::source_text(db, filename);\n\n lex_text(db, filename, source_text, 0)\n\n}\n\n\n\npub(crate) fn lex_filespan(db: &dyn crate::Db, span: FileSpan) -> TokenTree {\n\n let source_text = dada_ir::manifest::source_text(db, span.filename);\n\n let start = usize::from(span.start);\n\n let end = usize::from(span.end);\n\n lex_text(db, span.filename, &source_text[start..end], start)\n\n}\n\n\n", "file_path": "components/dada-lex/src/lex.rs", "rank": 7, "score": 292291.7489468366 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn parse_parameters(db: &dyn crate::Db, token_tree: TokenTree) -> Vec<Parameter> {\n\n Parser::new(db, token_tree).parse_only_parameters()\n\n}\n", "file_path": "components/dada-parse/src/parameter_parser.rs", "rank": 8, "score": 288278.38695782033 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn binary_ops(_db: &dyn crate::Db) -> Vec<BinaryOp> {\n\n vec![\n\n BinaryOp {\n\n binary_op: Op::Plus,\n\n assign_op: Op::PlusEqual,\n\n },\n\n BinaryOp {\n\n binary_op: Op::Minus,\n\n assign_op: Op::MinusEqual,\n\n },\n\n BinaryOp {\n\n binary_op: Op::Times,\n\n assign_op: Op::TimesEqual,\n\n },\n\n BinaryOp {\n\n binary_op: Op::DividedBy,\n\n assign_op: Op::DividedByEqual,\n\n },\n\n ]\n\n}\n", "file_path": "components/dada-ir/src/code/syntax/op.rs", "rank": 9, "score": 284621.515480305 }, { "content": "#[salsa::memoized(in crate::Jar)]\n\npub fn check_filename(db: &dyn crate::Db, filename: Filename) {\n\n let items = filename.items(db);\n\n\n\n filename.validate_root(db);\n\n\n\n for &item in items {\n\n match item {\n\n Item::Function(function) => {\n\n function.parameters(db);\n\n function.syntax_tree(db);\n\n function.validated_tree(db);\n\n }\n\n Item::Class(class) => {\n\n class.fields(db);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "components/dada-check/src/check.rs", "rank": 10, "score": 271285.4408121045 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\nfn line_table(db: &dyn crate::Db, filename: Filename) -> LineTable {\n\n let source_text = crate::manifest::source_text(db, filename);\n\n let mut p: usize = 0;\n\n let mut table = LineTable {\n\n line_endings: vec![],\n\n end_offset: Offset::from(source_text.len()),\n\n };\n\n for line in source_text.lines() {\n\n p += line.len();\n\n table.line_endings.push(Offset::from(p));\n\n p += 1;\n\n }\n\n table\n\n}\n", "file_path": "components/dada-ir/src/lines.rs", "rank": 11, "score": 263239.09626135946 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn source_text(_db: &dyn crate::Db, _filename: Filename) -> String {\n\n panic!(\"input\")\n\n}\n", "file_path": "components/dada-ir/src/manifest.rs", "rank": 12, "score": 255163.26821929612 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn parse_file(db: &dyn crate::Db, filename: Filename) -> Vec<Item> {\n\n let token_tree = dada_lex::lex_file(db, filename);\n\n let mut parser = Parser::new(db, token_tree);\n\n parser.parse_items()\n\n}\n", "file_path": "components/dada-parse/src/file_parser.rs", "rank": 13, "score": 252096.75973026472 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn root_definitions(db: &dyn crate::Db, filename: Filename) -> name_lookup::RootDefinitions {\n\n name_lookup::RootDefinitions::new(db, filename)\n\n}\n", "file_path": "components/dada-validate/src/validate.rs", "rank": 14, "score": 248969.0654022697 }, { "content": "/// Given a (1-based) line/column tuple, returns a character index.\n\npub fn offset(db: &dyn crate::Db, filename: Filename, position: LineColumn) -> Offset {\n\n let table = line_table(db, filename);\n\n\n\n if position.line0_usize() >= table.num_lines() {\n\n return table.end_offset;\n\n }\n\n let line_start = table.line_start(position.line0_usize());\n\n (line_start + position.column0()).min(table.end_offset)\n\n}\n\n\n", "file_path": "components/dada-ir/src/lines.rs", "rank": 15, "score": 248216.99093003134 }, { "content": "/// Converts a character index `position` into a line and column tuple.\n\npub fn line_column(db: &dyn crate::Db, filename: Filename, position: Offset) -> LineColumn {\n\n let table = line_table(db, filename);\n\n match table.line_endings.binary_search(&position) {\n\n Ok(line0) | Err(line0) => {\n\n let line_start = table.line_start(line0);\n\n LineColumn::new0(line0, position - line_start)\n\n }\n\n }\n\n}\n\n\n", "file_path": "components/dada-ir/src/lines.rs", "rank": 16, "score": 245089.2966020364 }, { "content": "#[salsa::memoized(in crate::Jar ref)]\n\n#[allow(clippy::needless_lifetimes)]\n\npub fn breakpoint_locations(_db: &dyn crate::Db, _filename: Filename) -> Vec<LineColumn> {\n\n vec![] // default: none\n\n}\n\n\n", "file_path": "components/dada-breakpoint/src/locations.rs", "rank": 17, "score": 244367.26278916223 }, { "content": "/// Given a cursor position, finds the breakpoint associated with that cursor\n\n/// (if any). This is the expression that the cursor is on.\n\npub fn find(db: &dyn crate::Db, filename: Filename, position: LineColumn) -> Option<Breakpoint> {\n\n let offset = dada_ir::lines::offset(db, filename, position);\n\n\n\n let item = find_item(db, filename, offset)?;\n\n let code = item.code(db)?;\n\n let syntax_tree = code.syntax_tree(db);\n\n let cusp_expr = find_syntax_expr(db, syntax_tree, offset);\n\n Some(Breakpoint {\n\n item,\n\n code,\n\n expr: cusp_expr,\n\n })\n\n}\n\n\n", "file_path": "components/dada-breakpoint/src/breakpoint.rs", "rank": 18, "score": 241573.06421334398 }, { "content": "pub fn find_item(db: &dyn crate::Db, filename: Filename, offset: Offset) -> Option<Item> {\n\n filename\n\n .items(db)\n\n .iter()\n\n .find(|item| item.span(db).contains(offset))\n\n .copied()\n\n}\n\n\n", "file_path": "components/dada-breakpoint/src/breakpoint.rs", "rank": 19, "score": 241573.06421334398 }, { "content": "fn add_temporary(brewery: &mut Brewery, origin: ExprOrigin) -> bir::LocalVariable {\n\n let temporary = brewery.add(\n\n bir::LocalVariableData {\n\n name: None,\n\n atomic: Atomic::No,\n\n },\n\n validated::LocalVariableOrigin::Temporary(origin.into()),\n\n );\n\n brewery.push_temporary(temporary);\n\n temporary\n\n}\n\n\n", "file_path": "components/dada-brew/src/brew.rs", "rank": 20, "score": 192860.5976538147 }, { "content": "fn add_temporary_place(brewery: &mut Brewery, origin: ExprOrigin) -> bir::Place {\n\n let temporary_var = add_temporary(brewery, origin);\n\n brewery.add(bir::PlaceData::LocalVariable(temporary_var), origin)\n\n}\n", "file_path": "components/dada-brew/src/brew.rs", "rank": 21, "score": 192860.5976538147 }, { "content": "struct CodeParser<'me, 'db> {\n\n parser: &'me mut Parser<'db>,\n\n tables: &'me mut Tables,\n\n spans: &'me mut Spans,\n\n}\n\n\n\nimpl<'db> std::ops::Deref for CodeParser<'_, 'db> {\n\n type Target = Parser<'db>;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n self.parser\n\n }\n\n}\n\n\n\nimpl<'db> std::ops::DerefMut for CodeParser<'_, 'db> {\n\n fn deref_mut(&mut self) -> &mut Self::Target {\n\n self.parser\n\n }\n\n}\n\n\n", "file_path": "components/dada-parse/src/parser/code.rs", "rank": 22, "score": 172097.6678922187 }, { "content": "pub fn main(_crate_options: &crate::Options, _options: &Options) -> eyre::Result<()> {\n\n let mut server = dada_lsp::LspServer::new()?;\n\n server.main_loop()?;\n\n Ok(())\n\n}\n", "file_path": "components/dada-lang/src/ide.rs", "rank": 23, "score": 157120.72764310203 }, { "content": "#[wasm_bindgen(start)]\n\npub fn start() -> Result<(), JsValue> {\n\n console_error_panic_hook::set_once();\n\n\n\n tracing_wasm::set_as_global_default_with_config(\n\n WASMLayerConfigBuilder::new()\n\n .set_max_level(tracing::Level::INFO)\n\n .build(),\n\n );\n\n\n\n Ok(())\n\n}\n\n\n\n#[wasm_bindgen]\n\n#[derive(Default)]\n\npub struct DadaCompiler {\n\n db: dada_db::Db,\n\n\n\n /// Current diagnostics emitted by the compiler.\n\n diagnostics: Vec<dada_ir::diagnostic::Diagnostic>,\n\n\n\n /// Current output emitted by the program.\n\n output: String,\n\n\n\n /// If a breakpoint was set, contains graphviz source\n\n /// for the heap at that point (else empty).\n\n heap_capture: Vec<(String, String)>,\n\n\n\n breakpoint_ranges: Vec<DadaRange>,\n\n}\n\n\n", "file_path": "components/dada-web/src/lib.rs", "rank": 24, "score": 153511.7387078867 }, { "content": "pub trait HasOriginIn<T> {\n\n type Origin: Clone;\n\n\n\n fn origin_in(self, origins: &T) -> &Self::Origin;\n\n}\n\n\n", "file_path": "components/dada-ir/src/origin_table.rs", "rank": 25, "score": 148075.2849732427 }, { "content": "pub trait PushOriginIn<T> {\n\n type Origin: Clone;\n\n\n\n fn push_origin_in(self, origins: &mut T, origin: Self::Origin);\n\n}\n", "file_path": "components/dada-ir/src/origin_table.rs", "rank": 26, "score": 145518.6917296821 }, { "content": "struct ASpan(dada_ir::span::FileSpan);\n\n\n\nimpl ariadne::Span for ASpan {\n\n type SourceId = Filename;\n\n\n\n fn source(&self) -> &Self::SourceId {\n\n &self.0.filename\n\n }\n\n\n\n fn start(&self) -> usize {\n\n self.0.start.into()\n\n }\n\n\n\n fn end(&self) -> usize {\n\n self.0.end.into()\n\n }\n\n}\n", "file_path": "components/dada-error-format/src/format.rs", "rank": 27, "score": 132900.36970211254 }, { "content": "pub trait Db:\n\n salsa::DbWithJar<Jar> + dada_ir::Db + dada_parse::Db + dada_brew::Db + dada_error_format::Db\n\n{\n\n}\n\n\n\nimpl<T> Db for T where\n\n T: salsa::DbWithJar<Jar> + dada_ir::Db + dada_parse::Db + dada_brew::Db + dada_error_format::Db\n\n{\n\n}\n\n\n\nmod error;\n\nmod ext;\n\npub mod heap_graph;\n\npub mod kernel;\n\npub mod machine;\n\nmod moment;\n\nmod run;\n\nmod step;\n\nmod thunk;\n\n\n\npub use error::DiagnosticError;\n\npub use run::interpret;\n", "file_path": "components/dada-execute/src/lib.rs", "rank": 28, "score": 131016.41580315673 }, { "content": "pub trait Db:\n\n salsa::DbWithJar<Jar>\n\n + dada_brew::Db\n\n + dada_ir::Db\n\n + dada_lex::Db\n\n + dada_parse::Db\n\n + dada_validate::Db\n\n{\n\n}\n\n\n\nimpl<T> Db for T where\n\n T: salsa::DbWithJar<Jar>\n\n + dada_brew::Db\n\n + dada_ir::Db\n\n + dada_lex::Db\n\n + dada_parse::Db\n\n + dada_validate::Db\n\n{\n\n}\n\n\n\npub use check::check_filename;\n", "file_path": "components/dada-check/src/lib.rs", "rank": 29, "score": 131016.41580315673 }, { "content": "pub trait Db:\n\n salsa::DbWithJar<Jar> + dada_breakpoint::Db + dada_ir::Db + dada_parse::Db + dada_validate::Db\n\n{\n\n}\n\n\n\nimpl<T> Db for T where\n\n T: salsa::DbWithJar<Jar>\n\n + dada_breakpoint::Db\n\n + dada_ir::Db\n\n + dada_parse::Db\n\n + dada_validate::Db\n\n{\n\n}\n\n\n\nmod brew;\n\nmod brewery;\n\nmod cursor;\n\npub mod prelude;\n", "file_path": "components/dada-brew/src/lib.rs", "rank": 30, "score": 131016.41580315673 }, { "content": "pub trait Db: salsa::DbWithJar<Jar> + dada_lex::Db + dada_ir::Db {}\n\nimpl<T> Db for T where T: salsa::DbWithJar<Jar> + dada_lex::Db + dada_ir::Db {}\n\n\n\npub mod prelude;\n", "file_path": "components/dada-parse/src/lib.rs", "rank": 31, "score": 127971.73574410632 }, { "content": "pub trait Db: salsa::DbWithJar<Jar> + dada_ir::Db + dada_parse::Db {}\n\n\n\nimpl<T> Db for T where T: salsa::DbWithJar<Jar> + dada_ir::Db + dada_parse::Db {}\n\n\n\npub mod prelude;\n", "file_path": "components/dada-validate/src/lib.rs", "rank": 32, "score": 127971.73574410632 }, { "content": "pub trait Db: salsa::DbWithJar<Jar> + dada_ir::Db + dada_parse::Db {}\n\n\n\nimpl<T> Db for T where T: salsa::DbWithJar<Jar> + dada_ir::Db + dada_parse::Db {}\n\n\n\npub mod breakpoint;\n\npub mod locations;\n", "file_path": "components/dada-breakpoint/src/lib.rs", "rank": 33, "score": 127971.73574410632 }, { "content": "pub trait Db: salsa::DbWithJar<Jar> + dada_ir::Db {\n\n fn lex(&self) -> &dyn Db;\n\n}\n\nimpl<T> Db for T\n\nwhere\n\n T: salsa::DbWithJar<Jar> + dada_ir::Db,\n\n{\n\n fn lex(&self) -> &dyn Db {\n\n self\n\n }\n\n}\n\n\n\npub use lex::closing_delimiter;\n\npub use lex::lex_file;\n", "file_path": "components/dada-lex/src/lib.rs", "rank": 34, "score": 127467.17100908431 }, { "content": "pub trait Db: salsa::DbWithJar<Jar> + dada_ir::Db {}\n\nimpl<T> Db for T where T: salsa::DbWithJar<Jar> + dada_ir::Db {}\n\n\n\npub use format::format_diagnostics;\n\npub use format::format_diagnostics_with_options;\n\npub use format::print_diagnostic;\n\npub use format::FormatOptions;\n", "file_path": "components/dada-error-format/src/lib.rs", "rank": 35, "score": 126206.73442603428 }, { "content": "pub fn print_diagnostic(\n\n db: &dyn crate::Db,\n\n diagnostic: &dada_ir::diagnostic::Diagnostic,\n\n) -> eyre::Result<()> {\n\n Ok(ariadne_diagnostic(db, diagnostic, DEFAULT_FORMATTING)?.print(SourceCache::new(db))?)\n\n}\n\n\n", "file_path": "components/dada-error-format/src/format.rs", "rank": 36, "score": 125844.46701474392 }, { "content": "pub fn format_diagnostics(\n\n db: &dyn crate::Db,\n\n diagnostics: &[dada_ir::diagnostic::Diagnostic],\n\n) -> eyre::Result<String> {\n\n format_diagnostics_with_options(db, diagnostics, DEFAULT_FORMATTING)\n\n}\n\n\n", "file_path": "components/dada-error-format/src/format.rs", "rank": 37, "score": 125844.46701474392 }, { "content": "pub fn format_diagnostics_with_options(\n\n db: &dyn crate::Db,\n\n diagnostics: &[dada_ir::diagnostic::Diagnostic],\n\n options: FormatOptions,\n\n) -> eyre::Result<String> {\n\n let mut output = Vec::new();\n\n let mut cursor = Cursor::new(&mut output);\n\n let mut cache = SourceCache::new(db);\n\n for diagnostic in diagnostics {\n\n let ariadne = ariadne_diagnostic(db, diagnostic, options)?;\n\n ariadne.write(&mut cache, &mut cursor)?;\n\n }\n\n Ok(String::from_utf8(output)?)\n\n}\n\n\n", "file_path": "components/dada-error-format/src/format.rs", "rank": 38, "score": 124042.84511423053 }, { "content": "pub trait Db: salsa::DbWithJar<Jar> {\n\n fn as_dyn_ir_db(&self) -> &dyn crate::Db;\n\n}\n\nimpl<T: salsa::DbWithJar<Jar>> Db for T {\n\n fn as_dyn_ir_db(&self) -> &dyn crate::Db {\n\n self\n\n }\n\n}\n", "file_path": "components/dada-ir/src/lib.rs", "rank": 39, "score": 123331.14515871994 }, { "content": "#[wasm_bindgen]\n\npub fn compiler() -> DadaCompiler {\n\n Default::default()\n\n}\n\n\n\n#[wasm_bindgen]\n\nimpl DadaCompiler {\n\n fn filename(&self) -> Filename {\n\n Filename::from(&self.db, \"input.dada\")\n\n }\n\n\n\n #[wasm_bindgen]\n\n pub fn with_source_text(mut self, source: String) -> Self {\n\n // FIXME: reset the database for now\n\n tracing::debug!(\"with_source_text: {source:?}\");\n\n self.db = Default::default();\n\n self.db.update_file(self.filename(), source);\n\n self\n\n }\n\n\n\n #[wasm_bindgen]\n", "file_path": "components/dada-web/src/lib.rs", "rank": 40, "score": 121585.91322958074 }, { "content": "#[track_caller]\n\npub fn escape(ch: char) -> char {\n\n match ch {\n\n 'n' => '\\n',\n\n 't' => '\\t',\n\n 'r' => '\\r',\n\n '\\\\' => '\\\\',\n\n '\"' => '\\\"',\n\n _ => panic!(\"not a escape: {:?}\", ch),\n\n }\n\n}\n\n\n", "file_path": "components/dada-validate/src/validate/validator.rs", "rank": 41, "score": 111411.27849431407 }, { "content": "#[track_caller]\n\npub fn closing_delimiter(ch: char) -> char {\n\n match ch {\n\n '(' => ')',\n\n '[' => ']',\n\n '{' => '}',\n\n _ => panic!(\"not a delimiter: {:?}\", ch),\n\n }\n\n}\n\n\n\nmacro_rules! op {\n\n () => {\n\n '+' | '-' | '/' | '*' | '>' | '<' | '&' | '|' | '.' | ':' | ';' | '='\n\n };\n\n}\n\n\n", "file_path": "components/dada-lex/src/lex.rs", "rank": 42, "score": 111411.27849431407 }, { "content": "pub trait InIrDbExt {\n\n fn in_ir_db<'me>(&'me self, db: &'me dyn crate::Db) -> InIrDb<'me, Self>;\n\n}\n\n\n\nimpl<T: ?Sized> InIrDbExt for T {\n\n fn in_ir_db<'me>(&'me self, db: &'me dyn crate::Db) -> InIrDb<'me, Self> {\n\n InIrDb { this: self, db }\n\n }\n\n}\n", "file_path": "components/dada-ir/src/in_ir_db.rs", "rank": 43, "score": 110055.31677440045 }, { "content": "fn find_keyword(\n\n db: &dyn crate::Db,\n\n filespan: FileSpan,\n\n kw: kw::Keyword,\n\n tokens: impl IntoIterator<Item = (Span, Token)>,\n\n) -> FileSpan {\n\n for (span, token) in tokens {\n\n match token {\n\n Token::Alphabetic(w) if w == kw.word(db) => return span.in_file(filespan.filename),\n\n _ => continue,\n\n }\n\n }\n\n filespan\n\n}\n", "file_path": "components/dada-lex/src/prelude.rs", "rank": 44, "score": 107405.68274426361 }, { "content": "struct TreeTraversal<'me> {\n\n spans: &'me syntax::Spans,\n\n tables: &'me syntax::Tables,\n\n offset: Offset,\n\n}\n\n\n\nmacro_rules! search {\n\n ($self:expr, $expr:expr) => {\n\n if let Some(r) = $self.find($expr) {\n\n return Some(r);\n\n }\n\n };\n\n}\n\n\n\nimpl TreeTraversal<'_> {\n\n fn find(&self, expr: syntax::Expr) -> Option<syntax::Expr> {\n\n let span = expr.origin_in(self.spans);\n\n\n\n // Note: we purposefully don't check against `span.start`.\n\n // We assume our parent has done any `span.start` checks.\n", "file_path": "components/dada-breakpoint/src/breakpoint.rs", "rank": 45, "score": 106653.81115343087 }, { "content": "#[derive(Debug)]\n\nstruct RefOutputDoesNotMatch {\n\n ref_path: PathBuf,\n\n expected: String,\n\n actual: String,\n\n}\n\n\n\nimpl std::error::Error for RefOutputDoesNotMatch {}\n\n\n\nimpl std::fmt::Display for RefOutputDoesNotMatch {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(\n\n f,\n\n \"{}\",\n\n similar::TextDiff::from_lines(&self.expected, &self.actual)\n\n .unified_diff()\n\n .header(&self.ref_path.display().to_string(), \"actual output\")\n\n )\n\n }\n\n}\n\n\n\n/// Test files have `#!` lines embedded in them indicating the\n\n/// errors, warnings, and other diganostics we expect the compiler\n\n/// to emit. Every diagnostic emitted by the compiler must have\n\n/// a line like this or the test will fail.\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 46, "score": 105523.34696941669 }, { "content": "pub trait ToString {\n\n fn to_string(self) -> String;\n\n}\n\n\n\nimpl ToString for String {\n\n fn to_string(self) -> String {\n\n self\n\n }\n\n}\n\n\n\nimpl ToString for &str {\n\n fn to_string(self) -> String {\n\n self.to_owned()\n\n }\n\n}\n\n\n\nimpl ToString for &std::path::Path {\n\n fn to_string(self) -> String {\n\n self.display().to_string()\n\n }\n", "file_path": "components/dada-ir/src/word.rs", "rank": 47, "score": 105222.402142551 }, { "content": "struct GraphvizValueEdge {\n\n source: GraphvizPlace,\n\n target: String,\n\n permission: PermissionNode,\n\n}\n\n\n\nimpl GraphvizWriter<'_> {\n\n fn with_prefix<'me>(&'me mut self, prefix: &'static str) -> GraphvizWriter<'me> {\n\n GraphvizWriter {\n\n db: self.db,\n\n name_prefix: prefix,\n\n writer: &mut *self.writer,\n\n indent: self.indent,\n\n include_temporaries: self.include_temporaries,\n\n node_queue: Default::default(),\n\n node_set: Default::default(),\n\n permissions: Default::default(),\n\n value_edge_list: vec![],\n\n diff_against: self.diff_against,\n\n }\n", "file_path": "components/dada-execute/src/heap_graph/graphviz.rs", "rank": 48, "score": 103647.62070041618 }, { "content": "pub trait InternValue {\n\n type Table;\n\n type Key: salsa::AsId;\n\n\n\n fn add(self, table: &mut Self::Table) -> Self::Key;\n\n}\n\n\n", "file_path": "components/dada-id/src/lib.rs", "rank": 49, "score": 103213.69407448443 }, { "content": "pub trait BrewExt {\n\n fn brew(self, db: &dyn crate::Db) -> bir::Bir;\n\n}\n\n\n\nimpl BrewExt for Function {\n\n fn brew(self, db: &dyn crate::Db) -> bir::Bir {\n\n let tree = self.validated_tree(db);\n\n crate::brew::brew(db, tree)\n\n }\n\n}\n\n\n", "file_path": "components/dada-brew/src/prelude.rs", "rank": 50, "score": 103200.53196588933 }, { "content": "pub trait IntoFileSpan {\n\n fn maybe_in_file(self, default_file: Filename) -> FileSpan;\n\n}\n\n\n\nimpl IntoFileSpan for FileSpan {\n\n fn maybe_in_file(self, _default_file: Filename) -> FileSpan {\n\n self\n\n }\n\n}\n\n\n\nimpl IntoFileSpan for Span {\n\n fn maybe_in_file(self, default_file: Filename) -> FileSpan {\n\n self.in_file(default_file)\n\n }\n\n}\n", "file_path": "components/dada-ir/src/diagnostic.rs", "rank": 51, "score": 103174.15396476188 }, { "content": "pub trait U32OrUsize {\n\n fn into_u32(self) -> u32;\n\n fn from_u32(n: u32) -> Self;\n\n fn into_usize(self) -> usize;\n\n fn from_usize(n: usize) -> Self;\n\n}\n\n\n\nimpl U32OrUsize for u32 {\n\n fn into_u32(self) -> u32 {\n\n self\n\n }\n\n\n\n fn from_u32(n: u32) -> Self {\n\n n\n\n }\n\n\n\n fn into_usize(self) -> usize {\n\n usize::try_from(self).unwrap()\n\n }\n\n\n", "file_path": "components/dada-ir/src/span.rs", "rank": 52, "score": 103174.15396476188 }, { "content": "fn write_parenthesized_places(\n\n f: &mut std::fmt::Formatter<'_>,\n\n vars: &[Place],\n\n db: &InIrDb<'_, Bir>,\n\n) -> std::fmt::Result {\n\n write!(f, \"(\")?;\n\n for (v, i) in vars.iter().zip(0..) {\n\n if i > 0 {\n\n write!(f, \", \")?;\n\n }\n\n write!(f, \"{:?}\", v.debug(db))?;\n\n }\n\n write!(f, \")\")?;\n\n Ok(())\n\n}\n\n\n\nid!(pub struct Place);\n\n\n\nimpl DebugWithDb<InIrDb<'_, Bir>> for Place {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Bir>) -> std::fmt::Result {\n", "file_path": "components/dada-ir/src/code/bir.rs", "rank": 53, "score": 102834.53941095498 }, { "content": "pub trait MaybeBrewExt {\n\n fn maybe_brew(self, db: &dyn crate::Db) -> Option<bir::Bir>;\n\n}\n\n\n\nimpl MaybeBrewExt for Item {\n\n fn maybe_brew(self, db: &dyn crate::Db) -> Option<bir::Bir> {\n\n self.validated_tree(db)\n\n .map(|tree| crate::brew::brew(db, tree))\n\n }\n\n}\n", "file_path": "components/dada-brew/src/prelude.rs", "rank": 54, "score": 101302.61944778092 }, { "content": "\n\n $(\n\n impl $crate::origin_table::HasOriginIn<$table> for $key {\n\n type Origin = $origins;\n\n\n\n fn origin_in(self, table: &$table) -> &Self::Origin {\n\n &table.$field[self]\n\n }\n\n }\n\n\n\n impl $crate::origin_table::PushOriginIn<$table> for $key {\n\n type Origin = $origins;\n\n\n\n fn push_origin_in(self, table: &mut $table, origin: Self::Origin) {\n\n assert_eq!(<$key>::from(table.$field.len()), self);\n\n table.$field.push(origin);\n\n }\n\n }\n\n )*\n\n }\n\n}\n\n\n", "file_path": "components/dada-ir/src/origin_table.rs", "rank": 55, "score": 82492.24260956096 }, { "content": " fn index(&self, index: K) -> &Self::Output {\n\n index.origin_in(self)\n\n }\n\n }\n\n\n\n impl $table {\n\n $pub fn get<K>(&self, k: K) -> K::Origin\n\n where\n\n K: $crate::origin_table::HasOriginIn<Self>,\n\n {\n\n <K::Origin>::clone(K::origin_in(k, self))\n\n }\n\n\n\n $pub fn push<K>(&mut self, k: K, s: K::Origin)\n\n where\n\n K: $crate::origin_table::PushOriginIn<Self>,\n\n {\n\n K::push_origin_in(k, self, s)\n\n }\n\n }\n", "file_path": "components/dada-ir/src/origin_table.rs", "rank": 56, "score": 82490.8354678433 }, { "content": "/// Creates a side table struct for tracking the \"origin\" of\n\n/// something in the IR. The meaning of origin depends on the IR:\n\n/// for a syntax tree, we map directly into the input. For other IRs,\n\n/// we typically map back to the previous IR.\n\nmacro_rules! origin_table {\n\n ($(#[$attr:meta])* $pub:vis struct $table:ident { $($(#[$field_attr:meta])* $field:ident : $key:ty => $origins:ty,)* }) => {\n\n $(#[$attr])*\n\n $pub struct $table {\n\n $(\n\n $(#[$field_attr])*\n\n $field: dada_collections::IndexVec<$key, $origins>,\n\n )*\n\n }\n\n\n\n impl<K> std::ops::Index<K> for $table\n\n where\n\n K: $crate::origin_table::HasOriginIn<$table>,\n\n {\n\n type Output = K::Origin;\n\n\n", "file_path": "components/dada-ir/src/origin_table.rs", "rank": 57, "score": 82487.7407899358 }, { "content": "trait OrDummyExpr {\n\n fn or_dummy_expr(self, parser: &mut CodeParser<'_, '_>) -> Expr;\n\n}\n\n\n\nimpl OrDummyExpr for Option<Expr> {\n\n fn or_dummy_expr(self, parser: &mut CodeParser<'_, '_>) -> Expr {\n\n self.unwrap_or_else(|| parser.add(ExprData::Error, parser.tokens.peek_span()))\n\n }\n\n}\n\n\n\nimpl ParseList for CodeParser<'_, '_> {\n\n fn skipped_newline(&self) -> bool {\n\n Parser::skipped_newline(self)\n\n }\n\n\n\n fn eat_comma(&mut self) -> bool {\n\n Parser::eat_comma(self)\n\n }\n\n}\n\n\n", "file_path": "components/dada-parse/src/parser/code.rs", "rank": 58, "score": 77673.85557202245 }, { "content": "trait TightenSpan {\n\n fn tighten_span(self, parser: &Parser<'_>) -> Self;\n\n}\n\n\n\nimpl TightenSpan for Span {\n\n fn tighten_span(self, parser: &Parser<'_>) -> Self {\n\n parser.tighten_span(self)\n\n }\n\n}\n\n\n\nimpl TightenSpan for LocalVariableDeclSpan {\n\n fn tighten_span(self, parser: &Parser<'_>) -> Self {\n\n LocalVariableDeclSpan {\n\n atomic_span: self.atomic_span.tighten_span(parser),\n\n name_span: self.name_span.tighten_span(parser),\n\n }\n\n }\n\n}\n", "file_path": "components/dada-parse/src/parser/code.rs", "rank": 59, "score": 77601.38295814613 }, { "content": "struct Kernel {}\n\n\n\nimpl Kernel {\n\n pub fn new() -> Self {\n\n Self {}\n\n }\n\n}\n\n\n\n#[async_trait::async_trait]\n\nimpl dada_execute::kernel::Kernel for Kernel {\n\n async fn print(&mut self, _await_pc: ProgramCounter, text: &str) -> eyre::Result<()> {\n\n let mut stdout = tokio::io::stdout();\n\n let mut text = text.as_bytes();\n\n while !text.is_empty() {\n\n let written = stdout.write(text).await?;\n\n text = &text[written..];\n\n }\n\n return Ok(());\n\n }\n\n\n", "file_path": "components/dada-lang/src/run.rs", "rank": 60, "score": 70235.65457133016 }, { "content": "#[derive(Debug)]\n\nstruct OtherErrors {\n\n #[allow(dead_code)] // used just for Debug\n\n others: Vec<eyre::Report>,\n\n}\n\n\n\nimpl OtherErrors {\n\n pub fn new(others: Vec<eyre::Report>) -> Self {\n\n Self { others }\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for OtherErrors {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{self:#?}\")\n\n }\n\n}\n\n\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 61, "score": 69189.52738020924 }, { "content": "#[derive(Debug, Default)]\n\nstruct Errors {\n\n reports: Vec<eyre::Report>,\n\n}\n\n\n\nimpl Errors {\n\n fn push_result(&mut self, r: eyre::Result<()>) {\n\n if let Err(e) = r {\n\n self.reports.push(e);\n\n }\n\n }\n\n\n\n fn push(&mut self, m: impl std::error::Error + Send + Sync + 'static) {\n\n self.reports.push(eyre::Report::new(m));\n\n }\n\n\n\n fn into_result(mut self) -> eyre::Result<()> {\n\n if self.reports.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n let r = self.reports.remove(0);\n\n if self.reports.is_empty() {\n\n return Err(r);\n\n }\n\n\n\n let others = OtherErrors::new(self.reports);\n\n Err(r.wrap_err(others))\n\n }\n\n}\n\n\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 62, "score": 69189.46023378363 }, { "content": "#[derive(Clone, Debug)]\n\nstruct Query {\n\n line: u32,\n\n column: u32,\n\n kind: QueryKind,\n\n message: Regex,\n\n}\n\n\n\n/// Kinds of queries we can perform (see [`Query`])\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 63, "score": 69189.46023378363 }, { "content": "#[derive(Debug, Default)]\n\nstruct Marks {\n\n /// Live objects: objects that had a live owning permission.\n\n live_objects: Set<Object>,\n\n\n\n /// Live permissions: permissions that appeared in a live location\n\n /// (e.g., a variable on some active stack frame).\n\n ///\n\n /// If a permission is live, then so are its tenants.\n\n ///\n\n /// Note that a permission may be live, but its *lessor* may not!\n\n /// In that case, the lessor will be canceled, and thus gc will\n\n /// in turn revoke the (live) permission.\n\n ///\n\n /// Example:\n\n ///\n\n /// ```notrust\n\n /// fn foo() -> {\n\n /// p = Object()\n\n /// q = p.lease\n\n /// q\n\n /// }\n\n /// ```\n\n ///\n\n /// This function creates an Object and returns a leased copy,\n\n /// In the callee, the leased value will be live, but not the owner.\n\n live_permissions: Set<Permission>,\n\n}\n\n\n", "file_path": "components/dada-execute/src/step/gc.rs", "rank": 64, "score": 69189.46023378363 }, { "content": "#[derive(Debug)]\n\nstruct ExpectedDiagnostics {\n\n compile: Vec<ExpectedDiagnostic>,\n\n runtime: Vec<ExpectedDiagnostic>,\n\n\n\n // If `None`, do not check the output.\n\n output: Option<Vec<ExpectedOutput>>,\n\n\n\n // Any `#! FIXME` annotations found\n\n fixmes: Vec<String>,\n\n}\n\n\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 65, "score": 68190.94972617108 }, { "content": "#[derive(Debug)]\n\nstruct OutputsDoNotMatch {\n\n expected: Vec<String>,\n\n actual: Vec<String>,\n\n}\n\n\n\nimpl std::error::Error for OutputsDoNotMatch {}\n\n\n\nimpl std::fmt::Display for OutputsDoNotMatch {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n display_diff(&self.expected, &self.actual, f)\n\n }\n\n}\n\n\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 66, "score": 68190.94972617108 }, { "content": "#[derive(Debug)]\n\nstruct DiagnosticsDoNotMatch {\n\n expected: Vec<String>,\n\n actual: Vec<String>,\n\n}\n\n\n\nimpl std::error::Error for DiagnosticsDoNotMatch {}\n\n\n\nimpl std::fmt::Display for DiagnosticsDoNotMatch {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n display_diff(&self.expected, &self.actual, f)\n\n }\n\n}\n\n\n\n/// Part of the code to check output: the output checker pushes\n\n/// strings into these vectors so we can display a nice diff.\n\n///\n\n/// If we find what we expected, we push the same string into expected/actual.\n\n///\n\n/// If we don't, we push the regex we expected into one, and the actual output\n\n/// into actual.\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 67, "score": 68190.94972617108 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ExpectedOutput {\n\n /// Line where the output should originate.\n\n line1: u32,\n\n\n\n /// A regular expression given by the user that must match\n\n /// against what was printed.\n\n message: Regex,\n\n}\n\n\n\n/// A query is indicated by a `#? ^ QK` annotation. It means that,\n\n/// on the preceding line, we should do some sort of interactive\n\n/// query (specified by the `QK` string, see [`QueryKind`]) at the column\n\n/// indicated by `^`. This could be a compilation\n\n/// or runtime query. The results will be dumped into a file\n\n/// but may also be queried with the regex in `message`.\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 68, "score": 68190.88257974546 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ExpectedDiagnostic {\n\n /// Line where the error is expected to start.\n\n start_line: u32,\n\n\n\n /// Start column, if given by the user.\n\n start_column: Option<u32>,\n\n\n\n /// End position, if given by the user.\n\n end_line_column: Option<(u32, u32)>,\n\n\n\n /// Expected severity (\"ERROR\", \"WARNING\", etc) of the diagnostic.\n\n severity: String,\n\n\n\n /// A regular expression given by the user that must match\n\n /// against the diagnostic.\n\n message: Regex,\n\n}\n\n\n\n/// Test files have `#! OUTPUT` lines that indicate output\n\n/// that is expected from a particular line.\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 69, "score": 68190.88257974546 }, { "content": "fn lex_text(\n\n db: &dyn crate::Db,\n\n filename: Filename,\n\n source_text: &str,\n\n start_offset: usize,\n\n) -> TokenTree {\n\n let chars = &mut source_text\n\n .char_indices()\n\n .map(|(offset, ch)| (offset + start_offset, ch))\n\n .inspect(|pair| tracing::debug!(\"lex::next = {pair:?}\"))\n\n .peekable();\n\n let mut lexer = Lexer {\n\n db,\n\n filename,\n\n chars,\n\n file_len: start_offset + source_text.len(),\n\n };\n\n lexer.lex_tokens(None)\n\n}\n\n\n", "file_path": "components/dada-lex/src/lex.rs", "rank": 70, "score": 67242.86550677527 }, { "content": "fn map_variables(\n\n db: &dyn crate::Db,\n\n validated_tree: validated::Tree,\n\n tables: &mut bir::Tables,\n\n origins: &mut bir::Origins,\n\n) -> Map<validated::LocalVariable, bir::LocalVariable> {\n\n let validated_data = validated_tree.data(db);\n\n let validated_tables = &validated_data.tables;\n\n let validated_origins = validated_tree.origins(db);\n\n validated_data\n\n .max_local_variable()\n\n .iter()\n\n .map(|validated_var| {\n\n let validated_var_data = validated_var.data(validated_tables);\n\n let validated_var_origin = *validated_var.origin_in(validated_origins);\n\n let bir_var = add(\n\n tables,\n\n origins,\n\n bir::LocalVariableData {\n\n name: validated_var_data.name,\n\n atomic: validated_var_data.atomic,\n\n },\n\n validated_var_origin,\n\n );\n\n (validated_var, bir_var)\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "components/dada-brew/src/brewery.rs", "rank": 71, "score": 67242.86550677527 }, { "content": "#[derive(Clone, Debug)]\n\nstruct GraphvizPlace {\n\n /// Id of the node within graphviz.\n\n node: String,\n\n\n\n /// Port of the row for this field.\n\n port: usize,\n\n}\n\n\n", "file_path": "components/dada-execute/src/heap_graph/graphviz.rs", "rank": 72, "score": 67240.84403663361 }, { "content": "struct Marker<'me> {\n\n machine: &'me dyn MachineOp,\n\n marks: &'me mut Marks,\n\n}\n\n\n\nimpl<'me> Marker<'me> {\n\n fn new(machine: &'me dyn MachineOp, marks: &'me mut Marks) -> Self {\n\n Self { machine, marks }\n\n }\n\n\n\n #[tracing::instrument(level = \"Debug\", skip(self))]\n\n fn mark(&mut self, in_flight_values: &[Value]) {\n\n for frame in self.machine.frames() {\n\n for local_value in &frame.locals {\n\n self.mark_value(*local_value);\n\n }\n\n }\n\n\n\n for in_flight_value in in_flight_values {\n\n self.mark_value(*in_flight_value);\n", "file_path": "components/dada-execute/src/step/gc.rs", "rank": 73, "score": 66470.74984372698 }, { "content": "fn display_diff(\n\n expected: &[String],\n\n actual: &[String],\n\n f: &mut std::fmt::Formatter<'_>,\n\n) -> std::fmt::Result {\n\n let expected: String = expected.iter().flat_map(|e| vec![&e[..], \"\\n\"]).collect();\n\n let actual: String = actual.iter().flat_map(|e| vec![&e[..], \"\\n\"]).collect();\n\n write!(\n\n f,\n\n \"{}\",\n\n similar::TextDiff::from_lines(&expected, &actual)\n\n .unified_diff()\n\n .header(\"from comments\", \"actual output\")\n\n )\n\n}\n\n\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 74, "score": 66249.29808513598 }, { "content": "fn ariadne_diagnostic(\n\n _db: &dyn crate::Db,\n\n diagnostic: &dada_ir::diagnostic::Diagnostic,\n\n options: FormatOptions,\n\n) -> eyre::Result<ariadne::Report<ASpan>> {\n\n let mut builder = Report::<ASpan>::build(\n\n ReportKind::Error,\n\n diagnostic.span.filename,\n\n diagnostic.span.start.into(),\n\n )\n\n .with_message(&diagnostic.message)\n\n .with_config(Config::default().with_color(options.with_color));\n\n\n\n for label in &diagnostic.labels {\n\n builder = builder.with_label(Label::new(ASpan(label.span())).with_message(&label.message));\n\n }\n\n\n\n Ok(builder.finish())\n\n}\n\n\n", "file_path": "components/dada-error-format/src/format.rs", "rank": 75, "score": 66249.29808513598 }, { "content": "struct SourceCache<'me> {\n\n db: &'me dyn crate::Db,\n\n map: dada_collections::Map<Filename, Source>,\n\n}\n\n\n\nimpl<'me> SourceCache<'me> {\n\n pub fn new(db: &'me dyn crate::Db) -> Self {\n\n Self {\n\n db,\n\n map: Default::default(),\n\n }\n\n }\n\n}\n\n\n\nimpl ariadne::Cache<Filename> for SourceCache<'_> {\n\n fn fetch(&mut self, id: &Filename) -> Result<&Source, Box<dyn std::fmt::Debug + '_>> {\n\n Ok(self.map.entry(*id).or_insert_with(|| {\n\n let source_text = dada_ir::manifest::source_text(self.db, *id);\n\n Source::from(source_text)\n\n }))\n\n }\n\n\n\n fn display<'a>(&self, id: &'a Filename) -> Option<Box<dyn std::fmt::Display + 'a>> {\n\n let s = id.as_str(self.db).to_string();\n\n Some(Box::new(s))\n\n }\n\n}\n\n\n", "file_path": "components/dada-error-format/src/format.rs", "rank": 76, "score": 65472.17218968881 }, { "content": "struct StringFormatBuffer<'me> {\n\n db: &'me dyn crate::Db,\n\n sections: Vec<FormatStringSection>,\n\n text: String,\n\n}\n\n\n\nimpl<'me> StringFormatBuffer<'me> {\n\n pub fn new(db: &'me dyn crate::Db) -> Self {\n\n Self {\n\n db,\n\n sections: Default::default(),\n\n text: Default::default(),\n\n }\n\n }\n\n\n\n fn push_char(&mut self, ch: char) {\n\n self.text.push(ch);\n\n }\n\n\n\n fn push_tree(&mut self, token_tree: TokenTree) {\n", "file_path": "components/dada-lex/src/lex.rs", "rank": 77, "score": 65472.17218968881 }, { "content": "struct Lexer<'me, I>\n\nwhere\n\n I: Iterator<Item = (usize, char)>,\n\n{\n\n db: &'me dyn crate::Db,\n\n filename: Filename,\n\n chars: &'me mut Peekable<I>,\n\n file_len: usize,\n\n}\n\n\n\nimpl<'me, I> Lexer<'me, I>\n\nwhere\n\n I: Iterator<Item = (usize, char)>,\n\n{\n\n #[tracing::instrument(level = \"debug\", skip(self))]\n\n fn lex_tokens(&mut self, end_ch: Option<char>) -> TokenTree {\n\n let mut tokens = vec![];\n\n let mut push_token = |t: Token| {\n\n tracing::debug!(\"push token: {:?}\", t);\n\n tokens.push(t);\n", "file_path": "components/dada-lex/src/lex.rs", "rank": 78, "score": 65270.80799910489 }, { "content": "struct AssertInvariants<'me> {\n\n machine: &'me dyn MachineOp,\n\n\n\n /// Every permission ought to be associated with \"at most one\" object.\n\n permission_map: Map<Permission, Object>,\n\n}\n\n\n\nimpl<'me> AssertInvariants<'me> {\n\n fn new(_db: &'me dyn crate::Db, machine: &'me dyn MachineOp) -> Self {\n\n Self {\n\n machine,\n\n permission_map: Default::default(),\n\n }\n\n }\n\n\n\n fn assert_all_ok(&mut self) -> eyre::Result<()> {\n\n for frame in self.machine.frames() {\n\n self.assert_frame_ok(frame)?;\n\n }\n\n\n", "file_path": "components/dada-execute/src/step/assert_invariants.rs", "rank": 79, "score": 64522.13364657696 }, { "content": "struct GraphvizWriter<'w> {\n\n /// If true, include temporary variables from stack frames\n\n /// in the output (usually false).\n\n include_temporaries: bool,\n\n\n\n /// Queue of edges to process.\n\n node_queue: Vec<ValueEdgeTarget>,\n\n\n\n /// Set of all edges we have ever processed; when a new edge\n\n /// is added to this set, it is pushed to the queue.\n\n node_set: IndexSet<ValueEdgeTarget>,\n\n\n\n /// A collection of edges from fields to their values,\n\n /// accumulated as we walk the `HeapGraph` and then\n\n /// dumped out at the end.\n\n value_edge_list: Vec<GraphvizValueEdge>,\n\n\n\n /// Maps from each permission to the place whose value has it.\n\n permissions: Map<PermissionNode, Vec<GraphvizPlace>>,\n\n\n", "file_path": "components/dada-execute/src/heap_graph/graphviz.rs", "rank": 80, "score": 64522.13364657696 }, { "content": "#[derive(Debug)]\n\nstruct ExpectedDiagnosticNotFound(ExpectedDiagnostic);\n\n\n\nimpl std::error::Error for ExpectedDiagnosticNotFound {}\n\n\n\nimpl std::fmt::Display for ExpectedDiagnosticNotFound {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{self:#?}\")\n\n }\n\n}\n\n\n\n/// Part of the code to check diagnostics: the diagnostics checker pushes\n\n/// strings into these vectors so we can display a nice diff.\n\n///\n\n/// If we find what we expected, we push the same string into expected/actual.\n\n///\n\n/// If we don't, we push the regex we expected into one, and the actual output\n\n/// into actual.\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 81, "score": 62758.980720758074 }, { "content": "fn main() -> eyre::Result<()> {\n\n Options::from_args().main()\n\n}\n\n\n\n#[derive(StructOpt)]\n\npub struct Options {\n\n #[structopt(long, default_value = \"info\")]\n\n log: String,\n\n\n\n #[structopt(subcommand)] // Note that we mark a field as a subcommand\n\n command: Command,\n\n}\n\n\n\n#[derive(StructOpt)]\n\npub enum Command {\n\n Deploy(deploy::Deploy),\n\n}\n\n\n\nimpl Options {\n\n fn main(&self) -> eyre::Result<()> {\n", "file_path": "components/xtask/src/main.rs", "rank": 82, "score": 62575.043801735184 }, { "content": "fn add<V, O>(\n\n tables: &mut bir::Tables,\n\n origins: &mut bir::Origins,\n\n data: V,\n\n origin: impl Into<O>,\n\n) -> V::Key\n\nwhere\n\n V: dada_id::InternValue<Table = bir::Tables>,\n\n V::Key: PushOriginIn<bir::Origins, Origin = O>,\n\n{\n\n let key = tables.add(data);\n\n origins.push(key, origin.into());\n\n key\n\n}\n\n\n\nimpl<'me, K> std::ops::Index<K> for Brewery<'me>\n\nwhere\n\n K: dada_id::InternKey<Table = bir::Tables>,\n\n{\n\n type Output = K::Value;\n", "file_path": "components/dada-brew/src/brewery.rs", "rank": 83, "score": 61581.47638009589 }, { "content": "pub trait InternAllocKey: InternKey {\n\n /// Get the \"max\", which is the next key of this type which would be allocated.\n\n /// Note that this is not (yet) a valid key.\n\n fn max_key(table: &Self::Table) -> Self;\n\n\n\n /// Get mut ref to data for this key from the given table.\n\n fn data_mut(self, table: &mut Self::Table) -> &mut Self::Value;\n\n}\n", "file_path": "components/dada-id/src/lib.rs", "rank": 84, "score": 59189.06853681222 }, { "content": "#[async_trait::async_trait]\n\npub trait Kernel: Send + Sync {\n\n /// Implementation for the `print` intrinsic, that prints a line of text.\n\n ///\n\n /// # Parameters\n\n ///\n\n /// * `await_pc` -- the program counter when the thunk was awaited\n\n /// * `text` -- the string to print\n\n async fn print(&mut self, await_pc: ProgramCounter, text: &str) -> eyre::Result<()>;\n\n\n\n /// Prints a newline.\n\n ///\n\n /// # Parameters\n\n ///\n\n /// * `await_pc` -- the program counter when the thunk was awaited\n\n async fn print_newline(&mut self, await_pc: ProgramCounter) -> eyre::Result<()> {\n\n self.print(await_pc, \"\\n\").await\n\n }\n\n\n\n /// Indicates that we have reached the start of a breakpoint expression.\n\n fn breakpoint_start(\n", "file_path": "components/dada-execute/src/kernel.rs", "rank": 85, "score": 59144.189439733076 }, { "content": "fn support_escape(s: &str) -> String {\n\n let mut buffer = String::new();\n\n let mut chars = s.chars().peekable();\n\n while let Some(ch) = chars.next() {\n\n if ch == '\\\\' {\n\n if let Some(c) = chars.peek() {\n\n match c {\n\n 'n' | 'r' | 't' | '\"' | '\\\\' => {\n\n buffer.push(escape(*c));\n\n chars.next();\n\n continue;\n\n }\n\n _ => {}\n\n }\n\n }\n\n }\n\n buffer.push(ch);\n\n }\n\n buffer\n\n}\n\n\n", "file_path": "components/dada-validate/src/validate/validator.rs", "rank": 86, "score": 57952.286007694376 }, { "content": "// Remove leading, trailing whitespace and common indent from multiline strings.\n\nfn convert_to_dada_string(s: &str) -> String {\n\n // If the string has only one line, leave it and return immediately.\n\n if s.lines().count() == 1 {\n\n return support_escape(s);\n\n }\n\n\n\n // Split string into lines and filter out empty lines.\n\n let mut non_empty_line_iter = s.lines().filter(|&line| !line.trim().is_empty());\n\n\n\n if let Some(first_line) = non_empty_line_iter.next() {\n\n let prefix = first_line\n\n .chars()\n\n .into_iter()\n\n .take_while(|c| c.is_whitespace())\n\n .collect::<String>();\n\n let common_indent = non_empty_line_iter\n\n .map(|s| count_bytes_in_common(prefix.as_bytes(), s.as_bytes()))\n\n .min()\n\n .unwrap_or(0);\n\n\n", "file_path": "components/dada-validate/src/validate/validator.rs", "rank": 87, "score": 57093.610644017375 }, { "content": "pub trait InternKey: salsa::AsId + 'static {\n\n type Table;\n\n type Value;\n\n\n\n /// Get the data for this key from the given table.\n\n fn data(self, table: &Self::Table) -> &Self::Value;\n\n}\n\n\n", "file_path": "components/dada-id/src/lib.rs", "rank": 88, "score": 55841.20561935085 }, { "content": "fn new_notification<T>(params: T::Params) -> Notification\n\nwhere\n\n T: lsp_types::notification::Notification,\n\n{\n\n Notification {\n\n method: T::METHOD.to_owned(),\n\n params: serde_json::to_value(&params).unwrap(),\n\n }\n\n}\n", "file_path": "components/dada-lsp/src/lib.rs", "rank": 89, "score": 53433.75001907593 }, { "content": "fn as_notification<T>(x: &Notification) -> Option<T::Params>\n\nwhere\n\n T: lsp_types::notification::Notification,\n\n T::Params: DeserializeOwned,\n\n{\n\n if x.method == T::METHOD {\n\n let params = serde_json::from_value(x.params.clone()).unwrap_or_else(|err| {\n\n panic!(\n\n \"Invalid notification\\nMethod: {}\\n error: {}\",\n\n x.method, err\n\n )\n\n });\n\n Some(params)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "components/dada-lsp/src/lib.rs", "rank": 90, "score": 53104.46245581161 }, { "content": "/// Remove system-specific absolute paths from output strings.\n\nfn sanitize_output(output: String) -> eyre::Result<String> {\n\n let local_file_prefix = format!(\n\n r#\"\"{}\"#,\n\n match env::var(\"CARGO_MANIFEST_DIR\") {\n\n Ok(v) => v,\n\n Err(_) => env::current_dir()?.display().to_string(),\n\n }\n\n );\n\n let replacement = r#\"\"(local-file-prefix)\"#;\n\n Ok(output.replace(&local_file_prefix, replacement))\n\n}\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 91, "score": 52650.29401847481 }, { "content": "fn cargo_path(env_var: &str) -> eyre::Result<PathBuf> {\n\n match std::env::var(env_var) {\n\n Ok(s) => {\n\n tracing::debug!(\"cargo_path({env_var}) = {s}\");\n\n Ok(PathBuf::from(s))\n\n }\n\n Err(_) => eyre::bail!(\"`{}` not set\", env_var),\n\n }\n\n}\n\n\n", "file_path": "components/xtask/src/deploy.rs", "rank": 92, "score": 52650.29401847481 }, { "content": "fn download_mdbook(dada_downloads: &Path) -> eyre::Result<PathBuf> {\n\n let version = \"v0.4.15\";\n\n let url = format!(\"https://github.com/rust-lang/mdBook/releases/download/{version}/mdbook-{version}-x86_64-unknown-linux-gnu.tar.gz\");\n\n let filename = format!(\"mdbook-{version}.tar.gz\");\n\n download_and_untar(dada_downloads, &url, &filename)?;\n\n Ok(dada_downloads.join(\"mdbook\"))\n\n}\n\n\n", "file_path": "components/xtask/src/deploy.rs", "rank": 93, "score": 52650.29401847481 }, { "content": "fn download_wasm_pack(dada_downloads: &Path) -> eyre::Result<PathBuf> {\n\n let version = \"v0.10.2\";\n\n let prefix = format!(\"wasm-pack-{version}-x86_64-unknown-linux-musl\");\n\n let filename = format!(\"{prefix}.tar.gz\");\n\n let url =\n\n format!(\"https://github.com/rustwasm/wasm-pack/releases/download/{version}/{filename}\");\n\n download_and_untar(dada_downloads, &url, &filename)?;\n\n Ok(dada_downloads.join(&prefix).join(\"wasm-pack\"))\n\n}\n\n\n", "file_path": "components/xtask/src/deploy.rs", "rank": 94, "score": 51900.794080174266 }, { "content": "/// Returns the diagnostics that we expect to see in the file, sorted by line number.\n\nfn expected_diagnostics(path: &Path) -> eyre::Result<ExpectedDiagnostics> {\n\n let file_contents = std::fs::read_to_string(path)?;\n\n\n\n let diagnostic_marker = regex::Regex::new(\n\n r\"^(?P<prefix>[^#]*)#!\\s*(?P<highlight>\\^+)?\\s*(?P<type>RUN)?\\s*(?P<severity>ERROR|WARNING|INFO)\\s*(?P<msg>.*)\",\n\n )\n\n .unwrap();\n\n\n\n let output_marker = regex::Regex::new(r\"^(?P<prefix>[^#]*)#!\\s*OUTPUT\\s+(?P<msg>.*)\").unwrap();\n\n\n\n let fixme_issue_marker =\n\n regex::Regex::new(r\"#!\\s*FIXME\\(#(?P<issue>[0-9]+)\\): (?P<message>.+)\").unwrap();\n\n let fixme_marker = regex::Regex::new(r\"#!\\s*FIXME: (?P<message>.+)\").unwrap();\n\n\n\n let any_output_marker = regex::Regex::new(r\"^(?P<prefix>[^#]*)#!\\s*OUTPUT ANY\").unwrap();\n\n\n\n let any_marker = regex::Regex::new(r\"^[^#]*#!\").unwrap();\n\n\n\n let mut last_code_line = 1;\n\n let mut compile_diagnostics = vec![];\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 95, "score": 51900.794080174266 }, { "content": "fn count_bytes_in_common(s1: &[u8], s2: &[u8]) -> usize {\n\n s1.iter().zip(s2).take_while(|(c1, c2)| c1 == c2).count()\n\n}\n\n\n", "file_path": "components/dada-validate/src/validate/validator.rs", "rank": 96, "score": 51900.794080174266 }, { "content": "/// Searches for a `#?` annotation, which indicates that we want to do a\n\n/// query at a particular point.\n\nfn expected_queries(path: &Path) -> eyre::Result<Vec<Query>> {\n\n let file_contents = std::fs::read_to_string(path)?;\n\n\n\n // The notation #? ^ indicates the line/column pictorially\n\n let query_at_re =\n\n regex::Regex::new(r\"^[^#]*#\\?\\s*(?P<pointer>\\^)\\s*(?P<kind>[^\\s]*)\\s*(?P<msg>.*)\").unwrap();\n\n\n\n // The notation #? @ 1:1 indicates the line/column by number\n\n let query_lc_re = regex::Regex::new(\n\n r\"^[^#]*#\\?\\s*@\\s*(?P<line>[+-]?\\d+):(?P<column>\\d+)\\s*(?P<kind>[^\\s]*)\\s*(?P<msg>.*)\",\n\n )\n\n .unwrap();\n\n\n\n // The notation #? @ 1:1 indicates the line/column by number\n\n let query_any_re = regex::Regex::new(r\"^[^#]*#\\?\").unwrap();\n\n\n\n let comment_line_re = regex::Regex::new(r\"^\\s*#\").unwrap();\n\n\n\n let mut last_code_line = 1;\n\n let mut result = vec![];\n", "file_path": "components/dada-lang/src/test_harness.rs", "rank": 97, "score": 50751.733403460064 }, { "content": "fn download_and_untar(dada_downloads: &Path, url: &str, file: &str) -> eyre::Result<()> {\n\n tracing::debug!(\"download_and_untar(url={url}, file={file})\");\n\n let _pushd = xshell::pushd(dada_downloads);\n\n let file = Path::new(file);\n\n if !file.exists() {\n\n xshell::cmd!(\"curl -L -o {file} {url}\").run()?;\n\n xshell::cmd!(\"tar zxf {file}\").run()?;\n\n } else {\n\n tracing::debug!(\"file already exists\");\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/xtask/src/deploy.rs", "rank": 98, "score": 48124.957444272615 }, { "content": "fn copy_all_files(source_dir: &Path, subdir: &str, target_dir: &Path) -> eyre::Result<()> {\n\n for f in xshell::read_dir(source_dir.join(subdir))? {\n\n assert!(!f.is_dir()); // FIXME\n\n let target_subdir = &target_dir.join(subdir);\n\n xshell::mkdir_p(target_subdir)?;\n\n xshell::cp(f, target_subdir)?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "components/xtask/src/deploy.rs", "rank": 99, "score": 47437.066960162425 } ]
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) => config,\n\n Err(io_err) => return Either::A(future::err(Error::from(io_err))),\n\n };\n\n // Get projects git account\n\n let git_config = match git::get_config(env, &config.git_user) {\n\n Ok(git_config) => git_config,\n\n Err(io_err) => return Either::A(future::err(Error::from(io_err))),\n\n };\n\n Either::B(git::setup_git_dir(\n\n env,\n\n project_git,\n\n git_config,\n\n config.git_repo_uri.clone(),\n\n ))\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 1, "score": 381382.30775806005 }, { "content": "pub fn get_config(env: &CliEnv, project: &str) -> io::Result<ProjectConfig> {\n\n let json_file = std::fs::File::open(env.config_dirs.projects.filepath(project))?;\n\n let buf_reader = io::BufReader::new(json_file);\n\n let config = serde_json::from_reader::<_, ProjectConfig>(buf_reader)?;\n\n Ok(config)\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 2, "score": 353947.37105193664 }, { "content": "pub fn get_config(env: &CliEnv, server: &str) -> io::Result<ServerConfig> {\n\n let json_file = std::fs::File::open(env.config_dirs.servers.filepath(server))?;\n\n let buf_reader = io::BufReader::new(json_file);\n\n let config = serde_json::from_reader::<_, ServerConfig>(buf_reader)?;\n\n Ok(config)\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 3, "score": 353263.3811707523 }, { "content": "/// Syncs plugins, themes, other site data between local and install\n\n/// on dev or server\n\npub fn sync_local(env: &CliEnv, project: ProjectConfig, on_server: bool) -> Result<()> {\n\n let local_data = get_local_site_data(env, &project)?;\n\n let cli_conn = wp_cli_conn(env, &project, on_server)?;\n\n if on_server {\n\n sync_files_to_prod(&cli_conn, &local_data)?;\n\n }\n\n let install_data = match wp_install_data(&cli_conn) {\n\n Ok(install_data) => install_data,\n\n Err(e) => return Err(format_err!(\"Install data error: {}\", e)),\n\n };\n\n // Ensure local plugins, themes and their dependencies are activated\n\n\n\n // First do deps, ideally this should be a bigger dependency graph,\n\n // so deps of deps are installed first.\n\n // also could consider running wp-cli without loading plugins\n\n for dep in local_data.deps {\n\n match install_data.plugins.get(&dep) {\n\n Some(plugin_data) => {\n\n // Plugin is installed, check for activated\n\n if plugin_data.status != \"active\" {\n", "file_path": "tools/cli/src/wp.rs", "rank": 5, "score": 348023.2581373318 }, { "content": "pub fn has_config(env: &CliEnv, project: &str) -> bool {\n\n env.config_dirs.projects.has_file(project)\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 6, "score": 344838.4248366399 }, { "content": "pub fn has_config(env: &CliEnv, server: &str) -> bool {\n\n env.config_dirs.servers.has_file(server)\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 7, "score": 344206.0509865217 }, { "content": "pub fn project_dir(env: &CliEnv, project: &str) -> PathBuf {\n\n env.get_project_path(project)\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 8, "score": 343298.8761731209 }, { "content": "/// Returns a connection to either dev server,\n\n/// or piped on prod server\n\npub fn wp_cli_conn(env: &CliEnv, project: &ProjectConfig, on_server: bool) -> Result<SshConn> {\n\n let server_config = if on_server {\n\n // Todo: Could allow to choose, or return error\n\n match project.get_server(&env) {\n\n Some(server_config) => Some(server_config),\n\n None => return Err(format_err!(\"Could not resolve server\")),\n\n }\n\n } else {\n\n None\n\n };\n\n let conn = if on_server {\n\n match server_config {\n\n Some(server_config) => {\n\n server::SshConn::connect_wp_cli(env, 2345, Some(&server_config))?\n\n }\n\n None => return Err(format_err!(\"No server config\")),\n\n }\n\n } else {\n\n server::SshConn::connect_wp_cli(env, 2345, None)?\n\n };\n\n Ok(conn)\n\n}\n\n\n", "file_path": "tools/cli/src/wp.rs", "rank": 9, "score": 331668.5248386042 }, { "content": "pub fn err_msg<T>(msg: impl Into<String>) -> Result<T> {\n\n Err(MyLibError::Msg(msg.into()))\n\n}\n\n\n", "file_path": "tools/mysql-utils/src/er.rs", "rank": 10, "score": 330569.7105722535 }, { "content": "pub fn index_menus(data: web::Data<AppData>) -> impl Future<Item = (), Error = Error> {\n\n let client = Client::default();\n\n client\n\n .get(\"http://192.168.33.10/wp-json/brygga/all-menus\")\n\n .timeout(std::time::Duration::new(15, 0))\n\n .send()\n\n .map_err(Error::from)\n\n .and_then(move |resp| {\n\n println!(\"Got index response: {}\", resp.status().as_u16());\n\n let status_code = resp.status().as_u16();\n\n println!(\"Status code: {}\", status_code);\n\n resp.from_err()\n\n .fold(BytesMut::new(), |mut acc, chunk| {\n\n acc.extend_from_slice(&chunk);\n\n Ok::<_, Error>(acc)\n\n })\n\n .map(move |body| {\n\n let body: AllMenus = serde_json::from_slice(&body).unwrap();\n\n index_menu_data(body, &data.index_data);\n\n // One reader per index\n\n ()\n\n })\n\n })\n\n}\n\n\n", "file_path": "tools/proxy/src/search.rs", "rank": 12, "score": 321578.845706441 }, { "content": "/// Resolve project from current directory, or error\n\npub fn resolve_current_project(env: &CliEnv) -> io::Result<ProjectConfig> {\n\n let cd = std::env::current_dir()?;\n\n let cd = cd\n\n .strip_prefix(&env.projects_dir)\n\n .map_err(|e| utils::io_error(format!(\"{:?}\", e)))?;\n\n // Then use first component\n\n match cd.components().next() {\n\n Some(std::path::Component::Normal(os_str)) => {\n\n match get_config(env, &os_str.to_string_lossy()) {\n\n Ok(project_config) => Ok(project_config),\n\n Err(e) => utils::io_err(format!(\"Could not resolve project config: {:?}\", e)),\n\n }\n\n }\n\n _ => utils::io_err(\"Could not resolve project dir\"),\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 13, "score": 312166.0572292141 }, { "content": "/// Initializes a git repo for the workspace, using\n\n/// defined git account\n\npub fn init_git<'a>(env: &'a CliEnv) -> impl Future<Item = (), Error = failure::Error> + 'a {\n\n let git_config = match git::select_account(env, None) {\n\n Ok(git_account) => git_account,\n\n Err(e) => return Either::A(future::err(failure::Error::from(e))),\n\n };\n\n let repo_name = match env.get_input(\"Repo name\", Some(\"workspace\".into())) {\n\n Ok(repo_name) => repo_name,\n\n Err(e) => return Either::A(future::err(failure::Error::from(e))),\n\n };\n\n\n\n let dir_git = match git::inspect_git(env.config_dirs.config_root.clone()) {\n\n Ok(dir_git) => dir_git,\n\n Err(e) => return Either::A(future::err(failure::Error::from(e))),\n\n };\n\n\n\n let git_uri = git_config.repo_uri(repo_name);\n\n\n\n Either::B(\n\n git::setup_git_dir(env, dir_git, git_config, git_uri).map_err(|e| failure::Error::from(e)),\n\n )\n\n}\n\n\n", "file_path": "tools/cli/src/workspace.rs", "rank": 14, "score": 309152.8298322456 }, { "content": "/// Resolves current project interactive, either\n\n/// by figuring it out from the current directory,\n\n/// or asking the user to select one\n\n// todo: Possibly make ProjEnv over CliEnv\n\n// (not so composy)\n\n// or something lessen boilerplate a little\n\n// shorter name\n\npub fn resolve_current_project_interactive(env: &CliEnv) -> io::Result<ProjectConfig> {\n\n match resolve_current_project(env) {\n\n Ok(project_confir) => Ok(project_confir),\n\n Err(_e) => {\n\n // Todo: Could allow init here if in appropriate directory\n\n let projects = get_projects(env)?;\n\n // A little speculative, but for now, auto select\n\n // project if there is only one\n\n if projects.len() == 1 {\n\n println!(\"Only one project, selecting {}!\", projects[0]);\n\n get_config(env, &projects[0])\n\n } else {\n\n env.select(\"Select project\", &projects, None)\n\n .and_then(|i| match projects.get(i) {\n\n Some(project_name) => get_config(env, project_name),\n\n None => utils::io_err(\"Error selecting project\"),\n\n })\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 15, "score": 308313.5909533562 }, { "content": "pub fn activate_theme(cli_conn: &SshConn, theme: &str) -> Result<()> {\n\n match cli_conn.exec(format!(\"wp theme activate {}\", theme)) {\n\n Ok(_) => {\n\n println!(\"Theme activated: {}\", theme);\n\n Ok(())\n\n }\n\n Err(e) => Err(format_err!(\"Couldn't activate theme: {}, {:?}\", theme, e)),\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/wp.rs", "rank": 16, "score": 307339.06719339197 }, { "content": "/// Prod container command through ssh\n\npub fn prod(env: &CliEnv, project: &ProjectConfig, mut user_args: Vec<String>) -> Result<()> {\n\n // Sync docker file\n\n crate::wp::create_docker_prod_yml(env, &project)?;\n\n let server = match project.get_server(env) {\n\n Some(server) => server,\n\n None => {\n\n return Err(format_err!(\n\n \"Missing server in project config, required for prod\"\n\n ))\n\n }\n\n };\n\n let conn = SshConn::connect(env, &server)?;\n\n let sftp = conn.sftp()?;\n\n crate::server::SyncSet::from_file(\n\n project.dir_and(env, \"docker/prod.yml\"),\n\n server.home_dir_and(&format!(\"projects/{}/docker\", project.name)),\n\n &sftp,\n\n false,\n\n )?\n\n .sync_plain(&sftp)?;\n", "file_path": "tools/cli/src/project.rs", "rank": 17, "score": 306225.0402613476 }, { "content": "pub fn sync_content_to_prod(env: &CliEnv, project: &ProjectConfig) -> Result<()> {\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/cli/src/wp.rs", "rank": 18, "score": 303436.4141516051 }, { "content": "pub fn error_msg(msg: impl Into<String>) -> MyLibError {\n\n MyLibError::Msg(msg.into())\n\n}\n\n\n\nimpl fmt::Debug for MyLibError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Self::Msg(msg) => write!(f, \"{}\", msg),\n\n Self::MySql(e) => write!(f, \"Mysql: {:?}\", e),\n\n Self::Io(e) => write!(f, \"Io: {:?}\", e),\n\n Self::Convert(e) => write!(f, \"Convert: {:?}\", e),\n\n }\n\n }\n\n}\n\nimpl fmt::Display for MyLibError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n", "file_path": "tools/mysql-utils/src/er.rs", "rank": 21, "score": 295038.7972772835 }, { "content": "// todo: Keep progress and allow to continue,\n\n// also allow to teardown when interrupted as well as completed.\n\n// Can first do a dry run to check permissions, then\n\n// alert user of missing permission to increase chance\n\n// of not aborted process\n\n// todo: Clean up stack to run in case of failures,\n\n// should be persisted\n\npub fn provision_server(env: &CliEnv, dry_run: bool) -> io::Result<()> {\n\n // todo: Allow \"reprovision\" of existing server\n\n let server_name = env.get_input(\"Server name\", None)?;\n\n if crate::server::has_config(env, &server_name) {\n\n eprintln!(\"Server name already exist. \\\"Reprovision\\\" not implemented\");\n\n return io_err(\"Server name already exist\");\n\n }\n\n let ec2_client = create_ec2_client(&env)?;\n\n // Select or provision address\n\n // Can use this to get ip of specific instance with filter\n\n let desribe_addr = ec2_client\n\n .describe_addresses(DescribeAddressesRequest {\n\n allocation_ids: None,\n\n dry_run: Some(dry_run),\n\n filters: None,\n\n public_ips: None,\n\n })\n\n .sync()\n\n .map_err(to_io_err)?;\n\n // Allow to select from those not assigned\n", "file_path": "tools/cli/src/aws.rs", "rank": 22, "score": 286502.8254465477 }, { "content": "pub fn select_server(env: &CliEnv) -> io::Result<ServerConfig> {\n\n let servers = get_servers(env)?;\n\n env.select(\"Select server\", &servers, None)\n\n .and_then(|i| match servers.get(i) {\n\n Some(server_name) => get_config(env, server_name),\n\n None => utils::io_err(\"Error selecting server\"),\n\n })\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 23, "score": 282348.80397357314 }, { "content": "// todo: Some of this would be phased out to dedicated images\n\n// hosted in docker hub or otherwise, though some remain like\n\n// compose files and custom images\n\n// In any case handy for development of server setup\n\n/// Syncs server base files, like Dockerfiles to server\n\npub fn sync_to_server(env: &CliEnv, server: ServerConfig) -> Result<()> {\n\n let conn = SshConn::connect(env, &server)?;\n\n let mut server_dir = env.workdir_dir.clone();\n\n server_dir.push(\"server\");\n\n let remote_server_dir = server.home_dir_and(\"workdir/server\");\n\n let sftp = conn.sftp()?;\n\n let mut sync_set = SyncSet::new(server_dir.clone(), remote_server_dir.clone());\n\n for subdir in [\"base\", \"prod\"].into_iter() {\n\n let mut local = server_dir.clone();\n\n local.push(subdir);\n\n sync_set.resolve(&local, &sftp, false)?;\n\n }\n\n sync_set.sync_zipped(&conn, &sftp)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 24, "score": 281840.9143103863 }, { "content": "/// Sets up remote server. Mainly docker\n\npub fn setup_server(env: &CliEnv, server: ServerConfig) -> Result<()> {\n\n // Could check instance status here\n\n let conn = SshConn::connect(env, &server)?;\n\n // https://gist.github.com/npearce/6f3c7826c7499587f00957fee62f8ee9\n\n conn.exec(\"sudo yum update\")?;\n\n conn.exec(\"sudo amazon-linux-extras install docker\")?;\n\n // Start docker and enable auto-start\n\n conn.exec(\"sudo systemctl enable --now docker.service\")?;\n\n conn.exec(\"sudo usermod -a -G docker ec2-user\")?;\n\n // Docker compose\n\n conn.exec(\"sudo curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose\")?;\n\n conn.exec(\"sudo chmod +x /usr/local/bin/docker-compose\")?;\n\n // Can see error code if docker-compose successfully installed\n\n conn.exec(\"docker-compose version\")?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 25, "score": 281835.9501343658 }, { "content": "/// Parses attribs until end of tag\n\n/// This will detect '>', so passes on\n\n/// Returns (self_closed, vec<attr, attr_value>)\n\npub fn parse_attributes(mut s: &[u8]) -> Result<(&[u8], bool, Vec<Attrib>)> {\n\n let mut attribs = Vec::new();\n\n loop {\n\n s = strip_space(s);\n\n s.len_gt(0)?;\n\n let next = s.chr();\n\n s = &s[1..];\n\n match next {\n\n RBRACKET => return Ok((s, false, attribs)), // Done\n\n FSLASH => {\n\n if let Some(s) = s.parse_chr_opt_space(RBRACKET) {\n\n return Ok((s, true, attribs));\n\n } else {\n\n return err(\"Expected '>' after '/'\", s);\n\n }\n\n }\n\n I => {\n\n s = if let Some(s2) = s.parse_ident1(D) {\n\n let (s2, attr_val) = parse_attr_value(s2)?;\n\n match attr_val {\n", "file_path": "tools/frontend/src/parser.rs", "rank": 26, "score": 281793.7868692669 }, { "content": "/// Ssh shell\n\npub fn ssh(env: &CliEnv, server: ServerConfig) -> Result<()> {\n\n let conn = SshConn::connect(env, &server)?;\n\n conn.shell()\n\n}\n", "file_path": "tools/cli/src/server.rs", "rank": 27, "score": 281274.0065526427 }, { "content": "pub fn install_plugin(cli_conn: &SshConn, plugin: &str, activate: bool) -> Result<()> {\n\n let mut args = vec![\"plugin\", \"install\", plugin];\n\n if activate {\n\n args.push(\"--activate\");\n\n }\n\n match cli_conn.exec(format!(\"wp {}\", args.join(\" \"))) {\n\n Ok(_) => {\n\n println!(\"Plugin installed and activated: {}\", plugin);\n\n Ok(())\n\n }\n\n Err(e) => Err(format_err!(\"Couldn't install: {}, {:?}\", plugin, e)),\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/wp.rs", "rank": 28, "score": 279050.1750157023 }, { "content": "pub fn get_config(env: &CliEnv, user: &str) -> io::Result<GitConfig> {\n\n let json_file = std::fs::File::open(env.config_dirs.git_accounts.filepath(user))?;\n\n let buf_reader = io::BufReader::new(json_file);\n\n let config = serde_json::from_reader::<_, GitConfig>(buf_reader)?;\n\n Ok(config)\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 29, "score": 278614.41570639773 }, { "content": "// Data from project, ie local\n\npub fn get_local_site_data(env: &CliEnv, project: &ProjectConfig) -> io::Result<WpLocalSiteData> {\n\n let project_dir = project.dir(env);\n\n let mut site_data = WpLocalSiteData {\n\n project_dir: project_dir.clone(),\n\n plugins: HashMap::new(),\n\n themes: HashMap::new(),\n\n deps: HashSet::new(),\n\n };\n\n // Plugins\n\n let mut plugins_dir = project_dir.clone();\n\n plugins_dir.push(\"plugins\");\n\n if plugins_dir.is_dir() {\n\n for plugin_path in utils::entries_in_dir(&plugins_dir)? {\n\n if plugin_path.is_dir() {\n\n let plugin_name = utils::file_name_string(&plugin_path)?;\n\n let from_project = plugin_path\n\n .strip_prefix(&project_dir)\n\n .map_err(|e| utils::io_error(format!(\"Strip path error: {:?}\", e)))?;\n\n let server_path = Path::new(\"/var/www/html/wp-content\").join(from_project);\n\n let mut plugin_conf_file = plugin_path.clone();\n", "file_path": "tools/cli/src/wp.rs", "rank": 30, "score": 275524.10485435824 }, { "content": "/// Returns names of projects\n\npub fn get_projects(env: &CliEnv) -> io::Result<Vec<String>> {\n\n utils::files_in_dir(&env.config_dirs.projects.0)\n\n}\n\n\n", "file_path": "tools/cli/src/project.rs", "rank": 31, "score": 273489.3633715762 }, { "content": "pub fn get_servers(env: &CliEnv) -> io::Result<Vec<String>> {\n\n utils::files_in_dir(&env.config_dirs.servers.0)\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 32, "score": 272807.0554937043 }, { "content": "pub fn select_account(env: &CliEnv, default: Option<String>) -> io::Result<GitConfig> {\n\n let entries = get_accounts(&env)?;\n\n let key = env\n\n .select(\n\n \"Git account\",\n\n &entries,\n\n default.and_then(|key| entries.iter().position(|e| *e == key)),\n\n )\n\n .and_then(|i| {\n\n entries\n\n .get(i)\n\n .ok_or_else(|| utils::io_error(\"Could not resolve account\"))\n\n })?\n\n .to_owned();\n\n get_config(env, &key)\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 33, "score": 271683.08075167565 }, { "content": "pub fn err<T, S: Into<String>>(msg: S, s: &[u8]) -> Result<T> {\n\n Err(ParseError::Msg(msg.into(), ParseError::around(s)))\n\n}\n\nimpl ParseError {\n\n fn around(s: &[u8]) -> String {\n\n const MAX: usize = 100;\n\n if s.len() >= MAX {\n\n String::from_utf8_lossy(&s[..MAX]).into()\n\n } else {\n\n String::from_utf8_lossy(s).into()\n\n }\n\n }\n\n}\n\nimpl std::fmt::Display for ParseError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n match self {\n\n ParseError::Msg(msg, around) => write!(f, \"{}, around: {}\", msg, around),\n\n }\n\n }\n\n}\n", "file_path": "tools/frontend/src/parse_utils.rs", "rank": 34, "score": 270525.751591459 }, { "content": "pub fn has_config(env: &CliEnv, user: &str) -> bool {\n\n env.config_dirs.git_accounts.has_file(user)\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 35, "score": 270422.1676867568 }, { "content": "pub fn write_config(env: &CliEnv, config: ServerConfig) -> io::Result<()> {\n\n let content_str = match serde_json::to_string_pretty(&config) {\n\n Ok(content_str) => content_str,\n\n Err(_) => return Err(io::Error::from(io::ErrorKind::InvalidData)),\n\n };\n\n\n\n env.config_dirs.servers.write(&config.name, &content_str)\n\n}\n\n\n\npub struct SshConn {\n\n pub tcp: TcpStream,\n\n pub session: ssh2::Session,\n\n pub tunnel: Option<SshTunnel>,\n\n}\n\nimpl Drop for SshConn {\n\n fn drop(&mut self) {\n\n if let Some(tunnel) = self.tunnel.take() {\n\n match tunnel.close() {\n\n Ok(_) => println!(\"Closed tunnel\"),\n\n Err(e) => eprintln!(\"Failed closing tunnel: {:?}\", e),\n", "file_path": "tools/cli/src/server.rs", "rank": 36, "score": 269446.11728264403 }, { "content": "pub fn create_docker_prod_yml(env: &CliEnv, project: &ProjectConfig) -> Result<()> {\n\n use crate::docker::{ComposeService, ComposeYml};\n\n // Set environment variable for external url\n\n let server = server::get_config(env, &project.server_name).map_err(er::Io::e)?;\n\n let mut proxy_env = BTreeMap::new();\n\n let elastic_ip = match server.elastic_ip {\n\n Some(elastic_ip) => elastic_ip,\n\n None => {\n\n eprintln!(\"Elastic ip is required for prod.yml\");\n\n return Err(format_err!(\"Elastic ip is required for prod.yml\"));\n\n }\n\n };\n\n proxy_env.insert(\n\n \"EXTERNAL\".to_string(),\n\n format!(\"http://{}\", elastic_ip.public_ip),\n\n );\n\n let proxy = ComposeService {\n\n volumes: Vec::new(),\n\n environment: proxy_env,\n\n };\n", "file_path": "tools/cli/src/wp.rs", "rank": 37, "score": 268516.76977494865 }, { "content": "pub fn write_err() -> Result<()> {\n\n Err(MyLibError::Msg(\"Failed to write\".into()))\n\n}\n\n\n", "file_path": "tools/mysql-utils/src/coltypes/mod.rs", "rank": 38, "score": 268455.1104196051 }, { "content": "pub fn sql_cli(env: &CliEnv, sql: &str) -> Result<()> {\n\n use mysql_utils::Db;\n\n let mut db = Db::new(\"127.0.0.1\", 3307, \"wordpress\", \"wordpress\", \"wordpress\")?;\n\n db.print_query(sql)?;\n\n Ok(())\n\n}", "file_path": "tools/cli/src/wp.rs", "rank": 40, "score": 265317.72091186 }, { "content": "/// Create mount entries for directories in\n\n/// plugins/ and themes/ folders\n\npub fn create_wp_docker_yml(env: &CliEnv, project: ProjectConfig) -> io::Result<()> {\n\n use crate::docker::{ComposeService, ComposeYml};\n\n // Iterate plugins and themes and collect mounts\n\n let mut mounts = Vec::new();\n\n let local_site = get_local_site_data(env, &project)?;\n\n\n\n // Plugin mounts\n\n for (_name, plugin) in local_site.plugins {\n\n mounts.push((\n\n plugin.paths.full_path.string(),\n\n plugin.paths.server_path.string(),\n\n ));\n\n }\n\n // Theme mounts\n\n for (_name, theme) in local_site.themes {\n\n mounts.push((\n\n theme.paths.full_path.string(),\n\n theme.paths.server_path.string(),\n\n ));\n\n }\n", "file_path": "tools/cli/src/wp.rs", "rank": 41, "score": 260817.46649748425 }, { "content": "/// While wp-specific, dev setup might be a different category\n\npub fn gen_vscode_debug_config(env: &CliEnv, project: ProjectConfig) -> io::Result<()> {\n\n // Using hjson here to preserve comments in json file\n\n // edit: unfortunately doesn't preserve comments, at least\n\n // parses it\n\n use serde_hjson::{Map, Value};\n\n // Collect mapping for plugins and themes\n\n let mut mappings = Map::new();\n\n let site_local = get_local_site_data(env, &project)?;\n\n for (_name, plugin) in site_local.plugins {\n\n mappings.insert(\n\n plugin.paths.server_path.string(),\n\n Value::String(format!(\n\n \"${{workspaceRoot}}/{}\",\n\n plugin.paths.from_project.cow()\n\n )),\n\n );\n\n }\n\n for (_name, theme) in site_local.themes {\n\n mappings.insert(\n\n theme.paths.server_path.string(),\n", "file_path": "tools/cli/src/wp.rs", "rank": 42, "score": 260808.55435232434 }, { "content": "pub fn run() -> Result<(), failure::Error> {\n\n let mut clap_app = cli::cli_app();\n\n let matches = clap_app.clone().get_matches();\n\n //println!(\"{:#?}\", matches);\n\n let home_dir = match dirs::home_dir() {\n\n Some(home_dir) => home_dir,\n\n None => {\n\n println!(\"Couldn't resolve home directory when resolving projects dir\");\n\n std::process::exit(1);\n\n }\n\n };\n\n // Workdir dir\n\n let mut workdir_dir = home_dir.clone();\n\n workdir_dir.push(\"workdir\");\n\n // Projects dir\n\n let mut projects_dir = home_dir.clone();\n\n projects_dir.push(\"projects\");\n\n let env = CliEnv::new(projects_dir, workdir_dir);\n\n match matches.subcommand() {\n\n (\"init\", Some(_sub_matches)) => {\n", "file_path": "tools/cli/src/cli_app.rs", "rank": 43, "score": 255918.18979489326 }, { "content": "fn get_config_file(env: &CliEnv) -> std::path::PathBuf {\n\n let mut config_file = env.config_dirs.config_root.clone();\n\n config_file.push(\"aws_credentials\");\n\n config_file\n\n}\n\n\n", "file_path": "tools/cli/src/aws.rs", "rank": 44, "score": 255699.18674952915 }, { "content": "/// Clone git repo\n\n/// Note that git_pass in the case of github also can be\n\n/// passed a token.\n\n// TODO: Errors\n\npub fn clone_repo(git_user: String, git_pass: String, repo_uri: &str, clone_to: &Path) {\n\n // Progress bars\n\n let indexed_status = indicatif::ProgressBar::new(0);\n\n indexed_status.set_style(\n\n indicatif::ProgressStyle::default_bar().template(\"{bar:25} {pos}/{len} objects {msg}\"),\n\n );\n\n // Attempt to clone repository\n\n let mut options = git2::FetchOptions::new();\n\n let mut callbacks = git2::RemoteCallbacks::new();\n\n callbacks\n\n .credentials(|repo_uri, arg2, cred_type| {\n\n println!(\"repo_uri: {}, arg2: {:?}\", repo_uri, arg2);\n\n if cred_type.is_user_pass_plaintext() {\n\n println!(\"Userpass plain\");\n\n git2::Cred::userpass_plaintext(&git_user, &git_pass)\n\n } else if cred_type.is_username() {\n\n println!(\"Username\");\n\n git2::Cred::username(&git_user)\n\n } else {\n\n Err(git2::Error::from_str(&format!(\n", "file_path": "tools/cli/src/git.rs", "rank": 45, "score": 255625.54016730993 }, { "content": "/// Wp-cli ssh shell\n\npub fn wp_cli_ssh(env: &CliEnv, port: u16, server: Option<&ServerConfig>) -> Result<()> {\n\n let conn = SshConn::connect_wp_cli(env, port, server)?;\n\n conn.shell()\n\n}\n\n\n", "file_path": "tools/cli/src/server.rs", "rank": 46, "score": 254262.14090007683 }, { "content": "/// Manually input or edit a server\n\n/// When running `provision`, a config will also be created\n\npub fn add_server(env: &CliEnv) -> io::Result<()> {\n\n // List current servers\n\n let current_files = utils::files_in_dir(&env.config_dirs.servers.0)?;\n\n if current_files.len() > 0 {\n\n println!(\"Current servers:\");\n\n for file in current_files {\n\n println!(\"{}\", file);\n\n }\n\n } else {\n\n println!(\"No existing servers\");\n\n }\n\n\n\n let name = env.get_input(\"Internal server name\", None)?;\n\n let current_config = if has_config(env, &name) {\n\n println!(\"Server config exists for: {}\", &name);\n\n println!(\"Modifying entry.\");\n\n Some(get_config(env, &name)?)\n\n } else {\n\n None\n\n };\n", "file_path": "tools/cli/src/server.rs", "rank": 47, "score": 254021.71113256636 }, { "content": "pub fn conv_err(e: Option<mysql::FromValueError>) -> Result<Option<ColValue>> {\n\n Err(MyLibError::Msg(format!(\"Failed to convert: {:?}\", e)))\n\n}\n\n\n", "file_path": "tools/mysql-utils/src/coltypes/mod.rs", "rank": 48, "score": 249526.41044116026 }, { "content": "pub fn name_email_from_repo(repo: &git2::Repository) -> Result<(String, String), git2::Error> {\n\n let c = repo.config()?;\n\n let name = c.get_string(\"user.name\")?;\n\n let email = c.get_string(\"user.email\")?;\n\n Ok((name, email))\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Fail)]\n\npub enum SetupGitError {\n\n GitError(String),\n\n ApiError(GithubApiError),\n\n CheckRepoError(RepoExistsError),\n\n}\n\nimpl fmt::Display for SetupGitError {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 50, "score": 249044.06426900544 }, { "content": "fn handle_error(err: BlockingError<io::Error>) -> Error {\n\n match err {\n\n BlockingError::Error(err) => err.into(),\n\n BlockingError::Canceled => ErrorInternalServerError(\"Unexpected error\").into(),\n\n }\n\n}\n\n\n\nimpl Stream for ChunkedReadFile {\n\n type Item = Bytes;\n\n type Error = Error;\n\n\n\n fn poll(&mut self) -> Poll<Option<Bytes>, Error> {\n\n if self.fut.is_some() {\n\n return match self.fut.as_mut().unwrap().poll().map_err(handle_error)? {\n\n Async::Ready((file, bytes)) => {\n\n self.fut.take();\n\n self.file = Some(file);\n\n self.offset += bytes.len() as u64;\n\n self.counter += bytes.len() as u64;\n\n Ok(Async::Ready(Some(bytes)))\n", "file_path": "tools/proxy/src/chunked_file.rs", "rank": 51, "score": 246387.97789164627 }, { "content": "pub fn el_str(el: &El) -> &'static str {\n\n match el {\n\n El::Div => \"div\",\n\n El::A => \"a\",\n\n El::H1 => \"h1\",\n\n El::H2 => \"h2\",\n\n El::P => \"p\",\n\n El::H3 => \"h3\",\n\n El::H4 => \"h4\",\n\n El::Html => \"html\",\n\n El::Head => \"head\",\n\n El::Title => \"title\",\n\n El::Body => \"body\",\n\n El::Form => \"form\",\n\n El::Select => \"select\",\n\n El::Opt => \"option\",\n\n El::Ul => \"ul\",\n\n El::Ol => \"ol\",\n\n El::Li => \"li\",\n\n El::Table => \"table\",\n", "file_path": "tools/frontend/src/ast.rs", "rank": 52, "score": 245779.58816618234 }, { "content": "/// Given git username and password, can recreate\n\n/// the workspace (with todos)\n\npub fn clone_workspace(env: &CliEnv) -> io::Result<()> {\n\n let dir_git = git::inspect_git(env.config_dirs.config_root.clone())?;\n\n if dir_git.repo.is_some() {\n\n println!(\"Found existing repo, not proceeding with clone\");\n\n return Ok(());\n\n } else if dir_git.has_files {\n\n println!(\"Found no repo, but existing files. Not proceeding with clone\");\n\n println!(\"Could initialize repository instead\");\n\n return utils::io_err(\"No repo, but files\");\n\n }\n\n\n\n let git_user = env.get_input(\"Git user\", None)?;\n\n let repo_name = env.get_input(\"Repo name\", Some(\"workspace\".into()))?;\n\n let git_pass = env.get_pass(\"Git password\")?;\n\n\n\n let repo_uri = format!(\"https://github.com/{}/{}\", git_user, repo_name);\n\n\n\n Ok(git::clone_repo(\n\n git_user,\n\n git_pass,\n\n &repo_uri,\n\n &env.config_dirs.config_root,\n\n ))\n\n}\n\n\n", "file_path": "tools/cli/src/workspace.rs", "rank": 53, "score": 244097.58223638101 }, { "content": "fn payload_to_bytes(payload: web::Payload) -> impl Future<Item = web::Bytes, Error = Error> {\n\n payload\n\n .map_err(Error::from)\n\n .fold(web::BytesMut::new(), move |mut body, chunk| {\n\n body.extend_from_slice(&chunk);\n\n Ok::<_, Error>(body)\n\n })\n\n .map(|body| body.freeze())\n\n}\n\n\n", "file_path": "tools/proxy/src/proxy.rs", "rank": 55, "score": 240612.36978936745 }, { "content": "fn index_file() -> impl Responder {\n\n let b = match std::fs::read_to_string(\"static/index.html\") {\n\n Ok(s) => s,\n\n Err(_) => \"\".to_string(),\n\n };\n\n HttpResponse::build(actix_web::http::StatusCode::from_u16(200).unwrap())\n\n .header(\"content-type\", \"text/html\")\n\n .body(b)\n\n}\n\n\n", "file_path": "tools/wp-cli-server/src/main.rs", "rank": 56, "score": 240275.19130768647 }, { "content": "pub fn escape_string(s: &str, mut b: String) -> String {\n\n b.push('\"');\n\n for chr in s.chars() {\n\n // Similar to char.escape_default()\n\n match chr {\n\n '\"' => b.push_str(\"\\\\\\\"\"),\n\n // Expecting \\n to be present as well\n\n '\\r' => (),\n\n '\\\\' => b.push_str(\"\\\\\\\\\"),\n\n other => b.push(other)\n\n }\n\n }\n\n b.push('\"');\n\n b\n\n}\n", "file_path": "tools/ser_utils/src/sexpr.rs", "rank": 57, "score": 237736.50824772913 }, { "content": "fn by_enum(e: &Enum, input: &[usize]) -> usize {\n\n use Enum::*;\n\n let another = input[2];\n\n let another1 = input[3];\n\n let another2 = input[4];\n\n let x = another + another1 + another2;\n\n match e {\n\n Case1 => input[1],\n\n Case2 => input[2],\n\n Case3 => input[3],\n\n Case4 => input[4],\n\n Case5(_) => input[5],\n\n Case6 => input[6],\n\n Case7 => input[7],\n\n Case8(_) => input[8],\n\n Case9 => input[9],\n\n Case10 => input[10],\n\n Case11 => input[11],\n\n _ => x / 3\n\n }\n\n}\n\n\n", "file_path": "tools/scratchpad/src/main.rs", "rank": 58, "score": 234817.8645636332 }, { "content": "pub fn json_escape_string(s: &str, mut b: String) -> String {\n\n b.push('\"');\n\n for chr in s.chars() {\n\n // Similar to char.escape_default()\n\n match chr {\n\n '\"' => b.push_str(\"\\\\\\\"\"),\n\n '\\n' => b.push_str(\"\\\\n\"),\n\n '\\t' => b.push_str(\"\\\\t\"),\n\n // Expecting \\n to be present as well\n\n '\\r' => (),\n\n '\\\\' => b.push_str(\"\\\\\\\\\"),\n\n non_uni @ '\\x20' ..= '\\x7e' => b.push(non_uni),\n\n other => {\n\n // from char.escape_unicode();\n\n let c = other as u32;\n\n let msb = 31 - (c | 1).leading_zeros();\n\n let ms_hex_digit = msb / 4;\n\n b.push_str(\"\\\\u\");\n\n // Fill\n\n if ms_hex_digit < 3 {\n", "file_path": "tools/ser_utils/src/json.rs", "rank": 59, "score": 234705.55382265412 }, { "content": "pub fn inspect_git(dir: PathBuf) -> io::Result<InspectGit> {\n\n let (has_dir, has_files, repo, origin_url) = if !dir.is_dir() {\n\n // Dir does not yet exist\n\n (false, false, None, None)\n\n } else if dir.is_file() {\n\n return Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"Given directory is a file\",\n\n ));\n\n } else {\n\n println!(\"Directory exists\");\n\n let has_files = match crate::utils::entries_in_dir(&dir) {\n\n Ok(entries) => entries.len() > 0,\n\n Err(err) => return Err(err),\n\n };\n\n let mut git_dir = dir.clone();\n\n git_dir.push(\".git\");\n\n if git_dir.is_dir() {\n\n println!(\"Git repo found\");\n\n match git2::Repository::open(&dir) {\n", "file_path": "tools/cli/src/git.rs", "rank": 60, "score": 234395.92611139303 }, { "content": "pub fn activate_plugin(cli_conn: &SshConn, plugin: &str) -> Result<()> {\n\n match cli_conn.exec(format!(\"wp plugin activate {}\", plugin)) {\n\n Ok(_) => {\n\n println!(\"Plugin activated: {}\", plugin);\n\n Ok(())\n\n }\n\n Err(e) => Err(format_err!(\"Couldn't activate: {}, {:?}\", plugin, e)),\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/wp.rs", "rank": 61, "score": 233807.89904965443 }, { "content": "pub fn get_config(env: &CliEnv) -> io::Result<AwsConfig> {\n\n let config_file = get_config_file(env);\n\n let json_file = std::fs::File::open(config_file)?;\n\n let buf_reader = io::BufReader::new(json_file);\n\n let config = serde_json::from_reader::<_, AwsConfig>(buf_reader)?;\n\n Ok(config)\n\n}\n\n\n", "file_path": "tools/cli/src/aws.rs", "rank": 62, "score": 233704.97709732264 }, { "content": "pub fn void_str(el: &Void) -> &'static str {\n\n match el {\n\n Void::Img => \"img\",\n\n Void::Input => \"input\",\n\n Void::Br => \"br\",\n\n Void::Link => \"link\",\n\n Void::Meta => \"meta\",\n\n Void::Doctype => \"doctype\",\n\n Void::Source => \"source\",\n\n Void::Embed => \"embed\",\n\n Void::Param => \"param\",\n\n Void::Command => \"command\",\n\n Void::Keygen => \"keygen\",\n\n Void::Hr => \"hr\",\n\n Void::Area => \"area\",\n\n Void::Base => \"base\",\n\n Void::Col => \"col\",\n\n Void::Track => \"track\",\n\n Void::Wbr => \"wbr\",\n\n }\n\n}\n", "file_path": "tools/frontend/src/ast.rs", "rank": 63, "score": 229865.30922125472 }, { "content": "pub fn get_accounts(env: &CliEnv) -> io::Result<Vec<String>> {\n\n utils::files_in_dir(&env.config_dirs.git_accounts.0)\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 64, "score": 229618.76979106787 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\nfn set_pem_perms(pem_file: &std::path::Path) -> io::Result<()> {\n\n use std::fs::Permissions;\n\n let metadata = pem_file.metadata()?;\n\n let mut permissions = metadata.permissions();\n\n permissions.set_readonly(true);\n\n std::fs::set_permissions(pem_file, permissions)\n\n}\n\n\n", "file_path": "tools/cli/src/aws.rs", "rank": 65, "score": 229344.8520995821 }, { "content": "pub fn parse_git_uri(repo_uri: &str) -> Result<GitUriParts, String> {\n\n let repo_uri = match repo_uri.parse::<Uri>() {\n\n Ok(uri) => uri,\n\n Err(_) => {\n\n return Err(\"Could not parse uri\".into());\n\n }\n\n };\n\n let host = match repo_uri.host() {\n\n Some(host) => {\n\n if host != \"github.com\" {\n\n return Err(\"Host not supported\".into());\n\n } else {\n\n host\n\n }\n\n }\n\n None => return Err(\"Host not found\".into()),\n\n };\n\n let path = Path::new(repo_uri.path());\n\n let path_names = path\n\n .components()\n", "file_path": "tools/cli/src/git.rs", "rank": 66, "score": 228399.71826515108 }, { "content": "/// Parses a list of children until closing tag or\n\n/// end of bytes\n\n/// Detects node type\n\npub fn parse_children(mut s: &[u8], mut nodes: Vec<Node>) -> Result<(&[u8], Vec<Node>)> {\n\n // Loop and collect elements\n\n loop {\n\n s = strip_space(s);\n\n let len = s.len();\n\n if len == 0 {\n\n return Ok((s, nodes));\n\n }\n\n // If '<' and tag possible (min 3 chars)\n\n if s.chr() == LBRACKET && len >= 3 {\n\n s = &s[1..];\n\n // There may be spaces here, though the likely\n\n // case is ident or /\n\n if is_space(s.chr()) {\n\n s = strip_space(s);\n\n s.len_gt(0)?;\n\n }\n\n if s.is_uc() {\n\n // Expecting Component\n\n // todo: Consider lib.my.comps.Comp notation\n", "file_path": "tools/frontend/src/parser.rs", "rank": 67, "score": 226538.32292996685 }, { "content": "fn ws_index(r: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {\n\n println!(\"r: {:?}\", r);\n\n let res = ws::start(MyWebSocket::new(), &r, stream);\n\n println!(\"{:?}\", res.as_ref().unwrap());\n\n res\n\n}\n\n\n", "file_path": "tools/wp-cli-server/src/main.rs", "rank": 68, "score": 225540.1301927312 }, { "content": "fn to_io_err<E: std::fmt::Debug>(rusoto_error: rusoto_core::RusotoError<E>) -> io::Error {\n\n utils::io_error(format!(\"Rusoto error: {:?}\", rusoto_error))\n\n}\n\n\n\n// Todo: Possibly os could be unix? How will it work for os x\n", "file_path": "tools/cli/src/aws.rs", "rank": 69, "score": 225482.1916491658 }, { "content": "pub fn tokens_from_file<P: AsRef<Path>>(path: P) -> TokenStream {\n\n use std::fs::File;\n\n use std::io::Read;\n\n use std::str::FromStr;\n\n let mut source_file = File::open(path).unwrap();\n\n let mut source = String::new();\n\n source_file.read_to_string(&mut source).unwrap();\n\n /*\n\n let mut b = String::new();\n\n for _ in 0..3000 {\n\n b.push_str(&source);\n\n }\n\n let before = std::time::Instant::now();*/\n\n let tokens = proc_macro2::TokenStream::from_str(&source).unwrap();\n\n //times(\"tokens\", before.elapsed());\n\n //println!(\"{:#?}\", tokens);\n\n tokens\n\n}\n\n\n\n\n", "file_path": "tools/rusc/src/main.rs", "rank": 70, "score": 224528.692406731 }, { "content": "pub fn uri_to_string(uri: http::uri::Uri, with_scheme: bool) -> Result<String, ()> {\n\n if with_scheme {\n\n match (\n\n uri.scheme_part().map(|s| s.as_str()),\n\n uri.host(),\n\n uri.port_u16(),\n\n ) {\n\n (Some(scheme), Some(host), None) => Ok(String::from(scheme) + \"://\" + host),\n\n (Some(scheme), Some(host), Some(port)) => {\n\n Ok(String::from(scheme) + \"://\" + host + \":\" + &port.to_string())\n\n }\n\n _ => Err(()),\n\n }\n\n } else {\n\n match (uri.host(), uri.port_u16()) {\n\n (Some(host), None) => Ok(String::from(host)),\n\n (Some(host), Some(port)) => Ok(String::from(host) + \":\" + &port.to_string()),\n\n _ => Err(()),\n\n }\n\n }\n\n}\n", "file_path": "tools/proxy/src/util.rs", "rank": 71, "score": 219985.37630882964 }, { "content": "pub fn make_origin_url(config: &GitConfig, repo_uri: &str) -> Result<String, String> {\n\n // Todo: This is not good security\n\n // Would like some credientials helper\n\n // or other solution\n\n let parts = parse_git_uri(repo_uri)?;\n\n Ok(format!(\n\n \"https://{}:{}@{}/{}/{}\",\n\n config.user, config.token, parts.host, parts.owner, parts.repo_name\n\n ))\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 73, "score": 217978.2630003401 }, { "content": "fn with_project<F, T>(env: &CliEnv, f: F) -> Result<T, failure::Error>\n\nwhere\n\n F: FnOnce(project::ProjectConfig) -> Result<T, failure::Error>,\n\n{\n\n match project::resolve_current_project_interactive(&env) {\n\n Ok(project) => f(project),\n\n Err(e) => {\n\n println!(\"Could not resolve project: {:?}\", e);\n\n std::process::exit(1);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/cli_app.rs", "rank": 74, "score": 217091.82865451742 }, { "content": "fn with_server<F, T>(env: &CliEnv, f: F) -> Result<T, failure::Error>\n\nwhere\n\n F: FnOnce(server::ServerConfig) -> Result<T, failure::Error>,\n\n{\n\n match server::select_server(env) {\n\n Ok(server) => f(server),\n\n Err(e) => {\n\n eprintln!(\"Error selecting server: {:?}\", e);\n\n std::process::exit(1);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tools/cli/src/cli_app.rs", "rank": 75, "score": 216611.84562530846 }, { "content": "pub fn set_account_config(config: &GitConfig, repo: &git2::Repository) -> Result<(), git2::Error> {\n\n let mut c = repo.config()?;\n\n c.open_level(git2::ConfigLevel::Local)?;\n\n c.set_str(\"user.name\", &config.user)?;\n\n c.set_str(\"user.email\", &config.email)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/cli/src/git.rs", "rank": 76, "score": 214842.52053623236 }, { "content": "#[inline]\n\npub fn dev_cmd(\n\n env: &CliEnv,\n\n current_process: utils::CurrentProcess,\n\n project: ProjectConfig,\n\n user_args: Vec<String>,\n\n) -> io::Result<utils::CurrentProcess> {\n\n dev_cmds(env, current_process, project, vec![user_args])\n\n}\n\n\n", "file_path": "tools/cli/src/docker.rs", "rank": 77, "score": 213860.30093532984 }, { "content": "pub fn commit(repo: &git2::Repository, tree: git2::Tree, message: &str) -> io::Result<()> {\n\n // Commit\n\n let signature = match name_email_from_repo(&repo) {\n\n Ok((conf_name, conf_email)) => match git2::Signature::now(&conf_name, &conf_email) {\n\n Ok(signature) => signature,\n\n Err(e) => return utils::io_err(format!(\"Error creating signature: {:?}\", e)),\n\n },\n\n Err(e) => {\n\n eprintln!(\"Failed getting name and email from config: {:?}\", e);\n\n return utils::io_err(\"Failed getting name and email from config\");\n\n }\n\n };\n\n // Get parent commit(s)\n\n // https://stackoverflow.com/questions/27672722/libgit2-commit-example\n\n let head_commit = match repo.head() {\n\n Ok(head) => match head.peel_to_commit() {\n\n Ok(commit) => commit,\n\n Err(e) => return utils::io_err(format!(\"Failed getting commit of head: {:?}\", e)),\n\n },\n\n Err(e) => return utils::io_err(format!(\"Error getting head: {:?}\", e)),\n", "file_path": "tools/cli/src/git.rs", "rank": 78, "score": 210683.74596235453 }, { "content": "// todo: Could run this automatically after config files have changed\n\n// when repo is initialized, could propose to add if not\n\npub fn push_workspace(env: &CliEnv) -> io::Result<()> {\n\n let dir_git = git::inspect_git(env.config_dirs.config_root.clone())?;\n\n let repo = match dir_git.repo {\n\n Some(repo) => {\n\n println!(\"Found repo\");\n\n repo\n\n }\n\n None => {\n\n // todo: propose run init\n\n println!(\"Please try workspace init-git, or setup repository manually\");\n\n return utils::io_err(\"No repo\");\n\n }\n\n };\n\n // todo: Possibly not necessary, could test,\n\n // also good to err on side of doing it\n\n std::env::set_current_dir(&dir_git.dir)?;\n\n let tree = git::add_all(&repo)?;\n\n let default_msg = format!(\"Workspace commit: {}\", utils::now_formatted());\n\n let message = env.get_input(\"Message\", Some(default_msg))?;\n\n git::commit(&repo, tree, &message)?;\n\n git::push_origin_master(&repo)?;\n\n println!(\"Commit and push to origin successful\");\n\n Ok(())\n\n}\n", "file_path": "tools/cli/src/workspace.rs", "rank": 79, "score": 209528.34060695302 }, { "content": "/// Add or modify git account\n\npub fn add_user(env: &CliEnv) -> io::Result<()> {\n\n // Todo: It would be nice to allow \"proxy\" git communications\n\n // where the project participants is administered\n\n\n\n // List current accounts\n\n let current_files = utils::files_in_dir(&env.config_dirs.git_accounts.0)?;\n\n if current_files.len() > 0 {\n\n println!(\"Current accounts:\");\n\n for file in current_files {\n\n println!(\"{}\", file);\n\n }\n\n } else {\n\n println!(\"No existing accounts\");\n\n }\n\n\n\n let user = env.get_input(\"Git user\", None)?;\n\n let current_config = if has_config(env, &user) {\n\n println!(\"Account config exists for: {}\", &user);\n\n println!(\"Modifying entry.\");\n\n Some(get_config(env, &user)?)\n", "file_path": "tools/cli/src/git.rs", "rank": 80, "score": 209524.09107511013 }, { "content": "pub fn aws_config(env: &CliEnv) -> io::Result<()> {\n\n let config_file = get_config_file(env);\n\n let current_config = if config_file.is_file() {\n\n Some(get_config(env)?)\n\n } else {\n\n None\n\n };\n\n match &current_config {\n\n Some(_current_config) => {\n\n println!(\"Config exists, modifying\");\n\n }\n\n None => {\n\n println!(\"No current config, creating\");\n\n println!(\"Expecting IAM user credentials with ec2 permissions\");\n\n }\n\n }\n\n let key = env.get_input(\"Key\", current_config.as_ref().map(|c| c.key.clone()))?;\n\n let secret = env.get_input(\"Secret\", current_config.as_ref().map(|c| c.key.clone()))?;\n\n let config = AwsConfig { key, secret };\n\n let content_str = match serde_json::to_string_pretty(&config) {\n", "file_path": "tools/cli/src/aws.rs", "rank": 81, "score": 209524.09107511013 }, { "content": "pub fn create_ec2_client(env: &CliEnv) -> io::Result<Ec2Client> {\n\n let aws_config = get_config(env)?;\n\n std::env::set_var(\"AWS_ACCESS_KEY_ID\", aws_config.key);\n\n std::env::set_var(\"AWS_SECRET_ACCESS_KEY\", aws_config.secret);\n\n /*\n\n let credentials = rusoto_credential::AwsCredentials::new(\n\n aws_config.key,\n\n aws_config.secret,\n\n None,\n\n None\n\n );*/\n\n Ok(Ec2Client::new(Region::EuNorth1))\n\n}\n\n\n\nuse server::ElasticIp;\n\n\n", "file_path": "tools/cli/src/aws.rs", "rank": 82, "score": 198638.02131431483 }, { "content": "fn write_cache_file(url_path: String, body: &[u8], cache_dir: String) -> io::Result<String> {\n\n let mut hasher = DefaultHasher::new();\n\n url_path.hash(&mut hasher);\n\n let filename = format!(\"{}/{:x}\", &cache_dir, &hasher.finish());\n\n let mut file = fs::File::create(&filename)?;\n\n file.write_all(body)?;\n\n Ok(filename)\n\n}\n\n\n", "file_path": "tools/proxy/src/proxy.rs", "rank": 83, "score": 194336.06333603396 }, { "content": "#[inline]\n\npub fn is_space(c: u8) -> bool {\n\n c == SPACE || c == TAB || c == NL || c == CR\n\n}\n\n\n\n/// Check if first byte is in given range\n\n/// Assumes len() > 0\n", "file_path": "tools/frontend/src/parse_utils.rs", "rank": 84, "score": 192865.66840137943 }, { "content": "#[inline]\n\npub fn is_alphanum(s: u8) -> bool {\n\n // Checking lowercase, then numbers\n\n in_range(s, 97, 122) || in_range(s, 48, 57) || in_range(s, 65, 90)\n\n}\n\n\n", "file_path": "tools/frontend/src/parse_utils.rs", "rank": 85, "score": 192865.66840137943 }, { "content": "#[inline]\n\npub fn is_numeric(s: u8) -> bool {\n\n in_range(s, 48, 57)\n\n}\n\n\n", "file_path": "tools/frontend/src/parse_utils.rs", "rank": 86, "score": 192865.66840137943 }, { "content": "#[inline]\n\npub fn is_alpha(s: u8) -> bool {\n\n in_range(s, 97, 122) || in_range(s, 65, 90)\n\n}\n\n\n", "file_path": "tools/frontend/src/parse_utils.rs", "rank": 87, "score": 192865.66840137943 }, { "content": "// todo: it would be nice with \"plugin\" architecture for subsystems\n\n/// Copy project files to container\n\npub fn sync_files_to_prod(cli_conn: &SshConn, site_local: &WpLocalSiteData) -> Result<()> {\n\n let sftp = cli_conn.sftp()?;\n\n // Make sync set\n\n // todo: This barely works, but it would be\n\n // be nice to combine sync_sets for example\n\n let mut sync_set = SyncSet::new(\n\n site_local.project_dir.clone(),\n\n PathBuf::from(\"/var/www/html/wp-content\"),\n\n );\n\n for (_name, plugin) in &site_local.plugins {\n\n sync_set.resolve(&plugin.paths.full_path.0, &sftp, false)?;\n\n }\n\n for (_name, theme) in &site_local.themes {\n\n sync_set.resolve(&theme.paths.full_path.0, &sftp, false)?;\n\n }\n\n sync_set.sync_zipped(cli_conn, &sftp)?;\n\n // Copy to docker volume\n\n // In this case, plugins and themes folders should be present,\n\n // but note that `cp` does not create parent folders\n\n // Specifying `-` for either source or destination will\n\n // accept a tar file from stdin, or export one to stdout\n\n // Using a tar file is a trick to handling file owner.\n\n Ok(())\n\n}\n\n\n", "file_path": "tools/cli/src/wp.rs", "rank": 88, "score": 192307.42485785257 }, { "content": "#[inline]\n\npub fn is_ident_char(c: u8) -> bool {\n\n is_alphanum(c) || c == DASH\n\n}\n\n\n\n/// Small helper to create a string with some\n\n/// initial content with a given capacity\n", "file_path": "tools/frontend/src/parse_utils.rs", "rank": 89, "score": 190263.6944628268 }, { "content": "#[derive(Debug)]\n\nstruct Fn {\n\n fn_token: Token![fn],\n\n ident: Ident,\n\n parens: token::Paren,\n\n args: Punctuated<Arg, Token![,]>,\n\n block: syn::Block\n\n}\n\nimpl Parse for Fn {\n\n fn parse(input: ParseStream) -> Result<Self> {\n\n let content;\n\n Ok(Fn {\n\n fn_token: input.parse()?,\n\n ident: input.parse()?,\n\n parens: parenthesized!(content in input),\n\n args: content.parse_terminated(Arg::parse)?,\n\n block: input.parse()?\n\n })\n\n }\n\n}\n", "file_path": "tools/rusc/src/item.rs", "rank": 90, "score": 188706.7247266416 }, { "content": "fn times(msg: &str, d: std::time::Duration) {\n\n println!(\n\n \"{}: {}\",\n\n msg,\n\n (d.as_secs() as f32) + (d.as_nanos() as f32) / (1_000_000_000 as f32)\n\n );\n\n}", "file_path": "tools/rusc/src/main.rs", "rank": 91, "score": 187224.18024056702 }, { "content": "fn times(msg: &str, d: std::time::Duration) {\n\n println!(\"{}: {}\", msg, (d.as_secs() as f32) + (d.as_nanos() as f32) / (1_000_000_000 as f32));\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use test::Bencher;\n\n}", "file_path": "tools/scratchpad/src/main.rs", "rank": 92, "score": 187224.18024056702 }, { "content": "fn times(msg: &str, d: std::time::Duration) {\n\n println!(\n\n \"{}: {}\",\n\n msg,\n\n (d.as_secs() as f32) + (d.as_nanos() as f32) / (1_000_000_000 as f32)\n\n );\n\n}\n\n\n", "file_path": "tools/frontend/src/main.rs", "rank": 93, "score": 187224.18024056702 }, { "content": "fn times(msg: &str, d: std::time::Duration) {\n\n println!(\"PRX: {}: {}\", msg, (d.as_secs() as f32) + (d.as_nanos() as f32) / (1_000_000_000 as f32));\n\n}\n\nimpl<W: io::Write> MysqlShim<W> for Backend {\n\n type Error = io::Error;\n\n\n\n fn on_prepare(&mut self, query: &str, info: StatementMetaWriter<W>) -> io::Result<()> {\n\n println!(\"Prepare query: {}\", query);\n\n info.reply(10, &[], &[])\n\n }\n\n\n\n fn on_execute(\n\n &mut self,\n\n id: u32,\n\n parser: ParamParser,\n\n results: QueryResultWriter<W>,\n\n ) -> io::Result<()> {\n\n println!(\"On execute\");\n\n results.completed(0, 0)\n\n }\n", "file_path": "tools/mysql-proxy/src/main.rs", "rank": 94, "score": 184722.59142991083 }, { "content": "fn init_project_config(env: &CliEnv) -> io::Result<(ProjectConfig, git::InspectGit)> {\n\n let name = env.get_input(\"Project name\", None)?;\n\n let current_config = if has_config(env, &name) {\n\n println!(\"Project config exists for: {}\", &name);\n\n println!(\"Modifying entry.\");\n\n Some(get_config(env, &name)?)\n\n } else {\n\n println!(\n\n \"Project config does not exist, collecting data for: {}\",\n\n &name\n\n );\n\n None\n\n };\n\n // Git account\n\n let git_account =\n\n git::select_account(env, current_config.as_ref().map(|c| c.git_user.to_owned()))?;\n\n let git_user = git_account.user.clone();\n\n // Git repo\n\n let project_git = git::inspect_git(project_dir(env, &name))?;\n\n let git_repo_uri = match project_git.origin_url.as_ref() {\n", "file_path": "tools/cli/src/project.rs", "rank": 95, "score": 183339.2058251301 }, { "content": "fn times(msg: &str, d: std::time::Duration) {\n\n println!(\n\n \"{}: {}\",\n\n msg,\n\n (d.as_secs() as f32) + (d.as_nanos() as f32) / (1_000_000_000 as f32)\n\n );\n\n}\n\n\n", "file_path": "tools/mysql-utils/examples/json_tables.rs", "rank": 96, "score": 182335.70490180294 }, { "content": "fn times(msg: &str, d: std::time::Duration) {\n\n println!(\n\n \"{}: {}\",\n\n msg,\n\n (d.as_secs() as f32) + (d.as_nanos() as f32) / (1_000_000_000 as f32)\n\n );\n\n}\n\n\n", "file_path": "tools/mysql-utils/examples/sexpr_tables.rs", "rank": 97, "score": 182335.70490180294 }, { "content": "/// Parses a text node\n\npub fn parse_text(mut s: &[u8]) -> (&[u8], Node) {\n\n let mut b = String::with_capacity(32);\n\n while let Some((size, chr)) = next_utf8(s) {\n\n // Break on '<'\n\n if chr == '<' {\n\n break;\n\n }\n\n b.push(chr);\n\n s = &s[size..];\n\n }\n\n // I think it makes sense to trim backwards here\n\n // for space efficiency and consistency with\n\n // trimmed left\n\n let mut blank_size = 0;\n\n for c in b.chars().rev() {\n\n if !c.is_ascii() {\n\n break;\n\n }\n\n match c as u8 {\n\n SPACE => blank_size += 1,\n", "file_path": "tools/frontend/src/parser.rs", "rank": 98, "score": 181018.304470532 } ]
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 EMPHASIS_UNDERSCORE.is_match(text) {\n\n let caps = EMPHASIS_UNDERSCORE.captures(text).unwrap();\n\n let t = caps.name(\"text\").unwrap().as_str();\n\n return Some((Emphasis(parse_spans(t)), t.len() + 2));\n\n } else if EMPHASIS_STAR.is_match(text) {\n\n let caps = EMPHASIS_STAR.captures(text).unwrap();\n\n let t = caps.name(\"text\").unwrap().as_str();\n\n return Some((Emphasis(parse_spans(t)), t.len() + 2));\n\n }\n\n None\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n", "file_path": "src/parser/span/emphasis.rs", "rank": 0, "score": 224487.92402780958 }, { "content": "pub fn parse_strong(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n static ref STRONG_UNDERSCORE: Regex = Regex::new(r\"^__(?P<text>.+?)__\").unwrap();\n\n static ref STRONG_STAR: Regex = Regex::new(r\"^\\*\\*(?P<text>.+?)\\*\\*\").unwrap();\n\n }\n\n\n\n if STRONG_UNDERSCORE.is_match(text) {\n\n let caps = STRONG_UNDERSCORE.captures(text).unwrap();\n\n let t = caps.name(\"text\").unwrap().as_str();\n\n return Some((Strong(parse_spans(t)), t.len() + 4));\n\n } else if STRONG_STAR.is_match(text) {\n\n let caps = STRONG_STAR.captures(text).unwrap();\n\n let t = caps.name(\"text\").unwrap().as_str();\n\n return Some((Strong(parse_spans(t)), t.len() + 4));\n\n }\n\n None\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n", "file_path": "src/parser/span/strong.rs", "rank": 1, "score": 224456.68157401375 }, { "content": "pub fn parse_image(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n static ref IMAGE: Regex =\n\n Regex::new(\"^!\\\\[(?P<text>.*?)\\\\]\\\\((?P<url>.*?)(?:\\\\s\\\"(?P<title>.*?)\\\")?\\\\)\")\n\n .unwrap();\n\n }\n\n\n\n if IMAGE.is_match(text) {\n\n let caps = IMAGE.captures(text).unwrap();\n\n let text = if let Some(mat) = caps.name(\"text\") {\n\n mat.as_str().to_owned()\n\n } else {\n\n \"\".to_owned()\n\n };\n\n let url = if let Some(mat) = caps.name(\"url\") {\n\n mat.as_str().to_owned()\n\n } else {\n\n \"\".to_owned()\n\n };\n\n let title = if let Some(mat) = caps.name(\"title\") {\n", "file_path": "src/parser/span/image.rs", "rank": 2, "score": 224394.20746108075 }, { "content": "pub fn parse_code(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n static ref CODE_SINGLE: Regex = Regex::new(r\"^`(?P<text>.+?)`\").unwrap();\n\n static ref CODE_DOUBLE: Regex = Regex::new(r\"^``(?P<text>.+?)``\").unwrap();\n\n }\n\n\n\n if CODE_DOUBLE.is_match(text) {\n\n let caps = CODE_DOUBLE.captures(text).unwrap();\n\n let t = caps.name(\"text\").unwrap().as_str();\n\n return Some((Code(t.to_owned()), t.len() + 4));\n\n } else if CODE_SINGLE.is_match(text) {\n\n let caps = CODE_SINGLE.captures(text).unwrap();\n\n let t = caps.name(\"text\").unwrap().as_str();\n\n return Some((Code(t.to_owned()), t.len() + 2));\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/parser/span/code.rs", "rank": 3, "score": 224107.12981126027 }, { "content": "pub fn parse_link(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n // This is the second part of the regex, that matches the reference or url and title.\n\n static ref LINK_ATTR_STR: &'static str = \"(?:\\\\s*\\\\[(?P<ref>.*)\\\\]|\\\\((?P<url>.*?)(?:\\\\s*\\\"(?P<title>.*?)\\\")?\\\\s*\\\\))?\";\n\n // This regex does not sufficiently cover the edge case where there are brackets (e.g. for\n\n // images) inside a link text. It's sufficient for identifying links anyway, we'll properly\n\n // figure out the braces below.\n\n static ref LINK_STR: String = \"^\\\\[(?P<text>.*?)\\\\]\".to_owned() + &LINK_ATTR_STR;\n\n static ref LINK: Regex =\n\n Regex::new(&LINK_STR).unwrap();\n\n static ref LINK_ATTR: Regex =\n\n Regex::new(&(\"^\".to_owned() + &LINK_ATTR_STR)).unwrap();\n\n }\n\n\n\n if LINK.is_match(text) {\n\n let mut chars = text.chars();\n\n let mut content = String::new();\n\n\n\n // This tracks open vs. closed braces, it starts at 1 because we have an initial\n\n // open brace, we want to reach 0 to find the closing brace for the link.\n", "file_path": "src/parser/span/link.rs", "rank": 4, "score": 223632.9418841487 }, { "content": "pub fn parse_break(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n static ref BR: Regex = Regex::new(r\"^ {2}$\").unwrap();\n\n }\n\n\n\n if BR.is_match(text) {\n\n return Some((Break, 2));\n\n }\n\n None\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::parse_break;\n\n use parser::Span::Break;\n\n\n\n #[test]\n\n fn finds_breaks() {\n\n assert_eq!(parse_break(\" \"), Some((Break, 2)));\n\n }\n\n\n\n #[test]\n\n fn no_false_positives() {\n\n assert_eq!(parse_break(\"this is a test \"), None);\n\n assert_eq!(parse_break(\" \"), None);\n\n assert_eq!(parse_break(\" a\"), None);\n\n }\n\n}\n", "file_path": "src/parser/span/br.rs", "rank": 5, "score": 215502.26390176607 }, { "content": "/// Converts a Markdown string to HTML\n\npub fn to_html(text: &str) -> String {\n\n let result = parser::parse(text);\n\n html::to_html(&result)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 6, "score": 214845.5069381763 }, { "content": "pub fn parse_spans(text: &str) -> Vec<Span> {\n\n let mut tokens = vec![];\n\n let mut t = String::new();\n\n let mut i = 0;\n\n while i < text.len() {\n\n match parse_span(&text[i..text.len()]) {\n\n Some((span, consumed_chars)) => {\n\n if !t.is_empty() {\n\n // if this text is on the very left\n\n // trim the left whitespace\n\n if tokens.is_empty() {\n\n t = t.trim_start().to_owned()\n\n }\n\n tokens.push(Text(t));\n\n }\n\n tokens.push(span);\n\n t = String::new();\n\n i += consumed_chars;\n\n }\n\n None => {\n", "file_path": "src/parser/span/mod.rs", "rank": 9, "score": 205203.7272268774 }, { "content": "/// Converts a Markdown string to a tokenset of Markdown items\n\npub fn tokenize(text: &str) -> Vec<Block> {\n\n parser::parse(text)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 10, "score": 203757.54748479964 }, { "content": "pub fn parse_code_block(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref CODE_BLOCK_SPACES: Regex = Regex::new(r\"^ {4}\").unwrap();\n\n static ref CODE_BLOCK_TABS: Regex = Regex::new(r\"^\\t\").unwrap();\n\n static ref CODE_BLOCK_BACKTICKS: Regex = Regex::new(r\"^```\").unwrap();\n\n }\n\n\n\n let mut content = String::new();\n\n let mut lang: Option<String> = None;\n\n let mut line_number = 0;\n\n let mut backtick_opened = false;\n\n let mut backtick_closed = false;\n\n\n\n for line in lines {\n\n if !backtick_opened && CODE_BLOCK_SPACES.is_match(line) {\n\n if line_number > 0 && !content.is_empty() {\n\n content.push('\\n');\n\n }\n\n // remove top-level spaces\n\n content.push_str(&line[4..line.len()]);\n", "file_path": "src/parser/block/code_block.rs", "rank": 14, "score": 183210.76886406753 }, { "content": "pub fn parse_hr(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref HORIZONTAL_RULE: Regex = Regex::new(r\"^(===+)$|^(---+)$\").unwrap();\n\n }\n\n\n\n if HORIZONTAL_RULE.is_match(lines[0]) {\n\n return Some((Hr, 1));\n\n }\n\n None\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::parse_hr;\n\n use parser::Block::Hr;\n\n\n\n #[test]\n\n fn finds_hr() {\n\n assert_eq!(parse_hr(&vec![\"-------\"]).unwrap(), (Hr, 1));\n\n assert_eq!(parse_hr(&vec![\"---\"]).unwrap(), (Hr, 1));\n", "file_path": "src/parser/block/hr.rs", "rank": 15, "score": 182286.0577069986 }, { "content": "pub fn parse_blockquote(lines: &[&str]) -> Option<(Block, usize)> {\n\n // if the first char isnt a blockquote don't even bother\n\n if lines[0].is_empty() || !lines[0].starts_with(\">\") {\n\n return None;\n\n }\n\n\n\n // the content of the blockquote\n\n let mut content = String::new();\n\n\n\n // counts the number of parsed lines to return\n\n let mut i = 0;\n\n\n\n // captures if the previous item was a newline\n\n // meaning the blockquote ends next if it's not\n\n // explicitly continued with a >\n\n let mut prev_newline = false;\n\n\n\n for line in lines {\n\n // stop parsing on two newlines or if the paragraph after\n\n // a newline isn't started with a >\n", "file_path": "src/parser/block/blockquote.rs", "rank": 16, "score": 182160.90919368694 }, { "content": "pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref HORIZONTAL_RULE_1: Regex = Regex::new(r\"^===+$\").unwrap();\n\n static ref HORIZONTAL_RULE_2: Regex = Regex::new(r\"^---+$\").unwrap();\n\n }\n\n\n\n if lines.len() > 1 && !lines[0].is_empty() {\n\n if HORIZONTAL_RULE_1.is_match(lines[1]) {\n\n return Some((Header(parse_spans(lines[0]), 1), 2));\n\n } else if HORIZONTAL_RULE_2.is_match(lines[1]) {\n\n return Some((Header(parse_spans(lines[0]), 2), 2));\n\n }\n\n }\n\n None\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::parse_setext_header;\n\n use parser::Block::Header;\n", "file_path": "src/parser/block/setext_header.rs", "rank": 19, "score": 175736.2939548114 }, { "content": "pub fn parse_atx_header(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref ATX_HEADER_RE: Regex =\n\n Regex::new(r\"^(?P<level>#{1,6})\\s(?P<text>.*?)(?:\\s#*)?$\").unwrap();\n\n }\n\n\n\n if ATX_HEADER_RE.is_match(lines[0]) {\n\n let caps = ATX_HEADER_RE.captures(lines[0]).unwrap();\n\n return Some((\n\n Header(\n\n parse_spans(caps.name(\"text\").unwrap().as_str()),\n\n caps.name(\"level\").unwrap().as_str().len(),\n\n ),\n\n 1,\n\n ));\n\n }\n\n None\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/parser/block/atx_header.rs", "rank": 20, "score": 175736.29395481138 }, { "content": "pub fn parse_link_reference(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref LINK_REFERENCE_SINGLE_LINE: Regex = Regex::new(\"^\\\\s*\\\\[(?P<id>[^\\\\[\\\\]]+)\\\\]:\\\\s*(?P<url>\\\\S+)(?:\\\\s+(?:'(?P<title1>.*)'|\\\"(?P<title2>.*)\\\"|\\\\((?P<title3>.*?)\\\\)))?\\n?\").unwrap();\n\n static ref LINK_REFERENCE_FIRST_LINE: Regex = Regex::new(\"^\\\\s*\\\\[(?P<id>[^\\\\[\\\\]]+)\\\\]:\").unwrap();\n\n static ref LINK_REFERENCE_SECOND_LINE: Regex = Regex::new(\"\\\\s*(?P<url>\\\\S+)(?:\\\\s+(?:'(?P<title1>.*)'|\\\"(?P<title2>.*)\\\"|\\\\((?P<title3>.*?)\\\\)))?\\n?\").unwrap();\n\n }\n\n\n\n if LINK_REFERENCE_SINGLE_LINE.is_match(lines[0]) {\n\n let caps = LINK_REFERENCE_SINGLE_LINE.captures(lines[0]).unwrap();\n\n return Some((\n\n LinkReference(\n\n caps.name(\"id\").unwrap().as_str().to_lowercase(),\n\n caps.name(\"url\").unwrap().as_str().to_owned(),\n\n caps.name(\"title1\")\n\n .or_else(|| caps.name(\"title2\"))\n\n .or_else(|| caps.name(\"title3\"))\n\n .map(|s| s.as_str().to_owned()),\n\n ),\n\n 1,\n\n ));\n", "file_path": "src/parser/block/link_reference.rs", "rank": 21, "score": 175127.89135009988 }, { "content": "fn parse_span(text: &str) -> Option<(Span, usize)> {\n\n pipe_opt!(\n\n text\n\n => parse_escape\n\n => parse_code\n\n => parse_strong\n\n => parse_emphasis\n\n => parse_break\n\n => parse_image\n\n => parse_link\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use parser::span::parse_spans;\n\n use parser::Span::{Break, Code, Emphasis, Image, Link, Literal, Strong, Text};\n\n use std::str;\n\n\n\n #[test]\n", "file_path": "src/parser/span/mod.rs", "rank": 24, "score": 168387.21571241913 }, { "content": "fn parse_escape(text: &str) -> Option<(Span, usize)> {\n\n let mut chars = text.chars();\n\n if let Some('\\\\') = chars.next() {\n\n return match chars.next() {\n\n Some(x @ '\\\\') | Some(x @ '`') | Some(x @ '*') | Some(x @ '_') | Some(x @ '{')\n\n | Some(x @ '}') | Some(x @ '[') | Some(x @ ']') | Some(x @ '(') | Some(x @ ')')\n\n | Some(x @ '#') | Some(x @ '+') | Some(x @ '-') | Some(x @ '.') | Some(x @ '!') => {\n\n Some((Literal(x), 2))\n\n }\n\n _ => None,\n\n };\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/parser/span/mod.rs", "rank": 25, "score": 163884.597587356 }, { "content": "pub fn parse_blocks(md: &str) -> Vec<Block> {\n\n let mut blocks = vec![];\n\n let mut t = vec![];\n\n let lines: Vec<&str> = md.lines().collect();\n\n let mut i = 0;\n\n while i < lines.len() {\n\n match parse_block(&lines[i..lines.len()]) {\n\n // if a block is found\n\n Some((block, consumed_lines)) => {\n\n // the current paragraph has ended,\n\n // push it to our blocks\n\n if !t.is_empty() {\n\n blocks.push(Paragraph(t));\n\n t = Vec::new();\n\n }\n\n blocks.push(block);\n\n i += consumed_lines;\n\n }\n\n // no known element, let's make this a paragraph\n\n None => {\n", "file_path": "src/parser/block/mod.rs", "rank": 26, "score": 161038.99988845258 }, { "content": "/// Convert tokenset of Markdown items back to String\n\npub fn generate_markdown(x: Vec<Block>) -> String {\n\n markdown_generator::generate(x)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 27, "score": 158269.62347231456 }, { "content": "pub fn parse(md: &str) -> Vec<Block> {\n\n block::parse_blocks(md)\n\n}\n", "file_path": "src/parser/mod.rs", "rank": 28, "score": 154186.85014847596 }, { "content": "pub fn generate(data: Vec<Block>) -> String {\n\n data.into_iter().map(gen_block).j(\"\\n\\n\")\n\n}\n", "file_path": "src/markdown_generator/mod.rs", "rank": 29, "score": 151795.60695479406 }, { "content": "pub fn parse_ordered_list(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref LIST_BEGIN: Regex =\n\n Regex::new(r\"^(?P<indent> *)(?P<numbering>[0-9.]+|[aAiI]+\\.) (?P<content>.*)\").unwrap();\n\n static ref NEW_PARAGRAPH: Regex = Regex::new(r\"^ +\").unwrap();\n\n static ref INDENTED: Regex = Regex::new(r\"^ {0,4}(?P<content>.*)\").unwrap();\n\n }\n\n\n\n // if the beginning doesn't match a list don't even bother\n\n if !LIST_BEGIN.is_match(lines[0]) {\n\n return None;\n\n }\n\n\n\n // a vec holding the contents and indentation\n\n // of each list item\n\n let mut contents = vec![];\n\n let mut prev_newline = false;\n\n let mut is_paragraph = false;\n\n\n\n // counts the number of parsed lines to return\n", "file_path": "src/parser/block/ordered_list.rs", "rank": 30, "score": 145474.30092538684 }, { "content": "pub fn parse_unordered_list(lines: &[&str]) -> Option<(Block, usize)> {\n\n lazy_static! {\n\n static ref LIST_BEGIN: Regex =\n\n Regex::new(r\"^(?P<indent> *)(-|\\+|\\*) (?P<content>.*)\").unwrap();\n\n static ref NEW_PARAGRAPH: Regex = Regex::new(r\"^ +\").unwrap();\n\n static ref INDENTED: Regex = Regex::new(r\"^ {0,4}(?P<content>.*)\").unwrap();\n\n }\n\n\n\n // if the beginning doesn't match a list don't even bother\n\n if !LIST_BEGIN.is_match(lines[0]) {\n\n return None;\n\n }\n\n\n\n // a vec holding the contents and indentation\n\n // of each list item\n\n let mut contents = vec![];\n\n let mut prev_newline = false;\n\n let mut is_paragraph = false;\n\n\n\n // counts the number of parsed lines to return\n", "file_path": "src/parser/block/unordered_list.rs", "rank": 31, "score": 145474.30092538684 }, { "content": "#[test]\n\npub fn paragraph() {\n\n compare(\"paragraph\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 33, "score": 136958.93064056346 }, { "content": "#[test]\n\npub fn code() {\n\n compare(\"code\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 34, "score": 136638.33207702235 }, { "content": "fn gen_span(s: Span) -> String {\n\n use Span::*;\n\n match s {\n\n Break => \" \\n\".to_string(),\n\n Text(x) => x,\n\n Literal(x) => format!(\"\\\\{}\", x),\n\n Code(x) => format!(\"`{}`\", x),\n\n Link(a, b, None) => format!(\"[{}]({})\", generate_from_spans(a), b),\n\n Link(a, b, Some(c)) => format!(\"[{}]({} \\\"{}\\\")\", generate_from_spans(a), b, c),\n\n RefLink(_, _, raw) => raw,\n\n Image(a, b, None) => format!(\"![{}]({})\", a, b),\n\n Image(a, b, Some(c)) => format!(\"![{}]({} \\\"{}\\\")\", a, b, c),\n\n Emphasis(x) => format!(\"*{}*\", generate_from_spans(x)),\n\n Strong(x) => format!(\"**{}**\", generate_from_spans(x)),\n\n }\n\n}\n\n\n", "file_path": "src/markdown_generator/mod.rs", "rank": 35, "score": 134075.57881026246 }, { "content": "fn gen_block(b: Block) -> String {\n\n use Block::*;\n\n match b {\n\n Header(s, level) => format!(\n\n \"{} {}\",\n\n ::std::iter::repeat(\"#\".to_string()).take(level).j(\"\"),\n\n generate_from_spans(s)\n\n ),\n\n Paragraph(s) => generate_from_spans(s),\n\n Blockquote(bb) => generate(bb).lines().map(|x| format!(\"> {}\", x)).j(\"\\n\"),\n\n CodeBlock(lang, x) => {\n\n if lang.is_none() {\n\n x.lines().map(|x| format!(\" {}\", x)).j(\"\\n\")\n\n } else {\n\n format!(\"```{}\\n{}```\", lang.unwrap(), x)\n\n }\n\n }\n\n // [TODO]: Ordered list generation - 2017-12-10 10:12pm\n\n OrderedList(_x, _num_type) => unimplemented!(\"Generate ordered list\"),\n\n UnorderedList(x) => generate_from_li(x),\n\n LinkReference(id, url, None) => format!(\"[{}]: {}\", id, url),\n\n LinkReference(id, url, Some(title)) => format!(\"[{}]: {} \\\"{}\\\"\", id, url, title),\n\n Raw(x) => x,\n\n Hr => \"===\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "src/markdown_generator/mod.rs", "rank": 36, "score": 133634.0102095421 }, { "content": "fn generate_from_spans(data: Vec<Span>) -> String {\n\n data.into_iter().map(gen_span).j(\"\")\n\n}\n\n\n", "file_path": "src/markdown_generator/mod.rs", "rank": 37, "score": 125990.97063471228 }, { "content": "fn parse_block(lines: &[&str]) -> Option<(Block, usize)> {\n\n pipe_opt!(\n\n lines\n\n => parse_hr\n\n => parse_atx_header\n\n => parse_code_block\n\n => parse_blockquote\n\n => parse_unordered_list\n\n => parse_ordered_list\n\n => parse_link_reference\n\n // Must not match before anything else. See: https://spec.commonmark.org/0.29/#setext-headings\n\n => parse_setext_header\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::parse_blocks;\n\n use parser::Block::{Blockquote, CodeBlock, Header, Hr, Paragraph};\n\n use parser::Span::Text;\n", "file_path": "src/parser/block/mod.rs", "rank": 38, "score": 124222.48837399427 }, { "content": "#[test]\n\nfn no_early_matching() {\n\n assert_eq!(parse_image(\"were ![an example](example.com) test\"), None);\n\n}\n", "file_path": "src/parser/span/image.rs", "rank": 39, "score": 115803.21300544543 }, { "content": "#[test]\n\nfn no_early_matching() {\n\n assert_eq!(parse_code(\"were ``testing things`` test\"), None);\n\n assert_eq!(parse_code(\"were `testing things` test\"), None);\n\n}\n", "file_path": "src/parser/span/code.rs", "rank": 40, "score": 115550.11529441619 }, { "content": "#[test]\n\npub fn paragraphs() {\n\n compare(\"paragraphs\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 41, "score": 109538.49141368584 }, { "content": "#[test]\n\npub fn headers() {\n\n compare(\"headers\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 42, "score": 109365.51306753681 }, { "content": "#[test]\n\npub fn links() {\n\n compare(\"links\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 43, "score": 108782.98167394864 }, { "content": "/// Opens a file and converts its contents to HTML\n\npub fn file_to_html(path: &Path) -> io::Result<String> {\n\n let mut file = File::open(path)?;\n\n\n\n let mut text = String::new();\n\n file.read_to_string(&mut text)?;\n\n\n\n let result = parser::parse(&text);\n\n Ok(html::to_html(&result))\n\n}\n", "file_path": "src/lib.rs", "rank": 44, "score": 106667.3992080231 }, { "content": "#[test]\n\npub fn rt_paragraphs() {\n\n roundtrip(\"paragraphs\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 45, "score": 106389.1661925274 }, { "content": "#[test]\n\npub fn rt_paragraph() {\n\n roundtrip(\"paragraph\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 46, "score": 106389.1661925274 }, { "content": "#[test]\n\npub fn rt_headers() {\n\n roundtrip(\"headers\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 47, "score": 106222.88983576809 }, { "content": "#[test]\n\npub fn rt_code() {\n\n roundtrip(\"code\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 48, "score": 106080.9891153691 }, { "content": "#[test]\n\npub fn blanks_in_code() {\n\n compare(\"blanks_in_code\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 49, "score": 106080.9891153691 }, { "content": "#[test]\n\npub fn rt_links() {\n\n roundtrip(\"links\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 50, "score": 105662.9284303081 }, { "content": "#[test]\n\npub fn brackets_in_links() {\n\n compare(\"brackets_in_links\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 51, "score": 105662.9284303081 }, { "content": "#[test]\n\npub fn rt_blanks_in_code() {\n\n roundtrip(\"blanks_in_code\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 52, "score": 103178.0953570781 }, { "content": "#[test]\n\npub fn rt_brackets_in_links() {\n\n roundtrip(\"brackets_in_links\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 53, "score": 102775.62813285485 }, { "content": "#[test]\n\nfn finds_image() {\n\n assert_eq!(\n\n parse_image(\"![an example](example.com) test\"),\n\n Some((\n\n Image(\"an example\".to_owned(), \"example.com\".to_owned(), None),\n\n 26\n\n ))\n\n );\n\n\n\n assert_eq!(\n\n parse_image(\"![](example.com) test\"),\n\n Some((Image(\"\".to_owned(), \"example.com\".to_owned(), None), 16))\n\n );\n\n\n\n assert_eq!(\n\n parse_image(\"![an example]() test\"),\n\n Some((Image(\"an example\".to_owned(), \"\".to_owned(), None), 15))\n\n );\n\n\n\n assert_eq!(\n", "file_path": "src/parser/span/image.rs", "rank": 54, "score": 96271.92375521676 }, { "content": "#[test]\n\nfn finds_code() {\n\n assert_eq!(\n\n parse_code(\"`testing things` test\"),\n\n Some((Code(\"testing things\".to_owned()), 16))\n\n );\n\n\n\n assert_eq!(\n\n parse_code(\"``testing things`` test\"),\n\n Some((Code(\"testing things\".to_owned()), 18))\n\n );\n\n\n\n assert_eq!(\n\n parse_code(\"``testing things`` things`` test\"),\n\n Some((Code(\"testing things\".to_owned()), 18))\n\n );\n\n\n\n assert_eq!(\n\n parse_code(\"`w` testing things test\"),\n\n Some((Code(\"w\".to_owned()), 3))\n\n );\n", "file_path": "src/parser/span/code.rs", "rank": 55, "score": 95941.25041066275 }, { "content": "#[test]\n\nfn no_false_positives() {\n\n assert_eq!(parse_image(\"![()] testing things test\"), None);\n\n assert_eq!(parse_image(\"!()[] testing things test\"), None);\n\n}\n\n\n", "file_path": "src/parser/span/image.rs", "rank": 56, "score": 87700.91233571981 }, { "content": "#[test]\n\nfn no_false_positives() {\n\n assert_eq!(parse_code(\"`` testing things test\"), None);\n\n assert_eq!(parse_code(\"` test\"), None);\n\n}\n\n\n", "file_path": "src/parser/span/code.rs", "rank": 57, "score": 87447.81462469058 }, { "content": "fn compare(name: &str) {\n\n let html = format!(\"tests/fixtures/files/{}.html\", name);\n\n let text = format!(\"tests/fixtures/files/{}.text\", name);\n\n let mut comp = String::new();\n\n File::open(Path::new(&html))\n\n .unwrap()\n\n .read_to_string(&mut comp)\n\n .unwrap();\n\n let md = Path::new(&text);\n\n\n\n let mut tokens = String::new();\n\n File::open(md).unwrap().read_to_string(&mut tokens).unwrap();\n\n println!(\"{:?} -> {:?}\", tokens, markdown::tokenize(&tokens));\n\n\n\n difference::assert_diff(&comp, &markdown::file_to_html(md).unwrap(), \" \", 0);\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 58, "score": 83278.78679286822 }, { "content": "fn roundtrip(name: &str) {\n\n let html = format!(\"tests/fixtures/files/{}.html\", name);\n\n let text = format!(\"tests/fixtures/files/{}.text\", name);\n\n let mut comp = String::new();\n\n File::open(Path::new(&html))\n\n .unwrap()\n\n .read_to_string(&mut comp)\n\n .unwrap();\n\n let md = Path::new(&text);\n\n\n\n let mut tokens = String::new();\n\n File::open(md).unwrap().read_to_string(&mut tokens).unwrap();\n\n\n\n let v = markdown::tokenize(&tokens);\n\n println!(\"{:?}\", v);\n\n let out = markdown::generate_markdown(v);\n\n\n\n println!(\"BEGIN\\n{}\\nEND\", out);\n\n\n\n difference::assert_diff(&comp, &markdown::to_html(&out), \" \", 0);\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 59, "score": 83278.78679286822 }, { "content": "#[test]\n\npub fn lists8() {\n\n compare(\"lists8\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 60, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn alt() {\n\n compare(\"alt\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 61, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn wrapping() {\n\n compare(\"wrapping\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 62, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn code3() {\n\n compare(\"code3\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 63, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn code2() {\n\n compare(\"code2\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 64, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn lists() {\n\n compare(\"lists\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 65, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn numbers() {\n\n compare(\"numbers\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 66, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn test() {\n\n compare(\"test\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 67, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn utf8() {\n\n compare(\"utf8\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 68, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn escaping() {\n\n compare(\"escaping\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 69, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn list2() {\n\n compare(\"list2\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 70, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn list1() {\n\n compare(\"list1\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 71, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn list3() {\n\n compare(\"list3\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 72, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn blank() {\n\n compare(\"blank\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 73, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn entities() {\n\n compare(\"entities\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 74, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn olist() {\n\n compare(\"olist\")\n\n}\n\n\n\n//#[test]\n\n//pub fn rt_olist() {\n\n//roundtrip(\"olist\")\n\n//}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 75, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn easy() {\n\n compare(\"easy\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 76, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn one() {\n\n compare(\"one\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 77, "score": 80390.35609800919 }, { "content": "#[test]\n\npub fn rt_entities() {\n\n roundtrip(\"entities\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 78, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn lists_ol() {\n\n compare(\"lists_ol\")\n\n}\n\n\n\n//#[test]\n\n//pub fn rt_lists_ol() {\n\n//roundtrip(\"lists_ol\")\n\n//}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 79, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_easy() {\n\n roundtrip(\"easy\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 80, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_lists8() {\n\n roundtrip(\"lists8\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 81, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_list3() {\n\n roundtrip(\"list3\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 82, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_utf8() {\n\n roundtrip(\"utf8\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 83, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_one() {\n\n roundtrip(\"one\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 84, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_list2() {\n\n roundtrip(\"list2\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 85, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_lists() {\n\n roundtrip(\"lists\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 86, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_blank() {\n\n roundtrip(\"blank\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 87, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn hex_entities() {\n\n compare(\"hex_entities\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 88, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_code3() {\n\n roundtrip(\"code3\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 89, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_alt() {\n\n roundtrip(\"alt\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 90, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_code2() {\n\n roundtrip(\"code2\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 91, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_escaping() {\n\n roundtrip(\"escaping\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 92, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_test() {\n\n roundtrip(\"test\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 93, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_list1() {\n\n roundtrip(\"list1\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 94, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_wrapping() {\n\n roundtrip(\"wrapping\")\n\n}\n", "file_path": "tests/fixtures/mod.rs", "rank": 95, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_numbers() {\n\n roundtrip(\"numbers\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 96, "score": 78370.36583677621 }, { "content": "#[test]\n\npub fn rt_hex_entities() {\n\n roundtrip(\"hex_entities\")\n\n}\n\n\n", "file_path": "tests/fixtures/mod.rs", "rank": 97, "score": 76501.06489007013 }, { "content": "fn generate_from_li(data: Vec<ListItem>) -> String {\n\n use ListItem::*;\n\n\n\n data.into_iter()\n\n .map(|x| {\n\n format!(\n\n \"* {}\",\n\n match x {\n\n Simple(x) => generate_from_spans(x),\n\n Paragraph(x) => format!(\n\n \"{}\\n\",\n\n generate(x)\n\n .lines()\n\n .enumerate()\n\n .map(|(i, x)| if i == 0 {\n\n x.to_string()\n\n } else {\n\n format!(\" {}\", x)\n\n })\n\n .j(\"\\n\")\n\n ),\n\n }\n\n )\n\n })\n\n .j(\"\\n\")\n\n}\n\n\n", "file_path": "src/markdown_generator/mod.rs", "rank": 98, "score": 71652.84775130208 }, { "content": " }\n\n } else if backtick_opened {\n\n content.push_str(line);\n\n content.push('\\n');\n\n\n\n line_number += 1;\n\n } else {\n\n break;\n\n }\n\n }\n\n\n\n if line_number > 0 && ((backtick_opened && backtick_closed) || !backtick_opened) {\n\n return Some((\n\n CodeBlock(lang, content.trim_matches('\\n').to_owned()),\n\n line_number,\n\n ));\n\n }\n\n\n\n None\n\n}\n", "file_path": "src/parser/block/code_block.rs", "rank": 99, "score": 63897.153383499535 } ]
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::MsgHeartbeat && msg.commit == 0)\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]\n\npub struct RaftNodeStatus {\n\n id: u64,\n\n role: String,\n\n promotable: bool,\n\n pass_election_timeout: bool,\n\n election_elapsed: usize,\n\n randomized_election_timeout: usize,\n\n term: u64,\n\n last_index: u64,\n\n}\n\n\n\n// unsafe impl Send for RaftNodeStatus {}\n", "file_path": "src/raft_node.rs", "rank": 0, "score": 191881.38430970625 }, { "content": "fn reply(tx: Sender<WsMessage>) -> Reply {\n\n Reply(RequestId(666), tx)\n\n}\n\n\n\nasync fn request(cx: Request<Node>, req: UrMsg, mut rx: Receiver<WsMessage>) -> Result<Response> {\n\n cx.state().tx.unbounded_send(req)?;\n\n rx.next()\n\n .await\n\n .ok_or(StatusCode::INTERNAL_SERVER_ERROR.into())\n\n .and_then(|msg| match msg {\n\n WsMessage::Reply(code, r) => response_json(code, r.data),\n\n _ => unreachable!(),\n\n })\n\n}\n\n\n", "file_path": "src/network/ws/rest.rs", "rank": 1, "score": 140952.3834122293 }, { "content": "#[cfg(not(feature = \"json-proto\"))]\n\nfn decode_ws(bin: &[u8]) -> RaftMessage {\n\n use protobuf::Message;\n\n let mut msg = RaftMessage::default();\n\n msg.merge_from_bytes(bin).unwrap();\n\n msg\n\n}\n\n\n", "file_path": "src/network/ws.rs", "rank": 2, "score": 136096.51408086965 }, { "content": "type LocalMailboxes = HashMap<NodeId, Sender<WsMessage>>;\n", "file_path": "src/network/ws.rs", "rank": 3, "score": 121356.53407437619 }, { "content": "type RemoteMailboxes = HashMap<NodeId, Sender<WsMessage>>;\n\n\n\n#[derive(Clone)]\n\npub(crate) struct Node {\n\n id: NodeId,\n\n tx: UnboundedSender<UrMsg>,\n\n logger: Logger,\n\n pubsub: pubsub::Channel,\n\n}\n\n\n\npub struct Network {\n\n id: NodeId,\n\n local_mailboxes: LocalMailboxes,\n\n remote_mailboxes: RemoteMailboxes,\n\n known_peers: HashMap<NodeId, String>,\n\n endpoint: String,\n\n logger: Logger,\n\n rx: UnboundedReceiver<UrMsg>,\n\n tx: UnboundedSender<UrMsg>,\n\n next_eid: u64,\n", "file_path": "src/network/ws.rs", "rank": 4, "score": 121356.53407437619 }, { "content": "struct Connection {\n\n addr: SocketAddr,\n\n rx: Receiver<TungstenMessage>,\n\n tx: Sender<TungstenMessage>,\n\n tasks: Sender<vnode::Task>,\n\n vnode: Option<u64>,\n\n}\n\n\n\nasync fn handle_connection(logger: Logger, mut connection: Connection) {\n\n while let Some(msg) = connection.rx.next().await {\n\n info!(\n\n logger,\n\n \"Received a message from {}: {}\", connection.addr, msg\n\n );\n\n match serde_json::from_slice(&msg.into_data()) {\n\n Ok(Message::HandoffStart { src, vnode }) => {\n\n assert!(connection.vnode.is_none());\n\n connection.vnode = Some(vnode);\n\n connection\n\n .tasks\n", "file_path": "mring-node/src/handoff.rs", "rank": 5, "score": 117805.66555454156 }, { "content": "#[cfg(not(feature = \"json-proto\"))]\n\nfn encode_ws(msg: RaftMessage) -> Bytes {\n\n use protobuf::Message;\n\n msg.write_to_bytes().unwrap().into()\n\n}\n\n\n\nimpl Network {\n\n pub fn new(\n\n logger: &Logger,\n\n id: NodeId,\n\n ws_endpoint: &str,\n\n rest_endpoint: Option<&str>,\n\n peers: Vec<String>,\n\n pubsub: pubsub::Channel,\n\n ) -> Self {\n\n let (tx, rx) = unbounded();\n\n\n\n for peer in peers {\n\n let logger = logger.clone();\n\n let tx = tx.clone();\n\n task::spawn(client::remote_endpoint(peer, tx, logger));\n", "file_path": "src/network/ws.rs", "rank": 6, "score": 108628.20695895547 }, { "content": "fn param_err<T: std::fmt::Debug>(e: ParamError<T>) -> Error {\n\n Error::Param(format!(\"{:?}\", e))\n\n}\n\nasync fn uring_get(cx: Request<Node>) -> Result<Response> {\n\n let (tx, mut rx) = channel(crate::CHANNEL_SIZE);\n\n let id: u64 = cx.param(\"id\").map_err(param_err)?;\n\n cx.state()\n\n .tx\n\n .unbounded_send(UrMsg::GetNode(NodeId(id), tx))?;\n\n\n\n rx.next()\n\n .await\n\n .ok_or(StatusCode::NOT_FOUND.into())\n\n .and_then(response_json_200)\n\n}\n\n\n\nasync fn uring_post(cx: Request<Node>) -> Result<Response> {\n\n let (tx, mut rx) = channel(crate::CHANNEL_SIZE);\n\n let id: u64 = cx.param(\"id\").map_err(param_err)?;\n\n cx.state()\n", "file_path": "src/network/ws/rest.rs", "rank": 7, "score": 103722.65557329296 }, { "content": "fn param_err<T: std::fmt::Debug>(e: ParamError<T>) -> Error {\n\n Error::Param(format!(\"{:?}\", e))\n\n}\n\n\n\npub(crate) async fn get(cx: Request<Node>) -> Result<Response> {\n\n let (tx, rx) = channel(crate::CHANNEL_SIZE);\n\n let key: String = cx.param(\"id\").map_err(param_err)?;\n\n let id = key.clone().into_bytes();\n\n info!(cx.state().logger, \"GET /kv/{}\", key);\n\n request(cx, UrMsg::Get(id.clone(), reply(tx)), rx).await\n\n}\n\n\n", "file_path": "src/network/ws/rest/kv.rs", "rank": 8, "score": 101534.82010419408 }, { "content": "#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]\n\nstruct VNode {\n\n id: u64,\n\n handoff: Option<handoff::Handoff>,\n\n data: Vec<String>,\n\n}\n\n\n\npub(crate) enum Task {\n\n HandoffOut {\n\n target: String,\n\n vnode: u64,\n\n },\n\n Assign {\n\n vnodes: Vec<u64>,\n\n },\n\n Update {\n\n next: MRingNodes,\n\n },\n\n HandoffInStart {\n\n src: String,\n\n vnode: u64,\n", "file_path": "mring-node/src/vnode.rs", "rank": 9, "score": 92536.7493181106 }, { "content": "#[derive(Default)]\n\nstruct State {\n\n vnodes: HashMap<u64, VNode>,\n\n mappings: HashMap<u64, String>,\n\n}\n\n\n\nimpl State {\n\n pub fn update_ring(&mut self, mapping: MRingNodes) {\n\n for node in mapping.into_iter() {\n\n for vnode in &node.vnodes {\n\n self.mappings.insert(*vnode, node.id.clone());\n\n }\n\n }\n\n }\n\n}\n\n\n\nasync fn handle_cmd(\n\n logger: &Logger,\n\n cmd: Option<Cmd>,\n\n state: &mut State,\n\n tasks_tx: &mut Sender<Task>,\n", "file_path": "mring-node/src/vnode.rs", "rank": 10, "score": 85416.43550218601 }, { "content": "fn main() {\n\n let decorator = slog_term::TermDecorator::new().build();\n\n let drain = slog_term::FullFormat::new(decorator).build().fuse();\n\n let drain = slog_async::Async::new(drain).build().fuse();\n\n let logger = slog::Logger::root(drain, o!());\n\n\n\n let (tasks_tx, tasks_rx) = channel(crate::CHANNEL_SIZE);\n\n\n\n let local = env::args()\n\n .nth(1)\n\n .unwrap_or_else(|| panic!(\"this program requires at least two arguments\"));\n\n\n\n // Specify the server address to which the client will be connecting.\n\n let remote = env::args()\n\n .nth(2)\n\n .unwrap_or_else(|| panic!(\"this program requires at least two argument\"));\n\n\n\n task::spawn(vnode::run(\n\n logger.clone(),\n\n local.clone(),\n", "file_path": "mring-node/src/main.rs", "rank": 11, "score": 84861.43010189716 }, { "content": "fn example_config() -> Config {\n\n Config {\n\n election_tick: 10,\n\n heartbeat_tick: 3,\n\n pre_vote: true,\n\n ..Default::default()\n\n }\n\n}\n\n\n", "file_path": "src/raft_node.rs", "rank": 12, "score": 78401.36504080518 }, { "content": "fn make_data_key(prefix: u16, key_s: &[u8]) -> Vec<u8> {\n\n let mut key = vec![0; 8 + key_s.len()];\n\n\n\n {\n\n key.put_u32_le(DATA_PREFIX as u32);\n\n key.put_u32_le(prefix as u32);\n\n key.write_all(key_s).unwrap();\n\n }\n\n\n\n key\n\n}\n", "file_path": "src/storage.rs", "rank": 13, "score": 70837.41030369683 }, { "content": " Ok(Request::Subscribe { channel: c }) => {\n\n let (tx, mut rx) = channel(64);\n\n let mut outbound = msg.outbound_channel;\n\n let id = msg.id;\n\n let data = serde_json::to_vec(&Reply::Subscribed { channel: c.clone() }).unwrap();\n\n outbound\n\n .send(HandlerOutboundMessage::partial(id, data))\n\n .await\n\n .unwrap();\n\n\n\n task::spawn(async move {\n\n while let Some(msg) = dbg!(rx.next().await) {\n\n let data = serde_json::to_vec(&msg).unwrap();\n\n outbound\n\n .send(HandlerOutboundMessage::partial(id, data))\n\n .await\n\n .unwrap();\n\n }\n\n });\n\n self.pubsub\n", "file_path": "src/protocol/pubsub.rs", "rank": 14, "score": 70512.26040735273 }, { "content": " .send(pubsub::Msg::Subscribe { channel: c, tx })\n\n .await\n\n .unwrap();\n\n\n\n interceptor::Reply::Terminate\n\n }\n\n Err(_) => interceptor::Reply::Err(DriverErrorType::BadInput),\n\n }\n\n }\n\n}\n", "file_path": "src/protocol/pubsub.rs", "rank": 15, "score": 70506.21395036406 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::pubsub;\n\nuse async_std::task;\n\nuse async_trait::async_trait;\n\nuse futures::channel::mpsc::channel;\n\nuse futures::{SinkExt, StreamExt};\n\nuse protocol_driver::{\n\n interceptor, DriverErrorType, HandlerInboundMessage, HandlerOutboundMessage,\n\n};\n\nuse serde_derive::{Deserialize, Serialize};\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n", "file_path": "src/protocol/pubsub.rs", "rank": 16, "score": 70497.13406997312 }, { "content": "#[derive(Deserialize, Serialize, Debug)]\n\nenum Reply {\n\n Subscribed { channel: String },\n\n}\n\n\n\n// FIXME: collect dead destinations\n\n// FIXME: guarantee unique ids\n\npub struct Handler {\n\n pubsub: pubsub::Channel,\n\n}\n\n\n\nimpl Handler {\n\n pub fn new(pubsub: pubsub::Channel) -> Self {\n\n Self { pubsub }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl interceptor::Intercept for Handler {\n\n async fn inbound(&mut self, msg: HandlerInboundMessage) -> interceptor::Reply {\n\n match dbg!(serde_json::from_slice(&msg.data)) {\n", "file_path": "src/protocol/pubsub.rs", "rank": 17, "score": 67156.48387719004 }, { "content": "#[derive(Deserialize, Serialize, Debug)]\n\nenum Request {\n\n Subscribe { channel: String },\n\n}\n\n\n", "file_path": "src/protocol/pubsub.rs", "rank": 18, "score": 67156.48387719004 }, { "content": "fn make_log_key(idx: u64) -> Vec<u8> {\n\n let mut key: Vec<u8> = vec![0; 16];\n\n\n\n {\n\n // let mut key = Cursor::new(&mut key[..]);\n\n key.put_u64_le(RAFT_PREFIX as u64);\n\n key.put_u64_le(idx);\n\n }\n\n\n\n key\n\n}\n\n\n", "file_path": "src/storage.rs", "rank": 19, "score": 66335.37876859994 }, { "content": " def pid(self):\n", "file_path": "contrib/__init__.py", "rank": 20, "score": 57589.03214178693 }, { "content": "#[derive(Serialize, Deserialize, Clone, Debug)]\n\nstruct HandoffKV {\n\n key: String,\n\n value: String,\n\n}\n\nimpl URRocksStorage {\n\n fn get_hard_state(&self) -> HardState {\n\n let mut hs = HardState::new();\n\n if let Ok(Some(data)) = self.backend.get(&HARD_STATE) {\n\n hs.merge_from_bytes(&data).unwrap();\n\n };\n\n hs\n\n }\n\n fn get_conf_state(&self) -> ConfState {\n\n let mut cs = ConfState::new();\n\n if let Ok(Some(data)) = self.backend.get(&CONF_STATE) {\n\n cs.merge_from_bytes(&data).unwrap();\n\n };\n\n cs\n\n }\n\n fn clear_log(&self) {\n", "file_path": "src/storage.rs", "rank": 21, "score": 55682.40187815755 }, { "content": " def set_node_id(self, id):\n", "file_path": "contrib/__init__.py", "rank": 22, "score": 53906.50240084754 }, { "content": "#[derive(Deserialize)]\n\nstruct CasBody {\n\n check: Option<String>,\n\n store: String,\n\n}\n\n\n\npub(crate) async fn cas(mut cx: Request<Node>) -> Result<Response> {\n\n let (tx, rx) = channel(crate::CHANNEL_SIZE);\n\n let id: String = cx.param(\"id\").map_err(param_err)?;\n\n let id = id.into_bytes();\n\n let body: CasBody = cx.body_json().await?;\n\n\n\n request(\n\n cx,\n\n UrMsg::Cas(\n\n id,\n\n body.check.clone().map(String::into_bytes),\n\n body.store.clone().into_bytes(),\n\n reply(tx),\n\n ),\n\n rx,\n", "file_path": "src/network/ws/rest/kv.rs", "rank": 23, "score": 51489.337441319134 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct PostBody {\n\n value: String,\n\n}\n\n\n\npub(crate) async fn post(mut cx: Request<Node>) -> Result<Response> {\n\n let (tx, rx) = channel(crate::CHANNEL_SIZE);\n\n let key: String = cx.param(\"id\").map_err(param_err)?;\n\n let id = key.clone().into_bytes();\n\n let body: PostBody = cx.body_json().await?;\n\n info!(cx.state().logger, \"POST /kv/{} -> {}\", key, body.value);\n\n request(\n\n cx,\n\n UrMsg::Put(id, body.value.clone().into_bytes(), reply(tx)),\n\n rx,\n\n )\n\n .await\n\n}\n\n\n", "file_path": "src/network/ws/rest/kv.rs", "rank": 24, "score": 51489.337441319134 }, { "content": "pub fn print() {\n\n eprintln!(\"uring version: {}\", VERSION);\n\n}\n\n\n", "file_path": "src/version.rs", "rank": 25, "score": 51393.145623410994 }, { "content": "type DriverOutboundData = Result<Vec<u8>, DriverError>;\n\n\n\npub type ClientId = u64;\n\npub type CorrelationId = u64;\n\n\n\npub struct ClientConnection {\n\n protocol: Protocol,\n\n enabled_protocols: Vec<CustomProtocol>,\n\n}\n\n\n\nimpl Default for ClientConnection {\n\n fn default() -> Self {\n\n ClientConnection {\n\n protocol: Protocol::Connect,\n\n enabled_protocols: vec![],\n\n }\n\n }\n\n}\n\n\n\n#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]\n", "file_path": "protocol-driver/src/lib.rs", "rank": 26, "score": 48788.08172689602 }, { "content": "type WSStream = async_tungstenite::WebSocketStream<TcpStream>;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n\npub(crate) enum Direction {\n\n Inbound,\n\n Outbound,\n\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n\npub(crate) struct Handoff {\n\n pub partner: String,\n\n pub chunk: u64,\n\n pub direction: Direction,\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n\npub(crate) enum Message {\n\n HandoffStart {\n\n src: String,\n\n vnode: u64,\n\n },\n", "file_path": "mring-node/src/handoff.rs", "rank": 27, "score": 46788.87950106736 }, { "content": "pub fn log(logger: &Logger) {\n\n info!(logger, \"uring version: {}\", VERSION);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn for_coverage_only() {\n\n print();\n\n log(&slog::Logger::root(slog::Discard, o!()));\n\n }\n\n}\n", "file_path": "src/version.rs", "rank": 28, "score": 43922.58762865956 }, { "content": "fn main() -> std::io::Result<()> {\n\n use version::VERSION;\n\n let matches = ClApp::new(\"cake\")\n\n .version(VERSION)\n\n .author(\"The Treamor Team\")\n\n .about(\"Uring Demo\")\n\n .arg(\n\n Arg::with_name(\"id\")\n\n .short(\"i\")\n\n .long(\"id\")\n\n .value_name(\"ID\")\n\n .help(\"The Node ID\")\n\n .takes_value(true),\n\n )\n\n .arg(\n\n Arg::with_name(\"bootstrap\")\n\n .short(\"b\")\n\n .long(\"bootstrap\")\n\n .value_name(\"BOOTSTRAP\")\n\n .help(\"Sets the node to bootstrap mode and become leader\")\n", "file_path": "src/main.rs", "rank": 29, "score": 43922.58762865956 }, { "content": "fn unerror(r: Result<Response>) -> tide::Result {\n\n Ok(match r {\n\n Ok(r) => r,\n\n Err(e) => e.into(),\n\n })\n\n}\n\n\n", "file_path": "src/network/ws/rest.rs", "rank": 30, "score": 37705.694231142916 }, { "content": "}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Self::Raft(e) => write!(f, \"{}\", e),\n\n }\n\n }\n\n}\n\nimpl std::error::Error for Error {}\n", "file_path": "src/errors.rs", "rank": 31, "score": 37378.80857411541 }, { "content": " let msg = serde_json::to_value(&msg).unwrap();\n\n let channel = channel.to_string();\n\n Self::Msg { channel, msg }\n\n }\n\n}\n\n\n\nasync fn pubsub_loop(logger: Logger, mut rx: Receiver<Msg>) {\n\n let mut subscriptions: HashMap<String, Vec<Sender<SubscriberMsg>>> = HashMap::new();\n\n while let Some(msg) = rx.next().await {\n\n match msg {\n\n Msg::Subscribe { channel, tx } => {\n\n info!(logger, \"Sub {}\", channel);\n\n let subscriptions = subscriptions.entry(channel).or_default();\n\n subscriptions.push(tx);\n\n }\n\n Msg::Msg { channel, msg } => {\n\n info!(logger, \"Msg: {} >> {}\", channel, msg);\n\n let subscriptions = subscriptions.entry(channel.clone()).or_default();\n\n let mut s1 = Vec::with_capacity(subscriptions.len());\n\n for mut tx in subscriptions.drain(..) {\n", "file_path": "src/pubsub.rs", "rank": 32, "score": 37371.43598183572 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse raft::Error as RaftError;\n\nuse std::fmt;\n\npub type Result<T> = std::result::Result<T, Error>;\n\n#[derive(Debug)]\n\npub enum Error {\n\n Raft(RaftError),\n", "file_path": "src/errors.rs", "rank": 33, "score": 37370.349902923626 }, { "content": "use ws_proto::SubscriberMsg;\n\n\n\npub type Channel = Sender<Msg>;\n\n\n\npub enum Msg {\n\n Subscribe {\n\n channel: String,\n\n tx: Sender<SubscriberMsg>,\n\n },\n\n Msg {\n\n channel: String,\n\n msg: serde_json::Value,\n\n },\n\n}\n\n\n\nimpl Msg {\n\n pub fn new<T>(channel: &str, msg: T) -> Self\n\n where\n\n T: Serialize,\n\n {\n", "file_path": "src/pubsub.rs", "rank": 34, "score": 37364.22261459875 }, { "content": " let channel = channel.clone();\n\n let msg = msg.clone();\n\n if tx.send(SubscriberMsg::Msg { channel, msg }).await.is_ok() {\n\n s1.push(tx)\n\n }\n\n }\n\n std::mem::swap(subscriptions, &mut s1);\n\n }\n\n }\n\n }\n\n}\n\n\n\npub(crate) fn start(logger: &Logger) -> Channel {\n\n let logger = logger.clone();\n\n let (tx, rx) = channel(crate::CHANNEL_SIZE);\n\n\n\n task::spawn(pubsub_loop(logger, rx));\n\n tx\n\n}\n", "file_path": "src/pubsub.rs", "rank": 35, "score": 37358.88321241293 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n// use crate::{NodeId, KV};\n\nuse async_std::task;\n\nuse futures::channel::mpsc::{channel, Receiver, Sender};\n\nuse futures::{SinkExt, StreamExt};\n\nuse serde::Serialize;\n\nuse slog::Logger;\n\nuse std::collections::HashMap;\n", "file_path": "src/pubsub.rs", "rank": 36, "score": 37353.5378215537 }, { "content": "pub mod kv;\n\npub mod network;\n\npub mod pubsub;\n\npub mod status;\n", "file_path": "src/protocol.rs", "rank": 37, "score": 36812.594051454886 }, { "content": "type Result<T> = std::result::Result<T, Error>;\n\n\n", "file_path": "src/network/ws/rest.rs", "rank": 38, "score": 35130.26943231394 }, { "content": "}\n\n\n\n#[derive(Default)]\n\npub struct Handler {\n\n ids: HashMap<RequestId, RequestId>,\n\n}\n\n\n\n#[async_trait]\n\nimpl interceptor::Intercept for Handler {\n\n async fn inbound(&mut self, mut msg: HandlerInboundMessage) -> interceptor::Reply {\n\n use kv::Event;\n\n msg.service_id = Some(kv::ID);\n\n msg.data = match dbg!(serde_json::from_slice(&msg.data)) {\n\n Ok(Request::Get { key, rid }) => {\n\n self.ids.insert(msg.id, rid);\n\n Event::get(key.into_bytes())\n\n }\n\n Ok(Request::Put { key, store, rid }) => {\n\n self.ids.insert(msg.id, rid);\n\n Event::put(key.into_bytes(), store.into_bytes())\n", "file_path": "src/protocol/kv.rs", "rank": 39, "score": 35020.89425425087 }, { "content": "pub(crate) struct Handler {\n\n network: UnboundedSender<UrMsg>,\n\n}\n\nimpl Handler {\n\n pub fn new(network: UnboundedSender<UrMsg>) -> Self {\n\n Self { network }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl interceptor::Intercept for Handler {\n\n async fn inbound(&mut self, msg: HandlerInboundMessage) -> interceptor::Reply {\n\n if let Some(service_id) = msg.service_id {\n\n if self\n\n .network\n\n .send(UrMsg::Protocol(ProtocolMessage::Event {\n\n id: msg.id,\n\n service_id,\n\n event: msg.data,\n\n reply: msg.outbound_channel,\n", "file_path": "src/protocol/network.rs", "rank": 40, "score": 35020.52655457221 }, { "content": " }\n\n Ok(Request::Delete { key, rid }) => {\n\n self.ids.insert(msg.id, rid);\n\n Event::delete(key.into_bytes())\n\n }\n\n Ok(Request::Cas {\n\n key,\n\n check,\n\n store,\n\n rid,\n\n }) => {\n\n self.ids.insert(msg.id, rid);\n\n kv::Event::cas(\n\n key.into_bytes(),\n\n check.map(String::into_bytes),\n\n store.into_bytes(),\n\n )\n\n }\n\n Err(_) => return interceptor::Reply::Err(DriverErrorType::BadInput),\n\n };\n", "file_path": "src/protocol/kv.rs", "rank": 41, "score": 35019.46177265371 }, { "content": " interceptor::Reply::Ok(msg)\n\n }\n\n fn result_id_map(&mut self, id: RequestId) -> Option<RequestId> {\n\n self.ids.remove(&id)\n\n }\n\n}\n\n\n\n/*\n\n{\"Connect\": [\"kv\", \"pubsub\"]}\n\n\n\n{\"Select\": \"pubsub\"}\n\n{\"Subscribe\": {\"channel\": \"kv\"}}\n\n\n\n{\"Select\": \"kv\"}\n\n{\"Put\": {\"key\": \"snot\", \"store\": \"badger\"}}\n\n{\"Get\": {\"key\": \"snot\"}}\n\n*/\n", "file_path": "src/protocol/kv.rs", "rank": 42, "score": 35013.12690333511 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::network::ws::{ProtocolMessage, UrMsg};\n\nuse async_trait::async_trait;\n\nuse futures::channel::mpsc::UnboundedSender;\n\nuse futures::SinkExt;\n\nuse protocol_driver::{interceptor, DriverErrorType, HandlerInboundMessage};\n\n\n", "file_path": "src/protocol/network.rs", "rank": 43, "score": 35010.09734255454 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::service::kv;\n\nuse async_trait::async_trait;\n\nuse protocol_driver::{interceptor, DriverErrorType, HandlerInboundMessage, RequestId};\n\nuse serde_derive::{Deserialize, Serialize};\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n", "file_path": "src/protocol/kv.rs", "rank": 44, "score": 35003.72347933534 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse crate::service::status;\n\nuse async_trait::async_trait;\n\nuse protocol_driver::{interceptor, DriverErrorType, HandlerInboundMessage, RequestId};\n\nuse serde_derive::{Deserialize, Serialize};\n\nuse std::collections::HashMap;\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n", "file_path": "src/protocol/status.rs", "rank": 45, "score": 35003.72347933534 }, { "content": " };\n\n interceptor::Reply::Ok(msg)\n\n }\n\n\n\n fn result_id_map(&mut self, id: RequestId) -> Option<RequestId> {\n\n self.ids.remove(&id)\n\n }\n\n}\n\n\n\n/*\n\n{\"Connect\": [\"status\"]}\n\n{\"Select\": \"status\"}\n\n{\"Get\": {\"rid\":42}}\n\n*/\n", "file_path": "src/protocol/status.rs", "rank": 46, "score": 35003.355914929605 }, { "content": " }))\n\n .await\n\n .is_ok()\n\n {\n\n interceptor::Reply::Terminate\n\n } else {\n\n interceptor::Reply::Err(DriverErrorType::SystemError)\n\n }\n\n } else {\n\n interceptor::Reply::Err(DriverErrorType::LogicalError)\n\n }\n\n }\n\n}\n", "file_path": "src/protocol/network.rs", "rank": 47, "score": 35000.94268425896 }, { "content": "fn response_json_200<S: Serialize>(v: S) -> Result<Response> {\n\n response_json(200, v)\n\n}\n\n\n\nasync fn version(cx: Request<Node>) -> Result<Response> {\n\n let (tx, rx) = channel(crate::CHANNEL_SIZE);\n\n request(cx, UrMsg::Version(RequestId(666), tx), rx).await\n\n}\n\n\n\nasync fn status(cx: Request<Node>) -> Result<Response> {\n\n let (tx, rx) = channel(crate::CHANNEL_SIZE);\n\n request(cx, UrMsg::Status(RequestId(666), tx), rx).await\n\n}\n\n\n", "file_path": "src/network/ws/rest.rs", "rank": 48, "score": 34802.02868554574 }, { "content": " RaftNetworkMsg::Event(eid, sid, data) => {\n\n if let Some(mut service) = self.services.get_mut(&sid) {\n\n if service.is_local(&data).unwrap() {\n\n let (code, value) = service.execute(raft, &mut self.pubsub, data).await.unwrap();\n\n self.network.event_reply(eid, code, value).await.unwrap();\n\n } else {\n\n let pid = self.next_pid();\n\n let from = self.id;\n\n if let Err(e) = self.propose_event(from, pid, sid, eid, data).await {\n\n error!(self.logger, \"Post forward error: {}\", e);\n\n self.network.event_reply(eid, 500, serde_json::to_vec(&format!(\"{}\", e)).unwrap()).await.unwrap();\n\n } else {\n\n self.pending_acks.insert(pid, eid);\n\n }\n\n }\n\n } else {\n\n error!(self.logger, \"Unknown Service: {}\", sid);\n\n self.network.event_reply(eid, 500, serde_json::to_vec(&format!(\"Service {} not known\", sid)).unwrap()).await.unwrap();\n\n }\n\n }\n", "file_path": "src/raft_node.rs", "rank": 49, "score": 34385.25398021585 }, { "content": " self.pubsub\n\n .send(pubsub::Msg::new(\n\n \"uring\",\n\n PSURing::ProposalReceived {\n\n from,\n\n pid,\n\n sid,\n\n eid,\n\n node: self.id,\n\n },\n\n ))\n\n .await\n\n .unwrap();\n\n if self.is_leader() {\n\n self.proposals\n\n .push_back(Proposal::normal(pid, from, eid, sid, data));\n\n Ok(())\n\n } else {\n\n self.network\n\n .forward_proposal(from, self.leader(), pid, sid, eid, data)\n", "file_path": "src/raft_node.rs", "rank": 50, "score": 34384.11217056638 }, { "content": " .await\n\n .map_err(|e| {\n\n Error::Io(IoError::new(\n\n IoErrorKind::ConnectionAborted,\n\n format!(\"{}\", e),\n\n ))\n\n })\n\n }\n\n }\n\n\n\n pub async fn add_node(&mut self, id: NodeId) -> bool {\n\n if self.is_leader() && !self.node_known(id).await {\n\n self.pubsub\n\n .send(pubsub::Msg::new(\n\n \"uring\",\n\n PSURing::AddNode {\n\n new_node: id,\n\n node: self.id,\n\n },\n\n ))\n", "file_path": "src/raft_node.rs", "rank": 51, "score": 34383.8863335834 }, { "content": " RaftNetworkMsg::GetNode(id, mut reply) => {\n\n info!(self.logger, \"Getting node status\"; \"id\" => id);\n\n reply.send(self.node_known(id).await).await.unwrap();\n\n }\n\n RaftNetworkMsg::AddNode(id, mut reply) => {\n\n info!(self.logger, \"Adding node\"; \"id\" => id);\n\n reply.send(self.add_node(id).await).await.unwrap();\n\n }\n\n RaftNetworkMsg::AckProposal(pid, success) => {\n\n info!(self.logger, \"proposal acknowledged\"; \"pid\" => pid);\n\n if let Some(proposal) = self.pending_proposals.remove(&pid) {\n\n if !success {\n\n self.proposals.push_back(proposal)\n\n }\n\n }\n\n if let Some(eid) = self.pending_acks.remove(&pid) {\n\n //self.network.event_reply(eid, Some(vec![skilled])).await.unwrap();\n\n }\n\n }\n\n RaftNetworkMsg::ForwardProposal(from, pid, sid, eid, data) => {\n", "file_path": "src/raft_node.rs", "rank": 52, "score": 34382.29503969362 }, { "content": " self.raft_group.as_mut().unwrap().try_lock().unwrap().tick();\n\n self.on_ready().await.unwrap();\n\n if self.is_leader() {\n\n // Handle new proposals.\n\n self.propose_all().await?;\n\n }\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n pub async fn propose_event(\n\n &mut self,\n\n from: NodeId,\n\n pid: ProposalId,\n\n sid: ServiceId,\n\n eid: EventId,\n\n data: Vec<u8>,\n\n ) -> Result<()> {\n", "file_path": "src/raft_node.rs", "rank": 53, "score": 34376.345475152666 }, { "content": " let mut i = Instant::now();\n\n\n\n loop {\n\n select! {\n\n msg = self.network.next().fuse() => {\n\n let msg = if let Some(msg) = msg {\n\n msg\n\n } else {\n\n break;\n\n };\n\n let raft = self.raft_group.as_ref().unwrap();\n\n match msg {\n\n RaftNetworkMsg::Status(rid, mut reply) => {\n\n info!(self.logger, \"Getting node status\");\n\n reply.send(WsMessage::Reply(200, ws_proto::Reply { code: 200, rid, data: serde_json::to_value(status(raft).await.unwrap()).unwrap() })).await.unwrap();\n\n }\n\n RaftNetworkMsg::Version(rid, mut reply) => {\n\n info!(self.logger, \"Getting version\");\n\n reply.send(WsMessage::Reply(200, ws_proto::Reply { code: 200, rid, data: serde_json::to_value(self.version()).unwrap() })).await.unwrap();\n\n }\n", "file_path": "src/raft_node.rs", "rank": 54, "score": 34375.967553596 }, { "content": " if !is_initial_msg(msg) {\n\n return;\n\n }\n\n let mut cfg = example_config();\n\n cfg.id = msg.to;\n\n let storage = Storage::new(self.id).await;\n\n self.raft_group = Some(Mutex::new(\n\n RawNode::new(&cfg, storage, &self.logger).unwrap(),\n\n ));\n\n }\n\n\n\n // Step a raft message, initialize the raft if need.\n\n pub async fn step(&mut self, msg: Message) -> Result<()> {\n\n if self.raft_group.is_none() {\n\n if is_initial_msg(&msg) {\n\n self.initialize_raft_from_message(&msg).await;\n\n } else {\n\n return Ok(());\n\n }\n\n }\n", "file_path": "src/raft_node.rs", "rank": 55, "score": 34375.1487739647 }, { "content": " if let Err(e) = self.propose_event(from, pid, sid, eid, data).await {\n\n error!(self.logger, \"Proposal forward error: {}\", e);\n\n }\n\n }\n\n\n\n // RAFT\n\n RaftNetworkMsg::RaftMsg(msg) => {\n\n if let Err(e) = self.step(msg).await {\n\n error!(self.logger, \"step error\"; \"error\" => format!(\"{}\", e));\n\n }\n\n }\n\n }\n\n },\n\n tick = ticks.next().fuse() => {\n\n if !self.is_running() {\n\n continue\n\n }\n\n if i.elapsed() >= Duration::from_secs(10) {\n\n self.log().await;\n\n i = Instant::now();\n", "file_path": "src/raft_node.rs", "rank": 56, "score": 34374.89847348652 }, { "content": " // .unwrap()\n\n // .lock()\n\n // .await\n\n // .raft\n\n // .raft_log\n\n // .store;\n\n let (code, value) = service\n\n .execute(\n\n self.raft_group.as_ref().unwrap(),\n\n &mut self.pubsub,\n\n event.data,\n\n )\n\n .await\n\n .unwrap();\n\n if event.nid == Some(self.id) {\n\n self.network\n\n .event_reply(event.eid, code, value)\n\n .await\n\n .unwrap();\n\n }\n", "file_path": "src/raft_node.rs", "rank": 57, "score": 34374.41264425345 }, { "content": " last_state: StateRole::PreCandidate,\n\n }\n\n }\n\n\n\n pub fn set_raft_tick_duration(&mut self, d: Duration) {\n\n self.tick_duration = d;\n\n }\n\n\n\n // Create a raft follower.\n\n pub async fn create_raft_follower(\n\n logger: &Logger,\n\n id: NodeId,\n\n pubsub: pubsub::Channel,\n\n network: Network,\n\n ) -> Self {\n\n let storage = Storage::new(id).await;\n\n Self {\n\n logger: logger.clone(),\n\n id,\n\n raft_group: if storage.last_index().unwrap() == 1 {\n", "file_path": "src/raft_node.rs", "rank": 58, "score": 34373.535054728236 }, { "content": " cc.merge_from_bytes(&entry.data).unwrap();\n\n let _node_id = cc.node_id;\n\n\n\n let cs: ConfState = self\n\n .raft_group\n\n .as_mut()\n\n .unwrap()\n\n .try_lock()\n\n .unwrap()\n\n .apply_conf_change(&cc)\n\n .unwrap();\n\n self.set_conf_state(cs).await?;\n\n } else {\n\n // For normal proposals, extract the key-value pair and then\n\n // insert them into the kv engine.\n\n if let Ok(event) = serde_json::from_slice::<Event>(&entry.data) {\n\n if let Some(service) = self.services.get_mut(&event.sid) {\n\n // let _store = &self\n\n // .raft_group\n\n // .as_ref()\n", "file_path": "src/raft_node.rs", "rank": 59, "score": 34372.591474996334 }, { "content": " self.network\n\n .ack_proposal(p.proposer, p.id, false)\n\n .await\n\n .map_err(|e| {\n\n Error::Io(IoError::new(\n\n IoErrorKind::ConnectionAborted,\n\n format!(\"{}\", e),\n\n ))\n\n })?;\n\n }\n\n }\n\n }\n\n for p in pending.drain(..) {\n\n self.proposals.push_back(p)\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\npub async fn status<Storage>(node: &Mutex<raft::RawNode<Storage>>) -> Result<RaftNodeStatus>\n", "file_path": "src/raft_node.rs", "rank": 60, "score": 34371.53942078065 }, { "content": " )\n\n } else {\n\n write!(f, \"UNINITIALIZED\")\n\n }\n\n }\n\n}\n\n\n\nimpl<Storage, Network> RaftNode<Storage, Network>\n\nwhere\n\n Storage: storage::Storage + Send + Sync,\n\n Network: network::Network,\n\n{\n\n pub fn add_service(&mut self, sid: ServiceId, service: Box<dyn Service<Storage>>) {\n\n self.services.insert(sid, service);\n\n }\n\n pub fn pubsub(&mut self) -> &mut pubsub::Channel {\n\n &mut self.pubsub\n\n }\n\n pub async fn node_loop(&mut self) -> Result<()> {\n\n let mut ticks = async_std::stream::interval(self.tick_duration);\n", "file_path": "src/raft_node.rs", "rank": 61, "score": 34371.11862910368 }, { "content": " None\n\n } else {\n\n let mut cfg = example_config();\n\n cfg.id = id.0;\n\n Some(Mutex::new(RawNode::new(&cfg, storage, logger).unwrap()))\n\n },\n\n proposals: VecDeque::new(),\n\n network,\n\n pending_proposals: HashMap::new(),\n\n pending_acks: HashMap::new(),\n\n proposal_id: 0,\n\n tick_duration: Duration::from_millis(100),\n\n services: HashMap::new(),\n\n pubsub,\n\n last_state: StateRole::PreCandidate,\n\n }\n\n }\n\n\n\n // Initialize raft for followers.\n\n pub async fn initialize_raft_from_message(&mut self, msg: &Message) {\n", "file_path": "src/raft_node.rs", "rank": 62, "score": 34370.67907233198 }, { "content": " proposer,\n\n normal: None,\n\n conf_change: Some(cc.clone()),\n\n transfer_leader: None,\n\n proposed: 0,\n\n }\n\n }\n\n #[allow(dead_code)]\n\n pub fn normal(\n\n id: ProposalId,\n\n proposer: NodeId,\n\n eid: EventId,\n\n sid: ServiceId,\n\n data: Vec<u8>,\n\n ) -> Self {\n\n Self {\n\n id,\n\n proposer,\n\n normal: Some(Event {\n\n nid: Some(proposer),\n", "file_path": "src/raft_node.rs", "rank": 63, "score": 34370.37180220981 }, { "content": " let mut raft_group = self.raft_group.as_mut().unwrap().try_lock().unwrap();\n\n raft_group.step(msg)\n\n }\n\n async fn append(&self, entries: &[Entry]) -> Result<()> {\n\n let raft_node = self.raft_group.as_ref().unwrap().try_lock().unwrap();\n\n raft_node.store().append(entries).await\n\n }\n\n async fn apply_snapshot(&mut self, snapshot: Snapshot) -> Result<()> {\n\n let mut raft_node = self.raft_group.as_ref().unwrap().try_lock().unwrap();\n\n raft_node.mut_store().apply_snapshot(snapshot).await\n\n }\n\n\n\n // interface for raft-rs\n\n async fn set_conf_state(&mut self, cs: ConfState) -> Result<()> {\n\n let mut raft_node = self.raft_group.as_ref().unwrap().try_lock().unwrap();\n\n raft_node.mut_store().set_conf_state(cs).await\n\n }\n\n\n\n // interface for raft-rs\n\n async fn set_hard_state(&mut self, commit: u64, term: u64) -> Result<()> {\n", "file_path": "src/raft_node.rs", "rank": 64, "score": 34370.2362410535 }, { "content": " info!(self.logger, \"Handling proposal(remote)\"; \"proposal-id\" => proposal.id, \"proposer\" => proposal.proposer);\n\n self.network\n\n .ack_proposal(proposal.proposer, proposal.id, true)\n\n .await\n\n .map_err(|e| {\n\n Error::Io(IoError::new(\n\n IoErrorKind::ConnectionAborted,\n\n format!(\"{}\", e),\n\n ))\n\n })?;\n\n }\n\n }\n\n }\n\n }\n\n if let Some(last_committed) = committed_entries.last() {\n\n self.set_hard_state(last_committed.index, last_committed.term)\n\n .await?;\n\n }\n\n }\n\n // Call `RawNode::advance` interface to update position flags in the raft.\n", "file_path": "src/raft_node.rs", "rank": 65, "score": 34370.18727061533 }, { "content": " pubsub: pubsub::Channel,\n\n network: Network,\n\n ) -> Self {\n\n let mut cfg = example_config();\n\n cfg.id = id.0;\n\n\n\n let storage = Storage::new_with_conf_state(id, ConfState::from((vec![id.0], vec![]))).await;\n\n let raft_group = Some(Mutex::new(RawNode::new(&cfg, storage, logger).unwrap()));\n\n Self {\n\n logger: logger.clone(),\n\n id,\n\n raft_group,\n\n proposals: VecDeque::new(),\n\n network,\n\n pending_proposals: HashMap::new(),\n\n pending_acks: HashMap::new(),\n\n proposal_id: 0,\n\n tick_duration: Duration::from_millis(100),\n\n services: HashMap::new(),\n\n pubsub,\n", "file_path": "src/raft_node.rs", "rank": 66, "score": 34369.58951965549 }, { "content": " .await\n\n .unwrap();\n\n let mut conf_change = ConfChange::default();\n\n conf_change.node_id = id.0;\n\n conf_change.set_change_type(ConfChangeType::AddNode);\n\n let pid = self.next_pid();\n\n let proposal = Proposal::conf_change(pid, self.id, &conf_change);\n\n\n\n self.proposals.push_back(proposal);\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n pub fn next_pid(&mut self) -> ProposalId {\n\n let pid = self.proposal_id;\n\n self.proposal_id += 1;\n\n ProposalId(pid)\n\n }\n", "file_path": "src/raft_node.rs", "rank": 67, "score": 34369.571501260354 }, { "content": " println!(\"apply snapshot fail: {:?}, need to retry or panic\", e);\n\n return Err(e);\n\n }\n\n }\n\n\n\n // Send out the messages come from the node.\n\n for msg in ready.messages.drain(..) {\n\n self.network.send_msg(msg).await.unwrap()\n\n }\n\n\n\n // Apply all committed proposals.\n\n if let Some(committed_entries) = ready.committed_entries.take() {\n\n for entry in &committed_entries {\n\n if entry.data.is_empty() {\n\n // From new elected leaders.\n\n continue;\n\n }\n\n if let EntryType::EntryConfChange = entry.get_entry_type() {\n\n // For conf change messages, make them effective.\n\n let mut cc = ConfChange::default();\n", "file_path": "src/raft_node.rs", "rank": 68, "score": 34369.12512798286 }, { "content": " let mut raft_node = self.raft_group.as_ref().unwrap().try_lock().unwrap();\n\n raft_node.mut_store().set_hard_state(commit, term).await\n\n }\n\n\n\n pub(crate) async fn on_ready(&mut self) -> Result<()> {\n\n if self.raft_group.as_ref().is_none() {\n\n return Ok(());\n\n };\n\n\n\n if !self\n\n .raft_group\n\n .as_ref()\n\n .unwrap()\n\n .try_lock()\n\n .unwrap()\n\n .has_ready()\n\n {\n\n return Ok(());\n\n }\n\n\n", "file_path": "src/raft_node.rs", "rank": 69, "score": 34369.0352510512 }, { "content": "where\n\n Storage: storage::Storage,\n\n{\n\n let node = node.try_lock().unwrap();\n\n Ok(RaftNodeStatus {\n\n id: node.raft.id,\n\n role: format!(\"{:?}\", node.raft.state),\n\n promotable: node.raft.promotable(),\n\n pass_election_timeout: node.raft.pass_election_timeout(),\n\n election_elapsed: node.raft.election_elapsed,\n\n randomized_election_timeout: node.raft.randomized_election_timeout(),\n\n term: node.raft.term,\n\n last_index: node.raft.raft_log.store.last_index().unwrap_or(0),\n\n })\n\n}\n\n\n\npub(crate) fn propose_and_check_failed_proposal<Storage>(\n\n raft_group: &mut RawNode<Storage>,\n\n proposal: &mut Proposal,\n\n) -> Result<bool>\n", "file_path": "src/raft_node.rs", "rank": 70, "score": 34368.75716427523 }, { "content": " self.raft_group\n\n .as_mut()\n\n .unwrap()\n\n .try_lock()\n\n .unwrap()\n\n .advance(ready);\n\n Ok(())\n\n }\n\n\n\n pub(crate) async fn propose_all(&mut self) -> Result<()> {\n\n let mut raft_group = self.raft_group.as_mut().unwrap().try_lock().unwrap();\n\n let mut pending = Vec::new();\n\n for p in self.proposals.iter_mut().skip_while(|p| p.proposed > 0) {\n\n if propose_and_check_failed_proposal(&mut *raft_group, p)? {\n\n // if propose_and_check_failed_proposal(&mut *raft_group.lock().await, p)? {\n\n if p.proposer == self.id {\n\n if let Some(prop) = self.pending_proposals.remove(&p.id) {\n\n pending.push(prop);\n\n }\n\n } else {\n", "file_path": "src/raft_node.rs", "rank": 71, "score": 34368.454829544295 }, { "content": "\n\n pub fn version(&self) -> String {\n\n VERSION.to_string()\n\n }\n\n\n\n pub async fn node_known(&self, id: NodeId) -> bool {\n\n if let Some(ref g) = self.raft_group {\n\n g.try_lock()\n\n .unwrap()\n\n .raft\n\n .prs()\n\n .conf()\n\n .voters()\n\n .contains(id.0)\n\n } else {\n\n false\n\n }\n\n }\n\n pub async fn log(&self) {\n\n if let Some(g) = self.raft_group.as_ref() {\n", "file_path": "src/raft_node.rs", "rank": 72, "score": 34367.35012776192 }, { "content": " pub fn is_leader(&self) -> bool {\n\n self.raft_group\n\n .as_ref()\n\n .map(|g| g.try_lock().unwrap().raft.state == StateRole::Leader)\n\n .unwrap_or_default()\n\n }\n\n\n\n pub fn leader(&self) -> NodeId {\n\n NodeId(\n\n self.raft_group\n\n .as_ref()\n\n .map(|g| g.try_lock().unwrap().raft.leader_id)\n\n .unwrap_or_default(),\n\n )\n\n }\n\n\n\n // Create a raft leader only with itself in its configuration.\n\n pub async fn create_raft_leader(\n\n logger: &Logger,\n\n id: NodeId,\n", "file_path": "src/raft_node.rs", "rank": 73, "score": 34367.285708598596 }, { "content": "// unsafe impl Sync for RaftNodeStatus {}\n\n\n\npub struct RaftNode<Storage, Network>\n\nwhere\n\n Storage: storage::Storage,\n\n Network: network::Network,\n\n{\n\n logger: Logger,\n\n // None if the raft is not initialized.\n\n id: NodeId,\n\n pub raft_group: Option<Mutex<RawNode<Storage>>>,\n\n network: Network,\n\n proposals: VecDeque<Proposal>,\n\n pending_proposals: HashMap<ProposalId, Proposal>,\n\n pending_acks: HashMap<ProposalId, EventId>,\n\n proposal_id: u64,\n\n tick_duration: Duration,\n\n services: HashMap<ServiceId, Box<dyn Service<Storage>>>,\n\n pub pubsub: pubsub::Channel,\n\n last_state: StateRole,\n", "file_path": "src/raft_node.rs", "rank": 74, "score": 34367.100394843255 }, { "content": " \"pass-election-timeout\" => raft.pass_election_timeout(),\n\n \"election-elapsed\" => raft.election_elapsed,\n\n \"randomized-election-timeout\" => raft.randomized_election_timeout(),\n\n\n\n \"connections\" => format!(\"{:?}\", &self.network.connections()),\n\n )\n\n } else {\n\n error!(self.logger, \"UNINITIALIZED NODE {}\", self.id)\n\n }\n\n }\n\n\n\n pub fn is_running(&self) -> bool {\n\n self.raft_group.is_some()\n\n }\n\n pub fn role(&self) -> StateRole {\n\n self.raft_group\n\n .as_ref()\n\n .map(|g| g.try_lock().unwrap().raft.state)\n\n .unwrap_or(StateRole::PreCandidate)\n\n }\n", "file_path": "src/raft_node.rs", "rank": 75, "score": 34366.59561676196 }, { "content": " // Get the `Ready` with `RawNode::ready` interface.\n\n let mut ready = self\n\n .raft_group\n\n .as_mut()\n\n .unwrap()\n\n .try_lock()\n\n .unwrap()\n\n .ready();\n\n\n\n // Persistent raft logs. It's necessary because in `RawNode::advance` we stabilize\n\n // raft logs to the latest position.\n\n if let Err(e) = self.append(ready.entries()).await {\n\n println!(\"persist raft log fail: {:?}, need to retry or panic\", e);\n\n return Err(e);\n\n }\n\n\n\n // Apply the snapshot. It's necessary because in `RawNode::advance` we stabilize the snapshot.\n\n if *ready.snapshot() != Snapshot::default() {\n\n let s = ready.snapshot().clone();\n\n if let Err(e) = self.apply_snapshot(s).await {\n", "file_path": "src/raft_node.rs", "rank": 76, "score": 34366.20395986662 }, { "content": " }\n\n\n\n\n\n let this_state = self.role();\n\n if this_state != self.last_state {\n\n let prev_state = format!(\"{:?}\", self.last_state);\n\n let next_state = format!(\"{:?}\", this_state);\n\n debug!(&self.logger, \"State transition\"; \"last-state\" => prev_state.clone(), \"next-state\" => next_state.clone());\n\n self.pubsub\n\n .send(pubsub::Msg::new(\n\n \"uring\",\n\n PSURing::StateChange {\n\n prev_state,\n\n next_state,\n\n node: self.id,\n\n },\n\n )).await\n\n .unwrap();\n\n self.last_state = this_state;\n\n }\n", "file_path": "src/raft_node.rs", "rank": 77, "score": 34365.64781697606 }, { "content": "term: {}\n\nlast index: {}\n\nvoted for: {}\n\nvotes: {:?}\n\nnodes: {:?}\n\nconnections: {:?}\n\n \"#,\n\n &g.raft.id,\n\n role,\n\n g.raft.promotable(),\n\n g.raft.pass_election_timeout(),\n\n g.raft.election_elapsed,\n\n g.raft.randomized_election_timeout(),\n\n &g.raft.leader_id,\n\n &g.raft.term,\n\n &g.raft.store().last_index().unwrap_or(0),\n\n &g.raft.vote,\n\n &g.raft.prs().votes(),\n\n &g.raft.prs().conf().voters(),\n\n &self.network.connections(),\n", "file_path": "src/raft_node.rs", "rank": 78, "score": 34364.604001131716 }, { "content": " let role = self.role();\n\n let g = g.try_lock().unwrap();\n\n let raft = &g.raft;\n\n info!(\n\n self.logger,\n\n \"NODE STATE\";\n\n \"node-id\" => &raft.id,\n\n \"role\" => format!(\"{:?}\", role),\n\n\n\n \"leader-id\" => raft.leader_id,\n\n \"term\" => raft.term,\n\n \"first-index\" => raft.raft_log.store.first_index().unwrap_or(0),\n\n \"last-index\" => raft.raft_log.store.last_index().unwrap_or(0),\n\n\n\n \"vote\" => raft.vote,\n\n \"votes\" => format!(\"{:?}\", raft.prs().votes()),\n\n\n\n \"voters\" => format!(\"{:?}\", raft.prs().conf().voters()),\n\n\n\n \"promotable\" => raft.promotable(),\n", "file_path": "src/raft_node.rs", "rank": 79, "score": 34363.79432192221 }, { "content": " } else {\n\n proposal.proposed = last_index1;\n\n Ok(false)\n\n }\n\n}\n\n\n\npub struct Proposal {\n\n id: ProposalId,\n\n proposer: NodeId, // node id of the proposer\n\n normal: Option<Event>,\n\n conf_change: Option<ConfChange>, // conf change.\n\n transfer_leader: Option<u64>,\n\n // If it's proposed, it will be set to the index of the entry.\n\n pub(crate) proposed: u64,\n\n}\n\n\n\nimpl Proposal {\n\n pub fn conf_change(id: ProposalId, proposer: NodeId, cc: &ConfChange) -> Self {\n\n Self {\n\n id,\n", "file_path": "src/raft_node.rs", "rank": 80, "score": 34363.646412021895 }, { "content": "use protobuf::Message as PBMessage;\n\nuse raft::eraftpb::ConfState;\n\nuse raft::eraftpb::Message;\n\nuse raft::{prelude::*, Error, Result, StateRole};\n\nuse serde_derive::{Deserialize, Serialize};\n\nuse slog::Logger;\n\nuse std::collections::{HashMap, VecDeque};\n\nuse std::fmt;\n\nuse std::io::{Error as IoError, ErrorKind as IoErrorKind};\n\n\n", "file_path": "src/raft_node.rs", "rank": 81, "score": 34362.86197140373 }, { "content": " eid,\n\n sid,\n\n data,\n\n }),\n\n conf_change: None,\n\n transfer_leader: None,\n\n proposed: 0,\n\n }\n\n }\n\n}\n", "file_path": "src/raft_node.rs", "rank": 82, "score": 34361.95721216666 }, { "content": "}\n\n\n\nimpl<Storage, Network> fmt::Debug for RaftNode<Storage, Network>\n\nwhere\n\n Storage: storage::Storage + Send + Sync,\n\n Network: network::Network,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n if let Some(g) = self.raft_group.as_ref() {\n\n let role = self.role();\n\n let g = g.try_lock().unwrap();\n\n write!(\n\n f,\n\n r#\"node id: {}\n\nrole: {:?}\n\npromotable: {}\n\npass election timeout: {}\n\nelection elapsed: {}\n\nrandomized election timeout: {}\n\nleader id: {}\n", "file_path": "src/raft_node.rs", "rank": 83, "score": 34361.597741517646 }, { "content": "// Copyright 2018-2020, Wayfair GmbH\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n\n\nuse super::*;\n\nuse crate::network::ws::WsMessage;\n\nuse crate::storage::*;\n\nuse crate::version::VERSION;\n\nuse async_std::sync::Mutex;\n\nuse futures::SinkExt;\n", "file_path": "src/raft_node.rs", "rank": 84, "score": 34360.37200749725 }, { "content": " }\n\n }\n\n }\n\n if self\n\n .raft_group\n\n .as_ref()\n\n .unwrap()\n\n .try_lock()\n\n .unwrap()\n\n .raft\n\n .state\n\n == StateRole::Leader\n\n {\n\n // The leader should response to the clients, tell them if their proposals\n\n // succeeded or not.\n\n if let Some(proposal) = self.proposals.pop_front() {\n\n if proposal.proposer == self.id {\n\n info!(self.logger, \"Handling proposal(local)\"; \"proposal-id\" => proposal.id);\n\n self.pending_proposals.remove(&proposal.id);\n\n } else {\n", "file_path": "src/raft_node.rs", "rank": 85, "score": 34357.25136672623 }, { "content": "where\n\n Storage: ReadStorage,\n\n{\n\n let last_index1 = raft_group.raft.raft_log.last_index() + 1;\n\n if let Some(ref event) = proposal.normal {\n\n let data = serde_json::to_vec(&event).unwrap();\n\n raft_group.propose(vec![], data)?;\n\n } else if let Some(ref cc) = proposal.conf_change {\n\n raft_group.propose_conf_change(vec![], cc.clone())?;\n\n } else if let Some(_transferee) = proposal.transfer_leader {\n\n // TODO 0.8\n\n // TODO: implement transfer leader.\n\n unimplemented!();\n\n } else {\n\n }\n\n\n\n let last_index2 = raft_group.raft.raft_log.last_index() + 1;\n\n if last_index2 == last_index1 {\n\n // Propose failed, don't forget to respond to the client.\n\n Ok(true)\n", "file_path": "src/raft_node.rs", "rank": 86, "score": 34356.02206295608 }, { "content": " let handler: &mut Sender<_> = unsafe { std::mem::transmute(handler) };\n\n let rid = self.register_pending(id, outbound_channel);\n\n let msg = HandlerInboundMessage {\n\n id: rid,\n\n data: data.clone(),\n\n outbound_channel: self.handler_tx.clone(),\n\n service_id: None,\n\n };\n\n handler.send(msg).await?;\n\n true\n\n } else {\n\n let err = format!(\"Invalid protocol {}\", proto);\n\n outbound_channel\n\n .send(DriverOutboundMessage::error(\n\n id,\n\n DriverErrorType::BadProtocol,\n\n err,\n\n ))\n\n .await\n\n .is_ok()\n", "file_path": "protocol-driver/src/lib.rs", "rank": 87, "score": 33382.117639038916 }, { "content": " pub transport_tx: DriverInboundChannelSender,\n\n\n\n handler_rx: HandlerOutboundChannelReceiver,\n\n handler_tx: HandlerOutboundChannelSender,\n\n\n\n pending: HashMap<RequestId, (MessageId, DriverOutboundChannelSender)>,\n\n clients: HashMap<ClientId, ClientConnection>,\n\n protocol_handlers: HashMap<CustomProtocol, HandlerInboundChannelSender>,\n\n next_rid: u64,\n\n}\n\n\n\nimpl Default for Driver {\n\n fn default() -> Self {\n\n let (transport_tx, transport_rx) = channel(64);\n\n let (handler_tx, handler_rx) = channel(64);\n\n Self {\n\n transport_rx,\n\n transport_tx,\n\n handler_rx,\n\n handler_tx,\n", "file_path": "protocol-driver/src/lib.rs", "rank": 88, "score": 33378.66600583628 }, { "content": " let err = format!(\"Protocol {} is not enabled.\", proto);\n\n outbound_channel\n\n .send(DriverOutboundMessage::error(\n\n id,\n\n DriverErrorType::BadProtocol,\n\n err,\n\n ))\n\n .await\n\n .is_ok()\n\n } else if let Some(handler) = self.protocol_handlers.get(proto) {\n\n // Rust does not recognize that the mutable borrow of handler never will relocate\n\n // when we register pending so we got to transmute the hell out of it.\n\n let handler: &mut Sender<_> = unsafe { std::mem::transmute(handler) };\n\n let rid = self.register_pending(id, outbound_channel);\n\n let msg = HandlerInboundMessage {\n\n id: rid,\n\n data: data.clone(),\n\n outbound_channel: self.handler_tx.clone(),\n\n service_id: None,\n\n };\n", "file_path": "protocol-driver/src/lib.rs", "rank": 89, "score": 33375.37101616613 }, { "content": " }\n\n }\n\n\n\n async fn inbound_handler(&mut self, mut msg: HandlerInboundMessage) -> Result<(), SendError> {\n\n let id = msg.id;\n\n let mut outbound_channel = msg.outbound_channel;\n\n msg.outbound_channel = self.service_reply_tx.clone();\n\n match self.handler.inbound(msg).await {\n\n Reply::Ok(msg) => {\n\n self.pending.insert(id, outbound_channel);\n\n if let Some(ref mut next) = self.next_tx {\n\n next.send(msg).await?;\n\n };\n\n }\n\n Reply::Terminate => {\n\n self.pending.insert(id, outbound_channel);\n\n }\n\n Reply::Err(e) => {\n\n outbound_channel\n\n .send(HandlerOutboundMessage::error(id, e, \"Interceptor failed\"))\n\n .await?;\n\n }\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "protocol-driver/src/interceptor.rs", "rank": 90, "score": 33375.29977677965 }, { "content": " T: ToString,\n\n {\n\n Self {\n\n id,\n\n close: true,\n\n data: DriverOutboundData::Err(DriverError {\n\n error,\n\n message: message.to_string(),\n\n }),\n\n }\n\n }\n\n}\n\npub type HandlerOutboundChannelReceiver = Receiver<HandlerOutboundMessage>;\n\npub type HandlerOutboundChannelSender = Sender<HandlerOutboundMessage>;\n\n\n\npub type HandlerInboundChannelReceiver = Receiver<HandlerInboundMessage>;\n\npub type HandlerInboundChannelSender = Sender<HandlerInboundMessage>;\n\n\n\npub struct Driver {\n\n transport_rx: DriverInboundChannelReceiver,\n", "file_path": "protocol-driver/src/lib.rs", "rank": 91, "score": 33373.22409991461 }, { "content": " handler.send(msg).await?;\n\n true\n\n } else {\n\n let err = format!(\"Protocol {} is not known.\", proto);\n\n outbound_channel\n\n .send(DriverOutboundMessage::error(\n\n id,\n\n DriverErrorType::BadProtocol,\n\n err,\n\n ))\n\n .await\n\n .is_ok()\n\n }\n\n }\n\n (_, DriverInboundData::Disconnect) => false,\n\n };\n\n if !keep_client {\n\n self.clients.remove(&id.client);\n\n }\n\n Ok(())\n", "file_path": "protocol-driver/src/lib.rs", "rank": 92, "score": 33370.31744081165 }, { "content": " }\n\n\n\n Ok(())\n\n }\n\n\n\n #[allow(mutable_transmutes)]\n\n async fn inbound_handler(&mut self, msg: DriverInboundMessage) -> Result<(), SendError> {\n\n let DriverInboundMessage {\n\n data,\n\n id,\n\n mut outbound_channel,\n\n } = msg;\n\n let client = self.clients.entry(id.client).or_default();\n\n let keep_client = match dbg!((&client.protocol, &data)) {\n\n // When we're in connect\n\n (Protocol::Connect, DriverInboundData::Connect(protos)) => {\n\n //TODO: Validate protocols\n\n client.protocol = Protocol::None;\n\n client.enabled_protocols = protos.clone();\n\n let reply = DriverInboundReply::Connected(client.enabled_protocols.clone());\n", "file_path": "protocol-driver/src/lib.rs", "rank": 93, "score": 33369.84605320467 }, { "content": " Err(e) => HandlerOutboundMessage::error(msg.id, e, \"Interceptor failed\"),\n\n }\n\n };\n\n\n\n if msg.close {\n\n if let Some(mut tx) = self.pending.remove(&msg.id) {\n\n tx.send(msg).await\n\n } else {\n\n println!(\"No pending reply to send to\");\n\n // TODO: handle error\n\n Ok(())\n\n }\n\n } else {\n\n if let Some(tx) = self.pending.get_mut(&msg.id) {\n\n tx.send(msg).await\n\n } else {\n\n println!(\"No pending reply to send to\");\n\n // TODO: handle error\n\n Ok(())\n\n }\n", "file_path": "protocol-driver/src/interceptor.rs", "rank": 94, "score": 33368.63575515039 }, { "content": " }\n\n (Protocol::None, _) => outbound_channel\n\n .send(DriverOutboundMessage::error(\n\n id,\n\n DriverErrorType::InvalidRequest,\n\n \"No protocol specified\",\n\n ))\n\n .await\n\n .is_ok(),\n\n // we have a default\n\n (Protocol::Custom(_), DriverInboundData::Connect(_)) => outbound_channel\n\n .send(DriverOutboundMessage::error(\n\n id,\n\n DriverErrorType::InvalidRequest,\n\n \"Can not call Connect twice\",\n\n ))\n\n .await\n\n .is_ok(),\n\n (Protocol::Custom(proto), DriverInboundData::Message(data)) => {\n\n if !client.enabled_protocols.contains(&proto) {\n", "file_path": "protocol-driver/src/lib.rs", "rank": 95, "score": 33368.50544684832 }, { "content": "{\n\n // interceptor In Tx\n\n pub tx: HandlerInboundChannelSender,\n\n rx: HandlerInboundChannelReceiver,\n\n\n\n // interceptor In Rx\n\n //network: Sender<UrMsg>,\n\n next_tx: Option<HandlerInboundChannelSender>,\n\n\n\n // Interceptor Out Rx\n\n service_reply_tx: HandlerOutboundChannelSender,\n\n service_reply_rx: HandlerOutboundChannelReceiver,\n\n\n\n // Interceptor Out Tx\n\n pending: HashMap<RequestId, HandlerOutboundChannelSender>,\n\n handler: Handler,\n\n}\n\n\n\npub enum Reply {\n\n Ok(HandlerInboundMessage),\n", "file_path": "protocol-driver/src/interceptor.rs", "rank": 96, "score": 33368.3087408627 } ]
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 package_id = 1;\n\n info!(\"Resource with package id 0 found. Recreate id with current package id\");\n\n }\n\n\n\n package_id\n\n }\n\n\n\n fn get_spec(&self) -> u8 {\n\n ((self & 0x00FF0000) >> 16) as u8\n\n }\n\n\n\n fn get_id(&self) -> u16 {\n\n (self & 0xFFFF) as u16\n\n }\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 0, "score": 98165.12831906407 }, { "content": "pub trait Library {\n\n fn get_name(&self) -> Option<String>;\n\n fn format_reference(\n\n &self,\n\n id: u32,\n\n key: u32,\n\n namespace: Option<String>,\n\n prefix: &str,\n\n ) -> Result<String, Error>;\n\n // fn get_entries(&self) -> &Entries;\n\n fn get_entry(&self, id: u32) -> Result<&Entry, Error>;\n\n fn get_entries_string(&self, str_id: u32) -> Result<Rc<String>, Error>;\n\n fn get_spec_string(&self, str_id: u32) -> Result<Rc<String>, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 1, "score": 98147.97205524136 }, { "content": "/// Implementors are able to be converted to well formed chunks as expected on `ChunkLoaderStream`\n\npub trait OwnedBuf: Debug {\n\n /// Token that identifies the current chunk\n\n fn get_token(&self) -> u16;\n\n /// Return the bytes corresponding to chunk's body\n\n fn get_body_data(&self) -> Result<Vec<u8>, Error>;\n\n\n\n /// Return the bytes corresponding to chunk's header\n\n fn get_header(&self) -> Result<Vec<u8>, Error> {\n\n Ok(Vec::new())\n\n }\n\n\n\n /// Convert the given `OwnedBuf` to a well formed chunk in form of vector of bytes\n\n fn to_vec(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n let body = self.get_body_data().context(\"could not read chunk body\")?;\n\n\n\n self.write_header(&mut out, &body)\n\n .context(\"could not write header\")?;\n\n\n\n out.extend(body.iter());\n", "file_path": "src/model/owned/mod.rs", "rank": 2, "score": 97758.20788933177 }, { "content": "pub trait Resources<'a> {\n\n type Library: Library + LibraryBuilder<'a>;\n\n\n\n fn get_package(&self, package_id: u8) -> Option<&Self::Library>;\n\n fn get_mut_package(&mut self, package_id: u8) -> Option<&mut Self::Library>;\n\n fn get_main_package(&self) -> Option<&Self::Library>;\n\n fn is_main_package(&self, package_id: u8) -> bool;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 3, "score": 96013.93718209637 }, { "content": "// Traits\n\npub trait StringTable {\n\n fn get_strings_len(&self) -> u32;\n\n fn get_styles_len(&self) -> u32;\n\n fn get_string(&self, idx: u32) -> Result<Rc<String>, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 4, "score": 92685.18980815778 }, { "content": "pub trait TableType {\n\n type Configuration: Configuration;\n\n\n\n fn get_id(&self) -> Result<u8, Error>;\n\n fn get_amount(&self) -> Result<u32, Error>;\n\n fn get_configuration(&self) -> Result<Self::Configuration, Error>;\n\n fn get_entry(&self, index: u32) -> Result<Entry, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 5, "score": 92685.18980815778 }, { "content": "pub trait LibraryBuilder<'a> {\n\n type StringTable: StringTable;\n\n type TypeSpec: TypeSpec;\n\n\n\n fn set_string_table(&mut self, string_table: Self::StringTable, origin: Origin);\n\n fn add_entries(&mut self, entries: Entries);\n\n fn add_type_spec(&mut self, type_spec: Self::TypeSpec) -> Result<(), Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 6, "score": 92192.50244881114 }, { "content": "fn parse_xml<'a>(content: &[u8], resources: &'a Resources<'a>) -> Result<String, Error> {\n\n let cursor = Cursor::new(content);\n\n let mut visitor = XmlVisitor::new(resources);\n\n\n\n Executor::xml(cursor, &mut visitor)?;\n\n\n\n match *visitor.get_root() {\n\n Some(ref root) => match *visitor.get_string_table() {\n\n Some(_) => {\n\n let res =\n\n Xml::encode(visitor.get_namespaces(), root).context(\"could note encode XML\")?;\n\n return Ok(res);\n\n }\n\n None => {\n\n println!(\"No string table found\");\n\n }\n\n },\n\n None => {\n\n println!(\"No root on target XML\");\n\n }\n\n }\n\n\n\n bail!(\"could not decode XML\")\n\n}\n", "file_path": "examples/converter.rs", "rank": 7, "score": 88878.05495963762 }, { "content": "pub fn compare_chunks(expected: &[u8], data: &[u8]) {\n\n if expected.len() != data.len() {\n\n eprintln!(\"Expected len: {}; Data len: {}\", expected.len(), data.len());\n\n }\n\n\n\n let mut is_equal = true;\n\n\n\n let len = if expected.len() < data.len() {\n\n expected.len()\n\n } else {\n\n data.len()\n\n };\n\n\n\n for i in 0..len {\n\n if expected[i] != data[i] {\n\n eprintln!(\"Difference @{}: {} <-> {}\", i, expected[i], data[i]);\n\n is_equal = false;\n\n }\n\n }\n\n\n", "file_path": "src/test.rs", "rank": 8, "score": 88184.03483713842 }, { "content": "fn run() -> Result<(), Error> {\n\n let apk_path = match env::args().nth(1) {\n\n Some(path) => path,\n\n None => {\n\n println!(\"Usage: converter <path>\");\n\n return Ok(());\n\n }\n\n };\n\n\n\n let target_file = match env::args().nth(2) {\n\n Some(path) => path,\n\n None => {\n\n println!(\"Usage: converter <path>\");\n\n return Ok(());\n\n }\n\n };\n\n\n\n // Android lib\n\n let android_resources_content = abxml::STR_ARSC.to_owned();\n\n\n", "file_path": "examples/converter.rs", "rank": 9, "score": 83014.43291608396 }, { "content": "fn run() -> Result<(), Error> {\n\n let apk_path = match env::args().nth(1) {\n\n Some(path) => path,\n\n None => {\n\n println!(\"Usage: exporter <apk> <path>\");\n\n return Ok(());\n\n }\n\n };\n\n\n\n let output = match env::args().nth(2) {\n\n Some(path) => path,\n\n None => {\n\n println!(\"Usage: exporter <apk> <path>\");\n\n return Ok(());\n\n }\n\n };\n\n\n\n let mut apk = Apk::from_path(&apk_path).context(\"error loading APK\")?;\n\n apk.export(Path::new(&output), true)\n\n .context(\"APK could not be exported\")?;\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/exporter.rs", "rank": 10, "score": 83014.43291608396 }, { "content": "pub trait TypeSpec {\n\n fn get_id(&self) -> Result<u16, Error>;\n\n fn get_amount(&self) -> Result<u32, Error>;\n\n fn get_flag(&self, index: u32) -> Result<u32, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 11, "score": 80846.58169965443 }, { "content": "use byteorder::{LittleEndian, WriteBytesExt};\n\nuse failure::{format_err, Error};\n\n\n\nconst MASK_COMPLEX: u16 = 0x0001;\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct EntryHeader {\n\n header_size: u16,\n\n flags: u16,\n\n key_index: u32,\n\n}\n\n\n\nimpl EntryHeader {\n\n pub fn new(header_size: u16, flags: u16, key_index: u32) -> Self {\n\n Self {\n\n header_size,\n\n flags,\n\n key_index,\n\n }\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 12, "score": 79430.03800419917 }, { "content": " out.write_u8(e.get_type())?;\n\n\n\n // Value\n\n out.write_u32::<LittleEndian>(e.get_value())?;\n\n }\n\n\n\n Ok(out)\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub enum Entry {\n\n Empty(u32, u32),\n\n Simple(SimpleEntry),\n\n Complex(ComplexEntry),\n\n}\n\n\n\nimpl Entry {\n\n pub fn simple(&self) -> Result<&SimpleEntry, Error> {\n\n if let Self::Simple(simple) = self {\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 13, "score": 79429.7120094961 }, { "content": " out.write_u8(self.get_type())?;\n\n\n\n // Value\n\n out.write_u32::<LittleEndian>(self.get_value())?;\n\n\n\n Ok(out)\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct ComplexEntry {\n\n id: u32,\n\n key_index: u32,\n\n parent_entry_id: u32,\n\n entries: Vec<SimpleEntry>,\n\n}\n\n\n\nimpl ComplexEntry {\n\n pub fn new(id: u32, key_index: u32, parent_entry_id: u32, entries: Vec<SimpleEntry>) -> Self {\n\n Self {\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 14, "score": 79428.06031315555 }, { "content": " }\n\n\n\n None\n\n }\n\n\n\n pub fn get_entries(&self) -> &Vec<SimpleEntry> {\n\n &self.entries\n\n }\n\n\n\n pub fn to_vec(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n\n\n // Header size\n\n out.write_u16::<LittleEndian>(16)?;\n\n\n\n // Flags => Complex entry\n\n out.write_u16::<LittleEndian>(1)?;\n\n\n\n // Key index\n\n out.write_u32::<LittleEndian>(self.key_index)?;\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 15, "score": 79425.32643405496 }, { "content": " }\n\n\n\n pub fn is_complex(self) -> bool {\n\n (self.flags & MASK_COMPLEX) == MASK_COMPLEX\n\n }\n\n\n\n pub fn get_key_index(self) -> u32 {\n\n self.key_index\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct SimpleEntry {\n\n id: u32,\n\n key_index: u32,\n\n value_type: u8,\n\n value_data: u32,\n\n}\n\n\n\nimpl SimpleEntry {\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 16, "score": 79424.68975071612 }, { "content": " Ok(simple)\n\n } else {\n\n Err(format_err!(\"asked for a complex entry on a simple one\"))\n\n }\n\n }\n\n\n\n pub fn complex(&self) -> Result<&ComplexEntry, Error> {\n\n if let Self::Complex(complex) = self {\n\n Ok(complex)\n\n } else {\n\n Err(format_err!(\"asked for a simple entry on a complex one\"))\n\n }\n\n }\n\n\n\n pub fn is_empty(&self) -> bool {\n\n if let Self::Empty(_, _) = self {\n\n true\n\n } else {\n\n false\n\n }\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 17, "score": 79423.8950011574 }, { "content": "\n\n pub fn get_value(&self) -> u32 {\n\n self.value_data\n\n }\n\n\n\n pub fn to_vec(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n\n\n // Header size\n\n out.write_u16::<LittleEndian>(8)?;\n\n\n\n // Flags => Simple entry\n\n out.write_u16::<LittleEndian>(0)?;\n\n\n\n // Key index\n\n out.write_u32::<LittleEndian>(self.get_key())?;\n\n\n\n // Value type\n\n out.write_u16::<LittleEndian>(8)?;\n\n out.write_u8(0)?;\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 18, "score": 79423.8884768599 }, { "content": " }\n\n\n\n pub fn get_id(&self) -> u32 {\n\n match self {\n\n Self::Complex(complex) => complex.get_id(),\n\n Self::Simple(simple) => simple.get_id(),\n\n Self::Empty(id, _) => *id,\n\n }\n\n }\n\n\n\n pub fn get_key(&self) -> u32 {\n\n match self {\n\n Self::Complex(complex) => complex.get_key(),\n\n Self::Simple(simple) => simple.get_key(),\n\n Self::Empty(_, key) => *key,\n\n }\n\n }\n\n\n\n pub fn to_vec(&self) -> Result<Vec<u8>, Error> {\n\n match self {\n\n Self::Complex(complex) => complex.to_vec(),\n\n Self::Simple(simple) => simple.to_vec(),\n\n Self::Empty(_, _) => Ok(Vec::new()),\n\n }\n\n }\n\n}\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 19, "score": 79423.10277782152 }, { "content": " id,\n\n key_index,\n\n parent_entry_id,\n\n entries,\n\n }\n\n }\n\n\n\n pub fn get_id(&self) -> u32 {\n\n self.id\n\n }\n\n\n\n pub fn get_key(&self) -> u32 {\n\n self.key_index\n\n }\n\n\n\n pub fn get_referent_id(&self, value: u32) -> Option<u32> {\n\n for e in &self.entries {\n\n if e.get_value() == value {\n\n return Some(e.get_id());\n\n }\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 20, "score": 79422.81500525886 }, { "content": " pub fn new(id: u32, key_index: u32, value_type: u8, value_data: u32) -> Self {\n\n Self {\n\n id,\n\n key_index,\n\n value_type,\n\n value_data,\n\n }\n\n }\n\n\n\n pub fn get_id(&self) -> u32 {\n\n self.id\n\n }\n\n\n\n pub fn get_key(&self) -> u32 {\n\n self.key_index\n\n }\n\n\n\n pub fn get_type(&self) -> u8 {\n\n self.value_type\n\n }\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 21, "score": 79422.32929584 }, { "content": "\n\n // Parent entry\n\n out.write_u32::<LittleEndian>(self.parent_entry_id)?;\n\n\n\n // Children entry amount\n\n let children_amount = self.entries.len() as u32;\n\n if children_amount == 0 {\n\n out.write_u32::<LittleEndian>(0xFFFF_FFFF)?;\n\n } else {\n\n out.write_u32::<LittleEndian>(self.entries.len() as u32)?;\n\n }\n\n\n\n for e in &self.entries {\n\n // TODO: Unify this with simple entry without header\n\n // Key index\n\n out.write_u32::<LittleEndian>(e.get_id())?;\n\n\n\n // Value type\n\n out.write_u16::<LittleEndian>(8)?;\n\n out.write_u8(0)?;\n", "file_path": "src/model/owned/table_type/entry.rs", "rank": 22, "score": 79419.30216373832 }, { "content": "pub trait Configuration {\n\n fn get_size(&self) -> Result<u32, Error>;\n\n fn get_mcc(&self) -> Result<u16, Error>;\n\n fn get_mnc(&self) -> Result<u16, Error>;\n\n fn get_language(&self) -> Result<String, Error>;\n\n fn get_region(&self) -> Result<String, Error>;\n\n fn get_orientation(&self) -> Result<u8, Error>;\n\n fn get_touchscreen(&self) -> Result<u8, Error>;\n\n fn get_density(&self) -> Result<u16, Error>;\n\n fn get_keyboard(&self) -> Result<u8, Error>;\n\n fn get_navigation(&self) -> Result<u8, Error>;\n\n fn get_input_flags(&self) -> Result<u8, Error>;\n\n fn get_width(&self) -> Result<u16, Error>;\n\n fn get_height(&self) -> Result<u16, Error>;\n\n fn get_sdk_version(&self) -> Result<u16, Error>;\n\n fn get_min_sdk_version(&self) -> Result<u16, Error>;\n\n fn get_screen_layout(&self) -> Result<u8, Error>;\n\n fn get_ui_mode(&self) -> Result<u8, Error>;\n\n fn get_smallest_screen(&self) -> Result<u16, Error>;\n\n fn get_screen_width(&self) -> Result<u16, Error>;\n", "file_path": "src/model/mod.rs", "rank": 23, "score": 68799.21229255831 }, { "content": "// TODO: Decide if the trait should return Results or not\n\npub trait Package {\n\n fn get_id(&self) -> Result<u32, Error>;\n\n fn get_name(&self) -> Result<String, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 24, "score": 68799.21229255831 }, { "content": "pub trait AttributeTrait {\n\n /// Return the namespace index. If there is no namespace, it will return 0xFFFF_FFFF\n\n fn get_namespace(&self) -> Result<u32, Error>;\n\n /// Returns the index of the attribute on the string table\n\n fn get_name(&self) -> Result<u32, Error>;\n\n /// Returns the ¿class?\n\n fn get_class(&self) -> Result<u32, Error>;\n\n /// Returns the data type (see `Values`)\n\n fn get_resource_value(&self) -> Result<u32, Error>;\n\n /// Returns the value (see `Values`)\n\n fn get_data(&self) -> Result<u32, Error>;\n\n\n\n /// Creates a `Value` depending on the data type and data value\n\n fn get_value(&self) -> Result<Value, Error> {\n\n let data_type = ((self.get_resource_value()? >> 24) & 0xFF) as u8;\n\n let data_value = self.get_data()?;\n\n let class = self.get_class()?;\n\n\n\n let value = if class == 0xFFFF_FFFF {\n\n Value::create(data_type, data_value)?\n\n } else {\n\n Value::StringReference(class)\n\n };\n\n\n\n Ok(value)\n\n }\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 25, "score": 66208.56199470015 }, { "content": "pub trait NamespaceStart {\n\n fn get_line(&self) -> Result<u32, Error>;\n\n fn get_prefix<S: StringTable>(&self, string_table: &S) -> Result<Rc<String>, Error>;\n\n fn get_namespace<S: StringTable>(&self, string_table: &S) -> Result<Rc<String>, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 26, "score": 66208.56199470015 }, { "content": "pub trait NamespaceEnd {\n\n fn get_line(&self) -> Result<u32, Error>;\n\n fn get_prefix<S: StringTable>(&self, string_table: &S) -> Result<Rc<String>, Error>;\n\n fn get_namespace<S: StringTable>(&self, string_table: &S) -> Result<Rc<String>, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 27, "score": 66208.56199470015 }, { "content": "pub trait TagEnd {\n\n fn get_id(&self) -> Result<u32, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 28, "score": 66208.56199470015 }, { "content": "/// Trait that represents a XML tag start\n\npub trait TagStart {\n\n /// Type of the attributes\n\n type Attribute: AttributeTrait;\n\n\n\n /// Return the ¿line in which the tag appear?\n\n fn get_line(&self) -> Result<u32, Error>;\n\n /// Return the content of the unknown field1\n\n fn get_field1(&self) -> Result<u32, Error>;\n\n /// Return the namespace index. If there is no namespace, it will return 0xFFFF_FFFF\n\n fn get_namespace_index(&self) -> Result<u32, Error>;\n\n /// Returns the index of the tag name on the string table\n\n fn get_element_name_index(&self) -> Result<u32, Error>;\n\n /// Return the content of the unknown field1\n\n fn get_field2(&self) -> Result<u32, Error>;\n\n /// Return the amount of attributes this tag contains\n\n fn get_attributes_amount(&self) -> Result<u32, Error>;\n\n /// Returns the ¿class?\n\n fn get_class(&self) -> Result<u32, Error>;\n\n /// Returns the attribute on the `index` position or error if it is greater than\n\n /// `get_attributes_amount`\n\n fn get_attribute(&self, index: u32) -> Result<Self::Attribute, Error>;\n\n}\n\n\n", "file_path": "src/model/mod.rs", "rank": 29, "score": 66208.56199470015 }, { "content": "pub trait ChunkVisitor<'a> {\n\n fn visit_string_table(&mut self, _string_table: StringTableWrapper<'a>, _origin: Origin) {}\n\n fn visit_package(&mut self, _package: PackageWrapper<'a>) {}\n\n fn visit_table_type(&mut self, _table_type: TableTypeWrapper<'a>) {}\n\n fn visit_type_spec(&mut self, _type_spec: TypeSpecWrapper<'a>) {}\n\n fn visit_xml_namespace_start(&mut self, _namespace_start: XmlNamespaceStartWrapper<'a>) {}\n\n fn visit_xml_namespace_end(&mut self, _namespace_end: XmlNamespaceEndWrapper<'a>) {}\n\n fn visit_xml_tag_start(&mut self, _tag_start: XmlTagStartWrapper<'a>) {}\n\n fn visit_xml_tag_end(&mut self, _tag_end: XmlTagEndWrapper<'a>) {}\n\n fn visit_xml_text(&mut self, _text: XmlTextWrapper<'a>) {}\n\n fn visit_resource(&mut self, _resource: ResourceWrapper<'a>) {}\n\n}\n\n\n\n/// Methods to decode a binary resource.arsc file or a binary xml file\n\n#[derive(Debug, Copy, Clone)]\n\npub struct Executor;\n\n\n\nimpl Executor {\n\n /// Given a valid `resources.arsc` file contents, it will call to the proper methods on the\n\n /// given visitor.\n", "file_path": "src/visitor/mod.rs", "rank": 30, "score": 65541.34074984048 }, { "content": "use std::io::Cursor;\n\n\n\nuse byteorder::{LittleEndian, ReadBytesExt};\n\nuse failure::{ensure, Error};\n\n\n\nuse crate::model::owned::ResourcesBuf;\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug)]\n\npub struct ResourceWrapper<'a> {\n\n raw_data: &'a [u8],\n\n}\n\n\n\nimpl<'a> ResourceWrapper<'a> {\n\n pub fn new(raw_data: &'a [u8]) -> Self {\n\n Self { raw_data }\n\n }\n\n\n\n pub fn get_resources(&self) -> Result<Vec<u32>, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n", "file_path": "src/chunks/resource.rs", "rank": 31, "score": 63135.22372777856 }, { "content": "\n\n pub fn to_buffer(&self) -> Result<ResourcesBuf, Error> {\n\n let mut owned = ResourcesBuf::default();\n\n\n\n for r in &self.get_resources()? {\n\n owned.push_resource(*r);\n\n }\n\n\n\n Ok(owned)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::ResourceWrapper;\n\n use crate::model::owned::{OwnedBuf, ResourcesBuf};\n\n\n\n #[test]\n\n fn it_can_not_decode_a_buffer_with_an_invalid_size() {\n\n let mut resources = ResourcesBuf::default();\n", "file_path": "src/chunks/resource.rs", "rank": 32, "score": 63128.04246251426 }, { "content": " cursor.set_position(4);\n\n\n\n let count = cursor.read_u32::<LittleEndian>()?;\n\n let amount_of_resources = (count / 4) - 2;\n\n\n\n ensure!(\n\n count <= self.raw_data.len() as u32,\n\n \"there is not enough data on the buffer ({}) to read the reported resources count ({})\",\n\n self.raw_data.len(),\n\n count\n\n );\n\n\n\n let mut resources = Vec::with_capacity(amount_of_resources as usize);\n\n\n\n for _ in 0..amount_of_resources {\n\n resources.push(cursor.read_u32::<LittleEndian>()?);\n\n }\n\n\n\n Ok(resources)\n\n }\n", "file_path": "src/chunks/resource.rs", "rank": 33, "score": 63118.11579748386 }, { "content": " resources.push_resource(111);\n\n resources.push_resource(222);\n\n let mut out = resources.to_vec().unwrap();\n\n\n\n out[4] = 255;\n\n\n\n let wrapper = ResourceWrapper::new(&out);\n\n\n\n let result = wrapper.get_resources();\n\n assert!(result.is_err());\n\n assert_eq!(\n\n \"there is not enough data on the buffer (16) to read the reported resources count \\\n\n (255)\",\n\n result.err().unwrap().to_string()\n\n );\n\n }\n\n}\n", "file_path": "src/chunks/resource.rs", "rank": 34, "score": 63115.107953940096 }, { "content": "use byteorder::{LittleEndian, WriteBytesExt};\n\nuse failure::Error;\n\n\n\nuse crate::{chunks::TOKEN_RESOURCE, model::owned::OwnedBuf};\n\n\n\n#[derive(Default, Debug)]\n\npub struct ResourcesBuf {\n\n resources: Vec<u32>,\n\n}\n\n\n\nimpl ResourcesBuf {\n\n pub fn push_resource(&mut self, resource: u32) {\n\n self.resources.push(resource);\n\n }\n\n\n\n pub fn pop_resource(&mut self) -> Option<u32> {\n\n self.resources.pop()\n\n }\n\n}\n\n\n", "file_path": "src/model/owned/resources.rs", "rank": 35, "score": 58421.70588570712 }, { "content": "impl OwnedBuf for ResourcesBuf {\n\n fn get_token(&self) -> u16 {\n\n TOKEN_RESOURCE\n\n }\n\n\n\n fn get_body_data(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n\n\n for r in &self.resources {\n\n out.write_u32::<LittleEndian>(*r)?;\n\n }\n\n\n\n Ok(out)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{OwnedBuf, ResourcesBuf};\n\n use crate::{chunks::ResourceWrapper, raw_chunks, test::compare_chunks};\n", "file_path": "src/model/owned/resources.rs", "rank": 36, "score": 58411.878471381584 }, { "content": "\n\n #[test]\n\n fn it_can_generate_a_chunk_with_the_given_data() {\n\n let mut resources = ResourcesBuf::default();\n\n resources.push_resource(111);\n\n resources.push_resource(222);\n\n\n\n let out = resources.to_vec().unwrap();\n\n\n\n let wrapper = ResourceWrapper::new(&out);\n\n\n\n let expected_resources: Vec<u32> = vec![111, 222];\n\n\n\n assert_eq!(expected_resources, wrapper.get_resources().unwrap());\n\n }\n\n\n\n #[test]\n\n fn it_can_generate_an_empty_chunk() {\n\n let resources = ResourcesBuf::default();\n\n let out = resources.to_vec().unwrap();\n", "file_path": "src/model/owned/resources.rs", "rank": 37, "score": 58404.12875523308 }, { "content": "\n\n let wrapper = ResourceWrapper::new(&out);\n\n\n\n let expected_resources: Vec<u32> = vec![];\n\n\n\n assert_eq!(expected_resources, wrapper.get_resources().unwrap());\n\n }\n\n\n\n #[test]\n\n fn identity() {\n\n let raw = raw_chunks::EXAMPLE_RESOURCES;\n\n\n\n let wrapper = ResourceWrapper::new(&raw);\n\n let owned = wrapper.to_buffer().unwrap();\n\n let new_raw = owned.to_vec().unwrap();\n\n\n\n compare_chunks(&raw, &new_raw);\n\n }\n\n}\n", "file_path": "src/model/owned/resources.rs", "rank": 38, "score": 58401.79630767116 }, { "content": "pub struct StringTableWrapper<'a> {\n\n raw_data: &'a [u8],\n\n}\n\n\n\nimpl<'a> StringTableWrapper<'a> {\n\n pub fn new(raw_data: &'a [u8]) -> Self {\n\n Self { raw_data }\n\n }\n\n\n\n pub fn get_flags(&self) -> u32 {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(16);\n\n\n\n cursor.read_u32::<LittleEndian>().unwrap_or(0)\n\n }\n\n\n\n pub fn to_buffer(&self) -> Result<StringTableBuf, Error> {\n\n let mut owned = StringTableBuf::default();\n\n\n\n if !self.is_utf8() {\n", "file_path": "src/chunks/string_table.rs", "rank": 39, "score": 58365.97433580922 }, { "content": "use std::{\n\n cell::RefCell,\n\n collections::{\n\n hash_map::Entry::{Occupied, Vacant},\n\n HashMap,\n\n },\n\n io::Cursor,\n\n rc::Rc,\n\n};\n\n\n\nuse byteorder::{LittleEndian, ReadBytesExt};\n\nuse encoding::codec::{utf_16, utf_8};\n\nuse failure::{ensure, format_err, Error};\n\n\n\nuse crate::model::{\n\n owned::{Encoding as EncodingType, StringTableBuf},\n\n StringTable,\n\n};\n\n\n\n#[derive(Debug)]\n", "file_path": "src/chunks/string_table.rs", "rank": 40, "score": 58365.830336976556 }, { "content": " .and_then(|position| self.parse_string(position as u32))?;\n\n\n\n Ok(Rc::new(string))\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct StringTableCache<S: StringTable> {\n\n inner: S,\n\n cache: RefCell<HashMap<u32, Rc<String>>>,\n\n}\n\n\n\nimpl<S: StringTable> StringTableCache<S> {\n\n pub fn new(inner: S) -> Self {\n\n Self {\n\n inner,\n\n cache: RefCell::new(HashMap::new()),\n\n }\n\n }\n\n}\n", "file_path": "src/chunks/string_table.rs", "rank": 41, "score": 58362.721398407964 }, { "content": "\n\nimpl<S: StringTable> StringTable for StringTableCache<S> {\n\n fn get_strings_len(&self) -> u32 {\n\n self.inner.get_strings_len()\n\n }\n\n\n\n fn get_styles_len(&self) -> u32 {\n\n self.inner.get_styles_len()\n\n }\n\n\n\n fn get_string(&self, idx: u32) -> Result<Rc<String>, Error> {\n\n let mut cache = self.cache.borrow_mut();\n\n let entry = cache.entry(idx);\n\n\n\n match entry {\n\n Vacant(entry) => {\n\n let string_ref = self.inner.get_string(idx)?;\n\n entry.insert(string_ref.clone());\n\n\n\n Ok(string_ref)\n\n }\n\n Occupied(entry) => Ok(entry.get().clone()),\n\n }\n\n }\n\n}\n", "file_path": "src/chunks/string_table.rs", "rank": 42, "score": 58362.63603623056 }, { "content": "impl<'a> StringTable for StringTableWrapper<'a> {\n\n fn get_strings_len(&self) -> u32 {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(8);\n\n\n\n cursor.read_u32::<LittleEndian>().unwrap_or(0)\n\n }\n\n\n\n fn get_styles_len(&self) -> u32 {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(12);\n\n\n\n cursor.read_u32::<LittleEndian>().unwrap_or(0)\n\n }\n\n\n\n fn get_string(&self, idx: u32) -> Result<Rc<String>, Error> {\n\n ensure!(idx <= self.get_strings_len(), \"index out of bounds\");\n\n\n\n let string = self\n\n .get_string_position(idx)\n", "file_path": "src/chunks/string_table.rs", "rank": 43, "score": 58358.4754364701 }, { "content": " let decode_error = decoder.raw_finish(&mut o);\n\n\n\n if decode_error.is_none() {\n\n Ok(o)\n\n } else {\n\n Err(format_err!(\"error decoding UTF8 string\"))\n\n }\n\n } else {\n\n let size1 = u32::from(cursor.read_u8()?);\n\n let size2 = u32::from(cursor.read_u8()?);\n\n\n\n let val = ((size2 & 0xFF) << 8) | size1 & 0xFF;\n\n\n\n let a = offset + 2;\n\n let b = a + val * 2;\n\n\n\n ensure!(\n\n a <= self.raw_data.len() as u32 && b <= self.raw_data.len() as u32 && a <= b,\n\n \"sub-slice out of raw_data range\"\n\n );\n", "file_path": "src/chunks/string_table.rs", "rank": 44, "score": 58356.63156910456 }, { "content": "\n\n for _ in 0..=idx {\n\n let current_offset = cursor.read_u32::<LittleEndian>()?;\n\n position = str_offset.wrapping_add(current_offset);\n\n\n\n if current_offset > max_offset {\n\n max_offset = current_offset\n\n }\n\n }\n\n\n\n Ok(u64::from(position))\n\n }\n\n\n\n fn parse_string(&self, offset: u32) -> Result<String, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(u64::from(offset));\n\n\n\n if self.is_utf8() {\n\n let mut ini_offset = offset;\n\n let v = u32::from(cursor.read_u8()?);\n", "file_path": "src/chunks/string_table.rs", "rank": 45, "score": 58355.60599823616 }, { "content": " owned.set_encoding(EncodingType::Utf16);\n\n }\n\n\n\n for i in 0..self.get_strings_len() {\n\n let string = &*self.get_string(i)?;\n\n owned.add_string(string.clone());\n\n }\n\n\n\n Ok(owned)\n\n }\n\n\n\n fn get_string_position(&self, idx: u32) -> Result<u64, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(20);\n\n let str_offset = cursor.read_u32::<LittleEndian>()?;\n\n\n\n cursor.set_position(28);\n\n\n\n let mut position = str_offset;\n\n let mut max_offset = 0;\n", "file_path": "src/chunks/string_table.rs", "rank": 46, "score": 58355.60168716264 }, { "content": "\n\n let subslice: &[u8] = &self.raw_data[a as usize..b as usize];\n\n\n\n let mut decoder = utf_16::UTF16Decoder::<utf_16::Little>::new();\n\n let mut o = String::new();\n\n decoder.raw_feed(subslice, &mut o);\n\n let decode_error = decoder.raw_finish(&mut o);\n\n\n\n match decode_error {\n\n None => Ok(o),\n\n Some(_) => Err(format_err!(\"error decoding UTF16 string\")),\n\n }\n\n }\n\n }\n\n\n\n fn is_utf8(&self) -> bool {\n\n (self.get_flags() & 0x00000100) == 0x00000100\n\n }\n\n}\n\n\n", "file_path": "src/chunks/string_table.rs", "rank": 47, "score": 58354.51414551117 }, { "content": " if v == 0 {\n\n break;\n\n } else {\n\n length += 1;\n\n }\n\n }\n\n\n\n let a = ini_offset;\n\n let b = ini_offset + length;\n\n\n\n ensure!(\n\n a <= self.raw_data.len() as u32 && b <= self.raw_data.len() as u32 && a <= b,\n\n \"sub-slice out of raw_data range\"\n\n );\n\n\n\n let subslice: &[u8] = &self.raw_data[a as usize..b as usize];\n\n\n\n let mut decoder = utf_8::UTF8Decoder::new();\n\n let mut o = String::new();\n\n decoder.raw_feed(subslice, &mut o);\n", "file_path": "src/chunks/string_table.rs", "rank": 48, "score": 58354.08720196111 }, { "content": " if v == 0x80 {\n\n ini_offset += 2;\n\n cursor.read_u8()?;\n\n } else {\n\n ini_offset += 1;\n\n }\n\n\n\n let v = u32::from(cursor.read_u8()?);\n\n if v == 0x80 {\n\n ini_offset += 2;\n\n cursor.read_u8()?;\n\n } else {\n\n ini_offset += 1;\n\n }\n\n\n\n let mut length = 0;\n\n\n\n loop {\n\n let v = cursor.read_u8()?;\n\n\n", "file_path": "src/chunks/string_table.rs", "rank": 49, "score": 58352.6914510535 }, { "content": "use std::io::Cursor;\n\n\n\nuse byteorder::{LittleEndian, ReadBytesExt};\n\nuse failure::{ensure, format_err, Error};\n\nuse log::debug;\n\n\n\nuse crate::model::{\n\n owned::{ComplexEntry, Entry, EntryHeader, SimpleEntry, TableTypeBuf},\n\n TableType,\n\n};\n\n\n\npub use self::configuration::{ConfigurationWrapper, Region};\n\n\n\nmod configuration;\n\n\n\n#[derive(Debug)]\n\npub struct TableTypeWrapper<'a> {\n\n raw_data: &'a [u8],\n\n data_offset: u64,\n\n}\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 50, "score": 55510.85414806294 }, { "content": "use std::io::Cursor;\n\n\n\nuse byteorder::{LittleEndian, ReadBytesExt};\n\nuse failure::{ensure, Error};\n\n\n\nuse crate::model::{owned::TableTypeSpecBuf, TypeSpec};\n\n\n\n#[derive(Clone, Debug)]\n\npub struct TypeSpecWrapper<'a> {\n\n raw_data: &'a [u8],\n\n}\n\n\n\nimpl<'a> TypeSpecWrapper<'a> {\n\n pub fn new(raw_data: &'a [u8]) -> Self {\n\n Self { raw_data }\n\n }\n\n\n\n pub fn to_buffer(&self) -> Result<TableTypeSpecBuf, Error> {\n\n let mut owned = TableTypeSpecBuf::new(self.get_id()?);\n\n let amount = self.get_amount()?;\n", "file_path": "src/chunks/table_type_spec.rs", "rank": 51, "score": 55510.14875270155 }, { "content": "use std::{io::Cursor, string::ToString};\n\n\n\nuse byteorder::{LittleEndian, ReadBytesExt};\n\nuse failure::{bail, ensure, Error};\n\n\n\nuse crate::model::{owned::ConfigurationBuf, Configuration};\n\n\n\n#[derive(Debug)]\n\npub struct ConfigurationWrapper<'a> {\n\n slice: &'a [u8],\n\n}\n\n\n\nimpl<'a> ConfigurationWrapper<'a> {\n\n pub fn new(slice: &'a [u8]) -> Self {\n\n Self { slice }\n\n }\n\n\n\n pub fn to_buffer(&self) -> Result<ConfigurationBuf, Error> {\n\n ConfigurationBuf::from_cursor(self.slice.into())\n\n }\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 52, "score": 55506.952748335374 }, { "content": "\n\nimpl<'a> TableTypeWrapper<'a> {\n\n pub fn new(raw_data: &'a [u8], data_offset: u64) -> Self {\n\n Self {\n\n raw_data,\n\n data_offset,\n\n }\n\n }\n\n\n\n pub fn to_buffer(&self) -> Result<TableTypeBuf, Error> {\n\n let id = self.get_id()?;\n\n let amount = self.get_amount()?;\n\n let config = self.get_configuration()?.to_buffer()?;\n\n let mut owned = TableTypeBuf::new(id & 0xF, config);\n\n\n\n for i in 0..amount {\n\n let entry = self.get_entry(i)?;\n\n owned.add_entry(entry);\n\n }\n\n\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 53, "score": 55504.648532368614 }, { "content": "\n\n if offsets[i as usize] == 0xFFFF_FFFF {\n\n entries.push(Entry::Empty(id, id));\n\n } else {\n\n let maybe_entry = Self::decode_entry(cursor, id)?;\n\n\n\n if let Some(e) = maybe_entry {\n\n entries.push(e);\n\n } else {\n\n debug!(\"Entry with a negative count\");\n\n }\n\n }\n\n }\n\n\n\n Ok(entries)\n\n }\n\n\n\n fn decode_entry(cursor: &mut Cursor<&[u8]>, id: u32) -> Result<Option<Entry>, Error> {\n\n let header_size = cursor.read_u16::<LittleEndian>()?;\n\n let flags = cursor.read_u16::<LittleEndian>()?;\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 54, "score": 55502.179119178974 }, { "content": " Ok(owned)\n\n }\n\n\n\n pub fn get_entries(&self) -> Result<Vec<Entry>, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(self.data_offset);\n\n\n\n self.decode_entries(&mut cursor)\n\n }\n\n\n\n fn decode_entries(&self, cursor: &mut Cursor<&[u8]>) -> Result<Vec<Entry>, Error> {\n\n let mut offsets = Vec::new();\n\n let mut entries = Vec::new();\n\n\n\n for _ in 0..self.get_amount()? {\n\n offsets.push(cursor.read_u32::<LittleEndian>()?);\n\n }\n\n\n\n for i in 0..self.get_amount()? {\n\n let id = i & 0xFFFF;\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 55, "score": 55502.004718470045 }, { "content": "impl<'a> TableType for TableTypeWrapper<'a> {\n\n type Configuration = ConfigurationWrapper<'a>;\n\n\n\n fn get_id(&self) -> Result<u8, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(8);\n\n let out_value = cursor.read_u32::<LittleEndian>()? & 0xF;\n\n\n\n Ok(out_value as u8)\n\n }\n\n\n\n fn get_amount(&self) -> Result<u32, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(12);\n\n\n\n Ok(cursor.read_u32::<LittleEndian>()?)\n\n }\n\n\n\n fn get_configuration(&self) -> Result<Self::Configuration, Error> {\n\n let ini = 20;\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 56, "score": 55501.09972389772 }, { "content": " let key_index = cursor.read_u32::<LittleEndian>()?;\n\n let header_entry = EntryHeader::new(header_size, flags, key_index);\n\n\n\n if header_entry.is_complex() {\n\n Self::decode_complex_entry(cursor, header_entry, id)\n\n } else {\n\n Self::decode_simple_entry(cursor, header_entry, id)\n\n }\n\n }\n\n\n\n fn decode_simple_entry(\n\n cursor: &mut Cursor<&[u8]>,\n\n header: EntryHeader,\n\n id: u32,\n\n ) -> Result<Option<Entry>, Error> {\n\n cursor.read_u16::<LittleEndian>()?;\n\n // Padding\n\n cursor.read_u8()?;\n\n let val_type = cursor.read_u8()?;\n\n let data = cursor.read_u32::<LittleEndian>()?;\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 57, "score": 55500.7759808493 }, { "content": "\n\n let simple = SimpleEntry::new(id, header.get_key_index(), val_type, data);\n\n let entry = Entry::Simple(simple);\n\n\n\n Ok(Some(entry))\n\n }\n\n\n\n fn decode_complex_entry(\n\n cursor: &mut Cursor<&[u8]>,\n\n header: EntryHeader,\n\n id: u32,\n\n ) -> Result<Option<Entry>, Error> {\n\n let parent_entry = cursor.read_u32::<LittleEndian>()?;\n\n let value_count = cursor.read_u32::<LittleEndian>()?;\n\n let mut entries = Vec::with_capacity(value_count as usize);\n\n\n\n if value_count == 0xFFFF_FFFF {\n\n return Ok(None);\n\n }\n\n\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 58, "score": 55499.393359995 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{TypeSpec, TypeSpecWrapper};\n\n use crate::raw_chunks;\n\n\n\n #[test]\n\n fn it_can_decode_a_type_spec() {\n\n let wrapper = TypeSpecWrapper::new(raw_chunks::EXAMPLE_TYPE_SPEC);\n\n\n\n assert_eq!(4, wrapper.get_id().unwrap());\n\n assert_eq!(1541, wrapper.get_amount().unwrap());\n\n\n\n assert_eq!(0x40000004, wrapper.get_flag(0).unwrap());\n\n assert_eq!(0, wrapper.get_flag(25).unwrap());\n\n assert_eq!(6, wrapper.get_flag(1540).unwrap());\n\n\n\n let errored_flag = wrapper.get_flag(1541);\n\n assert!(errored_flag.is_err());\n\n assert_eq!(\n\n \"invalid flag on index 1541 out of 1541\",\n\n errored_flag.err().unwrap().to_string()\n\n );\n\n }\n\n}\n", "file_path": "src/chunks/table_type_spec.rs", "rank": 59, "score": 55496.70496511934 }, { "content": "}\n\n\n\nimpl<'a> Configuration for ConfigurationWrapper<'a> {\n\n fn get_size(&self) -> Result<u32, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(0);\n\n\n\n Ok(cursor.read_u32::<LittleEndian>()?)\n\n }\n\n\n\n fn get_mcc(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(4);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_mnc(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(6);\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 60, "score": 55496.36907349509 }, { "content": "\n\n for i in 0..amount {\n\n owned.push_flag(self.get_flag(i)?);\n\n }\n\n\n\n Ok(owned)\n\n }\n\n}\n\n\n\nimpl<'a> TypeSpec for TypeSpecWrapper<'a> {\n\n fn get_id(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n\n cursor.set_position(8);\n\n let out_value = cursor.read_u32::<LittleEndian>()? & 0xFF;\n\n\n\n Ok(out_value as u16)\n\n }\n\n\n\n fn get_amount(&self) -> Result<u32, Error> {\n\n let mut cursor = Cursor::new(self.raw_data);\n", "file_path": "src/chunks/table_type_spec.rs", "rank": 61, "score": 55495.74124855248 }, { "content": " let end = self.data_offset as usize;\n\n\n\n ensure!(\n\n ini <= end\n\n && (end - ini) > 28\n\n && self.raw_data.len() >= ini\n\n && self.raw_data.len() >= end,\n\n \"configuration slice is not valid\"\n\n );\n\n\n\n let slice = &self.raw_data[ini..end];\n\n let wrapper = ConfigurationWrapper::new(slice);\n\n\n\n Ok(wrapper)\n\n }\n\n\n\n fn get_entry(&self, index: u32) -> Result<Entry, Error> {\n\n let entries = self.get_entries()?;\n\n entries\n\n .get(index as usize)\n\n .cloned()\n\n .ok_or_else(|| format_err!(\"entry not found\"))\n\n }\n\n}\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 62, "score": 55495.50826349085 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use super::{Configuration, ConfigurationWrapper, Region, ToString};\n\n use crate::raw_chunks::EXAMPLE_CONFIGURATION;\n\n\n\n #[test]\n\n fn it_can_encode_bytes_region_to_string() {\n\n let region = Region::from((99, 97));\n\n\n\n assert_eq!(\"ca\", region.to_string());\n\n }\n\n\n\n #[test]\n\n fn it_can_encode_bytes_region_to_string_any() {\n\n let region = Region::from((0, 0));\n\n\n\n assert_eq!(\"any\", region.to_string());\n\n }\n\n\n\n #[test]\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 63, "score": 55494.869248323506 }, { "content": " cursor.set_position(12);\n\n\n\n Ok(cursor.read_u32::<LittleEndian>()?)\n\n }\n\n\n\n fn get_flag(&self, index: u32) -> Result<u32, Error> {\n\n let amount = self.get_amount()?;\n\n ensure!(\n\n index < amount,\n\n \"invalid flag on index {} out of {}\",\n\n index,\n\n amount\n\n );\n\n\n\n let mut cursor = Cursor::new(self.raw_data);\n\n let flag_offset = 16 + u64::from(index) * 4;\n\n cursor.set_position(flag_offset);\n\n\n\n Ok(cursor.read_u32::<LittleEndian>()?)\n\n }\n", "file_path": "src/chunks/table_type_spec.rs", "rank": 64, "score": 55494.85416816609 }, { "content": "\n\n fn get_locale_script(&self) -> Result<Option<String>, Error> {\n\n bail!(\"not enough bytes to retrieve the field\")\n\n }\n\n\n\n fn get_locale_variant(&self) -> Result<Option<String>, Error> {\n\n bail!(\"not enough bytes to retrieve the field\")\n\n }\n\n\n\n fn get_secondary_layout(&self) -> Result<Option<u8>, Error> {\n\n bail!(\"not enough bytes to retrieve the field\")\n\n }\n\n}\n\n\n\n#[derive(Default, Debug, Copy, Clone)]\n\npub struct Region {\n\n low: u8,\n\n high: u8,\n\n}\n\n\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 65, "score": 55494.750968882654 }, { "content": " for _ in 0..value_count {\n\n let val_id = cursor.read_u32::<LittleEndian>()?;\n\n cursor.read_u16::<LittleEndian>()?;\n\n // Padding\n\n cursor.read_u8()?;\n\n let val_type = cursor.read_u8()?;\n\n let data = cursor.read_u32::<LittleEndian>()?;\n\n\n\n let simple_entry = SimpleEntry::new(val_id, header.get_key_index(), val_type, data);\n\n\n\n entries.push(simple_entry);\n\n }\n\n\n\n let complex = ComplexEntry::new(id, header.get_key_index(), parent_entry, entries);\n\n let entry = Entry::Complex(complex);\n\n\n\n Ok(Some(entry))\n\n }\n\n}\n\n\n", "file_path": "src/chunks/table_type/mod.rs", "rank": 66, "score": 55494.21148698686 }, { "content": "\n\n fn get_navigation(&self) -> Result<u8, Error> {\n\n Ok(self.slice[17])\n\n }\n\n\n\n fn get_input_flags(&self) -> Result<u8, Error> {\n\n Ok(self.slice[18])\n\n }\n\n\n\n fn get_width(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(20);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_height(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(22);\n\n\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 67, "score": 55493.533879449715 }, { "content": " }\n\n\n\n fn get_orientation(&self) -> Result<u8, Error> {\n\n Ok(self.slice[12])\n\n }\n\n\n\n fn get_touchscreen(&self) -> Result<u8, Error> {\n\n Ok(self.slice[13])\n\n }\n\n\n\n fn get_density(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(14);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_keyboard(&self) -> Result<u8, Error> {\n\n Ok(self.slice[16])\n\n }\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 68, "score": 55492.92033852194 }, { "content": " Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_sdk_version(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(24);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_min_sdk_version(&self) -> Result<u16, Error> {\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(26);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_screen_layout(&self) -> Result<u8, Error> {\n\n let size = self.get_size()?;\n\n ensure!(size >= 28, \"not enough bytes to retrieve the field\");\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 69, "score": 55492.71310193528 }, { "content": "\n\n fn get_screen_width(&self) -> Result<u16, Error> {\n\n let size = self.get_size()?;\n\n ensure!(size >= 32, \"not enough bytes to retrieve the field\");\n\n\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(32);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_screen_height(&self) -> Result<u16, Error> {\n\n let size = self.get_size()?;\n\n ensure!(size >= 34, \"not enough bytes to retrieve the field\");\n\n\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(34);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 70, "score": 55492.36267424486 }, { "content": "\n\n Ok(self.slice[28])\n\n }\n\n\n\n fn get_ui_mode(&self) -> Result<u8, Error> {\n\n let size = self.get_size()?;\n\n ensure!(size >= 29, \"not enough bytes to retrieve the field\");\n\n\n\n Ok(self.slice[29])\n\n }\n\n\n\n fn get_smallest_screen(&self) -> Result<u16, Error> {\n\n let size = self.get_size()?;\n\n ensure!(size >= 30, \"not enough bytes to retrieve the field\");\n\n\n\n let mut cursor = Cursor::new(self.slice);\n\n cursor.set_position(30);\n\n\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 71, "score": 55491.854491682396 }, { "content": "impl Into<(u8, u8)> for Region {\n\n fn into(self) -> (u8, u8) {\n\n (self.low, self.high)\n\n }\n\n}\n\n\n\nimpl<'a> From<&'a [u8]> for Region {\n\n fn from(input: &'a [u8]) -> Self {\n\n if let [low, high] = *input {\n\n Self { low, high }\n\n } else {\n\n Self::default()\n\n }\n\n }\n\n}\n\n\n\nimpl From<(u8, u8)> for Region {\n\n fn from(input: (u8, u8)) -> Self {\n\n Self {\n\n low: input.0,\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 72, "score": 55491.283271923196 }, { "content": "\n\n Ok(cursor.read_u16::<LittleEndian>()?)\n\n }\n\n\n\n fn get_language(&self) -> Result<String, Error> {\n\n let lang_low = self.slice[8];\n\n let lang_high = self.slice[9];\n\n\n\n let region = Region::from((lang_low, lang_high));\n\n\n\n Ok(region.to_string())\n\n }\n\n\n\n fn get_region(&self) -> Result<String, Error> {\n\n let lang_low = self.slice[10];\n\n let lang_high = self.slice[11];\n\n\n\n let region = Region::from((lang_low, lang_high));\n\n\n\n Ok(region.to_string())\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 73, "score": 55489.74231849648 }, { "content": " high: input.1,\n\n }\n\n }\n\n}\n\n\n\nimpl ToString for Region {\n\n fn to_string(&self) -> String {\n\n let mut chrs = Vec::new();\n\n\n\n if self.low == 0 && self.high == 0 {\n\n return \"any\".to_owned();\n\n }\n\n\n\n chrs.push(self.low);\n\n chrs.push(self.high);\n\n\n\n String::from_utf8(chrs).unwrap_or_else(|_| String::new())\n\n }\n\n}\n\n\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 74, "score": 55489.45613967699 }, { "content": " fn it_can_encode_bytes_region_from_string() {\n\n let region = Region::from(\"ps\".as_ref());\n\n let (low, high) = region.into();\n\n\n\n assert_eq!(112, low);\n\n assert_eq!(115, high);\n\n }\n\n\n\n #[test]\n\n fn it_can_encode_bytes_region_from_string_any() {\n\n let region = Region::from(\"any\".as_ref());\n\n let (low, high) = region.into();\n\n\n\n assert_eq!(0, low);\n\n assert_eq!(0, high);\n\n }\n\n\n\n #[test]\n\n fn it_can_decode_a_full_configuration_slice() {\n\n let wrapper = ConfigurationWrapper::new(EXAMPLE_CONFIGURATION);\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 75, "score": 55486.76602525472 }, { "content": "\n\n assert_eq!(56, wrapper.get_size().unwrap());\n\n assert_eq!(310, wrapper.get_mcc().unwrap());\n\n assert_eq!(800, wrapper.get_mnc().unwrap());\n\n assert_eq!(\"bs\", wrapper.get_language().unwrap());\n\n assert_eq!(\"BA\", wrapper.get_region().unwrap());\n\n assert_eq!(0, wrapper.get_orientation().unwrap());\n\n assert_eq!(0, wrapper.get_touchscreen().unwrap());\n\n assert_eq!(0, wrapper.get_density().unwrap());\n\n assert_eq!(0, wrapper.get_keyboard().unwrap());\n\n assert_eq!(0, wrapper.get_keyboard().unwrap());\n\n assert_eq!(0, wrapper.get_width().unwrap());\n\n assert_eq!(0, wrapper.get_height().unwrap());\n\n }\n\n}\n", "file_path": "src/chunks/table_type/configuration.rs", "rank": 76, "score": 55486.76602525472 }, { "content": "use std::rc::Rc;\n\n\n\nuse byteorder::{LittleEndian, WriteBytesExt};\n\nuse encoding::{\n\n codec::{utf_16, utf_8},\n\n Encoding as EncodingTrait,\n\n};\n\nuse failure::{bail, ensure, Error};\n\n\n\nuse crate::{\n\n chunks::TOKEN_STRING_TABLE,\n\n model::{owned::OwnedBuf, StringTable},\n\n};\n\n\n\n#[derive(Clone, Copy, PartialEq, Debug)]\n\npub enum Encoding {\n\n Utf8,\n\n Utf16,\n\n}\n\n\n", "file_path": "src/model/owned/string_table.rs", "rank": 77, "score": 54116.97029319104 }, { "content": " }\n\n\n\n fn get_styles_len(&self) -> u32 {\n\n self.styles.len() as u32\n\n }\n\n\n\n fn get_string(&self, idx: u32) -> Result<Rc<String>, Error> {\n\n if let Some(s) = self.strings.get(idx as usize) {\n\n Ok(s.clone())\n\n } else {\n\n bail!(\"string not found\")\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(clippy::non_ascii_literal)]\n\nmod tests {\n\n use super::{OwnedBuf, StringTable, StringTableBuf};\n\n use crate::{chunks::StringTableWrapper, raw_chunks, test::compare_chunks};\n", "file_path": "src/model/owned/string_table.rs", "rank": 78, "score": 54113.64689787547 }, { "content": "#[derive(Debug)]\n\npub struct StringTableBuf {\n\n strings: Vec<Rc<String>>,\n\n styles: Vec<Rc<String>>,\n\n encoding: Encoding,\n\n}\n\n\n\nimpl Default for StringTableBuf {\n\n fn default() -> Self {\n\n Self {\n\n strings: Vec::new(),\n\n styles: Vec::new(),\n\n encoding: Encoding::Utf8,\n\n }\n\n }\n\n}\n\n\n\nimpl StringTableBuf {\n\n pub fn set_encoding(&mut self, encoding: Encoding) {\n\n self.encoding = encoding;\n", "file_path": "src/model/owned/string_table.rs", "rank": 79, "score": 54110.52666371578 }, { "content": " }\n\n\n\n pub fn get_encoding(&self) -> Encoding {\n\n self.encoding\n\n }\n\n\n\n pub fn add_string(&mut self, new_string: String) {\n\n self.strings.push(Rc::new(new_string));\n\n }\n\n}\n\n\n\nimpl OwnedBuf for StringTableBuf {\n\n fn get_token(&self) -> u16 {\n\n TOKEN_STRING_TABLE\n\n }\n\n\n\n fn get_header(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n\n\n let flags = if self.encoding == Encoding::Utf8 {\n", "file_path": "src/model/owned/string_table.rs", "rank": 80, "score": 54107.56528756884 }, { "content": " fn get_body_data(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n\n\n let mut string_offsets: Vec<u32> = Vec::new();\n\n let mut style_offsets: Vec<u32> = Vec::new();\n\n let mut string_buffer: Vec<u8> = Vec::new();\n\n let style_buffer: Vec<u8> = Vec::new();\n\n\n\n let mut current_offset = 0;\n\n let mut encoder = if self.encoding == Encoding::Utf8 {\n\n utf_8::UTF8Encoder::new()\n\n } else {\n\n utf_16::UTF_16LE_ENCODING.raw_encoder()\n\n };\n\n\n\n // Encode strings and save offsets\n\n for string in &self.strings {\n\n string_offsets.push(current_offset);\n\n let mut encoded_string = Vec::new();\n\n let (size, error) = encoder.raw_feed(string, &mut encoded_string);\n", "file_path": "src/model/owned/string_table.rs", "rank": 81, "score": 54104.743740577804 }, { "content": "\n\n #[test]\n\n fn it_can_generate_an_empty_chunk() {\n\n let string_table = StringTableBuf::default();\n\n\n\n assert_eq!(0, string_table.get_strings_len());\n\n assert_eq!(0, string_table.get_styles_len());\n\n assert!(string_table.get_string(0).is_err());\n\n }\n\n\n\n #[test]\n\n fn it_can_generate_a_chunk_with_the_given_data() {\n\n let mut string_table = StringTableBuf::default();\n\n string_table.add_string(\"some string\".to_string());\n\n string_table.add_string(\"忠犬ハチ公\".to_string());\n\n\n\n assert_eq!(2, string_table.get_strings_len());\n\n assert_eq!(0, string_table.get_styles_len());\n\n assert_eq!(\"some string\", *(string_table.get_string(0).unwrap()));\n\n assert_eq!(\"忠犬ハチ公\", *(string_table.get_string(1).unwrap()));\n", "file_path": "src/model/owned/string_table.rs", "rank": 82, "score": 54104.48609349453 }, { "content": " }\n\n\n\n for offset in string_offsets {\n\n out.write_u32::<LittleEndian>(offset)?;\n\n }\n\n\n\n for offset in style_offsets {\n\n out.write_u32::<LittleEndian>(offset)?;\n\n }\n\n\n\n out.extend(string_buffer);\n\n out.extend(style_buffer);\n\n\n\n Ok(out)\n\n }\n\n}\n\n\n\nimpl StringTable for StringTableBuf {\n\n fn get_strings_len(&self) -> u32 {\n\n self.strings.len() as u32\n", "file_path": "src/model/owned/string_table.rs", "rank": 83, "score": 54103.23922868297 }, { "content": " assert!(string_table.get_string(2).is_err());\n\n }\n\n\n\n #[test]\n\n fn identity() {\n\n let raw = raw_chunks::EXAMPLE_STRING_TABLE;\n\n let wrapper = StringTableWrapper::new(&raw);\n\n\n\n let owned = wrapper.to_buffer().unwrap();\n\n let owned_as_vec = owned.to_vec().unwrap();\n\n\n\n compare_chunks(&owned_as_vec, &raw);\n\n }\n\n\n\n #[test]\n\n fn identity_utf8() {\n\n // TODO: Test with UTF8 encoding\n\n }\n\n}\n", "file_path": "src/model/owned/string_table.rs", "rank": 84, "score": 54102.87357878941 }, { "content": "\n\n ensure!(error.is_none(), \"error encoding string\");\n\n\n\n // Write size\n\n let low = (size & 0xFF) as u8;\n\n let high = ((size & 0xFF00) >> 8) as u8;\n\n string_buffer.push(low);\n\n string_buffer.push(high);\n\n string_buffer.extend(&encoded_string);\n\n string_buffer.push(0x00);\n\n string_buffer.push(0x00);\n\n\n\n current_offset = string_buffer.len() as u32;\n\n // println!(\"Current offset: {}\", current_offset);\n\n }\n\n\n\n // Encode styles and save offsets\n\n for _ in &self.styles {\n\n style_offsets.push(current_offset);\n\n // Encode with utf8/utf16 depending on the flag\n", "file_path": "src/model/owned/string_table.rs", "rank": 85, "score": 54100.30103462413 }, { "content": " 0x00000100\n\n } else {\n\n 0\n\n };\n\n\n\n let header_size = 7 * 4;\n\n let string_offset = header_size + self.get_strings_len() * 4 + self.get_styles_len() * 4;\n\n\n\n out.write_u32::<LittleEndian>(self.strings.len() as u32)?;\n\n out.write_u32::<LittleEndian>(self.styles.len() as u32)?;\n\n out.write_u32::<LittleEndian>(flags)?;\n\n\n\n // TODO: Calculate properly the offset as we are calculating on the decoding part\n\n let style_offset = 0;\n\n out.write_u32::<LittleEndian>(string_offset)?;\n\n out.write_u32::<LittleEndian>(style_offset)?;\n\n\n\n Ok(out)\n\n }\n\n\n", "file_path": "src/model/owned/string_table.rs", "rank": 86, "score": 54099.99924629878 }, { "content": "use byteorder::{LittleEndian, WriteBytesExt};\n\nuse failure::{format_err, Error};\n\n\n\nuse crate::model::{owned::OwnedBuf, TypeSpec};\n\n\n\n#[derive(Debug)]\n\npub struct TableTypeSpecBuf {\n\n id: u16,\n\n flags: Vec<u32>,\n\n}\n\n\n\nimpl TableTypeSpecBuf {\n\n pub fn new(id: u16) -> Self {\n\n Self {\n\n id,\n\n flags: Vec::new(),\n\n }\n\n }\n\n\n\n pub fn push_flag(&mut self, flag: u32) {\n", "file_path": "src/model/owned/table_type_spec.rs", "rank": 87, "score": 51594.593350784584 }, { "content": "use std::io::Cursor;\n\n\n\nuse byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};\n\nuse failure::Error;\n\n\n\nuse crate::{chunks::table_type::Region, model::Configuration};\n\n\n\n#[derive(Clone, Default, Debug)]\n\npub struct ConfigurationBuf {\n\n size: u32,\n\n original_size: u32,\n\n mcc: u16,\n\n mnc: u16,\n\n language: String,\n\n region: String,\n\n orientation: u8,\n\n touchscreen: u8,\n\n density: u16,\n\n keyboard: u8,\n\n navigation: u8,\n", "file_path": "src/model/owned/table_type/configuration.rs", "rank": 88, "score": 51591.4457641236 }, { "content": "use byteorder::{LittleEndian, WriteBytesExt};\n\nuse failure::{format_err, Error};\n\n\n\nuse crate::model::{owned::OwnedBuf, TableType};\n\n\n\nmod configuration;\n\nmod entry;\n\n\n\npub use self::{\n\n configuration::ConfigurationBuf,\n\n entry::{ComplexEntry, Entry, EntryHeader, SimpleEntry},\n\n};\n\n\n\n#[derive(Debug)]\n\npub struct TableTypeBuf {\n\n id: u8,\n\n config: ConfigurationBuf,\n\n entries: Vec<Entry>,\n\n}\n\n\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 89, "score": 51591.235478457966 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use super::{ComplexEntry, ConfigurationBuf, Entry, SimpleEntry, TableTypeBuf};\n\n use crate::{\n\n chunks::TableTypeWrapper,\n\n model::{owned::OwnedBuf, TableType},\n\n raw_chunks,\n\n test::compare_chunks,\n\n };\n\n\n\n #[test]\n\n fn it_can_generate_a_chunk_with_the_given_data() {\n\n let mut table_type = TableTypeBuf::new(5, ConfigurationBuf::default());\n\n\n\n let entry = Entry::Simple(SimpleEntry::new(1, 2, 3, 4));\n\n let sub_entry = SimpleEntry::new(5, 6, 7, 8);\n\n let sub_entry2 = SimpleEntry::new(9, 0, 1, 2);\n\n\n\n let entry2 = Entry::Complex(ComplexEntry::new(10, 11, 12, vec![sub_entry, sub_entry2]));\n\n let entry3 = Entry::Simple(SimpleEntry::new(20, 21, 22, 23));\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 90, "score": 51587.40635812591 }, { "content": "impl TableTypeBuf {\n\n pub fn new(id: u8, config: ConfigurationBuf) -> Self {\n\n Self {\n\n id,\n\n config,\n\n entries: Vec::new(),\n\n }\n\n }\n\n\n\n pub fn add_entry(&mut self, entry: Entry) {\n\n self.entries.push(entry);\n\n }\n\n}\n\n\n\nimpl OwnedBuf for TableTypeBuf {\n\n fn get_token(&self) -> u16 {\n\n 0x201\n\n }\n\n\n\n fn get_body_data(&self) -> Result<Vec<u8>, Error> {\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 91, "score": 51586.36146648917 }, { "content": " .cloned()\n\n .ok_or_else(|| format_err!(\"flag out of bounds\"))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{TableTypeSpecBuf, TypeSpec};\n\n use crate::{\n\n chunks::TypeSpecWrapper, model::owned::OwnedBuf, raw_chunks, test::compare_chunks,\n\n };\n\n\n\n #[test]\n\n fn it_can_generate_a_chunk_with_the_given_data() {\n\n let type_spec = TableTypeSpecBuf::new(14);\n\n\n\n assert_eq!(14, type_spec.get_id().unwrap());\n\n }\n\n\n\n #[test]\n", "file_path": "src/model/owned/table_type_spec.rs", "rank": 92, "score": 51582.13679416235 }, { "content": " Ok(out)\n\n }\n\n\n\n fn get_header(&self) -> Result<Vec<u8>, Error> {\n\n let mut out = Vec::new();\n\n\n\n let vec_config = self.config.to_vec()?;\n\n let header_size = (5 * 4) + vec_config.len() as u32;\n\n out.write_u32::<LittleEndian>(u32::from(self.id))?;\n\n out.write_u32::<LittleEndian>(self.entries.len() as u32)?;\n\n out.write_u32::<LittleEndian>(header_size + (self.entries.len() as u32 * 4))?;\n\n out.extend(&vec_config);\n\n\n\n Ok(out)\n\n }\n\n}\n\n\n\nimpl TableType for TableTypeBuf {\n\n type Configuration = ConfigurationBuf;\n\n\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 93, "score": 51582.005897452786 }, { "content": " fn get_id(&self) -> Result<u8, Error> {\n\n Ok(self.id)\n\n }\n\n\n\n fn get_amount(&self) -> Result<u32, Error> {\n\n Ok(self.entries.len() as u32)\n\n }\n\n\n\n fn get_configuration(&self) -> Result<Self::Configuration, Error> {\n\n Ok(self.config.clone())\n\n }\n\n\n\n fn get_entry(&self, index: u32) -> Result<Entry, Error> {\n\n self.entries\n\n .get(index as usize)\n\n .cloned()\n\n .ok_or_else(|| format_err!(\"entry out of bound\"))\n\n }\n\n}\n\n\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 94, "score": 51581.86586407903 }, { "content": " let mut out = Vec::new();\n\n\n\n let mut i = 0;\n\n let mut entries_body = Vec::new();\n\n\n\n for e in &self.entries {\n\n let current_entry = e.to_vec()?;\n\n\n\n if e.is_empty() {\n\n out.write_u32::<LittleEndian>(0xFFFF_FFFF)?;\n\n } else {\n\n out.write_u32::<LittleEndian>(i)?;\n\n i += current_entry.len() as u32;\n\n }\n\n\n\n entries_body.extend(&current_entry);\n\n }\n\n\n\n out.extend(&entries_body);\n\n\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 95, "score": 51579.95011845529 }, { "content": " let mut out = Vec::new();\n\n\n\n out.write_u32::<LittleEndian>(u32::from(self.id))?;\n\n out.write_u32::<LittleEndian>(self.flags.len() as u32)?;\n\n\n\n Ok(out)\n\n }\n\n}\n\n\n\nimpl TypeSpec for TableTypeSpecBuf {\n\n fn get_id(&self) -> Result<u16, Error> {\n\n Ok(self.id)\n\n }\n\n fn get_amount(&self) -> Result<u32, Error> {\n\n Ok(self.flags.len() as u32)\n\n }\n\n\n\n fn get_flag(&self, index: u32) -> Result<u32, Error> {\n\n self.flags\n\n .get(index as usize)\n", "file_path": "src/model/owned/table_type_spec.rs", "rank": 96, "score": 51579.664083883596 }, { "content": "\n\n compare_chunks(&new_raw, &raw_chunks::EXAMPLE_TABLE_TYPE);\n\n }\n\n\n\n #[test]\n\n fn identity_with_mixed_complex_and_simple_entries() {\n\n let wrapper = TableTypeWrapper::new(raw_chunks::EXAMPLE_TABLE_TYPE_WITH_COMPLEX, 76);\n\n let _ = wrapper.get_entries();\n\n\n\n let owned = wrapper.to_buffer().unwrap();\n\n let new_raw = owned.to_vec().unwrap();\n\n\n\n compare_chunks(&new_raw, &raw_chunks::EXAMPLE_TABLE_TYPE_WITH_COMPLEX);\n\n }\n\n}\n", "file_path": "src/model/owned/table_type/mod.rs", "rank": 97, "score": 51579.1041543285 }, { "content": " buffer.write_u8(self.input_flags)?;\n\n buffer.write_u8(0)?;\n\n\n\n buffer.write_u16::<LittleEndian>(self.width)?;\n\n buffer.write_u16::<LittleEndian>(self.height)?;\n\n buffer.write_u16::<LittleEndian>(self.sdk_version)?;\n\n buffer.write_u16::<LittleEndian>(self.min_sdk_version)?;\n\n\n\n let current = buffer.len();\n\n\n\n // Fill with 0 up to target size\n\n for _ in current..self.original_size as usize {\n\n buffer.write_u8(0)?;\n\n }\n\n\n\n Ok(buffer)\n\n }\n\n\n\n pub fn from_cursor(buffer: Vec<u8>) -> Result<Self, Error> {\n\n let original_size = buffer.len() as u32;\n", "file_path": "src/model/owned/table_type/configuration.rs", "rank": 98, "score": 51578.32697975836 }, { "content": " fn get_secondary_layout(&self) -> Result<Option<u8>, Error> {\n\n Ok(self.secondary_screen_layout)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{\n\n chunks::ConfigurationWrapper, raw_chunks::EXAMPLE_CONFIGURATION, test::compare_chunks,\n\n };\n\n\n\n #[test]\n\n fn identity() {\n\n let owned = ConfigurationWrapper::new(EXAMPLE_CONFIGURATION)\n\n .to_buffer()\n\n .unwrap();\n\n let new_raw = owned.to_vec().unwrap();\n\n\n\n compare_chunks(EXAMPLE_CONFIGURATION, &new_raw);\n\n }\n\n}\n", "file_path": "src/model/owned/table_type/configuration.rs", "rank": 99, "score": 51578.29905059759 } ]
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);\n", "file_path": "benches/main_all/basic/smtp.rs", "rank": 0, "score": 129080.11436036043 }, { "content": "fn fibo_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"Fibo binary {}\", LOOPS), |b| b.iter(all_binaries));\n\n}\n\n\n\ncriterion_group! {\n\n name = fib;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = fibo_mpst, fibo_binary\n\n}\n\n\n\ncriterion_main!(fib);\n", "file_path": "benches/main_all/basic/fib.rs", "rank": 1, "score": 129080.11436036043 }, { "content": "fn o_auth_mpst(c: &mut Criterion) {\n\n c.bench_function(&\"oAuth MPST\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = o_auth;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = o_auth_mpst\n\n}\n\n\n\ncriterion_main!(o_auth);\n", "file_path": "benches/main_all/basic/o_auth.rs", "rank": 3, "score": 129080.11436036043 }, { "content": "fn fibo_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"Fibo MPST {}\", LOOPS), |b| b.iter(all_mpst));\n\n}\n\n\n", "file_path": "benches/main_all/basic/fib.rs", "rank": 4, "score": 129080.11436036043 }, { "content": "fn smtp_main(c: &mut Criterion) {\n\n c.bench_function(&\"SMTP baking\".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);\n", "file_path": "benches/main_all/baking/smtp.rs", "rank": 5, "score": 129080.11436036043 }, { "content": "fn logging_main(c: &mut Criterion) {\n\n c.bench_function(&\"Logging\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = logging;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = logging_main\n\n}\n\n\n\ncriterion_main!(logging);\n", "file_path": "benches/main_all/basic/logging.rs", "rank": 6, "score": 129080.11436036043 }, { "content": "fn o_auth_mpst(c: &mut Criterion) {\n\n c.bench_function(&\"oAuth MPST baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = o_auth;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = o_auth_mpst\n\n}\n\n\n\ncriterion_main!(o_auth);\n", "file_path": "benches/main_all/baking/o_auth.rs", "rank": 7, "score": 129080.11436036043 }, { "content": "fn logging_main(c: &mut Criterion) {\n\n c.bench_function(&\"Logging baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = logging;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = logging_main\n\n}\n\n\n\ncriterion_main!(logging);\n", "file_path": "benches/main_all/baking/logging.rs", "rank": 8, "score": 129080.11436036043 }, { "content": "fn travel_main(c: &mut Criterion) {\n\n c.bench_function(&\"Travel MPST baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = travel_three;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = travel_main\n\n}\n\n\n\ncriterion_main!(travel_three);\n", "file_path": "benches/main_all/baking/travel_three.rs", "rank": 9, "score": 128145.19938594861 }, { "content": "fn travel_main(c: &mut Criterion) {\n\n c.bench_function(&\"Travel MPST\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = travel_three;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = travel_main\n\n}\n\n\n\ncriterion_main!(travel_three);\n", "file_path": "benches/main_all/basic/travel_three.rs", "rank": 10, "score": 128145.19938594861 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh eleven empty protocol binary {}\", LOOPS),\n\n |b| b.iter(all_binaries),\n\n );\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_eleven.rs", "rank": 11, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh seven empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_seven.rs", "rank": 12, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh seven empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_seven;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_seven);\n", "file_path": "benches/mesh_all/empty/mesh_seven.rs", "rank": 13, "score": 127236.4967650122 }, { "content": "fn logging_solo_main(c: &mut Criterion) {\n\n c.bench_function(&\"Logging solo\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = logging_solo;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = logging_solo_main\n\n}\n\n\n\ncriterion_main!(logging_solo);\n", "file_path": "benches/main_all/basic/logging_solo.rs", "rank": 14, "score": 127236.4967650122 }, { "content": "fn dns_imai_main(c: &mut Criterion) {\n\n c.bench_function(&\"DNS Imai\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = dns_imai;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = dns_imai_main\n\n}\n\n\n\ncriterion_main!(dns_imai);\n", "file_path": "benches/main_all/basic/dns_imai.rs", "rank": 15, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh five empty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_five.rs", "rank": 16, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh two empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_two.rs", "rank": 17, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh seven protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_seven;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_seven);\n", "file_path": "benches/mesh_all/normal/mesh_seven.rs", "rank": 18, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh three protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_three.rs", "rank": 19, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh seven protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_seven.rs", "rank": 20, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh three cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_three;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_three);\n", "file_path": "benches/mesh_all/cancel/mesh_three.rs", "rank": 21, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eight protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_eight;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_eight);\n", "file_path": "benches/mesh_all/empty/mesh_eight.rs", "rank": 22, "score": 127236.4967650122 }, { "content": "fn three_buyers_mpst(c: &mut Criterion) {\n\n c.bench_function(&\"Three buyers MPST\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = three_buyers;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = three_buyers_mpst\n\n}\n\n\n\ncriterion_main!(three_buyers);\n", "file_path": "benches/main_all/basic/three_buyers.rs", "rank": 23, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh three empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_three.rs", "rank": 24, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh four protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_four;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_four);\n", "file_path": "benches/mesh_all/normal/mesh_four.rs", "rank": 25, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh six protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_six;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_six);\n", "file_path": "benches/mesh_all/normal/mesh_six.rs", "rank": 26, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh four cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_four;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_four);\n", "file_path": "benches/mesh_all/cancel/mesh_four.rs", "rank": 27, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh twenty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_twenty.rs", "rank": 28, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh two empty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_two.rs", "rank": 29, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh two empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_two;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_two);\n", "file_path": "benches/mesh_all/empty/mesh_two.rs", "rank": 30, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh five protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_five;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_five);\n", "file_path": "benches/mesh_all/normal/mesh_five.rs", "rank": 31, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh five protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_five.rs", "rank": 32, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh five protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_five.rs", "rank": 33, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh three empty protocol binary {}\", LOOPS),\n\n |b| b.iter(all_binaries),\n\n );\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_three.rs", "rank": 34, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh nine protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_nine.rs", "rank": 35, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh six empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_six;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_six);\n", "file_path": "benches/mesh_all/empty/mesh_six.rs", "rank": 36, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eight protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_eight.rs", "rank": 37, "score": 127236.4967650122 }, { "content": "fn video_stream_main(c: &mut Criterion) {\n\n c.bench_function(&\"Video stream\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = video_stream;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = video_stream_main\n\n}\n\n\n\ncriterion_main!(video_stream);\n", "file_path": "benches/main_all/basic/video_stream.rs", "rank": 38, "score": 127236.4967650122 }, { "content": "fn ring_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"ring two cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = ring_two;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = ring_protocol_mpst\n\n}\n\n\n\ncriterion_main!(ring_two);\n", "file_path": "benches/ring_all/cancel/ring_two.rs", "rank": 39, "score": 127236.4967650122 }, { "content": "fn online_wallet_main(c: &mut Criterion) {\n\n c.bench_function(&\"Online wallet\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = online_wallet;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = online_wallet_main\n\n}\n\n\n\ncriterion_main!(online_wallet);\n", "file_path": "benches/main_all/basic/online_wallet.rs", "rank": 40, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh five empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_five.rs", "rank": 41, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh twenty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_twenty.rs", "rank": 42, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh nine cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_nine;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_nine);\n", "file_path": "benches/mesh_all/cancel/mesh_nine.rs", "rank": 43, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh twenty empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_twenty;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_twenty);\n", "file_path": "benches/mesh_all/empty/mesh_twenty.rs", "rank": 44, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh four empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_four;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_four);\n", "file_path": "benches/mesh_all/empty/mesh_four.rs", "rank": 45, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh eleven empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_eleven;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_eleven);\n", "file_path": "benches/mesh_all/empty/mesh_eleven.rs", "rank": 46, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eleven empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_eleven.rs", "rank": 47, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh twenty empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_twenty.rs", "rank": 48, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eleven protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_eleven;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_eleven);\n", "file_path": "benches/mesh_all/normal/mesh_eleven.rs", "rank": 49, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh four empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_four.rs", "rank": 50, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh eleven cancel protocol MPST {}\", LOOPS),\n\n |b| b.iter(all_mpst),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_eleven;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_eleven);\n", "file_path": "benches/mesh_all/cancel/mesh_eleven.rs", "rank": 51, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh nine empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_nine.rs", "rank": 52, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh twenty protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_twenty;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_twenty);\n", "file_path": "benches/mesh_all/normal/mesh_twenty.rs", "rank": 53, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh ten cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_ten;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_ten);\n", "file_path": "benches/mesh_all/cancel/mesh_ten.rs", "rank": 54, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh seven protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_seven.rs", "rank": 55, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh nine empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_nine;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_nine);\n", "file_path": "benches/mesh_all/empty/mesh_nine.rs", "rank": 56, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eight empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_eight.rs", "rank": 57, "score": 127236.4967650122 }, { "content": "fn dns_imai_main(c: &mut Criterion) {\n\n c.bench_function(&\"DNS Imai baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = dns_imai;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = dns_imai_main\n\n}\n\n\n\ncriterion_main!(dns_imai);\n", "file_path": "benches/main_all/baking/dns_imai.rs", "rank": 58, "score": 127236.4967650122 }, { "content": "fn simple_voting_mpst(c: &mut Criterion) {\n\n c.bench_function(&\"Simple voting MPST\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = simple_voting;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = simple_voting_mpst,\n\n}\n\n\n\ncriterion_main!(simple_voting);\n", "file_path": "benches/main_all/basic/simple_voting.rs", "rank": 59, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh six empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_six.rs", "rank": 60, "score": 127236.4967650122 }, { "content": "fn video_stream_main(c: &mut Criterion) {\n\n c.bench_function(&\"Video stream baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = video_stream;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = video_stream_main\n\n}\n\n\n\ncriterion_main!(video_stream);\n", "file_path": "benches/main_all/baking/video_stream.rs", "rank": 61, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh four protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_four.rs", "rank": 62, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh ten empty protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_ten.rs", "rank": 63, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh seven cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_seven;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_seven);\n", "file_path": "benches/mesh_all/cancel/mesh_seven.rs", "rank": 64, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eight protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_eight;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_eight);\n", "file_path": "benches/mesh_all/normal/mesh_eight.rs", "rank": 65, "score": 127236.4967650122 }, { "content": "fn circuit_breaker_main(c: &mut Criterion) {\n\n c.bench_function(&\"Circuit breaker baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = circuit_breaker;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = circuit_breaker_main\n\n}\n\n\n\ncriterion_main!(circuit_breaker);\n", "file_path": "benches/main_all/baking/circuit_breaker.rs", "rank": 66, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh two cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_two;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_two);\n", "file_path": "benches/mesh_all/cancel/mesh_two.rs", "rank": 67, "score": 127236.4967650122 }, { "content": "fn dns_fowler_main(c: &mut Criterion) {\n\n c.bench_function(&\"DNS Fowler baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = dns_fowler;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = dns_fowler_main\n\n}\n\n\n\ncriterion_main!(dns_fowler);\n", "file_path": "benches/main_all/baking/dns_fowler.rs", "rank": 68, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh five cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_five;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_five);\n", "file_path": "benches/mesh_all/cancel/mesh_five.rs", "rank": 69, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh nine empty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_nine.rs", "rank": 70, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh eight empty protocol binary {}\", LOOPS),\n\n |b| b.iter(all_binaries),\n\n );\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_eight.rs", "rank": 71, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh three protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_three.rs", "rank": 72, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh four protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_four.rs", "rank": 73, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh four empty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_four.rs", "rank": 74, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eight protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_eight.rs", "rank": 75, "score": 127236.4967650122 }, { "content": "fn distributed_calc_main(c: &mut Criterion) {\n\n c.bench_function(&\"Distributed calculator baking\".to_string(), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = distributed_calc;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = distributed_calc_main\n\n}\n\n\n\ncriterion_main!(distributed_calc);\n", "file_path": "benches/main_all/baking/distributed_calc.rs", "rank": 76, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh nine protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_nine.rs", "rank": 77, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eight cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_eight;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_eight);\n", "file_path": "benches/mesh_all/cancel/mesh_eight.rs", "rank": 78, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh seven empty protocol binary {}\", LOOPS),\n\n |b| b.iter(all_binaries),\n\n );\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_seven.rs", "rank": 79, "score": 127236.4967650122 }, { "content": "fn three_buyers_mpst(c: &mut Criterion) {\n\n c.bench_function(&\"Three buyers MPST baking\".to_string(), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = three_buyers;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = three_buyers_mpst\n\n}\n\n\n\ncriterion_main!(three_buyers);\n", "file_path": "benches/main_all/baking/three_buyers.rs", "rank": 80, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh five empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_five;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_five);\n", "file_path": "benches/mesh_all/empty/mesh_five.rs", "rank": 81, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh six empty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_six.rs", "rank": 82, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh six cancel protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_six;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_six);\n", "file_path": "benches/mesh_all/cancel/mesh_six.rs", "rank": 83, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh twenty cancel protocol MPST {}\", LOOPS),\n\n |b| b.iter(all_mpst),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_twenty;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst\n\n}\n\n\n\ncriterion_main!(mesh_twenty);\n", "file_path": "benches/mesh_all/cancel/mesh_twenty.rs", "rank": 84, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh ten empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_ten;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_ten);\n", "file_path": "benches/mesh_all/empty/mesh_ten.rs", "rank": 85, "score": 127236.4967650122 }, { "content": "fn distributed_calc_main(c: &mut Criterion) {\n\n c.bench_function(&\"Distributed calculator\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = distributed_calc;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = distributed_calc_main\n\n}\n\n\n\ncriterion_main!(distributed_calc);\n", "file_path": "benches/main_all/basic/distributed_calc.rs", "rank": 86, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eleven protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_eleven.rs", "rank": 87, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh twenty empty protocol binary {}\", LOOPS),\n\n |b| b.iter(all_binaries),\n\n );\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_twenty.rs", "rank": 88, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_mpst(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh six protocol MPST {}\", LOOPS), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_six.rs", "rank": 89, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh eleven protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_eleven.rs", "rank": 90, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh nine protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_nine;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_nine);\n", "file_path": "benches/mesh_all/normal/mesh_nine.rs", "rank": 91, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh three protocol crossbeam {}\", LOOPS), |b| {\n\n b.iter(all_crossbeam)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_three;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_three);\n", "file_path": "benches/mesh_all/normal/mesh_three.rs", "rank": 92, "score": 127236.4967650122 }, { "content": "fn online_wallet_main(c: &mut Criterion) {\n\n c.bench_function(&\"Online wallet baking\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = online_wallet;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = online_wallet_main\n\n}\n\n\n\ncriterion_main!(online_wallet);\n", "file_path": "benches/main_all/baking/online_wallet.rs", "rank": 93, "score": 127236.4967650122 }, { "content": "fn dns_fowler_main(c: &mut Criterion) {\n\n c.bench_function(&\"DNS Fowler\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = dns_fowler;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = dns_fowler_main\n\n}\n\n\n\ncriterion_main!(dns_fowler);\n", "file_path": "benches/main_all/basic/dns_fowler.rs", "rank": 94, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh ten empty protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/empty/mesh_ten.rs", "rank": 95, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_binary(c: &mut Criterion) {\n\n c.bench_function(&format!(\"mesh six protocol binary {}\", LOOPS), |b| {\n\n b.iter(all_binaries)\n\n });\n\n}\n\n\n", "file_path": "benches/mesh_all/normal/mesh_six.rs", "rank": 96, "score": 127236.4967650122 }, { "content": "fn circuit_breaker_main(c: &mut Criterion) {\n\n c.bench_function(&\"Circuit breaker\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = circuit_breaker;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = circuit_breaker_main\n\n}\n\n\n\ncriterion_main!(circuit_breaker);\n", "file_path": "benches/main_all/basic/circuit_breaker.rs", "rank": 97, "score": 127236.4967650122 }, { "content": "fn simple_voting_mpst(c: &mut Criterion) {\n\n c.bench_function(&\"Simple voting MPST baking\".to_string(), |b| {\n\n b.iter(all_mpst)\n\n });\n\n}\n\n\n\ncriterion_group! {\n\n name = simple_voting;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = simple_voting_mpst,\n\n}\n\n\n\ncriterion_main!(simple_voting);\n", "file_path": "benches/main_all/baking/simple_voting.rs", "rank": 98, "score": 127236.4967650122 }, { "content": "fn mesh_protocol_crossbeam(c: &mut Criterion) {\n\n c.bench_function(\n\n &format!(\"mesh three empty protocol crossbeam {}\", LOOPS),\n\n |b| b.iter(all_crossbeam),\n\n );\n\n}\n\n\n\ncriterion_group! {\n\n name = mesh_three;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = mesh_protocol_mpst, mesh_protocol_binary, mesh_protocol_crossbeam\n\n}\n\n\n\ncriterion_main!(mesh_three);\n", "file_path": "benches/mesh_all/empty/mesh_three.rs", "rank": 99, "score": 127236.4967650122 } ]
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": "pub fn path_of_data_column(base: impl AsRef<Path>, column_info: &ColumnCatalog) -> PathBuf {\n\n path_of_column(base, column_info, \".col\")\n\n}\n\n\n", "file_path": "src/storage/secondary/rowset/rowset_builder.rs", "rank": 1, "score": 193341.85560012446 }, { "content": "pub fn verify_checksum(\n\n checksum_type: ChecksumType,\n\n index_data: &[u8],\n\n checksum: u64,\n\n) -> StorageResult<()> {\n\n let chksum = match checksum_type {\n\n ChecksumType::None => 0,\n\n ChecksumType::Crc32 => crc32fast::hash(index_data) as u64,\n\n };\n\n if chksum != checksum {\n\n return Err(TracedStorageError::checksum(chksum, checksum));\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/storage/secondary/checksum.rs", "rank": 2, "score": 166387.42795316677 }, { "content": "/// Convert a [`DataChunk`] to sqllogictest string\n\npub fn datachunk_to_sqllogictest_string(chunk: &DataChunk) -> String {\n\n let mut output = String::new();\n\n for row in 0..chunk.cardinality() {\n\n use std::fmt::Write;\n\n for (col, array) in chunk.arrays().iter().enumerate() {\n\n if col != 0 {\n\n write!(output, \" \").unwrap();\n\n }\n\n match array.get(row) {\n\n DataValue::Null => write!(output, \"NULL\"),\n\n DataValue::Bool(v) => write!(output, \"{}\", v),\n\n DataValue::Int32(v) => write!(output, \"{}\", v),\n\n DataValue::Int64(v) => write!(output, \"{}\", v),\n\n DataValue::Float64(v) => write!(output, \"{}\", v),\n\n DataValue::String(s) if s.is_empty() => write!(output, \"(empty)\"),\n\n DataValue::String(s) => write!(output, \"{}\", s),\n\n DataValue::Blob(s) if s.is_empty() => write!(output, \"(empty)\"),\n\n DataValue::Blob(s) => write!(output, \"{}\", s),\n\n DataValue::Decimal(v) => write!(output, \"{}\", v),\n\n DataValue::Date(v) => write!(output, \"{}\", v),\n", "file_path": "src/array/data_chunk.rs", "rank": 3, "score": 166344.41323352733 }, { "content": "struct Inner {\n\n name: String,\n\n /// Mapping from column names to column ids\n\n column_idxs: HashMap<String, ColumnId>,\n\n columns: BTreeMap<ColumnId, ColumnCatalog>,\n\n\n\n #[allow(dead_code)]\n\n is_materialized_view: bool,\n\n next_column_id: ColumnId,\n\n}\n\n\n\nimpl TableCatalog {\n\n pub fn new(\n\n id: TableId,\n\n name: String,\n\n columns: Vec<ColumnCatalog>,\n\n is_materialized_view: bool,\n\n ) -> TableCatalog {\n\n let table_catalog = TableCatalog {\n\n id,\n", "file_path": "src/catalog/table.rs", "rank": 4, "score": 160473.6627751056 }, { "content": "pub fn path_of_column(\n\n base: impl AsRef<Path>,\n\n column_info: &ColumnCatalog,\n\n suffix: &str,\n\n) -> PathBuf {\n\n base.as_ref()\n\n .join(format!(\"{}{}\", column_info.id(), suffix))\n\n}\n\n\n\n/// Builds a Rowset from [`DataChunk`].\n\npub struct RowsetBuilder {\n\n /// Column information\n\n columns: Arc<[ColumnCatalog]>,\n\n\n\n /// Column data builders\n\n builders: Vec<ColumnBuilderImpl>,\n\n\n\n /// Output directory of the rowset\n\n directory: PathBuf,\n\n\n", "file_path": "src/storage/secondary/rowset/rowset_builder.rs", "rank": 5, "score": 160256.37343087204 }, { "content": "pub fn create_statistics_global_aggregator(\n\n ty: BlockStatisticsType,\n\n) -> Box<dyn StatisticsGlobalAgg> {\n\n match ty {\n\n BlockStatisticsType::RowCount => Box::new(RowCountGlobalAgg::create()),\n\n BlockStatisticsType::DistinctValue => Box::new(DistinctValueGlobalAgg::create()),\n\n }\n\n}\n", "file_path": "src/storage/secondary/statistics.rs", "rank": 6, "score": 160256.37343087204 }, { "content": "/// Find the id of the sort key among column catalogs\n\npub fn find_sort_key_id(column_infos: &[ColumnCatalog]) -> Option<usize> {\n\n let mut key = None;\n\n for (id, column_info) in column_infos.iter().enumerate() {\n\n if column_info.is_primary() {\n\n if key.is_some() {\n\n panic!(\"only one primary key is supported\");\n\n }\n\n key = Some(id);\n\n }\n\n }\n\n key\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::types::{DataTypeExt, DataTypeKind};\n\n\n\n #[test]\n\n fn test_column_catalog() {\n", "file_path": "src/catalog/column.rs", "rank": 7, "score": 148698.39022721903 }, { "content": "/// If primary key is found in [`ColumnCatalog`], sort all in-memory data using that key.\n\nfn sort_datachunk_by_pk(\n\n chunks: &Arc<Vec<DataChunk>>,\n\n column_infos: &[ColumnCatalog],\n\n) -> Arc<Vec<DataChunk>> {\n\n if let Some(sort_key_id) = find_sort_key_id(column_infos) {\n\n if chunks.is_empty() {\n\n return chunks.clone();\n\n }\n\n let mut builders = chunks[0]\n\n .arrays()\n\n .iter()\n\n .map(ArrayBuilderImpl::from_type_of_array)\n\n .collect_vec();\n\n\n\n for chunk in &**chunks {\n\n for (array, builder) in chunk.arrays().iter().zip(builders.iter_mut()) {\n\n builder.append(array);\n\n }\n\n }\n\n\n", "file_path": "src/storage/memory/transaction.rs", "rank": 8, "score": 145388.73137433425 }, { "content": "/// Append data to builder one by one. After appending each item, check if\n\n/// the block should be finished. Return true if a new block builder should\n\n/// be created.\n\n///\n\n/// In the future, for integer data, we should be able to skip the `should_finish`\n\n/// check, as we can calculate expected number of items to add simply by\n\n/// `size_of::<T>() * N`.\n\npub fn append_one_by_one<'a, A: Array>(\n\n iter: &mut Peekable<impl Iterator<Item = Option<&'a A::Item>>>,\n\n builder: &mut impl BlockBuilder<A>,\n\n) -> (usize, bool) {\n\n let mut cnt = 0;\n\n while let Some(to_be_appended) = iter.peek() {\n\n // peek and see if we could push more items into the builder\n\n\n\n if builder.should_finish(to_be_appended) {\n\n return (cnt, true);\n\n }\n\n\n\n // get the item from iterator and push it to the builder\n\n let to_be_appended = iter.next().unwrap();\n\n\n\n builder.append(to_be_appended);\n\n cnt += 1;\n\n }\n\n\n\n (cnt, false)\n", "file_path": "src/storage/secondary/column/primitive_column_builder.rs", "rank": 9, "score": 142179.0444223363 }, { "content": "#[enum_dispatch(SecondaryIterator)]\n\npub trait SecondaryIteratorImpl {}\n\n\n\n/// An iterator over all data in a transaction.\n\n///\n\n/// TODO: Lifetime of the iterator should be bound to the transaction.\n\n/// When the transaction end, accessing items inside iterator is UB.\n\n/// To achieve this, we must enable GAT.\n\npub struct SecondaryTableTxnIterator {\n\n iter: SecondaryIterator,\n\n}\n\n\n\nimpl SecondaryTableTxnIterator {\n\n pub(super) fn new(iter: SecondaryIterator) -> Self {\n\n Self { iter }\n\n }\n\n}\n\n\n\nimpl SecondaryIterator {\n\n #[async_recursion]\n\n pub async fn next_batch(\n", "file_path": "src/storage/secondary/txn_iterator.rs", "rank": 10, "score": 135155.21416364648 }, { "content": "pub trait MemTable {\n\n /// add data to memory table\n\n fn append(&mut self, columns: DataChunk) -> StorageResult<()>;\n\n\n\n /// flush data to [`DataChunk`]\n\n fn flush(self) -> StorageResult<DataChunk>;\n\n}\n\n\n\npub struct BTreeMapMemTable {\n\n columns: Arc<[ColumnCatalog]>,\n\n primary_key_idx: usize,\n\n multi_btree_map: BTreeMultiMap<ComparableDataValue, Row>,\n\n}\n\n\n\nimpl BTreeMapMemTable {\n\n fn new(columns: Arc<[ColumnCatalog]>, primary_key_idx: usize) -> Self {\n\n Self {\n\n columns,\n\n primary_key_idx,\n\n multi_btree_map: BTreeMultiMap::new(),\n", "file_path": "src/storage/secondary/rowset/mem_rowset.rs", "rank": 11, "score": 134840.8864991652 }, { "content": "pub fn build_checksum(checksum_type: ChecksumType, block_data: &[u8]) -> u64 {\n\n match checksum_type {\n\n ChecksumType::None => 0,\n\n ChecksumType::Crc32 => crc32fast::hash(block_data) as u64,\n\n }\n\n}\n\n\n", "file_path": "src/storage/secondary/checksum.rs", "rank": 12, "score": 130522.46897363849 }, { "content": "/// A table in the storage engine. [`Table`] is by default a reference to a table,\n\n/// so you could clone it and manipulate in different threads as you like.\n\npub trait Table: Sync + Send + Clone + 'static {\n\n /// Type of the transaction.\n\n type TransactionType: Transaction;\n\n\n\n type WriteResultFuture<'a>: Future<Output = StorageResult<Self::TransactionType>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type ReadResultFuture<'a>: Future<Output = StorageResult<Self::TransactionType>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type UpdateResultFuture<'a>: Future<Output = StorageResult<Self::TransactionType>> + Send + 'a\n\n where\n\n Self: 'a;\n\n\n\n /// Get schema of the current table\n\n fn columns(&self) -> StorageResult<Arc<[ColumnCatalog]>>;\n\n\n\n /// Begin a read-write-only txn\n\n fn write(&self) -> Self::WriteResultFuture<'_>;\n\n\n", "file_path": "src/storage/mod.rs", "rank": 13, "score": 128813.68006928467 }, { "content": "#[derive(Debug, Default)]\n\nstruct BinderContext {\n\n regular_tables: HashMap<String, TableRefId>,\n\n // Mapping the table name to column names\n\n column_names: HashMap<String, HashSet<String>>,\n\n // Mapping table name to its column ids\n\n column_ids: HashMap<String, Vec<ColumnId>>,\n\n // Mapping table name to its column descrptions\n\n column_descs: HashMap<String, Vec<ColumnDesc>>,\n\n // Stores alias information\n\n aliases: Vec<String>,\n\n}\n\n\n\n/// The binder resolves all expressions referring to schema objects such as\n\n/// tables or views with their column names and types.\n\npub struct Binder {\n\n catalog: Arc<RootCatalog>,\n\n context: BinderContext,\n\n upper_contexts: Vec<BinderContext>,\n\n base_table_refs: Vec<String>,\n\n}\n", "file_path": "src/binder/mod.rs", "rank": 14, "score": 124252.14876024936 }, { "content": "/// Parse the SQL string into a list of ASTs.\n\npub fn parse(sql: &str) -> Result<Vec<Statement>, ParserError> {\n\n let dialect = PostgreSqlDialect {};\n\n Parser::parse_sql(&dialect, sql)\n\n}\n", "file_path": "src/parser/mod.rs", "rank": 15, "score": 120791.73213605842 }, { "content": "struct Inner {\n\n name: String,\n\n table_idxs: HashMap<String, TableId>,\n\n tables: HashMap<TableId, Arc<TableCatalog>>,\n\n next_table_id: TableId,\n\n}\n\n\n\nimpl SchemaCatalog {\n\n pub fn new(id: SchemaId, name: String) -> SchemaCatalog {\n\n SchemaCatalog {\n\n id,\n\n inner: Mutex::new(Inner {\n\n name,\n\n table_idxs: HashMap::new(),\n\n tables: HashMap::new(),\n\n next_table_id: 0,\n\n }),\n\n }\n\n }\n\n\n", "file_path": "src/catalog/schema.rs", "rank": 16, "score": 117012.98906805906 }, { "content": "#[derive(Default)]\n\nstruct Inner {\n\n database_idxs: HashMap<String, DatabaseId>,\n\n databases: HashMap<DatabaseId, Arc<DatabaseCatalog>>,\n\n next_database_id: DatabaseId,\n\n}\n\n\n\nimpl Default for RootCatalog {\n\n fn default() -> Self {\n\n Self::new()\n\n }\n\n}\n\n\n\nimpl RootCatalog {\n\n pub fn new() -> RootCatalog {\n\n let root_catalog = RootCatalog {\n\n inner: Mutex::new(Inner::default()),\n\n };\n\n root_catalog\n\n .add_database(DEFAULT_DATABASE_NAME.into())\n\n .unwrap();\n", "file_path": "src/catalog/root.rs", "rank": 17, "score": 117012.98906805906 }, { "content": "struct Inner {\n\n name: String,\n\n schema_idxs: HashMap<String, SchemaId>,\n\n schemas: HashMap<SchemaId, Arc<SchemaCatalog>>,\n\n next_schema_id: SchemaId,\n\n}\n\n\n\nimpl DatabaseCatalog {\n\n pub fn new(id: DatabaseId, name: String) -> Self {\n\n let db_catalog = DatabaseCatalog {\n\n id,\n\n inner: Mutex::new(Inner {\n\n name,\n\n schema_idxs: HashMap::new(),\n\n schemas: HashMap::new(),\n\n next_schema_id: 0,\n\n }),\n\n };\n\n db_catalog.add_schema(DEFAULT_SCHEMA_NAME.into()).unwrap();\n\n db_catalog\n", "file_path": "src/catalog/database.rs", "rank": 18, "score": 117012.98906805906 }, { "content": "#[enum_dispatch]\n\npub trait StorageDispatch {}\n\n\n\nimpl<S: Storage> StorageDispatch for S {}\n\n\n\n#[cfg(test)]\n\nimpl StorageImpl {\n\n pub fn as_in_memory_storage(&self) -> Arc<InMemoryStorage> {\n\n self.clone().try_into().unwrap()\n\n }\n\n}\n\n\n\nimpl StorageImpl {\n\n pub fn enable_filter_scan(&self) -> bool {\n\n match self {\n\n Self::SecondaryStorage(_) => true,\n\n Self::InMemoryStorage(_) => false,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/storage/mod.rs", "rank": 19, "score": 113081.87017115191 }, { "content": "pub fn merge_conjunctions<I>(iter: I) -> BoundExpr\n\nwhere\n\n I: Iterator<Item = BoundExpr>,\n\n{\n\n let mut ret = BoundExpr::Constant(DataValue::Bool(true));\n\n for expr in iter {\n\n ret = BoundExpr::BinaryOp(BoundBinaryOp {\n\n op: And,\n\n left_expr: Box::new(ret),\n\n right_expr: Box::new(expr),\n\n return_type: Some(DataTypeKind::Boolean.nullable()),\n\n })\n\n }\n\n let rewriter = BoolExprSimplificationRule {};\n\n rewriter.rewrite_expr(&mut ret);\n\n ret\n\n}\n\n\n", "file_path": "src/optimizer/expr_utils.rs", "rank": 20, "score": 110313.69062126585 }, { "content": "pub fn input_col_refs(expr: &BoundExpr) -> BitSet {\n\n let mut set = BitSet::default();\n\n input_col_refs_inner(expr, &mut set);\n\n set\n\n}\n\n\n", "file_path": "src/optimizer/expr_utils.rs", "rank": 21, "score": 107561.50283185056 }, { "content": "pub fn conjunctions(expr: BoundExpr) -> Vec<BoundExpr> {\n\n let mut rets = vec![];\n\n conjunctions_inner(expr, &mut rets);\n\n rets\n\n}\n\n\n", "file_path": "src/optimizer/expr_utils.rs", "rank": 22, "score": 106739.23608567983 }, { "content": "/// Represents a storage engine.\n\npub trait Storage: Sync + Send + 'static {\n\n /// the following two result future types to avoid `impl Future` return different types when\n\n /// impl `Storage`.\n\n type CreateTableResultFuture<'a>: Future<Output = StorageResult<()>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type DropTableResultFuture<'a>: Future<Output = StorageResult<()>> + Send + 'a\n\n where\n\n Self: 'a;\n\n\n\n /// Type of the transaction.\n\n type TransactionType: Transaction;\n\n\n\n /// Type of the table belonging to this storage engine.\n\n type TableType: Table<TransactionType = Self::TransactionType>;\n\n\n\n fn create_table<'a>(\n\n &'a self,\n\n database_id: DatabaseId,\n\n schema_id: SchemaId,\n\n table_name: &'a str,\n\n column_descs: &'a [ColumnCatalog],\n\n ) -> Self::CreateTableResultFuture<'a>;\n\n\n\n fn get_table(&self, table_id: TableRefId) -> StorageResult<Self::TableType>;\n\n\n\n fn drop_table(&self, table_id: TableRefId) -> Self::DropTableResultFuture<'_>;\n\n}\n\n\n", "file_path": "src/storage/mod.rs", "rank": 23, "score": 104391.99225793556 }, { "content": "fn create_table(c: &mut Criterion) {\n\n let runtime = tokio::runtime::Runtime::new().unwrap();\n\n c.bench_function(\"create table\", |b| {\n\n b.to_async(&runtime).iter_batched(\n\n Database::new_in_memory,\n\n |db| async move {\n\n db.run(\"create table t(v1 int, v2 int, v3 int)\")\n\n .await\n\n .unwrap()\n\n },\n\n BatchSize::LargeInput,\n\n );\n\n });\n\n}\n\n\n", "file_path": "benches/e2e.rs", "rank": 24, "score": 103734.15134475772 }, { "content": "pub fn simd_op<T, O, F, const N: usize>(\n\n a: &PrimitiveArray<T>,\n\n b: &PrimitiveArray<T>,\n\n f: F,\n\n) -> PrimitiveArray<O>\n\nwhere\n\n T: NativeType + SimdElement,\n\n O: NativeType + SimdElement,\n\n F: Fn(Simd<T, N>, Simd<T, N>) -> Simd<O, N>,\n\n LaneCount<N>: SupportedLaneCount,\n\n{\n\n assert_eq!(a.len(), b.len());\n\n a.batch_iter::<N>()\n\n .zip(b.batch_iter::<N>())\n\n .map(|(a, b)| BatchItem {\n\n valid: a.valid & b.valid,\n\n data: f(a.data, b.data),\n\n len: a.len,\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/executor/evaluator.rs", "rank": 25, "score": 102615.25980931536 }, { "content": "pub fn shift_input_col_refs(expr: &mut BoundExpr, delta: i32) {\n\n use BoundExpr::*;\n\n match expr {\n\n ColumnRef(_) => {}\n\n InputRef(input_ref) => {\n\n input_ref.index = (input_ref.index as i32 + delta) as usize;\n\n }\n\n AggCall(agg) => {\n\n for arg in &mut agg.args {\n\n shift_input_col_refs(&mut *arg, delta);\n\n }\n\n }\n\n BinaryOp(binary_op) => {\n\n shift_input_col_refs(&mut *binary_op.left_expr, delta);\n\n shift_input_col_refs(&mut *binary_op.right_expr, delta);\n\n }\n\n UnaryOp(unary_op) => shift_input_col_refs(&mut *unary_op.expr, delta),\n\n TypeCast(cast) => shift_input_col_refs(&mut *cast.expr, delta),\n\n IsNull(isnull) => shift_input_col_refs(&mut *isnull.expr, delta),\n\n ExprWithAlias(inner) => shift_input_col_refs(&mut *inner.expr, delta),\n\n Constant(_) => {}\n\n Alias(_) => {}\n\n };\n\n}\n", "file_path": "src/optimizer/expr_utils.rs", "rank": 26, "score": 99797.26968453632 }, { "content": "pub trait ArrayImplSortExt {\n\n fn get_sorted_indices(&self) -> Vec<usize>;\n\n}\n\n\n\n/// Implement dispatch functions for `ArrayImplBuilderPickExt` and `ArrayImplSortExt`\n\nmacro_rules! impl_array_impl_shuffle_ext {\n\n ([], $( { $Abc:ident, $abc:ident, $AbcArray:ty, $AbcArrayBuilder:ty, $Value:ident } ),*) => {\n\n impl ArrayImplBuilderPickExt for ArrayBuilderImpl {\n\n fn pick_from(&mut self, array: &ArrayImpl, logical_rows: &[usize]) {\n\n match (self, array) {\n\n $(\n\n (Self::$Abc(builder), ArrayImpl::$Abc(arr)) => builder.pick_from(arr, logical_rows),\n\n )*\n\n _ => panic!(\"failed to push value: type mismatch\"),\n\n }\n\n }\n\n\n\n fn pick_from_multiple(\n\n &mut self,\n\n arrays: &[impl AsRef<ArrayImpl>],\n", "file_path": "src/array/shuffle_ext.rs", "rank": 27, "score": 99616.63308397988 }, { "content": "pub trait ArrayImplEstimateExt {\n\n /// Get estimated size of the array in memory\n\n fn get_estimated_size(&self) -> usize;\n\n}\n\n\n\n/// Implement dispatch functions for `ArrayImplValidExt` and `ArrayImplEstimateExt`\n\nmacro_rules! impl_array_impl_internal_ext {\n\n ([], $( { $Abc:ident, $abc:ident, $AbcArray:ty, $AbcArrayBuilder:ty, $Value:ident } ),*) => {\n\n impl ArrayImplValidExt for ArrayImpl {\n\n fn get_valid_bitmap(&self) -> &BitVec {\n\n match self {\n\n $(\n\n Self::$Abc(a) => a.get_valid_bitmap(),\n\n )*\n\n }\n\n }\n\n }\n\n\n\n impl ArrayImplEstimateExt for ArrayImpl {\n\n fn get_estimated_size(&self) -> usize {\n", "file_path": "src/array/internal_ext.rs", "rank": 28, "score": 99616.63308397988 }, { "content": "pub trait ArrayImplValidExt {\n\n fn get_valid_bitmap(&self) -> &BitVec;\n\n}\n\n\n", "file_path": "src/array/internal_ext.rs", "rank": 29, "score": 99616.63308397988 }, { "content": "/// An iterator over table in a transaction.\n\npub trait TxnIterator: Send {\n\n type NextFuture<'a>: Future<Output = StorageResult<Option<DataChunk>>> + Send + 'a\n\n where\n\n Self: 'a;\n\n\n\n /// get next batch of elements\n\n fn next_batch(&mut self, expected_size: Option<usize>) -> Self::NextFuture<'_>;\n\n}\n", "file_path": "src/storage/mod.rs", "rank": 30, "score": 99234.58540665993 }, { "content": "/// Get the aggregated statistics from pre-aggregated per-block statistics.\n\npub trait StatisticsGlobalAgg {\n\n fn apply_batch(&mut self, index: &ColumnIndex);\n\n fn get_output(&self) -> DataValue;\n\n}\n\n\n", "file_path": "src/storage/secondary/statistics.rs", "rank": 31, "score": 99020.56150403249 }, { "content": "pub fn conjunctions_inner(expr: BoundExpr, rets: &mut Vec<BoundExpr>) {\n\n match expr {\n\n BinaryOp(bin_expr) if bin_expr.op == And => {\n\n conjunctions_inner(*bin_expr.left_expr, rets);\n\n conjunctions_inner(*bin_expr.right_expr, rets);\n\n }\n\n _ => rets.push(expr),\n\n }\n\n}\n\n\n", "file_path": "src/optimizer/expr_utils.rs", "rank": 32, "score": 97858.73773130005 }, { "content": "pub trait ArrayImplBuilderPickExt {\n\n fn pick_from(&mut self, array: &ArrayImpl, logical_rows: &[usize]);\n\n\n\n fn pick_from_multiple(\n\n &mut self,\n\n arrays: &[impl AsRef<ArrayImpl>],\n\n logical_rows: &[(usize, usize)],\n\n );\n\n}\n\n\n", "file_path": "src/array/shuffle_ext.rs", "rank": 33, "score": 97684.91590624832 }, { "content": "pub fn input_col_refs_inner(expr: &BoundExpr, input_set: &mut BitSet) {\n\n use BoundExpr::*;\n\n\n\n match expr {\n\n ColumnRef(_) => {}\n\n InputRef(input_ref) => {\n\n input_set.insert(input_ref.index);\n\n }\n\n AggCall(agg) => {\n\n for arg in &agg.args {\n\n input_col_refs_inner(arg, input_set);\n\n }\n\n }\n\n BinaryOp(binary_op) => {\n\n input_col_refs_inner(binary_op.left_expr.as_ref(), input_set);\n\n input_col_refs_inner(binary_op.right_expr.as_ref(), input_set);\n\n }\n\n UnaryOp(unary_op) => input_col_refs_inner(unary_op.expr.as_ref(), input_set),\n\n TypeCast(cast) => input_col_refs_inner(cast.expr.as_ref(), input_set),\n\n IsNull(isnull) => input_col_refs_inner(isnull.expr.as_ref(), input_set),\n\n ExprWithAlias(inner) => input_col_refs_inner(inner.expr.as_ref(), input_set),\n\n Constant(_) => {}\n\n Alias(_) => {}\n\n };\n\n}\n\n\n", "file_path": "src/optimizer/expr_utils.rs", "rank": 34, "score": 96968.69919891884 }, { "content": "/// An iterator on a block. This iterator requires the block being pre-loaded in memory.\n\npub trait BlockIterator<A: Array> {\n\n /// Get a batch from the block. A `0` return value means that this batch contains no\n\n /// element. Some iterators might support exact size output. By using `expected_size`,\n\n /// developers can get an array of NO MORE THAN the `expected_size`.\n\n fn next_batch(&mut self, expected_size: Option<usize>, builder: &mut A::Builder) -> usize;\n\n\n\n /// Skip `cnt` items.\n\n fn skip(&mut self, cnt: usize);\n\n\n\n /// Number of items remaining in this block\n\n fn remaining_items(&self) -> usize;\n\n}\n\n\n\n/// A key in block cache contains `rowset_id`, `column_id` and `block_id`.\n\n///\n\n/// TODO: support per-table self-increment RowSet Id. Currently, all tables share one RowSet ID\n\n/// generator.\n\n#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]\n\npub struct BlockCacheKey {\n\n pub rowset_id: u32,\n", "file_path": "src/storage/secondary/block.rs", "rank": 35, "score": 95561.16008438815 }, { "content": "/// Builds a block. All builders should implement the trait, while\n\n/// ensuring that the format follows the block encoding scheme.\n\n///\n\n/// In RisingLight, the block encoding scheme is as follows:\n\n///\n\n/// ```plain\n\n/// | block_type | cksum_type | cksum | data |\n\n/// | 4B | 4B | 8B | variable |\n\n/// ```\n\npub trait BlockBuilder<A: Array> {\n\n /// Append one data into the block.\n\n fn append(&mut self, item: Option<&A::Item>);\n\n\n\n /// Get estimated size of block. Will be useful on runlength or compression encoding.\n\n fn estimated_size(&self) -> usize;\n\n\n\n /// Get distinct values count of block\n\n fn get_statistics(&self) -> Vec<BlockStatistics>;\n\n\n\n /// Check if we should finish the current block. If there is no item in the current\n\n /// builder, this function must return `true`.\n\n fn should_finish(&self, next_item: &Option<&A::Item>) -> bool;\n\n\n\n /// Finish a block and return encoded data.\n\n fn finish(self) -> Vec<u8>;\n\n}\n\n\n", "file_path": "src/storage/secondary/block.rs", "rank": 36, "score": 95561.16008438815 }, { "content": "/// Iterator on a column. This iterator may request data from disk while iterating.\n\npub trait ColumnIterator<A: Array> {\n\n type NextFuture<'a>: Future<Output = StorageResult<Option<(u32, A)>>> + 'a\n\n where\n\n Self: 'a;\n\n\n\n /// Get a batch and the starting row id from the column. A `None` return value means that\n\n /// there are no more elements from the block. By using `expected_size`, developers can\n\n /// get an array of NO MORE THAN the `expected_size` on supported column types.\n\n fn next_batch<'a>(\n\n &'a mut self,\n\n expected_size: Option<usize>,\n\n filter_bitmap: Option<&'a BitVec>,\n\n ) -> Self::NextFuture<'a>;\n\n\n\n /// Number of items that can be fetched without I/O. When the column iterator has finished\n\n /// iterating, the returned value should be 0.\n\n fn fetch_hint(&self) -> usize;\n\n\n\n /// Fetch the current row id in this column iterator\n\n fn fetch_current_row_id(&self) -> u32;\n", "file_path": "src/storage/secondary/column.rs", "rank": 37, "score": 95561.16008438815 }, { "content": "/// Builds a column. [`ColumnBuilder`] will automatically chunk [`Array`] into\n\n/// blocks, calls `BlockBuilder` to generate a block, and builds index for a\n\n/// column. Note that one [`Array`] might require multiple [`ColumnBuilder`] to build.\n\n///\n\n/// * For nullable columns, there will be a bitmap file built with `BitmapColumnBuilder`.\n\n/// * And for concrete data, there will be another column builder with concrete block builder.\n\n///\n\n/// After a single column has been built, an index file will also be generated with `IndexBuilder`.\n\npub trait ColumnBuilder<A: Array> {\n\n /// Append an [`Array`] to the column. [`ColumnBuilder`] will automatically chunk it into\n\n /// small parts.\n\n fn append(&mut self, array: &A);\n\n\n\n /// Finish a column, return block index information and encoded block data\n\n fn finish(self) -> (Vec<BlockIndex>, Vec<u8>);\n\n}\n\n\n", "file_path": "src/storage/secondary/column.rs", "rank": 38, "score": 95561.16008438815 }, { "content": "/// Represents a transaction in storage engine.\n\npub trait Transaction: Sync + Send + 'static {\n\n /// Type of the table iterator\n\n type TxnIteratorType: TxnIterator;\n\n\n\n /// Type of the unique reference to a row\n\n type RowHandlerType: RowHandler;\n\n\n\n type ScanResultFuture<'a>: Future<Output = StorageResult<Self::TxnIteratorType>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type AppendResultFuture<'a>: Future<Output = StorageResult<()>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type DeleteResultFuture<'a>: Future<Output = StorageResult<()>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type CommitResultFuture<'a>: Future<Output = StorageResult<()>> + Send + 'a\n\n where\n\n Self: 'a;\n\n type AbortResultFuture<'a>: Future<Output = StorageResult<()>> + Send + 'a\n", "file_path": "src/storage/mod.rs", "rank": 39, "score": 94189.33927851229 }, { "content": "/// Convert an object name into lower case\n\nfn lower_case_name(name: &ObjectName) -> ObjectName {\n\n ObjectName(\n\n name.0\n\n .iter()\n\n .map(|ident| Ident::new(ident.value.to_lowercase()))\n\n .collect::<Vec<_>>(),\n\n )\n\n}\n", "file_path": "src/binder/mod.rs", "rank": 40, "score": 93413.60567713052 }, { "content": "pub fn binary_op<A, B, O, F, V>(a: &A, b: &B, f: F) -> O\n\nwhere\n\n A: Array,\n\n B: Array,\n\n O: Array,\n\n V: Borrow<O::Item>,\n\n F: Fn(&A::Item, &B::Item) -> V,\n\n{\n\n assert_eq!(a.len(), b.len());\n\n let mut builder = O::Builder::with_capacity(a.len());\n\n for (a, b) in a.iter().zip(b.iter()) {\n\n if let (Some(a), Some(b)) = (a, b) {\n\n builder.push(Some(f(a, b).borrow()));\n\n } else {\n\n builder.push(None);\n\n }\n\n }\n\n builder.finish()\n\n}\n\n\n", "file_path": "src/executor/evaluator.rs", "rank": 41, "score": 92758.65163000947 }, { "content": "/// A temporary reference to a row in table.\n\npub trait RowHandler: Sync + Send + 'static {\n\n fn from_column(column: &ArrayImpl, idx: usize) -> Self;\n\n}\n\n\n", "file_path": "src/storage/mod.rs", "rank": 42, "score": 92222.72367362742 }, { "content": "// Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.\n\n\n\nuse std::collections::{BTreeMap, HashMap};\n\nuse std::sync::Mutex;\n\n\n\nuse super::*;\n\nuse crate::types::{ColumnId, TableId};\n\n\n\n/// The catalog of a table.\n\npub struct TableCatalog {\n\n id: TableId,\n\n inner: Mutex<Inner>,\n\n}\n\n\n", "file_path": "src/catalog/table.rs", "rank": 43, "score": 89814.24643709404 }, { "content": " pub fn name(&self) -> String {\n\n let inner = self.inner.lock().unwrap();\n\n inner.name.clone()\n\n }\n\n\n\n pub fn id(&self) -> TableId {\n\n self.id\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_table_catalog() {\n\n let col0 = ColumnCatalog::new(0, DataTypeKind::Int(None).not_null().to_column(\"a\".into()));\n\n let col1 = ColumnCatalog::new(1, DataTypeKind::Boolean.not_null().to_column(\"b\".into()));\n\n\n\n let col_catalogs = vec![col0, col1];\n", "file_path": "src/catalog/table.rs", "rank": 44, "score": 89812.43574411048 }, { "content": " inner: Mutex::new(Inner {\n\n name,\n\n column_idxs: HashMap::new(),\n\n columns: BTreeMap::new(),\n\n is_materialized_view,\n\n next_column_id: 0,\n\n }),\n\n };\n\n for col_catalog in columns {\n\n table_catalog.add_column(col_catalog).unwrap();\n\n }\n\n table_catalog\n\n }\n\n\n\n pub fn add_column(&self, col_catalog: ColumnCatalog) -> Result<ColumnId, CatalogError> {\n\n let mut inner = self.inner.lock().unwrap();\n\n if inner.column_idxs.contains_key(col_catalog.name()) {\n\n return Err(CatalogError::Duplicated(\n\n \"column\",\n\n col_catalog.name().into(),\n", "file_path": "src/catalog/table.rs", "rank": 45, "score": 89808.15280482934 }, { "content": " let table_catalog = TableCatalog::new(0, \"t\".into(), col_catalogs, false);\n\n\n\n assert!(!table_catalog.contains_column(\"c\"));\n\n assert!(table_catalog.contains_column(\"a\"));\n\n assert!(table_catalog.contains_column(\"b\"));\n\n\n\n assert_eq!(table_catalog.get_column_id_by_name(\"a\"), Some(0));\n\n assert_eq!(table_catalog.get_column_id_by_name(\"b\"), Some(1));\n\n\n\n let col0_catalog = table_catalog.get_column_by_id(0).unwrap();\n\n assert_eq!(col0_catalog.name(), \"a\");\n\n assert_eq!(col0_catalog.datatype().kind(), DataTypeKind::Int(None));\n\n\n\n let col1_catalog = table_catalog.get_column_by_id(1).unwrap();\n\n assert_eq!(col1_catalog.name(), \"b\");\n\n assert_eq!(col1_catalog.datatype().kind(), DataTypeKind::Boolean);\n\n }\n\n}\n", "file_path": "src/catalog/table.rs", "rank": 46, "score": 89806.85158296995 }, { "content": " ));\n\n }\n\n inner.next_column_id += 1;\n\n let id = col_catalog.id();\n\n inner\n\n .column_idxs\n\n .insert(col_catalog.name().to_string(), col_catalog.id());\n\n inner.columns.insert(id, col_catalog);\n\n Ok(id)\n\n }\n\n\n\n pub fn contains_column(&self, name: &str) -> bool {\n\n let inner = self.inner.lock().unwrap();\n\n inner.column_idxs.contains_key(name)\n\n }\n\n\n\n pub fn all_columns(&self) -> BTreeMap<ColumnId, ColumnCatalog> {\n\n let inner = self.inner.lock().unwrap();\n\n inner.columns.clone()\n\n }\n", "file_path": "src/catalog/table.rs", "rank": 47, "score": 89804.60113574669 }, { "content": "\n\n pub fn get_column_id_by_name(&self, name: &str) -> Option<ColumnId> {\n\n let inner = self.inner.lock().unwrap();\n\n inner.column_idxs.get(name).cloned()\n\n }\n\n\n\n pub fn get_column_by_id(&self, id: ColumnId) -> Option<ColumnCatalog> {\n\n let inner = self.inner.lock().unwrap();\n\n inner.columns.get(&id).cloned()\n\n }\n\n\n\n pub fn get_column_by_name(&self, name: &str) -> Option<ColumnCatalog> {\n\n let inner = self.inner.lock().unwrap();\n\n inner\n\n .column_idxs\n\n .get(name)\n\n .and_then(|id| inner.columns.get(id))\n\n .cloned()\n\n }\n\n\n", "file_path": "src/catalog/table.rs", "rank": 48, "score": 89803.84609898317 }, { "content": "// human-readable message\n\nfn print_chunk(chunk: &DataChunk) {\n\n match chunk.header() {\n\n Some(header) => match header[0].as_str() {\n\n \"$insert.row_counts\" => {\n\n println!(\"{} rows inserted\", chunk.array_at(0).get_to_string(0))\n\n }\n\n \"$create\" => println!(\"created\"),\n\n \"$explain\" => println!(\"{}\", chunk.array_at(0).get_to_string(0)),\n\n _ => println!(\"{}\", chunk),\n\n },\n\n None => println!(\"{}\", chunk),\n\n }\n\n}\n\n\n\n/// Run RisingLight interactive mode\n\nasync fn interactive(db: Database) -> Result<()> {\n\n let mut rl = Editor::<()>::new();\n\n let history_path = dirs::cache_dir().map(|p| {\n\n let cache_dir = p.join(\"risinglight\");\n\n std::fs::create_dir_all(cache_dir.as_path()).ok();\n", "file_path": "src/main.rs", "rank": 49, "score": 88492.54230995514 }, { "content": "\n\n pub async fn lock_for_deletion(&self) -> TransactionLock {\n\n self.txn_mgr.lock_for_deletion(self.table_id()).await\n\n }\n\n}\n\n\n\nimpl Table for SecondaryTable {\n\n type TransactionType = SecondaryTransaction;\n\n type ReadResultFuture<'a> = impl Future<Output = StorageResult<Self::TransactionType>> + 'a;\n\n type WriteResultFuture<'a> = impl Future<Output = StorageResult<Self::TransactionType>> + 'a;\n\n type UpdateResultFuture<'a> = impl Future<Output = StorageResult<Self::TransactionType>> + 'a;\n\n\n\n fn columns(&self) -> StorageResult<Arc<[ColumnCatalog]>> {\n\n Ok(self.columns.clone())\n\n }\n\n\n\n fn table_id(&self) -> TableRefId {\n\n self.table_ref_id\n\n }\n\n\n", "file_path": "src/storage/secondary/table.rs", "rank": 50, "score": 84361.52990272928 }, { "content": " }\n\n\n\n pub fn delete(&mut self, row_id: usize) -> Result<(), StorageError> {\n\n self.deleted_rows.insert(row_id);\n\n Ok(())\n\n }\n\n\n\n pub fn get_all_chunks(&self) -> Vec<DataChunk> {\n\n self.chunks.clone()\n\n }\n\n\n\n pub fn get_all_deleted_rows(&self) -> HashSet<usize> {\n\n self.deleted_rows.clone()\n\n }\n\n}\n\n\n\nimpl InMemoryTable {\n\n pub fn new(table_ref_id: TableRefId, columns: &[ColumnCatalog]) -> Self {\n\n Self {\n\n table_ref_id,\n", "file_path": "src/storage/memory/table.rs", "rank": 51, "score": 84360.33046844958 }, { "content": " /// refactored the storage API to have snapshot interface.\n\n pub block_cache: Cache<BlockCacheKey, Block>,\n\n\n\n /// Next RowSet Id and DV Id of the current storage engine\n\n next_id: Arc<(AtomicU32, AtomicU64)>,\n\n}\n\n\n\nimpl SecondaryTable {\n\n pub fn new(\n\n storage_options: Arc<StorageOptions>,\n\n table_ref_id: TableRefId,\n\n columns: &[ColumnCatalog],\n\n next_id: Arc<(AtomicU32, AtomicU64)>,\n\n version: Arc<VersionManager>,\n\n block_cache: Cache<BlockCacheKey, Block>,\n\n txn_mgr: Arc<TransactionManager>,\n\n ) -> Self {\n\n Self {\n\n columns: columns.into(),\n\n column_map: columns\n", "file_path": "src/storage/secondary/table.rs", "rank": 52, "score": 84358.66996090833 }, { "content": " columns: columns.into(),\n\n inner: Arc::new(RwLock::new(InMemoryTableInner::new())),\n\n }\n\n }\n\n}\n\n\n\nimpl Table for InMemoryTable {\n\n type TransactionType = InMemoryTransaction;\n\n type ReadResultFuture<'a> =\n\n impl Future<Output = StorageResult<Self::TransactionType>> + Send + 'a;\n\n type WriteResultFuture<'a> =\n\n impl Future<Output = StorageResult<Self::TransactionType>> + Send + 'a;\n\n type UpdateResultFuture<'a> =\n\n impl Future<Output = StorageResult<Self::TransactionType>> + Send + 'a;\n\n\n\n fn columns(&self) -> StorageResult<Arc<[ColumnCatalog]>> {\n\n Ok(self.columns.clone())\n\n }\n\n\n\n fn table_id(&self) -> TableRefId {\n", "file_path": "src/storage/memory/table.rs", "rank": 53, "score": 84358.56994296692 }, { "content": "// Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.\n\n\n\nuse std::collections::HashSet;\n\nuse std::sync::{Arc, RwLock};\n\nuse std::vec::Vec;\n\n\n\nuse futures::Future;\n\n\n\nuse super::*;\n\nuse crate::array::DataChunk;\n\nuse crate::catalog::TableRefId;\n\nuse crate::storage::Table;\n\n\n\n/// A table in in-memory engine. This struct can be freely cloned, as it\n\n/// only serves as a reference to a table.\n\n#[derive(Clone)]\n\npub struct InMemoryTable {\n\n pub(super) table_ref_id: TableRefId,\n\n pub(super) columns: Arc<[ColumnCatalog]>,\n\n pub(super) inner: InMemoryTableInnerRef,\n", "file_path": "src/storage/memory/table.rs", "rank": 54, "score": 84358.53083236962 }, { "content": "// Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.\n\n\n\nuse std::future::Future;\n\nuse std::path::PathBuf;\n\nuse std::sync::atomic::{AtomicU32, AtomicU64};\n\nuse std::sync::Arc;\n\n\n\nuse moka::future::Cache;\n\n\n\nuse super::*;\n\nuse crate::catalog::TableRefId;\n\nuse crate::storage::Table;\n\n\n\n/// A table in Secondary engine.\n\n///\n\n/// As `SecondaryStorage` holds the reference to `SecondaryTable`, we cannot store\n\n/// `Arc<SecondaryStorage>` inside `SecondaryTable`. This sturct only contains necessary information\n\n/// to decode the columns of the table.\n\n#[derive(Clone)]\n\npub struct SecondaryTable {\n", "file_path": "src/storage/secondary/table.rs", "rank": 55, "score": 84357.31499844311 }, { "content": "}\n\n\n\npub(super) struct InMemoryTableInner {\n\n chunks: Vec<DataChunk>,\n\n deleted_rows: HashSet<usize>,\n\n}\n\n\n\npub(super) type InMemoryTableInnerRef = Arc<RwLock<InMemoryTableInner>>;\n\n\n\nimpl InMemoryTableInner {\n\n pub fn new() -> Self {\n\n Self {\n\n chunks: vec![],\n\n deleted_rows: HashSet::new(),\n\n }\n\n }\n\n\n\n pub fn append(&mut self, chunk: DataChunk) -> Result<(), StorageError> {\n\n self.chunks.push(chunk);\n\n Ok(())\n", "file_path": "src/storage/memory/table.rs", "rank": 56, "score": 84356.71274913625 }, { "content": " /// Table id\n\n pub table_ref_id: TableRefId,\n\n\n\n /// All columns (ordered) in table\n\n pub columns: Arc<[ColumnCatalog]>,\n\n\n\n /// Mapping from [`ColumnId`] to column index in `columns`.\n\n pub column_map: HashMap<ColumnId, usize>,\n\n\n\n /// Root directory of the storage\n\n pub storage_options: Arc<StorageOptions>,\n\n\n\n /// `VersionManager` from `Storage`. Note that this should be removed after we have refactored\n\n /// the storage API to have snapshot interface.\n\n pub version: Arc<VersionManager>,\n\n\n\n /// Will be removed when we have `snapshot` interface.\n\n pub txn_mgr: Arc<TransactionManager>,\n\n\n\n /// Block cache of the storage engine. Note that this should be removed after we have\n", "file_path": "src/storage/secondary/table.rs", "rank": 57, "score": 84354.45991718478 }, { "content": " self.next_id\n\n .1\n\n .fetch_add(1, std::sync::atomic::Ordering::SeqCst)\n\n }\n\n\n\n pub fn get_rowset_path(&self, rowset_id: u32) -> PathBuf {\n\n self.storage_options\n\n .path\n\n .join(format!(\"{}_{}\", self.table_id(), rowset_id))\n\n }\n\n\n\n pub fn get_dv_path(&self, rowset_id: u32, dv_id: u64) -> PathBuf {\n\n self.storage_options\n\n .path\n\n .join(format!(\"dv/{}_{}_{}.dv\", self.table_id(), rowset_id, dv_id))\n\n }\n\n\n\n pub fn table_id(&self) -> u32 {\n\n self.table_ref_id.table_id\n\n }\n", "file_path": "src/storage/secondary/table.rs", "rank": 58, "score": 84349.78025255926 }, { "content": " .iter()\n\n .enumerate()\n\n .map(|(idx, col)| (col.id(), idx))\n\n .collect(),\n\n table_ref_id,\n\n storage_options,\n\n next_id,\n\n version,\n\n block_cache,\n\n txn_mgr,\n\n }\n\n }\n\n\n\n pub fn generate_rowset_id(&self) -> u32 {\n\n self.next_id\n\n .0\n\n .fetch_add(1, std::sync::atomic::Ordering::SeqCst)\n\n }\n\n\n\n pub fn generate_dv_id(&self) -> u64 {\n", "file_path": "src/storage/secondary/table.rs", "rank": 59, "score": 84347.1587032717 }, { "content": " self.table_ref_id\n\n }\n\n\n\n fn write(&self) -> Self::WriteResultFuture<'_> {\n\n async move { InMemoryTransaction::start(self) }\n\n }\n\n\n\n fn read(&self) -> Self::ReadResultFuture<'_> {\n\n async move { InMemoryTransaction::start(self) }\n\n }\n\n\n\n fn update(&self) -> Self::UpdateResultFuture<'_> {\n\n async move { InMemoryTransaction::start(self) }\n\n }\n\n}\n", "file_path": "src/storage/memory/table.rs", "rank": 60, "score": 84344.58192303413 }, { "content": " fn write(&self) -> Self::WriteResultFuture<'_> {\n\n async move { SecondaryTransaction::start(self, false, false).await }\n\n }\n\n\n\n fn read(&self) -> Self::ReadResultFuture<'_> {\n\n async move { SecondaryTransaction::start(self, true, false).await }\n\n }\n\n\n\n fn update(&self) -> Self::UpdateResultFuture<'_> {\n\n async move { SecondaryTransaction::start(self, false, true).await }\n\n }\n\n}\n", "file_path": "src/storage/secondary/table.rs", "rank": 61, "score": 84340.62824679427 }, { "content": "// Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.\n\n\n\nuse super::*;\n\nuse crate::catalog::{ColumnCatalog, ColumnDesc};\n\nuse crate::parser::{ColumnDef, ColumnOption, Statement};\n\nuse crate::types::{DataType, DatabaseId, SchemaId};\n\n\n\n/// A bound `create table` statement.\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct BoundCreateTable {\n\n pub database_id: DatabaseId,\n\n pub schema_id: SchemaId,\n\n pub table_name: String,\n\n pub columns: Vec<ColumnCatalog>,\n\n}\n\n\n\nimpl Binder {\n\n pub fn bind_create_table(&mut self, stmt: &Statement) -> Result<BoundCreateTable, BindError> {\n\n match stmt {\n\n Statement::CreateTable { name, columns, .. } => {\n", "file_path": "src/binder/statement/create_table.rs", "rank": 62, "score": 84261.36507577734 }, { "content": "\n\nimpl std::fmt::Debug for BoundJoinOperator {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n Self::Inner => write!(f, \"Inner\"),\n\n Self::LeftOuter => write!(f, \"Left Outer\"),\n\n Self::RightOuter => write!(f, \"Right Outer\"),\n\n Self::FullOuter => write!(f, \"Full Outer\"),\n\n }\n\n }\n\n}\n\n\n\nimpl Binder {\n\n pub fn bind_table_with_joins(\n\n &mut self,\n\n table_with_joins: &TableWithJoins,\n\n ) -> Result<BoundTableRef, BindError> {\n\n let relation = self.bind_table_ref(&table_with_joins.relation)?;\n\n let mut join_tables = vec![];\n\n for join in &table_with_joins.joins {\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 63, "score": 84256.75784659527 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::sync::Arc;\n\n\n\n use super::*;\n\n use crate::catalog::RootCatalog;\n\n use crate::parser::parse;\n\n use crate::types::{DataTypeExt, DataTypeKind};\n\n\n\n #[test]\n\n fn bind_create_table() {\n\n let catalog = Arc::new(RootCatalog::new());\n\n let mut binder = Binder::new(catalog.clone());\n\n let sql = \"\n\n create table t1 (v1 int not null, v2 int); \n\n create table t2 (a int not null, a int not null);\n\n create table t3 (v1 int not null);\";\n", "file_path": "src/binder/statement/create_table.rs", "rank": 64, "score": 84256.32228363348 }, { "content": "// Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.\n\n\n\nuse std::vec::Vec;\n\n\n\nuse serde::Serialize;\n\n\n\nuse super::BoundExpr::*;\n\nuse super::*;\n\nuse crate::parser::{JoinConstraint, JoinOperator, TableFactor, TableWithJoins};\n\nuse crate::types::DataValue::Bool;\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct BoundedSingleJoinTableRef {\n\n pub table_ref: Box<BoundTableRef>,\n\n pub join_op: BoundJoinOperator,\n\n pub join_cond: BoundExpr,\n\n}\n\n\n\n/// A bound table reference.\n\n#[derive(Debug, PartialEq, Clone)]\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 65, "score": 84251.69004456983 }, { "content": "\n\n assert_eq!(\n\n binder.bind_create_table(&stmts[1]),\n\n Err(BindError::DuplicatedColumn(\"a\".into()))\n\n );\n\n\n\n let database = catalog.get_database_by_id(0).unwrap();\n\n let schema = database.get_schema_by_id(0).unwrap();\n\n schema.add_table(\"t3\".into(), vec![], false).unwrap();\n\n assert_eq!(\n\n binder.bind_create_table(&stmts[2]),\n\n Err(BindError::DuplicatedTable(\"t3\".into()))\n\n );\n\n }\n\n}\n", "file_path": "src/binder/statement/create_table.rs", "rank": 66, "score": 84249.82683953129 }, { "content": " let stmts = parse(sql).unwrap();\n\n\n\n assert_eq!(\n\n binder.bind_create_table(&stmts[0]).unwrap(),\n\n BoundCreateTable {\n\n database_id: 0,\n\n schema_id: 0,\n\n table_name: \"t1\".into(),\n\n columns: vec![\n\n ColumnCatalog::new(\n\n 0,\n\n DataTypeKind::Int(None).not_null().to_column(\"v1\".into())\n\n ),\n\n ColumnCatalog::new(\n\n 1,\n\n DataTypeKind::Int(None).nullable().to_column(\"v2\".into())\n\n ),\n\n ],\n\n }\n\n );\n", "file_path": "src/binder/statement/create_table.rs", "rank": 67, "score": 84249.38853012962 }, { "content": "impl From<&ColumnDef> for ColumnCatalog {\n\n fn from(cdef: &ColumnDef) -> Self {\n\n let mut is_nullable = true;\n\n let mut is_primary_ = false;\n\n for opt in &cdef.options {\n\n match opt.option {\n\n ColumnOption::Null => is_nullable = true,\n\n ColumnOption::NotNull => is_nullable = false,\n\n ColumnOption::Unique { is_primary } => is_primary_ = is_primary,\n\n _ => todo!(\"column options\"),\n\n }\n\n }\n\n ColumnCatalog::new(\n\n 0,\n\n ColumnDesc::new(\n\n DataType::new(cdef.data_type.clone(), is_nullable),\n\n cdef.name.value.to_lowercase(),\n\n is_primary_,\n\n ),\n\n )\n", "file_path": "src/binder/statement/create_table.rs", "rank": 68, "score": 84246.70237725142 }, { "content": "pub enum BoundTableRef {\n\n BaseTableRef {\n\n ref_id: TableRefId,\n\n table_name: String,\n\n column_ids: Vec<ColumnId>,\n\n column_descs: Vec<ColumnDesc>,\n\n },\n\n JoinTableRef {\n\n relation: Box<BoundTableRef>,\n\n join_tables: Vec<BoundedSingleJoinTableRef>,\n\n },\n\n}\n\n\n\n#[derive(PartialEq, Clone, Copy, Serialize)]\n\npub enum BoundJoinOperator {\n\n Inner,\n\n LeftOuter,\n\n RightOuter,\n\n FullOuter,\n\n}\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 69, "score": 84245.99067914764 }, { "content": " pub fn bind_join_constraint(\n\n &mut self,\n\n join_constraint: &JoinConstraint,\n\n ) -> Result<BoundExpr, BindError> {\n\n match join_constraint {\n\n JoinConstraint::On(expr) => {\n\n let expr = self.bind_expr(expr)?;\n\n Ok(expr)\n\n }\n\n _ => todo!(\"Support more join constraints\"),\n\n }\n\n }\n\n\n\n pub fn bind_table_ref_with_name(\n\n &mut self,\n\n database_name: &str,\n\n schema_name: &str,\n\n table_name: &str,\n\n ) -> Result<BoundTableRef, BindError> {\n\n if self.context.regular_tables.contains_key(table_name) {\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 70, "score": 84245.61014829067 }, { "content": " return Err(BindError::DuplicatedTable(table_name.into()));\n\n }\n\n\n\n let ref_id = self\n\n .catalog\n\n .get_table_id_by_name(database_name, schema_name, table_name)\n\n .ok_or_else(|| BindError::InvalidTable(table_name.into()))?;\n\n self.context\n\n .regular_tables\n\n .insert(table_name.into(), ref_id);\n\n self.context\n\n .column_names\n\n .insert(table_name.into(), HashSet::new());\n\n self.context\n\n .column_ids\n\n .insert(table_name.into(), Vec::new());\n\n self.context\n\n .column_descs\n\n .insert(table_name.into(), Vec::new());\n\n let base_table_ref = BoundTableRef::BaseTableRef {\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 71, "score": 84245.17303583495 }, { "content": " .iter()\n\n .enumerate()\n\n .map(|(idx, col)| {\n\n let mut col = ColumnCatalog::from(col);\n\n col.set_id(idx as ColumnId);\n\n col\n\n })\n\n .collect();\n\n Ok(BoundCreateTable {\n\n database_id: db.id(),\n\n schema_id: schema.id(),\n\n table_name: table_name.into(),\n\n columns,\n\n })\n\n }\n\n _ => panic!(\"mismatched statement type\"),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/binder/statement/create_table.rs", "rank": 72, "score": 84245.02446945773 }, { "content": " ref_id,\n\n table_name: table_name.into(),\n\n column_ids: vec![],\n\n column_descs: vec![],\n\n };\n\n self.base_table_refs.push(table_name.into());\n\n Ok(base_table_ref)\n\n }\n\n\n\n pub fn bind_table_ref(&mut self, table: &TableFactor) -> Result<BoundTableRef, BindError> {\n\n match table {\n\n TableFactor::Table { name, alias, .. } => {\n\n let name = &lower_case_name(name);\n\n let (database_name, schema_name, mut table_name) = split_name(name)?;\n\n if let Some(alias) = alias {\n\n table_name = &alias.name.value;\n\n }\n\n self.bind_table_ref_with_name(database_name, schema_name, table_name)\n\n }\n\n _ => panic!(\"bind table ref\"),\n\n }\n\n }\n\n}\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 73, "score": 84244.86351284827 }, { "content": " let join_table = self.bind_table_ref(&join.relation)?;\n\n let (join_op, join_cond) = self.bind_join_op(&join.join_operator)?;\n\n let join_ref = BoundedSingleJoinTableRef {\n\n table_ref: (join_table.into()),\n\n join_op,\n\n join_cond,\n\n };\n\n join_tables.push(join_ref);\n\n }\n\n Ok(BoundTableRef::JoinTableRef {\n\n relation: (relation.into()),\n\n join_tables,\n\n })\n\n }\n\n pub fn bind_join_op(\n\n &mut self,\n\n join_op: &JoinOperator,\n\n ) -> Result<(BoundJoinOperator, BoundExpr), BindError> {\n\n match join_op {\n\n JoinOperator::Inner(constraint) => {\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 74, "score": 84244.65498181198 }, { "content": " let name = &lower_case_name(name);\n\n let (database_name, schema_name, table_name) = split_name(name)?;\n\n let db = self\n\n .catalog\n\n .get_database_by_name(database_name)\n\n .ok_or_else(|| BindError::InvalidDatabase(database_name.into()))?;\n\n let schema = db\n\n .get_schema_by_name(schema_name)\n\n .ok_or_else(|| BindError::InvalidSchema(schema_name.into()))?;\n\n if schema.get_table_by_name(table_name).is_some() {\n\n return Err(BindError::DuplicatedTable(table_name.into()));\n\n }\n\n // check duplicated column names\n\n let mut set = HashSet::new();\n\n for col in columns.iter() {\n\n if !set.insert(col.name.value.to_lowercase()) {\n\n return Err(BindError::DuplicatedColumn(col.name.value.clone()));\n\n }\n\n }\n\n let columns = columns\n", "file_path": "src/binder/statement/create_table.rs", "rank": 75, "score": 84243.97767776239 }, { "content": " let condition = self.bind_join_constraint(constraint)?;\n\n Ok((BoundJoinOperator::Inner, condition))\n\n }\n\n JoinOperator::LeftOuter(constraint) => {\n\n let condition = self.bind_join_constraint(constraint)?;\n\n Ok((BoundJoinOperator::LeftOuter, condition))\n\n }\n\n JoinOperator::RightOuter(constraint) => {\n\n let condition = self.bind_join_constraint(constraint)?;\n\n Ok((BoundJoinOperator::RightOuter, condition))\n\n }\n\n JoinOperator::FullOuter(constraint) => {\n\n let condition = self.bind_join_constraint(constraint)?;\n\n Ok((BoundJoinOperator::FullOuter, condition))\n\n }\n\n JoinOperator::CrossJoin => Ok((BoundJoinOperator::Inner, Constant(Bool(true)))),\n\n _ => todo!(\"Support more join types\"),\n\n }\n\n }\n\n\n", "file_path": "src/binder/table_ref/mod.rs", "rank": 76, "score": 84235.98616092095 }, { "content": "/// Split an object name into `(database name, schema name, table name)`.\n\nfn split_name(name: &ObjectName) -> Result<(&str, &str, &str), BindError> {\n\n Ok(match name.0.as_slice() {\n\n [table] => (DEFAULT_DATABASE_NAME, DEFAULT_SCHEMA_NAME, &table.value),\n\n [schema, table] => (DEFAULT_DATABASE_NAME, &schema.value, &table.value),\n\n [db, schema, table] => (&db.value, &schema.value, &table.value),\n\n _ => return Err(BindError::InvalidTableName(name.0.clone())),\n\n })\n\n}\n\n\n", "file_path": "src/binder/mod.rs", "rank": 77, "score": 83563.80247677543 }, { "content": "fn transform_chunk(chunk: DataChunk, output_columns: &[Column]) -> DataChunk {\n\n output_columns\n\n .iter()\n\n .map(|col| match col {\n\n Column::Pick { index } => chunk.array_at(*index).clone(),\n\n Column::Null { type_ } => {\n\n let mut builder = ArrayBuilderImpl::with_capacity(chunk.cardinality(), type_);\n\n for _ in 0..chunk.cardinality() {\n\n builder.push(&DataValue::Null);\n\n }\n\n builder.finish()\n\n }\n\n })\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::sync::Arc;\n\n\n", "file_path": "src/executor/insert.rs", "rank": 78, "score": 81751.01312786428 }, { "content": "/// Encode a primitive value into fixed-width buffer\n\npub trait PrimitiveFixedWidthEncode: Copy + Clone + 'static + Send + Sync {\n\n /// Width of each element\n\n const WIDTH: usize;\n\n const DEAFULT_VALUE: &'static Self;\n\n\n\n type ArrayType: Array<Item = Self>;\n\n\n\n /// Encode current primitive data to the end of an `Vec<u8>`.\n\n fn encode(&self, buffer: &mut impl BufMut);\n\n\n\n /// Decode a data from a bytes array.\n\n fn decode(buffer: &mut impl Buf) -> Self;\n\n}\n\n\n\nimpl PrimitiveFixedWidthEncode for bool {\n\n const WIDTH: usize = std::mem::size_of::<u8>();\n\n const DEAFULT_VALUE: &'static bool = &false;\n\n type ArrayType = BoolArray;\n\n\n\n fn encode(&self, buffer: &mut impl BufMut) {\n", "file_path": "src/storage/secondary/encode.rs", "rank": 79, "score": 81488.47656881268 }, { "content": "/// Unifying all iterators of a given type\n\npub trait BlockIteratorFactory<A: Array>: Send + Sync + 'static {\n\n /// Generally an enum for all supported iterators for a concrete type\n\n type BlockIteratorImpl: BlockIterator<A> + Send + 'static;\n\n\n\n /// Create iterator from block type, block index and block content, and seek to `start_pos`.\n\n fn get_iterator_for(\n\n &self,\n\n block_type: BlockType,\n\n block: Block,\n\n index: &BlockIndex,\n\n start_pos: usize,\n\n ) -> Self::BlockIteratorImpl;\n\n\n\n /// Create a [`FakeBlockIterator`](super::super::block::FakeBlockIterator) from block index and\n\n /// seek to `start_pos`.\n\n fn get_fake_iterator(&self, index: &BlockIndex, start_pos: usize) -> Self::BlockIteratorImpl;\n\n}\n\n\n\n/// Column iterator that operates on a concrete type\n\npub struct ConcreteColumnIterator<A: Array, F: BlockIteratorFactory<A>> {\n", "file_path": "src/storage/secondary/column/concrete_column_iterator.rs", "rank": 80, "score": 80023.84263444708 }, { "content": "#[derive(Parser, Debug)]\n\n#[clap(author, version, about, long_about = None)]\n\nstruct Args {\n\n /// File to execute. Can be either a SQL `sql` file or sqllogictest `slt` file.\n\n #[clap(short, long)]\n\n file: Option<String>,\n\n\n\n /// Whether to use in-memory engine\n\n #[clap(long)]\n\n memory: bool,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 81, "score": 74731.50897881835 }, { "content": "/// Generate an array of indexes for each element of the chunks.\n\nfn gen_index_array(chunks: &[DataChunk]) -> Vec<RowRef<'_>> {\n\n chunks.iter().flat_map(|chunk| chunk.rows()).collect()\n\n}\n", "file_path": "src/executor/order.rs", "rank": 82, "score": 74386.07552773968 }, { "content": "fn main() {\n\n // Scan test scripts and generate test cases.\n\n println!(\"cargo:rerun-if-changed=tests/sql\");\n\n const PATTERN: &str = \"tests/sql/**/[!_]*.slt\"; // ignore files start with '_'\n\n const MEM_BLOCKLIST: &[&str] = &[\"statistics.slt\"];\n\n const DISK_BLOCKLIST: &[&str] = &[\"blob.slt\"];\n\n\n\n let path = PathBuf::from(env::var(\"OUT_DIR\").unwrap()).join(\"testcase.rs\");\n\n let mut fout = std::fs::File::create(path).expect(\"failed to create file\");\n\n\n\n let paths = glob::glob(PATTERN).expect(\"failed to find test files\");\n\n let mut mem_attrs = String::new();\n\n let mut disk_attrs = String::new();\n\n for entry in paths {\n\n let path = entry.expect(\"failed to read glob entry\");\n\n let subpath = path.strip_prefix(\"tests/sql\").unwrap().to_str().unwrap();\n\n if !MEM_BLOCKLIST.iter().any(|p| subpath.contains(p)) {\n\n writeln!(mem_attrs, \"#[test_case::test_case({:?})]\", subpath).unwrap();\n\n }\n\n if !DISK_BLOCKLIST.iter().any(|p| subpath.contains(p)) {\n", "file_path": "build.rs", "rank": 83, "score": 74045.9337348038 }, { "content": "/// Wrapper for sqllogictest\n\nstruct DatabaseWrapper {\n\n tx: tokio::sync::mpsc::Sender<String>,\n\n rx: Mutex<tokio::sync::mpsc::Receiver<Result<Vec<DataChunk>, risinglight::Error>>>,\n\n}\n\n\n\nimpl sqllogictest::DB for DatabaseWrapper {\n\n type Error = risinglight::Error;\n\n fn run(&self, sql: &str) -> Result<String, Self::Error> {\n\n info!(\"{}\", sql);\n\n self.tx.blocking_send(sql.to_string()).unwrap();\n\n let chunks = self.rx.lock().unwrap().blocking_recv().unwrap()?;\n\n for chunk in &chunks {\n\n println!(\"{:?}\", chunk);\n\n }\n\n let output = chunks\n\n .iter()\n\n .map(datachunk_to_sqllogictest_string)\n\n .collect();\n\n Ok(output)\n\n }\n", "file_path": "src/main.rs", "rank": 84, "score": 73375.33947416178 }, { "content": "struct DatabaseWrapper {\n\n rt: Runtime,\n\n db: Database,\n\n}\n\n\n\nimpl sqllogictest::DB for DatabaseWrapper {\n\n type Error = Error;\n\n fn run(&self, sql: &str) -> Result<String, Self::Error> {\n\n let chunks = self.rt.block_on(self.db.run(sql))?;\n\n let output = chunks\n\n .iter()\n\n .map(datachunk_to_sqllogictest_string)\n\n .collect();\n\n Ok(output)\n\n }\n\n}\n\n\n\nimpl Drop for DatabaseWrapper {\n\n fn drop(&mut self) {\n\n self.rt.block_on(self.db.shutdown()).unwrap();\n\n }\n\n}\n", "file_path": "tests/sqllogictest.rs", "rank": 85, "score": 73375.33947416178 }, { "content": "fn main() {\n\n prost_build::compile_protos(&[\"src/proto/rowset.proto\"], &[\"src/proto\"]).unwrap();\n\n}\n", "file_path": "proto/build.rs", "rank": 86, "score": 72609.20019081328 }, { "content": "fn init_logger() {\n\n use std::sync::Once;\n\n static INIT: Once = Once::new();\n\n INIT.call_once(env_logger::init);\n\n}\n\n\n", "file_path": "tests/sqllogictest.rs", "rank": 87, "score": 71258.75766408199 }, { "content": "#[derive(Default)]\n\nstruct AggExtractor {\n\n agg_calls: Vec<BoundAggCall>,\n\n index: usize,\n\n}\n\n\n\nimpl AggExtractor {\n\n fn new(group_key_count: usize) -> Self {\n\n AggExtractor {\n\n agg_calls: vec![],\n\n index: group_key_count,\n\n }\n\n }\n\n\n\n fn visit_expr(&mut self, expr: &mut BoundExpr) {\n\n use BoundExpr::*;\n\n match expr {\n\n AggCall(agg) => {\n\n let input_ref = InputRef(BoundInputRef {\n\n index: self.index,\n\n return_type: agg.return_type.clone(),\n", "file_path": "src/logical_planner/select.rs", "rank": 88, "score": 70893.51266230807 }, { "content": "#[derive(Default)]\n\nstruct AliasExtractor<'a> {\n\n select_list: &'a [BoundExpr],\n\n}\n\n\n\nimpl<'a> AliasExtractor<'a> {\n\n fn new(select_list: &'a [BoundExpr]) -> Self {\n\n AliasExtractor { select_list }\n\n }\n\n\n\n fn visit_expr(&mut self, expr: BoundOrderBy) -> BoundOrderBy {\n\n use BoundExpr::{Alias, ColumnRef, ExprWithAlias, InputRef};\n\n match expr.expr {\n\n Alias(alias) => {\n\n // Binder has pushed the alias expression to `select_list`, so we can unwrap\n\n // directly\n\n let index = self\n\n .select_list\n\n .iter()\n\n .position(|inner_expr| {\n\n if let ExprWithAlias(e) = inner_expr {\n", "file_path": "src/logical_planner/select.rs", "rank": 89, "score": 68366.51139634282 }, { "content": "pub trait NativeType:\n\n PartialOrd + PartialEq + Debug + Copy + Send + Sync + Sized + Default + 'static\n\n{\n\n}\n\n\n\nmacro_rules! impl_native {\n\n ($($t:ty),*) => {\n\n $(impl NativeType for $t {})*\n\n }\n\n}\n\nimpl_native!(\n\n u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64, bool, Decimal, Date, Interval\n\n);\n", "file_path": "src/types/native.rs", "rank": 90, "score": 64729.12950574195 }, { "content": "fn test_disk(name: &str) {\n\n init_logger();\n\n let temp_dir = tempdir().unwrap();\n\n let rt = Runtime::new().unwrap();\n\n let db = rt.block_on(Database::new_on_disk(\n\n SecondaryStorageOptions::default_for_test(temp_dir.path().to_path_buf()),\n\n ));\n\n let mut tester = sqllogictest::Runner::new(DatabaseWrapper { rt, db });\n\n tester.enable_testdir();\n\n tester\n\n .run_file(Path::new(\"tests/sql\").join(name))\n\n .map_err(|e| panic!(\"{}\", e))\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/sqllogictest.rs", "rank": 91, "score": 64435.430266775395 }, { "content": "fn test_mem(name: &str) {\n\n init_logger();\n\n let mut tester = sqllogictest::Runner::new(DatabaseWrapper {\n\n rt: Runtime::new().unwrap(),\n\n db: Database::new_in_memory(),\n\n });\n\n tester.enable_testdir();\n\n tester\n\n .run_file(Path::new(\"tests/sql\").join(name))\n\n .map_err(|e| panic!(\"{}\", e))\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/sqllogictest.rs", "rank": 92, "score": 64435.430266775395 }, { "content": "fn insert(c: &mut Criterion) {\n\n let runtime = tokio::runtime::Runtime::new().unwrap();\n\n\n\n let mut group = c.benchmark_group(\"insert\");\n\n group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));\n\n for size in [1, 16, 256, 4096, 65536] {\n\n group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {\n\n let sql = std::iter::once(\"insert into t values \")\n\n .chain(std::iter::repeat(\"(1,10,100),\").take(size - 1))\n\n .chain(std::iter::once(\"(1,10,100)\"))\n\n .collect::<String>();\n\n b.to_async(&runtime).iter_batched(\n\n || async {\n\n let db = Database::new_in_memory();\n\n db.run(\"create table t(v1 int, v2 int, v3 int)\")\n\n .await\n\n .unwrap();\n\n db\n\n },\n\n |db| async {\n\n db.await.run(&sql).await.unwrap();\n\n },\n\n BatchSize::LargeInput,\n\n );\n\n });\n\n }\n\n group.finish();\n\n}\n\n\n", "file_path": "benches/e2e.rs", "rank": 93, "score": 63935.50538115355 }, { "content": "/// The extension methods for [`DataType`].\n\npub trait DataTypeExt {\n\n fn nullable(self) -> DataType;\n\n fn not_null(self) -> DataType;\n\n}\n\n\n\nimpl DataTypeExt for DataTypeKind {\n\n fn nullable(self) -> DataType {\n\n DataType::new(self, true)\n\n }\n\n\n\n fn not_null(self) -> DataType {\n\n DataType::new(self, false)\n\n }\n\n}\n\n\n\n// const CHAR_DEFAULT_LEN: u64 = 1;\n\nconst VARCHAR_DEFAULT_LEN: u64 = 256;\n\n\n\npub(crate) type DatabaseId = u32;\n\npub(crate) type SchemaId = u32;\n", "file_path": "src/types/mod.rs", "rank": 94, "score": 63598.86061919895 }, { "content": "fn array_sum(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"array sum\");\n\n group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));\n\n for size in [1, 16, 256, 4096, 65536, 1048576] {\n\n group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {\n\n use risinglight::array::Array;\n\n use risinglight::executor::sum_i32;\n\n let a1: I32Array = (0..size).collect();\n\n b.iter(|| {\n\n a1.iter().fold(None, sum_i32);\n\n })\n\n });\n\n }\n\n group.finish();\n\n\n\n let mut group = c.benchmark_group(\"array sum simd\");\n\n group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));\n\n for size in [1, 16, 256, 4096, 65536, 1048576] {\n\n group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {\n\n let a1: I32Array = (0..size).collect();\n\n b.iter(|| {\n\n a1.batch_iter::<32>().sum::<i32>();\n\n })\n\n });\n\n }\n\n group.finish();\n\n}\n\ncriterion_group!(benches, array_mul, array_sum);\n\ncriterion_main!(benches);\n", "file_path": "benches/array.rs", "rank": 95, "score": 62735.857982960486 }, { "content": "fn select_add(c: &mut Criterion) {\n\n let runtime = tokio::runtime::Runtime::new().unwrap();\n\n\n\n let mut group = c.benchmark_group(\"select add\");\n\n group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));\n\n for size in [1, 16, 256, 4096, 65536] {\n\n group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {\n\n let insert_sql = std::iter::once(\"insert into t values \")\n\n .chain(std::iter::repeat(\"(1,10),\").take(size - 1))\n\n .chain(std::iter::once(\"(1,10)\"))\n\n .collect::<String>();\n\n b.to_async(&runtime).iter_batched(\n\n || async {\n\n let db = Database::new_in_memory();\n\n db.run(\"create table t(v1 int, v2 int)\").await.unwrap();\n\n db.run(&insert_sql).await.unwrap();\n\n db\n\n },\n\n |db| async {\n\n db.await.run(\"select v1 + v2 from t\").await.unwrap();\n", "file_path": "benches/e2e.rs", "rank": 96, "score": 62735.857982960486 }, { "content": "fn array_mul(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"array mul\");\n\n group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));\n\n for size in [1, 16, 256, 4096, 65536] {\n\n group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {\n\n use risinglight::executor::evaluator;\n\n let a1: I32Array = (0..size).collect();\n\n let a2: I32Array = (0..size).collect();\n\n b.iter(|| {\n\n let _: I32Array = evaluator::binary_op(&a1, &a2, |a, b| a * b);\n\n });\n\n });\n\n }\n\n group.finish();\n\n\n\n let mut group = c.benchmark_group(\"array mul simd\");\n\n group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));\n\n for size in [1, 16, 256, 4096, 65536] {\n\n group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| {\n\n use risinglight::executor::evaluator;\n\n let a1: I32Array = (0..size).collect();\n\n let a2: I32Array = (0..size).collect();\n\n b.iter(|| {\n\n let _: I32Array = evaluator::simd_op::<_, _, _, 32>(&a1, &a2, |a, b| a * b);\n\n });\n\n });\n\n }\n\n group.finish();\n\n}\n\n\n", "file_path": "benches/array.rs", "rank": 97, "score": 62735.857982960486 }, { "content": "/// The upcast trait for `PlanNode`.\n\npub trait IntoPlanRef {\n\n fn into_plan_ref(self) -> PlanRef;\n\n fn clone_as_plan_ref(&self) -> PlanRef;\n\n}\n", "file_path": "src/optimizer/plan_nodes/mod.rs", "rank": 98, "score": 62529.19641038278 }, { "content": "/// The common trait over all plan nodes.\n\npub trait PlanNode:\n\n WithPlanNodeType\n\n + IntoPlanRef\n\n + PlanTreeNode\n\n + Debug\n\n + Display\n\n + Downcast\n\n + erased_serde::Serialize\n\n + Send\n\n + Sync\n\n{\n\n /// Get schema of current plan node\n\n fn schema(&self) -> Vec<ColumnDesc> {\n\n vec![]\n\n }\n\n\n\n /// Output column types\n\n fn out_types(&self) -> Vec<DataType> {\n\n self.schema()\n\n .iter()\n", "file_path": "src/optimizer/plan_nodes/mod.rs", "rank": 99, "score": 62529.19641038278 } ]
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 type_name == NAME {\n\n println!(\"===gen impl dl_cr start: {}\", type_name);\n\n }\n\n let mut to_c_quote = Vec::new();\n\n let mut ptr_rust_quote = Vec::new();\n\n for field in fields.iter() {\n\n if let Some(ident) = field.ident.as_ref() {\n\n let c_field_name = ident;\n\n let r_field_name = format_ident!(\"{}\",to_snake_name(&c_field_name.to_string()));\n\n //test\n\n if type_name == NAME {\n\n println!(\"field name: {}:\", c_field_name.to_string());\n", "file_path": "bc/wallets_macro/src/cr.rs", "rank": 0, "score": 326953.67057158484 }, { "content": "pub fn get(url: String, json_req: String, result_in: ThreadOut<String>) {\n\n start_rpc_client_thread(url, json_req, result_in, on_get_request_msg)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/mod.rs", "rank": 3, "score": 280666.5565711395 }, { "content": "pub fn init_wallets_context(c_ctx: *mut *mut CContext) -> *mut CError {\n\n let p = init_parameters();\n\n let c_parameters = CInitParameters::to_c_ptr(&p);\n\n let c_err = unsafe {\n\n let c_err = Wallets_init(c_parameters, c_ctx) as *mut CError;\n\n assert_eq!(0 as CU64, (*c_err).code, \"{:?}\", *c_err);\n\n Wallets_changeNetType(*c_ctx,to_c_char(\"Test\")) as *mut CError\n\n };\n\n c_err\n\n}\n\n\n", "file_path": "bc/wallets_cdl/tests/data/mod.rs", "rank": 4, "score": 280170.97923464584 }, { "content": "pub fn create_wallet(c_ctx: *mut *mut CContext) -> Wallet {\n\n unsafe {\n\n let mnemonic = {\n\n let p_mn = CStr_dAlloc();\n\n {\n\n let c_err = Wallets_generateMnemonic(18, p_mn) as *mut CError;\n\n assert_eq!(0 as CU64, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n\n }\n\n let mn = to_str(*p_mn).to_owned();\n\n CStr_dFree(p_mn);\n\n mn\n\n };\n\n //invalid parameters\n\n let mut c_parameters = CCreateWalletParameters::to_c_ptr(&CreateWalletParameters {\n\n name: \"test\".to_owned(),\n\n password: \"123456\".to_string(),\n\n mnemonic: mnemonic.clone(),\n\n wallet_type: mav::WalletType::Test.to_string(),\n\n });\n", "file_path": "bc/wallets_cdl/tests/data/mod.rs", "rank": 5, "score": 279276.9513307146 }, { "content": "pub fn send_extrinsic(url: String, json_req: String, result_in: ThreadOut<String>) {\n\n start_rpc_client_thread(url, json_req, result_in, on_extrinsic_msg_until_ready)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/mod.rs", "rank": 6, "score": 278188.8016497289 }, { "content": "pub fn start_subcriber(url: String, json_req: String, result_in: ThreadOut<String>) {\n\n start_rpc_client_thread(url, json_req, result_in, on_subscription_msg)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/mod.rs", "rank": 7, "score": 278188.8016497289 }, { "content": "//Currently only erc20 transfer method will be parsed\n\npub fn decode_tranfer_data(input: &str) -> Result<String, error::Error> {\n\n if !input.starts_with(\"0x\") {\n\n return Err(error::Error::Decoder(\"data format error\".to_string()));\n\n }\n\n //0xa9059cbb is the transfer prefix\n\n //Currently only parse additional data\n\n let addition = if input.starts_with(\"0xa9059cbb\") {\n\n let start_len = 2 + 8;\n\n input.get(start_len + 64 * 2..).unwrap()\n\n } else {\n\n input.get(2..).unwrap()\n\n };\n\n // if decode hex string fail,ret\n\n match hex::decode(addition) {\n\n Ok(data) => {\n\n Ok(String::from_utf8(data)?)\n\n }\n\n Err(err) => {\n\n log::error!(\"decode addition fail: {}\", err);\n\n Ok(input.to_string())\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "bc/chain/eth/src/lib.rs", "rank": 8, "score": 271466.4869641885 }, { "content": "pub fn uuid() -> String {\n\n Uuid::new_v4().to_string()\n\n}\n\n\n", "file_path": "bc/mav/src/kits.rs", "rank": 14, "score": 255128.48732785898 }, { "content": "//Generate btc address from uncompressed public key\n\n// bip39 44 32\n\npub fn generate_btc_address(mn: &[u8], chain_type: &str) -> Result<(String, String), error::Error> {\n\n let mn = String::from_utf8(mn.to_vec())?;\n\n let network = match chain_type {\n\n \"BTC\" => Network::Bitcoin,\n\n \"BtcTest\" => Network::Testnet,\n\n \"BtcPrivate\" => Network::Regtest,\n\n \"BtcPrivateTest\" => Network::Regtest,\n\n _ => Network::Testnet,\n\n };\n\n let mnemonic = Mnemonic::from_str(&mn)?;\n\n let mut master = MasterAccount::from_mnemonic(&mnemonic, 0, network, \"\", None)?;\n\n let mut unlocker = Unlocker::new_for_master(&master, \"\")?;\n\n // path(0,0)\n\n let account = Account::new(&mut unlocker, AccountAddressType::P2PKH, 0, 0, 10)?;\n\n master.add_account(account);\n\n let account = master.get_mut((0, 0)).unwrap();\n\n let instance_key = account.next_key().unwrap();\n\n let address = instance_key.address.clone().to_string();\n\n let public_key = instance_key.public.clone();\n\n let ser = public_key.serialize();\n\n let public_key = format!(\"0x{}\", hex::encode(ser));\n\n Ok((address, public_key))\n\n}\n\n\n", "file_path": "bc/chain/btc/src/lib.rs", "rank": 15, "score": 252347.0335417853 }, { "content": "pub fn now_ts_seconds() -> i64 {\n\n chrono::offset::Utc::now().timestamp()\n\n}\n\n\n\n/// 如果数据库文件不存在,则创建它\n\n/// 如果连接出错直接panic\n\npub async fn make_rbatis(db_file_name: &str) -> Result<Rbatis, Error> {\n\n if fs::metadata(db_file_name).is_err() {\n\n let file = path::Path::new(db_file_name);\n\n let dir = file.parent();\n\n if dir.is_none() {\n\n return Err(Error::from(db_file_name));\n\n }\n\n let dir = dir.unwrap();\n\n fs::create_dir_all(dir)?;\n\n fs::File::create(db_file_name)?;\n\n }\n\n let rb = Rbatis::new();\n\n let url = \"sqlite://\".to_owned().add(db_file_name);\n\n rb.link(url.as_str()).await?;\n", "file_path": "bc/mav/src/kits.rs", "rank": 16, "score": 249995.82394663664 }, { "content": "pub fn sql_left_join_get_a(a: &str, a_id: &str, b: &str, b_id: &str) -> String {\n\n let sql = {\n\n format!(\"select {}.* from {} left join {} on {}.{} = {}.{}\",\n\n a, a, b, a, a_id, b, b_id\n\n )\n\n };\n\n sql\n\n}", "file_path": "bc/mav/src/kits.rs", "rank": 17, "score": 249350.80269704474 }, { "content": "pub fn sql_left_join_get_b(a: &str, a_id: &str, b: &str, b_id: &str) -> String {\n\n let sql = {\n\n format!(\"select {}.* from {} left join {} on {}.{} = {}.{}\",\n\n b, a, b, a, a_id, b, b_id\n\n )\n\n };\n\n sql\n\n}\n\n\n", "file_path": "bc/mav/src/kits.rs", "rank": 18, "score": 249350.80269704474 }, { "content": "/// free the memory that make by to_c_char or CString::into_raw\n\npub fn free_c_char(cs: &mut *mut c_char) {\n\n unsafe {\n\n if !cs.is_null() {\n\n CString::from_raw(*cs);\n\n *cs = null_mut(); //sure null\n\n }\n\n };\n\n}\n\n\n", "file_path": "bc/wallets_cdl/src/kits.rs", "rank": 20, "score": 244287.51396577136 }, { "content": "/// free the memory that make by to_c_char or CString::into_raw\n\npub fn free_c_char(cs: &mut *mut c_char) {\n\n unsafe {\n\n if !cs.is_null() {\n\n CString::from_raw(*cs);\n\n *cs = null_mut(); //sure null\n\n }\n\n };\n\n}\n\n\n", "file_path": "demo/ffi/cdl/src/kits.rs", "rank": 21, "score": 244287.51396577136 }, { "content": "pub fn d_ptr_alloc<T>() -> *mut *mut T {\n\n Box::into_raw(Box::new(null_mut()))\n\n}\n\n\n", "file_path": "demo/ffi/cdl/src/kits.rs", "rank": 22, "score": 244281.90396649612 }, { "content": "/// d表示 指针的指针\n\npub fn d_ptr_alloc<T>() -> *mut *mut T {\n\n Box::into_raw(Box::new(null_mut()))\n\n}\n", "file_path": "bc/wallets_cdl/src/kits.rs", "rank": 23, "score": 244281.90396649612 }, { "content": "pub fn state_get_metadata_with_id(id: u32) -> Value {\n\n json_req(\"state_getMetadata\", Value::Null, id)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 24, "score": 232230.46854690238 }, { "content": "/// d表示 指针的指针\n\npub fn d_ptr_free<T: CStruct + Any>(d_ptr: &mut *mut *mut T) {\n\n (*d_ptr).free();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::os::raw::c_char;\n\n use std::ptr::null_mut;\n\n\n\n use wallets_macro::{DlDefault, DlStruct, DlDrop};\n\n\n\n use crate::kits::{CArray, CStruct, d_ptr_alloc, d_ptr_free, to_c_char};\n\n\n\n #[allow(unused_assignments)]\n\n #[test]\n\n fn c_array() {\n\n #[derive(DlDrop)]\n\n struct Data {}\n\n impl CStruct for Data {\n\n fn free(&mut self) {}\n", "file_path": "bc/wallets_cdl/src/kits.rs", "rank": 25, "score": 230798.38907611923 }, { "content": "pub fn state_get_runtime_version_with_id(id: u32) -> Value {\n\n json_req(\"state_getRuntimeVersion\", Value::Null, id)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 26, "score": 230274.1537918844 }, { "content": "pub fn vec_to_string(vec: Vec<u8>) -> String {\n\n let mut r = String::new();\n\n for v in vec {\n\n write!(r, \"{:02x}\", v).expect(\"No write\");\n\n }\n\n r\n\n}\n\n\n", "file_path": "bc/chain/btc/murmel/src/kit.rs", "rank": 27, "score": 230019.73147881243 }, { "content": "#[allow(non_snake_case)]\n\npub fn Str_free(cs: *mut c_char) {\n\n unsafe {\n\n if !cs.is_null() {\n\n Box::from_raw(cs);\n\n }\n\n }\n\n}\n\n\n", "file_path": "demo/ffi/shared/src/lib.rs", "rank": 28, "score": 228518.76595986588 }, { "content": "pub fn hash160(str: &str) -> String {\n\n let decode: Vec<u8> = bitcoin_hashes::hex::FromHex::from_hex(str).expect(\"Invalid public key\");\n\n let hash = bitcoin_hashes::hash160::Hash::hash(&decode[..]);\n\n hash.to_hex()\n\n}\n\n\n", "file_path": "bc/chain/btc/murmel/src/kit.rs", "rank": 29, "score": 228458.1669774967 }, { "content": "fn save_basic_info(c_ctx: *mut *mut CContext, chain_version: &ChainVersion, metadata: String) -> Result<(), String> {\n\n let m_chain_basic_info = init_basic_info_parameters(chain_version, metadata);\n\n let chain_basic_info = SubChainBasicInfo::from(m_chain_basic_info);\n\n let mut c_basic_info = CSubChainBasicInfo::to_c_ptr(&chain_basic_info);\n\n unsafe {\n\n let c_err = chain_eee_c::ChainEee_updateBasicInfo(*c_ctx, c_basic_info) as *mut CError;\n\n let res = {\n\n if Error::SUCCESS().code == (*c_err).code {\n\n Ok(())\n\n } else {\n\n Err(format!(\"{:?}\", *c_err))\n\n }\n\n };\n\n CError_free(c_err);\n\n c_basic_info.free();\n\n res\n\n }\n\n}\n\n\n", "file_path": "bc/wallets_cdl/tests/chain_eee_c.rs", "rank": 30, "score": 228026.32400619335 }, { "content": "pub fn tx_to_hex(tx: &Transaction) -> String {\n\n let ser = bitcoin::consensus::serialize(tx);\n\n vec_to_string(ser)\n\n}\n\n\n", "file_path": "bc/chain/btc/murmel/src/kit.rs", "rank": 31, "score": 226096.8914200386 }, { "content": "/// call free_c_char to free memory\n\npub fn to_c_char(s: &str) -> *mut c_char {\n\n match CString::new(s) {\n\n Err(_e) => {\n\n null_mut()\n\n }\n\n Ok(cs) => cs.into_raw()\n\n }\n\n}\n\n\n", "file_path": "demo/ffi/cdl/src/kits.rs", "rank": 32, "score": 224690.7375096185 }, { "content": "/// call free_c_char to free memory\n\npub fn to_c_char(s: &str) -> *mut c_char {\n\n match CString::new(s) {\n\n Err(_e) => {\n\n null_mut()\n\n }\n\n Ok(cs) => cs.into_raw()\n\n }\n\n}\n\n\n", "file_path": "bc/wallets_cdl/src/kits.rs", "rank": 33, "score": 224690.7375096185 }, { "content": "/// Directly encode a slice as base58\n\npub fn encode_slice(data: &[u8]) -> String {\n\n encode_iter(data.iter().cloned())\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/util/base58.rs", "rank": 34, "score": 223809.3390716106 }, { "content": "// call Str_free to free memory\n\npub fn to_c_char(rs: &str) -> *mut c_char {\n\n let cstr = CString::new(rs).expect(\"Failed to create CString\");\n\n return cstr.into_raw();\n\n}\n\n\n", "file_path": "demo/ffi/shared/src/lib.rs", "rank": 35, "score": 222251.2643077753 }, { "content": "/// Obtain a string with the base58check encoding of a slice\n\n/// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.)\n\npub fn check_encode_slice(data: &[u8]) -> String {\n\n let checksum = sha256d::Hash::hash(&data);\n\n encode_iter(\n\n data.iter()\n\n .cloned()\n\n .chain(checksum[0..4].iter().cloned())\n\n )\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/util/base58.rs", "rank": 36, "score": 221597.49331381678 }, { "content": "pub fn ptr_alloc<T: Default>() -> *mut T {\n\n Box::into_raw(Box::new(T::default()))\n\n}\n", "file_path": "demo/ffi/cdl/src/kits.rs", "rank": 37, "score": 219889.16363785794 }, { "content": "pub fn send_extrinsic_and_wait_until_in_block(\n\n url: String,\n\n json_req: String,\n\n result_in: ThreadOut<String>,\n\n) {\n\n start_rpc_client_thread(url, json_req, result_in, on_extrinsic_msg_until_in_block)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/mod.rs", "rank": 38, "score": 219722.92277196213 }, { "content": "pub fn send_extrinsic_and_wait_until_finalized(\n\n url: String,\n\n json_req: String,\n\n result_in: ThreadOut<String>,\n\n) {\n\n start_rpc_client_thread(url, json_req, result_in, on_extrinsic_msg_until_finalized)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/mod.rs", "rank": 39, "score": 219722.92277196213 }, { "content": "pub fn send_extrinsic_and_wait_until_broadcast(\n\n url: String,\n\n json_req: String,\n\n result_in: ThreadOut<String>,\n\n) {\n\n start_rpc_client_thread(url, json_req, result_in, on_extrinsic_msg_until_broadcast)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/mod.rs", "rank": 40, "score": 219722.92277196213 }, { "content": "//Generate ETH address from uncompressed public key\n\npub fn generate_eth_address(secret_byte: &[u8]) -> Result<(String, String), error::Error> {\n\n let context = Secp256k1::new();\n\n let secret = SecretKey::from_slice(&secret_byte)?;\n\n let public_key = PublicKey::from_secret_key(&context, &secret);\n\n //the uncompressed public key used for address generation\n\n let puk_uncompressed = &public_key.serialize_uncompressed()[..];\n\n let public_key_hash = keccak(&puk_uncompressed[1..]);\n\n let address_str = hex::encode(&public_key_hash[12..]);\n\n let puk_str = hex::encode(&public_key.serialize()[..]);\n\n Ok((format!(\"0x{}\", address_str), format!(\"0x{}\", puk_str)))\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct EthTxHelper {\n\n abi: Contract,\n\n}\n\n\n\n\n\nimpl EthTxHelper {\n\n fn load(abi_data: &[u8]) -> Self {\n", "file_path": "bc/chain/eth/src/lib.rs", "rank": 41, "score": 219364.95196364308 }, { "content": "// do not free the cs's memory\n\npub fn to_str(cs: *mut c_char) -> &'static str {\n\n let cstr = unsafe {\n\n assert!(!cs.is_null()); //todo 别的方法处理\n\n CStr::from_ptr(cs)\n\n };\n\n return cstr.to_str().expect(\"Failed to create str\");\n\n}\n\n\n", "file_path": "demo/ffi/shared/src/lib.rs", "rank": 42, "score": 214536.9190950576 }, { "content": "pub fn author_submit_and_watch_extrinsic_with_id(xthex_prefixed: &str, id: u32) -> Value {\n\n json_req(\"author_submitAndWatchExtrinsic\", vec![xthex_prefixed], id)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 43, "score": 213081.5034340453 }, { "content": "pub fn init_parameters() -> InitParameters {\n\n let mut p = InitParameters::default();\n\n //p.is_memory_db=mav::CTrue;\n\n //let prefix = format!(\"{}_\",kits::uuid());\n\n let prefix = \"test_\";\n\n p.db_name.0 = mav::ma::DbName::new(&prefix, \"\");\n\n p.context_note = format!(\"test_{}\", prefix);\n\n p\n\n}", "file_path": "bc/wallets_cdl/tests/data/mod.rs", "rank": 44, "score": 212416.40672903883 }, { "content": "/// Helper to decode an integer in script format\n\n/// Notice that this fails on overflow: the result is the same as in\n\n/// bitcoind, that only 4-byte signed-magnitude values may be read as\n\n/// numbers. They can be added or subtracted (and a long time ago,\n\n/// multiplied and divided), and this may result in numbers which\n\n/// can't be written out in 4 bytes or less. This is ok! The number\n\n/// just can't be read as a number again.\n\n/// This is a bit crazy and subtle, but it makes sense: you can load\n\n/// 32-bit numbers and do anything with them, which back when mult/div\n\n/// was allowed, could result in up to a 64-bit number. We don't want\n\n/// overflow since that's surprising --- and we don't want numbers that\n\n/// don't fit in 64 bits (for efficiency on modern processors) so we\n\n/// simply say, anything in excess of 32 bits is no longer a number.\n\n/// This is basically a ranged type implementation.\n\npub fn read_scriptint(v: &[u8]) -> Result<i64, Error> {\n\n let len = v.len();\n\n if len == 0 { return Ok(0); }\n\n if len > 4 { return Err(Error::NumericOverflow); }\n\n\n\n let (mut ret, sh) = v.iter()\n\n .fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8));\n\n if v[len - 1] & 0x80 != 0 {\n\n ret &= (1 << (sh - 1)) - 1;\n\n ret = -ret;\n\n }\n\n Ok(ret)\n\n}\n\n\n\n/// This is like \"`read_scriptint` then map 0 to false and everything\n\n/// else as true\", except that the overflow rules don't apply.\n", "file_path": "bc/chain/btc/bitcoin/src/blockdata/script.rs", "rank": 45, "score": 210114.87420401856 }, { "content": "pub fn state_subscribe_storage_with_id(key: Vec<StorageKey>, id: u32) -> Value {\n\n // don't know why we need an additional vec here...\n\n json_req(\"state_subscribeStorage\", vec![key], id)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 46, "score": 208455.6904431239 }, { "content": "pub fn chain_get_block_hash_with_id(number: Option<u32>, id: u32) -> Value {\n\n json_req(\"chain_getBlockHash\", vec![number], id)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 47, "score": 208455.6904431239 }, { "content": "pub fn create_tx_input_sql() -> &'static str {\n\n \"CREATE TABLE IF NOT EXISTS tx_input(id INTEGER PRIMARY KEY AUTOINCREMENT,tx TEXT NOT NULL,sig_script TEXT, prev_tx TEXT, prev_vout TEXT, sequence INTEGER);\"\n\n}\n\n\n", "file_path": "demo/rbatis_demo/src/main.rs", "rank": 48, "score": 204166.44521618786 }, { "content": "// example for how to generate btc address from mnemonic\n\n// use bip39 for mnemonic and get seed .\n\n// use bip44 for extend private keys\n\n// use Secp256k1 for secret key and public key\n\n// use different prefix for different types of addresses\n\n// use hash160 and sha256 for checksum and change output to base58. now you get address\n\npub fn generate_btc_address2(chain_type: &str) {\n\n let network = match chain_type {\n\n \"BTC\" => Network::Bitcoin,\n\n \"BtcTest\" => Network::Testnet,\n\n \"BtcPrivate\" => Network::Regtest,\n\n \"BtcPrivateTest\" => Network::Regtest,\n\n _ => Network::Testnet,\n\n };\n\n\n\n let phrase = \"lawn duty beauty guilt sample fiction name zero demise disagree cram hand\";\n\n let mnemonic = bip39::Mnemonic::from_phrase(phrase, Language::English).unwrap();\n\n let seed = bip39::Seed::new(&mnemonic, \"\"); //\n\n println!(\"{:?}\", &seed);\n\n let path = switch_path(&network);\n\n // mainnet \"m/44'/0'/0'/0/0\"\n\n let ext_private =\n\n tiny_hderive::bip32::ExtendedPrivKey::derive(seed.as_bytes(), path).unwrap();\n\n\n\n let context = Secp256k1::new();\n\n let secret = SecretKey::from_slice(&ext_private.secret().to_vec()).unwrap();\n", "file_path": "bc/chain/btc/src/lib.rs", "rank": 49, "score": 203916.79150940923 }, { "content": "///通过 struct name生成表名\n\nfn gen_table_name(type_name: &str) -> String {\n\n let mut type_name = type_name.to_owned();\n\n let names: Vec<&str> = type_name.split(\"::\").collect();\n\n type_name = names.last().expect(\"gen_table_name -- names.last()\").to_string();\n\n type_name = to_snake_name(&type_name);\n\n type_name\n\n}\n\n\n", "file_path": "bc/wallets_macro/src/db_meta.rs", "rank": 50, "score": 202325.06306566755 }, { "content": "/// Encode an object into a hex-encoded string\n\npub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {\n\n hex_encode(serialize(data))\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/consensus/encode.rs", "rank": 51, "score": 201119.90208757727 }, { "content": "pub fn state_get_storage_with_id(key: StorageKey, at_block: Option<Hash>, id: u32) -> Value {\n\n json_req(\n\n \"state_getStorage\",\n\n vec![to_value(key).unwrap(), to_value(at_block).unwrap()],\n\n id,\n\n )\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 52, "score": 197385.995212505 }, { "content": "fn find_by_id_test(c_ctx: *mut CContext, wallet_id: &str) -> Wallet {\n\n unsafe {\n\n //invalid parameters\n\n\n\n let mut c_wallet_id = to_c_char(\"t\");\n\n let mut c_wallet = CWallet_dAlloc();\n\n {\n\n let c_err = Wallets_findById(null_mut(), null_mut(), null_mut()) as *mut CError;\n\n assert_eq!(Error::PARAMETER().code, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n\n let c_err = Wallets_findById(null_mut(), c_wallet_id, null_mut()) as *mut CError;\n\n assert_eq!(Error::PARAMETER().code, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n\n let c_err = Wallets_findById(null_mut(), null_mut(), c_wallet) as *mut CError;\n\n assert_eq!(Error::PARAMETER().code, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n\n\n\n let c_err = Wallets_findById(c_ctx, null_mut(), null_mut()) as *mut CError;\n\n assert_eq!(Error::PARAMETER().code, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n", "file_path": "bc/wallets_cdl/tests/wallets_c.rs", "rank": 53, "score": 196289.67045041395 }, { "content": "pub fn on_subscription_msg(msg: Message, _out: Sender, result: ThreadOut<String>) -> Result<()> {\n\n info!(\"got on_subscription_msg {}\", msg);\n\n let retstr = msg.as_text().unwrap();\n\n let value: serde_json::Value = serde_json::from_str(retstr).unwrap();\n\n match value[\"id\"].as_str() {\n\n Some(_idstr) => {}\n\n _ => {\n\n // subscriptions\n\n debug!(\"no id field found in response. must be subscription\");\n\n debug!(\"method: {:?}\", value[\"method\"].as_str());\n\n match value[\"method\"].as_str() {\n\n Some(\"state_storage\") => {\n\n let changes = &value[\"params\"][\"result\"][\"changes\"];\n\n\n\n match changes[0][1].as_str() {\n\n Some(change_set) => result.send(change_set.to_owned()).unwrap(),\n\n None => println!(\"No events happened\"),\n\n };\n\n }\n\n Some(\"chain_finalizedHead\") => {\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 54, "score": 193529.06160177052 }, { "content": "///\n\n/// btc now just have three type </br>\n\n/// 1. Bitcoin Mainnet\n\n/// 2. Testnet\n\n/// 3. Regtest (Private)\n\n///\n\npub fn start(net_type: &NetType, address: Vec<&MAddress>) {\n\n let (chain_type, network) = match net_type {\n\n NetType::Main => (ChainType::BTC, Network::Bitcoin),\n\n NetType::Test => (ChainType::BtcTest, Network::Testnet),\n\n NetType::Private => (ChainType::BtcPrivate, Network::Regtest),\n\n _ => (ChainType::BtcTest, Network::Testnet),\n\n };\n\n\n\n let address = address\n\n .iter()\n\n .filter(|&&a| a.chain_type.eq(chain_type.to_string().as_str()))\n\n .collect::<Vec<&&MAddress>>();\n\n\n\n //#[cfg(test)]\n\n simple_logger::SimpleLogger::new()\n\n .with_level(LevelFilter::Debug)\n\n .init()\n\n .unwrap();\n\n\n\n let port = match network {\n", "file_path": "bc/chain/btc/murmel/src/wallet/api.rs", "rank": 55, "score": 193503.2854313381 }, { "content": "/// Search for `needle` in the vector `haystack` and remove every\n\n/// instance of it, returning the number of instances removed.\n\n/// Loops through the vector opcode by opcode, skipping pushed data.\n\npub fn script_find_and_remove(haystack: &mut Vec<u8>, needle: &[u8]) -> usize {\n\n if needle.len() > haystack.len() { return 0; }\n\n if needle.len() == 0 { return 0; }\n\n\n\n let mut top = haystack.len() - needle.len();\n\n let mut n_deleted = 0;\n\n\n\n let mut i = 0;\n\n while i <= top {\n\n if &haystack[i..(i + needle.len())] == needle {\n\n for j in i..top {\n\n haystack.swap(j + needle.len(), j);\n\n }\n\n n_deleted += 1;\n\n // This is ugly but prevents infinite loop in case of overflow\n\n let overflow = top < needle.len();\n\n top = top.wrapping_sub(needle.len());\n\n if overflow { break; }\n\n } else {\n\n i += match opcodes::All::from((*haystack)[i]).classify() {\n", "file_path": "bc/chain/btc/bitcoin/src/util/misc.rs", "rank": 56, "score": 193142.43774325046 }, { "content": "pub fn on_get_request_msg(msg: Message, out: Sender, result: ThreadOut<String>) -> Result<()> {\n\n info!(\"Got get_request_msg {}\", msg);\n\n let retstr = msg.as_text().unwrap();\n\n let value: serde_json::Value = serde_json::from_str(retstr).unwrap();\n\n\n\n result.send(value[\"result\"].to_string()).unwrap();\n\n out.close(CloseCode::Normal).unwrap();\n\n Ok(())\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 57, "score": 191504.38941211105 }, { "content": "/// Obtain a string with the base58check encoding of a slice\n\n/// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.)\n\npub fn check_encode_slice_to_fmt(fmt: &mut fmt::Formatter, data: &[u8]) -> fmt::Result {\n\n let checksum = sha256d::Hash::hash(&data);\n\n let iter = data.iter()\n\n .cloned()\n\n .chain(checksum[0..4].iter().cloned());\n\n format_iter(fmt, iter)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use hex::decode as hex_decode;\n\n\n\n #[test]\n\n fn test_base58_encode() {\n\n // Basics\n\n assert_eq!(&encode_slice(&[0][..]), \"1\");\n\n assert_eq!(&encode_slice(&[1][..]), \"2\");\n\n assert_eq!(&encode_slice(&[58][..]), \"21\");\n\n assert_eq!(&encode_slice(&[13, 36][..]), \"211\");\n", "file_path": "bc/chain/btc/bitcoin/src/util/base58.rs", "rank": 58, "score": 185829.11800963807 }, { "content": "#[cfg(feature = \"std\")]\n\ntype StringBuf = String;\n\n\n\n/// Current prefix of metadata\n\npub const META_RESERVED: u32 = 0x6174656d; // 'meta' warn endianness\n\n\n\n/// On `no_std` we do not support `Decode` and thus `StringBuf` is just `&'static str`.\n\n/// So, if someone tries to decode this stuff on `no_std`, they will get a compilation error.\n", "file_path": "bc/chain/eee/frame-metadata/src/lib.rs", "rank": 59, "score": 185376.15103558256 }, { "content": "///\n\n/// static tx fee mybe not a good idea <br>\n\n/// https://coinb.in/#fees <br>\n\n/// tx fee changes over time <br>\n\n/// size = inputsNum * 148 + outputsNum * 34 + 10 (+/-) 40 <br>\n\n/// tx fee related to inputs and outputs <br>\n\n/// use low fee compaire with tx fee in Mainet <br>\n\n/// '19' comes from coinb.in (Satoshi per Byte: 19) </br>\n\n///\n\n/// another website https://bitcoinfees.earn.com/api/v1/fees/recommended\n\n///\n\npub fn tx_fee(input_sum: u32, outputs_num: u32) -> u32 {\n\n let size = input_sum * 148u32 + outputs_num * 34u32 + 10;\n\n size * 19\n\n}\n\n\n\nmod test {\n\n use crate::kit::tx_fee;\n\n\n\n #[test]\n\n pub fn tx_fee_test() {\n\n let fee = tx_fee(1, 1);\n\n println!(\"{:?}\", fee);\n\n }\n\n}\n", "file_path": "bc/chain/btc/murmel/src/kit.rs", "rank": 60, "score": 182817.34510033773 }, { "content": "#[cfg(target_os = \"android\")]\n\npub fn init_logger_once() {\n\n android_logger::init_once(\n\n android_logger::Config::default()\n\n .with_min_level(log::Level::Error) // limit log level\n\n .with_tag(\"rust\") // logs will show under mytag tag\n\n .with_filter( // configure messages for specific crate\n\n android_logger::FilterBuilder::new()\n\n .parse(\"debug,hello::crate=debug\")\n\n .build())\n\n );\n\n log::trace!(\"init logger\");\n\n}", "file_path": "bc/wallets/src/logger.rs", "rank": 61, "score": 176755.0258064254 }, { "content": "fn init_parameters(c_ctx: *mut *mut CContext) -> *mut CError {\n\n let mut p = InitParameters::default();\n\n p.db_name.0 = mav::ma::DbName::new(\"test_\", \"\");\n\n p.context_note = format!(\"test_{}\", kits::uuid());\n\n let c_parameters = CInitParameters::to_c_ptr(&p);\n\n\n\n let c_err = unsafe { Wallets_init(c_parameters, c_ctx) as *mut CError };\n\n c_err\n\n}\n\n\n", "file_path": "bc/wallets_cdl/tests/chain_btc_c.rs", "rank": 62, "score": 175358.1880365974 }, { "content": "#[cfg(target_os = \"android\")]\n\npub fn init_logger_once() {\n\n android_logger::init_once(\n\n android_logger::Config::default()\n\n .with_min_level(log::Level::Trace) // limit log level\n\n .with_tag(\"rust\") // logs will show under mytag tag\n\n .with_filter( // configure messages for specific crate\n\n android_logger::FilterBuilder::new()\n\n .parse(\"debug,hello::crate=error\")\n\n .build())\n\n );\n\n log::trace!(\"init logger\");\n\n}\n\n\n", "file_path": "demo/ffi/shared/src/lib.rs", "rank": 63, "score": 174961.6336658297 }, { "content": "#[test]\n\npub fn init_wallet_once() {\n\n let c_ctx = CContext_dAlloc();\n\n assert_ne!(null_mut(), c_ctx);\n\n unsafe {\n\n let c_init_parameters = {\n\n let mut p = InitParameters::default();\n\n p.is_memory_db = CFalse;\n\n let prefix = \"test_\";\n\n p.db_name.0 = mav::ma::DbName::new(&prefix, \"\");\n\n p.context_note = format!(\"test_{}\", prefix);\n\n CInitParameters::to_c_ptr(&p)\n\n };\n\n let c_err = Wallets_init(c_init_parameters, c_ctx) as *mut CError;\n\n assert_eq!(0 as CU64, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n\n let c_array_wallet = CArrayCWallet_dAlloc();\n\n let c_err = Wallets_findWalletBaseByName(*c_ctx, to_c_char(\"murmel\"),c_array_wallet) as *mut CError;\n\n assert_eq!(0 as CU64, (*c_err).code, \"Wallets_findWalletBaseByName {:?}\", *c_err);\n\n let wallets: Vec<Wallet> = CArray::to_rust(&**c_array_wallet);\n\n CError_free(c_err);\n\n CArrayCWallet_dFree(c_array_wallet);\n\n CContext_dFree(c_ctx);\n\n assert!(wallets.len() > 0);\n\n println!(\"{:#?}\", wallets);\n\n }\n\n}", "file_path": "bc/wallets_cdl/tests/wallets_c.rs", "rank": 64, "score": 174961.6336658297 }, { "content": "/// 生成创建表的sql script\n\nfn generate_table_script(type_name: &str, fields: &Fields) -> TableMeta {\n\n let mut tm = TableMeta::default();\n\n tm.type_name = type_name.to_owned();\n\n let mut cols = String::new();\n\n for field in fields {\n\n let col_name = field.ident.as_ref().expect(\"field.ident.as_ref()\").to_string();\n\n let type_name = if let Type::Path(TypePath { path, .. }) = &field.ty {\n\n if let Some(PathSegment { ident, arguments }) = path.segments.last() {\n\n match arguments {\n\n PathArguments::None => ident.to_string(),\n\n PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }) => {\n\n if let Some(GenericArgument::Type(Type::Path(TypePath { path, .. }))) = args.last() {\n\n format!(\"{}<{}>\", ident.to_string(), path.segments.last().expect(\"ident.to_string(),path.segments.last()\").ident.to_string())\n\n } else {\n\n panic!(\"{}\", format!(\"generate create table is not support type {} -- {} -- AngleBracketed args is None\", type_name, col_name))\n\n }\n\n }\n\n PathArguments::Parenthesized(_) => panic!(\"{}\", format!(\"generate create table is not support type {} -- {} -- Parenthesized\", type_name, col_name)),\n\n }\n\n } else {\n", "file_path": "bc/wallets_macro/src/db_meta.rs", "rank": 65, "score": 174938.51443036727 }, { "content": "#[test]\n\npub fn init_murmel_try(){\n\n // must free all c_err context c parameters\n\n // different type have different free() functions\n\n let c_ctx = CContext_dAlloc();\n\n assert_ne!(null_mut(), c_ctx);\n\n unsafe {\n\n let init_parameters = {\n\n let mut p = InitParameters::default();\n\n p.is_memory_db = CFalse;\n\n let prefix = \"test_\";\n\n p.db_name.0 = mav::ma::DbName::new(&prefix, \"\");\n\n p.context_note = format!(\"test_{}\", prefix);\n\n p\n\n };\n\n let c_init_parameters = CInitParameters::to_c_ptr(&init_parameters);\n\n let c_err = Wallets_init(c_init_parameters, c_ctx) as *mut CError;\n\n assert_ne!(null_mut(), c_err);\n\n assert_eq!(0 as CU64, (*c_err).code, \"{:?}\", *c_err);\n\n CError_free(c_err);\n\n let c_err = Wallets_changeNetType(*c_ctx,to_c_char(NetType::Test.to_string().as_str())) as *mut CError;\n", "file_path": "bc/wallets_cdl/tests/wallets_c.rs", "rank": 66, "score": 173227.96366968553 }, { "content": "pub fn on_extrinsic_msg_until_finalized(\n\n msg: Message,\n\n out: Sender,\n\n result: ThreadOut<String>,\n\n) -> Result<()> {\n\n let retstr = msg.as_text().unwrap();\n\n debug!(\"got msg {}\", retstr);\n\n match parse_status(retstr) {\n\n (XtStatus::Finalized, val) => end_process(out, result, val),\n\n (XtStatus::Error, e) => panic!(e.unwrap()),\n\n (XtStatus::Future, _) => {\n\n warn!(\"extrinsic has 'future' status. aborting\");\n\n end_process(out, result, None);\n\n }\n\n _ => (),\n\n };\n\n Ok(())\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 67, "score": 171551.08144674415 }, { "content": "pub fn on_extrinsic_msg_until_ready(\n\n msg: Message,\n\n out: Sender,\n\n result: ThreadOut<String>,\n\n) -> Result<()> {\n\n let retstr = msg.as_text().unwrap();\n\n debug!(\"got msg {}\", retstr);\n\n match parse_status(retstr) {\n\n (XtStatus::Finalized, val) => end_process(out, result, val),\n\n (XtStatus::Ready, _) => end_process(out, result, None),\n\n (XtStatus::Future, _) => end_process(out, result, None),\n\n (XtStatus::Error, e) => panic!(e.unwrap()),\n\n _ => (),\n\n };\n\n Ok(())\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 68, "score": 171551.08144674415 }, { "content": "pub fn on_extrinsic_msg_until_in_block(\n\n msg: Message,\n\n out: Sender,\n\n result: ThreadOut<String>,\n\n) -> Result<()> {\n\n let retstr = msg.as_text().unwrap();\n\n debug!(\"got msg {}\", retstr);\n\n match parse_status(retstr) {\n\n (XtStatus::Finalized, val) => end_process(out, result, val),\n\n (XtStatus::InBlock, val) => end_process(out, result, val),\n\n (XtStatus::Future, _) => end_process(out, result, None),\n\n (XtStatus::Error, e) => panic!(e.unwrap()),\n\n _ => (),\n\n };\n\n Ok(())\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 69, "score": 171551.08144674415 }, { "content": "pub fn on_extrinsic_msg_until_broadcast(\n\n msg: Message,\n\n out: Sender,\n\n result: ThreadOut<String>,\n\n) -> Result<()> {\n\n let retstr = msg.as_text().unwrap();\n\n debug!(\"got msg {}\", retstr);\n\n match parse_status(retstr) {\n\n (XtStatus::Finalized, val) => end_process(out, result, val),\n\n (XtStatus::Broadcast, _) => end_process(out, result, None),\n\n (XtStatus::Future, _) => end_process(out, result, None),\n\n (XtStatus::Error, e) => panic!(e.unwrap()),\n\n _ => (),\n\n };\n\n Ok(())\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 70, "score": 171551.08144674415 }, { "content": "/// Tweak a single key using some arbitrary data\n\npub fn tweak_key<C: secp256k1::Verification>(secp: &Secp256k1<C>, mut key: PublicKey, contract: &[u8]) -> PublicKey {\n\n let hmac_result = compute_tweak(&key, contract);\n\n key.key.add_exp_assign(secp, &hmac_result[..]).expect(\"HMAC cannot produce invalid tweak\");\n\n key\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/util/contracthash.rs", "rank": 71, "score": 168123.61887624982 }, { "content": "pub fn create_master() -> Transaction {\n\n let words = \"lawn duty beauty guilt sample fiction name zero demise disagree cram hand\";\n\n let mnemonic = Mnemonic::from_str(&words).expect(\"don't have right mnemonic\");\n\n let mut master =\n\n MasterAccount::from_mnemonic(&mnemonic, 0, Network::Testnet, PASSPHRASE, None).unwrap();\n\n let mut unlocker = Unlocker::new_for_master(&master, PASSPHRASE).unwrap();\n\n let account = Account::new(&mut unlocker, AccountAddressType::P2PKH, 0, 0, 10).unwrap();\n\n master.add_account(account);\n\n\n\n let account = master.get_mut((0, 0)).unwrap();\n\n let instance_key = account.next_key().unwrap();\n\n let source = instance_key.address.clone();\n\n let public_key = instance_key.public.clone();\n\n let public_compressed = public_key.serialize();\n\n let public_compressed = hex::encode(public_compressed);\n\n error!(\"source {}\", &source);\n\n error!(\"public_compressed {:#?}\", &public_compressed);\n\n\n\n let account = Account::new(&mut unlocker, AccountAddressType::P2PKH, 0, 1, 10).unwrap();\n\n master.add_account(account);\n", "file_path": "bc/chain/btc/murmel/src/walletlib.rs", "rank": 72, "score": 164244.56540382086 }, { "content": "pub fn state_get_metadata() -> Value {\n\n state_get_metadata_with_id(1)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 73, "score": 161050.35748419847 }, { "content": "fn eee_basic_info_check(c_ctx: *mut *mut CContext) -> Result<(), Error> {\n\n if c_ctx.is_null() {\n\n return Err(Error::PARAMETER().append_message(\" : ctx is null\"));\n\n }\n\n\n\n // query chain basic info\n\n let chain_version = ChainVersion {\n\n genesis_hash: GENESIS_HASH.to_string(),\n\n runtime_version: RUNTIME_VERSION as i32,\n\n tx_version: TX_VERSION as i32,\n\n };\n\n if get_chain_basic_info(c_ctx, &chain_version).is_none() {\n\n let chain_metadata = include_str!(\"data/chain_metadata.rs\");\n\n let save_res = save_basic_info(c_ctx, &chain_version, chain_metadata.to_string());\n\n assert_eq!(save_res.is_ok(), true);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "bc/wallets_cdl/tests/chain_eee_c.rs", "rank": 74, "score": 160834.51929778268 }, { "content": "pub fn chain_get_genesis_hash() -> Value {\n\n chain_get_block_hash(Some(0))\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 75, "score": 159528.0501499019 }, { "content": "pub fn chain_get_finalized_head() -> Value {\n\n json_req(\"chain_getFinalizedHead\", Value::Null, 1)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 76, "score": 159528.0501499019 }, { "content": "pub fn state_get_runtime_version() -> Value {\n\n state_get_runtime_version_with_id(1)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 77, "score": 159528.0501499019 }, { "content": "pub fn chain_subscribe_finalized_heads() -> Value {\n\n json_req(\"chain_subscribeFinalizedHeads\", Value::Null, 1)\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/json_req.rs", "rank": 78, "score": 159528.0501499019 }, { "content": "fn end_process(out: Sender, result: ThreadOut<String>, value: Option<String>) {\n\n // return result to calling thread\n\n debug!(\"Thread end result :{:?} value:{:?}\", result, value);\n\n let val = value.unwrap_or_else(|| \"\".to_string());\n\n result.send(val).unwrap();\n\n out.close(CloseCode::Normal).unwrap();\n\n}\n\n\n", "file_path": "bc/chain/eee/tests/rpc/client.rs", "rank": 79, "score": 156933.6131734404 }, { "content": "pub fn create_chain_sql() -> &'static str {\n\n \"CREATE TABLE IF NOT EXISTS block_header(id INTEGER PRIMARY KEY AUTOINCREMENT,header TEXT,scanned TEXT,timestamp TEXT);\"\n\n}\n\n\n", "file_path": "demo/rbatis_demo/src/main.rs", "rank": 80, "score": 156681.4743179644 }, { "content": "pub fn create_progress_sql() -> &'static str {\n\n \"CREATE TABLE IF NOT EXISTS progress(id INTEGER PRIMARY KEY AUTOINCREMENT,key TEXT,header TEXT,timestamp TEXT);\"\n\n}\n\n\n", "file_path": "demo/rbatis_demo/src/main.rs", "rank": 81, "score": 156681.4743179644 }, { "content": "fn get_path(short_name: &str) -> String {\n\n const CARGO_MANIFEST_DIR: &str = \"CARGO_MANIFEST_DIR\";\n\n let mut cur = \"generated_sql\".to_owned();\n\n if let Ok(p) = std::env::var(CARGO_MANIFEST_DIR) {\n\n let p = path::Path::new(p.as_str()).join(cur);\n\n cur = p.to_str().expect(\"cur = p.to_str().expect\").to_owned();\n\n }\n\n\n\n if fs::metadata(cur.as_str()).is_err() {\n\n let _ = fs::create_dir(cur.as_str());\n\n }\n\n let full = path::Path::new(cur.as_str()).join(short_name);\n\n return full.to_str().expect(\"full.to_str().\").to_owned();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n // use proc_macro_roids::FieldExt;\n\n use syn::{Fields, FieldsNamed, parse_quote};\n\n\n", "file_path": "bc/wallets_macro/src/db_meta.rs", "rank": 82, "score": 155817.13346210658 }, { "content": "pub fn create_user_address_sql() -> &'static str {\n\n \"CREATE TABLE IF NOT EXISTS user_address(id INTEGER PRIMARY KEY AUTOINCREMENT,address TEXT NOT NULL,compressed_pub_key TEXT);\"\n\n}\n\n\n", "file_path": "demo/rbatis_demo/src/main.rs", "rank": 83, "score": 155110.106081568 }, { "content": "pub fn create_local_tx_sql() -> &'static str {\n\n \"CREATE TABLE IF NOT EXISTS local_tx(id INTEGER PRIMARY KEY AUTOINCREMENT,address_from TEXT not null ,address_to TEXT,value TEXT,status TEXT);\"\n\n}\n\n\n\npub struct ChainSqlite {\n\n rb: Rbatis,\n\n url: String,\n\n}\n\n\n\nasync fn init_rbatis(db_file_name: &str) -> Rbatis {\n\n print!(\"init_rbatis\");\n\n if std::fs::metadata(db_file_name).is_err() {\n\n let file = std::fs::File::create(db_file_name);\n\n if file.is_err() {\n\n print!(\"init file {:?}\", file.err().unwrap());\n\n }\n\n }\n\n let rb = Rbatis::new();\n\n let url = \"sqlite://\".to_owned().add(db_file_name);\n\n print!(\"file url: {:?}\", url);\n", "file_path": "demo/rbatis_demo/src/main.rs", "rank": 84, "score": 155110.106081568 }, { "content": "pub fn create_tx_output_sql() -> &'static str {\n\n \"CREATE TABLE IF NOT EXISTS tx_output(id INTEGER PRIMARY KEY AUTOINCREMENT,tx TEXT not null ,script TEXT, value TEXT, vin TEXT);\"\n\n}\n\n\n", "file_path": "demo/rbatis_demo/src/main.rs", "rank": 85, "score": 155110.106081568 }, { "content": "pub fn is_true(b: CBool) -> bool {\n\n b != CFalse\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn add(a: c_int, b: c_int) -> c_int {\n\n return a + b;\n\n}\n\n\n\n#[no_mangle]\n\npub unsafe extern \"C\" fn multi_i32(v: *mut *mut i32) -> u32 {\n\n if v.is_null() {\n\n return CFalse;\n\n }\n\n (*v).free();\n\n // 释放 *v 的内存\n\n let re = Box::into_raw(Box::new(1));\n\n *v = re;\n\n CTrue\n\n}\n", "file_path": "demo/ffi/cdl/src/lib.rs", "rank": 86, "score": 153379.87143983238 }, { "content": "pub trait CR<C: CStruct, R> {\n\n fn to_c(r: &R) -> C;\n\n\n\n fn to_c_ptr(r: &R) -> *mut C;\n\n\n\n fn to_rust(c: &C) -> R;\n\n\n\n fn ptr_rust(c: *mut C) -> R;\n\n}\n\n\n\n/// c的数组需要定义两个字段,所定义一个结构体进行统一管理\n\n/// 注:c不支持范型,所以cbindgen工具会使用具体的类型来代替\n\n#[repr(C)]\n\n#[derive(Debug)] //,DlStruct,DlDefault\n\npub struct CArray<T: CStruct> {\n\n ptr: *mut T,\n\n //数组指针,变量命名参考 rust Vec\n\n len: CU64,\n\n //数组长度,由于usize是不确定大小类型,在跨语言时不方便使用,所以使用u64类型\n\n cap: CU64, //数组的最大容量,由于usize是不确定大小类型,在跨语言时不方便使用,所以使用u64类型\n", "file_path": "demo/ffi/cdl/src/kits.rs", "rank": 87, "score": 152876.6500236349 }, { "content": "/// c struct 与 rust struct之间的转换\n\npub trait CR<C: CStruct, R> {\n\n /// 从rust 到 c的转换\n\n fn to_c(r: &R) -> C;\n\n /// 从rust 到 c 指针(*mut C)的转换\n\n fn to_c_ptr(r: &R) -> *mut C;\n\n /// 从c到rust的转换\n\n fn to_rust(c: &C) -> R;\n\n /// 从c指针(*mut C)到rust的转换\n\n fn ptr_rust(c: *mut C) -> R;\n\n}\n\n\n", "file_path": "bc/wallets_cdl/src/kits.rs", "rank": 88, "score": 152876.6500236349 }, { "content": "fn encode_iter<I>(data: I) -> String\n\nwhere\n\n I: Iterator<Item = u8> + Clone,\n\n{\n\n let mut ret = String::new();\n\n format_iter(&mut ret, data).expect(\"writing into string shouldn't fail\");\n\n ret\n\n}\n\n\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/util/base58.rs", "rank": 89, "score": 152424.8692988761 }, { "content": "pub fn switch_path(network: &Network) -> &str {\n\n return match network {\n\n Network::Bitcoin => \"m/44'/0'/0'/0/0\",\n\n Network::Testnet => \"m/44'/1'/0'/0/0\",\n\n _ => \"m/44'/1'/0'/0/0\",\n\n };\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::generate_btc_address2;\n\n\n\n #[test]\n\n fn it_works() {\n\n assert_eq!(2 + 2, 4);\n\n }\n\n\n\n #[test]\n\n fn test_genera() {\n\n generate_btc_address2(\"BtcTest\");\n\n }\n\n}\n", "file_path": "bc/chain/btc/src/lib.rs", "rank": 91, "score": 151757.03175660636 }, { "content": "pub fn address_legal(address: &str) -> bool {\n\n let address = address.trim().to_lowercase();\n\n if address.is_empty() || !address.starts_with(\"0x\") || address.len() != 42 {\n\n return false;\n\n }\n\n let chars = address.get(2..).unwrap().chars();\n\n for c in chars {\n\n if !(('a'..='z').contains(&c) || ('0'..='9').contains(&c)) {\n\n log::error!(\"illegal {}\", c);\n\n return false;\n\n }\n\n }\n\n true\n\n}\n\n\n", "file_path": "bc/chain/eth/src/lib.rs", "rank": 92, "score": 151757.03175660636 }, { "content": "/// Helper to encode an integer in script format\n\nfn build_scriptint(n: i64) -> Vec<u8> {\n\n if n == 0 { return vec![] }\n\n\n\n let neg = n < 0;\n\n\n\n let mut abs = if neg { -n } else { n } as usize;\n\n let mut v = vec![];\n\n while abs > 0xFF {\n\n v.push((abs & 0xFF) as u8);\n\n abs >>= 8;\n\n }\n\n // If the number's value causes the sign bit to be set, we need an extra\n\n // byte to get the correct value and correct sign bit\n\n if abs & 0x80 != 0 {\n\n v.push(abs as u8);\n\n v.push(if neg { 0x80u8 } else { 0u8 });\n\n }\n\n // Otherwise we just set the sign bit ourselves\n\n else {\n\n abs |= if neg { 0x80 } else { 0 };\n\n v.push(abs as u8);\n\n }\n\n v\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/blockdata/script.rs", "rank": 93, "score": 150999.8219753139 }, { "content": "/// The maximum value allowed in an output (useful for sanity checking,\n\n/// since keeping everything below this value should prevent overflows\n\n/// if you are doing anything remotely sane with monetary values).\n\npub fn max_money(_: Network) -> u64 {\n\n 21_000_000 * COIN_VALUE\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/blockdata/constants.rs", "rank": 94, "score": 150190.88341835435 }, { "content": "/// In Bitcoind this is insanely described as ~((u256)0 >> 32)\n\npub fn max_target(_: Network) -> Uint256 {\n\n Uint256::from_u64(0xFFFF).unwrap() << 208\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/blockdata/constants.rs", "rank": 95, "score": 150185.66352020996 }, { "content": "/// Deserialize an object from a vector, but will not report an error if said deserialization\n\n/// doesn't consume the entire vector.\n\npub fn deserialize_partial<'a, T: Decodable>(\n\n data: &'a [u8],\n\n) -> Result<(T, usize), Error> {\n\n let mut decoder = Cursor::new(data);\n\n let rv = Decodable::consensus_decode(&mut decoder)?;\n\n let consumed = decoder.position() as usize;\n\n\n\n Ok((rv, consumed))\n\n}\n\n\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/consensus/encode.rs", "rank": 96, "score": 150185.66352020996 }, { "content": "#[inline]\n\npub fn read_scriptbool(v: &[u8]) -> bool {\n\n !(v.is_empty() ||\n\n ((v[v.len() - 1] == 0 || v[v.len() - 1] == 0x80) &&\n\n v.iter().rev().skip(1).all(|&w| w == 0)))\n\n}\n\n\n", "file_path": "bc/chain/btc/bitcoin/src/blockdata/script.rs", "rank": 97, "score": 150185.66352020996 }, { "content": "/// Convert public key into the address\n\npub fn public_to_address(public: &Public) -> Address {\n\n let hash = public.keccak256();\n\n let mut result = Address::zero();\n\n result.as_bytes_mut().copy_from_slice(&hash[12..]);\n\n result\n\n}\n\n\n\nimpl SignedTransaction {\n\n // t_nb 5.3.1 Try to verify transaction and recover sender.\n\n pub fn new(transaction: UnverifiedTransaction) -> Result<Self, publickey::Error> {\n\n if transaction.is_unsigned() {\n\n return Err(publickey::Error::InvalidSignature);\n\n }\n\n let public = transaction.recover_public()?;\n\n let sender = public_to_address(&public);\n\n Ok(SignedTransaction {\n\n transaction,\n\n sender,\n\n public: Some(public),\n\n })\n", "file_path": "bc/chain/eth/src/transaction/transaction.rs", "rank": 98, "score": 150185.66352020996 }, { "content": "pub trait Chain2WalletType {\n\n fn chain_type(wallet_type: &WalletType,net_type:&NetType) -> ChainType;\n\n /// 减少调用时把类型给错,而增加的方法,但不是每次都有实例,所以还保留了无 self的方法\n\n //fn to_chain_type(&self, wallet_type: &WalletType) -> ChainType;\n\n\n\n fn wallet_type(chain_type: &ChainType) -> WalletType {\n\n match chain_type {\n\n ChainType::ETH | ChainType::BTC | ChainType::EEE => WalletType::Normal,\n\n ChainType::EthTest | ChainType::BtcTest | ChainType::EeeTest=>WalletType::Test,\n\n ChainType::EthPrivate | ChainType::BtcPrivate | ChainType::EeePrivate => WalletType::Test,\n\n ChainType::EthPrivateTest | ChainType::BtcPrivateTest | ChainType::EeePrivateTest => WalletType::Test,\n\n }\n\n }\n\n}\n", "file_path": "bc/wallets_types/src/chain.rs", "rank": 99, "score": 149731.62358958984 } ]
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\n let hash = {\n\n let mut hasher = DefaultHasher::new();\n\n hasher.write(path.as_bytes());\n\n hasher.finish()\n\n };\n\n\n\n format!(\"unix://{}/{:x}.sock\", SOCKET_ROOT, hash)\n\n}\n\n\n", "file_path": "crates/shim/src/lib.rs", "rank": 2, "score": 481747.4379597813 }, { "content": "/// Add a process to the given relative cgroup path\n\npub fn add_task_to_cgroup(path: &str, pid: u32) -> Result<()> {\n\n let h = hierarchies::auto();\n\n // use relative path here, need to trim prefix '/'\n\n let path = path.trim_start_matches('/');\n\n\n\n Cgroup::load(h, path)\n\n .add_task(CgroupPid::from(pid as u64))\n\n .map_err(other_error!(e, \"add task to cgroup\"))\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 3, "score": 437192.19094992615 }, { "content": "pub fn write_address(address: &str) -> crate::Result<()> {\n\n let path = Path::new(\"address\");\n\n write_str_to_path(path, address)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 4, "score": 423593.2099760798 }, { "content": "fn path_to_string(path: impl AsRef<Path>) -> Result<String, Error> {\n\n path.as_ref()\n\n .to_str()\n\n .map(|v| v.to_string())\n\n .ok_or_else(|| {\n\n let e = std::io::Error::new(\n\n std::io::ErrorKind::Other,\n\n format!(\"invalid UTF-8 string: {}\", path.as_ref().to_string_lossy()),\n\n );\n\n Error::InvalidPath(e)\n\n })\n\n}\n\n\n", "file_path": "crates/runc/src/utils.rs", "rank": 7, "score": 407702.38422649534 }, { "content": "pub fn write_options(bundle: &str, opt: &Options) -> crate::Result<()> {\n\n let json_opt = JsonOptions::from(opt.to_owned());\n\n let opts_str = serde_json::to_string(&json_opt)?;\n\n let path = Path::new(bundle).join(OPTIONS_FILE_NAME);\n\n write_str_to_path(path.as_path(), opts_str.as_str())\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 8, "score": 406321.4936619889 }, { "content": "pub fn connect(address: impl AsRef<str>) -> Result<RawFd> {\n\n use nix::sys::socket::*;\n\n use nix::unistd::close;\n\n\n\n let unix_addr = UnixAddr::new(address.as_ref())?;\n\n let sock_addr = SockAddr::Unix(unix_addr);\n\n\n\n // SOCK_CLOEXEC flag is Linux specific\n\n #[cfg(target_os = \"linux\")]\n\n const SOCK_CLOEXEC: SockFlag = SockFlag::SOCK_CLOEXEC;\n\n\n\n #[cfg(not(target_os = \"linux\"))]\n\n const SOCK_CLOEXEC: SockFlag = SockFlag::empty();\n\n\n\n let fd = socket(AddressFamily::Unix, SockType::Stream, SOCK_CLOEXEC, None)?;\n\n\n\n // MacOS doesn't support atomic creation of a socket descriptor with `SOCK_CLOEXEC` flag,\n\n // so there is a chance of leak if fork + exec happens in between of these calls.\n\n #[cfg(not(target_os = \"linux\"))]\n\n {\n", "file_path": "crates/shim/src/util.rs", "rank": 10, "score": 389178.4912289497 }, { "content": "pub fn write_str_to_path(filename: &Path, s: &str) -> crate::Result<()> {\n\n let file = filename\n\n .file_name()\n\n .ok_or_else(|| Error::InvalidArgument(String::from(\"pid path illegal\")))?;\n\n let tmp_path = filename\n\n .parent()\n\n .map(|x| x.join(format!(\".{}\", file.to_str().unwrap_or(\"\"))))\n\n .ok_or_else(|| Error::InvalidArgument(String::from(\"failed to create tmp path\")))?;\n\n let tmp_path = tmp_path\n\n .to_str()\n\n .ok_or_else(|| Error::InvalidArgument(String::from(\"failed to get path\")))?;\n\n let mut f = OpenOptions::new()\n\n .write(true)\n\n .create_new(true)\n\n .open(tmp_path)\n\n .map_err(io_error!(e, \"open {}\", filename.to_str().unwrap()))?;\n\n f.write_all(s.as_bytes())\n\n .map_err(io_error!(e, \"write tmp file\"))?;\n\n rename(tmp_path, filename).map_err(io_error!(\n\n e,\n\n \"rename tmp file to {}\",\n\n filename.to_str().unwrap()\n\n ))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 11, "score": 385636.3332350877 }, { "content": "pub fn monitor_notify_by_exec(id: &str, exec_id: &str, exit_code: i32) -> Result<()> {\n\n let monitor = MONITOR.lock().unwrap();\n\n monitor.notify_by_exec(id, exec_id, exit_code)\n\n}\n\n\n\npub struct Monitor {\n\n pub(crate) seq_id: i64,\n\n pub(crate) subscribers: HashMap<i64, Subscriber>,\n\n pub(crate) topic_subs: HashMap<Topic, Vec<i64>>,\n\n}\n\n\n\npub(crate) struct Subscriber {\n\n pub(crate) topic: Topic,\n\n pub(crate) tx: Sender<ExitEvent>,\n\n}\n\n\n\npub struct Subscription {\n\n pub id: i64,\n\n pub rx: Receiver<ExitEvent>,\n\n}\n", "file_path": "crates/shim/src/synchronous/monitor.rs", "rank": 12, "score": 378261.93317041965 }, { "content": "pub fn abs_string<P>(path: P) -> Result<String, Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n path_to_string(abs_path_buf(path)?)\n\n}\n\n\n", "file_path": "crates/runc/src/utils.rs", "rank": 13, "score": 376932.0001922685 }, { "content": "fn kill_process(pid: u32, exit_at: Option<OffsetDateTime>, sig: u32) -> Result<()> {\n\n if pid == 0 {\n\n Err(Error::FailedPreconditionError(\n\n \"process not created\".to_string(),\n\n ))\n\n } else if exit_at.is_some() {\n\n Err(Error::NotFoundError(\"process already finished\".to_string()))\n\n } else {\n\n kill(\n\n Pid::from_raw(pid as i32),\n\n nix::sys::signal::Signal::try_from(sig as i32).unwrap(),\n\n )\n\n .map_err(Into::into)\n\n }\n\n}\n\n\n\npub(crate) struct InitProcess {\n\n pub(crate) common: CommonProcess,\n\n pub(crate) bundle: String,\n\n pub(crate) runtime: runc::Runc,\n", "file_path": "crates/runc-shim/src/synchronous/runc.rs", "rank": 14, "score": 375925.64323425596 }, { "content": "pub fn read_runtime(bundle: impl AsRef<Path>) -> crate::Result<String> {\n\n let path = bundle.as_ref().join(RUNTIME_FILE_NAME);\n\n read_file_to_str(path)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 15, "score": 369407.67980167776 }, { "content": "pub fn init(debug: bool) -> Result<(), Error> {\n\n let logger = FifoLogger::new().map_err(io_error!(e, \"failed to init logger\"))?;\n\n let level = if debug {\n\n log::LevelFilter::Debug\n\n } else {\n\n log::LevelFilter::Info\n\n };\n\n\n\n log::set_boxed_logger(Box::new(logger))?;\n\n log::set_max_level(level);\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use log::{Log, Record};\n\n use nix::{sys::stat, unistd};\n\n\n\n use super::*;\n", "file_path": "crates/shim/src/logger.rs", "rank": 16, "score": 365352.81772160303 }, { "content": "pub fn read_address() -> crate::Result<String> {\n\n let path = Path::new(\"address\");\n\n read_file_to_str(path)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 17, "score": 364923.87474388484 }, { "content": "pub fn read_file_to_str<P: AsRef<Path>>(filename: P) -> crate::Result<String> {\n\n let mut file = File::open(&filename).map_err(io_error!(\n\n e,\n\n \"open {}\",\n\n filename.as_ref().to_string_lossy()\n\n ))?;\n\n let mut content: String = String::new();\n\n file.read_to_string(&mut content).map_err(io_error!(\n\n e,\n\n \"read {}\",\n\n filename.as_ref().to_string_lossy()\n\n ))?;\n\n Ok(content)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 18, "score": 362455.60435599537 }, { "content": "pub fn read_pid_from_file(pid_path: &Path) -> crate::Result<i32> {\n\n let pid_str = read_file_to_str(pid_path)?;\n\n let pid = pid_str.parse::<i32>()?;\n\n Ok(pid)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 19, "score": 361706.3382144955 }, { "content": "pub fn read_options(bundle: impl AsRef<Path>) -> crate::Result<Options> {\n\n let path = bundle.as_ref().join(OPTIONS_FILE_NAME);\n\n let opts_str = read_file_to_str(path)?;\n\n let json_opt: JsonOptions = serde_json::from_str(&opts_str)?;\n\n Ok(json_opt.into())\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 20, "score": 361446.6361388377 }, { "content": "pub fn spawn_copy<R: Read + Send + 'static, W: Write + Send + 'static>(\n\n mut from: R,\n\n mut to: W,\n\n wg_opt: Option<&WaitGroup>,\n\n on_close_opt: Option<Box<dyn FnOnce() + Send + Sync>>,\n\n) -> JoinHandle<()> {\n\n let wg_opt_clone = wg_opt.cloned();\n\n std::thread::spawn(move || {\n\n if let Err(e) = std::io::copy(&mut from, &mut to) {\n\n debug!(\"copy io error: {}\", e);\n\n }\n\n if let Some(x) = on_close_opt {\n\n x()\n\n };\n\n if let Some(x) = wg_opt_clone {\n\n std::mem::drop(x)\n\n };\n\n })\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/io.rs", "rank": 21, "score": 345676.1677904638 }, { "content": "#[cfg(not(feature = \"async\"))]\n\npub fn write_value_to_temp_file<T: Serialize>(value: &T) -> Result<(NamedTempFile, String), Error> {\n\n let filename = format!(\"{}/runc-process-{}\", xdg_runtime_dir(), Uuid::new_v4());\n\n let mut temp_file = Builder::new()\n\n .prefix(&filename)\n\n .rand_bytes(0)\n\n .tempfile()\n\n .map_err(Error::SpecFileCreationFailed)?;\n\n let f = temp_file.as_file_mut();\n\n let spec_json = serde_json::to_string(value).map_err(Error::JsonDeserializationFailed)?;\n\n f.write(spec_json.as_bytes())\n\n .map_err(Error::SpecFileCreationFailed)?;\n\n f.flush().map_err(Error::SpecFileCreationFailed)?;\n\n Ok((temp_file, filename))\n\n}\n\n\n\n/// Write the serialized 'value' to a temp file\n\n/// Unlike the same function in non-async feature,\n\n/// it returns the filename, without the NamedTempFile object,\n\n/// which implements Drop trait to remove the file if it goes out of scope.\n\n/// the async Drop is still not supported in rust,\n", "file_path": "crates/runc/src/utils.rs", "rank": 22, "score": 341536.87449862144 }, { "content": "pub fn mkdir(path: impl AsRef<Path>, mode: mode_t) -> crate::Result<()> {\n\n let path_buf = path.as_ref().to_path_buf();\n\n if !path_buf.as_path().exists() {\n\n let mode = Mode::from_bits(mode).ok_or_else(|| other!(\"invalid dir mode {}\", mode))?;\n\n nix::unistd::mkdir(path_buf.as_path(), mode)?;\n\n }\n\n Ok(())\n\n}\n\n\n\n/// A helper to help remove temperate file or dir when it became useless\n\npub struct HelperRemoveFile {\n\n path: String,\n\n}\n\n\n\nimpl HelperRemoveFile {\n\n pub fn new(path: String) -> Self {\n\n Self { path }\n\n }\n\n}\n\n\n\nimpl Drop for HelperRemoveFile {\n\n fn drop(&mut self) {\n\n std::fs::remove_file(&self.path)\n\n .unwrap_or_else(|e| warn!(\"remove dir {} error: {}\", &self.path, e));\n\n }\n\n}\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 24, "score": 333501.28702961706 }, { "content": "fn start_listener(address: &str) -> std::io::Result<UnixListener> {\n\n let path = parse_sockaddr(address);\n\n // Try to create the needed directory hierarchy.\n\n if let Some(parent) = Path::new(path).parent() {\n\n std::fs::create_dir_all(parent)?;\n\n }\n\n UnixListener::bind(path)\n\n}\n\n\n\npub struct Console {\n\n pub file: File,\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::start_listener;\n\n\n\n #[test]\n\n fn test_start_listener() {\n\n let tmpdir = tempfile::tempdir().unwrap();\n", "file_path": "crates/shim/src/lib.rs", "rank": 25, "score": 330609.4230721699 }, { "content": "pub fn monitor_notify_by_pid(pid: i32, exit_code: i32) -> Result<()> {\n\n let monitor = MONITOR.lock().unwrap();\n\n monitor.notify_by_pid(pid, exit_code)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/monitor.rs", "rank": 26, "score": 329405.84553729236 }, { "content": "pub fn write_runtime(bundle: &str, binary_name: &str) -> crate::Result<()> {\n\n let path = Path::new(bundle).join(RUNTIME_FILE_NAME);\n\n write_str_to_path(path.as_path(), binary_name)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 27, "score": 320900.88854728674 }, { "content": "pub trait Io: Debug + Send + Sync {\n\n /// Return write side of stdin\n\n #[cfg(not(feature = \"async\"))]\n\n fn stdin(&self) -> Option<Box<dyn Write + Send + Sync>> {\n\n None\n\n }\n\n\n\n /// Return read side of stdout\n\n #[cfg(not(feature = \"async\"))]\n\n fn stdout(&self) -> Option<Box<dyn Read + Send>> {\n\n None\n\n }\n\n\n\n /// Return read side of stderr\n\n #[cfg(not(feature = \"async\"))]\n\n fn stderr(&self) -> Option<Box<dyn Read + Send>> {\n\n None\n\n }\n\n\n\n /// Return write side of stdin\n", "file_path": "crates/runc/src/io.rs", "rank": 28, "score": 318571.3673414923 }, { "content": "#[tonic::async_trait]\n\npub trait Snapshotter: Send + Sync + 'static {\n\n /// Error type returned from the underlying snapshotter implementation.\n\n ///\n\n /// This type must be convertable to GRPC status.\n\n type Error: Debug;\n\n\n\n /// Returns the info for an active or committed snapshot by name or key.\n\n ///\n\n /// Should be used for parent resolution, existence checks and to discern\n\n /// the kind of snapshot.\n\n async fn stat(&self, key: String) -> Result<Info, Self::Error>;\n\n\n\n /// Update updates the info for a snapshot.\n\n ///\n\n /// Only mutable properties of a snapshot may be updated.\n\n async fn update(\n\n &self,\n\n info: Info,\n\n fieldpaths: Option<Vec<String>>,\n\n ) -> Result<Info, Self::Error>;\n", "file_path": "crates/snapshots/src/lib.rs", "rank": 29, "score": 318321.2804389035 }, { "content": "/// Sets the OOM score for the process to the parents OOM score + 1\n\n/// to ensure that they parent has a lower score than the shim\n\npub fn adjust_oom_score(pid: u32) -> Result<()> {\n\n let score = read_process_oom_score(std::os::unix::process::parent_id())?;\n\n if score < OOM_SCORE_ADJ_MAX {\n\n write_process_oom_score(pid, score + 1)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 30, "score": 317636.5941406777 }, { "content": "// helper to resolve path (such as path for runc binary, pid files, etc. )\n\npub fn abs_path_buf<P>(path: P) -> Result<PathBuf, Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n Ok(path\n\n .as_ref()\n\n .absolutize()\n\n .map_err(Error::InvalidPath)?\n\n .to_path_buf())\n\n}\n\n\n", "file_path": "crates/runc/src/utils.rs", "rank": 31, "score": 317428.92057604576 }, { "content": "pub fn set_cgroup_and_oom_score(pid: u32) -> Result<()> {\n\n if pid == 0 {\n\n return Ok(());\n\n }\n\n\n\n // set cgroup\n\n let mut data: Vec<u8> = Vec::new();\n\n std::io::stdin()\n\n .read_to_end(&mut data)\n\n .map_err(io_error!(e, \"read stdin\"))?;\n\n\n\n if !data.is_empty() {\n\n let opts = Any::parse_from_bytes(&data)\n\n .and_then(|any| Options::parse_from_bytes(any.get_value()))?;\n\n\n\n if !opts.shim_cgroup.is_empty() {\n\n add_task_to_cgroup(opts.shim_cgroup.as_str(), pid)?;\n\n }\n\n }\n\n\n\n // set oom score\n\n adjust_oom_score(pid)\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 32, "score": 312479.09219333786 }, { "content": "/// Collect process cgroup stats, return only necessary parts of it\n\npub fn collect_metrics(pid: u32) -> Result<Metrics> {\n\n let mut metrics = Metrics::new();\n\n // get container main process cgroup\n\n let path =\n\n get_cgroups_relative_paths_by_pid(pid).map_err(other_error!(e, \"get process cgroup\"))?;\n\n let cgroup = Cgroup::load_with_relative_paths(hierarchies::auto(), Path::new(\".\"), path);\n\n\n\n // to make it easy, fill the necessary metrics only.\n\n for sub_system in Cgroup::subsystems(&cgroup) {\n\n match sub_system {\n\n Subsystem::CpuAcct(cpuacct_ctr) => {\n\n let mut cpu_usage = CPUUsage::new();\n\n cpu_usage.set_total(cpuacct_ctr.cpuacct().usage);\n\n let mut cpu_stat = CPUStat::new();\n\n cpu_stat.set_usage(cpu_usage);\n\n metrics.set_cpu(cpu_stat);\n\n }\n\n Subsystem::Mem(mem_ctr) => {\n\n let mem = mem_ctr.memory_stat();\n\n let mut mem_entry = MemoryEntry::new();\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 33, "score": 310695.1140926246 }, { "content": "pub fn read_spec_from_file(bundle: &str) -> crate::Result<Spec> {\n\n let path = Path::new(bundle).join(\"config.json\");\n\n Spec::load(path).map_err(other_error!(e, \"read spec file\"))\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/util.rs", "rank": 34, "score": 309171.3542132789 }, { "content": "pub fn create_task(service: Arc<std::boxed::Box<dyn Task + Send + Sync>>) -> HashMap <String, Box<dyn ::ttrpc::MethodHandler + Send + Sync>> {\n\n let mut methods = HashMap::new();\n\n\n\n methods.insert(\"/containerd.task.v2.Task/State\".to_string(),\n\n std::boxed::Box::new(StateMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Create\".to_string(),\n\n std::boxed::Box::new(CreateMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Start\".to_string(),\n\n std::boxed::Box::new(StartMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Delete\".to_string(),\n\n std::boxed::Box::new(DeleteMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Pids\".to_string(),\n\n std::boxed::Box::new(PidsMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Pause\".to_string(),\n\n std::boxed::Box::new(PauseMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n", "file_path": "crates/shim-protos/src/shim/shim_ttrpc.rs", "rank": 35, "score": 308230.5953107641 }, { "content": "// Original containerd's protobuf files contain Go style imports:\n\n// import \"github.com/containerd/containerd/api/types/mount.proto\";\n\n//\n\n// Tonic produces invalid code for these imports:\n\n// error[E0433]: failed to resolve: there are too many leading `super` keywords\n\n// --> /containerd-rust-extensions/target/debug/build/containerd-client-protos-0a328c0c63f60cd0/out/containerd.services.diff.v1.rs:47:52\n\n// |\n\n// 47 | pub diff: ::core::option::Option<super::super::super::types::Descriptor>,\n\n// | ^^^^^ there are too many leading `super` keywords\n\n//\n\n// This func fixes imports to crate level ones, like `crate::types::Mount`\n\nfn fixup_imports(path: &str) -> Result<(), io::Error> {\n\n let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n let path = format!(\"{}/{}.rs\", out_dir, path);\n\n\n\n let contents = fs::read_to_string(&path)?\n\n .replace(\"super::super::super::v1::types\", \"crate::types::v1\") // for tasks service\n\n .replace(\"super::super::super::types\", \"crate::types\")\n\n .replace(\"super::super::super::super::google\", \"crate::google\");\n\n fs::write(path, contents)?;\n\n Ok(())\n\n}\n", "file_path": "crates/client/build.rs", "rank": 36, "score": 303189.20985859097 }, { "content": "// Original containerd's protobuf files contain Go style imports:\n\n// import \"github.com/containerd/containerd/api/types/mount.proto\";\n\n//\n\n// Tonic produces invalid code for these imports:\n\n// error[E0433]: failed to resolve: there are too many leading `super` keywords\n\n// --> /containerd-rust-extensions/target/debug/build/containerd-client-protos-0a328c0c63f60cd0/out/containerd.services.diff.v1.rs:47:52\n\n// |\n\n// 47 | pub diff: ::core::option::Option<super::super::super::types::Descriptor>,\n\n// | ^^^^^ there are too many leading `super` keywords\n\n//\n\n// This func fixes imports to crate level ones, like `crate::types::Mount`\n\nfn fixup_imports(path: &str) -> Result<(), io::Error> {\n\n let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n let path = format!(\"{}/{}.rs\", out_dir, path);\n\n\n\n let contents =\n\n fs::read_to_string(&path)?.replace(\"super::super::super::types\", \"crate::api::types\");\n\n fs::write(path, contents)?;\n\n Ok(())\n\n}\n", "file_path": "crates/snapshots/build.rs", "rank": 37, "score": 303189.20985859097 }, { "content": "#[async_trait]\n\npub trait Task: Sync {\n\n async fn state(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::StateRequest) -> ::ttrpc::Result<super::shim::StateResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/State is not supported\".to_string())))\n\n }\n\n async fn create(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::CreateTaskRequest) -> ::ttrpc::Result<super::shim::CreateTaskResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Create is not supported\".to_string())))\n\n }\n\n async fn start(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::StartRequest) -> ::ttrpc::Result<super::shim::StartResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Start is not supported\".to_string())))\n\n }\n\n async fn delete(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::DeleteRequest) -> ::ttrpc::Result<super::shim::DeleteResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Delete is not supported\".to_string())))\n\n }\n\n async fn pids(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::PidsRequest) -> ::ttrpc::Result<super::shim::PidsResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Pids is not supported\".to_string())))\n\n }\n\n async fn pause(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::PauseRequest) -> ::ttrpc::Result<super::empty::Empty> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Pause is not supported\".to_string())))\n\n }\n\n async fn resume(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::shim::ResumeRequest) -> ::ttrpc::Result<super::empty::Empty> {\n", "file_path": "crates/shim-protos/src/shim/shim_ttrpc_async.rs", "rank": 38, "score": 298690.56016446423 }, { "content": "pub fn create_task(service: Arc<std::boxed::Box<dyn Task + Send + Sync>>) -> HashMap <String, Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>> {\n\n let mut methods = HashMap::new();\n\n\n\n methods.insert(\"/containerd.task.v2.Task/State\".to_string(),\n\n std::boxed::Box::new(StateMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Create\".to_string(),\n\n std::boxed::Box::new(CreateMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Start\".to_string(),\n\n std::boxed::Box::new(StartMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Delete\".to_string(),\n\n std::boxed::Box::new(DeleteMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Pids\".to_string(),\n\n std::boxed::Box::new(PidsMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n\n\n\n methods.insert(\"/containerd.task.v2.Task/Pause\".to_string(),\n\n std::boxed::Box::new(PauseMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n", "file_path": "crates/shim-protos/src/shim/shim_ttrpc_async.rs", "rank": 39, "score": 296491.3049576333 }, { "content": "pub fn create_events(service: Arc<std::boxed::Box<dyn Events + Send + Sync>>) -> HashMap <String, Box<dyn ::ttrpc::MethodHandler + Send + Sync>> {\n\n let mut methods = HashMap::new();\n\n\n\n methods.insert(\"/containerd.services.events.ttrpc.v1.Events/Forward\".to_string(),\n\n std::boxed::Box::new(ForwardMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);\n\n\n\n methods\n\n}\n", "file_path": "crates/shim-protos/src/shim/events_ttrpc.rs", "rank": 40, "score": 295548.09558553493 }, { "content": "/// Update process cgroup limits\n\npub fn update_metrics(pid: u32, resources: &LinuxResources) -> Result<()> {\n\n // get container main process cgroup\n\n let path =\n\n get_cgroups_relative_paths_by_pid(pid).map_err(other_error!(e, \"get process cgroup\"))?;\n\n let cgroup = Cgroup::load_with_relative_paths(hierarchies::auto(), Path::new(\".\"), path);\n\n\n\n for sub_system in Cgroup::subsystems(&cgroup) {\n\n match sub_system {\n\n Subsystem::Pid(pid_ctr) => {\n\n // set maximum number of PIDs\n\n if let Some(pids) = resources.pids() {\n\n pid_ctr\n\n .set_pid_max(MaxValue::Value(pids.limit()))\n\n .map_err(other_error!(e, \"set pid max\"))?;\n\n }\n\n }\n\n Subsystem::Mem(mem_ctr) => {\n\n if let Some(memory) = resources.memory() {\n\n // set memory limit in bytes\n\n if let Some(limit) = memory.limit() {\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 41, "score": 294458.43467014335 }, { "content": "/// Parses command line arguments passed to the shim.\n\n/// This func replicates https://github.com/containerd/containerd/blob/master/runtime/v2/shim/shim.go#L110\n\npub fn parse<S: AsRef<OsStr>>(args: &[S]) -> Result<Flags> {\n\n let mut flags = Flags::default();\n\n\n\n let args: Vec<String> = go_flag::parse_args(args, |f| {\n\n f.add_flag(\"debug\", &mut flags.debug);\n\n f.add_flag(\"namespace\", &mut flags.namespace);\n\n f.add_flag(\"id\", &mut flags.id);\n\n f.add_flag(\"socket\", &mut flags.socket);\n\n f.add_flag(\"bundle\", &mut flags.bundle);\n\n f.add_flag(\"address\", &mut flags.address);\n\n f.add_flag(\"publish-binary\", &mut flags.publish_binary);\n\n })\n\n .map_err(|e| Error::InvalidArgument(e.to_string()))?;\n\n\n\n if let Some(action) = args.get(0) {\n\n flags.action = action.into();\n\n }\n\n\n\n if flags.namespace.is_empty() {\n\n return Err(Error::InvalidArgument(String::from(\n", "file_path": "crates/shim/src/args.rs", "rank": 42, "score": 293144.9541974338 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/types/task.rs", "rank": 43, "score": 291641.9741761909 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/events/namespace.rs", "rank": 44, "score": 291384.95578315726 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/events/task.rs", "rank": 45, "score": 290906.622349424 }, { "content": "pub fn create_events(service: Arc<std::boxed::Box<dyn Events + Send + Sync>>) -> HashMap <String, Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>> {\n\n let mut methods = HashMap::new();\n\n\n\n methods.insert(\"/containerd.services.events.ttrpc.v1.Events/Forward\".to_string(),\n\n std::boxed::Box::new(ForwardMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::r#async::MethodHandler + Send + Sync>);\n\n\n\n methods\n\n}\n", "file_path": "crates/shim-protos/src/shim/events_ttrpc_async.rs", "rank": 46, "score": 284692.40125985094 }, { "content": "fn write_process_oom_score(pid: u32, score: i64) -> Result<()> {\n\n fs::write(format!(\"/proc/{}/oom_score_adj\", pid), score.to_string())\n\n .map_err(io_error!(e, \"write oom score\"))\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 47, "score": 278680.73862500367 }, { "content": "/// Resolve a binary path according to the `PATH` environment variable.\n\n///\n\n/// Note, the case that `path` is already an absolute path is implicitly handled by\n\n/// `dir.join(path.as_ref())`. `Path::join(parent_path, path)` directly returns `path` when `path`\n\n/// is an absolute path.\n\npub fn binary_path<P>(path: P) -> Option<PathBuf>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n env::var_os(\"PATH\").and_then(|paths| {\n\n env::split_paths(&paths).find_map(|dir| {\n\n let full_path = dir.join(path.as_ref());\n\n if full_path.is_file() {\n\n Some(full_path)\n\n } else {\n\n None\n\n }\n\n })\n\n })\n\n}\n", "file_path": "crates/runc/src/utils.rs", "rank": 48, "score": 276706.96607874194 }, { "content": "#[async_trait]\n\npub trait Events: Sync {\n\n async fn forward(&self, _ctx: &::ttrpc::r#async::TtrpcContext, _req: super::events::ForwardRequest) -> ::ttrpc::Result<super::empty::Empty> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.services.events.ttrpc.v1.Events/Forward is not supported\".to_string())))\n\n }\n\n}\n\n\n", "file_path": "crates/shim-protos/src/shim/events_ttrpc_async.rs", "rank": 49, "score": 276286.426062879 }, { "content": "pub fn check_kill_error(emsg: String) -> Error {\n\n let emsg = emsg.to_lowercase();\n\n if emsg.contains(\"process already finished\")\n\n || emsg.contains(\"container not running\")\n\n || emsg.contains(\"no such process\")\n\n {\n\n Error::NotFoundError(\"process already finished\".to_string())\n\n } else if emsg.contains(\"does not exist\") {\n\n Error::NotFoundError(\"no such container\".to_string())\n\n } else {\n\n other!(\"unknown error after kill {}\", emsg)\n\n }\n\n}\n\n\n\nconst DEFAULT_RUNC_ROOT: &str = \"/run/containerd/runc\";\n\nconst DEFAULT_COMMAND: &str = \"runc\";\n\n\n", "file_path": "crates/runc-shim/src/common.rs", "rank": 50, "score": 275440.46808658075 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/shim/events.rs", "rank": 51, "score": 269111.65471323807 }, { "content": "/// Set current process as subreaper for child processes.\n\n///\n\n/// A subreaper fulfills the role of `init` for its descendant processes. When a process becomes\n\n/// orphaned (i.e., its immediate parent terminates), then that process will be reparented to the\n\n/// nearest still living ancestor subreaper. Subsequently, calls to `getppid()` in the orphaned\n\n/// process will now return the PID of the subreaper process, and when the orphan terminates,\n\n/// it is the subreaper process that will receive a SIGCHLD signal and will be able to `wait()`\n\n/// on the process to discover its termination status.\n\npub fn set_subreaper() -> Result<()> {\n\n use crate::error::Error;\n\n prctl::set_child_subreaper(true).map_err(other_error!(code, \"linux prctl returned\"))\n\n}\n\n\n", "file_path": "crates/shim/src/reap.rs", "rank": 52, "score": 266564.9793841384 }, { "content": "pub fn convert_to_timestamp(exited_at: Option<OffsetDateTime>) -> Timestamp {\n\n let mut ts = Timestamp::new();\n\n if let Some(ea) = exited_at {\n\n ts.seconds = ea.unix_timestamp();\n\n ts.nanos = ea.nanosecond() as i32;\n\n }\n\n ts\n\n}\n\n\n", "file_path": "crates/shim/src/util.rs", "rank": 53, "score": 262649.6813488902 }, { "content": "#[inline]\n\nfn handle_err(err: impl fmt::Debug) -> ! {\n\n eprintln!(\"{:?}\", err);\n\n process::exit(1);\n\n}\n", "file_path": "crates/logging/src/lib.rs", "rank": 54, "score": 261333.73229293883 }, { "content": "pub fn timestamp() -> Result<Timestamp> {\n\n let now = SystemTime::now().duration_since(UNIX_EPOCH)?;\n\n\n\n let mut ts = Timestamp::default();\n\n ts.set_seconds(now.as_secs() as _);\n\n ts.set_nanos(now.subsec_nanos() as _);\n\n\n\n Ok(ts)\n\n}\n\n\n", "file_path": "crates/shim/src/util.rs", "rank": 55, "score": 261300.13191097937 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/types/empty.rs", "rank": 56, "score": 260534.1657677185 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/types/mount.rs", "rank": 57, "score": 260534.1657677185 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/events/container.rs", "rank": 59, "score": 259798.8139409516 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/events/content.rs", "rank": 60, "score": 259798.8139409516 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/events/snapshot.rs", "rank": 61, "score": 259798.8139409516 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/events/image.rs", "rank": 62, "score": 259798.8139409516 }, { "content": "pub trait AsOption {\n\n fn as_option(&self) -> Option<&Self>;\n\n}\n\n\n\nimpl AsOption for str {\n\n fn as_option(&self) -> Option<&Self> {\n\n if self.is_empty() {\n\n None\n\n } else {\n\n Some(self)\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_timestamp() {\n\n let ts = timestamp().unwrap();\n\n assert!(ts.seconds > 0);\n\n }\n\n}\n", "file_path": "crates/shim/src/util.rs", "rank": 63, "score": 258806.8477650526 }, { "content": "pub trait IntoOption\n\nwhere\n\n Self: Sized,\n\n{\n\n fn none_if<F>(self, callback: F) -> Option<Self>\n\n where\n\n F: Fn(&Self) -> bool,\n\n {\n\n if callback(&self) {\n\n None\n\n } else {\n\n Some(self)\n\n }\n\n }\n\n}\n\n\n\nimpl<T> IntoOption for T {}\n\n\n", "file_path": "crates/shim/src/util.rs", "rank": 64, "score": 258806.8477650526 }, { "content": "fn read_process_oom_score(pid: u32) -> Result<i64> {\n\n let content = fs::read_to_string(format!(\"/proc/{}/oom_score_adj\", pid))\n\n .map_err(io_error!(e, \"read oom score\"))?;\n\n let score = content\n\n .trim()\n\n .parse::<i64>()\n\n .map_err(other_error!(e, \"parse oom score\"))?;\n\n Ok(score)\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/cgroup.rs", "rank": 65, "score": 255864.6334512027 }, { "content": "fn status<E: Debug>(err: E) -> tonic::Status {\n\n let message = format!(\"{:?}\", err);\n\n tonic::Status::internal(message)\n\n}\n", "file_path": "crates/snapshots/src/wrap.rs", "rank": 66, "score": 255616.3507548254 }, { "content": "fn setup_signals_tokio(config: &Config) -> Signals {\n\n if config.no_reaper {\n\n Signals::new(&[SIGTERM, SIGINT, SIGPIPE]).expect(\"new signal failed\")\n\n } else {\n\n Signals::new(&[SIGTERM, SIGINT, SIGPIPE, SIGCHLD]).expect(\"new signal failed\")\n\n }\n\n}\n\n\n\nasync fn handle_signals(signals: Signals) {\n\n let mut signals = signals.fuse();\n\n while let Some(sig) = signals.next().await {\n\n match sig {\n\n SIGTERM | SIGINT => {\n\n debug!(\"received {}\", sig);\n\n return;\n\n }\n\n SIGCHLD => {\n\n let mut status: c_int = 0;\n\n let options: c_int = libc::WNOHANG;\n\n let res_pid = asyncify(move || -> Result<pid_t> {\n", "file_path": "crates/shim/src/asynchronous/mod.rs", "rank": 67, "score": 255577.30553251854 }, { "content": "#[async_trait]\n\npub trait Shim {\n\n /// Type to provide task service for the shim.\n\n type T: Task + Send + Sync;\n\n\n\n /// Create a new instance of async Shim.\n\n ///\n\n /// # Arguments\n\n /// - `runtime_id`: identifier of the container runtime.\n\n /// - `id`: identifier of the shim/container, passed in from Containerd.\n\n /// - `namespace`: namespace of the shim/container, passed in from Containerd.\n\n /// - `config`: for the shim to pass back configuration information\n\n async fn new(runtime_id: &str, id: &str, namespace: &str, config: &mut Config) -> Self;\n\n\n\n /// Start shim will be called by containerd when launching new shim instance.\n\n ///\n\n /// It expected to return TTRPC address containerd daemon can use to communicate with\n\n /// the given shim instance.\n\n /// See https://github.com/containerd/containerd/tree/master/runtime/v2#start\n\n /// this is an asynchronous call\n\n async fn start_shim(&mut self, opts: StartOpts) -> Result<String>;\n", "file_path": "crates/shim/src/asynchronous/mod.rs", "rank": 69, "score": 252124.6868323433 }, { "content": "pub fn receive_socket(stream_fd: RawFd) -> containerd_shim::Result<RawFd> {\n\n let mut buf = [0u8; 4096];\n\n let iovec = [IoVec::from_mut_slice(&mut buf)];\n\n let mut space = cmsg_space!([RawFd; 2]);\n\n let (path, fds) = match recvmsg(stream_fd, &iovec, Some(&mut space), MsgFlags::empty()) {\n\n Ok(msg) => {\n\n let mut iter = msg.cmsgs();\n\n if let Some(ControlMessageOwned::ScmRights(fds)) = iter.next() {\n\n (iovec[0].as_slice(), fds)\n\n } else {\n\n return Err(other!(\"received message is empty\"));\n\n }\n\n }\n\n Err(e) => {\n\n return Err(other!(\"failed to receive message: {}\", e));\n\n }\n\n };\n\n if fds.is_empty() {\n\n return Err(other!(\"received message is empty\"));\n\n }\n", "file_path": "crates/runc-shim/src/common.rs", "rank": 70, "score": 248516.94280686593 }, { "content": "pub trait Event: Message {\n\n fn topic(&self) -> String;\n\n}\n\n\n\nimpl Event for TaskCreate {\n\n fn topic(&self) -> String {\n\n \"/tasks/create\".to_string()\n\n }\n\n}\n\n\n\nimpl Event for TaskStart {\n\n fn topic(&self) -> String {\n\n \"/tasks/start\".to_string()\n\n }\n\n}\n\n\n\nimpl Event for TaskExecAdded {\n\n fn topic(&self) -> String {\n\n \"/tasks/exec-added\".to_string()\n\n }\n", "file_path": "crates/shim/src/event.rs", "rank": 71, "score": 247860.84270800685 }, { "content": "pub trait Task {\n\n fn state(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::StateRequest) -> ::ttrpc::Result<super::shim::StateResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/State is not supported\".to_string())))\n\n }\n\n fn create(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::CreateTaskRequest) -> ::ttrpc::Result<super::shim::CreateTaskResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Create is not supported\".to_string())))\n\n }\n\n fn start(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::StartRequest) -> ::ttrpc::Result<super::shim::StartResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Start is not supported\".to_string())))\n\n }\n\n fn delete(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::DeleteRequest) -> ::ttrpc::Result<super::shim::DeleteResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Delete is not supported\".to_string())))\n\n }\n\n fn pids(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::PidsRequest) -> ::ttrpc::Result<super::shim::PidsResponse> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Pids is not supported\".to_string())))\n\n }\n\n fn pause(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::PauseRequest) -> ::ttrpc::Result<super::empty::Empty> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.task.v2.Task/Pause is not supported\".to_string())))\n\n }\n\n fn resume(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::shim::ResumeRequest) -> ::ttrpc::Result<super::empty::Empty> {\n", "file_path": "crates/shim-protos/src/shim/shim_ttrpc.rs", "rank": 72, "score": 247019.68712399088 }, { "content": "pub fn monitor_subscribe(topic: Topic) -> Result<Subscription> {\n\n let mut monitor = MONITOR.lock().unwrap();\n\n let s = monitor.subscribe(topic)?;\n\n Ok(s)\n\n}\n\n\n", "file_path": "crates/shim/src/synchronous/monitor.rs", "rank": 74, "score": 244740.0760731736 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/shim/shim.rs", "rank": 75, "score": 243408.76346577134 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/shim/oci.rs", "rank": 76, "score": 238359.61060251633 }, { "content": "pub fn convert_to_any(obj: Box<dyn Message>) -> Result<Any> {\n\n let mut data = Vec::new();\n\n obj.write_to_vec(&mut data)?;\n\n\n\n let mut any = Any::new();\n\n any.set_value(data);\n\n any.set_type_url(obj.descriptor().full_name().to_string());\n\n\n\n Ok(any)\n\n}\n\n\n\n/// Returns a temp dir. If the environment variable \"XDG_RUNTIME_DIR\" is set, return its value.\n\n/// Otherwise if `std::env::temp_dir()` failed, return current dir or return the temp dir depended on OS.\n\npub(crate) fn xdg_runtime_dir() -> String {\n\n env::var(\"XDG_RUNTIME_DIR\")\n\n .unwrap_or_else(|_| env::temp_dir().to_str().unwrap_or(\".\").to_string())\n\n}\n\n\n", "file_path": "crates/shim/src/util.rs", "rank": 77, "score": 229991.33631372973 }, { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "crates/shim-protos/src/cgroups/metrics.rs", "rank": 78, "score": 229046.76983022987 }, { "content": "pub trait Args {\n\n type Output;\n\n\n\n fn args(&self) -> Self::Output;\n\n}\n\n\n\n/// Global options builder for the runc binary.\n\n///\n\n/// These options will be passed for all subsequent runc calls.\n\n/// See <https://github.com/opencontainers/runc/blob/main/man/runc.8.md#global-options>\n\n#[derive(Debug, Default)]\n\npub struct GlobalOpts {\n\n /// Override the name of the runc binary. If [`None`], `runc` is used.\n\n command: Option<PathBuf>,\n\n /// Debug logging.\n\n ///\n\n /// If true, debug level logs are emitted.\n\n debug: bool,\n\n /// Path to log file.\n\n log: Option<PathBuf>,\n", "file_path": "crates/runc/src/options.rs", "rank": 79, "score": 228324.28221377364 }, { "content": "#[async_trait]\n\npub trait ProcessFactory<E> {\n\n async fn create(&self, req: &ExecProcessRequest) -> Result<E>;\n\n}\n\n\n\n/// ContainerTemplate is a template struct to implement Container,\n\n/// most of the methods can be delegated to either init process or exec process.\n\n/// that's why we provides a ContainerTemplate struct,\n\n/// library users only need to implements Process for their own.\n\npub struct ContainerTemplate<T, E, P> {\n\n /// container id\n\n pub id: String,\n\n /// container bundle path\n\n pub bundle: String,\n\n /// init process of this container\n\n pub init: T,\n\n /// process factory that create processes when exec\n\n pub process_factory: P,\n\n /// exec processes of this container\n\n pub processes: HashMap<String, E>,\n\n}\n", "file_path": "crates/shim/src/asynchronous/container.rs", "rank": 80, "score": 228084.52788985672 }, { "content": "pub trait Events {\n\n fn forward(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::events::ForwardRequest) -> ::ttrpc::Result<super::empty::Empty> {\n\n Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, \"/containerd.services.events.ttrpc.v1.Events/Forward is not supported\".to_string())))\n\n }\n\n}\n\n\n", "file_path": "crates/shim-protos/src/shim/events_ttrpc.rs", "rank": 81, "score": 222406.47662227383 }, { "content": "type EventSender = Sender<(String, Box<dyn Message>)>;\n\n\n\n/// TaskService is a Task template struct, it is considered a helper struct,\n\n/// which has already implemented `Task` trait, so that users can make it the type `T`\n\n/// parameter of `Service`, and implements their own `ContainerFactory` and `Container`.\n\npub struct TaskService<F, C> {\n\n pub factory: F,\n\n pub containers: Arc<Mutex<HashMap<String, C>>>,\n\n pub namespace: String,\n\n pub exit: Arc<ExitSignal>,\n\n pub tx: EventSender,\n\n}\n\n\n\nimpl<F, C> TaskService<F, C>\n\nwhere\n\n F: Default,\n\n{\n\n pub fn new(ns: &str, exit: Arc<ExitSignal>, tx: EventSender) -> Self {\n\n Self {\n\n factory: Default::default(),\n", "file_path": "crates/shim/src/asynchronous/task.rs", "rank": 82, "score": 213221.27619834215 }, { "content": "type EventSender = Sender<(String, Box<dyn Message>)>;\n\n\n\npub struct ShimTask<F, C> {\n\n pub containers: Arc<Mutex<HashMap<String, C>>>,\n\n factory: F,\n\n namespace: String,\n\n exit: Arc<ExitSignal>,\n\n /// Prevent multiple shutdown\n\n shutdown: Once,\n\n tx: Arc<Mutex<EventSender>>,\n\n}\n\n\n\nimpl<F, C> ShimTask<F, C>\n\nwhere\n\n F: Default,\n\n{\n\n pub fn new(ns: &str, exit: Arc<ExitSignal>, tx: EventSender) -> Self {\n\n Self {\n\n factory: Default::default(),\n\n containers: Arc::new(Mutex::new(Default::default())),\n", "file_path": "crates/runc-shim/src/synchronous/task.rs", "rank": 83, "score": 208766.91331880324 }, { "content": "#[cfg(feature = \"async\")]\n\n#[async_trait]\n\npub trait Spawner: Debug {\n\n async fn execute(&self, cmd: Command) -> Result<(ExitStatus, u32, String, String)>;\n\n}\n\n\n\n/// Async implementation for [Runc].\n\n///\n\n/// Note that you MUST use this client on tokio runtime, as this client internally use [`tokio::process::Command`]\n\n/// and some other utilities.\n\n#[cfg(feature = \"async\")]\n\nimpl Runc {\n\n async fn launch(&self, cmd: Command, combined_output: bool) -> Result<Response> {\n\n debug!(\"Execute command {:?}\", cmd);\n\n let (status, pid, stdout, stderr) = self.spawner.execute(cmd).await?;\n\n if status.success() {\n\n let output = if combined_output {\n\n stdout + stderr.as_str()\n\n } else {\n\n stdout\n\n };\n\n Ok(Response {\n", "file_path": "crates/runc/src/lib.rs", "rank": 84, "score": 207591.275023096 }, { "content": "fn read_std<T>(std: Option<T>) -> String\n\nwhere\n\n T: Read,\n\n{\n\n let mut std = std;\n\n if let Some(mut std) = std.take() {\n\n let mut out = String::new();\n\n std.read_to_string(&mut out).unwrap_or_else(|e| {\n\n error!(\"failed to read stdout {}\", e);\n\n 0\n\n });\n\n return out;\n\n }\n\n \"\".to_string()\n\n}\n\n\n", "file_path": "crates/runc-shim/src/synchronous/runc.rs", "rank": 85, "score": 196536.2631120894 }, { "content": "#[async_trait]\n\npub trait ProcessMonitor {\n\n /// Spawn a process and return its output.\n\n ///\n\n /// In order to capture the output/error, it is necessary for the caller to create new pipes\n\n /// between parent and child.\n\n /// Use [tokio::process::Command::stdout(Stdio::piped())](https://docs.rs/tokio/1.16.1/tokio/process/struct.Command.html#method.stdout)\n\n /// and/or [tokio::process::Command::stderr(Stdio::piped())](https://docs.rs/tokio/1.16.1/tokio/process/struct.Command.html#method.stderr)\n\n /// respectively, when creating the [Command](https://docs.rs/tokio/1.16.1/tokio/process/struct.Command.html#).\n\n async fn start(&self, mut cmd: Command, tx: Sender<Exit>) -> std::io::Result<Output> {\n\n let chi = cmd.spawn()?;\n\n // Safe to expect() because wait() hasn't been called yet, dependence on tokio interanl\n\n // implementation details.\n\n let pid = chi\n\n .id()\n\n .expect(\"failed to take pid of the container process.\");\n\n let out = chi.wait_with_output().await?;\n\n let ts = OffsetDateTime::now_utc();\n\n // On Unix, out.status.code() will return None if the process was terminated by a signal.\n\n let status = out.status.code().unwrap_or(-1);\n\n match tx.send(Exit { ts, pid, status }) {\n", "file_path": "crates/runc/src/monitor.rs", "rank": 86, "score": 194054.1998018132 }, { "content": "fn wait_pid(pid: i32, s: Subscription) -> i32 {\n\n loop {\n\n if let Ok(ExitEvent {\n\n subject: Subject::Pid(epid),\n\n exit_code: code,\n\n }) = s.rx.recv()\n\n {\n\n if pid == epid {\n\n return code;\n\n }\n\n }\n\n }\n\n}\n", "file_path": "crates/runc-shim/src/synchronous/runc.rs", "rank": 87, "score": 188587.37741510605 }, { "content": "#[cfg(target_os = \"linux\")]\n\nstruct Flag {\n\n clear: bool,\n\n flags: MsFlags,\n\n}\n\n\n\n#[cfg(target_os = \"linux\")]\n\nlazy_static! {\n\n static ref MOUNT_FLAGS: HashMap<&'static str, Flag> = {\n\n let mut mf = HashMap::new();\n\n let zero: MsFlags = MsFlags::from_bits(0).unwrap();\n\n mf.insert(\n\n \"async\",\n\n Flag {\n\n clear: true,\n\n flags: MsFlags::MS_SYNCHRONOUS,\n\n },\n\n );\n\n mf.insert(\n\n \"atime\",\n\n Flag {\n", "file_path": "crates/shim/src/mount.rs", "rank": 88, "score": 186191.2359005283 }, { "content": "fn forward(publisher: RemotePublisher, ns: String, rx: Receiver<(String, Box<dyn Message>)>) {\n\n std::thread::spawn(move || {\n\n for (topic, e) in rx.iter() {\n\n publisher\n\n .publish(Context::default(), &topic, &ns, e)\n\n .unwrap_or_else(|e| warn!(\"publish {} to containerd: {}\", topic, e));\n\n }\n\n });\n\n}\n", "file_path": "crates/runc-shim/src/synchronous/service.rs", "rank": 89, "score": 181518.90338473202 }, { "content": "fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {\n\n ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()\n\n}\n\n\n", "file_path": "crates/shim-protos/src/types/task.rs", "rank": 90, "score": 179746.01869214547 }, { "content": "fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {\n\n ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()\n\n}\n\n\n", "file_path": "crates/shim-protos/src/events/namespace.rs", "rank": 91, "score": 179475.43768429314 }, { "content": "fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {\n\n ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()\n\n}\n\n\n", "file_path": "crates/shim-protos/src/events/task.rs", "rank": 92, "score": 178971.8630526828 }, { "content": "/// Returns a temp dir. If the environment variable \"XDG_RUNTIME_DIR\" is set, return its value.\n\n/// Otherwise if `std::env::temp_dir()` failed, return current dir or return the temp dir depended on OS.\n\nfn xdg_runtime_dir() -> String {\n\n env::var(\"XDG_RUNTIME_DIR\")\n\n .unwrap_or_else(|_| abs_string(env::temp_dir()).unwrap_or_else(|_| \".\".to_string()))\n\n}\n\n\n\n/// Write the serialized 'value' to a temp file\n", "file_path": "crates/runc/src/utils.rs", "rank": 93, "score": 176500.54446005024 }, { "content": "fn parse_sockaddr(addr: &str) -> &str {\n\n if let Some(addr) = addr.strip_prefix(\"unix://\") {\n\n return addr;\n\n }\n\n\n\n if let Some(addr) = addr.strip_prefix(\"vsock://\") {\n\n return addr;\n\n }\n\n\n\n addr\n\n}\n\n\n", "file_path": "crates/shim/src/lib.rs", "rank": 94, "score": 175851.68729259016 }, { "content": "#[test]\n\nfn test_delete_task() {\n\n let mut req = DeleteRequest::default();\n\n req.set_id(\"test1\".to_owned());\n\n let mut buf = Vec::with_capacity(req.compute_size() as usize);\n\n let mut s = CodedOutputStream::vec(&mut buf);\n\n req.write_to(&mut s).unwrap();\n\n s.flush().unwrap();\n\n assert_eq!(buf.len(), 7);\n\n\n\n let (ctx, rx) = create_ttrpc_context();\n\n let mut request = Request::new();\n\n request.set_service(\"containerd.task.v2.Task\".to_owned());\n\n request.set_method(\"Delete\".to_owned());\n\n request.set_payload(buf);\n\n request.set_timeout_nano(10000);\n\n request.set_metadata(ttrpc::context::to_pb(ctx.metadata.clone()));\n\n\n\n let server = Arc::new(Box::new(FakeServer::new()) as Box<dyn Task + Send + Sync>);\n\n let task = create_task(server.clone());\n\n let delete = task.get(\"/containerd.task.v2.Task/Delete\").unwrap();\n", "file_path": "crates/shim-protos/tests/ttrpc.rs", "rank": 95, "score": 175416.1818475293 }, { "content": "#[async_trait]\n\npub trait Container {\n\n async fn start(&mut self, exec_id: Option<&str>) -> Result<i32>;\n\n async fn state(&self, exec_id: Option<&str>) -> Result<StateResponse>;\n\n async fn kill(&mut self, exec_id: Option<&str>, signal: u32, all: bool) -> Result<()>;\n\n async fn wait_channel(&mut self, exec_id: Option<&str>) -> Result<Receiver<()>>;\n\n async fn get_exit_info(\n\n &self,\n\n exec_id: Option<&str>,\n\n ) -> Result<(i32, i32, Option<OffsetDateTime>)>;\n\n async fn delete(\n\n &mut self,\n\n exec_id_opt: Option<&str>,\n\n ) -> Result<(i32, i32, Option<OffsetDateTime>)>;\n\n async fn exec(&mut self, req: ExecProcessRequest) -> Result<()>;\n\n async fn resize_pty(&mut self, exec_id: Option<&str>, height: u32, width: u32) -> Result<()>;\n\n async fn pid(&self) -> i32;\n\n async fn id(&self) -> String;\n\n}\n\n\n", "file_path": "crates/shim/src/asynchronous/container.rs", "rank": 96, "score": 170859.9879720722 }, { "content": "#[async_trait]\n\npub trait Process {\n\n async fn start(&mut self) -> crate::Result<()>;\n\n async fn set_exited(&mut self, exit_code: i32);\n\n async fn pid(&self) -> i32;\n\n async fn state(&self) -> crate::Result<StateResponse>;\n\n async fn kill(&mut self, signal: u32, all: bool) -> crate::Result<()>;\n\n async fn delete(&mut self) -> crate::Result<()>;\n\n async fn wait_channel(&mut self) -> crate::Result<Receiver<()>>;\n\n async fn exit_code(&self) -> i32;\n\n async fn exited_at(&self) -> Option<OffsetDateTime>;\n\n async fn resize_pty(&mut self, height: u32, width: u32) -> crate::Result<()>;\n\n}\n\n\n", "file_path": "crates/shim/src/asynchronous/processes.rs", "rank": 97, "score": 170859.9879720722 }, { "content": "/*\n\n Copyright The containerd Authors.\n\n\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n\n you may not use this file except in compliance with the License.\n\n You may obtain a copy of the License at\n\n\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\n\n Unless required by applicable law or agreed to in writing, software\n\n distributed under the License is distributed on an \"AS IS\" BASIS,\n\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n See the License for the specific language governing permissions and\n\n limitations under the License.\n\n*/\n\n\n\n//! Task event topic typically used in shim implementations.\n\n\n\npub const TASK_CREATE_EVENT_TOPIC: &str = \"/tasks/create\";\n\npub const TASK_START_EVENT_TOPIC: &str = \"/tasks/start\";\n", "file_path": "crates/shim-protos/src/topics.rs", "rank": 98, "score": 117.94424216189721 }, { "content": "/*\n\n Copyright The containerd Authors.\n\n\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n\n you may not use this file except in compliance with the License.\n\n You may obtain a copy of the License at\n\n\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\n\n Unless required by applicable law or agreed to in writing, software\n\n distributed under the License is distributed on an \"AS IS\" BASIS,\n\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n See the License for the specific language governing permissions and\n\n limitations under the License.\n\n*/\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Stdio {\n\n pub stdin: String,\n\n pub stdout: String,\n", "file_path": "crates/shim/src/io.rs", "rank": 99, "score": 117.91963531398326 } ]
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 NativeJoystick {\n\n\ttype WithState = NativeJoystick;\n\n\ttype NativeEvent = ::Event;\n\n\ttype Error = Error;\n\n\tfn open(index: u8) -> Result<NativeJoystick, &'static str> {\n\n\t\tunsafe {\n\n\t\t\tlet mut caps: Capabilities = mem::uninitialized();\n\n\t\t\tlet code = XInputGetCapabilities(index as u32, 0, &mut caps);\n\n\t\t\tif code == 0 {\n\n\t\t\t\tOk(NativeJoystick {\n", "file_path": "src/windows.rs", "rank": 0, "score": 74975.75306045722 }, { "content": "/// A lightweight Backend that tracks and polls all the available joysticks.\n\n///\n\n/// Each `Backend` has its own event queue tied to the events of the joysticks.\n\n///\n\n/// ``` rust\n\n/// use reminisce::*;\n\n/// let mut backend = Native::new();\n\n/// let mut dir = 0;\n\n/// let mut left = 30;\n\n/// for event in &mut backend {\n\n/// left -= 1;\n\n/// if(left <= 0) { break }\n\n/// match event {\n\n/// Event::AxisMoved(_, 0, nx) =>\n\n/// dir = -1,\n\n/// Event::AxisMoved(_, 1, ny) =>\n\n/// dir = 1,\n\n/// _ => ()\n\n/// }\n\n/// }\n\n/// ```\n\npub trait Backend: Sized {\n\n /// The kind of joystick this Backend tracks.\n\n type Joystick : Joystick;\n\n\n\n /// Create a new Backend and scan for joysticks.\n\n fn new() -> Self;\n\n\n\n /// Returns the number of joysticks connected.\n\n fn num_joysticks(&self) -> usize {\n\n self.joysticks().len()\n\n }\n\n\n\n /// Return a reference to the joysticks connected.\n\n fn joysticks(&self) -> &[Self::Joystick];\n\n\n\n /// Poll this Backend non-blockingly for events from any joysticks.\n\n fn poll(&mut self) -> Option<Event>;\n\n\n\n /// Iterate through the events that haven't been processed yet\n\n fn iter(&mut self) -> Poller<Self> {\n", "file_path": "src/reminisce.rs", "rank": 1, "score": 47263.3063765849 }, { "content": "/// A joystick or gamepad.\n\npub trait Joystick: Sized {\n\n /// The error that could be thrown while trying to open the joystick\n\n type OpenError: Debug;\n\n\n\n /// Attempts to open a joystick from its index\n\n ///\n\n /// If an error occurs, this will return the textual representation of that error.\n\n ///\n\n /// ``` rust\n\n /// use reminisce::{Backend, Joystick, Native};\n\n /// if let Ok(joystick) = <Native as Backend>::Joystick::open(0) {\n\n /// println!(\"{}\", joystick.id())\n\n /// } else {\n\n /// println!(\"No joystick plugged in\")\n\n /// }\n\n /// ```\n\n fn open(index: JoystickIndex) -> Result<Self, Self::OpenError>;\n\n\n\n /// Check if the joystick is still connected.\n\n fn connected(&self) -> bool;\n", "file_path": "src/reminisce.rs", "rank": 2, "score": 47164.786651146875 }, { "content": "fn main() {\n\n\tlet mut backend = Native::new();\n\n\tfor js in backend.joysticks() {\n\n\t\tprintln!(\"Joystick #{}: {}\", js.index(), js.id());\n\n\t\tprintln!(\"\\tAxes: {}\", js.num_axes());\n\n\t\tprintln!(\"\\tButtons: {}\", js.num_buttons());\n\n\t}\n\n\tloop {\n\n\t\tfor event in backend.poll() {\n\n\t\t\tprintln!(\"{:?}\", event);\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "examples/debug.rs", "rank": 3, "score": 29839.092953670923 }, { "content": "#[cfg(not(windows))]\n\nfn main() {\n\n}\n", "file_path": "src/build.rs", "rank": 4, "score": 29839.092953670923 }, { "content": "#[repr(C)]\n\nstruct Battery {\n\n\t_type: BatteryType,\n\n\tlevel: BatteryLevel\n\n}\n\n\n", "file_path": "src/windows.rs", "rank": 5, "score": 29591.4114222477 }, { "content": "#[repr(C)]\n\nstruct State {\n\n\tpacket: i32,\n\n\tgamepad: Gamepad\n\n}\n\n\n", "file_path": "src/windows.rs", "rank": 6, "score": 29591.4114222477 }, { "content": "#[repr(C)]\n\n#[derive(Copy)]\n\nstruct Gamepad {\n\n\tbuttons: Buttons,\n\n\tleft_trigger: u8,\n\n\tright_trigger: u8,\n\n\tthumb_lx: i16,\n\n\tthumb_ly: i16,\n\n\tthumb_rx: i16,\n\n\tthumb_ry: i16\n\n}\n", "file_path": "src/windows.rs", "rank": 7, "score": 29591.4114222477 }, { "content": "#[repr(C)]\n\nstruct Vibration {\n\n\tleft_motor_speed: i32,\n\n\tright_motor_speed: i32\n\n}\n\n\n", "file_path": "src/windows.rs", "rank": 8, "score": 29591.4114222477 }, { "content": "#[repr(C)]\n\nstruct Capabilities {\n\n\t_type: u8,\n\n\tsub_type: u8,\n\n\tflags: u32,\n\n\tgamepad: Gamepad,\n\n\tvibration: Vibration\n\n}\n\n\n\nbitflags!(\n\n\tflags Buttons: u32 {\n\n\t\tconst DPAD_UP = 0x0001,\n\n\t\tconst DPAD_DOWN = 0x0002,\n\n\t\tconst DPAD_LEFT = 0x0004,\n\n\t\tconst DPAD_RIGHT = 0x0008,\n\n\t\tconst START = 0x0010,\n\n\t\tconst BACK = 0x0020,\n\n\t\tconst LEFT_THUMB = 0x0040,\n\n\t\tconst RIGHT_THUMB = 0x0080,\n\n\t\tconst LEFT_SHOULDER = 0x0100,\n\n\t\tconst RIGHT_SHOULDER = 0x0200,\n\n\t\tconst A = 0x1000,\n\n\t\tconst B = 0x2000,\n\n\t\tconst X = 0x4000,\n\n\t\tconst Y = 0x8000,\n\n\t}\n\n);\n", "file_path": "src/windows.rs", "rank": 9, "score": 29591.4114222477 }, { "content": "#[repr(u8)]\n\nenum BatteryType {\n\n\tDisconnected,\n\n\tWired,\n\n\tAlkaline,\n\n\tNimh,\n\n\tUnknown = 0xFF\n\n}\n\n\n", "file_path": "src/windows.rs", "rank": 10, "score": 16821.74949907498 }, { "content": "use sdl2::joystick::*;\n\nuse sdl2::{init, event, Sdl, JoystickSubsystem, ErrorMessage};\n\n\n\nuse std::borrow::Cow;\n\nuse std::mem;\n\n\n\nuse {Backend, Event};\n\n\n\npub struct Native {\n\n sdl: Sdl,\n\n system: JoystickSubsystem,\n\n joysticks: Vec<NativeJoystick>\n\n}\n\nimpl Backend for Native {\n\n type Joystick = NativeJoystick;\n\n fn new() -> Self {\n\n let sdl = init().unwrap();\n\n let system = sdl.joystick().unwrap();\n\n Native {\n\n sdl: sdl,\n", "file_path": "src/sdl.rs", "rank": 14, "score": 16.75308265672031 }, { "content": "//! Reminisce is a lightweight library intended to be used for detecting and\n\n//! reading from joysticks at a low level across many different operating\n\n//! systems.\n\n//!\n\n//! Scanning for joysticks\n\n//! ----------------------\n\n//! To scan for joysticks, a `Backend` must be created.\n\n//!\n\n//! Scanning for events\n\n//! -------------------\n\n//! To scan events, a `Backend` must be created and polled.\n\n//!\n\n//! ``` rust\n\n//! use reminisce::{Backend, Native};\n\n//! let mut backend = Native::new();\n\n//! for event in backend.iter() {\n\n//! println!(\"{:?}\", event);\n\n//! }\n\n//! ```\n\nextern crate libc;\n", "file_path": "src/reminisce.rs", "rank": 15, "score": 16.475796920998736 }, { "content": " Event::ButtonPressed(i, b) if i == index => {\n\n self.buttons |= (i as i32) << b;\n\n },\n\n Event::ButtonReleased(i, b) if i == index => {\n\n self.buttons &= !((i as i32) << b);\n\n },\n\n Event::AxisMoved(i, a, v) if i == index => {\n\n self.axes[a as usize] = v;\n\n },\n\n Event::HatMoved(i, h, v) if i == index => {\n\n self.hats[h as usize] = v;\n\n },\n\n _ => ()\n\n }\n\n }\n\n}\n\nimpl<J> Joystick for StatefulJoystick<J> where J: Joystick {\n\n type OpenError = J::OpenError;\n\n fn open(index: JoystickIndex) -> Result<Self, Self::OpenError> {\n\n let joystick = try!(J::open(index));\n", "file_path": "src/reminisce.rs", "rank": 17, "score": 14.059148248003265 }, { "content": "}\n\n\n\n/// A lightweight Backend that tracks and polls all the available joysticks.\n\n///\n\n/// Each `Backend` has its own event queue tied to the events of the joysticks.\n\n///\n\n/// ``` rust\n\n/// use reminisce::*;\n\n/// let mut backend = Native::new();\n\n/// let mut dir = 0;\n\n/// let mut left = 30;\n\n/// for event in &mut backend {\n\n/// left -= 1;\n\n/// if(left <= 0) { break }\n\n/// match event {\n\n/// Event::AxisMoved(_, 0, nx) =>\n\n/// dir = -1,\n\n/// Event::AxisMoved(_, 1, ny) =>\n\n/// dir = 1,\n\n/// _ => ()\n\n/// }\n\n/// }\n\n/// ```\n", "file_path": "src/reminisce.rs", "rank": 18, "score": 14.026881731213297 }, { "content": " event::Event::JoyButtonDown { which, button_idx, .. } =>\n\n Some(Event::ButtonPressed(which as ::JoystickIndex, button_idx)),\n\n event::Event::JoyButtonUp { which, button_idx, .. } =>\n\n Some(Event::ButtonReleased(which as ::JoystickIndex, button_idx)),\n\n event::Event::JoyAxisMotion { which, axis_idx, value , .. } =>\n\n Some(Event::AxisMoved(which as ::JoystickIndex, axis_idx, value as f32 / ::MAX_AXIS_VALUE as f32)),\n\n event::Event::JoyHatMotion { which, hat_idx, state, .. } =>\n\n Some(Event::HatMoved(which as ::JoystickIndex, hat_idx, unsafe { mem::transmute(state) })),\n\n _ => None,\n\n }).next()\n\n }\n\n}\n\n\n\n\n\n/// A native joystick using SDL\n\npub type NativeJoystick = Joystick;\n\n\n\nimpl ::Joystick for NativeJoystick {\n\n type OpenError = ErrorMessage;\n\n fn open(index: u8) -> Result<NativeJoystick, ErrorMessage> {\n", "file_path": "src/sdl.rs", "rank": 19, "score": 13.682613867798565 }, { "content": " system: system,\n\n joysticks: Vec::new()\n\n }\n\n }\n\n fn num_joysticks(&self) -> usize {\n\n self.system.num_joysticks().unwrap_or(0) as usize\n\n }\n\n fn joysticks(&self) -> &[NativeJoystick] {\n\n &self.joysticks\n\n }\n\n fn poll(&mut self) -> Option<Event> {\n\n self.sdl.event_pump().unwrap().poll_iter().filter_map(|e| match e {\n\n event::Event::JoyDeviceAdded { which , ..} => {\n\n self.joysticks.push(self.system.open(which as u32).unwrap());\n\n Some(Event::Connected(which as ::JoystickIndex))\n\n },\n\n event::Event::JoyDeviceRemoved { which, .. } => {\n\n self.joysticks.remove(which as usize);\n\n Some(Event::Disconnected(which as ::JoystickIndex))\n\n },\n", "file_path": "src/sdl.rs", "rank": 21, "score": 12.810482167667157 }, { "content": "\t\t\t\t\tindex: index,\n\n\t\t\t\t\tlast: caps.gamepad,\n\n\t\t\t\t\tlast_packet: 0,\n\n\t\t\t\t\tevents: VecDeque::with_capacity(10)\n\n\t\t\t\t})\n\n\t\t\t} else {\n\n\t\t\t\tErr(Error::from_os_error(code))\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfn poll_native(&mut self) -> Option<::Event> {\n\n\t\tuse ::StatefulJoystick;\n\n\t\tself.update();\n\n\t\tself.events.pop_back()\n\n\t}\n\n\tfn connected(&self) -> bool {\n\n\t\ttrue\n\n\t}\n\n\tfn battery(&self) -> Option<f32> {\n\n\t\tunsafe {\n", "file_path": "src/windows.rs", "rank": 25, "score": 11.80392291587805 }, { "content": " }\n\n fn num_buttons(&self) -> Button {\n\n self.joystick.num_buttons()\n\n }\n\n fn num_hats(&self) -> Hat {\n\n self.joystick.num_hats()\n\n }\n\n fn battery(&self) -> Option<f32> {\n\n self.joystick.battery()\n\n }\n\n}\n\n\n\n/// An iterator over a Backend's event queue.\n\npub struct Poller<'a, J> where J:Backend+'a {\n\n backend: &'a mut J\n\n}\n\n\n\nimpl<'a, C> Iterator for Poller<'a, C> where C:Backend {\n\n type Item = Event;\n\n /// This calls the `Backend.poll()` method to poll for the next event\n\n fn next(&mut self) -> Option<Event> {\n\n self.backend.poll()\n\n }\n\n}\n", "file_path": "src/reminisce.rs", "rank": 26, "score": 11.548395447164083 }, { "content": "#[cfg(all(target_os = \"windows\", not(feature = \"sdl\")))]\n\npub use windows as native;\n\n\n\n#[cfg(feature = \"sdl\")]\n\npub mod sdl;\n\n\n\n#[cfg(feature = \"sdl\")]\n\npub use sdl as native;\n\n\n\n/// The native joystick backend exposed as a `Backend`.\n\npub use native::Native;\n\n\n\n\n\n/// The maximum axis value\n\nconst MAX_AXIS_VALUE:i16 = 32767;\n\n\n\nuse std::borrow::Cow;\n\nuse std::fmt::Debug;\n\n\n\n/// A direction on a joystick.\n", "file_path": "src/reminisce.rs", "rank": 27, "score": 11.466978475669622 }, { "content": " /// Get the position of the axis.\n\n pub fn axis(&self, axis: Axis) -> Option<f32> {\n\n self.axes.get(axis as usize).cloned()\n\n }\n\n /// Get the position of the hat.\n\n pub fn hat(&self, hat: Hat) -> Option<HatPos> {\n\n self.hats.get(hat as usize).cloned()\n\n }\n\n /// Check if the button given is being pressed.\n\n pub fn button(&self, button: Button) -> Option<bool> {\n\n if button < self.joystick.num_buttons() {\n\n Some(self.buttons & (1 << button) > 0)\n\n } else {\n\n None\n\n }\n\n }\n\n /// Update this joystick's state with the event given.\n\n pub fn process(&mut self, event: Event) {\n\n let index = self.joystick.index();\n\n match event {\n", "file_path": "src/reminisce.rs", "rank": 29, "score": 11.018713283269303 }, { "content": " Poller { backend: self }\n\n }\n\n}\n\n\n\nimpl<'a> IntoIterator for &'a mut Native {\n\n type Item = Event;\n\n type IntoIter = Poller<'a, Native>;\n\n fn into_iter(self) -> Poller<'a, Native> {\n\n self.iter()\n\n }\n\n}\n\n\n", "file_path": "src/reminisce.rs", "rank": 30, "score": 11.018474495531652 }, { "content": "#[cfg(target_os = \"linux\")]\n\nextern crate inotify;\n\n#[cfg(target_os = \"windows\")]\n\n#[macro_use] extern crate rustc_bitflags;\n\n\n\n#[cfg(feature = \"sdl\")]\n\nextern crate sdl2;\n\n\n\n#[cfg(target_os = \"linux\")]\n\nextern crate glob;\n\n\n\n#[cfg(all(target_os = \"linux\", not(feature = \"sdl\")))]\n\npub mod linux;\n\n\n\n#[cfg(all(target_os = \"linux\", not(feature = \"sdl\")))]\n\npub use linux as native;\n\n\n\n#[cfg(all(target_os = \"windows\", not(feature = \"sdl\")))]\n\npub mod windows;\n\n\n", "file_path": "src/reminisce.rs", "rank": 32, "score": 8.939355864923984 }, { "content": "pub type JoystickIndex = u8;\n\n#[derive(Copy, Clone, Debug, PartialEq)]\n\n/// An event emitted by a joystick\n\npub enum Event {\n\n /// Fired when a joystick is connected with its index.\n\n Connected(JoystickIndex),\n\n /// Fired when a joystick is disconnected with its index.\n\n Disconnected(JoystickIndex),\n\n /// Fired when a button is pressed with the joystick index and the\n\n /// button's index.\n\n ButtonPressed(JoystickIndex, Button),\n\n /// Fired when a button is released with the joystick index and the\n\n /// button's index.\n\n ButtonReleased(JoystickIndex, Button),\n\n /// Fired when a axis is moved with the joystick index, axis index\n\n /// and its value, which is between `-1` and `1`\n\n AxisMoved(JoystickIndex, Axis, f32),\n\n /// Fired when a hat is moved with the joystick index and the hat's\n\n /// index and position.\n\n HatMoved(JoystickIndex, Hat, HatPos)\n", "file_path": "src/reminisce.rs", "rank": 33, "score": 8.468577633601203 }, { "content": " /// Get the number of hats this joystick has\n\n fn num_hats(&self) -> Hat;\n\n\n\n /// Get the battery level of this joystick\n\n ///\n\n /// Returns none if the joystick is wired or this operation is not supported\n\n /// by the backend\n\n fn battery(&self) -> Option<f32>;\n\n}\n\n\n\n/// A joystick that tracks its state.\n\n///\n\n/// You must call `process` before you query anything.\n\npub struct StatefulJoystick<J> where J: Joystick {\n\n joystick: J,\n\n buttons: i32,\n\n axes: Vec<f32>,\n\n hats: Vec<HatPos>\n\n}\n\nimpl<J> StatefulJoystick<J> where J: Joystick {\n", "file_path": "src/reminisce.rs", "rank": 35, "score": 7.7108266611130745 }, { "content": "use std::borrow::Cow;\n\nuse std::collections::VecDeque;\n\nuse std::error::Error;\n\nuse std::mem;\n\n// I tried\n\n// It's a bit hard to write this without a Windows pc on hand...\n\n// But this should work on Windows Vista, 7, and 8\n\n#[link(name = \"XInput9_1_0\")]\n\nextern \"stdcall\" {\n\n\tfn XInputGetCapabilities(index: u32, flags: u32, capabilities: *mut Capabilities) -> i32;\n\n\tfn XInputGetState(index: u32, state: *mut State) -> i32;\n\n\tfn XInputGetBatteryInformation(index: u32, ty: u8, information: *mut Battery) -> i32;\n\n\n\n}\n\n\n\n#[repr(u8)]\n", "file_path": "src/windows.rs", "rank": 36, "score": 7.267751623673818 }, { "content": "pub type Axis = u8;\n\n\n\n/// A button on a joystick.\n\npub type Button = u8;\n\n\n\n/// A hat on a joystick.\n\npub type Hat = u8;\n\n\n\n/// A hat position on a joystick.\n\n#[derive(Debug, PartialEq, Eq, Copy, Clone)]\n\npub enum HatPos {\n\n Centered,\n\n Up,\n\n Right,\n\n Down,\n\n Left\n\n}\n\n\n\n/// A joystick index.\n\n\n", "file_path": "src/reminisce.rs", "rank": 37, "score": 6.707409383498751 }, { "content": "\t\t\t}\n\n\t\t}\n\n\t);\n\n\t(axis $this:expr, $now:expr, $last:expr, $field:ident, $id:expr) => (\n\n\t\tif $now.$field != $last.$field {\n\n\t\t\t$this.events.push_back(::Event::AxisMoved($id, $now.$field))\n\n\t\t}\n\n\t);\n\n\t(axes $this:expr, $now:expr, $last:expr, $($field:ident => $id:expr),+) => ({\n\n\t\t$(event!(axis $this, $now, $last, $field, $id);)+\n\n\t});\n\n\t(buttons $this:expr, $now:expr, $last:expr, $($btn:ident => $id:expr),+) => ({\n\n\t\t$(event!(button $this, $now, $last, $btn, $id);)+\n\n\t});\n\n}\n\nimpl ::StatefulJoystick for NativeJoystick {\n\n\tfn axis(&self, index: ::Axis) -> Option<i16> {\n\n\t\tmatch index {\n\n\t\t\t::Axis::LeftX => Some(self.last.thumb_lx),\n\n\t\t\t::Axis::LeftY => Some(self.last.thumb_ly),\n", "file_path": "src/windows.rs", "rank": 38, "score": 6.703803326677255 }, { "content": "# Reminisce\n\n[![Build Status](https://travis-ci.org/TomBebbington/reminisce.svg?branch=master)](https://travis-ci.org/TomBebbington/reminisce)\n\n[![Cargo Version](http://meritbadge.herokuapp.com/reminisce)](https://crates.io/crates/reminisce)\n\n[![Gitter Chat](https://badges.gitter.im/TomBebbington/reminisce.png)](https://gitter.im/TomBebbington/reminisce)\n\n\n\n~~rusted joy, geddit?~~\n\n\n\nReminisce is a primarily event-based Rust library for detecting gamepads / joysticks\n\nand reading input from them non-blockingly, without any external C dependencies.\n\nIt does this by using the native platform's raw Joystick API.\n\n\n\nThis is intended for use with Glutin, since it doesn't implement a Joystick API.\n\n\n\n## Documentation\n\nDocumentation is available [here](https://tombebbington.github.io/TomBebbington).\n\n\n\n## Supported platforms\n\n+ Linux (using the Joystick API or using SDL)\n\n+ Windows Vista or higher (XInput should work but for the moment just SDL is supported)\n", "file_path": "README.md", "rank": 39, "score": 6.691927319022275 }, { "content": "\t\t\tlet mut battery = mem::uninitialized();\n\n\t\t\tXInputGetBatteryInformation(self.index as u32, 0, &mut battery);\n\n\t\t\tmatch battery._type {\n\n\t\t\t\tBatteryType::Wired | BatteryType::Disconnected =>\n\n\t\t\t\t\tNone,\n\n\t\t\t\t_ =>\n\n\t\t\t\t\tSome(match battery.level {\n\n\t\t\t\t\t\tBatteryLevel::Empty => 0.0,\n\n\t\t\t\t\t\tBatteryLevel::Low => 0.25,\n\n\t\t\t\t\t\tBatteryLevel::Medium => 0.5,\n\n\t\t\t\t\t\tBatteryLevel::High => 1.0\n\n\t\t\t\t\t})\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tfn id(&self) -> Cow<str> {\n\n\t\t\"XInput Device\".into()\n\n\t}\n\n\tfn index(&self) -> u8 {\n\n\t\tself.index\n", "file_path": "src/windows.rs", "rank": 40, "score": 6.548856838713189 }, { "content": "\t}\n\n\tfn update(&mut self) {\n\n\t\tlet state = unsafe {\n\n\t\t\tlet mut state: State = mem::uninitialized();\n\n\t\t\tXInputGetState(self.index as u32, &mut state);\n\n\t\t\tstate\n\n\t\t};\n\n\t\tlet now = state.gamepad;\n\n\t\tif state.packet != self.last_packet {\n\n\t\t\tlet last = self.last;\n\n\t\t\tevent!{axes self, now, last,\n\n\t\t\t\tthumb_lx => ::Axis::LeftX,\n\n\t\t\t\tthumb_ly => ::Axis::LeftY,\n\n\t\t\t\tthumb_rx => ::Axis::RightX,\n\n\t\t\t\tthumb_ry => ::Axis::RightY\n\n\t\t\t}\n\n\t\t\tevent!{buttons self, now, last,\n\n\t\t\t\tA => ::Button::A,\n\n\t\t\t\tB => ::Button::B,\n\n\t\t\t\tX => ::Button::X,\n", "file_path": "src/windows.rs", "rank": 41, "score": 5.932139544230564 }, { "content": "extern crate reminisce;\n\nuse reminisce::*;\n", "file_path": "examples/debug.rs", "rank": 42, "score": 5.22950874184936 }, { "content": " let axes = (0..joystick.num_axes()).map(|_| 0f32).collect();\n\n let hats = (0..joystick.num_hats()).map(|_| HatPos::Centered).collect();\n\n Ok(StatefulJoystick {\n\n joystick: joystick,\n\n buttons: 0,\n\n hats: hats,\n\n axes: axes\n\n })\n\n }\n\n fn connected(&self) -> bool {\n\n self.joystick.connected()\n\n }\n\n fn id(&self) -> Cow<str> {\n\n self.joystick.id()\n\n }\n\n fn index(&self) -> JoystickIndex {\n\n self.joystick.index()\n\n }\n\n fn num_axes(&self) -> Axis {\n\n self.joystick.num_axes()\n", "file_path": "src/reminisce.rs", "rank": 43, "score": 4.8139364169471754 }, { "content": "\n\n /// Get the identifier of this joystick.\n\n ///\n\n /// This is copy-on-write because it can be a borrowed or owned String,\n\n /// depending on the implementation.\n\n fn id(&self) -> Cow<str>;\n\n\n\n /// Get the index of this joystick.\n\n fn index(&self) -> JoystickIndex;\n\n\n\n /// Get the number of axes this joystick has\n\n ///\n\n /// This is capped at 6 axes for now.\n\n fn num_axes(&self) -> Axis;\n\n\n\n /// Get the number of buttons this joystick has\n\n ///\n\n /// This is capped at 16 buttons currently.\n\n fn num_buttons(&self) -> Button;\n\n\n", "file_path": "src/reminisce.rs", "rank": 44, "score": 4.630047910859133 }, { "content": "\t}\n\n\tfn num_buttons(&self) -> u8 {\n\n\t\t4\n\n\t}\n\n\tfn num_axes(&self) -> u8 {\n\n\t\t4\n\n\t}\n\n\tfn with_state(self) -> NativeJoystick {\n\n\t\tself\n\n\t}\n\n}\n\nmacro_rules! event{\n\n\t(button $this:expr, $now:expr, $last:expr, $btn:expr, $id:expr) => (\n\n\t\t{\n\n\t\t\tlet now_btn = $now.buttons.contains($btn);\n\n\t\t\tlet last_btn = $last.buttons.contains($btn);\n\n\t\t\tif now_btn && !last_btn {\n\n\t\t\t\t$this.events.push_back(::Event::ButtonPressed($id))\n\n\t\t\t} else if !now_btn && last_btn {\n\n\t\t\t\t$this.events.push_back(::Event::ButtonReleased($id))\n", "file_path": "src/windows.rs", "rank": 45, "score": 4.605409142888887 }, { "content": " init().unwrap().joystick().unwrap().open(index as u32)\n\n }\n\n fn connected(&self) -> bool {\n\n self.attached()\n\n }\n\n fn index(&self) -> u8 {\n\n self.instance_id() as u8\n\n }\n\n fn id(&self) -> Cow<str> {\n\n self.name().into()\n\n }\n\n fn num_buttons(&self) -> u8 {\n\n self.num_buttons() as u8\n\n }\n\n fn num_hats(&self) -> u8 {\n\n self.num_hats() as u8\n\n }\n\n fn num_axes(&self) -> u8 {\n\n self.num_axes() as u8\n\n }\n\n fn battery(&self) -> Option<f32> {\n\n None\n\n }\n\n}", "file_path": "src/sdl.rs", "rank": 46, "score": 3.122270027687801 }, { "content": "\t\t\t::Axis::RightX => Some(self.last.thumb_rx),\n\n\t\t\t::Axis::RightY => Some(self.last.thumb_ry),\n\n\t\t\t_ => None\n\n\t\t}\n\n\t}\n\n\tfn button(&self, index: ::Button) -> Option<bool> {\n\n\t\tlet bits = match index {\n\n\t\t\t::Button::A => Some(A),\n\n\t\t\t::Button::B => Some(B),\n\n\t\t\t::Button::X => Some(X),\n\n\t\t\t::Button::Y => Some(Y),\n\n\t\t\t::Button::LeftShoulder => Some(LEFT_SHOULDER),\n\n\t\t\t::Button::RightShoulder => Some(RIGHT_SHOULDER),\n\n\t\t\t::Button::Select => Some(BACK),\n\n\t\t\t::Button::Start => Some(START),\n\n\t\t\t::Button::LeftStick => Some(LEFT_THUMB),\n\n\t\t\t::Button::RightStick => Some(RIGHT_THUMB),\n\n\t\t\t_ => None\n\n\t\t};\n\n\t\tbits.map(|v| self.last.buttons.contains(v))\n", "file_path": "src/windows.rs", "rank": 47, "score": 1.612902777725501 } ]
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 {\n\n if !activity_map.neurons.is_empty() {\n\n objects.push(Object {\n\n name: \"neurons\".to_owned(),\n\n vertices: activity_map\n\n .neurons\n\n .iter()\n\n .map(|p| Vertex {\n\n x: p.x,\n\n y: p.y,\n\n z: p.z,\n\n })\n\n .collect(),\n\n tex_vertices: if config.color_storage == ColorStorage::TexVertices {\n\n let Color(r, g, b) = neurons;\n\n repeat(TVertex {\n\n u: Scalar::from(*r) / 255.0,\n", "file_path": "psyche-graphics/src/obj.rs", "rank": 0, "score": 194485.63090130128 }, { "content": "#[inline]\n\npub fn config_to_bytes(config: &Config) -> BinResult<Vec<u8>> {\n\n bincode::serialize(config)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 1, "score": 191717.02478948777 }, { "content": "#[inline]\n\npub fn brain_to_bytes(brain: &Brain) -> BinResult<Vec<u8>> {\n\n bincode::serialize(brain)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 2, "score": 190138.51765470044 }, { "content": "#[inline]\n\npub fn config_to_json(config: &Config, pretty: bool) -> JsonResult<String> {\n\n if pretty {\n\n serde_json::to_string_pretty(config)\n\n } else {\n\n serde_json::to_string(config)\n\n }\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 3, "score": 185297.2757801946 }, { "content": "#[inline]\n\npub fn brain_to_json(brain: &Brain, pretty: bool) -> JsonResult<String> {\n\n if pretty {\n\n serde_json::to_string_pretty(brain)\n\n } else {\n\n serde_json::to_string(brain)\n\n }\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 4, "score": 183740.9912270882 }, { "content": "fn connection_into_line(pair: &(Position, Position, Scalar), rot: &Quaternion<Scalar>) -> [f64; 4] {\n\n let p0 = Point3::new(pair.0.x, pair.0.y, pair.0.z);\n\n let p1 = Point3::new(pair.1.x, pair.1.y, pair.1.z);\n\n let p0 = rot.rotate_point(p0);\n\n let p1 = rot.rotate_point(p1);\n\n [p0.x, p0.y, p1.x, p1.y]\n\n}\n\n\n", "file_path": "demos/src/brain-activity/main.rs", "rank": 5, "score": 180376.4291353324 }, { "content": "#[derive(Debug, Copy, Clone, Default)]\n\nstruct GridCell(pub Scalar, pub Scalar);\n\n\n\nimpl Add for GridCell {\n\n type Output = Self;\n\n\n\n fn add(self, other: Self) -> Self {\n\n GridCell(self.0 + other.0, self.1 + other.1)\n\n }\n\n}\n\n\n\nimpl AddAssign for GridCell {\n\n fn add_assign(&mut self, other: Self) {\n\n self.0 += other.0;\n\n self.1 += other.1;\n\n }\n\n}\n\n\n\nimpl Div<Scalar> for GridCell {\n\n type Output = Self;\n\n\n", "file_path": "demos/src/spore/managers/physics_manager/mod.rs", "rank": 6, "score": 172059.10812222402 }, { "content": "fn merge_scalar(a: Scalar, b: Scalar) -> Scalar {\n\n (a + b) * 0.5\n\n}\n", "file_path": "psyche-core/src/config.rs", "rank": 7, "score": 171256.77965787225 }, { "content": "fn make_default_brain_builder(config: Config) -> BrainBuilder {\n\n BrainBuilder::new()\n\n .config(config)\n\n .neurons(600)\n\n .connections(1000)\n\n .min_neurogenesis_range(5.0)\n\n .max_neurogenesis_range(15.0)\n\n .radius(50.0)\n\n .sensors(50)\n\n .effectors(25)\n\n}\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 8, "score": 171092.78624594456 }, { "content": "fn point(point: Position, rot: &Quaternion<Scalar>) -> (Scalar, Scalar) {\n\n let p = Point3::new(point.x, point.y, point.z);\n\n let p = rot.rotate_point(p);\n\n (p.x, p.y)\n\n}\n\n\n", "file_path": "demos/src/brain-activity/main.rs", "rank": 9, "score": 162771.44609890488 }, { "content": "#[inline]\n\npub fn angle(value: Scalar) -> Angle {\n\n Rad::<_>(value)\n\n}\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub struct Renderable {\n\n id: RenderableID,\n\n pub depth: Scalar,\n\n pub transform: Transform,\n\n pub graphics: Graphics,\n\n}\n\n\n\nimpl Named<Self> for Renderable {\n\n #[inline]\n\n fn id(&self) -> RenderableID {\n\n self.id\n\n }\n\n}\n\n\n\nimpl Renderable {\n", "file_path": "demos/src/spore/managers/renderables_manager/renderable.rs", "rank": 10, "score": 161016.11397679604 }, { "content": "#[inline]\n\npub fn brain_builder_to_bytes(brain_builder: &BrainBuilder) -> BinResult<Vec<u8>> {\n\n bincode::serialize(brain_builder)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 11, "score": 157837.14815738727 }, { "content": "/// generates OBJ string from activity map.\n\n/// NOTE: Colors are stored either in vertices normals or texture vertices.\n\npub fn generate_string(activity_map: &BrainActivityMap, config: &Config) -> Result<String> {\n\n match String::from_utf8(generate(activity_map, config)?) {\n\n Ok(s) => Ok(s),\n\n Err(e) => Err(utf8_into_error(e)),\n\n }\n\n}\n\n\n", "file_path": "psyche-graphics/src/obj.rs", "rank": 12, "score": 157073.23024763135 }, { "content": "#[inline]\n\npub fn config_to_yaml(config: &Config) -> YamlResult<String> {\n\n serde_yaml::to_string(config)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 13, "score": 153142.4621784079 }, { "content": "#[inline]\n\npub fn brain_builder_to_json(brain_builder: &BrainBuilder, pretty: bool) -> JsonResult<String> {\n\n if pretty {\n\n serde_json::to_string_pretty(brain_builder)\n\n } else {\n\n serde_json::to_string(brain_builder)\n\n }\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 14, "score": 152894.60708819405 }, { "content": "#[inline]\n\npub fn brain_to_yaml(brain: &Brain) -> YamlResult<String> {\n\n serde_yaml::to_string(brain)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 15, "score": 151541.23218161028 }, { "content": "#[inline]\n\npub fn brain_activity_map_to_bytes(bam: &BrainActivityMap) -> BinResult<Vec<u8>> {\n\n bincode::serialize(bam)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 16, "score": 149461.69298443006 }, { "content": "#[inline]\n\npub fn brain_activity_map_to_json(bam: &BrainActivityMap, pretty: bool) -> JsonResult<String> {\n\n if pretty {\n\n serde_json::to_string_pretty(bam)\n\n } else {\n\n serde_json::to_string(bam)\n\n }\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 17, "score": 144585.10202496484 }, { "content": "#[inline]\n\npub fn config_from_json(json: &str) -> JsonResult<Config> {\n\n serde_json::from_str(json)\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 18, "score": 140030.26714572439 }, { "content": "#[inline]\n\npub fn config_from_bytes(bytes: &[u8]) -> BinResult<Config> {\n\n bincode::deserialize(bytes)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 19, "score": 140030.26714572439 }, { "content": "#[inline]\n\npub fn config_from_yaml(yaml: &str) -> YamlResult<Config> {\n\n serde_yaml::from_str(yaml)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 20, "score": 140030.26714572439 }, { "content": "#[inline]\n\npub fn brain_from_yaml(yaml: &str) -> YamlResult<Brain> {\n\n serde_yaml::from_str(yaml)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 21, "score": 138620.7441523892 }, { "content": "#[inline]\n\npub fn brain_from_json(json: &str) -> JsonResult<Brain> {\n\n serde_json::from_str(json)\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 22, "score": 138620.7441523892 }, { "content": "#[inline]\n\npub fn brain_from_bytes(bytes: &[u8]) -> BinResult<Brain> {\n\n bincode::deserialize(bytes)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 23, "score": 138620.7441523892 }, { "content": "fn lerp(start: Position, end: Position, factor: Scalar) -> Position {\n\n let factor = factor.max(0.0).min(1.0);\n\n Position {\n\n x: (end.x - start.x) * factor + start.x,\n\n y: (end.y - start.y) * factor + start.y,\n\n z: (end.z - start.z) * factor + start.z,\n\n }\n\n}\n\n\n", "file_path": "psyche-graphics/src/obj.rs", "rank": 24, "score": 127198.23853556678 }, { "content": "#[inline]\n\npub fn brain_builder_to_yaml(brain_builder: &BrainBuilder) -> YamlResult<String> {\n\n serde_yaml::to_string(brain_builder)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 25, "score": 119972.7807254011 }, { "content": "fn make_brain() -> Brain {\n\n let mut config = Config::default();\n\n config.propagation_speed = 50.0;\n\n config.synapse_reconnection_range = Some(15.0);\n\n // config.synapse_overdose_receptors = Some(10.0);\n\n config.neuron_potential_decay = 0.1;\n\n config.synapse_propagation_decay = 0.01;\n\n config.synapse_new_connection_receptors = Some(2.0);\n\n // config.action_potential_treshold = 0.1;\n\n\n\n BrainBuilder::new()\n\n .config(config)\n\n .neurons(600)\n\n .connections(1000)\n\n .min_neurogenesis_range(5.0)\n\n .max_neurogenesis_range(15.0)\n\n .radius(50.0)\n\n .sensors(50)\n\n .effectors(25)\n\n .build()\n", "file_path": "demos/src/brain-activity/main.rs", "rank": 26, "score": 118656.21244376746 }, { "content": "#[inline]\n\npub fn offspring_builder_to_bytes(offspring_builder: &OffspringBuilder) -> BinResult<Vec<u8>> {\n\n bincode::serialize(offspring_builder)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 27, "score": 117584.88551177148 }, { "content": "#[inline]\n\npub fn brain_builder_from_json(json: &str) -> JsonResult<BrainBuilder> {\n\n serde_json::from_str(json)\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 28, "score": 116402.95802170533 }, { "content": "#[inline]\n\npub fn brain_builder_from_yaml(yaml: &str) -> YamlResult<BrainBuilder> {\n\n serde_yaml::from_str(yaml)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 29, "score": 116402.95802170533 }, { "content": "#[inline]\n\npub fn brain_builder_from_bytes(bytes: &[u8]) -> BinResult<BrainBuilder> {\n\n bincode::deserialize(bytes)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 30, "score": 116402.95802170533 }, { "content": "#[inline]\n\npub fn brain_activity_map_from_bytes(bytes: &[u8]) -> BinResult<BrainActivityMap> {\n\n bincode::deserialize(bytes)\n\n}\n\n\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 31, "score": 112220.32830593815 }, { "content": "#[inline]\n\npub fn brain_activity_map_from_json(json: &str) -> JsonResult<BrainActivityMap> {\n\n serde_json::from_str(json)\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 32, "score": 112220.32830593815 }, { "content": "#[inline]\n\npub fn brain_activity_map_to_yaml(bam: &BrainActivityMap) -> YamlResult<String> {\n\n serde_yaml::to_string(bam)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 33, "score": 112220.32830593815 }, { "content": "#[inline]\n\npub fn brain_activity_map_from_yaml(yaml: &str) -> YamlResult<BrainActivityMap> {\n\n serde_yaml::from_str(yaml)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 34, "score": 112220.32830593815 }, { "content": "fn bytes_from_raw(source: *const libc::c_uchar, size: usize) -> Vec<u8> {\n\n if source.is_null() || size == 0 {\n\n return vec![];\n\n }\n\n let mut result = vec![0; size];\n\n let target = result.as_mut_ptr();\n\n unsafe { copy_nonoverlapping(source, target, size) };\n\n result\n\n}\n\n\n", "file_path": "psyche-capi/src/lib.rs", "rank": 35, "score": 104405.14984935973 }, { "content": "#[inline]\n\npub fn offspring_builder_to_json(\n\n offspring_builder: &OffspringBuilder,\n\n pretty: bool,\n\n) -> JsonResult<String> {\n\n if pretty {\n\n serde_json::to_string_pretty(offspring_builder)\n\n } else {\n\n serde_json::to_string(offspring_builder)\n\n }\n\n}\n\n\n", "file_path": "psyche-serde/src/json.rs", "rank": 36, "score": 101742.72223671582 }, { "content": "fn make_brain(matches: &ArgMatches) -> Brain {\n\n if let Some(snapshot) = matches.value_of(\"snapshot\") {\n\n if snapshot.ends_with(\".json\") {\n\n brain_from_json(from_utf8(&read(snapshot).unwrap()).unwrap()).unwrap()\n\n } else if snapshot.ends_with(\".yaml\") {\n\n brain_from_yaml(from_utf8(&read(snapshot).unwrap()).unwrap()).unwrap()\n\n } else {\n\n panic!(\n\n \"Snapshot file with no specified format extension: {}\",\n\n snapshot\n\n )\n\n }\n\n } else if let Some(builder) = matches.value_of(\"builder\") {\n\n if builder.ends_with(\".json\") {\n\n brain_builder_from_json(from_utf8(&read(builder).unwrap()).unwrap())\n\n .unwrap()\n\n .build()\n\n } else if builder.ends_with(\".yaml\") {\n\n brain_builder_from_yaml(from_utf8(&read(builder).unwrap()).unwrap())\n\n .unwrap()\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 37, "score": 101656.50380304063 }, { "content": "#[test]\n\nfn test_config() {\n\n let config = Config::default();\n\n\n\n let json = config_to_json(&config, true).unwrap();\n\n let config_json = config_from_json(&json).unwrap();\n\n assert_eq!(config, config_json);\n\n\n\n let bytes = config_to_bytes(&config).unwrap();\n\n let config_bytes = config_from_bytes(&bytes).unwrap();\n\n assert_eq!(config, config_bytes);\n\n\n\n let yaml = config_to_yaml(&config).unwrap();\n\n let config_yaml = config_from_yaml(&yaml).unwrap();\n\n assert_eq!(config, config_yaml);\n\n}\n", "file_path": "psyche-serde/src/tests.rs", "rank": 38, "score": 87131.33065977639 }, { "content": "#[test]\n\nfn test_brain() {\n\n let mut brain = Brain::new();\n\n let n1 = brain.create_neuron(Position {\n\n x: 0.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let n2 = brain.create_neuron(Position {\n\n x: 1.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let n3 = brain.create_neuron(Position {\n\n x: 4.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n brain.create_sensor(n1).unwrap();\n\n brain.bind_neurons(n1, n2).unwrap();\n\n brain.bind_neurons(n2, n3).unwrap();\n", "file_path": "psyche-serde/src/tests.rs", "rank": 39, "score": 85841.50900203723 }, { "content": "#[allow(clippy::cyclomatic_complexity)]\n\nfn main() {\n\n let mut window: PistonWindow =\n\n WindowSettings::new(\"Psyche - Brain Activity Visualizer\", [600, 600])\n\n .exit_on_esc(true)\n\n .build()\n\n .unwrap();\n\n\n\n // let mut brain =\n\n // psyche_serde::bytes::brain_from_bytes(&::std::fs::read(\"./brain.bin\").unwrap()).unwrap();\n\n let mut brain = make_brain();\n\n drop(::std::fs::write(\n\n \"./brain.bin\",\n\n &psyche::serde::bytes::brain_to_bytes(&brain).unwrap(),\n\n ));\n\n // brain.ignite_random_synapses(brain.synapses_count(), (1.0, 1.0));\n\n\n\n let vx = 300.0;\n\n let vy = 300.0;\n\n let zoom = 5.0;\n\n let thickness = 0.5 / zoom;\n", "file_path": "demos/src/brain-activity/main.rs", "rank": 40, "score": 85841.50900203723 }, { "content": "#[test]\n\nfn test_brain() {\n\n let mut brain = Brain::new();\n\n let n1 = brain.create_neuron(Position {\n\n x: 0.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let n2 = brain.create_neuron(Position {\n\n x: 1.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let n3 = brain.create_neuron(Position {\n\n x: 4.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let s1 = brain.create_sensor(n1).unwrap();\n\n let e1 = brain.create_effector(n3).unwrap();\n\n brain.bind_neurons(n1, n2).unwrap();\n\n brain.bind_neurons(n2, n3).unwrap();\n\n assert!(brain.bind_neurons(n3, n1).is_err());\n\n brain.sensor_trigger_impulse(s1, 10.0).unwrap();\n\n\n\n for _ in 0..4 {\n\n brain.process(1.0).unwrap();\n\n }\n\n assert!(brain.effector_potential_release(e1).unwrap() > 0.0);\n\n}\n\n\n", "file_path": "psyche-core/src/tests.rs", "rank": 41, "score": 85841.50900203723 }, { "content": "#[test]\n\nfn test_brain_builder() {\n\n let _brain = BrainBuilder::new()\n\n .config(Config::default())\n\n .neurons(1000)\n\n .connections(1000)\n\n .min_neurogenesis_range(0.1)\n\n .max_neurogenesis_range(10.0)\n\n .radius(20.0)\n\n .sensors(10)\n\n .effectors(10)\n\n .build();\n\n // println!(\"brain: {:#?}\", brain);\n\n // println!(\"neurons: {}\", brain.get_neurons().len());\n\n // println!(\"synapses: {}\", brain.synapses_count());\n\n // println!(\"sensors: {}\", brain.get_sensors().len());\n\n // println!(\"effectors: {}\", brain.get_effectors().len());\n\n // println!(\"brain energy: {}\", brain.energy());\n\n // println!(\"brain activity: {:#?}\", brain.build_activity_map());\n\n}\n\n\n", "file_path": "psyche-core/src/tests.rs", "rank": 42, "score": 83486.23641509621 }, { "content": "fn impulse_into_point(\n\n impulse: &(Position, Position, Scalar),\n\n rot: &Quaternion<Scalar>,\n\n) -> (Scalar, Scalar) {\n\n point(\n\n Position {\n\n x: (impulse.1.x - impulse.0.x) * impulse.2 + impulse.0.x,\n\n y: (impulse.1.y - impulse.0.y) * impulse.2 + impulse.0.y,\n\n z: (impulse.1.z - impulse.0.z) * impulse.2 + impulse.0.z,\n\n },\n\n rot,\n\n )\n\n}\n\n\n", "file_path": "demos/src/brain-activity/main.rs", "rank": 43, "score": 83486.23641509621 }, { "content": "fn string_from_raw_unsized(mut source: *const libc::c_uchar) -> String {\n\n if source.is_null() {\n\n return \"\".to_owned();\n\n }\n\n let mut bytes = vec![];\n\n unsafe {\n\n while *source != 0 {\n\n bytes.push(*source);\n\n source = source.add(1);\n\n }\n\n }\n\n let cstring = unsafe { CString::from_vec_unchecked(bytes) };\n\n cstring.into_string().unwrap()\n\n}\n", "file_path": "psyche-capi/src/lib.rs", "rank": 44, "score": 82898.66053120034 }, { "content": "fn print_stats(stats: BrainActivityStats) {\n\n println!(\"=== BRAIN ACTIVITY STATS ===\");\n\n println!(\"Count:\");\n\n println!(\"- neurons: {}\", stats.neurons_count);\n\n println!(\"- synapses: {}\", stats.synapses_count);\n\n println!(\"- impulses: {}\", stats.impulses_count);\n\n println!(\"Potential:\");\n\n println!(\"- neurons: {}\", stats.neurons_potential.0);\n\n println!(\" - min: {}\", stats.neurons_potential.1.start);\n\n println!(\" - max: {}\", stats.neurons_potential.1.end);\n\n println!(\"- impulses: {}\", stats.impulses_potential.0);\n\n println!(\" - min: {}\", stats.impulses_potential.1.start);\n\n println!(\" - max: {}\", stats.impulses_potential.1.end);\n\n println!(\"- all: {}\", stats.all_potential.0);\n\n println!(\" - min: {}\", stats.all_potential.1.start);\n\n println!(\" - max: {}\", stats.all_potential.1.end);\n\n println!(\"Neurons connections:\");\n\n println!(\"- Incoming:\");\n\n println!(\" - min: {}\", stats.incoming_neuron_connections.start);\n\n println!(\" - max: {}\", stats.incoming_neuron_connections.end);\n\n println!(\"- Outgoing:\");\n\n println!(\" - min: {}\", stats.outgoing_neuron_connections.start);\n\n println!(\" - max: {}\", stats.outgoing_neuron_connections.end);\n\n println!(\"Synapses receptors:\");\n\n println!(\"- min: {}\", stats.synapses_receptors.start);\n\n println!(\"- max: {}\", stats.synapses_receptors.end);\n\n}\n", "file_path": "demos/src/brain-activity/main.rs", "rank": 45, "score": 82566.34430716316 }, { "content": "#[test]\n\nfn test_brain_activity_map() {\n\n let mut brain = Brain::new();\n\n let n1 = brain.create_neuron(Position {\n\n x: 0.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let n2 = brain.create_neuron(Position {\n\n x: 1.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let n3 = brain.create_neuron(Position {\n\n x: 4.0,\n\n y: 0.0,\n\n z: 0.0,\n\n });\n\n let s1 = brain.create_sensor(n1).unwrap();\n\n brain.bind_neurons(n1, n2).unwrap();\n\n brain.bind_neurons(n2, n3).unwrap();\n", "file_path": "psyche-serde/src/tests.rs", "rank": 46, "score": 81291.72834491232 }, { "content": "#[inline]\n\npub fn offspring_builder_from_json(json: &str) -> JsonResult<OffspringBuilder> {\n\n serde_json::from_str(json)\n\n}\n", "file_path": "psyche-serde/src/json.rs", "rank": 47, "score": 80553.10582065894 }, { "content": "#[inline]\n\npub fn offspring_builder_from_bytes(bytes: &[u8]) -> BinResult<OffspringBuilder> {\n\n bincode::deserialize(bytes)\n\n}\n", "file_path": "psyche-serde/src/bytes.rs", "rank": 48, "score": 80553.10582065894 }, { "content": "#[inline]\n\npub fn offspring_builder_from_yaml(yaml: &str) -> YamlResult<OffspringBuilder> {\n\n serde_yaml::from_str(yaml)\n\n}\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 49, "score": 80553.10582065894 }, { "content": "#[inline]\n\npub fn offspring_builder_to_yaml(offspring_builder: &OffspringBuilder) -> YamlResult<String> {\n\n serde_yaml::to_string(offspring_builder)\n\n}\n\n\n", "file_path": "psyche-serde/src/yaml.rs", "rank": 50, "score": 79110.58535888774 }, { "content": "/// Trait used to obtain zero value for given type. It is used by built-in samplers and it's\n\n/// implemented for `f32` and `f64` types so if you want to sample any other type of grid, you have\n\n/// implement this trait for that type.\n\npub trait GridSampleZeroValue<T> {\n\n /// produce zero value for given type.\n\n ///\n\n /// # Return\n\n /// Zero value of given type.\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use psyche_utils::grid::{Grid, GridSamplerCluster, GridSampleZeroValue};\n\n /// use std::ops::Add;\n\n ///\n\n /// #[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\n /// struct Integer(pub i32);\n\n ///\n\n /// impl Add for Integer {\n\n /// type Output = Integer;\n\n /// fn add(self, other: Integer) -> Integer { Integer(self.0 + other.0) }\n\n /// }\n\n ///\n\n /// impl GridSampleZeroValue<Self> for Integer {\n", "file_path": "psyche-utils/src/grid.rs", "rank": 51, "score": 79055.3123353995 }, { "content": "fn main_visual(builder: BrainBuilder) {\n\n let mut window: PistonWindow = WindowSettings::new(\"Spores Evolution Simulator\", WORLD_SIZE)\n\n .exit_on_esc(true)\n\n .build()\n\n .unwrap();\n\n\n\n let size = (window.size().width, window.size().height);\n\n window.set_max_fps(60);\n\n window.set_ups(20);\n\n let mut world = WorldBuilder::new()\n\n .size(size)\n\n .grid_cols_rows((\n\n size.0 as usize / FLUID_RESOLUTION,\n\n size.1 as usize / FLUID_RESOLUTION,\n\n ))\n\n .randomized_fluid(RANDOMIZED_FLUID)\n\n .fluid_diffuse(FLUID_DIFFUSE)\n\n .fluid_drag(FLUID_DRAG)\n\n .spores_count(SPORES_COUNT)\n\n .spores_radius(SPORES_RADIUS)\n", "file_path": "demos/src/spore/main.rs", "rank": 52, "score": 75982.7442261058 }, { "content": "fn main_headless(builder: BrainBuilder) {\n\n let size = (Scalar::from(WORLD_SIZE[0]), Scalar::from(WORLD_SIZE[1]));\n\n let dt = 1.0 / 20.0;\n\n\n\n let mut world = WorldBuilder::new()\n\n .size(size)\n\n .grid_cols_rows((\n\n WORLD_SIZE[0] as usize / FLUID_RESOLUTION,\n\n WORLD_SIZE[1] as usize / FLUID_RESOLUTION,\n\n ))\n\n .randomized_fluid(RANDOMIZED_FLUID)\n\n .fluid_diffuse(FLUID_DIFFUSE)\n\n .fluid_drag(FLUID_DRAG)\n\n .spores_count(SPORES_COUNT)\n\n .spores_radius(SPORES_RADIUS)\n\n .spores_brain_builder(builder)\n\n .food_count(FOOD_COUNT)\n\n .food_calories(FOOD_CALORIES)\n\n .build();\n\n\n\n loop {\n\n world.process(dt);\n\n }\n\n}\n\n\n", "file_path": "demos/src/spore/main.rs", "rank": 53, "score": 75982.7442261058 }, { "content": "fn print_stats(stats: BrainActivityStats) {\n\n println!(\"- brain activity stats:\");\n\n println!(\" Count:\");\n\n println!(\" - neurons: {}\", stats.neurons_count);\n\n println!(\" - synapses: {}\", stats.synapses_count);\n\n println!(\" - impulses: {}\", stats.impulses_count);\n\n println!(\" Potential:\");\n\n println!(\" - neurons: {}\", stats.neurons_potential.0);\n\n println!(\" - min: {}\", stats.neurons_potential.1.start);\n\n println!(\" - max: {}\", stats.neurons_potential.1.end);\n\n println!(\" - impulses: {}\", stats.impulses_potential.0);\n\n println!(\" - min: {}\", stats.impulses_potential.1.start);\n\n println!(\" - max: {}\", stats.impulses_potential.1.end);\n\n println!(\" - all: {}\", stats.all_potential.0);\n\n println!(\" - min: {}\", stats.all_potential.1.start);\n\n println!(\" - max: {}\", stats.all_potential.1.end);\n\n println!(\" Neurons connections:\");\n\n println!(\" - Incoming:\");\n\n println!(\" - min: {}\", stats.incoming_neuron_connections.start);\n\n println!(\" - max: {}\", stats.incoming_neuron_connections.end);\n\n println!(\" - Outgoing:\");\n\n println!(\" - min: {}\", stats.outgoing_neuron_connections.start);\n\n println!(\" - max: {}\", stats.outgoing_neuron_connections.end);\n\n println!(\" Synapses receptors:\");\n\n println!(\" - min: {}\", stats.synapses_receptors.start);\n\n println!(\" - max: {}\", stats.synapses_receptors.end);\n\n}\n\n\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 54, "score": 72264.154751113 }, { "content": "struct GameBundle;\n\n\n\nimpl<'a, 'b> SystemBundle<'a, 'b> for GameBundle {\n\n fn build(self, builder: &mut DispatcherBuilder<'a, 'b>) -> Result<(), Error> {\n\n builder.add(EnvironmentSystem, \"environment_system\", &[]);\n\n builder.add(ShibaSystem, \"shiba_system\", &[\"environment_system\"]);\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "amethyst-demo/src/main.rs", "rank": 55, "score": 61405.45253942343 }, { "content": "fn main() {\n\n let matches = App::new(\"Spores\")\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(env!(\"CARGO_PKG_AUTHORS\"))\n\n .about(\"Spores Evolution Simulator\")\n\n .arg(\n\n Arg::with_name(\"headless\")\n\n .short(\"h\")\n\n .long(\"headless\")\n\n .help(\"Headless mode\"),\n\n )\n\n .get_matches();\n\n\n\n let mut config = Config::default();\n\n config.propagation_speed = 50.0;\n\n config.synapse_reconnection_range = Some(15.0);\n\n config.neuron_potential_decay = 0.1;\n\n config.synapse_propagation_decay = 0.01;\n\n config.synapse_new_connection_receptors = Some(2.0);\n\n let builder = BrainBuilder::new()\n", "file_path": "demos/src/spore/main.rs", "rank": 56, "score": 54198.54971542499 }, { "content": "#[test]\n\nfn test_offspring_builder() {\n\n let brain_a = BrainBuilder::new()\n\n .config(Config::default())\n\n .neurons(1000)\n\n .connections(1000)\n\n .min_neurogenesis_range(0.1)\n\n .max_neurogenesis_range(10.0)\n\n .radius(20.0)\n\n .sensors(10)\n\n .effectors(10)\n\n .build();\n\n let brain_b = BrainBuilder::new()\n\n .config(Config::default())\n\n .neurons(1000)\n\n .connections(1000)\n\n .min_neurogenesis_range(0.1)\n\n .max_neurogenesis_range(10.0)\n\n .radius(20.0)\n\n .sensors(10)\n\n .effectors(10)\n", "file_path": "psyche-core/src/tests.rs", "rank": 57, "score": 51724.18489477014 }, { "content": "#[test]\n\nfn test_general() {\n\n let mut bs = BucketStrainer::new(vec![\n\n Layer::new(vec![Bucket::new(\"range\".to_owned(), Box::new(11..20))]),\n\n Layer::new(vec![\n\n Bucket::new(\"even\".to_owned(), Box::new(EvenOrOddRule::Even)),\n\n Bucket::new(\"odd\".to_owned(), Box::new(EvenOrOddRule::Odd)),\n\n ]),\n\n ]);\n\n\n\n let leftovers = bs.process((0..=15).collect());\n\n let meta = bs.buckets_items_pairs();\n\n assert_eq!(meta.len(), 3);\n\n assert_eq!(meta[0].0, \"range\");\n\n assert_eq!(meta[0].1, [11, 12, 13, 14, 15]);\n\n assert_eq!(meta[1].0, \"even\");\n\n assert_eq!(meta[1].1, [0, 2, 4, 6, 8, 10]);\n\n assert_eq!(meta[2].0, \"odd\");\n\n assert_eq!(meta[2].1, [1, 3, 5, 7, 9]);\n\n assert_eq!(leftovers.len(), 0);\n\n}\n", "file_path": "psyche-utils/src/bucket_strainer/tests.rs", "rank": 58, "score": 50613.67255658606 }, { "content": "pub trait Named<T> {\n\n fn id(&self) -> ID<T>;\n\n}\n\n\n", "file_path": "demos/src/spore/managers/items_manager.rs", "rank": 59, "score": 50060.03742333759 }, { "content": "fn main() -> Result<()> {\n\n let matches = App::new(\"Psyche AI Simulator CLI\")\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(env!(\"CARGO_PKG_AUTHORS\"))\n\n .about(env!(\"CARGO_PKG_DESCRIPTION\"))\n\n .arg(\n\n Arg::with_name(\"snapshot\")\n\n .short(\"s\")\n\n .long(\"snapshot\")\n\n .value_name(\"FILE\")\n\n .help(\"Brain snapshot file path\")\n\n .takes_value(true)\n\n .required(false),\n\n )\n\n .arg(\n\n Arg::with_name(\"builder\")\n\n .short(\"b\")\n\n .long(\"builder\")\n\n .value_name(\"FILE\")\n\n .help(\"Brain builder config file path\")\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 60, "score": 49943.24300738623 }, { "content": "/// Trait used to tell how much successfuly bucket has to get incoming item.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use psyche_utils::bucket_strainer::{Bucket, Rule};\n\n/// use psyche_utils::Scalar;\n\n///\n\n/// #[derive(Clone)]\n\n/// struct SuccessRule;\n\n///\n\n/// impl<T> Rule<T> for SuccessRule\n\n/// where\n\n/// T: Clone,\n\n/// {\n\n/// fn score(&self, _: &T, _: &Bucket<T>) -> Scalar {\n\n/// 1.0\n\n/// }\n\n///\n\n/// fn box_clone(&self) -> Box<dyn Rule<T>> {\n\n/// Box::new((*self).clone())\n\n/// }\n\n/// }\n\n/// ```\n\npub trait Rule<T>\n\nwhere\n\n T: Clone,\n\n{\n\n /// Score incoming item.\n\n ///\n\n /// # Arguments\n\n /// * `item` - Incoming item.\n\n /// * `bucket` - Bucket that tests incoming item.\n\n ///\n\n /// # Return\n\n /// Score for given item that tell how lucky it is to fall into given bucket.\n\n fn score(&self, item: &T, bucket: &Bucket<T>) -> Scalar;\n\n\n\n /// Create boxed clone for this rule.\n\n fn box_clone(&self) -> Box<dyn Rule<T>>;\n\n}\n\n\n\nimpl<T> Clone for Box<Rule<T>>\n\nwhere\n\n T: Clone,\n\n{\n\n fn clone(&self) -> Box<Rule<T>> {\n\n self.box_clone()\n\n }\n\n}\n", "file_path": "psyche-utils/src/bucket_strainer/rules/mod.rs", "rank": 61, "score": 49107.67716218367 }, { "content": "pub trait ItemsManager<T>\n\nwhere\n\n T: Named<T>,\n\n{\n\n fn items(&self) -> &[T];\n\n\n\n fn add(&mut self, item: T) -> ID<T>;\n\n\n\n fn create(&mut self) -> ID<T>;\n\n\n\n fn create_with<F>(&mut self, with: F) -> ID<T>\n\n where\n\n F: FnMut(&mut T, &mut Self);\n\n\n\n fn destroy(&mut self, id: ID<T>) -> bool;\n\n\n\n fn with<F, R>(&mut self, id: ID<T>, with: F) -> Option<R>\n\n where\n\n F: FnMut(&mut T, &mut Self) -> R;\n\n\n\n fn item(&self, id: ID<T>) -> Option<&T>;\n\n\n\n fn item_mut(&mut self, id: ID<T>) -> Option<&mut T>;\n\n}\n", "file_path": "demos/src/spore/managers/items_manager.rs", "rank": 62, "score": 49081.97279529844 }, { "content": "/// Trait used to sample pair of single value and weight from grid.\n\npub trait GridSampler<T, W> {\n\n /// Sample value and weight from given grid.\n\n ///\n\n /// # Arguments\n\n /// * `grid` - Grid that we sample from.\n\n ///\n\n /// # Return\n\n /// Pair of single value and weight as result of grid sampling.\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use psyche_utils::grid::{Grid, GridSampler};\n\n ///\n\n /// struct MySampler;\n\n ///\n\n /// impl GridSampler<f32, usize> for MySampler {\n\n /// fn sample(self, grid: &Grid<f32>) -> Option<(f32, usize)> {\n\n /// let value = grid.fields().iter().cloned().sum();\n\n /// let weight = grid.fields().len();\n\n /// Some((value, weight))\n\n /// }\n\n /// }\n\n ///\n\n /// let grid = Grid::new(2, 2, 1.0);\n\n /// let sampler = MySampler {};\n\n /// assert_eq!(grid.sample(sampler).unwrap(), (4.0, 4));\n\n /// ```\n\n fn sample(self, grid: &Grid<T>) -> Option<(T, W)>;\n\n}\n\n\n", "file_path": "psyche-utils/src/grid.rs", "rank": 63, "score": 48545.705840340925 }, { "content": "fn main() -> amethyst::Result<()> {\n\n let matches = App::new(\"Amethyst Demo\")\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .author(env!(\"CARGO_PKG_AUTHORS\"))\n\n .about(\"Amethyst Demo\")\n\n .arg(\n\n Arg::with_name(\"snapshot\")\n\n .short(\"s\")\n\n .long(\"snapshot\")\n\n .value_name(\"FILE\")\n\n .help(\"Snapshot file\")\n\n .takes_value(true)\n\n .required(false),\n\n )\n\n .get_matches();\n\n\n\n // amethyst::start_logger(Default::default());\n\n\n\n let app_root: PathBuf = application_root_dir().into();\n\n let display_config_path = app_root.join(\"assets/display.ron\");\n", "file_path": "amethyst-demo/src/main.rs", "rank": 64, "score": 48464.861135027546 }, { "content": "fn utf8_into_error(error: FromUtf8Error) -> Error {\n\n Error::simple(format!(\"{}\", error))\n\n}\n", "file_path": "psyche-graphics/src/obj.rs", "rank": 65, "score": 44099.308644391494 }, { "content": "fn main_template(matches: &ArgMatches) -> Result<()> {\n\n let format = matches.value_of(\"format\").unwrap();\n\n let type_ = matches.value_of(\"type\").unwrap();\n\n if let Some(output) = matches.value_of(\"output\") {\n\n match type_ {\n\n \"builder\" => match format {\n\n \"json\" => write(\n\n output,\n\n brain_builder_to_json(&make_default_brain_builder(Config::default()), true)\n\n .unwrap(),\n\n )\n\n .unwrap(),\n\n \"yaml\" => write(\n\n output,\n\n brain_builder_to_yaml(&make_default_brain_builder(Config::default())).unwrap(),\n\n )\n\n .unwrap(),\n\n name => panic!(\"Unsupported template format: {}\", name),\n\n },\n\n \"timeline\" => match format {\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 66, "score": 43188.48740496105 }, { "content": "fn main_simulation(matches: ArgMatches) -> Result<()> {\n\n let mut brain = make_brain(&matches);\n\n let timeline = make_timeline(&matches);\n\n let fps = matches.value_of(\"fps\").unwrap().parse::<usize>().unwrap();\n\n let output_dir = Path::new(matches.value_of(\"output_dir\").unwrap())\n\n .to_str()\n\n .unwrap()\n\n .to_owned();\n\n let name = matches.value_of(\"name\").unwrap().to_owned();\n\n let render_neurons = !matches.is_present(\"ignore-neurons\");\n\n let render_connections = !matches.is_present(\"ignore-connections\");\n\n let render_impulses = !matches.is_present(\"ignore-impulses\");\n\n let render_sensors = !matches.is_present(\"ignore-sensors\");\n\n let render_effectors = !matches.is_present(\"ignore-effectors\");\n\n let dry = matches.is_present(\"dry\");\n\n let verbose = matches.is_present(\"verbose\");\n\n\n\n let mut rng = thread_rng();\n\n let delta_time = 1.0 / fps as Scalar;\n\n let mut last_time = 0.0;\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 67, "score": 43188.48740496105 }, { "content": "fn make_timeline(matches: &ArgMatches) -> Timeline {\n\n if let Some(timeline) = matches.value_of(\"timeline\") {\n\n if timeline.ends_with(\".json\") {\n\n Timeline::from_json(from_utf8(&read(timeline).unwrap()).unwrap()).unwrap()\n\n } else if timeline.ends_with(\".yaml\") {\n\n Timeline::from_yaml(from_utf8(&read(timeline).unwrap()).unwrap()).unwrap()\n\n } else {\n\n panic!(\n\n \"Timeline file with no specified format extension: {}\",\n\n timeline\n\n )\n\n }\n\n } else {\n\n Default::default()\n\n }\n\n}\n\n\n", "file_path": "psyche-simulator-cli/src/main.rs", "rank": 68, "score": 43188.48740496105 }, { "content": "use crate::id::ID;\n\nuse crate::neuron::NeuronID;\n\nuse crate::Scalar;\n\nuse serde::{Deserialize, Serialize};\n\n\n\npub type EffectorID = ID<Effector>;\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub struct Effector {\n\n pub(crate) id: EffectorID,\n\n pub(crate) source: NeuronID,\n\n pub(crate) potential: Scalar,\n\n}\n", "file_path": "psyche-core/src/effector.rs", "rank": 69, "score": 37119.77727112168 }, { "content": "use crate::id::ID;\n\nuse crate::neuron::NeuronID;\n\nuse serde::{Deserialize, Serialize};\n\n\n\npub type SensorID = ID<Sensor>;\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\npub struct Sensor {\n\n pub(crate) id: SensorID,\n\n pub(crate) target: NeuronID,\n\n}\n", "file_path": "psyche-core/src/sensor.rs", "rank": 70, "score": 37116.99659835926 }, { "content": "use serde::{Deserialize, Serialize};\n\nuse std::cmp::Ordering;\n\nuse std::fmt;\n\nuse std::hash::{Hash, Hasher};\n\nuse std::marker::PhantomData;\n\nuse uuid::Uuid;\n\n\n\n/// Universal Identifier (uuidv4).\n\n#[derive(Clone, Serialize, Deserialize)]\n\n#[repr(C)]\n\npub struct ID<T> {\n\n id: Uuid,\n\n #[serde(skip_serializing, skip_deserializing)]\n\n _phantom: PhantomData<T>,\n\n}\n\n\n\nimpl<T> ID<T> {\n\n /// Creates new identifier.\n\n #[inline]\n\n pub fn new() -> Self {\n", "file_path": "psyche-core/src/id.rs", "rank": 71, "score": 37067.85948937822 }, { "content": "use crate::brain::BrainID;\n\nuse crate::id::ID;\n\nuse crate::Scalar;\n\nuse serde::{Deserialize, Serialize};\n\n\n\npub type NeuronID = ID<Neuron>;\n\n\n\n#[derive(Debug, Default, Copy, Clone, PartialEq, Serialize, Deserialize)]\n\n#[repr(C)]\n\npub struct Impulse {\n\n pub potential: Scalar,\n\n pub timeout: Scalar,\n\n}\n\n\n\n#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]\n\npub(crate) struct Synapse {\n\n pub source: NeuronID,\n\n pub target: NeuronID,\n\n pub distance: Scalar,\n\n pub receptors: Scalar,\n", "file_path": "psyche-core/src/neuron.rs", "rank": 72, "score": 37066.57363601218 }, { "content": " owner_id: BrainID,\n\n position: Position,\n\n potential: Scalar,\n\n}\n\n\n\nimpl Neuron {\n\n pub(crate) fn new(owner_id: BrainID, position: Position) -> Self {\n\n Self {\n\n id: Default::default(),\n\n owner_id,\n\n position,\n\n potential: 0.0,\n\n }\n\n }\n\n\n\n pub(crate) fn with_id(id: NeuronID, owner_id: BrainID, position: Position) -> Self {\n\n Self {\n\n id,\n\n owner_id,\n\n position,\n", "file_path": "psyche-core/src/neuron.rs", "rank": 73, "score": 37063.49520792436 }, { "content": " Self::default()\n\n }\n\n\n\n /// Creates new identifier from raw bytes.\n\n #[inline]\n\n pub fn from_bytes(bytes: [u8; 16]) -> Self {\n\n Self {\n\n id: Uuid::from_bytes(bytes),\n\n _phantom: PhantomData,\n\n }\n\n }\n\n\n\n /// Gets underlying UUID object.\n\n #[inline]\n\n pub fn uuid(&self) -> Uuid {\n\n self.id\n\n }\n\n}\n\n\n\nimpl<T> Default for ID<T> {\n", "file_path": "psyche-core/src/id.rs", "rank": 74, "score": 37059.568144432014 }, { "content": " pub impulses: Vec<Impulse>,\n\n pub inactivity: Scalar,\n\n}\n\n\n\n#[derive(Debug, Default, Copy, Clone, PartialEq, Serialize, Deserialize)]\n\n#[repr(C)]\n\npub struct Position {\n\n pub x: Scalar,\n\n pub y: Scalar,\n\n pub z: Scalar,\n\n}\n\n\n\nimpl Position {\n\n #[inline]\n\n pub fn magnitude_sqr(&self) -> Scalar {\n\n self.x * self.x + self.y * self.y + self.z * self.z\n\n }\n\n\n\n #[inline]\n\n pub fn magnitude(&self) -> Scalar {\n", "file_path": "psyche-core/src/neuron.rs", "rank": 75, "score": 37058.18995483256 }, { "content": " }\n\n}\n\n\n\nimpl<T> Hash for ID<T> {\n\n #[inline]\n\n fn hash<H>(&self, state: &mut H)\n\n where\n\n H: Hasher,\n\n {\n\n self.id.hash(state)\n\n }\n\n}\n\n\n\nimpl<T> PartialEq for ID<T> {\n\n #[inline]\n\n fn eq(&self, other: &Self) -> bool {\n\n self.id == other.id\n\n }\n\n}\n\n\n", "file_path": "psyche-core/src/id.rs", "rank": 76, "score": 37056.84050871467 }, { "content": " #[inline]\n\n fn default() -> Self {\n\n Self {\n\n id: Uuid::new_v4(),\n\n _phantom: PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<T> fmt::Debug for ID<T> {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.to_string())\n\n }\n\n}\n\n\n\nimpl<T> ToString for ID<T> {\n\n #[inline]\n\n fn to_string(&self) -> String {\n\n format!(\"ID({})\", self.id)\n", "file_path": "psyche-core/src/id.rs", "rank": 77, "score": 37056.38454522325 }, { "content": "impl<T> Eq for ID<T> {}\n\nimpl<T> Copy for ID<T> where T: Clone {}\n\n\n\nimpl<T> PartialOrd for ID<T> {\n\n #[inline]\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n Some(self.id.cmp(&other.id))\n\n }\n\n}\n\n\n\nimpl<T> Ord for ID<T> {\n\n #[inline]\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n self.id.cmp(&other.id)\n\n }\n\n}\n", "file_path": "psyche-core/src/id.rs", "rank": 78, "score": 37054.97068268045 }, { "content": " self.magnitude_sqr().sqrt()\n\n }\n\n\n\n pub fn distance_sqr(&self, other: Self) -> Scalar {\n\n let dx = self.x - other.x;\n\n let dy = self.y - other.y;\n\n let dz = self.z - other.z;\n\n dx * dx + dy * dy + dz * dz\n\n }\n\n\n\n #[inline]\n\n pub fn distance(&self, other: Self) -> Scalar {\n\n self.distance_sqr(other).sqrt()\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[repr(C)]\n\npub struct Neuron {\n\n id: NeuronID,\n", "file_path": "psyche-core/src/neuron.rs", "rank": 79, "score": 37054.77676611121 }, { "content": " potential: 0.0,\n\n }\n\n }\n\n\n\n #[inline]\n\n pub fn id(&self) -> NeuronID {\n\n self.id\n\n }\n\n\n\n #[inline]\n\n pub fn owner_id(&self) -> BrainID {\n\n self.owner_id\n\n }\n\n\n\n #[inline]\n\n pub fn position(&self) -> Position {\n\n self.position\n\n }\n\n\n\n #[inline]\n", "file_path": "psyche-core/src/neuron.rs", "rank": 80, "score": 37049.06083665091 }, { "content": " pub fn potential(&self) -> Scalar {\n\n self.potential\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn push_potential(&mut self, value: Scalar) {\n\n self.potential += value;\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn process_potential(&mut self, delta_time_times_decay: Scalar) {\n\n if self.potential < -delta_time_times_decay {\n\n self.potential = (self.potential + delta_time_times_decay).min(0.0);\n\n } else if self.potential > delta_time_times_decay {\n\n self.potential = (self.potential - delta_time_times_decay).max(0.0);\n\n } else {\n\n self.potential = 0.0;\n\n }\n\n }\n\n\n\n #[inline]\n\n pub(crate) fn fire(&mut self) {\n\n self.potential = 0.0;\n\n }\n\n}\n", "file_path": "psyche-core/src/neuron.rs", "rank": 81, "score": 37042.897312562105 }, { "content": "use crate::Scalar;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::ops::Range;\n\n\n\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\n#[repr(C)]\n\npub struct Config {\n\n pub propagation_speed: Scalar,\n\n pub neuron_potential_decay: Scalar,\n\n pub action_potential_treshold: Scalar,\n\n pub receptors_excitation: Scalar,\n\n pub receptors_inhibition: Scalar,\n\n pub default_receptors: Range<Scalar>,\n\n pub synapse_inactivity_time: Scalar,\n\n pub synapse_reconnection_range: Option<Scalar>,\n\n pub synapse_overdose_receptors: Option<Scalar>,\n\n pub synapse_propagation_decay: Scalar,\n\n pub synapse_new_connection_receptors: Option<Scalar>,\n\n}\n\n\n", "file_path": "psyche-core/src/config.rs", "rank": 82, "score": 36948.22665592964 }, { "content": "impl Default for Config {\n\n fn default() -> Self {\n\n Self {\n\n propagation_speed: 1.0,\n\n neuron_potential_decay: 1.0,\n\n action_potential_treshold: 1.0,\n\n receptors_excitation: 1.0,\n\n receptors_inhibition: 0.05,\n\n default_receptors: 0.5..1.5,\n\n synapse_inactivity_time: 0.05,\n\n synapse_reconnection_range: None,\n\n synapse_overdose_receptors: None,\n\n synapse_propagation_decay: 0.0,\n\n synapse_new_connection_receptors: None,\n\n }\n\n }\n\n}\n\n\n\nimpl Config {\n\n pub fn merge(&self, other: &Self) -> Self {\n", "file_path": "psyche-core/src/config.rs", "rank": 83, "score": 36943.718621734515 }, { "content": " (Some(a), None) => Some(a),\n\n (None, Some(b)) => Some(b),\n\n _ => None,\n\n },\n\n synapse_propagation_decay: merge_scalar(\n\n self.synapse_propagation_decay,\n\n other.synapse_propagation_decay,\n\n ),\n\n synapse_new_connection_receptors: match (\n\n self.synapse_new_connection_receptors,\n\n other.synapse_new_connection_receptors,\n\n ) {\n\n (Some(a), Some(b)) => Some(merge_scalar(a, b)),\n\n (Some(a), None) => Some(a),\n\n (None, Some(b)) => Some(b),\n\n _ => None,\n\n },\n\n }\n\n }\n\n}\n\n\n", "file_path": "psyche-core/src/config.rs", "rank": 84, "score": 36932.56070558997 }, { "content": " Self {\n\n propagation_speed: merge_scalar(self.propagation_speed, other.propagation_speed),\n\n neuron_potential_decay: merge_scalar(\n\n self.neuron_potential_decay,\n\n other.neuron_potential_decay,\n\n ),\n\n action_potential_treshold: merge_scalar(\n\n self.action_potential_treshold,\n\n other.action_potential_treshold,\n\n ),\n\n receptors_excitation: merge_scalar(\n\n self.receptors_excitation,\n\n other.receptors_excitation,\n\n ),\n\n receptors_inhibition: merge_scalar(\n\n self.receptors_inhibition,\n\n other.receptors_inhibition,\n\n ),\n\n default_receptors: Range {\n\n start: merge_scalar(self.default_receptors.start, other.default_receptors.start),\n", "file_path": "psyche-core/src/config.rs", "rank": 85, "score": 36930.47245167529 }, { "content": " end: merge_scalar(self.default_receptors.end, other.default_receptors.end),\n\n },\n\n synapse_inactivity_time: merge_scalar(\n\n self.synapse_inactivity_time,\n\n other.synapse_inactivity_time,\n\n ),\n\n synapse_reconnection_range: match (\n\n self.synapse_reconnection_range,\n\n other.synapse_reconnection_range,\n\n ) {\n\n (Some(a), Some(b)) => Some(merge_scalar(a, b)),\n\n (Some(a), None) => Some(a),\n\n (None, Some(b)) => Some(b),\n\n _ => None,\n\n },\n\n synapse_overdose_receptors: match (\n\n self.synapse_overdose_receptors,\n\n other.synapse_overdose_receptors,\n\n ) {\n\n (Some(a), Some(b)) => Some(merge_scalar(a, b)),\n", "file_path": "psyche-core/src/config.rs", "rank": 86, "score": 36924.36142437226 }, { "content": "}\n\n\n\n#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]\n\npub struct Brain {\n\n id: BrainID,\n\n neurons: Vec<Neuron>,\n\n synapses: Vec<Synapse>,\n\n sensors: Vec<Sensor>,\n\n effectors: Vec<Effector>,\n\n config: Config,\n\n new_connections_accum: Scalar,\n\n}\n\n\n\nimpl Brain {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n pub fn duplicate(&self) -> Self {\n\n let id = Default::default();\n", "file_path": "psyche-core/src/brain.rs", "rank": 87, "score": 35585.08810147877 }, { "content": " pub const NONE: usize = 0;\n\n pub const CONNECTIONS: usize = 1;\n\n pub const IMPULSES: usize = 1 << 1;\n\n pub const SENSORS: usize = 1 << 2;\n\n pub const EFFECTORS: usize = 1 << 3;\n\n pub const NEURONS: usize = 1 << 4;\n\n pub const ALL: usize = 0xFF;\n\n}\n\n\n\npub type BrainID = ID<Brain>;\n\n\n\n#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]\n\n#[repr(C)]\n\npub struct BrainActivityMap {\n\n // (point from, point to, receptors)\n\n pub connections: Vec<(Position, Position, Scalar)>,\n\n // (point from, point to, factor)\n\n pub impulses: Vec<(Position, Position, Scalar)>,\n\n // point\n\n pub sensors: Vec<Position>,\n", "file_path": "psyche-core/src/brain.rs", "rank": 88, "score": 35574.663963596104 }, { "content": " .collect::<Vec<_>>();\n\n Self {\n\n id,\n\n neurons,\n\n synapses,\n\n sensors,\n\n effectors,\n\n config: self.config.clone(),\n\n new_connections_accum: 0.0,\n\n }\n\n }\n\n\n\n pub fn merge(&self, other: &Self) -> Self {\n\n let mut rng = thread_rng();\n\n let id = Default::default();\n\n let brain_a = self.duplicate();\n\n let brain_b = other.duplicate();\n\n let neurons_count = (brain_a.neurons.len() + brain_b.neurons.len()) / 2;\n\n let synapses_count = (brain_a.synapses.len() + brain_b.synapses.len()) / 2;\n\n let sensors_count = (brain_a.sensors.len() + brain_b.sensors.len()) / 2;\n", "file_path": "psyche-core/src/brain.rs", "rank": 89, "score": 35573.5961040063 }, { "content": " .effectors\n\n .iter()\n\n .chain(brain_b.effectors.iter())\n\n .cloned()\n\n .collect();\n\n let mut brain = Self {\n\n id,\n\n neurons,\n\n synapses,\n\n sensors,\n\n effectors,\n\n config: brain_a.config().merge(brain_b.config()),\n\n new_connections_accum: 0.0,\n\n };\n\n while brain.neurons.len() > neurons_count {\n\n if brain\n\n .kill_neuron(\n\n brain.neurons[rng.gen_range(0, brain.neurons.len()) % brain.neurons.len()].id(),\n\n )\n\n .is_err()\n", "file_path": "psyche-core/src/brain.rs", "rank": 90, "score": 35570.37720313525 }, { "content": " .collect::<Vec<_>>();\n\n for (index, from, to) in synapses_to_connect.into_iter().rev() {\n\n if let Some(receptors) = self.bind_neurons(from, to)? {\n\n self.synapses[index].receptors -= receptors;\n\n }\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn select_neuron<R>(&self, position: Position, rng: &mut R) -> Option<NeuronID>\n\n where\n\n R: Rng,\n\n {\n\n let srr = self.config.synapse_reconnection_range;\n\n let filtered = iter!(self.neurons)\n\n .filter_map(|neuron| {\n\n if iter!(self.sensors).any(|s| s.target == neuron.id()) {\n\n return None;\n", "file_path": "psyche-core/src/brain.rs", "rank": 91, "score": 35567.764465662556 }, { "content": "use crate::config::Config;\n\nuse crate::effector::{Effector, EffectorID};\n\nuse crate::error::*;\n\nuse crate::id::ID;\n\nuse crate::neuron::{Impulse, Neuron, NeuronID, Position, Synapse};\n\nuse crate::sensor::{Sensor, SensorID};\n\nuse crate::Scalar;\n\nuse rand::{thread_rng, Rng};\n\n#[cfg(feature = \"parallel\")]\n\nuse rayon::prelude::*;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::ops::Range;\n\n\n\n#[cfg(feature = \"parallel\")]\n\nmacro_rules! iter {\n\n ($v:expr) => {\n\n $v.par_iter()\n\n };\n\n}\n\n#[cfg(not(feature = \"parallel\"))]\n", "file_path": "psyche-core/src/brain.rs", "rank": 92, "score": 35565.93837016581 }, { "content": " while let Some(index) = index {\n\n self.sensors.swap_remove(index);\n\n }\n\n #[cfg(feature = \"parallel\")]\n\n let index = self.effectors.par_iter().position_any(|e| e.source == id);\n\n #[cfg(not(feature = \"parallel\"))]\n\n let index = self.effectors.iter().position(|e| e.source == id);\n\n while let Some(index) = index {\n\n self.effectors.swap_remove(index);\n\n }\n\n Ok(())\n\n } else {\n\n Err(Error::NeuronDoesNotExists(id))\n\n }\n\n }\n\n\n\n pub fn bind_neurons(&mut self, from: NeuronID, to: NeuronID) -> Result<Option<Scalar>> {\n\n if from == to {\n\n return Err(Error::BindingNeuronToItSelf(from));\n\n }\n", "file_path": "psyche-core/src/brain.rs", "rank": 93, "score": 35564.0372529981 }, { "content": "\n\n pub fn unbind_neurons(&mut self, from: NeuronID, to: NeuronID) -> Result<bool> {\n\n if from == to {\n\n return Err(Error::UnbindingNeuronFromItSelf(from));\n\n }\n\n if iter!(self.neurons).any(|n| n.id() == from) {\n\n if iter!(self.neurons).any(|n| n.id() == to) {\n\n #[cfg(feature = \"parallel\")]\n\n let index = self\n\n .synapses\n\n .par_iter()\n\n .position_any(|s| s.source == from && s.target == to);\n\n #[cfg(not(feature = \"parallel\"))]\n\n let index = self\n\n .synapses\n\n .iter()\n\n .position(|s| s.source == from && s.target == to);\n\n if let Some(index) = index {\n\n self.synapses.swap_remove(index);\n\n Ok(true)\n", "file_path": "psyche-core/src/brain.rs", "rank": 94, "score": 35561.69636624825 }, { "content": " vec![]\n\n };\n\n let effectors = if flags & activity::EFFECTORS != 0 {\n\n iter!(self.effectors)\n\n .map(|e| self.neuron(e.source).unwrap().position())\n\n .collect()\n\n } else {\n\n vec![]\n\n };\n\n let neurons = if flags & activity::NEURONS != 0 {\n\n iter!(self.neurons).map(|n| n.position()).collect()\n\n } else {\n\n vec![]\n\n };\n\n\n\n BrainActivityMap {\n\n connections,\n\n impulses,\n\n sensors,\n\n effectors,\n", "file_path": "psyche-core/src/brain.rs", "rank": 95, "score": 35561.55072163149 }, { "content": " let effectors_count = (brain_a.effectors.len() + brain_b.effectors.len()) / 2;\n\n let neurons = brain_a\n\n .neurons\n\n .iter()\n\n .chain(brain_b.neurons.iter())\n\n .map(|n| Neuron::with_id(n.id(), id, n.position()))\n\n .collect();\n\n let synapses = brain_a\n\n .synapses\n\n .iter()\n\n .chain(brain_b.synapses.iter())\n\n .cloned()\n\n .collect();\n\n let sensors = brain_a\n\n .sensors\n\n .iter()\n\n .chain(brain_b.sensors.iter())\n\n .cloned()\n\n .collect();\n\n let effectors = brain_a\n", "file_path": "psyche-core/src/brain.rs", "rank": 96, "score": 35561.12693454068 }, { "content": "\n\n pub fn effector_potential_release(&mut self, id: EffectorID) -> Result<Scalar> {\n\n #[cfg(feature = \"parallel\")]\n\n let effector = self.effectors.par_iter_mut().find_any(|e| e.id == id);\n\n #[cfg(not(feature = \"parallel\"))]\n\n let effector = self.effectors.iter_mut().find(|e| e.id == id);\n\n if let Some(effector) = effector {\n\n let potential = effector.potential;\n\n effector.potential = 0.0;\n\n Ok(potential)\n\n } else {\n\n Err(Error::EffectorDoesNotExists(id))\n\n }\n\n }\n\n\n\n pub fn create_neuron(&mut self, position: Position) -> NeuronID {\n\n let neuron = Neuron::new(self.id, position);\n\n let id = neuron.id();\n\n self.neurons.push(neuron);\n\n id\n", "file_path": "psyche-core/src/brain.rs", "rank": 97, "score": 35560.705268307574 }, { "content": " id: s.id,\n\n target: neurons[index].id(),\n\n }\n\n })\n\n .collect::<Vec<_>>();\n\n let effectors = iter!(self.effectors)\n\n .map(|e| {\n\n #[cfg(feature = \"parallel\")]\n\n let index = neuron_indices\n\n .par_iter()\n\n .position_any(|n| *n == e.source)\n\n .unwrap();\n\n #[cfg(not(feature = \"parallel\"))]\n\n let index = neuron_indices.iter().position(|n| *n == e.source).unwrap();\n\n Effector {\n\n id: e.id,\n\n source: neurons[index].id(),\n\n potential: 0.0,\n\n }\n\n })\n", "file_path": "psyche-core/src/brain.rs", "rank": 98, "score": 35560.42174363956 }, { "content": " // point\n\n pub effectors: Vec<Position>,\n\n // point\n\n pub neurons: Vec<Position>,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\n#[repr(C)]\n\npub struct BrainActivityStats {\n\n pub neurons_count: usize,\n\n pub synapses_count: usize,\n\n pub impulses_count: usize,\n\n // (current, min..max)\n\n pub neurons_potential: (Scalar, Range<Scalar>),\n\n // (current, min..max)\n\n pub impulses_potential: (Scalar, Range<Scalar>),\n\n // (current, min..max)\n\n pub all_potential: (Scalar, Range<Scalar>),\n\n // min..max\n\n pub incoming_neuron_connections: Range<usize>,\n", "file_path": "psyche-core/src/brain.rs", "rank": 99, "score": 35559.967190002215 } ]
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 .collect();\n\n\n\n #[rustfmt::skip]\n\n let expected = vec![\n\n (0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), //\n\n (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), //\n\n (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2), //\n\n (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), //\n\n (0, 4), (1, 4), (2, 4), (3, 4), (4, 4), (5, 4), (6, 4), (7, 4), //\n\n (0, 5), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), (7, 5), //\n\n (0, 6), (1, 6), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), (7, 6), //\n\n (0, 7), (1, 7), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (7, 7), ];\n\n\n\n assert_eq!(pixels, expected);\n\n}\n", "file_path": "tests/coordinates.rs", "rank": 14, "score": 52094.64612502625 }, { "content": "#[test]\n\nfn chessboard_8px_1bit() {\n\n let bmp =\n\n RawBmp::from_slice(include_bytes!(\"./chessboard-8px-1bit.bmp\")).expect(\"Failed to parse\");\n\n\n\n assert_eq!(\n\n bmp.header(),\n\n &Header {\n\n file_size: 94,\n\n image_data_start: 62,\n\n bpp: Bpp::Bits1,\n\n image_size: Size::new(8, 8),\n\n image_data_len: 32,\n\n channel_masks: None,\n\n }\n\n );\n\n\n\n assert_eq!(bmp.image_data().len(), 94 - 62);\n\n}\n\n\n", "file_path": "tests/chessboard-8px-1bit.rs", "rank": 18, "score": 44637.95435036547 }, { "content": "#[test]\n\nfn chessboard_8px_24bit() {\n\n let bmp = RawBmp::from_slice(DATA).expect(\"Failed to parse\");\n\n\n\n assert_eq!(\n\n bmp.header(),\n\n &Header {\n\n file_size: 314,\n\n image_data_start: 122,\n\n bpp: Bpp::Bits24,\n\n image_size: Size::new(8, 8),\n\n image_data_len: 192,\n\n channel_masks: None,\n\n }\n\n );\n\n\n\n assert_eq!(bmp.image_data().len(), 314 - 122);\n\n}\n\n\n", "file_path": "tests/chessboard-8px-24bit.rs", "rank": 19, "score": 44637.95435036547 }, { "content": "#[test]\n\nfn chessboard_8px_1bit_iter() {\n\n let bmp =\n\n RawBmp::from_slice(include_bytes!(\"./chessboard-8px-1bit.bmp\")).expect(\"Failed to parse\");\n\n\n\n let pixels: Vec<u32> = bmp.pixels().map(|pixel| pixel.color).collect();\n\n\n\n // 8px x 8px image. Check that iterator returns all pixels in it\n\n assert_eq!(pixels.len(), 8 * 8);\n\n\n\n let expected = vec![\n\n 1, 1, 0, 0, 1, 1, 0, 0, //\n\n 1, 1, 0, 0, 1, 1, 0, 0, //\n\n 0, 0, 1, 1, 0, 0, 1, 1, //\n\n 0, 0, 1, 1, 0, 0, 1, 1, //\n\n 1, 1, 0, 0, 1, 1, 0, 0, //\n\n 1, 1, 0, 0, 1, 1, 0, 0, //\n\n 0, 0, 1, 1, 0, 0, 1, 1, //\n\n 0, 0, 1, 1, 0, 0, 1, 1, //\n\n ];\n\n\n\n assert_eq!(pixels, expected);\n\n}\n", "file_path": "tests/chessboard-8px-1bit.rs", "rank": 20, "score": 43138.71173790787 }, { "content": "#[test]\n\nfn chessboard_8px_24bit_iter() {\n\n let bmp = RawBmp::from_slice(DATA).expect(\"Failed to parse\");\n\n\n\n let pixels: Vec<u32> = bmp.pixels().map(|pixel| pixel.color).collect();\n\n\n\n assert_eq!(pixels.len(), 8 * 8);\n\n\n\n // 24BPP black/white chessboard\n\n let expected = vec![\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n ];\n\n\n\n assert_eq!(pixels, expected);\n\n}\n", "file_path": "tests/chessboard-8px-24bit.rs", "rank": 21, "score": 43138.71173790787 }, { "content": "#[test]\n\nfn chessboard_8px_24bit_truncated_iter() {\n\n // corrupt data by removing the last 10 bytes\n\n let truncated_data = &DATA[..DATA.len() - 10];\n\n\n\n let bmp = RawBmp::from_slice(truncated_data).expect(\"Failed to parse\");\n\n\n\n assert_eq!(\n\n bmp.header(),\n\n &Header {\n\n file_size: 314,\n\n image_data_start: 122,\n\n bpp: Bpp::Bits24,\n\n image_size: Size::new(8, 8),\n\n image_data_len: 192,\n\n channel_masks: None,\n\n }\n\n );\n\n\n\n let pixels: Vec<u32> = bmp.pixels().map(|pixel| pixel.color).collect();\n\n\n", "file_path": "tests/chessboard-8px-24bit.rs", "rank": 23, "score": 41752.442629499594 }, { "content": "#[test]\n\nfn chessboard_8px_color_16bit() {\n\n let bmp = RawBmp::from_slice(include_bytes!(\"./chessboard-8px-color-16bit.bmp\"))\n\n .expect(\"Failed to parse\");\n\n\n\n assert_eq!(\n\n bmp.header(),\n\n &Header {\n\n file_size: 266,\n\n image_data_start: 138,\n\n bpp: Bpp::Bits16,\n\n image_size: Size::new(8, 8),\n\n image_data_len: 128,\n\n channel_masks: Some(ChannelMasks::RGB565)\n\n }\n\n );\n\n\n\n assert_eq!(bmp.image_data().len(), 266 - 138);\n\n}\n\n\n", "file_path": "tests/chessboard-8px-color-16bit.rs", "rank": 24, "score": 41752.442629499594 }, { "content": "#[test]\n\nfn chessboard_8px_color_16bit_iter() {\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<u32> = bmp.pixels().map(|pixel| pixel.color).collect();\n\n\n\n // 8px x 8px image. Check that iterator returns all pixels in it\n\n assert_eq!(pixels.len(), 8 * 8);\n\n\n\n let expected = vec![\n\n 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, //\n\n 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, //\n\n 0x0000, 0x0000, 0xf800, 0xf800, 0x0000, 0x0000, 0x07e0, 0x07e0, //\n\n 0x0000, 0x0000, 0xf800, 0xf800, 0x0000, 0x0000, 0x07e0, 0x07e0, //\n\n 0xffff, 0xffff, 0x0000, 0x0000, 0x001f, 0x001f, 0x0000, 0x0000, //\n\n 0xffff, 0xffff, 0x0000, 0x0000, 0x001f, 0x001f, 0x0000, 0x0000, //\n\n 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, //\n\n 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, //\n\n ];\n\n\n\n assert_eq!(pixels, expected);\n\n}\n", "file_path": "tests/chessboard-8px-color-16bit.rs", "rank": 25, "score": 40466.84120938445 }, { "content": " pub fn as_raw(&self) -> &RawBmp<'a> {\n\n &self.raw_bmp\n\n }\n\n}\n\n\n\nimpl<C> ImageDrawable for DynamicBmp<'_, C>\n\nwhere\n\n C: PixelColor + From<Rgb555> + From<Rgb565> + From<Rgb888> + From<Gray8>,\n\n{\n\n type Color = C;\n\n\n\n fn draw<D>(&self, target: &mut D) -> Result<(), D::Error>\n\n where\n\n D: DrawTarget<Color = C>,\n\n {\n\n match self.color_type {\n\n ColorType::Rgb555 => self.raw_bmp.draw(&mut target.color_converted::<Rgb555>()),\n\n ColorType::Rgb565 => self.raw_bmp.draw(&mut target.color_converted::<Rgb565>()),\n\n ColorType::Rgb888 => self.raw_bmp.draw(&mut target.color_converted::<Rgb888>()),\n\n ColorType::Gray8 => self.raw_bmp.draw(&mut target.color_converted::<Gray8>()),\n", "file_path": "src/dynamic_bmp.rs", "rank": 26, "score": 24577.311018383654 }, { "content": "use core::marker::PhantomData;\n\nuse embedded_graphics::{\n\n pixelcolor::{Gray8, PixelColor, Rgb555, Rgb565, Rgb888},\n\n prelude::*,\n\n primitives::Rectangle,\n\n};\n\n\n\nuse crate::{\n\n header::{Bpp, ChannelMasks},\n\n raw_bmp::RawBmp,\n\n ParseError,\n\n};\n\n\n\n/// Dynamic BMP image.\n\n///\n\n/// `DynamicBmp` is used to draw images that don't have a known color type at compile time,\n\n/// for example user supplied images. If the color type is known at compile time consider using\n\n/// [`Bmp`] for improved performance.\n\n///\n\n/// `DynamicBmp` works for all embedded-graphics draw targets that use a color type that implements\n", "file_path": "src/dynamic_bmp.rs", "rank": 27, "score": 24575.88729409664 }, { "content": "/// `From` for `Rgb555, `Rgb565`, `Rgb888` and `Gray8`, like every `Rgb...` and `Bgr...` type\n\n/// included in embedded-graphics.\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct DynamicBmp<'a, C> {\n\n raw_bmp: RawBmp<'a>,\n\n color_type: ColorType,\n\n target_color_type: PhantomData<C>,\n\n}\n\n\n\nimpl<'a, C> DynamicBmp<'a, C>\n\nwhere\n\n C: PixelColor + From<Rgb555> + From<Rgb565> + From<Rgb888> + From<Gray8>,\n\n{\n\n /// Creates a bitmap object from a byte slice.\n\n pub fn from_slice(bytes: &'a [u8]) -> Result<Self, ParseError> {\n\n let raw_bmp = RawBmp::from_slice(bytes)?;\n\n\n\n let color_type = match raw_bmp.color_bpp() {\n\n Bpp::Bits1 => return Err(ParseError::UnsupportedDynamicBmpFormat),\n\n Bpp::Bits8 => ColorType::Gray8,\n", "file_path": "src/dynamic_bmp.rs", "rank": 28, "score": 24572.89802436063 }, { "content": "use embedded_graphics::{prelude::*, primitives::Rectangle};\n\n\n\nuse crate::{\n\n header::{Bpp, Header},\n\n pixels::Pixels,\n\n raw_pixels::RawPixels,\n\n ParseError,\n\n};\n\n\n\n/// A BMP-format bitmap.\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct RawBmp<'a> {\n\n /// Image header.\n\n header: Header,\n\n\n\n /// Image data.\n\n image_data: &'a [u8],\n\n}\n\n\n\nimpl<'a> RawBmp<'a> {\n", "file_path": "src/raw_bmp.rs", "rank": 29, "score": 24571.125454956396 }, { "content": " Bpp::Bits16 => {\n\n if let Some(masks) = raw_bmp.header().channel_masks {\n\n match masks {\n\n ChannelMasks::RGB555 => ColorType::Rgb555,\n\n ChannelMasks::RGB565 => ColorType::Rgb565,\n\n _ => return Err(ParseError::UnsupportedDynamicBmpFormat),\n\n }\n\n } else {\n\n // According to the GDI docs the default 16 bpp color format is Rgb555 if no\n\n // color masks are defined:\n\n // https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader\n\n ColorType::Rgb555\n\n }\n\n }\n\n Bpp::Bits24 => ColorType::Rgb888,\n\n Bpp::Bits32 => {\n\n if let Some(masks) = raw_bmp.header().channel_masks {\n\n if masks == ChannelMasks::RGB888 {\n\n ColorType::Rgb888\n\n } else {\n", "file_path": "src/dynamic_bmp.rs", "rank": 30, "score": 24569.937149390455 }, { "content": " }\n\n }\n\n\n\n fn draw_sub_image<D>(&self, target: &mut D, area: &Rectangle) -> Result<(), D::Error>\n\n where\n\n D: DrawTarget<Color = Self::Color>,\n\n {\n\n self.draw(&mut target.translated(-area.top_left).clipped(area))\n\n }\n\n}\n\n\n\nimpl<C> OriginDimensions for DynamicBmp<'_, C>\n\nwhere\n\n C: PixelColor,\n\n{\n\n fn size(&self) -> Size {\n\n self.raw_bmp.size()\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n", "file_path": "src/dynamic_bmp.rs", "rank": 31, "score": 24569.108460003234 }, { "content": " return Err(ParseError::UnsupportedDynamicBmpFormat);\n\n }\n\n } else {\n\n ColorType::Rgb888\n\n }\n\n }\n\n };\n\n\n\n Ok(Self {\n\n raw_bmp,\n\n color_type,\n\n target_color_type: PhantomData,\n\n })\n\n }\n\n\n\n /// Returns a reference to the raw BMP image.\n\n ///\n\n /// The [`RawBmp`] instance can be used to access lower level information about the BMP file.\n\n ///\n\n /// [`RawBmp`]: struct.RawBmp.html\n", "file_path": "src/dynamic_bmp.rs", "rank": 32, "score": 24568.735557010816 }, { "content": " ///\n\n /// The iterator returns the raw pixel colors as `u32` values. To automatically convert the raw\n\n /// values into the color specified by `C` use [`pixels`] instead.\n\n ///\n\n /// [`pixels`]: #method.pixels\n\n pub fn pixels<'b>(&'b self) -> RawPixels<'b, 'a> {\n\n RawPixels::new(self)\n\n }\n\n\n\n /// Returns the row length in bytes.\n\n ///\n\n /// Each row in a BMP file is a multiple of 4 bytes long.\n\n pub(crate) fn bytes_per_row(&self) -> usize {\n\n let bits_per_row =\n\n self.header.image_size.width as usize * usize::from(self.header.bpp.bits());\n\n\n\n (bits_per_row + 31) / 32 * (32 / 8)\n\n }\n\n\n\n pub(crate) fn draw<D>(&self, target: &mut D) -> Result<(), D::Error>\n", "file_path": "src/raw_bmp.rs", "rank": 33, "score": 24567.300857327922 }, { "content": " pub fn size(&self) -> Size {\n\n self.header.image_size\n\n }\n\n\n\n /// Returns the BPP (bits per pixel) for this image.\n\n pub fn color_bpp(&self) -> Bpp {\n\n self.header.bpp\n\n }\n\n\n\n /// Returns a slice containing the raw image data.\n\n pub fn image_data(&self) -> &'a [u8] {\n\n self.image_data\n\n }\n\n\n\n /// Returns a reference to the BMP header.\n\n pub fn header(&self) -> &Header {\n\n &self.header\n\n }\n\n\n\n /// Returns an iterator over the raw pixels in the image.\n", "file_path": "src/raw_bmp.rs", "rank": 34, "score": 24567.004807837973 }, { "content": " /// Create a bitmap object from a byte slice.\n\n ///\n\n /// The created object keeps a shared reference to the input and does not dynamically allocate\n\n /// memory.\n\n ///\n\n /// In contrast to the [`from_slice`] constructor no color type needs to be specified when\n\n /// calling this method. This will disable all functions that requires a specified color type,\n\n /// like the [`pixels`] method.\n\n ///\n\n /// [`from_slice`]: #method.from_slice\n\n /// [`pixels`]: #method.pixels\n\n pub fn from_slice(bytes: &'a [u8]) -> Result<Self, ParseError> {\n\n let (_remaining, header) = Header::parse(bytes).map_err(|_| ParseError::Header)?;\n\n\n\n let image_data = &bytes[header.image_data_start..];\n\n\n\n Ok(Self { header, image_data })\n\n }\n\n\n\n /// Returns the size of this image in pixels.\n", "file_path": "src/raw_bmp.rs", "rank": 35, "score": 24564.534647715678 }, { "content": " where\n\n D: DrawTarget,\n\n D::Color: From<<D::Color as PixelColor>::Raw>,\n\n {\n\n target.fill_contiguous(\n\n &Rectangle::new(Point::zero(), self.size()),\n\n Pixels::new(self.pixels()).map(|Pixel(_, color)| color),\n\n )\n\n }\n\n}\n", "file_path": "src/raw_bmp.rs", "rank": 36, "score": 24560.63952344068 }, { "content": "use tinybmp::RawBmp;\n\n\n\n#[test]\n", "file_path": "tests/coordinates.rs", "rank": 37, "score": 23692.867280829803 }, { "content": "#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\nenum ColorType {\n\n Rgb555,\n\n Rgb565,\n\n Rgb888,\n\n Gray8,\n\n}\n", "file_path": "src/dynamic_bmp.rs", "rank": 39, "score": 22381.49000061466 }, { "content": "use embedded_graphics::prelude::*;\n\nuse tinybmp::{Bpp, Header, RawBmp};\n\n\n\nconst DATA: &[u8] = include_bytes!(\"./chessboard-8px-24bit.bmp\");\n\n\n\n#[test]\n", "file_path": "tests/chessboard-8px-24bit.rs", "rank": 40, "score": 21498.16699879838 }, { "content": "use embedded_graphics::prelude::*;\n\nuse tinybmp::{Bpp, Header, RawBmp};\n\n\n\n#[test]\n", "file_path": "tests/chessboard-8px-1bit.rs", "rank": 41, "score": 21496.261279210128 }, { "content": " assert_eq!(pixels.len(), 8 * 8);\n\n\n\n // 24BPP black/white chessboard.\n\n // Because BMP files are stored bottom line first the truncated data shows up as\n\n // zeroes in the top image row.\n\n let expected = vec![\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, //\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n 0x000000, 0x000000, 0xffffff, 0xffffff, 0x000000, 0x000000, 0xffffff, 0xffffff, //\n\n ];\n\n\n\n assert_eq!(pixels, expected);\n\n}\n\n\n", "file_path": "tests/chessboard-8px-24bit.rs", "rank": 42, "score": 21488.06909903849 }, { "content": "use embedded_graphics::prelude::*;\n\nuse tinybmp::{Bpp, ChannelMasks, Header, RawBmp};\n\n\n\n#[test]\n", "file_path": "tests/chessboard-8px-color-16bit.rs", "rank": 43, "score": 20542.81220125727 }, { "content": "//! ```rust\n\n//! # fn main() -> Result<(), core::convert::Infallible> {\n\n//! use embedded_graphics::{image::Image, prelude::*};\n\n//! use tinybmp::DynamicBmp;\n\n//! # use embedded_graphics::mock_display::MockDisplay;\n\n//! # use embedded_graphics::pixelcolor::Rgb565;\n\n//! # let mut display: MockDisplay<Rgb565> = MockDisplay::default();\n\n//!\n\n//! let bmp_data = include_bytes!(\"../tests/chessboard-8px-color-16bit.bmp\");\n\n//!\n\n//! // Load BMP image with unknown color format.\n\n//! // Note: There is no need to explicitly specify the color type.\n\n//! let bmp = DynamicBmp::from_slice(bmp_data).unwrap();\n\n//!\n\n//! // Draw the image with the top left corner at (10, 20) by wrapping it in\n\n//! // an embedded-graphics `Image`.\n\n//! Image::new(&bmp, Point::new(10, 20)).draw(&mut display)?;\n\n//! # Ok::<(), core::convert::Infallible>(()) }\n\n//! ```\n\n//!\n", "file_path": "src/lib.rs", "rank": 44, "score": 18.312675173398468 }, { "content": "//! # let mut display: MockDisplay<Rgb565> = MockDisplay::default();\n\n//!\n\n//! let bmp_data = include_bytes!(\"../tests/chessboard-8px-color-16bit.bmp\");\n\n//!\n\n//! // Load 16 BPP 8x8px image.\n\n//! // Note: The color type is specified explicitly to match the format used by the BMP image.\n\n//! let bmp = Bmp::<Rgb565>::from_slice(bmp_data).unwrap();\n\n//!\n\n//! // Draw the image with the top left corner at (10, 20) by wrapping it in\n\n//! // an embedded-graphics `Image`.\n\n//! Image::new(&bmp, Point::new(10, 20)).draw(&mut display)?;\n\n//! # Ok::<(), core::convert::Infallible>(()) }\n\n//! ```\n\n//!\n\n//! ## Using `DynamicBmp` to draw a BMP image\n\n//!\n\n//! If the exact color format used in the BMP file isn't known at compile time, for example to read\n\n//! user supplied images, the [`DynamicBmp`] can be used. Because automatic color conversion will\n\n//! be used the drawing performance might be degraded in comparison to [`Bmp`].\n\n//!\n", "file_path": "src/lib.rs", "rank": 45, "score": 15.418900493583617 }, { "content": "//! A small BMP parser designed for embedded, no-std environments but usable anywhere. Beyond\n\n//! parsing the image header, no other allocations are made.\n\n//!\n\n//! To use `tinybmp` without [`embedded-graphics`] the raw data for individual pixels in an image\n\n//! can be accessed using the methods provided by the [`RawBmp`] struct.\n\n//!\n\n//! # Examples\n\n//!\n\n//! ## Using `Bmp` to draw a BMP image\n\n//!\n\n//! If the color format inside the BMP file is known at compile time the [`Bmp`] type can be used\n\n//! to draw an image to an [`embedded-graphics`] draw target. The BMP file used in this example\n\n//! uses 16 bits per pixel with a RGB565 format.\n\n//!\n\n//! ```rust\n\n//! # fn main() -> Result<(), core::convert::Infallible> {\n\n//! use embedded_graphics::{image::Image, prelude::*};\n\n//! use tinybmp::Bmp;\n\n//! # use embedded_graphics::mock_display::MockDisplay;\n\n//! # use embedded_graphics::pixelcolor::Rgb565;\n", "file_path": "src/lib.rs", "rank": 46, "score": 14.495423905801136 }, { "content": "### Using `DynamicBmp` to draw a BMP image\n\n\n\nIf the exact color format used in the BMP file isn't known at compile time, for example to read\n\nuser supplied images, the `DynamicBmp` can be used. Because automatic color conversion will\n\nbe used the drawing performance might be degraded in comparison to `Bmp`.\n\n\n\n```rust\n\nuse embedded_graphics::{image::Image, prelude::*};\n\nuse tinybmp::DynamicBmp;\n\n\n\nlet bmp_data = include_bytes!(\"../tests/chessboard-8px-color-16bit.bmp\");\n\n\n\n// Load BMP image with unknown color format.\n\n// Note: There is no need to explicitly specify the color type.\n\nlet bmp = DynamicBmp::from_slice(bmp_data).unwrap();\n\n\n\n// Draw the image with the top left corner at (10, 20) by wrapping it in\n\n// an embedded-graphics `Image`.\n\nImage::new(&bmp, Point::new(10, 20)).draw(&mut display)?;\n\n```\n\n\n\n### Accessing the raw image data\n\n\n\nThe `RawBmp` struct provides methods to access lower level information about a BMP file,\n\nlike the BMP header or the raw image data. An instance of this type can be created by using\n\n`from_slice` or by accessing the underlying raw object of a `Bmp` or `DynamicBmp` object\n\nby using `as_raw`.\n\n\n\n```rust\n\nuse embedded_graphics::prelude::*;\n\nuse tinybmp::{RawBmp, Bpp, Header, RawPixel};\n\n\n\nlet bmp = RawBmp::from_slice(include_bytes!(\"../tests/chessboard-8px-24bit.bmp\"))\n\n .expect(\"Failed to parse BMP image\");\n\n\n\n// Read the BMP header\n\nassert_eq!(\n\n bmp.header(),\n\n &Header {\n\n file_size: 314,\n\n image_data_start: 122,\n\n bpp: Bpp::Bits24,\n\n image_size: Size::new(8, 8),\n\n image_data_len: 192,\n\n channel_masks: None,\n\n }\n\n);\n\n\n\n// Check that raw image data slice is the correct length (according to parsed header)\n\nassert_eq!(bmp.image_data().len(), bmp.header().image_data_len as usize);\n\n\n\n// Get an iterator over the pixel coordinates and values in this image and load into a vec\n\nlet pixels: Vec<RawPixel> = bmp.pixels().collect();\n\n\n\n// Loaded example image is 8x8px\n\nassert_eq!(pixels.len(), 8 * 8);\n\n```\n\n\n\n[`embedded-graphics`]: https://crates.io/crates/embedded-graphics\n\n\n", "file_path": "README.md", "rank": 47, "score": 12.908490195458509 }, { "content": "# TinyBMP\n\n\n\n[![Build Status](https://circleci.com/gh/embedded-graphics/tinybmp/tree/master.svg?style=shield)](https://circleci.com/gh/embedded-graphics/tinybmp/tree/master)\n\n[![Crates.io](https://img.shields.io/crates/v/tinybmp.svg)](https://crates.io/crates/tinybmp)\n\n[![Docs.rs](https://docs.rs/tinybmp/badge.svg)](https://docs.rs/tinybmp)\n\n[![embedded-graphics on Matrix](https://img.shields.io/matrix/rust-embedded-graphics:matrix.org)](https://matrix.to/#/#rust-embedded-graphics:matrix.org)\n\n\n\n## [Documentation](https://docs.rs/tinybmp)\n\n\n\nA small BMP parser designed for embedded, no-std environments but usable anywhere. Beyond\n\nparsing the image header, no other allocations are made.\n\n\n\nTo use `tinybmp` without `embedded-graphics` the raw data for individual pixels in an image\n\ncan be accessed using the methods provided by the `RawBmp` struct.\n\n\n\n## Examples\n\n\n\n### Using `Bmp` to draw a BMP image\n\n\n\nIf the color format inside the BMP file is known at compile time the `Bmp` type can be used\n\nto draw an image to an `embedded-graphics` draw target. The BMP file used in this example\n\nuses 16 bits per pixel with a RGB565 format.\n\n\n\n```rust\n\nuse embedded_graphics::{image::Image, prelude::*};\n\nuse tinybmp::Bmp;\n\n\n\nlet bmp_data = include_bytes!(\"../tests/chessboard-8px-color-16bit.bmp\");\n\n\n\n// Load 16 BPP 8x8px image.\n\n// Note: The color type is specified explicitly to match the format used by the BMP image.\n\nlet bmp = Bmp::<Rgb565>::from_slice(bmp_data).unwrap();\n\n\n\n// Draw the image with the top left corner at (10, 20) by wrapping it in\n\n// an embedded-graphics `Image`.\n\nImage::new(&bmp, Point::new(10, 20)).draw(&mut display)?;\n\n```\n\n\n", "file_path": "README.md", "rank": 48, "score": 12.618082936036323 }, { "content": "\n\n /// Returns a reference to the raw BMP image.\n\n ///\n\n /// The [`RawBmp`] instance can be used to access lower level information about the BMP file.\n\n ///\n\n /// [`RawBmp`]: struct.RawBmp.html\n\n pub fn as_raw(&self) -> &RawBmp<'a> {\n\n &self.raw_bmp\n\n }\n\n}\n\n\n\nimpl<C> ImageDrawable for Bmp<'_, C>\n\nwhere\n\n C: PixelColor + From<<C as PixelColor>::Raw>,\n\n{\n\n type Color = C;\n\n\n\n fn draw<D>(&self, target: &mut D) -> Result<(), D::Error>\n\n where\n\n D: DrawTarget<Color = C>,\n", "file_path": "src/lib.rs", "rank": 49, "score": 11.332857619884523 }, { "content": "//! ## Accessing the raw image data\n\n//!\n\n//! The [`RawBmp`] struct provides methods to access lower level information about a BMP file,\n\n//! like the BMP header or the raw image data. An instance of this type can be created by using\n\n//! [`from_slice`] or by accessing the underlying raw object of a [`Bmp`] or [`DynamicBmp`] object\n\n//! by using [`as_raw`].\n\n//!\n\n//! ```rust\n\n//! use embedded_graphics::prelude::*;\n\n//! use tinybmp::{RawBmp, Bpp, Header, RawPixel};\n\n//!\n\n//! let bmp = RawBmp::from_slice(include_bytes!(\"../tests/chessboard-8px-24bit.bmp\"))\n\n//! .expect(\"Failed to parse BMP image\");\n\n//!\n\n//! // Read the BMP header\n\n//! assert_eq!(\n\n//! bmp.header(),\n\n//! &Header {\n\n//! file_size: 314,\n\n//! image_data_start: 122,\n", "file_path": "src/lib.rs", "rank": 50, "score": 10.517415733265434 }, { "content": "## [0.2.3] - 2020-05-26\n\n\n\n### Added\n\n\n\n- #352 Added support for decoding 1 bit pixel depth BMP images.\n\n\n\n## [0.2.2] - 2020-03-20\n\n\n\n## [0.2.1] - 2020-02-17\n\n\n\n- [#244](https://github.com/embedded-graphics/embedded-graphics/pull/244) Added `.into_iter()` support to the `Bmp` struct to get an iterator over every pixel in the image.\n\n\n\n### Changed\n\n\n\n- **(breaking)** [#247](https://github.com/embedded-graphics/embedded-graphics/pull/247) \"reverse\" integration of tinybmp into [`embedded-graphics`](https://crates.io/crates/embedded-graphics). tinybmp now has a `graphics` feature that must be turned on to enable embedded-graphics support. The `bmp` feature from embedded-graphics is removed.\n\n\n\n **Before**\n\n\n\n `Cargo.toml`\n\n\n\n ```toml\n\n [dependencies]\n\n embedded-graphics = { version = \"0.6.0-alpha.3\", features = [ \"bmp\" ]}\n\n ```\n\n\n\n Your code\n\n\n\n ```rust\n\n use embedded_graphics::prelude::*;\n\n use embedded_graphics::image::ImageBmp;\n\n\n\n let image = ImageBmp::new(include_bytes!(\"../../../assets/patch.bmp\")).unwrap();\n\n display.draw(&image);\n\n ```\n\n\n\n **After**\n\n\n\n `Cargo.toml`\n\n\n\n ```toml\n\n [dependencies]\n\n embedded-graphics = \"0.6.0\"\n\n tinybmp = { version = \"*\", features = [ \"graphics\" ]}\n\n ```\n\n\n\n Your code\n\n\n\n ```rust\n\n use embedded_graphics::{prelude::*, image::Image};\n\n use tinybmp::Bmp;\n\n\n\n let image = Bmp::new(include_bytes!(\"../../../assets/patch.bmp\")).unwrap();\n\n let image = Image::new(&image);\n\n display.draw(&image);\n\n ```\n\n\n\n## 0.1.1\n\n\n\n### Fixed\n\n\n\n- #218 Test README examples in CI and update them to work with latest crate versions.\n\n\n\n### Changed\n\n\n\n- #228 Upgraded to nom 5 internally. No user-facing changes.\n\n\n\n## 0.1.0\n\n\n\n### Added\n\n\n\n- Release `tinybmp` crate to crates.io\n\n\n\n<!-- next-url -->\n\n[unreleased]: https://github.com/embedded-graphics/tinybmp/compare/v0.3.0-alpha.1...HEAD\n\n\n\n[0.3.0-alpha.1]: https://github.com/embedded-graphics/tinybmp/compare/after-split...v0.3.0-alpha.1\n\n[0.3.0-alpha.1 - `embedded-graphics` repository]: https://github.com/embedded-graphics/embedded-graphics/compare/tinybmp-v0.2.3...before-split\n\n[0.2.3]: https://github.com/embedded-graphics/embedded-graphics/compare/tinybmp-v0.2.2...tinybmp-v0.2.3\n\n[0.2.2]: https://github.com/embedded-graphics/embedded-graphics/compare/tinybmp-v0.2.0...tinybmp-v0.2.2\n\n[0.2.1]: https://github.com/embedded-graphics/embedded-graphics/compare/tinybmp-v0.1.1...tinybmp-v0.2.1\n", "file_path": "CHANGELOG.md", "rank": 51, "score": 10.41231055887539 }, { "content": "use core::marker::PhantomData;\n\nuse embedded_graphics::prelude::*;\n\n\n\nuse crate::raw_pixels::RawPixels;\n\n\n\n/// Iterator over the pixels in a BMP image.\n\n///\n\n/// See the [`pixels`] method documentation for more information.\n\n///\n\n/// [`pixels`]: struct.Bmp.html#method.pixels\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct Pixels<'a, 'b, C> {\n\n raw: RawPixels<'a, 'b>,\n\n color_type: PhantomData<C>,\n\n}\n\n\n\nimpl<'a, 'b, C> Pixels<'a, 'b, C> {\n\n pub(crate) fn new(raw: RawPixels<'a, 'b>) -> Self {\n\n Self {\n\n raw,\n", "file_path": "src/pixels.rs", "rank": 52, "score": 9.822672674047345 }, { "content": "use embedded_graphics::prelude::*;\n\n\n\nuse crate::{header::Bpp, raw_bmp::RawBmp};\n\n\n\n/// Iterator over individual BMP pixels.\n\n///\n\n/// Each pixel is returned as a `u32` regardless of the bit depth of the source image.\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct RawPixels<'a, 'b> {\n\n /// Reference to original BMP image.\n\n raw_bmp: &'a RawBmp<'b>,\n\n\n\n /// Image pixel data as a byte slice, little endian ordering.\n\n pixel_data: &'b [u8],\n\n\n\n /// Current position.\n\n position: Point,\n\n\n\n /// Start bit index for the current pixel.\n\n ///\n", "file_path": "src/raw_pixels.rs", "rank": 53, "score": 9.819253305150259 }, { "content": " ///\n\n /// The created object keeps a shared reference to the input and does not dynamically allocate\n\n /// memory.\n\n ///\n\n /// The color type must be explicitly specified when this method is called, for example by\n\n /// using the turbofish syntax. An error is returned if the bit depth of the specified color\n\n /// type doesn't match the bit depth of the BMP file.\n\n pub fn from_slice(bytes: &'a [u8]) -> Result<Self, ParseError> {\n\n let raw_bmp = RawBmp::from_slice(bytes)?;\n\n\n\n if C::Raw::BITS_PER_PIXEL != usize::from(raw_bmp.color_bpp().bits()) {\n\n if raw_bmp.color_bpp() == Bpp::Bits32 && C::Raw::BITS_PER_PIXEL == 24 {\n\n // Allow 24BPP color types for 32BPP images to support RGB888 BMP files with\n\n // 4 bytes per pixel.\n\n // This check could be improved by using the bit masks available in BMP headers\n\n // with version >= 4, but we don't currently parse this information.\n\n } else {\n\n return Err(ParseError::MismatchedBpp(raw_bmp.color_bpp().bits()));\n\n }\n\n }\n", "file_path": "src/lib.rs", "rank": 54, "score": 9.258900195216818 }, { "content": " {\n\n self.as_raw().draw(target)\n\n }\n\n\n\n fn draw_sub_image<D>(&self, target: &mut D, area: &Rectangle) -> Result<(), D::Error>\n\n where\n\n D: DrawTarget<Color = Self::Color>,\n\n {\n\n self.draw(&mut target.translated(-area.top_left).clipped(area))\n\n }\n\n}\n\n\n\nimpl<C> OriginDimensions for Bmp<'_, C>\n\nwhere\n\n C: PixelColor,\n\n{\n\n fn size(&self) -> Size {\n\n self.raw_bmp.size()\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 55, "score": 9.017657504719775 }, { "content": "//! [`as_raw`]: ./struct.Bmp.html#method.as_raw\n\n//! [`DynamicBmp`]: ./struct.DynamicBmp.html\n\n//! [`RawBmp`]: ./struct.RawBmp.html\n\n//! [`from_slice`]: ./struct.RawBmp.html#method.from_slice\n\n//! [`pixels`]: ./struct.RawBmp.html#method.pixels\n\n//! [`image_data`]: ./struct.RawBmp.html#method.image_data\n\n\n\n#![no_std]\n\n#![deny(missing_docs)]\n\n#![deny(missing_debug_implementations)]\n\n\n\nmod dynamic_bmp;\n\nmod header;\n\nmod pixels;\n\nmod raw_bmp;\n\nmod raw_pixels;\n\n\n\nuse core::marker::PhantomData;\n\nuse embedded_graphics::{prelude::*, primitives::Rectangle};\n\n\n", "file_path": "src/lib.rs", "rank": 56, "score": 8.257570395725025 }, { "content": "pub use crate::{\n\n dynamic_bmp::DynamicBmp,\n\n header::{Bpp, ChannelMasks, Header},\n\n pixels::Pixels,\n\n raw_bmp::RawBmp,\n\n raw_pixels::{RawPixel, RawPixels},\n\n};\n\n\n\n/// A BMP-format bitmap\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct Bmp<'a, C> {\n\n raw_bmp: RawBmp<'a>,\n\n color_type: PhantomData<C>,\n\n}\n\n\n\nimpl<'a, C> Bmp<'a, C>\n\nwhere\n\n C: PixelColor,\n\n{\n\n /// Creates a bitmap object from a byte slice.\n", "file_path": "src/lib.rs", "rank": 57, "score": 7.428096972999269 }, { "content": "\n\n Ok(Self {\n\n raw_bmp,\n\n color_type: PhantomData,\n\n })\n\n }\n\n\n\n /// Returns an iterator over the pixels in this image.\n\n ///\n\n /// The iterator automatically converts the pixel colors into an `embedded-graphics` color type,\n\n /// that is when the [`from_slice`] constructor was called. This method isn't available when\n\n /// the [`from_slice_raw`] constructor was used and the pixel can only be accessed by using the\n\n /// [`raw_pixels`] method.\n\n ///\n\n /// [`from_slice`]: #method.from_slice\n\n /// [`from_slice_raw`]: #method.from_slice_raw\n\n /// [`raw_pixels`]: #method.raw_pixels\n\n pub fn pixels<'b>(&'b self) -> Pixels<'b, 'a, C> {\n\n Pixels::new(self.raw_bmp.pixels())\n\n }\n", "file_path": "src/lib.rs", "rank": 58, "score": 6.879713071800751 }, { "content": "\n\n/// Parse error.\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]\n\npub enum ParseError {\n\n /// An error occurred while parsing the header.\n\n Header,\n\n\n\n /// The image uses a bit depth that isn't supported by tinybmp.\n\n UnsupportedBpp(u16),\n\n\n\n /// The image bit depth doesn't match the specified color type.\n\n MismatchedBpp(u16),\n\n\n\n /// The image format isn't supported by `DynamicBmp`.\n\n UnsupportedDynamicBmpFormat,\n\n}\n", "file_path": "src/lib.rs", "rank": 59, "score": 6.022452943388609 }, { "content": " /// This is incremented by `pixel_stride` bits every iteration.\n\n bit_idx: usize,\n\n}\n\n\n\nimpl<'a, 'b> RawPixels<'a, 'b> {\n\n pub(crate) fn new(raw_bmp: &'a RawBmp<'b>) -> Self {\n\n Self {\n\n raw_bmp,\n\n pixel_data: raw_bmp.image_data(),\n\n position: Point::zero(),\n\n bit_idx: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl Iterator for RawPixels<'_, '_> {\n\n type Item = RawPixel;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n if self.position.y >= self.raw_bmp.size().height as i32 {\n", "file_path": "src/raw_pixels.rs", "rank": 60, "score": 5.794759275740978 }, { "content": "# Changelog\n\n\n\n[`tinybmp`](https://crates.io/crates/tinybmp) is a no_std, low memory footprint BMP loading library for embedded applications.\n\n\n\n<!-- next-header -->\n\n\n\n## [Unreleased] - ReleaseDate\n\n\n\n## [0.3.0-alpha.1] - 2020-12-27\n\n\n\n### Changed\n\n\n\n- **(breaking)** [#3](https://github.com/embedded-graphics/tinybmp/pull/3) `tinybmp` now depends on `embedded-graphics-core` instead of `embedded-graphics`.\n\n\n\n## [0.3.0-alpha.1 - `embedded-graphics` repository] - 2020-12-27\n\n\n\n> Note: PR numbers from this point onwards are from the old `embedded-graphics/embedded-graphics` repository. New PR numbers above this note refer to PRs in the `embedded-graphics/tinybmp` repository.\n\n\n\n### Added\n\n\n\n- [#453](https://github.com/embedded-graphics/embedded-graphics/pull/453) `DynamicBmp` was added to load images with an unknown color format at compile time.\n\n\n\n### Changed\n\n\n\n- **(breaking)** [#420](https://github.com/embedded-graphics/embedded-graphics/pull/420) To support the new embedded-graphics 0.7 image API a color type parameter was added to `Bmp`.\n\n- **(breaking)** [#444](https://github.com/embedded-graphics/embedded-graphics/pull/444) The `graphics` feature was removed and the `embedded-graphics` dependency is now non optional.\n\n- **(breaking)** [#444](https://github.com/embedded-graphics/embedded-graphics/pull/444) `Bmp` no longer implements `IntoIterator`. Pixel iterators can now be created using the `pixels` methods.\n\n- **(breaking)** [#444](https://github.com/embedded-graphics/embedded-graphics/pull/444) `Bmp::width` and `Bmp::height` were replaced by `Bmp::size` which requires `embedded_graphics::geometry::OriginDimensions` to be in scope (also included in the embedded-graphics `prelude`).\n\n- **(breaking)** [#444](https://github.com/embedded-graphics/embedded-graphics/pull/444) `Bmp::from_slice` now checks if the image BPP matches the specified color type. To report possible errors it now returns the dedicated error type `ParseError` instead of `()`.\n\n- **(breaking)** [#444](https://github.com/embedded-graphics/embedded-graphics/pull/444) `Bmp::bpp` was renamed to `Bmp::color_bpp` to be consistent with `tinytga` and the return type was changed to an enum.\n\n- **(breaking)** [#453](https://github.com/embedded-graphics/embedded-graphics/pull/453) The methods to access the raw image data and header were moved to a new `RawBmp` type, which can be used on its own or can be accessed by using `Bmp::as_raw` or `DynamicBmp::as_raw`.\n\n\n", "file_path": "CHANGELOG.md", "rank": 61, "score": 5.583678890381556 }, { "content": " color_type: PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<C> Iterator for Pixels<'_, '_, C>\n\nwhere\n\n C: PixelColor + From<<C as PixelColor>::Raw>,\n\n{\n\n type Item = Pixel<C>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n self.raw\n\n .next()\n\n .map(|p| Pixel(p.position, C::Raw::from_u32(p.color).into()))\n\n }\n\n}\n", "file_path": "src/pixels.rs", "rank": 62, "score": 5.486987569313445 }, { "content": "//! bpp: Bpp::Bits24,\n\n//! image_size: Size::new(8, 8),\n\n//! image_data_len: 192,\n\n//! channel_masks: None,\n\n//! }\n\n//! );\n\n//!\n\n//! // Check that raw image data slice is the correct length (according to parsed header)\n\n//! assert_eq!(bmp.image_data().len(), bmp.header().image_data_len as usize);\n\n//!\n\n//! // Get an iterator over the pixel coordinates and values in this image and load into a vec\n\n//! let pixels: Vec<RawPixel> = bmp.pixels().collect();\n\n//!\n\n//! // Loaded example image is 8x8px\n\n//! assert_eq!(pixels.len(), 8 * 8);\n\n//! ```\n\n//!\n\n//! [`embedded-graphics`]: https://crates.io/crates/embedded-graphics\n\n//! [`Header`]: ./header/struct.Header.html\n\n//! [`Bmp`]: ./struct.Bmp.html\n", "file_path": "src/lib.rs", "rank": 63, "score": 5.416505097068201 }, { "content": "//! Bitmap header\n\n//!\n\n//! Information gleaned from [wikipedia](https://en.wikipedia.org/wiki/BMP_file_format) and\n\n//! [this website](http://paulbourke.net/dataformats/bmp/)\n\n\n\nuse embedded_graphics::prelude::*;\n\nuse nom::{\n\n bytes::complete::tag,\n\n combinator::map_opt,\n\n number::complete::{le_u16, le_u32},\n\n IResult,\n\n};\n\n\n\n/// Bits per pixel.\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\n#[non_exhaustive]\n\npub enum Bpp {\n\n /// 1 bit per pixel.\n\n Bits1,\n\n /// 8 bits per pixel.\n", "file_path": "src/header.rs", "rank": 64, "score": 5.314831002618485 }, { "content": " /// Rgb565 color masks.\n\n pub const RGB565: Self = Self {\n\n red: 0b11111_000000_00000,\n\n green: 0b00000_111111_00000,\n\n blue: 0b00000_000000_11111,\n\n alpha: 0,\n\n };\n\n\n\n /// Rgb888 color masks.\n\n pub const RGB888: Self = Self {\n\n red: 0xFF0000,\n\n green: 0x00FF00,\n\n blue: 0x0000FF,\n\n alpha: 0,\n\n };\n\n}\n\n\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub enum CompressionMethod {\n\n Rgb,\n", "file_path": "src/header.rs", "rank": 65, "score": 4.941151417134476 }, { "content": " pub(crate) fn parse(input: &[u8]) -> IResult<&[u8], Header> {\n\n let (input, _) = tag(\"BM\")(input)?;\n\n let (input, file_size) = le_u32(input)?;\n\n let (input, _reserved_1) = le_u16(input)?;\n\n let (input, _reserved_2) = le_u16(input)?;\n\n let (input, image_data_start) = le_u32(input)?;\n\n let (input, header_size) = le_u32(input)?;\n\n let (input, image_width) = le_u32(input)?;\n\n let (input, image_height) = le_u32(input)?;\n\n let (input, _color_planes) = le_u16(input)?;\n\n let (input, bpp) = Bpp::parse(input)?;\n\n let (input, compression_method) = CompressionMethod::parse(input)?;\n\n let (input, image_data_len) = le_u32(input)?;\n\n\n\n let (input, channel_masks) = if compression_method == CompressionMethod::Bitfields {\n\n // BMP header versions can be distinguished by the header length.\n\n // The color bit masks are only included in headers with at least version 3.\n\n if header_size >= 56 {\n\n let (input, _pels_per_meter_x) = le_u32(input)?;\n\n let (input, _pels_per_meter_y) = le_u32(input)?;\n", "file_path": "src/header.rs", "rank": 66, "score": 4.604847019030554 }, { "content": " let mut pixel_value = [0u8; 4];\n\n\n\n match self.raw_bmp.color_bpp() {\n\n Bpp::Bits1 => self.pixel_data.get(byte_idx).map(|byte| {\n\n let mask = 0b_1000_0000 >> self.bit_idx % 8;\n\n pixel_value[0] = (byte & mask != 0) as u8;\n\n }),\n\n Bpp::Bits8 => self\n\n .pixel_data\n\n .get(byte_idx)\n\n .map(|byte| pixel_value[0] = *byte),\n\n Bpp::Bits16 => self.pixel_data.get(byte_idx..byte_idx + 2).map(|data| {\n\n pixel_value[0..2].copy_from_slice(data);\n\n }),\n\n Bpp::Bits24 => self.pixel_data.get(byte_idx..byte_idx + 3).map(|data| {\n\n pixel_value[0..3].copy_from_slice(data);\n\n }),\n\n Bpp::Bits32 => self.pixel_data.get(byte_idx..byte_idx + 4).map(|data| {\n\n pixel_value[0..4].copy_from_slice(data);\n\n }),\n", "file_path": "src/raw_pixels.rs", "rank": 67, "score": 4.169204072389828 }, { "content": "\n\n fn parse(input: &[u8]) -> IResult<&[u8], Self> {\n\n map_opt(le_u16, Bpp::new)(input)\n\n }\n\n\n\n /// Returns the number of bits.\n\n pub fn bits(self) -> u16 {\n\n match self {\n\n Self::Bits1 => 1,\n\n Self::Bits8 => 8,\n\n Self::Bits16 => 16,\n\n Self::Bits24 => 24,\n\n Self::Bits32 => 32,\n\n }\n\n }\n\n}\n\n\n\n/// BMP header information\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]\n\npub struct Header {\n", "file_path": "src/header.rs", "rank": 68, "score": 3.9064469819908094 }, { "content": " } else {\n\n (input, None)\n\n };\n\n\n\n Ok((\n\n input,\n\n Header {\n\n file_size,\n\n image_data_start: image_data_start as usize,\n\n image_size: Size::new(image_width, image_height),\n\n image_data_len,\n\n bpp,\n\n channel_masks,\n\n },\n\n ))\n\n }\n\n}\n\n\n\n/// Masks for the color channels.\n\n#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]\n", "file_path": "src/header.rs", "rank": 69, "score": 3.073310911123694 }, { "content": " /// Total file size in bytes.\n\n pub file_size: u32,\n\n\n\n /// Byte offset from beginning of file at which pixel data begins.\n\n pub image_data_start: usize,\n\n\n\n /// Image size in pixels.\n\n pub image_size: Size,\n\n\n\n /// Number of bits per pixel.\n\n pub bpp: Bpp,\n\n\n\n /// Length in bytes of the image data.\n\n pub image_data_len: u32,\n\n\n\n /// Bit masks for the color channels.\n\n pub channel_masks: Option<ChannelMasks>,\n\n}\n\n\n\nimpl Header {\n", "file_path": "src/header.rs", "rank": 70, "score": 2.8346702483244517 }, { "content": " Bitfields,\n\n}\n\n\n\nimpl CompressionMethod {\n\n fn new(value: u32) -> Option<Self> {\n\n Some(match value {\n\n 0 => Self::Rgb,\n\n 3 => Self::Bitfields,\n\n _ => return None,\n\n })\n\n }\n\n\n\n fn parse(input: &[u8]) -> IResult<&[u8], Self> {\n\n map_opt(le_u32, Self::new)(input)\n\n }\n\n}\n", "file_path": "src/header.rs", "rank": 71, "score": 2.7694753301783104 }, { "content": " return None;\n\n }\n\n\n\n let p = self.position;\n\n\n\n if self.position.x == 0 {\n\n let row_index = (self.raw_bmp.size().height as i32 - 1) - self.position.y;\n\n let row_start = self.raw_bmp.bytes_per_row() * row_index as usize;\n\n\n\n self.bit_idx = row_start * 8;\n\n }\n\n\n\n self.position.x += 1;\n\n if self.position.x >= self.raw_bmp.size().width as i32 {\n\n self.position.y += 1;\n\n self.position.x = 0;\n\n }\n\n\n\n let byte_idx = self.bit_idx / 8;\n\n\n", "file_path": "src/raw_pixels.rs", "rank": 72, "score": 2.526370484540644 }, { "content": "pub struct ChannelMasks {\n\n /// Red channel mask.\n\n pub red: u32,\n\n /// Green channel mask.\n\n pub green: u32,\n\n /// Blue channel mask.\n\n pub blue: u32,\n\n /// Alpha channel mask.\n\n pub alpha: u32,\n\n}\n\n\n\nimpl ChannelMasks {\n\n /// Rgb555 color masks.\n\n pub const RGB555: Self = Self {\n\n red: 0b11111_00000_00000,\n\n green: 0b00000_11111_00000,\n\n blue: 0b00000_00000_11111,\n\n alpha: 0,\n\n };\n\n\n", "file_path": "src/header.rs", "rank": 73, "score": 2.5150289193530946 }, { "content": " };\n\n\n\n self.bit_idx += usize::from(self.raw_bmp.color_bpp().bits());\n\n\n\n Some(RawPixel::new(p, u32::from_le_bytes(pixel_value)))\n\n }\n\n}\n\n\n\n/// Pixel with raw pixel color stored as a `u32`.\n\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Default)]\n\npub struct RawPixel {\n\n /// The position relative to the top left corner of the image.\n\n pub position: Point,\n\n\n\n /// The raw pixel color.\n\n pub color: u32,\n\n}\n\n\n\nimpl RawPixel {\n\n /// Creates a new raw pixel.\n\n pub fn new(position: Point, color: u32) -> Self {\n\n Self { position, color }\n\n }\n\n}\n", "file_path": "src/raw_pixels.rs", "rank": 74, "score": 2.459823770159617 }, { "content": " let (input, _clr_used) = le_u32(input)?;\n\n let (input, _clr_important) = le_u32(input)?;\n\n let (input, mask_red) = le_u32(input)?;\n\n let (input, mask_green) = le_u32(input)?;\n\n let (input, mask_blue) = le_u32(input)?;\n\n let (input, mask_alpha) = le_u32(input)?;\n\n\n\n (\n\n input,\n\n Some(ChannelMasks {\n\n red: mask_red,\n\n green: mask_green,\n\n blue: mask_blue,\n\n alpha: mask_alpha,\n\n }),\n\n )\n\n } else {\n\n // TODO: this should probably be an error\n\n (input, None)\n\n }\n", "file_path": "src/header.rs", "rank": 75, "score": 1.4559279096405864 } ]
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 some written bytes might get lost!\n\n///\n\n/// # Examples\n\n///\n\n/// Write into a file:\n\n///\n\n/// ```no_run\n\n/// use futures::prelude::*;\n\n/// use smol::{blocking, writer};\n\n/// use std::fs::File;\n\n///\n\n/// # smol::run(async {\n\n/// // Open a file for writing.\n\n/// let file = blocking!(File::open(\"foo.txt\"))?;\n\n/// let mut file = writer(file);\n\n///\n\n/// // Write some bytes into the file and flush.\n\n/// file.write_all(b\"hello\").await?;\n\n/// file.flush().await?;\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\n///\n\n/// Write into standard output:\n\n///\n\n/// ```no_run\n\n/// use futures::prelude::*;\n\n/// use smol::writer;\n\n///\n\n/// # smol::run(async {\n\n/// // Create an async writer to stdout.\n\n/// let mut stdout = writer(std::io::stdout());\n\n///\n\n/// // Write a message and flush.\n\n/// stdout.write_all(b\"hello\").await?;\n\n/// stdout.flush().await?;\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\npub fn writer(writer: impl Write + Send + 'static) -> impl AsyncWrite + Send + Unpin + 'static {\n\n /// Current state of the writer.\n\n enum State<T> {\n\n /// The writer is idle.\n\n Idle(Option<T>),\n\n /// The writer is running in a blocking task and receiving bytes from a pipe.\n\n Busy(Option<piper::Writer>, Task<(io::Result<()>, T)>),\n\n }\n\n\n\n impl<T: AsyncWrite + Send + Unpin + 'static> State<T> {\n\n /// Starts a blocking task.\n\n fn start(&mut self) {\n\n if let State::Idle(io) = self {\n\n // If idle, take the I/O handle out to write on a blocking task.\n\n let mut io = io.take().unwrap();\n\n\n\n // This pipe capacity seems to work well in practice. If it's too low, there will\n\n // be too much synchronization between tasks. If too high, memory consumption\n\n // increases.\n\n let (reader, writer) = piper::pipe(8 * 1024 * 1024); // 8 MB\n", "file_path": "src/blocking.rs", "rank": 0, "score": 216042.53089676006 }, { "content": "/// Creates an async reader that runs on a thread.\n\n///\n\n/// This adapter converts any kind of synchronous reader into an asynchronous reader by running it\n\n/// on the blocking executor and sending bytes back over a pipe.\n\n///\n\n/// # Examples\n\n///\n\n/// Read from a file:\n\n///\n\n/// ```no_run\n\n/// use futures::prelude::*;\n\n/// use smol::{blocking, reader};\n\n/// use std::fs::File;\n\n///\n\n/// # smol::run(async {\n\n/// // Open a file for reading.\n\n/// let file = blocking!(File::open(\"foo.txt\"))?;\n\n/// let mut file = reader(file);\n\n///\n\n/// // Read the whole file.\n\n/// let mut contents = Vec::new();\n\n/// file.read_to_end(&mut contents).await?;\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\n///\n\n/// Read output from a process:\n\n///\n\n/// ```no_run\n\n/// use futures::prelude::*;\n\n/// use smol::reader;\n\n/// use std::process::{Command, Stdio};\n\n///\n\n/// # smol::run(async {\n\n/// // Spawn a child process and make an async reader for its stdout.\n\n/// let child = Command::new(\"dir\").stdout(Stdio::piped()).spawn()?;\n\n/// let mut child_stdout = reader(child.stdout.unwrap());\n\n///\n\n/// // Read the entire output.\n\n/// let mut output = String::new();\n\n/// child_stdout.read_to_string(&mut output).await?;\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\npub fn reader(reader: impl Read + Send + 'static) -> impl AsyncRead + Send + Unpin + 'static {\n\n /// Current state of the reader.\n\n enum State<T> {\n\n /// The reader is idle.\n\n Idle(Option<T>),\n\n /// The reader is running in a blocking task and sending bytes into a pipe.\n\n Busy(piper::Reader, Task<(io::Result<()>, T)>),\n\n }\n\n\n\n impl<T: AsyncRead + Send + Unpin + 'static> AsyncRead for State<T> {\n\n fn poll_read(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &mut [u8],\n\n ) -> Poll<io::Result<usize>> {\n\n // Throttle if the current task has done too many I/O operations without yielding.\n\n futures_util::ready!(throttle::poll(cx));\n\n\n\n match &mut *self {\n\n State::Idle(io) => {\n", "file_path": "src/blocking.rs", "rank": 1, "score": 216027.56799198414 }, { "content": "/// Polls or waits on the locked reactor.\n\n///\n\n/// If any of the I/O events are ready or there are more tasks to run, the reactor is polled.\n\n/// Otherwise, the current thread waits on it until a timer fires or an I/O event occurs.\n\n///\n\n/// I/O events are cleared at the end of this function.\n\nfn react(mut reactor_lock: ReactorLock<'_>, io_events: &[&IoEvent], mut more_tasks: bool) {\n\n // Clear all I/O events and check if any of them were triggered.\n\n for ev in io_events {\n\n if ev.clear() {\n\n more_tasks = true;\n\n }\n\n }\n\n\n\n if more_tasks {\n\n // If there might be more tasks to run, just poll without blocking.\n\n reactor_lock.poll().expect(\"failure while polling I/O\");\n\n } else {\n\n // Otherwise, block until the first I/O event or a timer.\n\n reactor_lock.wait().expect(\"failure while waiting on I/O\");\n\n\n\n // Clear all I/O events before dropping the lock. This is not really necessary, but\n\n // clearing flags here might prevent a redundant wakeup in the future.\n\n for ev in io_events {\n\n ev.clear();\n\n }\n\n }\n\n}\n", "file_path": "src/run.rs", "rank": 3, "score": 138231.77189085638 }, { "content": "pub fn spawn_benchmark(c: &mut Criterion) {\n\n std::thread::spawn(|| smol::run(future::pending::<()>()));\n\n c.bench_function(\"spawn time\", |b| {\n\n b.iter(|| {\n\n let x = black_box(5);\n\n smol::block_on(async {\n\n Task::spawn(async move {\n\n let _ = x + 1;\n\n })\n\n .await;\n\n });\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, spawn_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "benches/spawn.rs", "rank": 5, "score": 129748.2150088796 }, { "content": "/// Pins a future and then polls it.\n\nfn poll_future<T>(cx: &mut Context<'_>, fut: impl Future<Output = T>) -> Poll<T> {\n\n futures_util::pin_mut!(fut);\n\n fut.poll(cx)\n\n}\n\n\n\nimpl<T: Read> AsyncRead for Async<T> {\n\n fn poll_read(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &mut [u8],\n\n ) -> Poll<io::Result<usize>> {\n\n poll_future(cx, self.read_with_mut(|io| io.read(buf)))\n\n }\n\n\n\n fn poll_read_vectored(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n bufs: &mut [IoSliceMut<'_>],\n\n ) -> Poll<io::Result<usize>> {\n\n poll_future(cx, self.read_with_mut(|io| io.read_vectored(bufs)))\n", "file_path": "src/async_io.rs", "rank": 7, "score": 117392.02370799994 }, { "content": "/// Retries a steal operation for as long as it returns `Steal::Retry`.\n\nfn retry_steal<T>(mut steal_op: impl FnMut() -> deque::Steal<T>) -> Option<T> {\n\n loop {\n\n match steal_op() {\n\n deque::Steal::Success(t) => return Some(t),\n\n deque::Steal::Empty => return None,\n\n deque::Steal::Retry => {}\n\n }\n\n }\n\n}\n", "file_path": "src/work_stealing.rs", "rank": 9, "score": 108218.10681246353 }, { "content": "/// Runs executors and polls the reactor.\n\n///\n\n/// This function simultaneously runs the thread-local executor, runs the work-stealing\n\n/// executor, and polls the reactor for I/O events and timers. At least one thread has to be\n\n/// calling [`run()`] in order for futures waiting on I/O and timers to get notified.\n\n///\n\n/// # Examples\n\n///\n\n/// Single-threaded executor:\n\n///\n\n/// ```\n\n/// // Run the thread-local and work-stealing executor on the current thread.\n\n/// smol::run(async {\n\n/// println!(\"Hello from the smol executor!\");\n\n/// });\n\n/// ```\n\n///\n\n/// Multi-threaded executor:\n\n///\n\n/// ```no_run\n\n/// use futures::future;\n\n/// use smol::Task;\n\n/// use std::thread;\n\n///\n\n/// // Same number of threads as there are CPU cores.\n\n/// let num_threads = num_cpus::get().max(1);\n\n///\n\n/// // Run the thread-local and work-stealing executor on a thread pool.\n\n/// for _ in 0..num_threads {\n\n/// // A pending future is one that simply yields forever.\n\n/// thread::spawn(|| smol::run(future::pending::<()>()));\n\n/// }\n\n///\n\n/// // No need to `run()`, now we can just block on the main future.\n\n/// smol::block_on(async {\n\n/// Task::spawn(async {\n\n/// println!(\"Hello from an executor thread!\");\n\n/// })\n\n/// .await;\n\n/// });\n\n/// ```\n\n///\n\n/// Stoppable multi-threaded executor:\n\n///\n\n/// ```\n\n/// use smol::Task;\n\n/// use std::thread;\n\n///\n\n/// // Same number of threads as there are CPU cores.\n\n/// let num_threads = num_cpus::get().max(1);\n\n///\n\n/// // A channel that sends the shutdown signal.\n\n/// let (s, r) = piper::chan::<()>(0);\n\n/// let mut threads = Vec::new();\n\n///\n\n/// // Create an executor thread pool.\n\n/// for _ in 0..num_threads {\n\n/// // Spawn an executor thread that waits for the shutdown signal.\n\n/// let r = r.clone();\n\n/// threads.push(thread::spawn(move || smol::run(r.recv())));\n\n/// }\n\n///\n\n/// // No need to `run()`, now we can just block on the main future.\n\n/// smol::block_on(async {\n\n/// Task::spawn(async {\n\n/// println!(\"Hello from an executor thread!\");\n\n/// })\n\n/// .await;\n\n/// });\n\n///\n\n/// // Send a shutdown signal.\n\n/// drop(s);\n\n///\n\n/// // Wait for threads to finish.\n\n/// for t in threads {\n\n/// t.join().unwrap();\n\n/// }\n\n/// ```\n\npub fn run<T>(future: impl Future<Output = T>) -> T {\n\n // Create a thread-local executor and a worker in the work-stealing executor.\n\n let local = ThreadLocalExecutor::new();\n\n let ws_executor = WorkStealingExecutor::get();\n\n let worker = ws_executor.worker();\n\n let reactor = Reactor::get();\n\n\n\n // Create a waker that triggers an I/O event in the thread-local scheduler.\n\n let ev = local.event().clone();\n\n let waker = async_task::waker_fn(move || ev.notify());\n\n let cx = &mut Context::from_waker(&waker);\n\n futures_util::pin_mut!(future);\n\n\n\n // Set up tokio (if enabled) and the thread-locals before execution begins.\n\n let enter = context::enter;\n\n let enter = |f| local.enter(|| enter(f));\n\n let enter = |f| worker.enter(|| enter(f));\n\n\n\n enter(|| {\n\n // A list of I/O events that indicate there is work to do.\n", "file_path": "src/run.rs", "rank": 10, "score": 105839.50603161709 }, { "content": "/// Blocks on a single future.\n\n///\n\n/// This function polls the future in a loop, parking the current thread after each step to wait\n\n/// until its waker is woken.\n\n///\n\n/// Unlike [`run()`], it does not run executors or poll the reactor!\n\n///\n\n/// You can think of it as the easiest and most efficient way of turning an async operation into a\n\n/// blocking operation.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use futures::future;\n\n/// use smol::{Async, Timer};\n\n/// use std::thread;\n\n/// use std::time::Duration;\n\n///\n\n/// // Run executors and the reactor on a separeate thread, forever.\n\n/// thread::spawn(|| smol::run(future::pending::<()>()));\n\n///\n\n/// smol::block_on(async {\n\n/// // Sleep for a second.\n\n/// // This timer only works because there's a thread calling `run()`.\n\n/// Timer::after(Duration::from_secs(1)).await;\n\n/// })\n\n/// ```\n\n///\n\n/// [`run()`]: crate::run()\n\npub fn block_on<T>(future: impl Future<Output = T>) -> T {\n\n thread_local! {\n\n // Parker and waker associated with the current thread.\n\n static CACHE: RefCell<(Parker, Waker)> = {\n\n let parker = Parker::new();\n\n let unparker = parker.unparker().clone();\n\n let waker = async_task::waker_fn(move || unparker.unpark());\n\n RefCell::new((parker, waker))\n\n };\n\n }\n\n\n\n CACHE.with(|cache| {\n\n // Panic if `block_on()` is called recursively.\n\n let (parker, waker) = &mut *cache.try_borrow_mut().expect(\"recursive `block_on()`\");\n\n\n\n // If enabled, set up tokio before execution begins.\n\n context::enter(|| {\n\n futures_util::pin_mut!(future);\n\n let cx = &mut Context::from_waker(&waker);\n\n\n\n loop {\n\n match future.as_mut().poll(cx) {\n\n Poll::Ready(output) => return output,\n\n Poll::Pending => parker.park(),\n\n }\n\n }\n\n })\n\n })\n\n}\n", "file_path": "src/block_on.rs", "rank": 11, "score": 105831.82380269855 }, { "content": "#[test]\n\nfn tcp_peek_read() -> io::Result<()> {\n\n smol::run(async {\n\n let listener = Async::<TcpListener>::bind(\"127.0.0.1:12301\")?;\n\n\n\n let mut stream = Async::<TcpStream>::connect(\"127.0.0.1:12301\").await?;\n\n stream.write_all(LOREM_IPSUM).await?;\n\n\n\n let mut buf = [0; 1024];\n\n let mut incoming = listener.incoming();\n\n let mut stream = incoming.next().await.unwrap()?;\n\n\n\n let n = stream.peek(&mut buf).await?;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n let n = stream.read(&mut buf).await?;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "tests/async_io.rs", "rank": 12, "score": 91769.24917361497 }, { "content": "type Client = Arc<Async<TcpStream>>;\n\n\n", "file_path": "examples/chat-server.rs", "rank": 13, "score": 89512.5256248936 }, { "content": "#[cfg(unix)]\n\nfn io_err(err: nix::Error) -> io::Error {\n\n match err {\n\n nix::Error::Sys(code) => code.into(),\n\n err => io::Error::new(io::ErrorKind::Other, Box::new(err)),\n\n }\n\n}\n\n\n\n/// Raw bindings to epoll (Linux, Android, illumos).\n\n#[cfg(any(target_os = \"linux\", target_os = \"android\", target_os = \"illumos\"))]\n\nmod sys {\n\n use std::convert::TryInto;\n\n use std::io;\n\n use std::os::unix::io::RawFd;\n\n use std::time::Duration;\n\n\n\n use nix::sys::epoll::{\n\n epoll_create1, epoll_ctl, epoll_wait, EpollCreateFlags, EpollEvent, EpollFlags, EpollOp,\n\n };\n\n\n\n use super::io_err;\n", "file_path": "src/reactor.rs", "rank": 14, "score": 88518.63941384427 }, { "content": "/// Creates a stream that iterates on a thread.\n\n///\n\n/// This adapter converts any kind of synchronous iterator into an asynchronous stream by running\n\n/// it on the blocking executor and sending items back over a channel.\n\n///\n\n/// # Examples\n\n///\n\n/// List files in the current directory:\n\n///\n\n/// ```no_run\n\n/// use futures::stream::StreamExt;\n\n/// use smol::{blocking, iter};\n\n/// use std::fs;\n\n///\n\n/// # smol::run(async {\n\n/// // Load a directory.\n\n/// let mut dir = blocking!(fs::read_dir(\".\"))?;\n\n/// let mut dir = iter(dir);\n\n///\n\n/// // Iterate over the contents of the directory.\n\n/// while let Some(res) = dir.next().await {\n\n/// println!(\"{}\", res?.file_name().to_string_lossy());\n\n/// }\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\npub fn iter<T: Send + 'static>(\n\n iter: impl Iterator<Item = T> + Send + 'static,\n\n) -> impl Stream<Item = T> + Send + Unpin + 'static {\n\n /// Current state of the iterator.\n\n enum State<T, I> {\n\n /// The iterator is idle.\n\n Idle(Option<I>),\n\n /// The iterator is running in a blocking task and sending items into a channel.\n\n Busy(piper::Receiver<T>, Task<I>),\n\n }\n\n\n\n impl<T, I> Unpin for State<T, I> {}\n\n\n\n impl<T: Send + 'static, I: Iterator<Item = T> + Send + 'static> Stream for State<T, I> {\n\n type Item = T;\n\n\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {\n\n // Throttle if the current task has done too many I/O operations without yielding.\n\n futures_util::ready!(throttle::poll(cx));\n\n\n", "file_path": "src/blocking.rs", "rank": 15, "score": 84917.39540466381 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\nfn main() {\n\n println!(\"This example works only on Linux!\");\n\n}\n", "file_path": "examples/linux-timerfd.rs", "rank": 16, "score": 81292.88814776792 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\nfn main() {\n\n println!(\"This example works only on Linux!\");\n\n}\n", "file_path": "examples/linux-inotify.rs", "rank": 17, "score": 81292.88814776792 }, { "content": "fn main() -> Result<()> {\n\n smol::run(async {\n\n // Create a request.\n\n let addr = \"https://www.rust-lang.org\";\n\n let req = Request::new(Method::Get, Url::parse(addr)?);\n\n\n\n // Fetch the response.\n\n let mut resp = fetch(req).await?;\n\n println!(\"{:#?}\", resp);\n\n\n\n // Read the message body.\n\n let mut body = Vec::new();\n\n resp.read_to_end(&mut body).await?;\n\n println!(\"{}\", String::from_utf8_lossy(&body));\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/async-h1-client.rs", "rank": 19, "score": 72357.10751807378 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate, private key, and password.\n\n let identity = Identity::from_pkcs12(include_bytes!(\"identity.pfx\"), \"password\")?;\n\n let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);\n\n\n\n // Create an executor thread pool.\n\n let num_threads = num_cpus::get().max(1);\n\n for _ in 0..num_threads {\n\n thread::spawn(|| smol::run(future::pending::<()>()));\n\n }\n\n\n\n // Start HTTP and HTTPS servers.\n\n smol::block_on(async {\n\n let http = listen(Async::<TcpListener>::bind(\"127.0.0.1:8000\")?, None);\n\n let https = listen(Async::<TcpListener>::bind(\"127.0.0.1:8001\")?, Some(tls));\n\n future::try_join(http, https).await?;\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/async-h1-server.rs", "rank": 20, "score": 72357.10751807378 }, { "content": "#[cfg(unix)]\n\n#[test]\n\nfn udp_connect() -> io::Result<()> {\n\n smol::run(async {\n\n let dir = tempdir()?;\n\n let path = dir.path().join(\"socket\");\n\n\n\n let listener = Async::<UnixListener>::bind(&path)?;\n\n\n\n let mut stream = Async::<UnixStream>::connect(&path).await?;\n\n stream.write_all(LOREM_IPSUM).await?;\n\n\n\n let mut buf = [0; 1024];\n\n let mut incoming = listener.incoming();\n\n let mut stream = incoming.next().await.unwrap()?;\n\n\n\n let n = stream.read(&mut buf).await?;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "tests/async_io.rs", "rank": 21, "score": 68281.61412628669 }, { "content": "#[cfg(unix)]\n\n#[test]\n\nfn uds_connect() -> io::Result<()> {\n\n smol::run(async {\n\n let dir = tempdir()?;\n\n let path = dir.path().join(\"socket\");\n\n let listener = Async::<UnixListener>::bind(&path)?;\n\n\n\n let addr = listener.get_ref().local_addr()?;\n\n let task = Task::spawn(async move { listener.accept().await });\n\n\n\n let stream2 = Async::<UnixStream>::connect(addr.as_pathname().unwrap()).await?;\n\n let stream1 = task.await?.0;\n\n\n\n assert_eq!(\n\n stream1.get_ref().peer_addr()?.as_pathname(),\n\n stream2.get_ref().local_addr()?.as_pathname(),\n\n );\n\n assert_eq!(\n\n stream2.get_ref().peer_addr()?.as_pathname(),\n\n stream1.get_ref().local_addr()?.as_pathname(),\n\n );\n", "file_path": "tests/async_io.rs", "rank": 22, "score": 68281.61412628669 }, { "content": "#[test]\n\nfn tcp_connect() -> io::Result<()> {\n\n smol::run(async {\n\n let listener = Async::<TcpListener>::bind(\"127.0.0.1:12300\")?;\n\n let addr = listener.get_ref().local_addr()?;\n\n let task = Task::spawn(async move { listener.accept().await });\n\n\n\n let stream2 = Async::<TcpStream>::connect(&addr).await?;\n\n let stream1 = task.await?.0;\n\n\n\n assert_eq!(\n\n stream1.get_ref().peer_addr()?,\n\n stream2.get_ref().local_addr()?,\n\n );\n\n assert_eq!(\n\n stream2.get_ref().peer_addr()?,\n\n stream1.get_ref().local_addr()?,\n\n );\n\n\n\n // Now that the listener is closed, connect should fail.\n\n let err = Async::<TcpStream>::connect(&addr).await.unwrap_err();\n\n assert_eq!(err.kind(), io::ErrorKind::ConnectionRefused);\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "tests/async_io.rs", "rank": 23, "score": 68281.61412628669 }, { "content": "#[cfg(target_os = \"linux\")]\n\nfn main() -> std::io::Result<()> {\n\n use std::ffi::OsString;\n\n use std::io;\n\n\n\n use inotify::{EventMask, Inotify, WatchMask};\n\n use smol::Async;\n\n\n\n type Event = (OsString, EventMask);\n\n\n\n /// Reads some events without blocking.\n\n ///\n\n /// If there are no events, an [`io::ErrorKind::WouldBlock`] error is returned.\n\n fn read_op(inotify: &mut Inotify) -> io::Result<Vec<Event>> {\n\n let mut buffer = [0; 1024];\n\n let events = inotify\n\n .read_events(&mut buffer)?\n\n .filter_map(|ev| ev.name.map(|name| (name.to_owned(), ev.mask)))\n\n .collect::<Vec<_>>();\n\n\n\n if events.is_empty() {\n", "file_path": "examples/linux-inotify.rs", "rank": 24, "score": 68066.0836392206 }, { "content": "#[cfg(target_os = \"linux\")]\n\nfn main() -> std::io::Result<()> {\n\n use std::io;\n\n use std::os::unix::io::AsRawFd;\n\n use std::time::{Duration, Instant};\n\n\n\n use smol::Async;\n\n use timerfd::{SetTimeFlags, TimerFd, TimerState};\n\n\n\n /// Converts a [`nix::Error`] into [`std::io::Error`].\n\n fn io_err(err: nix::Error) -> io::Error {\n\n match err {\n\n nix::Error::Sys(code) => code.into(),\n\n err => io::Error::new(io::ErrorKind::Other, Box::new(err)),\n\n }\n\n }\n\n\n\n /// Sleeps using an OS timer.\n\n async fn sleep(dur: Duration) -> io::Result<()> {\n\n // Create an OS timer.\n\n let mut timer = TimerFd::new()?;\n", "file_path": "examples/linux-timerfd.rs", "rank": 25, "score": 68066.0836392206 }, { "content": "#[cfg(unix)]\n\n#[test]\n\nfn uds_send_recv() -> io::Result<()> {\n\n smol::run(async {\n\n let (socket1, socket2) = Async::<UnixDatagram>::pair()?;\n\n\n\n socket1.send(LOREM_IPSUM).await?;\n\n let mut buf = [0; 1024];\n\n let n = socket2.recv(&mut buf).await?;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "tests/async_io.rs", "rank": 26, "score": 66113.38513475374 }, { "content": "#[cfg(unix)]\n\n#[test]\n\nfn uds_send_to_recv_from() -> io::Result<()> {\n\n smol::run(async {\n\n let dir = tempdir()?;\n\n let path = dir.path().join(\"socket\");\n\n let socket1 = Async::<UnixDatagram>::bind(&path)?;\n\n let socket2 = Async::<UnixDatagram>::unbound()?;\n\n\n\n socket2.send_to(LOREM_IPSUM, &path).await?;\n\n let mut buf = [0; 1024];\n\n let n = socket1.recv_from(&mut buf).await?.0;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "tests/async_io.rs", "rank": 27, "score": 66113.38513475374 }, { "content": "#[test]\n\nfn udp_send_recv() -> io::Result<()> {\n\n smol::run(async {\n\n let socket1 = Async::<UdpSocket>::bind(\"127.0.0.1:12302\")?;\n\n let socket2 = Async::<UdpSocket>::bind(\"127.0.0.1:12303\")?;\n\n socket1.get_ref().connect(socket2.get_ref().local_addr()?)?;\n\n\n\n let mut buf = [0u8; 1024];\n\n\n\n socket1.send(LOREM_IPSUM).await?;\n\n let n = socket2.peek(&mut buf).await?;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n let n = socket2.recv(&mut buf).await?;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n\n\n socket2\n\n .send_to(LOREM_IPSUM, socket1.get_ref().local_addr()?)\n\n .await?;\n\n let n = socket1.peek_from(&mut buf).await?.0;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n let n = socket1.recv_from(&mut buf).await?.0;\n\n assert_eq!(&buf[..n], LOREM_IPSUM);\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "tests/async_io.rs", "rank": 28, "score": 66113.38513475374 }, { "content": "#[derive(Debug)]\n\nstruct Wakers {\n\n /// Tasks waiting for the next readability event.\n\n readers: Vec<Waker>,\n\n\n\n /// Tasks waiting for the next writability event.\n\n writers: Vec<Waker>,\n\n}\n\n\n\nimpl Source {\n\n /// Re-registers the I/O event to wake the poller.\n\n pub(crate) fn reregister_io_event(&self) -> io::Result<()> {\n\n let wakers = self.wakers.lock();\n\n Reactor::get()\n\n .sys\n\n .reregister(self.raw, self.key, true, !wakers.writers.is_empty())?;\n\n Ok(())\n\n }\n\n\n\n /// Waits until the I/O source is readable.\n\n ///\n", "file_path": "src/reactor.rs", "rank": 29, "score": 58449.75692571869 }, { "content": "/// Current state of the blocking executor.\n\nstruct State {\n\n /// Number of idle threads in the pool.\n\n ///\n\n /// Idle threads are sleeping, waiting to get a task to run.\n\n idle_count: usize,\n\n\n\n /// Total number of thread in the pool.\n\n ///\n\n /// This is the number of idle threads + the number of active threads.\n\n thread_count: usize,\n\n\n\n /// The queue of blocking tasks.\n\n queue: VecDeque<Runnable>,\n\n}\n\n\n\nimpl BlockingExecutor {\n\n /// Returns a reference to the blocking executor.\n\n pub fn get() -> &'static BlockingExecutor {\n\n static EXECUTOR: Lazy<BlockingExecutor> = Lazy::new(|| BlockingExecutor {\n\n state: Mutex::new(State {\n", "file_path": "src/blocking.rs", "rank": 30, "score": 58449.75692571869 }, { "content": "#[derive(Clone)]\n\nstruct SmolExecutor;\n\n\n\nimpl<F: Future + Send + 'static> hyper::rt::Executor<F> for SmolExecutor {\n\n fn execute(&self, fut: F) {\n\n Task::spawn(async { drop(fut.await) }).detach();\n\n }\n\n}\n\n\n", "file_path": "examples/hyper-server.rs", "rank": 31, "score": 55321.11832310063 }, { "content": "/// Listens for incoming connections.\n\nstruct SmolListener {\n\n listener: Async<TcpListener>,\n\n tls: Option<TlsAcceptor>,\n\n}\n\n\n\nimpl SmolListener {\n\n fn new(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Self {\n\n Self { listener, tls }\n\n }\n\n}\n\n\n\nimpl hyper::server::accept::Accept for SmolListener {\n\n type Conn = SmolStream;\n\n type Error = Error;\n\n\n\n fn poll_accept(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context,\n\n ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {\n\n let poll = Pin::new(&mut self.listener.incoming()).poll_next(cx);\n", "file_path": "examples/hyper-server.rs", "rank": 32, "score": 55321.11832310063 }, { "content": "#[derive(Clone)]\n\nstruct SmolExecutor;\n\n\n\nimpl<F: Future + Send + 'static> hyper::rt::Executor<F> for SmolExecutor {\n\n fn execute(&self, fut: F) {\n\n Task::spawn(async { drop(fut.await) }).detach();\n\n }\n\n}\n\n\n\n/// Connects to URLs.\n", "file_path": "examples/hyper-client.rs", "rank": 33, "score": 55321.11832310063 }, { "content": "#[derive(Clone)]\n\nstruct SmolConnector;\n\n\n\nimpl hyper::service::Service<Uri> for SmolConnector {\n\n type Response = SmolStream;\n\n type Error = Error;\n\n type Future = future::BoxFuture<'static, Result<Self::Response, Self::Error>>;\n\n\n\n fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {\n\n Poll::Ready(Ok(()))\n\n }\n\n\n\n fn call(&mut self, uri: Uri) -> Self::Future {\n\n Box::pin(async move {\n\n let host = uri.host().context(\"cannot parse host\")?;\n\n\n\n match uri.scheme_str() {\n\n Some(\"http\") => {\n\n let addr = format!(\"{}:{}\", uri.host().unwrap(), uri.port_u16().unwrap_or(80));\n\n let stream = Async::<TcpStream>::connect(addr).await?;\n\n Ok(SmolStream::Plain(stream))\n", "file_path": "examples/hyper-client.rs", "rank": 34, "score": 55321.11832310063 }, { "content": "#[test]\n\nfn spawn() {\n\n assert_eq!(42, smol::run(smol::Task::spawn(async { 42 })));\n\n}\n\n\n", "file_path": "tests/task.rs", "rank": 35, "score": 52147.90742813463 }, { "content": "#[test]\n\nfn timer_after() {\n\n let before = smol::run(async {\n\n let now = Instant::now();\n\n Timer::after(Duration::from_secs(1)).await;\n\n now\n\n });\n\n\n\n assert!(before.elapsed() >= Duration::from_secs(1));\n\n}\n", "file_path": "tests/timer.rs", "rank": 36, "score": 52147.90742813463 }, { "content": "#[test]\n\nfn timer_at() {\n\n let before = smol::run(async {\n\n let now = Instant::now();\n\n let when = now + Duration::from_secs(1);\n\n Timer::at(when).await;\n\n now\n\n });\n\n\n\n assert!(before.elapsed() >= Duration::from_secs(1));\n\n}\n\n\n", "file_path": "tests/timer.rs", "rank": 37, "score": 52147.90742813463 }, { "content": "#[test]\n\nfn blocking() {\n\n assert_eq!(42, smol::run(smol::Task::blocking(async { 42 })));\n\n}\n\n\n", "file_path": "tests/task.rs", "rank": 38, "score": 52147.90742813463 }, { "content": "fn main() {\n\n // Set a handler that sends a message through a channel.\n\n let (s, ctrl_c) = piper::chan(100);\n\n let handle = move || {\n\n let _ = s.send(()).now_or_never();\n\n };\n\n ctrlc::set_handler(handle).unwrap();\n\n\n\n smol::run(async {\n\n println!(\"Waiting for Ctrl-C...\");\n\n\n\n // Receive a message that indicates the Ctrl-C signal occured.\n\n ctrl_c.recv().await;\n\n\n\n println!(\"Done!\");\n\n })\n\n}\n", "file_path": "examples/ctrl-c.rs", "rank": 39, "score": 52147.90742813463 }, { "content": "#[test]\n\nfn blocking_detach() {\n\n let (s, r) = piper::chan(1);\n\n smol::Task::blocking(async move { s.send(()).await }).detach();\n\n assert_eq!(Some(()), smol::run(r.recv()));\n\n}\n", "file_path": "tests/task.rs", "rank": 40, "score": 50550.67351470057 }, { "content": "#[cfg(not(unix))]\n\nfn main() {\n\n println!(\"This example works only on Unix systems!\");\n\n}\n", "file_path": "examples/unix-signal.rs", "rank": 41, "score": 50550.67351470057 }, { "content": "#[test]\n\nfn spawn_detach() {\n\n let (s, r) = piper::chan(1);\n\n smol::Task::spawn(async move { s.send(()).await }).detach();\n\n assert_eq!(Some(()), smol::run(r.recv()));\n\n}\n\n\n", "file_path": "tests/task.rs", "rank": 42, "score": 50550.67351470057 }, { "content": "#[cfg(not(windows))]\n\nfn main() {\n\n println!(\"This example works only on Windows!\");\n\n}\n", "file_path": "examples/windows-uds.rs", "rank": 43, "score": 50550.67351470057 }, { "content": "fn main() -> Result<()> {\n\n smol::run(async {\n\n // Sleep using async-std.\n\n let start = Instant::now();\n\n println!(\"Sleeping using async-std...\");\n\n async_std::task::sleep(Duration::from_secs(1)).await;\n\n println!(\"Woke up after {:?}\", start.elapsed());\n\n\n\n // Sleep using tokio (the `tokio02` feature must be enabled).\n\n let start = Instant::now();\n\n println!(\"Sleeping using tokio...\");\n\n tokio::time::delay_for(Duration::from_secs(1)).await;\n\n println!(\"Woke up after {:?}\", start.elapsed());\n\n\n\n // Make a GET request using surf.\n\n let body = surf::get(\"https://www.rust-lang.org\")\n\n .recv_string()\n\n .await\n\n .map_err(Error::msg)?;\n\n println!(\"Body from surf: {:?}\", body);\n\n\n\n // Make a GET request using reqwest (the `tokio02` feature must be enabled).\n\n let resp = reqwest::get(\"https://www.rust-lang.org\").await?;\n\n let body = resp.text().await?;\n\n println!(\"Body from reqwest: {:?}\", body);\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/other-runtimes.rs", "rank": 44, "score": 48457.80449209733 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate, private key, and password.\n\n let identity = Identity::from_pkcs12(include_bytes!(\"identity.pfx\"), \"password\")?;\n\n let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);\n\n\n\n // Create an executor thread pool.\n\n let num_threads = num_cpus::get().max(1);\n\n for _ in 0..num_threads {\n\n thread::spawn(|| smol::run(future::pending::<()>()));\n\n }\n\n\n\n // Start HTTP and HTTPS servers.\n\n smol::run(async {\n\n let http = listen(Async::<TcpListener>::bind(\"127.0.0.1:8000\")?, None);\n\n let https = listen(Async::<TcpListener>::bind(\"127.0.0.1:8001\")?, Some(tls));\n\n future::try_join(http, https).await?;\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/simple-server.rs", "rank": 45, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n smol::run(async {\n\n // Create a request.\n\n let req = Request::get(\"https://www.rust-lang.org\").body(Body::empty())?;\n\n\n\n // Fetch the response.\n\n let resp = fetch(req).await?;\n\n println!(\"{:#?}\", resp);\n\n\n\n // Read the message body.\n\n let body = resp\n\n .into_body()\n\n .try_fold(Vec::new(), |mut body, chunk| async move {\n\n body.extend_from_slice(&chunk);\n\n Ok(body)\n\n })\n\n .await?;\n\n println!(\"{}\", String::from_utf8_lossy(&body));\n\n\n\n Ok(())\n\n })\n\n}\n\n\n\n/// Spawns futures.\n", "file_path": "examples/hyper-client.rs", "rank": 46, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n smol::run(async {\n\n let addr = \"https://www.rust-lang.org\";\n\n let resp = fetch(addr).await?;\n\n println!(\"{}\", String::from_utf8_lossy(&resp));\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/simple-client.rs", "rank": 47, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate, private key, and password.\n\n let identity = Identity::from_pkcs12(include_bytes!(\"identity.pfx\"), \"password\")?;\n\n let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);\n\n\n\n // Create an executor thread pool.\n\n for _ in 0..num_cpus::get().max(1) {\n\n thread::spawn(|| smol::run(future::pending::<()>()));\n\n }\n\n\n\n // Start WS and WSS servers.\n\n smol::block_on(async {\n\n let ws = listen(Async::<TcpListener>::bind(\"127.0.0.1:9000\")?, None);\n\n let wss = listen(Async::<TcpListener>::bind(\"127.0.0.1:9001\")?, Some(tls));\n\n future::try_join(ws, wss).await?;\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "examples/websocket-server.rs", "rank": 48, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate.\n\n let mut builder = native_tls::TlsConnector::builder();\n\n builder.add_root_certificate(Certificate::from_pem(include_bytes!(\"certificate.pem\"))?);\n\n let tls = TlsConnector::from(builder);\n\n\n\n smol::run(async {\n\n // Create async stdin and stdout handles.\n\n let stdin = smol::reader(std::io::stdin());\n\n let mut stdout = smol::writer(std::io::stdout());\n\n\n\n // Connect to the server.\n\n let stream = Async::<TcpStream>::connect(\"127.0.0.1:7001\").await?;\n\n let stream = tls.connect(\"127.0.0.1\", stream).await?;\n\n println!(\"Connected to {}\", stream.get_ref().get_ref().peer_addr()?);\n\n println!(\"Type a message and hit enter!\\n\");\n\n\n\n // Pipe messages from stdin to the server and pipe messages from the server to stdout.\n\n let stream = Mutex::new(stream);\n\n future::try_join(\n\n io::copy(stdin, &mut &stream),\n\n io::copy(&stream, &mut stdout),\n\n )\n\n .await?;\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/tls-client.rs", "rank": 49, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate, private key, and password.\n\n let identity = Identity::from_pkcs12(include_bytes!(\"identity.pfx\"), \"password\")?;\n\n let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);\n\n\n\n // Create an executor thread pool.\n\n for _ in 0..num_cpus::get().max(1) {\n\n thread::spawn(|| smol::run(future::pending::<()>()));\n\n }\n\n\n\n // Start HTTP and HTTPS servers.\n\n smol::block_on(async {\n\n let http = listen(Async::<TcpListener>::bind(\"127.0.0.1:8000\")?, None);\n\n let https = listen(Async::<TcpListener>::bind(\"127.0.0.1:8001\")?, Some(tls));\n\n future::try_join(http, https).await?;\n\n Ok(())\n\n })\n\n}\n\n\n\n/// Spawns futures.\n", "file_path": "examples/hyper-server.rs", "rank": 50, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate.\n\n let mut builder = native_tls::TlsConnector::builder();\n\n builder.add_root_certificate(Certificate::from_pem(include_bytes!(\"certificate.pem\"))?);\n\n let tls = TlsConnector::from(builder);\n\n\n\n smol::run(async {\n\n // Connect to the server.\n\n let (mut stream, resp) = connect(\"wss://127.0.0.1:9001\", tls).await?;\n\n dbg!(resp);\n\n\n\n // Send a message and receive a response.\n\n stream.send(Message::text(\"Hello!\")).await?;\n\n dbg!(stream.next().await);\n\n\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "examples/websocket-client.rs", "rank": 51, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n // Initialize TLS with the local certificate, private key, and password.\n\n let identity = Identity::from_pkcs12(include_bytes!(\"identity.pfx\"), \"password\")?;\n\n let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);\n\n\n\n smol::run(async {\n\n // Create a listener.\n\n let listener = Async::<TcpListener>::bind(\"127.0.0.1:7001\")?;\n\n println!(\"Listening on {}\", listener.get_ref().local_addr()?);\n\n println!(\"Now start a TLS client.\");\n\n\n\n // Accept clients in a loop.\n\n loop {\n\n let (stream, _) = listener.accept().await?;\n\n let stream = tls.accept(stream).await?;\n\n println!(\n\n \"Accepted client: {}\",\n\n stream.get_ref().get_ref().peer_addr()?\n\n );\n\n\n\n // Spawn a task that echoes messages from the client back to it.\n\n Task::spawn(echo(stream)).unwrap().detach();\n\n }\n\n })\n\n}\n", "file_path": "examples/tls-server.rs", "rank": 52, "score": 47014.727203016155 }, { "content": "fn main() -> Result<()> {\n\n smol::run(async {\n\n let mut seen = HashSet::new();\n\n let mut queue = VecDeque::new();\n\n seen.insert(ROOT.to_string());\n\n queue.push_back(ROOT.to_string());\n\n\n\n let (s, r) = piper::chan(200);\n\n let mut tasks = 0;\n\n\n\n // Loop while the queue is not empty or tasks are fetching pages.\n\n while queue.len() + tasks > 0 {\n\n // Limit the number of concurrent tasks.\n\n while tasks < s.capacity() {\n\n // Process URLs in the queue and fetch more pages.\n\n match queue.pop_front() {\n\n None => break,\n\n Some(url) => {\n\n println!(\"{}\", url);\n\n tasks += 1;\n", "file_path": "examples/web-crawler.rs", "rank": 53, "score": 47014.727203016155 }, { "content": "/// Same as `std::thread::current().id()`, but more efficient.\n\nfn thread_id() -> ThreadId {\n\n thread_local! {\n\n static ID: ThreadId = thread::current().id();\n\n }\n\n\n\n ID.try_with(|id| *id)\n\n .unwrap_or_else(|_| thread::current().id())\n\n}\n", "file_path": "src/thread_local.rs", "rank": 54, "score": 44509.62970852317 }, { "content": "fn main() -> io::Result<()> {\n\n smol::run(async {\n\n // Create a listener for incoming client connections.\n\n let listener = Async::<TcpListener>::bind(\"127.0.0.1:6000\")?;\n\n\n\n // Intro messages.\n\n println!(\"Listening on {}\", listener.get_ref().local_addr()?);\n\n println!(\"Start a chat client now!\\n\");\n\n\n\n // Spawn a background task that dispatches events to clients.\n\n let (sender, receiver) = piper::chan(100);\n\n Task::spawn(dispatch(receiver)).unwrap().detach();\n\n\n\n loop {\n\n // Accept the next connection.\n\n let (stream, addr) = listener.accept().await?;\n\n let client = Arc::new(stream);\n\n let sender = sender.clone();\n\n\n\n // Spawn a background task reading messages from the client.\n", "file_path": "examples/chat-server.rs", "rank": 55, "score": 43996.88430166576 }, { "content": "fn main() -> io::Result<()> {\n\n smol::run(async {\n\n // Create a listener.\n\n let listener = Async::<TcpListener>::bind(\"127.0.0.1:7000\")?;\n\n println!(\"Listening on {}\", listener.get_ref().local_addr()?);\n\n println!(\"Now start a TCP client.\");\n\n\n\n // Accept clients in a loop.\n\n loop {\n\n let (stream, peer_addr) = listener.accept().await?;\n\n println!(\"Accepted client: {}\", peer_addr);\n\n\n\n // Spawn a task that echoes messages from the client back to it.\n\n Task::spawn(echo(stream)).unwrap().detach();\n\n }\n\n })\n\n}\n", "file_path": "examples/tcp-server.rs", "rank": 56, "score": 43996.88430166576 }, { "content": "fn main() -> io::Result<()> {\n\n smol::run(async {\n\n // Connect to the server and create async stdin and stdout.\n\n let stream = Async::<TcpStream>::connect(\"127.0.0.1:6000\").await?;\n\n let stdin = smol::reader(std::io::stdin());\n\n let mut stdout = smol::writer(std::io::stdout());\n\n\n\n // Intro messages.\n\n println!(\"Connected to {}\", stream.get_ref().peer_addr()?);\n\n println!(\"My nickname: {}\", stream.get_ref().local_addr()?);\n\n println!(\"Type a message and hit enter!\\n\");\n\n\n\n // References to `Async<T>` also implement `AsyncRead` and `AsyncWrite`.\n\n let stream_r = &stream;\n\n let mut stream_w = &stream;\n\n\n\n // Wait until the standard input is closed or the connection is closed.\n\n futures::select! {\n\n _ = io::copy(stdin, &mut stream_w).fuse() => println!(\"Quit!\"),\n\n _ = io::copy(stream_r, &mut stdout).fuse() => println!(\"Server disconnected!\"),\n\n }\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/chat-client.rs", "rank": 57, "score": 43996.88430166576 }, { "content": "fn main() -> io::Result<()> {\n\n smol::run(async {\n\n // Create async stdin and stdout handles.\n\n let stdin = smol::reader(std::io::stdin());\n\n let mut stdout = smol::writer(std::io::stdout());\n\n\n\n // Connect to the server.\n\n let stream = Async::<TcpStream>::connect(\"127.0.0.1:7000\").await?;\n\n println!(\"Connected to {}\", stream.get_ref().peer_addr()?);\n\n println!(\"Type a message and hit enter!\\n\");\n\n\n\n // Pipe messages from stdin to the server and pipe messages from the server to stdout.\n\n future::try_join(\n\n io::copy(stdin, &mut &stream),\n\n io::copy(&stream, &mut stdout),\n\n )\n\n .await?;\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/tcp-client.rs", "rank": 58, "score": 43996.88430166576 }, { "content": "/// Returns a random number in the interval `0..n`.\n\nfn fast_random(n: usize) -> usize {\n\n thread_local! {\n\n static RNG: Cell<Wrapping<u32>> = Cell::new(Wrapping(1));\n\n }\n\n\n\n RNG.with(|rng| {\n\n // This is the 32-bit variant of Xorshift: https://en.wikipedia.org/wiki/Xorshift\n\n let mut x = rng.get();\n\n x ^= x << 13;\n\n x ^= x >> 17;\n\n x ^= x << 5;\n\n rng.set(x);\n\n\n\n // This is a fast alternative to `x % n`:\n\n // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/\n\n ((x.0 as u64).wrapping_mul(n as u64) >> 32) as usize\n\n })\n\n}\n\n\n", "file_path": "src/work_stealing.rs", "rank": 59, "score": 41382.20044526545 }, { "content": "#[cfg(unix)]\n\nfn main() -> std::io::Result<()> {\n\n use std::os::unix::net::UnixStream;\n\n\n\n use futures::prelude::*;\n\n use smol::Async;\n\n\n\n smol::run(async {\n\n // Create a Unix stream that receives a byte on each signal occurrence.\n\n let (a, mut b) = Async::<UnixStream>::pair()?;\n\n signal_hook::pipe::register(signal_hook::SIGINT, a)?;\n\n println!(\"Waiting for Ctrl-C...\");\n\n\n\n // Receive a byte that indicates the Ctrl-C signal occured.\n\n b.read_exact(&mut [0]).await?;\n\n\n\n println!(\"Done!\");\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "examples/unix-signal.rs", "rank": 60, "score": 41382.20044526545 }, { "content": "#[cfg(windows)]\n\nfn main() -> std::io::Result<()> {\n\n use std::path::PathBuf;\n\n\n\n use futures::io;\n\n use futures::prelude::*;\n\n use smol::{Async, Task};\n\n use tempfile::tempdir;\n\n use uds_windows::{UnixListener, UnixStream};\n\n\n\n async fn client(addr: PathBuf) -> io::Result<()> {\n\n // Connect to the address.\n\n let stream = Async::new(UnixStream::connect(addr)?)?;\n\n println!(\"Connected to {:?}\", stream.get_ref().peer_addr()?);\n\n\n\n // Pipe the stream to stdout.\n\n let mut stdout = smol::writer(std::io::stdout());\n\n io::copy(&stream, &mut stdout).await?;\n\n Ok(())\n\n }\n\n\n", "file_path": "examples/windows-uds.rs", "rank": 61, "score": 41382.20044526545 }, { "content": "/// Extracts links from a HTML body.\n\nfn links(body: String) -> Vec<String> {\n\n let mut v = Vec::new();\n\n for elem in Html::parse_fragment(&body).select(&Selector::parse(\"a\").unwrap()) {\n\n if let Some(link) = elem.value().attr(\"href\") {\n\n v.push(link.to_string());\n\n }\n\n }\n\n v\n\n}\n\n\n", "file_path": "examples/web-crawler.rs", "rank": 62, "score": 39088.97273643721 }, { "content": " timer.set_state(TimerState::Oneshot(dur), SetTimeFlags::Default);\n\n\n\n // When the OS timer fires, a 64-bit integer can be read from it.\n\n Async::new(timer)?\n\n .read_with(|t| nix::unistd::read(t.as_raw_fd(), &mut [0u8; 8]).map_err(io_err))\n\n .await?;\n\n Ok(())\n\n }\n\n\n\n smol::run(async {\n\n let start = Instant::now();\n\n println!(\"Sleeping...\");\n\n\n\n // Sleep for a second using an OS timer.\n\n sleep(Duration::from_secs(1)).await?;\n\n\n\n println!(\"Woke up after {:?}\", start.elapsed());\n\n Ok(())\n\n })\n\n}\n\n\n", "file_path": "examples/linux-timerfd.rs", "rank": 63, "score": 32410.36159504375 }, { "content": " Err(io::ErrorKind::WouldBlock.into())\n\n } else {\n\n Ok(events)\n\n }\n\n }\n\n\n\n smol::run(async {\n\n // Watch events in the current directory.\n\n let mut inotify = Async::new(Inotify::init()?)?;\n\n inotify.get_mut().add_watch(\".\", WatchMask::ALL_EVENTS)?;\n\n println!(\"Watching for filesystem events in the current directory...\");\n\n println!(\"Try opening a file to trigger some events.\");\n\n println!();\n\n\n\n // Wait for events in a loop and print them on the screen.\n\n loop {\n\n for event in inotify.read_with_mut(read_op).await? {\n\n println!(\"{:?}\", event);\n\n }\n\n }\n\n })\n\n}\n\n\n", "file_path": "examples/linux-inotify.rs", "rank": 64, "score": 32401.54131651692 }, { "content": "//! Uses the `timerfd` crate to sleep using an OS timer.\n\n//!\n\n//! Run with:\n\n//!\n\n//! ```\n\n//! cd examples # make sure to be in this directory\n\n//! cargo run --example linux-timerfd\n\n//! ```\n\n\n\n#[cfg(target_os = \"linux\")]\n", "file_path": "examples/linux-timerfd.rs", "rank": 65, "score": 32387.974529302268 }, { "content": "//! Uses the `inotify` crate to watch for changes in the current directory.\n\n//!\n\n//! Run with:\n\n//!\n\n//! ```\n\n//! cd examples # make sure to be in this directory\n\n//! cargo run --example linux-inotify\n\n//! ```\n\n\n\n#[cfg(target_os = \"linux\")]\n", "file_path": "examples/linux-inotify.rs", "rank": 66, "score": 32387.18971021897 }, { "content": " /// let len = socket.write_with_mut(|s| s.send(msg)).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn write_with_mut<R>(\n\n &mut self,\n\n op: impl FnMut(&mut T) -> io::Result<R>,\n\n ) -> io::Result<R> {\n\n let mut op = op;\n\n loop {\n\n match op(self.get_mut()) {\n\n Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}\n\n res => return res,\n\n }\n\n self.source.writable().await?;\n\n }\n\n }\n\n}\n\n\n\nimpl<T> Drop for Async<T> {\n\n fn drop(&mut self) {\n", "file_path": "src/async_io.rs", "rank": 67, "score": 30959.560931646105 }, { "content": " ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::TcpListener;\n\n ///\n\n /// # smol::run(async {\n\n /// let mut listener = Async::<TcpListener>::bind(\"127.0.0.1:80\")?;\n\n ///\n\n /// // Accept a new client asynchronously.\n\n /// let (stream, addr) = listener.read_with_mut(|l| l.accept()).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn read_with_mut<R>(\n\n &mut self,\n\n op: impl FnMut(&mut T) -> io::Result<R>,\n\n ) -> io::Result<R> {\n\n let mut op = op;\n\n loop {\n\n match op(self.get_mut()) {\n\n Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}\n", "file_path": "src/async_io.rs", "rank": 68, "score": 30956.21614745096 }, { "content": " /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::UdpSocket;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let (len, addr) = socket.peek_from(&mut buf).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {\n\n self.read_with(|io| io.peek_from(buf)).await\n\n }\n\n\n\n /// Sends data to the specified address.\n\n ///\n\n /// Returns the number of bytes writen.\n\n ///\n\n /// # Examples\n", "file_path": "src/async_io.rs", "rank": 69, "score": 30955.81229569861 }, { "content": " ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n /// socket.get_ref().connect(\"127.0.0.1:8000\")?;\n\n ///\n\n /// let msg = b\"hello\";\n\n /// let len = socket.write_with(|s| s.send(msg)).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn write_with<R>(&self, op: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {\n\n let mut op = op;\n\n loop {\n\n match op(self.get_ref()) {\n\n Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}\n\n res => return res,\n\n }\n\n self.source.writable().await?;\n\n }\n\n }\n\n\n", "file_path": "src/async_io.rs", "rank": 70, "score": 30955.549859868705 }, { "content": " let stream = Async::new(socket.into_tcp_stream())?;\n\n\n\n // Waits for connect to complete.\n\n let wait_connect = |mut stream: &TcpStream| match stream.write(&[]) {\n\n Err(err) if err.kind() == io::ErrorKind::NotConnected => match stream.take_error()? {\n\n Some(err) => Err(err),\n\n None => Err(io::ErrorKind::WouldBlock.into()),\n\n },\n\n res => res.map(|_| ()),\n\n };\n\n\n\n // The stream becomes writable when connected.\n\n match stream.write_with(|io| wait_connect(io)).await {\n\n Ok(()) => Ok(stream),\n\n Err(err) => match stream.get_ref().take_error()? {\n\n Some(err) => Err(err),\n\n None => Err(err),\n\n },\n\n }\n\n }\n", "file_path": "src/async_io.rs", "rank": 71, "score": 30955.27992060843 }, { "content": " Err(err)\n\n }\n\n })?;\n\n let stream = Async::new(socket.into_unix_stream())?;\n\n\n\n // Waits for connect to complete.\n\n let wait_connect = |mut stream: &UnixStream| match stream.write(&[]) {\n\n Err(err) if err.kind() == io::ErrorKind::NotConnected => match stream.take_error()? {\n\n Some(err) => Err(err),\n\n None => Err(io::ErrorKind::WouldBlock.into()),\n\n },\n\n res => res.map(|_| ()),\n\n };\n\n\n\n // The stream becomes writable when connected.\n\n match stream.write_with(|io| wait_connect(io)).await {\n\n Ok(()) => Ok(stream),\n\n Err(err) => match stream.get_ref().take_error()? {\n\n Some(err) => Err(err),\n\n None => Err(err),\n", "file_path": "src/async_io.rs", "rank": 72, "score": 30955.046761852238 }, { "content": " /// use smol::Async;\n\n /// use std::net::UdpSocket;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n /// socket.get_ref().connect(\"127.0.0.1:8000\")?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let len = socket.peek(&mut buf).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.read_with(|io| io.peek(buf)).await\n\n }\n\n\n\n /// Sends data to the connected peer.\n\n ///\n\n /// Returns the number of bytes written.\n\n ///\n\n /// The [`connect`][`UdpSocket::connect()`] method connects this socket to a remote address.\n", "file_path": "src/async_io.rs", "rank": 73, "score": 30954.871179783375 }, { "content": " /// ```no_run\n\n /// use smol::Async;\n\n /// use std::os::unix::net::UnixDatagram;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UnixDatagram>::bind(\"/tmp/socket\")?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let (len, addr) = socket.recv_from(&mut buf).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, UnixSocketAddr)> {\n\n self.read_with(|io| io.recv_from(buf)).await\n\n }\n\n\n\n /// Sends data to the specified address.\n\n ///\n\n /// Returns the number of bytes written.\n\n ///\n\n /// # Examples\n", "file_path": "src/async_io.rs", "rank": 74, "score": 30954.800976687435 }, { "content": "/// futures::io::copy(reader, &mut writer).await?;\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\n///\n\n/// If a type does but its reference doesn't implement [`AsyncRead`] and [`AsyncWrite`], wrap it in\n\n/// [piper]'s `Mutex`:\n\n///\n\n/// ```no_run\n\n/// use futures::prelude::*;\n\n/// use piper::{Arc, Mutex};\n\n/// use smol::Async;\n\n/// use std::net::TcpStream;\n\n///\n\n/// # smol::run(async {\n\n/// // Reads data from a stream and echoes it back.\n\n/// async fn echo(stream: impl AsyncRead + AsyncWrite + Unpin) -> std::io::Result<u64> {\n\n/// let stream = Mutex::new(stream);\n\n///\n\n/// // Create two handles to the stream.\n\n/// let reader = Arc::new(stream);\n", "file_path": "src/async_io.rs", "rank": 75, "score": 30954.24372557651 }, { "content": " ///\n\n /// The [`connect`][`UnixDatagram::connect()`] method connects this socket to a remote address.\n\n /// This method will fail if the socket is not connected.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::os::unix::net::UnixDatagram;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UnixDatagram>::bind(\"/tmp/socket1\")?;\n\n /// socket.get_ref().connect(\"/tmp/socket2\")?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let len = socket.recv(&mut buf).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.read_with(|io| io.recv(buf)).await\n", "file_path": "src/async_io.rs", "rank": 76, "score": 30953.852590495913 }, { "content": "\n\n /// Reads data from the stream without removing it from the buffer.\n\n ///\n\n /// Returns the number of bytes read. Successive calls of this method read the same data.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::TcpStream;\n\n ///\n\n /// # smol::run(async {\n\n /// let stream = Async::<TcpStream>::connect(\"127.0.0.1:8080\").await?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let len = stream.peek(&mut buf).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.read_with(|io| io.peek(buf)).await\n", "file_path": "src/async_io.rs", "rank": 77, "score": 30953.033642069757 }, { "content": " /// # Examples\n\n ///\n\n /// ```\n\n /// use smol::Async;\n\n /// use std::net::TcpListener;\n\n ///\n\n /// # smol::run(async {\n\n /// let listener = Async::<TcpListener>::bind(\"127.0.0.1:80\")?;\n\n /// let inner = listener.into_inner()?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub fn into_inner(mut self) -> io::Result<T> {\n\n let io = *self.io.take().unwrap();\n\n Reactor::get().remove_io(&self.source)?;\n\n Ok(io)\n\n }\n\n\n\n #[doc(hidden)]\n\n #[deprecated(note = \"use `read_with()` or `write_with()` instead\")]\n\n pub async fn with<R>(&self, op: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {\n", "file_path": "src/async_io.rs", "rank": 78, "score": 30952.76589535797 }, { "content": " let mut op = op;\n\n let io = self.io.as_ref().unwrap();\n\n loop {\n\n match op(io) {\n\n Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}\n\n res => return res,\n\n }\n\n\n\n // Wait until the I/O handle is readable or writable.\n\n let readable = self.source.readable();\n\n let writable = self.source.writable();\n\n futures_util::pin_mut!(readable);\n\n futures_util::pin_mut!(writable);\n\n let _ = future::select(readable, writable).await;\n\n }\n\n }\n\n\n\n #[doc(hidden)]\n\n #[deprecated(note = \"use `read_with_mut()` or `write_with_mut()` instead\")]\n\n pub async fn with_mut<R>(&mut self, op: impl FnMut(&mut T) -> io::Result<R>) -> io::Result<R> {\n", "file_path": "src/async_io.rs", "rank": 79, "score": 30951.97383009925 }, { "content": "}\n\n#[cfg(windows)]\n\nimpl<T: AsRawSocket> Async<T> {\n\n /// Creates an async I/O handle.\n\n ///\n\n /// This function will put the handle in non-blocking mode and register it in [epoll] on\n\n /// Linux/Android, [kqueue] on macOS/iOS/BSD, or [wepoll] on Windows.\n\n /// On Unix systems, the handle must implement `AsRawFd`, while on Windows it must implement\n\n /// `AsRawSocket`.\n\n ///\n\n /// If the handle implements [`Read`] and [`Write`], then `Async<T>` automatically\n\n /// implements [`AsyncRead`] and [`AsyncWrite`].\n\n /// Other I/O operations can be *asyncified* by methods [`Async::with()`] and\n\n /// [`Async::with_mut()`].\n\n ///\n\n /// **NOTE**: Do not use this type with [`File`][`std::fs::File`], [`Stdin`][`std::io::Stdin`],\n\n /// [`Stdout`][`std::io::Stdout`], or [`Stderr`][`std::io::Stderr`] because they're not\n\n /// supported by epoll/kqueue/wepoll.\n\n /// Use [`reader()`][`crate::reader()`] and [`writer()`][`crate::writer()`] functions instead\n\n /// to read/write on a thread.\n", "file_path": "src/async_io.rs", "rank": 80, "score": 30951.626873535824 }, { "content": " /// This method will fail if the socket is not connected.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::UdpSocket;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n /// socket.get_ref().connect(\"127.0.0.1:8000\")?;\n\n ///\n\n /// let msg = b\"hello\";\n\n /// let len = socket.send(msg).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {\n\n self.write_with(|io| io.send(buf)).await\n\n }\n\n}\n", "file_path": "src/async_io.rs", "rank": 81, "score": 30951.30679734592 }, { "content": " /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let (len, addr) = socket.recv_from(&mut buf).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {\n\n self.read_with(|io| io.recv_from(buf)).await\n\n }\n\n\n\n /// Receives a single datagram message without removing it from the queue.\n\n ///\n\n /// Returns the number of bytes read and the address the message came from.\n\n ///\n\n /// This method must be called with a valid byte slice of sufficient size to hold the message.\n\n /// If the message is too long to fit, excess bytes may get discarded.\n\n ///\n\n /// # Examples\n\n ///\n", "file_path": "src/async_io.rs", "rank": 82, "score": 30951.21448450397 }, { "content": " ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::os::unix::net::UnixDatagram;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UnixDatagram>::unbound()?;\n\n ///\n\n /// let msg = b\"hello\";\n\n /// let addr = \"/tmp/socket\";\n\n /// let len = socket.send_to(msg, addr).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {\n\n self.write_with(|io| io.send_to(buf, &path)).await\n\n }\n\n\n\n /// Receives data from the connected peer.\n\n ///\n\n /// Returns the number of bytes read and the address the message came from.\n", "file_path": "src/async_io.rs", "rank": 83, "score": 30950.862241549385 }, { "content": " ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::UdpSocket;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n ///\n\n /// let msg = b\"hello\";\n\n /// let addr = ([127, 0, 0, 1], 8000);\n\n /// let len = socket.send_to(msg, addr).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn send_to<A: Into<SocketAddr>>(&self, buf: &[u8], addr: A) -> io::Result<usize> {\n\n let addr = addr.into();\n\n self.write_with(|io| io.send_to(buf, addr)).await\n\n }\n\n\n\n /// Receives a single datagram message from the connected peer.\n\n ///\n", "file_path": "src/async_io.rs", "rank": 84, "score": 30950.52904307751 }, { "content": " /// ```no_run\n\n /// use smol::Async;\n\n /// use std::os::unix::net::UnixStream;\n\n ///\n\n /// # smol::run(async {\n\n /// let stream = Async::<UnixStream>::connect(\"/tmp/socket\").await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Async<UnixStream>> {\n\n // Create a socket.\n\n let socket = Socket::new(Domain::unix(), Type::stream(), None)?;\n\n\n\n // Begin async connect and ignore the inevitable \"in progress\" error.\n\n socket.set_nonblocking(true)?;\n\n socket\n\n .connect(&socket2::SockAddr::unix(path)?)\n\n .or_else(|err| {\n\n if err.raw_os_error() == Some(nix::libc::EINPROGRESS) {\n\n Ok(())\n\n } else {\n", "file_path": "src/async_io.rs", "rank": 85, "score": 30950.280318553687 }, { "content": " poll_future(cx, self.read_with(|io| (&*io).read_vectored(bufs)))\n\n }\n\n}\n\n\n\nimpl<T: Write> AsyncWrite for Async<T> {\n\n fn poll_write(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &[u8],\n\n ) -> Poll<io::Result<usize>> {\n\n poll_future(cx, self.write_with_mut(|io| io.write(buf)))\n\n }\n\n\n\n fn poll_write_vectored(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n bufs: &[IoSlice<'_>],\n\n ) -> Poll<io::Result<usize>> {\n\n poll_future(cx, self.write_with_mut(|io| io.write_vectored(bufs)))\n\n }\n", "file_path": "src/async_io.rs", "rank": 86, "score": 30950.22386985859 }, { "content": "/// instead to read/write on a thread.\n\n///\n\n/// # Examples\n\n///\n\n/// To make an async I/O handle cloneable, wrap it in [piper]'s `Arc`:\n\n///\n\n/// ```no_run\n\n/// use piper::Arc;\n\n/// use smol::Async;\n\n/// use std::net::TcpStream;\n\n///\n\n/// # smol::run(async {\n\n/// // Connect to a local server.\n\n/// let stream = Async::<TcpStream>::connect(\"127.0.0.1:8000\").await?;\n\n///\n\n/// // Create two handles to the stream.\n\n/// let reader = Arc::new(stream);\n\n/// let mut writer = reader.clone();\n\n///\n\n/// // Echo all messages from the read side of the stream into the write side.\n", "file_path": "src/async_io.rs", "rank": 87, "score": 30950.10919645577 }, { "content": " /// invokes the `op` closure in a loop until it succeeds or returns an error other than\n\n /// [`io::ErrorKind::WouldBlock`]. In between iterations of the loop, it waits until the OS\n\n /// sends a notification that the I/O handle is readable.\n\n ///\n\n /// The closure receives a shared reference to the I/O handle.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::TcpListener;\n\n ///\n\n /// # smol::run(async {\n\n /// let listener = Async::<TcpListener>::bind(\"127.0.0.1:80\")?;\n\n ///\n\n /// // Accept a new client asynchronously.\n\n /// let (stream, addr) = listener.read_with(|l| l.accept()).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn read_with<R>(&self, op: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {\n", "file_path": "src/async_io.rs", "rank": 88, "score": 30949.36990963222 }, { "content": " pub async fn accept(&self) -> io::Result<(Async<TcpStream>, SocketAddr)> {\n\n let (stream, addr) = self.read_with(|io| io.accept()).await?;\n\n Ok((Async::new(stream)?, addr))\n\n }\n\n\n\n /// Returns a stream of incoming TCP connections.\n\n ///\n\n /// The stream is infinite, i.e. it never stops with a [`None`] item.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use futures::prelude::*;\n\n /// use smol::Async;\n\n /// use std::net::TcpListener;\n\n ///\n\n /// # smol::run(async {\n\n /// let listener = Async::<TcpListener>::bind(\"127.0.0.1:80\")?;\n\n /// let mut incoming = listener.incoming();\n\n ///\n", "file_path": "src/async_io.rs", "rank": 89, "score": 30949.28314531311 }, { "content": "\n\n /// The inner I/O handle.\n\n io: Option<Box<T>>,\n\n}\n\n\n\n#[cfg(unix)]\n\nimpl<T: AsRawFd> Async<T> {\n\n /// Creates an async I/O handle.\n\n ///\n\n /// This function will put the handle in non-blocking mode and register it in [epoll] on\n\n /// Linux/Android, [kqueue] on macOS/iOS/BSD, or [wepoll] on Windows.\n\n /// On Unix systems, the handle must implement `AsRawFd`, while on Windows it must implement\n\n /// `AsRawSocket`.\n\n ///\n\n /// If the handle implements [`Read`] and [`Write`], then `Async<T>` automatically\n\n /// implements [`AsyncRead`] and [`AsyncWrite`].\n\n /// Other I/O operations can be *asyncified* by methods [`Async::with()`] and\n\n /// [`Async::with_mut()`].\n\n ///\n\n /// **NOTE**: Do not use this type with [`File`][`std::fs::File`], [`Stdin`][`std::io::Stdin`],\n", "file_path": "src/async_io.rs", "rank": 90, "score": 30948.161177446556 }, { "content": " }\n\n}\n\n\n\nimpl<T> AsyncRead for &Async<T>\n\nwhere\n\n for<'a> &'a T: Read,\n\n{\n\n fn poll_read(\n\n self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &mut [u8],\n\n ) -> Poll<io::Result<usize>> {\n\n poll_future(cx, self.read_with(|io| (&*io).read(buf)))\n\n }\n\n\n\n fn poll_read_vectored(\n\n self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n bufs: &mut [IoSliceMut<'_>],\n\n ) -> Poll<io::Result<usize>> {\n", "file_path": "src/async_io.rs", "rank": 91, "score": 30948.124290795316 }, { "content": " }\n\n\n\n /// Sends data to the connected peer.\n\n ///\n\n /// Returns the number of bytes written.\n\n ///\n\n /// The [`connect`][`UnixDatagram::connect()`] method connects this socket to a remote address.\n\n /// This method will fail if the socket is not connected.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::os::unix::net::UnixDatagram;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UnixDatagram>::bind(\"/tmp/socket1\")?;\n\n /// socket.get_ref().connect(\"/tmp/socket2\")?;\n\n ///\n\n /// let msg = b\"hello\";\n\n /// let len = socket.send(msg).await?;\n\n /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {\n\n self.write_with(|io| io.send(buf)).await\n\n }\n\n}\n", "file_path": "src/async_io.rs", "rank": 92, "score": 30947.934528153128 }, { "content": "\n\nuse futures_io::{AsyncRead, AsyncWrite};\n\nuse futures_util::future;\n\nuse futures_util::stream::{self, Stream};\n\nuse socket2::{Domain, Protocol, Socket, Type};\n\n\n\nuse crate::reactor::{Reactor, Source};\n\nuse crate::task::Task;\n\n\n\n/// Async I/O.\n\n///\n\n/// This type converts a blocking I/O type into an async type, provided it is supported by\n\n/// [epoll]/[kqueue]/[wepoll].\n\n///\n\n/// I/O operations can then be *asyncified* by methods [`Async::with()`] and [`Async::with_mut()`],\n\n/// or you can use the predefined async methods on the standard networking types.\n\n///\n\n/// **NOTE**: Do not use this type with [`File`][`std::fs::File`], [`Stdin`][`std::io::Stdin`],\n\n/// [`Stdout`][`std::io::Stdout`], or [`Stderr`][`std::io::Stderr`] because they're not\n\n/// supported. Use [`reader()`][`crate::reader()`] and [`writer()`][`crate::writer()`] functions\n", "file_path": "src/async_io.rs", "rank": 93, "score": 30947.029171687744 }, { "content": " /// Returns the number of bytes read.\n\n ///\n\n /// This method must be called with a valid byte slice of sufficient size to hold the message.\n\n /// If the message is too long to fit, excess bytes may get discarded.\n\n ///\n\n /// The [`connect`][`UdpSocket::connect()`] method connects this socket to a remote address.\n\n /// This method will fail if the socket is not connected.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use smol::Async;\n\n /// use std::net::UdpSocket;\n\n ///\n\n /// # smol::run(async {\n\n /// let socket = Async::<UdpSocket>::bind(\"127.0.0.1:9000\")?;\n\n /// socket.get_ref().connect(\"127.0.0.1:8000\")?;\n\n ///\n\n /// let mut buf = [0u8; 1024];\n\n /// let len = socket.recv(&mut buf).await?;\n", "file_path": "src/async_io.rs", "rank": 94, "score": 30947.00015960637 }, { "content": " /// # std::io::Result::Ok(()) });\n\n /// ```\n\n pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.write_with(|io| io.recv(buf)).await\n\n }\n\n\n\n /// Receives a single datagram message from the connected peer without removing it from the\n\n /// queue.\n\n ///\n\n /// Returns the number of bytes read and the address the message came from.\n\n ///\n\n /// This method must be called with a valid byte slice of sufficient size to hold the message.\n\n /// If the message is too long to fit, excess bytes may get discarded.\n\n ///\n\n /// The [`connect`][`UdpSocket::connect()`] method connects this socket to a remote address.\n\n /// This method will fail if the socket is not connected.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n", "file_path": "src/async_io.rs", "rank": 95, "score": 30946.997982570607 }, { "content": "/// let mut writer = reader.clone();\n\n///\n\n/// // Echo all messages from the read side of the stream into the write side.\n\n/// futures::io::copy(reader, &mut writer).await\n\n/// }\n\n///\n\n/// // Connect to a local server and echo its messages back.\n\n/// let stream = Async::<TcpStream>::connect(\"127.0.0.1:8000\").await?;\n\n/// echo(stream).await?;\n\n/// # std::io::Result::Ok(()) });\n\n/// ```\n\n///\n\n/// [piper]: https://docs.rs/piper\n\n/// [epoll]: https://en.wikipedia.org/wiki/Epoll\n\n/// [kqueue]: https://en.wikipedia.org/wiki/Kqueue\n\n/// [wepoll]: https://github.com/piscisaureus/wepoll\n\n#[derive(Debug)]\n\npub struct Async<T> {\n\n /// A source registered in the reactor.\n\n source: Arc<Source>,\n", "file_path": "src/async_io.rs", "rank": 96, "score": 30946.850444831125 }, { "content": "\n\n fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {\n\n poll_future(cx, self.write_with_mut(|io| io.flush()))\n\n }\n\n\n\n fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {\n\n self.poll_flush(cx)\n\n }\n\n}\n\n\n\nimpl<T> AsyncWrite for &Async<T>\n\nwhere\n\n for<'a> &'a T: Write,\n\n{\n\n fn poll_write(\n\n self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &[u8],\n\n ) -> Poll<io::Result<usize>> {\n\n poll_future(cx, self.write_with(|io| (&*io).write(buf)))\n", "file_path": "src/async_io.rs", "rank": 97, "score": 30946.609928224858 }, { "content": " pub fn new(io: T) -> io::Result<Async<T>> {\n\n Ok(Async {\n\n source: Reactor::get().insert_io(io.as_raw_fd())?,\n\n io: Some(Box::new(io)),\n\n })\n\n }\n\n}\n\n\n\n#[cfg(unix)]\n\nimpl<T: AsRawFd> AsRawFd for Async<T> {\n\n fn as_raw_fd(&self) -> RawFd {\n\n self.source.raw\n\n }\n\n}\n\n\n\n#[cfg(unix)]\n\nimpl<T: IntoRawFd> IntoRawFd for Async<T> {\n\n fn into_raw_fd(self) -> RawFd {\n\n self.into_inner().unwrap().into_raw_fd()\n\n }\n", "file_path": "src/async_io.rs", "rank": 98, "score": 30945.66182547227 } ]
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().unwrap();\n\n if let Some(split_point) = file_name.rfind('.') {\n\n let (name, ext) = file_name.split_at(split_point);\n\n if ext.to_lowercase() == \".zip\" {\n\n result.push(name.to_string());\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Most recent dates come first\n\n // Dates come before non-dates\n\n // Non-dates are sorted alphabetically\n", "file_path": "canon_collision_lib/src/replays_files.rs", "rank": 0, "score": 240608.96672633477 }, { "content": "pub fn get_hurtboxes() -> HashMap<String, Vec<HurtBox>> {\n\n let mut hurtboxes = HashMap::new();\n\n\n\n hurtboxes.insert(\n\n \"Toriel.cbor\".into(),\n\n vec!(\n\n HurtBox::new(\"Hips\", 0.0, 2.2, 0.0, 1.0, 0.0),\n\n HurtBox::new(\"Waist\", 0.0, 2.2, 0.0, 1.2, 0.3),\n\n HurtBox::new(\"Chest\", 0.0, 2.2, 0.0, 1.6, 0.3),\n\n HurtBox::new(\"Head\", 0.0, 2.8, 0.0, 1.4, 0.0),\n\n HurtBox::new(\"Snout\", 0.0, 1.0, 0.0, 1.1, 0.0),\n\n\n\n HurtBox::new(\"Thigh.L\", 4.0, 1.0, 0.0, 0.0, 0.0),\n\n HurtBox::new(\"Thigh.R\", 4.0, 1.0, 0.0, 0.0, 0.0),\n\n HurtBox::new(\"Shin.L\", 4.0, 1.0, 0.0, 0.0, 0.0),\n\n HurtBox::new(\"Shin.R\", 4.0, 1.0, 0.0, 0.0, 0.0),\n\n\n\n HurtBox::new(\"Shoulder.L\", 0.0, 1.0, 0.0, 0.0, 0.0),\n\n HurtBox::new(\"Shoulder.R\", 0.0, 1.0, 0.0, 0.0, 0.0),\n\n HurtBox::new(\"Arm.L\", 4.0, 1.0, 0.0, 0.0, 0.0),\n", "file_path": "generate_hurtboxes/src/hurtbox.rs", "rank": 1, "score": 225165.62369735722 }, { "content": "pub fn load_struct_json<T: DeserializeOwned>(filename: &Path) -> Result<T, String> {\n\n let json = load_file(filename)?;\n\n serde_json::from_str(&json).map_err(|x| format!(\"{:?}\", x))\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 2, "score": 217423.83017341042 }, { "content": "pub fn load_struct_bincode<T: DeserializeOwned>(filename: &Path) -> Result<T, String> {\n\n let file = File::open(filename).map_err(|x| format!(\"{:?}\", x))?;\n\n bincode::deserialize_from(file).map_err(|x| format!(\"{:?}\", x))\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 3, "score": 217423.83017341042 }, { "content": "fn is_process_running(process: &mut Option<Child>) -> bool {\n\n process\n\n .as_mut()\n\n .map(|x| x.try_wait().unwrap().is_none())\n\n .unwrap_or(false)\n\n}\n\n\n", "file_path": "canon_collision_hot_reload/src/main.rs", "rank": 4, "score": 205316.51483134815 }, { "content": "pub fn get_colors() -> Vec<Color> {\n\n vec!(\n\n Color { name: String::from(\"Blue\"), value: [0.0, 90.0, 224.0] },\n\n Color { name: String::from(\"Orange\"), value: [239.0, 100.0, 0.0] },\n\n Color { name: String::from(\"Red\"), value: [255.0, 0.0, 40.0] },\n\n Color { name: String::from(\"Green\"), value: [10.0, 150.0, 38.0] },\n\n\n\n Color { name: String::from(\"Pink\"), value: [255.0, 0.0, 163.0] },\n\n Color { name: String::from(\"Green #2\"), value: [124.0, 184.0, 0.0] },\n\n Color { name: String::from(\"Purple\"), value: [120.0, 46.0, 252.0] },\n\n Color { name: String::from(\"Light Blue\"), value: [81.0, 229.0, 237.0] },\n\n )\n\n}\n", "file_path": "canon_collision/src/graphics.rs", "rank": 5, "score": 186715.2522676867 }, { "content": "pub fn build_version() -> String { String::from(env!(\"BUILD_VERSION\")) }\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 6, "score": 183828.98233120225 }, { "content": "pub fn load_file(filename: &Path) -> Result<String, String> {\n\n std::fs::read_to_string(&filename)\n\n .map_err(|x| format!(\"Failed to open file: {} because: {}\", filename.to_str().unwrap(), x))\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 7, "score": 183828.98233120225 }, { "content": "fn get_vec<'a>(parent: &'a mut Value, member: &str) -> Option<&'a mut Vec<Value>> {\n\n if let &mut Value::Map (ref mut map) = parent {\n\n if let Some (array) = map.get_mut(&Value::Text(member.into())) {\n\n if let &mut Value::Array (ref mut array) = array {\n\n return Some (array);\n\n }\n\n }\n\n }\n\n return None;\n\n}\n\n\n", "file_path": "package_upgrader/src/main.rs", "rank": 8, "score": 176078.2965789416 }, { "content": "pub fn save_struct_bincode<T: Serialize>(filename: &Path, object: &T) {\n\n // ensure parent directories exists\n\n DirBuilder::new().recursive(true).create(filename.parent().unwrap()).unwrap();\n\n\n\n // save\n\n let file = File::create(filename).unwrap();\n\n bincode::serialize_into(file, object).unwrap();\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 9, "score": 173497.1320907236 }, { "content": "pub fn save_struct_cbor<T: Serialize>(filename: &Path, object: &T) {\n\n // ensure parent directories exists\n\n DirBuilder::new().recursive(true).create(filename.parent().unwrap()).unwrap();\n\n\n\n // save\n\n let file = File::create(filename).unwrap();\n\n serde_cbor::to_writer(file, object).unwrap();\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 10, "score": 173497.1320907236 }, { "content": "pub fn save_struct_json<T: Serialize>(filename: &Path, object: &T) {\n\n // ensure parent directories exists\n\n DirBuilder::new().recursive(true).create(filename.parent().unwrap()).unwrap();\n\n\n\n // save\n\n let json = serde_json::to_string_pretty(object).unwrap();\n\n std::fs::write(filename, &json.as_bytes()).unwrap();\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 11, "score": 173497.1320907236 }, { "content": "pub fn gen_inputs(game: &Game) -> Vec<ControllerInput> {\n\n game.selected_ais.iter().map(|_| {\n\n ControllerInput {\n\n plugged_in: true,\n\n\n\n up: false,\n\n down: false,\n\n right: false,\n\n left: false,\n\n y: false,\n\n x: false,\n\n b: false,\n\n a: false,\n\n l: false,\n\n r: false,\n\n z: false,\n\n start: false,\n\n\n\n stick_x: 0.0,\n\n stick_y: 0.0,\n\n c_stick_x: 0.0,\n\n c_stick_y: 0.0,\n\n l_trigger: 0.0,\n\n r_trigger: 0.0,\n\n }\n\n }).collect()\n\n}\n", "file_path": "canon_collision/src/ai.rs", "rank": 12, "score": 170070.84918702554 }, { "content": "pub fn load_replay(name: &str) -> Result<Replay, String> {\n\n let replay_path = replays_files::get_replay_path(name);\n\n files::load_struct_bincode(&replay_path)\n\n}\n\n\n", "file_path": "canon_collision/src/replays.rs", "rank": 13, "score": 166185.97317542703 }, { "content": "pub fn has_ext(path: &Path, check_ext: &str) -> bool {\n\n if let Some(ext) = path.extension() {\n\n if let Some(ext) = ext.to_str() {\n\n if ext.to_lowercase().as_str() == check_ext {\n\n return true\n\n }\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 14, "score": 164055.05648706006 }, { "content": "// On linux we only need the code so we strip out the kind, so the numbers are nicer to work with (when creating maps)\n\npub fn code_to_usize(code: &EvCode) -> usize {\n\n (code.into_u32() & 0xFFFF) as usize\n\n}\n\n\n", "file_path": "canon_collision_lib/src/input/generic.rs", "rank": 15, "score": 160899.87401204457 }, { "content": "pub fn load_cbor(filename: &Path) -> Result<serde_cbor::Value, String> {\n\n let file = File::open(filename).map_err(|x| format!(\"{:?}\", x))?;\n\n serde_cbor::from_reader(&file).map_err(|x| format!(\"{:?}\", x))\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 16, "score": 156320.51112934004 }, { "content": "pub fn load_json(filename: &Path) -> Result<serde_json::Value, String> {\n\n let json = load_file(filename)?;\n\n serde_json::from_str(&json).map_err(|x| format!(\"{:?}\", x))\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 17, "score": 156320.51112934004 }, { "content": "pub fn get_team_color3(i: usize) -> [f32; 3] {\n\n let colors = get_colors();\n\n let color = colors[i % colors.len()].value;\n\n [color[0]/255.0, color[1]/255.0, color[2]/255.0]\n\n}\n\n\n\npub struct Color {\n\n pub name: String,\n\n pub value: [f32; 3]\n\n}\n\n\n", "file_path": "canon_collision/src/graphics.rs", "rank": 18, "score": 154153.0235107202 }, { "content": "#[allow(unused)] // Needed for headless build\n\npub fn get_team_color4(i: usize) -> [f32; 4] {\n\n let colors = get_colors();\n\n let color = colors[i % colors.len()].value;\n\n [color[0]/255.0, color[1]/255.0, color[2]/255.0, 1.0]\n\n}\n\n\n", "file_path": "canon_collision/src/graphics.rs", "rank": 19, "score": 154153.0235107202 }, { "content": "fn upgrade_to_latest_entity(path: &Path, dry_run: bool) {\n\n let file_name = path.file_name().unwrap().to_str().unwrap();\n\n let mut entity = load_cbor(path).unwrap();\n\n let entity_engine_version = get_engine_version(&entity);\n\n if entity_engine_version > engine_version() {\n\n panic!(\n\n \"EntityDef: {} is newer than this version of Canon Collision.\",\n\n path.file_name().unwrap().to_str().unwrap()\n\n );\n\n }\n\n else if entity_engine_version < engine_version() {\n\n for upgrade_from in entity_engine_version..engine_version() {\n\n match upgrade_from {\n\n 19 => { upgrade_entity19(&mut entity) }\n\n 18 => { upgrade_entity18(&mut entity, file_name) }\n\n 17 => { upgrade_entity17(&mut entity) }\n\n 16 => { upgrade_entity16(&mut entity) }\n\n 15 => { upgrade_entity15(&mut entity) }\n\n _ => { }\n\n }\n", "file_path": "package_upgrader/src/main.rs", "rank": 20, "score": 153064.28265440394 }, { "content": "fn new_object(entries: Vec<(&str, Value)>) -> Value {\n\n let mut map = BTreeMap::new();\n\n for (key, value) in entries {\n\n map.insert(Value::Text(key.into()), value);\n\n }\n\n Value::Map(map)\n\n}\n\n\n", "file_path": "package_upgrader/src/main.rs", "rank": 21, "score": 152726.63468863006 }, { "content": "fn skeleton_from_gltf_node(node: &Node, blob: &[u8], node_to_joints_lookup: &[usize], ibms: &[Matrix4<f32>], parent_transform: Matrix4<f32>) -> Joint {\n\n let mut children = vec!();\n\n let node_index = node.index();\n\n let index = node_to_joints_lookup.iter().enumerate().find(|(_, x)| **x == node_index).unwrap().0;\n\n let name = node.name().unwrap_or(\"\").to_string();\n\n\n\n let ibm = &ibms[index];\n\n let pose_transform = parent_transform * transform_to_matrix4(node.transform());\n\n\n\n for child in node.children() {\n\n children.push(skeleton_from_gltf_node(&child, blob, node_to_joints_lookup, ibms, pose_transform.clone()));\n\n }\n\n\n\n let transform = pose_transform; // TODO: Modified to remove the IBM, how to handle when merging ????\n\n let ibm = ibm.clone();\n\n\n\n let (translation, rotation, scale) = match node.transform() {\n\n Transform::Matrix { .. } => unimplemented!(\"It is assumed that gltf node transforms only use decomposed form.\"),\n\n Transform::Decomposed { translation, rotation, scale } => {\n\n let translation: Vector3<f32> = translation.into();\n\n let rotation = Quaternion::new(rotation[3], rotation[0], rotation[1], rotation[2]).into();\n\n let scale: Vector3<f32> = scale.into();\n\n (translation, rotation, scale)\n\n }\n\n };\n\n\n\n Joint { node_index, index, name, children, transform, ibm, translation, rotation, scale }\n\n}\n\n\n", "file_path": "generate_hurtboxes/src/model.rs", "rank": 22, "score": 145926.36916142763 }, { "content": "fn run_in_thread(mut backend: GCAdapterBackend) -> Receiver<[ControllerInput; 4]> {\n\n let (input_tx, input_rx) = mpsc::channel();\n\n thread::spawn(move || {\n\n loop {\n\n if input_tx.send(backend.read()).is_err() {\n\n return;\n\n }\n\n }\n\n });\n\n input_rx\n\n}\n\n\n", "file_path": "canon_collision_lib/src/input/gcadapter.rs", "rank": 23, "score": 138964.12474694793 }, { "content": "fn run(mut cli_results: CLIResults, event_rx: Receiver<WindowEvent<'static>>, render_tx: Sender<GraphicsMessage>) {\n\n let mut config = Config::load();\n\n if let ContinueFrom::Close = cli_results.continue_from {\n\n return;\n\n }\n\n\n\n let mut input = Input::new();\n\n let mut net_command_line = NetCommandLine::new();\n\n let mut netplay = Netplay::new();\n\n\n\n let mut package = if let Some(path) = Package::find_package_in_parent_dirs() {\n\n if let Some(package) = Package::open(path) {\n\n Some(package)\n\n } else {\n\n println!(\"Could not load package\");\n\n return;\n\n }\n\n }\n\n else {\n\n println!(\"Could not find package/ in current directory or any of its parent directories.\");\n", "file_path": "canon_collision/src/app.rs", "rank": 24, "score": 138259.0418561015 }, { "content": "pub fn set_animated_joints(animation: &Animation, frame: f32, root_joint: &mut Joint, parent_transform: Matrix4<f32>) {\n\n let mut translation = root_joint.translation.clone();\n\n let mut rotation = root_joint.rotation.clone();\n\n let mut scale = root_joint.scale.clone();\n\n\n\n for channel in &animation.channels {\n\n if root_joint.node_index == channel.target_node_index {\n\n match (&channel.outputs, &channel.interpolation) {\n\n (ChannelOutputs::Translations (translations), Interpolation::Linear) => {\n\n let (index_pre, index_next, amount) = index_linear(channel, frame);\n\n let pre = translations[index_pre];\n\n let next = translations[index_next];\n\n translation = pre.lerp(next, amount);\n\n }\n\n (ChannelOutputs::Translations (translations), Interpolation::Step) => {\n\n let output_index = index_step(channel, frame);\n\n translation = translations[output_index];\n\n }\n\n (ChannelOutputs::Translations (translations), Interpolation::CubicSpline) => {\n\n translation = match index_cubicspline(channel, frame) {\n", "file_path": "generate_hurtboxes/src/animation.rs", "rank": 25, "score": 136978.78926015113 }, { "content": "/// returns a list of hit results for each entity\n\npub fn collision_check(entities: &Entities, entity_definitions: &KeyedContextVec<EntityDef>, surfaces: &[Surface]) -> SecondaryMap<EntityKey, Vec<CollisionResult>> {\n\n let mut result = SecondaryMap::<EntityKey, Vec<CollisionResult>>::new();\n\n for key in entities.keys() {\n\n result.insert(key, vec!());\n\n }\n\n\n\n 'entity_atk: for (entity_atk_i, entity_atk) in entities.iter() {\n\n let entity_atk_xy = entity_atk.public_bps_xy(entities, entity_definitions, surfaces);\n\n let entity_atk_def = &entity_definitions[entity_atk.state.entity_def_key.as_ref()];\n\n let frame_atk = entity_atk.relative_frame(entity_atk_def, surfaces);\n\n let colboxes_atk = frame_atk.get_hitboxes();\n\n for (entity_defend_i, entity_defend) in entities.iter() {\n\n let entity_defend_xy = entity_defend.public_bps_xy(entities, entity_definitions, surfaces);\n\n if entity_atk_i != entity_defend_i && entity_atk.can_hit(entity_defend) && entity_atk.hitlist().iter().all(|x| *x != entity_defend_i) {\n\n let entity_defend_def = &entity_definitions[entity_defend.state.entity_def_key.as_ref()];\n\n let frame_defend = entity_defend.relative_frame(entity_defend_def, surfaces);\n\n\n\n 'hitbox_atk: for colbox_atk in &colboxes_atk {\n\n if let CollisionBoxRole::Hit (ref hitbox_atk) = colbox_atk.role {\n\n if let EntityType::Fighter(fighter) = &entity_defend.ty {\n", "file_path": "canon_collision/src/collision/collision_box.rs", "rank": 26, "score": 136429.36184364406 }, { "content": "pub fn init() {\n\n let env_var = env::var(\"CC_LOG\").unwrap_or(\"warn\".into());\n\n Builder::new().format(format).parse_filters(&env_var).init()\n\n}\n\n\n", "file_path": "canon_collision_lib/src/logger.rs", "rank": 27, "score": 134329.39126935528 }, { "content": "pub fn run_in_thread(cli_results: CLIResults) -> (Sender<WindowEvent<'static>>, Receiver<GraphicsMessage>) {\n\n let (render_tx, render_rx) = channel();\n\n let (event_tx, event_rx) = mpsc::channel();\n\n thread::spawn(move || {\n\n run(cli_results, event_rx, render_tx);\n\n });\n\n (event_tx, render_rx)\n\n}\n\n\n", "file_path": "canon_collision/src/app.rs", "rank": 28, "score": 130453.8765792197 }, { "content": "/// Checks if segment p1q1 intersects with segment p2q2\n\n/// Implemented as described here http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/\n\npub fn segments_intersect(p1: (f32, f32), q1: (f32, f32), p2: (f32, f32), q2: (f32, f32)) -> bool {\n\n let o1 = triplet_orientation(p1, q1, p2);\n\n let o2 = triplet_orientation(p1, q1, q2);\n\n let o3 = triplet_orientation(p2, q2, p1);\n\n let o4 = triplet_orientation(p2, q2, q1);\n\n\n\n // general case\n\n (o1 != o2 && o3 != o4) ||\n\n // colinear cases\n\n (o1 == 0 && point_on_segment(p1, p2, q1)) ||\n\n (o2 == 0 && point_on_segment(p1, q2, q1)) ||\n\n (o3 == 0 && point_on_segment(p2, p1, q2)) ||\n\n (o4 == 0 && point_on_segment(p2, q1, q2))\n\n}\n\n\n", "file_path": "canon_collision_lib/src/geometry.rs", "rank": 29, "score": 130242.98751179069 }, { "content": "pub fn cli() -> CLIResults {\n\n let args: Vec<String> = env::args().collect();\n\n let program = &args[0];\n\n\n\n let mut opts = Options::new();\n\n opts.optflag(\"h\", \"hitboxes\", \"Delete any existing hitboxes on the generated actions\");\n\n opts.optflag(\"r\", \"resize\", \"Resize generated action length\");\n\n opts.reqopt (\"f\", \"fighter\", \"Use the fighter specified\", \"NAME\");\n\n opts.optopt (\"a\", \"actions\", \"Generate hurtboxes for the actions specified\", \"NAME1,NAME2,NAME3...\");\n\n\n\n let mut results = CLIResults::new();\n\n\n\n let matches = match opts.parse(&args[1..]) {\n\n Ok(m) => m,\n\n Err(_) => {\n\n print_usage(program, opts);\n\n return results;\n\n },\n\n };\n\n\n", "file_path": "generate_hurtboxes/src/cli.rs", "rank": 30, "score": 128060.26936158843 }, { "content": "pub fn cli() -> CLIResults {\n\n let args: Vec<String> = env::args().collect();\n\n let program = &args[0];\n\n\n\n let mut opts = Options::new();\n\n opts.optflag(\"d\", \"debug\", \"Start the game with every debug tool turned on\");\n\n opts.optopt(\"s\", \"stage\", \"Use the stage specified\", \"NAME\");\n\n opts.optopt(\"f\", \"fighters\", \"Use the fighters specified\", \"NAME1,NAME2,NAME3...\");\n\n opts.optopt(\"h\", \"humanplayers\", \"Number of human players in the game\", \"NUM_HUMAN_PLAYERS\");\n\n opts.optopt(\"c\", \"cpuplayers\", \"Number of CPU players in the game\", \"NUM_CPU_PLAYERS\");\n\n opts.optopt(\"a\", \"address\", \"IP Address of other client to start netplay with\", \"IP_ADDRESS\");\n\n opts.optopt(\"n\", \"netplayplayers\", \"Search for a netplay game with the specified number of players\", \"NUM_PLAYERS\");\n\n opts.optopt(\"r\", \"netplayregion\", \"Search for a netplay game with the specified region\", \"REGION\");\n\n opts.optopt(\"k\", \"replay\", \"load the replay in the replays folder with the specified filename. Replay additionally loads normally unused data that is kept specifically for hot reloading.\", \"FILENAME\");\n\n opts.optopt(\"m\", \"maxhistoryframes\", \"The oldest history frame is removed when number of history frames exceeds this value\", \"NUM_FRAMES\");\n\n opts.optopt(\"g\", \"graphics\", \"Graphics backend to use\",\n\n if cfg!(feature = \"wgpu_renderer\") {\n\n \"[wgpu|none]\"\n\n } else {\n\n \"[none]\"\n", "file_path": "canon_collision/src/cli.rs", "rank": 31, "score": 128060.26936158843 }, { "content": "#[test]\n\npub fn controller_maps_file_is_valid() {\n\n let maps = include_str!(\"controller_maps.json\");\n\n let _controller_maps: ControllerMaps = serde_json::from_str(maps).unwrap();\n\n}\n", "file_path": "canon_collision_lib/src/input/maps.rs", "rank": 32, "score": 127213.00255464225 }, { "content": "pub fn generate_joint_transforms(animation: &Animation, frame: f32, root_joint: &Joint, parent_transform: Matrix4<f32>, buffer: &mut JointTransforms) {\n\n let mut translation = root_joint.translation.clone();\n\n let mut rotation = root_joint.rotation.clone();\n\n let mut scale = root_joint.scale.clone();\n\n\n\n for channel in &animation.channels {\n\n if root_joint.node_index == channel.target_node_index {\n\n match (&channel.outputs, &channel.interpolation) {\n\n (ChannelOutputs::Translations (translations), Interpolation::Linear) => {\n\n let (index_pre, index_next, amount) = index_linear(channel, frame);\n\n let pre = translations[index_pre];\n\n let next = translations[index_next];\n\n translation = pre.lerp(next, amount);\n\n }\n\n (ChannelOutputs::Translations (translations), Interpolation::Step) => {\n\n let output_index = index_step(channel, frame);\n\n translation = translations[output_index];\n\n }\n\n (ChannelOutputs::Translations (translations), Interpolation::CubicSpline) => {\n\n translation = match index_cubicspline(channel, frame) {\n", "file_path": "canon_collision/src/wgpu/animation.rs", "rank": 33, "score": 126937.84736623985 }, { "content": "pub fn get_path() -> PathBuf {\n\n let mut data_local = dirs_next::data_local_dir().expect(\"Could not get data_local_dir\");\n\n data_local.push(\"CanonCollision\");\n\n data_local\n\n}\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 34, "score": 124507.41907272325 }, { "content": "fn upgrade_entity19(entity: &mut Value) {\n\n if let Value::Map(entity) = entity {\n\n entity.insert(Value::Text(\"css_action\".into()), Value::Text(\"Idle\".into()));\n\n if let Some(entity_type) = entity.get_mut(&Value::Text(\"ty\".into())) {\n\n if let Value::Map(entity_type) = entity_type {\n\n if let Some(fighter) = entity_type.get_mut(&Value::Text(\"Fighter\".into())) {\n\n if let Value::Map(fighter) = fighter {\n\n fighter.insert(Value::Text(\"ty\".into()), Value::Text(\"Toriel\".into()));\n\n }\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "package_upgrader/src/main.rs", "rank": 35, "score": 123443.65035716021 }, { "content": "fn upgrade_entity16(entity: &mut Value) {\n\n if let Value::Map(entity) = entity {\n\n entity.insert(Value::Text(\"ty\".into()), Value::Text(\"Generic\".into()));\n\n }\n\n}\n\n\n", "file_path": "package_upgrader/src/main.rs", "rank": 36, "score": 123443.65035716021 }, { "content": "fn upgrade_entity15(entity: &mut Value) {\n\n if let Value::Map(entity) = entity {\n\n entity.insert(Value::Text(\"ledge_grab_x\".into()), Value::Float(-2.0));\n\n entity.insert(Value::Text(\"ledge_grab_y\".into()), Value::Float(-24.0));\n\n }\n\n\n\n for action in get_vec(entity, \"actions\").unwrap() {\n\n for frame in get_vec(action, \"frames\").unwrap() {\n\n if let Value::Map(frame) = frame {\n\n frame.insert(Value::Text(\"grabbing_x\".into()), Value::Float(8.0));\n\n frame.insert(Value::Text(\"grabbing_y\".into()), Value::Float(11.0));\n\n frame.insert(Value::Text(\"grabbed_x\".into()), Value::Float(4.0));\n\n frame.insert(Value::Text(\"grabbed_y\".into()), Value::Float(11.0));\n\n }\n\n }\n\n }\n\n\n\n let action = new_object(vec!(\n\n (\"frames\", Value::Array(vec!(\n\n new_object(vec!(\n", "file_path": "package_upgrader/src/main.rs", "rank": 37, "score": 123443.65035716021 }, { "content": "fn upgrade_entity17(entity: &mut Value) {\n\n let action = new_object(vec!(\n\n (\"frames\", Value::Array(vec!(\n\n new_object(vec!(\n\n (\"ecb\", new_object(vec!(\n\n (\"top\", Value::Float(16.0)),\n\n (\"left\", Value::Float(-4.0)),\n\n (\"right\", Value::Float(4.0)),\n\n (\"bottom\", Value::Float(0.0)),\n\n ))),\n\n (\"colboxes\", Value::Array(vec!())),\n\n (\"item_hold_x\", Value::Float(4.0)),\n\n (\"item_hold_y\", Value::Float(11.0)),\n\n (\"grabbing_x\", Value::Float(8.0)),\n\n (\"grabbing_y\", Value::Float(11.0)),\n\n (\"grabbed_x\", Value::Float(4.0)),\n\n (\"grabbed_y\", Value::Float(11.0)),\n\n (\"pass_through\", Value::Bool(true)),\n\n (\"ledge_cancel\", Value::Bool(true)),\n\n (\"use_platform_angle\", Value::Bool(false)),\n", "file_path": "package_upgrader/src/main.rs", "rank": 38, "score": 123443.65035716021 }, { "content": "pub fn engine_version() -> u64 { 20 }\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 39, "score": 122562.41031371568 }, { "content": "pub fn save_replay(replay: &Replay) {\n\n let replay_path = replays_files::get_replay_path(&format!(\"{}.zip\", replay.timestamp.to_rfc2822())); // TODO: could still collide under strange circumstances: check and handle\n\n files::save_struct_bincode(&replay_path, &replay)\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub struct Replay {\n\n pub init_seed: u64,\n\n pub timestamp: DateTime<Local>,\n\n pub input_history: Vec<Vec<ControllerInput>>,\n\n pub entity_history: Vec<Entities>,\n\n pub stage_history: Vec<Stage>,\n\n pub selected_controllers: Vec<usize>,\n\n pub selected_players: Vec<PlayerSetup>,\n\n pub selected_ais: Vec<usize>,\n\n pub selected_stage: String,\n\n pub rules: Rules,\n\n pub max_history_frames: Option<usize>,\n\n pub deleted_history_frames: usize,\n\n pub hot_reload_current_frame: usize,\n", "file_path": "canon_collision/src/replays.rs", "rank": 40, "score": 122562.41031371568 }, { "content": "fn run(rx: Receiver<Event>) {\n\n let mut process: Option<Child> = None;\n\n let profile_arg = env!(\"PROFILE\");\n\n\n\n for event in rx {\n\n if let Event::Write (_) | Event::Create (_) = event {\n\n let mut args = env::args();\n\n args.next();\n\n let args: Vec<String> = args.collect();\n\n let pass_through_args: Vec<&str> = args.iter().map(|x| x.as_ref()).collect();\n\n\n\n let build_status = if env!(\"PROFILE\") == \"release\" {\n\n Command::new(\"cargo\")\n\n .current_dir(\"../canon_collision\")\n\n //.args(&[\"build\", \"-Z\", \"unstable-options\", \"--profile\", &profile_arg]) // TODO: when --profile is stablized we can use that which is much nicer\n\n .args(&[\"build\", \"--release\"])\n\n .status()\n\n .unwrap()\n\n } else {\n\n Command::new(\"cargo\")\n", "file_path": "canon_collision_hot_reload/src/main.rs", "rank": 41, "score": 122147.87743004702 }, { "content": "fn upgrade_engine_version(meta: &mut Value) {\n\n if let &mut Value::Map (ref mut map) = meta {\n\n map.insert(Value::Text(String::from(\"engine_version\")), Value::Integer(engine_version() as i128));\n\n }\n\n}\n\n\n", "file_path": "package_upgrader/src/main.rs", "rank": 42, "score": 121703.86205570298 }, { "content": "/// deletes all files in the passed directory\n\n/// if the directory does not exist it is created\n\npub fn nuke_dir(path: &Path) {\n\n fs::remove_dir_all(path).ok();\n\n fs::create_dir_all(path).unwrap();\n\n}\n\n\n", "file_path": "canon_collision_lib/src/files.rs", "rank": 43, "score": 120825.72250766667 }, { "content": "/// returns true on success\n\nfn send_to_cc(message: &str) -> bool {\n\n match TcpStream::connect(\"127.0.0.1:1613\") {\n\n Ok(mut stream) => {\n\n stream.write(format!(\"C{}\", message).as_bytes()).unwrap();\n\n\n\n // We need to receive to ensure we block, but we dont really care what the response is.\n\n let mut result = String::new();\n\n stream.read_to_string(&mut result).is_ok()\n\n }\n\n Err(_) => false,\n\n }\n\n}\n", "file_path": "canon_collision_hot_reload/src/main.rs", "rank": 44, "score": 120311.46574075724 }, { "content": "pub fn delete_replay(name: &str) {\n\n fs::remove_file(get_replay_path(&format!(\"{}.zip\", name))).ok();\n\n}\n", "file_path": "canon_collision_lib/src/replays_files.rs", "rank": 45, "score": 119163.4043957437 }, { "content": "fn path_to_handler() -> Result<PathBuf, String> {\n\n match env::current_exe() {\n\n Ok(mut path) => {\n\n path.pop();\n\n if cfg!(target_os = \"windows\") {\n\n path.push(\"panic_handler.exe\");\n\n } else {\n\n path.push(\"panic_handler\");\n\n }\n\n Ok(path)\n\n }\n\n Err(err) => Err(format!(\"Failed to get path of executable: {}\", err))\n\n }\n\n}\n\n\n", "file_path": "canon_collision_lib/src/panic_handler.rs", "rank": 46, "score": 118510.77081391345 }, { "content": "fn f32_equal(a: f32, b: f32) -> bool {\n\n (a - b).abs() < 0.0000001\n\n}\n\n\n\npub struct FloorInfo {\n\n pub left_i: Option<usize>,\n\n pub right_i: Option<usize>,\n\n}\n\n\n\n#[derive(Clone, Default, Serialize, Deserialize, Node)]\n\npub struct Surface {\n\n pub x1: f32,\n\n pub y1: f32,\n\n pub grab1: bool,\n\n pub x2: f32,\n\n pub y2: f32,\n\n pub grab2: bool,\n\n pub wall: bool,\n\n pub ceiling: bool,\n\n pub floor: Option<Floor>,\n", "file_path": "canon_collision_lib/src/stage.rs", "rank": 47, "score": 115978.16394091232 }, { "content": "pub fn trigger_filter(trigger: u8) -> f32 {\n\n let value = (trigger as f32) / 140.0;\n\n if value > 1.0 {\n\n 1.0\n\n } else {\n\n value\n\n }\n\n}\n\n\n", "file_path": "canon_collision_lib/src/input/filter.rs", "rank": 48, "score": 114425.35853834181 }, { "content": "#[derive(Clone, Deserialize)]\n\nstruct MatchMakingResponse {\n\n addresses: Vec<SocketAddr>\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub struct InitConnection {\n\n build_version: String,\n\n random: u64\n\n}\n\n\n\n#[derive(Clone, Default, Copy)]\n\npub struct Ping {\n\n time_sent: Option<Instant>,\n\n time_received: Option<Instant>,\n\n}\n\n\n", "file_path": "canon_collision_lib/src/network.rs", "rank": 49, "score": 113302.45443451345 }, { "content": "/// Logic:\n\n/// 1. Checks for collisions between players item_grab_box and items item_grab_box\n\n/// 2. Assign each player its closest colliding item, unless another player is already closer to that item.\n\n/// 3. Repeat until stable (10x max, in case the distances are equal or something)\n\npub fn collision_check(entities: &Entities, entity_definitions: &KeyedContextVec<EntityDef>, surfaces: &[Surface]) -> SecondaryMap<EntityKey, EntityKey> {\n\n let mut player_grabs = SecondaryMap::<EntityKey, PlayerGrabHit>::new();\n\n\n\n let mut player_grabs_last_len = 0;\n\n for _ in 0..10 {\n\n for (player_i, entity_player) in entities.iter() {\n\n if let EntityType::Fighter (fighter) = &entity_player.ty {\n\n let player = fighter.get_player();\n\n if player.get_held_item(entities).is_none() {\n\n let (player_x, player_y) = entity_player.public_bps_xy(entities, entity_definitions, surfaces);\n\n let player_item_grab_box = entity_player.item_grab_box(entities, entity_definitions, surfaces);\n\n 'entity_check: for (item_i, entity_item) in entities.iter() {\n\n if let EntityType::Item (item) = &entity_item.ty {\n\n if !item.body.is_grabbed() {\n\n let (item_x, item_y) = entity_item.public_bps_xy(entities, entity_definitions, surfaces);\n\n let item_item_grab_box = entity_item.item_grab_box(entities, entity_definitions, surfaces);\n\n let collision = match (&player_item_grab_box, &item_item_grab_box) {\n\n (Some(a), Some(b)) => a.collision(b),\n\n _ => false,\n\n };\n", "file_path": "canon_collision/src/collision/item_grab.rs", "rank": 50, "score": 113064.8874069498 }, { "content": "#[allow(unused)] // Needed for headless build\n\npub fn get_render_id(role: &CollisionBoxRole) -> u32 {\n\n match role {\n\n &CollisionBoxRole::Hurt (_) => { 1 }\n\n &CollisionBoxRole::Hit (_) => { 2 }\n\n &CollisionBoxRole::Grab => { 3 }\n\n &CollisionBoxRole::Invincible => { 6 }\n\n &CollisionBoxRole::Reflect => { 7 }\n\n &CollisionBoxRole::Absorb => { 8 }\n\n }\n\n}\n\n\n", "file_path": "canon_collision/src/graphics.rs", "rank": 51, "score": 112898.13313563722 }, { "content": "fn upgrade_entity18(entity: &mut Value, file_name: &str) {\n\n let item_action_names = [\n\n \"Spawn\",\n\n \"Idle\",\n\n \"Fall\",\n\n \"Held\",\n\n \"Thrown\",\n\n \"Dropped\",\n\n ];\n\n\n\n let projectile_action_names = [\n\n \"Spawn\",\n\n \"Travel\",\n\n \"Hit\",\n\n ];\n\n\n\n let fighter_action_names = [\n\n \"Spawn\",\n\n \"ReSpawn\",\n\n \"ReSpawnIdle\",\n", "file_path": "package_upgrader/src/main.rs", "rank": 52, "score": 112478.9179732715 }, { "content": "pub fn get_replay_path(name: &str) -> PathBuf {\n\n let mut replay_path = get_replays_dir_path();\n\n replay_path.push(name.to_string());\n\n replay_path\n\n}\n\n\n", "file_path": "canon_collision_lib/src/replays_files.rs", "rank": 53, "score": 111432.36032665252 }, { "content": "fn format(buf: &mut Formatter, record: &Record) -> io::Result<()> {\n\n let level = record.level();\n\n let level_color = match level {\n\n Level::Trace => Color::White,\n\n Level::Debug => Color::Blue,\n\n Level::Info => Color::Green,\n\n Level::Warn => Color::Yellow,\n\n Level::Error => Color::Red,\n\n };\n\n\n\n let mut style = buf.style();\n\n style.set_color(level_color);\n\n\n\n let write_level = write!(buf, \"{:>5}\", style.value(level));\n\n let write_args = if let Some(module_path) = record.module_path() {\n\n writeln!(buf, \" {} {}\", module_path, record.args())\n\n }\n\n else {\n\n writeln!(buf, \" {}\", record.args())\n\n };\n\n\n\n write_level.and(write_args)\n\n}\n", "file_path": "canon_collision_lib/src/logger.rs", "rank": 54, "score": 106410.71186357952 }, { "content": "/// use the first received stick value to reposition the current stick value around 128\n\npub fn stick_deadzone(current: u8, first: u8) -> u8 {\n\n if current > first {\n\n 128u8.saturating_add(current - first)\n\n } else {\n\n 128u8.saturating_sub(first - current)\n\n }\n\n}\n\n\n", "file_path": "canon_collision_lib/src/input/filter.rs", "rank": 55, "score": 106345.89271142418 }, { "content": "pub fn stick_filter(in_stick_x: u8, in_stick_y: u8) -> (f32, f32) {\n\n let raw_stick_x = in_stick_x as f32 - 128.0;\n\n let raw_stick_y = in_stick_y as f32 - 128.0;\n\n let angle = (raw_stick_y).atan2(raw_stick_x);\n\n\n\n let max_x = (angle.cos() * 80.0).trunc();\n\n let max_y = (angle.sin() * 80.0).trunc();\n\n let stick_x = if in_stick_x == 128 { // avoid raw_stick_x = 0 and thus division by zero in the atan2)\n\n 0.0\n\n } else {\n\n abs_min(raw_stick_x, max_x) / 80.0\n\n };\n\n let stick_y = abs_min(raw_stick_y, max_y) / 80.0;\n\n\n\n let deadzone = 0.28;\n\n (\n\n if stick_x.abs() < deadzone { 0.0 } else { stick_x },\n\n if stick_y.abs() < deadzone { 0.0 } else { stick_y }\n\n )\n\n}\n\n\n", "file_path": "canon_collision_lib/src/input/filter.rs", "rank": 56, "score": 102844.19091281098 }, { "content": "fn generate_hurtbox(frame: &mut ActionFrame, root_joint: &Joint, hurtbox: &HurtBox) {\n\n for child in &root_joint.children {\n\n generate_hurtbox(frame, child, hurtbox);\n\n }\n\n\n\n if root_joint.name == hurtbox.bone {\n\n let role = CollisionBoxRole::Hurt(Default::default());\n\n let radius = hurtbox.radius; // TODO: Multiply by scale of transform\n\n\n\n let count = (hurtbox.bone_length / radius) as usize;\n\n let transform = &root_joint.transform;\n\n let o = &hurtbox.offset;\n\n let point1 = transform.transform_point(Point3::new(o.x, o.y, o.z));\n\n let point2 = transform.transform_point(Point3::new(o.x, o.y + hurtbox.bone_length, o.z));\n\n\n\n if count > 1 {\n\n for i in 0..count {\n\n let point1 = Vector3::new(point1.x, point1.y, point1.z);\n\n let point2 = Vector3::new(point2.x, point2.y, point2.z);\n\n let lerped = point1.lerp(point2, i as f32 / count as f32);\n", "file_path": "generate_hurtboxes/src/main.rs", "rank": 57, "score": 102175.94188388222 }, { "content": "/// Enables the panic handler.\n\n/// Only use on Canon Collision applications with a gui\n\npub fn setup(build_version: &'static str, crate_name: &'static str) {\n\n // only enable if the handler exists, this ensures we get regular panics if run in a dev\n\n // environment and the panic handler isnt built.\n\n //\n\n // I have considered immediately quitting Canon Collision if it cant locate the panic handler i.e. the user has moved\n\n // the exe to a different folder. However that would break the above case.\n\n let pfs_dev_not_true = env::var(\"CC_DEV\").map(|x| x.to_lowercase() != \"true\").unwrap_or(true);\n\n let handler_exists = path_to_handler().map(|x| x.exists()).unwrap_or(false);\n\n if pfs_dev_not_true && handler_exists {\n\n panic::set_hook(Box::new(move |panic_info: &PanicInfo| {\n\n let (location_file, location_line, location_column) = match panic_info.location() {\n\n Some(loc) => (Some(loc.file().to_string()), Some(loc.line()), Some(loc.column())),\n\n None => (None, None, None)\n\n };\n\n\n\n let operating_system = if cfg!(windows) {\n\n \"windows\".into()\n\n } else {\n\n let platform = os_type::current_platform();\n\n format!(\"unix:{:?}\", platform.os_type).into()\n", "file_path": "canon_collision_lib/src/panic_handler.rs", "rank": 58, "score": 101495.42713891377 }, { "content": "fn generate_item_hold(frame: &mut ActionFrame, root_joint: &Joint, bone_name: &str) {\n\n for child in &root_joint.children {\n\n generate_item_hold(frame, child, bone_name);\n\n }\n\n\n\n if root_joint.name == bone_name {\n\n let transform = Matrix4::from_angle_y(Rad(f32::consts::PI / 2.0)) * &root_joint.transform;\n\n let point = transform.transform_point(Point3::new(0.0, 0.0, 0.0));\n\n let quaternion = matrix_to_quaternion(&transform);\n\n\n\n if frame.item_hold.is_some() {\n\n frame.item_hold = Some(ItemHold {\n\n translation_x: point.x,\n\n translation_y: point.y,\n\n translation_z: point.z,\n\n quaternion_x: quaternion.1,\n\n quaternion_y: quaternion.2,\n\n quaternion_z: quaternion.3,\n\n quaternion_rotation: -quaternion.0, // No idea why this needs to be inverted but it makes everything work ¯\\_(ツ)_/¯\n\n });\n\n }\n\n }\n\n}\n\n\n", "file_path": "generate_hurtboxes/src/main.rs", "rank": 59, "score": 100871.48494780282 }, { "content": "/// Given p, q, r are colinear,\n\n/// checks if point q lies on segment pr\n\nfn point_on_segment(p: (f32, f32), q: (f32, f32), r: (f32, f32)) -> bool {\n\n q.0 <= p.0.max(r.0) && q.0 >= p.0.min(r.0) && \n\n q.1 <= p.1.max(r.1) && q.1 >= p.1.min(r.1)\n\n}\n\n\n\n#[derive(Debug, Clone, Default, Serialize, Deserialize, Node)]\n\npub struct Rect {\n\n pub x1: f32,\n\n pub y1: f32,\n\n pub x2: f32,\n\n pub y2: f32\n\n}\n\n\n\nimpl Rect {\n\n pub fn from_tuples(p1: (f32, f32), p2: (f32, f32)) -> Rect {\n\n Rect {\n\n x1: p1.0,\n\n y1: p1.1,\n\n x2: p2.0,\n\n y2: p2.1\n", "file_path": "canon_collision_lib/src/geometry.rs", "rank": 60, "score": 100045.96112307628 }, { "content": "fn index_linear(channel: &Channel, frame: f32) -> (usize, usize, f32) {\n\n let seconds = frame / 60.0; // 60fps\n\n\n\n if seconds < *channel.inputs.first().unwrap() || channel.inputs.len() < 2 {\n\n return (0, 0, 0.0);\n\n }\n\n\n\n for (i, window) in channel.inputs.windows(2).enumerate() {\n\n let input_pre = window[0];\n\n let input_next = window[1];\n\n if seconds >= input_pre && seconds < input_next {\n\n let amount = (seconds - input_pre) / (input_next - input_pre);\n\n return (i, i + 1, amount);\n\n }\n\n }\n\n\n\n // seconds must be larger than highest input, so return the last index\n\n let last = channel.inputs.len() - 1;\n\n (last, last, 0.0)\n\n}\n\n\n", "file_path": "generate_hurtboxes/src/animation.rs", "rank": 61, "score": 99540.20032695276 }, { "content": "fn index_linear(channel: &Channel, frame: f32) -> (usize, usize, f32) {\n\n let seconds = frame / 60.0; // 60fps\n\n\n\n if seconds < *channel.inputs.first().unwrap() || channel.inputs.len() < 2 {\n\n return (0, 0, 0.0);\n\n }\n\n\n\n for (i, window) in channel.inputs.windows(2).enumerate() {\n\n let input_pre = window[0];\n\n let input_next = window[1];\n\n if seconds >= input_pre && seconds < input_next {\n\n let amount = (seconds - input_pre) / (input_next - input_pre);\n\n return (i, i + 1, amount);\n\n }\n\n }\n\n\n\n // seconds must be larger than highest input, so return the last index\n\n let last = channel.inputs.len() - 1;\n\n (last, last, 0.0)\n\n}\n\n\n", "file_path": "canon_collision/src/wgpu/animation.rs", "rank": 62, "score": 98176.39588965748 }, { "content": "fn digital_input_vbox(state: Rc<RwLock<State>>, input_text: String, dest: DigitalDest) -> Box {\n\n let vbox = Box::new(Orientation::Vertical, 5);\n\n\n\n let input_gc = digital_input_gc_hbox(state.clone(), vbox.clone(), input_text, dest.clone());\n\n vbox.add(&input_gc);\n\n\n\n let controller = state.read().unwrap().controller;\n\n if let Some(controller) = controller {\n\n let maps = state.read().unwrap().controller_maps.maps[controller].get_digital_maps(dest);\n\n for (index, map) in maps {\n\n input_digital_map_hbox(state.clone(), map, index, &vbox);\n\n }\n\n }\n\n\n\n vbox\n\n}\n\n\n", "file_path": "map_controllers/src/main.rs", "rank": 63, "score": 94884.64666468507 }, { "content": "fn analog_input_vbox(state: Rc<RwLock<State>>, input_text: String, dest: AnalogDest) -> Box {\n\n let vbox = Box::new(Orientation::Vertical, 5);\n\n\n\n let input_gc = analog_input_gc_hbox(state.clone(), vbox.clone(), input_text, dest.clone());\n\n vbox.add(&input_gc);\n\n\n\n let controller = state.read().unwrap().controller;\n\n if let Some(controller) = controller {\n\n let maps = state.read().unwrap().controller_maps.maps[controller].get_analog_maps(dest);\n\n for (index, map) in maps {\n\n input_analog_map_hbox(state.clone(), map, index, &vbox);\n\n }\n\n }\n\n\n\n vbox\n\n}\n\n\n", "file_path": "map_controllers/src/main.rs", "rank": 64, "score": 94884.64666468507 }, { "content": "fn index_step(channel: &Channel, frame: f32) -> usize {\n\n let seconds = frame / 60.0; // 60fps\n\n\n\n if seconds < *channel.inputs.first().unwrap() || channel.inputs.len() < 2 {\n\n return 0;\n\n }\n\n\n\n for (i, window) in channel.inputs.windows(2).enumerate() {\n\n let input_pre = window[0];\n\n let input_next = window[1];\n\n if seconds >= input_pre && seconds < input_next {\n\n return i;\n\n }\n\n }\n\n\n\n // seconds must be larger than highest input, so return the last index\n\n channel.inputs.len() - 1\n\n}\n\n\n", "file_path": "generate_hurtboxes/src/animation.rs", "rank": 65, "score": 93519.3887993136 }, { "content": "fn index_step(channel: &Channel, frame: f32) -> usize {\n\n let seconds = frame / 60.0; // 60fps\n\n\n\n if seconds < *channel.inputs.first().unwrap() || channel.inputs.len() < 2 {\n\n return 0;\n\n }\n\n\n\n for (i, window) in channel.inputs.windows(2).enumerate() {\n\n let input_pre = window[0];\n\n let input_next = window[1];\n\n if seconds >= input_pre && seconds < input_next {\n\n return i;\n\n }\n\n }\n\n\n\n // seconds must be larger than highest input, so return the last index\n\n channel.inputs.len() - 1\n\n}\n\n\n", "file_path": "canon_collision/src/wgpu/animation.rs", "rank": 66, "score": 91923.21855796003 }, { "content": "fn regenerate_action(action: &mut ActionDef, root_joint: &Joint, animation: &Animation, cli: &CLIResults, hurtboxes: &[HurtBox]) {\n\n if cli.resize {\n\n let frames = animation.len().max(1);\n\n while action.frames.len() > frames {\n\n action.frames.pop();\n\n }\n\n while action.frames.len() < frames {\n\n action.frames.push(ActionFrame::default());\n\n }\n\n }\n\n\n\n for frame in action.frames.iter_mut() {\n\n if cli.delete_hitboxes {\n\n frame.colboxes.clear();\n\n }\n\n else {\n\n for i in (0..frame.colboxes.len()).rev() {\n\n if let CollisionBoxRole::Hurt(_) = frame.colboxes[i].role {\n\n frame.colboxes.remove(i);\n\n }\n", "file_path": "generate_hurtboxes/src/main.rs", "rank": 67, "score": 89664.22919524078 }, { "content": "fn digital_input_gc_hbox(state: Rc<RwLock<State>>, vbox: Box, input_text: String, dest: DigitalDest) -> Box {\n\n let hbox = Box::new(Orientation::Horizontal, 5);\n\n\n\n let input_label = Label::new(Some(input_text.as_str()));\n\n hbox.add(&input_label);\n\n\n\n let detect_button = Button::with_label(\"Add from last input\");\n\n detect_button.connect_clicked(clone!(state, vbox, dest => move |_| {\n\n let last_code = state.read().unwrap().last_code.clone();\n\n match last_code {\n\n Code::Analog (code, history) => {\n\n let map = DigitalMap {\n\n dest: dest.clone(),\n\n filter: DigitalFilter::FromAnalog { min: history.last_value, max: history.last_value },\n\n source: code,\n\n };\n\n new_input_digital_map(state.clone(), vbox.clone(), map);\n\n }\n\n Code::Digital (code) => {\n\n let map = DigitalMap {\n", "file_path": "map_controllers/src/main.rs", "rank": 68, "score": 88621.73511038459 }, { "content": "fn analog_input_gc_hbox(state: Rc<RwLock<State>>, vbox: Box, input_text: String, dest: AnalogDest) -> Box {\n\n let hbox = Box::new(Orientation::Horizontal, 5);\n\n\n\n let input_label = Label::new(Some(input_text.as_str()));\n\n hbox.add(&input_label);\n\n\n\n let detect_button = Button::with_label(\"Add from last input\");\n\n detect_button.connect_clicked(clone!(state, vbox, dest => move |_| {\n\n let last_code = state.read().unwrap().last_code.clone();\n\n match last_code {\n\n Code::Analog (code, history) => {\n\n let map = AnalogMap {\n\n dest: dest.clone(),\n\n filter: AnalogFilter::FromAnalog { min: history.min, max: history.max, flip: false },\n\n source: code,\n\n };\n\n new_input_analog_map(state.clone(), vbox.clone(), map);\n\n }\n\n Code::Digital (code) => {\n\n let map = AnalogMap {\n", "file_path": "map_controllers/src/main.rs", "rank": 69, "score": 88621.73511038459 }, { "content": "fn new_input_digital_map(state: Rc<RwLock<State>>, vbox: Box, map: DigitalMap) {\n\n let push_index = {\n\n let mut state = state.write().unwrap();\n\n let i = state.controller.unwrap();\n\n state.controller_maps.maps[i].digital_maps.push(map.clone());\n\n state.controller_maps.maps[i].digital_maps.len() - 1\n\n };\n\n\n\n input_digital_map_hbox(state.clone(), map, push_index, &vbox);\n\n vbox.show_all();\n\n}\n\n\n", "file_path": "map_controllers/src/main.rs", "rank": 70, "score": 80688.69833189122 }, { "content": "fn new_input_analog_map(state: Rc<RwLock<State>>, vbox: Box, map: AnalogMap) {\n\n let push_index = {\n\n let mut state = state.write().unwrap();\n\n let i = state.controller.unwrap();\n\n state.controller_maps.maps[i].analog_maps.push(map.clone());\n\n state.controller_maps.maps[i].analog_maps.len() - 1\n\n };\n\n\n\n input_analog_map_hbox(state.clone(), map, push_index, &vbox);\n\n vbox.show_all();\n\n}\n\n\n", "file_path": "map_controllers/src/main.rs", "rank": 71, "score": 80688.69833189122 }, { "content": "fn colbox_shield_collision_check(player1_xy: (f32, f32), colbox1: &CollisionBox, player2_xy: (f32, f32), player2: &Player, fighter2: &EntityDef, player2_state: &ActionState) -> bool {\n\n if let &Some(ref shield) = &fighter2.shield {\n\n if player2.is_shielding(player2_state) {\n\n let x1 = player1_xy.0 + colbox1.point.0;\n\n let y1 = player1_xy.1 + colbox1.point.1;\n\n let r1 = colbox1.radius;\n\n\n\n let x2 = player2_xy.0 + player2.shield_offset_x + shield.offset_x;\n\n let y2 = player2_xy.1 + player2.shield_offset_y + shield.offset_y;\n\n let r2 = player2.shield_size(shield);\n\n\n\n let check_distance = r1 + r2;\n\n let real_distance = ((x1 - x2).powi(2) + (y1 - y2).powi(2)).sqrt();\n\n check_distance > real_distance\n\n } else {\n\n false\n\n }\n\n }\n\n else {\n\n false\n", "file_path": "canon_collision/src/collision/collision_box.rs", "rank": 72, "score": 76049.24210756444 }, { "content": "fn input_analog_map_hbox(state: Rc<RwLock<State>>, analog_map: AnalogMap, index: usize, parent: &Box) {\n\n let uuid = Uuid::new_v4();\n\n state.write().unwrap().ui_to_analog_map.insert(uuid, index);\n\n\n\n let hbox = Box::new(Orientation::Horizontal, 5);\n\n hbox.set_margin_start(60);\n\n\n\n hbox.add(&Label::new(Some(if analog_map.filter.is_digital_source() { \"Digital code\" } else { \"Analog code\" })));\n\n\n\n let input_code = analog_map.source.to_string();\n\n let code_entry_buffer = EntryBuffer::new(Some(input_code.as_ref()));\n\n let code_entry = Entry::with_buffer(&code_entry_buffer);\n\n code_entry.connect_changed(clone!(state => move |_| {\n\n if let Ok(value) = code_entry_buffer.text().parse() {\n\n let mut state = state.write().unwrap();\n\n let map_i = state.controller.unwrap();\n\n let analog_map_i = state.ui_to_analog_map[&uuid];\n\n state.controller_maps.maps[map_i].analog_maps[analog_map_i].source = value;\n\n }\n\n }));\n", "file_path": "map_controllers/src/main.rs", "rank": 73, "score": 75687.94416394722 }, { "content": "fn input_digital_map_hbox(state: Rc<RwLock<State>>, digital_map: DigitalMap, index: usize, parent: &Box) {\n\n let uuid = Uuid::new_v4();\n\n state.write().unwrap().ui_to_digital_map.insert(uuid, index);\n\n\n\n let hbox = Box::new(Orientation::Horizontal, 5);\n\n hbox.set_margin_start(60);\n\n\n\n hbox.add(&Label::new(Some(if digital_map.filter.is_digital_source() { \"Digital code\" } else { \"Analog code\" })));\n\n\n\n let input_code = digital_map.source.to_string();\n\n let code_entry_buffer = EntryBuffer::new(Some(input_code.as_ref()));\n\n let code_entry = Entry::with_buffer(&code_entry_buffer);\n\n code_entry.connect_changed(clone!(state => move |_| {\n\n if let Ok(value) = code_entry_buffer.text().parse() {\n\n let mut state = state.write().unwrap();\n\n let map_i = state.controller.unwrap();\n\n let digital_map_i = state.ui_to_digital_map[&uuid];\n\n state.controller_maps.maps[map_i].digital_maps[digital_map_i].source = value;\n\n }\n\n }));\n", "file_path": "map_controllers/src/main.rs", "rank": 74, "score": 75687.94416394722 }, { "content": "struct Draw {\n\n ty: DrawType,\n\n buffers: Rc<Buffers>,\n\n}\n\n\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 75, "score": 74221.59351915859 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct InputConfirm {\n\n inputs: Vec<ControllerInput>,\n\n frame: usize,\n\n}\n", "file_path": "canon_collision_lib/src/network.rs", "rank": 76, "score": 73226.79698458091 }, { "content": "#[derive(Clone, Copy)]\n\n#[repr(C)]\n\nstruct AnimatedUniform {\n\n transform: [[f32; 4]; 4],\n\n joint_transforms: JointTransforms,\n\n frame_count: f32,\n\n}\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 77, "score": 73216.86052501162 }, { "content": "#[derive(Clone, Copy, Pod, Zeroable)]\n\n#[repr(C)]\n\nstruct HitboxUniform {\n\n edge_color: [f32; 4],\n\n color: [f32; 4],\n\n transform: [[f32; 4]; 4],\n\n}\n\n\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 78, "score": 73216.86052501162 }, { "content": "struct StagingBelt {\n\n pub staging_belt: wgpu::util::StagingBelt,\n\n local_pool: futures::executor::LocalPool,\n\n local_spawner: futures::executor::LocalSpawner,\n\n}\n\n\n\nimpl StagingBelt {\n\n pub fn new() -> Self {\n\n let staging_belt = wgpu::util::StagingBelt::new(1024);\n\n let local_pool = futures::executor::LocalPool::new();\n\n let local_spawner = local_pool.spawner();\n\n StagingBelt { staging_belt, local_pool, local_spawner }\n\n }\n\n\n\n pub fn finish(&mut self) {\n\n self.staging_belt.finish();\n\n }\n\n\n\n /// Recall unused staging buffers\n\n pub fn recall(&mut self) {\n\n use futures::task::SpawnExt;\n\n\n\n self.local_spawner\n\n .spawn(self.staging_belt.recall())\n\n .expect(\"Recall staging belt\");\n\n\n\n self.local_pool.run_until_stalled();\n\n }\n\n}\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 79, "score": 73216.86052501162 }, { "content": "#[derive(Clone, Copy, Pod, Zeroable)]\n\n#[repr(C)]\n\nstruct TransformUniform {\n\n transform: [[f32; 4]; 4],\n\n}\n\n\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 80, "score": 73216.86052501162 }, { "content": "struct StageVertexConstructor;\n\nimpl FillVertexConstructor<ColorVertex> for StageVertexConstructor {\n\n fn new_vertex(&mut self, fill_vertex: FillVertex) -> ColorVertex {\n\n let position = fill_vertex.position();\n\n ColorVertex {\n\n position: [position.x, position.y, 0.0, 1.0],\n\n color: [0.16, 0.16, 0.16, 1.0]\n\n }\n\n }\n\n}\n\n\n\npub struct Buffers {\n\n pub vertex: Buffer,\n\n pub index: Buffer,\n\n pub index_count: u32,\n\n}\n\n\n\nimpl Buffers {\n\n pub fn new<T>(device: &Device, vertices: &[T], indices: &[u16]) -> Rc<Buffers> where T: Pod {\n\n let vertex = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {\n", "file_path": "canon_collision/src/wgpu/buffers.rs", "rank": 81, "score": 72258.10633584564 }, { "content": "#[derive(Clone, Copy, Pod, Zeroable)]\n\n#[repr(C)]\n\nstruct TransformUniformCycle {\n\n transform: [[f32; 4]; 4],\n\n frame_count: f32,\n\n}\n\n\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 82, "score": 72258.10633584564 }, { "content": "struct WindowSizeDependent {\n\n multisampled_framebuffer: TextureView,\n\n depth_stencil: TextureView,\n\n}\n\n\n\nimpl WindowSizeDependent {\n\n /// This method is called once during initialization, then again whenever the window is resized\n\n fn new(device: &Device, surface: &Surface, width: u32, height: u32) -> WindowSizeDependent {\n\n surface.configure(\n\n device,\n\n &wgpu::SurfaceConfiguration {\n\n usage: wgpu::TextureUsages::RENDER_ATTACHMENT,\n\n format: wgpu::TextureFormat::Bgra8Unorm,\n\n present_mode: wgpu::PresentMode::Mailbox,\n\n width,\n\n height,\n\n },\n\n );\n\n\n\n let multisampled_frame_descriptor = &wgpu::TextureDescriptor {\n", "file_path": "canon_collision/src/wgpu/mod.rs", "rank": 83, "score": 72258.10633584564 }, { "content": "struct GCAdapterBackend {\n\n pub handle: DeviceHandle<Context>,\n\n pub deadzones: [Deadzone; 4]\n\n}\n\n\n\nimpl GCAdapterBackend {\n\n /// Add 4 GC adapter controllers to inputs\n\n fn read(&mut self) -> [ControllerInput; 4] {\n\n let mut inputs = [ControllerInput::default(); 4];\n\n let mut data: [u8; 37] = [0; 37];\n\n if let Ok(_) = self.handle.read_interrupt(0x81, &mut data, Duration::new(1, 0)) {\n\n for port in 0..4 {\n\n let plugged_in = data[9*port+1] == 20 || data[9*port+1] == 16;\n\n let raw_stick_x = data[9*port+4];\n\n let raw_stick_y = data[9*port+5];\n\n let raw_c_stick_x = data[9*port+6];\n\n let raw_c_stick_y = data[9*port+7];\n\n let raw_l_trigger = data[9*port+8];\n\n let raw_r_trigger = data[9*port+9];\n\n\n", "file_path": "canon_collision_lib/src/input/gcadapter.rs", "rank": 84, "score": 71342.24541438751 }, { "content": "#[derive(Debug)]\n\nstruct PlayerGrabHit {\n\n item_i: EntityKey,\n\n distance: f32\n\n}\n", "file_path": "canon_collision/src/collision/item_grab.rs", "rank": 85, "score": 71342.24541438751 }, { "content": "fn main() {\n\n let mut cmd = Command::new(\"git\");\n\n cmd.args(&[\"describe\", \"--always\", \"--long\", \"--dirty\"]);\n\n\n\n let version = if let Ok(output) = cmd.output() {\n\n if output.status.success() {\n\n String::from_utf8(output.stdout).unwrap_or_else(|_| \"NO GIT\".into())\n\n } else {\n\n String::from(\"NO GIT\")\n\n }\n\n } else {\n\n String::from(\"NO GIT\")\n\n };\n\n println!(\"cargo:rustc-env=BUILD_VERSION={}\", version.trim());\n\n}\n", "file_path": "map_controllers/build.rs", "rank": 86, "score": 70758.54583172651 }, { "content": "fn main() {\n\n let mut cmd = Command::new(\"git\");\n\n cmd.args(&[\"describe\", \"--always\", \"--long\", \"--dirty\"]);\n\n\n\n let version = if let Ok(output) = cmd.output() {\n\n if output.status.success() {\n\n String::from_utf8(output.stdout).unwrap_or(String::from(\"NO GIT\"))\n\n } else {\n\n String::from(\"NO GIT\")\n\n }\n\n } else {\n\n String::from(\"NO GIT\")\n\n };\n\n println!(\"cargo:rustc-env=BUILD_VERSION={}\", version.trim());\n\n}\n", "file_path": "canon_collision/build.rs", "rank": 87, "score": 70758.54583172651 }, { "content": "/// This code is checked in to:\n\n/// * refer back to past changes\n\n/// * copy paste from previous similar transforms\n\n/// * allow for review of transforms run in a PR\n\n/// * makes it possible to restore old deleted files to the current format (via per file versioning)\n\nfn main() {\n\n if std::env::args().any(|x| x.to_lowercase() == \"init\") {\n\n let path = std::env::current_dir().unwrap().join(\"package\");\n\n Package::generate_base(path);\n\n println!(\"Created an empty package in the current directory.\");\n\n return;\n\n }\n\n\n\n if std::env::args().any(|x| x.to_lowercase() == \"action_indexes\") {\n\n for action in PlayerAction::iter() {\n\n println!(\"{:?} {}\", &action, action.clone() as usize);\n\n }\n\n return;\n\n }\n\n\n\n let dry_run = std::env::args().any(|x| x.to_lowercase() == \"dryrun\");\n\n\n\n if let Some(package_path) = Package::find_package_in_parent_dirs() {\n\n if let Ok (dir) = fs::read_dir(package_path.join(\"Entities\")) {\n\n for path in dir {\n\n let full_path = path.unwrap().path();\n\n upgrade_to_latest_entity(&full_path, dry_run);\n\n }\n\n }\n\n } else {\n\n println!(\"Could not find package in current directory or any of its parent directories.\");\n\n }\n\n}\n\n\n", "file_path": "package_upgrader/src/main.rs", "rank": 88, "score": 69670.41520989787 }, { "content": "fn main() {\n\n let cli = cli::cli();\n\n\n\n let mut assets = Assets::new().unwrap();\n\n\n\n if let Some(fighter_key) = &cli.fighter_name {\n\n let mut package = if let Some(path) = Package::find_package_in_parent_dirs() {\n\n if let Some(package) = Package::open(path) {\n\n package\n\n } else {\n\n println!(\"Could not load package\");\n\n return;\n\n }\n\n }\n\n else {\n\n println!(\"Could not find package/ in current directory or any of its parent directories.\");\n\n return;\n\n };\n\n\n\n let hurtboxes = hurtbox::get_hurtboxes();\n", "file_path": "generate_hurtboxes/src/main.rs", "rank": 89, "score": 69666.39933692942 }, { "content": "fn main() {\n\n canon_collision_lib::setup_panic_handler!();\n\n logger::init();\n\n\n\n let cli_results = cli::cli();\n\n let graphics_backend = cli_results.graphics_backend.clone();\n\n let (event_tx, render_rx) = app::run_in_thread(cli_results);\n\n\n\n match graphics_backend {\n\n #[cfg(feature = \"wgpu_renderer\")]\n\n GraphicsBackendChoice::Wgpu => {\n\n let event_loop = EventLoop::new();\n\n let mut graphics = futures::executor::block_on(WgpuGraphics::new(&event_loop, event_tx, render_rx));\n\n event_loop.run(move |event, _, control_flow| {\n\n graphics.update(event, control_flow);\n\n });\n\n }\n\n GraphicsBackendChoice::Headless => {\n\n // very silly way to do nothing, but I dont know a better way...\n\n let one_hundred_years_in_seconds = 60 * 60 * 24 * 365 * 100;\n\n std::thread::sleep(std::time::Duration::from_secs(one_hundred_years_in_seconds));\n\n }\n\n }\n\n}\n", "file_path": "canon_collision/src/main.rs", "rank": 90, "score": 69666.39933692942 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if let Some(file_name) = args.get(1) {\n\n display_window(file_name);\n\n }\n\n else {\n\n // The user probably just manually ran the executable dont tell them to report anything\n\n }\n\n}\n\n\n", "file_path": "panic_handler/src/main.rs", "rank": 91, "score": 69666.39933692942 }, { "content": "fn main() {\n\n std::process::exit(main_main());\n\n}\n\n\n", "file_path": "cc_cli/src/main.rs", "rank": 92, "score": 69666.39933692942 }, { "content": "fn main() {\n\n let mut cmd = Command::new(\"git\");\n\n cmd.args(&[\"describe\", \"--always\", \"--long\", \"--dirty\"]);\n\n\n\n let version = if let Ok(output) = cmd.output() {\n\n if output.status.success() {\n\n String::from_utf8(output.stdout).unwrap_or(String::from(\"NO GIT\"))\n\n } else {\n\n String::from(\"NO GIT\")\n\n }\n\n } else {\n\n String::from(\"NO GIT\")\n\n };\n\n println!(\"cargo:rustc-env=BUILD_VERSION={}\", version.trim());\n\n}\n", "file_path": "canon_collision_lib/build.rs", "rank": 93, "score": 69666.39933692942 }, { "content": "fn main() {\n\n canon_collision_lib::setup_panic_handler!();\n\n\n\n // Need to be careful with the rw lock.\n\n // It is easy to accidentally create a deadlock by accidentally triggering\n\n // a write locking callback, while we have a read lock, or vice versa.\n\n let state = Rc::new(RwLock::new(State::new()));\n\n\n\n gtk::init().unwrap();\n\n\n\n let window = Window::new(WindowType::Toplevel);\n\n window.set_default_height(800);\n\n window.set_title(\"CC Controller Mapper\");\n\n\n\n let vbox = Box::new(Orientation::Vertical, 5);\n\n vbox.set_margin_start(10);\n\n vbox.set_margin_top(10);\n\n vbox.add(&save_copy_hbox(state.clone()));\n\n window.add(&vbox);\n\n\n", "file_path": "map_controllers/src/main.rs", "rank": 94, "score": 69666.39933692942 }, { "content": "fn main() {\n\n let profile = env::var(\"PROFILE\").unwrap();\n\n println!(\"cargo:rustc-env=PROFILE={}\", profile);\n\n}\n", "file_path": "canon_collision_hot_reload/build.rs", "rank": 95, "score": 68626.62871830826 }, { "content": "fn main() {\n\n let (tx, rx) = std::sync::mpsc::channel();\n\n\n\n // run once\n\n tx.send(Event::Write(PathBuf::new())).unwrap();\n\n\n\n // run on file change\n\n let mut hotwatch = Hotwatch::new().unwrap();\n\n let clone_tx = tx.clone();\n\n hotwatch.watch(\"../canon_collision\", move |event| {\n\n clone_tx.send(event).unwrap();\n\n }).unwrap();\n\n hotwatch.watch(\"../canon_collision_lib\", move |event| {\n\n tx.send(event).unwrap();\n\n }).unwrap();\n\n\n\n run(rx);\n\n}\n\n\n", "file_path": "canon_collision_hot_reload/src/main.rs", "rank": 96, "score": 67635.55453214138 }, { "content": "pub trait FighterTrait {\n\n fn frame_step(&mut self, context: &mut StepContext, state: &ActionState) -> Option<ActionResult>;\n\n fn action_expired(&mut self, context: &mut StepContext, state: &ActionState) -> Option<ActionResult>;\n\n}\n\n\n\nimpl Fighter {\n\n pub fn get_player(&self) -> &Player {\n\n match self {\n\n Fighter::Toriel (fighter) => &fighter.player,\n\n }\n\n }\n\n\n\n pub fn get_player_mut(&mut self) -> &mut Player {\n\n match self {\n\n Fighter::Toriel (fighter) => &mut fighter.player,\n\n }\n\n }\n\n\n\n fn get_fighter_mut(&mut self) -> &mut dyn FighterTrait {\n\n match self {\n", "file_path": "canon_collision/src/entity/fighters/mod.rs", "rank": 97, "score": 67276.85604268823 }, { "content": "#[test]\n\nfn stick_deadzone_test() {\n\n // stick_deadzone(*, 0)\n\n assert_eq!(stick_deadzone(0, 0), 128);\n\n assert_eq!(stick_deadzone(1, 0), 129);\n\n assert_eq!(stick_deadzone(126, 0), 254);\n\n assert_eq!(stick_deadzone(127, 0), 255);\n\n assert_eq!(stick_deadzone(255, 0), 255);\n\n\n\n // stick_deadzone(*, 127)\n\n assert_eq!(stick_deadzone(0, 127), 1);\n\n assert_eq!(stick_deadzone(1, 127), 2);\n\n assert_eq!(stick_deadzone(127, 127), 128);\n\n assert_eq!(stick_deadzone(128, 127), 129);\n\n assert_eq!(stick_deadzone(129, 127), 130);\n\n assert_eq!(stick_deadzone(253, 127), 254);\n\n assert_eq!(stick_deadzone(254, 127), 255);\n\n assert_eq!(stick_deadzone(255, 127), 255);\n\n\n\n // stick_deadzone(*, 128)\n\n assert_eq!(stick_deadzone(0, 128), 0);\n", "file_path": "canon_collision_lib/src/input/filter.rs", "rank": 98, "score": 65786.42381187942 }, { "content": "fn main_main() -> i32 {\n\n let mut args = env::args();\n\n args.next();\n\n let out_vec: Vec<String> = args.collect();\n\n let out: String = format!(\"C{}\", out_vec.join(\" \"));\n\n\n\n match TcpStream::connect(\"127.0.0.1:1613\") {\n\n Ok(mut stream) => {\n\n stream.write_all(out.as_bytes()).unwrap();\n\n\n\n let mut result = String::new();\n\n if let Ok(_) = stream.read_to_string(&mut result) {\n\n println!(\"{}\", result);\n\n }\n\n 0\n\n }\n\n Err(e) => {\n\n println!(\"Could not connect to Canon Collision host: {}\", e);\n\n 1\n\n }\n\n }\n\n}\n", "file_path": "cc_cli/src/main.rs", "rank": 99, "score": 65184.283150187985 } ]
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 \"..\" => {\n\n v.pop();\n\n }\n\n a => {\n\n v.push(a);\n\n }\n\n }\n\n }\n\n\n\n v.retain(|&x| x != \".\");\n\n if v.len() == 0 {\n\n return None;\n\n }\n\n if v[0] != \"\" {\n\n return None;\n\n }\n\n\n\n Some(v.join(\"/\"))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 116394.48026313364 }, { "content": "pub fn extension(target: &String) -> Option<&str> {\n\n match Path::new(target.as_str()).extension() {\n\n Some(s) => s.to_str(),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 1, "score": 113151.13986978684 }, { "content": "pub fn ip() -> String {\n\n CONF.with(|c| c.borrow().ip.clone())\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 3, "score": 95098.7408728145 }, { "content": "pub fn port() -> String {\n\n CONF.with(|c| c.borrow().port.clone())\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 4, "score": 95098.7408728145 }, { "content": "pub fn server() -> String {\n\n CONF.with(|c| c.borrow().server.clone())\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 5, "score": 95098.7408728145 }, { "content": "pub fn root() -> String {\n\n CONF.with(|c| c.borrow().root.clone())\n\n}\n\n\n\n#[derive(Clone, Deserialize)]\n\npub struct ServerConf {\n\n pub ip: String,\n\n pub port: String,\n\n pub server: String,\n\n pub root: String,\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 6, "score": 95098.7408728145 }, { "content": "pub fn load(path: &str) -> ServerConf {\n\n let mut buffer = String::new();\n\n match File::open(path) {\n\n Ok(mut file) => match file.read_to_string(&mut buffer) {\n\n Ok(_) => {}\n\n Err(e) => {\n\n panic!(e);\n\n }\n\n },\n\n Err(e) => {\n\n panic!(e);\n\n }\n\n };\n\n\n\n match serde_json::from_str(buffer.as_str()) {\n\n Ok(conf) => {\n\n //CONF.with(|c| { *c.borrow_mut() = conf.clone(); });\n\n return conf;\n\n }\n\n Err(e) => {\n\n panic!(e);\n\n }\n\n }\n\n}\n", "file_path": "src/conf.rs", "rank": 7, "score": 90860.9765996437 }, { "content": "fn new_conf() -> ServerConf {\n\n ServerConf {\n\n ip: String::new(),\n\n port: String::new(),\n\n server: String::new(),\n\n root: String::new(),\n\n }\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 10, "score": 88642.20083039725 }, { "content": "pub fn modified(target: &String) -> Result<DateTime<Utc>, String> {\n\n\n\n fs::metadata(target)\n\n .map_err(|e| e.to_string())\n\n .and_then(|m| m.modified().map_err(|e| e.to_string()))\n\n .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).map_err(|e| e.to_string()))\n\n .and_then(|n| Ok(DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(n.as_secs() as i64, 0), Utc)))\n\n\n\n /*\n\n match fs::metadata(target) {\n\n Ok(metadata) => {\n\n match metadata.modified() {\n\n Ok(time) => {\n\n match time.duration_since(SystemTime::UNIX_EPOCH) {\n\n Ok(n) => Ok(DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(n.as_secs() as i64, 0), Utc)),\n\n Err(e) => Err(e.to_string()),\n\n }\n\n }\n\n Err(e) => Err(e.to_string()),\n\n }\n\n }\n\n Err(e) => Err(e.to_string()),\n\n }\n\n */\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 11, "score": 83563.95352742838 }, { "content": "pub fn set(conf: ServerConf) {\n\n CONF.with(|c| {\n\n *c.borrow_mut() = conf;\n\n })\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 12, "score": 79427.69394307902 }, { "content": "fn request_body() -> String {\n\n //format!(\"GET /get HTTP/1.0\\r\\n\\r\\n\")\n\n\n\n // Simple-Request\n\n //format!(\"GET http://{}/\\r\\n\", host);\n\n //format!(\"GET http://www.google.com/\\r\\n\", host);\n\n //format!(\"GET http://www.google.com/\\r\\n\");\n\n //format!(\"GET /index.html\\r\\n\")\n\n //format!(\"GET /index.html HTTP/1.0\\r\\n\\r\\n\");\n\n\n\n // HTTP/1.0\n\n //format!(\"GET / HTTP/1.0\\r\\nPragma: no-cache\\r\\n\\r\\n\");\n\n //format!(\"GET /ip HTTP/1.0\\r\\nPragma: no-cache\\r\\n\\r\\n\");\n\n //format!(\"GET /get HTTP/1.0\\r\\n\\r\\n\");\n\n\n\n // HTTP/1.1\n\n //format!(\"GET /index.html HTTP/1.1\\r\\n\\r\\n\");\n\n\n\n // httpbin.org\n\n let mut s = \"GET /../Cargo.toml HTTP/1.0\".to_string();\n", "file_path": "src/http-client.rs", "rank": 13, "score": 74830.70139680606 }, { "content": "pub fn datetime_to_http_date(dt: &DateTime<Utc>) -> String {\n\n let date_str = dt.to_rfc2822();\n\n format!(\"{} GMT\", &date_str[..date_str.len() - 6])\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 14, "score": 73729.4480948246 }, { "content": "pub fn new() -> Response {\n\n Response {\n\n version: Version::V0_9,\n\n status: status::OK,\n\n host: \"\",\n\n path: String::new(),\n\n header: HashMap::new(),\n\n\n\n modified_datetime: None,\n\n\n\n entity_body: Vec::new(),\n\n }\n\n}\n\n\n\nimpl Response {\n\n pub fn add_header(&mut self, name: &str, value: String) {\n\n self.header.insert(name.to_string(), value);\n\n }\n\n\n\n fn status_line(&self) -> String {\n", "file_path": "src/http_response.rs", "rank": 15, "score": 73478.45925079749 }, { "content": "pub fn new() -> Request {\n\n Request {\n\n //bytes: Cursor::new(Vec::new()),\n\n bytes: Vec::new(),\n\n method: method::GET,\n\n uri: String::new(),\n\n version: Version::V0_9,\n\n header: HashMap::new(),\n\n\n\n entity_body: String::new(),\n\n\n\n idx: 0,\n\n space_count: 0,\n\n }\n\n}\n\n\n\nimpl Request {\n\n fn skip_space(&mut self) {\n\n let mut length = 0;\n\n while self.idx + length < self.bytes.len() {\n", "file_path": "src/http_request.rs", "rank": 16, "score": 73478.45925079749 }, { "content": "pub fn to_string(c: Code) -> String {\n\n format!(\"{} {}\", c.0, c.1)\n\n}\n\n\n\npub const OK: Code = (200, \"OK\");\n\npub const CREATED: Code = (201, \"Created\");\n\npub const ACCEPTED: Code = (202, \"Accepted\");\n\npub const NO_CONTENT: Code = (204, \"No Content\");\n\npub const MOVED_PERMANENTLY: Code3 = (301, \"Moved Permanently\");\n\npub const MOVED_TEMPORARILY: Code3 = (302, \"Moved Temporarily\");\n\npub const NOT_MODIFIED: Code3 = (304, \"Not Modified\");\n\npub const BAD_REQUEST: Code = (400, \"Bad Request\");\n\npub const UNAUTHORIZED: Code = (401, \"Unauthorized\");\n\npub const FORBIDDEN: Code = (403, \"Forbidden\");\n\npub const NOT_FOUND: Code = (404, \"Not Found\");\n\npub const INTERNAL_SERVER_ERROR: Code = (500, \"Internal Server Error\");\n\npub const NOT_IMPLEMENTED: Code = (501, \"Not Implemented\");\n\npub const BAD_GATEWAY: Code = (502, \"Bad Gateway\");\n\npub const SERVICE_UNAVAILABLE: Code = (503, \"Service Unavailable\");\n\n\n", "file_path": "src/status.rs", "rank": 18, "score": 72962.13767046292 }, { "content": "pub fn read_file(file_name: &String, buf: &mut String) -> Result<usize, std::io::Error> {\n\n match File::open(file_name) {\n\n Ok(mut file) => file.read_to_string(buf),\n\n Err(e) => Err(e),\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 20, "score": 70699.54556773764 }, { "content": "fn is_ctl(u: u8) -> bool {\n\n return u == 127 || u <= 31;\n\n}\n\n\n", "file_path": "src/http_request.rs", "rank": 21, "score": 70378.42466010294 }, { "content": "fn is_char(u: u8) -> bool {\n\n return u <= 127;\n\n}\n\n\n", "file_path": "src/http_request.rs", "rank": 22, "score": 70378.42466010294 }, { "content": "fn is_tspecial(u: u8) -> bool {\n\n let ts = vec![\n\n 40, // \"(\"\n\n 41, // \")\"\n\n 60, // \"<\"\n\n 62, // \">\"\n\n 64, // \"@\"\n\n 44, // \",\"\n\n 59, // \";\"\n\n 58, // \":\"\n\n 92, // \"\\\\\"\n\n DQ, // \"\\\"\"\n\n 47, // \"/\"\n\n 91, // \"[\"\n\n 93, // \"]\"\n\n 63, // \"?\"\n\n 61, // \"=\"\n\n 123, // \"{\"\n\n 125, // \"}\"\n\n SP, HT,\n", "file_path": "src/http_request.rs", "rank": 23, "score": 70378.42466010294 }, { "content": "pub fn parse_http_date(s: &String) -> Result<DateTime<Utc>, chrono::format::ParseError> {\n\n let str_rfc2822 = format!(\"{} +0000\", &s.as_str()[..s.len()-4]);\n\n DateTime::<FixedOffset>::parse_from_rfc2822(str_rfc2822.as_str()).map(|dt| dt.with_timezone(&Utc))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 24, "score": 61639.40451734075 }, { "content": "pub fn ext(i: isize, s: &'static str) -> Code {\n\n (i, s)\n\n}\n\n\n", "file_path": "src/status.rs", "rank": 25, "score": 58897.97796166533 }, { "content": "#[test]\n\nfn test_parse_http_date() {\n\n let expected = \"Sat, 29 Oct 1994 19:43:31 +0000\";\n\n let arg = format!(\"{} GMT\", &expected[..expected.len()-6]);\n\n let dt = parse_http_date(&arg);\n\n\n\n assert_eq!(dt.map(|d| d.to_rfc2822()), Ok(expected.to_string()));\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 26, "score": 58684.28681777009 }, { "content": "fn main() -> std::io::Result<()> {\n\n //let host = \"www.google.com:80\";\n\n //let host = \"httpbin.org:80\";\n\n let mut stream = TcpStream::connect(HOST)?;\n\n\n\n // Ex.) curl 127.0.0.1:34254 --http1.0\n\n //let cnt = format!(\"GET / HTTP/1.0\\r\\nHost: {}\\r\\nUser-Agent: curl/7.58.0\\r\\nAccept: */*\\r\\n\\r\\n\", host);\n\n\n\n print!(\"sending ... \");\n\n stream.write(request_body().as_bytes())?;\n\n println!(\"done.\");\n\n\n\n //let mut buf = vec![0; 1024*1024*1024];\n\n let mut buf = vec![0; 1024];\n\n let mut response = Vec::new();\n\n loop {\n\n match stream.read(&mut buf) {\n\n Ok(n) => {\n\n //println!(\"> {} {}\", n, String::from_utf8(buf[0..n].to_vec()).unwrap());\n\n //print!(\"{}\", String::from_utf8(buf[0..n].to_vec()).unwrap());\n", "file_path": "src/http-client.rs", "rank": 30, "score": 31832.97325076852 }, { "content": "pub type Method = &'static str;\n\n\n\npub const GET: Method = \"GET\";\n\npub const HEAD: Method = \"HEAD\";\n\npub const POST: Method = \"POST\";\n\n\n\n// NOT IMPLEMENTED\n\npub const PUT: Method = \"PUT\";\n\npub const DELETE: Method = \"DELETE\";\n\npub const CONNECT: Method = \"CONNECT\";\n\npub const OPTIONS: Method = \"OPTIONS\";\n\npub const TRACE: Method = \"TRACE\";\n\npub const PATCH: Method = \"PATCH\";\n", "file_path": "src/method.rs", "rank": 31, "score": 26149.317676811916 }, { "content": "use std::cell::RefCell;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\n\n\nuse serde::Deserialize;\n\n\n\nthread_local! {\n\n static CONF: RefCell<ServerConf> = RefCell::new(new_conf());\n\n}\n\n\n", "file_path": "src/conf.rs", "rank": 32, "score": 25570.255030451313 }, { "content": "use std::fs;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::path::Path;\n\n\n\nuse std::time::SystemTime;\n\nuse chrono::{DateTime, FixedOffset, Utc, NaiveDateTime};\n\n\n", "file_path": "src/util.rs", "rank": 33, "score": 25563.494843019125 }, { "content": "use std::collections::HashMap;\n\nuse chrono::{DateTime, Utc};\n\n\n\nuse crate::http_request::*;\n\nuse crate::method;\n\nuse crate::status;\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Response {\n\n pub version: Version,\n\n pub status: status::Code,\n\n pub host: &'static str,\n\n pub path: String,\n\n pub header: HashMap<String, String>,\n\n\n\n pub modified_datetime: Option<DateTime<Utc>>,\n\n\n\n pub entity_body: Vec<u8>,\n\n}\n\n\n", "file_path": "src/http_response.rs", "rank": 38, "score": 9.69874845216178 }, { "content": "use std::collections::HashMap;\n\nuse chrono::{DateTime, Utc};\n\n\n\nuse crate::method;\n\nuse crate::util;\n\n\n\nconst CR: u8 = 13;\n\nconst LF: u8 = 10;\n\nconst SP: u8 = 32;\n\nconst HT: u8 = 9;\n\nconst DQ: u8 = 34;\n\n\n", "file_path": "src/http_request.rs", "rank": 39, "score": 9.249917282664871 }, { "content": " }\n\n Some(\"HEAD\") => {\n\n self.method = method::HEAD;\n\n }\n\n Some(\"POST\") => {\n\n self.method = method::POST;\n\n }\n\n m => {\n\n return Err(format!(\"The content has an unknown method: {:?}\", m));\n\n }\n\n }\n\n\n\n match self.next_word() {\n\n Some(s) => {\n\n self.uri = s.to_string();\n\n }\n\n None => {\n\n return Err(\"illegal state\".to_string());\n\n }\n\n }\n", "file_path": "src/http_request.rs", "rank": 40, "score": 7.466271818111618 }, { "content": "\n\n pub fn user_agent(&self) -> Option<&String> {\n\n self.get_header(\"User-Agent\")\n\n }\n\n\n\n pub fn pragma(&self) -> Option<&String> {\n\n self.get_header(\"Pragma\")\n\n }\n\n\n\n pub fn is_no_cache(&self) -> bool {\n\n match self.pragma() {\n\n Some(s) => s.contains(\"no-cache\"),\n\n None => false,\n\n }\n\n }\n\n\n\n pub fn authorization(&self) -> Vec<&str> {\n\n match self.get_header(\"Authorization\") {\n\n Some(s) => {\n\n if s.len() < 1 {\n", "file_path": "src/http_request.rs", "rank": 41, "score": 7.045645796684566 }, { "content": " self.header.get(&s.to_lowercase())\n\n }\n\n\n\n pub fn from(&self) -> Option<&String> {\n\n self.get_header(\"From\")\n\n }\n\n\n\n pub fn if_modified_since(&self) -> Option<DateTime<Utc>> {\n\n match self.get_header(\"If-Modified-Since\") {\n\n Some(s) => match util::parse_http_date(s) {\n\n Ok(dt) => Some(dt),\n\n Err(_) => None,\n\n }\n\n None => None,\n\n }\n\n }\n\n\n\n pub fn referer(&self) -> Option<&String> {\n\n self.get_header(\"Referer\")\n\n }\n", "file_path": "src/http_request.rs", "rank": 42, "score": 6.149783007722794 }, { "content": "\n\n #[allow(dead_code)]\n\n pub fn allow(&mut self, m: method::Method) {\n\n let value = match self.header.get(\"Allow\") {\n\n Some(s) => format!(\"{}, {}\", s, m),\n\n None => m.to_string(),\n\n };\n\n\n\n self.header.insert(\"Allow\".to_string(), value);\n\n }\n\n\n\n pub fn set_host(&mut self, ip_port: String) {\n\n self.header.insert(\"HOST\".to_string(), ip_port);\n\n }\n\n\n\n pub fn set_server(&mut self, name: String) {\n\n // Server = \"Server\" \":\" 1*( product | comment )\n\n self.header.insert(\"Server\".to_string(), name);\n\n }\n\n\n", "file_path": "src/http_response.rs", "rank": 43, "score": 6.145549466857779 }, { "content": "use std::io::prelude::*;\n\nuse std::net::TcpStream;\n\n\n\nconst HOST: &str = \"127.0.0.1:34254\";\n\n//const HOST: &str = \"httpbin.org:80\";\n\n\n", "file_path": "src/http-client.rs", "rank": 44, "score": 5.457631814435812 }, { "content": " Version::V0_9 => \"0.9\".to_string(), // The server would never generate this.\n\n Version::V1_0 => \"1.0\".to_string(),\n\n Version::V1_1 => \"1.1\".to_string(),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Request {\n\n //bytes: Cursor<Vec<u8>>,\n\n bytes: Vec<u8>,\n\n\n\n method: method::Method,\n\n pub uri: String,\n\n pub version: Version,\n\n header: HashMap<String,String>,\n\n\n\n entity_body: String,\n\n\n\n idx: usize,\n\n space_count: u32,\n\n}\n\n\n", "file_path": "src/http_request.rs", "rank": 45, "score": 5.36449841824 }, { "content": " while let Ok(()) = self.parse_header_entry() {\n\n let crlf = self.try_crlf();\n\n if crlf != None {\n\n // the end of header fields.\n\n self.idx += 2;\n\n break;\n\n }\n\n }\n\n\n\n // Entity-Body\n\n if self.idx < self.bytes.len() {\n\n for b in self.bytes[self.idx..].iter() {\n\n self.entity_body.push(char::from(*b));\n\n }\n\n }\n\n\n\n return Ok(());\n\n }\n\n\n\n pub fn get_header(&self, s: &str) -> Option<&String> {\n", "file_path": "src/http_request.rs", "rank": 46, "score": 4.908399493056816 }, { "content": " Ok(s) => Some(s),\n\n Err(_) => None,\n\n };\n\n }\n\n }\n\n return None;\n\n }\n\n\n\n fn parse_header_field_value(&mut self) -> Option<&str> {\n\n // field-value = *( field-content | LWS )\n\n //\n\n // LWS = [CRLF] 1*( SP | HT )\n\n //\n\n // field-content = <the OCTETs making up the field-value\n\n // and consisting of either *TEXT or combinations\n\n // of token, tspecials, and quoted-string>\n\n //\n\n // TEXT = <any OCTET except CTLs,\n\n // but including LWS>\n\n //\n", "file_path": "src/http_request.rs", "rank": 47, "score": 4.906455684471384 }, { "content": " return Vec::new();\n\n }\n\n // The first character is a space.\n\n s[1..].split(' ').collect()\n\n }\n\n None => Vec::new(),\n\n }\n\n }\n\n\n\n pub fn bytes(&self) -> Vec<u8> {\n\n self.bytes.clone()\n\n }\n\n}\n", "file_path": "src/http_request.rs", "rank": 48, "score": 4.87352831782992 }, { "content": " ];\n\n\n\n for i in ts {\n\n if i == u {\n\n return true;\n\n }\n\n }\n\n return false;\n\n}\n\n\n\n#[derive(PartialEq, Clone, Debug)]\n\npub enum Version {\n\n V0_9,\n\n V1_0,\n\n V1_1,\n\n}\n\n\n\nimpl Version {\n\n pub fn to_string(&self) -> String {\n\n match self {\n", "file_path": "src/http_request.rs", "rank": 50, "score": 4.659362761237671 }, { "content": " }\n\n\n\n None\n\n }\n\n\n\n fn try_lws(&self) -> Option<&str> {\n\n let u = self.bytes[self.idx];\n\n if u == SP || u == HT {\n\n let length = 1;\n\n return match std::str::from_utf8(&self.bytes[self.idx - length..self.idx]) {\n\n Ok(s) => Some(s),\n\n Err(_) => None,\n\n };\n\n }\n\n if self.idx + 2 < self.bytes.len() {\n\n let v = self.bytes[self.idx + 1];\n\n let w = self.bytes[self.idx + 2];\n\n if v == LF && (w == SP || w == HT) {\n\n let length = 3;\n\n return match std::str::from_utf8(&self.bytes[self.idx - length..self.idx]) {\n", "file_path": "src/http_request.rs", "rank": 51, "score": 4.577892023961379 }, { "content": " // TODO Divide headers into General-Header, Request-Header, Entity-Header.\n\n fn parse_header_entry(&mut self) -> Result<(), String> {\n\n // HTTP-header = field-name \":\" [ field-value ] CRLF\n\n\n\n let name = match self.next_token() {\n\n Some(s) => s.to_string(),\n\n None => {\n\n return Err(\"Error: filed name of request header.\".to_string());\n\n }\n\n };\n\n\n\n self.idx += 1; // Expect ':'.\n\n\n\n let value = match self.parse_header_field_value() {\n\n Some(s) => s.to_string(),\n\n None => {\n\n return Err(\"Error: filed value of request header.\".to_string());\n\n }\n\n };\n\n\n", "file_path": "src/http_request.rs", "rank": 52, "score": 4.571190777755917 }, { "content": " }\n\n } else if is_ctl(u) {\n\n length -= 1;\n\n break;\n\n } else {\n\n length += 1;\n\n }\n\n }\n\n\n\n if length > 0 {\n\n self.idx += length;\n\n return match std::str::from_utf8(&self.bytes[self.idx - length..self.idx]) {\n\n Ok(s) => Some(s),\n\n Err(_) => None,\n\n };\n\n }\n\n\n\n None\n\n }\n\n\n", "file_path": "src/http_request.rs", "rank": 53, "score": 4.5353324436990325 }, { "content": " self.idx += 2; // Expect \"CR LF\".\n\n self.header.insert(name.to_lowercase(), value.clone());\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn parse(&mut self, content: &mut Vec<u8>) -> Result<(), String> {\n\n if self.bytes.len() > 0 {\n\n return Ok(()); // already done.\n\n }\n\n\n\n self.bytes.append(content);\n\n\n\n if self.bytes.len() < 4 {\n\n return Err(\"The content is too short.\".to_string());\n\n }\n\n\n\n match self.next_word() {\n\n Some(\"GET\") => {\n\n self.method = method::GET;\n", "file_path": "src/http_request.rs", "rank": 55, "score": 4.194560041251675 }, { "content": " // quoted-string = ( <\"> *(qdtext) <\"> )\n\n //\n\n // qdtext = <any CHAR except <\"> and CTLs,\n\n // but including LWS>\n\n\n\n // TODO combinations of token, tspecials, and quoted-string\n\n\n\n // *TEXT\n\n let mut length = 0;\n\n while self.idx + length < self.bytes.len() {\n\n let u = self.bytes[self.idx + length];\n\n if u == CR || u == SP || u == HT {\n\n match self.try_lws() {\n\n Some(s) => {\n\n length += s.len();\n\n }\n\n None => {\n\n length -= 1;\n\n break;\n\n }\n", "file_path": "src/http_request.rs", "rank": 56, "score": 3.702037236448518 }, { "content": " // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF\n\n // \"HTTP/\" 1*DIGIT \".\" 1*DIGIT SP 3DIGIT SP\n\n format!(\n\n \"HTTP/{} {}\\r\\n\",\n\n self.version.to_string(),\n\n status::to_string(self.status)\n\n )\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn set_location(&mut self, status: status::Code3, absolute_uri: String) {\n\n // Location = \"Location\" \":\" absoluteURI\n\n self.status = status;\n\n self.header.insert(\"Location\".to_string(), absolute_uri);\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn set_extention_status(&mut self, id: isize, phrase: &'static str) {\n\n self.status = (id, phrase);\n\n }\n", "file_path": "src/http_response.rs", "rank": 57, "score": 3.435628376321101 }, { "content": " match self.bytes[self.idx + length] {\n\n //SP | CR | LF => {\n\n SP => {\n\n length += 1;\n\n }\n\n _ => {\n\n break;\n\n }\n\n }\n\n }\n\n self.idx += length;\n\n }\n\n\n\n fn next_word(&mut self) -> Option<&str> {\n\n self.skip_space();\n\n let mut length = 1;\n\n if self.idx + length >= self.bytes.len() {\n\n return None;\n\n }\n\n while self.idx + length < self.bytes.len() {\n", "file_path": "src/http_request.rs", "rank": 58, "score": 3.328705615653386 }, { "content": " s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Host: httpbin.org\");\n\n // s.push_str(\"\\r\\n\");\n\n s.push_str(\"Accept: application/json\");\n\n s.push_str(\"\\r\\n\");\n\n // s.push_str(\"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0\");\n\n // s.push_str(\"\\r\\n\");\n\n // //s.push_str(\"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\");\n\n // //s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Accept-Language: ja,en-US;q=0.7,en;q=0.3\");\n\n // s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Accept-Encoding: gzip, deflate\");\n\n // s.push_str(\"\\r\\n\");\n\n // s.push_str(\"DNT: 1\");\n\n // s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Connection: keep-alive\");\n\n // s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Upgrade-Insecure-Requests: 1\");\n\n // s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Pragma: no-cache\");\n\n // s.push_str(\"\\r\\n\");\n\n // s.push_str(\"Cache-Control: no-cache\");\n\n // s.push_str(\"\\r\\n\");\n\n s.push_str(\"\\r\\n\");\n\n return s;\n\n}\n\n\n", "file_path": "src/http-client.rs", "rank": 59, "score": 3.23382738907605 }, { "content": "# learn-http\n\n\n\n`learn-http` is a simple toy HTTP server. \n\n\n\n# Usage\n\n\n\n\n\n1. Run a server.\n\n\n\n```\n\n% cargo run --bin http-server\n\n```\n\n\n\n2. Access with a simple client.\n\n\n\n```\n\n% cargo run --bin http-client\n\n```\n\n\n\n# Features\n\n\n\n## HTTP/0.9\n\n\n\nHTTP/1.0 contains HTTP/0.9 features, and `learn-http` supports them.\n\n\n\n## HTTP/1.0\n\n\n\n* Configuration\n\n * [x] Content root\n\n * [x] Host's IP address\n\n * [x] Listen port\n\n * [x] Extension status code\n\n * [ ] Allow\n\n * [ ] Content-Encoding\n\n * [ ] Expires\n\n * [ ] Location\n\n\n\n* Header\n\n * [ ] Allow https://tools.ietf.org/html/rfc1945#section-10.1\n\n * [x] Authorization https://tools.ietf.org/html/rfc1945#section-10.2\n\n * [ ] Content-Encoding https://tools.ietf.org/html/rfc1945#section-10.3\n\n * [x] Content-Length\n\n * [x] Content-Type\n\n * [x] Date\n\n * [ ] Expires https://tools.ietf.org/html/rfc1945#section-10.7\n\n * [x] From\n\n * [x] If-Modified-Since\n\n * [x] Last-Modified\n\n * [ ] Location\n\n * [x] Pragma\n\n * [x] Referer\n\n * [x] Server\n\n * [x] User-Agent\n\n * [x] WWW-authenticate https://tools.ietf.org/html/rfc1945#section-10.16\n\n \n\n \n\n* Additinal Header\n\n * [ ] Accept\n\n * [ ] Accept-Charset\n\n * [ ] Accept-Encoding\n\n * [ ] Accept-Language\n\n * [ ] Link\n\n * [ ] MIME-Version\n\n * [ ] Retry-After\n\n * [ ] Title\n\n * [ ] URI\n\n \n\n\n\n* Access Authentication https://tools.ietf.org/html/rfc1945#section-11\n\n * [x] Basic authentication\n\n\n\n## HTTP/1.1\n\n\n\n* Method\n\n\n\n* Header\n\n\n\n* Access Authentication https://tools.ietf.org/html/rfc2616#section-11\n\n * [ ] Digest authentication https://tools.ietf.org/html/rfc2616#ref-43\n", "file_path": "README.md", "rank": 61, "score": 2.7212984853105597 }, { "content": " response.append(&mut buf[0..n].to_vec());\n\n if n == 0 {\n\n break;\n\n }\n\n }\n\n Err(e) => {\n\n println!(\"{:?}\", e);\n\n }\n\n }\n\n }\n\n\n\n unsafe {\n\n println!(\"{}\", String::from_utf8_unchecked(response));\n\n }\n\n //println!(\"{}\", String::from_utf8(response).unwrap());\n\n Ok(())\n\n}\n", "file_path": "src/http-client.rs", "rank": 63, "score": 2.5132898286270082 }, { "content": " break;\n\n }\n\n }\n\n\n\n match std::str::from_utf8(&self.bytes[self.idx..self.idx + length]) {\n\n Ok(s) => {\n\n self.idx += length;\n\n Some(s)\n\n }\n\n Err(e) => {\n\n panic!(e);\n\n }\n\n }\n\n }\n\n\n\n fn try_crlf(&self) -> Option<&str> {\n\n if self.idx + 1 < self.bytes.len() {\n\n if self.bytes[self.idx] == CR && self.bytes[self.idx + 1] == LF {\n\n return Some(\"\\r\\n\");\n\n }\n", "file_path": "src/http_request.rs", "rank": 66, "score": 2.363509466062603 }, { "content": "#![allow(dead_code)]\n\n\n\npub type Code = (isize, &'static str);\n\npub type Code3 = Code;\n\n\n", "file_path": "src/status.rs", "rank": 67, "score": 2.2360115656311517 }, { "content": "\n\n match std::str::from_utf8(&self.bytes[self.idx..self.idx + length]) {\n\n Ok(s) => {\n\n self.idx += length;\n\n Some(s)\n\n }\n\n Err(e) => {\n\n panic!(e);\n\n }\n\n }\n\n }\n\n\n\n fn next_token(&mut self) -> Option<&str> {\n\n let mut length = 0;\n\n while self.idx + length < self.bytes.len() {\n\n // token = 1*<any CHAR except CTLs or tspecials>\n\n let u = self.bytes[self.idx + length];\n\n if is_char(u) && !is_ctl(u) && !is_tspecial(u) {\n\n length += 1;\n\n } else {\n", "file_path": "src/http_request.rs", "rank": 68, "score": 2.1307118832346372 }, { "content": " // TODO WWW-Authenticate\n\n\n\n pub fn to_bytes(&self) -> Vec<u8> {\n\n let mut ret = Vec::new();\n\n\n\n // Status-Line\n\n ret.append(&mut Vec::from(self.status_line().as_bytes()));\n\n\n\n // Header\n\n for (k, v) in &self.header {\n\n ret.append(&mut Vec::from(format!(\"{}: {}\\r\\n\", k, v).as_bytes()));\n\n }\n\n\n\n ret.append(&mut Vec::from(\"\\r\\n\".as_bytes()));\n\n\n\n ret.append(&mut self.entity_body.clone());\n\n\n\n return ret;\n\n }\n\n}\n", "file_path": "src/http_response.rs", "rank": 69, "score": 1.5377102981037627 }, { "content": "# HTTP/1.1\n\n\n\nhttps://tools.ietf.org/html/rfc2616\n\n\n\n# HTTP/2.0\n\n\n\nhttps://tools.ietf.org/html/rfc7540\n\n\n\n# memo\n\n\n\nhttps://developer.mozilla.org/ja/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP\n\n\n\n\n\nhttps://yamitzky.hatenablog.com/entry/2016/05/13/204107\n\n\n\nhttps://httpbin.org/ip\n\n\n\n\n\nhttps://nullsweep.com/http-security-headers-a-complete-guide/\n", "file_path": "doc/doc.md", "rank": 70, "score": 1.481659033215868 }, { "content": "https://tools.ietf.org/html/rfc1700\n\n\n\n```\n\nContent Types and Subtypes\n\n--------------------------\n\n\n\nType Subtype Description Reference\n\n---- ------- ----------- ---------\n\ntext plain [RFC1521,NSB]\n\n richtext [RFC1521,NSB]\n\n tab-separated-values [Paul Lindner]\n\n\n\nmultipart mixed [RFC1521,NSB]\n\n alternative [RFC1521,NSB]\n\n digest [RFC1521,NSB]\n\n parallel [RFC1521,NSB]\n\n appledouble [MacMime,Patrik Faltstrom]\n\n header-set [Dave Crocker]\n\n\n\nmessage rfc822 [RFC1521,NSB]\n\n partial [RFC1521,NSB]\n\n external-body [RFC1521,NSB]\n", "file_path": "doc/media_type.md", "rank": 71, "score": 1.23821509091271 }, { "content": " news [RFC 1036, Henry Spencer]\n\n\n\napplication octet-stream [RFC1521,NSB]\n\n postscript [RFC1521,NSB]\n\n oda [RFC1521,NSB]\n\n atomicmail [atomicmail,NSB]\n\n andrew-inset [andrew-inset,NSB]\n\n slate [slate,terry crowley]\n\n wita [Wang Info Transfer,Larry Campbell]\n\n dec-dx [Digital Doc Trans, Larry Campbell]\n\n dca-rft [IBM Doc Content Arch, Larry Campbell]\n\n activemessage [Ehud Shapiro]\n\n rtf [Paul Lindner]\n\n applefile [MacMime,Patrik Faltstrom]\n\n mac-binhex40 [MacMime,Patrik Faltstrom]\n\n news-message-id [RFC1036, Henry Spencer]\n\n news-transmission [RFC1036, Henry Spencer]\n\n wordperfect5.1 [Paul Lindner]\n\n pdf [Paul Lindner]\n\n zip [Paul Lindner]\n\n macwriteii [Paul Lindner]\n\n msword [Paul Lindner]\n\n remote-printing [RFC1486,MTR]\n\n\n\nimage jpeg [RFC1521,NSB]\n\n gif [RFC1521,NSB]\n\n ief Image Exchange Format [RFC1314]\n\n tiff Tag Image File Format [MTR]\n\n\n\naudio basic [RFC1521,NSB]\n\n\n\nvideo mpeg [RFC1521,NSB]\n\n quicktime [Paul Lindner]\n\n```\n", "file_path": "doc/media_type.md", "rank": 72, "score": 0.7874590934581325 }, { "content": "# HTTP/1.0\n\n\n\nhttps://tools.ietf.org/html/rfc1945\n\n\n\nhttps://tools.ietf.org/html/rfc1945#section-4.1\n\n\n\n```\n\nFull-Request = Request-Line ; Section 5.1\n\n *( General-Header ; Section 4.3\n\n | Request-Header ; Section 5.2\n\n | Entity-Header ) ; Section 7.1\n\n CRLF\n\n [ Entity-Body ] ; Section 7.2\n\n\n\nRequest-Line = Method SP Request-URI SP HTTP-Version CRLF\n\n```\n\n\n\n```\n\n LWS = [CRLF] 1*( SP | HT )\n\n\n\n token = 1*<any CHAR except CTLs or tspecials>\n\n\n\n tspecials = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n\n | \",\" | \";\" | \":\" | \"\\\" | <\">\n\n | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n\n | \"{\" | \"}\" | SP | HT\n\n```\n\n\n\n\n\n## Response\n\n\n\nhttps://tools.ietf.org/html/rfc1945#section-6\n\n\n\n\n\n```\n\n Response = Simple-Response | Full-Response\n\n\n\n Simple-Response = [ Entity-Body ]\n\n\n\n Full-Response = Status-Line ; Section 6.1\n\n *( General-Header ; Section 4.3\n\n | Response-Header ; Section 6.2\n\n | Entity-Header ) ; Section 7.1\n\n CRLF\n\n [ Entity-Body ] ; Section 7.2\n\n```\n\n\n\n```\n\n Response-Header = Location ; Section 10.11\n\n | Server ; Section 10.14\n\n | WWW-Authenticate ; Section 10.16\n\n```\n\n\n\n\n\nhttps://tools.ietf.org/html/rfc1945#section-7.1\n\n\n\n```\n\n Entity-Header = Allow ; Section 10.1\n\n | Content-Encoding ; Section 10.3\n\n | Content-Length ; Section 10.4\n\n | Content-Type ; Section 10.5\n\n | Expires ; Section 10.7\n\n | Last-Modified ; Section 10.10\n\n | extension-header\n\n\n\n extension-header = HTTP-header\n\n```\n\n\n\n\n\n\n", "file_path": "doc/doc.md", "rank": 73, "score": 0.7179227145597418 } ]
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 return Err(\"Name shouldn't be empty\".to_owned());\n\n }\n\n if !name\n\n .as_bytes()\n\n .iter()\n\n .copied()\n\n .all(is_allowed_component_char)\n\n {\n\n return Err(format!(\n\n \"Name `{}` contains invalid chars (allowed: `A-Z`, `a-z`, `0-9`, `_` and `-`)\",\n\n name\n\n ));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/derive/src/db_traits.rs", "rank": 1, "score": 379905.35768840555 }, { "content": "/// Validates that an index `name` consists of allowed chars. This method does not check\n\n/// if `name` is empty.\n\npub fn is_valid_identifier(name: &str) -> bool {\n\n name.as_bytes()\n\n .iter()\n\n .all(|&c| is_allowed_index_name_char(c) || c == b'.')\n\n}\n\n\n", "file_path": "components/merkledb/src/validation.rs", "rank": 2, "score": 357346.9933235658 }, { "content": "pub fn serialize<S>(inner: &Result<(), ExecutionError>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n ExecutionStatus::from(inner.as_ref().map(|_| ())).serialize(serializer)\n\n}\n\n\n", "file_path": "exonum/src/runtime/error/execution_result.rs", "rank": 3, "score": 344430.08497905324 }, { "content": "fn start_service_instance(testkit: &mut TestKit, instance_name: &str) -> InstanceId {\n\n let api = testkit.api();\n\n assert!(!service_instance_exists(&api, instance_name));\n\n let request = start_service_request(default_artifact(), instance_name, testkit.height().next());\n\n let hash = start_service(&api, request);\n\n testkit.create_block();\n\n api.exonum_api().assert_tx_success(hash);\n\n\n\n let api = testkit.api(); // Update the API\n\n assert!(service_instance_exists(&api, instance_name));\n\n find_instance_id(&api, instance_name)\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/main.rs", "rank": 4, "score": 331422.867335484 }, { "content": "pub fn serialize<S>(inner: &ExecutionError, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n ExecutionStatus::from(Err(inner)).serialize(serializer)\n\n}\n\n\n", "file_path": "exonum/src/runtime/error/execution_error.rs", "rank": 5, "score": 323747.3362097859 }, { "content": "/// Validates that a `prefix` consists of chars allowed for an index prefix.\n\n///\n\n/// Unlike [full names], prefixes are not allowed to contain a dot char `'.'`.\n\n///\n\n/// [full names]: fn.is_valid_identifier.html\n\npub fn is_valid_index_name_component(prefix: &str) -> bool {\n\n prefix\n\n .as_bytes()\n\n .iter()\n\n .copied()\n\n .all(is_allowed_index_name_char)\n\n}\n\n\n", "file_path": "components/merkledb/src/validation.rs", "rank": 6, "score": 313999.0230533183 }, { "content": "/// Prompt user for a passphrase. The user must enter the passphrase twice.\n\n/// Passphrase must not be empty.\n\nfn prompt_passphrase(prompt: &str) -> Result<Passphrase, Error> {\n\n loop {\n\n let password = Passphrase::read_from_tty(prompt)?;\n\n if password.is_empty() {\n\n eprintln!(\"Passphrase must not be empty. Try again.\");\n\n continue;\n\n }\n\n\n\n let confirmation = Passphrase::read_from_tty(\"Enter same passphrase again: \")?;\n\n\n\n if password == confirmation {\n\n return Ok(password);\n\n } else {\n\n eprintln!(\"Passphrases do not match. Try again.\");\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "cli/src/password.rs", "rank": 7, "score": 302603.44228593074 }, { "content": "pub fn deserialize<'a, D>(deserializer: D) -> Result<Result<(), ExecutionError>, D::Error>\n\nwhere\n\n D: Deserializer<'a>,\n\n{\n\n ExecutionStatus::deserialize(deserializer)\n\n .and_then(|status| status.into_result().map_err(D::Error::custom))\n\n}\n", "file_path": "exonum/src/runtime/error/execution_result.rs", "rank": 8, "score": 302095.5162337858 }, { "content": "/// Saves TOML-encoded file.\n\n///\n\n/// Creates directory if needed.\n\npub fn save_config_file<P, T>(value: &T, path: P) -> Result<(), Error>\n\nwhere\n\n T: Serialize,\n\n P: AsRef<Path>,\n\n{\n\n let path = path.as_ref();\n\n do_save(value, path).with_context(|_| format!(\"saving config to {}\", path.display()))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "cli/src/io.rs", "rank": 9, "score": 300485.5345520736 }, { "content": "fn artifact_exists(api: &TestKitApi, name: &str) -> bool {\n\n let artifacts = &api.exonum_api().services().artifacts;\n\n artifacts.iter().any(|a| a.name == name)\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/main.rs", "rank": 10, "score": 299971.92129070015 }, { "content": "/// Computes the root hash of the Merkle Patricia tree backing the specified entries\n\n/// in the map view.\n\n///\n\n/// The tree is not restored in full; instead, we add the paths to\n\n/// the tree in their lexicographic order (i.e., according to the `PartialOrd` implementation\n\n/// of `ProofPath`) and keep track of the rightmost nodes (the right contour) of the tree.\n\n/// It is easy to see that adding paths in the lexicographic order means that only\n\n/// the nodes in the right contour may be updated on each step. Further, on each step\n\n/// zero or more nodes are evicted from the contour, and a single new node is\n\n/// added to it.\n\n///\n\n/// `entries` are assumed to be sorted by the path in increasing order.\n\nfn collect(entries: &[Cow<'_, MapProofEntry>]) -> Result<Hash, MapProofError> {\n\n fn common_prefix(x: &ProofPath, y: &ProofPath) -> ProofPath {\n\n x.prefix(x.common_prefix_len(y))\n\n }\n\n\n\n fn hash_branch(left_child: &MapProofEntry, right_child: &MapProofEntry) -> Hash {\n\n let mut branch = BranchNode::empty();\n\n branch.set_child(ChildKind::Left, &left_child.path, &left_child.hash);\n\n branch.set_child(ChildKind::Right, &right_child.path, &right_child.hash);\n\n branch.object_hash()\n\n }\n\n\n\n /// Folds two last entries in a contour and replaces them with the folded entry.\n\n ///\n\n /// Returns an updated common prefix between two last entries in the contour.\n\n fn fold(contour: &mut Vec<MapProofEntry>, last_prefix: ProofPath) -> Option<ProofPath> {\n\n let last_entry = contour.pop().unwrap();\n\n let penultimate_entry = contour.pop().unwrap();\n\n\n\n contour.push(MapProofEntry {\n", "file_path": "components/merkledb/src/indexes/proof_map/proof.rs", "rank": 11, "score": 298915.2705085702 }, { "content": "/// Returns API builder instance with the appropriate endpoints for the specified\n\n/// Rust runtime instance.\n\npub fn endpoints(runtime: &RustRuntime) -> impl IntoIterator<Item = (String, ApiBuilder)> {\n\n let artifact_proto_sources = runtime\n\n .available_artifacts\n\n .iter()\n\n .map(|(artifact_id, service_factory)| {\n\n (\n\n artifact_id.clone(),\n\n service_factory.artifact_protobuf_spec(),\n\n )\n\n })\n\n .collect::<HashMap<_, _>>();\n\n let exonum_sources = exonum_proto_sources();\n\n // Cache filtered sources to avoid expensive operations in the endpoint handler.\n\n let filtered_sources = artifact_proto_sources\n\n .into_iter()\n\n .map(|(artifact_id, sources)| {\n\n let mut proto = sources.sources;\n\n proto.extend(filter_exonum_proto_sources(\n\n sources.includes,\n\n &exonum_sources,\n", "file_path": "exonum/src/runtime/rust/runtime_api.rs", "rank": 12, "score": 297406.86919159174 }, { "content": "fn service_instance_exists(api: &TestKitApi, name: &str) -> bool {\n\n let services = &api.exonum_api().services().services;\n\n services.iter().any(|s| s.spec.name == name)\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/main.rs", "rank": 13, "score": 295530.0622988926 }, { "content": "/// This function checks that the given database is compatible with the current `MerkleDB` version.\n\npub fn check_database(db: &mut dyn Database) -> Result<()> {\n\n let fork = db.fork();\n\n {\n\n let addr = ResolvedAddress::system(DB_METADATA);\n\n let mut view = View::new(&fork, addr);\n\n if let Some(saved_version) = view.get::<_, u8>(VERSION_NAME) {\n\n if saved_version != DB_VERSION {\n\n return Err(Error::new(format!(\n\n \"Database version doesn't match: actual {}, expected {}\",\n\n saved_version, DB_VERSION\n\n )));\n\n }\n\n\n\n return Ok(());\n\n } else {\n\n view.put(VERSION_NAME, DB_VERSION);\n\n }\n\n }\n\n db.merge(fork.into_patch())\n\n}\n", "file_path": "components/merkledb/src/db.rs", "rank": 14, "score": 286439.54108788917 }, { "content": "fn bench_fn<F>(c: &mut Criterion, name: &str, benchmark: F)\n\nwhere\n\n F: Fn(&mut Bencher<'_>, usize) + 'static,\n\n{\n\n let item_counts = ITEM_COUNTS.iter().cloned();\n\n c.bench(\n\n name,\n\n ParameterizedBenchmark::new(\n\n \"items\",\n\n move |b: &mut Bencher<'_>, &len: &usize| benchmark(b, len),\n\n item_counts,\n\n )\n\n .throughput(|s| Throughput::Elements((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 15, "score": 284831.0378909351 }, { "content": "/// Performs the logger initialization.\n\npub fn init_logger() -> Result<(), SetLoggerError> {\n\n Builder::from_default_env()\n\n .default_format_timestamp_nanos(true)\n\n .try_init()\n\n}\n\n\n\n/// Generates testnet configuration. This function needs to be public to be used in `tests`.\n", "file_path": "exonum/src/helpers/mod.rs", "rank": 16, "score": 280684.82971481734 }, { "content": "pub fn deserialize<'a, D>(deserializer: D) -> Result<ExecutionError, D::Error>\n\nwhere\n\n D: Deserializer<'a>,\n\n{\n\n ExecutionStatus::deserialize(deserializer).and_then(|status| {\n\n status\n\n .into_result()\n\n .and_then(|res| match res {\n\n Err(err) => Ok(err),\n\n Ok(()) => Err(\"Not an error\"),\n\n })\n\n .map_err(D::Error::custom)\n\n })\n\n}\n", "file_path": "exonum/src/runtime/error/execution_error.rs", "rank": 17, "score": 280612.3176045589 }, { "content": "fn copy_secured(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<(), failure::Error> {\n\n let mut source_file = fs::File::open(&from)?;\n\n\n\n let mut destination_file = {\n\n let mut open_options = OpenOptions::new();\n\n open_options.create(true).write(true);\n\n #[cfg(unix)]\n\n open_options.mode(0o600);\n\n open_options.open(&to)?\n\n };\n\n\n\n std::io::copy(&mut source_file, &mut destination_file)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "cli/tests/cli.rs", "rank": 18, "score": 279449.6095601853 }, { "content": "/// Check that the artifact name contains only allowed characters and is not empty.\n\n///\n\n/// Only these combination of symbols are allowed:\n\n///\n\n/// `[0..9]`, `[a-z]`, `[A-Z]`, `_`, `-`, `.`, ':'\n\nfn check_artifact_name(name: impl AsRef<[u8]>) -> bool {\n\n name.as_ref()\n\n .iter()\n\n .copied()\n\n .all(is_allowed_artifact_name_char)\n\n}\n\n\n", "file_path": "components/derive/src/service_factory.rs", "rank": 19, "score": 274524.40606709325 }, { "content": "/// Takes a subset of hashes at a particular height in the Merkle tree and\n\n/// computes all known hashes on the next height.\n\n///\n\n/// # Arguments\n\n///\n\n/// - `last_index` is the index of the last element in the Merkle tree on the given height.\n\n///\n\n/// # Return value\n\n///\n\n/// The `layer` is modified in place. An error is returned if the layer is malformed (e.g.,\n\n/// there is insufficient data to hash it).\n\n///\n\n/// # Examples\n\n///\n\n/// See unit tests at the end of this file.\n\nfn hash_layer(layer: &mut Vec<HashedEntry>, last_index: u64) -> Result<(), ListProofError> {\n\n let new_len = (layer.len() + 1) / 2;\n\n for i in 0..new_len {\n\n let x = &layer[2 * i];\n\n layer[i] = if let Some(y) = layer.get(2 * i + 1) {\n\n // To be able to zip two hashes on the layer, they need to be adjacent to each other,\n\n // and the first of them needs to have an even index.\n\n if !x.key.is_left() || y.key.index() != x.key.index() + 1 {\n\n return Err(ListProofError::MissingHash);\n\n }\n\n HashedEntry::new(x.key.parent(), HashTag::hash_node(&x.hash, &y.hash))\n\n } else {\n\n // If there is an odd number of hashes on the layer, the solitary hash must have\n\n // the greatest possible index.\n\n if last_index % 2 == 1 || x.key.index() != last_index {\n\n return Err(ListProofError::MissingHash);\n\n }\n\n HashedEntry::new(x.key.parent(), HashTag::hash_single_node(&x.hash))\n\n };\n\n }\n", "file_path": "components/merkledb/src/indexes/proof_list/proof.rs", "rank": 20, "score": 271291.7949498298 }, { "content": "fn reject_transaction(schema: &mut Schema<&Fork>, hash: &Hash) -> Result<(), ()> {\n\n let contains = schema.transactions_pool().contains(hash);\n\n schema.transactions_pool().remove(hash);\n\n schema.transactions().remove(hash);\n\n\n\n if contains {\n\n let x = schema.transactions_pool_len_index().get().unwrap();\n\n schema.transactions_pool_len_index().set(x - 1);\n\n Ok(())\n\n } else {\n\n Err(())\n\n }\n\n}\n\n\n", "file_path": "test-suite/consensus-tests/src/lib.rs", "rank": 21, "score": 269672.35181546933 }, { "content": "pub fn generate_index_type() -> impl Strategy<Value = IndexType> {\n\n prop_oneof![\n\n strategy::Just(IndexType::Entry),\n\n strategy::Just(IndexType::ProofEntry),\n\n strategy::Just(IndexType::List),\n\n strategy::Just(IndexType::ProofList),\n\n strategy::Just(IndexType::Map),\n\n strategy::Just(IndexType::ProofMap),\n\n ]\n\n}\n\n\n", "file_path": "components/merkledb/tests/work/mod.rs", "rank": 22, "score": 269238.2007245064 }, { "content": "fn find_instance_id(api: &TestKitApi, instance_name: &str) -> InstanceId {\n\n let services = &api.exonum_api().services().services;\n\n services\n\n .iter()\n\n .find(|service| service.spec.name == instance_name)\n\n .expect(\"Can't find the instance\")\n\n .spec\n\n .id\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/main.rs", "rank": 23, "score": 268337.9499321363 }, { "content": "/// Loads TOML-encoded file.\n\npub fn load_config_file<P, T>(path: P) -> Result<T, Error>\n\nwhere\n\n T: for<'r> Deserialize<'r>,\n\n P: AsRef<Path>,\n\n{\n\n let path = path.as_ref();\n\n let res = do_load(path).with_context(|_| format!(\"loading config from {}\", path.display()))?;\n\n Ok(res)\n\n}\n\n\n", "file_path": "cli/src/io.rs", "rank": 24, "score": 266954.0516015272 }, { "content": "fn check_index_does_not_exist<S: Access>(snapshot: S, addr: IndexAddress) -> TestCaseResult {\n\n if let Some(index_type) = snapshot.index_type(addr) {\n\n prop_assert!(false, \"{:?}\", index_type);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/merkledb/tests/backup.rs", "rank": 25, "score": 263820.68980341725 }, { "content": "fn bench_binary_value<F, V>(c: &mut Criterion, name: &str, f: F)\n\nwhere\n\n F: Fn() -> V + 'static + Clone + Copy,\n\n V: BinaryValue + ObjectHash + PartialEq + Debug,\n\n{\n\n // Checks that binary value is correct.\n\n let val = f();\n\n let bytes = val.to_bytes();\n\n let val2 = V::from_bytes(bytes.into()).unwrap();\n\n assert_eq!(val, val2);\n\n // Runs benchmarks.\n\n c.bench_function(\n\n &format!(\"encoding/{}/to_bytes\", name),\n\n move |b: &mut Bencher<'_>| {\n\n b.iter_with_setup(f, |data| black_box(data.to_bytes()));\n\n },\n\n );\n\n c.bench_function(\n\n &format!(\"encoding/{}/into_bytes\", name),\n\n move |b: &mut Bencher<'_>| {\n", "file_path": "components/merkledb/benches/encoding.rs", "rank": 26, "score": 262538.5533962349 }, { "content": "#[doc(hidden)]\n\npub fn clear_consensus_messages_cache(fork: &Fork) {\n\n Schema::new(fork).consensus_messages_cache().clear();\n\n}\n\n\n", "file_path": "exonum/src/helpers/mod.rs", "rank": 27, "score": 260945.9372449725 }, { "content": "/// Generates an `IndexAddress` optionally placed in a group.\n\npub fn generate_address() -> impl Strategy<Value = IndexAddress> {\n\n let index_name = sample::select(INDEX_NAMES).prop_map(IndexAddress::from_root);\n\n prop_oneof![\n\n // Non-prefixed addresses\n\n index_name.clone(),\n\n // Prefixed addresses\n\n (index_name, 1_u8..8).prop_map(|(addr, prefix)| addr.append_key(&prefix)),\n\n ]\n\n}\n\n\n", "file_path": "components/merkledb/tests/work/mod.rs", "rank": 28, "score": 259158.32421492672 }, { "content": "fn plain_map_index_iter(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = fork.get_map(NAME);\n\n assert!(table.keys().next().is_none());\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> = snapshot.get_map(NAME);\n\n for (key, value) in &index {\n\n black_box(key);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 29, "score": 258193.19096732803 }, { "content": "fn assert_valid_name_url(name: &str) {\n\n let urlencoded: String = byte_serialize(name.as_bytes()).collect();\n\n assert_eq!(is_valid_identifier(name), name == urlencoded)\n\n}\n\n\n", "file_path": "components/merkledb/src/views/tests.rs", "rank": 30, "score": 257596.33719908877 }, { "content": "fn commit_block(blockchain: &mut BlockchainMut, fork: Fork) {\n\n // Since `BlockchainMut::create_patch` invocation in `create_block` does not use transactions,\n\n // the `after_transactions` hook does not change artifact / service statuses. Thus, we need to call\n\n // `activate_pending` manually.\n\n // FIXME: Fix this behavior [ECR-3222]\n\n blockchain.dispatcher().activate_pending(&fork);\n\n // Get state hash from the block proposal.\n\n let patch = fork.into_patch();\n\n let state_hash_in_patch = SystemSchema::new(&patch).state_hash();\n\n\n\n // Commit block to the blockchain.\n\n blockchain\n\n .commit(patch, Hash::zero(), vec![], &mut BTreeMap::new())\n\n .unwrap();\n\n\n\n // Make sure that the state hash is the same before and after the block is committed.\n\n let snapshot = blockchain.snapshot();\n\n let state_hash_in_block = SystemSchema::new(&snapshot).state_hash();\n\n assert_eq!(state_hash_in_block, state_hash_in_patch);\n\n}\n\n\n", "file_path": "exonum/src/runtime/rust/tests.rs", "rank": 31, "score": 256819.76890492486 }, { "content": "fn plain_map_index_with_family_iter(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = fork.get_map((NAME, FAMILY));\n\n assert!(table.keys().next().is_none());\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> = snapshot.get_map((NAME, FAMILY));\n\n for (key, value) in &index {\n\n black_box(key);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 32, "score": 254350.6291698228 }, { "content": "pub fn get_schema<'a>(snapshot: &'a dyn Snapshot) -> CurrencySchema<impl Access + 'a> {\n\n CurrencySchema::new(snapshot.for_service(INSTANCE_NAME).unwrap())\n\n}\n\n\n", "file_path": "examples/cryptocurrency/tests/tx_logic.rs", "rank": 33, "score": 253964.70582462155 }, { "content": "fn do_save<T: Serialize>(value: &T, path: &Path) -> Result<(), Error> {\n\n if let Some(dir) = path.parent() {\n\n fs::create_dir_all(dir)?;\n\n }\n\n let mut file = File::create(path)?;\n\n let value_toml = toml::Value::try_from(value)?;\n\n file.write_all(value_toml.to_string().as_bytes())?;\n\n Ok(())\n\n}\n", "file_path": "cli/src/io.rs", "rank": 34, "score": 250042.62827970448 }, { "content": "#[doc(hidden)]\n\npub fn user_agent() -> String {\n\n let os = os_info::get();\n\n format!(\"{}/{}\", USER_AGENT, os)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n // Checks that user agent string contains three nonempty components.\n\n #[test]\n\n fn components() {\n\n let user_agent = user_agent();\n\n let components: Vec<_> = user_agent.split('/').collect();\n\n assert_eq!(components.len(), 3);\n\n\n\n for val in components {\n\n assert!(!val.is_empty());\n\n }\n\n }\n\n}\n", "file_path": "exonum/src/helpers/user_agent.rs", "rank": 35, "score": 249672.8846254506 }, { "content": "fn check_valid_name(name: &str) -> bool {\n\n let db = TemporaryDB::new();\n\n let catch_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {\n\n let fork = db.fork();\n\n let _: ListIndex<_, u8> = fork.get_list(name.as_ref());\n\n }));\n\n catch_result.is_ok()\n\n}\n\n\n", "file_path": "components/merkledb/src/views/tests.rs", "rank": 36, "score": 249394.47604910354 }, { "content": "/// Invokes closure, capturing the cause of the unwinding panic if one occurs.\n\n///\n\n/// This function will return the result of the closure if the closure does not panic.\n\n/// If the closure panics, it returns an `Unexpected` error with the description derived\n\n/// from the panic object.\n\n///\n\n/// `merkledb`s are not caught by this method.\n\npub fn catch_panic<F, T>(maybe_panic: F) -> Result<T, ExecutionError>\n\nwhere\n\n F: FnOnce() -> Result<T, ExecutionError>,\n\n{\n\n let result = panic::catch_unwind(panic::AssertUnwindSafe(maybe_panic));\n\n match result {\n\n // ExecutionError without panic.\n\n Ok(Err(e)) => Err(e),\n\n // Panic.\n\n Err(panic) => {\n\n if panic.is::<MerkledbError>() {\n\n // Continue panic unwinding if the reason is MerkledbError.\n\n panic::resume_unwind(panic);\n\n }\n\n Err(ExecutionError::from_panic(panic))\n\n }\n\n // Normal execution.\n\n Ok(Ok(value)) => Ok(value),\n\n }\n\n}\n", "file_path": "exonum/src/runtime/error.rs", "rank": 37, "score": 249113.30338504072 }, { "content": "fn flatten_err<T>(res: Result<Result<T, api::Error>, MailboxError>) -> Result<T, api::Error> {\n\n match res {\n\n Ok(Ok(value)) => Ok(value),\n\n Ok(Err(e)) => Err(e),\n\n Err(e) => Err(api::Error::InternalError(e.into())),\n\n }\n\n}\n\n\n", "file_path": "test-suite/testkit/src/server.rs", "rank": 38, "score": 246365.5755154492 }, { "content": "fn do_save<T: Serialize>(value: &T, path: &Path) -> Result<(), Error> {\n\n if let Some(dir) = path.parent() {\n\n fs::create_dir_all(dir)?;\n\n }\n\n let mut file = File::create(path)?;\n\n let value_toml = toml::Value::try_from(value)?;\n\n file.write_all(value_toml.to_string().as_bytes())?;\n\n Ok(())\n\n}\n\n\n\n/// Structure that handles work with config file at runtime.\n\n#[derive(Debug)]\n\npub struct ConfigManager {\n\n handle: thread::JoinHandle<()>,\n\n tx: mpsc::Sender<ConfigRequest>,\n\n}\n\n\n\n/// Messages for ConfigManager.\n\n#[derive(Debug)]\n\npub enum ConfigRequest {\n", "file_path": "exonum/src/helpers/config.rs", "rank": 39, "score": 246185.57423215237 }, { "content": "fn get_object_hash<S>(snapshot: S, name: &str, index_type: IndexType) -> Hash\n\nwhere\n\n S: Access + Copy,\n\n{\n\n match index_type {\n\n IndexType::ProofEntry => snapshot.get_proof_entry::<_, ()>(name).object_hash(),\n\n IndexType::ProofList => snapshot.get_proof_list::<_, ()>(name).object_hash(),\n\n IndexType::ProofMap => snapshot.get_proof_map::<_, (), ()>(name).object_hash(),\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "components/merkledb/tests/migration.rs", "rank": 40, "score": 245810.1361668271 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n exonum::helpers::init_logger().unwrap();\n\n NodeBuilder::new()\n\n .with_service(exonum_time::TimeServiceFactory::default())\n\n .with_service(exonum_timestamping::TimestampingService)\n\n .run()\n\n}\n", "file_path": "examples/timestamping/backend/src/main.rs", "rank": 41, "score": 242010.65871453058 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n exonum::helpers::init_logger().unwrap();\n\n NodeBuilder::new()\n\n .with_service(TimeServiceFactory::default())\n\n .run()\n\n}\n", "file_path": "services/time/examples/exonum_time.rs", "rank": 42, "score": 242010.65871453058 }, { "content": "pub fn log_error<E: Display>(error: E) {\n\n error!(\"An error occurred: {}\", error)\n\n}\n\n\n", "file_path": "exonum/src/events/error.rs", "rank": 43, "score": 241825.5766979698 }, { "content": "/// Checks that a character is allowed in an index name.\n\n///\n\n/// Only these combination of symbols are allowed:\n\n/// `[0-9]`, `[a-z]`, `[A-Z]`, `_`, `-`.\n\npub fn is_allowed_index_name_char(c: u8) -> bool {\n\n match c {\n\n b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'-' | b'_' => true,\n\n _ => false,\n\n }\n\n}\n\n\n\n// Allow because it's looks more readable.\n", "file_path": "components/merkledb/src/validation.rs", "rank": 44, "score": 240913.69130146614 }, { "content": "fn create_user(name: &str) -> PublicKey {\n\n let name = name.to_string().object_hash();\n\n PublicKey::from_bytes(name.as_ref().into()).unwrap()\n\n}\n\n\n", "file_path": "components/merkledb/examples/blockchain.rs", "rank": 45, "score": 238962.93801992497 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n exonum::helpers::init_logger().unwrap();\n\n NodeBuilder::new()\n\n .with_service(cryptocurrency::CryptocurrencyService)\n\n .run()\n\n}\n", "file_path": "examples/cryptocurrency-advanced/backend/src/main.rs", "rank": 46, "score": 238705.78919329605 }, { "content": "pub fn get_state_aggregator<T: RawAccess>(\n\n access: T,\n\n namespace: &str,\n\n) -> ProofMapIndex<T, str, Hash> {\n\n let view = ViewWithMetadata::get_or_create_unchecked(\n\n access,\n\n &(STATE_AGGREGATOR, namespace).into(),\n\n IndexType::ProofMap,\n\n )\n\n .expect(\"Internal MerkleDB failure while aggregating state\");\n\n ProofMapIndex::new(view)\n\n}\n\n\n\n/// System-wide information about the database.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # use exonum_merkledb::{access::AccessExt, Database, ObjectHash, TemporaryDB, SystemSchema};\n\n/// let db = TemporaryDB::new();\n", "file_path": "components/merkledb/src/views/system_schema.rs", "rank": 47, "score": 238241.80592200096 }, { "content": "fn map_addrs() -> impl Strategy<Value = IndexAddress> {\n\n prop_oneof![\n\n strategy::Just(\"map\".into()),\n\n strategy::Just(\"other_map\".into()),\n\n strategy::Just(\"another_map\".into()),\n\n strategy::Just(\"prefixed.map\".into()),\n\n strategy::Just((\"group\", &2_u8).into()),\n\n ]\n\n}\n\n\n", "file_path": "components/merkledb/tests/state_aggregation.rs", "rank": 48, "score": 237515.95236458752 }, { "content": "fn entry_addrs() -> impl Strategy<Value = IndexAddress> {\n\n prop_oneof![\n\n strategy::Just(\"entry\".into()),\n\n strategy::Just(\"other_entry\".into()),\n\n strategy::Just((\"group\", &3_u8).into()),\n\n ]\n\n}\n\n\n", "file_path": "components/merkledb/tests/state_aggregation.rs", "rank": 49, "score": 237515.95236458752 }, { "content": "fn list_addrs() -> impl Strategy<Value = IndexAddress> {\n\n prop_oneof![\n\n strategy::Just(\"list\".into()),\n\n strategy::Just(\"other_list\".into()),\n\n strategy::Just(\"another_list\".into()),\n\n strategy::Just(\"prefixed.list\".into()),\n\n strategy::Just((\"group\", &1_u8).into()),\n\n ]\n\n}\n\n\n", "file_path": "components/merkledb/tests/state_aggregation.rs", "rank": 50, "score": 237515.95236458752 }, { "content": "/// Creates a TOML file that contains encrypted master and returns `Keys` derived from it.\n\npub fn generate_keys<P: AsRef<Path>>(path: P, passphrase: &[u8]) -> Result<Keys, failure::Error> {\n\n let tree = SecretTree::new(&mut thread_rng());\n\n save_master_key(path, passphrase, tree.seed())?;\n\n generate_keys_from_master_password(tree)\n\n .ok_or_else(|| format_err!(\"Error deriving keys from master key.\"))\n\n}\n\n\n", "file_path": "components/keys/src/lib.rs", "rank": 51, "score": 236185.90300898923 }, { "content": "/// We guarantee that the genesis block will be committed by the time\n\n/// `Runtime::after_commit()` is called. Thus, we need to perform this commitment\n\n/// manually here, emulating the relevant part of `BlockchainMut::create_genesis_block()`.\n\nfn create_genesis_block(dispatcher: &mut Dispatcher, fork: Fork) -> Patch {\n\n let is_genesis_block = CoreSchema::new(&fork).block_hashes_by_height().is_empty();\n\n assert!(is_genesis_block);\n\n dispatcher.activate_pending(&fork);\n\n\n\n let block = Block {\n\n height: Height(0),\n\n tx_count: 0,\n\n prev_hash: Hash::zero(),\n\n tx_hash: Hash::zero(),\n\n state_hash: Hash::zero(),\n\n error_hash: Hash::zero(),\n\n additional_headers: AdditionalHeaders::new(),\n\n };\n\n\n\n let block_hash = block.object_hash();\n\n let schema = CoreSchema::new(&fork);\n\n schema.block_hashes_by_height().push(block_hash);\n\n schema.blocks().put(&block_hash, block);\n\n\n", "file_path": "exonum/src/runtime/dispatcher/tests.rs", "rank": 52, "score": 234932.73006271612 }, { "content": "pub fn bench_transactions(c: &mut Criterion) {\n\n exonum_crypto::init();\n\n\n\n let mut group = c.benchmark_group(\"plain_transactions\");\n\n group\n\n .throughput(Throughput::Elements(TOTAL_TX_COUNT))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE);\n\n\n\n for &params in ITEM_COUNTS {\n\n group.bench_function(params.to_string(), |bencher| {\n\n do_bench(bencher, params, false);\n\n });\n\n }\n\n group.finish();\n\n\n\n let mut group = c.benchmark_group(\"isolated_transactions\");\n\n group\n\n .throughput(Throughput::Elements(TOTAL_TX_COUNT))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE);\n\n\n\n for &params in ITEM_COUNTS {\n\n group.bench_function(params.to_string(), |bencher| {\n\n do_bench(bencher, params, true);\n\n });\n\n }\n\n group.finish();\n\n}\n", "file_path": "components/merkledb/benches/transactions.rs", "rank": 53, "score": 234252.2645015784 }, { "content": "pub fn bench_storage(c: &mut Criterion) {\n\n exonum_crypto::init();\n\n // MapIndex\n\n bench_fn(c, \"storage/plain_map/insert\", plain_map_index_insert);\n\n bench_fn(c, \"storage/plain_map/iter\", plain_map_index_iter);\n\n bench_fn(\n\n c,\n\n \"storage/plain_map_with_family/insert\",\n\n plain_map_index_with_family_insert,\n\n );\n\n bench_fn(\n\n c,\n\n \"storage/plain_map_with_family/iter\",\n\n plain_map_index_with_family_iter,\n\n );\n\n bench_fn(c, \"storage/plain_map/read\", plain_map_index_read);\n\n bench_fn(\n\n c,\n\n \"storage/plain_map_with_family/read\",\n\n plain_map_index_with_family_read,\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 54, "score": 234252.2645015784 }, { "content": "pub fn bench_encoding(c: &mut Criterion) {\n\n exonum_crypto::init();\n\n bench_binary_value(c, \"bytes\", gen_bytes_data);\n\n bench_binary_value(c, \"simple\", gen_sample_data);\n\n bench_binary_value(c, \"cursor\", gen_cursor_data);\n\n c.bench_function(\"encoding/storage_key/concat\", bench_binary_key_concat);\n\n}\n", "file_path": "components/merkledb/benches/encoding.rs", "rank": 55, "score": 234252.2645015784 }, { "content": "pub fn bench_crypto(c: &mut Criterion) {\n\n ::exonum::crypto::init();\n\n\n\n // Testing crypto functions with different data sizes.\n\n //\n\n // 2^6 = 64 - is relatively small message, and our starting test point.\n\n // 2^16 = 65536 - is relatively big message, and our end point.\n\n\n\n c.bench(\n\n \"hash\",\n\n ParameterizedBenchmark::new(\"hash\", bench_hash, (6..16).map(|i| pow(2, i)))\n\n .throughput(|s| Throughput::Bytes((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)),\n\n );\n\n c.bench(\n\n \"sign\",\n\n ParameterizedBenchmark::new(\"sign\", bench_sign, (6..16).map(|i| pow(2, i)))\n\n .throughput(|s| Throughput::Bytes((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)),\n\n );\n\n c.bench(\n\n \"verify\",\n\n ParameterizedBenchmark::new(\"verify\", bench_verify, (6..16).map(|i| pow(2, i)))\n\n .throughput(|s| Throughput::Bytes((*s).try_into().unwrap()))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)),\n\n );\n\n}\n", "file_path": "exonum/benches/criterion/crypto.rs", "rank": 56, "score": 234252.2645015784 }, { "content": "pub fn impl_from_access(input: TokenStream) -> TokenStream {\n\n let input: DeriveInput = syn::parse(input).unwrap();\n\n let from_access = match FromAccess::from_derive_input(&input) {\n\n Ok(access) => access,\n\n Err(e) => return e.write_errors().into(),\n\n };\n\n let tokens = quote!(#from_access);\n\n tokens.into()\n\n}\n", "file_path": "components/derive/src/db_traits.rs", "rank": 57, "score": 233758.24459362405 }, { "content": "/// Formats warning string according to the following format:\n\n/// \"<warn-code> <warn-agent> \\\"<warn-text>\\\" [<warn-date>]\"\n\n/// <warn-code> in our case is 299, which means a miscellaneous persistent warning.\n\n/// <warn-agent> is optional, so we set it to \"-\".\n\n/// <warn-text> is a warning description, which is taken as an only argument.\n\n/// <warn-date> is not required.\n\n/// For details you can see RFC 7234, section 5.5: Warning.\n\nfn create_warning_header(warning_text: &str) -> String {\n\n format!(\"299 - \\\"{}\\\"\", warning_text)\n\n}\n\n\n\nimpl From<EndpointMutability> for actix_web::http::Method {\n\n fn from(mutability: EndpointMutability) -> Self {\n\n match mutability {\n\n EndpointMutability::Immutable => actix_web::http::Method::GET,\n\n EndpointMutability::Mutable => actix_web::http::Method::POST,\n\n }\n\n }\n\n}\n\n\n\nimpl<Q, I, F> From<NamedWith<Q, I, api::Result<I>, F>> for RequestHandler\n\nwhere\n\n F: Fn(Q) -> api::Result<I> + 'static + Send + Sync + Clone,\n\n Q: DeserializeOwned + 'static,\n\n I: Serialize + 'static,\n\n{\n\n fn from(f: NamedWith<Q, I, api::Result<I>, F>) -> Self {\n", "file_path": "exonum/src/api/backends/actix.rs", "rank": 58, "score": 232822.10109101993 }, { "content": "pub fn bench_verify_transactions(c: &mut Criterion) {\n\n crypto::init();\n\n\n\n let parameters = (7..12).map(|i| 1 << i).collect::<Vec<_>>();\n\n\n\n c.bench(\n\n \"transactions/simple\",\n\n ParameterizedBenchmark::new(\"size\", bench_verify_messages_simple, parameters.clone())\n\n .throughput(|_| Throughput::Elements(MESSAGES_COUNT))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n c.bench(\n\n \"transactions/event_loop\",\n\n ParameterizedBenchmark::new(\"size\", bench_verify_messages_event_loop, parameters.clone())\n\n .throughput(|_| Throughput::Elements(MESSAGES_COUNT))\n\n .plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n}\n", "file_path": "exonum/benches/criterion/transactions.rs", "rank": 59, "score": 230949.20790347218 }, { "content": "pub fn bench_block(criterion: &mut Criterion) {\n\n use log::LevelFilter;\n\n use std::panic;\n\n\n\n log::set_max_level(LevelFilter::Off);\n\n\n\n execute_block_rocksdb(\n\n criterion,\n\n \"block/timestamping\",\n\n timestamping::Timestamping,\n\n timestamping::transactions(SeedableRng::from_seed([2; 32])),\n\n );\n\n\n\n // We expect lots of panics here, so we switch their reporting off.\n\n let panic_hook = panic::take_hook();\n\n panic::set_hook(Box::new(|_| ()));\n\n execute_block_rocksdb(\n\n criterion,\n\n \"block/timestamping_panic\",\n\n timestamping::Timestamping,\n", "file_path": "exonum/benches/criterion/block.rs", "rank": 60, "score": 230949.20790347218 }, { "content": "pub fn into_failure<E: StdError + Sync + Send + 'static>(error: E) -> Error {\n\n Error::from_boxed_compat(Box::new(error))\n\n}\n\n\n\nimpl<T, E> LogError for Result<T, E>\n\nwhere\n\n E: Display,\n\n{\n\n fn log_error(self) {\n\n if let Err(error) = self {\n\n error!(\"An error occurred: {}\", error);\n\n }\n\n }\n\n}\n", "file_path": "exonum/src/events/error.rs", "rank": 61, "score": 229968.2346920114 }, { "content": "#[test]\n\nfn iter() {\n\n let db = TemporaryDB::new();\n\n let fork = db.fork();\n\n let mut list_index = fork.get_proof_list(IDX_NAME);\n\n\n\n list_index.extend(vec![1_u8, 2, 3]);\n\n\n\n assert_eq!(list_index.iter().collect::<Vec<u8>>(), vec![1, 2, 3]);\n\n assert_eq!(list_index.iter_from(0).collect::<Vec<u8>>(), vec![1, 2, 3]);\n\n assert_eq!(list_index.iter_from(1).collect::<Vec<u8>>(), vec![2, 3]);\n\n assert_eq!(\n\n list_index.iter_from(3).collect::<Vec<u8>>(),\n\n Vec::<u8>::new()\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/src/indexes/proof_list/tests.rs", "rank": 62, "score": 229483.28755254883 }, { "content": "/// Creates block with the specified transaction and returns its execution result.\n\nfn execute_transaction(testkit: &mut TestKit, tx: Verified<AnyTx>) -> Result<(), ExecutionError> {\n\n testkit.create_block_with_transaction(tx).transactions[0]\n\n .status()\n\n .map_err(Clone::clone)\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/service_lifecycle.rs", "rank": 63, "score": 228994.7360809748 }, { "content": "fn execute_transaction(testkit: &mut TestKit, tx: Verified<AnyTx>) -> Result<(), ExecutionError> {\n\n testkit.create_block_with_transaction(tx).transactions[0]\n\n .status()\n\n .map_err(Clone::clone)\n\n}\n\n\n", "file_path": "test-suite/testkit/tests/interfaces/main.rs", "rank": 64, "score": 228982.7418113585 }, { "content": "#[cfg(unix)]\n\n#[cfg_attr(feature = \"cargo-clippy\", allow(clippy::verbose_bit_mask))]\n\nfn validate_file_mode(mode: u32) -> Result<(), Error> {\n\n // Check that group and other bits are not set.\n\n if (mode & 0o_077) == 0 {\n\n Ok(())\n\n } else {\n\n Err(Error::new(ErrorKind::Other, \"Wrong file's mode\"))\n\n }\n\n}\n\n\n\n/// Struct containing all validator key pairs.\n\n#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize)]\n\npub struct Keys {\n\n /// Consensus keypair.\n\n pub consensus: KeyPair,\n\n /// Service keypair.\n\n pub service: KeyPair,\n\n}\n\n\n\nimpl Keys {\n\n /// Create validator keys from provided keypairs.\n", "file_path": "components/keys/src/lib.rs", "rank": 65, "score": 228517.01608782596 }, { "content": "pub fn bench_schema_patterns(c: &mut Criterion) {\n\n exonum_crypto::init();\n\n\n\n c.bench(\n\n \"schema_patterns\",\n\n Benchmark::new(\"eager\", |b| bench::<EagerStyle>(b, false))\n\n .with_function(\"lazy\", |b| bench::<LazyStyle>(b, false))\n\n .with_function(\"wrapper\", |b| bench::<WrapperStyle>(b, false))\n\n .throughput(Throughput::Elements(TX_COUNT as u64))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n\n\n c.bench(\n\n \"schema_patterns/prefixed\",\n\n Benchmark::new(\"eager\", |b| bench::<EagerStyle>(b, true))\n\n .with_function(\"lazy\", |b| bench::<LazyStyle>(b, true))\n\n .with_function(\"wrapper\", |b| bench::<WrapperStyle>(b, true))\n\n .throughput(Throughput::Elements(TX_COUNT as u64))\n\n .sample_size(SAMPLE_SIZE),\n\n );\n\n}\n", "file_path": "components/merkledb/benches/schema_patterns.rs", "rank": 66, "score": 227795.58392263926 }, { "content": "pub fn wire(builder: &mut ServiceApiBuilder) {\n\n builder\n\n .private_scope()\n\n .endpoint_mut(\"deploy-artifact\", |state, query| {\n\n ApiImpl(state).deploy_artifact(query)\n\n })\n\n .endpoint_mut(\"propose-config\", |state, query| {\n\n ApiImpl(state).propose_config(query)\n\n })\n\n .endpoint_mut(\"confirm-config\", |state, query| {\n\n ApiImpl(state).confirm_config(query)\n\n })\n\n .endpoint(\"configuration-number\", |state, _query: ()| {\n\n ApiImpl(state).configuration_number()\n\n })\n\n .endpoint(\"supervisor-config\", |state, _query: ()| {\n\n ApiImpl(state).supervisor_config()\n\n });\n\n builder\n\n .public_scope()\n\n .endpoint(\"consensus-config\", |state, _query: ()| {\n\n ApiImpl(state).consensus_config()\n\n })\n\n .endpoint(\"config-proposal\", |state, _query: ()| {\n\n ApiImpl(state).config_proposal()\n\n });\n\n}\n", "file_path": "services/supervisor/src/api.rs", "rank": 67, "score": 227795.58392263926 }, { "content": "/// Extension trait allowing for easy access to indexes from any type implementing\n\n/// `Access`.\n\n///\n\n/// # Implementation details\n\n///\n\n/// This trait is essentially a thin wrapper around [`FromAccess`]. Where `FromAccess` returns\n\n/// an access error, the methods of this trait will `unwrap()` the error and panic.\n\n///\n\n/// [`FromAccess`]: trait.FromAccess.html\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use exonum_merkledb::{access::AccessExt, Database, ListIndex, TemporaryDB};\n\n///\n\n/// let db = TemporaryDB::new();\n\n/// let fork = db.fork();\n\n/// // Extension methods can be used on `Fork`s:\n\n/// {\n\n/// let mut list: ListIndex<_, String> = fork.get_list(\"list\");\n\n/// list.push(\"foo\".to_owned());\n\n/// }\n\n///\n\n/// // ...and on `Snapshot`s:\n\n/// let snapshot = db.snapshot();\n\n/// assert!(snapshot\n\n/// .get_map::<_, u64, String>(\"map\")\n\n/// .get(&0)\n\n/// .is_none());\n\n///\n\n/// // ...and on `ReadonlyFork`s:\n\n/// {\n\n/// let list = fork.readonly().get_list::<_, String>(\"list\");\n\n/// assert_eq!(list.len(), 1);\n\n/// }\n\n///\n\n/// // ...and on `Patch`es:\n\n/// let patch = fork.into_patch();\n\n/// let list = patch.get_list::<_, String>(\"list\");\n\n/// assert_eq!(list.len(), 1);\n\n/// ```\n\npub trait AccessExt: Access {\n\n /// Returns a group of indexes. All indexes in the group have the same type.\n\n /// Indexes are initialized lazily; i.e., no initialization is performed when the group\n\n /// is created.\n\n ///\n\n /// Note that unlike other methods, this one requires address to be a string.\n\n /// This is to prevent collisions among groups.\n\n fn get_group<K, I>(self, name: impl Into<String>) -> Group<Self, K, I>\n\n where\n\n K: BinaryKey + ?Sized,\n\n I: FromAccess<Self>,\n\n {\n\n Group::from_access(self, IndexAddress::from_root(name))\n\n .unwrap_or_else(|e| panic!(\"MerkleDB error: {}\", e))\n\n }\n\n\n\n /// Gets an entry index with the specified address.\n\n ///\n\n /// # Panics\n\n ///\n", "file_path": "components/merkledb/src/access/extensions.rs", "rank": 68, "score": 227370.64636860281 }, { "content": "pub fn latest_assigned_instance_id(testkit: &TestKit) -> Option<InstanceId> {\n\n let snapshot = testkit.snapshot();\n\n let schema = Schema::new(snapshot.for_service(Supervisor::NAME).unwrap());\n\n schema.vacant_instance_id.get().map(|x| x - 1)\n\n}\n", "file_path": "services/supervisor/tests/supervisor/utils.rs", "rank": 69, "score": 222322.7926849185 }, { "content": "fn write_short_hex(f: &mut fmt::Formatter<'_>, slice: &[u8]) -> fmt::Result {\n\n for byte in slice.iter().take(BYTES_IN_DEBUG) {\n\n write!(f, \"{:02x}\", byte)?;\n\n }\n\n if slice.len() > BYTES_IN_DEBUG {\n\n write!(f, \"...\")?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/crypto/src/lib.rs", "rank": 70, "score": 219478.11339509484 }, { "content": "fn invalid_method(span: &impl Spanned) -> darling::Error {\n\n darling::Error::custom(INVALID_METHOD_MSG).with_span(span)\n\n}\n\n\n\nimpl ServiceMethodDescriptor {\n\n /// Tries to parse a method definition from its declaration in the trait. The method needs\n\n /// to correspond to the following form:\n\n ///\n\n /// ```text\n\n /// fn foo(&self, ctx: Ctx, arg: Bar) -> Self::Output;\n\n /// ```\n\n ///\n\n /// where `Ctx` is the context type param defined in the trait.\n\n fn try_from(\n\n method_id: u32,\n\n ctx: &Ident,\n\n method: &TraitItemMethod,\n\n ) -> Result<Self, darling::Error> {\n\n use syn::{PatType, TypePath};\n\n\n", "file_path": "components/derive/src/exonum_interface.rs", "rank": 71, "score": 219425.81164260174 }, { "content": "/// Starts service instance and gets its ID\n\nfn start_inc_service(testkit: &mut TestKit) -> InstanceId {\n\n let keypair = testkit.us().service_keypair();\n\n // Start `inc` service instance\n\n execute_transaction(\n\n testkit,\n\n ConfigPropose::immediate(0)\n\n .start_service(\n\n IncService.artifact_id(),\n\n IncService::INSTANCE_NAME,\n\n Vec::default(),\n\n )\n\n .sign_for_supervisor(keypair.0, &keypair.1),\n\n )\n\n .expect(\"Start service transaction should be processed\");\n\n // Get started service instance ID.\n\n latest_assigned_instance_id(&testkit).unwrap()\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/service_lifecycle.rs", "rank": 72, "score": 217264.70892022498 }, { "content": "/// Creates a sample blockchain for the example.\n\n///\n\n/// The blockchain has a single non-genesis block with 3 transactions:\n\n///\n\n/// - A successfully executed transaction\n\n/// - An erroneous transaction\n\n/// - A panicking transaction\n\n///\n\n/// Additionally, a single transaction is placed into the pool.\n\npub fn sample_blockchain() -> BlockchainMut {\n\n let mut blockchain = create_blockchain();\n\n let alice = gen_keypair();\n\n let bob = gen_keypair();\n\n\n\n let tx_alice = alice.create_wallet(SERVICE_ID, CreateWallet::new(\"Alice\"));\n\n let tx_bob = bob.create_wallet(SERVICE_ID, CreateWallet::new(\"Bob\"));\n\n let tx_transfer = alice.transfer(SERVICE_ID, Transfer::new(&bob.0, 100));\n\n create_block(&mut blockchain, vec![tx_alice, tx_bob, tx_transfer]);\n\n\n\n blockchain.add_transactions_into_pool(iter::once(mempool_transaction()));\n\n blockchain\n\n}\n\n\n", "file_path": "exonum/examples/explorer.rs", "rank": 73, "score": 215488.27388656535 }, { "content": "fn compare_key_set(set: &KeySetIndex<Rc<Fork>, u8>, ref_set: &HashSet<u8>) -> TestCaseResult {\n\n for k in ref_set {\n\n prop_assert!(set.contains(k));\n\n }\n\n for k in set.iter() {\n\n prop_assert!(ref_set.contains(&k));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/merkledb/tests/set.rs", "rank": 74, "score": 213564.77068503617 }, { "content": "fn plain_map_index_read(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = fork.get_map(NAME);\n\n assert!(table.keys().next().is_none());\n\n for item in data.clone() {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> = snapshot.get_map(NAME);\n\n for item in &data {\n\n let value = index.get(&item.0);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 75, "score": 213300.8960619102 }, { "content": "fn plain_map_index_insert(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || (TemporaryDB::default(), data.clone()),\n\n |(db, data)| {\n\n let fork = db.fork();\n\n {\n\n let mut table = fork.get_map(NAME);\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 76, "score": 213300.8960619102 }, { "content": "/// Converts an arbitrary array of data to the Curve25519-compatible private key.\n\npub fn convert_to_private_key(key: &mut [u8; 32]) {\n\n let converted = convert_ed_sk_to_curve25519(key);\n\n\n\n key.copy_from_slice(&converted);\n\n}\n\n\n", "file_path": "components/crypto/src/crypto_lib/sodiumoxide/x25519.rs", "rank": 77, "score": 213076.9377422953 }, { "content": "pub fn work_on_index<T>(\n\n fork: T,\n\n addr: IndexAddress,\n\n mut index_type: IndexType,\n\n value: Option<Vec<u8>>,\n\n) -> IndexType\n\nwhere\n\n T: Access + Copy,\n\n T::Base: RawAccessMut,\n\n{\n\n if let Some(real_type) = fork.index_type(addr.clone()) {\n\n index_type = real_type;\n\n }\n\n\n\n match index_type {\n\n IndexType::Entry => {\n\n let mut entry = fork.get_entry(addr);\n\n if let Some(val) = value {\n\n entry.set(val);\n\n } else {\n", "file_path": "components/merkledb/tests/work/mod.rs", "rank": 78, "score": 211258.9382093827 }, { "content": "fn proof_map_index_build_proofs(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n let mut table = fork.get_proof_map(NAME);\n\n\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n let table_hash = table.object_hash();\n\n let mut proofs = Vec::with_capacity(data.len());\n\n\n\n b.iter(|| {\n\n proofs.clear();\n\n proofs.extend(data.iter().map(|item| table.get_proof(item.0)));\n\n });\n\n\n\n for (i, proof) in proofs.into_iter().enumerate() {\n\n let checked_proof = proof.check_against_hash(table_hash).unwrap();\n\n assert_eq!(*checked_proof.entries().next().unwrap().1, data[i].1);\n\n }\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 79, "score": 210429.86128514708 }, { "content": "fn proof_list_index_verify_proofs(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_values(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n let mut table = fork.get_proof_list(NAME);\n\n\n\n for item in &data {\n\n table.push(item.clone());\n\n }\n\n let table_root_hash = table.object_hash();\n\n let proofs: Vec<_> = (0..len).map(|i| table.get_proof(i as u64)).collect();\n\n\n\n b.iter(|| {\n\n for proof in &proofs {\n\n let items = proof.check_against_hash(table_root_hash).unwrap();\n\n assert_eq!(items.entries().len(), 1);\n\n }\n\n });\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 80, "score": 210429.86128514708 }, { "content": "fn proof_list_index_build_proofs(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_values(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n let mut table = fork.get_proof_list(NAME);\n\n\n\n for item in &data {\n\n table.push(item.clone());\n\n }\n\n let mut proofs = Vec::with_capacity(data.len());\n\n\n\n b.iter(|| {\n\n proofs.clear();\n\n proofs.extend((0..len).map(|i| table.get_proof(i as u64)));\n\n });\n\n\n\n let table_hash = table.object_hash();\n\n for proof in proofs {\n\n let checked_proof = proof.check().unwrap();\n\n assert_eq!(checked_proof.index_hash(), table_hash);\n\n assert_eq!(checked_proof.entries().len(), 1);\n\n }\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 81, "score": 210429.86128514708 }, { "content": "fn plain_map_index_with_family_read(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n\n\n {\n\n let mut table = fork.get_map((NAME, FAMILY));\n\n assert!(table.keys().next().is_none());\n\n for item in data.clone() {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n\n\n b.iter_with_setup(\n\n || db.snapshot(),\n\n |snapshot| {\n\n let index: MapIndex<_, Hash, Vec<u8>> = snapshot.get_map((NAME, FAMILY));\n\n for item in &data {\n\n let value = index.get(&item.0);\n\n black_box(value);\n\n }\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 82, "score": 210429.86128514708 }, { "content": "fn plain_map_index_with_family_insert(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n b.iter_with_setup(\n\n || (TemporaryDB::default(), data.clone()),\n\n |(db, data)| {\n\n let fork = db.fork();\n\n {\n\n let mut table = fork.get_map((NAME, FAMILY));\n\n for item in data {\n\n table.put(&item.0, item.1);\n\n }\n\n }\n\n db.merge_sync(fork.into_patch()).unwrap();\n\n },\n\n );\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 83, "score": 210429.86128514708 }, { "content": "fn proof_map_index_verify_proofs(b: &mut Bencher<'_>, len: usize) {\n\n let data = generate_random_kv(len);\n\n let db = TemporaryDB::default();\n\n let fork = db.fork();\n\n let mut table = fork.get_proof_map(NAME);\n\n\n\n for item in &data {\n\n table.put(&item.0, item.1.clone());\n\n }\n\n let table_hash = table.object_hash();\n\n let proofs: Vec<_> = data.iter().map(|item| table.get_proof(item.0)).collect();\n\n\n\n b.iter(|| {\n\n for (i, proof) in proofs.iter().enumerate() {\n\n let checked_proof = proof.check_against_hash(table_hash).unwrap();\n\n assert_eq!(*checked_proof.entries().next().unwrap().1, data[i].1);\n\n }\n\n });\n\n}\n\n\n", "file_path": "components/merkledb/benches/storage.rs", "rank": 84, "score": 210429.86128514708 }, { "content": "fn do_load<T: DeserializeOwned>(path: &Path) -> Result<T, Error> {\n\n let mut file = File::open(path)?;\n\n let mut toml = String::new();\n\n file.read_to_string(&mut toml)?;\n\n Ok(toml::de::from_str(&toml)?)\n\n}\n\n\n", "file_path": "cli/src/io.rs", "rank": 85, "score": 209334.97784095778 }, { "content": "/// Creates a blockchain with no blocks.\n\npub fn create_blockchain() -> BlockchainMut {\n\n let config = generate_testnet_config(1, 0)[0].clone();\n\n let blockchain = Blockchain::new(\n\n TemporaryDB::new(),\n\n config.service_keypair(),\n\n ApiSender::closed(),\n\n );\n\n\n\n let my_service = MyService;\n\n let my_service_artifact = my_service.artifact_id();\n\n let genesis_config = GenesisConfigBuilder::with_consensus_config(config.consensus)\n\n .with_artifact(my_service_artifact.clone())\n\n .with_instance(my_service_artifact.into_default_instance(SERVICE_ID, \"my-service\"))\n\n .build();\n\n let rust_runtime = RustRuntime::new(mpsc::channel(1).0).with_factory(my_service);\n\n BlockchainBuilder::new(blockchain, genesis_config)\n\n .with_runtime(rust_runtime)\n\n .build()\n\n .unwrap()\n\n}\n\n\n", "file_path": "exonum/tests/explorer/blockchain/mod.rs", "rank": 86, "score": 208721.8491626918 }, { "content": "fn recv_text_msg(client: &mut Client<TcpStream>) -> Option<String> {\n\n if let Ok(response) = client.recv_message() {\n\n match response {\n\n OwnedMessage::Text(text) => return Some(text),\n\n other => panic!(\"Incorrect response: {:?}\", other),\n\n }\n\n }\n\n None\n\n}\n\n\n\n/// Checks that ws client accepts valid transactions and discards transactions with incorrect instance ID.\n", "file_path": "exonum/tests/websocket/main.rs", "rank": 87, "score": 208476.39920870995 }, { "content": "/// Simplified compared to real life / testkit, but we don't need to test *everything*\n\n/// here.\n\npub fn create_block(blockchain: &mut BlockchainMut, transactions: Vec<Verified<AnyTx>>) {\n\n use exonum::helpers::{Round, ValidatorId};\n\n use exonum::messages::{Precommit, Propose};\n\n use std::time::SystemTime;\n\n\n\n let tx_hashes: Vec<_> = transactions.iter().map(ObjectHash::object_hash).collect();\n\n let height = blockchain.as_ref().last_block().height.next();\n\n blockchain.add_transactions_into_pool(transactions);\n\n\n\n let mut tx_cache = BTreeMap::new();\n\n let (block_hash, patch) =\n\n blockchain.create_patch(ValidatorId(0).into(), height, &tx_hashes, &mut tx_cache);\n\n let (consensus_public_key, consensus_secret_key) = consensus_keys();\n\n\n\n let propose = Verified::from_value(\n\n Propose::new(\n\n ValidatorId(0),\n\n height,\n\n Round::first(),\n\n blockchain.as_ref().last_hash(),\n", "file_path": "exonum/tests/explorer/blockchain/mod.rs", "rank": 88, "score": 207903.89992404316 }, { "content": "fn compare_map(map: &MapIndex<Rc<Fork>, u8, i32>, ref_map: &HashMap<u8, i32>) -> TestCaseResult {\n\n for k in ref_map.keys() {\n\n prop_assert!(map.contains(k));\n\n }\n\n for (k, v) in map.iter() {\n\n prop_assert_eq!(Some(&v), ref_map.get(&k));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "components/merkledb/tests/map.rs", "rank": 89, "score": 207106.3374475069 }, { "content": "fn test_failed_deployment(db: Arc<TemporaryDB>, runtime: DeploymentRuntime, artifact_name: &str) {\n\n let blockchain = Blockchain::new(\n\n Arc::clone(&db) as Arc<dyn Database>,\n\n gen_keypair(),\n\n ApiSender(mpsc::channel(1).0),\n\n );\n\n let mut dispatcher = DispatcherBuilder::new()\n\n .with_runtime(2, runtime.clone())\n\n .finalize(&blockchain);\n\n\n\n let patch = create_genesis_block(&mut dispatcher, db.fork());\n\n db.merge_sync(patch).unwrap();\n\n\n\n // Queue an artifact for deployment.\n\n let (artifact, spec) = runtime.deploy_test_artifact(artifact_name, &mut dispatcher, &db);\n\n // We should not panic during async deployment.\n\n assert!(!dispatcher.is_artifact_deployed(&artifact));\n\n assert_eq!(runtime.deploy_attempts(&artifact), 1);\n\n\n\n let fork = db.fork();\n\n Dispatcher::commit_artifact(&fork, artifact, spec).unwrap();\n\n dispatcher.commit_block_and_notify_runtimes(fork); // << should panic\n\n}\n\n\n", "file_path": "exonum/src/runtime/dispatcher/tests.rs", "rank": 90, "score": 206976.69900317315 }, { "content": "fn do_load<T: DeserializeOwned>(path: &Path) -> Result<T, Error> {\n\n let mut file = File::open(path)?;\n\n let mut toml = String::new();\n\n file.read_to_string(&mut toml)?;\n\n Ok(toml::de::from_str(&toml)?)\n\n}\n\n\n", "file_path": "exonum/src/helpers/config.rs", "rank": 91, "score": 206449.74574390642 }, { "content": "fn is_supervisor(instance_id: InstanceId) -> bool {\n\n instance_id == crate::runtime::SUPERVISOR_INSTANCE_ID\n\n}\n", "file_path": "exonum/src/runtime/rust/service.rs", "rank": 92, "score": 203592.7435937915 }, { "content": "#[doc(hidden)]\n\npub fn get_transaction<T: RawAccess>(\n\n hash: &Hash,\n\n txs: &MapIndex<T, Hash, Verified<AnyTx>>,\n\n tx_cache: &BTreeMap<Hash, Verified<AnyTx>>,\n\n) -> Option<Verified<AnyTx>> {\n\n txs.get(&hash).or_else(|| tx_cache.get(&hash).cloned())\n\n}\n\n\n\n/// Check that transaction exists in the persistent pool or in the transaction cache.\n", "file_path": "exonum/src/blockchain/mod.rs", "rank": 93, "score": 203454.07097622368 }, { "content": "#[doc(hidden)]\n\npub fn contains_transaction<T: RawAccess>(\n\n hash: &Hash,\n\n txs: &MapIndex<T, Hash, Verified<AnyTx>>,\n\n tx_cache: &BTreeMap<Hash, Verified<AnyTx>>,\n\n) -> bool {\n\n txs.contains(&hash) || tx_cache.contains_key(&hash)\n\n}\n", "file_path": "exonum/src/blockchain/mod.rs", "rank": 94, "score": 203454.07097622368 }, { "content": "/// Generates a value to place in the index. if `None` is generated, the index will be cleared\n\n/// instead.\n\npub fn generate_value() -> impl Strategy<Value = Option<Vec<u8>>> {\n\n option::weighted(0.8, vec(0_u8..4, 1..=1))\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct IndexData {\n\n pub ty: IndexType,\n\n pub values: Vec<Vec<u8>>,\n\n}\n\n\n\nimpl IndexData {\n\n pub fn check<S>(&self, snapshot: S, addr: IndexAddress) -> TestCaseResult\n\n where\n\n S: Access,\n\n {\n\n match self.ty {\n\n IndexType::Entry => {\n\n let val = snapshot.get_entry::<_, Vec<u8>>(addr).get();\n\n prop_assert_eq!(val.as_ref(), self.values.last());\n\n }\n", "file_path": "components/merkledb/tests/work/mod.rs", "rank": 95, "score": 203239.99730748514 }, { "content": "pub fn check_service_actual_param(testkit: &TestKit, param: Option<String>) {\n\n let snapshot = testkit.snapshot();\n\n let actual_params = snapshot\n\n .for_service(CONFIG_SERVICE_NAME)\n\n .unwrap()\n\n .get_entry::<_, String>(\"params\");\n\n match param {\n\n Some(param) => assert_eq!(actual_params.get().unwrap(), param),\n\n None => assert!(!actual_params.exists()),\n\n }\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/utils.rs", "rank": 96, "score": 202816.3449947521 }, { "content": "fn create_block(blockchain: &BlockchainMut) -> Fork {\n\n let height = CoreSchema::new(&blockchain.snapshot()).height();\n\n let (_, patch) = blockchain.create_patch(\n\n ValidatorId(0).into(),\n\n height.next(),\n\n &[],\n\n &mut BTreeMap::new(),\n\n );\n\n Fork::from(patch)\n\n}\n\n\n", "file_path": "exonum/src/runtime/rust/tests.rs", "rank": 97, "score": 201088.9363837269 }, { "content": "fn get_master_key_path(path: Option<PathBuf>) -> Result<PathBuf, Error> {\n\n let path = path.map_or_else(|| Ok(PathBuf::new()), |path| path.canonicalize())?;\n\n Ok(path.join(MASTER_KEY_FILE_NAME))\n\n}\n\n\n", "file_path": "cli/src/command/generate_config.rs", "rank": 98, "score": 200777.72998010932 }, { "content": "pub fn check_second_service_actual_param(testkit: &TestKit, param: Option<String>) {\n\n let snapshot = testkit.snapshot();\n\n let actual_params = snapshot\n\n .for_service(SECOND_SERVICE_NAME)\n\n .unwrap()\n\n .get_entry::<_, String>(\"params\");\n\n match param {\n\n Some(param) => assert_eq!(actual_params.get().unwrap(), param),\n\n None => assert!(!actual_params.exists()),\n\n }\n\n}\n\n\n", "file_path": "services/supervisor/tests/supervisor/utils.rs", "rank": 99, "score": 200376.84987841846 } ]
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#[should_panic]\n\n#[case::panic(42, \"Foo\")]\n\n#[case::foo(3, \"Foo\")]\n\nfn all(#[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": 1, "score": 290186.5000610549 }, { "content": "#[rstest]\n\n#[case(0, \"ciao\")]\n\n#[case(0, \"Foo\")]\n\n#[should_panic]\n\nfn all_panic(#[case] expected: usize, #[case] input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n", "file_path": "tests/resources/rstest/cases/use_attr.rs", "rank": 2, "score": 285222.2387449855 }, { "content": "#[rstest]\n\n#[case(\"impl\", \"nothing\")]\n\nfn not_convert_impl(#[case] that_impl: impl MyTrait, #[case] s: &str) {\n\n assert_eq!(42, that_impl.my_trait());\n\n assert_eq!(42, s.my_trait());\n\n}\n\n\n", "file_path": "tests/resources/rstest/convert_string_literal.rs", "rank": 3, "score": 283443.7954577248 }, { "content": "#[rstest]\n\nfn simple(fixture: impl AsRef<str>) {\n\n assert_eq!(3, fixture.as_ref().len());\n\n}\n\n\n\n#[rstest(\n\n expected, input,\n\n case(4, String::from(\"ciao\")),\n\n case(3, \"Foo\")\n\n)]\n", "file_path": "tests/resources/rstest/impl_param.rs", "rank": 4, "score": 257775.87098417297 }, { "content": "#[rstest(expected, input)]\n\n#[case::ciao(4, \"ciao\")]\n\n#[case::foo(3, \"Foo\")]\n\n#[should_panic]\n\n#[case::panic(42, \"Foo\")]\n\nfn just_cases(expected: usize, input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n\n\n\n#[rstest(\n\n case::ciao(4, \"ciao\"),\n\n case::foo(3, \"Foo\"),\n\n #[should_panic]\n\n case::panic(42, \"Foo\"),\n\n)]\n", "file_path": "tests/resources/rstest/cases/use_attr.rs", "rank": 5, "score": 252309.72953179324 }, { "content": "#[rstest(expected, case(0), case(1000))]\n\nfn default(fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 6, "score": 250332.55926142127 }, { "content": "#[rstest]\n\n#[case(\"hello\", \"hello\")]\n\n#[case(\"doesn't mater\", \"error\")]\n\nfn convert_without_debug(#[case] expected: &str, #[case] converted: MyType) {\n\n assert_eq!(expected, converted.0);\n\n}\n", "file_path": "tests/resources/rstest/convert_string_literal.rs", "rank": 7, "score": 239755.4798091057 }, { "content": "#[rstest]\n\n#[case(42, \"str\", (\"ss\", -12))]\n\n#[case(24, \"trs\", (\"tt\", -24))]\n\n#[trace]\n\nfn cases_fail(#[case] u: u32, #[case] s: &str, #[case] t: (&str, i32)) {\n\n assert!(false);\n\n}\n\n\n", "file_path": "tests/resources/rstest/dump_debug.rs", "rank": 8, "score": 238077.91150107372 }, { "content": "fn strlen_test(expected: usize, input: impl AsRef<str>) {\n\n assert_eq!(expected, input.as_ref().len());\n\n}\n", "file_path": "tests/resources/rstest/impl_param.rs", "rank": 9, "score": 237337.9824126453 }, { "content": "#[rstest]\n\n#[case::first_no_dump(\"Please don't trace me\")]\n\n#[trace]\n\n#[case::dump_me(\"Trace it!\")]\n\n#[case::last_no_dump(\"Please don't trace me\")]\n\nfn cases(#[case] s: &str) {\n\n assert!(false);\n\n}\n", "file_path": "tests/resources/rstest/cases/dump_just_one_case.rs", "rank": 10, "score": 235739.14543109303 }, { "content": "#[fixture]\n\nfn fixture() -> String { \"str\".to_owned() }\n\n\n", "file_path": "tests/resources/rstest/impl_param.rs", "rank": 11, "score": 224390.1033492728 }, { "content": "fn default_fixture_resolve(ident: &Ident) -> Cow<Expr> {\n\n Cow::Owned(parse_quote! { #ident::default() })\n\n}\n\n\n", "file_path": "src/render/inject.rs", "rank": 12, "score": 219468.45176718233 }, { "content": "fn strlen_test(expected: usize, input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n", "file_path": "tests/resources/rstest/cases/simple.rs", "rank": 13, "score": 212705.74404442243 }, { "content": "#[test]\n\nfn use_mutable_fixture_in_parametric_argumnts() {\n\n let (output, _) = run_test(\"use_mutable_fixture_in_parametric_argumnts.rs\");\n\n\n\n TestResults::new()\n\n .ok(\"use_mutate_fixture::case_1::b_1\")\n\n .assert(output);\n\n}\n\n\n", "file_path": "tests/rstest/mod.rs", "rank": 14, "score": 202720.96859817588 }, { "content": "fn prj(res: &str) -> Project {\n\n let path = Path::new(\"fixture\").join(res);\n\n crate::prj().set_code_file(resources(path))\n\n}\n\n\n", "file_path": "tests/fixture/mod.rs", "rank": 15, "score": 200371.70384800454 }, { "content": "#[fixture]\n\nfn s() -> &'static str {\n\n \"42\"\n\n}\n\n\n", "file_path": "tests/resources/fixture/clean_up_default_generics.rs", "rank": 16, "score": 200092.07574017448 }, { "content": "fn append(s: &mut String, a: &str) -> String {\n\n s.push_str(\"-\");\n\n s.push_str(a);\n\n s.clone()\n\n}\n\n\n", "file_path": "tests/resources/rstest/use_mutable_fixture_in_parametric_argumnts.rs", "rank": 17, "score": 197216.49188143126 }, { "content": "#[rstest]\n\nfn default(fixture: u32) {\n\n assert_eq!(fixture, 0);\n\n}\n\n\n", "file_path": "tests/resources/rstest/single/partial.rs", "rank": 18, "score": 197182.43459239963 }, { "content": "fn first(#[values(4, 2*3-2)] expected: usize, input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n\n\n\n#[rstest(\n\n expected => [4, 2*3-2]\n\n)]\n", "file_path": "tests/resources/rstest/matrix/use_attr.rs", "rank": 19, "score": 196595.97352203075 }, { "content": "#[rstest(f, case(42))]\n\nfn error_case_wrong_type(f: &str) {}\n\n\n\n#[rstest(condition,\n\n case(vec![1,2,3].contains(2)))\n\n]\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 20, "score": 194195.51855402146 }, { "content": "#[fixture]\n\nfn fixture() -> String { \"str\".to_owned() }\n\n\n", "file_path": "tests/resources/rstest/generic.rs", "rank": 21, "score": 193249.7874630558 }, { "content": "#[rstest]\n\n#[case(true, \"1.2.3.4:42\")]\n\n#[case(true, r#\"4.3.2.1:24\"#)]\n\n#[case(false, \"[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443\")]\n\n#[case(false, r#\"[2aa1:db8:85a3:8af:1319:8a2e:375:4873]:344\"#)]\n\n#[case(false, \"this.is.not.a.socket.address\")]\n\n#[case(false, r#\"this.is.not.a.socket.address\"#)]\n\nfn cases(#[case] expected: bool, #[case] addr: SocketAddr) {\n\n assert_eq!(expected, addr.is_ipv4());\n\n}\n\n\n", "file_path": "tests/resources/rstest/convert_string_literal.rs", "rank": 22, "score": 192342.47942481528 }, { "content": "fn second(expected: usize, #[values(\"ciao\", \"buzz\")] input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n", "file_path": "tests/resources/rstest/matrix/use_attr.rs", "rank": 23, "score": 192341.37748697246 }, { "content": "#[rstest]\n\n#[case(\"1.2.3.4\", \"1.2.3.4:42\")]\n\n#[case(\"1.2.3.4\".to_owned(), \"1.2.3.4:42\")]\n\nfn not_convert_generics<S: AsRef<str>>(#[case] ip: S, #[case] addr: SocketAddr) {\n\n assert_eq!(addr.ip().to_string(), ip.as_ref());\n\n}\n\n\n", "file_path": "tests/resources/rstest/convert_string_literal.rs", "rank": 24, "score": 191480.16727471753 }, { "content": "fn cases_fail(u: u32, s: &str, t: (&str, i32)) {\n\n assert!(false);\n\n}\n\n\n\n#[rstest(\n\n u => [1, 2],\n\n s => [\"rst\", \"srt\"],\n\n t => [(\"SS\", -12), (\"TT\", -24)]\n\n ::trace\n\n)]\n", "file_path": "tests/resources/rstest/dump_debug_compact.rs", "rank": 25, "score": 190079.3400152107 }, { "content": "fn handling_magic_conversion_code(fixture: Cow<Expr>, arg_type: &Type) -> Expr {\n\n parse_quote! {\n\n {\n\n struct __Wrap<T>(std::marker::PhantomData<T>);\n\n\n", "file_path": "src/render/inject.rs", "rank": 26, "score": 188091.03414466788 }, { "content": "#[rstest(fixture(2, 4), expected, case(42), case(1000))]\n\nfn partial_2(fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 27, "score": 185926.67311558226 }, { "content": "#[rstest(fixture(7), expected, case(7), case(1000))]\n\nfn partial_1(fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 28, "score": 185926.67311558226 }, { "content": "#[rstest(fixture(2, 4, 5), expected, case(542), case(1000))]\n\nfn complete(fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 29, "score": 185926.67311558226 }, { "content": "fn cases_data(\n\n data: &RsTestData,\n\n name_span: Span,\n\n) -> impl Iterator<Item = (Ident, &[syn::Attribute], HashMap<String, &syn::Expr>)> {\n\n let display_len = data.cases().count().display_len();\n\n data.cases().enumerate().map({\n\n move |(n, case)| {\n\n let resolver_case = data\n\n .case_args()\n\n .map(|a| a.to_string())\n\n .zip(case.args.iter())\n\n .collect::<HashMap<_, _>>();\n\n (\n\n Ident::new(&format_case_name(case, n + 1, display_len), name_span),\n\n case.attrs.as_slice(),\n\n resolver_case,\n\n )\n\n }\n\n })\n\n}\n", "file_path": "src/render/mod.rs", "rank": 30, "score": 185799.47822375753 }, { "content": "#[test]\n\nfn resolve_default() {\n\n assert_eq!(42, my_fixture::default());\n\n}\n\n\n", "file_path": "tests/resources/fixture/fixture_struct.rs", "rank": 31, "score": 185032.18246415918 }, { "content": "fn prj(res: impl AsRef<Path>) -> Project {\n\n let path = Path::new(\"rstest\").join(res.as_ref());\n\n crate::prj().set_code_file(resources(path))\n\n}\n\n\n", "file_path": "tests/rstest/mod.rs", "rank": 32, "score": 184043.69247021657 }, { "content": "#[rstest]\n\nfn both(#[values(4, 2*3-2)] expected: usize, #[values(\"ciao\", \"buzz\")] input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n\n\n\n#[rstest(\n\n input => [\"ciao\", \"buzz\"]\n\n)]\n", "file_path": "tests/resources/rstest/matrix/use_attr.rs", "rank": 33, "score": 183482.25768805557 }, { "content": "#[fixture]\n\n#[default(u32)]\n\n#[partial_1(u32)]\n\n#[once]\n\nfn once_fixture(#[default(())] a: (), #[default(())] b: ()) -> u32 {\n\n eprintln!(\"Exec fixture() just once\");\n\n 42\n\n}\n\n\n", "file_path": "tests/resources/fixture/once_defined_type.rs", "rank": 34, "score": 183419.14724544334 }, { "content": "#[rstest]\n\n#[case(\"donald duck\")]\n\nfn error_convert_to_type_that_not_implement_from_str(#[case] s: S) {}\n\n\n\n#[rstest]\n\n#[case(async { \"hello\" } )]\n\nasync fn error_future_on_impl_type(#[case] #[future] s: impl AsRef<str>) {}\n\n\n\n#[rstest]\n\n#[case(async { 42 } )]\n\nasync fn error_future_on_impl_type(#[case] #[future] #[future] a: i32) {}\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 35, "score": 182849.42019636664 }, { "content": "#[test]\n\nfn impl_input() {\n\n let (output, _) = run_test(\"impl_param.rs\");\n\n\n\n TestResults::new()\n\n .ok(\"simple\")\n\n .ok(\"strlen_test::case_1\")\n\n .ok(\"strlen_test::case_2\")\n\n .assert(output);\n\n}\n\n\n", "file_path": "tests/rstest/mod.rs", "rank": 36, "score": 182399.4817994193 }, { "content": "fn strlen_test(expected: usize, input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n", "file_path": "tests/resources/rstest/matrix/simple.rs", "rank": 37, "score": 179623.80397483808 }, { "content": "#[rstest(expected, case(7), case(1000))]\n\nfn partial_attr_1(#[with(7)] fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 38, "score": 178894.5819031409 }, { "content": "#[rstest]\n\nfn simple<S: AsRef<str>>(fixture: S) {\n\n assert_eq!(3, fixture.as_ref().len());\n\n}\n\n\n\n#[rstest(\n\n expected, input,\n\n case(4, String::from(\"ciao\")),\n\n case(3, \"Foo\")\n\n)]\n", "file_path": "tests/resources/rstest/generic.rs", "rank": 39, "score": 178851.00928559212 }, { "content": "#[rstest(expected, case(42), case(1000))]\n\nfn partial_attr_2(#[with(2, 4)] fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 40, "score": 177914.64291090786 }, { "content": "#[rstest]\n\nfn default(fixture: u32) {\n\n assert_eq!(fixture, 0);\n\n}\n\n\n", "file_path": "tests/resources/fixture/partial.rs", "rank": 41, "score": 177896.753623343 }, { "content": "#[rstest]\n\n#[case(append(&mut f, \"a\"), \"f-a\", \"f-a-b\")]\n\nfn use_mutate_fixture(\n\n mut f: String,\n\n #[case] a: String,\n\n #[values(append(&mut f, \"b\"))] b: String,\n\n #[case] expected_a: &str,\n\n #[case] expected_b: &str,\n\n) {\n\n assert_eq!(expected_a, a);\n\n assert_eq!(expected_b, b);\n\n}\n", "file_path": "tests/resources/rstest/use_mutable_fixture_in_parametric_argumnts.rs", "rank": 42, "score": 177739.66376783254 }, { "content": "#[test]\n\nfn ignore_underscore_args() {\n\n let (output, _) = run_test(\"ignore_args.rs\");\n\n\n\n TestResults::new()\n\n .ok(\"test::case_1::_ignore3_1\")\n\n .ok(\"test::case_1::_ignore3_2\")\n\n .ok(\"test::case_1::_ignore3_3\")\n\n .ok(\"test::case_1::_ignore3_4\")\n\n .ok(\"test::case_2::_ignore3_1\")\n\n .ok(\"test::case_2::_ignore3_2\")\n\n .ok(\"test::case_2::_ignore3_3\")\n\n .ok(\"test::case_2::_ignore3_4\")\n\n .assert(output);\n\n}\n\n\n\nmod should_show_correct_errors {\n\n use std::process::Output;\n\n\n\n use lazy_static::lazy_static;\n\n\n", "file_path": "tests/rstest/mod.rs", "rank": 43, "score": 177286.8407077623 }, { "content": "#[rstest(expected, case(542), case(1000))]\n\nfn complete_attr(#[with(2, 4, 5)] fixture: u32, expected: u32) {\n\n assert_eq!(fixture, expected);\n\n}\n", "file_path": "tests/resources/rstest/cases/partial.rs", "rank": 44, "score": 177029.77156162122 }, { "content": "#[rstest(a => [0, 1], b => [0, 2])]\n\nfn default(fixture: u32, a: u32, b: u32) {\n\n assert_eq!(fixture, a * b);\n\n}\n\n\n", "file_path": "tests/resources/rstest/matrix/partial.rs", "rank": 45, "score": 176372.1865306155 }, { "content": "fn run_test(res: &str) -> (std::process::Output, String) {\n\n let prj = prj(res);\n\n (\n\n prj.run_tests().unwrap(),\n\n prj.get_name().to_owned().to_string(),\n\n )\n\n}\n\n\n\nmod should {\n\n use rstest_test::CountMessageOccurrence;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn use_input_fixtures() {\n\n let (output, _) = run_test(\"simple_injection.rs\");\n\n\n\n TestResults::new().ok(\"success\").fail(\"fail\").assert(output);\n\n }\n\n\n", "file_path": "tests/fixture/mod.rs", "rank": 46, "score": 174838.9830389765 }, { "content": "#[rstest]\n\nfn default(fixture: u32) {\n\n assert_eq!(fixture, 0);\n\n}\n\n\n", "file_path": "tests/resources/fixture/partial_in_attr.rs", "rank": 47, "score": 174663.71720370496 }, { "content": "#[test]\n\nfn resolve() {\n\n assert_eq!(2, fx::default())\n\n}\n\n\n", "file_path": "tests/resources/fixture/clean_up_default_generics.rs", "rank": 48, "score": 174465.0191835844 }, { "content": "fn error_no_match_args() {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 49, "score": 173273.68112676853 }, { "content": "#[rstest]\n\n#[case(2)]\n\n#[case(3)]\n\n#[case(7)]\n\nfn cases(once_fixture: &u32, #[case] divisor: u32) {\n\n assert_eq!(0, *once_fixture % divisor);\n\n}\n", "file_path": "tests/resources/fixture/once.rs", "rank": 50, "score": 172730.53537855914 }, { "content": "#[rstest(a, a, case(42))]\n\nfn error_define_a_case_arg_that_is_already_a_case_arg(a: u32) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 51, "score": 172188.9060397642 }, { "content": "#[rstest]\n\n#[case(42, 2)]\n\n#[case(43, 3)]\n\nfn test(#[case] _ignore1: u32, #[case] _ignore2: u32, #[values(1, 2, 3, 4)] _ignore3: u32) {}\n", "file_path": "tests/resources/rstest/ignore_args.rs", "rank": 52, "score": 170139.59905982087 }, { "content": "#[test]\n\nfn resolve_partial() {\n\n assert_eq!(12, fx_double::partial_1(10))\n\n}\n", "file_path": "tests/resources/fixture/clean_up_default_generics.rs", "rank": 53, "score": 169880.1678867106 }, { "content": "#[fixture]\n\nfn fx_nested_multiple_impl_return() -> (impl Iterator<Item=impl ToString>, impl ToString) {\n\n (std::iter::once(42), 42i32)\n\n}\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 54, "score": 169231.63239215594 }, { "content": "#[rstest]\n\n#[case(2)]\n\n#[case(3)]\n\n#[case(7)]\n\nfn cases(once_fixture: &u32, #[case] divisor: u32) {\n\n assert_eq!(0, *once_fixture % divisor);\n\n}\n", "file_path": "tests/resources/fixture/once_defined_type.rs", "rank": 55, "score": 167318.34243843533 }, { "content": "#[fixture]\n\nfn name() -> &'static str {\n\n \"name\"\n\n}\n\n\n", "file_path": "tests/resources/fixture/errors.rs", "rank": 56, "score": 167149.84458621667 }, { "content": "#[test]\n\nfn should_map_fixture_by_remove_first_underscore_if_any() {\n\n let (output, _) = run_test(\"remove_underscore.rs\");\n\n\n\n TestResults::new().ok(\"ignore_input\").assert(output);\n\n}\n\n\n", "file_path": "tests/rstest/mod.rs", "rank": 57, "score": 166185.85637237414 }, { "content": "fn case_args_without_cases(params: &RsTestData) -> Errors {\n\n if !params.has_cases() {\n\n return Box::new(\n\n params\n\n .case_args()\n\n .map(|a| syn::Error::new(a.span(), \"No cases for this argument.\")),\n\n );\n\n }\n\n Box::new(std::iter::empty())\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::test::{assert_eq, *};\n\n use rstest_test::assert_in;\n\n\n\n use super::*;\n\n\n\n #[rstest]\n\n #[case::generics(\"fn f<G: SomeTrait>(){}\")]\n", "file_path": "src/error.rs", "rank": 58, "score": 165435.98662672468 }, { "content": "fn strlen_test<S: AsRef<str>>(expected: usize, input: S) {\n\n assert_eq!(expected, input.as_ref().len());\n\n}\n", "file_path": "tests/resources/rstest/generic.rs", "rank": 59, "score": 164795.01972088465 }, { "content": "fn description(expected: bool) {\n\n assert!(expected);\n\n}\n", "file_path": "tests/resources/rstest/cases/description.rs", "rank": 60, "score": 164422.60375065714 }, { "content": "#[cfg(test)]\n\n#[rstest(a, case(42, 43), case(12), case(24, 34))]\n\nfn error_too_much_arguments(a: u32) {}\n\n\n", "file_path": "tests/resources/rstest/cases/case_with_wrong_args.rs", "rank": 61, "score": 163955.98178917347 }, { "content": "#[fixture]\n\nfn f(name: &str) -> String {\n\n name.to_owned()\n\n}\n\n\n", "file_path": "tests/resources/fixture/errors.rs", "rank": 62, "score": 163399.3719693896 }, { "content": "#[rstest]\n\n#[case(\"1.2.3.4:8080\", 8080)]\n\n#[case(\"127.0.0.1:9000\", 9000)]\n\nfn check_port(#[case] addr: SocketAddr, #[case] expected: u16) {\n\n assert_eq!(expected, addr.port());\n\n}\n", "file_path": "playground/src/main.rs", "rank": 63, "score": 163057.5214798164 }, { "content": "#[rstest(f, case(42))]\n\nfn error_cannot_resolve_fixture(no_fixture: u32, f: u32) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 64, "score": 162790.72700146676 }, { "content": "fn run_test(res: impl AsRef<Path>) -> (std::process::Output, String) {\n\n let prj = prj(res);\n\n (\n\n prj.run_tests().unwrap(),\n\n prj.get_name().to_owned().to_string(),\n\n )\n\n}\n\n\n", "file_path": "tests/rstest/mod.rs", "rank": 65, "score": 162269.84408069088 }, { "content": "#[fixture]\n\nfn valid(#[default(\"some\")] t: MyType) -> MyType {\n\n t\n\n}\n\n\n", "file_path": "tests/resources/fixture/default_conversion.rs", "rank": 66, "score": 162091.1145872476 }, { "content": "#[rstest]\n\nfn nested_impl_return(mut fx_nested_impl_return: impl Iterator<Item=impl ToString>) {\n\n assert_eq!(\"42\", fx_nested_impl_return.next().unwrap().to_string());\n\n}\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 67, "score": 161641.1970215681 }, { "content": "#[fixture]\n\nfn f() -> String {\n\n \"f\".to_owned()\n\n}\n\n\n", "file_path": "tests/resources/rstest/use_mutable_fixture_in_parametric_argumnts.rs", "rank": 68, "score": 160610.52284738774 }, { "content": "#[fixture]\n\nfn fail(#[default(\"error\")] t: MyType) -> MyType {\n\n t\n\n}\n\n\n", "file_path": "tests/resources/fixture/default_conversion.rs", "rank": 69, "score": 159203.0152436354 }, { "content": "#[rstest(f => [42])]\n\nfn error_matrix_wrong_type(f: &str) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 70, "score": 159095.92771818922 }, { "content": "#[rstest(empty => [])]\n\nfn error_empty_list(empty: &str) {}\n\n\n\n#[rstest(not_exist_1 => [42],\n\n not_exist_2 => [42])]\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 71, "score": 159095.7845045401 }, { "content": "#[rstest]\n\nfn nested_multiple_impl_return(mut fx_nested_multiple_impl_return: (impl Iterator<Item=impl ToString>, impl ToString)) {\n\n assert_eq!(fx_nested_multiple_impl_return.0.next().unwrap().to_string(), fx_nested_multiple_impl_return.1.to_string());\n\n}\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 72, "score": 159051.609874548 }, { "content": "#[fixture]\n\n#[once]\n\nfn error_generics_once_fixture() -> impl Iterator<Item: u32> {\n\n std::iter::once(42)\n\n}\n", "file_path": "tests/resources/fixture/errors.rs", "rank": 73, "score": 158939.59411106995 }, { "content": "#[fixture]\n\nfn fx_nested_impl_return() -> impl Iterator<Item=impl ToString> { std::iter::once(42) }\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 74, "score": 158600.3798484322 }, { "content": "fn matrix_fail(u: u32, s: &str, t: (&str, i32)) {\n\n assert!(false);\n\n}\n", "file_path": "tests/resources/rstest/dump_debug_compact.rs", "rank": 75, "score": 157919.77608623664 }, { "content": "#[cfg(test)]\n\n#[rstest(a, b, case(42), case(1, 2), case(43))]\n\nfn error_less_arguments(a: u32, b: u32) {}\n\n\n", "file_path": "tests/resources/rstest/cases/case_with_wrong_args.rs", "rank": 76, "score": 157517.8333479958 }, { "content": "#[fixture]\n\nfn byte_array(#[default(b\"1234\")] some: &[u8]) -> usize {\n\n some.len()\n\n}\n\n\n", "file_path": "tests/resources/fixture/default_conversion.rs", "rank": 77, "score": 156581.26901973382 }, { "content": "#[fixture]\n\nfn fx_nested_impl_input(mut fx_nested_impl_return: impl Iterator<Item=impl ToString>) -> String {\n\n fx_nested_impl_return.next().unwrap().to_string()\n\n}\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 78, "score": 156026.71802214018 }, { "content": "#[rstest]\n\nfn should_success() -> Result<(), &'static str> {\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/resources/rstest/return_result.rs", "rank": 79, "score": 155345.45510136214 }, { "content": "#[rstest]\n\nfn should_fail() -> Result<(), &'static str> {\n\n Err(\"Return Error\")\n\n}\n\n\n\n#[rstest(ret,\n\n case::should_success(Ok(())),\n\n case::should_fail(Err(\"Return Error\"))\n\n)]\n", "file_path": "tests/resources/rstest/return_result.rs", "rank": 80, "score": 155345.45510136214 }, { "content": "#[rstest]\n\n#[trace]\n\n#[case(A{}, B{}, D{})]\n\nfn cases(fu32: u32, #[case] #[notrace] a: A, #[case] #[notrace] b: B, #[case] d: D) {\n\n assert!(false);\n\n}\n\n\n", "file_path": "tests/resources/rstest/dump_exclude_some_inputs.rs", "rank": 81, "score": 154648.01669986863 }, { "content": "#[rstest(f, f(42), case(12))]\n\nfn error_inject_a_fixture_that_is_already_a_case(f: u32) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 82, "score": 154531.6972101909 }, { "content": "#[fixture]\n\nfn fx_nested_multiple_impl_input(mut fx_nested_multiple_impl_return: (impl Iterator<Item=impl ToString>, impl ToString)) -> bool {\n\n fx_nested_multiple_impl_return.0.next().unwrap().to_string() == fx_nested_multiple_impl_return.1.to_string()\n\n}\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 83, "score": 154393.55948484212 }, { "content": "#[fixture]\n\npub fn simple(#[default(42)] value: u32) -> u32 {\n\n value\n\n}\n\n\n", "file_path": "tests/resources/fixture/default_in_attrs.rs", "rank": 84, "score": 153841.66640063532 }, { "content": "fn resolve_default_test_attr(is_async: bool) -> TokenStream {\n\n if is_async {\n\n quote! { #[async_std::test] }\n\n } else {\n\n quote! { #[test] }\n\n }\n\n}\n\n\n", "file_path": "src/render/mod.rs", "rank": 85, "score": 153229.7667122247 }, { "content": "fn return_type(ret: Result<(), &'static str>) -> Result<(), &'static str> {\n\n ret\n\n}\n", "file_path": "tests/resources/rstest/return_result.rs", "rank": 86, "score": 153152.23869416237 }, { "content": "#[fixture]\n\nfn base(#[default(\"1.2.3.4\")] ip: Ipv4Addr, #[default(r#\"8080\"#)] port: u16) -> SocketAddr {\n\n SocketAddr::new(ip.into(), port)\n\n}\n\n\n", "file_path": "tests/resources/fixture/default_conversion.rs", "rank": 87, "score": 152729.79884328973 }, { "content": "#[rstest]\n\nfn base_impl_return(mut fx_base_impl_return: impl Iterator<Item=u32>) {\n\n assert_eq!(42, fx_base_impl_return.next().unwrap());\n\n}\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 88, "score": 152545.62979158136 }, { "content": "fn trace_argument_code_string(arg_name: &str) -> String {\n\n let arg_name = ident(arg_name);\n\n let statment: Stmt = parse_quote! {\n\n println!(\"{} = {:?}\", stringify!(#arg_name) ,#arg_name);\n\n };\n\n statment.display_code()\n\n}\n\n\n\nmod single_test_should {\n\n use rstest_test::{assert_in, assert_not_in};\n\n\n\n use crate::test::{assert_eq, *};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn add_return_type_if_any() {\n\n let input_fn: ItemFn = \"fn function(fix: String) -> Result<i32, String> { Ok(42) }\".ast();\n\n\n\n let result: ItemFn = single(input_fn.clone(), Default::default()).ast();\n", "file_path": "src/render/test.rs", "rank": 89, "score": 152541.0706221785 }, { "content": "#[rstest(one, two, three)]\n\nfn should_show_error_for_no_case(one: u32, two: u32, three: u32) {}\n", "file_path": "tests/resources/rstest/cases/args_with_no_cases.rs", "rank": 90, "score": 152022.24977514078 }, { "content": "#[fixture]\n\npub fn double(#[default(20 + 1)] value: u32, #[default(1 + 1)] mult: u32) -> u32 {\n\n value * mult\n\n}\n\n\n", "file_path": "tests/resources/fixture/default_in_attrs.rs", "rank": 91, "score": 151613.44467063947 }, { "content": "#[rstest(f(42), f, case(12))]\n\nfn error_define_case_that_is_already_an_injected_fixture(f: u32) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 92, "score": 150801.99737436487 }, { "content": "#[fixture]\n\nfn my_fixture_injected(my_fixture: u32, multiplier: impl Mult) -> u32 { multiplier.mult(my_fixture) }\n\n\n", "file_path": "tests/resources/fixture/fixture_struct.rs", "rank": 93, "score": 149659.2372558789 }, { "content": "#[rstest(a => [42], a, case(42))]\n\nfn error_define_a_case_arg_that_is_already_a_value_list(a: u32) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 94, "score": 148838.81680859538 }, { "content": "#[rstest(a, case(42), a => [42])]\n\nfn error_define_a_value_list_that_is_already_a_case_arg(a: u32) {}\n\n\n", "file_path": "tests/resources/rstest/errors.rs", "rank": 95, "score": 148838.81680859538 }, { "content": "fn format_case_name(case: &TestCase, index: usize, display_len: usize) -> String {\n\n let description = case\n\n .description\n\n .as_ref()\n\n .map(|d| format!(\"_{}\", d))\n\n .unwrap_or_default();\n\n format!(\n\n \"case_{:0len$}{d}\",\n\n index,\n\n len = display_len,\n\n d = description\n\n )\n\n}\n\n\n", "file_path": "src/render/mod.rs", "rank": 96, "score": 148749.11537920323 }, { "content": "#[rstest]\n\n#[case()]\n\n#[case()]\n\n#[case()]\n\nfn cases(_once_fixture: ()) {\n\n assert!(true);\n\n}\n", "file_path": "tests/resources/fixture/once_no_return.rs", "rank": 97, "score": 148622.74090192287 }, { "content": "#[fixture]\n\nfn fx_base_impl_return() -> impl Iterator<Item=u32> { std::iter::once(42) }\n\n\n", "file_path": "tests/resources/fixture/impl.rs", "rank": 98, "score": 148265.68383614166 }, { "content": "#[test]\n\nfn sync(expected: u32, value: u32) { assert_eq!(expected, value); }\n\n\n\n#[rstest(expected, value,\n\n case::pass(42, async { 42 }),\n\n #[should_panic]\n\n case::panic(41, async { 42 }),\n\n case::fail(1, async { 42 })\n\n)]\n\n#[actix_rt::test]\n\nasync fn fn_async(expected: u32, value: impl Future<Output=u32>) { assert_eq!(expected, value.await); }\n", "file_path": "tests/resources/rstest/cases/inject.rs", "rank": 99, "score": 147825.4007938993 } ]
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 => write_xml(writer, key),\n\n }\n\n}\n\n\n", "file_path": "src/format/kf_writer.rs", "rank": 0, "score": 433251.44354354066 }, { "content": "/// Attempts to write string data.\n\npub fn write_string<W: Write>(writer: &mut EventWriter<W>, value: &String) -> Result<()> {\n\n try!(writer.write(value.as_str()));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 1, "score": 415586.42929342727 }, { "content": "fn write_binary<W: Write>(writer: &mut W, key: &KeyFile) -> Result<()> {\n\n try!(writer.write(key.key.unsecure()));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kf_writer.rs", "rank": 2, "score": 411764.08428455755 }, { "content": "fn write_version<W: Write>(writer: &mut W, version: &Version) -> Result<()> {\n\n try!(writer.write_u16::<LittleEndian>(version.minor));\n\n try!(writer.write_u16::<LittleEndian>(version.major));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 3, "score": 400796.4361625668 }, { "content": "/// Attempts to write a tag that contains an i32.\n\npub fn write_i32_tag<W: Write>(writer: &mut EventWriter<W>, tag: &str, value: i32) -> Result<()> {\n\n write_string_tag(writer, tag, &format!(\"{}\", value))\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 4, "score": 392719.14632888953 }, { "content": "/// Attempts to write a tag that contains boolean data.\n\npub fn write_bool_tag<W: Write>(writer: &mut EventWriter<W>, tag: &str, value: bool) -> Result<()> {\n\n write_bool_opt_tag(writer, tag, &Some(value))\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 5, "score": 392699.80619848304 }, { "content": "/// Attempts to write binary data.\n\npub fn write_binary<W: Write>(writer: &mut EventWriter<W>, data: &[u8]) -> Result<()> {\n\n write_string(writer, &data.to_base64(STANDARD))\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 6, "score": 385581.4585005085 }, { "content": "fn write_xml<W: Write>(writer: &mut W, key: &KeyFile) -> Result<()> {\n\n let config = EmitterConfig::new().perform_indent(true).indent_string(\"\\t\");\n\n\n\n {\n\n let mut writer = EventWriter::new_with_config(writer, config);\n\n try!(write_xml_key_file_section(&mut writer, key));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kf_writer.rs", "rank": 7, "score": 381734.09369465464 }, { "content": "fn write_hex<W: Write>(writer: &mut W, key: &KeyFile) -> Result<()> {\n\n let hex = key.key.unsecure().to_hex();\n\n try!(writer.write(&hex.into_bytes()));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kf_writer.rs", "rank": 8, "score": 381734.09369465464 }, { "content": "fn write_comment<W: Write>(writer: &mut W, opt: &Option<Comment>) -> Result<()> {\n\n match *opt {\n\n Some(ref comment) => {\n\n try!(write_header_id(writer, kdb2::COMMENT_HID));\n\n try!(write_header_size(writer, comment.0.len() as u16));\n\n try!(write_bytes(writer, &comment.0));\n\n Ok(())\n\n }\n\n None => Ok(()),\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 9, "score": 377416.05908279226 }, { "content": "fn write_protected_stream_key<W: Write>(writer: &mut W, key: &ProtectedStreamKey) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::PROTECTED_STREAM_KEY_HID));\n\n try!(write_header_size(writer, kdb2::PROTECTED_STREAM_KEY_SIZE));\n\n try!(write_bytes(writer, &key.0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 10, "score": 375593.90236109134 }, { "content": "fn write_xml_key_section<W: Write>(writer: &mut EventWriter<W>, key: &KeyFile) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kf::KEY_TAG));\n\n try!(xml::write_binary_tag(writer, kf::DATA_TAG, key.key.unsecure()));\n\n xml::write_end_tag(writer)\n\n}\n", "file_path": "src/format/kf_writer.rs", "rank": 11, "score": 371783.20743690606 }, { "content": "/// Attempts to write an end tag.\n\npub fn write_end_tag<W: Write>(writer: &mut EventWriter<W>) -> Result<()> {\n\n try!(writer.write(writer::XmlEvent::end_element()));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 12, "score": 370717.59787859896 }, { "content": "fn write_compression<W: Write>(writer: &mut W, compression: &Compression) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::COMPRESSION_HID));\n\n try!(write_header_size(writer, kdb2::COMPRESSION_SIZE));\n\n let id = match *compression {\n\n Compression::None => 0u32,\n\n Compression::GZip => 1u32,\n\n };\n\n try!(writer.write_u32::<LittleEndian>(id));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 13, "score": 370063.7402087939 }, { "content": "fn write_xml_key_file_section<W: Write>(writer: &mut EventWriter<W>, key: &KeyFile) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kf::KEY_FILE_TAG));\n\n try!(write_xml_meta_section(writer));\n\n try!(write_xml_key_section(writer, key));\n\n xml::write_end_tag(writer)\n\n}\n\n\n", "file_path": "src/format/kf_writer.rs", "rank": 14, "score": 368486.22490601754 }, { "content": "/// Attempts to write the database content to the writer.\n\npub fn write<W: Log + Write>(writer: &mut W, db: &Database) -> Result<()> {\n\n let mut random = try!(RandomGen::new());\n\n let transform_seed = TransformSeed(random.next_32_bytes());\n\n let transformed_key =\n\n TransformedKey::new(&db.composite_key, &transform_seed, &db.transform_rounds);\n\n let master_iv = MasterIV(random.next_16_bytes());\n\n let master_seed = MasterSeed(random.next_32_bytes());\n\n let master_key = MasterKey::new(&master_seed, &transformed_key);\n\n let protected_stream_key = ProtectedStreamKey(random.next_32_bytes());\n\n let stream_key = StreamKey::new(&protected_stream_key);\n\n let stream_start_bytes = StreamStartBytes(random.next_32_bytes());\n\n\n\n try!(write_sig_1(writer));\n\n try!(write_sig_2(writer));\n\n try!(write_version(writer, &db.version));\n\n try!(write_comment(writer, &db.comment));\n\n try!(write_master_cipher(writer, &db.master_cipher));\n\n try!(write_compression(writer, &db.compression));\n\n try!(write_master_seed(writer, &master_seed));\n\n try!(write_transform_seed(writer, &transform_seed));\n", "file_path": "src/format/kdb2_writer.rs", "rank": 15, "score": 368183.89828910003 }, { "content": "/// Attempts to read an i32.\n\npub fn read_i32<R: Read>(reader: &mut EventReader<R>) -> Result<i32> {\n\n match try!(read_i32_opt(reader)) {\n\n Some(num) => Ok(num),\n\n None => read_err(reader, \"No Number value found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 16, "score": 366406.7264801398 }, { "content": "/// Attempts to read a boolean.\n\npub fn read_bool<R: Read>(reader: &mut EventReader<R>) -> Result<bool> {\n\n match try!(read_bool_opt(reader)) {\n\n Some(b) => Ok(b),\n\n None => read_err(reader, \"No Bool value found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 17, "score": 366386.50737996097 }, { "content": "/// Attempts to read a string.\n\npub fn read_string<R: Read>(reader: &mut EventReader<R>) -> Result<String> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => Ok(string),\n\n None => Ok(String::new()),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 18, "score": 366038.52246651717 }, { "content": "/// Attempts to read the database content from the reader.\n\npub fn read<R>(reader: &mut R, composite_key: &CompositeKey) -> Result<(MetaData, XmlData)>\n\n where R: Log + Read\n\n{\n\n let version = try!(read_version(reader));\n\n let mut comment: Option<Comment> = None;\n\n let mut compression: Option<Compression> = None;\n\n let mut master_cipher: Option<MasterCipher> = None;\n\n let mut master_iv: Option<MasterIV> = None;\n\n let mut master_seed: Option<MasterSeed> = None;\n\n let mut protected_stream_key: Option<ProtectedStreamKey> = None;\n\n let mut stream_cipher: Option<StreamCipher> = None;\n\n let mut stream_start_bytes: Option<StreamStartBytes> = None;\n\n let mut transform_rounds: Option<TransformRounds> = None;\n\n let mut transform_seed: Option<TransformSeed> = None;\n\n\n\n loop {\n\n let header_id = try!(reader.read_u8());\n\n match header_id {\n\n kdb2::COMMENT_HID => {\n\n comment = Some(try!(read_comment(reader)));\n", "file_path": "src/format/kdb2_reader.rs", "rank": 19, "score": 365329.61215962394 }, { "content": "/// Attempts to read an optional binary key.\n\npub fn read_binary_key_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<BinaryKey>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => Ok(Some(BinaryKey(string))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 20, "score": 363211.64871327556 }, { "content": "/// Attempts to read an optional string key\n\npub fn read_string_key_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<StringKey>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => Ok(Some(StringKey::from_string(&string))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 21, "score": 363135.3403566028 }, { "content": "/// Attempts to write GZip compressed data.\n\npub fn write_gzip<W: Write>(writer: &mut EventWriter<W>, data: &[u8]) -> Result<()> {\n\n let compressed = try!(gzip::encode(data));\n\n write_binary(writer, &compressed)\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 22, "score": 356161.669685904 }, { "content": "/// Attempts to read an optional i32.\n\npub fn read_i32_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<i32>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => {\n\n match string.parse::<i32>() {\n\n Ok(num) => Ok(Some(num)),\n\n Err(err) => read_err(reader, format!(\"Number {}\", err)),\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 23, "score": 353490.77654981567 }, { "content": "/// Attempts to read an optional boolean.\n\npub fn read_bool_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<bool>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => {\n\n match string.to_lowercase().as_str() {\n\n \"false\" => Ok(Some(false)),\n\n \"null\" => Ok(None),\n\n \"true\" => Ok(Some(true)),\n\n val => read_err(reader, format!(\"Bool invalid value: {}\", val)),\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 24, "score": 353471.028448003 }, { "content": "/// Attempts to read an optional color.\n\npub fn read_color_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<Color>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => {\n\n match Color::from_hex_string(&string) {\n\n Ok(color) => Ok(Some(color)),\n\n Err(err) => read_err(reader, format!(\"Color {}\", err)),\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 25, "score": 353341.83717616345 }, { "content": "/// Attempts to read an optional string.\n\npub fn read_string_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<String>> {\n\n let event = try!(reader.next());\n\n match event {\n\n reader::XmlEvent::Characters(val) => Ok(Some(val)),\n\n reader::XmlEvent::EndElement { .. } => Ok(None),\n\n _ => read_err(reader, \"No characters found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 26, "score": 353133.2013118084 }, { "content": "/// Attempts to write a start tag.\n\npub fn write_start_tag<W: Write>(writer: &mut EventWriter<W>, tag: &str) -> Result<()> {\n\n try!(writer.write(writer::XmlEvent::start_element(tag)));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 27, "score": 352334.3142184089 }, { "content": "/// Attempts to write a tag that contains no data.\n\npub fn write_null_tag<W: Write>(writer: &mut EventWriter<W>, tag: &str) -> Result<()> {\n\n try!(write_start_tag(writer, tag));\n\n try!(write_end_tag(writer));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 28, "score": 352334.27375642327 }, { "content": "fn write_auto_type_section<W: Write>(writer: &mut EventWriter<W>, entry: &Entry) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::AUTO_TYPE_TAG));\n\n try!(xml::write_i32_tag(writer,\n\n kdb2::DATA_TRANSFER_OBFUSCATION_TAG,\n\n entry.auto_type_obfuscation.to_i32()));\n\n try!(xml::write_string_tag(writer, kdb2::DEFAULT_SEQUENCE_TAG, &entry.auto_type_def_sequence));\n\n try!(xml::write_bool_tag(writer, kdb2::ENABLED_TAG, entry.auto_type_enabled));\n\n\n\n for assoc in &entry.associations {\n\n try!(write_association_section(writer, assoc));\n\n }\n\n xml::write_end_tag(writer)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 29, "score": 346574.4104129969 }, { "content": "/// Attempts to read a key file from the reader.\n\npub fn read<R: Read>(reader: &mut R) -> Result<KeyFile> {\n\n let mut data = Vec::new();\n\n try!(reader.read_to_end(&mut data));\n\n match data.len() {\n\n kf::BINARY_KEY_FILE_LEN => read_binary(data),\n\n kf::HEX_KEY_FILE_LEN => read_hex(data),\n\n _ => read_xml(&mut Cursor::new(data)),\n\n }\n\n}\n\n\n", "file_path": "src/format/kf_reader.rs", "rank": 30, "score": 343433.1478275083 }, { "content": "/// Attempts to read a date and time.\n\npub fn read_datetime<R: Read>(reader: &mut EventReader<R>) -> Result<DateTime<UTC>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => {\n\n match string.parse::<DateTime<UTC>>() {\n\n Ok(datetime) => Ok(datetime),\n\n Err(err) => read_err(reader, format!(\"DateTime {}\", err)),\n\n }\n\n }\n\n None => read_err(reader, \"No DateTime value found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 31, "score": 343320.84648239583 }, { "content": "fn write_sig_1<W: Write>(writer: &mut W) -> Result<()> {\n\n try!(writer.write(&common::DB_SIGNATURE));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 32, "score": 342254.3522282107 }, { "content": "fn write_sig_2<W: Write>(writer: &mut W) -> Result<()> {\n\n try!(writer.write(&common::KDB2_SIGNATURE));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 33, "score": 342254.3522282107 }, { "content": "fn write_end_header<W: Write>(writer: &mut W) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::END_HID));\n\n try!(write_header_size(writer, 0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 34, "score": 338516.8488415386 }, { "content": "/// Attempts to write a tag that contains a UUID.\n\npub fn write_uuid_tag<W: Write>(writer: &mut EventWriter<W>, tag: &str, uuid: &Uuid) -> Result<()> {\n\n write_binary_tag(writer, tag, uuid.as_bytes())\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 35, "score": 336010.5298321653 }, { "content": "fn read_comment<R: Read>(reader: &mut R) -> Result<Comment> {\n\n let size = try!(reader.read_u16::<LittleEndian>()) as usize;\n\n let data = try!(read_bytes_size(reader, &size));\n\n Ok(Comment(data))\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 36, "score": 334325.9757510229 }, { "content": "fn read_version<R: Read>(reader: &mut R) -> Result<Version> {\n\n let minor = try!(reader.read_u16::<LittleEndian>());\n\n let major = try!(reader.read_u16::<LittleEndian>());\n\n Ok(Version {\n\n major: major,\n\n minor: minor,\n\n })\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 37, "score": 334309.5929632668 }, { "content": "fn write_xml_meta_section<W: Write>(writer: &mut EventWriter<W>) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kf::META_TAG));\n\n try!(xml::write_string_tag(writer, kf::VERSION_TAG, &String::from(kf::XML_KEY_FILE_VERSION)));\n\n xml::write_end_tag(writer)\n\n}\n\n\n", "file_path": "src/format/kf_writer.rs", "rank": 38, "score": 327560.7619952065 }, { "content": "/// Attempts to read binary data.\n\npub fn read_binary<R: Read>(reader: &mut EventReader<R>) -> Result<Vec<u8>> {\n\n match try!(read_binary_opt(reader)) {\n\n Some(bytes) => Ok(bytes),\n\n None => Ok(Vec::new()),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 39, "score": 326950.78908592113 }, { "content": "/// Attempts to read the XML data from the reader.\n\npub fn read<R: Read>(reader: &mut R, stream_key: &StreamKey) -> Result<XmlData> {\n\n let mut data = XmlData::default();\n\n let mut reader = EventReader::new(reader);\n\n let mut cipher = salsa20::new_cipher(stream_key);\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::KEE_PASS_FILE_TAG => {\n\n try!(read_kee_pass_file(&mut reader, &mut data, &mut cipher));\n\n }\n\n _ => return xml::read_err(&mut reader, \"Invalid root node\"),\n\n }\n\n }\n\n\n\n XmlEvent::EndDocument { .. } => {\n\n break;\n\n }\n\n\n\n _ => {}\n\n }\n\n }\n\n\n\n Ok(data)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 40, "score": 325217.43340688804 }, { "content": "fn write_bytes<W: Write>(writer: &mut W, bytes: &[u8]) -> Result<()> {\n\n try!(writer.write(bytes));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 41, "score": 324325.5484779825 }, { "content": "fn write_block_final<W: Write>(writer: &mut W, id: u32) -> Result<()> {\n\n try!(writer.write_u32::<LittleEndian>(id));\n\n try!(writer.write(&kdb2::FINAL_BLOCK_HASH));\n\n try!(writer.write_u32::<LittleEndian>(0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 42, "score": 320847.3954358471 }, { "content": "fn write_header_size<W: Write>(writer: &mut W, size: u16) -> Result<()> {\n\n try!(writer.write_u16::<LittleEndian>(size));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 43, "score": 320847.3954358471 }, { "content": "fn write_header_id<W: Write>(writer: &mut W, id: u8) -> Result<()> {\n\n try!(writer.write_u8(id));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 44, "score": 320847.3954358471 }, { "content": "fn read_binaries<R: Read>(reader: &mut EventReader<R>) -> Result<BinariesMap> {\n\n let mut map = BinariesMap::new();\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, attributes, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::BINARY_TAG => {\n\n let id = BinaryId(try!(get_id_attr_value(reader, &attributes)));\n\n let compressed = try!(get_compressed_attr_value(reader, &attributes));\n\n let bytes = if compressed {\n\n try!(xml::read_gzip(reader))\n\n } else {\n\n try!(xml::read_binary(reader))\n\n };\n\n map.insert(id, bytes);\n\n }\n\n _ => {}\n\n }\n\n }\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 45, "score": 320323.1194208234 }, { "content": "fn read_custom_data_item<R: Read>(reader: &mut EventReader<R>) -> Result<(String, String)> {\n\n let mut key: Option<String> = None;\n\n let mut value: Option<String> = None;\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::KEY_TAG => {\n\n key = try!(xml::read_string_opt(reader));\n\n }\n\n kdb2::VALUE_TAG => {\n\n value = try!(xml::read_string_opt(reader));\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kdb2::ITEM_TAG {\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 46, "score": 318165.8167095939 }, { "content": "fn write_master_iv<W: Write>(writer: &mut W, iv: &MasterIV) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::MASTER_IV_HID));\n\n try!(write_header_size(writer, kdb2::MASTER_IV_SIZE));\n\n try!(write_bytes(writer, &iv.0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 47, "score": 317488.537590435 }, { "content": "fn write_master_cipher<W: Write>(writer: &mut W, cipher: &MasterCipher) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::MASTER_CIPHER_HID));\n\n try!(write_header_size(writer, kdb2::MASTER_CIPHER_SIZE));\n\n match *cipher {\n\n MasterCipher::Aes256 => try!(write_bytes(writer, &kdb2::AES_CIPHER_ID)),\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 48, "score": 317488.537590435 }, { "content": "fn write_transform_seed<W: Write>(writer: &mut W, seed: &TransformSeed) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::TRANSFORM_SEED_HID));\n\n try!(write_header_size(writer, kdb2::TRANSFORM_SEED_SIZE));\n\n try!(write_bytes(writer, &seed.0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 49, "score": 317488.53759043507 }, { "content": "fn write_transform_rounds<W: Write>(writer: &mut W, rounds: &TransformRounds) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::TRANSFORM_ROUNDS_HID));\n\n try!(write_header_size(writer, kdb2::TRANSFORM_ROUNDS_SIZE));\n\n try!(writer.write_u64::<LittleEndian>(rounds.0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 50, "score": 317488.53759043507 }, { "content": "fn write_stream_cipher<W: Write>(writer: &mut W, cipher: &StreamCipher) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::STREAM_CIPHER_HID));\n\n try!(write_header_size(writer, kdb2::STREAM_CIPHER_SIZE));\n\n let id = match *cipher {\n\n StreamCipher::Salsa20 => 2u32,\n\n };\n\n try!(writer.write_u32::<LittleEndian>(id));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 51, "score": 317488.53759043507 }, { "content": "fn write_master_seed<W: Write>(writer: &mut W, seed: &MasterSeed) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::MASTER_SEED_HID));\n\n try!(write_header_size(writer, kdb2::MASTER_SEED_SIZE));\n\n try!(write_bytes(writer, &seed.0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 52, "score": 317488.537590435 }, { "content": "/// Attempts to read optional binary data.\n\npub fn read_binary_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<Vec<u8>>> {\n\n match try!(read_string_opt(reader)) {\n\n Some(string) => {\n\n match string.from_base64() {\n\n Ok(bin) => Ok(Some(bin)),\n\n Err(err) => read_err(reader, format!(\"Base64 {}\", err)),\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 53, "score": 315385.024435158 }, { "content": "fn read_compression<R: Read>(reader: &mut R) -> Result<Compression> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::COMPRESSION_SIZE {\n\n let data = try!(reader.read_u32::<LittleEndian>());\n\n match data {\n\n 0 => Ok(Compression::None),\n\n 1 => Ok(Compression::GZip),\n\n _ => Err(Error::UnhandledCompression(data)),\n\n }\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::COMPRESSION_HID,\n\n expected: kdb2::COMPRESSION_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 54, "score": 311357.6360204535 }, { "content": "fn write_stream_start_bytes<W: Write>(writer: &mut W, bytes: &StreamStartBytes) -> Result<()> {\n\n try!(write_header_id(writer, kdb2::STREAM_START_BYTES_HID));\n\n try!(write_header_size(writer, kdb2::STREAM_START_BYTES_SIZE));\n\n try!(write_bytes(writer, &bytes.0));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 55, "score": 311104.13557786646 }, { "content": "fn write_block<W: Write>(writer: &mut W, id: u32, data: &[u8]) -> Result<()> {\n\n try!(writer.write_u32::<LittleEndian>(id));\n\n try!(writer.write(&sha256::hash(&[data])));\n\n try!(writer.write_u32::<LittleEndian>(data.len() as u32));\n\n try!(writer.write(data));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_writer.rs", "rank": 56, "score": 308551.06029962515 }, { "content": "/// Attempts to read an icon.\n\npub fn read_icon<R: Read>(reader: &mut EventReader<R>) -> Result<Icon> {\n\n match try!(read_i32_opt(reader)) {\n\n Some(num) => {\n\n match Icon::from_i32(num) {\n\n Ok(icon) => Ok(icon),\n\n Err(err) => read_err(reader, format!(\"{}\", err)),\n\n }\n\n }\n\n None => read_err(reader, \"No Icon value found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 57, "score": 305209.941082387 }, { "content": "/// Attempts to read a UUID.\n\npub fn read_uuid<R: Read>(reader: &mut EventReader<R>) -> Result<Uuid> {\n\n match try!(read_uuid_opt(reader)) {\n\n Some(uuid) => Ok(uuid),\n\n None => read_err(reader, \"No UUID value found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 58, "score": 305209.941082387 }, { "content": "/// Attempts to read an obfuscation type.\n\npub fn read_obfuscation<R: Read>(reader: &mut EventReader<R>) -> Result<Obfuscation> {\n\n match try!(read_i32_opt(reader)) {\n\n Some(num) => {\n\n match Obfuscation::from_i32(num) {\n\n Ok(val) => Ok(val),\n\n Err(err) => read_err(reader, format!(\"{}\", err)),\n\n }\n\n }\n\n None => read_err(reader, \"No Obfuscation value found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 59, "score": 305209.941082387 }, { "content": "/// Attempts to read GZip compressed binary data.\n\npub fn read_gzip<R: Read>(reader: &mut EventReader<R>) -> Result<Vec<u8>> {\n\n match try!(read_binary_opt(reader)) {\n\n Some(bytes) => {\n\n let decompressed = try!(gzip::decode(&bytes));\n\n Ok(decompressed)\n\n }\n\n None => Ok(Vec::new()),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 60, "score": 297535.1168353111 }, { "content": "fn read_xml<R: Read>(reader: &mut R) -> Result<KeyFile> {\n\n let mut opt_key: Option<SecStr> = None;\n\n let mut reader = EventReader::new(reader);\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n if name.local_name == kf::KEY_FILE_TAG {\n\n opt_key = Some(try!(read_xml_key_file(&mut reader)));\n\n }\n\n }\n\n XmlEvent::EndDocument { .. } => {\n\n break;\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n match opt_key {\n\n Some(key) => {\n\n Ok(KeyFile {\n\n key: key,\n\n file_type: KeyFileType::Xml,\n\n })\n\n }\n\n None => xml::read_err(&mut reader, \"No KeyFile tag found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/kf_reader.rs", "rank": 61, "score": 297023.2976923769 }, { "content": "fn read_protected_stream_key<R: Read>(reader: &mut R) -> Result<ProtectedStreamKey> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::PROTECTED_STREAM_KEY_SIZE {\n\n let data = try!(read_bytes_32(reader));\n\n Ok(ProtectedStreamKey(data))\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::PROTECTED_STREAM_KEY_HID,\n\n expected: kdb2::PROTECTED_STREAM_KEY_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 62, "score": 296761.35767408495 }, { "content": "/// Attempts to read an optional UUID.\n\npub fn read_uuid_opt<R: Read>(reader: &mut EventReader<R>) -> Result<Option<Uuid>> {\n\n match try!(read_binary_opt(reader)) {\n\n Some(bytes) => {\n\n match Uuid::from_bytes(&bytes) {\n\n Ok(uuid) => Ok(Some(uuid)),\n\n Err(err) => read_err(reader, format!(\"UUID {}\", err)),\n\n }\n\n }\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 63, "score": 294236.2213084218 }, { "content": "fn read_auto_type<R: Read>(reader: &mut EventReader<R>, node: &mut Entry) -> Result<()> {\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::ASSOCIATION_TAG => {\n\n node.associations.push(try!(read_association(reader)));\n\n }\n\n kdb2::DATA_TRANSFER_OBFUSCATION_TAG => {\n\n node.auto_type_obfuscation = try!(xml::read_obfuscation(reader));\n\n }\n\n kdb2::DEFAULT_SEQUENCE_TAG => {\n\n node.auto_type_def_sequence = try!(xml::read_string(reader));\n\n }\n\n kdb2::ENABLED_TAG => {\n\n node.auto_type_enabled = try!(xml::read_bool(reader));\n\n }\n\n _ => {}\n\n }\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 64, "score": 292250.8122113417 }, { "content": "fn read_xml_key<R: Read>(reader: &mut EventReader<R>) -> Result<SecStr> {\n\n let mut opt_key: Option<SecStr> = None;\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n if name.local_name == kf::DATA_TAG {\n\n opt_key = Some(SecStr::new(try!(xml::read_binary(reader))));\n\n }\n\n }\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kf::KEY_TAG {\n\n break;\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n match opt_key {\n\n Some(key) => Ok(key),\n\n None => xml::read_err(reader, \"No Data tag found\"),\n\n }\n\n}\n", "file_path": "src/format/kf_reader.rs", "rank": 65, "score": 287708.82397743803 }, { "content": "fn read_xml_key_file<R: Read>(reader: &mut EventReader<R>) -> Result<SecStr> {\n\n let mut opt_key: Option<SecStr> = None;\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n if name.local_name == kf::KEY_TAG {\n\n opt_key = Some(try!(read_xml_key(reader)));\n\n } else if name.local_name == kf::META_TAG {\n\n try!(read_xml_meta(reader));\n\n }\n\n }\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kf::KEY_FILE_TAG {\n\n break;\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n match opt_key {\n\n Some(key) => Ok(key),\n\n None => xml::read_err(reader, \"No Key tag found\"),\n\n }\n\n}\n\n\n", "file_path": "src/format/kf_reader.rs", "rank": 66, "score": 284607.34671965626 }, { "content": "/// Creates a new read error result.\n\npub fn read_err<S, R, X>(reader: &mut EventReader<R>, msg: S) -> Result<X>\n\n where R: Read,\n\n S: Into<String>\n\n{\n\n let msg: String = msg.into();\n\n let pos = reader.position();\n\n let err = format!(\"{} {}\", pos, msg);\n\n Err(Error::XmlError(err))\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 67, "score": 283447.97473712696 }, { "content": "fn write_times_section<T, W>(writer: &mut EventWriter<W>, node: &T) -> Result<()>\n\n where T: Times,\n\n W: Write\n\n{\n\n try!(xml::write_start_tag(writer, kdb2::TIMES_TAG));\n\n try!(xml::write_datetime_tag(writer, kdb2::CREATION_TIME_TAG, &node.creation_time()));\n\n try!(xml::write_datetime_tag(writer, kdb2::EXPIRY_TIME_TAG, &node.expiry_time()));\n\n try!(xml::write_bool_tag(writer, kdb2::EXPIRES_TAG, node.expires()));\n\n try!(xml::write_datetime_tag(writer, kdb2::LAST_ACCESS_TIME_TAG, &node.last_accessed()));\n\n try!(xml::write_datetime_tag(writer, kdb2::LAST_MODIFICATION_TIME_TAG, &node.last_modified()));\n\n try!(xml::write_datetime_tag(writer, kdb2::LOCATION_CHANGED_TAG, &node.location_changed()));\n\n try!(xml::write_i32_tag(writer, kdb2::USAGE_COUNT_TAG, node.usage_count()));\n\n xml::write_end_tag(writer)\n\n}\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 68, "score": 282377.9530910492 }, { "content": "fn read_custom_data<R: Read>(reader: &mut EventReader<R>) -> Result<CustomDataMap> {\n\n let mut map = CustomDataMap::new();\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::ITEM_TAG => {\n\n let (key, value) = try!(read_custom_data_item(reader));\n\n map.insert(key, value);\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kdb2::CUSTOM_DATA_TAG {\n\n break;\n\n }\n\n }\n\n\n\n _ => {}\n\n }\n\n }\n\n\n\n Ok(map)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 69, "score": 276292.9401794757 }, { "content": "fn read_custom_icons<R: Read>(reader: &mut EventReader<R>) -> Result<CustomIconsMap> {\n\n let mut map = CustomIconsMap::new();\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::ICON_TAG => {\n\n let (uuid, data) = try!(read_custom_icon(reader));\n\n map.insert(uuid, data);\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kdb2::CUSTOM_ICONS_TAG {\n\n break;\n\n }\n\n }\n\n\n\n _ => {}\n\n }\n\n }\n\n\n\n Ok(map)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 70, "score": 276292.9401794757 }, { "content": "/// Attempts to write the database's XML data to the writer.\n\npub fn write<W: Write>(\n\n writer: &mut W,\n\n db: &Database,\n\n hash: &HeaderHash,\n\n key: &StreamKey\n\n) -> Result<()> {\n\n let mut cipher = salsa20::new_cipher(key);\n\n let config = EmitterConfig::new().perform_indent(true).indent_string(\"\\t\");\n\n\n\n {\n\n let mut writer = EventWriter::new_with_config(writer, config);\n\n try!(write_kee_pass_file_section(&mut writer, db, hash, &mut cipher));\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 71, "score": 276082.2848715732 }, { "content": "fn read_end_header<R: Read>(reader: &mut R) -> Result<()> {\n\n let size = try!(reader.read_u16::<LittleEndian>()) as usize;\n\n try!(read_bytes_size(reader, &size));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 72, "score": 274470.5255792378 }, { "content": "/// Attempts to write a tag that contains an optional color.\n\npub fn write_color_tag<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n tag: &str,\n\n value: &Option<Color>\n\n) -> Result<()> {\n\n match *value {\n\n Some(ref c) => write_string_tag(writer, tag, &c.to_hex_string()),\n\n None => write_null_tag(writer, tag),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 73, "score": 269334.21810601884 }, { "content": "/// Attempts to write a tag that contains binary data.\n\npub fn write_binary_tag<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n tag: &str,\n\n value: &[u8]\n\n) -> Result<()> {\n\n write_string_tag(writer, tag, &value.to_base64(STANDARD))\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 74, "score": 269306.86349590425 }, { "content": "/// Attempts to write a tag that contains a string.\n\npub fn write_string_tag<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n tag: &str,\n\n value: &String\n\n) -> Result<()> {\n\n try!(write_start_tag(writer, tag));\n\n try!(write_string(writer, value));\n\n try!(write_end_tag(writer));\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 75, "score": 269238.0433361467 }, { "content": "fn read_xml_meta<R: Read>(reader: &mut EventReader<R>) -> Result<()> {\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n if name.local_name == kf::VERSION_TAG {\n\n let version = try!(xml::read_string(reader));\n\n if version != kf::XML_KEY_FILE_VERSION {\n\n return xml::read_err(reader, \"Unsupported key file version\");\n\n }\n\n }\n\n }\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kf::META_TAG {\n\n break;\n\n }\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/format/kf_reader.rs", "rank": 76, "score": 268921.9822433189 }, { "content": "fn read_times<N, R>(reader: &mut EventReader<R>, node: &mut N) -> Result<()>\n\n where N: Times,\n\n R: Read\n\n{\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::CREATION_TIME_TAG => {\n\n node.set_creation_time(try!(xml::read_datetime(reader)));\n\n }\n\n kdb2::EXPIRY_TIME_TAG => {\n\n node.set_expiry_time(try!(xml::read_datetime(reader)));\n\n }\n\n kdb2::EXPIRES_TAG => {\n\n node.set_expires(try!(xml::read_bool(reader)));\n\n }\n\n kdb2::LAST_ACCESS_TIME_TAG => {\n\n node.set_last_accessed(try!(xml::read_datetime(reader)));\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 77, "score": 266997.21493347874 }, { "content": "fn read_bytes_32<R: Read>(reader: &mut R) -> Result<[u8; 32]> {\n\n let mut data = [0; 32];\n\n try!(reader.read(&mut data));\n\n Ok(data)\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 78, "score": 265915.1159026034 }, { "content": "fn read_bytes_16<R: Read>(reader: &mut R) -> Result<[u8; 16]> {\n\n let mut data = [0; 16];\n\n try!(reader.read(&mut data));\n\n Ok(data)\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 79, "score": 265915.1159026034 }, { "content": "/// Attempts to write a tag that contains optional boolean data.\n\npub fn write_bool_opt_tag<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n tag: &str,\n\n value: &Option<bool>\n\n) -> Result<()> {\n\n match *value {\n\n Some(false) => write_string_tag(writer, tag, &String::from(\"false\")),\n\n Some(true) => write_string_tag(writer, tag, &String::from(\"true\")),\n\n None => write_string_tag(writer, tag, &String::from(\"null\")),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 80, "score": 265751.1369571288 }, { "content": "fn read_meta<R: Read>(reader: &mut EventReader<R>, data: &mut XmlData) -> Result<()> {\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::BINARIES_TAG => {\n\n data.binaries = try!(read_binaries(reader));\n\n }\n\n kdb2::COLOR_TAG => {\n\n data.color = try!(xml::read_color_opt(reader));\n\n }\n\n kdb2::CUSTOM_DATA_TAG => {\n\n data.custom_data = try!(read_custom_data(reader));\n\n }\n\n kdb2::CUSTOM_ICONS_TAG => {\n\n data.custom_icons = try!(read_custom_icons(reader));\n\n }\n\n kdb2::DATABASE_DESCRIPTION_TAG => {\n\n data.description = try!(xml::read_string(reader));\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 81, "score": 264566.2694604661 }, { "content": "/// Attempts to read an optional custom icon UUID.\n\npub fn read_custom_icon_uuid_opt<R: Read>(reader: &mut EventReader<R>)\n\n -> Result<Option<CustomIconUuid>> {\n\n match try!(read_uuid_opt(reader)) {\n\n Some(uuid) => Ok(Some(CustomIconUuid(uuid))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/format/xml.rs", "rank": 82, "score": 264358.3954741547 }, { "content": "fn read_master_cipher<R: Read>(reader: &mut R) -> Result<MasterCipher> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::MASTER_CIPHER_SIZE {\n\n let data = try!(read_bytes_16(reader));\n\n if data == &kdb2::AES_CIPHER_ID[..] {\n\n Ok(MasterCipher::Aes256)\n\n } else {\n\n Err(Error::UnhandledMasterCipher(data))\n\n }\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::MASTER_CIPHER_HID,\n\n expected: kdb2::MASTER_CIPHER_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 83, "score": 264065.3353292806 }, { "content": "fn read_master_iv<R: Read>(reader: &mut R) -> Result<MasterIV> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::MASTER_IV_SIZE {\n\n let data = try!(read_bytes_16(reader));\n\n Ok(MasterIV(data))\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::MASTER_IV_HID,\n\n expected: kdb2::MASTER_IV_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 84, "score": 264065.3353292806 }, { "content": "fn read_master_seed<R: Read>(reader: &mut R) -> Result<MasterSeed> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::MASTER_SEED_SIZE {\n\n let data = try!(read_bytes_32(reader));\n\n Ok(MasterSeed(data))\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::MASTER_SEED_HID,\n\n expected: kdb2::MASTER_SEED_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 85, "score": 264065.3353292806 }, { "content": "fn read_stream_cipher<R: Read>(reader: &mut R) -> Result<StreamCipher> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::STREAM_CIPHER_SIZE {\n\n let data = try!(reader.read_u32::<LittleEndian>());\n\n match data {\n\n 2 => Ok(StreamCipher::Salsa20),\n\n _ => Err(Error::UnhandledStreamCipher(data)),\n\n }\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::STREAM_CIPHER_HID,\n\n expected: kdb2::STREAM_CIPHER_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 86, "score": 264065.3353292806 }, { "content": "fn read_transform_seed<R: Read>(reader: &mut R) -> Result<TransformSeed> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::TRANSFORM_SEED_SIZE {\n\n let data = try!(read_bytes_32(reader));\n\n Ok(TransformSeed(data))\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::TRANSFORM_SEED_HID,\n\n expected: kdb2::TRANSFORM_SEED_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 87, "score": 264065.3353292806 }, { "content": "fn read_transform_rounds<R: Read>(reader: &mut R) -> Result<TransformRounds> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::TRANSFORM_ROUNDS_SIZE {\n\n let data = try!(reader.read_u64::<LittleEndian>());\n\n Ok(TransformRounds(data))\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::TRANSFORM_ROUNDS_HID,\n\n expected: kdb2::TRANSFORM_ROUNDS_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 88, "score": 264065.3353292806 }, { "content": "fn read_memory_protection<R: Read>(reader: &mut EventReader<R>, data: &mut XmlData) -> Result<()> {\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::PROTECT_NOTES_TAG => {\n\n data.protect_notes = try!(xml::read_bool(reader));\n\n }\n\n kdb2::PROTECT_PASSWORD_TAG => {\n\n data.protect_password = try!(xml::read_bool(reader));\n\n }\n\n kdb2::PROTECT_TITLE_TAG => {\n\n data.protect_title = try!(xml::read_bool(reader));\n\n }\n\n kdb2::PROTECT_URL_TAG => {\n\n data.protect_url = try!(xml::read_bool(reader));\n\n }\n\n kdb2::PROTECT_USERNAME_TAG => {\n\n data.protect_username = try!(xml::read_bool(reader));\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 89, "score": 262207.7101274106 }, { "content": "fn read_association<R: Read>(reader: &mut EventReader<R>) -> Result<Association> {\n\n let mut keystroke: Option<String> = None;\n\n let mut window: Option<String> = None;\n\n loop {\n\n let event = try!(reader.next());\n\n match event {\n\n XmlEvent::StartElement { name, .. } => {\n\n match name.local_name.as_str() {\n\n kdb2::KEYSTROKE_SEQUENCE_TAG => {\n\n keystroke = try!(xml::read_string_opt(reader));\n\n }\n\n kdb2::WINDOW_TAG => {\n\n window = try!(xml::read_string_opt(reader));\n\n }\n\n _ => {}\n\n }\n\n }\n\n\n\n XmlEvent::EndElement { name, .. } => {\n\n if name.local_name == kdb2::ASSOCIATION_TAG {\n", "file_path": "src/format/kdb2_xml_reader.rs", "rank": 90, "score": 262099.60551717982 }, { "content": "fn read_enc_payload<R: Read>(reader: &mut R) -> Result<Vec<u8>> {\n\n let mut data = Vec::new();\n\n try!(reader.read_to_end(&mut data));\n\n Ok(data)\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 91, "score": 259974.2048603177 }, { "content": "fn read_stream_start_bytes<R: Read>(reader: &mut R) -> Result<StreamStartBytes> {\n\n let size = try!(reader.read_u16::<LittleEndian>());\n\n if size == kdb2::STREAM_START_BYTES_SIZE {\n\n let data = try!(read_bytes_32(reader));\n\n Ok(StreamStartBytes(data))\n\n } else {\n\n Err(Error::InvalidHeaderSize {\n\n id: kdb2::STREAM_START_BYTES_HID,\n\n expected: kdb2::STREAM_START_BYTES_SIZE,\n\n actual: size,\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 92, "score": 258540.56550432672 }, { "content": "fn read_bytes_size<R: Read>(reader: &mut R, size: &usize) -> Result<Vec<u8>> {\n\n let mut data = vec![0; *size];\n\n try!(reader.read(&mut data));\n\n Ok(data)\n\n}\n\n\n", "file_path": "src/format/kdb2_reader.rs", "rank": 93, "score": 247211.3556314872 }, { "content": "fn write_root_section<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n db: &Database,\n\n cipher: &mut Salsa20\n\n) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::ROOT_TAG));\n\n match db.group_uuid {\n\n Some(ref uuid) => {\n\n match db.groups.get(uuid) {\n\n Some(group) => {\n\n try!(write_group_section(writer, db, cipher, group));\n\n }\n\n None => {}\n\n }\n\n }\n\n None => {}\n\n }\n\n xml::write_end_tag(writer)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 94, "score": 243470.1658666847 }, { "content": "fn write_history_section<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n db: &Database,\n\n cipher: &mut Salsa20,\n\n entries: &Option<&Vec<Entry>>\n\n) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::HISTORY_TAG));\n\n match *entries {\n\n Some(list) => {\n\n for entry in list {\n\n try!(write_entry_section(writer, db, cipher, entry, EntryState::History));\n\n }\n\n }\n\n None => {}\n\n }\n\n xml::write_end_tag(writer)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 95, "score": 243456.56008294685 }, { "content": "fn write_binary_section<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n cipher: &mut Salsa20,\n\n key: &BinaryKey,\n\n value: &BinaryValue\n\n) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::BINARY_TAG));\n\n try!(xml::write_start_tag(writer, kdb2::KEY_TAG));\n\n try!(xml::write_string(writer, &key.0));\n\n try!(xml::write_end_tag(writer));\n\n\n\n match *value {\n\n BinaryValue::Plain(ref bytes) => {\n\n try!(xml::write_start_tag(writer, kdb2::VALUE_TAG));\n\n try!(xml::write_binary(writer, bytes));\n\n try!(xml::write_end_tag(writer));\n\n }\n\n BinaryValue::Protected(ref sec) => {\n\n let tag = XmlEvent::start_element(kdb2::VALUE_TAG);\n\n let tag = tag.attr(\"Protected\", \"True\");\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 96, "score": 243258.27933210036 }, { "content": "fn write_binaries_section<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n binaries: &BinariesMap\n\n) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::BINARIES_TAG));\n\n for (id, data) in binaries {\n\n let tag = XmlEvent::start_element(kdb2::BINARY_TAG);\n\n let tag = tag.attr(\"ID\", id.0.as_str());\n\n let tag = tag.attr(\"Compressed\", \"True\");\n\n try!(writer.write(tag));\n\n try!(xml::write_gzip(writer, &data));\n\n try!(xml::write_end_tag(writer));\n\n }\n\n xml::write_end_tag(writer)\n\n}\n\n\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 97, "score": 243258.2793321003 }, { "content": "fn write_group_section<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n db: &Database,\n\n cipher: &mut Salsa20,\n\n group: &Group\n\n) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::GROUP_TAG));\n\n try!(xml::write_uuid_tag(writer, kdb2::UUID_TAG, &group.uuid.0));\n\n try!(xml::write_string_tag(writer,\n\n kdb2::DEFAULT_AUTO_TYPE_SEQUENCE_TAG,\n\n &group.def_auto_type_sequence));\n\n try!(xml::write_bool_opt_tag(writer, kdb2::ENABLE_AUTO_TYPE_TAG, &group.enable_auto_type));\n\n try!(xml::write_bool_opt_tag(writer, kdb2::ENABLE_SEARCHING_TAG, &group.enable_searching));\n\n try!(xml::write_i32_tag(writer, kdb2::ICON_ID_TAG, group.icon.to_i32()));\n\n try!(xml::write_bool_tag(writer, kdb2::IS_EXPANDED_TAG, group.is_expanded));\n\n try!(xml::write_uuid_tag(writer,\n\n kdb2::LAST_TOP_VISIBLE_ENTRY_TAG,\n\n &group.last_top_visible_entry.0));\n\n try!(xml::write_string_tag(writer, kdb2::NAME_TAG, &group.name));\n\n try!(xml::write_string_tag(writer, kdb2::NOTES_TAG, &group.notes));\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 98, "score": 243258.2793321003 }, { "content": "fn write_entry_section<W: Write>(\n\n writer: &mut EventWriter<W>,\n\n db: &Database,\n\n cipher: &mut Salsa20,\n\n entry: &Entry,\n\n state: EntryState\n\n) -> Result<()> {\n\n try!(xml::write_start_tag(writer, kdb2::ENTRY_TAG));\n\n try!(xml::write_uuid_tag(writer, kdb2::UUID_TAG, &entry.uuid.0));\n\n try!(write_auto_type_section(writer, entry));\n\n try!(xml::write_color_tag(writer, kdb2::BACKGROUND_COLOR_TAG, &entry.background_color));\n\n try!(xml::write_custom_icon_uuid_tag(writer,\n\n kdb2::CUSTOM_ICON_UUID_TAG,\n\n &entry.custom_icon_uuid));\n\n try!(xml::write_color_tag(writer, kdb2::FOREGROUND_COLOR_TAG, &entry.foreground_color));\n\n try!(xml::write_i32_tag(writer, kdb2::ICON_ID_TAG, entry.icon.to_i32()));\n\n try!(xml::write_string_tag(writer, kdb2::OVERRIDE_URL_TAG, &entry.override_url));\n\n try!(xml::write_string_tag(writer, kdb2::TAGS_TAG, &entry.tags));\n\n try!(write_times_section(writer, entry));\n\n\n", "file_path": "src/format/kdb2_xml_writer.rs", "rank": 99, "score": 243204.5388523807 } ]
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 task\"\n\n );\n\n e\n\n });\n\n match result {\n\n Ok(result) => result.expect(\"Conductor shutdown error\"),\n\n Err(error) => match error.try_into_panic() {\n\n Ok(reason) => {\n\n // Resume the panic on the main task\n\n std::panic::resume_unwind(reason);\n\n }\n\n Err(error) => panic!(\"Error while joining threads during shutdown {:?}\", error),\n\n },\n\n }\n\n}\n\n\n", "file_path": "crates/aingle/src/conductor/manager/mod.rs", "rank": 0, "score": 374261.4946903194 }, { "content": "fn mapper<P: AsRef<std::path::Path>>(path: P) -> impl FnOnce(std::io::Error) -> IoError {\n\n move |e| IoError::new(e, path.as_ref().to_owned())\n\n}\n\n\n\nmacro_rules! impl_ffs {\n\n ( $( fn $name:ident (path $(, $arg:ident : $arg_ty:ty)* ) -> $output:ty ; )* ) => {\n\n\n\n $(\n\n pub async fn $name<P: Clone + AsRef<std::path::Path>>(path: P $(, $arg : $arg_ty)*) -> IoResult<$output> {\n\n\n\n #[cfg(feature = \"tokio\")]\n\n return tokio::fs::$name(path.clone() $(, $arg)*).await.map_err(mapper(path));\n\n\n\n #[cfg(not(feature = \"tokio\"))]\n\n return std::fs::$name(path.clone() $(, $arg)*).map_err(mapper(path));\n\n }\n\n )*\n\n\n\n /// Wrap dunce::canonicalize, since std::fs::canonicalize has problems for Windows\n\n /// (see https://docs.rs/dunce/1.0.1/dunce/index.html)\n", "file_path": "crates/aingle_util/src/ffs/mod.rs", "rank": 1, "score": 312047.722025729 }, { "content": "fn test_db(kind: DbKind) -> TestDb {\n\n let tmpdir = Arc::new(TempDir::new(\"aingle-test-environments\").unwrap());\n\n TestDb {\n\n db: DbWrite::new(tmpdir.path(), kind).expect(\"Couldn't create test database\"),\n\n tmpdir,\n\n }\n\n}\n\n\n", "file_path": "crates/aingle_sqlite/src/test_utils.rs", "rank": 2, "score": 307821.8375472097 }, { "content": "pub fn write_config(mut path: PathBuf, config: &ConductorConfig) -> PathBuf {\n\n path.push(\"conductor_config.yml\");\n\n std::fs::write(path.clone(), serde_yaml::to_string(&config).unwrap()).unwrap();\n\n path\n\n}\n\n\n\n#[instrument(skip(aingle, response))]\n\nasync fn check_timeout<T>(\n\n aingle: &mut Child,\n\n response: impl Future<Output = Result<T, WebsocketError>>,\n\n timeout_millis: u64,\n\n) -> T {\n\n match tokio::time::timeout(std::time::Duration::from_millis(timeout_millis), response).await {\n\n Ok(response) => response.unwrap(),\n\n Err(_) => {\n\n aingle.kill().await.unwrap();\n\n error!(\"Timeout\");\n\n panic!(\"Timed out on request after {}\", timeout_millis);\n\n }\n\n }\n", "file_path": "crates/aingle/tests/websocket.rs", "rank": 3, "score": 306197.07482553273 }, { "content": "/// Write [`ConductorConfig`] to [`CONDUCTOR_CONFIG`]\n\npub fn write_config(mut path: PathBuf, config: &ConductorConfig) -> PathBuf {\n\n path.push(CONDUCTOR_CONFIG);\n\n std::fs::write(path.clone(), serde_yaml::to_string(&config).unwrap()).unwrap();\n\n path\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/config.rs", "rank": 4, "score": 303875.4423731794 }, { "content": "/// Spawns a tokio task with given future/async block.\n\n/// Captures a new TaskCounter instance to track task count.\n\npub fn metric_task<T, E, F>(f: F) -> tokio::task::JoinHandle<Result<T, E>>\n\nwhere\n\n T: 'static + Send,\n\n E: 'static + Send + std::fmt::Debug,\n\n F: 'static + Send + std::future::Future<Output = Result<T, E>>,\n\n{\n\n let counter = MetricTaskCounter::new();\n\n tokio::task::spawn(async move {\n\n let _counter = counter;\n\n let res = f.await;\n\n if let Err(e) = &res {\n\n ghost_actor::dependencies::tracing::error!(?e, \"METRIC TASK ERROR\");\n\n }\n\n res\n\n })\n\n}\n\n\n\n/// System Info.\n\n#[derive(Debug, Clone, serde::Serialize)]\n\npub struct MetricSysInfo {\n", "file_path": "crates/kitsune_p2p/types/src/metrics.rs", "rank": 5, "score": 300540.1261896461 }, { "content": "#[cfg(feature = \"packing\")]\n\npub fn prune_path<P: AsRef<Path>>(mut path: PathBuf, subpath: P) -> UnpackingResult<PathBuf> {\n\n if path.ends_with(&subpath) {\n\n for _ in subpath.as_ref().components() {\n\n let _ = path.pop();\n\n }\n\n Ok(path)\n\n } else {\n\n Err(UnpackingError::ManifestPathSuffixMismatch(\n\n path,\n\n subpath.as_ref().to_owned(),\n\n ))\n\n }\n\n}\n", "file_path": "crates/mr_bundle/src/util.rs", "rank": 6, "score": 295631.9749589473 }, { "content": "/// Returns the path to the root config directory for all of AIngle.\n\n/// If we can get a user directory it will be an XDG compliant path\n\n/// like \"/home/peter/.config/aingle\".\n\n/// If it can't get a user directory it will default to \"/etc/aingle\".\n\npub fn config_root() -> PathBuf {\n\n project_root()\n\n .map(|dirs| dirs.config_dir().to_owned())\n\n .unwrap_or_else(|| PathBuf::from(\"/etc\").join(APPLICATION))\n\n}\n\n\n", "file_path": "crates/aingle_conductor_api/src/config/conductor/paths.rs", "rank": 7, "score": 291613.9455437464 }, { "content": "/// Returns the path to the root data directory for all of AIngle.\n\n/// If we can get a user directory it will be an XDG compliant path\n\n/// like \"/home/peter/.local/share/aingle\".\n\n/// If it can't get a user directory it will default to \"/etc/aingle\".\n\npub fn data_root() -> PathBuf {\n\n project_root()\n\n .map(|dirs| dirs.data_dir().to_owned())\n\n .unwrap_or_else(|| PathBuf::from(\"/etc\").join(APPLICATION))\n\n}\n\n\n", "file_path": "crates/aingle_conductor_api/src/config/conductor/paths.rs", "rank": 8, "score": 291613.91979948466 }, { "content": "/// Returns the path to where agent keys are stored and looked for by default.\n\n/// Something like \"~/.config/aingle/keys\".\n\npub fn keys_directory() -> PathBuf {\n\n config_root().join(KEYS_DIRECTORY)\n\n}\n\n\n\n/// Newtype for the Conductor Config file path. Has a Default.\n\n#[derive(\n\n Clone,\n\n From,\n\n Into,\n\n Debug,\n\n PartialEq,\n\n AsRef,\n\n FromStr,\n\n Display,\n\n serde::Serialize,\n\n serde::Deserialize,\n\n)]\n\n#[display(fmt = \"{}\", \"_0.display()\")]\n\npub struct ConfigFilePath(PathBuf);\n\nimpl Default for ConfigFilePath {\n\n fn default() -> Self {\n\n Self(config_root().join(PathBuf::from(CONFIG_FILENAME)))\n\n }\n\n}\n", "file_path": "crates/aingle_conductor_api/src/config/conductor/paths.rs", "rank": 9, "score": 291613.31177578075 }, { "content": "#[tracing::instrument(skip(kind))]\n\nfn handle_completed_task(kind: &TaskKind, result: ManagedTaskResult, name: String) -> TaskOutcome {\n\n use TaskOutcome::*;\n\n match kind {\n\n TaskKind::Ignore => match result {\n\n Ok(_) => LogInfo(name),\n\n Err(err) => MinorError(err, name),\n\n },\n\n TaskKind::Unrecoverable => match result {\n\n Ok(_) => LogInfo(name),\n\n Err(err) => ShutdownConductor(Box::new(err), name),\n\n },\n\n TaskKind::CellCritical(cell_id) => match result {\n\n Ok(_) => LogInfo(name),\n\n Err(err) => match &err {\n\n ManagedTaskError::Conductor(conductor_err) => match conductor_err {\n\n // If the error was due to validation failure during genesis,\n\n // just uninstall the app.\n\n ConductorError::WorkflowError(WorkflowError::GenesisFailure(_))\n\n | ConductorError::GenesisFailed { .. } => {\n\n UninstallApp(cell_id.to_owned(), Box::new(err), name)\n", "file_path": "crates/aingle/src/conductor/manager/mod.rs", "rank": 10, "score": 289784.81799857924 }, { "content": "fn test_env(kind: DbKind) -> TestEnv {\n\n let tmpdir = Arc::new(TempDir::new(\"aingle-test-environments\").unwrap());\n\n TestEnv {\n\n env: EnvWrite::test(&tmpdir, kind, test_keystore()).expect(\"Couldn't create test database\"),\n\n tmpdir,\n\n }\n\n}\n\n\n", "file_path": "crates/aingle_state/src/test_utils.rs", "rank": 11, "score": 287945.9770542277 }, { "content": "/// Update the first admin interface to use this port.\n\npub fn force_admin_port(path: PathBuf, port: u16) -> anyhow::Result<()> {\n\n let mut config = read_config(path.clone())?.expect(\"Failed to find config to force admin port\");\n\n set_admin_port(&mut config, port);\n\n write_config(path, &config);\n\n Ok(())\n\n}\n\n\n\n/// List the admin ports for each sandbox.\n\npub async fn get_admin_ports(paths: Vec<PathBuf>) -> anyhow::Result<Vec<u16>> {\n\n let live_ports = crate::save::find_ports(std::env::current_dir()?, &paths[..])?;\n\n let mut ports = Vec::new();\n\n for (p, port) in paths.into_iter().zip(live_ports) {\n\n if let Some(port) = port {\n\n ports.push(port);\n\n continue;\n\n }\n\n if let Some(config) = read_config(p)? {\n\n if let Some(ai) = config.admin_interfaces {\n\n if let Some(AdminInterfaceConfig {\n\n driver: InterfaceDriver::Websocket { port },\n", "file_path": "crates/ai_sandbox/src/ports.rs", "rank": 12, "score": 287669.84362891293 }, { "content": "/// Read the [`ConductorConfig`] from the file [`CONDUCTOR_CONFIG`] in the provided path.\n\npub fn read_config(mut path: PathBuf) -> anyhow::Result<Option<ConductorConfig>> {\n\n path.push(CONDUCTOR_CONFIG);\n\n\n\n match std::fs::read_to_string(path) {\n\n Ok(yaml) => Ok(Some(serde_yaml::from_str(&yaml)?)),\n\n Err(_) => Ok(None),\n\n }\n\n}\n", "file_path": "crates/ai_sandbox/src/config.rs", "rank": 13, "score": 279980.40494272625 }, { "content": "/// Prompts user to enter a database path\n\npub fn prompt_for_database_dir(path: &Path) -> std::io::Result<()> {\n\n let prompt = format!(\n\n \"There is no database at the path specified ({})\\nWould you like to create one now?\",\n\n path.display()\n\n );\n\n if ask_yn(prompt, Some(true))? {\n\n std::fs::create_dir_all(path)?;\n\n Ok(())\n\n } else {\n\n Err(std::io::Error::new(\n\n std::io::ErrorKind::Other,\n\n \"Cannot continue without database.\",\n\n ))\n\n }\n\n}\n\n\n", "file_path": "crates/aingle/src/conductor/interactive.rs", "rank": 14, "score": 278393.8608521754 }, { "content": "/// Create a new default [`ConductorConfig`] with environment path\n\n/// and keystore all in the same directory.\n\npub fn create_config(environment_path: PathBuf) -> ConductorConfig {\n\n let mut conductor_config = ConductorConfig {\n\n environment_path: environment_path.clone().into(),\n\n ..Default::default()\n\n };\n\n let mut keystore_path = environment_path;\n\n keystore_path.push(\"keystore\");\n\n conductor_config.keystore_path = Some(keystore_path);\n\n conductor_config\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/config.rs", "rank": 15, "score": 276526.8781287039 }, { "content": "/// Parse a happ bundle.\n\n/// If paths are directories then each directory\n\n/// will be searched for the first file that matches\n\n/// `*.saf`.\n\npub fn parse_happ(happ: Option<PathBuf>) -> anyhow::Result<PathBuf> {\n\n let mut happ = happ.unwrap_or(std::env::current_dir()?);\n\n if happ.is_dir() {\n\n let file_path = search_for_happ(&happ)?;\n\n happ = file_path;\n\n }\n\n ensure!(\n\n happ.file_name()\n\n .map(|f| f.to_string_lossy().ends_with(\".happ\"))\n\n .unwrap_or(false),\n\n \"File {} is not a valid happ file name: (e.g. my-happ.happ)\",\n\n happ.display()\n\n );\n\n Ok(happ)\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/bundles.rs", "rank": 16, "score": 269072.1889182026 }, { "content": "/// Save all sandboxes to the `.ai` file in the `ai_dir` directory.\n\npub fn save(mut ai_dir: PathBuf, paths: Vec<PathBuf>) -> anyhow::Result<()> {\n\n use std::io::Write;\n\n std::fs::create_dir_all(&ai_dir)?;\n\n ai_dir.push(\".ai\");\n\n let mut file = std::fs::OpenOptions::new()\n\n .append(true)\n\n .create(true)\n\n .open(ai_dir)?;\n\n\n\n for path in paths {\n\n writeln!(file, \"{}\", path.display())?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/save.rs", "rank": 17, "score": 263803.4542013805 }, { "content": "/// Helper to get a [`Store`] from an [`EnvRead`].\n\npub fn fresh_store_test<F, R>(env: &EnvRead, f: F) -> R\n\nwhere\n\n F: FnOnce(&dyn Store) -> R,\n\n{\n\n fresh_reader_test!(env, |txn| {\n\n let store = Txn::from(&txn);\n\n f(&store)\n\n })\n\n}\n\n\n", "file_path": "crates/aingle_state/src/test_utils.rs", "rank": 18, "score": 263029.63160159497 }, { "content": "/// Load sandbox paths from the `.ai` file.\n\npub fn load(mut ai_dir: PathBuf) -> anyhow::Result<Vec<PathBuf>> {\n\n let mut paths = Vec::new();\n\n ai_dir.push(\".ai\");\n\n if ai_dir.exists() {\n\n let existing = std::fs::read_to_string(ai_dir)?;\n\n for sandbox in existing.lines() {\n\n let path = PathBuf::from(sandbox);\n\n let mut config_path = path.clone();\n\n config_path.push(CONDUCTOR_CONFIG);\n\n if config_path.exists() {\n\n paths.push(path);\n\n } else {\n\n tracing::error!(\"Failed to load path {} from existing .ai\", path.display());\n\n }\n\n }\n\n }\n\n Ok(paths)\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/save.rs", "rank": 19, "score": 262795.6579136825 }, { "content": "/// Function to help avoid needing to specify types.\n\npub fn print_stmts_test<E, F, R>(env: E, f: F) -> R\n\nwhere\n\n E: Into<EnvRead>,\n\n F: FnOnce(Transaction) -> R,\n\n{\n\n aingle_sqlite::print_stmts_test!(&env.into(), f)\n\n}\n\n\n", "file_path": "crates/aingle_state/src/test_utils.rs", "rank": 20, "score": 259490.46387548454 }, { "content": "/// Function to help avoid needing to specify types.\n\npub fn fresh_reader_test<E, F, R>(env: E, f: F) -> R\n\nwhere\n\n E: Into<EnvRead>,\n\n F: FnOnce(Transaction) -> R,\n\n{\n\n fresh_reader_test!(&env.into(), f)\n\n}\n\n\n", "file_path": "crates/aingle_state/src/test_utils.rs", "rank": 21, "score": 259490.46387548454 }, { "content": "/// if result.is_none() -- we are done, end the loop for now\n\n/// if result.is_some() -- we got more items to process\n\nfn batch_check_end(kind: DbKind) -> Option<Vec<InOpBatchEntry>> {\n\n let mut lock = IN_OP_BATCH.lock();\n\n let batch = lock.entry(kind).or_insert_with(InOpBatch::default);\n\n assert!(batch.is_running);\n\n let out: Vec<InOpBatchEntry> = batch.pending.drain(..).collect();\n\n if out.is_empty() {\n\n // pending was empty, we can end the loop for now\n\n batch.is_running = false;\n\n None\n\n } else {\n\n // we have some more pending, continue the running loop\n\n Some(out)\n\n }\n\n}\n\n\n", "file_path": "crates/aingle/src/core/workflow/incoming_sgd_ops_workflow.rs", "rank": 22, "score": 259477.33872856107 }, { "content": "/// Decode message-pack data from given reader into an owned item.\n\n/// You may wish to first wrap your reader in a BufReader.\n\npub fn rmp_decode<R, D>(r: &mut R) -> Result<D, std::io::Error>\n\nwhere\n\n R: std::io::Read,\n\n for<'de> D: Sized + serde::Deserialize<'de>,\n\n{\n\n let mut de = rmp_serde::decode::Deserializer::new(r);\n\n D::deserialize(&mut de).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))\n\n}\n\n\n", "file_path": "crates/kitsune_p2p/types/src/codec.rs", "rank": 23, "score": 257583.3649002646 }, { "content": "/// Parse a list of safs.\n\n/// If paths are directories then each directory\n\n/// will be searched for the first file that matches\n\n/// `*.saf`.\n\npub fn parse_safs(mut safs: Vec<PathBuf>) -> anyhow::Result<Vec<PathBuf>> {\n\n if safs.is_empty() {\n\n safs.push(std::env::current_dir()?);\n\n }\n\n for saf in safs.iter_mut() {\n\n if saf.is_dir() {\n\n let file_path = search_for_saf(&saf)?;\n\n *saf = file_path;\n\n }\n\n ensure!(\n\n saf.file_name()\n\n .map(|f| f.to_string_lossy().ends_with(\".saf\"))\n\n .unwrap_or(false),\n\n \"File {} is not a valid saf file name: (e.g. my-saf.saf)\",\n\n saf.display()\n\n );\n\n }\n\n Ok(safs)\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/bundles.rs", "rank": 24, "score": 256889.21282535576 }, { "content": "/// Promote a tx2 transport adapter to a tx2 transport frontend.\n\npub fn tx2_pool_promote(\n\n adapter: AdapterFactory,\n\n tuning_params: KitsuneP2pTuningParams,\n\n) -> EpFactory {\n\n Arc::new(PromoteFactory {\n\n adapter,\n\n tuning_params,\n\n })\n\n}\n\n\n\n// -- private -- //\n\n\n", "file_path": "crates/kitsune_p2p/types/src/tx2/tx2_pool_promote.rs", "rank": 25, "score": 256521.1839621713 }, { "content": "/// Same as load ports but only returns ports for paths passed in.\n\npub fn find_ports(ai_dir: PathBuf, paths: &[PathBuf]) -> anyhow::Result<Vec<Option<u16>>> {\n\n let mut ports = Vec::new();\n\n let all_paths = load(ai_dir.clone())?;\n\n for path in paths {\n\n let index = all_paths.iter().position(|p| p == path);\n\n match index {\n\n Some(i) => {\n\n let mut ai = ai_dir.clone();\n\n ai.push(format!(\".ai_live_{}\", i));\n\n if ai.exists() {\n\n let live = std::fs::read_to_string(ai)?;\n\n let p = live.lines().next().and_then(|l| l.parse::<u16>().ok());\n\n ports.push(p)\n\n } else {\n\n ports.push(None);\n\n }\n\n }\n\n None => ports.push(None),\n\n }\n\n }\n", "file_path": "crates/ai_sandbox/src/save.rs", "rank": 26, "score": 256205.23309439793 }, { "content": "/// Fetch an Entry from a DB by its hash. Requires no joins.\n\npub fn get_entry_from_db(\n\n txn: &Transaction,\n\n entry_hash: &EntryHash,\n\n) -> StateQueryResult<Option<Entry>> {\n\n let entry = txn.query_row_named(\n\n \"\n\n SELECT Entry.blob AS entry_blob FROM Entry\n\n WHERE hash = :entry_hash\n\n \",\n\n named_params! {\n\n \":entry_hash\": entry_hash,\n\n },\n\n |row| {\n\n Ok(from_blob::<Entry>(\n\n row.get(row.column_index(\"entry_blob\")?)?,\n\n ))\n\n },\n\n );\n\n if let Err(aingle_sqlite::rusqlite::Error::QueryReturnedNoRows) = &entry {\n\n Ok(None)\n\n } else {\n\n Ok(Some(entry??))\n\n }\n\n}\n", "file_path": "crates/aingle_state/src/query.rs", "rank": 27, "score": 255330.20196600328 }, { "content": "/// Create a [TestDb] of [DbKind::Cell], backed by a temp directory.\n\npub fn test_cell_db() -> TestDb {\n\n let cell_id = fake_cell_id(1);\n\n test_db(DbKind::Cell(cell_id))\n\n}\n\n\n", "file_path": "crates/aingle_sqlite/src/test_utils.rs", "rank": 28, "score": 254512.74042474545 }, { "content": "/// Query the p2p_metrics database in a variety of ways\n\npub fn query_metrics(\n\n txn: &mut Transaction,\n\n query: MetricQuery,\n\n) -> DatabaseResult<MetricQueryAnswer> {\n\n Ok(match query {\n\n MetricQuery::LastSync { agent } => {\n\n let agent_bytes: &[u8] = agent.as_ref();\n\n let timestamp: Option<i64> = txn.query_row(\n\n sql_p2p_metrics::QUERY_LAST_SYNC,\n\n named_params! {\n\n \":agent\": agent_bytes,\n\n \":kind\": MetricKind::QuickGossip.to_string(),\n\n },\n\n |row| row.get(0),\n\n )?;\n\n let time = match timestamp {\n\n Some(t) => Some(time_from_micros(t)?),\n\n None => None,\n\n };\n\n MetricQueryAnswer::LastSync(time)\n", "file_path": "crates/aingle_sqlite/src/db/p2p_metrics.rs", "rank": 29, "score": 252072.9409372048 }, { "content": "/// Run a blocking thread on `TOKIO` with a timeout.\n\npub fn block_on<F>(\n\n f: F,\n\n timeout: std::time::Duration,\n\n) -> Result<F::Output, tokio::time::error::Elapsed>\n\nwhere\n\n F: futures::future::Future,\n\n{\n\n block_on_given(tokio::time::timeout(timeout, f), &TOKIO)\n\n}\n\n\n", "file_path": "crates/aingle_util/src/tokio_helper.rs", "rank": 30, "score": 250596.0987874165 }, { "content": "/// Use the `git` shell command to detect changed files in the given directory between the given revisions.\n\n///\n\n/// Inspired by: https://github.com/sunng87/cargo-release/blob/master/src/git.rs\n\nfn changed_files(dir: &Path, from_rev: &str, to_rev: &str) -> Fallible<Vec<PathBuf>> {\n\n use bstr::ByteSlice;\n\n\n\n let output = Command::new(\"git\")\n\n .arg(\"diff\")\n\n .arg(&format!(\"{}..{}\", from_rev, to_rev))\n\n .arg(\"--name-only\")\n\n .arg(\"--exit-code\")\n\n .arg(\".\")\n\n .current_dir(dir)\n\n .output()?;\n\n\n\n match output.status.code() {\n\n Some(0) => Ok(Vec::new()),\n\n Some(1) => {\n\n let paths = output\n\n .stdout\n\n .lines()\n\n .map(|l| dir.join(l.to_path_lossy()))\n\n .collect();\n\n Ok(paths)\n\n }\n\n code => Err(anyhow!(\"git exited with code: {:?}\", code)),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub(crate) mod tests;\n", "file_path": "crates/release-automation/src/crate_selection/mod.rs", "rank": 31, "score": 250171.59750797448 }, { "content": "/// Record a p2p metric datum\n\npub fn put_metric_datum(\n\n txn: &mut Transaction,\n\n agent: Arc<KitsuneAgent>,\n\n metric: MetricKind,\n\n timestamp: std::time::SystemTime,\n\n) -> DatabaseResult<()> {\n\n let agent_bytes: &[u8] = agent.as_ref();\n\n txn.execute(\n\n sql_p2p_metrics::INSERT,\n\n named_params! {\n\n \":agent\": agent_bytes,\n\n \":kind\": metric.to_string(),\n\n \":moment\": time_to_micros(timestamp)?\n\n },\n\n )?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/aingle_sqlite/src/db/p2p_metrics.rs", "rank": 32, "score": 248938.20839346002 }, { "content": "/// Print out the sandboxes contained in the `.ai` file.\n\npub fn list(ai_dir: PathBuf, verbose: usize) -> anyhow::Result<()> {\n\n let out = load(ai_dir)?.into_iter().enumerate().try_fold(\n\n \"\\nSandboxes contained in `.ai`\\n\".to_string(),\n\n |out, (i, path)| {\n\n let r = match verbose {\n\n 0 => format!(\"{}{}: {}\\n\", out, i, path.display()),\n\n _ => {\n\n let config = config::read_config(path.clone())?;\n\n format!(\n\n \"{}{}: {}\\nConductor Config:\\n{:?}\\n\",\n\n out,\n\n i,\n\n path.display(),\n\n config\n\n )\n\n }\n\n };\n\n anyhow::Result::<_, anyhow::Error>::Ok(r)\n\n },\n\n )?;\n", "file_path": "crates/ai_sandbox/src/save.rs", "rank": 33, "score": 245907.61010111385 }, { "content": "#[tracing::instrument(skip(txn))]\n\npub fn dump_db(txn: &Transaction) {\n\n let dump = |mut stmt: Statement| {\n\n let mut rows = stmt.query([]).unwrap();\n\n while let Some(row) = rows.next().unwrap() {\n\n for column in row.column_names() {\n\n let row = row.get_ref_unwrap(column);\n\n match row {\n\n aingle_sqlite::rusqlite::types::ValueRef::Null\n\n | aingle_sqlite::rusqlite::types::ValueRef::Integer(_)\n\n | aingle_sqlite::rusqlite::types::ValueRef::Real(_) => {\n\n tracing::debug!(?column, ?row);\n\n }\n\n aingle_sqlite::rusqlite::types::ValueRef::Text(text) => {\n\n tracing::debug!(?column, row = ?String::from_utf8_lossy(text));\n\n }\n\n aingle_sqlite::rusqlite::types::ValueRef::Blob(blob) => {\n\n let blob = base64::encode_config(blob, base64::URL_SAFE_NO_PAD);\n\n tracing::debug!(\"column: {:?} row:{}\", column, blob);\n\n }\n\n }\n", "file_path": "crates/aingle_state/src/test_utils.rs", "rank": 34, "score": 239917.49232231482 }, { "content": "/// For each registered setup, if it has a lockfile, return the port of the running conductor,\n\n/// otherwise return None.\n\n/// The resulting Vec has the same number of elements as lines in the `.ai` file\n\npub fn load_ports(ai_dir: PathBuf) -> anyhow::Result<Vec<Option<u16>>> {\n\n let mut ports = Vec::new();\n\n let paths = load(ai_dir.clone())?;\n\n for (i, _) in paths.into_iter().enumerate() {\n\n let mut ai = ai_dir.clone();\n\n ai.push(format!(\".ai_live_{}\", i));\n\n if ai.exists() {\n\n let live = std::fs::read_to_string(ai)?;\n\n let p = live.lines().next().and_then(|l| l.parse::<u16>().ok());\n\n ports.push(p)\n\n } else {\n\n ports.push(None);\n\n }\n\n }\n\n Ok(ports)\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/save.rs", "rank": 35, "score": 236847.20057626878 }, { "content": "/// Create an Admin Interface, which only receives AdminRequest messages\n\n/// from the external client\n\npub fn spawn_admin_interface_task<A: InterfaceApi>(\n\n handle: ListenerHandle,\n\n listener: impl futures::stream::Stream<Item = ListenerItem> + Send + 'static,\n\n api: A,\n\n mut stop_rx: StopReceiver,\n\n) -> InterfaceResult<ManagedTaskHandle> {\n\n Ok(tokio::task::spawn(async move {\n\n // Task that will kill the listener and all child connections.\n\n tokio::task::spawn(\n\n handle.close_on(async move { stop_rx.recv().await.map(|_| true).unwrap_or(true) }),\n\n );\n\n\n\n let num_connections = Arc::new(AtomicIsize::new(0));\n\n futures::pin_mut!(listener);\n\n // establish a new connection to a client\n\n while let Some(connection) = listener.next().await {\n\n match connection {\n\n Ok((_, rx_from_iface)) => {\n\n if num_connections.fetch_add(1, Ordering::Relaxed) > MAX_CONNECTIONS {\n\n // Max connections so drop this connection\n", "file_path": "crates/aingle/src/conductor/interface/websocket.rs", "rank": 36, "score": 234035.3828406685 }, { "content": "/// Remove sandboxes by their index in the file.\n\n/// You can get the index by calling [`load`].\n\n/// If no sandboxes are passed in then all are deleted.\n\n/// If all sandboxes are deleted the `.ai` file will be removed.\n\npub fn clean(mut ai_dir: PathBuf, sandboxes: Vec<usize>) -> anyhow::Result<()> {\n\n let existing = load(ai_dir.clone())?;\n\n let sandboxes_len = sandboxes.len();\n\n let to_remove: Vec<_> = if sandboxes.is_empty() {\n\n existing.iter().collect()\n\n } else {\n\n sandboxes\n\n .into_iter()\n\n .filter_map(|i| existing.get(i))\n\n .collect()\n\n };\n\n let to_remove_len = to_remove.len();\n\n for p in to_remove {\n\n if p.exists() && p.is_dir() {\n\n if let Err(e) = std::fs::remove_dir_all(p) {\n\n tracing::error!(\"Failed to remove {} because {:?}\", p.display(), e);\n\n }\n\n }\n\n }\n\n if sandboxes_len == 0 || sandboxes_len == to_remove_len {\n", "file_path": "crates/ai_sandbox/src/save.rs", "rank": 37, "score": 233319.31784215226 }, { "content": "fn bundle_path_to_dir(path: &Path, extension: &'static str) -> AinBundleResult<PathBuf> {\n\n let bad_ext_err = || AinBundleError::FileExtensionMissing(extension, path.to_owned());\n\n let ext = path.extension().ok_or_else(bad_ext_err)?;\n\n if ext != extension {\n\n return Err(bad_ext_err());\n\n }\n\n let stem = path\n\n .file_stem()\n\n .expect(\"A file with an extension also has a stem\");\n\n\n\n Ok(path\n\n .parent()\n\n .expect(\"file path should have parent\")\n\n .join(stem))\n\n}\n\n\n\n/// Pack a directory containing a SAF manifest into a SafBundle, returning\n\n/// the path to which the bundle file was written\n\npub async fn pack<M: Manifest>(\n\n dir_path: &std::path::Path,\n", "file_path": "crates/ai_bundle/src/packing.rs", "rank": 38, "score": 231874.69341716834 }, { "content": "struct TaskManager {\n\n stream: FuturesUnordered<ManagedTaskAdd>,\n\n}\n\n\n\nimpl TaskManager {\n\n fn new() -> Self {\n\n let stream = FuturesUnordered::new();\n\n TaskManager { stream }\n\n }\n\n}\n\n\n\npub(crate) fn spawn_task_manager(\n\n handle: ConductorHandle,\n\n) -> (mpsc::Sender<ManagedTaskAdd>, TaskManagerRunHandle) {\n\n let (send, recv) = mpsc::channel(CHANNEL_SIZE);\n\n (send, tokio::spawn(run(handle, recv)))\n\n}\n\n\n\n/// A super pessimistic task that is just waiting to die\n\n/// but gets to live as long as the process\n", "file_path": "crates/aingle/src/conductor/manager/mod.rs", "rank": 39, "score": 228041.1024902071 }, { "content": "#[deprecated = \"Raising visibility into a change that needs to happen after `use_existing` is implemented\"]\n\npub fn we_must_remember_to_rework_cell_panic_handling_after_implementing_use_existing_cell_resolution(\n\n) {\n\n}\n\n\n\n/// The result of running Cell resolution\n\n// TODO: rework, make fields private\n\n#[allow(missing_docs)]\n\n#[derive(PartialEq, Eq, Debug)]\n\npub struct CellSlotResolution {\n\n pub agent: AgentPubKey,\n\n pub safs_to_register: Vec<(SafFile, Option<MembraneProof>)>,\n\n pub slots: Vec<(SlotId, AppSlot)>,\n\n}\n\n\n\n#[allow(missing_docs)]\n\nimpl CellSlotResolution {\n\n pub fn new(agent: AgentPubKey) -> Self {\n\n Self {\n\n agent,\n\n safs_to_register: Default::default(),\n", "file_path": "crates/aingle_types/src/app/app_bundle.rs", "rank": 40, "score": 227464.2947850574 }, { "content": "fn search_for_happ(happ: &Path) -> anyhow::Result<PathBuf> {\n\n let dir = WalkDir::new(happ)\n\n .max_depth(1)\n\n .into_iter()\n\n .filter_map(|e| e.ok())\n\n .filter(|d| d.file_type().is_file())\n\n .find(|f| f.file_name().to_string_lossy().ends_with(\".happ\"))\n\n .map(|f| f.into_path());\n\n match dir {\n\n Some(dir) => Ok(dir),\n\n None => {\n\n bail!(\n\n \"Could not find a happ file (e.g. my-happ.happ) in directory {}\",\n\n happ.display()\n\n )\n\n }\n\n }\n\n}\n", "file_path": "crates/ai_sandbox/src/bundles.rs", "rank": 41, "score": 226823.24457154382 }, { "content": "// TODO: Look for multiple safs\n\nfn search_for_saf(saf: &Path) -> anyhow::Result<PathBuf> {\n\n let dir: Vec<_> = WalkDir::new(saf)\n\n .max_depth(1)\n\n .into_iter()\n\n .filter_map(|e| e.ok())\n\n .filter(|d| d.file_type().is_file())\n\n .filter(|f| f.file_name().to_string_lossy().ends_with(\".saf\"))\n\n .map(|f| f.into_path())\n\n .collect();\n\n if dir.len() != 1 {\n\n bail!(\n\n \"Could not find a SAF file (e.g. my-saf.saf) in directory {}\",\n\n saf.display()\n\n )\n\n }\n\n Ok(dir.into_iter().next().expect(\"Safe due to check above\"))\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/bundles.rs", "rank": 42, "score": 226823.24457154382 }, { "content": "#[allow(clippy::let_and_return)]\n\npub fn mdns_listen(service_type: String) -> impl Stream<Item = Result<MdnsResponse, MdnsError>> {\n\n //let service_name = format!(\"{}.local\", AI_SERVICE_TYPE);\n\n let svc_type = format!(\"_{}{}.local\", service_type, AI_SERVICE_PROTOCOL);\n\n //println!(\"MDNS query for service type '{}'\", svc_type);\n\n let query = mdns::discover::all(svc_type, Duration::from_secs(QUERY_INTERVAL_SEC))\n\n .expect(\"mdns Discover failed\");\n\n // Get Mdns Response stream\n\n let response_stream = query.listen();\n\n // Change it into a MdnsResponse stream\n\n let mdns_stream = response_stream\n\n // Filtering out Empty responses\n\n .filter(move |res| {\n\n match res {\n\n Ok(response) => !response.is_empty() && response.ip_addr().is_some(),\n\n Err(_) => true, // Keep errors\n\n }\n\n })\n\n .map(|maybe_response| {\n\n if let Err(e) = maybe_response {\n\n return Err(MdnsError::Mdns(e));\n", "file_path": "crates/kitsune_p2p/mdns/src/lib.rs", "rank": 43, "score": 226322.64796032454 }, { "content": "/// Run a blocking thread on `TOKIO`.\n\npub fn block_forever_on<F>(f: F) -> F::Output\n\nwhere\n\n F: futures::future::Future,\n\n{\n\n block_on_given(f, &TOKIO)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[tokio::test(flavor = \"multi_thread\")]\n\n async fn block_on_works() {\n\n block_forever_on(async { println!(\"stdio can block\") });\n\n assert_eq!(1, super::block_forever_on(async { 1 }));\n\n\n\n let r = \"1\";\n\n let test1 = super::block_forever_on(async { r.to_string() });\n\n assert_eq!(\"1\", &test1);\n\n\n", "file_path": "crates/aingle_util/src/tokio_helper.rs", "rank": 44, "score": 223884.31292863053 }, { "content": "/// Returns every entry hash in a vector from the root of an anchor.\n\n/// Hashes are sorted in the same way that paths sort children.\n\npub fn list_anchor_type_addresses() -> ExternResult<Vec<EntryHash>> {\n\n let links = Path::from(ROOT)\n\n .children()?\n\n .into_inner()\n\n .into_iter()\n\n .map(|link| link.target)\n\n .collect();\n\n Ok(links)\n\n}\n\n\n", "file_path": "crates/adk/src/hash_path/anchor.rs", "rank": 45, "score": 222003.50240842492 }, { "content": "pub fn time_to_micros(t: SystemTime) -> DatabaseResult<i64> {\n\n t.duration_since(std::time::UNIX_EPOCH)\n\n .map_err(|e| DatabaseError::Other(e.into()))?\n\n .as_micros()\n\n .try_into()\n\n .map_err(|e: TryFromIntError| DatabaseError::Other(e.into()))\n\n}\n\n\n", "file_path": "crates/aingle_sqlite/src/db/p2p_metrics.rs", "rank": 46, "score": 221302.48583768235 }, { "content": "fn releaseworkspace_path_only_fmt(\n\n ws: &&ReleaseWorkspace<'_>,\n\n f: &mut fmt::Formatter,\n\n) -> fmt::Result {\n\n write!(f, \"{:?}\", &ws.root_path)\n\n}\n\n\n\n#[derive(custom_debug::Debug)]\n\npub(crate) struct Crate<'a> {\n\n package: CargoPackage,\n\n changelog: Option<CrateChangelog<'a>>,\n\n #[debug(with = \"releaseworkspace_path_only_fmt\")]\n\n workspace: &'a ReleaseWorkspace<'a>,\n\n #[debug(skip)]\n\n dependencies_in_workspace: OnceCell<LinkedHashSet<cargo::core::Dependency>>,\n\n}\n\n\n\nimpl<'a> Crate<'a> {\n\n /// Instantiate a new Crate with the given CargoPackage.\n\n pub(crate) fn with_cargo_package(\n", "file_path": "crates/release-automation/src/crate_selection/mod.rs", "rank": 47, "score": 219937.32648836417 }, { "content": "pub fn fill_db(env: &EnvWrite, op: SgdOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, false).unwrap();\n\n set_validation_status(txn, hash.clone(), ValidationStatus::Valid).unwrap();\n\n set_when_integrated(txn, hash, timestamp::now()).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/aingle_cascade/src/test_utils.rs", "rank": 48, "score": 218664.91509769196 }, { "content": "pub fn time_from_micros(micros: i64) -> DatabaseResult<SystemTime> {\n\n std::time::UNIX_EPOCH\n\n .checked_add(Duration::from_micros(micros as u64))\n\n .ok_or_else(|| {\n\n DatabaseError::Other(anyhow::anyhow!(\n\n \"Got invalid i64 microsecond timestamp: {}\",\n\n micros\n\n ))\n\n })\n\n}\n\n\n", "file_path": "crates/aingle_sqlite/src/db/p2p_metrics.rs", "rank": 49, "score": 218664.91509769196 }, { "content": "pub fn fill_db_as_author(env: &EnvWrite, op: SgdOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n insert_op(txn, op, true).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n\n#[async_trait::async_trait]\n\nimpl AIngleP2pCellT for MockNetwork {\n\n async fn get_validation_package(\n\n &mut self,\n\n request_from: AgentPubKey,\n\n header_hash: HeaderHash,\n\n ) -> actor::AIngleP2pResult<ValidationPackageResponse> {\n\n self.0\n\n .lock()\n\n .await\n", "file_path": "crates/aingle_cascade/src/test_utils.rs", "rank": 50, "score": 216112.49729880205 }, { "content": "pub fn fill_db_rejected(env: &EnvWrite, op: SgdOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, false).unwrap();\n\n set_validation_status(txn, hash.clone(), ValidationStatus::Rejected).unwrap();\n\n set_when_integrated(txn, hash, timestamp::now()).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/aingle_cascade/src/test_utils.rs", "rank": 51, "score": 216112.49729880205 }, { "content": "pub fn fill_db_pending(env: &EnvWrite, op: SgdOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, false).unwrap();\n\n set_validation_status(txn, hash, ValidationStatus::Valid).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/aingle_cascade/src/test_utils.rs", "rank": 52, "score": 216112.49729880205 }, { "content": "fn dir_to_bundle_path(dir_path: &Path, name: String, extension: &str) -> AinBundleResult<PathBuf> {\n\n Ok(dir_path.join(format!(\"{}.{}\", name, extension)))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use aingle_types::prelude::SafManifest;\n\n use mr_bundle::error::{MrBundleError, UnpackingError};\n\n\n\n use super::*;\n\n\n\n #[tokio::test(flavor = \"multi_thread\")]\n\n async fn test_roundtrip() {\n\n let tmpdir = tempdir::TempDir::new(\"ai-bundle-test\").unwrap();\n\n let dir = tmpdir.path().join(\"test-saf\");\n\n std::fs::create_dir(&dir).unwrap();\n\n\n", "file_path": "crates/ai_bundle/src/packing.rs", "rank": 53, "score": 213293.0138254671 }, { "content": "/// Old version of aingle that anchors was designed for had two part link tags but now link\n\n/// tags are a single array of bytes, so to get an external interface that is somewhat backwards\n\n/// compatible we need to rebuild the anchors from the paths serialized into the links and then\n\n/// return them.\n\npub fn list_anchor_tags(anchor_type: String) -> ExternResult<Vec<String>> {\n\n let path: Path = (&Anchor {\n\n anchor_type,\n\n anchor_text: None,\n\n })\n\n .into();\n\n path.ensure()?;\n\n let hopefully_anchor_tags: Result<Vec<String>, SerializedBytesError> = path\n\n .children()?\n\n .into_inner()\n\n .into_iter()\n\n .map(|link| match Path::try_from(&link.tag) {\n\n Ok(path) => match Anchor::try_from(&path) {\n\n Ok(anchor) => match anchor.anchor_text {\n\n Some(text) => Ok(text),\n\n None => Err(SerializedBytesError::Deserialize(\n\n \"missing anchor text\".into(),\n\n )),\n\n },\n\n Err(e) => Err(e),\n\n },\n\n Err(e) => Err(e),\n\n })\n\n .collect();\n\n let mut anchor_tags = hopefully_anchor_tags?;\n\n anchor_tags.sort();\n\n anchor_tags.dedup();\n\n Ok(anchor_tags)\n\n}\n\n\n", "file_path": "crates/adk/src/hash_path/anchor.rs", "rank": 54, "score": 213061.0084380347 }, { "content": "/// Attempt to get an anchor by its hash.\n\n/// Returns None if the hash doesn't point to an anchor.\n\n/// We can't do anything fancy like ensure the anchor if not exists because we only have a hash.\n\npub fn get_anchor(anchor_address: EntryHash) -> ExternResult<Option<Anchor>> {\n\n Ok(\n\n match crate::prelude::get(anchor_address, GetOptions::content())?.and_then(|el| el.into()) {\n\n Some(Entry::App(eb)) => {\n\n let path = Path::try_from(SerializedBytes::from(eb))?;\n\n Some(Anchor::try_from(&path)?)\n\n }\n\n _ => None,\n\n },\n\n )\n\n}\n\n\n", "file_path": "crates/adk/src/hash_path/anchor.rs", "rank": 55, "score": 213055.58903738216 }, { "content": "pub fn trace(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: TraceMsg,\n\n) -> Result<(), WasmError> {\n\n // Avoid dialing out to the environment on every trace.\n\n let wasm_log = Lazy::new(|| {\n\n std::env::var(\"WASM_LOG\").unwrap_or_else(|_| \"[wasm_trace]=debug\".to_string())\n\n });\n\n let collector = tracing_subscriber::fmt()\n\n .with_env_filter(tracing_subscriber::EnvFilter::new((*wasm_log).clone()))\n\n .with_target(false)\n\n .finish();\n\n tracing::subscriber::with_default(collector, || wasm_trace(input));\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/trace.rs", "rank": 56, "score": 212672.6985814534 }, { "content": "pub fn sign(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: Sign,\n\n) -> Result<Signature, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n call_context.host_access.keystore().sign(input).await\n\n })\n\n .map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n\n use ::fixt::prelude::*;\n\n use adk::prelude::test_utils::fake_agent_pubkey_1;\n\n use adk::prelude::test_utils::fake_agent_pubkey_2;\n\n use adk::prelude::*;\n\n use aingle_state::host_fn_workspace::HostFnWorkspace;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/sign.rs", "rank": 57, "score": 212672.6985814534 }, { "content": "pub fn schedule(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: core::time::Duration,\n\n) -> Result<(), WasmError> {\n\n unimplemented!()\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/schedule.rs", "rank": 58, "score": 212672.6985814534 }, { "content": "pub fn sleep(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: core::time::Duration,\n\n) -> Result<(), WasmError> {\n\n unimplemented!()\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/sleep.rs", "rank": 59, "score": 212672.6985814534 }, { "content": "pub fn call(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n call: Call,\n\n) -> Result<ZomeCallResponse, WasmError> {\n\n // Get the conductor handle\n\n let host_access = call_context.host_access();\n\n let conductor_handle = host_access.call_zome_handle();\n\n let workspace = host_access.workspace();\n\n\n\n // Get the cell id if it's not passed in\n\n let cell_id = call\n\n .to_cell\n\n .unwrap_or_else(|| conductor_handle.cell_id().clone());\n\n\n\n let zome_name = call.zome_name.clone();\n\n\n\n // Create the invocation for this call\n\n let invocation = ZomeCall {\n\n cell_id,\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/call.rs", "rank": 60, "score": 212672.6985814534 }, { "content": "pub fn version(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<ZomeApiVersion, WasmError> {\n\n unreachable!();\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/version.rs", "rank": 61, "score": 212672.6985814534 }, { "content": "pub fn unreachable(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<(), WasmError> {\n\n unreachable!();\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/unreachable.rs", "rank": 62, "score": 212672.6985814534 }, { "content": "pub fn query(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: ChainQueryFilter,\n\n) -> Result<Vec<Element>, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n let elements: Vec<Element> = call_context\n\n .host_access\n\n .workspace()\n\n .source_chain()\n\n .query(input)\n\n .await\n\n .map_err(|source_chain_error| WasmError::Host(source_chain_error.to_string()))?;\n\n Ok(elements)\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod slow_tests {\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/query.rs", "rank": 63, "score": 212672.6985814534 }, { "content": "/// Returns every entry hash in a vector from the second level of an anchor.\n\n/// Uses the string argument to build the path from the root.\n\n/// Hashes are sorted in the same way that paths sort children.\n\npub fn list_anchor_addresses(anchor_type: String) -> ExternResult<Vec<EntryHash>> {\n\n let path: Path = (&Anchor {\n\n anchor_type,\n\n anchor_text: None,\n\n })\n\n .into();\n\n path.ensure()?;\n\n let links = path\n\n .children()?\n\n .into_inner()\n\n .into_iter()\n\n .map(|link| link.target)\n\n .collect();\n\n Ok(links)\n\n}\n\n\n", "file_path": "crates/adk/src/hash_path/anchor.rs", "rank": 64, "score": 210597.16450130733 }, { "content": "fn channels_path() -> Path {\n\n let path = Path::from(\"channels\");\n\n path.ensure().expect(\"Couldn't ensure path\");\n\n path\n\n}\n\n\n", "file_path": "crates/test_utils/wasm/wasm_workspace/ser_regression/src/lib.rs", "rank": 65, "score": 209908.3505593598 }, { "content": "/// Merge two sub-streams so they can be polled in parallel, but\n\n/// still know when each individually ends, unlike futures::stream::select()\n\npub fn auto_stream_select<LeftType, RightType, LSt, RSt>(\n\n left: LSt,\n\n right: RSt,\n\n) -> impl futures::stream::Stream<Item = AutoStreamSelect<LeftType, RightType>>\n\nwhere\n\n LSt: futures::stream::Stream<Item = LeftType> + Unpin,\n\n RSt: futures::stream::Stream<Item = RightType> + Unpin,\n\n{\n\n let mut left = Some(left);\n\n let mut l_done = false;\n\n let left = futures::stream::poll_fn(move |ctx| {\n\n if l_done {\n\n return Ready(None);\n\n }\n\n let rleft = left.as_mut().unwrap();\n\n tokio::pin!(rleft);\n\n match futures::stream::Stream::poll_next(rleft, ctx) {\n\n Ready(Some(v)) => Ready(Some(AutoStreamSelect::Left(Some(v)))),\n\n Ready(None) => {\n\n l_done = true;\n", "file_path": "crates/kitsune_p2p/types/src/auto_stream_select.rs", "rank": 66, "score": 208980.2639620655 }, { "content": "/// return the access info used for this call\n\n/// also return who is originated the call (pubkey)\n\npub fn capability_info(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<(), WasmError> {\n\n unimplemented!();\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/capability_info.rs", "rank": 67, "score": 208729.36224459694 }, { "content": "pub fn call_info(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<CallInfo, WasmError> {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/call_info.rs", "rank": 68, "score": 208723.39201532278 }, { "content": "pub fn sign_ephemeral(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: SignEphemeral,\n\n) -> Result<EphemeralSignatures, WasmError> {\n\n let rng = SystemRandom::new();\n\n let mut seed = [0; 32];\n\n rng.fill(&mut seed)\n\n .map_err(|e| WasmError::Guest(e.to_string()))?;\n\n let ephemeral_keypair =\n\n Ed25519KeyPair::from_seed_unchecked(&seed).map_err(|e| WasmError::Host(e.to_string()))?;\n\n\n\n let signatures: Result<Vec<Signature>, _> = input\n\n .into_inner()\n\n .into_iter()\n\n .map(|data| ephemeral_keypair.sign(&data).as_ref().try_into())\n\n .collect();\n\n\n\n Ok(EphemeralSignatures {\n\n signatures: signatures.map_err(|e| WasmError::Host(e.to_string()))?,\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/sign_ephemeral.rs", "rank": 69, "score": 208723.39201532278 }, { "content": "pub fn verify_signature(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: VerifySignature,\n\n) -> Result<bool, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n input\n\n .key\n\n .verify_signature_raw(input.as_ref(), input.as_data_ref())\n\n .await\n\n })\n\n .map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n\n use ::fixt::prelude::*;\n\n use adk::prelude::test_utils::fake_agent_pubkey_1;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/verify_signature.rs", "rank": 70, "score": 208723.39201532278 }, { "content": "pub fn call_remote(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: CallRemote,\n\n) -> Result<ZomeCallResponse, WasmError> {\n\n // it is the network's responsibility to handle timeouts and return an Err result in that case\n\n let result: Result<SerializedBytes, _> = tokio_helper::block_forever_on(async move {\n\n let mut network = call_context.host_access().network().clone();\n\n network\n\n .call_remote(\n\n input.target_agent_as_ref().to_owned(),\n\n input.zome_name_as_ref().to_owned(),\n\n input.fn_name_as_ref().to_owned(),\n\n input.cap_as_ref().to_owned(),\n\n input.payload_as_ref().to_owned(),\n\n )\n\n .await\n\n });\n\n let result = match result {\n\n Ok(r) => ZomeCallResponse::try_from(r)?,\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/call_remote.rs", "rank": 71, "score": 208723.39201532278 }, { "content": "/// list all the grants stored locally in the chain filtered by tag\n\n/// this is only the current grants as per local CRUD\n\npub fn capability_grants(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<(), WasmError> {\n\n unimplemented!();\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n\n use crate::{conductor::ConductorBuilder, sweettest::SweetConductor};\n\n use crate::{sweettest::SweetSafFile};\n\n use ::fixt::prelude::*;\n\n use adk::prelude::*;\n\n use aingle_state::host_fn_workspace::HostFnWorkspace;\n\n use aingle_types::fixt::CapSecretFixturator;\n\n use aingle_types::prelude::*;\n\n use aingle_types::test_utils::fake_agent_pubkey_1;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/capability_grants.rs", "rank": 72, "score": 208723.39201532278 }, { "content": "pub fn emit_signal(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: AppSignal,\n\n) -> Result<(), WasmError> {\n\n let cell_id = call_context.host_access().cell_id().clone();\n\n let signal = Signal::App(cell_id, input);\n\n call_context.host_access().signal_tx().send(signal).map_err(|interface_error| WasmError::Host(interface_error.to_string()))?;\n\n Ok(())\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/emit_signal.rs", "rank": 73, "score": 208723.39201532278 }, { "content": "pub fn zome_info(\n\n ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<ZomeInfo, WasmError> {\n\n Ok(ZomeInfo {\n\n saf_name: ribosome.saf_def().name.clone(),\n\n zome_name: call_context.zome.zome_name().clone(),\n\n saf_hash: ribosome.saf_def().as_hash().clone(),\n\n zome_id: ribosome\n\n .zome_to_id(&call_context.zome)\n\n .expect(\"Failed to get ID for current zome\"),\n\n properties: ribosome.saf_def().properties.clone(),\n\n // @TODO\n\n // public_token: \"\".into(),\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/zome_info.rs", "rank": 74, "score": 208723.39201532278 }, { "content": "#[tracing::instrument(skip(_ribosome, call_context, input))]\n\npub fn remote_signal(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: RemoteSignal,\n\n) -> Result<(), WasmError> {\n\n const FN_NAME: &str = \"recv_remote_signal\";\n\n // Timeouts and errors are ignored,\n\n // this is a send and forget operation.\n\n let network = call_context.host_access().network().clone();\n\n let RemoteSignal { agents, signal } = input;\n\n let zome_name: ZomeName = call_context.zome().into();\n\n let fn_name: FunctionName = FN_NAME.into();\n\n for agent in agents {\n\n tokio::task::spawn(\n\n {\n\n let mut network = network.clone();\n\n let zome_name = zome_name.clone();\n\n let fn_name = fn_name.clone();\n\n let payload = signal.clone();\n\n async move {\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/remote_signal.rs", "rank": 75, "score": 208723.39201532278 }, { "content": "pub fn sys_time(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<core::time::Duration, WasmError> {\n\n let start = std::time::SystemTime::now();\n\n let since_the_epoch = start\n\n .duration_since(std::time::UNIX_EPOCH)\n\n .expect(\"Time went backwards\");\n\n Ok(since_the_epoch)\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n\n use ::fixt::prelude::*;\n\n use aingle_state::host_fn_workspace::HostFnWorkspace;\n\n use aingle_wasm_test_utils::TestWasm;\n\n use aingle_zome_types::fake_agent_pubkey_1;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/sys_time.rs", "rank": 76, "score": 208723.39201532278 }, { "content": "/// return n crypto secure random bytes from the standard aingle crypto lib\n\npub fn random_bytes(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: u32,\n\n) -> Result<Bytes, WasmError> {\n\n let system_random = ring::rand::SystemRandom::new();\n\n let mut bytes = vec![0; input as _];\n\n system_random\n\n .fill(&mut bytes)\n\n .map_err(|ring_unspecified_error| WasmError::Host(ring_unspecified_error.to_string()))?;\n\n\n\n Ok(Bytes::from(bytes))\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use crate::core::ribosome::host_fn::random_bytes::random_bytes;\n\n\n\n use crate::fixt::CallContextFixturator;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/random_bytes.rs", "rank": 77, "score": 208723.39201532278 }, { "content": "pub fn hash_entry(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: Entry,\n\n) -> Result<EntryHash, WasmError> {\n\n let entry_hash = aingle_types::entry::EntryHashed::from_content_sync(input).into_hash();\n\n\n\n Ok(entry_hash)\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use super::*;\n\n use crate::core::ribosome::host_fn::hash_entry::hash_entry;\n\n\n\n use crate::fixt::CallContextFixturator;\n\n use crate::fixt::EntryFixturator;\n\n use crate::fixt::RealRibosomeFixturator;\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/hash_entry.rs", "rank": 78, "score": 208723.39201532278 }, { "content": "pub fn extract_entry_def(\n\n ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n entry_def_id: EntryDefId,\n\n) -> Result<(aingle_zome_types::header::EntryDefIndex, EntryVisibility), WasmError> {\n\n let app_entry_type = match ribosome\n\n .run_entry_defs((&call_context.host_access).into(), EntryDefsInvocation)\n\n .map_err(|ribosome_error| WasmError::Host(ribosome_error.to_string()))?\n\n {\n\n // the ribosome returned some defs\n\n EntryDefsResult::Defs(defs) => {\n\n let maybe_entry_defs = defs.get(call_context.zome.zome_name());\n\n match maybe_entry_defs {\n\n // convert the entry def id string into a numeric position in the defs\n\n Some(entry_defs) => {\n\n entry_defs.entry_def_index_from_id(entry_def_id.clone()).map(|index| {\n\n // build an app entry type from the entry def at the found position\n\n (index, entry_defs[index.0 as usize].visibility)\n\n })\n\n }\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/create.rs", "rank": 79, "score": 208723.39201532278 }, { "content": "/// lists all the local claims filtered by tag\n\npub fn capability_claims(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<(), WasmError> {\n\n unimplemented!();\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/capability_claims.rs", "rank": 80, "score": 208723.39201532278 }, { "content": "pub fn saf_info(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<SafInfo, WasmError> {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/saf_info.rs", "rank": 81, "score": 208723.39201532278 }, { "content": "pub fn app_info(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<AppInfo, WasmError> {\n\n unimplemented!()\n\n}\n\n\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/app_info.rs", "rank": 82, "score": 208723.39201532278 }, { "content": "#[allow(clippy::extra_unused_lifetimes)]\n\npub fn delete<'a>(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: HeaderHash,\n\n) -> Result<HeaderHash, WasmError> {\n\n let deletes_entry_address = get_original_address(call_context.clone(), input.clone())?;\n\n\n\n let host_access = call_context.host_access();\n\n\n\n // handle timeouts at the source chain layer\n\n tokio_helper::block_forever_on(async move {\n\n let source_chain = host_access.workspace().source_chain();\n\n let header_builder = builder::Delete {\n\n deletes_address: input,\n\n deletes_entry_address,\n\n };\n\n let header_hash = source_chain\n\n .put(header_builder, None)\n\n .await\n\n .map_err(|source_chain_error| WasmError::Host(source_chain_error.to_string()))?;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/delete.rs", "rank": 83, "score": 207880.48859933877 }, { "content": "#[allow(clippy::extra_unused_lifetimes)]\n\npub fn get<'a>(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: GetInput,\n\n) -> Result<Option<Element>, WasmError> {\n\n let GetInput {\n\n any_sgd_hash,\n\n get_options,\n\n } = input;\n\n\n\n // Get the network from the context\n\n let network = call_context.host_access.network().clone();\n\n\n\n // timeouts must be handled by the network\n\n tokio_helper::block_forever_on(async move {\n\n let workspace = call_context.host_access.workspace();\n\n let mut cascade = Cascade::from_workspace_network(workspace, network);\n\n let maybe_element = cascade\n\n .sgd_get(any_sgd_hash, get_options)\n\n .await\n\n .map_err(|cascade_error| WasmError::Host(cascade_error.to_string()))?;\n\n\n\n Ok(maybe_element)\n\n })\n\n}\n\n\n\n// we are relying on the create tests to show the commit/get round trip\n\n// See commit_entry.rs\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/get.rs", "rank": 84, "score": 207880.48859933877 }, { "content": "#[allow(clippy::extra_unused_lifetimes)]\n\npub fn update<'a>(\n\n ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: UpdateInput,\n\n) -> Result<HeaderHash, WasmError> {\n\n // destructure the args out into an app type def id and entry\n\n let UpdateInput {\n\n original_header_address,\n\n entry_with_def_id,\n\n } = input;\n\n\n\n // build the entry hash\n\n let async_entry = AsRef::<Entry>::as_ref(&entry_with_def_id).to_owned();\n\n let entry_hash =\n\n aingle_types::entry::EntryHashed::from_content_sync(async_entry).into_hash();\n\n\n\n // extract the zome position\n\n let header_zome_id = ribosome\n\n .zome_to_id(&call_context.zome)\n\n .map_err(|source_chain_error| WasmError::Host(source_chain_error.to_string()))?;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/update.rs", "rank": 85, "score": 207880.48859933877 }, { "content": "#[allow(clippy::extra_unused_lifetimes)]\n\npub fn create<'a>(\n\n ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: EntryWithDefId,\n\n) -> Result<HeaderHash, WasmError> {\n\n // build the entry hash\n\n let async_entry = AsRef::<Entry>::as_ref(&input).to_owned();\n\n let entry_hash =\n\n aingle_types::entry::EntryHashed::from_content_sync(async_entry).into_hash();\n\n\n\n // extract the zome position\n\n let header_zome_id = ribosome\n\n .zome_to_id(&call_context.zome)\n\n .expect(\"Failed to get ID for current zome\");\n\n\n\n // extract the entry defs for a zome\n\n let entry_type = match AsRef::<EntryDefId>::as_ref(&input) {\n\n EntryDefId::App(entry_def_id) => {\n\n let (header_entry_def_id, entry_visibility) = extract_entry_def(\n\n ribosome,\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/create.rs", "rank": 86, "score": 207880.48859933877 }, { "content": "/// Generate a new sandbox.\n\n/// This creates a directory and a [`ConductorConfig`]\n\n/// from an optional network.\n\n/// The root directory and inner directory\n\n/// (where this sandbox will be created) can be overridden.\n\n/// For example `my_root_dir/this_sandbox_dir/`\n\npub fn generate(\n\n network: Option<KitsuneP2pConfig>,\n\n root: Option<PathBuf>,\n\n directory: Option<PathBuf>,\n\n) -> anyhow::Result<PathBuf> {\n\n let dir = generate_directory(root, directory)?;\n\n let mut config = create_config(dir.clone());\n\n config.network = network;\n\n random_admin_port(&mut config);\n\n let path = write_config(dir.clone(), &config);\n\n msg!(\"Config {:?}\", config);\n\n msg!(\n\n \"Created directory at: {} {}\",\n\n ansi_term::Style::new()\n\n .bold()\n\n .underline()\n\n .on(ansi_term::Color::Fixed(254))\n\n .fg(ansi_term::Color::Fixed(4))\n\n .paint(dir.display().to_string()),\n\n ansi_term::Style::new()\n\n .bold()\n\n .paint(\"Keep this path to rerun the same sandbox\")\n\n );\n\n msg!(\"Created config at {}\", path.display());\n\n Ok(dir)\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/generate.rs", "rank": 87, "score": 207009.34842193165 }, { "content": "pub fn x_25519_x_salsa20_poly1305_encrypt(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: X25519XSalsa20Poly1305Encrypt,\n\n) -> Result<XSalsa20Poly1305EncryptedData, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n call_context\n\n .host_access\n\n .keystore()\n\n .x_25519_x_salsa20_poly1305_encrypt(input)\n\n .await\n\n })\n\n .map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/x_25519_x_salsa20_poly1305_encrypt.rs", "rank": 88, "score": 205007.3515547981 }, { "content": "pub fn get_agent_activity(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: GetAgentActivityInput,\n\n) -> Result<AgentActivity, WasmError> {\n\n let GetAgentActivityInput {\n\n agent_pubkey,\n\n chain_query_filter,\n\n activity_request,\n\n } = input;\n\n let options = match activity_request {\n\n ActivityRequest::Status => GetActivityOptions {\n\n include_valid_activity: false,\n\n include_rejected_activity: false,\n\n ..Default::default()\n\n },\n\n ActivityRequest::Full => GetActivityOptions {\n\n include_valid_activity: true,\n\n include_rejected_activity: true,\n\n ..Default::default()\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/get_agent_activity.rs", "rank": 89, "score": 205007.3515547981 }, { "content": "pub fn x_salsa20_poly1305_encrypt(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: XSalsa20Poly1305Encrypt,\n\n) -> Result<XSalsa20Poly1305EncryptedData, WasmError> {\n\n let system_random = ring::rand::SystemRandom::new();\n\n let mut nonce_bytes = [0; aingle_zome_types::x_salsa20_poly1305::nonce::NONCE_BYTES];\n\n system_random\n\n .fill(&mut nonce_bytes)\n\n .map_err(|ring_unspecified| WasmError::Host(ring_unspecified.to_string()))?;\n\n\n\n // @todo use the real libsodium somehow instead of this rust crate.\n\n // The main issue here is dependency management - it's not necessarily simple to get libsodium\n\n // reliably on consumer devices, e.g. we might want to statically link it somewhere.\n\n // @todo this key ref should be an opaque ref to lair and the encrypt should happen in lair.\n\n let lib_key = GenericArray::from_slice(input.as_key_ref_ref().as_ref());\n\n let cipher = XSalsa20Poly1305::new(lib_key);\n\n let lib_nonce = GenericArray::from_slice(&nonce_bytes);\n\n let lib_encrypted_data = cipher\n\n .encrypt(lib_nonce, input.as_data_ref().as_ref())\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/x_salsa20_poly1305_encrypt.rs", "rank": 90, "score": 205007.3515547981 }, { "content": "pub fn create_x25519_keypair(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<X25519PubKey, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n call_context\n\n .host_access\n\n .keystore()\n\n .create_x25519_keypair()\n\n .await\n\n })\n\n .map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))\n\n}\n\n\n\n// See x_25519_x_salsa20_poly1305_encrypt for testing encryption using created keypairs.\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/create_x25519_keypair.rs", "rank": 91, "score": 205007.3515547981 }, { "content": "pub fn x_salsa20_poly1305_decrypt(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: XSalsa20Poly1305Decrypt,\n\n) -> Result<Option<XSalsa20Poly1305Data>, WasmError> {\n\n // @todo use a libsodium wrapper instead of an ad-hoc rust implementation.\n\n // Note that the we're mapping any decrypting error to None here.\n\n // @todo this decrypt should be in lair and key refs should be refs to keys in lair\n\n let lib_key = GenericArray::from_slice(input.as_key_ref_ref().as_ref());\n\n let cipher = XSalsa20Poly1305::new(lib_key);\n\n let lib_nonce = GenericArray::from_slice(input.as_encrypted_data_ref().as_nonce_ref().as_ref());\n\n Ok(\n\n match cipher.decrypt(lib_nonce, input.as_encrypted_data_ref().as_encrypted_data_ref()) {\n\n Ok(data) => Some(XSalsa20Poly1305Data::from(data)),\n\n Err(_) => None,\n\n }\n\n )\n\n}\n\n\n\n// Tests for the decrypt round trip are in xsalsa20_poly1305_encrypt.\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/x_salsa20_poly1305_decrypt.rs", "rank": 92, "score": 205007.3515547981 }, { "content": "pub fn x_25519_x_salsa20_poly1305_decrypt(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: X25519XSalsa20Poly1305Decrypt,\n\n) -> Result<Option<XSalsa20Poly1305Data>, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n call_context\n\n .host_access\n\n .keystore()\n\n .x_25519_x_salsa20_poly1305_decrypt(input)\n\n .await\n\n })\n\n .map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))\n\n}\n", "file_path": "crates/aingle/src/core/ribosome/host_fn/x_25519_x_salsa20_poly1305_decrypt.rs", "rank": 93, "score": 205007.3515547981 }, { "content": "/// # Call\n\n/// Make a Zome call in another Zome.\n\n/// The Zome can be in another Cell or the\n\n/// same Cell but must be installed on the same conductor.\n\n///\n\n/// ## Parameters\n\n/// - to_cell: The cell you want to call (If None will call the current cell).\n\n/// - zome_name: The name of the zome you want to call.\n\n/// - fn_name: The name of the function in the zome you are calling.\n\n/// - cap_secret: The capability secret if required.\n\n/// - payload: The arguments to the function you are calling.\n\npub fn call<I>(\n\n to_cell: Option<CellId>,\n\n zome_name: ZomeName,\n\n fn_name: FunctionName,\n\n cap_secret: Option<CapSecret>,\n\n payload: I,\n\n) -> ExternResult<ZomeCallResponse>\n\nwhere\n\n I: serde::Serialize + std::fmt::Debug,\n\n{\n\n // @todo is this secure to set this in the wasm rather than have the host inject it?\n\n let provenance = agent_info()?.agent_latest_pubkey;\n\n ADK.with(|h| {\n\n h.borrow().call(Call::new(\n\n to_cell,\n\n zome_name,\n\n fn_name,\n\n cap_secret,\n\n ExternIO::encode(payload)?,\n\n provenance,\n\n ))\n\n })\n\n}\n\n\n", "file_path": "crates/adk/src/p2p.rs", "rank": 94, "score": 204786.18033351435 }, { "content": "/// Update a capability secret.\n\n///\n\n/// Wraps the [ `update` ] ADK function with system type parameters set.\n\n/// This guards against updating application entries or setting the wrong entry types.\n\n///\n\n/// Capability grant updates work exactly as a delete+create of the old+new grant entries.\n\n///\n\n/// The first argument is the header hash of the old grant being deleted as per [ `delete_cap_grant` ].\n\n/// The second argument is the entry value of the new grant to create as per [ `create_cap_grant` ].\n\npub fn update_cap_grant(\n\n old_grant_header_hash: HeaderHash,\n\n new_grant_value: CapGrantEntry,\n\n) -> ExternResult<HeaderHash> {\n\n update(\n\n old_grant_header_hash,\n\n EntryWithDefId::new(EntryDefId::CapGrant, Entry::CapGrant(new_grant_value)),\n\n )\n\n}\n", "file_path": "crates/adk/src/capability.rs", "rank": 95, "score": 204552.81235392706 }, { "content": "/// Set when a [`SgdOp`] was integrated.\n\npub fn set_when_integrated(\n\n txn: &mut Transaction,\n\n hash: SgdOpHash,\n\n time: Timestamp,\n\n) -> StateMutationResult<()> {\n\n sgd_op_update!(txn, hash, {\n\n \"when_integrated_ns\": to_blob(time)?,\n\n \"when_integrated\": time,\n\n })?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/aingle_state/src/mutations.rs", "rank": 96, "score": 204548.08241402346 }, { "content": "/// Insert a [`SgdOp`] into the database.\n\npub fn insert_op(\n\n txn: &mut Transaction,\n\n op: SgdOpHashed,\n\n is_authored: bool,\n\n) -> StateMutationResult<()> {\n\n let (op, hash) = op.into_inner();\n\n let op_light = op.to_light();\n\n let header = op.header();\n\n let timestamp = header.timestamp();\n\n let signature = op.signature().clone();\n\n if let Some(entry) = op.entry() {\n\n let entry_hashed = EntryHashed::with_pre_hashed(\n\n entry.clone(),\n\n header\n\n .entry_hash()\n\n .ok_or_else(|| SgdOpError::HeaderWithoutEntry(header.clone()))?\n\n .clone(),\n\n );\n\n insert_entry(txn, entry_hashed)?;\n\n }\n\n let header_hashed = HeaderHashed::with_pre_hashed(header, op_light.header_hash().to_owned());\n\n let header_hashed = SignedHeaderHashed::with_presigned(header_hashed, signature);\n\n let op_order = OpOrder::new(op_light.get_type(), header_hashed.header().timestamp());\n\n insert_header(txn, header_hashed)?;\n\n insert_op_lite(txn, op_light, hash, is_authored, op_order, timestamp)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/aingle_state/src/mutations.rs", "rank": 97, "score": 204548.08241402346 }, { "content": "/// Generate a new sandbox from a full config.\n\npub fn generate_with_config(\n\n config: Option<ConductorConfig>,\n\n root: Option<PathBuf>,\n\n directory: Option<PathBuf>,\n\n) -> anyhow::Result<PathBuf> {\n\n let dir = generate_directory(root, directory)?;\n\n let config = config.unwrap_or_else(|| create_config(dir.clone()));\n\n write_config(dir.clone(), &config);\n\n Ok(dir)\n\n}\n\n\n", "file_path": "crates/ai_sandbox/src/generate.rs", "rank": 98, "score": 204548.08241402346 }, { "content": "/// Query the _headers_ of a remote agent's chain.\n\n///\n\n/// The agent activity is only the headers of their source chain.\n\n/// The agent activity is held by the neighbourhood centered on the agent's public key, rather than a content hash like the rest of the SGD.\n\n///\n\n/// The agent activity can be filtered with [ `ChainQueryFilter` ] like a local chain query.\n\npub fn get_agent_activity(\n\n agent: AgentPubKey,\n\n query: ChainQueryFilter,\n\n request: ActivityRequest,\n\n) -> ExternResult<AgentActivity> {\n\n ADK.with(|h| {\n\n h.borrow()\n\n .get_agent_activity(GetAgentActivityInput::new(agent, query, request))\n\n })\n\n}\n\n\n", "file_path": "crates/adk/src/chain.rs", "rank": 99, "score": 204548.08241402346 } ]
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_path": "parity-ethereum/util/triehash-ethereum/src/lib.rs", "rank": 1, "score": 414276.7212673584 }, { "content": "/// Generates a key-hashed (secure) trie root hash for a vector of key-value tuples.\n\npub fn sec_trie_root<I, K, V>(input: I) -> H256\n\nwhere\n\n I: IntoIterator<Item = (K, V)>,\n\n K: AsRef<[u8]>,\n\n V: AsRef<[u8]>,\n\n{\n\n triehash::sec_trie_root::<KeccakHasher, _, _, _>(input)\n\n}\n\n\n", "file_path": "parity-ethereum/util/triehash-ethereum/src/lib.rs", "rank": 2, "score": 409782.0450906085 }, { "content": "/// Returns temp state\n\npub fn get_temp_state() -> State<::state_db::StateDB> {\n\n\tlet journal_db = get_temp_state_db();\n\n\tState::new(journal_db, U256::from(0), Default::default())\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 3, "score": 381531.9095579291 }, { "content": "/// Returns the key from the key server associated with the contract\n\npub fn address_to_key(contract_address: &Address) -> H256 {\n\n\t// Current solution uses contract address extended with 0 as id\n\n\tlet contract_address_extended: H256 = (*contract_address).into();\n\n\n\n\tH256::from_slice(contract_address_extended.as_bytes())\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/private-tx/src/key_server_keys.rs", "rank": 4, "score": 367403.98598956876 }, { "content": "/// Returns hash and header of the correct dummy block\n\npub fn get_good_dummy_block_hash() -> (H256, Bytes) {\n\n\tlet mut block_header = Header::new();\n\n\tlet test_spec = spec::new_test();\n\n\tlet genesis_gas = test_spec.genesis_header().gas_limit().clone();\n\n\tblock_header.set_gas_limit(genesis_gas);\n\n\tblock_header.set_difficulty(U256::from(0x20000));\n\n\tblock_header.set_timestamp(40);\n\n\tblock_header.set_number(1);\n\n\tblock_header.set_parent_hash(test_spec.genesis_header().hash());\n\n\tblock_header.set_state_root(test_spec.genesis_header().state_root().clone());\n\n\n\n\t(block_header.hash(), create_test_block(&block_header))\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 5, "score": 365663.5513870004 }, { "content": "/// Returns the address (of the contract), that corresponds to the key\n\npub fn key_to_address(key: &H256) -> Address {\n\n\tAddress::from_slice(&key.as_bytes()[..10])\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/private-tx/src/key_server_keys.rs", "rank": 6, "score": 363355.9586002552 }, { "content": "pub fn dump_account(statedb: &StateDatabase, address: &Address, key: &Option<EthereumH256>) -> String {\n\n let dump = AccountDump {\n\n address: address.clone(),\n\n balance: statedb.balance(address).unwrap(),\n\n nonce: statedb.nonce(address).unwrap(),\n\n code: statedb.code(address).unwrap().map(|arc|(*arc).clone()),\n\n key: key.clone(),\n\n value: key.and_then(|ref k|statedb.storage_at(address, k).ok()),\n\n };\n\n serde_json::to_string_pretty(&dump).unwrap()\n\n}\n", "file_path": "src/visualization/dump.rs", "rank": 7, "score": 359556.9694585718 }, { "content": "#[derive(Debug)]\n\nstruct DiskMap<K: hash::Hash + Eq, V> {\n\n\tpath: PathBuf,\n\n\tcache: HashMap<K, V>,\n\n\ttransient: bool,\n\n}\n\n\n\nimpl<K: hash::Hash + Eq, V> ops::Deref for DiskMap<K, V> {\n\n\ttype Target = HashMap<K, V>;\n\n\tfn deref(&self) -> &Self::Target {\n\n\t\t&self.cache\n\n\t}\n\n}\n\n\n\nimpl<K: hash::Hash + Eq, V> ops::DerefMut for DiskMap<K, V> {\n\n\tfn deref_mut(&mut self) -> &mut Self::Target {\n\n\t\t&mut self.cache\n\n\t}\n\n}\n\n\n\nimpl<K: hash::Hash + Eq, V> DiskMap<K, V> {\n", "file_path": "parity-ethereum/accounts/src/stores.rs", "rank": 8, "score": 358718.66259090067 }, { "content": "/// Returns temp state using coresponding factory\n\npub fn get_temp_state_with_factory(factory: EvmFactory) -> State<::state_db::StateDB> {\n\n\tlet journal_db = get_temp_state_db();\n\n\tlet mut factories = Factories::default();\n\n\tfactories.vm = factory.into();\n\n\tState::new(journal_db, U256::from(0), factories)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 9, "score": 355506.32964586595 }, { "content": "/// Returns temp state db\n\npub fn get_temp_state_db() -> StateDB {\n\n\tlet db = new_db();\n\n\tlet journal_db = ::journaldb::new(db.key_value().clone(), ::journaldb::Algorithm::EarlyMerge, ::db::COL_STATE);\n\n\tStateDB::new(journal_db, 5 * 1024 * 1024)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 10, "score": 348924.8520979545 }, { "content": "/// Generates a trie root hash for a vector of values\n\npub fn ordered_trie_root<I, V>(input: I) -> H256\n\nwhere\n\n I: IntoIterator<Item = V>,\n\n V: AsRef<[u8]>,\n\n{\n\n triehash::ordered_trie_root::<KeccakHasher, I>(input)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse super::{trie_root, sec_trie_root, ordered_trie_root, H256};\n\n use triehash;\n\n\tuse keccak_hasher::KeccakHasher;\n\n\tuse std::str::FromStr;\n\n\n\n\t#[test]\n\n\tfn simple_test() {\n\n\t\tassert_eq!(trie_root(vec![\n\n\t\t\t(b\"A\", b\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" as &[u8])\n\n\t\t]), H256::from_str(\"d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab\").unwrap());\n", "file_path": "parity-ethereum/util/triehash-ethereum/src/lib.rs", "rank": 11, "score": 336524.9424292213 }, { "content": "/// Returns hash of the dummy block with incorrect state root\n\npub fn get_bad_state_dummy_block() -> Bytes {\n\n\tlet mut block_header = Header::new();\n\n\tlet test_spec = spec::new_test();\n\n\tlet genesis_gas = test_spec.genesis_header().gas_limit().clone();\n\n\n\n\tblock_header.set_gas_limit(genesis_gas);\n\n\tblock_header.set_difficulty(U256::from(0x20000));\n\n\tblock_header.set_timestamp(40);\n\n\tblock_header.set_number(1);\n\n\tblock_header.set_parent_hash(test_spec.genesis_header().hash());\n\n\tblock_header.set_state_root(H256::from_low_u64_be(0xbad));\n\n\n\n\tcreate_test_block(&block_header)\n\n}\n\n\n\n/// Test actor for chain events\n\n#[derive(Default)]\n\npub struct TestNotify {\n\n\t/// Messages store\n\n\tpub messages: RwLock<Vec<Bytes>>,\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 12, "score": 334019.75603532454 }, { "content": "/// Determine difference between two optionally existant `Account`s. Returns None\n\n/// if they are the same.\n\npub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option<AccountDiff> {\n\n\tmatch (pre, post) {\n\n\t\t(None, Some(x)) => Some(AccountDiff {\n\n\t\t\tbalance: Diff::Born(x.balance),\n\n\t\t\tnonce: Diff::Born(x.nonce),\n\n\t\t\tcode: Diff::Born(x.code.as_ref().expect(\"account is newly created; newly created accounts must be given code; all caches should remain in place; qed\").clone()),\n\n\t\t\tstorage: x.storage.iter().map(|(k, v)| (k.clone(), Diff::Born(v.clone()))).collect(),\n\n\t\t}),\n\n\t\t(Some(x), None) => Some(AccountDiff {\n\n\t\t\tbalance: Diff::Died(x.balance),\n\n\t\t\tnonce: Diff::Died(x.nonce),\n\n\t\t\tcode: Diff::Died(x.code.as_ref().expect(\"account is deleted; only way to delete account is running SUICIDE; account must have had own code cached to make operation; all caches should remain in place; qed\").clone()),\n\n\t\t\tstorage: x.storage.iter().map(|(k, v)| (k.clone(), Diff::Died(v.clone()))).collect(),\n\n\t\t}),\n\n\t\t(Some(pre), Some(post)) => {\n\n\t\t\tlet storage: Vec<_> = pre.storage.keys().merge(post.storage.keys())\n\n\t\t\t\t.filter(|k| pre.storage.get(k).unwrap_or(&H256::zero()) != post.storage.get(k).unwrap_or(&H256::zero()))\n\n\t\t\t\t.collect();\n\n\t\t\tlet r = AccountDiff {\n\n\t\t\t\tbalance: Diff::new(pre.balance, post.balance),\n", "file_path": "parity-ethereum/ethcore/pod/src/account.rs", "rank": 13, "score": 327870.713323016 }, { "content": "/// Returns new address created from address, nonce, and code hash\n\npub fn contract_address(address_scheme: CreateContractAddress, sender: &Address, nonce: &U256, code: &[u8]) -> (Address, Option<H256>) {\n\n\tmatch address_scheme {\n\n\t\tCreateContractAddress::FromSenderAndNonce => {\n\n\t\t\tlet mut stream = RlpStream::new_list(2);\n\n\t\t\tstream.append(sender);\n\n\t\t\tstream.append(nonce);\n\n\t\t\t(From::from(keccak(stream.as_raw())), None)\n\n\t\t},\n\n\t\tCreateContractAddress::FromSenderSaltAndCodeHash(salt) => {\n\n\t\t\tlet code_hash = keccak(code);\n\n\t\t\tlet mut buffer = [0u8; 1 + 20 + 32 + 32];\n\n\t\t\tbuffer[0] = 0xff;\n\n\t\t\t&mut buffer[1..(1+20)].copy_from_slice(&sender[..]);\n\n\t\t\t&mut buffer[(1+20)..(1+20+32)].copy_from_slice(&salt[..]);\n\n\t\t\t&mut buffer[(1+20+32)..].copy_from_slice(&code_hash[..]);\n\n\t\t\t(From::from(keccak(&buffer[..])), Some(code_hash))\n\n\t\t},\n\n\t\tCreateContractAddress::FromSenderAndCodeHash => {\n\n\t\t\tlet code_hash = keccak(code);\n\n\t\t\tlet mut buffer = [0u8; 20 + 32];\n\n\t\t\t&mut buffer[..20].copy_from_slice(&sender[..]);\n\n\t\t\t&mut buffer[20..].copy_from_slice(&code_hash[..]);\n\n\t\t\t(From::from(keccak(&buffer[..])), Some(code_hash))\n\n\t\t},\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/machine/src/executive.rs", "rank": 14, "score": 321823.60324861907 }, { "content": "#[cfg(test_utility)]\n\npub fn get_temp_state_database() -> StateDatabase {\n\n let state = ethcore::test_helpers::get_temp_state();\n\n let state = Mutex::new(state);\n\n let machine = spec::new_prism_test_machine();\n\n StateDatabase {\n\n state,\n\n machine,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::StateDatabase;\n\n use crate::crypto::hash::{Address, EthereumH256 as H256};\n\n use crate::transaction::{Action, RawTransaction};\n\n use ethereum_types::U256;\n\n use parity_crypto::publickey::{KeyPair, Random, Secret, Public, Generator};\n\n use std::sync::Mutex;\n\n\n\n fn get_temp_state_database() -> StateDatabase {\n", "file_path": "src/statedb/mod.rs", "rank": 15, "score": 313162.2729051805 }, { "content": "pub fn get_temp_state_db() -> StateDB {\n\n\tlet db = kvdb_memorydb::create(NUM_COLUMNS);\n\n\tlet journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE);\n\n\tStateDB::new(journal_db, 1024 * 1024)\n\n}\n\n\n\nimpl ReopenBlock for TestBlockChainClient {\n\n\tfn reopen_block(&self, block: ClosedBlock) -> OpenBlock {\n\n\t\tblock.reopen(&*self.spec.engine)\n\n\t}\n\n}\n\n\n\nimpl PrepareOpenBlock for TestBlockChainClient {\n\n\tfn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> Result<OpenBlock, Error> {\n\n\t\tlet engine = &*self.spec.engine;\n\n\t\tlet genesis_header = self.spec.genesis_header();\n\n\t\tlet db = self.spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();\n\n\n\n\t\tlet last_hashes = vec![genesis_header.hash()];\n\n\t\tlet mut open_block = OpenBlock::new(\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/test_client.rs", "rank": 16, "score": 309574.8083526444 }, { "content": "pub fn to_url(address: &Option<::Host>) -> Option<String> {\n\n\taddress.as_ref().map(|host| (**host).to_owned())\n\n}\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/mod.rs", "rank": 17, "score": 301423.889320376 }, { "content": "/// Returns sequence of hashes of the dummy blocks beginning from corresponding parent\n\npub fn get_good_dummy_block_fork_seq(start_number: usize, count: usize, parent_hash: &H256) -> Vec<Bytes> {\n\n\tlet test_spec = spec::new_test();\n\n\tlet genesis_gas = test_spec.genesis_header().gas_limit().clone();\n\n\tlet mut rolling_timestamp = start_number as u64 * 10;\n\n\tlet mut parent = *parent_hash;\n\n\tlet mut r = Vec::new();\n\n\tfor i in start_number .. start_number + count + 1 {\n\n\t\tlet mut block_header = Header::new();\n\n\t\tblock_header.set_gas_limit(genesis_gas);\n\n\t\tblock_header.set_difficulty(U256::from(i) * U256([0, 1, 0, 0]));\n\n\t\tblock_header.set_timestamp(rolling_timestamp);\n\n\t\tblock_header.set_number(i as u64);\n\n\t\tblock_header.set_parent_hash(parent);\n\n\t\tblock_header.set_state_root(test_spec.genesis_header().state_root().clone());\n\n\n\n\t\tparent = block_header.hash();\n\n\t\trolling_timestamp = rolling_timestamp + 10;\n\n\n\n\t\tr.push(create_test_block(&block_header));\n\n\t}\n\n\tr\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 18, "score": 300229.61335993477 }, { "content": "/// Returns a eth_sign-compatible hash of data to sign.\n\n/// The data is prepended with special message to prevent\n\n/// malicious DApps from using the function to sign forged transactions.\n\npub fn eth_data_hash(mut data: Bytes) -> H256 {\n\n\tlet mut message_data =\n\n\t\tformat!(\"\\x19Ethereum Signed Message:\\n{}\", data.len())\n\n\t\t.into_bytes();\n\n\tmessage_data.append(&mut data);\n\n\tkeccak(message_data)\n\n}\n\n\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/dispatch/mod.rs", "rank": 19, "score": 299663.19756553404 }, { "content": "pub fn request(address: &SocketAddr, request: &str) -> Response {\n\n\tlet mut req = connect(address);\n\n\treq.set_read_timeout(Some(Duration::from_secs(2))).unwrap();\n\n\treq.write_all(request.as_bytes()).unwrap();\n\n\n\n\tlet mut response = Vec::new();\n\n\tloop {\n\n\t\tlet mut chunk = [0; 32 *1024];\n\n\t\tmatch req.read(&mut chunk) {\n\n\t\t\tErr(ref err) if err.kind() == io::ErrorKind::WouldBlock => break,\n\n\t\t\tErr(err) => panic!(\"Unable to read response: {:?}\", err),\n\n\t\t\tOk(0) => break,\n\n\t\t\tOk(read) => response.extend_from_slice(&chunk[..read]),\n\n\t\t}\n\n\t}\n\n\n\n\tlet response = String::from_utf8_lossy(&response).into_owned();\n\n\tlet mut lines = response.lines();\n\n\tlet status = lines.next().expect(\"Expected a response\").to_owned();\n\n\tlet headers_raw = read_block(&mut lines, false);\n", "file_path": "parity-ethereum/rpc/src/tests/http_client.rs", "rank": 20, "score": 297742.1998760629 }, { "content": "/// Convert RPC confirmation payload to signer confirmation payload.\n\n/// May need to resolve in the future to fetch things like gas price.\n\npub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, dispatcher: &D) -> BoxFuture<ConfirmationPayload>\n\n\twhere D: Dispatcher\n\n{\n\n\tmatch payload {\n\n\t\tRpcConfirmationPayload::SendTransaction(request) => {\n\n\t\t\tBox::new(dispatcher.fill_optional_fields(request.into(), default_account, false)\n\n\t\t\t\t.map(ConfirmationPayload::SendTransaction))\n\n\t\t},\n\n\t\tRpcConfirmationPayload::SignTransaction(request) => {\n\n\t\t\tBox::new(dispatcher.fill_optional_fields(request.into(), default_account, false)\n\n\t\t\t\t.map(ConfirmationPayload::SignTransaction))\n\n\t\t},\n\n\t\tRpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {\n\n\t\t\tBox::new(future::ok(ConfirmationPayload::Decrypt(address, msg.into())))\n\n\t\t},\n\n\t\tRpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {\n\n\t\t\tBox::new(future::ok(ConfirmationPayload::EthSignMessage(address, data.into())))\n\n\t\t},\n\n\t\tRpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {\n\n\t\t\tBox::new(future::ok(ConfirmationPayload::SignMessage(address, data)))\n\n\t\t},\n\n\t}\n\n}\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/dispatch/mod.rs", "rank": 21, "score": 297225.10978472076 }, { "content": "/// Creates test block with corresponding header\n\npub fn create_test_block(header: &Header) -> Bytes {\n\n\tlet mut rlp = RlpStream::new_list(3);\n\n\trlp.append(header);\n\n\trlp.append_raw(&rlp::EMPTY_LIST_RLP, 1);\n\n\trlp.append_raw(&rlp::EMPTY_LIST_RLP, 1);\n\n\trlp.out()\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 22, "score": 288301.4586123028 }, { "content": "/// Fill the storage of an account.\n\npub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) {\n\n\tlet map = StandardMap {\n\n\t\talphabet: Alphabet::All,\n\n\t\tmin_key: 6,\n\n\t\tjournal_key: 6,\n\n\t\tvalue_mode: ValueMode::Random,\n\n\t\tcount: 100,\n\n\t};\n\n\t{\n\n\t\tlet mut trie = if *root == KECCAK_NULL_RLP {\n\n\t\t\tSecTrieDBMut::new(&mut db, root)\n\n\t\t} else {\n\n\t\t\tSecTrieDBMut::from_existing(&mut db, root).unwrap()\n\n\t\t};\n\n\n\n\t\tfor (k, v) in map.make_with(&mut seed.to_fixed_bytes()) {\n\n\t\t\ttrie.insert(&k, &v).unwrap();\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/snapshot/snapshot-tests/src/helpers.rs", "rank": 23, "score": 287764.9021082531 }, { "content": "/// A cache for arbitrary key-value pairs.\n\npub trait Cache<K, V> {\n\n\t/// Insert an entry into the cache and get the old value.\n\n\tfn insert(&mut self, k: K, v: V) -> Option<V>;\n\n\n\n\t/// Remove an entry from the cache, getting the old value if it existed.\n\n\tfn remove(&mut self, k: &K) -> Option<V>;\n\n\n\n\t/// Query the cache for a key's associated value.\n\n\tfn get(&self, k: &K) -> Option<&V>;\n\n}\n\n\n\nimpl<K, V> Cache<K, V> for HashMap<K, V> where K: Hash + Eq {\n\n\tfn insert(&mut self, k: K, v: V) -> Option<V> {\n\n\t\tHashMap::insert(self, k, v)\n\n\t}\n\n\n\n\tfn remove(&mut self, k: &K) -> Option<V> {\n\n\t\tHashMap::remove(self, k)\n\n\t}\n\n\n\n\tfn get(&self, k: &K) -> Option<&V> {\n\n\t\tHashMap::get(self, k)\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/db/src/db.rs", "rank": 24, "score": 287125.6229459762 }, { "content": "/// Returns hash of the correct dummy block\n\npub fn get_good_dummy_block() -> Bytes {\n\n\tlet (_, bytes) = get_good_dummy_block_hash();\n\n\tbytes\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 25, "score": 286506.9634862058 }, { "content": "/// Generates dummy client (not test client) with corresponding amount of blocks, txs per block and spec\n\npub fn generate_dummy_client_with_spec_and_data<F>(\n\n\ttest_spec: F, block_number: u32, txs_per_block: usize, tx_gas_prices: &[U256], force_sealing: bool,\n\n) -> Arc<Client> where\n\n\tF: Fn() -> Spec\n\n{\n\n\tlet test_spec = test_spec();\n\n\tlet client_db = new_db();\n\n\n\n\tlet miner = Miner::new_for_tests_force_sealing(&test_spec, None, force_sealing);\n\n\n\n\tlet client = Client::new(\n\n\t\tClientConfig::default(),\n\n\t\t&test_spec,\n\n\t\tclient_db,\n\n\t\tArc::new(miner),\n\n\t\tIoChannel::disconnected(),\n\n\t).unwrap();\n\n\tlet test_engine = &*test_spec.engine;\n\n\n\n\tlet mut db = test_spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 26, "score": 282812.4158629896 }, { "content": "/// Returns empty dummy blockchain\n\npub fn generate_dummy_empty_blockchain() -> BlockChain {\n\n\tlet db = new_db();\n\n\tlet bc = BlockChain::new(BlockChainConfig::default(), &create_unverifiable_block(0, H256::zero()), db.clone());\n\n\tbc\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 27, "score": 282806.0672370126 }, { "content": "/// Generates dummy client (not test client) with corresponding spec and accounts\n\npub fn generate_dummy_client_with_spec<F>(test_spec: F) -> Arc<Client> where F: Fn() -> Spec {\n\n\tgenerate_dummy_client_with_spec_and_data(test_spec, 0, 0, &[], false)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 28, "score": 275026.3541900025 }, { "content": "/// Creates dummy client (not test client) with corresponding blocks\n\npub fn get_test_client_with_blocks(blocks: Vec<Bytes>) -> Arc<Client> {\n\n\tlet test_spec = spec::new_test();\n\n\tlet client_db = new_db();\n\n\n\n\tlet client = Client::new(\n\n\t\tClientConfig::default(),\n\n\t\t&test_spec,\n\n\t\tclient_db,\n\n\t\tArc::new(Miner::new_for_tests(&test_spec, None)),\n\n\t\tIoChannel::disconnected(),\n\n\t).unwrap();\n\n\n\n\tfor block in blocks {\n\n\t\tif let Err(e) = client.import_block(Unverified::from_rlp(block).unwrap()) {\n\n\t\t\tpanic!(\"error importing block which is well-formed: {:?}\", e);\n\n\t\t}\n\n\t}\n\n\tclient.flush_queue();\n\n\tclient\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 29, "score": 271005.5297425252 }, { "content": "/// Creates new test instance of `BlockChainDB`\n\npub fn new_db() -> Arc<dyn BlockChainDB> {\n\n\tlet blooms_dir = TempDir::new(\"\").unwrap();\n\n\tlet trace_blooms_dir = TempDir::new(\"\").unwrap();\n\n\n\n\tlet db = TestBlockChainDB {\n\n\t\tblooms: blooms_db::Database::open(blooms_dir.path()).unwrap(),\n\n\t\ttrace_blooms: blooms_db::Database::open(trace_blooms_dir.path()).unwrap(),\n\n\t\t_blooms_dir: blooms_dir,\n\n\t\t_trace_blooms_dir: trace_blooms_dir,\n\n\t\tkey_value: Arc::new(::kvdb_memorydb::create(::db::NUM_COLUMNS))\n\n\t};\n\n\n\n\tArc::new(db)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 30, "score": 269968.81971709884 }, { "content": "pub fn to_address(s: Option<String>) -> Result<Address, String> {\n\n\tmatch s {\n\n\t\tSome(ref a) => clean_0x(a).parse().map_err(|_| format!(\"Invalid address: {:?}\", a)),\n\n\t\tNone => Ok(Address::zero())\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/parity/helpers.rs", "rank": 31, "score": 268864.37252419384 }, { "content": "pub fn new(\n\n mempool: &Arc<Mutex<MemoryPool>>,\n\n blockchain: &Arc<BlockChain>,\n\n blockdb: &Arc<BlockDatabase>,\n\n ctx_update_source: Receiver<ContextUpdateSignal>,\n\n ctx_update_tx: &Sender<ContextUpdateSignal>,\n\n server: &ServerHandle,\n\n config: BlockchainConfig,\n\n) -> (Context, Handle) {\n\n let (signal_chan_sender, signal_chan_receiver) = unbounded();\n\n let mut contents: Vec<Content> = vec![];\n\n\n\n let proposer_content = proposer::Content {\n\n transaction_refs: vec![],\n\n proposer_refs: vec![],\n\n };\n\n contents.push(Content::Proposer(proposer_content));\n\n\n\n let transaction_content = transaction::Content {\n\n transactions: vec![],\n", "file_path": "src/miner/mod.rs", "rank": 32, "score": 266968.05575318227 }, { "content": "pub fn ico(\n\n recipients: &[Address], // addresses of all the ico recipients\n\n statedb: &Arc<StateDatabase>,\n\n wallet: &Arc<Wallet>,\n\n num_coins: usize,\n\n) -> Result<(), rocksdb::Error> {\n\n let num_coins: U256 = num_coins.into();\n\n for recipient in recipients.iter() {\n\n statedb.add_balance(recipient, &num_coins).expect(\"ICO state db error\");\n\n }\n\n\n\n statedb.commit().expect(\"ICO state db error\");\n\n Ok(())\n\n}\n", "file_path": "src/experiment/mod.rs", "rank": 33, "score": 266968.0557531822 }, { "content": "/// Generates dummy blockchain with corresponding amount of blocks\n\npub fn generate_dummy_blockchain(block_number: u32) -> BlockChain {\n\n\tlet db = new_db();\n\n\tlet bc = BlockChain::new(BlockChainConfig::default(), &create_unverifiable_block(0, H256::zero()), db.clone());\n\n\n\n\tlet mut batch = db.key_value().transaction();\n\n\tfor block_order in 1..block_number {\n\n\t\t// Total difficulty is always 0 here.\n\n\t\tbc.insert_block(&mut batch, encoded::Block::new(create_unverifiable_block(block_order, bc.best_block_hash())), vec![], ExtrasInsert {\n\n\t\t\tfork_choice: ForkChoice::New,\n\n\t\t\tis_finalized: false,\n\n\t\t});\n\n\t\tbc.commit();\n\n\t}\n\n\tdb.key_value().write(batch).unwrap();\n\n\tbc\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 34, "score": 266514.72678306664 }, { "content": "pub fn decode(raw: &[u8]) -> PanicPayload {\n\n\tlet mut rdr = io::Cursor::new(raw);\n\n\tlet msg = read_string(&mut rdr).ok().and_then(|x| x);\n\n\tlet file = read_string(&mut rdr).ok().and_then(|x| x);\n\n\tlet line = rdr.read_u32::<LittleEndian>().ok();\n\n\tlet col = rdr.read_u32::<LittleEndian>().ok();\n\n\tPanicPayload {\n\n\t\tmsg: msg,\n\n\t\tfile: file,\n\n\t\tline: line,\n\n\t\tcol: col,\n\n\t}\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse super::*;\n\n\tuse byteorder::WriteBytesExt;\n\n\n\n\tfn write_u32(payload: &mut Vec<u8>, val: u32) {\n", "file_path": "parity-ethereum/ethcore/wasm/src/panic_payload.rs", "rank": 35, "score": 264856.63292406726 }, { "content": "fn dump_state(state: &State<state_db::StateDB>) -> Option<PodState> {\n\n\tstate.to_pod_full().ok()\n\n}\n\n\n\nimpl<'a> fmt::Debug for EvmTestClient<'a> {\n\n\tfn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n\n\t\tfmt.debug_struct(\"EvmTestClient\")\n\n\t\t\t.field(\"state\", &self.state)\n\n\t\t\t.field(\"spec\", &self.spec.name)\n\n\t\t\t.finish()\n\n\t}\n\n}\n\n\n\nimpl<'a> EvmTestClient<'a> {\n\n\t/// Converts a json spec definition into spec.\n\n\tpub fn fork_spec_from_json(spec: &ForkSpec) -> Option<spec::Spec> {\n\n\t\tmatch *spec {\n\n\t\t\tForkSpec::Frontier => Some(spec::new_frontier_test()),\n\n\t\t\tForkSpec::Homestead => Some(spec::new_homestead_test()),\n\n\t\t\tForkSpec::EIP150 => Some(spec::new_eip150_test()),\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/evm_test_client.rs", "rank": 36, "score": 264339.1937667609 }, { "content": "fn create_unverifiable_block(order: u32, parent_hash: H256) -> Bytes {\n\n\tcreate_test_block(&create_unverifiable_block_header(order, parent_hash))\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 37, "score": 264327.23631302005 }, { "content": "/// Generates dummy blockchain with corresponding amount of blocks (using creation with extra method for blocks creation)\n\npub fn generate_dummy_blockchain_with_extra(block_number: u32) -> BlockChain {\n\n\tlet db = new_db();\n\n\tlet bc = BlockChain::new(BlockChainConfig::default(), &create_unverifiable_block(0, H256::zero()), db.clone());\n\n\n\n\tlet mut batch = db.key_value().transaction();\n\n\tfor block_order in 1..block_number {\n\n\t\t// Total difficulty is always 0 here.\n\n\t\tbc.insert_block(&mut batch, encoded::Block::new(create_unverifiable_block_with_extra(block_order, bc.best_block_hash(), None)), vec![], ExtrasInsert {\n\n\t\t\tfork_choice: ForkChoice::New,\n\n\t\t\tis_finalized: false,\n\n\t\t});\n\n\t\tbc.commit();\n\n\t}\n\n\tdb.key_value().write(batch).unwrap();\n\n\tbc\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 38, "score": 263190.59398460004 }, { "content": "/// Difficulty quick check for POW preverification\n\n///\n\n/// `header_hash` The hash of the header\n\n/// `nonce` The block's nonce\n\n/// `mix_hash` The mix digest hash\n\n/// Boundary recovered from mix hash\n\npub fn quick_get_difficulty(header_hash: &H256, nonce: u64, mix_hash: &H256, progpow: bool) -> H256 {\n\n\tunsafe {\n\n\t\tif progpow {\n\n\t\t\tlet seed = keccak_f800_short(*header_hash, nonce, [0u32; 8]);\n\n\t\t\tkeccak_f800_long(*header_hash, seed, mem::transmute(*mix_hash))\n\n\t\t} else {\n\n\t\t\tlet mut buf = [0u8; 64 + 32];\n\n\n\n\t\t\tlet hash_len = header_hash.len();\n\n\t\t\tbuf[..hash_len].copy_from_slice(header_hash);\n\n\t\t\tbuf[hash_len..hash_len + mem::size_of::<u64>()].copy_from_slice(&nonce.to_ne_bytes());\n\n\n\n\t\t\tkeccak_512::unchecked(buf.as_mut_ptr(), 64, buf.as_ptr(), 40);\n\n\t\t\tbuf[64..].copy_from_slice(mix_hash);\n\n\n\n\t\t\tlet mut hash = [0u8; 32];\n\n\t\t\tkeccak_256::unchecked(hash.as_mut_ptr(), hash.len(), buf.as_ptr(), buf.len());\n\n\n\n\t\t\thash\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethash/src/compute.rs", "rank": 39, "score": 262952.78382842825 }, { "content": "/// Verify that the data hash with a vector of proofs will produce the Merkle root. Also need the\n\n/// index of data and `leaf_size`, the total number of leaves.\n\npub fn verify(root: &H256, data: &H256, proof: &[H256], index: usize, leaf_size: usize) -> bool {\n\n if index >= leaf_size {\n\n return false;\n\n }\n\n let mut this_layer_size = leaf_size;\n\n let mut layer_size = vec![];\n\n loop {\n\n if this_layer_size == 1 {\n\n layer_size.push(this_layer_size);\n\n break;\n\n }\n\n if this_layer_size & 0x01 == 1 {\n\n this_layer_size += 1;\n\n }\n\n layer_size.push(this_layer_size);\n\n this_layer_size >>= 1;\n\n }\n\n //DELETE:println!(\"Verify, layer size len: {}, proof len: {}\", layer_size.len(), proof.len());\n\n if layer_size.len() != proof.len() + 1 {\n\n return false;\n", "file_path": "src/crypto/merkle.rs", "rank": 40, "score": 262907.4132317417 }, { "content": "/// Generates dummy client (not test client) with corresponding amount of blocks\n\npub fn generate_dummy_client(block_number: u32) -> Arc<Client> {\n\n\tgenerate_dummy_client_with_spec_and_data(spec::new_test, block_number, 0, &[], false)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 41, "score": 262650.480384398 }, { "content": "pub fn slow_hash_block_number(block_number: u64) -> H256 {\n\n\tSeedHashCompute::resume_compute_seedhash([0u8; 32], 0, block_number / ETHASH_EPOCH_LENGTH)\n\n}\n\n\n", "file_path": "parity-ethereum/ethash/src/compute.rs", "rank": 42, "score": 261872.6896747836 }, { "content": "pub fn to_addresses(s: &Option<String>) -> Result<Vec<Address>, String> {\n\n\tmatch *s {\n\n\t\tSome(ref adds) if !adds.is_empty() => adds.split(',')\n\n\t\t\t.map(|a| clean_0x(a).parse().map_err(|_| format!(\"Invalid address: {:?}\", a)))\n\n\t\t\t.collect(),\n\n\t\t_ => Ok(Vec::new()),\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/parity/helpers.rs", "rank": 43, "score": 261678.5819051428 }, { "content": "fn create_unverifiable_block_header(order: u32, parent_hash: H256) -> Header {\n\n\tlet mut header = Header::new();\n\n\theader.set_gas_limit(0.into());\n\n\theader.set_difficulty((order * 100).into());\n\n\theader.set_timestamp((order * 10) as u64);\n\n\theader.set_number(order as u64);\n\n\theader.set_parent_hash(parent_hash);\n\n\theader.set_state_root(H256::zero());\n\n\n\n\theader\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 44, "score": 260992.21773735073 }, { "content": "/// Validate a block that already passes pow and sortition test. See if parents/refs are missing.\n\npub fn check_data_availability(\n\n block: &Block,\n\n blockchain: &BlockChain,\n\n blockdb: &BlockDatabase,\n\n) -> BlockResult {\n\n let mut missing = vec![];\n\n\n\n // check whether the parent exists\n\n let parent = block.header.parent;\n\n let parent_availability = check_proposer_block_exists(parent, blockchain);\n\n if !parent_availability {\n\n missing.push(parent);\n\n }\n\n\n\n // match the block type and check content\n\n match &block.content {\n\n Content::Proposer(content) => {\n\n // check for missing references\n\n let missing_refs =\n\n proposer_block::get_missing_references(&content, blockchain, blockdb);\n", "file_path": "src/validation/mod.rs", "rank": 45, "score": 259542.03213307608 }, { "content": "/// Check block content semantic\n\npub fn check_content_semantic(\n\n block: &Block,\n\n blockchain: &BlockChain,\n\n _blockdb: &BlockDatabase,\n\n) -> BlockResult {\n\n let parent = block.header.parent;\n\n match &block.content {\n\n Content::Proposer(content) => {\n\n // check refed proposer level should be less than its level\n\n if !proposer_block::check_ref_proposer_level(&parent, &content, blockchain) {\n\n return BlockResult::WrongProposerRef;\n\n }\n\n BlockResult::Pass\n\n }\n\n Content::Voter(content) => {\n\n // check chain number\n\n if !voter_block::check_chain_number(&content, blockchain) {\n\n return BlockResult::WrongChainNumber;\n\n }\n\n // check whether all proposer levels deeper than the one our parent voted are voted\n", "file_path": "src/validation/mod.rs", "rank": 46, "score": 259535.63890030255 }, { "content": "/// Returns sequence of hashes of the dummy blocks\n\npub fn get_good_dummy_block_seq(count: usize) -> Vec<Bytes> {\n\n\tlet test_spec = spec::new_test();\n\n\tget_good_dummy_block_fork_seq(1, count, &test_spec.genesis_header().hash())\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 47, "score": 259313.4764903318 }, { "content": "#[cfg(test)]\n\npub fn create_default_decryption_session() -> Arc<SessionImpl> {\n\n\tuse acl_storage::DummyAclStorage;\n\n\tuse key_server_cluster::cluster::tests::DummyCluster;\n\n\tuse ethereum_types::H512;\n\n\n\n\tArc::new(SessionImpl::new(SessionParams {\n\n\t\tmeta: SessionMeta {\n\n\t\t\tid: Default::default(),\n\n\t\t\tself_node_id: Default::default(),\n\n\t\t\tmaster_node_id: Default::default(),\n\n\t\t\tthreshold: 0,\n\n\t\t\tconfigured_nodes_count: 0,\n\n\t\t\tconnected_nodes_count: 0,\n\n\t\t},\n\n\t\taccess_key: Secret::zero(),\n\n\t\tkey_share: Default::default(),\n\n\t\tacl_storage: Arc::new(DummyAclStorage::default()),\n\n\t\tcluster: Arc::new(DummyCluster::new(Default::default())),\n\n\t\tnonce: 0,\n\n\t}, Some(Requester::Public(H512::from_low_u64_be(2)))).unwrap().0)\n", "file_path": "parity-ethereum/secret-store/src/key_server_cluster/client_sessions/decryption_session.rs", "rank": 48, "score": 259157.9152157894 }, { "content": "/// Convert an Ethash boundary to its original difficulty. Basically just `f(x) = 2^256 / x`.\n\npub fn boundary_to_difficulty(boundary: &ethereum_types::H256) -> U256 {\n\n\tdifficulty_to_boundary_aux(&boundary.into_uint())\n\n}\n\n\n", "file_path": "parity-ethereum/ethash/src/lib.rs", "rank": 49, "score": 258668.13189951668 }, { "content": "/// Convert an Ethash difficulty to the target boundary. Basically just `f(x) = 2^256 / x`.\n\npub fn difficulty_to_boundary(difficulty: &U256) -> ethereum_types::H256 {\n\n\tBigEndianHash::from_uint(&difficulty_to_boundary_aux(difficulty))\n\n}\n\n\n", "file_path": "parity-ethereum/ethash/src/lib.rs", "rank": 50, "score": 258668.13189951668 }, { "content": "#[test]\n\nfn get_state_proofs() {\n\n\tlet capabilities = capabilities();\n\n\n\n\tlet (provider, proto) = setup(capabilities);\n\n\tlet flow_params = proto.flow_params.read().clone();\n\n\n\n\tlet provider = TestProvider(provider);\n\n\n\n\tlet cur_status = status(provider.0.client.chain_info());\n\n\n\n\t{\n\n\t\tlet packet_body = write_handshake(&cur_status, &capabilities, &proto);\n\n\t\tproto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body.clone()));\n\n\t\tproto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &packet_body);\n\n\t}\n\n\n\n\tlet req_id = 112;\n\n\tlet key1: H256 = BigEndianHash::from_uint(&U256::from(11223344));\n\n\tlet key2: H256 = BigEndianHash::from_uint(&U256::from(99988887));\n\n\n", "file_path": "parity-ethereum/ethcore/light/src/net/tests/mod.rs", "rank": 51, "score": 258295.54731595947 }, { "content": "pub fn keccak_f800_long(header_hash: H256, nonce: u64, result: [u32; 8]) -> H256 {\n\n\tlet mut st = [0u32; 25];\n\n\tkeccak_f800(header_hash, nonce, result, &mut st);\n\n\n\n\t// NOTE: transmute from `[u32; 8]` to `[u8; 32]`\n\n\tunsafe {\n\n\t\tstd::mem::transmute(\n\n\t\t\t[st[0], st[1], st[2], st[3], st[4], st[5], st[6], st[7]]\n\n\t\t)\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethash/src/progpow.rs", "rank": 52, "score": 258039.55141651313 }, { "content": "/// Creates test block with corresponding header and data\n\npub fn create_test_block_with_data(header: &Header, transactions: &[SignedTransaction], uncles: &[Header]) -> Bytes {\n\n\tlet mut rlp = RlpStream::new_list(3);\n\n\trlp.append(header);\n\n\trlp.begin_list(transactions.len());\n\n\tfor t in transactions {\n\n\t\trlp.append_raw(&rlp::encode(t), 1);\n\n\t}\n\n\trlp.append_list(&uncles);\n\n\trlp.out()\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 53, "score": 255991.13508820118 }, { "content": "/// Provide a `HashSet` of all accounts available for import from the Geth keystore.\n\npub fn read_geth_accounts(testnet: bool) -> Vec<Address> {\n\n\tRootDiskDirectory::at(dir::geth(testnet))\n\n\t\t.load()\n\n\t\t.map(|d| d.into_iter().map(|a| a.address).collect())\n\n\t\t.unwrap_or_else(|_| Vec::new())\n\n}\n\n\n", "file_path": "parity-ethereum/accounts/ethstore/src/import.rs", "rank": 54, "score": 255978.29184918606 }, { "content": "/// Adds one block with transactions\n\npub fn push_block_with_transactions(client: &Arc<Client>, transactions: &[SignedTransaction]) {\n\n\tlet test_spec = spec::new_test();\n\n\tlet test_engine = &*test_spec.engine;\n\n\tlet block_number = client.chain_info().best_block_number as u64 + 1;\n\n\n\n\tlet mut b = client.prepare_open_block(Address::zero(), (0.into(), 5000000.into()), Bytes::new()).unwrap();\n\n\tb.set_timestamp(block_number * 10);\n\n\n\n\tfor t in transactions {\n\n\t\tb.push_transaction(t.clone(), None).unwrap();\n\n\t}\n\n\tlet b = b.close_and_lock().unwrap().seal(test_engine, vec![]).unwrap();\n\n\n\n\tif let Err(e) = client.import_block(Unverified::from_rlp(b.rlp_bytes()).unwrap()) {\n\n\t\tpanic!(\"error importing block which is valid by definition: {:?}\", e);\n\n\t}\n\n\n\n\tclient.flush_queue();\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 55, "score": 255846.6351495906 }, { "content": "#[test]\n\nfn fork_post_cht() {\n\n\tconst CHAIN_LENGTH: u64 = 50; // shouldn't be longer than ::light::cht::size();\n\n\n\n\tlet mut net = TestNet::light(1, 2);\n\n\n\n\t// peer 2 is on a higher TD chain.\n\n\tnet.peer(1).chain().add_blocks(CHAIN_LENGTH as usize, EachBlockWith::Nothing);\n\n\tnet.peer(2).chain().add_blocks(CHAIN_LENGTH as usize + 1, EachBlockWith::Uncle);\n\n\n\n\t// get the light peer on peer 1's chain.\n\n\tfor id in (0..CHAIN_LENGTH).map(|x| x + 1).map(BlockId::Number) {\n\n\t\tlet (light_peer, full_peer) = (net.peer(0), net.peer(1));\n\n\t\tlet light_chain = light_peer.light_chain();\n\n\t\tlet header = full_peer.chain().block_header(id).unwrap().decode().expect(\"decoding failure\");\n\n\t\tlet _ = light_chain.import_header(header);\n\n\t\tlight_chain.flush_queue();\n\n\t\tlight_chain.import_verified();\n\n\t\tassert!(light_chain.block_header(id).is_some());\n\n\t}\n\n\n\n\tnet.sync();\n\n\n\n\tfor id in (0..CHAIN_LENGTH).map(|x| x + 1).map(BlockId::Number) {\n\n\t\tassert_eq!(\n\n\t\t\tnet.peer(0).light_chain().block_header(id).unwrap(),\n\n\t\t\tnet.peer(2).chain().block_header(id).unwrap()\n\n\t\t);\n\n\t}\n\n}\n", "file_path": "parity-ethereum/ethcore/sync/src/light_sync/tests/mod.rs", "rank": 56, "score": 254490.41616191802 }, { "content": "/// encodes and hashes the given EIP712 struct\n\npub fn hash_structured_data(typed_data: EIP712) -> Result<H256> {\n\n\t// validate input\n\n\ttyped_data.validate()?;\n\n\t// EIP-191 compliant\n\n\tlet prefix = (b\"\\x19\\x01\").to_vec();\n\n\tlet domain = to_value(&typed_data.domain).unwrap();\n\n\tlet (domain_hash, data_hash) = (\n\n\t\tencode_data(\n\n\t\t\t&Type::Custom(\"EIP712Domain\".into()),\n\n\t\t\t&typed_data.types,\n\n\t\t\t&domain,\n\n\t\t\tNone\n\n\t\t)?,\n\n\t\tencode_data(\n\n\t\t\t&Type::Custom(typed_data.primary_type),\n\n\t\t\t&typed_data.types,\n\n\t\t\t&typed_data.message,\n\n\t\t\tNone\n\n\t\t)?\n\n\t);\n", "file_path": "parity-ethereum/util/EIP-712/src/encode.rs", "rank": 57, "score": 253199.0139990049 }, { "content": "/// Creates a new temporary `BlockChainDB` on FS\n\npub fn new_temp_db(tempdir: &Path) -> Arc<dyn BlockChainDB> {\n\n\tlet blooms_dir = TempDir::new(\"\").unwrap();\n\n\tlet trace_blooms_dir = TempDir::new(\"\").unwrap();\n\n\tlet key_value_dir = tempdir.join(\"key_value\");\n\n\n\n\tlet db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);\n\n\tlet key_value_db = Database::open(&db_config, key_value_dir.to_str().unwrap()).unwrap();\n\n\n\n\tlet db = TestBlockChainDB {\n\n\t\tblooms: blooms_db::Database::open(blooms_dir.path()).unwrap(),\n\n\t\ttrace_blooms: blooms_db::Database::open(trace_blooms_dir.path()).unwrap(),\n\n\t\t_blooms_dir: blooms_dir,\n\n\t\t_trace_blooms_dir: trace_blooms_dir,\n\n\t\tkey_value: Arc::new(key_value_db)\n\n\t};\n\n\n\n\tArc::new(db)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 58, "score": 252627.34317361866 }, { "content": "struct Verification<K: Kind> {\n\n\t// All locks must be captured in the order declared here.\n\n\tunverified: LenCachingMutex<VecDeque<K::Unverified>>,\n\n\tverifying: LenCachingMutex<VecDeque<Verifying<K>>>,\n\n\tverified: LenCachingMutex<VecDeque<K::Verified>>,\n\n\tbad: Mutex<HashSet<H256>>,\n\n\tsizes: Sizes,\n\n\tcheck_seal: bool,\n\n}\n\n\n\nimpl<K: Kind, C> VerificationQueue<K, C> {\n\n\t/// Creates a new queue instance.\n\n\tpub fn new(config: Config, engine: Arc<dyn Engine>, message_channel: IoChannel<ClientIoMessage<C>>, check_seal: bool) -> Self {\n\n\t\tlet verification = Arc::new(Verification {\n\n\t\t\tunverified: LenCachingMutex::new(VecDeque::new()),\n\n\t\t\tverifying: LenCachingMutex::new(VecDeque::new()),\n\n\t\t\tverified: LenCachingMutex::new(VecDeque::new()),\n\n\t\t\tbad: Mutex::new(HashSet::new()),\n\n\t\t\tsizes: Sizes {\n\n\t\t\t\tunverified: AtomicUsize::new(0),\n", "file_path": "parity-ethereum/ethcore/verification/src/queue/mod.rs", "rank": 59, "score": 252245.6874923411 }, { "content": "/// Check a proof for a CHT.\n\n/// Given a set of a trie nodes, a number to query, and a trie root,\n\n/// verify the given trie branch and extract the canonical hash and total difficulty.\n\n// TODO: better support for partially-checked queries.\n\npub fn check_proof(proof: &[Bytes], num: u64, root: H256) -> Option<(H256, U256)> {\n\n\tlet mut db = new_memory_db();\n\n\n\n\tfor node in proof { db.insert(hash_db::EMPTY_PREFIX, &node[..]); }\n\n\tlet res = match TrieDB::new(&db, &root) {\n\n\t\tErr(_) => return None,\n\n\t\tOk(trie) => trie.get_with(&key!(num), |val: &[u8]| {\n\n\t\t\tlet rlp = Rlp::new(val);\n\n\t\t\trlp.val_at::<H256>(0)\n\n\t\t\t\t.and_then(|h| rlp.val_at::<U256>(1).map(|td| (h, td)))\n\n\t\t\t\t.ok()\n\n\t\t})\n\n\t};\n\n\n\n\tmatch res {\n\n\t\tOk(Some(Some((hash, td)))) => Some((hash, td)),\n\n\t\t_ => None,\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/light/src/cht.rs", "rank": 60, "score": 252016.63803316685 }, { "content": "#[inline]\n\nfn combine_key<'a>(address_hash: &'a H256, key: &'a H256) -> H256 {\n\n\tlet mut dst = key.clone();\n\n\t{\n\n\t\tlet last_src: &[u8] = address_hash.as_bytes();\n\n\t\tlet last_dst: &mut [u8] = dst.as_bytes_mut();\n\n\t\tfor (k, a) in last_dst[12..].iter_mut().zip(&last_src[12..]) {\n\n\t\t\t*k ^= *a\n\n\t\t}\n\n\t}\n\n\n\n\tdst\n\n}\n\n\n\n/// A factory for different kinds of account dbs.\n\n#[derive(Debug, Clone)]\n\npub enum Factory {\n\n\t/// Mangle hashes based on address. This is the default.\n\n\tMangled,\n\n\t/// Don't mangle hashes.\n\n\tPlain,\n", "file_path": "parity-ethereum/ethcore/account-db/src/lib.rs", "rank": 61, "score": 251718.87642326904 }, { "content": "fn no_dump_state(_: &State<state_db::StateDB>) -> Option<PodState> {\n\n\tNone\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/evm_test_client.rs", "rank": 62, "score": 250735.77574960492 }, { "content": "#[test]\n\nfn should_return_none_when_transaction_from_given_address_does_not_exist() {\n\n\t// given\n\n\tlet txq = new_queue();\n\n\n\n\t// then\n\n\tassert_eq!(txq.next_nonce(TestClient::new(), &Default::default()), None);\n\n}\n\n\n", "file_path": "parity-ethereum/miner/src/pool/tests/mod.rs", "rank": 63, "score": 250625.4966473187 }, { "content": "/// Returns vector of logs topics to listen to.\n\npub fn mask_topics(mask: &ApiMask) -> Vec<H256> {\n\n\tlet mut topics = Vec::new();\n\n\tif mask.server_key_generation_requests {\n\n\t\ttopics.push(*SERVER_KEY_GENERATION_REQUESTED_EVENT_NAME_HASH);\n\n\t}\n\n\tif mask.server_key_retrieval_requests {\n\n\t\ttopics.push(*SERVER_KEY_RETRIEVAL_REQUESTED_EVENT_NAME_HASH);\n\n\t}\n\n\tif mask.document_key_store_requests {\n\n\t\ttopics.push(*DOCUMENT_KEY_STORE_REQUESTED_EVENT_NAME_HASH);\n\n\t}\n\n\tif mask.document_key_shadow_retrieval_requests {\n\n\t\ttopics.push(*DOCUMENT_KEY_COMMON_PART_RETRIEVAL_REQUESTED_EVENT_NAME_HASH);\n\n\t\ttopics.push(*DOCUMENT_KEY_PERSONAL_PART_RETRIEVAL_REQUESTED_EVENT_NAME_HASH);\n\n\t}\n\n\ttopics\n\n}\n\n\n\nimpl ServerKeyGenerationService {\n\n\t/// Parse request log entry.\n", "file_path": "parity-ethereum/secret-store/src/listener/service_contract.rs", "rank": 64, "score": 250595.97409480135 }, { "content": "/// Check the given proof of execution.\n\n/// `Err(ExecutionError::Internal)` indicates failure, everything else indicates\n\n/// a successful proof (as the transaction itself may be poorly chosen).\n\npub fn check_proof(\n\n\tproof: &[DBValue],\n\n\troot: H256,\n\n\ttransaction: &SignedTransaction,\n\n\tmachine: &Machine,\n\n\tenv_info: &EnvInfo,\n\n) -> ProvedExecution {\n\n\tlet backend = self::backend::ProofCheck::new(proof);\n\n\tlet mut factories = Factories::default();\n\n\tfactories.accountdb = account_db::Factory::Plain;\n\n\n\n\tlet res = State::from_existing(\n\n\t\tbackend,\n\n\t\troot,\n\n\t\tmachine.account_start_nonce(env_info.number),\n\n\t\tfactories\n\n\t);\n\n\n\n\tlet mut state = match res {\n\n\t\tOk(state) => state,\n", "file_path": "parity-ethereum/ethcore/executive-state/src/lib.rs", "rank": 65, "score": 249881.79625139112 }, { "content": "struct TestOracle(HashMap<H256, u64>);\n\n\n\nimpl Oracle for TestOracle {\n\n\tfn to_number(&self, hash: H256) -> Option<u64> {\n\n\t\tself.0.get(&hash).cloned()\n\n\t}\n\n\n\n\tfn is_major_importing(&self) -> bool { false }\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/snapshot/snapshot-tests/src/watcher.rs", "rank": 66, "score": 249505.99770953498 }, { "content": "/// Open a new light client DB.\n\npub fn open_db_light(\n\n\tclient_path: &str,\n\n\tcache_config: &CacheConfig,\n\n\tcompaction: &DatabaseCompactionProfile\n\n) -> io::Result<Arc<dyn BlockChainDB>> {\n\n\tlet path = Path::new(client_path);\n\n\n\n\tlet db_config = DatabaseConfig {\n\n\t\tmemory_budget: helpers::memory_per_column_light(cache_config.blockchain() as usize),\n\n\t\tcompaction: helpers::compaction_profile(&compaction, path),\n\n\t\t.. DatabaseConfig::with_columns(NUM_COLUMNS)\n\n\t};\n\n\n\n\topen_database(client_path, &db_config)\n\n}\n\n\n", "file_path": "parity-ethereum/parity/db/rocksdb/mod.rs", "rank": 67, "score": 249460.838477958 }, { "content": "#[inline]\n\nfn u256_to_address(value: &U256) -> Address {\n\n\tlet addr: H256 = BigEndianHash::from_uint(value);\n\n\tAddress::from(addr)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/evm/src/interpreter/mod.rs", "rank": 68, "score": 249423.4421202216 }, { "content": "#[inline]\n\nfn address_to_u256(value: Address) -> U256 {\n\n\tH256::from(value).into_uint()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse std::sync::Arc;\n\n\tuse rustc_hex::FromHex;\n\n\tuse factory::Factory;\n\n\tuse vm::{self, Exec, ActionParams, ActionValue};\n\n\tuse vm::tests::{FakeExt, test_finalize};\n\n\tuse ethereum_types::Address;\n\n\n\n\tfn interpreter(params: ActionParams, ext: &dyn vm::Ext) -> Box<dyn Exec> {\n\n\t\tFactory::new(1).create(params, ext.schedule(), ext.depth())\n\n\t}\n\n\n\n\t#[test]\n\n\tfn should_not_fail_on_tracing_mem() {\n\n\t\tlet code = \"7feeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff006000527faaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa6020526000620f120660406000601773945304eb96065b2a98b57a48a06ae28d285a71b56101f4f1600055\".from_hex().unwrap();\n", "file_path": "parity-ethereum/ethcore/evm/src/interpreter/mod.rs", "rank": 69, "score": 249423.4421202216 }, { "content": "/// Restore a snapshot into a given database. This will read chunks from the given reader\n\n/// write into the given database.\n\npub fn restore(\n\n\tdb: Arc<dyn BlockChainDB>,\n\n\tengine: &dyn Engine,\n\n\treader: &dyn SnapshotReader,\n\n\tgenesis: &[u8],\n\n) -> Result<(), EthcoreError> {\n\n\tlet flag = AtomicBool::new(true);\n\n\tlet chunker = chunker(engine.snapshot_mode()).expect(\"the engine used here supports snapshots\");\n\n\tlet manifest = reader.manifest();\n\n\n\n\tlet mut state = StateRebuilder::new(db.key_value().clone(), journaldb::Algorithm::Archive);\n\n\tlet mut secondary = {\n\n\t\tlet chain = BlockChain::new(Default::default(), genesis, db.clone());\n\n\t\tchunker.rebuilder(chain, db, manifest).unwrap()\n\n\t};\n\n\n\n\tlet mut snappy_buffer = Vec::new();\n\n\n\n\ttrace!(target: \"snapshot\", \"restoring state\");\n\n\tfor state_chunk_hash in manifest.state_hashes.iter() {\n", "file_path": "parity-ethereum/ethcore/snapshot/snapshot-tests/src/helpers.rs", "rank": 70, "score": 249351.75370386356 }, { "content": "/// Recover block creator from signature\n\npub fn recover_creator(header: &Header) -> Result<Address, Error> {\n\n\t// Initialization\n\n\tlet mut cache = CREATOR_BY_HASH.write();\n\n\n\n\tif let Some(creator) = cache.get_mut(&header.hash()) {\n\n\t\treturn Ok(*creator);\n\n\t}\n\n\n\n\tlet data = header.extra_data();\n\n\tif data.len() < VANITY_LENGTH {\n\n\t\tErr(EngineError::CliqueMissingVanity)?\n\n\t}\n\n\n\n\tif data.len() < VANITY_LENGTH + SIGNATURE_LENGTH {\n\n\t\tErr(EngineError::CliqueMissingSignature)?\n\n\t}\n\n\n\n\t// Split `signed_extra data` and `signature`\n\n\tlet (signed_data_slice, signature_slice) = data.split_at(data.len() - SIGNATURE_LENGTH);\n\n\n", "file_path": "parity-ethereum/ethcore/engines/clique/src/util.rs", "rank": 71, "score": 247918.41043012886 }, { "content": "/// Walk the given state database starting from the given root,\n\n/// creating chunks and writing them out.\n\n/// `part` is a number between 0 and 15, which describe which part of\n\n/// the tree should be chunked.\n\n///\n\n/// Returns a list of hashes of chunks created, or any error it may\n\n/// have encountered.\n\npub fn chunk_state<'a>(\n\n\tdb: &dyn HashDB<KeccakHasher, DBValue>,\n\n\troot: &H256,\n\n\twriter: &Mutex<dyn SnapshotWriter + 'a>,\n\n\tprogress: &'a RwLock<Progress>,\n\n\tpart: Option<usize>,\n\n\tthread_idx: usize,\n\n) -> Result<Vec<H256>, Error> {\n\n\tlet account_trie = TrieDB::new(&db, &root)?;\n\n\n\n\tlet mut chunker = StateChunker {\n\n\t\thashes: Vec::new(),\n\n\t\trlps: Vec::new(),\n\n\t\tcur_size: 0,\n\n\t\tsnappy_buffer: vec![0; snappy::max_compressed_len(PREFERRED_CHUNK_SIZE)],\n\n\t\twriter,\n\n\t\tprogress,\n\n\t\tthread_idx,\n\n\t};\n\n\n", "file_path": "parity-ethereum/ethcore/snapshot/src/lib.rs", "rank": 72, "score": 247503.8893657079 }, { "content": "#[test]\n\nfn rpc_trace_raw_transaction_state_pruned() {\n\n\tlet tester = io();\n\n\t*tester.client.execution_result.write() = Some(Err(CallError::StatePruned));\n\n\n\n\tlet request = r#\"{\"jsonrpc\":\"2.0\",\"method\":\"trace_rawTransaction\",\"params\":[\"0xf869018609184e72a0008276c094d46e8dd67c5d32be8058bb8eb970870f07244567849184e72a801ba0617f39c1a107b63302449c476d96a6cb17a5842fc98ff0c5bcf4d5c4d8166b95a009fdb6097c6196b9bbafc3a59f02f38d91baeef23d0c60a8e4f23c7714cea3a9\", [\"stateDiff\", \"vmTrace\", \"trace\"]],\"id\":1}\"#;\n\n\tlet response = r#\"{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32000,\"message\":\"This request is not supported because your node is running with state pruning. Run with --pruning=archive.\"},\"id\":1}\"#;\n\n\n\n\tassert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));\n\n}\n\n\n", "file_path": "parity-ethereum/rpc/src/v1/tests/mocked/traces.rs", "rank": 73, "score": 247328.67460701882 }, { "content": "fn is_step_proposer(validators: &dyn ValidatorSet, bh: &H256, step: u64, address: &Address) -> bool {\n\n\tstep_proposer(validators, bh, step) == *address\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/engines/authority-round/src/lib.rs", "rank": 74, "score": 246928.86411150586 }, { "content": "#[test]\n\nfn should_return_correct_nonce_when_transactions_from_given_address_exist() {\n\n\t// given\n\n\tlet txq = new_queue();\n\n\tlet tx = Tx::default().signed();\n\n\tlet from = tx.sender();\n\n\tlet nonce = tx.nonce;\n\n\n\n\t// when\n\n\ttxq.import(TestClient::new(), vec![tx.local()]);\n\n\n\n\t// then\n\n\tassert_eq!(txq.next_nonce(TestClient::new(), &from), Some(nonce + 1 ));\n\n}\n\n\n", "file_path": "parity-ethereum/miner/src/pool/tests/mod.rs", "rank": 75, "score": 246919.28893998946 }, { "content": "#[test]\n\nfn should_handle_same_transaction_imported_twice_with_different_state_nonces() {\n\n\t// given\n\n\tlet txq = new_queue();\n\n\tlet (tx, tx2) = Tx::default().signed_replacement();\n\n\tlet hash = tx2.hash();\n\n\tlet client = TestClient::new().with_nonce(122);\n\n\n\n\t// First insert one transaction to future\n\n\tlet res = txq.import(client.clone(), vec![tx].local());\n\n\tassert_eq!(res, vec![Ok(())]);\n\n\t// next_nonce === None -> transaction is in future\n\n\tassert_eq!(txq.next_nonce(client.clone(), &tx2.sender()), None);\n\n\n\n\t// now import second transaction to current\n\n\tlet res = txq.import(TestClient::new(), vec![tx2.local()]);\n\n\n\n\t// and then there should be only one transaction in current (the one with higher gas_price)\n\n\tassert_eq!(res, vec![Ok(())]);\n\n\tassert_eq!(txq.status().status.transaction_count, 1);\n\n\tlet top = txq.pending(TestClient::new(), PendingSettings::all_prioritized(0, 0));\n\n\tassert_eq!(top[0].hash, hash);\n\n}\n\n\n", "file_path": "parity-ethereum/miner/src/pool/tests/mod.rs", "rank": 76, "score": 246765.37321062403 }, { "content": "/// Run all tests under the given path (except for the test files named in the skip list) using the\n\n/// provided runner function.\n\npub fn run_test_path<H: FnMut(&str, HookType)>(\n\n\tpath: &Path,\n\n\tskip: &[&'static str],\n\n\trunner: fn(path: &Path, json_data: &[u8], start_stop_hook: &mut H) -> Vec<String>,\n\n\tstart_stop_hook: &mut H\n\n) {\n\n\tif !skip.is_empty() {\n\n\t\t// todo[dvdplm] it's really annoying to have to use flushln here. Should be `info!(target:\n\n\t\t// \"json-tests\", …)`. Issue https://github.com/paritytech/parity-ethereum/issues/11084\n\n\t\tflushln!(\"[run_test_path] Skipping tests in {}: {:?}\", path.display(), skip);\n\n\t}\n\n\tlet mut errors = Vec::new();\n\n\trun_test_path_inner(path, skip, runner, start_stop_hook, &mut errors);\n\n\tlet empty: [String; 0] = [];\n\n\tassert_eq!(errors, empty, \"\\nThere were {} tests in '{}' that failed.\", errors.len(), path.display());\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/json_tests/test_common.rs", "rank": 77, "score": 246705.02356433932 }, { "content": "pub fn run_test_file<H: FnMut(&str, HookType)>(\n\n\tpath: &Path,\n\n\trunner: fn(path: &Path, json_data: &[u8], start_stop_hook: &mut H) -> Vec<String>,\n\n\tstart_stop_hook: &mut H\n\n) {\n\n\tlet mut data = Vec::new();\n\n\tlet mut file = match File::open(&path) {\n\n\t\tOk(file) => file,\n\n\t\tErr(_) => panic!(\"Error opening test file at: {:?}\", path),\n\n\t};\n\n\tfile.read_to_end(&mut data).expect(\"Error reading test file\");\n\n\tlet results = runner(&path, &data, start_stop_hook);\n\n\tlet empty: [String; 0] = [];\n\n\tassert_eq!(results, empty);\n\n}\n\n\n\n#[cfg(test)]\n\nmacro_rules! test {\n\n\t($name: expr, $skip: expr) => {\n\n\t\t::json_tests::test_common::run_test_path(\n", "file_path": "parity-ethereum/ethcore/src/json_tests/test_common.rs", "rank": 78, "score": 246691.3832581276 }, { "content": "/// Start WS server and return `Server` handle.\n\npub fn start_ws<M, S, H, T, U, V>(\n\n\taddr: &SocketAddr,\n\n\thandler: H,\n\n\tallowed_origins: ws::DomainsValidation<ws::Origin>,\n\n\tallowed_hosts: ws::DomainsValidation<ws::Host>,\n\n\tmax_connections: usize,\n\n\textractor: T,\n\n\tmiddleware: V,\n\n\tstats: U,\n\n) -> Result<ws::Server, ws::Error> where\n\n\tM: jsonrpc_core::Metadata,\n\n\tS: jsonrpc_core::Middleware<M>,\n\n\tH: Into<jsonrpc_core::MetaIoHandler<M, S>>,\n\n\tT: ws::MetaExtractor<M>,\n\n\tU: ws::SessionStats,\n\n\tV: ws::RequestMiddleware,\n\n{\n\n\tws::ServerBuilder::with_meta_extractor(handler, extractor)\n\n\t\t.request_middleware(middleware)\n\n\t\t.allowed_origins(allowed_origins)\n\n\t\t.allowed_hosts(allowed_hosts)\n\n\t\t.max_connections(max_connections)\n\n\t\t.session_stats(stats)\n\n\t\t.start(addr)\n\n}\n", "file_path": "parity-ethereum/rpc/src/lib.rs", "rank": 79, "score": 245834.09169645282 }, { "content": "/// Calculate Keccak(ordered servers set)\n\npub fn ordered_servers_keccak(servers_set: BTreeSet<H512>) -> H256 {\n\n\tlet mut servers_set_keccak = Keccak::new_keccak256();\n\n\tfor server in servers_set {\n\n\t\tservers_set_keccak.update(&server.0);\n\n\t}\n\n\n\n\tlet mut servers_set_keccak_value = [0u8; 32];\n\n\tservers_set_keccak.finalize(&mut servers_set_keccak_value);\n\n\n\n\tservers_set_keccak_value.into()\n\n}\n\n\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/secretstore.rs", "rank": 80, "score": 245663.6563300566 }, { "content": "/// Convert hash to EC scalar (modulo curve order).\n\npub fn to_scalar(hash: H256) -> Result<Secret, Error> {\n\n\tlet scalar: U256 = hash.into_uint();\n\n\tlet scalar: H256 = BigEndianHash::from_uint(&(scalar % *ec_math_utils::CURVE_ORDER));\n\n\tlet scalar = Secret::from(scalar.0);\n\n\tscalar.check_validity()?;\n\n\tOk(scalar)\n\n}\n\n\n", "file_path": "parity-ethereum/secret-store/src/key_server_cluster/math.rs", "rank": 81, "score": 245229.6940283842 }, { "content": "fn signature(accounts: &AccountProvider, address: Address, hash: H256, password: SignWith) -> Result<WithToken<Signature>> {\n\n\tmatch password.clone() {\n\n\t\tSignWith::Nothing => accounts.sign(address, None, hash).map(WithToken::No),\n\n\t\tSignWith::Password(pass) => accounts.sign(address, Some(pass), hash).map(WithToken::No),\n\n\t\tSignWith::Token(token) => accounts.sign_with_token(address, token, hash).map(Into::into),\n\n\t}.map_err(|e| match password {\n\n\t\tSignWith::Nothing => errors::signing(e),\n\n\t\t_ => errors::password(e),\n\n\t})\n\n}\n\n\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/dispatch/signing.rs", "rank": 82, "score": 243452.37056621374 }, { "content": "fn create_unverifiable_block_with_extra(order: u32, parent_hash: H256, extra: Option<Bytes>) -> Bytes {\n\n\tlet mut header = create_unverifiable_block_header(order, parent_hash);\n\n\theader.set_extra_data(match extra {\n\n\t\tSome(extra_data) => extra_data,\n\n\t\tNone => {\n\n\t\t\tlet base = (order & 0x000000ff) as u8;\n\n\t\t\tlet generated: Vec<u8> = vec![base + 1, base + 2, base + 3];\n\n\t\t\tgenerated\n\n\t\t}\n\n\t});\n\n\tcreate_test_block(&header)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 83, "score": 242015.209879948 }, { "content": "pub fn json_difficulty_test<H: FnMut(&str, HookType)>(\n\n\tpath: &Path,\n\n\tjson_data: &[u8],\n\n\tspec: Spec,\n\n\tstart_stop_hook: &mut H\n\n) -> Vec<String> {\n\n\tlet _ = env_logger::try_init();\n\n\tlet tests = DifficultyTest::load(json_data)\n\n\t\t.expect(&format!(\"Could not parse JSON difficulty test data from {}\", path.display()));\n\n\tlet engine = &spec.engine;\n\n\n\n\tfor (name, test) in tests.into_iter() {\n\n\t\tstart_stop_hook(&name, HookType::OnStart);\n\n\n\n\t\tflush!(\" - {}...\", name);\n\n\t\tprintln!(\" - {}...\", name);\n\n\n\n\t\tlet mut parent_header = Header::new();\n\n\t\tlet block_number: u64 = test.current_block_number.into();\n\n\t\tparent_header.set_number(block_number - 1);\n", "file_path": "parity-ethereum/ethcore/src/json_tests/difficulty.rs", "rank": 84, "score": 241360.98399442335 }, { "content": "/// Default data path\n\npub fn default_data_path() -> String {\n\n\tlet app_info = AppInfo { name: PRODUCT, author: AUTHOR };\n\n\tget_app_root(AppDataType::UserData, &app_info).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| \"$HOME/.parity\".to_owned())\n\n}\n\n\n", "file_path": "parity-ethereum/util/dir/src/lib.rs", "rank": 85, "score": 241331.62752841756 }, { "content": "/// Default local path\n\npub fn default_local_path() -> String {\n\n\tlet app_info = AppInfo { name: PRODUCT, author: AUTHOR };\n\n\tget_app_root(AppDataType::UserCache, &app_info).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| \"$HOME/.parity\".to_owned())\n\n}\n\n\n", "file_path": "parity-ethereum/util/dir/src/lib.rs", "rank": 86, "score": 241331.62752841756 }, { "content": "pub fn state_pruned() -> Error {\n\n\tError {\n\n\t\tcode: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST),\n\n\t\tmessage: \"This request is not supported because your node is running with state pruning. Run with --pruning=archive.\".into(),\n\n\t\tdata: None,\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/errors.rs", "rank": 87, "score": 241151.0198565488 }, { "content": "pub fn state_corrupt() -> Error {\n\n\tinternal(\"State corrupt\", \"\")\n\n}\n\n\n", "file_path": "parity-ethereum/rpc/src/v1/helpers/errors.rs", "rank": 88, "score": 241151.0198565488 }, { "content": "#[cfg(test)]\n\npub fn new_test_cluster(\n\n\tmessages: MessagesQueue,\n\n\tconfig: ClusterConfiguration,\n\n) -> Result<Arc<ClusterCore<Arc<TestConnections>>>, Error> {\n\n\tlet nodes = config.key_server_set.snapshot().current_set;\n\n\tlet connections = new_test_connections(messages, *config.self_key_pair.public(), nodes.keys().cloned().collect());\n\n\n\n\tlet connection_trigger = Box::new(SimpleConnectionTrigger::with_config(&config));\n\n\tlet servers_set_change_creator_connector = connection_trigger.servers_set_change_creator_connector();\n\n\tlet mut sessions = ClusterSessions::new(&config, servers_set_change_creator_connector.clone());\n\n\tif config.preserve_sessions {\n\n\t\tsessions.preserve_sessions();\n\n\t}\n\n\tlet sessions = Arc::new(sessions);\n\n\n\n\tlet message_processor = Arc::new(SessionsMessageProcessor::new(\n\n\t\tconfig.self_key_pair.clone(),\n\n\t\tservers_set_change_creator_connector.clone(),\n\n\t\tsessions.clone(),\n\n\t\tconnections.provider(),\n", "file_path": "parity-ethereum/secret-store/src/key_server_cluster/cluster.rs", "rank": 89, "score": 240390.59199733203 }, { "content": "pub fn block_gas_limit(full_client: &dyn BlockChainClient, header: &Header, address: Address) -> Option<U256> {\n\n\tlet (data, decoder) = contract::functions::block_gas_limit::call();\n\n\tlet value = full_client.call_contract(BlockId::Hash(*header.parent_hash()), address, data).map_err(|err| {\n\n\t\terror!(target: \"block_gas_limit\", \"Contract call failed. Not changing the block gas limit. {:?}\", err);\n\n\t}).ok()?;\n\n\tif value.is_empty() {\n\n\t\tdebug!(target: \"block_gas_limit\", \"Contract call returned nothing. Not changing the block gas limit.\");\n\n\t\tNone\n\n\t} else {\n\n\t\tdecoder.decode(&value).ok()\n\n\t}\n\n}\n", "file_path": "parity-ethereum/ethcore/block-gas-limit/src/lib.rs", "rank": 90, "score": 239553.81979836067 }, { "content": "/// Tiny wrapper around executive externalities.\n\n/// Stores callcreates.\n\nstruct TestExt<'a, T: 'a, V: 'a, B: 'a>\n\n\twhere T: Tracer, V: VMTracer, B: StateBackend\n\n{\n\n\text: Externalities<'a, T, V, B>,\n\n\tcallcreates: Vec<CallCreate>,\n\n\tnonce: U256,\n\n\tsender: Address,\n\n}\n\n\n\nimpl<'a, T: 'a, V: 'a, B: 'a> TestExt<'a, T, V, B>\n\n\twhere T: Tracer, V: VMTracer, B: StateBackend,\n\n{\n\n\tfn new(\n\n\t\tstate: &'a mut State<B>,\n\n\t\tinfo: &'a EnvInfo,\n\n\t\tmachine: &'a Machine,\n\n\t\tschedule: &'a Schedule,\n\n\t\tdepth: usize,\n\n\t\torigin_info: &'a OriginInfo,\n\n\t\tsubstate: &'a mut Substate,\n", "file_path": "parity-ethereum/ethcore/src/json_tests/executive.rs", "rank": 91, "score": 238866.21279099863 }, { "content": "/// Compute a CHT root from an iterator of (hash, td) pairs. Fails if shorter than\n\n/// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.\n\n/// Discards the trie's nodes.\n\npub fn compute_root<I>(cht_num: u64, iterable: I) -> Option<H256>\n\n\twhere I: IntoIterator<Item=(H256, U256)>\n\n{\n\n\tlet mut v = Vec::with_capacity(SIZE as usize);\n\n\tlet start_num = start_number(cht_num) as usize;\n\n\n\n\tfor (i, (h, td)) in iterable.into_iter().take(SIZE as usize).enumerate() {\n\n\t\tv.push((key!(i + start_num), val!(h, td)))\n\n\t}\n\n\n\n\tif v.len() == SIZE as usize {\n\n\t\tSome(::triehash::trie_root(v))\n\n\t} else {\n\n\t\tNone\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/light/src/cht.rs", "rank": 92, "score": 238614.54233726204 }, { "content": "/// Default hypervisor path\n\npub fn default_hypervisor_path() -> PathBuf {\n\n\tlet app_info = AppInfo { name: PRODUCT_HYPERVISOR, author: AUTHOR };\n\n\tget_app_root(AppDataType::UserData, &app_info).unwrap_or_else(|_| \"$HOME/.parity-hypervisor\".into())\n\n}\n\n\n", "file_path": "parity-ethereum/util/dir/src/lib.rs", "rank": 93, "score": 238331.5266979115 }, { "content": "// Execute a given transaction without committing changes.\n\n//\n\n// `virt` signals that we are executing outside of a block set and restrictions like\n\n// gas limits and gas costs should be lifted.\n\nfn execute<B, T, V>(\n\n\tstate: &mut State<B>,\n\n\tenv_info: &EnvInfo,\n\n\tmachine: &Machine,\n\n\tt: &SignedTransaction,\n\n\toptions: TransactOptions<T, V>,\n\n\tvirt: bool\n\n) -> Result<RawExecuted<T::Output, V::Output>, ExecutionError>\n\n\twhere\n\n\t\tB: Backend,\n\n\t\tT: trace::Tracer,\n\n\t\tV: trace::VMTracer,\n\n{\n\n\tlet schedule = machine.schedule(env_info.number);\n\n\tlet mut e = Executive::new(state, env_info, machine, &schedule);\n\n\n\n\tmatch virt {\n\n\t\ttrue => e.transact_virtual(t, options),\n\n\t\tfalse => e.transact(t, options),\n\n\t}\n", "file_path": "parity-ethereum/ethcore/executive-state/src/lib.rs", "rank": 94, "score": 238296.2574770155 }, { "content": "/// Creates new instance of KeyValueDBHandler\n\npub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box<dyn BlockChainDBHandler> {\n\n\tstruct RestorationDBHandler {\n\n\t\tconfig: kvdb_rocksdb::DatabaseConfig,\n\n\t}\n\n\n\n\tstruct RestorationDB {\n\n\t\tblooms: blooms_db::Database,\n\n\t\ttrace_blooms: blooms_db::Database,\n\n\t\tkey_value: Arc<dyn KeyValueDB>,\n\n\t}\n\n\n\n\timpl BlockChainDB for RestorationDB {\n\n\t\tfn key_value(&self) -> &Arc<dyn KeyValueDB> {\n\n\t\t\t&self.key_value\n\n\t\t}\n\n\n\n\t\tfn blooms(&self) -> &blooms_db::Database {\n\n\t\t\t&self.blooms\n\n\t\t}\n\n\n", "file_path": "parity-ethereum/ethcore/src/test_helpers/mod.rs", "rank": 95, "score": 237634.60874303355 }, { "content": "#[allow(dead_code)]\n\npub fn json_chain_test<H: FnMut(&str, HookType)>(path: &Path, json_data: &[u8], start_stop_hook: &mut H) -> Vec<String> {\n\n\tlet _ = ::env_logger::try_init();\n\n\tlet tests = ethjson::test_helpers::state::Test::load(json_data)\n\n\t\t.expect(&format!(\"Could not parse JSON state test data from {}\", path.display()));\n\n\tlet mut failed = Vec::new();\n\n\n\n\tfor (name, test) in tests.into_iter() {\n\n\t\tstart_stop_hook(&name, HookType::OnStart);\n\n\n\n\t\t{\n\n\t\t\tlet multitransaction = test.transaction;\n\n\t\t\tlet env: EnvInfo = test.env.into();\n\n\t\t\tlet pre: PodState = test.pre_state.into();\n\n\n\n\t\t\tfor (spec_name, states) in test.post_states {\n\n\t\t\t\tlet total = states.len();\n\n\t\t\t\tlet spec = match EvmTestClient::fork_spec_from_json(&spec_name) {\n\n\t\t\t\t\tSome(spec) => spec,\n\n\t\t\t\t\tNone => {\n\n\t\t\t\t\t\tprintln!(\" - {} | {:?} Ignoring tests because of missing chainspec\", name, spec_name);\n", "file_path": "parity-ethereum/ethcore/src/json_tests/state.rs", "rank": 96, "score": 236587.65577679814 }, { "content": "#[cfg(test)]\n\npub fn default_network_config() -> ::sync::NetworkConfiguration {\n\n\tuse network::NatType;\n\n\tuse sync::{NetworkConfiguration};\n\n\tuse super::network::IpFilter;\n\n\tNetworkConfiguration {\n\n\t\tconfig_path: Some(replace_home(&::dir::default_data_path(), \"$BASE/network\")),\n\n\t\tnet_config_path: None,\n\n\t\tlisten_address: Some(\"0.0.0.0:30303\".into()),\n\n\t\tpublic_address: None,\n\n\t\tudp_port: None,\n\n\t\tnat_enabled: true,\n\n\t\tnat_type: NatType::Any,\n\n\t\tdiscovery_enabled: true,\n\n\t\tboot_nodes: Vec::new(),\n\n\t\tuse_secret: None,\n\n\t\tmax_peers: 50,\n\n\t\tmin_peers: 25,\n\n\t\tsnapshot_peers: 0,\n\n\t\tmax_pending_peers: 64,\n\n\t\tip_filter: IpFilter::default(),\n\n\t\treserved_nodes: Vec::new(),\n\n\t\tallow_non_reserved: true,\n\n\t\tclient_version: ::parity_version::version(),\n\n\t}\n\n}\n\n\n", "file_path": "parity-ethereum/parity/helpers.rs", "rank": 97, "score": 236408.2296095838 }, { "content": "pub fn check_levels_voted(content: &Content, blockchain: &BlockChain, parent: &H256) -> bool {\n\n let mut start = blockchain\n\n .deepest_voted_level(&content.voter_parent)\n\n .unwrap(); //need to be +1\n\n let end = blockchain.proposer_level(parent).unwrap();\n\n\n\n if start > end {\n\n return false;\n\n } //end < start means incorrect parent level\n\n if content.votes.len() != (end - start) as usize {\n\n return false;\n\n } //\n\n for vote in content.votes.iter() {\n\n start += 1;\n\n if start != blockchain.proposer_level(vote).unwrap() {\n\n return false;\n\n }\n\n }\n\n true\n\n}\n", "file_path": "src/validation/voter_block.rs", "rank": 98, "score": 236018.38221882272 }, { "content": "/// Extract signer list from extra_data.\n\n///\n\n/// Layout of extra_data:\n\n/// ----\n\n/// VANITY: 32 bytes\n\n/// Signers: N * 32 bytes as hex encoded (20 characters)\n\n/// Signature: 65 bytes\n\n/// --\n\npub fn extract_signers(header: &Header) -> Result<BTreeSet<Address>, Error> {\n\n\tlet data = header.extra_data();\n\n\n\n\tif data.len() <= VANITY_LENGTH + SIGNATURE_LENGTH {\n\n\t\tErr(EngineError::CliqueCheckpointNoSigner)?\n\n\t}\n\n\n\n\t// extract only the portion of extra_data which includes the signer list\n\n\tlet signers_raw = &data[(VANITY_LENGTH)..data.len() - (SIGNATURE_LENGTH)];\n\n\n\n\tif signers_raw.len() % ADDRESS_LENGTH != 0 {\n\n\t\tErr(EngineError::CliqueCheckpointInvalidSigners(signers_raw.len()))?\n\n\t}\n\n\n\n\tlet num_signers = signers_raw.len() / 20;\n\n\n\n\tlet signers: BTreeSet<Address> = (0..num_signers)\n\n\t\t.map(|i| {\n\n\t\t\tlet start = i * ADDRESS_LENGTH;\n\n\t\t\tlet end = start + ADDRESS_LENGTH;\n\n\t\t\tAddress::from_slice(&signers_raw[start..end])\n\n\t\t})\n\n\t\t.collect();\n\n\n\n\tOk(signers)\n\n}\n\n\n", "file_path": "parity-ethereum/ethcore/engines/clique/src/util.rs", "rank": 99, "score": 235551.28487760422 } ]
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": 141164.74183049065 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n msg!(\n\n \"{} Owner Invalid, Expected {}, Got {}\",\n\n account.key,\n\n owner,\n\n account.owner\n\n );\n\n Err(AuctionError::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "auction/program/src/utils.rs", "rank": 1, "score": 135872.18051900947 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(MetaplexError::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 2, "score": 135872.18051900947 }, { "content": "/// Assert owned by\n\npub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(ProgramError::IllegalOwner)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 3, "score": 134679.69176476428 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(ErrorCode::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "auction-house/program/src/utils.rs", "rank": 4, "score": 134679.69176476428 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(ErrorCode::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n///TokenTransferParams\n\npub struct TokenTransferParams<'a: 'b, 'b> {\n\n /// source\n\n pub source: AccountInfo<'a>,\n\n /// destination\n\n pub destination: AccountInfo<'a>,\n\n /// amount\n\n pub amount: u64,\n\n /// authority\n\n pub authority: AccountInfo<'a>,\n\n /// authority_signer_seeds\n\n pub authority_signer_seeds: &'b [&'b [u8]],\n\n /// token_program\n\n pub token_program: AccountInfo<'a>,\n\n}\n\n\n", "file_path": "candy-machine/program/src/utils.rs", "rank": 5, "score": 134679.69176476428 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(MetadataError::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 6, "score": 134679.69176476428 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(VaultError::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-vault/program/src/utils.rs", "rank": 7, "score": 134679.69176476428 }, { "content": "pub fn assert_owned_by(account: &AccountInfo, owner: &Pubkey) -> ProgramResult {\n\n if account.owner != owner {\n\n Err(ErrorCode::IncorrectOwner.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-entangler/program/src/utils.rs", "rank": 8, "score": 134679.69176476428 }, { "content": "/// Assert uninitialized\n\npub fn assert_uninitialized<T: IsInitialized>(account: &T) -> ProgramResult {\n\n if account.is_initialized() {\n\n Err(ProgramError::AccountAlreadyInitialized)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 9, "score": 123513.09753195084 }, { "content": "/// puff metadata account instruction\n\npub fn puff_metadata_account(program_id: Pubkey, metadata_account: Pubkey) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![AccountMeta::new(metadata_account, false)],\n\n data: MetadataInstruction::PuffMetadata.try_to_vec().unwrap(),\n\n }\n\n}\n\n\n\n/// creates a update_primary_sale_happened_via_token instruction\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 10, "score": 122291.11322723141 }, { "content": "mod edition_marker;\n\nmod external_price;\n\nmod master_edition_v2;\n\nmod metadata;\n\nmod vault;\n\n\n\npub use edition_marker::EditionMarker;\n\npub use external_price::ExternalPrice;\n\npub use master_edition_v2::MasterEditionV2;\n\npub use metadata::Metadata;\n\nuse solana_program_test::*;\n\nuse solana_sdk::{\n\n account::Account, program_pack::Pack, pubkey::Pubkey, signature::Signer,\n\n signer::keypair::Keypair, system_instruction, transaction::Transaction, transport,\n\n};\n\nuse spl_token::state::Mint;\n\npub use vault::Vault;\n\n\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 11, "score": 121444.65257015772 }, { "content": " ),\n\n spl_token::instruction::initialize_account(\n\n &spl_token::id(),\n\n &account.pubkey(),\n\n mint,\n\n manager,\n\n )\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, &account],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn create_mint(\n\n context: &mut ProgramTestContext,\n\n mint: &Keypair,\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 12, "score": 121432.36262370409 }, { "content": "\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn create_token_account(\n\n context: &mut ProgramTestContext,\n\n account: &Keypair,\n\n mint: &Pubkey,\n\n manager: &Pubkey,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &account.pubkey(),\n\n rent.minimum_balance(spl_token::state::Account::LEN),\n\n spl_token::state::Account::LEN as u64,\n\n &spl_token::id(),\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 13, "score": 121432.21632986295 }, { "content": " mint: &Pubkey,\n\n account: &Pubkey,\n\n amount: u64,\n\n owner: &Pubkey,\n\n additional_signer: Option<&Keypair>,\n\n) -> transport::Result<()> {\n\n let mut signing_keypairs = vec![&context.payer];\n\n if let Some(signer) = additional_signer {\n\n signing_keypairs.push(signer);\n\n }\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n spl_token::instruction::mint_to(&spl_token::id(), mint, account, owner, &[], amount)\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &signing_keypairs,\n\n context.last_blockhash,\n\n );\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 14, "score": 121431.38595512515 }, { "content": " manager: &Pubkey,\n\n freeze_authority: Option<&Pubkey>,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &mint.pubkey(),\n\n rent.minimum_balance(spl_token::state::Mint::LEN),\n\n spl_token::state::Mint::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_mint(\n\n &spl_token::id(),\n\n &mint.pubkey(),\n\n &manager,\n\n freeze_authority,\n\n 0,\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 15, "score": 121431.1669002808 }, { "content": " )\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, &mint],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 16, "score": 121421.62254614188 }, { "content": "export class Account<T = unknown> {\n\n readonly pubkey: PublicKey;\n\n readonly info: AccountInfo<Buffer>;\n\n data: T;\n\n\n\n constructor(pubkey: AnyPublicKey, info?: AccountInfo<Buffer>) {\n\n this.pubkey = new PublicKey(pubkey);\n\n this.info = info;\n\n }\n\n\n\n static from<T>(this: AccountConstructor<T>, account: Account<unknown>) {\n\n return new this(account.pubkey, account.info);\n\n }\n\n\n\n static async load<T>(\n\n this: AccountConstructor<T>,\n\n connection: Connection,\n\n pubkey: AnyPublicKey,\n\n ): Promise<T> {\n\n const info = await Account.getInfo(connection, pubkey);\n\n\n\n return new this(pubkey, info);\n\n }\n\n\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n\n static isCompatible(_data: Buffer): boolean {\n\n throw new Error(`method 'isCompatible' is not implemented`);\n\n }\n\n\n\n static async getInfo(connection: Connection, pubkey: AnyPublicKey) {\n\n const info = await connection.getAccountInfo(new PublicKey(pubkey));\n\n if (!info) {\n\n throw ERROR_ACCOUNT_NOT_FOUND(pubkey);\n\n }\n\n\n\n return { ...info, data: Buffer.from(info?.data) };\n\n }\n\n\n\n static async getInfos(\n\n connection: Connection,\n\n pubkeys: AnyPublicKey[],\n\n commitment: Commitment = 'recent',\n\n ) {\n\n const BATCH_SIZE = 99; // Must batch above this limit.\n\n\n\n const promises: Promise<Map<AnyPublicKey, AccountInfo<Buffer>> | undefined>[] = [];\n\n for (let i = 0; i < pubkeys.length; i += BATCH_SIZE) {\n\n promises.push(\n\n Account.getMultipleAccounts(\n\n connection,\n\n pubkeys.slice(i, Math.min(pubkeys.length, i + BATCH_SIZE)),\n\n commitment,\n\n ),\n\n );\n\n }\n\n\n\n const results = new Map<AnyPublicKey, AccountInfo<Buffer>>();\n\n (await Promise.all(promises)).forEach((result) =>\n\n [...(result?.entries() ?? [])].forEach(([k, v]) => results.set(k, v)),\n\n );\n\n return results;\n\n }\n\n\n\n private static async getMultipleAccounts(\n\n connection: Connection,\n\n pubkeys: AnyPublicKey[],\n\n commitment: Commitment,\n\n ) {\n\n const args = connection._buildArgs([pubkeys.map((k) => k.toString())], commitment, 'base64');\n\n const unsafeRes = await (connection as ConnnectionWithRpcRequest)._rpcRequest(\n\n 'getMultipleAccounts',\n\n args,\n\n );\n\n if (unsafeRes.error) {\n\n throw new Error('failed to get info about accounts ' + unsafeRes.error.message);\n\n }\n\n if (!unsafeRes.result.value) return;\n\n const infos = (unsafeRes.result.value as AccountInfo<string[]>[])\n\n .filter(Boolean)\n\n .map((info) => ({\n\n ...info,\n\n data: Buffer.from(info.data[0], 'base64'),\n\n })) as AccountInfo<Buffer>[];\n\n return infos.reduce((acc, info, index) => {\n\n acc.set(pubkeys[index], info);\n\n return acc;\n\n }, new Map<AnyPublicKey, AccountInfo<Buffer>>());\n\n }\n\n\n\n assertOwner(pubkey: AnyPublicKey) {\n\n return this.info?.owner.equals(new PublicKey(pubkey));\n\n }\n\n\n\n toJSON() {\n\n return {\n\n pubkey: this.pubkey.toString(),\n\n info: {\n\n executable: !!this.info?.executable,\n\n owner: this.info?.owner ? new PublicKey(this.info?.owner) : null,\n\n lamports: this.info?.lamports,\n\n data: this.info?.data.toJSON(),\n\n },\n\n data: this.data,\n\n };\n\n }\n\n\n\n toString() {\n\n return JSON.stringify(this.toJSON());\n\n }\n", "file_path": "core/js/src/accounts/Account.ts", "rank": 17, "score": 117270.34780414248 }, { "content": "pub fn program_test<'a>() -> ProgramTest {\n\n ProgramTest::new(\"mpl_token_metadata\", mpl_token_metadata::id(), None)\n\n}\n\n\n\npub async fn get_account(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Account {\n\n context\n\n .banks_client\n\n .get_account(*pubkey)\n\n .await\n\n .expect(\"account not found\")\n\n .expect(\"account empty\")\n\n}\n\n\n\npub async fn get_mint(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Mint {\n\n let account = get_account(context, pubkey).await;\n\n Mint::unpack(&account.data).unwrap()\n\n}\n\n\n\npub async fn mint_tokens(\n\n context: &mut ProgramTestContext,\n", "file_path": "core/rust/testing-utils/src/utils/mod.rs", "rank": 18, "score": 114647.51585173781 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn create_deprecated_populate_participation_printing_account_instruction(\n\n program_id: Pubkey,\n\n safety_deposit_token_store: Pubkey,\n\n transient_one_time_mint_account: Pubkey,\n\n participation_state_printing_account: Pubkey,\n\n one_time_printing_authorization_mint: Pubkey,\n\n printing_mint: Pubkey,\n\n participation_safety_deposit_box: Pubkey,\n\n vault: Pubkey,\n\n fraction_mint: Pubkey,\n\n auction: Pubkey,\n\n auction_manager: Pubkey,\n\n store: Pubkey,\n\n master_edition: Pubkey,\n\n transfer_authority: Pubkey,\n\n payer: Pubkey,\n\n) -> Instruction {\n\n let accounts = vec![\n\n AccountMeta::new(safety_deposit_token_store, false),\n\n AccountMeta::new(transient_one_time_mint_account, false),\n", "file_path": "metaplex/program/src/instruction.rs", "rank": 19, "score": 114491.14050682083 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn create_update_external_price_account_instruction(\n\n program_id: Pubkey,\n\n external_price_account: Pubkey,\n\n price_per_share: u64,\n\n price_mint: Pubkey,\n\n allowed_to_combine: bool,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![AccountMeta::new(external_price_account, true)],\n\n data: VaultInstruction::UpdateExternalPriceAccount(ExternalPriceAccount {\n\n key: Key::ExternalAccountKeyV1,\n\n price_per_share,\n\n price_mint,\n\n allowed_to_combine,\n\n })\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n\n\n\n/// Creates an AddTokenToInactiveVault instruction\n", "file_path": "token-vault/program/src/instruction.rs", "rank": 20, "score": 114491.14050682083 }, { "content": "/// Assert account key\n\npub fn assert_account_key(account_info: &AccountInfo, key: &Pubkey) -> ProgramResult {\n\n if *account_info.key != *key {\n\n Err(ProgramError::InvalidArgument)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 21, "score": 113832.42349712481 }, { "content": "export class Uses extends Borsh.Data<UsesArgs> {\n\n static readonly SCHEMA = Uses.struct([\n\n ['useMethod', 'u8'],\n\n ['total', 'u64'],\n\n ['remaining', 'u64'],\n\n ]);\n\n useMethod: UseMethod;\n\n total: number;\n\n remaining: number;\n\n\n\n constructor(args: UsesArgs) {\n\n super(args);\n\n this.useMethod = args.useMethod;\n\n this.total = args.total;\n\n this.remaining = args.remaining;\n\n }\n", "file_path": "token-metadata/js/src/accounts/Uses.ts", "rank": 22, "score": 113683.13332533411 }, { "content": "pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {\n\n if !account_info.is_signer {\n\n Err(ProgramError::MissingRequiredSignature)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 23, "score": 112620.11076933017 }, { "content": "pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {\n\n if !account_info.is_signer {\n\n Err(ProgramError::MissingRequiredSignature)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "auction/program/src/utils.rs", "rank": 24, "score": 112620.11076933017 }, { "content": " constructor(args: UsesArgs) {\n\n super(args);\n\n this.useMethod = args.useMethod;\n\n this.total = args.total;\n\n this.remaining = args.remaining;\n", "file_path": "token-metadata/js/src/accounts/Uses.ts", "rank": 25, "score": 112453.50233934066 }, { "content": "mod assert;\n\nmod edition_marker;\n\nmod external_price;\n\nmod master_edition_v2;\n\nmod metadata;\n\nmod vault;\n\n\n\npub use assert::*;\n\npub use edition_marker::EditionMarker;\n\npub use external_price::ExternalPrice;\n\npub use master_edition_v2::MasterEditionV2;\n\npub use metadata::Metadata;\n\nuse solana_program_test::*;\n\nuse solana_sdk::{\n\n account::Account, program_pack::Pack, pubkey::Pubkey, signature::Signer,\n\n signer::keypair::Keypair, system_instruction, transaction::Transaction, transport::{self, TransportError},\n\n};\n\nuse spl_token::state::Mint;\n\npub use vault::Vault;\n\n\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 26, "score": 112111.61794411494 }, { "content": "// //! Module provide utilities for testing.\n\n\n\n// #![allow(unused)]\n\n\n\npub mod setup_functions;\n\n\n\n// use std::{env, str::FromStr};\n\n\n\n// use anchor_client::{\n\n// solana_client::{client_error::ClientError, rpc_client::RpcClient},\n\n// solana_sdk::{\n\n// program_pack::Pack, pubkey::Pubkey, signature::Keypair, signer::Signer, system_instruction,\n\n// system_program, sysvar, transaction::Transaction,\n\n// },\n\n// Program,\n\n// };\n\n// use constants::{AUCTION_HOUSE, FEE_PAYER, SIGNER, TREASURY};\n\n\n\n// use solana_program_test::*;\n\n\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 27, "score": 112108.47169733608 }, { "content": "pub use pack_set::TestPackSet;\n\npub use pack_voucher::TestPackVoucher;\n\nuse solana_program::clock::Clock;\n\nuse solana_program_test::*;\n\nuse solana_sdk::{\n\n account::Account, program_pack::Pack, pubkey::Pubkey, signature::Signer,\n\n signer::keypair::Keypair, system_instruction, transaction::Transaction, transport,\n\n};\n\nuse spl_token::state::Mint;\n\nuse std::time;\n\npub use user::*;\n\npub use vault::TestVault;\n\n\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 28, "score": 112105.43334995511 }, { "content": "#![allow(dead_code)]\n\nmod assert;\n\nmod edition;\n\nmod edition_marker;\n\nmod external_price;\n\nmod master_edition_v2;\n\nmod metadata;\n\nmod pack_card;\n\nmod pack_set;\n\nmod pack_voucher;\n\nmod user;\n\nmod vault;\n\n\n\npub use assert::*;\n\npub use edition::*;\n\npub use edition_marker::TestEditionMarker;\n\npub use external_price::TestExternalPrice;\n\npub use master_edition_v2::TestMasterEditionV2;\n\npub use metadata::TestMetadata;\n\npub use pack_card::TestPackCard;\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 29, "score": 112103.10369892015 }, { "content": "// let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n\n\n// let tx = Transaction::new_signed_with_payer(\n\n// &[\n\n// system_instruction::create_account(\n\n// &wallet.pubkey(),\n\n// &token_account.pubkey(),\n\n// spl_token::state::Account::LEN as u64,\n\n// connection\n\n// .get_minimum_balance_for_rent_exemption(spl_token::state::Account::LEN)?,\n\n// &spl_token::id(),\n\n// ),\n\n// spl_token::instruction::initialize_account(\n\n// &spl_token::id(),\n\n// &token_account.pubkey(),\n\n// token_mint,\n\n// owner,\n\n// )\n\n// .unwrap(),\n\n// ],\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 30, "score": 112100.73453716593 }, { "content": "\n\npub async fn create_token_account(\n\n context: &mut ProgramTestContext,\n\n account: &Keypair,\n\n mint: &Pubkey,\n\n manager: &Pubkey,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &account.pubkey(),\n\n rent.minimum_balance(spl_token::state::Account::LEN),\n\n spl_token::state::Account::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_account(\n\n &spl_token::id(),\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 31, "score": 112100.60011638176 }, { "content": " ),\n\n spl_token::instruction::initialize_account(\n\n &spl_token::id(),\n\n &account.pubkey(),\n\n mint,\n\n manager,\n\n )\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, &account],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn create_mint(\n\n context: &mut ProgramTestContext,\n\n mint: &Keypair,\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 32, "score": 112099.3966350061 }, { "content": "\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn create_token_account(\n\n context: &mut ProgramTestContext,\n\n account: &Keypair,\n\n mint: &Pubkey,\n\n manager: &Pubkey,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &account.pubkey(),\n\n rent.minimum_balance(spl_token::state::Account::LEN),\n\n spl_token::state::Account::LEN as u64,\n\n &spl_token::id(),\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 33, "score": 112099.25034116495 }, { "content": "// /// Return `spl_token` token account.\n\n// pub fn get_token_account(\n\n// connection: &RpcClient,\n\n// token_account: &Pubkey,\n\n// ) -> Result<spl_token::state::Account, ClientError> {\n\n// let data = connection.get_account_data(token_account)?;\n\n// Ok(spl_token::state::Account::unpack(&data).unwrap())\n\n// }\n\n\n\n// /// Perform native lamports transfer.\n\n// pub fn transfer_lamports(\n\n// connection: &RpcClient,\n\n// wallet: &Keypair,\n\n// to: &Pubkey,\n\n// amount: u64,\n\n// ) -> Result<(), ClientError> {\n\n// let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n\n\n// let tx = Transaction::new_signed_with_payer(\n\n// &[system_instruction::transfer(&wallet.pubkey(), to, amount)],\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 34, "score": 112099.15792842401 }, { "content": " context: &mut ProgramTestContext,\n\n account: &Keypair,\n\n owner: &Pubkey,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &account.pubkey(),\n\n rent.minimum_balance(S::LEN),\n\n S::LEN as u64,\n\n owner,\n\n )],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, account],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 35, "score": 112099.0622907233 }, { "content": "\n\n// let tx = Transaction::new_signed_with_payer(\n\n// &[mpl_token_metadata::instruction::create_metadata_accounts(\n\n// program_id,\n\n// metadata_account,\n\n// *mint,\n\n// wallet.pubkey(),\n\n// wallet.pubkey(),\n\n// wallet.pubkey(),\n\n// name,\n\n// symbol,\n\n// uri,\n\n// None,\n\n// seller_fee_basis_points,\n\n// false,\n\n// false,\n\n// )],\n\n// Some(&wallet.pubkey()),\n\n// &[wallet],\n\n// recent_blockhash,\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 36, "score": 112098.99503252249 }, { "content": "// let program_id = Pubkey::from_str(&pid).unwrap();\n\n// // let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n// let recent_blockhash = context.last_blockhash;\n\n// let (metadata_account, _) = Pubkey::find_program_address(\n\n// &[\n\n// mpl_token_metadata::state::PREFIX.as_bytes(),\n\n// program_id.as_ref(),\n\n// mint.as_ref(),\n\n// ],\n\n// &program_id,\n\n// );\n\n\n\n// let tx = Transaction::new_signed_with_payer(\n\n// &[mpl_token_metadata::instruction::create_metadata_accounts(\n\n// program_id,\n\n// metadata_account,\n\n// *mint,\n\n// wallet.pubkey(),\n\n// wallet.pubkey(),\n\n// wallet.pubkey(),\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 37, "score": 112098.70849814896 }, { "content": " mint: &Pubkey,\n\n account: &Pubkey,\n\n amount: u64,\n\n owner: &Pubkey,\n\n additional_signer: Option<&Keypair>,\n\n) -> transport::Result<()> {\n\n let mut signing_keypairs = vec![&context.payer];\n\n if let Some(signer) = additional_signer {\n\n signing_keypairs.push(signer);\n\n }\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n spl_token::instruction::mint_to(&spl_token::id(), mint, account, owner, &[], amount)\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &signing_keypairs,\n\n context.last_blockhash,\n\n );\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 38, "score": 112098.41996642716 }, { "content": " manager: &Pubkey,\n\n freeze_authority: Option<&Pubkey>,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &mint.pubkey(),\n\n rent.minimum_balance(spl_token::state::Mint::LEN),\n\n spl_token::state::Mint::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_mint(\n\n &spl_token::id(),\n\n &mint.pubkey(),\n\n &manager,\n\n freeze_authority,\n\n 0,\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 39, "score": 112098.20091158281 }, { "content": "}\n\n\n\npub async fn create_mint(\n\n context: &mut ProgramTestContext,\n\n mint: &Keypair,\n\n manager: &Pubkey,\n\n freeze_authority: Option<&Pubkey>,\n\n) -> transport::Result<()> {\n\n let rent = context.banks_client.get_rent().await.unwrap();\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &context.payer.pubkey(),\n\n &mint.pubkey(),\n\n rent.minimum_balance(spl_token::state::Mint::LEN),\n\n spl_token::state::Mint::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_mint(\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 40, "score": 112098.09415683225 }, { "content": ") -> transport::Result<()> {\n\n let tx = Transaction::new_signed_with_payer(\n\n &[spl_token::instruction::transfer(\n\n &spl_token::id(),\n\n source,\n\n destination,\n\n &authority.pubkey(),\n\n &[],\n\n amount,\n\n )\n\n .unwrap()],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, authority],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn create_account<S: Pack>(\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 41, "score": 112097.73189808987 }, { "content": "// let tx = Transaction::new_signed_with_payer(\n\n// &[system_instruction::transfer(&wallet.pubkey(), to, amount)],\n\n// Some(&wallet.pubkey()),\n\n// &[wallet],\n\n// recent_blockhash,\n\n// );\n\n\n\n// // connection.send_and_confirm_transaction(&tx)?;\n\n// context.banks_client.process_transaction(tx);\n\n\n\n// Ok(())\n\n// }\n\n\n\n// /// Create new `TokenMetadata` using `RpcClient`.\n\n// pub fn create_token_metadata(\n\n// connection: &RpcClient,\n\n// wallet: &Keypair,\n\n// mint: &Pubkey,\n\n// name: String,\n\n// symbol: String,\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 42, "score": 112097.73821934567 }, { "content": "// authority: *wallet,\n\n// fee_withdrawal_destination: *fee_withdrawal_destination,\n\n// treasury_withdrawal_destination: *treasury_withdrawal_destination,\n\n// treasury_withdrawal_destination_owner: *wallet,\n\n// auction_house,\n\n// auction_house_fee_account,\n\n// auction_house_treasury,\n\n// token_program: spl_token::id(),\n\n// ata_program: spl_associated_token_account::id(),\n\n// rent: sysvar::rent::id(),\n\n// system_program: system_program::id(),\n\n// })\n\n// .args(mpl_auction_house::instruction::CreateAuctionHouse {\n\n// bump,\n\n// can_change_sale_price,\n\n// fee_payer_bump,\n\n// requires_sign_off,\n\n// seller_fee_basis_points,\n\n// treasury_bump,\n\n// })\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 43, "score": 112097.6728636796 }, { "content": " owner: &Pubkey,\n\n additional_signers: Option<Vec<&Keypair>>,\n\n) -> transport::Result<()> {\n\n let mut signing_keypairs = vec![&context.payer];\n\n if let Some(signers) = additional_signers {\n\n signing_keypairs.extend(signers)\n\n }\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n spl_token::instruction::mint_to(&spl_token::id(), mint, account, owner, &[], amount)\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &signing_keypairs,\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 44, "score": 112097.19946745766 }, { "content": " .expect(\"account not found\")\n\n .expect(\"account empty\")\n\n}\n\n\n\npub async fn get_mint(context: &mut ProgramTestContext, pubkey: &Pubkey) -> Mint {\n\n let account = get_account(context, pubkey).await;\n\n Mint::unpack(&account.data).unwrap()\n\n}\n\n\n\n/// Will warp to next `N` slots until `Clock` program account `unix_timestamp` field matches current time + `duration`.\n\npub async fn warp_sleep(context: &mut ProgramTestContext, duration: time::Duration) {\n\n let current_time = context\n\n .banks_client\n\n .get_sysvar::<Clock>()\n\n .await\n\n .unwrap()\n\n .unix_timestamp;\n\n let end_time = current_time + duration.as_millis() as i64;\n\n\n\n loop {\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 45, "score": 112094.95480624771 }, { "content": "// .send()\n\n// .unwrap();\n\n\n\n// Ok(())\n\n// }\n\n\n\n// /// Return `Clone` of provided `Keypair`.\n\n\n\n// /// Create and return new mint.\n\n\n\n// /// Create and return new associated token account.\n\n\n\n// /// Create new token account.\n\n// pub fn create_token_account(\n\n// connection: &RpcClient,\n\n// wallet: &Keypair,\n\n// token_account: &Keypair,\n\n// token_mint: &Pubkey,\n\n// owner: &Pubkey,\n\n// ) -> Result<(), ClientError> {\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 46, "score": 112094.94800173615 }, { "content": "// program: &Program,\n\n// treasury_mint: &Pubkey,\n\n// wallet: &Pubkey,\n\n// fee_withdrawal_destination: &Pubkey,\n\n// treasury_withdrawal_destination: &Pubkey,\n\n// can_change_sale_price: bool,\n\n// requires_sign_off: bool,\n\n// seller_fee_basis_points: u16,\n\n// ) -> Result<(), ClientError> {\n\n// let (auction_house, bump) = find_auction_house_address(wallet, treasury_mint);\n\n// let (auction_house_fee_account, fee_payer_bump) =\n\n// find_auction_house_fee_account_address(&auction_house);\n\n// let (auction_house_treasury, treasury_bump) =\n\n// find_auction_house_treasury_address(&auction_house);\n\n\n\n// program\n\n// .request()\n\n// .accounts(mpl_auction_house::accounts::CreateAuctionHouse {\n\n// treasury_mint: *treasury_mint,\n\n// payer: *wallet,\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 47, "score": 112094.46150347478 }, { "content": " &account.pubkey(),\n\n mint,\n\n manager,\n\n )\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, account],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn transfer_token(\n\n context: &mut ProgramTestContext,\n\n source: &Pubkey,\n\n destination: &Pubkey,\n\n authority: &Keypair,\n\n amount: u64,\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 48, "score": 112094.20648465825 }, { "content": ") -> transport::Result<Pubkey> {\n\n let metaplex_key = mpl_metaplex::id();\n\n let admin_key = admin.pubkey();\n\n\n\n let store_path = &[\n\n mpl_metaplex::state::PREFIX.as_bytes(),\n\n metaplex_key.as_ref(),\n\n admin_key.as_ref(),\n\n ];\n\n let (store_key, _) = Pubkey::find_program_address(store_path, &mpl_metaplex::id());\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[mpl_metaplex::instruction::create_set_store_instruction(\n\n mpl_metaplex::id(),\n\n store_key,\n\n admin_key,\n\n context.payer.pubkey(),\n\n public,\n\n )],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, admin],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await.unwrap();\n\n\n\n Ok(store_key)\n\n}\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 49, "score": 112093.90040375043 }, { "content": "// Some(&wallet.pubkey()),\n\n// &[wallet, token_account],\n\n// recent_blockhash,\n\n// );\n\n\n\n// connection.send_and_confirm_transaction(&tx)?;\n\n\n\n// Ok(())\n\n// }\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 50, "score": 112093.8206278673 }, { "content": "// mint,\n\n// to,\n\n// &wallet.pubkey(),\n\n// &[&wallet.pubkey()],\n\n// amount,\n\n// )\n\n// .unwrap()],\n\n// Some(&wallet.pubkey()),\n\n// &[wallet],\n\n// recent_blockhash,\n\n// );\n\n\n\n// // connection.send_and_confirm_transaction(&tx)?;\n\n// context.banks_client.process_transaction(tx);\n\n// // context.banks_client.process_transaction(tx);\n\n// Ok(())\n\n// }\n\n\n\n// /// Create new `AuctionHouse` using `Program`.\n\n// pub fn create_auction_house(\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 51, "score": 112093.47655820375 }, { "content": "// connection: &RpcClient,\n\n// wallet: &Keypair,\n\n// mint: &Pubkey,\n\n// to: &Pubkey,\n\n// amount: u64,\n\n// ) -> Result<(), ClientError> {\n\n// let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n\n\n// let tx = Transaction::new_signed_with_payer(\n\n// &[spl_token::instruction::mint_to(\n\n// &spl_token::id(),\n\n// mint,\n\n// to,\n\n// &wallet.pubkey(),\n\n// &[&wallet.pubkey()],\n\n// amount,\n\n// )\n\n// .unwrap()],\n\n// Some(&wallet.pubkey()),\n\n// &[wallet],\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 52, "score": 112093.37010509256 }, { "content": "// name,\n\n// symbol,\n\n// uri,\n\n// None,\n\n// seller_fee_basis_points,\n\n// false,\n\n// false,\n\n// )],\n\n// Some(&wallet.pubkey()),\n\n// &[wallet],\n\n// recent_blockhash,\n\n// );\n\n\n\n// // connection.send_and_confirm_transaction(&tx)?;\n\n// context.banks_client.process_transaction(tx);\n\n// Ok(metadata_account)\n\n// }\n\n\n\n// /// Mint tokens.\n\n// pub fn mint_to(\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 53, "score": 112093.25791324965 }, { "content": " receiver: &Pubkey,\n\n amount: u64,\n\n) -> Result<(), TransportError> {\n\n let tx = Transaction::new_signed_with_payer(\n\n &[system_instruction::transfer(\n\n &context.payer.pubkey(),\n\n receiver,\n\n amount,\n\n )],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await.unwrap();\n\n Ok(())\n\n}\n\n\n\npub async fn mint_tokens(\n\n context: &mut ProgramTestContext,\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 54, "score": 112093.25019273536 }, { "content": "// recent_blockhash,\n\n// );\n\n\n\n// connection.send_and_confirm_transaction(&tx)?;\n\n\n\n// Ok(())\n\n// }\n\n\n\n// pub fn mint_to_v2(\n\n// context: &mut ProgramTestContext,\n\n// wallet: &Keypair,\n\n// mint: &Pubkey,\n\n// to: &Pubkey,\n\n// amount: u64,\n\n// ) -> Result<(), ClientError> {\n\n// // let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n// let recent_blockhash = context.last_blockhash;\n\n// let tx = Transaction::new_signed_with_payer(\n\n// &[spl_token::instruction::mint_to(\n\n// &spl_token::id(),\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 55, "score": 112093.18112983232 }, { "content": " let last_time = context\n\n .banks_client\n\n .get_sysvar::<Clock>()\n\n .await\n\n .unwrap()\n\n .unix_timestamp;\n\n if last_time >= end_time {\n\n break;\n\n }\n\n\n\n let current_slot = context.banks_client.get_root_slot().await.unwrap();\n\n context.warp_to_slot(current_slot + 500).unwrap();\n\n }\n\n}\n\n\n\npub async fn mint_tokens(\n\n context: &mut ProgramTestContext,\n\n mint: &Pubkey,\n\n account: &Pubkey,\n\n amount: u64,\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 56, "score": 112092.93180949104 }, { "content": "// );\n\n\n\n// connection.send_and_confirm_transaction(&tx)?;\n\n// Ok(metadata_account)\n\n// }\n\n\n\n// pub fn create_token_metadata_v2(\n\n// context: &mut ProgramTestContext,\n\n// wallet: &Keypair,\n\n// mint: &Pubkey,\n\n// name: String,\n\n// symbol: String,\n\n// uri: String,\n\n// seller_fee_basis_points: u16,\n\n// ) -> Result<Pubkey, ClientError> {\n\n// let pid = match env::var(\"TOKEN_METADATA_PID\") {\n\n// Ok(val) => val,\n\n// Err(_) => mpl_token_metadata::id().to_string(),\n\n// };\n\n\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 57, "score": 112092.82626927046 }, { "content": "// uri: String,\n\n// seller_fee_basis_points: u16,\n\n// ) -> Result<Pubkey, ClientError> {\n\n// let pid = match env::var(\"TOKEN_METADATA_PID\") {\n\n// Ok(val) => val,\n\n// Err(_) => mpl_token_metadata::id().to_string(),\n\n// };\n\n\n\n// let program_id = Pubkey::from_str(&pid).unwrap();\n\n\n\n// let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n\n\n// let (metadata_account, _) = Pubkey::find_program_address(\n\n// &[\n\n// mpl_token_metadata::state::PREFIX.as_bytes(),\n\n// program_id.as_ref(),\n\n// mint.as_ref(),\n\n// ],\n\n// &program_id,\n\n// );\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 58, "score": 112092.72581431184 }, { "content": " &spl_token::id(),\n\n &mint.pubkey(),\n\n manager,\n\n freeze_authority,\n\n 0,\n\n )\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, mint],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n\n\n\npub async fn create_store(\n\n context: &mut ProgramTestContext,\n\n admin: &Keypair,\n\n public: bool,\n", "file_path": "nft-packs/program/tests/utils/mod.rs", "rank": 59, "score": 112088.65655744389 }, { "content": "// Some(&wallet.pubkey()),\n\n// &[wallet],\n\n// recent_blockhash,\n\n// );\n\n\n\n// connection.send_and_confirm_transaction(&tx)?;\n\n\n\n// Ok(())\n\n// }\n\n\n\n// /// Perform native lamports transfer.\n\n// pub fn transfer_lamports_v2(\n\n// context: &mut ProgramTestContext,\n\n// wallet: &Keypair,\n\n// to: &Pubkey,\n\n// amount: u64,\n\n// ) -> Result<(), ClientError> {\n\n// // let (recent_blockhash, _) = connection.get_recent_blockhash()?;\n\n// let recent_blockhash = context.last_blockhash;\n\n\n", "file_path": "auction-house/program/tests/utils/mod.rs", "rank": 60, "score": 112088.65655744389 }, { "content": " )\n\n .unwrap(),\n\n ],\n\n Some(&context.payer.pubkey()),\n\n &[&context.payer, &mint],\n\n context.last_blockhash,\n\n );\n\n\n\n context.banks_client.process_transaction(tx).await\n\n}\n", "file_path": "token-metadata/program/tests/utils/mod.rs", "rank": 61, "score": 112088.65655744389 }, { "content": "pub fn assert_signer(account_info: &AccountInfo) -> ProgramResult {\n\n if !account_info.is_signer {\n\n Err(ProgramError::MissingRequiredSignature)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 62, "score": 111400.05085655271 }, { "content": "export class UseAuthorityRecord extends Borsh.Data<UseAuthorityRecordArgs> {\n\n static readonly SCHEMA = UseAuthorityRecord.struct([\n\n ['key', 'u8'],\n\n ['allowedUses', 'u64'],\n\n ['bump', 'u8'],\n\n ]);\n\n key: MetadataKey;\n\n allowedUses: number;\n\n bump: number;\n\n\n\n constructor(args: UseAuthorityRecordArgs) {\n\n super(args);\n\n this.key = MetadataKey.UseAuthorityRecord;\n\n this.allowedUses = args.allowedUses;\n\n this.bump = args.bump;\n\n }\n", "file_path": "token-metadata/js/src/accounts/Uses.ts", "rank": 63, "score": 111251.61773192919 }, { "content": "pub mod helpers;\n\npub mod setup_functions;\n", "file_path": "fixed-price-sale/program/tests/utils/mod.rs", "rank": 64, "score": 110399.55841296587 }, { "content": "#[inline(always)]\n\npub fn spl_token_create_account<'a>(params: TokenCreateAccount<'_, '_>) -> ProgramResult {\n\n let TokenCreateAccount {\n\n payer,\n\n mint,\n\n account,\n\n authority,\n\n authority_seeds,\n\n token_program,\n\n system_program,\n\n rent,\n\n } = params;\n\n let acct = &account.key.clone();\n\n\n\n create_or_allocate_account_raw(\n\n *token_program.key,\n\n &account,\n\n &rent,\n\n &system_program,\n\n &payer,\n\n spl_token::state::Account::LEN,\n", "file_path": "auction/program/src/utils.rs", "rank": 65, "score": 110207.56210230754 }, { "content": " constructor(args: UseAuthorityRecordArgs) {\n\n super(args);\n\n this.key = MetadataKey.UseAuthorityRecord;\n\n this.allowedUses = args.allowedUses;\n\n this.bump = args.bump;\n", "file_path": "token-metadata/js/src/accounts/Uses.ts", "rank": 66, "score": 110076.50645449453 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn utilize(\n\n program_id: Pubkey,\n\n metadata: Pubkey,\n\n token_account: Pubkey,\n\n mint: Pubkey,\n\n use_authority_record_pda: Option<Pubkey>,\n\n use_authority: Pubkey,\n\n owner: Pubkey,\n\n burner: Option<Pubkey>,\n\n number_of_uses: u64,\n\n) -> Instruction {\n\n let mut accounts = vec![\n\n AccountMeta::new(metadata, false),\n\n AccountMeta::new(token_account, false),\n\n AccountMeta::new(mint, false),\n\n AccountMeta::new(use_authority, true),\n\n AccountMeta::new_readonly(owner, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n AccountMeta::new_readonly(spl_associated_token_account::id(), false),\n\n AccountMeta::new_readonly(solana_program::system_program::id(), false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 67, "score": 109988.62723827419 }, { "content": "pub fn assert_uninitialized<T: Pack + IsInitialized>(account_info: &AccountInfo) -> ProgramResult {\n\n msg!(\"assert_uninitialized\");\n\n let err = T::unpack_unchecked(&account_info.data.borrow());\n\n match err {\n\n Ok(account) => Err(AuctionError::BidderPotTokenAccountMustBeNew.into()),\n\n Err(err) => Ok(()),\n\n }\n\n}\n\n\n", "file_path": "auction/program/src/utils.rs", "rank": 68, "score": 109041.67639040167 }, { "content": "pub fn assert_rent_exempt(rent: &Rent, account_info: &AccountInfo) -> ProgramResult {\n\n if !rent.is_exempt(account_info.lamports(), account_info.data_len()) {\n\n Err(AuctionError::NotRentExempt.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "auction/program/src/utils.rs", "rank": 69, "score": 109041.67639040167 }, { "content": "pub fn assert_rent_exempt(rent: &Rent, account_info: &AccountInfo) -> ProgramResult {\n\n if !rent.is_exempt(account_info.lamports(), account_info.data_len()) {\n\n Err(MetaplexError::NotRentExempt.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 70, "score": 109041.67639040167 }, { "content": "/// Assert account rent exempt\n\npub fn assert_rent_exempt(rent: &Rent, account_info: &AccountInfo) -> ProgramResult {\n\n if !rent.is_exempt(account_info.lamports(), account_info.data_len()) {\n\n Err(ProgramError::AccountNotRentExempt)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 71, "score": 107906.9369188162 }, { "content": "pub fn assert_rent_exempt(rent: &Rent, account_info: &AccountInfo) -> ProgramResult {\n\n if !rent.is_exempt(account_info.lamports(), account_info.data_len()) {\n\n Err(MetadataError::NotRentExempt.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 72, "score": 107901.4721092728 }, { "content": "/// cheap method to just get supply off a mint without unpacking whole object\n\npub fn get_mint_decimals(account_info: &AccountInfo) -> Result<u8, ProgramError> {\n\n // In token program, 36, 8, 1, 1, is the layout, where the first 1 is decimals u8.\n\n // so we start at 36.\n\n let data = account_info.try_borrow_data().unwrap();\n\n Ok(data[44])\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 73, "score": 107901.4721092728 }, { "content": "/// cheap method to just get supply off a mint without unpacking whole object\n\npub fn get_mint_supply(account_info: &AccountInfo) -> Result<u64, ProgramError> {\n\n // In token program, 36, 8, 1, 1 is the layout, where the first 8 is supply u64.\n\n // so we start at 36.\n\n let data = account_info.try_borrow_data().unwrap();\n\n let bytes = array_ref![data, 36, 8];\n\n\n\n Ok(u64::from_le_bytes(*bytes))\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 74, "score": 107901.4721092728 }, { "content": "/// cheap method to just get supply of a mint without unpacking whole object\n\npub fn get_mint_supply(account_info: &AccountInfo) -> Result<u64, ProgramError> {\n\n // In token program, 36, 8, 1, 1 is the layout, where the first 8 is supply u64.\n\n // so we start at 36.\n\n let data = account_info.try_borrow_data().unwrap();\n\n let bytes = array_ref![data, 36, 8];\n\n\n\n Ok(u64::from_le_bytes(*bytes))\n\n}\n", "file_path": "token-entangler/program/src/utils.rs", "rank": 75, "score": 107901.4721092728 }, { "content": "pub fn assert_rent_exempt(rent: &Rent, account_info: &AccountInfo) -> ProgramResult {\n\n if !rent.is_exempt(account_info.lamports(), account_info.data_len()) {\n\n Err(VaultError::NotRentExempt.into())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "token-vault/program/src/utils.rs", "rank": 76, "score": 107901.4721092728 }, { "content": "pub fn close_token_account<'a>(\n\n account: AccountInfo<'a>,\n\n destination: AccountInfo<'a>,\n\n owner: AccountInfo<'a>,\n\n signer_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::close_account(\n\n &spl_token::id(),\n\n account.key,\n\n destination.key,\n\n owner.key,\n\n &[],\n\n )?;\n\n\n\n invoke_signed(&ix, &[account, destination, owner], &[signer_seeds])\n\n}\n\n\n\n/// TokenMintToParams\n\npub struct TokenCreateAccount<'a: 'b, 'b> {\n\n /// payer\n", "file_path": "auction/program/src/utils.rs", "rank": 77, "score": 107898.10719285306 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn revoke_use_authority(\n\n program_id: Pubkey,\n\n use_authority_record: Pubkey,\n\n user: Pubkey,\n\n owner: Pubkey,\n\n owner_token_account: Pubkey,\n\n metadata: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(use_authority_record, false),\n\n AccountMeta::new(owner, true),\n\n AccountMeta::new_readonly(user, false),\n\n AccountMeta::new(owner_token_account, false),\n\n AccountMeta::new_readonly(mint, false),\n\n AccountMeta::new_readonly(metadata, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n AccountMeta::new_readonly(solana_program::system_program::id(), false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 78, "score": 107683.1795865718 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn approve_use_authority(\n\n program_id: Pubkey,\n\n use_authority_record: Pubkey,\n\n user: Pubkey,\n\n owner: Pubkey,\n\n payer: Pubkey,\n\n owner_token_account: Pubkey,\n\n metadata: Pubkey,\n\n mint: Pubkey,\n\n burner: Pubkey,\n\n number_of_uses: u64,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(use_authority_record, false),\n\n AccountMeta::new(owner, true),\n\n AccountMeta::new(payer, true),\n\n AccountMeta::new_readonly(user, false),\n\n AccountMeta::new(owner_token_account, false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 79, "score": 107683.1795865718 }, { "content": "/// update metadata account instruction\n\n/// #[deprecated(since=\"1.1.0\", note=\"please use `update_metadata_accounts_v2` instead\")]\n\npub fn update_metadata_accounts(\n\n program_id: Pubkey,\n\n metadata_account: Pubkey,\n\n update_authority: Pubkey,\n\n new_update_authority: Option<Pubkey>,\n\n data: Option<Data>,\n\n primary_sale_happened: Option<bool>,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(metadata_account, false),\n\n AccountMeta::new_readonly(update_authority, true),\n\n ],\n\n data: MetadataInstruction::UpdateMetadataAccount(UpdateMetadataAccountArgs {\n\n data,\n\n update_authority: new_update_authority,\n\n primary_sale_happened,\n\n })\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 80, "score": 106875.37986609092 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn freeze_delegated_account(\n\n program_id: Pubkey,\n\n delegate: Pubkey,\n\n token_account: Pubkey,\n\n edition: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(delegate, true),\n\n AccountMeta::new(token_account, false),\n\n AccountMeta::new_readonly(edition, false),\n\n AccountMeta::new_readonly(mint, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n ],\n\n data: MetadataInstruction::FreezeDelegatedAccount\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 81, "score": 106858.28617343289 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn create_metadata_accounts(\n\n program_id: Pubkey,\n\n metadata_account: Pubkey,\n\n mint: Pubkey,\n\n mint_authority: Pubkey,\n\n payer: Pubkey,\n\n update_authority: Pubkey,\n\n name: String,\n\n symbol: String,\n\n uri: String,\n\n creators: Option<Vec<Creator>>,\n\n seller_fee_basis_points: u16,\n\n update_authority_is_signer: bool,\n\n is_mutable: bool,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(metadata_account, false),\n\n AccountMeta::new_readonly(mint, false),\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 82, "score": 106858.28617343289 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn thaw_delegated_account(\n\n program_id: Pubkey,\n\n delegate: Pubkey,\n\n token_account: Pubkey,\n\n edition: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(delegate, true),\n\n AccountMeta::new(token_account, false),\n\n AccountMeta::new_readonly(edition, false),\n\n AccountMeta::new_readonly(mint, false),\n\n AccountMeta::new_readonly(spl_token::id(), false),\n\n ],\n\n data: MetadataInstruction::ThawDelegatedAccount\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 83, "score": 106858.28617343289 }, { "content": "/// Initialize SPL account instruction.\n\npub fn spl_initialize_account<'a>(\n\n account: AccountInfo<'a>,\n\n mint: AccountInfo<'a>,\n\n authority: AccountInfo<'a>,\n\n rent: AccountInfo<'a>,\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::initialize_account(\n\n &spl_token::id(),\n\n account.key,\n\n mint.key,\n\n authority.key,\n\n )?;\n\n\n\n invoke(&ix, &[account, mint, authority, rent])\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 84, "score": 106324.82792190388 }, { "content": "/// Close token account\n\npub fn close_token_account<'a>(\n\n account: AccountInfo<'a>,\n\n destination: AccountInfo<'a>,\n\n owner: AccountInfo<'a>,\n\n) -> ProgramResult {\n\n let ix = spl_token::instruction::close_account(\n\n &spl_token::id(),\n\n account.key,\n\n destination.key,\n\n owner.key,\n\n &[],\n\n )?;\n\n\n\n invoke(&ix, &[account, destination, owner])\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 85, "score": 106319.02145739911 }, { "content": "/// Cheap method to just grab amount from token account, instead of deserializing entire thing\n\npub fn get_amount_from_token_account(\n\n token_account_info: &AccountInfo,\n\n) -> Result<u64, ProgramError> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let amount_data = array_ref![data, 64, 8];\n\n Ok(u64::from_le_bytes(*amount_data))\n\n}\n\n\n", "file_path": "metaplex/program/src/utils.rs", "rank": 86, "score": 106318.74906146627 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n) -> Result<(), ProgramError> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n invoke(\n\n &system_instruction::transfer(&payer_info.key, new_account_info.key, required_lamports),\n\n &[\n", "file_path": "metaplex/program/src/utils.rs", "rank": 87, "score": 106313.52105608162 }, { "content": "/// transfer all the SOL from source to receiver\n\npub fn empty_account_balance(\n\n source: &AccountInfo,\n\n receiver: &AccountInfo,\n\n) -> Result<(), ProgramError> {\n\n let mut from = source.try_borrow_mut_lamports()?;\n\n let mut to = receiver.try_borrow_mut_lamports()?;\n\n **to += **from;\n\n **from = 0;\n\n Ok(())\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 88, "score": 106313.52105608162 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n) -> Result<(), ProgramError> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n invoke(\n\n &system_instruction::transfer(&payer_info.key, new_account_info.key, required_lamports),\n\n &[\n", "file_path": "auction/program/src/utils.rs", "rank": 89, "score": 106313.52105608162 }, { "content": "pub fn get_mint_authority(account_info: &AccountInfo) -> Result<COption<Pubkey>, ProgramError> {\n\n // In token program, 36, 8, 1, 1 is the layout, where the first 36 is mint_authority\n\n // so we start at 0.\n\n let data = account_info.try_borrow_data().unwrap();\n\n let authority_bytes = array_ref![data, 0, 36];\n\n\n\n Ok(unpack_coption_key(&authority_bytes)?)\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 90, "score": 105694.6371020668 }, { "content": "// update metadata account v2 instruction\n\npub fn update_metadata_accounts_v2(\n\n program_id: Pubkey,\n\n metadata_account: Pubkey,\n\n update_authority: Pubkey,\n\n new_update_authority: Option<Pubkey>,\n\n data: Option<DataV2>,\n\n primary_sale_happened: Option<bool>,\n\n is_mutable: Option<bool>,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(metadata_account, false),\n\n AccountMeta::new_readonly(update_authority, true),\n\n ],\n\n data: MetadataInstruction::UpdateMetadataAccountV2(UpdateMetadataAccountArgsV2 {\n\n data,\n\n update_authority: new_update_authority,\n\n primary_sale_happened,\n\n is_mutable,\n\n })\n\n .try_to_vec()\n\n .unwrap(),\n\n }\n\n}\n\n\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 91, "score": 105322.91828716647 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn create_metadata_accounts_v2(\n\n program_id: Pubkey,\n\n metadata_account: Pubkey,\n\n mint: Pubkey,\n\n mint_authority: Pubkey,\n\n payer: Pubkey,\n\n update_authority: Pubkey,\n\n name: String,\n\n symbol: String,\n\n uri: String,\n\n creators: Option<Vec<Creator>>,\n\n seller_fee_basis_points: u16,\n\n update_authority_is_signer: bool,\n\n is_mutable: bool,\n\n collection: Option<Collection>,\n\n uses: Option<Uses>,\n\n) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n", "file_path": "token-metadata/program/src/instruction.rs", "rank": 92, "score": 105311.68411497072 }, { "content": "/// Create token `Account` from `spl_token` program.\n\npub fn create_token_account(\n\n client: &RpcClient,\n\n payer: &Keypair,\n\n account: &Keypair,\n\n mint: &Pubkey,\n\n owner: &Pubkey,\n\n) -> Result<(), error::Error> {\n\n let recent_blockhash = client.get_latest_blockhash()?;\n\n let lamports = client.get_minimum_balance_for_rent_exemption(spl_token::state::Account::LEN)?;\n\n\n\n let tx = Transaction::new_signed_with_payer(\n\n &[\n\n system_instruction::create_account(\n\n &payer.pubkey(),\n\n &account.pubkey(),\n\n lamports,\n\n spl_token::state::Account::LEN as u64,\n\n &spl_token::id(),\n\n ),\n\n spl_token::instruction::initialize_account(\n", "file_path": "fixed-price-sale/cli/src/utils.rs", "rank": 93, "score": 104780.19858787641 }, { "content": "/// Cheap method to just grab owner Pubkey from token account, instead of deserializing entire thing\n\npub fn get_owner_from_token_account(\n\n token_account_info: &AccountInfo,\n\n) -> Result<Pubkey, ProgramError> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let owner_data = array_ref![data, 32, 32];\n\n Ok(Pubkey::new_from_array(*owner_data))\n\n}\n\n\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 94, "score": 104779.99943893206 }, { "content": "/// Cheap method to just grab delegate Pubkey from token account, instead of deserializing entire thing\n\npub fn get_delegate_from_token_account(\n\n token_account_info: &AccountInfo,\n\n) -> Result<Option<Pubkey>, ProgramError> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let key_data = array_ref![data, 76, 32];\n\n let coption_data = u32::from_le_bytes(*array_ref![data, 72, 4]);\n\n if coption_data == 0 {\n\n Ok(None)\n\n } else {\n\n Ok(Some(Pubkey::new_from_array(*key_data)))\n\n }\n\n}\n\n\n\n/// Create account almost from scratch, lifted from\n\n/// https://github.com/solana-labs/solana-program-library/blob/7d4873c61721aca25464d42cc5ef651a7923ca79/associated-token-account/program/src/processor.rs#L51-L98\n", "file_path": "auction-house/program/src/utils.rs", "rank": 95, "score": 104779.99943893206 }, { "content": "/// Cheap method to just grab mint Pubkey from token account, instead of deserializing entire thing\n\npub fn get_mint_from_token_account(\n\n token_account_info: &AccountInfo,\n\n) -> Result<Pubkey, ProgramError> {\n\n // TokeAccount layout: mint(32), owner(32), ...\n\n let data = token_account_info.try_borrow_data()?;\n\n let mint_data = array_ref![data, 0, 32];\n\n Ok(Pubkey::new_from_array(*mint_data))\n\n}\n\n\n", "file_path": "auction-house/program/src/utils.rs", "rank": 96, "score": 104779.99943893206 }, { "content": "#[inline(always)]\n\npub fn sys_create_account<'a>(\n\n from: &AccountInfo<'a>,\n\n to: &AccountInfo<'a>,\n\n lamports: u64,\n\n space: usize,\n\n owner: &Pubkey,\n\n signer_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n invoke_signed(\n\n &system_instruction::create_account(from.key, to.key, lamports, space as u64, owner),\n\n &[from.clone(), to.clone()],\n\n &[&signer_seeds],\n\n )?;\n\n\n\n Ok(())\n\n}\n\n\n\n/// Wrapper of `transfer` instruction from `system_program` program\n", "file_path": "fixed-price-sale/program/src/utils.rs", "rank": 97, "score": 104774.80359770093 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n) -> ProgramResult {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n invoke(\n\n &system_instruction::transfer(&payer_info.key, new_account_info.key, required_lamports),\n\n &[\n", "file_path": "token-metadata/program/src/utils.rs", "rank": 98, "score": 104774.80359770093 }, { "content": "#[inline(always)]\n\npub fn create_or_allocate_account_raw<'a>(\n\n program_id: Pubkey,\n\n new_account_info: &AccountInfo<'a>,\n\n rent_sysvar_info: &AccountInfo<'a>,\n\n system_program_info: &AccountInfo<'a>,\n\n payer_info: &AccountInfo<'a>,\n\n size: usize,\n\n signer_seeds: &[&[u8]],\n\n new_acct_seeds: &[&[u8]],\n\n) -> Result<(), ProgramError> {\n\n let rent = &Rent::from_account_info(rent_sysvar_info)?;\n\n let required_lamports = rent\n\n .minimum_balance(size)\n\n .max(1)\n\n .saturating_sub(new_account_info.lamports());\n\n\n\n if required_lamports > 0 {\n\n msg!(\"Transfer {} lamports to the new account\", required_lamports);\n\n let seeds: &[&[&[u8]]];\n\n let as_arr = [signer_seeds];\n", "file_path": "auction-house/program/src/utils.rs", "rank": 99, "score": 104774.80359770093 } ]
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 None => Err(Error::new(\n\n ErrorKind::Other,\n\n \"Conversion from PathBuf to String failed.\",\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/key_info_managers/on_disk_manager/mod.rs", "rank": 0, "score": 87905.84564307096 }, { "content": "/// Decodes base64 bytes to its original String value.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error as a string if either the decoding or the bytes conversion to UTF-8 failed.\n\nfn base64_data_to_string(base64_bytes: &[u8]) -> Result<String, String> {\n\n match base64::decode_config(base64_bytes, base64::URL_SAFE) {\n\n Ok(decode_bytes) => match String::from_utf8(decode_bytes) {\n\n Ok(string) => Ok(string),\n\n Err(error) => Err(error.to_string()),\n\n },\n\n Err(error) => Err(error.to_string()),\n\n }\n\n}\n\n\n", "file_path": "src/key_info_managers/on_disk_manager/mod.rs", "rank": 1, "score": 83428.85874169652 }, { "content": "pub fn signature_data_to_bytes(data: SignatureData, key_attributes: Attributes) -> Result<Vec<u8>> {\n\n match data {\n\n SignatureData::RsaSignature(signature) => Ok(signature),\n\n SignatureData::EcdsaSignature { mut r, mut s } => {\n\n // ECDSA signature data is represented the concatenation of the two result values, r and s,\n\n // in big endian format, as described here:\n\n // https://parallaxsecond.github.io/parsec-book/parsec_client/operations/psa_algorithm.html#asymmetricsignature-algorithm\n\n let p_byte_size = key_attributes.bits / 8; // should not fail for valid keys\n\n if r.len() != p_byte_size || s.len() != p_byte_size {\n\n if crate::utils::GlobalConfig::log_error_details() {\n\n error!(\n\n \"Received ECC signature with invalid size: r - {} bytes; s - {} bytes\",\n\n r.len(),\n\n s.len()\n\n );\n\n } else {\n\n error!(\"Received ECC signature with invalid size.\");\n\n }\n\n return Err(ResponseStatus::PsaErrorGenericError);\n\n }\n\n\n\n let mut signature = vec![];\n\n signature.append(&mut r);\n\n signature.append(&mut s);\n\n Ok(signature)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 2, "score": 74731.56041053397 }, { "content": "pub fn pub_key_to_bytes(pub_key: PublicKey, key_attributes: Attributes) -> Result<Vec<u8>> {\n\n match pub_key {\n\n PublicKey::Rsa(key) => picky_asn1_der::to_vec(&RSAPublicKey {\n\n modulus: IntegerAsn1::from_unsigned_bytes_be(key),\n\n public_exponent: IntegerAsn1::from_signed_bytes_be(PUBLIC_EXPONENT.to_vec()),\n\n })\n\n .or(Err(ResponseStatus::PsaErrorGenericError)),\n\n PublicKey::Ecc { x, y } => {\n\n let p_byte_size = key_attributes.bits / 8; // should not fail for valid keys\n\n if x.len() != p_byte_size || y.len() != p_byte_size {\n\n if crate::utils::GlobalConfig::log_error_details() {\n\n error!(\n\n \"Received ECC public key with invalid size: x - {} bytes; y - {} bytes\",\n\n x.len(),\n\n y.len()\n\n );\n\n } else {\n\n error!(\"Received ECC public key with invalid size.\");\n\n }\n\n return Err(ResponseStatus::PsaErrorCommunicationFailure);\n\n }\n\n Ok(elliptic_curve_point_to_octet_string(x, y))\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 3, "score": 73591.445198451 }, { "content": "// Points on elliptic curves are represented as defined in section 2.3.3 of https://www.secg.org/sec1-v2.pdf\n\n// The (uncompressed) representation is [ 0x04 || x || y ] where x and y are the coordinates of the point\n\nfn elliptic_curve_point_to_octet_string(mut x: Vec<u8>, mut y: Vec<u8>) -> Vec<u8> {\n\n let mut octet_string = vec![0x04];\n\n octet_string.append(&mut x);\n\n octet_string.append(&mut y);\n\n octet_string\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 4, "score": 65465.77036389227 }, { "content": "#[derive(Arbitrary, Debug)]\n\nstruct MockStream(Vec<u8>);\n\n\n\nimpl Read for MockStream {\n\n fn read(&mut self, buf: &mut [u8]) -> Result<usize> {\n\n if self.0.is_empty() {\n\n return Ok(0);\n\n }\n\n let n = cmp::min(buf.len(), self.0.len());\n\n for (idx, val) in self.0.drain(0..n).enumerate() {\n\n buf[idx] = val;\n\n }\n\n\n\n Ok(n)\n\n }\n\n}\n\n\n\nimpl Write for MockStream {\n\n fn write(&mut self, buf: &[u8]) -> Result<usize> {\n\n Ok(buf.len())\n\n }\n\n\n\n fn flush(&mut self) -> Result<()> {\n\n Ok(())\n\n }\n\n}\n\n\n\nfuzz_target!(|stream: MockStream| {\n\n FRONT_END_HANDLER.handle_request(stream);\n\n});\n\n\n", "file_path": "fuzz/fuzz_targets/fuzz_service.rs", "rank": 5, "score": 53470.37129363736 }, { "content": "#[test]\n\nfn create_and_verify() -> Result<()> {\n\n let mut client = TestClient::new();\n\n client.do_not_destroy_keys();\n\n\n\n let key_name = String::from(\"🤡 Clown's Master Key 🤡\");\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n let signature = client.sign_with_rsa_sha256(key_name.clone(), HASH.to_vec())?;\n\n\n\n client.verify_with_rsa_sha256(key_name, HASH.to_vec(), signature)\n\n}\n", "file_path": "e2e_tests/tests/per_provider/persistent_before.rs", "rank": 6, "score": 53071.26332140011 }, { "content": "#[test]\n\nfn reuse_to_sign() -> Result<()> {\n\n let mut client = TestClient::new();\n\n\n\n let key_name = String::from(\"🤡 Clown's Master Key 🤡\");\n\n\n\n let signature = client.sign_with_rsa_sha256(key_name.clone(), HASH.to_vec())?;\n\n\n\n client.verify_with_rsa_sha256(key_name.clone(), HASH.to_vec(), signature)?;\n\n client.destroy_key(key_name)\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/persistent_after.rs", "rank": 7, "score": 53071.26332140011 }, { "content": "#[test]\n\nfn sign_verify_with_provider_discovery() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"sign_verify_with_provider_discovery\");\n\n client.generate_rsa_sign_key(key_name)\n\n}\n", "file_path": "e2e_tests/tests/all_providers/mod.rs", "rank": 8, "score": 52134.64528461699 }, { "content": "fn remove_key_id(key_triple: &KeyTriple, store_handle: &mut dyn ManageKeyInfo) -> Result<()> {\n\n // ID Counter not affected as overhead and extra complication deemed unnecessary\n\n match store_handle.remove(key_triple) {\n\n Ok(_) => Ok(()),\n\n Err(string) => Err(key_info_managers::to_response_status(string)),\n\n }\n\n}\n\n\n", "file_path": "src/providers/mbed_provider/key_management.rs", "rank": 9, "score": 51527.011124017445 }, { "content": "#[test]\n\nfn test_ping() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let version = client.ping()?;\n\n assert_eq!(version.0, 1);\n\n assert_eq!(version.1, 0);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/ping.rs", "rank": 10, "score": 51255.07763736932 }, { "content": "#[test]\n\nfn import_key() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"import_key\");\n\n\n\n client.import_rsa_public_key(key_name, KEY_DATA.to_vec())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 11, "score": 50427.50193831945 }, { "content": "#[test]\n\nfn export_key() -> Result<()> {\n\n let mut client = TestClient::new();\n\n\n\n if !client.is_operation_supported(Opcode::PsaExportKey) {\n\n return Ok(());\n\n }\n\n\n\n let key_name = String::from(\"export_key\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let _ = client.export_key(key_name)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_key.rs", "rank": 12, "score": 50427.50193831945 }, { "content": "#[test]\n\nfn delete_wrong_key() -> Result<()> {\n\n let key_name = String::from(\"delete_wrong_key\");\n\n let mut client = TestClient::new();\n\n let auth1 = String::from(\"first_client\");\n\n let auth2 = String::from(\"second_client\");\n\n\n\n client.set_auth(auth1);\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n client.set_auth(auth2);\n\n let status = client\n\n .destroy_key(key_name)\n\n .expect_err(\"Destroying key should have failed\");\n\n assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist);\n\n\n\n Ok(())\n\n}\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/auth.rs", "rank": 13, "score": 50427.50193831945 }, { "content": "fn example_modulus_1024() -> Vec<u8> {\n\n vec![\n\n 153, 165, 220, 135, 89, 101, 254, 229, 28, 33, 138, 247, 20, 102, 253, 217, 247, 246, 142,\n\n 107, 51, 40, 179, 149, 45, 117, 254, 236, 161, 109, 16, 81, 135, 72, 112, 132, 150, 175,\n\n 128, 173, 182, 122, 227, 214, 196, 130, 54, 239, 93, 5, 203, 185, 233, 61, 159, 156, 7,\n\n 161, 87, 48, 234, 105, 161, 108, 215, 211, 150, 168, 156, 212, 6, 63, 81, 24, 101, 72, 160,\n\n 97, 243, 142, 86, 10, 160, 122, 8, 228, 178, 252, 35, 209, 222, 228, 16, 143, 99, 143, 146,\n\n 241, 186, 187, 22, 209, 86, 141, 24, 159, 12, 146, 44, 111, 254, 183, 54, 229, 109, 28, 39,\n\n 22, 141, 173, 85, 26, 58, 9, 128, 27, 57, 131,\n\n ]\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 14, "score": 49987.86079206261 }, { "content": "#[test]\n\nfn two_auths_same_key_name() -> Result<()> {\n\n let key_name = String::from(\"two_auths_same_key_name\");\n\n let mut client = TestClient::new();\n\n let auth1 = String::from(\"first_client\");\n\n let auth2 = String::from(\"second_client\");\n\n\n\n client.set_auth(auth1);\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n client.set_auth(auth2);\n\n client.generate_rsa_sign_key(key_name)\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/auth.rs", "rank": 15, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn check_export_possible() -> Result<()> {\n\n let mut client = TestClient::new();\n\n\n\n if !client.is_operation_supported(Opcode::PsaExportKey) {\n\n return Ok(());\n\n }\n\n\n\n let key_name = String::from(\"check_export_possible\");\n\n\n\n let key_attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaKeyPair,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: false,\n\n sign_message: false,\n\n verify_message: false,\n\n export: true,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_key.rs", "rank": 16, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn only_verify_from_internet() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"only_verify\");\n\n\n\n // \"Les carottes sont cuites.\" hashed with SHA256\n\n let digest = vec![\n\n 0x02, 0x2b, 0x26, 0xb1, 0xc3, 0x18, 0xdb, 0x73, 0x36, 0xef, 0x6f, 0x50, 0x9c, 0x35, 0xdd,\n\n 0xaa, 0xe1, 0x3d, 0x21, 0xdf, 0x83, 0x68, 0x0f, 0x48, 0xae, 0x5d, 0x8a, 0x5d, 0x37, 0x3c,\n\n 0xc1, 0x05,\n\n ];\n\n\n\n // The private part of that key was used to sign the digest with RSA PKCS #1 and produce\n\n // the following signature.\n\n let public_key = vec![\n\n 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0x96, 0xdc, 0x72, 0x77, 0x49, 0x82, 0xfd, 0x2d,\n\n 0x06, 0x65, 0x8c, 0xe5, 0x3a, 0xcd, 0xed, 0xbd, 0x50, 0xd7, 0x6f, 0x3b, 0xe5, 0x6a, 0x76,\n\n 0xed, 0x3e, 0xd8, 0xf9, 0x93, 0x40, 0x55, 0x86, 0x6f, 0xbe, 0x76, 0x60, 0xd2, 0x03, 0x23,\n\n 0x59, 0x19, 0x8d, 0xfc, 0x51, 0x6a, 0x95, 0xc8, 0x5d, 0x5a, 0x89, 0x4d, 0xe5, 0xea, 0x44,\n\n 0x78, 0x29, 0x62, 0xdb, 0x3f, 0xf0, 0xf7, 0x49, 0x15, 0xa5, 0xae, 0x6d, 0x81, 0x8f, 0x06,\n\n 0x7b, 0x0b, 0x50, 0x7a, 0x2f, 0xeb, 0x00, 0xb6, 0x12, 0xf3, 0x10, 0xaf, 0x4d, 0x4a, 0xa9,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 17, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn create_and_import_key() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"create_and_import_key\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let status = client\n\n .import_rsa_public_key(key_name, KEY_DATA.to_vec())\n\n .expect_err(\"Key should have already existed\");\n\n assert_eq!(status, ResponseStatus::PsaErrorAlreadyExists);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 18, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn check_format_import2() -> Result<()> {\n\n // If the bits field of the key attributes is zero, the operation should still work.\n\n // The size of the key is always taken from the data parameter.\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"check_format_import2\");\n\n\n\n let public_key = RSAPublicKey {\n\n modulus: IntegerAsn1::from_unsigned_bytes_be(example_modulus_1024()),\n\n public_exponent: IntegerAsn1::from_unsigned_bytes_be(vec![0x01, 0x00, 0x01]),\n\n };\n\n\n\n let attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaPublicKey,\n\n bits: 0,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: true,\n\n sign_message: false,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 19, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn create_and_destroy() -> Result<()> {\n\n let mut client = TestClient::new();\n\n client.do_not_destroy_keys();\n\n let key_name = String::from(\"create_and_destroy\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n client.destroy_key(key_name)\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 20, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn check_format_import1() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"check_format_import\");\n\n\n\n let public_key = RSAPublicKey {\n\n modulus: IntegerAsn1::from_unsigned_bytes_be(example_modulus_1024()),\n\n public_exponent: IntegerAsn1::from_unsigned_bytes_be(vec![0x01, 0x00, 0x01]),\n\n };\n\n\n\n client.import_rsa_public_key(key_name, picky_asn1_der::to_vec(&public_key).unwrap())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 21, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn import_key_twice() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"import_key_twice\");\n\n\n\n client.import_rsa_public_key(key_name.clone(), KEY_DATA.to_vec())?;\n\n let status = client\n\n .import_rsa_public_key(key_name, KEY_DATA.to_vec())\n\n .expect_err(\"The key with the same name has already been created.\");\n\n assert_eq!(status, ResponseStatus::PsaErrorAlreadyExists);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 22, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn create_twice() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"create_twice\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n let status = client\n\n .generate_rsa_sign_key(key_name)\n\n .expect_err(\"A key with the same name can not be created twice.\");\n\n assert_eq!(status, ResponseStatus::PsaErrorAlreadyExists);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 23, "score": 49647.44059592052 }, { "content": "#[test]\n\nfn check_format_import3() -> Result<()> {\n\n // If the bits field of the key attributes is different that the size of the key parsed\n\n // from the data parameter, the operation should fail.\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"check_format_import3\");\n\n\n\n let public_key = RSAPublicKey {\n\n modulus: IntegerAsn1::from_unsigned_bytes_be(vec![0xDE; 1024]),\n\n public_exponent: IntegerAsn1::from_unsigned_bytes_be(vec![0x01, 0x00, 0x01]),\n\n };\n\n\n\n let attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaPublicKey,\n\n bits: 1023,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: true,\n\n sign_message: false,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 24, "score": 49647.44059592052 }, { "content": "type LocalIdStore = HashSet<[u8; 4]>;\n\n\n\nmod asym_sign;\n\nmod key_management;\n\nmod utils;\n\n\n\nconst SUPPORTED_OPCODES: [Opcode; 6] = [\n\n Opcode::PsaGenerateKey,\n\n Opcode::PsaDestroyKey,\n\n Opcode::PsaSignHash,\n\n Opcode::PsaVerifyHash,\n\n Opcode::PsaImportKey,\n\n Opcode::PsaExportPublicKey,\n\n];\n\n\n\n/// Provider for Public Key Cryptography Standard #11\n\n///\n\n/// Operations for this provider are serviced through a PKCS11 interface,\n\n/// allowing any libraries exposing said interface to be loaded and used\n\n/// at runtime.\n", "file_path": "src/providers/pkcs11_provider/mod.rs", "rank": 25, "score": 49620.071022195625 }, { "content": "pub fn key_info_exists(key_triple: &KeyTriple, store_handle: &dyn ManageKeyInfo) -> Result<bool> {\n\n match store_handle.exists(key_triple) {\n\n Ok(val) => Ok(val),\n\n Err(string) => Err(key_info_managers::to_response_status(string)),\n\n }\n\n}\n\n\n\nimpl Pkcs11Provider {\n\n /// Find the PKCS 11 object handle corresponding to the key ID and the key type (public or\n\n /// private key) given as parameters for the current session.\n\n pub(super) fn find_key(\n\n &self,\n\n session: CK_SESSION_HANDLE,\n\n key_id: [u8; 4],\n\n key_type: KeyPairType,\n\n ) -> Result<CK_OBJECT_HANDLE> {\n\n let mut template = vec![CK_ATTRIBUTE::new(pkcs11::types::CKA_ID).with_bytes(&key_id)];\n\n match key_type {\n\n KeyPairType::PublicKey => template.push(\n\n CK_ATTRIBUTE::new(pkcs11::types::CKA_CLASS)\n", "file_path": "src/providers/pkcs11_provider/key_management.rs", "rank": 26, "score": 49221.28141057453 }, { "content": "pub fn key_info_exists(key_triple: &KeyTriple, store_handle: &dyn ManageKeyInfo) -> Result<bool> {\n\n store_handle\n\n .exists(key_triple)\n\n .map_err(key_info_managers::to_response_status)\n\n}\n\n\n\nimpl MbedProvider {\n\n pub(super) fn psa_generate_key_internal(\n\n &self,\n\n app_name: ApplicationName,\n\n op: psa_generate_key::Operation,\n\n ) -> Result<psa_generate_key::Result> {\n\n let key_name = op.key_name;\n\n let key_attributes = op.attributes;\n\n let key_triple = KeyTriple::new(app_name, ProviderID::MbedCrypto, key_name);\n\n let mut store_handle = self\n\n .key_info_store\n\n .write()\n\n .expect(\"Key store lock poisoned\");\n\n if key_info_exists(&key_triple, &*store_handle)? {\n", "file_path": "src/providers/mbed_provider/key_management.rs", "rank": 27, "score": 49221.28141057453 }, { "content": "#[test]\n\nfn export_public_key() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"export_public_key\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let _ = client.export_public_key(key_name)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_public_key.rs", "rank": 28, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn failed_imported_key_should_be_removed() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"failed_imported_key_should_be_removed\");\n\n\n\n let public_key = RSAPublicKey {\n\n modulus: IntegerAsn1::from_unsigned_bytes_be(example_modulus_1024()),\n\n public_exponent: IntegerAsn1::from_unsigned_bytes_be(vec![0x01, 0x00, 0x01]),\n\n };\n\n\n\n let attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n // Not supported\n\n key_type: Type::Aes,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: true,\n\n sign_message: false,\n\n verify_message: true,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 29, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn create_destroy_twice() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"create_destroy_twice_1\");\n\n let key_name_2 = String::from(\"create_destroy_twice_2\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n client.generate_rsa_sign_key(key_name_2.clone())?;\n\n\n\n client.destroy_key(key_name)?;\n\n client.destroy_key(key_name_2)\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 30, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn simple_sign_hash() -> Result<()> {\n\n let key_name = String::from(\"simple_sign_hash\");\n\n let mut client = TestClient::new();\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let hash = hasher.result().to_vec();\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let _ = client.sign_with_rsa_sha256(key_name, hash)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 31, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn sign_hash_not_permitted() -> Result<()> {\n\n let key_name = String::from(\"sign_hash_not_permitted\");\n\n let mut client = TestClient::new();\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let hash = hasher.result().to_vec();\n\n\n\n let attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaKeyPair,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: true,\n\n sign_message: true,\n\n verify_message: true,\n\n export: false,\n\n encrypt: false,\n\n decrypt: false,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 32, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn fail_verify_hash2() -> Result<()> {\n\n let key_name = String::from(\"fail_verify_hash2\");\n\n let mut client = TestClient::new();\n\n\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let mut hash = hasher.result().to_vec();\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let signature = client.sign_with_rsa_sha256(key_name.clone(), hash.clone())?;\n\n // Modify hash\n\n hash[4] += 1;\n\n let status = client\n\n .verify_with_rsa_sha256(key_name, hash, signature)\n\n .unwrap_err();\n\n assert_eq!(status, ResponseStatus::PsaErrorInvalidSignature);\n\n Ok(())\n\n}\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 33, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn check_rsa_export_format() -> Result<()> {\n\n let mut client = TestClient::new();\n\n\n\n if !client.is_operation_supported(Opcode::PsaExportKey) {\n\n return Ok(());\n\n }\n\n\n\n let key_name = String::from(\"check_public_rsa_export_format\");\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n let key = client.export_key(key_name)?;\n\n\n\n // That should not fail if the bytes are in the expected format.\n\n let _public_key: RSAPublicKey = picky_asn1_der::from_bytes(&key).unwrap();\n\n let _private_key: RSAPrivateKey = picky_asn1_der::from_bytes(&key).unwrap();\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_key.rs", "rank": 34, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn verify_hash_not_permitted() -> Result<()> {\n\n let key_name = String::from(\"verify_hash_not_permitted\");\n\n let mut client = TestClient::new();\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let hash = hasher.result().to_vec();\n\n\n\n let attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaKeyPair,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: true,\n\n verify_hash: false,\n\n sign_message: true,\n\n verify_message: true,\n\n export: false,\n\n encrypt: false,\n\n decrypt: false,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 35, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn create_destroy_and_operation() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let hash = vec![0xDE; 32];\n\n let key_name = String::from(\"create_destroy_and_operation\");\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n client.destroy_key(key_name.clone())?;\n\n\n\n let status = client\n\n .sign_with_rsa_sha256(key_name, hash)\n\n .expect_err(\"The key used by this operation should have been deleted.\");\n\n assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 36, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn asym_verify_fail() -> Result<()> {\n\n let key_name = String::from(\"asym_verify_fail\");\n\n let signature = vec![0xff; 128];\n\n let mut client = TestClient::new();\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let status = client\n\n .verify_with_rsa_sha256(key_name, HASH.to_vec(), signature)\n\n .expect_err(\"Verification should fail.\");\n\n if !(status == ResponseStatus::PsaErrorInvalidSignature\n\n || status == ResponseStatus::PsaErrorCorruptionDetected)\n\n {\n\n panic!(\"An invalid signature or a tampering detection should be the only reasons of the verification failing.\");\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 37, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn import_and_export_public_key() -> Result<()> {\n\n let mut client = TestClient::new();\n\n\n\n if !client.is_operation_supported(Opcode::PsaExportKey) {\n\n return Ok(());\n\n }\n\n\n\n let key_name = String::from(\"import_and_export_public_key\");\n\n let key_data = vec![\n\n 48, 129, 137, 2, 129, 129, 0, 153, 165, 220, 135, 89, 101, 254, 229, 28, 33, 138, 247, 20,\n\n 102, 253, 217, 247, 246, 142, 107, 51, 40, 179, 149, 45, 117, 254, 236, 161, 109, 16, 81,\n\n 135, 72, 112, 132, 150, 175, 128, 173, 182, 122, 227, 214, 196, 130, 54, 239, 93, 5, 203,\n\n 185, 233, 61, 159, 156, 7, 161, 87, 48, 234, 105, 161, 108, 215, 211, 150, 168, 156, 212,\n\n 6, 63, 81, 24, 101, 72, 160, 97, 243, 142, 86, 10, 160, 122, 8, 228, 178, 252, 35, 209,\n\n 222, 228, 16, 143, 99, 143, 146, 241, 186, 187, 22, 209, 86, 141, 24, 159, 12, 146, 44,\n\n 111, 254, 183, 54, 229, 109, 28, 39, 22, 141, 173, 85, 26, 58, 9, 128, 27, 57, 131, 2, 3,\n\n 1, 0, 1,\n\n ];\n\n client.import_rsa_public_key(key_name.clone(), key_data.clone())?;\n\n\n\n assert_eq!(key_data, client.export_key(key_name)?);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_key.rs", "rank": 38, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn fail_verify_hash() -> Result<()> {\n\n let key_name = String::from(\"fail_verify_hash\");\n\n let mut client = TestClient::new();\n\n\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let hash = hasher.result().to_vec();\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let mut signature = client.sign_with_rsa_sha256(key_name.clone(), hash.clone())?;\n\n // Modify signature\n\n signature[4] += 1;\n\n let status = client\n\n .verify_with_rsa_sha256(key_name, hash, signature)\n\n .unwrap_err();\n\n assert_eq!(status, ResponseStatus::PsaErrorInvalidSignature);\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 39, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn simple_verify_hash() -> Result<()> {\n\n let key_name = String::from(\"simple_verify_hash\");\n\n let mut client = TestClient::new();\n\n\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let hash = hasher.result().to_vec();\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let signature = client.sign_with_rsa_sha256(key_name.clone(), hash.clone())?;\n\n client.verify_with_rsa_sha256(key_name, hash, signature)\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 40, "score": 48910.915822844036 }, { "content": "#[test]\n\nfn failed_created_key_should_be_removed() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"failed_created_key_should_be_removed\");\n\n const GARBAGE_IMPORT_DATA: [u8; 1] = [48];\n\n\n\n // The data being imported is garbage, should fail\n\n let _ = client\n\n .import_rsa_public_key(key_name.clone(), GARBAGE_IMPORT_DATA.to_vec())\n\n .unwrap_err();\n\n // The key should not exist anymore in the KIM\n\n client.generate_rsa_sign_key(key_name)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 41, "score": 48214.38179188858 }, { "content": "#[test]\n\nfn check_export_public_possible() -> Result<()> {\n\n // Exporting a public key is always permitted\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"check_export_public_possible\");\n\n\n\n let key_attributes = Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaKeyPair,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: false,\n\n sign_message: false,\n\n verify_message: false,\n\n export: false,\n\n encrypt: false,\n\n decrypt: false,\n\n cache: false,\n\n copy: false,\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_public_key.rs", "rank": 42, "score": 48214.38179188858 }, { "content": "#[test]\n\nfn sign_hash_bad_format() -> Result<()> {\n\n let key_name = String::from(\"sign_hash_bad_format\");\n\n let mut client = TestClient::new();\n\n let hash1 = vec![0xEE; 31];\n\n let hash2 = vec![0xBB; 33];\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let status1 = client\n\n .sign_with_rsa_sha256(key_name.clone(), hash1)\n\n .unwrap_err();\n\n let status2 = client.sign_with_rsa_sha256(key_name, hash2).unwrap_err();\n\n\n\n assert_eq!(status1, ResponseStatus::PsaErrorInvalidArgument);\n\n assert_eq!(status2, ResponseStatus::PsaErrorInvalidArgument);\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 43, "score": 48214.38179188858 }, { "content": "#[test]\n\nfn import_and_export_public_key() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"import_and_export_public_key\");\n\n let key_data = vec![\n\n 48, 129, 137, 2, 129, 129, 0, 153, 165, 220, 135, 89, 101, 254, 229, 28, 33, 138, 247, 20,\n\n 102, 253, 217, 247, 246, 142, 107, 51, 40, 179, 149, 45, 117, 254, 236, 161, 109, 16, 81,\n\n 135, 72, 112, 132, 150, 175, 128, 173, 182, 122, 227, 214, 196, 130, 54, 239, 93, 5, 203,\n\n 185, 233, 61, 159, 156, 7, 161, 87, 48, 234, 105, 161, 108, 215, 211, 150, 168, 156, 212,\n\n 6, 63, 81, 24, 101, 72, 160, 97, 243, 142, 86, 10, 160, 122, 8, 228, 178, 252, 35, 209,\n\n 222, 228, 16, 143, 99, 143, 146, 241, 186, 187, 22, 209, 86, 141, 24, 159, 12, 146, 44,\n\n 111, 254, 183, 54, 229, 109, 28, 39, 22, 141, 173, 85, 26, 58, 9, 128, 27, 57, 131, 2, 3,\n\n 1, 0, 1,\n\n ];\n\n client.import_rsa_public_key(key_name.clone(), key_data.clone())?;\n\n\n\n assert_eq!(key_data, client.export_public_key(key_name)?);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_public_key.rs", "rank": 44, "score": 48214.38179188858 }, { "content": "#[test]\n\nfn verify_hash_bad_format() -> Result<()> {\n\n let key_name = String::from(\"verify_hash_bad_format\");\n\n let mut client = TestClient::new();\n\n let mut hasher = Sha256::new();\n\n hasher.input(b\"Bob wrote this message.\");\n\n let good_hash = hasher.result().to_vec();\n\n let hash1 = vec![0xEE; 255];\n\n let hash2 = vec![0xBB; 257];\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let signature = client.sign_with_rsa_sha256(key_name.clone(), good_hash)?;\n\n let status1 = client\n\n .verify_with_rsa_sha256(key_name.clone(), hash1, signature.clone())\n\n .unwrap_err();\n\n let status2 = client\n\n .verify_with_rsa_sha256(key_name, hash2, signature)\n\n .unwrap_err();\n\n\n\n assert_eq!(status1, ResponseStatus::PsaErrorInvalidArgument);\n\n assert_eq!(status2, ResponseStatus::PsaErrorInvalidArgument);\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 45, "score": 48214.38179188858 }, { "content": "#[test]\n\nfn check_public_rsa_export_format() -> Result<()> {\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"check_public_rsa_export_format\");\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n let public_key = client.export_public_key(key_name)?;\n\n\n\n // That should not fail if the bytes are in the expected format.\n\n let _public_key: RSAPublicKey = picky_asn1_der::from_bytes(&public_key).unwrap();\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_public_key.rs", "rank": 46, "score": 47554.66755089685 }, { "content": "#[test]\n\nfn asym_sign_and_verify_rsa_pkcs() -> Result<()> {\n\n let key_name = String::from(\"asym_sign_and_verify_rsa_pkcs\");\n\n let mut client = TestClient::new();\n\n\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n\n\n let signature = client.sign_with_rsa_sha256(key_name.clone(), HASH.to_vec())?;\n\n\n\n client.verify_with_rsa_sha256(key_name, HASH.to_vec(), signature)\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 47, "score": 47554.66755089685 }, { "content": "#[test]\n\nfn generate_public_rsa_check_modulus() -> Result<()> {\n\n // As stated in the operation page, the public exponent of RSA key pair should be 65537\n\n // (0x010001).\n\n let mut client = TestClient::new();\n\n let key_name = String::from(\"generate_public_rsa_check_modulus\");\n\n client.generate_rsa_sign_key(key_name.clone())?;\n\n let public_key = client.export_public_key(key_name)?;\n\n\n\n let public_key: RSAPublicKey = picky_asn1_der::from_bytes(&public_key).unwrap();\n\n assert_eq!(\n\n public_key.public_exponent.as_unsigned_bytes_be(),\n\n [0x01, 0x00, 0x01]\n\n );\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 48, "score": 47554.66755089685 }, { "content": "#[allow(deprecated)]\n\nfn convert_hash_to_tpm(hash: Hash) -> Result<HashingAlgorithm> {\n\n match hash {\n\n Hash::Sha1 => Ok(HashingAlgorithm::Sha1),\n\n Hash::Sha256 => Ok(HashingAlgorithm::Sha256),\n\n Hash::Sha384 => Ok(HashingAlgorithm::Sha384),\n\n Hash::Sha512 => Ok(HashingAlgorithm::Sha512),\n\n Hash::Sha3_256 => Ok(HashingAlgorithm::Sha3_256),\n\n Hash::Sha3_384 => Ok(HashingAlgorithm::Sha3_384),\n\n Hash::Sha3_512 => Ok(HashingAlgorithm::Sha3_512),\n\n _ => Err(ResponseStatus::PsaErrorNotSupported),\n\n }\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 49, "score": 44090.38157058343 }, { "content": "fn convert_curve_to_tpm(key_attributes: Attributes) -> Result<EllipticCurve> {\n\n match key_attributes.key_type {\n\n Type::EccKeyPair {\n\n curve_family: EccFamily::SecpR1,\n\n }\n\n | Type::EccPublicKey {\n\n curve_family: EccFamily::SecpR1,\n\n } => match key_attributes.bits {\n\n 192 => Ok(EllipticCurve::NistP192),\n\n 224 => Ok(EllipticCurve::NistP224),\n\n 256 => Ok(EllipticCurve::NistP256),\n\n 384 => Ok(EllipticCurve::NistP384),\n\n 512 => Ok(EllipticCurve::NistP521),\n\n _ => Err(ResponseStatus::PsaErrorNotSupported),\n\n },\n\n _ => Err(ResponseStatus::PsaErrorNotSupported),\n\n }\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 50, "score": 43353.856797506945 }, { "content": "fn convert_asym_scheme_to_tpm(algorithm: Algorithm) -> Result<AsymSchemeUnion> {\n\n match algorithm {\n\n Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {\n\n hash_alg: SignHash::Specific(hash_alg),\n\n }) => Ok(AsymSchemeUnion::RSASSA(convert_hash_to_tpm(hash_alg)?)),\n\n Algorithm::AsymmetricSignature(AsymmetricSignature::Ecdsa {\n\n hash_alg: SignHash::Specific(hash_alg),\n\n }) => Ok(AsymSchemeUnion::ECDSA(convert_hash_to_tpm(hash_alg)?)),\n\n _ => Err(ResponseStatus::PsaErrorNotSupported),\n\n }\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 51, "score": 42657.32276655149 }, { "content": "pub fn parsec_to_tpm_params(attributes: Attributes) -> Result<KeyParams> {\n\n match attributes.key_type {\n\n Type::RsaKeyPair => {\n\n let size = match attributes.bits {\n\n x @ 1024 | x @ 2048 | x @ 3072 | x @ 4096 => x.try_into().unwrap(), // will not fail on the matched values\n\n _ => return Err(ResponseStatus::PsaErrorInvalidArgument),\n\n };\n\n Ok(KeyParams::Rsa {\n\n size,\n\n scheme: convert_asym_scheme_to_tpm(attributes.policy.permitted_algorithms)?,\n\n pub_exponent: 0,\n\n })\n\n }\n\n Type::EccKeyPair { .. } => Ok(KeyParams::Ecc {\n\n scheme: convert_asym_scheme_to_tpm(attributes.policy.permitted_algorithms)?,\n\n curve: convert_curve_to_tpm(attributes)?,\n\n }),\n\n _ => Err(ResponseStatus::PsaErrorNotSupported),\n\n }\n\n}\n\n\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 52, "score": 42048.166637020506 }, { "content": "fn get_key_info_manager(config: &KeyInfoManagerConfig) -> Result<KeyInfoManager> {\n\n let manager = match config.manager_type {\n\n KeyInfoManagerType::OnDisk => {\n\n let store_path = if let Some(store_path) = &config.store_path {\n\n store_path.to_owned()\n\n } else {\n\n DEFAULT_MAPPINGS_PATH.to_string()\n\n };\n\n\n\n OnDiskKeyInfoManagerBuilder::new()\n\n .with_mappings_dir_path(PathBuf::from(store_path))\n\n .build()?\n\n }\n\n };\n\n\n\n Ok(Arc::new(RwLock::new(manager)))\n\n}\n", "file_path": "src/utils/service_builder.rs", "rank": 53, "score": 41371.869732023646 }, { "content": "/// Lists all the directory paths in the given directory path.\n\nfn list_dirs(path: &PathBuf) -> std::io::Result<Vec<PathBuf>> {\n\n // read_dir returning an iterator over Result<DirEntry>, there is first a conversion to a path\n\n // and then a check if the path is a directory or not.\n\n let dir_entries: std::io::Result<Vec<DirEntry>> = path.read_dir()?.collect();\n\n Ok(dir_entries?\n\n .iter()\n\n .map(|dir_entry| dir_entry.path())\n\n .filter(|dir_path| dir_path.is_dir())\n\n .collect())\n\n}\n\n\n", "file_path": "src/key_info_managers/on_disk_manager/mod.rs", "rank": 54, "score": 37364.15422059943 }, { "content": "/// Lists all the file paths in the given directory path.\n\nfn list_files(path: &PathBuf) -> std::io::Result<Vec<PathBuf>> {\n\n let dir_entries: std::io::Result<Vec<DirEntry>> = path.read_dir()?.collect();\n\n Ok(dir_entries?\n\n .iter()\n\n .map(|dir_entry| dir_entry.path())\n\n .filter(|dir_path| dir_path.is_file())\n\n .collect())\n\n}\n\n\n\n/// Filesystem-based `KeyInfoManager`\n\n///\n\n/// The `OnDiskKeyInfoManager` relies on access control mechanisms provided by the OS for\n\n/// the filesystem to ensure security of the mappings.\n\nimpl OnDiskKeyInfoManager {\n\n /// Creates an instance of the on-disk manager from the mapping files. This function will\n\n /// create the mappings directory if it does not already exist.\n\n /// The mappings folder is composed of three levels: two levels of directory and one level\n\n /// of files. The key triple to key info mappings are represented on disk as the following:\n\n ///\n\n /// mappings_dir_path/\n", "file_path": "src/key_info_managers/on_disk_manager/mod.rs", "rank": 55, "score": 37364.15422059943 }, { "content": "/// Converts an OsStr reference to a ProviderID value.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns a custom std::io error if the conversion failed.\n\nfn os_str_to_provider_id(os_str: &OsStr) -> std::io::Result<ProviderID> {\n\n match os_str.to_str() {\n\n Some(str) => match str.parse::<u8>() {\n\n Ok(provider_id_u8) => match ProviderID::try_from(provider_id_u8) {\n\n Ok(provider_id) => Ok(provider_id),\n\n Err(response_status) => {\n\n Err(Error::new(ErrorKind::Other, response_status.to_string()))\n\n }\n\n },\n\n Err(_) => Err(Error::new(\n\n ErrorKind::Other,\n\n \"Failed to convert Provider directory name to an u8 number.\",\n\n )),\n\n },\n\n None => Err(Error::new(\n\n ErrorKind::Other,\n\n \"Conversion from PathBuf to String failed.\",\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/key_info_managers/on_disk_manager/mod.rs", "rank": 56, "score": 37242.18993697506 }, { "content": "/// Management interface for key name to key info mapping\n\n///\n\n/// Interface to be implemented for persistent storage of key name -> key info mappings.\n\npub trait ManageKeyInfo {\n\n /// Returns a reference to the key info corresponding to this key triple or `None` if it does not\n\n /// exist.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns an error as a String if there was a problem accessing the Key Info Manager.\n\n fn get(&self, key_triple: &KeyTriple) -> Result<Option<&KeyInfo>, String>;\n\n\n\n /// Returns a Vec of reference to the key triples corresponding to this provider.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Returns an error as a String if there was a problem accessing the Key Info Manager.\n\n fn get_all(&self, provider_id: ProviderID) -> Result<Vec<&KeyTriple>, String>;\n\n\n\n /// Inserts a new mapping between the key triple and the key info. If the triple already exists,\n\n /// overwrite the existing mapping and returns the old `KeyInfo`. Otherwise returns `None`.\n\n ///\n\n /// # Errors\n", "file_path": "src/key_info_managers/mod.rs", "rank": 57, "score": 25688.9947240836 }, { "content": "fn gen_ecc_sign_key_op(key_name: String) -> psa_generate_key::Operation {\n\n psa_generate_key::Operation {\n\n key_name,\n\n attributes: Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::EccKeyPair {\n\n curve_family: EccFamily::SecpR1,\n\n },\n\n bits: 256,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n export: true,\n\n copy: false,\n\n cache: false,\n\n encrypt: false,\n\n decrypt: false,\n\n sign_message: true,\n\n sign_hash: true,\n\n verify_message: true,\n\n verify_hash: true,\n\n derive: false,\n\n },\n\n permitted_algorithms: Algorithm::AsymmetricSignature(AsymmetricSignature::Ecdsa {\n\n hash_alg: Hash::Sha256.into(),\n\n }),\n\n },\n\n },\n\n }\n\n}\n\n\n", "file_path": "tests/providers/tpm.rs", "rank": 58, "score": 19644.952899132255 }, { "content": "fn gen_rsa_sign_key_op(key_name: String) -> psa_generate_key::Operation {\n\n psa_generate_key::Operation {\n\n key_name,\n\n attributes: Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaKeyPair,\n\n bits: 2048,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n export: true,\n\n copy: false,\n\n cache: false,\n\n encrypt: false,\n\n decrypt: false,\n\n sign_message: true,\n\n sign_hash: true,\n\n verify_message: true,\n\n verify_hash: true,\n\n derive: false,\n\n },\n\n permitted_algorithms: Algorithm::AsymmetricSignature(\n\n AsymmetricSignature::RsaPkcs1v15Sign {\n\n hash_alg: Hash::Sha256.into(),\n\n },\n\n ),\n\n },\n\n },\n\n }\n\n}\n\n\n", "file_path": "tests/providers/tpm.rs", "rank": 59, "score": 19644.952899132255 }, { "content": "type KeyInfoManager = Arc<RwLock<dyn ManageKeyInfo + Send + Sync>>;\n", "file_path": "src/utils/service_builder.rs", "rank": 60, "score": 16863.525365251327 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::operations::psa_algorithm::*;\n\nuse parsec_client::core::interface::operations::psa_key_attributes::*;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse parsec_client::core::interface::requests::Result;\n\nuse picky_asn1::wrapper::IntegerAsn1;\n\nuse picky_asn1_x509::RSAPublicKey;\n\n\n\nconst KEY_DATA: [u8; 140] = [\n\n 48, 129, 137, 2, 129, 129, 0, 153, 165, 220, 135, 89, 101, 254, 229, 28, 33, 138, 247, 20, 102,\n\n 253, 217, 247, 246, 142, 107, 51, 40, 179, 149, 45, 117, 254, 236, 161, 109, 16, 81, 135, 72,\n\n 112, 132, 150, 175, 128, 173, 182, 122, 227, 214, 196, 130, 54, 239, 93, 5, 203, 185, 233, 61,\n\n 159, 156, 7, 161, 87, 48, 234, 105, 161, 108, 215, 211, 150, 168, 156, 212, 6, 63, 81, 24, 101,\n\n 72, 160, 97, 243, 142, 86, 10, 160, 122, 8, 228, 178, 252, 35, 209, 222, 228, 16, 143, 99, 143,\n\n 146, 241, 186, 187, 22, 209, 86, 141, 24, 159, 12, 146, 44, 111, 254, 183, 54, 229, 109, 28,\n\n 39, 22, 141, 173, 85, 26, 58, 9, 128, 27, 57, 131, 2, 3, 1, 0, 1,\n\n];\n\n\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/import_key.rs", "rank": 61, "score": 9.775209344816409 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::operations::psa_algorithm::*;\n\nuse parsec_client::core::interface::operations::psa_key_attributes::*;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse parsec_client::core::interface::requests::Result;\n\nuse sha2::{Digest, Sha256};\n\n\n\nconst HASH: [u8; 32] = [\n\n 0x69, 0x3E, 0xDB, 0x1B, 0x22, 0x79, 0x03, 0xF4, 0xC0, 0xBF, 0xD6, 0x91, 0x76, 0x37, 0x84, 0xA2,\n\n 0x94, 0x8E, 0x92, 0x50, 0x35, 0xC2, 0x8C, 0x5C, 0x3C, 0xCA, 0xFE, 0x18, 0xE8, 0x81, 0x37, 0x78,\n\n];\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/asym_sign_verify.rs", "rank": 62, "score": 8.395727642300528 }, { "content": " ciphertext: Vec<u8>,\n\n ) -> Result<Vec<u8>> {\n\n self.asymmetric_decrypt_message(\n\n key_name,\n\n AsymmetricEncryption::RsaPkcs1v15Crypt,\n\n &ciphertext,\n\n None,\n\n )\n\n }\n\n\n\n pub fn asymmetric_encrypt_message(\n\n &mut self,\n\n key_name: String,\n\n encryption_alg: AsymmetricEncryption,\n\n plaintext: &[u8],\n\n salt: Option<&[u8]>,\n\n ) -> Result<Vec<u8>> {\n\n self.basic_client\n\n .psa_asymmetric_encrypt(key_name, encryption_alg, &plaintext, salt)\n\n .map_err(convert_error)\n", "file_path": "e2e_tests/src/lib.rs", "rank": 63, "score": 8.162318015861086 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::requests::{Opcode, ProviderID, Result};\n\nuse std::collections::HashSet;\n\nuse uuid::Uuid;\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/all_providers/mod.rs", "rank": 65, "score": 7.789162966436378 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse parsec_client::core::interface::requests::Result;\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/auth.rs", "rank": 66, "score": 7.73084655817463 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse super::{utils, KeyInfo, KeyPairType, LocalIdStore, Pkcs11Provider, ReadWriteSession, Session};\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::key_info_managers::KeyTriple;\n\nuse crate::key_info_managers::{self, ManageKeyInfo};\n\nuse log::{error, info, trace, warn};\n\nuse parsec_interface::operations::psa_key_attributes::*;\n\nuse parsec_interface::operations::{\n\n psa_destroy_key, psa_export_public_key, psa_generate_key, psa_import_key,\n\n};\n\nuse parsec_interface::requests::{ProviderID, ResponseStatus, Result};\n\nuse parsec_interface::secrecy::ExposeSecret;\n\nuse picky_asn1::wrapper::IntegerAsn1;\n\nuse picky_asn1_x509::RSAPublicKey;\n\nuse pkcs11::types::{CKR_OK, CK_ATTRIBUTE, CK_MECHANISM, CK_OBJECT_HANDLE, CK_SESSION_HANDLE};\n\nuse std::mem;\n\n\n\n// Public exponent value for all RSA keys.\n\nconst PUBLIC_EXPONENT: [u8; 3] = [0x01, 0x00, 0x01];\n\n\n\n/// Gets a key identifier and key attributes from the Key Info Manager.\n", "file_path": "src/providers/pkcs11_provider/key_management.rs", "rank": 67, "score": 7.729744728734412 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\n// These functions test for the service persistency to shutdown. They will be executed after the\n\n// service is shutdown, after the persistent_before tests are executed.\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::requests::Result;\n\nuse parsec_client::core::interface::requests::{ProviderID, ResponseStatus};\n\n\n\nconst HASH: [u8; 32] = [\n\n 0x69, 0x3E, 0xDB, 0x1B, 0x22, 0x79, 0x03, 0xF4, 0xC0, 0xBF, 0xD6, 0x91, 0x76, 0x37, 0x84, 0xA2,\n\n 0x94, 0x8E, 0x92, 0x50, 0x35, 0xC2, 0x8C, 0x5C, 0x3C, 0xCA, 0xFE, 0x18, 0xE8, 0x81, 0x37, 0x78,\n\n];\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/persistent_after.rs", "rank": 68, "score": 7.7294744364045265 }, { "content": " trivial_casts,\n\n trivial_numeric_casts,\n\n unused_extern_crates,\n\n unused_import_braces,\n\n unused_qualifications,\n\n unused_results,\n\n missing_copy_implementations\n\n)]\n\n// This one is hard to avoid.\n\n#![allow(clippy::multiple_crate_versions)]\n\n\n\nuse parsec_client::auth::AuthenticationData;\n\nuse parsec_client::core::interface::operations::psa_algorithm::*;\n\nuse parsec_client::core::interface::operations::psa_key_attributes::*;\n\nuse parsec_client::core::interface::operations::*;\n\nuse parsec_client::core::interface::requests::ProviderID;\n\nuse parsec_client::core::ipc_handler::{Connect, ReadWrite};\n\nuse parsec_client::core::operation_client::OperationClient;\n\nuse parsec_client::error::Result;\n\nuse std::path::PathBuf;\n\nuse std::time::Duration;\n\n\n", "file_path": "fuzz/build.rs", "rank": 69, "score": 7.700168918456231 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse super::{key_management, MbedProvider};\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::key_info_managers::KeyTriple;\n\nuse parsec_interface::operations::{psa_sign_hash, psa_verify_hash};\n\nuse parsec_interface::requests::{ProviderID, ResponseStatus, Result};\n\nuse psa_crypto::operations::asym_signature;\n\nuse psa_crypto::types::key;\n\n\n\nimpl MbedProvider {\n\n pub(super) fn psa_sign_hash_internal(\n\n &self,\n\n app_name: ApplicationName,\n\n op: psa_sign_hash::Operation,\n\n ) -> Result<psa_sign_hash::Result> {\n\n let key_name = op.key_name;\n\n let hash = op.hash;\n\n let alg = op.alg;\n\n let key_triple = KeyTriple::new(app_name, ProviderID::MbedCrypto, key_name);\n", "file_path": "src/providers/mbed_provider/asym_sign.rs", "rank": 70, "score": 7.679610809448935 }, { "content": " signature: Vec<u8>,\n\n ) -> Result<()> {\n\n self.basic_client\n\n .psa_verify_hash(key_name, &hash, alg, &signature)\n\n .map_err(convert_error)\n\n }\n\n\n\n /// Verifies a signature made with an RSA key.\n\n pub fn verify_with_rsa_sha256(\n\n &mut self,\n\n key_name: String,\n\n hash: Vec<u8>,\n\n signature: Vec<u8>,\n\n ) -> Result<()> {\n\n self.verify(\n\n key_name,\n\n AsymmetricSignature::RsaPkcs1v15Sign {\n\n hash_alg: Hash::Sha256.into(),\n\n },\n\n hash,\n", "file_path": "e2e_tests/src/lib.rs", "rank": 71, "score": 7.663365502926434 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse parsec_client::core::interface::requests::Result;\n\nuse picky_asn1_x509::RSAPublicKey;\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/create_destroy_key.rs", "rank": 72, "score": 7.646051900508676 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! Convert requests to calls to the underlying provider\n\n//!\n\n//! The backend handler embodies the last processing step from external request\n\n//! to internal function call - parsing of the request body and conversion to a\n\n//! native operation which is then passed to the provider.\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::providers::Provide;\n\nuse derivative::Derivative;\n\nuse log::trace;\n\nuse parsec_interface::operations::Convert;\n\nuse parsec_interface::operations::{NativeOperation, NativeResult};\n\nuse parsec_interface::requests::{\n\n request::RequestHeader, Request, Response, ResponseStatus, Result,\n\n};\n\nuse parsec_interface::requests::{BodyType, ProviderID};\n\nuse std::io::{Error, ErrorKind};\n\n\n\n/// Back end handler component\n", "file_path": "src/back/backend_handler.rs", "rank": 73, "score": 7.6327462870711695 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse super::{key_management, utils, TpmProvider};\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::key_info_managers::KeyTriple;\n\nuse log::error;\n\nuse parsec_interface::operations::psa_algorithm::*;\n\nuse parsec_interface::operations::{psa_sign_hash, psa_verify_hash};\n\nuse parsec_interface::requests::{ProviderID, ResponseStatus, Result};\n\n\n\nimpl TpmProvider {\n\n pub(super) fn psa_sign_hash_internal(\n\n &self,\n\n app_name: ApplicationName,\n\n op: psa_sign_hash::Operation,\n\n ) -> Result<psa_sign_hash::Result> {\n\n let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, op.key_name.clone());\n\n\n\n let store_handle = self.key_info_store.read().expect(\"Key store lock poisoned\");\n\n let mut esapi_context = self\n", "file_path": "src/providers/tpm_provider/asym_sign.rs", "rank": 74, "score": 7.596973576151526 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse super::{key_management, MbedProvider};\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::key_info_managers::KeyTriple;\n\nuse parsec_interface::operations::{psa_asymmetric_decrypt, psa_asymmetric_encrypt};\n\nuse parsec_interface::requests::{ProviderID, ResponseStatus, Result};\n\nuse psa_crypto::operations::asym_encryption;\n\nuse psa_crypto::types::key;\n\n\n\nimpl MbedProvider {\n\n pub(super) fn psa_asymmetric_encrypt_internal(\n\n &self,\n\n app_name: ApplicationName,\n\n op: psa_asymmetric_encrypt::Operation,\n\n ) -> Result<psa_asymmetric_encrypt::Result> {\n\n let key_name = op.key_name.clone();\n\n\n\n let key_triple = KeyTriple::new(app_name, ProviderID::MbedCrypto, key_name);\n\n let store_handle = self.key_info_store.read().expect(\"Key store lock poisoned\");\n", "file_path": "src/providers/mbed_provider/asym_encryption.rs", "rank": 75, "score": 7.556370489209797 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\n// These functions test for the service persistency to shutdown. They will be executed before the\n\n// service is shutdown and before the persistent_after tests are executed.\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::requests::Result;\n\n\n\nconst HASH: [u8; 32] = [\n\n 0x69, 0x3E, 0xDB, 0x1B, 0x22, 0x79, 0x03, 0xF4, 0xC0, 0xBF, 0xD6, 0x91, 0x76, 0x37, 0x84, 0xA2,\n\n 0x94, 0x8E, 0x92, 0x50, 0x35, 0xC2, 0x8C, 0x5C, 0x3C, 0xCA, 0xFE, 0x18, 0xE8, 0x81, 0x37, 0x78,\n\n];\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/persistent_before.rs", "rank": 76, "score": 7.554373207310756 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! Direct authenticator\n\n//!\n\n//! The `DirectAuthenticator` implements the [direct authentication](https://parallaxsecond.github.io/parsec-book/parsec_service/system_architecture.html#authentication-tokens)\n\n//! functionality set out in the system architecture. As such, it attempts to parse the request\n\n//! authentication field into an UTF-8 string and returns the result as an application name.\n\n//! This authenticator does not offer any security value and should only be used in environments\n\n//! where all the clients and the service are mutually trustworthy.\n\n\n\nuse super::ApplicationName;\n\nuse super::Authenticate;\n\nuse crate::front::listener::ConnectionMetadata;\n\nuse log::error;\n\nuse parsec_interface::requests::request::RequestAuth;\n\nuse parsec_interface::requests::{ResponseStatus, Result};\n\nuse parsec_interface::secrecy::ExposeSecret;\n\nuse std::str;\n\n\n\n#[derive(Copy, Clone, Debug)]\n", "file_path": "src/authenticators/direct_authenticator/mod.rs", "rank": 77, "score": 7.483834952438413 }, { "content": "use crate::providers::tpm_provider::TpmProviderBuilder;\n\n#[cfg(any(\n\n feature = \"mbed-crypto-provider\",\n\n feature = \"pkcs11-provider\",\n\n feature = \"tpm-provider\"\n\n))]\n\nuse log::info;\n\n\n\nconst WIRE_PROTOCOL_VERSION_MINOR: u8 = 0;\n\nconst WIRE_PROTOCOL_VERSION_MAJOR: u8 = 1;\n\n\n\n/// Default value for the limit on the request body size (in bytes) - equal to 1MB\n\nconst DEFAULT_BODY_LEN_LIMIT: usize = 1 << 19;\n\n\n", "file_path": "src/utils/service_builder.rs", "rank": 78, "score": 7.459375545546678 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::operations::psa_algorithm::*;\n\nuse parsec_client::core::interface::operations::psa_key_attributes::*;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse parsec_client::core::interface::requests::Result;\n\nuse picky_asn1_x509::RSAPublicKey;\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/export_public_key.rs", "rank": 79, "score": 7.39763588874194 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n\n\nuse log::error;\n\nuse parsec_interface::operations::psa_algorithm::*;\n\nuse parsec_interface::operations::psa_key_attributes::*;\n\nuse parsec_interface::requests::{ResponseStatus, Result};\n\nuse picky_asn1::wrapper::IntegerAsn1;\n\nuse picky_asn1_x509::RSAPublicKey;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::convert::TryInto;\n\nuse tss_esapi::abstraction::transient::KeyParams;\n\nuse tss_esapi::response_code::{Error, Tss2ResponseCodeKind};\n\nuse tss_esapi::utils::algorithm_specifiers::{EllipticCurve, HashingAlgorithm};\n\nuse tss_esapi::utils::{AsymSchemeUnion, PublicKey, Signature, SignatureData, TpmsContext};\n\nuse zeroize::Zeroizing;\n\nconst PUBLIC_EXPONENT: [u8; 3] = [0x01, 0x00, 0x01];\n\n\n\n/// Convert the TSS library specific error values to ResponseStatus values that are returned on\n\n/// the wire protocol\n\n///\n\n/// Most of them are PsaErrorCommunicationFailure as, in the general case, the calls to the TSS\n\n/// library should suceed with the values crafted by the provider.\n\n/// If an error happens in the TSS library, it means that it was badly used by the provider or that\n\n/// it failed in an unexpected way and hence the PsaErrorCommunicationFailure error.\n\n/// The errors translated to response status are related with signature verification failure, lack\n\n/// of memory, hardware failure, corruption detection, lack of entropy and unsupported operations.\n", "file_path": "src/providers/tpm_provider/utils.rs", "rank": 80, "score": 7.377020501554425 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse e2e_tests::RequestClient;\n\nuse e2e_tests::TestClient;\n\nuse parsec_client::core::interface::requests::request::{Request, RequestAuth, RequestBody};\n\nuse parsec_client::core::interface::requests::Opcode;\n\nuse parsec_client::core::interface::requests::ProviderID;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse parsec_client::core::interface::requests::Result;\n\n\n\n#[test]\n", "file_path": "e2e_tests/tests/per_provider/normal_tests/ping.rs", "rank": 81, "score": 7.296854823799098 }, { "content": " }\n\n\n\n pub fn asymmetric_decrypt_message(\n\n &mut self,\n\n key_name: String,\n\n encryption_alg: AsymmetricEncryption,\n\n ciphertext: &[u8],\n\n salt: Option<&[u8]>,\n\n ) -> Result<Vec<u8>> {\n\n self.basic_client\n\n .psa_asymmetric_decrypt(key_name, encryption_alg, &ciphertext, salt)\n\n .map_err(convert_error)\n\n }\n\n\n\n /// Lists the provider available for the Parsec service.\n\n pub fn list_providers(&mut self) -> Result<Vec<ProviderInfo>> {\n\n self.basic_client.list_providers().map_err(convert_error)\n\n }\n\n\n\n /// Lists the opcodes available for one provider to execute.\n", "file_path": "e2e_tests/src/lib.rs", "rank": 82, "score": 7.2588839008558725 }, { "content": " },\n\n permitted_algorithms: AsymmetricEncryption::RsaPkcs1v15Crypt.into(),\n\n },\n\n },\n\n data,\n\n )\n\n }\n\n\n\n /// Import a 1024 bit RSA public key.\n\n /// The key can only be used for verifying with the RSA PKCS 1v15 signing algorithm with SHA-256.\n\n pub fn import_rsa_public_key(&mut self, key_name: String, data: Vec<u8>) -> Result<()> {\n\n self.import_key(\n\n key_name,\n\n Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaPublicKey,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n", "file_path": "e2e_tests/src/lib.rs", "rank": 83, "score": 7.224806395946839 }, { "content": " pub fn list_opcodes(&mut self, provider_id: ProviderID) -> Result<HashSet<Opcode>> {\n\n self.basic_client\n\n .list_opcodes(provider_id)\n\n .map_err(convert_error)\n\n }\n\n\n\n /// Executes a ping operation.\n\n pub fn ping(&mut self) -> Result<(u8, u8)> {\n\n self.basic_client.ping().map_err(convert_error)\n\n }\n\n}\n\n\n\nimpl Default for TestClient {\n\n fn default() -> Self {\n\n TestClient::new()\n\n }\n\n}\n\n\n\nimpl Drop for TestClient {\n\n fn drop(&mut self) {\n", "file_path": "e2e_tests/src/lib.rs", "rank": 84, "score": 7.03740701261658 }, { "content": "\n\n /// Exports a key\n\n pub fn export_key(&mut self, key_name: String) -> Result<Vec<u8>> {\n\n self.basic_client\n\n .psa_export_key(key_name)\n\n .map_err(convert_error)\n\n }\n\n\n\n /// Exports a public key.\n\n pub fn export_public_key(&mut self, key_name: String) -> Result<Vec<u8>> {\n\n self.basic_client\n\n .psa_export_public_key(key_name)\n\n .map_err(convert_error)\n\n }\n\n\n\n /// Destroys a key.\n\n pub fn destroy_key(&mut self, key_name: String) -> Result<()> {\n\n self.basic_client\n\n .psa_destroy_key(key_name.clone())\n\n .map_err(convert_error)?;\n", "file_path": "e2e_tests/src/lib.rs", "rank": 85, "score": 7.024934475764435 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! Service front using Unix domain sockets\n\n//!\n\n//! Expose Parsec functionality using Unix domain sockets as an IPC layer.\n\n//! The local socket is created at a predefined location.\n\nuse super::listener;\n\nuse listener::Connection;\n\nuse listener::Listen;\n\nuse log::error;\n\nuse std::fs;\n\nuse std::fs::Permissions;\n\nuse std::io::{Error, ErrorKind, Result};\n\nuse std::os::unix::fs::PermissionsExt;\n\nuse std::os::unix::io::FromRawFd;\n\nuse std::os::unix::net::UnixListener;\n\nuse std::path::Path;\n\nuse std::time::Duration;\n\n\n\nstatic SOCKET_PATH: &str = \"/tmp/parsec/parsec.sock\";\n", "file_path": "src/front/domain_socket.rs", "rank": 86, "score": 6.985266224302107 }, { "content": "};\n\nuse parsec_client::core::interface::requests::{Opcode, ProviderID, ResponseStatus, Result};\n\nuse parsec_client::core::secrecy::{ExposeSecret, Secret};\n\nuse parsec_client::error::Error;\n\nuse std::collections::HashSet;\n\nuse std::time::Duration;\n\n\n\n/// Client structure automatically choosing a provider and high-level operation functions.\n\n#[derive(Debug)]\n\npub struct TestClient {\n\n basic_client: BasicClient,\n\n created_keys: Option<HashSet<(String, String, ProviderID)>>,\n\n}\n\n\n", "file_path": "e2e_tests/src/lib.rs", "rank": 87, "score": 6.867332522592077 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! Entry point for IPC data into the service\n\n//!\n\n//! The front end handler accepts streams of data that it can use to read requests,\n\n//! pass them to the rest of the service and write the responses back.\n\nuse crate::authenticators::Authenticate;\n\nuse crate::back::dispatcher::Dispatcher;\n\nuse crate::front::listener::Connection;\n\nuse derivative::Derivative;\n\nuse log::{info, trace};\n\nuse parsec_interface::requests::AuthType;\n\nuse parsec_interface::requests::ResponseStatus;\n\nuse parsec_interface::requests::{Request, Response};\n\nuse std::collections::HashMap;\n\nuse std::io::{Error, ErrorKind, Result};\n\n\n\n/// Read and verify request from IPC stream\n\n///\n\n/// Service component that serializes requests and deserializes responses\n", "file_path": "src/front/front_end.rs", "rank": 88, "score": 6.83333448619155 }, { "content": "/// Service information provider\n\n///\n\n/// The core provider is a non-cryptographic provider tasked with offering\n\n/// structured information about the status of the service and the providers\n\n/// available.\n\n#[derive(Debug)]\n\npub struct CoreProvider {\n\n wire_protocol_version_min: u8,\n\n wire_protocol_version_maj: u8,\n\n provider_info: Vec<ProviderInfo>,\n\n provider_opcodes: HashMap<ProviderID, HashSet<Opcode>>,\n\n}\n\n\n\nimpl Provide for CoreProvider {\n\n fn list_opcodes(&self, op: list_opcodes::Operation) -> Result<list_opcodes::Result> {\n\n trace!(\"list_opcodes ingress\");\n\n Ok(list_opcodes::Result {\n\n opcodes: self\n\n .provider_opcodes\n\n .get(&op.provider_id)\n", "file_path": "src/providers/core_provider/mod.rs", "rank": 89, "score": 6.8328368490502 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse super::Pkcs11Provider;\n\nuse super::{key_management::get_key_info, utils, KeyPairType, ReadWriteSession, Session};\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::key_info_managers::KeyTriple;\n\nuse log::{error, info, trace};\n\nuse parsec_interface::operations::psa_algorithm::*;\n\nuse parsec_interface::operations::{psa_sign_hash, psa_verify_hash};\n\nuse parsec_interface::requests::{ProviderID, ResponseStatus, Result};\n\nuse picky::AlgorithmIdentifier;\n\nuse picky_asn1::wrapper::OctetStringAsn1;\n\nuse picky_asn1_x509::SHAVariant;\n\nuse pkcs11::types::CK_MECHANISM;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Serialize, Deserialize)]\n", "file_path": "src/providers/pkcs11_provider/asym_sign.rs", "rank": 90, "score": 6.829903952548751 }, { "content": " signature,\n\n )\n\n }\n\n\n\n pub fn asymmetric_encrypt_message_with_rsapkcs1v15(\n\n &mut self,\n\n key_name: String,\n\n plaintext: Vec<u8>,\n\n ) -> Result<Vec<u8>> {\n\n self.asymmetric_encrypt_message(\n\n key_name,\n\n AsymmetricEncryption::RsaPkcs1v15Crypt,\n\n &plaintext,\n\n None,\n\n )\n\n }\n\n\n\n pub fn asymmetric_decrypt_message_with_rsapkcs1v15(\n\n &mut self,\n\n key_name: String,\n", "file_path": "e2e_tests/src/lib.rs", "rank": 91, "score": 6.806665532389877 }, { "content": "// Copyright 2020 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\nuse super::TestClient;\n\nuse log::info;\n\nuse parsec_client::core::interface::requests::ResponseStatus;\n\nuse rand::Rng;\n\nuse rand::{\n\n distributions::{Alphanumeric, Distribution, Standard},\n\n thread_rng,\n\n};\n\nuse std::convert::TryInto;\n\nuse std::iter;\n\nuse std::sync::mpsc::{channel, Receiver};\n\nuse std::thread;\n\nuse std::time::Duration;\n\n\n\nconst HASH: [u8; 32] = [\n\n 0x69, 0x3E, 0xDB, 0x1B, 0x22, 0x79, 0x03, 0xF4, 0xC0, 0xBF, 0xD6, 0x91, 0x76, 0x37, 0x84, 0xA2,\n\n 0x94, 0x8E, 0x92, 0x50, 0x35, 0xC2, 0x8C, 0x5C, 0x3C, 0xCA, 0xFE, 0x18, 0xE8, 0x81, 0x37, 0x78,\n\n];\n", "file_path": "e2e_tests/src/stress.rs", "rank": 92, "score": 6.804770208575811 }, { "content": " /// The key pair can only be used for encryption and decryption with RSA PKCS 1v15\n\n pub fn import_rsa_key_pair_for_encryption(&mut self, key_name: String, data: Vec<u8>) -> Result<()> {\n\n self.import_key(\n\n key_name,\n\n Attributes {\n\n lifetime: Lifetime::Persistent,\n\n key_type: Type::RsaKeyPair,\n\n bits: 1024,\n\n policy: Policy {\n\n usage_flags: UsageFlags {\n\n sign_hash: false,\n\n verify_hash: false,\n\n sign_message: false,\n\n verify_message: true,\n\n export: true,\n\n encrypt: true,\n\n decrypt: true,\n\n cache: false,\n\n copy: false,\n\n derive: false,\n", "file_path": "e2e_tests/src/lib.rs", "rank": 93, "score": 6.797721815057066 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! Dispatch requests to the correct backend\n\n//!\n\n//! The dispatcher's role is to direct requests to the provider they specify, if\n\n//! said provider is available on the system, thus acting as a multiplexer.\n\nuse super::backend_handler::BackEndHandler;\n\nuse crate::authenticators::ApplicationName;\n\nuse log::trace;\n\nuse parsec_interface::requests::request::Request;\n\nuse parsec_interface::requests::ProviderID;\n\nuse parsec_interface::requests::{Response, ResponseStatus};\n\nuse std::collections::HashMap;\n\nuse std::io::{Error, ErrorKind, Result};\n\n\n\n/// Dispatcher to backend\n\n///\n\n/// Component tasked with identifying the backend handler that can\n\n/// service a request.\n\n///\n", "file_path": "src/back/dispatcher.rs", "rank": 94, "score": 6.756483015122083 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! TPM 2.0 provider\n\n//!\n\n//! Provider allowing clients to use hardware or software TPM 2.0 implementations\n\n//! for their Parsec operations.\n\nuse super::Provide;\n\nuse crate::authenticators::ApplicationName;\n\nuse crate::key_info_managers::ManageKeyInfo;\n\nuse derivative::Derivative;\n\nuse log::{info, trace};\n\nuse parsec_interface::operations::list_providers::ProviderInfo;\n\nuse parsec_interface::operations::{\n\n psa_destroy_key, psa_export_public_key, psa_generate_key, psa_import_key, psa_sign_hash,\n\n psa_verify_hash,\n\n};\n\nuse parsec_interface::requests::{Opcode, ProviderID, ResponseStatus, Result};\n\nuse std::collections::HashSet;\n\nuse std::io::ErrorKind;\n\nuse std::str::FromStr;\n", "file_path": "src/providers/tpm_provider/mod.rs", "rank": 95, "score": 6.7537180939406785 }, { "content": " .map_err(convert_error)\n\n }\n\n\n\n /// Signs a short digest with an RSA key.\n\n pub fn sign_with_rsa_sha256(&mut self, key_name: String, hash: Vec<u8>) -> Result<Vec<u8>> {\n\n self.sign(\n\n key_name,\n\n AsymmetricSignature::RsaPkcs1v15Sign {\n\n hash_alg: Hash::Sha256.into(),\n\n },\n\n hash,\n\n )\n\n }\n\n\n\n /// Verifies a signature.\n\n pub fn verify(\n\n &mut self,\n\n key_name: String,\n\n alg: AsymmetricSignature,\n\n hash: Vec<u8>,\n", "file_path": "e2e_tests/src/lib.rs", "rank": 96, "score": 6.734932187043894 }, { "content": "// Copyright 2019 Contributors to the Parsec project.\n\n// SPDX-License-Identifier: Apache-2.0\n\n//! Core information source for the service\n\n//!\n\n//! The core provider acts as a source of information for the Parsec service,\n\n//! aiding clients in discovering the capabilities offered by their underlying\n\n//! platform.\n\nuse super::Provide;\n\nuse log::trace;\n\nuse parsec_interface::operations::list_providers::ProviderInfo;\n\nuse parsec_interface::operations::{list_opcodes, list_providers, ping};\n\nuse parsec_interface::requests::{Opcode, ProviderID, ResponseStatus, Result};\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::io::{Error, ErrorKind};\n\nuse std::str::FromStr;\n\nuse uuid::Uuid;\n\nuse version::{version, Version};\n\n\n\nconst SUPPORTED_OPCODES: [Opcode; 3] = [Opcode::ListProviders, Opcode::ListOpcodes, Opcode::Ping];\n\n\n", "file_path": "src/providers/core_provider/mod.rs", "rank": 97, "score": 6.680874039808969 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl ManageKeyInfo for OnDiskKeyInfoManager {\n\n fn get(&self, key_triple: &KeyTriple) -> Result<Option<&KeyInfo>, String> {\n\n // An Option<&Vec<u8>> can not automatically coerce to an Option<&[u8]>, it needs to be\n\n // done by hand.\n\n if let Some(key_info) = self.key_store.get(key_triple) {\n\n Ok(Some(key_info))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n\n\n fn get_all(&self, provider_id: ProviderID) -> Result<Vec<&KeyTriple>, String> {\n\n Ok(self\n\n .key_store\n\n .keys()\n\n .filter(|key_triple| key_triple.belongs_to_provider(provider_id))\n", "file_path": "src/key_info_managers/on_disk_manager/mod.rs", "rank": 98, "score": 6.618731399312898 }, { "content": "use crate::key_info_managers::{KeyInfoManagerConfig, KeyInfoManagerType, ManageKeyInfo};\n\nuse crate::providers::{core_provider::CoreProviderBuilder, Provide, ProviderConfig};\n\nuse log::{error, warn, LevelFilter};\n\nuse parsec_interface::operations_protobuf::ProtobufConverter;\n\nuse parsec_interface::requests::AuthType;\n\nuse parsec_interface::requests::{BodyType, ProviderID};\n\nuse serde::Deserialize;\n\nuse std::collections::HashMap;\n\nuse std::io::{Error, ErrorKind, Result};\n\nuse std::path::PathBuf;\n\nuse std::sync::Arc;\n\nuse std::sync::RwLock;\n\nuse std::time::Duration;\n\nuse threadpool::{Builder as ThreadPoolBuilder, ThreadPool};\n\n\n\n#[cfg(feature = \"mbed-crypto-provider\")]\n\nuse crate::providers::mbed_provider::MbedProviderBuilder;\n\n#[cfg(feature = \"pkcs11-provider\")]\n\nuse crate::providers::pkcs11_provider::Pkcs11ProviderBuilder;\n\n#[cfg(feature = \"tpm-provider\")]\n", "file_path": "src/utils/service_builder.rs", "rank": 99, "score": 6.572306937376255 } ]
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}\n\n\n", "file_path": "src/instruction.rs", "rank": 1, "score": 252625.2478533912 }, { "content": "pub fn format_qubits(qubits: &[Qubit]) -> String {\n\n qubits\n\n .iter()\n\n .map(|q| format!(\"{}\", q))\n\n .collect::<Vec<String>>()\n\n .join(\" \")\n\n}\n\n\n", "file_path": "src/instruction.rs", "rank": 3, "score": 245316.60320877202 }, { "content": "pub fn get_string_parameter_string(parameters: &[String]) -> String {\n\n if parameters.is_empty() {\n\n return String::from(\"\");\n\n }\n\n\n\n let parameter_str: String = parameters.join(\",\");\n\n format!(\"({})\", parameter_str)\n\n}\n\n\n\nimpl fmt::Display for Instruction {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Instruction::Arithmetic(Arithmetic {\n\n operator,\n\n destination,\n\n source,\n\n }) => write!(f, \"{} {} {}\", operator, destination, source),\n\n Instruction::CalibrationDefinition(calibration) => {\n\n let parameter_str = get_expression_parameter_string(&calibration.parameters);\n\n write!(\n", "file_path": "src/instruction.rs", "rank": 5, "score": 230465.90627353737 }, { "content": "pub fn format_integer_vector(values: &[u64]) -> String {\n\n values\n\n .iter()\n\n .map(|q| format!(\"{}\", q))\n\n .collect::<Vec<String>>()\n\n .join(\" \")\n\n}\n\n\n", "file_path": "src/instruction.rs", "rank": 6, "score": 229674.82582785876 }, { "content": "pub fn format_instructions(values: &[Instruction]) -> String {\n\n values\n\n .iter()\n\n .map(|i| format!(\"{}\", i))\n\n .collect::<Vec<String>>()\n\n .join(\"\\n\\t\")\n\n}\n\n\n", "file_path": "src/instruction.rs", "rank": 8, "score": 218597.86575634027 }, { "content": "/// Parse an expression at the head of the current input, for as long as the expression continues.\n\n/// Return an error only if the first token(s) do not form an expression.\n\npub fn parse_expression(input: ParserInput) -> ParserResult<Expression> {\n\n parse(input, Precedence::Lowest)\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 9, "score": 218350.330620525 }, { "content": "/// Parse the next instructon from the input, skipping past leading newlines, comments, and semicolons.\n\npub fn parse_instruction(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, _) = common::skip_newlines_and_comments(input)?;\n\n match input.split_first() {\n\n None => Err(nom::Err::Error(Error {\n\n input,\n\n error: ErrorKind::EndOfInput,\n\n })),\n\n Some((Token::Command(command), remainder)) => {\n\n match command {\n\n Command::Add => command::parse_arithmetic(ArithmeticOperator::Add, remainder),\n\n // Command::And => {}\n\n Command::Capture => command::parse_capture(remainder, true),\n\n // Command::Convert => {}\n\n Command::Declare => command::parse_declare(remainder),\n\n Command::DefCal => command::parse_defcal(remainder),\n\n Command::DefCircuit => command::parse_defcircuit(remainder),\n\n Command::DefFrame => command::parse_defframe(remainder),\n\n // Command::DefGate => Ok((remainder, cut(parse_command_defgate))),\n\n Command::DefWaveform => command::parse_defwaveform(remainder),\n\n Command::Delay => command::parse_delay(remainder),\n", "file_path": "src/parser/instruction.rs", "rank": 10, "score": 217112.99379602546 }, { "content": "/// Parse the contents of a `JUMP-UNLESS` instruction.\n\npub fn parse_jump_unless<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, target) = token!(Label(v))(input)?;\n\n let (input, condition) = common::parse_memory_reference(input)?;\n\n Ok((\n\n input,\n\n Instruction::JumpUnless(JumpUnless { target, condition }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 11, "score": 216241.06820552133 }, { "content": "/// Parse all instructions from the input, trimming leading and trailing newlines and comments.\n\n/// Returns an error if it does not reach the end of input.\n\npub fn parse_instructions(input: ParserInput) -> ParserResult<Vec<Instruction>> {\n\n all_consuming(delimited(\n\n common::skip_newlines_and_comments,\n\n many0(parse_instruction),\n\n common::skip_newlines_and_comments,\n\n ))(input)\n\n}\n\n\n", "file_path": "src/parser/instruction.rs", "rank": 12, "score": 210898.18525897223 }, { "content": "/// Parse a block of indented \"block instructions.\"\n\npub fn parse_block(input: ParserInput) -> ParserResult<Vec<Instruction>> {\n\n many1(parse_block_instruction)(input)\n\n}\n\n\n", "file_path": "src/parser/instruction.rs", "rank": 13, "score": 205922.23005468957 }, { "content": "/// Parse a single indented \"block instruction.\"\n\npub fn parse_block_instruction<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n preceded(\n\n token!(NewLine),\n\n preceded(token!(Indentation), parse_instruction),\n\n )(input)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::HashMap;\n\n\n\n use crate::instruction::{\n\n Label, Reset, SetFrequency, SetPhase, SetScale, ShiftFrequency, ShiftPhase,\n\n };\n\n use crate::parser::lexer::lex;\n\n use crate::{\n\n expression::Expression,\n\n instruction::{\n\n Arithmetic, ArithmeticOperand, ArithmeticOperator, AttributeValue, Calibration,\n\n Capture, FrameDefinition, FrameIdentifier, Gate, Instruction, Jump, JumpWhen,\n", "file_path": "src/parser/instruction.rs", "rank": 14, "score": 204648.79278961703 }, { "content": "/// Parse the contents of a `MEASURE` instruction.\n\npub fn parse_measurement(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, qubit) = parse_qubit(input)?;\n\n let (input, target) = match parse_memory_reference(input) {\n\n Ok((input, target)) => (input, Some(target)),\n\n Err(_) => (input, None),\n\n };\n\n\n\n Ok((\n\n input,\n\n Instruction::Measurement(Measurement { qubit, target }),\n\n ))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::expression::Expression;\n\n use crate::parser::lexer::lex;\n\n use crate::{\n\n instruction::{\n\n CircuitDefinition, Declaration, Gate, Instruction, Measurement, MemoryReference,\n", "file_path": "src/parser/command.rs", "rank": 15, "score": 202886.88742377778 }, { "content": "/// Parse the contents of a `FENCE` instruction.\n\npub fn parse_fence(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, qubits) = many0(parse_qubit)(input)?;\n\n\n\n Ok((input, Instruction::Fence(Fence { qubits })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 16, "score": 202886.88742377778 }, { "content": "/// Parse the contents of an `EXCHANGE` instruction.\n\npub fn parse_exchange(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, left) = common::parse_memory_reference(input)?;\n\n let (input, right) = common::parse_memory_reference(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::Exchange(Exchange {\n\n left: ArithmeticOperand::MemoryReference(left),\n\n right: ArithmeticOperand::MemoryReference(right),\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 17, "score": 202886.88742377775 }, { "content": "/// Parse the contents of a `RESET` instruction.\n\npub fn parse_reset(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, qubit) = opt(parse_qubit)(input)?;\n\n\n\n Ok((input, Instruction::Reset(Reset { qubit })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 18, "score": 202886.88742377778 }, { "content": "/// Parse the contents of a `MOVE` instruction.\n\npub fn parse_move(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, destination) = common::parse_arithmetic_operand(input)?;\n\n let (input, source) = common::parse_arithmetic_operand(input)?;\n\n Ok((\n\n input,\n\n Instruction::Move(Move {\n\n destination,\n\n source,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 19, "score": 202886.88742377778 }, { "content": "/// Parse the contents of a `SHIFT-FREQUENCY` instruction.\n\npub fn parse_shift_frequency(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, frequency) = parse_expression(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::ShiftFrequency(ShiftFrequency { frame, frequency }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 20, "score": 200039.26048202632 }, { "content": "/// Parse the contents of a `SET-FREQUENCY` instruction.\n\npub fn parse_set_frequency(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, frequency) = parse_expression(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::SetFrequency(SetFrequency { frame, frequency }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 21, "score": 200039.26048202632 }, { "content": "/// Parse the contents of a `SET-SCALE` instruction.\n\npub fn parse_set_scale(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, scale) = parse_expression(input)?;\n\n\n\n Ok((input, Instruction::SetScale(SetScale { frame, scale })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 22, "score": 200039.26048202632 }, { "content": "/// Parse the contents of a `SET-PHASE` instruction.\n\npub fn parse_set_phase(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, phase) = parse_expression(input)?;\n\n\n\n Ok((input, Instruction::SetPhase(SetPhase { frame, phase })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 23, "score": 200039.26048202632 }, { "content": "/// Parse the contents of a `SHIFT-PHASE` instruction.\n\npub fn parse_shift_phase(input: ParserInput) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, phase) = parse_expression(input)?;\n\n\n\n Ok((input, Instruction::ShiftPhase(ShiftPhase { frame, phase })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 24, "score": 200039.26048202632 }, { "content": "pub fn format_matrix(matrix: &[Vec<Expression>]) -> String {\n\n matrix\n\n .iter()\n\n .map(|row| {\n\n row.iter()\n\n .map(|cell| format!(\"{}\", cell))\n\n .collect::<Vec<String>>()\n\n .join(\", \")\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\"\\n\\t\")\n\n}\n\n\n", "file_path": "src/instruction.rs", "rank": 26, "score": 197202.5926352564 }, { "content": "/// Parse a gate instruction.\n\npub fn parse_gate<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, modifiers) = many0(parse_gate_modifier)(input)?;\n\n let (input, name) = token!(Identifier(v))(input)?;\n\n let (input, parameters) = opt(delimited(\n\n token!(LParenthesis),\n\n separated_list0(token!(Comma), parse_expression),\n\n token!(RParenthesis),\n\n ))(input)?;\n\n let parameters = parameters.unwrap_or_default();\n\n let (input, qubits) = many0(common::parse_qubit)(input)?;\n\n Ok((\n\n input,\n\n Instruction::Gate(Gate {\n\n name,\n\n parameters,\n\n qubits,\n\n modifiers,\n\n }),\n\n ))\n\n}\n", "file_path": "src/parser/gate.rs", "rank": 27, "score": 193150.86640715768 }, { "content": "/// Parse the contents of a `JUMP` instruction.\n\npub fn parse_jump<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, target) = token!(Label(v))(input)?;\n\n Ok((input, Instruction::Jump(Jump { target })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 28, "score": 193150.81530856088 }, { "content": "/// Parse the contents of a `DECLARE` instruction.\n\npub fn parse_label<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, name) = token!(Label(v))(input)?;\n\n Ok((input, Instruction::Label(Label(name))))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 29, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `DELAY` instruction.\n\npub fn parse_delay<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, qubits) = many0(parse_qubit)(input)?;\n\n let (input, frame_names) = many0(token!(String(v)))(input)?;\n\n let (input, duration) = parse_expression(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::Delay(Delay {\n\n duration,\n\n frame_names,\n\n qubits,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 30, "score": 193150.81530856088 }, { "content": "/// Parse the contents of a `PRAGMA` instruction.\n\npub fn parse_pragma<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, pragma_type) = token!(Identifier(v))(input)?;\n\n // FIXME: Also allow Int (not just Identifier)\n\n let (input, arguments) = many0(token!(Identifier(v)))(input)?;\n\n let (input, data) = opt(token!(String(v)))(input)?;\n\n Ok((\n\n input,\n\n Instruction::Pragma(Pragma {\n\n name: pragma_type,\n\n arguments,\n\n data,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 31, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `LOAD` instruction.\n\npub fn parse_load<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, destination) = common::parse_memory_reference(input)?;\n\n let (input, source) = token!(Identifier(v))(input)?;\n\n let (input, offset) = common::parse_memory_reference(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::Load(Load {\n\n destination,\n\n source,\n\n offset,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 32, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `DEFFRAME` instruction.\n\npub fn parse_defframe<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, identifier) = parse_frame_identifier(input)?;\n\n let (input, _) = token!(Colon)(input)?;\n\n let (input, attribute_pairs) = many1(parse_frame_attribute)(input)?;\n\n let attributes = attribute_pairs.iter().cloned().collect();\n\n\n\n Ok((\n\n input,\n\n Instruction::FrameDefinition(FrameDefinition {\n\n identifier,\n\n attributes,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 33, "score": 193150.81530856088 }, { "content": "/// Parse the contents of a `DEFWAVEFORM` instruction.\n\npub fn parse_defwaveform<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, name) = token!(Identifier(v))(input)?;\n\n let (input, parameters) = opt(delimited(\n\n token!(LParenthesis),\n\n separated_list0(token!(Comma), token!(Variable(v))),\n\n token!(RParenthesis),\n\n ))(input)?;\n\n let parameters = parameters.unwrap_or_default();\n\n\n\n let (input, sample_rate) = alt((\n\n map_res(token!(Float(v)), |v| Ok(v) as Result<f64, Error<&[Token]>>),\n\n map_res(token!(Integer(v)), |v| {\n\n let result = v as f64;\n\n if result as u64 != v {\n\n Err(Error {\n\n input,\n\n error: ErrorKind::UnsupportedPrecision,\n\n })\n\n } else {\n\n Ok(result)\n", "file_path": "src/parser/command.rs", "rank": 34, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `STORE` instruction.\n\npub fn parse_store<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, destination) = token!(Identifier(v))(input)?;\n\n let (input, offset) = common::parse_memory_reference(input)?;\n\n let (input, source) = common::parse_arithmetic_operand(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::Store(Store {\n\n destination,\n\n offset,\n\n source,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 35, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `DEFCAL` instruction.\n\npub fn parse_defcal<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, modifiers) = many0(parse_gate_modifier)(input)?;\n\n let (input, name) = token!(Identifier(v))(input)?;\n\n let (input, parameters) = opt(delimited(\n\n token!(LParenthesis),\n\n separated_list0(token!(Comma), parse_expression),\n\n token!(RParenthesis),\n\n ))(input)?;\n\n let parameters = parameters.unwrap_or_default();\n\n let (input, qubits) = many0(parse_qubit)(input)?;\n\n let (input, _) = token!(Colon)(input)?;\n\n let (input, instructions) = instruction::parse_block(input)?;\n\n Ok((\n\n input,\n\n Instruction::CalibrationDefinition(Calibration {\n\n instructions,\n\n modifiers,\n\n name,\n\n parameters,\n\n qubits,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 36, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `DECLARE` instruction.\n\npub fn parse_declare<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, name) = token!(Identifier(v))(input)?;\n\n let (input, size) = common::parse_vector(input)?;\n\n Ok((\n\n input,\n\n Instruction::Declaration(Declaration {\n\n name,\n\n sharing: None,\n\n size,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 37, "score": 193150.8153085609 }, { "content": "/// Parse the contents of a `JUMP-WHEN` instruction.\n\npub fn parse_jump_when<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, target) = token!(Label(v))(input)?;\n\n let (input, condition) = common::parse_memory_reference(input)?;\n\n Ok((input, Instruction::JumpWhen(JumpWhen { target, condition })))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 38, "score": 193150.81530856088 }, { "content": "pub fn parse_defcircuit<'a>(input: ParserInput<'a>) -> ParserResult<'a, Instruction> {\n\n let (input, name) = token!(Identifier(v))(input)?;\n\n let (input, parameters) = opt(delimited(\n\n token!(LParenthesis),\n\n separated_list0(token!(Comma), token!(Variable(v))),\n\n token!(RParenthesis),\n\n ))(input)?;\n\n let parameters = parameters.unwrap_or_default();\n\n let (input, qubit_variables) = many0(parse_variable_qubit)(input)?;\n\n let (input, _) = token!(Colon)(input)?;\n\n let (input, instructions) = parse_block(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::CircuitDefinition(CircuitDefinition {\n\n name,\n\n parameters,\n\n qubit_variables,\n\n instructions,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 39, "score": 193147.1149856735 }, { "content": "/// Parse the contents of a `CAPTURE` instruction.\n\n///\n\n/// Unlike most other instructions, this can be _prefixed_ with the NONBLOCKING keyword,\n\n/// and thus it expects and parses the CAPTURE token itself.\n\npub fn parse_capture(input: ParserInput, blocking: bool) -> ParserResult<Instruction> {\n\n let (input, frame) = common::parse_frame_identifier(input)?;\n\n let (input, waveform) = common::parse_waveform_invocation(input)?;\n\n let (input, memory_reference) = common::parse_memory_reference(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::Capture(Capture {\n\n blocking,\n\n frame,\n\n memory_reference,\n\n waveform,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 40, "score": 190609.80911865883 }, { "content": "/// Parse the contents of a `PULSE` instruction.\n\npub fn parse_pulse(input: ParserInput, blocking: bool) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, waveform) = parse_waveform_invocation(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::Pulse(Pulse {\n\n blocking,\n\n frame,\n\n waveform,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 41, "score": 190606.01407412818 }, { "content": "/// Completely lex a string, returning the tokens within. Panics if the string cannot be completely read.\n\npub fn lex(input: &str) -> Vec<Token> {\n\n let result: Result<(&str, Vec<Token>), String> =\n\n all_consuming(_lex)(input).map_err(|err| format!(\"Error remains: {:?}\", err));\n\n result.unwrap().1\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 42, "score": 188163.70258166664 }, { "content": "/// Parse the contents of a `RAW-CAPTURE` instruction.\n\npub fn parse_raw_capture(input: ParserInput, blocking: bool) -> ParserResult<Instruction> {\n\n let (input, frame) = parse_frame_identifier(input)?;\n\n let (input, duration) = parse_expression(input)?;\n\n let (input, memory_reference) = parse_memory_reference(input)?;\n\n\n\n Ok((\n\n input,\n\n Instruction::RawCapture(RawCapture {\n\n blocking,\n\n frame,\n\n duration,\n\n memory_reference,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 43, "score": 188037.06655562227 }, { "content": "/// Identifiers have to be handled specially because some have special meaning.\n\n///\n\n/// By order of precedence:\n\n///\n\n/// 1. Memory references with brackets\n\n/// 2. Special function and constant identifiers\n\n/// 3. Anything else is considered to be a memory reference without index brackets\n\nfn parse_expression_identifier(input: ParserInput) -> ParserResult<Expression> {\n\n let (input, memory_reference) = opt(parse_memory_reference_with_brackets)(input)?;\n\n if let Some(memory_reference) = memory_reference {\n\n return Ok((input, Expression::Address(memory_reference)));\n\n }\n\n\n\n match input.split_first() {\n\n None => unexpected_eof!(input),\n\n Some((Token::Identifier(ident), remainder)) => match ident.as_str() {\n\n \"cis\" => parse_function_call(remainder, ExpressionFunction::Cis),\n\n \"cos\" => parse_function_call(remainder, ExpressionFunction::Cosine),\n\n \"exp\" => parse_function_call(remainder, ExpressionFunction::Exponent),\n\n \"i\" => Ok((remainder, Expression::Number(imag!(1f64)))),\n\n \"pi\" => Ok((remainder, Expression::PiConstant)),\n\n \"sin\" => parse_function_call(remainder, ExpressionFunction::Sine),\n\n name => Ok((\n\n remainder,\n\n Expression::Address(MemoryReference {\n\n name: name.to_owned(),\n\n index: 0,\n\n }),\n\n )),\n\n },\n\n Some((other_token, _)) => expected_token!(input, other_token, \"identifier\".to_owned()),\n\n }\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 45, "score": 175168.4496976799 }, { "content": "/// To be called following an opening parenthesis, this will parse the expression to its end\n\n/// and then expect a closing right parenthesis.\n\nfn parse_grouped_expression(input: ParserInput) -> ParserResult<Expression> {\n\n let (input, expression) = parse(input, Precedence::Lowest)?;\n\n match input.split_first() {\n\n None => unexpected_eof!(input),\n\n Some((Token::RParenthesis, remainder)) => Ok((remainder, expression)),\n\n Some((other_token, _)) => {\n\n expected_token!(input, other_token, \"right parenthesis\".to_owned())\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 46, "score": 175165.33835856663 }, { "content": "/// Returns successfully if the head of input is the identifier `i`, returns error otherwise.\n\nfn parse_i(input: ParserInput) -> ParserResult<()> {\n\n match input.split_first() {\n\n None => unexpected_eof!(input),\n\n Some((Token::Identifier(v), remainder)) if v == \"i\" => Ok((remainder, ())),\n\n Some((other_token, _)) => expected_token!(input, other_token, \"i\".to_owned()),\n\n }\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 48, "score": 170842.05329368502 }, { "content": "/// Parse an infix operator and then the expression to the right of the operator, and return the\n\n/// resulting infixed expression.\n\nfn parse_infix(input: ParserInput, left: Expression) -> ParserResult<Expression> {\n\n match input.split_first() {\n\n None => unexpected_eof!(input),\n\n Some((Token::Operator(token_operator), remainder)) => {\n\n let expression_operator = match token_operator {\n\n Operator::Plus => InfixOperator::Plus,\n\n Operator::Minus => InfixOperator::Minus,\n\n Operator::Caret => InfixOperator::Caret,\n\n Operator::Slash => InfixOperator::Slash,\n\n Operator::Star => InfixOperator::Star,\n\n };\n\n let precedence = get_precedence(remainder);\n\n let (remainder, right) = parse(remainder, precedence)?;\n\n let infix_expression = Expression::Infix {\n\n left: Box::new(left),\n\n operator: expression_operator,\n\n right: Box::new(right),\n\n };\n\n Ok((remainder, infix_expression))\n\n }\n\n Some((other_token, _)) => expected_token!(input, other_token, \"infix operator\".to_owned()),\n\n }\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 49, "score": 167484.59906640073 }, { "content": "/// Recursively parse an expression as long as operator precedence is satisfied.\n\nfn parse(input: ParserInput, precedence: Precedence) -> ParserResult<Expression> {\n\n let (input, prefix) = opt(parse_prefix)(input)?;\n\n let (mut input, mut left) = match input.split_first() {\n\n None => unexpected_eof!(input),\n\n Some((Token::Integer(value), remainder)) => {\n\n let (remainder, imaginary) = opt(parse_i)(remainder)?;\n\n match imaginary {\n\n None => Ok((remainder, Expression::Number(crate::real!(*value as f64)))),\n\n Some(_) => Ok((remainder, Expression::Number(crate::imag!(*value as f64)))),\n\n }\n\n }\n\n Some((Token::Float(value), remainder)) => {\n\n let (remainder, imaginary) = opt(parse_i)(remainder)?;\n\n match imaginary {\n\n None => Ok((remainder, Expression::Number(crate::real!(*value as f64)))),\n\n Some(_) => Ok((remainder, Expression::Number(crate::imag!(*value as f64)))),\n\n }\n\n }\n\n Some((Token::Variable(name), remainder)) => {\n\n Ok((remainder, Expression::Variable(name.clone())))\n", "file_path": "src/parser/expression.rs", "rank": 50, "score": 164462.56532339563 }, { "content": "/// Return the prefix operator at the beginning of the input, if any.\n\nfn parse_prefix(input: ParserInput) -> ParserResult<PrefixOperator> {\n\n match input.split_first() {\n\n None => unexpected_eof!(input),\n\n Some((Token::Operator(Operator::Minus), remainder)) => {\n\n Ok((remainder, PrefixOperator::Minus))\n\n }\n\n Some((other_token, _)) => expected_token!(input, other_token, \"prefix operator\".to_owned()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{expression::PrefixOperator, parser::lexer::lex};\n\n use crate::{\n\n expression::{Expression, ExpressionFunction, InfixOperator},\n\n imag, real,\n\n };\n\n\n\n use super::parse_expression;\n\n\n", "file_path": "src/parser/expression.rs", "rank": 53, "score": 160495.74763897146 }, { "content": "fn get_precedence(input: ParserInput) -> Precedence {\n\n match input.first() {\n\n Some(v) => Precedence::from(v),\n\n None => Precedence::Lowest,\n\n }\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 54, "score": 148314.53840227687 }, { "content": "fn _lex(input: &str) -> IResult<&str, Vec<Token>> {\n\n terminated(\n\n many0(alt((\n\n value(Token::Indentation, tag(\" \")),\n\n preceded(many0(tag(\" \")), lex_token),\n\n ))),\n\n many0(one_of(\"\\n\\t \")),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 55, "score": 134848.97624621086 }, { "content": "fn lex_identifier_raw(input: &str) -> IResult<&str, String> {\n\n map(\n\n tuple((\n\n take_while1(is_valid_identifier_leading_character),\n\n take_while(is_valid_identifier_character),\n\n )),\n\n |result| [result.0, result.1].concat(),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 56, "score": 134056.11162649072 }, { "content": "type ParserResult<'a, R> = IResult<&'a [Token], R, Error<&'a [Token]>>;\n", "file_path": "src/parser/mod.rs", "rank": 57, "score": 132892.7015571443 }, { "content": "fn lex_modifier(input: &str) -> LexResult {\n\n alt((\n\n value(Token::As, tag(\"AS\")),\n\n value(Token::Matrix, tag(\"MATRIX\")),\n\n value(Token::Modifier(Modifier::Controlled), tag(\"CONTROLLED\")),\n\n value(Token::Modifier(Modifier::Dagger), tag(\"DAGGER\")),\n\n value(Token::Modifier(Modifier::Forked), tag(\"FORKED\")),\n\n value(Token::Permutation, tag(\"PERMUTATION\")),\n\n value(Token::Sharing, tag(\"SHARING\")),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 58, "score": 117470.03888881802 }, { "content": "fn lex_token(input: &str) -> LexResult {\n\n alt((\n\n lex_comment,\n\n // Instruction must come before identifier\n\n lex_instruction,\n\n lex_data_type,\n\n lex_modifier,\n\n lex_punctuation,\n\n lex_label,\n\n lex_string,\n\n // Operator must come before number (or it may be parsed as a prefix)\n\n lex_operator,\n\n lex_number,\n\n lex_variable,\n\n lex_non_blocking,\n\n // This should come last because it's sort of a catch all\n\n lex_identifier,\n\n ))(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 59, "score": 117424.65432394626 }, { "content": "fn lex_string(input: &str) -> LexResult {\n\n map(\n\n delimited(tag(\"\\\"\"), take_until(\"\\\"\"), tag(\"\\\"\")),\n\n |v: &str| Token::String(v.to_owned()),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 60, "score": 117350.1483327516 }, { "content": "fn lex_instruction(input: &str) -> LexResult {\n\n use Command::*;\n\n\n\n // TODO: Switch these `map`s over to `value`s\n\n\n\n // The `alt`s are nested because there is a limit to how many branches are allowed in one of them\n\n // https://github.com/Geal/nom/issues/1144\n\n let result = alt((\n\n alt((\n\n map(tag(\"DEFGATE\"), |_| DefGate),\n\n map(tag(\"DEFCIRCUIT\"), |_| DefCircuit),\n\n map(tag(\"MEASURE\"), |_| Measure),\n\n map(tag(\"HALT\"), |_| Halt),\n\n map(tag(\"JUMP-WHEN\"), |_| JumpWhen),\n\n map(tag(\"JUMP-UNLESS\"), |_| JumpUnless),\n\n // Note: this must follow the other jump commands\n\n map(tag(\"JUMP\"), |_| Jump),\n\n map(tag(\"RESET\"), |_| Reset),\n\n map(tag(\"WAIT\"), |_| Wait),\n\n map(tag(\"NOP\"), |_| Nop),\n", "file_path": "src/parser/lexer.rs", "rank": 61, "score": 115687.40522179683 }, { "content": "type ParserInput<'a> = &'a [Token];\n", "file_path": "src/parser/mod.rs", "rank": 62, "score": 112640.56238067536 }, { "content": "/// Parse an arithmetic instruction of the form `destination source`.\n\n/// Called using the arithmetic operator itself (such as `ADD`) which should be previously parsed.\n\npub fn parse_arithmetic(\n\n operator: ArithmeticOperator,\n\n input: ParserInput,\n\n) -> ParserResult<Instruction> {\n\n let (input, destination_memory_reference) = common::parse_memory_reference(input)?;\n\n let destination = ArithmeticOperand::MemoryReference(destination_memory_reference);\n\n let (input, source) = common::parse_arithmetic_operand(input)?;\n\n Ok((\n\n input,\n\n Instruction::Arithmetic(Arithmetic {\n\n operator,\n\n destination,\n\n source,\n\n }),\n\n ))\n\n}\n\n\n", "file_path": "src/parser/command.rs", "rank": 63, "score": 99983.01116464274 }, { "content": "fn lex_variable(input: &str) -> LexResult {\n\n map(preceded(tag(\"%\"), lex_identifier_raw), |ident| {\n\n Token::Variable(ident)\n\n })(input)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{lex, Command, Operator, Token};\n\n\n\n #[test]\n\n fn comment() {\n\n let input = \"# hello\\n#world\";\n\n let tokens = lex(input);\n\n assert_eq!(\n\n tokens,\n\n vec![\n\n Token::Comment(\" hello\".to_owned()),\n\n Token::NewLine,\n\n Token::Comment(\"world\".to_owned())\n", "file_path": "src/parser/lexer.rs", "rank": 67, "score": 88254.05420483487 }, { "content": "fn lex_comment(input: &str) -> LexResult {\n\n let (input, _) = tag(\"#\")(input)?;\n\n let (input, content) = is_not(\"\\n\")(input)?;\n\n Ok((input, Token::Comment(content.to_owned())))\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 68, "score": 88254.05420483487 }, { "content": "fn lex_label(input: &str) -> LexResult {\n\n let (input, _) = tag(\"@\")(input)?;\n\n let (input, label) = lex_identifier_raw(input)?;\n\n Ok((input, Token::Label(label)))\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 69, "score": 88254.05420483487 }, { "content": "fn lex_punctuation(input: &str) -> LexResult {\n\n use Token::*;\n\n alt((\n\n value(Colon, tag(\":\")),\n\n value(Comma, tag(\",\")),\n\n value(Indentation, alt((tag(\" \"), tag(\"\\t\")))),\n\n value(LBracket, tag(\"[\")),\n\n value(LParenthesis, tag(\"(\")),\n\n value(NewLine, alt((is_a(\"\\n\"), is_a(\"\\r\\n\")))),\n\n value(RBracket, tag(\"]\")),\n\n value(RParenthesis, tag(\")\")),\n\n value(Semicolon, tag(\";\")),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 70, "score": 88254.05420483487 }, { "content": "fn lex_operator(input: &str) -> LexResult {\n\n use Operator::*;\n\n map(\n\n alt((\n\n value(Caret, tag(\"^\")),\n\n value(Minus, tag(\"-\")),\n\n value(Plus, tag(\"+\")),\n\n value(Slash, tag(\"/\")),\n\n value(Star, tag(\"*\")),\n\n )),\n\n Token::Operator,\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 71, "score": 88254.05420483487 }, { "content": "fn lex_number(input: &str) -> LexResult {\n\n let (input, float_string): (&str, &str) = recognize(double)(input)?;\n\n let integer_parse_result: IResult<&str, _> = all_consuming(digit1)(float_string);\n\n Ok((\n\n input,\n\n match integer_parse_result {\n\n Ok(_) => Token::Integer(float_string.parse::<u64>().unwrap()),\n\n Err(_) => Token::Float(double(float_string)?.1 as f64),\n\n },\n\n ))\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 72, "score": 88254.05420483487 }, { "content": "fn lex_identifier(input: &str) -> LexResult {\n\n lex_identifier_raw(input).map(|(input, ident)| (input, Token::Identifier(ident)))\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 73, "score": 88254.05420483487 }, { "content": "fn lex_non_blocking(input: &str) -> LexResult {\n\n value(Token::NonBlocking, tag(\"NONBLOCKING\"))(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 74, "score": 86525.43658316864 }, { "content": "fn lex_data_type(input: &str) -> LexResult {\n\n alt((\n\n value(Token::DataType(DataType::Bit), tag(\"BIT\")),\n\n value(Token::DataType(DataType::Integer), tag(\"INTEGER\")),\n\n value(Token::DataType(DataType::Octet), tag(\"OCTET\")),\n\n value(Token::DataType(DataType::Real), tag(\"REAL\")),\n\n ))(input)\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 75, "score": 86525.43658316864 }, { "content": "/// Escape strings for use as DOT format quoted ID's\n\nfn write_escaped(f: &mut fmt::Formatter, s: &str) -> fmt::Result {\n\n for c in s.chars() {\n\n write_char(f, c)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/program/graph.rs", "rank": 76, "score": 86177.93465670403 }, { "content": "/// Escape a single character for use within a DOT format quoted ID.\n\nfn write_char(f: &mut fmt::Formatter, c: char) -> fmt::Result {\n\n use std::fmt::Write;\n\n match c {\n\n '\"' | '\\\\' => f.write_char('\\\\')?,\n\n // \\l is for left justified linebreak\n\n '\\n' => return f.write_str(\"\\\\l\"),\n\n _ => {}\n\n }\n\n f.write_char(c)\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct ScheduledProgram {\n\n /// All blocks within the ScheduledProgram, keyed on string label.\n\n pub blocks: IndexMap<String, InstructionBlock>,\n\n}\n\n\n\nmacro_rules! terminate_working_block {\n\n ($terminator:expr, $working_instructions:ident, $blocks:ident, $working_label:ident, $program: ident) => {{\n\n // If this \"block\" has no instructions and no terminator, it's not worth storing - skip it\n", "file_path": "src/program/graph.rs", "rank": 77, "score": 86173.96714655758 }, { "content": "/// Compute the result of an infix expression where both operands are complex.\n\nfn calculate_infix(\n\n left: &num_complex::Complex64,\n\n operator: &InfixOperator,\n\n right: &num_complex::Complex64,\n\n) -> num_complex::Complex64 {\n\n use InfixOperator::*;\n\n match operator {\n\n Caret => left.powc(*right),\n\n Plus => left + right,\n\n Minus => left - right,\n\n Slash => left / right,\n\n Star => left * right,\n\n }\n\n}\n\n\n", "file_path": "src/expression.rs", "rank": 78, "score": 81213.73721992367 }, { "content": "/// Compute the result of a Quil-defined expression function where the operand is complex.\n\nfn calculate_function(\n\n function: &ExpressionFunction,\n\n argument: &num_complex::Complex64,\n\n) -> num_complex::Complex64 {\n\n use ExpressionFunction::*;\n\n match function {\n\n Sine => argument.sin(),\n\n Cis => argument.cos() + imag!(1f64) * argument.sin(),\n\n Cosine => argument.cos(),\n\n Exponent => argument.exp(),\n\n SquareRoot => argument.sqrt(),\n\n }\n\n}\n\n\n\nimpl Expression {\n\n /// Consume the expression, simplifying it as much as possible.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n", "file_path": "src/expression.rs", "rank": 79, "score": 81213.53512602212 }, { "content": "/// Given an expression function, parse the expression within its parentheses.\n\nfn parse_function_call<'a>(\n\n input: ParserInput<'a>,\n\n function: ExpressionFunction,\n\n) -> ParserResult<'a, Expression> {\n\n let (input, _) = token!(LParenthesis)(input)?;\n\n let (input, expression) = parse(input, Precedence::Lowest)?; // TODO: different precedence?\n\n let (input, _) = token!(RParenthesis)(input)?;\n\n Ok((\n\n input,\n\n Expression::FunctionCall {\n\n function,\n\n expression: Box::new(expression),\n\n },\n\n ))\n\n}\n\n\n", "file_path": "src/parser/expression.rs", "rank": 80, "score": 75830.17831658611 }, { "content": "/// Hash value helper: turn a hashable thing into a u64.\n\nfn _hash_to_u64<T: Hash>(t: &T) -> u64 {\n\n let mut s = DefaultHasher::new();\n\n t.hash(&mut s);\n\n s.finish()\n\n}\n\n\n\nimpl Hash for Expression {\n\n // Implemented by hand since we can't derive with f64s hidden inside.\n\n // Also to understand when things should be the same, like with commutativity (`1 + 2 == 2 + 1`).\n\n // See https://github.com/rigetti/quil-rust/issues/27\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n use std::cmp::{max_by_key, min_by_key};\n\n use Expression::*;\n\n match self {\n\n Address(m) => {\n\n \"Address\".hash(state);\n\n m.hash(state);\n\n }\n\n FunctionCall {\n\n function,\n", "file_path": "src/expression.rs", "rank": 81, "score": 69560.43805029406 }, { "content": "fn is_valid_identifier_character(chr: char) -> bool {\n\n is_valid_identifier_leading_character(chr) || chr.is_ascii_digit() || chr == '\\\\' || chr == '-'\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 82, "score": 40421.82158959535 }, { "content": "fn is_valid_identifier_leading_character(chr: char) -> bool {\n\n chr.is_ascii_alphabetic() || chr == '_'\n\n}\n\n\n", "file_path": "src/parser/lexer.rs", "rank": 83, "score": 39562.322803392395 }, { "content": "/**\n\n * Copyright 2021 Rigetti Computing\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n **/\n\nuse std::collections::{hash_map::DefaultHasher, HashMap};\n\nuse std::f64::consts::PI;\n\nuse std::fmt;\n\nuse std::hash::{Hash, Hasher};\n\nuse std::str::FromStr;\n", "file_path": "src/expression.rs", "rank": 84, "score": 36464.80837597482 }, { "content": " Some(value) => Ok(*value),\n\n None => Err(EvaluationError::Incomplete),\n\n },\n\n Address(memory_reference) => memory_references\n\n .get(memory_reference.name.as_str())\n\n .and_then(|values| {\n\n let value = values.get(memory_reference.index as usize)?;\n\n Some(real!(*value))\n\n })\n\n .ok_or(EvaluationError::Incomplete),\n\n PiConstant => Ok(real!(PI)),\n\n Number(number) => Ok(*number),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> FromStr for Expression {\n\n type Err = String;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n", "file_path": "src/expression.rs", "rank": 85, "score": 36414.10549881881 }, { "content": " ///\n\n /// assert_eq!(evaluated, Complex64::from(3.0))\n\n /// ```\n\n pub fn evaluate(\n\n &self,\n\n variables: &HashMap<String, num_complex::Complex64>,\n\n memory_references: &HashMap<&str, Vec<f64>>,\n\n ) -> Result<num_complex::Complex64, EvaluationError> {\n\n use Expression::*;\n\n\n\n match self {\n\n FunctionCall {\n\n function,\n\n expression,\n\n } => {\n\n let evaluated = expression.evaluate(variables, memory_references)?;\n\n Ok(calculate_function(function, &evaluated))\n\n }\n\n Infix {\n\n left,\n", "file_path": "src/expression.rs", "rank": 86, "score": 36412.36514226891 }, { "content": "\n\n#[cfg(test)]\n\nuse proptest_derive::Arbitrary;\n\n\n\nuse crate::parser::{lex, parse_expression};\n\nuse crate::{imag, instruction::MemoryReference, real};\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq)]\n\npub enum EvaluationError {\n\n Incomplete,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum Expression {\n\n Address(MemoryReference),\n\n FunctionCall {\n\n function: ExpressionFunction,\n\n expression: Box<Expression>,\n\n },\n\n Infix {\n", "file_path": "src/expression.rs", "rank": 87, "score": 36409.87992014548 }, { "content": " let tokens = lex(s);\n\n let (extra, expression) =\n\n parse_expression(&tokens).map_err(|_| String::from(\"Failed to parse expression\"))?;\n\n if extra.is_empty() {\n\n Ok(expression)\n\n } else {\n\n Err(format!(\n\n \"Parsed valid expression {} but found {} extra tokens\",\n\n expression,\n\n extra.len(),\n\n ))\n\n }\n\n }\n\n}\n\n\n\n/// Format a num_complex::Complex64 value in a way that omits the real or imaginary part when\n\n/// reasonable. That is:\n\n///\n\n/// - When imaginary is set but real is 0, show only imaginary\n\n/// - When imaginary is 0, show real only\n", "file_path": "src/expression.rs", "rank": 88, "score": 36408.30534844748 }, { "content": " /// Evaluate an expression, expecting that it may be fully reduced to a single complex number.\n\n /// If it cannot be reduced to a complex number, return an error.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n\n /// use quil_rs::expression::Expression;\n\n /// use std::str::FromStr;\n\n /// use std::collections::HashMap;\n\n /// use num_complex::Complex64;\n\n ///\n\n /// let expression = Expression::from_str(\"%beta + theta[0]\").unwrap();\n\n ///\n\n /// let mut variables = HashMap::with_capacity(1);\n\n /// variables.insert(String::from(\"beta\"), Complex64::from(1.0));\n\n ///\n\n /// let mut memory_references = HashMap::with_capacity(1);\n\n /// memory_references.insert(\"theta\", vec![2.0]);\n\n ///\n\n /// let evaluated = expression.evaluate(&variables, &memory_references).unwrap();\n", "file_path": "src/expression.rs", "rank": 89, "score": 36408.00014304997 }, { "content": " )\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::HashSet;\n\n\n\n use num_complex::Complex64;\n\n use proptest::prelude::*;\n\n\n\n use crate::{\n\n expression::{EvaluationError, Expression, ExpressionFunction},\n\n real,\n\n };\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn simplify_and_evaluate() {\n", "file_path": "src/expression.rs", "rank": 90, "score": 36407.524807052105 }, { "content": " }};\n\n}\n\n\n\nimpl fmt::Display for Expression {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use Expression::*;\n\n match self {\n\n Address(memory_reference) => write!(f, \"{}\", memory_reference),\n\n FunctionCall {\n\n function,\n\n expression,\n\n } => write!(f, \"{}({})\", function, expression),\n\n Infix {\n\n left,\n\n operator,\n\n right,\n\n } => write!(f, \"({}{}{})\", left, operator, right),\n\n Number(value) => write!(f, \"{}\", format_complex!(value)),\n\n PiConstant => write!(f, \"pi\"),\n\n Prefix {\n", "file_path": "src/expression.rs", "rank": 91, "score": 36406.941890395145 }, { "content": " operator,\n\n right,\n\n } => {\n\n let left_evaluated = left.evaluate(variables, memory_references)?;\n\n let right_evaluated = right.evaluate(variables, memory_references)?;\n\n Ok(calculate_infix(&left_evaluated, operator, &right_evaluated))\n\n }\n\n Prefix {\n\n operator,\n\n expression,\n\n } => {\n\n use PrefixOperator::*;\n\n let value = expression.evaluate(variables, memory_references)?;\n\n if matches!(operator, Minus) {\n\n Ok(-value)\n\n } else {\n\n Ok(value)\n\n }\n\n }\n\n Variable(identifier) => match variables.get(identifier.as_str()) {\n", "file_path": "src/expression.rs", "rank": 92, "score": 36406.7366454024 }, { "content": " /// use quil_rs::expression::Expression;\n\n /// use std::str::FromStr;\n\n /// use num_complex::Complex64;\n\n ///\n\n /// let expression = Expression::from_str(\"cos(2 * pi) + 2\").unwrap().simplify();\n\n ///\n\n /// assert_eq!(expression, Expression::Number(Complex64::from(3.0)));\n\n /// ```\n\n pub fn simplify(self) -> Self {\n\n use Expression::*;\n\n\n\n let simplified = match self {\n\n FunctionCall {\n\n function,\n\n expression,\n\n } => {\n\n let simplified = expression.simplify();\n\n if let Number(number) = simplified {\n\n Number(calculate_function(&function, &number))\n\n } else {\n", "file_path": "src/expression.rs", "rank": 93, "score": 36403.518391961086 }, { "content": " fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use ExpressionFunction::*;\n\n write!(\n\n f,\n\n \"{}\",\n\n match self {\n\n Cis => \"cis\",\n\n Cosine => \"cos\",\n\n Exponent => \"exp\",\n\n Sine => \"sin\",\n\n SquareRoot => \"sqrt\",\n\n }\n\n )\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Hash)]\n\n#[cfg_attr(test, derive(Arbitrary))]\n\npub enum PrefixOperator {\n\n Plus,\n", "file_path": "src/expression.rs", "rank": 94, "score": 36403.168068953615 }, { "content": " let simplified = case.expression.simplify();\n\n assert_eq!(simplified, case.simplified);\n\n }\n\n }\n\n\n\n /// Generate an arbitrary Expression for a property test.\n\n /// See https://docs.rs/proptest/1.0.0/proptest/prelude/trait.Strategy.html#method.prop_recursive\n\n fn arb_expr() -> impl Strategy<Value = Expression> {\n\n use Expression::*;\n\n let leaf = prop_oneof![\n\n any::<MemoryReference>().prop_map(Address),\n\n (any::<f64>(), any::<f64>())\n\n .prop_map(|(re, im)| Number(num_complex::Complex64::new(re, im))),\n\n Just(PiConstant),\n\n \".*\".prop_map(Variable),\n\n ];\n\n (leaf).prop_recursive(\n\n 4, // No more than 4 branch levels deep\n\n 64, // Target around 64 total nodes\n\n 2, // Each \"collection\" is up to 2 elements\n", "file_path": "src/expression.rs", "rank": 95, "score": 36403.12418910426 }, { "content": " use Expression::*;\n\n\n\n let one = real!(1.0);\n\n let empty_variables = HashMap::new();\n\n\n\n let mut variables = HashMap::new();\n\n variables.insert(\"foo\".to_owned(), real!(10f64));\n\n variables.insert(\"bar\".to_owned(), real!(100f64));\n\n\n\n let empty_memory = HashMap::new();\n\n\n\n let mut memory_references = HashMap::new();\n\n memory_references.insert(\"theta\", vec![1.0, 2.0]);\n\n memory_references.insert(\"beta\", vec![3.0, 4.0]);\n\n\n\n struct TestCase<'a> {\n\n expression: Expression,\n\n variables: &'a HashMap<String, Complex64>,\n\n memory_references: &'a HashMap<&'a str, Vec<f64>>,\n\n simplified: Expression,\n", "file_path": "src/expression.rs", "rank": 96, "score": 36402.22702311023 }, { "content": " match (&operator, expression) {\n\n (Minus, expr) => Prefix {\n\n operator,\n\n expression: Box::new(expr.simplify()),\n\n },\n\n (Plus, expr) => expr.simplify(),\n\n }\n\n }\n\n Variable(identifier) => Variable(identifier),\n\n Address(memory_reference) => Address(memory_reference),\n\n PiConstant => PiConstant,\n\n Number(number) => Number(number),\n\n };\n\n if let Ok(number) = simplified.evaluate(&HashMap::new(), &HashMap::new()) {\n\n Number(number)\n\n } else {\n\n simplified\n\n }\n\n }\n\n\n", "file_path": "src/expression.rs", "rank": 97, "score": 36401.52780270953 }, { "content": " expression,\n\n } => {\n\n \"FunctionCall\".hash(state);\n\n function.hash(state);\n\n expression.hash(state);\n\n }\n\n Infix {\n\n left,\n\n operator,\n\n right,\n\n } => {\n\n \"Infix\".hash(state);\n\n operator.hash(state);\n\n match operator {\n\n InfixOperator::Plus | InfixOperator::Star => {\n\n // commutative, so put left & right in decreasing order by hash value\n\n let (a, b) = (\n\n min_by_key(left, right, _hash_to_u64),\n\n max_by_key(left, right, _hash_to_u64),\n\n );\n", "file_path": "src/expression.rs", "rank": 98, "score": 36401.46479502468 }, { "content": " Minus,\n\n}\n\n\n\nimpl fmt::Display for PrefixOperator {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use PrefixOperator::*;\n\n write!(\n\n f,\n\n \"{}\",\n\n match self {\n\n Plus => \"+\",\n\n Minus => \"-\",\n\n }\n\n )\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Eq, Hash)]\n\n#[cfg_attr(test, derive(Arbitrary))]\n\npub enum InfixOperator {\n", "file_path": "src/expression.rs", "rank": 99, "score": 36400.92812744908 } ]
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) * bits[i]\n\n }\n\n }\n\n return ret;\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 147255.85768834598 }, { "content": "pub fn str_to_vec(bits_str: &[u8], bit_len: usize) -> Vec<i8> {\n\n assert!(bits_str.len() <= bit_len);\n\n let mut bits: Vec<i8> = vec![];\n\n for i in 0..bit_len {\n\n if bits_str.len() < i + 1 {\n\n bits.push(0);\n\n continue;\n\n }\n\n match bits_str[bits_str.len() - i - 1] as char {\n\n '0' => bits.push(0),\n\n '1' => bits.push(1),\n\n _ => bits.push(-1),\n\n };\n\n }\n\n bits\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/util.rs", "rank": 2, "score": 84560.99536665628 }, { "content": "pub fn factor_dfs(\n\n n: &Integer,\n\n p_bits: Vec<i8>,\n\n q_bits: Vec<i8>,\n\n bit_len: usize,\n\n _verbose: bool,\n\n) -> Option<(Integer, Integer)> {\n\n let mut p: Integer = \"0\".parse().unwrap();\n\n for i in 0..p_bits.len() {\n\n if p_bits[i] == 1 {\n\n p += Integer::from(1) << (i as u32);\n\n }\n\n }\n\n let mut q: Integer = \"0\".parse().unwrap();\n\n for i in 0..q_bits.len() {\n\n if q_bits[i] == 1 {\n\n q += Integer::from(1) << (i as u32);\n\n }\n\n }\n\n fn dfs(\n", "file_path": "src/factor/dfs.rs", "rank": 4, "score": 73424.95374745387 }, { "content": "pub fn factor_core(\n\n n: &Integer,\n\n p_bits: Vec<i8>,\n\n q_bits: Vec<i8>,\n\n bit_len: usize,\n\n verbose: bool,\n\n search: String,\n\n) -> Option<(Integer, Integer)> {\n\n match search.as_str() {\n\n \"dfs\" => factor_dfs(n, p_bits, q_bits, bit_len, verbose),\n\n _ => factor_bfs(n, p_bits, q_bits, bit_len, verbose),\n\n }\n\n}\n", "file_path": "src/factor/mod.rs", "rank": 5, "score": 73424.95374745387 }, { "content": "#[bench]\n\nfn bench_factor(b: &mut Bencher) {\n\n // 110,366,524 ns/iter (+/- 8,439,610)\n\n // 8,601,455 ns/iter (+/- 263,670) bits_to_num に saved_p を導入\n\n // 7,060,782 ns/iter (+/- 606,827) 細かい部分で Integer を再利用\n\n let n: Integer = \"104158954646372695568095796310479805403678314919693272509836778997179683485437763692891984254171869987446475357518587344178264028334102088429629785065036660148146855007349113784322098795994839040721664806905084554147298456659074384855277678993200563966327086005547016327991986225930798076081014377904788085807\".parse().unwrap();\n\n let bit_len = 512;\n\n let p_bits = str_to_vec(\"1010101111000NNN11000NNN11100NNN11010NNN0NNN0NNN0NNN100110000NNN0NNN0NNN0NNN11000NNN0NNN0NNN110110010NNN11001100100111010NNN100011000NNN0NNN0NNN0NNN11111000111111100NNN1101110010000NNN0NNN0NNN0NNN10110NNN0NNN0NNN0NNN0NNN0NNN1100101111000NNN0NNN1001111011110NNN0NNN10000NNN0NNN0NNN11010NNN1010101110110NNN0NNN0NNN0NNN0NNN10010NNN1011101011100NNN110111010NNN0NNN0NNN0NNN101010110NNN0NNN10000NNN1000101011000NNN0NNN0NNN0NNN101010000NNN11010NNN111010000NNN0NNN11110NNN0NNN10010NNN111010010NNN0NNN0NNN10100NNN0NNN0NNN\".as_bytes(), bit_len);\n\n let q_bits = str_to_vec(\"110111010NNN111011110NNN0NNN1000100110001110100111100NNN0NNN10110NNN11000NNN0NNN10110NNN11100NNN10000NNN0NNN0NNN11111100110010100NNN10000NNN11100NNN0NNN110010110NNN101110010NNN10010NNN11110NNN11110NNN0NNN1101111011000NNN101010110NNN10100NNN0NNN10100NNN1010101011010NNN0NNN0NNN100110110NNN0NNN10000NNN0NNN0NNN1000101110010NNN1111110010110NNN0NNN0NNN0NNN101110100NNN0NNN1100101111000NNN10100NNN0NNN0NNN0NNN0NNN0NNN0NNN10010NNN0NNN0NNN10100NNN10010NNN0NNN0NNN0NNN101011110NNN0NNN111110000NNN0NNN11110NNN0NNN10100NNN\".as_bytes(), bit_len);\n\n b.iter(|| {\n\n factor_core(\n\n &n,\n\n p_bits.clone(),\n\n q_bits.clone(),\n\n bit_len,\n\n false,\n\n \"bfs\".to_string(),\n\n )\n\n });\n\n}\n", "file_path": "benches/bench.rs", "rank": 6, "score": 70694.92761860907 }, { "content": "#[pyfunction]\n\nfn from_str(\n\n n: BigInt,\n\n p_bits_str: String,\n\n q_bits_str: String,\n\n verbose: Option<bool>,\n\n search: Option<String>,\n\n) -> PyResult<Option<(BigInt, BigInt)>> {\n\n // ctrlc::set_handler(|| std::process::exit(2));\n\n let n: Integer = n.to_str_radix(10).parse().unwrap();\n\n let bit_len = p_bits_str.len().max(q_bits_str.len());\n\n let p_bits = str_to_vec(p_bits_str.as_bytes(), bit_len);\n\n let q_bits = str_to_vec(q_bits_str.as_bytes(), bit_len);\n\n match factor_core(\n\n &n,\n\n p_bits,\n\n q_bits,\n\n bit_len,\n\n verbose.unwrap_or(false),\n\n search.unwrap_or(\"bfs\".to_string()),\n\n ) {\n\n Some((p, q)) => Ok(Some((\n\n p.to_string_radix(10).parse().unwrap(),\n\n q.to_string_radix(10).parse().unwrap(),\n\n ))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 7, "score": 38950.14040743755 }, { "content": "#[pyfunction]\n\nfn from_vector(\n\n n: BigInt,\n\n p_bits: Vec<i8>,\n\n q_bits: Vec<i8>,\n\n verbose: Option<bool>,\n\n search: Option<String>,\n\n) -> PyResult<Option<(BigInt, BigInt)>> {\n\n // ctrlc::set_handler(|| std::process::exit(2));\n\n let n: Integer = n.to_str_radix(10).parse().unwrap();\n\n let bit_len = p_bits.len().max(q_bits.len());\n\n let mut p_bits = p_bits.clone();\n\n let mut q_bits = q_bits.clone();\n\n p_bits.reverse();\n\n q_bits.reverse();\n\n match factor_core(\n\n &n,\n\n p_bits,\n\n q_bits,\n\n bit_len,\n\n verbose.unwrap_or(false),\n", "file_path": "src/lib.rs", "rank": 8, "score": 38950.14040743755 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let n: Integer = args[1].parse().unwrap();\n\n let p_bits_str = args[2].as_bytes();\n\n let q_bits_str = args[3].as_bytes();\n\n let bit_len = p_bits_str.len().max(q_bits_str.len());\n\n let p_bits = str_to_vec(p_bits_str, bit_len);\n\n let q_bits = str_to_vec(q_bits_str, bit_len);\n\n assert_eq!(p_bits.len(), q_bits.len());\n\n match factor_core(&n, p_bits, q_bits, bit_len, false, \"bfs\".to_string()) {\n\n Some((p, q)) => println!(\"{}, {}\", p, q),\n\n None => println!(\"Not found\"),\n\n };\n\n}\n", "file_path": "examples/factor_cui.rs", "rank": 9, "score": 38037.797186756885 }, { "content": "#[pymodule]\n\nfn factor(_py: Python, m: &PyModule) -> PyResult<()> {\n\n m.add_function(wrap_pyfunction!(from_vector, m)?)?;\n\n m.add_function(wrap_pyfunction!(from_str, m)?)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/lib.rs", "rank": 10, "score": 29672.84618584124 }, { "content": " n: &Integer,\n\n p: &mut Integer,\n\n q: &mut Integer,\n\n p_bits: &Vec<i8>,\n\n q_bits: &Vec<i8>,\n\n bit: usize,\n\n max_bit: usize,\n\n ) -> bool {\n\n let mut bit = bit;\n\n while bit < max_bit {\n\n if p_bits[bit] == -1 || q_bits[bit] == -1 {\n\n break;\n\n }\n\n bit += 1;\n\n }\n\n if bit == max_bit {\n\n let mut tmp_n = p.clone();\n\n tmp_n *= q.clone();\n\n return &tmp_n == n;\n\n }\n", "file_path": "src/factor/dfs.rs", "rank": 19, "score": 10.66588835000951 }, { "content": " for i in 0..2 {\n\n for j in 0..2 {\n\n let mut p_ = Integer::new();\n\n if p_bits[bit] == -1 && i == 1 {\n\n p_.assign(Integer::from(1) << bit as u32);\n\n } else {\n\n p_.assign(0);\n\n }\n\n let mut q_ = Integer::new();\n\n if q_bits[bit] == -1 && j == 1 {\n\n q_.assign(Integer::from(1) << bit as u32);\n\n } else {\n\n q_.assign(0);\n\n }\n\n *p += &p_;\n\n *q += &q_;\n\n let mut tmp_n = p.clone();\n\n tmp_n *= q.clone();\n\n tmp_n -= n;\n\n tmp_n %= Integer::from(1) << (bit + 1) as u32;\n", "file_path": "src/factor/dfs.rs", "rank": 20, "score": 9.164331142536998 }, { "content": " if tmp_n == 0 && dfs(n, p, q, p_bits, q_bits, bit + 1, max_bit) {\n\n return true;\n\n }\n\n *p -= p_;\n\n *q -= q_;\n\n }\n\n }\n\n false\n\n }\n\n match dfs(n, &mut p, &mut q, &p_bits, &q_bits, 0, bit_len) {\n\n true => Some((p, q)),\n\n false => None,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "src/factor/dfs.rs", "rank": 21, "score": 7.738893633200373 }, { "content": "use once_cell::sync::Lazy;\n\nuse rug::{ops::Pow, Integer};\n\n\n\npub static TWO: Lazy<Integer> = Lazy::new(|| \"2\".parse().unwrap());\n\n\n", "file_path": "src/util.rs", "rank": 22, "score": 7.64533748859152 }, { "content": "// use ctrlc;\n\npub mod factor;\n\npub mod util;\n\n\n\nuse num_bigint::BigInt;\n\nuse pyo3::prelude::*;\n\nuse pyo3::wrap_pyfunction;\n\nuse rug::Integer;\n\n\n\nuse crate::factor::factor_core;\n\nuse crate::util::str_to_vec;\n\n\n\n/// from_vector(n, p_bits, q_bits, verbose=False, search=\"bfs\")\n\n/// --\n\n///\n\n/// factor `n` from `p` (`list` like `[-1, 1, 0, -1, 0, 1, -1]`) and `q` whose bits are known around more than 50%.\n\n///\n\n/// Args:\n\n/// n (int): `n` to be factored. `str` of decimal number.\n\n/// p_bits (list[int]): `list[int]` of `p`'s bits like `[-1, 1, 0, -1, 0, 1, -1]` (big endian).\n", "file_path": "src/lib.rs", "rank": 24, "score": 4.724878124594245 }, { "content": "\n\n #[test]\n\n fn test_bits_to_num() {\n\n let bits: Vec<i8> = vec![1, 0, 1, 0, 1];\n\n let n = 3;\n\n let saved: Integer = \"1\".parse().unwrap();\n\n let saved_idx = 1;\n\n let expected: Integer = \"5\".parse().unwrap();\n\n assert_eq!(bits_to_num(&bits, n, &saved, saved_idx), expected);\n\n\n\n let n = 4;\n\n let saved: Integer = \"1\".parse().unwrap();\n\n let saved_idx = 1;\n\n let expected: Integer = \"5\".parse().unwrap();\n\n assert_eq!(bits_to_num(&bits, n, &saved, saved_idx), expected);\n\n\n\n let n = 5;\n\n let saved: Integer = \"1\".parse().unwrap();\n\n let saved_idx = 1;\n\n let expected: Integer = \"21\".parse().unwrap();\n", "file_path": "src/util.rs", "rank": 25, "score": 4.4074018463591 }, { "content": "use rug::{Assign, Integer};\n\n\n", "file_path": "src/factor/dfs.rs", "rank": 26, "score": 4.264962731185021 }, { "content": "/// q_bits (list[int]): the same as `p_bits`\n\n/// Returns:\n\n/// (int, int) or None: (p, q) such that n == p * q.\n\n/// Examples:\n\n/// >>> import factor\n\n/// >>> factor.from_vector(35, [1, 1, -1], [-1, 0, 1])\n\n/// (7, 5)\n\n/// >>> factor.from_vector(35, [0, 1, -1], [-1, 0, 1]) is None\n\n/// True\n\n#[pyfunction]\n", "file_path": "src/lib.rs", "rank": 27, "score": 4.110166271371383 }, { "content": "#![feature(test)]\n\nuse rug::Integer;\n\nuse std::env;\n\nextern crate test;\n\n\n\nuse factor::factor::factor_core;\n\nuse factor::util::str_to_vec;\n\n\n", "file_path": "examples/factor_cui.rs", "rank": 28, "score": 3.9576564184711307 }, { "content": "#![feature(test)]\n\nextern crate test;\n\nuse rug::Integer;\n\nuse test::Bencher;\n\n\n\nuse factor::factor::factor_core;\n\nuse factor::util::str_to_vec;\n\n\n\n#[bench]\n", "file_path": "benches/bench.rs", "rank": 29, "score": 3.9154589040925454 }, { "content": "mod bfs;\n\nmod dfs;\n\n\n\nuse rug::Integer;\n\n\n\nuse crate::factor::bfs::factor_bfs;\n\nuse crate::factor::dfs::factor_dfs;\n\n\n", "file_path": "src/factor/mod.rs", "rank": 30, "score": 3.8940869213374203 }, { "content": " search.unwrap_or(\"bfs\".to_string()),\n\n ) {\n\n Some((p, q)) => Ok(Some((\n\n p.to_string_radix(10).parse().unwrap(),\n\n q.to_string_radix(10).parse().unwrap(),\n\n ))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n\n/// from_str(n, p_bits_str, q_bits_str, verbose=False, search=\"bfs\")\n\n/// --\n\n///\n\n/// factor `n` from `p` (str like \"_10_01__1\") and `q` whose bits are known around more than 50%.\n\n///\n\n/// Args:\n\n/// n (int): `n` to be factored.\n\n/// p_bits_str (str): string of `p`'s bits like \"?10?01??1\" (big endian).\n\n/// q_bits_str (str): the same as `p_bits_str`\n\n/// Returns:\n\n/// (int, int) or None: (p, q) such that n == p * q.\n\n/// Examples:\n\n/// >>> import factor\n\n/// >>> factor.from_str(35, \"11_\", \"_01\")\n\n/// (7, 5)\n\n/// >>> factor.from_str(35, \"11?\", \"?01\")\n\n/// (7, 5)\n\n/// >>> factor.from_str(35, \"01_\", \"_01\") is None\n\n/// True\n", "file_path": "src/lib.rs", "rank": 32, "score": 3.0801101026357243 }, { "content": " assert_eq!(bits_to_num(&bits, n, &saved, saved_idx), expected);\n\n }\n\n\n\n #[test]\n\n fn test_str_to_vec() {\n\n assert_eq!(str_to_vec(\"101\".as_bytes(), 3), [1, 0, 1]);\n\n assert_eq!(str_to_vec(\"101\".as_bytes(), 4), [1, 0, 1, 0]);\n\n assert_eq!(str_to_vec(\"101\".as_bytes(), 5), [1, 0, 1, 0, 0]);\n\n\n\n assert_eq!(str_to_vec(\"_01\".as_bytes(), 3), [1, 0, -1]);\n\n assert_eq!(str_to_vec(\"?01\".as_bytes(), 3), [1, 0, -1]);\n\n }\n\n\n\n #[test]\n\n #[should_panic]\n\n fn test_str_to_vec_panic() {\n\n str_to_vec(\"101\".as_bytes(), 2);\n\n }\n\n}\n", "file_path": "src/util.rs", "rank": 33, "score": 2.811324660154095 }, { "content": "# Factor from random known bits\n\n\n\nPython's library written in Rust to quickly factor `n = pq` when around >50% bits of `p` and `q` are known which are distributed at random.\n\nUsed mainly for CTF challenges, especially about RSA.\n\n\n\n```python\n\n>>> import factor\n\n>>> factor.from_str(91, \"110_\", \"0__1\")\n\n (13, 7)\n\n>>> factor.from_vector(91, [1, 1, 0, -1], [0, -1, -1, 1])\n\n (13, 7)\n\n>>> n = 104158954646372695568095796310479805403678314919693272509836778997179683485437763692891984254171869987446475357518587344178264028334102088429629785065036660148146855007349113784322098795994839040721664806905084554147298456659074384855277678993200563966327086005547016327991986225930798076081014377904788085807\n\n>>> p_bits_str = \"1010101111000___11000___11100___11010___0___0___0___100110000___0___0___0___11000___0___0___110110010___11001100100111010___100011000___0___0___0___11111000111111100___1101110010000___0___0___0___10110___0___0___0___0___0___1100101111000___0___1001111011110___0___10000___0___0___11010___1010101110110___0___0___0___0___10010___1011101011100___110111010___0___0___0___101010110___0___10000___1000101011000___0___0___0___101010000___11010___111010000___0___11110___0___10010___111010010___0___0___10100___0___0___\"\n\n>>> q_bits_str = \"110111010___111011110___0___1000100110001110100111100___0___10110___11000___0___10110___11100___10000___0___0___11111100110010100___10000___11100___0___110010110___101110010___10010___11110___11110___0___1101111011000___101010110___10100___0___10100___1010101011010___0___0___100110110___0___10000___0___0___1000101110010___1111110010110___0___0___0___101110100___0___1100101111000___10100___0___0___0___0___0___0___10010___0___0___10100___10010___0___0___0___101011110___0___111110000___0___11110___0___10100___\"\n\n>>> p_q = factor.from_str(n, p_bits_str, q_bits_str)\n\n>>> assert p_q is not None\n\n>>> p, q = p_q\n\n>>> assert p * q == n\n\n```\n\n\n\nIn addition, of course, this can be used in Rust program. See `examples/factor_cui.rs`.\n\n```bash\n\n$ cargo run --release --example factor_cui 3233 1_0__1 1___01\n\n53, 61\n\n```\n\n\n", "file_path": "README.md", "rank": 34, "score": 2.412485039575089 }, { "content": "# SECCON 2020 This is RSA\n\n\n\n```ruby\n\nrequire 'openssl'\n\n\n\ndef get_prime\n\n i = OpenSSL::BN.rand(512).to_s.unpack1('H*').hex\n\n OpenSSL::BN.new(i).prime? ? i : get_prime\n\nend\n\n\n\np = get_prime\n\nq = get_prime\n\nn = p * q\n\ne = 65537\n\nm = File.read('flag.txt').unpack1('H*').hex\n\nc = m.pow(e, n)\n\n\n\nputs \"N = #{n}\"\n\nputs \"c = #{c}\"\n\n```\n\n\n\n## Writeup\n\n\n\n`OpenSSL::BN.rand(512).to_s.unpack1('H*').hex` returns `0x3_3_3_...`.\n\nSo we know that `p` and `q` are `\"...0011____0011____...0011____\"` in binary.\n\n\n\n## Run solver\n\n\n\n```bash\n\npython solver.py\n\n```\n", "file_path": "examples/seccon_2020_this_is_rsa/README.md", "rank": 35, "score": 2.1355787768939662 }, { "content": " fn test_factor() {\n\n let n: Integer = \"323\".parse().unwrap();\n\n let p_bits = vec![-1, -1, -1, -1, -1]; // NNNNN\n\n let q_bits = vec![-1, 1, -1, -1, -1]; // NNN1N\n\n let bit_len = 5;\n\n let expected: Option<(Integer, Integer)> =\n\n Some((\"17\".parse().unwrap(), \"19\".parse().unwrap()));\n\n assert_eq!(\n\n factor_dfs(&n, p_bits.clone(), q_bits.clone(), bit_len, false),\n\n expected\n\n );\n\n }\n\n}\n", "file_path": "src/factor/dfs.rs", "rank": 36, "score": 2.0535124922183186 }, { "content": "# HSCTF 8 regulus-calendula\n\n## Run challenge server\n\n\n\n```bash\n\nsocat tcp4-listen:1337,reuseaddr,fork \"system:python3 server.py\"\n\n```\n\nThis `server.py` is modified to use fixed primes generated in advance because `getPrime(4096)` takes too much time...\n\n\n\n## Writeup\n\n\n\nThe payload `88...88`, `99...99`, ..., `ff...ff` reveals about the half of the bits of `p` and `q`. We also know that unknown positions' MSB is 0. So over 50% bits are known. This is enough to factor.\n\n\n\n## Run solver\n\n\n\n```bash\n\npython solver.py\n\n```\n", "file_path": "examples/hsctf_8_regulus_calendula/README.md", "rank": 37, "score": 1.0048872572209802 }, { "content": "## Install\n\n\n\n```bash\n\n# If you have not yet installed Rust, run command below\n\n$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\n\n\n\n# Install as a Python package\n\n$ pip install -r requirements.txt\n\n$ python setup.py install\n\n```\n\n\n\nYou can also use a docker environment.\n\n\n\n```bash\n\n$ docker run -it --rm y011d4/factor-from-random-known-bits:0.1.0\n\nPython 3.9.6 (default, Jun 29 2021, 19:27:32)\n\n[GCC 8.3.0] on linux\n\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n\n>>>\n\n```\n\n\n\n## Examples in CTF\n\n\n\nThere are some examples in `examples` directory.\n\n- \"This is RSA\" in SECCON CTF 2020\n\n- \"regulus-calendula\" in HSCTF 8\n\n\n\n## License\n\n\n\nLicensed under either of\n\n\n\n * Apache License, Version 2.0\n\n ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n\n * MIT license\n\n ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\n\n\nat your option.\n\n\n\n## Contribution\n\n\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\n\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\n\ndual licensed as above, without any additional terms or conditions.\n", "file_path": "README.md", "rank": 38, "score": 0.59429766680437 } ]
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\", \"clip3\", \"foo\"];\n\n\n\n actual.sort();\n\n expected.sort();\n\n\n\n assert_eq!(actual, expected, \"ruffle output != flash player output\");\n\n Ok(())\n\n}\n\n\n\n/// Wrapper around string slice that makes debug output `{:?}` to print string same way as `{}`.\n\n/// Used in different `assert*!` macros in combination with `pretty_assertions` crate to make\n\n/// test failures to show nice diffs.\n\n/// Courtesy of https://github.com/colin-kiegel/rust-pretty-assertions/issues/24\n\n#[derive(PartialEq, Eq)]\n\n#[doc(hidden)]\n\npub struct PrettyString<'a>(pub &'a str);\n\n\n", "file_path": "core/tests/regression_tests.rs", "rank": 0, "score": 123173.71675252906 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\nimpl<'gc> Avm1<'gc> {\n\n pub fn new(gc_context: MutationContext<'gc, '_>, player_version: u8) -> Self {\n\n let (prototypes, globals, system_listeners) = create_globals(gc_context);\n\n\n\n Self {\n\n player_version,\n\n constant_pool: GcCell::allocate(gc_context, vec![]),\n\n globals,\n\n prototypes,\n\n system_listeners,\n\n display_properties: stage_object::DisplayPropertyMap::new(gc_context),\n\n stack_frames: vec![],\n\n stack: vec![],\n\n registers: [\n\n Value::Undefined,\n\n Value::Undefined,\n\n Value::Undefined,\n\n Value::Undefined,\n", "file_path": "core/src/avm1.rs", "rank": 1, "score": 108995.21980837219 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\nimpl WebAudioBackend {\n\n pub fn new() -> Result<Self, Error> {\n\n let context = AudioContext::new().map_err(|_| \"Unable to create AudioContext\")?;\n\n\n\n // Deduce the minimum sample rate for this browser.\n\n let mut min_sample_rate = 44100;\n\n while min_sample_rate > 5512\n\n && context\n\n .create_buffer(1, 1, (min_sample_rate >> 1) as f32)\n\n .is_ok()\n\n {\n\n min_sample_rate >>= 1;\n\n }\n\n log::info!(\"Minimum audio buffer sample rate: {}\", min_sample_rate);\n\n\n\n Ok(Self {\n\n context,\n\n sounds: Arena::new(),\n", "file_path": "web/src/audio.rs", "rank": 2, "score": 108995.21980837219 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\npub struct GliumRenderBackend {\n\n display: Display,\n\n target: Option<Frame>,\n\n shader_program: glium::Program,\n\n gradient_shader_program: glium::Program,\n\n bitmap_shader_program: glium::Program,\n\n meshes: Vec<Mesh>,\n\n quad_shape: ShapeHandle,\n\n textures: Vec<(swf::CharacterId, Texture)>,\n\n num_masks: u32,\n\n num_masks_active: u32,\n\n write_stencil_mask: u32,\n\n test_stencil_mask: u32,\n\n next_stencil_mask: u32,\n\n mask_stack: Vec<(u32, u32)>,\n\n viewport_width: f32,\n\n viewport_height: f32,\n\n view_matrix: [[f32; 4]; 4],\n", "file_path": "desktop/src/render.rs", "rank": 3, "score": 108995.21980837219 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\n/// Holds all in-progress loads for the player.\n\npub struct LoadManager<'gc>(Arena<Loader<'gc>>);\n\n\n\nunsafe impl<'gc> Collect for LoadManager<'gc> {\n\n fn trace(&self, cc: CollectionContext) {\n\n for (_, loader) in self.0.iter() {\n\n loader.trace(cc)\n\n }\n\n }\n\n}\n\n\n\nimpl<'gc> LoadManager<'gc> {\n\n /// Construct a new `LoadManager`.\n\n pub fn new() -> Self {\n\n Self(Arena::new())\n\n }\n\n\n\n /// Add a new loader to the `LoadManager`.\n", "file_path": "core/src/loader.rs", "rank": 4, "score": 108995.21980837219 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\nmake_arena!(GcArena, GcRoot);\n\n\n", "file_path": "core/src/player.rs", "rank": 5, "score": 108995.21980837219 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\nmod text_format;\n\n\n\npub use text_format::TextFormat;\n\n\n\n#[derive(Debug, Clone, Collect, Copy)]\n\n#[collect(no_drop)]\n\npub struct Font<'gc>(Gc<'gc, FontData>);\n\n\n", "file_path": "core/src/font.rs", "rank": 6, "score": 108995.21980837219 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n", "file_path": "core/src/backend/audio.rs", "rank": 7, "score": 108316.91156134811 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\n// This macro generates test cases for a given list of SWFs.\n\nmacro_rules! swf_tests {\n\n ($($(#[$attr:meta])* ($name:ident, $path:expr, $num_frames:literal),)*) => {\n\n $(\n\n #[test]\n\n $(#[$attr])*\n\n fn $name() -> Result<(), Error> {\n\n test_swf(\n\n concat!(\"tests/swfs/\", $path, \"/test.swf\"),\n\n $num_frames,\n\n concat!(\"tests/swfs/\", $path, \"/output.txt\"),\n\n )\n\n }\n\n )*\n\n };\n\n}\n\n\n\n// This macro generates test cases for a given list of SWFs using `test_swf_approx`.\n", "file_path": "core/tests/regression_tests.rs", "rank": 8, "score": 108316.91156134811 }, { "content": "type Error = Box<dyn std::error::Error>;\n\n\n\n/// A set of text formatting options to be applied to some part, or the whole\n\n/// of, a given text field.\n\n///\n\n/// Any property set to `None` is treated as undefined, which has different\n\n/// meanings based on the context by which the `TextFormat` is used. For\n\n/// example, when getting the format of a particular region of text, `None`\n\n/// means that multiple regions of text apply. When setting the format of a\n\n/// particular region of text, `None` means that the existing setting for that\n\n/// property will be retained.\n\n#[derive(Clone, Debug)]\n\npub struct TextFormat {\n\n font: Option<String>,\n\n size: Option<f64>,\n\n color: Option<swf::Color>,\n\n align: Option<swf::TextAlign>,\n\n bold: Option<bool>,\n\n italic: Option<bool>,\n\n underline: Option<bool>,\n", "file_path": "core/src/font/text_format.rs", "rank": 9, "score": 107652.92555315013 }, { "content": "pub trait TObject<'gc>: 'gc + Collect + Debug + Into<Object<'gc>> + Clone + Copy {\n\n /// Retrieve a named property from this object exclusively.\n\n ///\n\n /// This function takes a redundant `this` parameter which should be\n\n /// the object's own `GcCell`, so that it can pass it to user-defined\n\n /// overrides that may need to interact with the underlying object.\n\n ///\n\n /// This function should not inspect prototype chains. Instead, use `get`\n\n /// to do ordinary property look-up and resolution.\n\n fn get_local(\n\n &self,\n\n name: &str,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n this: Object<'gc>,\n\n ) -> Result<ReturnValue<'gc>, Error>;\n\n\n\n /// Retrieve a named property from the object, or it's prototype.\n\n fn get(\n\n &self,\n", "file_path": "core/src/avm1/object.rs", "rank": 10, "score": 104723.36877076683 }, { "content": "//! Object impl for boxed values\n\n\n\nuse crate::avm1::function::Executable;\n\nuse crate::avm1::object::{ObjectPtr, TObject};\n\nuse crate::avm1::property::Attribute;\n\nuse crate::avm1::return_value::ReturnValue;\n\nuse crate::avm1::{Avm1, Error, Object, ScriptObject, UpdateContext, Value};\n\nuse enumset::EnumSet;\n\nuse gc_arena::{Collect, GcCell, MutationContext};\n\nuse std::collections::HashSet;\n\nuse std::fmt;\n\n\n\n/// An Object that serves as a box for a primitive value.\n\n#[derive(Clone, Copy, Collect)]\n\n#[collect(no_drop)]\n\npub struct ValueObject<'gc>(GcCell<'gc, ValueObjectData<'gc>>);\n\n\n\n/// The internal data for a boxed value.\n\n#[derive(Clone, Collect)]\n\n#[collect(no_drop)]\n", "file_path": "core/src/avm1/value_object.rs", "rank": 11, "score": 99009.46163243998 }, { "content": "\n\n fn call(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n this: Object<'gc>,\n\n args: &[Value<'gc>],\n\n ) -> Result<ReturnValue<'gc>, Error> {\n\n self.0.read().base.call(avm, context, this, args)\n\n }\n\n\n\n #[allow(clippy::new_ret_no_self)]\n\n fn new(\n\n &self,\n\n _avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n this: Object<'gc>,\n\n _args: &[Value<'gc>],\n\n ) -> Result<Object<'gc>, Error> {\n\n Ok(ValueObject::empty_box(context.gc_context, Some(this)))\n", "file_path": "core/src/avm1/value_object.rs", "rank": 12, "score": 99003.90326868373 }, { "content": "pub struct ValueObjectData<'gc> {\n\n /// Base implementation of ScriptObject.\n\n base: ScriptObject<'gc>,\n\n\n\n /// The value being boxed.\n\n ///\n\n /// It is a logic error for this to be another object. All extant\n\n /// constructors for `ValueObject` guard against this by returning the\n\n /// original object if an attempt is made to box objects.\n\n value: Value<'gc>,\n\n}\n\n\n\nimpl<'gc> ValueObject<'gc> {\n\n /// Box a value into a `ValueObject`.\n\n ///\n\n /// If this function is given an object to box, then this function returns\n\n /// the already-defined object.\n\n ///\n\n /// If a class exists for a given value type, this function automatically\n\n /// selects the correct prototype for it from the system prototypes list.\n", "file_path": "core/src/avm1/value_object.rs", "rank": 13, "score": 99003.85626542164 }, { "content": "impl<'gc> TObject<'gc> for ValueObject<'gc> {\n\n fn get_local(\n\n &self,\n\n name: &str,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n this: Object<'gc>,\n\n ) -> Result<ReturnValue<'gc>, Error> {\n\n self.0.read().base.get_local(name, avm, context, this)\n\n }\n\n\n\n fn set(\n\n &self,\n\n name: &str,\n\n value: Value<'gc>,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<(), Error> {\n\n self.0.read().base.set(name, value, avm, context)\n\n }\n", "file_path": "core/src/avm1/value_object.rs", "rank": 14, "score": 99003.7301091882 }, { "content": " pub fn boxed(\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n value: Value<'gc>,\n\n ) -> Object<'gc> {\n\n if let Value::Object(ob) = value {\n\n ob\n\n } else {\n\n let proto = match &value {\n\n Value::Bool(_) => Some(avm.prototypes.boolean),\n\n Value::Number(_) => Some(avm.prototypes.number),\n\n Value::String(_) => Some(avm.prototypes.string),\n\n _ => None,\n\n };\n\n\n\n let obj = ValueObject(GcCell::allocate(\n\n context.gc_context,\n\n ValueObjectData {\n\n base: ScriptObject::object(context.gc_context, proto),\n\n value: Value::Undefined,\n", "file_path": "core/src/avm1/value_object.rs", "rank": 15, "score": 98999.9178542315 }, { "content": " obj.into()\n\n }\n\n }\n\n\n\n /// Construct an empty box to be filled by a constructor.\n\n pub fn empty_box(\n\n gc_context: MutationContext<'gc, '_>,\n\n proto: Option<Object<'gc>>,\n\n ) -> Object<'gc> {\n\n ValueObject(GcCell::allocate(\n\n gc_context,\n\n ValueObjectData {\n\n base: ScriptObject::object(gc_context, proto),\n\n value: Value::Undefined,\n\n },\n\n ))\n\n .into()\n\n }\n\n\n\n /// Retrieve the boxed value.\n", "file_path": "core/src/avm1/value_object.rs", "rank": 16, "score": 98999.73350811713 }, { "content": " pub fn unbox(self) -> Value<'gc> {\n\n self.0.read().value.clone()\n\n }\n\n\n\n /// Change the value in the box.\n\n pub fn replace_value(&mut self, gc_context: MutationContext<'gc, '_>, value: Value<'gc>) {\n\n self.0.write(gc_context).value = value;\n\n }\n\n}\n\n\n\nimpl fmt::Debug for ValueObject<'_> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let this = self.0.read();\n\n f.debug_struct(\"ValueObject\")\n\n .field(\"base\", &this.base)\n\n .field(\"value\", &this.value)\n\n .finish()\n\n }\n\n}\n\n\n", "file_path": "core/src/avm1/value_object.rs", "rank": 17, "score": 98998.96356427234 }, { "content": " fn interfaces(&self) -> Vec<Object<'gc>> {\n\n self.0.read().base.interfaces()\n\n }\n\n\n\n fn set_interfaces(&mut self, context: MutationContext<'gc, '_>, iface_list: Vec<Object<'gc>>) {\n\n self.0\n\n .write(context)\n\n .base\n\n .set_interfaces(context, iface_list)\n\n }\n\n\n\n fn as_script_object(&self) -> Option<ScriptObject<'gc>> {\n\n Some(self.0.read().base)\n\n }\n\n\n\n fn as_value_object(&self) -> Option<ValueObject<'gc>> {\n\n Some(*self)\n\n }\n\n\n\n fn as_ptr(&self) -> *const ObjectPtr {\n", "file_path": "core/src/avm1/value_object.rs", "rank": 18, "score": 98998.8838016807 }, { "content": " self.0.read().base.as_ptr() as *const ObjectPtr\n\n }\n\n\n\n fn length(&self) -> usize {\n\n self.0.read().base.length()\n\n }\n\n\n\n fn array(&self) -> Vec<Value<'gc>> {\n\n self.0.read().base.array()\n\n }\n\n\n\n fn set_length(&self, gc_context: MutationContext<'gc, '_>, length: usize) {\n\n self.0.read().base.set_length(gc_context, length)\n\n }\n\n\n\n fn array_element(&self, index: usize) -> Value<'gc> {\n\n self.0.read().base.array_element(index)\n\n }\n\n\n\n fn set_array_element(\n", "file_path": "core/src/avm1/value_object.rs", "rank": 19, "score": 98996.06940429595 }, { "content": " },\n\n ));\n\n\n\n // Constructor populates the boxed object with the value.\n\n match &value {\n\n Value::Bool(_) => {\n\n let _ =\n\n crate::avm1::globals::boolean::boolean(avm, context, obj.into(), &[value]);\n\n }\n\n Value::Number(_) => {\n\n let _ =\n\n crate::avm1::globals::number::number(avm, context, obj.into(), &[value]);\n\n }\n\n Value::String(_) => {\n\n let _ =\n\n crate::avm1::globals::string::string(avm, context, obj.into(), &[value]);\n\n }\n\n _ => (),\n\n }\n\n\n", "file_path": "core/src/avm1/value_object.rs", "rank": 20, "score": 98993.64948321722 }, { "content": " fn define_value(\n\n &self,\n\n gc_context: MutationContext<'gc, '_>,\n\n name: &str,\n\n value: Value<'gc>,\n\n attributes: EnumSet<Attribute>,\n\n ) {\n\n self.0\n\n .read()\n\n .base\n\n .define_value(gc_context, name, value, attributes)\n\n }\n\n\n\n fn set_attributes(\n\n &mut self,\n\n gc_context: MutationContext<'gc, '_>,\n\n name: Option<&str>,\n\n set_attributes: EnumSet<Attribute>,\n\n clear_attributes: EnumSet<Attribute>,\n\n ) {\n", "file_path": "core/src/avm1/value_object.rs", "rank": 21, "score": 98993.21324792076 }, { "content": " &self,\n\n index: usize,\n\n value: Value<'gc>,\n\n gc_context: MutationContext<'gc, '_>,\n\n ) -> usize {\n\n self.0\n\n .read()\n\n .base\n\n .set_array_element(index, value, gc_context)\n\n }\n\n\n\n fn delete_array_element(&self, index: usize, gc_context: MutationContext<'gc, '_>) {\n\n self.0.read().base.delete_array_element(index, gc_context)\n\n }\n\n}\n", "file_path": "core/src/avm1/value_object.rs", "rank": 22, "score": 98992.79396634724 }, { "content": " self.0.write(gc_context).base.set_attributes(\n\n gc_context,\n\n name,\n\n set_attributes,\n\n clear_attributes,\n\n )\n\n }\n\n\n\n fn proto(&self) -> Option<Object<'gc>> {\n\n self.0.read().base.proto()\n\n }\n\n\n\n fn has_property(&self, context: &mut UpdateContext<'_, 'gc, '_>, name: &str) -> bool {\n\n self.0.read().base.has_property(context, name)\n\n }\n\n\n\n fn has_own_property(&self, context: &mut UpdateContext<'_, 'gc, '_>, name: &str) -> bool {\n\n self.0.read().base.has_own_property(context, name)\n\n }\n\n\n", "file_path": "core/src/avm1/value_object.rs", "rank": 23, "score": 98990.77507929303 }, { "content": " }\n\n\n\n fn delete(&self, gc_context: MutationContext<'gc, '_>, name: &str) -> bool {\n\n self.0.read().base.delete(gc_context, name)\n\n }\n\n\n\n fn add_property(\n\n &self,\n\n gc_context: MutationContext<'gc, '_>,\n\n name: &str,\n\n get: Executable<'gc>,\n\n set: Option<Executable<'gc>>,\n\n attributes: EnumSet<Attribute>,\n\n ) {\n\n self.0\n\n .read()\n\n .base\n\n .add_property(gc_context, name, get, set, attributes)\n\n }\n\n\n", "file_path": "core/src/avm1/value_object.rs", "rank": 24, "score": 98986.76977132786 }, { "content": " fn is_property_overwritable(&self, name: &str) -> bool {\n\n self.0.read().base.is_property_overwritable(name)\n\n }\n\n\n\n fn is_property_enumerable(&self, name: &str) -> bool {\n\n self.0.read().base.is_property_enumerable(name)\n\n }\n\n\n\n fn get_keys(&self) -> HashSet<String> {\n\n self.0.read().base.get_keys()\n\n }\n\n\n\n fn as_string(&self) -> String {\n\n self.0.read().base.as_string()\n\n }\n\n\n\n fn type_of(&self) -> &'static str {\n\n self.0.read().base.type_of()\n\n }\n\n\n", "file_path": "core/src/avm1/value_object.rs", "rank": 25, "score": 98986.76977132786 }, { "content": "/// Implements `Object.prototype.valueOf`\n\nfn value_of<'gc>(\n\n _: &mut Avm1<'gc>,\n\n _: &mut UpdateContext<'_, 'gc, '_>,\n\n this: Object<'gc>,\n\n _: &[Value<'gc>],\n\n) -> Result<ReturnValue<'gc>, Error> {\n\n Ok(ReturnValue::Immediate(this.into()))\n\n}\n\n\n", "file_path": "core/src/avm1/globals/object.rs", "rank": 26, "score": 94191.94449118394 }, { "content": "fn run_player(input_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {\n\n let swf_data = std::fs::read(&input_path)?;\n\n\n\n let event_loop: EventLoop<RuffleEvent> = EventLoop::with_user_event();\n\n let window_builder = WindowBuilder::new().with_title(format!(\n\n \"Ruffle - {}\",\n\n input_path.file_name().unwrap_or_default().to_string_lossy()\n\n ));\n\n let windowed_context = ContextBuilder::new()\n\n .with_vsync(true)\n\n .with_multisampling(4)\n\n .with_srgb(true)\n\n .with_stencil_buffer(8)\n\n .build_windowed(window_builder, &event_loop)?;\n\n let audio: Box<dyn AudioBackend> = match audio::CpalAudioBackend::new() {\n\n Ok(audio) => Box::new(audio),\n\n Err(e) => {\n\n log::error!(\"Unable to create audio device: {}\", e);\n\n Box::new(NullAudioBackend::new())\n\n }\n", "file_path": "desktop/src/main.rs", "rank": 27, "score": 89096.55716280443 }, { "content": "pub trait TDisplayObject<'gc>: 'gc + Collect + Debug + Into<DisplayObject<'gc>> {\n\n fn id(&self) -> CharacterId;\n\n fn depth(&self) -> Depth;\n\n fn set_depth(&self, gc_context: MutationContext<'gc, '_>, depth: Depth);\n\n\n\n /// The untransformed inherent bounding box of this object.\n\n /// These bounds do **not** include child DisplayObjects.\n\n /// To get the bounds including children, use `bounds`, `local_bounds`, or `world_bounds`.\n\n ///\n\n /// Implementors must override this method.\n\n /// Leaf DisplayObjects should return their bounds.\n\n /// Composite DisplayObjects that only contain children should return `&Default::default()`\n\n fn self_bounds(&self) -> BoundingBox;\n\n\n\n /// The untransformed bounding box of this object including children.\n\n fn bounds(&self) -> BoundingBox {\n\n self.bounds_with_transform(&Matrix::default())\n\n }\n\n\n\n /// The local bounding box of this object including children, in its parent's coordinate system.\n", "file_path": "core/src/display_object.rs", "rank": 29, "score": 83727.38377453256 }, { "content": "/// TODO: FSCommand URL handling\n\npub fn handle(fscommand: &str, _avm: &mut Avm1, _ac: &mut UpdateContext) -> Result<(), Error> {\n\n log::warn!(\"Unhandled FSCommand: {}\", fscommand);\n\n\n\n //This should be an error.\n\n Ok(())\n\n}\n", "file_path": "core/src/avm1/fscommand.rs", "rank": 30, "score": 82758.56655619055 }, { "content": "/// Partially construct `Function.prototype`.\n\n///\n\n/// `__proto__` and other cross-linked properties of this object will *not*\n\n/// be defined here. The caller of this function is responsible for linking\n\n/// them in order to obtain a valid ECMAScript `Function` prototype. The\n\n/// returned object is also a bare object, which will need to be linked into\n\n/// the prototype of `Object`.\n\npub fn create_proto<'gc>(gc_context: MutationContext<'gc, '_>, proto: Object<'gc>) -> Object<'gc> {\n\n let function_proto = ScriptObject::object_cell(gc_context, Some(proto));\n\n let this = Some(function_proto);\n\n function_proto\n\n .as_script_object()\n\n .unwrap()\n\n .force_set_function(\"call\", call, gc_context, EnumSet::empty(), this);\n\n function_proto\n\n .as_script_object()\n\n .unwrap()\n\n .force_set_function(\"apply\", apply, gc_context, EnumSet::empty(), this);\n\n function_proto\n\n .as_script_object()\n\n .unwrap()\n\n .force_set_function(\"toString\", to_string, gc_context, EnumSet::empty(), this);\n\n\n\n function_proto\n\n}\n", "file_path": "core/src/avm1/globals/function.rs", "rank": 31, "score": 82056.98019791929 }, { "content": "#[test]\n\nfn test_prototype_enumerate() -> Result<(), Error> {\n\n let trace_log = run_swf(\"tests/swfs/avm1/prototype_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![\"a\", \"b\", \"c\", \"d\", \"e\"];\n\n\n\n actual.sort();\n\n expected.sort();\n\n\n\n assert_eq!(actual, expected, \"ruffle output != flash player output\");\n\n Ok(())\n\n}\n\n\n", "file_path": "core/tests/regression_tests.rs", "rank": 32, "score": 80771.90223150243 }, { "content": "fn main() -> Result<(), std::io::Error> {\n\n env_logger::init();\n\n\n\n let opt = Opt::from_args();\n\n let to_scan = find_files(&opt.input_path, &opt.ignore);\n\n let total = to_scan.len() as u64;\n\n let mut good = 0;\n\n let mut bad = 0;\n\n let progress = ProgressBar::new(total);\n\n let mut writer = csv::Writer::from_path(opt.output_path)?;\n\n\n\n progress.set_style(\n\n ProgressStyle::default_bar()\n\n .template(\n\n \"[{elapsed_precise}] {bar:40.cyan/blue} [{eta_precise}] {pos:>7}/{len:7} {msg}\",\n\n )\n\n .progress_chars(\"##-\"),\n\n );\n\n\n\n writer.write_record(&[\"Filename\", \"Error\"])?;\n", "file_path": "scanner/src/main.rs", "rank": 33, "score": 77734.99556243481 }, { "content": "/// Loads an SWF and runs it through the Ruffle core for a number of frames.\n\n/// Tests that the trace output matches the given expected output.\n\nfn run_swf(swf_path: &str, num_frames: u32) -> Result<String, Error> {\n\n let _ = log::set_logger(&TRACE_LOGGER).map(|()| log::set_max_level(log::LevelFilter::Info));\n\n\n\n let base_path = Path::new(swf_path).parent().unwrap();\n\n let swf_data = std::fs::read(swf_path)?;\n\n let (mut executor, channel) = NullExecutor::new();\n\n let player = Player::new(\n\n Box::new(NullRenderer),\n\n Box::new(NullAudioBackend::new()),\n\n Box::new(NullNavigatorBackend::with_base_path(base_path, channel)),\n\n Box::new(NullInputBackend::new()),\n\n swf_data,\n\n )?;\n\n\n\n for _ in 0..num_frames {\n\n player.lock().unwrap().run_frame();\n\n executor.poll_all().unwrap();\n\n }\n\n\n\n executor.block_all().unwrap();\n\n\n\n Ok(trace_log())\n\n}\n\n\n\nthread_local! {\n\n static TRACE_LOG: RefCell<String> = RefCell::new(String::new());\n\n}\n\n\n\nstatic TRACE_LOGGER: TraceLogger = TraceLogger;\n\n\n", "file_path": "core/tests/regression_tests.rs", "rank": 34, "score": 66467.90834257558 }, { "content": "/// Utility function used by `Avm1::action_wait_for_frame` and\n\n/// `Avm1::action_wait_for_frame_2`.\n\nfn skip_actions(reader: &mut Reader<'_>, num_actions_to_skip: u8) -> Result<(), Error> {\n\n for _ in 0..num_actions_to_skip {\n\n reader.read_action()?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "core/src/avm1.rs", "rank": 35, "score": 66047.66401517665 }, { "content": "/// Loads an SWF and runs it through the Ruffle core for a number of frames.\n\n/// Tests that the trace output matches the given expected output.\n\nfn test_swf(swf_path: &str, num_frames: u32, expected_output_path: &str) -> Result<(), Error> {\n\n let expected_output = std::fs::read_to_string(expected_output_path)?.replace(\"\\r\\n\", \"\\n\");\n\n\n\n let trace_log = run_swf(swf_path, num_frames)?;\n\n assert_eq!(\n\n trace_log, expected_output,\n\n \"ruffle output != flash player output\"\n\n );\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "core/tests/regression_tests.rs", "rank": 36, "score": 62917.82347955278 }, { "content": " static from_native_object_element(elem) {\n\n let external_name = register_element(\"ruffle-object\", RuffleObject);\n\n let ruffle_obj = document.createElement(external_name);\n\n for (let attrib of elem.attributes) {\n\n if (attrib.specified) {\n\n ruffle_obj.setAttribute(attrib.name, attrib.value);\n\n }\n\n }\n\n\n\n for (let node of Array.from(elem.children)) {\n\n ruffle_obj.appendChild(node);\n\n }\n\n\n\n return ruffle_obj;\n", "file_path": "web/js-src/ruffle-object.js", "rank": 37, "score": 59532.80783749533 }, { "content": "#[derive(Collect, EnumSetType, Debug)]\n\n#[collect(no_drop)]\n\nenum DisplayObjectFlags {\n\n /// Whether this object has been removed from the display list.\n\n /// Necessary in AVM1 to throw away queued actions from removed movie clips.\n\n Removed,\n\n\n\n /// If this object is visible (`_visible` property).\n\n Visible,\n\n\n\n /// Whether the `_xscale`, `_yscale` and `_rotation` of the object have been calculated and cached.\n\n ScaleRotationCached,\n\n\n\n /// Whether this object has been transformed by ActionScript.\n\n /// When this flag is set, changes from SWF `PlaceObject` tags are ignored.\n\n TransformedByScript,\n\n}\n\n\n\npub struct ChildIter<'gc> {\n\n cur_child: Option<DisplayObject<'gc>>,\n\n}\n\n\n", "file_path": "core/src/display_object.rs", "rank": 38, "score": 58200.21572121962 }, { "content": "#[derive(Debug)]\n\nstruct GotoPlaceObject {\n\n /// The frame number that this character was first placed on.\n\n frame: FrameNumber,\n\n /// The display properties of the object.\n\n place_object: swf::PlaceObject,\n\n /// Increasing index of this place command, for sorting.\n\n index: usize,\n\n}\n\n\n\nimpl GotoPlaceObject {\n\n fn new(\n\n frame: FrameNumber,\n\n mut place_object: swf::PlaceObject,\n\n is_rewind: bool,\n\n index: usize,\n\n ) -> Self {\n\n if is_rewind {\n\n if let swf::PlaceObjectAction::Place(_) = place_object.action {\n\n if place_object.matrix.is_none() {\n\n place_object.matrix = Some(Default::default());\n", "file_path": "core/src/display_object/movie_clip.rs", "rank": 39, "score": 56487.36271433295 }, { "content": "export default class RuffleObject extends RufflePlayer {\n\n constructor(...args) {\n\n return super(...args);\n\n }\n\n\n\n connectedCallback() {\n\n super.connectedCallback();\n\n \n\n this.params = RuffleObject.params_of(this);\n\n \n\n //Kick off the SWF download.\n\n if (this.attributes.data) {\n\n this.stream_swf_url(this.attributes.data.value);\n\n } else if (this.params.movie) {\n\n this.stream_swf_url(this.params.movie);\n\n }\n\n }\n\n\n\n get data() {\n\n return this.attributes.data.value;\n\n }\n\n\n\n set data(href) {\n\n this.attributes.data = href;\n\n }\n\n\n\n static is_interdictable(elem) {\n\n return elem.type === FLASH_MIMETYPE || elem.type === FUTURESPLASH_MIMETYPE || elem.attributes.classid.value === FLASH_ACTIVEX_CLASSID;\n\n }\n\n\n\n static params_of(elem) {\n\n let params = {};\n\n\n\n for (let param of elem.children) {\n\n if (param.constructor === HTMLParamElement) {\n\n params[param.name] = param.value;\n\n }\n\n }\n\n\n\n return params;\n\n }\n\n\n\n static from_native_object_element(elem) {\n\n let external_name = register_element(\"ruffle-object\", RuffleObject);\n\n let ruffle_obj = document.createElement(external_name);\n\n for (let attrib of elem.attributes) {\n\n if (attrib.specified) {\n\n ruffle_obj.setAttribute(attrib.name, attrib.value);\n\n }\n\n }\n\n\n\n for (let node of Array.from(elem.children)) {\n\n ruffle_obj.appendChild(node);\n\n }\n\n\n\n return ruffle_obj;\n\n }\n", "file_path": "web/js-src/ruffle-object.js", "rank": 40, "score": 55668.195340168066 }, { "content": " set data(href) {\n\n this.attributes.data = href;\n", "file_path": "web/js-src/ruffle-object.js", "rank": 41, "score": 54872.44711861493 }, { "content": " static params_of(elem) {\n\n let params = {};\n\n\n\n for (let param of elem.children) {\n\n if (param.constructor === HTMLParamElement) {\n\n params[param.name] = param.value;\n\n }\n\n }\n\n\n\n return params;\n", "file_path": "web/js-src/ruffle-object.js", "rank": 42, "score": 54872.44711861493 }, { "content": " constructor(...args) {\n\n return super(...args);\n", "file_path": "web/js-src/ruffle-object.js", "rank": 43, "score": 54872.44711861493 }, { "content": " static is_interdictable(elem) {\n\n return elem.type === FLASH_MIMETYPE || elem.type === FUTURESPLASH_MIMETYPE || elem.attributes.classid.value === FLASH_ACTIVEX_CLASSID;\n", "file_path": "web/js-src/ruffle-object.js", "rank": 44, "score": 54872.44711861493 }, { "content": " connectedCallback() {\n\n super.connectedCallback();\n\n \n\n this.params = RuffleObject.params_of(this);\n\n \n\n //Kick off the SWF download.\n\n if (this.attributes.data) {\n\n this.stream_swf_url(this.attributes.data.value);\n\n } else if (this.params.movie) {\n\n this.stream_swf_url(this.params.movie);\n\n }\n", "file_path": "web/js-src/ruffle-object.js", "rank": 45, "score": 54099.12790899976 }, { "content": " write!(f, \": {}\", source)?;\n\n }\n\n Ok(())\n\n }\n\n Error::IoError(e) => e.fmt(f),\n\n Error::InvalidData(message) => write!(f, \"Invalid data: {}\", message),\n\n Error::Unsupported(message) => write!(f, \"Unsupported data: {}\", message),\n\n }\n\n }\n\n}\n\n\n\nimpl error::Error for Error {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n use std::ops::Deref;\n\n match self {\n\n Error::Avm1ParseError { source, .. } => source.as_ref().map(|s| s.deref()),\n\n Error::IoError(e) => e.source(),\n\n Error::InvalidData(_) => None,\n\n Error::SwfParseError { source, .. } => source.as_ref().map(|s| s.deref()),\n\n Error::Unsupported(_) => None,\n", "file_path": "swf/src/error.rs", "rank": 46, "score": 52838.0403822484 }, { "content": "use std::{borrow, error, fmt, io};\n\n\n\n/// A `Result` from reading SWF data.\n\npub type Result<T> = std::result::Result<T, Error>;\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n /// An error occurred while parsing an AVM1 action.\n\n /// This can contain sub-errors with further information (`Error::source`)\n\n Avm1ParseError {\n\n opcode: u8,\n\n source: Option<Box<dyn error::Error + 'static>>,\n\n },\n\n\n\n /// Invalid or unknown data was encountered.\n\n InvalidData(borrow::Cow<'static, str>),\n\n\n\n /// An error occurred while parsing an SWF tag.\n\n /// This can contain sub-errors with further information (`Error::source`)\n\n SwfParseError {\n", "file_path": "swf/src/error.rs", "rank": 47, "score": 52837.80472698 }, { "content": " #[inline]\n\n pub fn swf_parse_error_with_source(tag_code: u16, source: impl error::Error + 'static) -> Self {\n\n Error::SwfParseError {\n\n tag_code,\n\n source: Some(Box::new(source)),\n\n }\n\n }\n\n /// Helper method to create `Error::Unsupported`.\n\n #[inline]\n\n pub fn unsupported(message: impl Into<borrow::Cow<'static, str>>) -> Self {\n\n Error::Unsupported(message.into())\n\n }\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use crate::num_traits::FromPrimitive;\n\n match self {\n\n Error::Avm1ParseError { opcode, source } => {\n\n let op = crate::avm1::opcode::OpCode::from_u8(*opcode);\n", "file_path": "swf/src/error.rs", "rank": 48, "score": 52837.5849390085 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl From<io::Error> for Error {\n\n fn from(error: io::Error) -> Error {\n\n Error::IoError(error)\n\n }\n\n}\n", "file_path": "swf/src/error.rs", "rank": 49, "score": 52834.47384511368 }, { "content": " tag_code: u16,\n\n source: Option<Box<dyn error::Error + 'static>>,\n\n },\n\n /// An IO error occurred (probably unexpected EOF).\n\n IoError(io::Error),\n\n /// This SWF requires unsupported features.\n\n Unsupported(borrow::Cow<'static, str>),\n\n}\n\n\n\nimpl Error {\n\n /// Helper method to create `Error::Avm1ParseError`.\n\n #[inline]\n\n pub fn avm1_parse_error(opcode: u8) -> Self {\n\n Error::Avm1ParseError {\n\n opcode,\n\n source: None,\n\n }\n\n }\n\n /// Helper method to create `Error::Avm1ParseError`.\n\n #[inline]\n", "file_path": "swf/src/error.rs", "rank": 50, "score": 52834.31539622987 }, { "content": " pub fn avm1_parse_error_with_source(opcode: u8, source: impl error::Error + 'static) -> Self {\n\n Error::Avm1ParseError {\n\n opcode,\n\n source: Some(Box::new(source)),\n\n }\n\n }\n\n /// Helper method to create `Error::InvalidData`.\n\n #[inline]\n\n pub fn invalid_data(message: impl Into<borrow::Cow<'static, str>>) -> Self {\n\n Error::InvalidData(message.into())\n\n }\n\n /// Helper method to create `Error::SwfParseError`.\n\n #[inline]\n\n pub fn swf_parse_error(tag_code: u16) -> Self {\n\n Error::SwfParseError {\n\n tag_code,\n\n source: None,\n\n }\n\n }\n\n /// Helper method to create `Error::SwfParseError`.\n", "file_path": "swf/src/error.rs", "rank": 51, "score": 52834.280023591215 }, { "content": " \"Error parsing AVM1 action \".fmt(f)?;\n\n if let Some(op) = op {\n\n write!(f, \"{:?}\", op)?;\n\n } else {\n\n write!(f, \"Unknown({})\", opcode)?;\n\n };\n\n if let Some(source) = source {\n\n write!(f, \": {}\", source)?;\n\n }\n\n Ok(())\n\n }\n\n Error::SwfParseError { tag_code, source } => {\n\n let tag = crate::tag_code::TagCode::from_u16(*tag_code);\n\n \"Error parsing SWF tag \".fmt(f)?;\n\n if let Some(tag) = tag {\n\n write!(f, \"{:?}\", tag)?;\n\n } else {\n\n write!(f, \"Unknown({})\", tag_code)?;\n\n };\n\n if let Some(source) = source {\n", "file_path": "swf/src/error.rs", "rank": 52, "score": 52833.50982111729 }, { "content": "//! Error types used in XML handling\n\n\n\nuse gc_arena::{Collect, CollectionContext};\n\nuse quick_xml::Error as QXError;\n\nuse std::error::Error as StdError;\n\nuse std::fmt::Error as FmtError;\n\nuse std::fmt::{Display, Formatter};\n\nuse std::rc::Rc;\n\n\n\n/// Boxed error type.\n\npub type Error = Box<dyn std::error::Error>;\n\n\n\n/// Boxed `quick_xml` error\n\n///\n\n/// We can't clone `quick_xml` errors, nor can we clone several of the error\n\n/// types it wraps over, so this creates an RC boxed version of the error that\n\n/// can then be used elsewhere.\n\n#[derive(Clone, Debug)]\n\npub struct ParseError(Rc<QXError>);\n\n\n", "file_path": "core/src/xml/error.rs", "rank": 53, "score": 51457.85692364501 }, { "content": "unsafe impl Collect for ParseError {\n\n /// ParseError does not contain GC pointers.\n\n fn trace(&self, _cc: CollectionContext<'_>) {}\n\n}\n\n\n\nimpl ParseError {\n\n ///Convert a quick_xml error into a `ParseError`.\n\n pub fn from_quickxml_error(err: QXError) -> Self {\n\n ParseError(Rc::new(err))\n\n }\n\n\n\n pub fn ref_error(&self) -> &QXError {\n\n &*self.0\n\n }\n\n}\n\n\n\nimpl Display for ParseError {\n\n fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), FmtError> {\n\n self.0.fmt(fmt)\n\n }\n", "file_path": "core/src/xml/error.rs", "rank": 54, "score": 51451.15574177354 }, { "content": "}\n\n\n\nimpl StdError for ParseError {\n\n #[allow(deprecated)]\n\n fn cause(&self) -> Option<&dyn StdError> {\n\n self.0.cause()\n\n }\n\n\n\n fn source(&self) -> Option<&(dyn StdError + 'static)> {\n\n self.0.source()\n\n }\n\n}\n", "file_path": "core/src/xml/error.rs", "rank": 55, "score": 51450.8079321846 }, { "content": "use crate::avm1::return_value::ReturnValue;\n\nuse crate::avm1::{Avm1, Error, Object, TObject, UpdateContext};\n\nuse std::f64::NAN;\n\n\n\n#[derive(Debug, Clone)]\n\n#[allow(dead_code)]\n\npub enum Value<'gc> {\n\n Undefined,\n\n Null,\n\n Bool(bool),\n\n Number(f64),\n\n String(String),\n\n Object(Object<'gc>),\n\n}\n\n\n\nimpl<'gc> From<String> for Value<'gc> {\n\n fn from(string: String) -> Self {\n\n Value::String(string)\n\n }\n\n}\n", "file_path": "core/src/avm1/value.rs", "rank": 56, "score": 51346.82878035968 }, { "content": " }\n\n\n\n pub fn as_string(&self) -> Result<&String, Error> {\n\n match self {\n\n Value::String(s) => Ok(s),\n\n _ => Err(format!(\"Expected String, found {:?}\", self).into()),\n\n }\n\n }\n\n\n\n pub fn as_object(&self) -> Result<Object<'gc>, Error> {\n\n if let Value::Object(object) = self {\n\n Ok(*object)\n\n } else {\n\n Err(format!(\"Expected Object, found {:?}\", self).into())\n\n }\n\n }\n\n\n\n pub fn call(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n", "file_path": "core/src/avm1/value.rs", "rank": 57, "score": 51342.072246434545 }, { "content": " context: &mut UpdateContext<'_, 'gc, '_>,\n\n this: Object<'gc>,\n\n args: &[Value<'gc>],\n\n ) -> Result<ReturnValue<'gc>, Error> {\n\n if let Value::Object(object) = self {\n\n object.call(avm, context, this, args)\n\n } else {\n\n Ok(Value::Undefined.into())\n\n }\n\n }\n\n}\n\n\n\n/// Converts an `f64` to a String with (hopefully) the same output as Flash.\n\n/// For example, NAN returns `\"NaN\"`, and infinity returns `\"Infinity\"`.\n", "file_path": "core/src/avm1/value.rs", "rank": 58, "score": 51340.77010384598 }, { "content": " ) -> Result<ReturnValue<'gc>, Error> {\n\n Ok(5.0.into())\n\n }\n\n\n\n let valueof = FunctionObject::function(\n\n context.gc_context,\n\n Executable::Native(value_of_impl),\n\n Some(protos.function),\n\n None,\n\n );\n\n\n\n let o = ScriptObject::object_cell(context.gc_context, Some(protos.object));\n\n o.define_value(\n\n context.gc_context,\n\n \"valueOf\",\n\n valueof.into(),\n\n EnumSet::empty(),\n\n );\n\n\n\n assert_eq!(\n", "file_path": "core/src/avm1/value.rs", "rank": 59, "score": 51340.56165935706 }, { "content": " /// return `undefined` rather than yielding a runtime error.\n\n pub fn to_primitive_num(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<Value<'gc>, Error> {\n\n Ok(match self {\n\n Value::Object(object) => {\n\n let value_of_impl = object.get(\"valueOf\", avm, context)?.resolve(avm, context)?;\n\n\n\n let fake_args = Vec::new();\n\n value_of_impl\n\n .call(avm, context, *object, &fake_args)?\n\n .resolve(avm, context)?\n\n }\n\n val => val.to_owned(),\n\n })\n\n }\n\n\n\n /// ECMA-262 2nd edition s. 11.8.5 Abstract relational comparison algorithm\n", "file_path": "core/src/avm1/value.rs", "rank": 60, "score": 51339.638855890254 }, { "content": " /// The value will be wrapped in the range [-2^31, 2^31).\n\n /// This will call `valueOf` and do any conversions that are necessary.\n\n #[allow(dead_code)]\n\n pub fn coerce_to_u32(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<u32, Error> {\n\n self.as_number(avm, context).map(f64_to_wrapping_u32)\n\n }\n\n\n\n /// Coerce a value to a string.\n\n pub fn coerce_to_string(\n\n self,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<String, Error> {\n\n Ok(match self {\n\n Value::Object(object) => {\n\n let to_string_impl = object\n", "file_path": "core/src/avm1/value.rs", "rank": 61, "score": 51339.38867172692 }, { "content": " context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<f64, Error> {\n\n Ok(match self {\n\n Value::Object(_) => self\n\n .to_primitive_num(avm, context)?\n\n .primitive_as_number(avm, context),\n\n val => val.primitive_as_number(avm, context),\n\n })\n\n }\n\n\n\n /// ECMA-262 2nd edition s. 9.1 ToPrimitive (hint: Number)\n\n ///\n\n /// Flash diverges from spec in a number of ways. These ways are, as far as\n\n /// we are aware, version-gated:\n\n ///\n\n /// * `toString` is never called when `ToPrimitive` is invoked with number\n\n /// hint.\n\n /// * Objects with uncallable `valueOf` implementations are coerced to\n\n /// `undefined`. This is not a special-cased behavior: All values are\n\n /// callable in `AVM1`. Values that are not callable objects instead\n", "file_path": "core/src/avm1/value.rs", "rank": 62, "score": 51339.03636128343 }, { "content": " return Ok(true.into());\n\n }\n\n\n\n Ok(false.into())\n\n }\n\n (Value::String(a), Value::String(b)) => Ok((a == b).into()),\n\n (Value::Bool(a), Value::Bool(b)) => Ok((a == b).into()),\n\n (Value::Object(a), Value::Object(b)) => Ok(Object::ptr_eq(*a, *b).into()),\n\n (Value::Object(a), Value::Null) | (Value::Object(a), Value::Undefined) => {\n\n Ok(Object::ptr_eq(*a, avm.global_object_cell()).into())\n\n }\n\n (Value::Null, Value::Object(b)) | (Value::Undefined, Value::Object(b)) => {\n\n Ok(Object::ptr_eq(*b, avm.global_object_cell()).into())\n\n }\n\n (Value::Undefined, Value::Null) => Ok(true.into()),\n\n (Value::Null, Value::Undefined) => Ok(true.into()),\n\n (Value::Number(_), Value::String(_)) => Ok(self.abstract_eq(\n\n Value::Number(other.as_number(avm, context)?),\n\n avm,\n\n context,\n", "file_path": "core/src/avm1/value.rs", "rank": 63, "score": 51338.35019628288 }, { "content": " if let Value::Object(_) = non_obj_self {\n\n return Ok(false.into());\n\n }\n\n\n\n Ok(non_obj_self.abstract_eq(other, avm, context, true)?)\n\n }\n\n _ => Ok(false.into()),\n\n }\n\n }\n\n\n\n /// Converts a bool value into the appropriate value for the platform.\n\n /// This should be used when pushing a bool onto the stack.\n\n /// This handles SWFv4 pushing a Number, 0 or 1.\n\n pub fn from_bool(value: bool, swf_version: u8) -> Value<'gc> {\n\n // SWF version 4 did not have true bools and will push bools as 0 or 1.\n\n // e.g. SWF19 p. 72:\n\n // \"If the numbers are equal, true is pushed to the stack for SWF 5 and later. For SWF 4, 1 is pushed to the stack.\"\n\n if swf_version >= 5 {\n\n Value::Bool(value)\n\n } else {\n", "file_path": "core/src/avm1/value.rs", "rank": 64, "score": 51338.26885643691 }, { "content": " Value::String(other_value) => value == other_value,\n\n _ => false,\n\n },\n\n Value::Object(value) => match other {\n\n Value::Object(other_value) => Object::ptr_eq(*value, *other_value),\n\n _ => false,\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl<'gc> Value<'gc> {\n\n pub fn into_number_v1(self) -> f64 {\n\n match self {\n\n Value::Bool(true) => 1.0,\n\n Value::Number(v) => v,\n\n Value::String(v) => v.parse().unwrap_or(0.0),\n\n _ => 0.0,\n\n }\n\n }\n", "file_path": "core/src/avm1/value.rs", "rank": 65, "score": 51337.67688871169 }, { "content": "\n\nimpl<'gc> From<&str> for Value<'gc> {\n\n fn from(string: &str) -> Self {\n\n Value::String(string.to_owned())\n\n }\n\n}\n\n\n\nimpl<'gc> From<bool> for Value<'gc> {\n\n fn from(value: bool) -> Self {\n\n Value::Bool(value)\n\n }\n\n}\n\n\n\nimpl<'gc, T> From<T> for Value<'gc>\n\nwhere\n\n Object<'gc>: From<T>,\n\n{\n\n fn from(value: T) -> Self {\n\n Value::Object(Object::from(value))\n\n }\n", "file_path": "core/src/avm1/value.rs", "rank": 66, "score": 51337.48181450617 }, { "content": " avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<i16, Error> {\n\n self.as_number(avm, context).map(f64_to_wrapping_i16)\n\n }\n\n\n\n /// Coerce a number to an `i32` following the ECMAScript specifications for `ToInt32`.\n\n /// The value will be wrapped modulo 2^32.\n\n /// This will call `valueOf` and do any conversions that are necessary.\n\n /// If you are writing AVM code that accepts an integer, you probably want to use this.\n\n #[allow(dead_code)]\n\n pub fn coerce_to_i32(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<i32, Error> {\n\n self.as_number(avm, context).map(f64_to_wrapping_i32)\n\n }\n\n\n\n /// Coerce a number to an `u32` following the ECMAScript specifications for `ToUInt32`.\n", "file_path": "core/src/avm1/value.rs", "rank": 67, "score": 51337.28916269149 }, { "content": " Ok(self.abstract_eq(non_obj_other, avm, context, true)?)\n\n }\n\n (Value::Number(_), Value::Object(_)) => {\n\n let non_obj_other = other.to_primitive_num(avm, context)?;\n\n if let Value::Object(_) = non_obj_other {\n\n return Ok(false.into());\n\n }\n\n\n\n Ok(self.abstract_eq(non_obj_other, avm, context, true)?)\n\n }\n\n (Value::Object(_), Value::String(_)) => {\n\n let non_obj_self = self.to_primitive_num(avm, context)?;\n\n if let Value::Object(_) = non_obj_self {\n\n return Ok(false.into());\n\n }\n\n\n\n Ok(non_obj_self.abstract_eq(other, avm, context, true)?)\n\n }\n\n (Value::Object(_), Value::Number(_)) => {\n\n let non_obj_self = self.to_primitive_num(avm, context)?;\n", "file_path": "core/src/avm1/value.rs", "rank": 68, "score": 51337.21710576037 }, { "content": " let bo = Value::Object(ScriptObject::bare_object(context.gc_context).into());\n\n\n\n assert_eq!(bo.as_number(avm, context).unwrap(), 0.0);\n\n });\n\n }\n\n\n\n #[test]\n\n fn abstract_lt_num() {\n\n with_avm(8, |avm, context, _this| {\n\n let a = Value::Number(1.0);\n\n let b = Value::Number(2.0);\n\n\n\n assert_eq!(a.abstract_lt(b, avm, context).unwrap(), Value::Bool(true));\n\n\n\n let nan = Value::Number(NAN);\n\n assert_eq!(a.abstract_lt(nan, avm, context).unwrap(), Value::Undefined);\n\n\n\n let inf = Value::Number(INFINITY);\n\n assert_eq!(a.abstract_lt(inf, avm, context).unwrap(), Value::Bool(true));\n\n\n", "file_path": "core/src/avm1/value.rs", "rank": 69, "score": 51336.61869785074 }, { "content": " true,\n\n )?),\n\n (Value::String(_), Value::Number(_)) => {\n\n Ok(Value::Number(self.as_number(avm, context)?)\n\n .abstract_eq(other, avm, context, true)?)\n\n }\n\n (Value::Bool(_), _) => Ok(Value::Number(self.as_number(avm, context)?)\n\n .abstract_eq(other, avm, context, true)?),\n\n (_, Value::Bool(_)) => Ok(self.abstract_eq(\n\n Value::Number(other.as_number(avm, context)?),\n\n avm,\n\n context,\n\n true,\n\n )?),\n\n (Value::String(_), Value::Object(_)) => {\n\n let non_obj_other = other.to_primitive_num(avm, context)?;\n\n if let Value::Object(_) = non_obj_other {\n\n return Ok(false.into());\n\n }\n\n\n", "file_path": "core/src/avm1/value.rs", "rank": 70, "score": 51336.37371600689 }, { "content": " let bo = Value::Object(ScriptObject::bare_object(context.gc_context).into());\n\n\n\n assert!(bo.as_number(avm, context).unwrap().is_nan());\n\n });\n\n }\n\n\n\n #[test]\n\n #[allow(clippy::float_cmp)]\n\n fn to_number_swf6() {\n\n with_avm(6, |avm, context, _this| {\n\n let t = Value::Bool(true);\n\n let u = Value::Undefined;\n\n let f = Value::Bool(false);\n\n let n = Value::Null;\n\n\n\n assert_eq!(t.as_number(avm, context).unwrap(), 1.0);\n\n assert_eq!(u.as_number(avm, context).unwrap(), 0.0);\n\n assert_eq!(f.as_number(avm, context).unwrap(), 0.0);\n\n assert_eq!(n.as_number(avm, context).unwrap(), 0.0);\n\n\n", "file_path": "core/src/avm1/value.rs", "rank": 71, "score": 51336.341537981716 }, { "content": " if swf_version >= 7 {\n\n !v.is_empty()\n\n } else {\n\n let num = v.parse().unwrap_or(0.0);\n\n num != 0.0\n\n }\n\n }\n\n Value::Object(_) => true,\n\n _ => false,\n\n }\n\n }\n\n\n\n pub fn type_of(&self) -> Value<'gc> {\n\n Value::String(\n\n match self {\n\n Value::Undefined => \"undefined\",\n\n Value::Null => \"null\",\n\n Value::Number(_) => \"number\",\n\n Value::Bool(_) => \"boolean\",\n\n Value::String(_) => \"string\",\n", "file_path": "core/src/avm1/value.rs", "rank": 72, "score": 51335.90831049395 }, { "content": " let t = Value::Bool(true);\n\n let u = Value::Undefined;\n\n let f = Value::Bool(false);\n\n let n = Value::Null;\n\n\n\n assert_eq!(t.to_primitive_num(avm, context).unwrap(), t);\n\n assert_eq!(u.to_primitive_num(avm, context).unwrap(), u);\n\n assert_eq!(f.to_primitive_num(avm, context).unwrap(), f);\n\n assert_eq!(n.to_primitive_num(avm, context).unwrap(), n);\n\n\n\n let (protos, global, _) = create_globals(context.gc_context);\n\n let vglobal = Value::Object(global);\n\n\n\n assert_eq!(vglobal.to_primitive_num(avm, context).unwrap(), u);\n\n\n\n fn value_of_impl<'gc>(\n\n _: &mut Avm1<'gc>,\n\n _: &mut UpdateContext<'_, 'gc, '_>,\n\n _: Object<'gc>,\n\n _: &[Value<'gc>],\n", "file_path": "core/src/avm1/value.rs", "rank": 73, "score": 51335.744820093874 }, { "content": " Value::Number(if value { 1.0 } else { 0.0 })\n\n }\n\n }\n\n\n\n /// Coerce a value to a string without calling object methods.\n\n pub fn into_string(self, swf_version: u8) -> String {\n\n match self {\n\n Value::Undefined => {\n\n if swf_version >= 7 {\n\n \"undefined\".to_string()\n\n } else {\n\n \"\".to_string()\n\n }\n\n }\n\n Value::Null => \"null\".to_string(),\n\n Value::Bool(v) => v.to_string(),\n\n Value::Number(v) => f64_to_string(v),\n\n Value::String(v) => v,\n\n Value::Object(object) => object.as_string(),\n\n }\n", "file_path": "core/src/avm1/value.rs", "rank": 74, "score": 51335.69820578312 }, { "content": " Value::Number(f64::from(value))\n\n }\n\n}\n\n\n\nimpl<'gc> From<usize> for Value<'gc> {\n\n fn from(value: usize) -> Self {\n\n Value::Number(value as f64)\n\n }\n\n}\n\n\n\nunsafe impl<'gc> gc_arena::Collect for Value<'gc> {\n\n fn trace(&self, cc: gc_arena::CollectionContext) {\n\n if let Value::Object(object) = self {\n\n object.trace(cc);\n\n }\n\n }\n\n}\n\n\n\nimpl PartialEq for Value<'_> {\n\n fn eq(&self, other: &Self) -> bool {\n", "file_path": "core/src/avm1/value.rs", "rank": 75, "score": 51335.62450752817 }, { "content": " pub fn abstract_eq(\n\n &self,\n\n other: Value<'gc>,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n coerced: bool,\n\n ) -> Result<Value<'gc>, Error> {\n\n match (self, &other) {\n\n (Value::Undefined, Value::Undefined) => Ok(true.into()),\n\n (Value::Null, Value::Null) => Ok(true.into()),\n\n (Value::Number(a), Value::Number(b)) => {\n\n if !coerced && a.is_nan() && b.is_nan() {\n\n return Ok(true.into());\n\n }\n\n\n\n if a == b {\n\n return Ok(true.into());\n\n }\n\n\n\n if *a == 0.0 && *b == -0.0 || *a == -0.0 && *b == 0.0 {\n", "file_path": "core/src/avm1/value.rs", "rank": 76, "score": 51335.50097703921 }, { "content": " Value::Object(o).to_primitive_num(avm, context).unwrap(),\n\n Value::Number(5.0)\n\n );\n\n });\n\n }\n\n\n\n #[test]\n\n #[allow(clippy::float_cmp)]\n\n fn to_number_swf7() {\n\n with_avm(7, |avm, context, _this| {\n\n let t = Value::Bool(true);\n\n let u = Value::Undefined;\n\n let f = Value::Bool(false);\n\n let n = Value::Null;\n\n\n\n assert_eq!(t.as_number(avm, context).unwrap(), 1.0);\n\n assert!(u.as_number(avm, context).unwrap().is_nan());\n\n assert_eq!(f.as_number(avm, context).unwrap(), 0.0);\n\n assert!(n.as_number(avm, context).unwrap().is_nan());\n\n\n", "file_path": "core/src/avm1/value.rs", "rank": 77, "score": 51334.90700085221 }, { "content": " .get(\"toString\", avm, context)?\n\n .resolve(avm, context)?;\n\n let fake_args = Vec::new();\n\n match to_string_impl\n\n .call(avm, context, object, &fake_args)?\n\n .resolve(avm, context)?\n\n {\n\n Value::String(s) => s,\n\n _ => \"[type Object]\".to_string(),\n\n }\n\n }\n\n _ => self.into_string(avm.current_swf_version()),\n\n })\n\n }\n\n\n\n pub fn as_bool(&self, swf_version: u8) -> bool {\n\n match self {\n\n Value::Bool(v) => *v,\n\n Value::Number(v) => !v.is_nan() && *v != 0.0,\n\n Value::String(v) => {\n", "file_path": "core/src/avm1/value.rs", "rank": 78, "score": 51334.81829593779 }, { "content": " /// (see https://github.com/rust-lang/rust/issues/10184)\n\n #[allow(clippy::unreadable_literal)]\n\n pub fn as_u32(&self) -> Result<u32, Error> {\n\n self.as_f64().map(f64_to_wrapping_u32)\n\n }\n\n\n\n pub fn as_i64(&self) -> Result<i64, Error> {\n\n self.as_f64().map(|n| n as i64)\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub fn as_usize(&self) -> Result<usize, Error> {\n\n self.as_f64().map(|n| n as usize)\n\n }\n\n\n\n pub fn as_f64(&self) -> Result<f64, Error> {\n\n match *self {\n\n Value::Number(v) => Ok(v),\n\n _ => Err(format!(\"Expected Number, found {:?}\", self).into()),\n\n }\n", "file_path": "core/src/avm1/value.rs", "rank": 79, "score": 51334.4909269301 }, { "content": " Value::Object(object) => object.type_of(),\n\n }\n\n .to_string(),\n\n )\n\n }\n\n\n\n /// Casts a Number into an `i32` following the ECMA-262 `ToInt32` specs.\n\n /// The number will have 32-bit wrapping semantics if it is outside the range of an `i32`.\n\n /// NaN and Infinities will return 0.\n\n /// This is written to avoid undefined behavior when casting out-of-bounds floats to ints in Rust.\n\n /// (see https://github.com/rust-lang/rust/issues/10184)\n\n #[allow(clippy::unreadable_literal)]\n\n pub fn as_i32(&self) -> Result<i32, Error> {\n\n self.as_f64().map(f64_to_wrapping_i32)\n\n }\n\n\n\n /// Casts a Number into an `i32` following the ECMA-262 `ToUInt32` specs.\n\n /// The number will have 32-bit wrapping semantics if it is outside the range of an `u32`.\n\n /// NaN and Infinities will return 0.\n\n /// This is written to avoid undefined behavior when casting out-of-bounds floats to ints in Rust.\n", "file_path": "core/src/avm1/value.rs", "rank": 80, "score": 51334.43604921476 }, { "content": " #[allow(clippy::float_cmp)]\n\n pub fn abstract_lt(\n\n &self,\n\n other: Value<'gc>,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<Value<'gc>, Error> {\n\n let prim_self = self.to_primitive_num(avm, context)?;\n\n let prim_other = other.to_primitive_num(avm, context)?;\n\n\n\n if let (Value::String(a), Value::String(b)) = (&prim_self, &prim_other) {\n\n return Ok(a.to_string().bytes().lt(b.to_string().bytes()).into());\n\n }\n\n\n\n let num_self = prim_self.primitive_as_number(avm, context);\n\n let num_other = prim_other.primitive_as_number(avm, context);\n\n\n\n if num_self.is_nan() || num_other.is_nan() {\n\n return Ok(Value::Undefined);\n\n }\n", "file_path": "core/src/avm1/value.rs", "rank": 81, "score": 51334.268607202495 }, { "content": "\n\n #[test]\n\n fn abstract_gt_str() {\n\n with_avm(8, |avm, context, _this| {\n\n let a = Value::String(\"a\".to_owned());\n\n let b = Value::String(\"b\".to_owned());\n\n\n\n assert_eq!(b.abstract_lt(a, avm, context).unwrap(), Value::Bool(false))\n\n })\n\n }\n\n\n\n #[test]\n\n #[allow(clippy::unreadable_literal)]\n\n\n\n fn wrapping_u16() {\n\n use super::f64_to_wrapping_u16;\n\n assert_eq!(f64_to_wrapping_u16(0.0), 0);\n\n assert_eq!(f64_to_wrapping_u16(1.0), 1);\n\n assert_eq!(f64_to_wrapping_u16(-1.0), 65535);\n\n assert_eq!(f64_to_wrapping_u16(123.1), 123);\n", "file_path": "core/src/avm1/value.rs", "rank": 82, "score": 51334.112289869685 }, { "content": " }\n\n\n\n /// Coerce a number to an `u16` following the ECMAScript specifications for `ToUInt16`.\n\n /// The value will be wrapped modulo 2^16.\n\n /// This will call `valueOf` and do any conversions that are necessary.\n\n #[allow(dead_code)]\n\n pub fn coerce_to_u16(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n\n context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> Result<u16, Error> {\n\n self.as_number(avm, context).map(f64_to_wrapping_u16)\n\n }\n\n\n\n /// Coerce a number to an `i16` following the wrapping behavior ECMAScript specifications.\n\n /// The value will be wrapped in the range [-2^15, 2^15).\n\n /// This will call `valueOf` and do any conversions that are necessary.\n\n #[allow(dead_code)]\n\n pub fn coerce_to_i16(\n\n &self,\n", "file_path": "core/src/avm1/value.rs", "rank": 83, "score": 51334.03452164998 }, { "content": " b'c' | b'C' => 12,\n\n b'd' | b'D' => 13,\n\n b'e' | b'E' => 14,\n\n b'f' | b'F' => 15,\n\n _ => return NAN,\n\n }\n\n }\n\n f64::from(n as i32)\n\n }\n\n \"\" => NAN,\n\n _ => v.trim_start().parse().unwrap_or(NAN),\n\n },\n\n Value::Object(_) => NAN,\n\n }\n\n }\n\n\n\n /// ECMA-262 2nd edition s. 9.3 ToNumber\n\n pub fn as_number(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n", "file_path": "core/src/avm1/value.rs", "rank": 84, "score": 51333.84111904859 }, { "content": " match self {\n\n Value::Undefined => match other {\n\n Value::Undefined => true,\n\n _ => false,\n\n },\n\n Value::Null => match other {\n\n Value::Null => true,\n\n _ => false,\n\n },\n\n Value::Bool(value) => match other {\n\n Value::Bool(other_value) => value == other_value,\n\n _ => false,\n\n },\n\n Value::Number(value) => match other {\n\n Value::Number(other_value) => {\n\n (value == other_value) || (value.is_nan() && other_value.is_nan())\n\n }\n\n _ => false,\n\n },\n\n Value::String(value) => match other {\n", "file_path": "core/src/avm1/value.rs", "rank": 85, "score": 51331.74553446315 }, { "content": "impl<'gc> From<i16> for Value<'gc> {\n\n fn from(value: i16) -> Self {\n\n Value::Number(f64::from(value))\n\n }\n\n}\n\n\n\nimpl<'gc> From<u16> for Value<'gc> {\n\n fn from(value: u16) -> Self {\n\n Value::Number(f64::from(value))\n\n }\n\n}\n\n\n\nimpl<'gc> From<i32> for Value<'gc> {\n\n fn from(value: i32) -> Self {\n\n Value::Number(f64::from(value))\n\n }\n\n}\n\n\n\nimpl<'gc> From<u32> for Value<'gc> {\n\n fn from(value: u32) -> Self {\n", "file_path": "core/src/avm1/value.rs", "rank": 86, "score": 51331.620402745524 }, { "content": "}\n\n\n\nimpl<'gc> From<f64> for Value<'gc> {\n\n fn from(value: f64) -> Self {\n\n Value::Number(value)\n\n }\n\n}\n\n\n\nimpl<'gc> From<f32> for Value<'gc> {\n\n fn from(value: f32) -> Self {\n\n Value::Number(f64::from(value))\n\n }\n\n}\n\n\n\nimpl<'gc> From<u8> for Value<'gc> {\n\n fn from(value: u8) -> Self {\n\n Value::Number(f64::from(value))\n\n }\n\n}\n\n\n", "file_path": "core/src/avm1/value.rs", "rank": 87, "score": 51331.614570091675 }, { "content": " Value::Bool(true)\n\n );\n\n\n\n let zero = Value::Number(0.0);\n\n assert_eq!(\n\n zero.abstract_lt(a, avm, context).unwrap(),\n\n Value::Bool(true)\n\n );\n\n });\n\n }\n\n\n\n #[test]\n\n fn abstract_lt_str() {\n\n with_avm(8, |avm, context, _this| {\n\n let a = Value::String(\"a\".to_owned());\n\n let b = Value::String(\"b\".to_owned());\n\n\n\n assert_eq!(a.abstract_lt(b, avm, context).unwrap(), Value::Bool(true))\n\n })\n\n }\n", "file_path": "core/src/avm1/value.rs", "rank": 88, "score": 51331.17500192709 }, { "content": " let neg_inf = Value::Number(NEG_INFINITY);\n\n assert_eq!(\n\n a.abstract_lt(neg_inf, avm, context).unwrap(),\n\n Value::Bool(false)\n\n );\n\n\n\n let zero = Value::Number(0.0);\n\n assert_eq!(\n\n a.abstract_lt(zero, avm, context).unwrap(),\n\n Value::Bool(false)\n\n );\n\n });\n\n }\n\n\n\n #[test]\n\n fn abstract_gt_num() {\n\n with_avm(8, |avm, context, _this| {\n\n let a = Value::Number(1.0);\n\n let b = Value::Number(2.0);\n\n\n", "file_path": "core/src/avm1/value.rs", "rank": 89, "score": 51331.13989130303 }, { "content": " assert_eq!(\n\n b.abstract_lt(a.clone(), avm, context).unwrap(),\n\n Value::Bool(false)\n\n );\n\n\n\n let nan = Value::Number(NAN);\n\n assert_eq!(\n\n nan.abstract_lt(a.clone(), avm, context).unwrap(),\n\n Value::Undefined\n\n );\n\n\n\n let inf = Value::Number(INFINITY);\n\n assert_eq!(\n\n inf.abstract_lt(a.clone(), avm, context).unwrap(),\n\n Value::Bool(false)\n\n );\n\n\n\n let neg_inf = Value::Number(NEG_INFINITY);\n\n assert_eq!(\n\n neg_inf.abstract_lt(a.clone(), avm, context).unwrap(),\n", "file_path": "core/src/avm1/value.rs", "rank": 90, "score": 51330.96973810158 }, { "content": " Value::Bool(true) => 1.0,\n\n Value::Number(v) => *v,\n\n Value::String(v) => match v.as_str() {\n\n v if avm.current_swf_version() >= 6 && v.starts_with(\"0x\") => {\n\n let mut n: u32 = 0;\n\n for c in v[2..].bytes() {\n\n n = n.wrapping_shl(4);\n\n n |= match c {\n\n b'0' => 0,\n\n b'1' => 1,\n\n b'2' => 2,\n\n b'3' => 3,\n\n b'4' => 4,\n\n b'5' => 5,\n\n b'6' => 6,\n\n b'7' => 7,\n\n b'8' => 8,\n\n b'9' => 9,\n\n b'a' | b'A' => 10,\n\n b'b' | b'B' => 11,\n", "file_path": "core/src/avm1/value.rs", "rank": 91, "score": 51330.87065413038 }, { "content": "\n\n /// ECMA-262 2nd edtion s. 9.3 ToNumber (after calling `to_primitive_num`)\n\n ///\n\n /// Flash diverges from spec in a number of ways. These ways are, as far as\n\n /// we are aware, version-gated:\n\n ///\n\n /// * In SWF6 and lower, `undefined` is coerced to `0.0` (like `false`)\n\n /// rather than `NaN` as required by spec.\n\n /// * In SWF5 and lower, hexadecimal is unsupported.\n\n fn primitive_as_number(\n\n &self,\n\n avm: &mut Avm1<'gc>,\n\n _context: &mut UpdateContext<'_, 'gc, '_>,\n\n ) -> f64 {\n\n match self {\n\n Value::Undefined if avm.current_swf_version() < 7 => 0.0,\n\n Value::Null if avm.current_swf_version() < 7 => 0.0,\n\n Value::Undefined => NAN,\n\n Value::Null => NAN,\n\n Value::Bool(false) => 0.0,\n", "file_path": "core/src/avm1/value.rs", "rank": 92, "score": 51330.69235412943 }, { "content": " }\n\n\n\n #[test]\n\n #[allow(clippy::unreadable_literal)]\n\n fn wrapping_i32() {\n\n use super::f64_to_wrapping_i32;\n\n assert_eq!(f64_to_wrapping_i32(0.0), 0);\n\n assert_eq!(f64_to_wrapping_i32(1.0), 1);\n\n assert_eq!(f64_to_wrapping_i32(-1.0), -1);\n\n assert_eq!(f64_to_wrapping_i32(123.1), 123);\n\n assert_eq!(f64_to_wrapping_i32(4294968295.9), 999);\n\n assert_eq!(f64_to_wrapping_i32(2147484648.3), -2147482648);\n\n assert_eq!(f64_to_wrapping_i32(-8589934591.2), 1);\n\n assert_eq!(f64_to_wrapping_i32(4294966896.1), -400);\n\n assert_eq!(f64_to_wrapping_i32(std::f64::NAN), 0);\n\n assert_eq!(f64_to_wrapping_i32(std::f64::INFINITY), 0);\n\n assert_eq!(f64_to_wrapping_i32(std::f64::NEG_INFINITY), 0);\n\n }\n\n\n\n #[test]\n", "file_path": "core/src/avm1/value.rs", "rank": 93, "score": 51327.917674104625 }, { "content": " assert_eq!(f64_to_wrapping_u16(66535.9), 999);\n\n assert_eq!(f64_to_wrapping_u16(-9980.7), 55556);\n\n assert_eq!(f64_to_wrapping_u16(-196608.0), 0);\n\n assert_eq!(f64_to_wrapping_u16(std::f64::NAN), 0);\n\n assert_eq!(f64_to_wrapping_u16(std::f64::INFINITY), 0);\n\n assert_eq!(f64_to_wrapping_u16(std::f64::NEG_INFINITY), 0);\n\n }\n\n\n\n #[test]\n\n #[allow(clippy::unreadable_literal)]\n\n\n\n fn wrapping_i16() {\n\n use super::f64_to_wrapping_i16;\n\n assert_eq!(f64_to_wrapping_i16(0.0), 0);\n\n assert_eq!(f64_to_wrapping_i16(1.0), 1);\n\n assert_eq!(f64_to_wrapping_i16(-1.0), -1);\n\n assert_eq!(f64_to_wrapping_i16(123.1), 123);\n\n assert_eq!(f64_to_wrapping_i16(32768.9), -32768);\n\n assert_eq!(f64_to_wrapping_i16(-32769.9), 32767);\n\n assert_eq!(f64_to_wrapping_i16(-33268.1), 32268);\n", "file_path": "core/src/avm1/value.rs", "rank": 94, "score": 51327.760650376156 }, { "content": " fn f64_to_string() {\n\n use super::f64_to_string;\n\n assert_eq!(f64_to_string(0.0), \"0\");\n\n assert_eq!(f64_to_string(-0.0), \"0\");\n\n assert_eq!(f64_to_string(1.0), \"1\");\n\n assert_eq!(f64_to_string(1.4), \"1.4\");\n\n assert_eq!(f64_to_string(-990.123), \"-990.123\");\n\n assert_eq!(f64_to_string(std::f64::NAN), \"NaN\");\n\n assert_eq!(f64_to_string(std::f64::INFINITY), \"Infinity\");\n\n assert_eq!(f64_to_string(std::f64::NEG_INFINITY), \"-Infinity\");\n\n assert_eq!(f64_to_string(9.9999e14), \"999990000000000\");\n\n assert_eq!(f64_to_string(-9.9999e14), \"-999990000000000\");\n\n assert_eq!(f64_to_string(1e15), \"1e+15\");\n\n assert_eq!(f64_to_string(-1e15), \"-1e+15\");\n\n assert_eq!(f64_to_string(1e-5), \"0.00001\");\n\n assert_eq!(f64_to_string(-1e-5), \"-0.00001\");\n\n assert_eq!(f64_to_string(0.999e-5), \"9.99e-6\");\n\n assert_eq!(f64_to_string(-0.999e-5), \"-9.99e-6\");\n\n }\n\n}\n", "file_path": "core/src/avm1/value.rs", "rank": 95, "score": 51327.74408990423 }, { "content": " assert_eq!(f64_to_wrapping_i16(-196608.0), 0);\n\n assert_eq!(f64_to_wrapping_i16(std::f64::NAN), 0);\n\n assert_eq!(f64_to_wrapping_i16(std::f64::INFINITY), 0);\n\n assert_eq!(f64_to_wrapping_i16(std::f64::NEG_INFINITY), 0);\n\n }\n\n\n\n #[test]\n\n #[allow(clippy::unreadable_literal)]\n\n fn wrapping_u32() {\n\n use super::f64_to_wrapping_u32;\n\n assert_eq!(f64_to_wrapping_u32(0.0), 0);\n\n assert_eq!(f64_to_wrapping_u32(1.0), 1);\n\n assert_eq!(f64_to_wrapping_u32(-1.0), 4294967295);\n\n assert_eq!(f64_to_wrapping_u32(123.1), 123);\n\n assert_eq!(f64_to_wrapping_u32(4294968295.9), 999);\n\n assert_eq!(f64_to_wrapping_u32(-4289411740.3), 5555556);\n\n assert_eq!(f64_to_wrapping_u32(-12884901888.0), 0);\n\n assert_eq!(f64_to_wrapping_u32(std::f64::NAN), 0);\n\n assert_eq!(f64_to_wrapping_u32(std::f64::INFINITY), 0);\n\n assert_eq!(f64_to_wrapping_u32(std::f64::NEG_INFINITY), 0);\n", "file_path": "core/src/avm1/value.rs", "rank": 96, "score": 51327.52874214331 }, { "content": "\n\n if num_self == num_other\n\n || num_self == 0.0 && num_other == -0.0\n\n || num_self == -0.0 && num_other == 0.0\n\n || num_self.is_infinite() && num_self.is_sign_positive()\n\n || num_other.is_infinite() && num_other.is_sign_negative()\n\n {\n\n return Ok(false.into());\n\n }\n\n\n\n if num_self.is_infinite() && num_self.is_sign_negative()\n\n || num_other.is_infinite() && num_other.is_sign_positive()\n\n {\n\n return Ok(true.into());\n\n }\n\n\n\n Ok((num_self < num_other).into())\n\n }\n\n\n\n /// ECMA-262 2nd edition s. 11.9.3 Abstract equality comparison algorithm\n", "file_path": "core/src/avm1/value.rs", "rank": 97, "score": 51324.50180810329 }, { "content": "//! Object trait to expose objects to AVM\n\n\n\nuse crate::avm1::function::{Executable, FunctionObject};\n\nuse crate::avm1::property::Attribute;\n\nuse crate::avm1::return_value::ReturnValue;\n\nuse crate::avm1::super_object::SuperObject;\n\nuse crate::avm1::value_object::ValueObject;\n\nuse crate::avm1::xml_attributes_object::XMLAttributesObject;\n\nuse crate::avm1::xml_idmap_object::XMLIDMapObject;\n\nuse crate::avm1::xml_object::XMLObject;\n\nuse crate::avm1::{Avm1, Error, ScriptObject, SoundObject, StageObject, UpdateContext, Value};\n\nuse crate::display_object::DisplayObject;\n\nuse crate::xml::XMLNode;\n\nuse enumset::EnumSet;\n\nuse gc_arena::{Collect, MutationContext};\n\nuse ruffle_macros::enum_trait_object;\n\nuse std::collections::HashSet;\n\nuse std::fmt::Debug;\n\n\n\n/// Represents an object that can be directly interacted with by the AVM\n", "file_path": "core/src/avm1/object.rs", "rank": 98, "score": 50276.27171515295 }, { "content": "//! `Boolean` class impl\n\n\n\nuse crate::avm1::function::{Executable, FunctionObject};\n\nuse crate::avm1::return_value::ReturnValue;\n\nuse crate::avm1::value_object::ValueObject;\n\nuse crate::avm1::{Avm1, Error, Object, TObject, Value};\n\nuse crate::context::UpdateContext;\n\nuse enumset::EnumSet;\n\nuse gc_arena::MutationContext;\n\n\n\n/// `Boolean` constructor/function\n", "file_path": "core/src/avm1/globals/boolean.rs", "rank": 99, "score": 23.643864225967867 } ]
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, "score": 452576.0573945366 }, { "content": "pub fn should_emit_asm(ctxt: &SemContext, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = ctxt.args.flag_emit_asm {\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": 1, "score": 413730.87451213575 }, { "content": "fn fct_pattern_match(ctxt: &SemContext, fct: &Fct, pattern: &str) -> bool {\n\n if pattern == \"all\" {\n\n return true;\n\n }\n\n\n\n let name = ctxt.interner.str(fct.name);\n\n\n\n for part in pattern.split(',') {\n\n if *name == part {\n\n return true;\n\n }\n\n }\n\n\n\n false\n\n}\n", "file_path": "src/baseline/codegen.rs", "rank": 3, "score": 374538.4803114369 }, { "content": "pub fn make_iterable_region(ctxt: &SemContext, start: Address, end: Address) {\n\n if start == end {\n\n // nothing to do\n\n\n\n } else if end.offset_from(start) == mem::ptr_width_usize() {\n\n unsafe {\n\n *start.to_mut_ptr::<usize>() = 0;\n\n }\n\n } else if end.offset_from(start) == Header::size() as usize {\n\n // fill with object\n\n let cls_id = ctxt.vips.obj(ctxt);\n\n let cls = ctxt.class_defs[cls_id].borrow();\n\n let vtable: *const VTable = &**cls.vtable.as_ref().unwrap();\n\n\n\n unsafe {\n\n *start.to_mut_ptr::<usize>() = vtable as usize;\n\n }\n\n } else {\n\n // fill with int array\n\n let cls_id = ctxt.vips.int_array(ctxt);\n", "file_path": "src/gc/tlab.rs", "rank": 4, "score": 373961.38856297394 }, { "content": "fn is_test_fct<'ast>(ctxt: &SemContext<'ast>, fct: &Fct<'ast>) -> bool {\n\n // tests need to be standalone functions, with no return type and a single parameter\n\n if !fct.parent.is_none() || !fct.return_type.is_unit() || fct.param_types.len() != 1 {\n\n return false;\n\n }\n\n\n\n // parameter needs to be of type Testing\n\n let testing_cls = ctxt.cls(ctxt.vips.testing_class);\n\n if fct.param_types[0] != testing_cls {\n\n return false;\n\n }\n\n\n\n // the functions name needs to start with `test`\n\n let fct_name = ctxt.interner.str(fct.name);\n\n fct_name.starts_with(\"test\")\n\n}\n\n\n", "file_path": "src/driver/start.rs", "rank": 5, "score": 368859.8667652148 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn munmap(ptr: *const u8, size: usize) {\n\n use kernel32::VirtualFree;\n\n use winapi;\n\n use winapi::winnt::MEM_RELEASE;\n\n\n\n let res = unsafe { VirtualFree(ptr as *mut winapi::c_void, 0, MEM_RELEASE) };\n\n\n\n if res == 0 {\n\n panic!(\"VirtualFree failed\");\n\n }\n\n}\n\n\n", "file_path": "src/os/mem.rs", "rank": 6, "score": 366544.32372216415 }, { "content": "pub fn exception_get_and_clear() -> *const u8 {\n\n unsafe {\n\n let val = EXCEPTION_OBJECT;\n\n\n\n if !val.is_null() {\n\n EXCEPTION_OBJECT = ptr::null();\n\n }\n\n\n\n val\n\n }\n\n}\n\n\n", "file_path": "src/ctxt.rs", "rank": 7, "score": 359676.3267031276 }, { "content": "fn run_test<'ast>(ctxt: &SemContext<'ast>, fct: FctId) -> bool {\n\n let testing_class = ctxt.vips.testing_class;\n\n let testing_class = specialize_class_id(ctxt, testing_class);\n\n let testing = object::alloc(ctxt, testing_class).cast();\n\n ctxt.run_test(fct, testing);\n\n\n\n // see if test failed with exception\n\n let exception = exception_get_and_clear();\n\n\n\n exception.is_null() && !testing.has_failed()\n\n}\n\n\n", "file_path": "src/driver/start.rs", "rank": 8, "score": 356805.15673973784 }, { "content": "pub fn flush_icache(start: *const u8, len: usize) {\n\n let start = start as usize;\n\n let end = start + len;\n\n\n\n let (icacheline_size, dcacheline_size) = cacheline_sizes();\n\n\n\n let istart = start & !(icacheline_size - 1);\n\n let dstart = start & !(dcacheline_size - 1);\n\n\n\n let mut ptr = dstart;\n\n\n\n while ptr < end {\n\n unsafe {\n\n asm!(\"dc civac, $0\":: \"r\"(ptr) : \"memory\" : \"volatile\");\n\n }\n\n\n\n ptr += dcacheline_size;\n\n }\n\n\n\n unsafe {\n", "file_path": "src/cpu/arm64/mod.rs", "rank": 9, "score": 356300.28185929137 }, { "content": "pub fn exception_set(val: *const u8) {\n\n unsafe {\n\n EXCEPTION_OBJECT = val;\n\n }\n\n}\n\n\n", "file_path": "src/ctxt.rs", "rank": 10, "score": 353516.472200503 }, { "content": "fn detect_polling_page_check(ctxt: &SemContext, signo: libc::c_int, addr: *const u8) -> bool {\n\n signo == libc::SIGSEGV && ctxt.polling_page.addr() == addr\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\npub enum Trap {\n\n DIV0,\n\n ASSERT,\n\n INDEX_OUT_OF_BOUNDS,\n\n NIL,\n\n THROW,\n\n CAST,\n\n UNEXPECTED,\n\n OOM,\n\n}\n\n\n\nimpl Trap {\n\n pub fn int(self) -> u32 {\n\n match self {\n\n Trap::DIV0 => 1,\n", "file_path": "src/os/signal.rs", "rank": 11, "score": 350870.41056005366 }, { "content": "#[cfg(target_family = \"unix\")]\n\npub fn mprotect(ptr: *const u8, size: usize, prot: ProtType) {\n\n debug_assert!(mem::is_page_aligned(ptr as usize));\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n let res = unsafe { libc::mprotect(ptr as *mut libc::c_void, size, prot.to_libc()) };\n\n\n\n if res != 0 {\n\n panic!(\"mprotect() failed\");\n\n }\n\n}\n", "file_path": "src/os/mem.rs", "rank": 12, "score": 339717.81696896564 }, { "content": "pub fn generate<'a, 'ast: 'a>(ctxt: &'a SemContext<'ast>, fct: InternalFct, dbg: bool) -> JitFctId {\n\n let fct_desc = fct.desc.clone();\n\n\n\n let ngen = NativeGen {\n\n ctxt: ctxt,\n\n masm: MacroAssembler::new(),\n\n fct: fct,\n\n dbg: dbg,\n\n };\n\n\n\n let jit_fct = ngen.generate();\n\n let jit_fct_id = ctxt.jit_fcts.len().into();\n\n\n\n let code_desc = match fct_desc {\n\n InternalFctDescriptor::NativeThunk(_) => CodeDescriptor::NativeThunk(jit_fct_id),\n\n InternalFctDescriptor::TrapThunk => CodeDescriptor::TrapThunk,\n\n InternalFctDescriptor::AllocThunk => CodeDescriptor::AllocThunk,\n\n };\n\n\n\n ctxt.insert_code_map(jit_fct.ptr_start(), jit_fct.ptr_end(), code_desc);\n\n ctxt.jit_fcts.push(JitFct::Base(jit_fct));\n\n\n\n jit_fct_id\n\n}\n\n\n", "file_path": "src/baseline/dora_native.rs", "rank": 13, "score": 339371.8912236036 }, { "content": "fn native_fct<'ast>(ctxt: &mut SemContext<'ast>, name: &str, fctptr: *const u8) {\n\n internal_fct(ctxt, name, FctKind::Native(fctptr));\n\n}\n\n\n", "file_path": "src/semck/prelude.rs", "rank": 14, "score": 318835.1446682827 }, { "content": "pub fn start_native_call(fp: *const u8, pc: usize) {\n\n unsafe {\n\n // fp is framepointer of native stub\n\n\n\n let dtn_size = size_of::<DoraToNativeInfo>() as isize;\n\n let dtn: *mut DoraToNativeInfo = fp.offset(-dtn_size) as *mut DoraToNativeInfo;\n\n let dtn: &mut DoraToNativeInfo = &mut *dtn;\n\n\n\n dtn.fp = fp as usize;\n\n dtn.pc = pc;\n\n\n\n let ctxt = get_ctxt();\n\n\n\n ctxt.push_dtn(dtn);\n\n ctxt.handles.push_border();\n\n }\n\n}\n\n\n", "file_path": "src/baseline/dora_native.rs", "rank": 15, "score": 316547.1333528205 }, { "content": "#[cfg(target_os = \"linux\")]\n\npub fn register_with_perf(jit_fct: &JitBaselineFct, ctxt: &SemContext, name: Name) {\n\n use libc;\n\n use std::fs::OpenOptions;\n\n use std::io::prelude::*;\n\n\n\n let pid = unsafe { libc::getpid() };\n\n let fname = format!(\"/tmp/perf-{}.map\", pid);\n\n\n\n let mut options = OpenOptions::new();\n\n let mut file = options.create(true).append(true).open(&fname).unwrap();\n\n\n\n let code_start = jit_fct.ptr_start() as usize;\n\n let code_end = jit_fct.ptr_end() as usize;\n\n let name = ctxt.interner.str(name);\n\n\n\n let line = format!(\n\n \"{:x} {:x} dora::{}\\n\",\n\n code_start,\n\n code_end - code_start,\n\n name\n\n );\n\n file.write_all(line.as_bytes()).unwrap();\n\n}\n\n\n", "file_path": "src/os/perf.rs", "rank": 16, "score": 309853.4444638911 }, { "content": "pub fn finish_native_call() -> *const u8 {\n\n let ctxt = get_ctxt();\n\n\n\n ctxt.handles.pop_border();\n\n ctxt.pop_dtn();\n\n\n\n exception_get_and_clear()\n\n}\n", "file_path": "src/baseline/dora_native.rs", "rank": 17, "score": 307702.2696056162 }, { "content": "pub fn has_exception() -> bool {\n\n unsafe { !EXCEPTION_OBJECT.is_null() }\n\n}\n\n\n", "file_path": "src/ctxt.rs", "rank": 18, "score": 297767.95859514584 }, { "content": "pub fn flush_icache(_: *const u8, _: usize) {\n\n // no flushing needed on x86_64, but emit compiler barrier\n\n\n\n unsafe {\n\n asm!(\"\" ::: \"memory\" : \"volatile\");\n\n }\n\n}\n\n\n", "file_path": "src/cpu/x64/mod.rs", "rank": 19, "score": 290658.06221927126 }, { "content": "pub fn specialize_struct_id(ctxt: &SemContext, struct_id: StructId) -> StructDefId {\n\n let struc = ctxt.structs[struct_id].borrow();\n\n specialize_struct(ctxt, &*struc, TypeParams::empty())\n\n}\n\n\n", "file_path": "src/semck/specialize.rs", "rank": 20, "score": 289332.05094565725 }, { "content": "pub fn read_execstate(uc: *const u8) -> ExecState {\n\n unsafe {\n\n let mut es: ExecState = std::mem::uninitialized();\n\n\n\n let uc = uc as *const CONTEXT;\n\n let uc = &(*uc);\n\n\n\n es.pc = uc.Rip as usize;\n\n es.sp = uc.Rsp as usize;\n\n es.ra = 0;\n\n\n\n es.regs[cpu::RAX] = uc.Rax as usize;\n\n es.regs[cpu::RCX] = uc.Rcx as usize;\n\n es.regs[cpu::RDX] = uc.Rdx as usize;\n\n es.regs[cpu::RBX] = uc.Rbx as usize;\n\n es.regs[cpu::RSP] = uc.Rsp as usize;\n\n es.regs[cpu::RBP] = uc.Rbp as usize;\n\n es.regs[cpu::RSI] = uc.Rsi as usize;\n\n es.regs[cpu::RDI] = uc.Rdi as usize;\n\n es.regs[cpu::R8] = uc.R8 as usize;\n", "file_path": "src/os_cpu/win_x64.rs", "rank": 21, "score": 283921.1695306492 }, { "content": "pub fn read_execstate(uc: *const u8) -> ExecState {\n\n let mut es: ExecState = unsafe { std::mem::uninitialized() };\n\n\n\n unsafe {\n\n let uc = uc as *mut ucontext_t;\n\n let mc = &(*uc).uc_mcontext;\n\n\n\n es.pc = mc.regs[REG_RIP];\n\n es.sp = mc.regs[REG_RSP];\n\n es.ra = 0;\n\n\n\n for i in 0..es.regs.len() {\n\n let src = reg2ucontext(i);\n\n let dest = i;\n\n\n\n es.regs[dest] = mc.regs[src];\n\n }\n\n }\n\n\n\n es\n\n}\n\n\n", "file_path": "src/os_cpu/linux_x64.rs", "rank": 22, "score": 283921.1695306492 }, { "content": "pub fn read_execstate(uc: *const u8) -> ExecState {\n\n let mut es: ExecState = unsafe { std::mem::uninitialized() };\n\n\n\n let uc = uc as *mut ucontext_t;\n\n let mc = unsafe { &(*uc).uc_mcontext };\n\n\n\n es.pc = mc.pc;\n\n es.sp = mc.sp;\n\n es.ra = 0;\n\n\n\n for i in 0..es.regs.len() {\n\n es.regs[i] = mc.regs[i];\n\n }\n\n\n\n es\n\n}\n\n\n", "file_path": "src/os_cpu/linux_arm64.rs", "rank": 23, "score": 283921.1695306492 }, { "content": "pub fn read_execstate(uc: *const u8) -> ExecState {\n\n let mut es: ExecState = unsafe { std::mem::uninitialized() };\n\n\n\n unsafe {\n\n let uc = uc as *mut ucontext_t;\n\n let mc = (*uc).uc_mcontext;\n\n let ss = &(*mc).ss[..];\n\n\n\n es.pc = ss[REG_RIP] as usize;\n\n es.sp = ss[REG_RSP] as usize;\n\n es.ra = 0;\n\n\n\n for i in 0..es.regs.len() {\n\n let src = reg2ucontext(i);\n\n let dest = i;\n\n\n\n es.regs[dest] = ss[src] as usize;\n\n }\n\n }\n\n\n\n es\n\n}\n\n\n", "file_path": "src/os_cpu/darwin_x64.rs", "rank": 24, "score": 283921.1695306492 }, { "content": "pub fn commit(ptr: Address, size: usize, executable: bool) {\n\n debug_assert!(mem::is_page_aligned(ptr.to_usize()));\n\n debug_assert!(mem::is_page_aligned(size));\n\n\n\n use libc;\n\n\n\n let mut prot = libc::PROT_READ | libc::PROT_WRITE;\n\n\n\n if executable {\n\n prot |= libc::PROT_EXEC;\n\n }\n\n\n\n let val = unsafe {\n\n libc::mmap(\n\n ptr.to_mut_ptr(),\n\n size,\n\n prot,\n\n libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_FIXED,\n\n -1,\n\n 0,\n\n )\n\n };\n\n\n\n if val == libc::MAP_FAILED {\n\n panic!(\"committing memory with mmap() failed\");\n\n }\n\n}\n\n\n", "file_path": "src/gc/arena.rs", "rank": 25, "score": 281860.3139343023 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn mmap(size: usize, exec: ProtType) -> *const u8 {\n\n use kernel32::VirtualAlloc;\n\n use winapi::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE};\n\n\n\n let prot = if exec == Executable {\n\n PAGE_EXECUTE_READWRITE\n\n } else {\n\n PAGE_READWRITE\n\n };\n\n\n\n let ptr = unsafe { VirtualAlloc(ptr::null_mut(), size as u64, MEM_COMMIT | MEM_RESERVE, prot) };\n\n\n\n if ptr.is_null() {\n\n panic!(\"VirtualAlloc failed\");\n\n }\n\n\n\n ptr as *const u8\n\n}\n\n\n", "file_path": "src/os/mem.rs", "rank": 26, "score": 277651.5695886546 }, { "content": "#[cfg(target_family = \"unix\")]\n\npub fn mmap(size: usize, prot: ProtType) -> *const u8 {\n\n let ptr = unsafe {\n\n libc::mmap(\n\n ptr::null_mut(),\n\n size,\n\n prot.to_libc(),\n\n libc::MAP_PRIVATE | libc::MAP_ANON,\n\n -1,\n\n 0,\n\n ) as *mut libc::c_void\n\n };\n\n\n\n if ptr == libc::MAP_FAILED {\n\n panic!(\"mmap failed\");\n\n }\n\n\n\n ptr as *const u8\n\n}\n\n\n", "file_path": "src/os/mem.rs", "rank": 27, "score": 277651.5695886546 }, { "content": "/// returns true if value fits into u8 (unsigned 8bits).\n\npub fn fits_u8(value: i64) -> bool {\n\n 0 <= value && value <= 255\n\n}\n\n\n", "file_path": "src/mem.rs", "rank": 28, "score": 272823.52577021933 }, { "content": "pub fn make_iterable(ctxt: &SemContext) {\n\n let tlab = ctxt.tld.borrow().tlab_region();\n\n make_iterable_region(ctxt, tlab.start, tlab.end);\n\n}\n\n\n", "file_path": "src/gc/tlab.rs", "rank": 29, "score": 269309.6579628 }, { "content": "#[cfg(target_family = \"windows\")]\n\npub fn register_signals(ctxt: &SemContext) {\n\n use kernel32::AddVectoredExceptionHandler;\n\n\n\n unsafe {\n\n AddVectoredExceptionHandler(1, Some(handler));\n\n }\n\n}\n\n\n\n#[cfg(target_family = \"windows\")]\n\nextern \"system\" fn handler(exception: *mut EXCEPTION_POINTERS) -> i32 {\n\n use winapi::excpt;\n\n\n\n if fault_handler(exception) {\n\n return excpt::ExceptionContinueExecution.0 as i32;\n\n }\n\n\n\n excpt::ExceptionContinueSearch.0 as i32\n\n}\n\n\n", "file_path": "src/os/signal.rs", "rank": 30, "score": 269309.6579628 }, { "content": "fn native_method<'ast>(ctxt: &mut SemContext<'ast>, clsid: ClassId, name: &str, fctptr: *const u8) {\n\n internal_method(ctxt, clsid, name, FctKind::Native(fctptr));\n\n}\n\n\n", "file_path": "src/semck/prelude.rs", "rank": 31, "score": 265566.5189798869 }, { "content": "fn check_static<'ast>(ctxt: &SemContext<'ast>, fct: &Fct<'ast>) {\n\n if !fct.is_static {\n\n return;\n\n }\n\n\n\n // static isn't allowed with these modifiers\n\n if fct.is_abstract || fct.has_open || fct.has_override || fct.has_final {\n\n let modifier = if fct.is_abstract {\n\n \"abstract\"\n\n } else if fct.has_open {\n\n \"open\"\n\n } else if fct.has_override {\n\n \"override\"\n\n } else {\n\n \"final\"\n\n };\n\n\n\n let msg = Msg::ModifierNotAllowedForStaticMethod(modifier.into());\n\n ctxt.diag.borrow_mut().report(fct.pos, msg);\n\n }\n\n}\n\n\n", "file_path": "src/semck/fctdefck.rs", "rank": 32, "score": 263254.5121910878 }, { "content": "fn check_abstract<'ast>(ctxt: &SemContext<'ast>, fct: &Fct<'ast>) {\n\n if !fct.is_abstract {\n\n return;\n\n }\n\n\n\n let cls_id = fct.cls_id();\n\n let cls = ctxt.classes[cls_id].borrow();\n\n\n\n if !fct.kind.is_definition() {\n\n let msg = Msg::AbstractMethodWithImplementation;\n\n ctxt.diag.borrow_mut().report(fct.pos, msg);\n\n }\n\n\n\n if !cls.is_abstract {\n\n let msg = Msg::AbstractMethodNotInAbstractClass;\n\n ctxt.diag.borrow_mut().report(fct.pos, msg);\n\n }\n\n}\n\n\n", "file_path": "src/semck/fctdefck.rs", "rank": 33, "score": 263254.5121910878 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>, map_impl_defs: &NodeMap<ImplId>) {\n\n let mut clsck = ImplCheck {\n\n ctxt: ctxt,\n\n ast: ctxt.ast,\n\n impl_id: None,\n\n map_impl_defs: map_impl_defs,\n\n };\n\n\n\n clsck.check();\n\n}\n\n\n", "file_path": "src/semck/impldefck.rs", "rank": 34, "score": 261565.8193841904 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>, map_const_defs: &NodeMap<ConstId>) {\n\n let mut clsck = ConstCheck {\n\n ctxt: ctxt,\n\n ast: ctxt.ast,\n\n const_id: None,\n\n map_const_defs: map_const_defs,\n\n };\n\n\n\n clsck.check();\n\n}\n\n\n", "file_path": "src/semck/constdefck.rs", "rank": 35, "score": 261517.14387425987 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>, map_struct_defs: &NodeMap<StructId>) {\n\n let mut clsck = StructCheck {\n\n ctxt: ctxt,\n\n ast: ctxt.ast,\n\n struct_id: None,\n\n map_struct_defs: map_struct_defs,\n\n };\n\n\n\n clsck.check();\n\n}\n\n\n", "file_path": "src/semck/structdefck.rs", "rank": 36, "score": 261446.0873832995 }, { "content": "pub fn stacktrace_from_last_dtn(ctxt: &SemContext) -> Stacktrace {\n\n let mut stacktrace = Stacktrace::new();\n\n frames_from_dtns(&mut stacktrace, ctxt);\n\n return stacktrace;\n\n}\n\n\n", "file_path": "src/exception.rs", "rank": 37, "score": 259878.50707029074 }, { "content": "pub fn start() -> i32 {\n\n let args = cmd::parse();\n\n\n\n if args.flag_version {\n\n println!(\"dora v0.01b\");\n\n return 0;\n\n }\n\n\n\n let mut interner = Interner::new();\n\n let id_generator = NodeIdGenerator::new();\n\n let mut ast = Ast::new();\n\n\n\n if let Err(code) = parse_dir(\"stdlib\", &id_generator, &mut ast, &mut interner).and_then(|_| {\n\n let path = Path::new(&args.arg_file);\n\n\n\n if path.is_file() {\n\n parse_file(&args.arg_file, &id_generator, &mut ast, &mut interner)\n\n } else if path.is_dir() {\n\n parse_dir(&args.arg_file, &id_generator, &mut ast, &mut interner)\n\n } else {\n", "file_path": "src/driver/start.rs", "rank": 38, "score": 259344.07821950474 }, { "content": "fn check_against_methods(ctxt: &SemContext, ty: BuiltinType, fct: &Fct, methods: &[FctId]) {\n\n for &method in methods {\n\n if method == fct.id {\n\n continue;\n\n }\n\n\n\n let method = ctxt.fcts[method].borrow();\n\n\n\n if method.initialized && method.name == fct.name && method.is_static == fct.is_static {\n\n let cls_name = ty.name(ctxt);\n\n let method_name = ctxt.interner.str(method.name).to_string();\n\n\n\n let msg = Msg::MethodExists(cls_name, method_name, method.pos);\n\n ctxt.diag.borrow_mut().report(fct.ast.pos, msg);\n\n return;\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/semck/fctdefck.rs", "rank": 39, "score": 258266.21038716036 }, { "content": "pub fn check<'ast>(ctxt: &SemContext<'ast>) {\n\n for fct in ctxt.fcts.iter() {\n\n let fct = fct.borrow();\n\n\n\n if !fct.is_src() {\n\n continue;\n\n }\n\n\n\n let src = fct.src();\n\n let mut src = src.borrow_mut();\n\n let ast = fct.ast;\n\n\n\n let mut flowck = FlowCheck {\n\n ctxt: ctxt,\n\n fct: &fct,\n\n src: &mut src,\n\n ast: ast,\n\n in_loop: false,\n\n };\n\n\n\n flowck.check();\n\n }\n\n}\n\n\n", "file_path": "src/semck/flowck.rs", "rank": 40, "score": 254241.5809841255 }, { "content": "pub fn initialize(ctxt: &SemContext, tlab: Region) {\n\n ctxt.tld.borrow_mut().tlab_initialize(tlab.start, tlab.end);\n\n}\n\n\n", "file_path": "src/gc/tlab.rs", "rank": 41, "score": 254241.5809841255 }, { "content": "pub fn check<'ast>(ctxt: &SemContext<'ast>) {\n\n for fct in ctxt.fcts.iter() {\n\n let fct = fct.borrow();\n\n\n\n if !fct.is_src() {\n\n continue;\n\n }\n\n\n\n let src = fct.src();\n\n let mut src = src.borrow_mut();\n\n let ast = fct.ast;\n\n\n\n let mut returnck = ReturnCheck {\n\n ctxt: ctxt,\n\n fct: &fct,\n\n src: &mut src,\n\n ast: ast,\n\n };\n\n\n\n returnck.check();\n\n }\n\n}\n\n\n", "file_path": "src/semck/returnck.rs", "rank": 42, "score": 254241.5809841255 }, { "content": "pub fn check<'ast>(ctxt: &SemContext<'ast>) {\n\n for fct in ctxt.fcts.iter() {\n\n let fct = fct.borrow();\n\n\n\n if !fct.is_src() {\n\n continue;\n\n }\n\n\n\n let src = fct.src();\n\n let mut src = src.borrow_mut();\n\n let ast = fct.ast;\n\n\n\n let mut nameck = NameCheck {\n\n ctxt: ctxt,\n\n fct: &fct,\n\n src: &mut src,\n\n ast: ast,\n\n };\n\n\n\n nameck.check();\n\n }\n\n}\n\n\n", "file_path": "src/semck/nameck.rs", "rank": 43, "score": 254241.5809841255 }, { "content": "pub fn start(\n\n rootset: &[Slot],\n\n heap: Region,\n\n perm: Region,\n\n number_workers: usize,\n\n threadpool: &ThreadPool,\n\n) {\n\n let mut workers = Vec::with_capacity(number_workers);\n\n let mut stealers = Vec::with_capacity(number_workers);\n\n\n\n for _ in 0..number_workers {\n\n let (w, s) = deque::lifo();\n\n workers.push(w);\n\n stealers.push(s);\n\n }\n\n\n\n for root in rootset {\n\n let root_ptr = root.get();\n\n\n\n if heap.contains(root_ptr) {\n", "file_path": "src/gc/swiper/marking.rs", "rank": 44, "score": 252793.51272449087 }, { "content": "fn detect_nil_check(ctxt: &SemContext, pc: usize) -> bool {\n\n let code_map = ctxt.code_map.lock().unwrap();\n\n\n\n if let Some(CodeDescriptor::DoraFct(fid)) = code_map.get(pc as *const u8) {\n\n let jit_fct = ctxt.jit_fcts[fid].borrow();\n\n let offset = pc - (jit_fct.fct_ptr() as usize);\n\n\n\n let jit_fct = jit_fct.to_base().expect(\"baseline expected\");\n\n jit_fct.nil_check_for_offset(offset as i32)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/os/signal.rs", "rank": 45, "score": 251907.39871371468 }, { "content": "pub fn check_override<'ast>(ctxt: &SemContext<'ast>) {\n\n for cls in ctxt.classes.iter() {\n\n let cls = cls.borrow();\n\n\n\n for &fct_id in &cls.methods {\n\n let mut fct = ctxt.fcts[fct_id].borrow_mut();\n\n check_fct_modifier(ctxt, &*cls, &mut *fct);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/semck/superck.rs", "rank": 46, "score": 251114.33023107552 }, { "content": "pub fn get_rootset(ctxt: &SemContext) -> Vec<Slot> {\n\n let mut rootset = Vec::new();\n\n\n\n determine_rootset_from_stack(&mut rootset, ctxt);\n\n determine_rootset_from_globals(&mut rootset, ctxt);\n\n determine_rootset_from_handles(&mut rootset, ctxt);\n\n\n\n rootset\n\n}\n\n\n", "file_path": "src/gc/root.rs", "rank": 47, "score": 251114.33023107552 }, { "content": "pub fn check<'a, 'ast>(ctxt: &SemContext<'ast>) {\n\n for fct in ctxt.fcts.iter() {\n\n let fct = fct.borrow();\n\n\n\n if !fct.is_src() {\n\n continue;\n\n }\n\n\n\n let src = fct.src();\n\n let mut src = src.borrow_mut();\n\n let ast = fct.ast;\n\n\n\n let mut typeck = TypeCheck {\n\n ctxt: ctxt,\n\n fct: &fct,\n\n src: &mut src,\n\n ast: ast,\n\n expr_type: BuiltinType::Unit,\n\n negative_expr_id: NodeId(0),\n\n };\n", "file_path": "src/semck/typeck.rs", "rank": 48, "score": 249042.48971808117 }, { "content": "pub fn check<'a, 'ast>(ctxt: &SemContext<'ast>) {\n\n debug_assert!(ctxt.sym.borrow().levels() == 1);\n\n\n\n for fct in ctxt.fcts.iter() {\n\n let mut fct = fct.borrow_mut();\n\n let ast = fct.ast;\n\n\n\n // check modifiers for function\n\n check_abstract(ctxt, &*fct);\n\n check_static(ctxt, &*fct);\n\n\n\n if !(fct.is_src() || fct.kind.is_definition()) {\n\n continue;\n\n }\n\n\n\n ctxt.sym.borrow_mut().push_level();\n\n\n\n match fct.parent {\n\n FctParent::Class(owner_class) => {\n\n let cls = ctxt.classes[owner_class].borrow();\n", "file_path": "src/semck/fctdefck.rs", "rank": 49, "score": 249042.48971808117 }, { "content": "fn check_fct_modifier<'ast>(ctxt: &SemContext<'ast>, cls: &Class, fct: &mut Fct<'ast>) {\n\n // catch: class A { open fun f() } (A is not derivable)\n\n // catch: open final fun f()\n\n if fct.has_open && (!cls.has_open || fct.has_final) {\n\n let name = ctxt.interner.str(fct.name).to_string();\n\n ctxt.diag\n\n .borrow_mut()\n\n .report(fct.pos(), Msg::SuperfluousOpen(name));\n\n return;\n\n }\n\n\n\n if cls.parent_class.is_none() {\n\n if fct.has_override {\n\n let name = ctxt.interner.str(fct.name).to_string();\n\n ctxt.diag\n\n .borrow_mut()\n\n .report(fct.pos(), Msg::SuperfluousOverride(name));\n\n return;\n\n }\n\n\n", "file_path": "src/semck/superck.rs", "rank": 50, "score": 247987.410855257 }, { "content": "fn alloc_polling_page() -> *const u8 {\n\n let ptr = unsafe {\n\n libc::mmap(\n\n ptr::null_mut(),\n\n os::page_size() as usize,\n\n libc::PROT_READ,\n\n libc::MAP_PRIVATE | libc::MAP_ANON,\n\n -1,\n\n 0,\n\n ) as *mut libc::c_void\n\n };\n\n\n\n if ptr == libc::MAP_FAILED {\n\n panic!(\"mmap failed\");\n\n }\n\n\n\n ptr as *const u8\n\n}\n\n\n", "file_path": "src/safepoint.rs", "rank": 51, "score": 247473.02413275058 }, { "content": "fn find_main<'ast>(ctxt: &SemContext<'ast>) -> Option<FctId> {\n\n let name = ctxt.interner.intern(\"main\");\n\n let fctid = match ctxt.sym.borrow().get_fct(name) {\n\n Some(id) => id,\n\n None => {\n\n ctxt.diag\n\n .borrow_mut()\n\n .report(Position::new(1, 1), Msg::MainNotFound);\n\n return None;\n\n }\n\n };\n\n\n\n let fct = ctxt.fcts[fctid].borrow();\n\n let ret = fct.return_type;\n\n\n\n if (ret != BuiltinType::Unit && ret != BuiltinType::Int) || fct.params_without_self().len() > 0\n\n {\n\n let pos = fct.ast.pos;\n\n ctxt.diag.borrow_mut().report(pos, Msg::WrongMainDefinition);\n\n return None;\n\n }\n\n\n\n Some(fctid)\n\n}\n", "file_path": "src/driver/start.rs", "rank": 52, "score": 247040.32372371454 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>) {\n\n for ximpl in &ctxt.impls {\n\n let ximpl = ximpl.borrow();\n\n let xtrait = ctxt.traits[ximpl.trait_id()].borrow();\n\n let cls = ctxt.classes[ximpl.cls_id()].borrow().ty;\n\n\n\n let all: HashSet<_> = xtrait.methods.iter().cloned().collect();\n\n let mut defined = HashSet::new();\n\n\n\n for &method_id in &ximpl.methods {\n\n let mut method = ctxt.fcts[method_id].borrow_mut();\n\n\n\n if let Some(fid) = xtrait.find_method(\n\n ctxt,\n\n method.is_static,\n\n method.name,\n\n Some(cls),\n\n method.params_without_self(),\n\n ) {\n\n method.impl_for = Some(fid);\n", "file_path": "src/semck/implck.rs", "rank": 53, "score": 245915.23896503123 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>) {\n\n cycle_detection(ctxt);\n\n\n\n if ctxt.diag.borrow().has_errors() {\n\n return;\n\n }\n\n\n\n // determine_struct_sizes(ctxt);\n\n determine_vtables(ctxt);\n\n}\n\n\n", "file_path": "src/semck/superck.rs", "rank": 54, "score": 245915.23896503123 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>) {\n\n let mut map_cls_defs = NodeMap::new(); // get ClassId from ast node\n\n let mut map_struct_defs = NodeMap::new(); // get StructId from ast node\n\n let mut map_trait_defs = NodeMap::new(); // get TraitId from ast node\n\n let mut map_impl_defs = NodeMap::new(); // get ImplId from ast node\n\n let mut map_global_defs = NodeMap::new(); // get GlobalId from ast node\n\n let mut map_const_defs = NodeMap::new(); // get ConstId from ast node\n\n\n\n // add user defined fcts and classes to ctxt\n\n // this check does not look into fct or class bodies\n\n globaldef::check(\n\n ctxt,\n\n &mut map_cls_defs,\n\n &mut map_struct_defs,\n\n &mut map_trait_defs,\n\n &mut map_impl_defs,\n\n &mut map_global_defs,\n\n &mut map_const_defs,\n\n );\n\n return_on_error!(ctxt);\n", "file_path": "src/semck/mod.rs", "rank": 55, "score": 245915.2389650312 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>) {\n\n let mut abstract_methods: HashMap<ClassId, Rc<Vec<FctId>>> = HashMap::new();\n\n\n\n for cls in ctxt.classes.iter() {\n\n let cls = cls.borrow();\n\n\n\n // we are only interested in non-abstract classes\n\n // with abstract super classes\n\n\n\n if cls.is_abstract {\n\n continue;\n\n }\n\n\n\n if let Some(super_cls_id) = cls.parent_class {\n\n let super_cls = ctxt.classes[super_cls_id].borrow();\n\n\n\n if super_cls.is_abstract {\n\n check_abstract(ctxt, &*cls, &*super_cls, &mut abstract_methods);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/semck/abstractck.rs", "rank": 56, "score": 245915.2389650312 }, { "content": "pub fn internal_functions<'ast>(ctxt: &mut SemContext<'ast>) {\n\n native_fct(ctxt, \"fatalError\", stdlib::fatal_error as *const u8);\n\n native_fct(ctxt, \"abort\", stdlib::abort as *const u8);\n\n native_fct(ctxt, \"exit\", stdlib::exit as *const u8);\n\n\n\n native_fct(ctxt, \"print\", stdlib::print as *const u8);\n\n native_fct(ctxt, \"println\", stdlib::println as *const u8);\n\n native_fct(ctxt, \"address_of\", stdlib::addr as *const u8);\n\n intrinsic_fct(ctxt, \"assert\", Intrinsic::Assert);\n\n intrinsic_fct(ctxt, \"debug\", Intrinsic::Debug);\n\n native_fct(ctxt, \"argc\", stdlib::argc as *const u8);\n\n native_fct(ctxt, \"argv\", stdlib::argv as *const u8);\n\n native_fct(ctxt, \"forceCollect\", stdlib::gc_collect as *const u8);\n\n native_fct(ctxt, \"timestamp\", stdlib::timestamp as *const u8);\n\n native_fct(\n\n ctxt,\n\n \"forceMinorCollect\",\n\n stdlib::gc_minor_collect as *const u8,\n\n );\n\n\n", "file_path": "src/semck/prelude.rs", "rank": 57, "score": 242946.3678319524 }, { "content": "pub fn internal_classes<'ast>(ctxt: &mut SemContext<'ast>) {\n\n ctxt.vips.bool_class = internal_class(ctxt, \"bool\", Some(BuiltinType::Bool));\n\n ctxt.vips.byte_class = internal_class(ctxt, \"byte\", Some(BuiltinType::Byte));\n\n ctxt.vips.char_class = internal_class(ctxt, \"char\", Some(BuiltinType::Char));\n\n ctxt.vips.int_class = internal_class(ctxt, \"int\", Some(BuiltinType::Int));\n\n ctxt.vips.long_class = internal_class(ctxt, \"long\", Some(BuiltinType::Long));\n\n\n\n ctxt.vips.float_class = internal_class(ctxt, \"float\", Some(BuiltinType::Float));\n\n ctxt.vips.double_class = internal_class(ctxt, \"double\", Some(BuiltinType::Double));\n\n\n\n ctxt.vips.object_class = internal_class(ctxt, \"Object\", None);\n\n ctxt.vips.str_class = internal_class(ctxt, \"Str\", None);\n\n ctxt.classes[ctxt.vips.str_class].borrow_mut().is_str = true;\n\n\n\n ctxt.vips.array_class = internal_class(ctxt, \"Array\", None);\n\n ctxt.classes[ctxt.vips.array_class].borrow_mut().is_array = true;\n\n\n\n ctxt.vips.testing_class = internal_class(ctxt, \"Testing\", None);\n\n\n\n ctxt.vips.exception_class = internal_class(ctxt, \"Exception\", None);\n\n ctxt.vips.stack_trace_element_class = internal_class(ctxt, \"StackTraceElement\", None);\n\n\n\n ctxt.vips.comparable_trait = find_trait(ctxt, \"Comparable\");\n\n ctxt.vips.equals_trait = find_trait(ctxt, \"Equals\");\n\n ctxt.vips.iterator_trait = Cell::new(Some(find_trait(ctxt, \"Iterator\")));\n\n}\n\n\n", "file_path": "src/semck/prelude.rs", "rank": 58, "score": 242946.3678319524 }, { "content": "pub fn stacktrace_from_es(ctxt: &SemContext, es: &ExecState) -> Stacktrace {\n\n let mut stacktrace = Stacktrace::new();\n\n let fp = fp_from_execstate(es);\n\n frames_from_pc(&mut stacktrace, ctxt, es.pc, fp);\n\n frames_from_dtns(&mut stacktrace, ctxt);\n\n return stacktrace;\n\n}\n\n\n", "file_path": "src/exception.rs", "rank": 59, "score": 242946.3678319524 }, { "content": "fn run_main<'ast>(ctxt: &SemContext<'ast>, main: FctId) -> i32 {\n\n let res = ctxt.run(main);\n\n let is_unit = ctxt.fcts[main].borrow().return_type.is_unit();\n\n\n\n // main-fct without return value exits with status 0\n\n if is_unit {\n\n 0\n\n\n\n // else use return value of main for exit status\n\n } else {\n\n res\n\n }\n\n}\n\n\n", "file_path": "src/driver/start.rs", "rank": 60, "score": 239796.55106187364 }, { "content": "pub fn get_ctxt() -> &'static SemContext<'static> {\n\n unsafe { &*(CTXT.unwrap() as *const SemContext) }\n\n}\n\n\n\npub struct SemContext<'ast> {\n\n pub args: Args,\n\n pub interner: Interner,\n\n pub ast: &'ast ast::Ast,\n\n pub diag: RefCell<Diagnostic>,\n\n pub sym: RefCell<SymTable>,\n\n pub vips: KnownElements,\n\n pub consts: GrowableVec<ConstData<'ast>>, // stores all const definitions\n\n pub structs: GrowableVec<StructData>, // stores all struct source definitions\n\n pub struct_defs: GrowableVec<StructDef>, // stores all struct definitions\n\n pub classes: GrowableVec<Class>, // stores all class source definitions\n\n pub class_defs: GrowableVec<ClassDef>, // stores all class definitions\n\n pub fcts: GrowableVec<Fct<'ast>>, // stores all function definitions\n\n pub jit_fcts: GrowableVec<JitFct>, // stores all function implementations\n\n pub traits: Vec<RefCell<TraitData>>, // stores all trait definitions\n\n pub impls: Vec<RefCell<ImplData>>, // stores all impl definitions\n", "file_path": "src/ctxt.rs", "rank": 61, "score": 238412.6664790754 }, { "content": "pub fn allocate(ctxt: &SemContext, size: usize) -> Option<Address> {\n\n assert!(size < TLAB_OBJECT_SIZE);\n\n let tlab = ctxt.tld.borrow().tlab_region();\n\n\n\n if size <= tlab.size() {\n\n ctxt.tld\n\n .borrow_mut()\n\n .tlab_initialize(tlab.start.offset(size), tlab.end);\n\n Some(tlab.start)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/gc/tlab.rs", "rank": 62, "score": 238136.00676177623 }, { "content": "fn set_exception_backtrace(ctxt: &SemContext, obj: Handle<Exception>, via_retrieve: bool) {\n\n let stacktrace = stacktrace_from_last_dtn(ctxt);\n\n let mut obj = ctxt.handles.root(obj);\n\n\n\n let skip = if via_retrieve { 2 } else { 0 };\n\n let len = stacktrace.len() - skip;\n\n\n\n let cls_id = ctxt.vips.int_array(ctxt);\n\n let array: Handle<IntArray> = Array::alloc(ctxt, len * 2, 0, cls_id);\n\n let mut array = ctxt.handles.root(array);\n\n let mut i = 0;\n\n\n\n // ignore first element of stack trace (ctor of Exception)\n\n for elem in stacktrace.elems.iter().skip(skip) {\n\n array.set_at(i, elem.lineno);\n\n array.set_at(i + 1, elem.fct_id.idx() as i32);\n\n\n\n i += 2;\n\n }\n\n\n\n obj.backtrace = array.direct();\n\n}\n", "file_path": "src/exception.rs", "rank": 63, "score": 236125.21059510508 }, { "content": "pub fn alloc(ctxt: &SemContext, clsid: ClassDefId) -> Handle<Obj> {\n\n let cls_def = ctxt.class_defs[clsid].borrow();\n\n\n\n let size = match cls_def.size {\n\n ClassSize::Fixed(size) => size as usize,\n\n _ => panic!(\"alloc only supports fix-sized types\"),\n\n };\n\n\n\n let size = mem::align_usize(size, mem::ptr_width() as usize);\n\n\n\n let ptr = ctxt.gc.alloc(ctxt, size, false).to_usize();\n\n let vtable: *const VTable = &**cls_def.vtable.as_ref().unwrap();\n\n let mut handle: Handle<Obj> = ptr.into();\n\n handle.header_mut().vtable = vtable as *mut VTable;\n\n\n\n handle\n\n}\n\n\n\npub struct Exception {\n\n pub header: Header,\n", "file_path": "src/object.rs", "rank": 64, "score": 235313.7806927666 }, { "content": "pub fn specialize_class_ty(ctxt: &SemContext, ty: BuiltinType) -> ClassDefId {\n\n match ty {\n\n BuiltinType::Class(cls_id, list_id) => {\n\n let params = ctxt.lists.borrow().get(list_id);\n\n specialize_class_id_params(ctxt, cls_id, params)\n\n }\n\n\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/semck/specialize.rs", "rank": 65, "score": 232436.17748506967 }, { "content": "fn determine_stack_entry(stacktrace: &mut Stacktrace, ctxt: &SemContext, pc: usize) -> bool {\n\n let code_map = ctxt.code_map.lock().unwrap();\n\n let data = code_map.get(pc as *const u8);\n\n\n\n match data {\n\n Some(CodeDescriptor::DoraFct(fct_id)) => {\n\n let jit_fct = ctxt.jit_fcts[fct_id].borrow();\n\n\n\n let offset = pc - (jit_fct.fct_ptr() as usize);\n\n let jit_fct = jit_fct.to_base().expect(\"baseline expected\");\n\n let lineno = jit_fct.lineno_for_offset(offset as i32);\n\n\n\n if lineno == 0 {\n\n panic!(\"lineno not found for program point\");\n\n }\n\n\n\n stacktrace.push_entry(fct_id, lineno);\n\n\n\n true\n\n }\n", "file_path": "src/exception.rs", "rank": 66, "score": 231557.39522194257 }, { "content": "pub fn alloc_exception(ctxt: &SemContext, msg: Handle<Str>) -> Handle<Exception> {\n\n let cls_id = ctxt.vips.exception(ctxt);\n\n let obj: Handle<Exception> = alloc(ctxt, cls_id).cast();\n\n let mut obj = ctxt.handles.root(obj);\n\n\n\n obj.msg = msg;\n\n set_exception_backtrace(ctxt, obj.direct(), false);\n\n\n\n obj.direct()\n\n}\n\n\n", "file_path": "src/exception.rs", "rank": 67, "score": 230850.1235680408 }, { "content": "pub fn specialize_class_id(ctxt: &SemContext, cls_id: ClassId) -> ClassDefId {\n\n let cls = ctxt.classes[cls_id].borrow();\n\n specialize_class(ctxt, &*cls, TypeParams::empty())\n\n}\n\n\n", "file_path": "src/semck/specialize.rs", "rank": 68, "score": 230103.92253821658 }, { "content": "/// returns true if given value is a multiple of a page size.\n\npub fn is_page_aligned(val: usize) -> bool {\n\n let align = os::page_size_bits();\n\n\n\n // we can use shifts here since we know that\n\n // page size is power of 2\n\n val == ((val >> align) << align)\n\n}\n\n\n", "file_path": "src/mem.rs", "rank": 69, "score": 229755.04131093668 }, { "content": "/// returns true if value fits into i32 (signed 32bits).\n\npub fn fits_i32(value: i64) -> bool {\n\n i32::MIN as i64 <= value && value <= i32::MAX as i64\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_fits_u8() {\n\n assert_eq!(true, fits_u8(0));\n\n assert_eq!(true, fits_u8(255));\n\n assert_eq!(false, fits_u8(256));\n\n assert_eq!(false, fits_u8(-1));\n\n }\n\n\n\n #[test]\n\n fn test_fits_i32() {\n\n assert_eq!(true, fits_i32(0));\n\n assert_eq!(true, fits_i32(i32::MAX as i64));\n\n assert_eq!(true, fits_i32(i32::MIN as i64));\n\n assert_eq!(false, fits_i32(i32::MAX as i64 + 1));\n\n assert_eq!(false, fits_i32(i32::MIN as i64 - 1));\n\n }\n\n}\n", "file_path": "src/mem.rs", "rank": 70, "score": 229755.04131093668 }, { "content": "pub fn always_returns(s: &Stmt) -> bool {\n\n match returnck::returns_value(s) {\n\n Ok(_) => true,\n\n Err(_) => false,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ctxt::SemContext;\n\n use dora_parser::error::msg::Msg;\n\n use dora_parser::lexer::position::Position;\n\n use test;\n\n\n\n pub fn ok(code: &'static str) {\n\n test::parse_with_errors(code, |ctxt| {\n\n let diag = ctxt.diag.borrow();\n\n let errors = diag.errors();\n\n\n\n println!(\"errors = {:?}\", errors);\n", "file_path": "src/semck/mod.rs", "rank": 71, "score": 229755.04131093668 }, { "content": "pub fn generate<'a, 'ast: 'a>(ctxt: &'a SemContext<'ast>) -> Address {\n\n let ngen = DoraCompileGen {\n\n ctxt: ctxt,\n\n masm: MacroAssembler::new(),\n\n dbg: ctxt.args.flag_emit_debug_compile,\n\n };\n\n\n\n let jit_fct = ngen.generate();\n\n let addr = Address::from_ptr(jit_fct.fct_ptr());\n\n ctxt.insert_code_map(\n\n jit_fct.ptr_start(),\n\n jit_fct.ptr_end(),\n\n CodeDescriptor::CompilerThunk,\n\n );\n\n ctxt.jit_fcts.push(JitFct::Base(jit_fct));\n\n\n\n addr\n\n}\n\n\n", "file_path": "src/baseline/dora_compile.rs", "rank": 72, "score": 229519.21752107987 }, { "content": "pub fn generate<'a, 'ast: 'a>(ctxt: &'a SemContext<'ast>) -> Address {\n\n let ngen = DoraEntryGen {\n\n ctxt: ctxt,\n\n masm: MacroAssembler::new(),\n\n dbg: ctxt.args.flag_emit_debug_entry,\n\n };\n\n\n\n let jit_fct = ngen.generate();\n\n let ptr = Address::from_ptr(jit_fct.fct_ptr());\n\n\n\n ctxt.insert_code_map(\n\n jit_fct.ptr_start(),\n\n jit_fct.ptr_end(),\n\n CodeDescriptor::DoraEntry,\n\n );\n\n ctxt.jit_fcts.push(JitFct::Base(jit_fct));\n\n\n\n ptr\n\n}\n\n\n", "file_path": "src/baseline/dora_entry.rs", "rank": 73, "score": 229519.21752107987 }, { "content": "pub fn generate<'a, 'ast: 'a>(ctxt: &'a SemContext<'ast>) -> Address {\n\n let ngen = DoraThrowGen {\n\n ctxt: ctxt,\n\n masm: MacroAssembler::new(),\n\n dbg: ctxt.args.flag_emit_debug_compile,\n\n };\n\n\n\n let jit_fct = ngen.generate();\n\n ctxt.insert_code_map(\n\n jit_fct.ptr_start(),\n\n jit_fct.ptr_end(),\n\n CodeDescriptor::ThrowThunk,\n\n );\n\n let addr = Address::from_ptr(jit_fct.fct_ptr());\n\n\n\n ctxt.jit_fcts.push(JitFct::Base(jit_fct));\n\n\n\n addr\n\n}\n\n\n", "file_path": "src/baseline/dora_throw.rs", "rank": 74, "score": 229519.21752107985 }, { "content": "pub fn emit_rex(buf: &mut MacroAssembler, w: u8, r: u8, x: u8, b: u8) {\n\n assert!(w == 0 || w == 1);\n\n assert!(r == 0 || r == 1);\n\n assert!(x == 0 || x == 1);\n\n assert!(b == 0 || b == 1);\n\n\n\n buf.emit_u8(0x4 << 4 | w << 3 | r << 2 | x << 1 | b);\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 75, "score": 228164.33509569737 }, { "content": "#[cfg(target_family = \"unix\")]\n\nfn handler(signo: libc::c_int, info: *const siginfo_t, ucontext: *const u8) {\n\n let es = read_execstate(ucontext);\n\n let ctxt = get_ctxt();\n\n\n\n let addr = unsafe { (*info).si_addr } as *const u8;\n\n\n\n if detect_nil_check(ctxt, es.pc) {\n\n println!(\"nil check failed\");\n\n let stacktrace = stacktrace_from_es(ctxt, &es);\n\n stacktrace.dump(ctxt);\n\n unsafe {\n\n libc::_exit(104);\n\n }\n\n } else if detect_polling_page_check(ctxt, signo, addr) {\n\n // polling page read failed => enter safepoint\n\n safepoint::enter(&es);\n\n\n\n // otherwise trap not dected => crash\n\n } else {\n\n println!(\n", "file_path": "src/os/signal.rs", "rank": 76, "score": 224051.27412534077 }, { "content": "pub fn dump_fct(fct: &Function, interner: &Interner) {\n\n let mut dumper = AstDumper {\n\n interner: interner,\n\n indent: 0,\n\n };\n\n\n\n dumper.dump_fct(fct);\n\n}\n\n\n", "file_path": "lib/dora-parser/src/ast/dump.rs", "rank": 77, "score": 223439.75269296122 }, { "content": "pub fn fits_u12(imm: u32) -> bool {\n\n imm < 4096\n\n}\n\n\n", "file_path": "src/cpu/arm64/asm.rs", "rank": 78, "score": 222960.63763715496 }, { "content": "pub fn fits_i8(imm: i32) -> bool {\n\n imm == (imm as i8) as i32\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 79, "score": 222960.63763715496 }, { "content": "pub fn forget(ptr: Address, size: usize) {\n\n use libc;\n\n\n\n let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) };\n\n\n\n if res != 0 {\n\n panic!(\"forgetting memory with madvise() failed\");\n\n }\n\n}\n", "file_path": "src/gc/arena.rs", "rank": 80, "score": 222660.86684910057 }, { "content": "pub fn uncommit(ptr: Address, size: usize) {\n\n use libc;\n\n\n\n let val = unsafe {\n\n libc::mmap(\n\n ptr.to_mut_ptr(),\n\n size,\n\n libc::PROT_NONE,\n\n libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE,\n\n -1,\n\n 0,\n\n )\n\n };\n\n\n\n if val == libc::MAP_FAILED {\n\n panic!(\"uncommitting memory with mmap() failed\");\n\n }\n\n}\n\n\n", "file_path": "src/gc/arena.rs", "rank": 81, "score": 222660.86684910057 }, { "content": "pub fn emit_sib(buf: &mut MacroAssembler, scale: u8, index: u8, base: u8) {\n\n assert!(scale < 4);\n\n assert!(index < 8);\n\n assert!(base < 8);\n\n\n\n buf.emit_u8(scale << 6 | index << 3 | base);\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 82, "score": 220535.5031844806 }, { "content": "pub fn emit_modrm(buf: &mut MacroAssembler, mode: u8, reg: u8, rm: u8) {\n\n assert!(mode < 4);\n\n assert!(reg < 8);\n\n assert!(rm < 8);\n\n\n\n buf.emit_u8(mode << 6 | reg << 3 | rm);\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 83, "score": 220535.5031844806 }, { "content": "pub fn emit_u8(buf: &mut MacroAssembler, val: u8) {\n\n buf.emit_u8(val)\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 84, "score": 219097.34817319064 }, { "content": "fn run_tests<'ast>(ctxt: &SemContext<'ast>) -> i32 {\n\n let mut tests = 0;\n\n let mut passed = 0;\n\n\n\n for fct in ctxt.fcts.iter() {\n\n let fct = fct.borrow();\n\n\n\n if !is_test_fct(ctxt, &*fct) {\n\n continue;\n\n }\n\n\n\n tests += 1;\n\n\n\n print!(\"test {} ... \", ctxt.interner.str(fct.name));\n\n\n\n if run_test(ctxt, fct.id) {\n\n passed += 1;\n\n println!(\"ok\");\n\n } else {\n\n println!(\"failed\");\n", "file_path": "src/driver/start.rs", "rank": 85, "score": 218997.82388560916 }, { "content": "pub fn check<'a, 'ast>(ctxt: &SemContext<'ast>, map_global_defs: &NodeMap<GlobalId>) {\n\n let mut checker = GlobalDefCheck {\n\n ctxt: ctxt,\n\n current_type: BuiltinType::Unit,\n\n map_global_defs: map_global_defs,\n\n };\n\n\n\n checker.visit_ast(ctxt.ast);\n\n}\n\n\n", "file_path": "src/semck/globaldefck.rs", "rank": 86, "score": 216676.77222734404 }, { "content": "pub fn read_type<'ast>(ctxt: &SemContext<'ast>, t: &'ast Type) -> Option<BuiltinType> {\n\n match *t {\n\n TypeSelf(_) => {\n\n return Some(BuiltinType::This);\n\n }\n\n\n\n TypeBasic(ref basic) => {\n\n if let Some(sym) = ctxt.sym.borrow().get(basic.name) {\n\n match sym {\n\n SymClass(cls_id) => {\n\n let ty = if basic.params.len() > 0 {\n\n let mut type_params = Vec::new();\n\n\n\n for param in &basic.params {\n\n let param = read_type(ctxt, param);\n\n\n\n if let Some(param) = param {\n\n type_params.push(param);\n\n } else {\n\n return None;\n", "file_path": "src/semck/mod.rs", "rank": 87, "score": 215135.1056724462 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>, map_cls_defs: &NodeMap<ClassId>) {\n\n let mut clsck = ClsCheck {\n\n ctxt: ctxt,\n\n ast: ctxt.ast,\n\n cls_id: None,\n\n map_cls_defs: map_cls_defs,\n\n };\n\n\n\n clsck.check();\n\n}\n\n\n", "file_path": "src/semck/clsdefck.rs", "rank": 88, "score": 214447.05523219646 }, { "content": "pub fn check<'ast>(ctxt: &mut SemContext<'ast>, map_trait_defs: &NodeMap<TraitId>) {\n\n let mut clsck = TraitCheck {\n\n ctxt: ctxt,\n\n ast: ctxt.ast,\n\n trait_id: None,\n\n map_trait_defs: map_trait_defs,\n\n };\n\n\n\n clsck.check();\n\n}\n\n\n", "file_path": "src/semck/traitdefck.rs", "rank": 89, "score": 214447.05523219646 }, { "content": "fn determine_rootset(rootset: &mut Vec<Slot>, ctxt: &SemContext, fp: usize, pc: usize) -> bool {\n\n let code_map = ctxt.code_map.lock().unwrap();\n\n let data = code_map.get(pc as *const u8);\n\n\n\n match data {\n\n Some(CodeDescriptor::DoraFct(fct_id)) => {\n\n let jit_fct = ctxt.jit_fcts[fct_id].borrow();\n\n\n\n let offset = pc - (jit_fct.fct_ptr() as usize);\n\n let jit_fct = jit_fct.to_base().expect(\"baseline expected\");\n\n let gcpoint = jit_fct\n\n .gcpoint_for_offset(offset as i32)\n\n .expect(\"no gcpoint\");\n\n\n\n for &offset in &gcpoint.offsets {\n\n let addr = (fp as isize + offset as isize) as usize;\n\n rootset.push(Slot::at(addr.into()));\n\n }\n\n\n\n true\n", "file_path": "src/gc/root.rs", "rank": 90, "score": 212261.5770927463 }, { "content": "pub fn specialize_struct(\n\n ctxt: &SemContext,\n\n struc: &StructData,\n\n type_params: TypeParams,\n\n) -> StructDefId {\n\n if let Some(&id) = struc.specializations.borrow().get(&type_params) {\n\n return id;\n\n }\n\n\n\n create_specialized_struct(ctxt, struc, type_params)\n\n}\n\n\n", "file_path": "src/semck/specialize.rs", "rank": 91, "score": 209265.8183332761 }, { "content": "pub fn fits_movz(imm: u64, register_size: u32) -> bool {\n\n assert!(register_size == 32 || register_size == 64);\n\n\n\n count_empty_half_words(imm, register_size) >= (register_size / 16 - 1)\n\n}\n\n\n", "file_path": "src/cpu/arm64/asm.rs", "rank": 92, "score": 206074.49254304275 }, { "content": "pub fn fits_movn(imm: u64, register_size: u32) -> bool {\n\n fits_movz(!imm, register_size)\n\n}\n\n\n", "file_path": "src/cpu/arm64/asm.rs", "rank": 93, "score": 206074.49254304275 }, { "content": "pub fn emit_op(buf: &mut MacroAssembler, opcode: u8) {\n\n buf.emit_u8(opcode);\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 94, "score": 205981.9367476649 }, { "content": "#[inline(always)]\n\npub fn ptr_width() -> i32 {\n\n size_of::<*const u8>() as i32\n\n}\n\n\n", "file_path": "src/mem.rs", "rank": 95, "score": 205955.0163114971 }, { "content": "#[cfg(not(target_os = \"linux\"))]\n\npub fn register_with_perf(_: &JitBaselineFct, _: &SemContext, _: Name) {\n\n // nothing to do\n\n}\n", "file_path": "src/os/perf.rs", "rank": 96, "score": 205221.60383262156 }, { "content": "fn internal_fct<'ast>(ctxt: &mut SemContext<'ast>, name: &str, kind: FctKind) {\n\n let name = ctxt.interner.intern(name);\n\n let fctid = ctxt.sym.borrow().get_fct(name);\n\n\n\n if let Some(fctid) = fctid {\n\n let mut fct = ctxt.fcts[fctid].borrow_mut();\n\n\n\n if fct.internal {\n\n fct.kind = kind;\n\n fct.internal_resolved = true;\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/semck/prelude.rs", "rank": 97, "score": 204645.42991261522 }, { "content": "pub fn emit_shr_reg_imm(buf: &mut MacroAssembler, x64: u8, dest: Reg, imm: u8) {\n\n if dest.msb() != 0 || x64 != 0 {\n\n emit_rex(buf, x64, 0, 0, dest.msb());\n\n }\n\n\n\n emit_op(buf, if imm == 1 { 0xD1 } else { 0xC1 });\n\n emit_modrm(buf, 0b11, 0b101, dest.and7());\n\n\n\n if imm != 1 {\n\n emit_u8(buf, imm);\n\n }\n\n}\n\n\n", "file_path": "src/cpu/x64/asm.rs", "rank": 98, "score": 203336.71114166942 } ]
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` (`id`)\n\n on delete cascade\n\n);\n\n\n", "file_path": "migrations/20201116031038_new.sql", "rank": 0, "score": 31818.16315514529 }, { "content": "CREATE TABLE `artist` (\n\n `id` integer primary key autoincrement,\n\n `name` varchar(255) not null,\n\n `bio` varchar(255),\n\n `picture` varchar(255),\n\n `created_at` datetime not null,\n\n `updated_at` datetime,\n\n `similar` varchar(255),\n\n `tags` varchar(255)\n\n);\n\n\n", "file_path": "migrations/20201116031038_new.sql", "rank": 1, "score": 31818.16315514529 }, { "content": " number: i64,\n\n lossless: bool,\n\n created_at: String,\n\n updated_at: Option<String>,\n\n artists: Vec<Artist>,\n\n playlists: Vec<i64>, // was serde_json::Value\n\n album: Album,\n\n genre: Option<Genre>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Album {\n\n id: i64,\n\n name: String,\n\n picture: String,\n\n year: i64,\n\n created_at: String,\n\n updated_at: Option<String>,\n\n artist: Artist,\n\n}\n", "file_path": "src/api/search.rs", "rank": 4, "score": 12.37759230375803 }, { "content": " \"#,\n\n metadata.name,\n\n )\n\n .fetch_all(&mut pool.acquire().await?)\n\n .await\n\n {\n\n Ok(e) => {\n\n if e.len() > 0 {\n\n return Ok(e[0].id.unwrap() as i32);\n\n } else {\n\n let now = chrono::offset::Utc::now().to_rfc3339();\n\n let v = artist.into_iter().map(|n| n.to_string()).collect::<Vec<String>>().join(\",\");\n\n let p = metadata.path.to_str().unwrap();\n\n let n = metadata.number as i64;\n\n let d = metadata.duration as i64;\n\n let a = album as i64;\n\n let _ = match sqlx::query!(\n\n r#\"\n\n INSERT INTO `song` (number, name, path, album, artist, artists, liked, duration, plays, lossless, genre, created_at)\n\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 10, $11, $12);\n", "file_path": "src/index/db.rs", "rank": 5, "score": 12.206290411702955 }, { "content": " name: track.name,\n\n artist: track.artist,\n\n path: track.path,\n\n plays: track.plays,\n\n duration: track.duration as f64,\n\n liked: match track.liked{\n\n Some(e) => e,\n\n None => false\n\n },\n\n last_play: None,\n\n year: 2020,\n\n number: match track.number{\n\n Some(e) => e,\n\n None => 1\n\n },\n\n lossless: match track.lossless{\n\n Some(e) => e,\n\n None => false\n\n },\n\n created_at: track.created_at.to_string(),\n", "file_path": "src/api/search.rs", "rank": 6, "score": 10.435871805202655 }, { "content": "\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\npub struct Artist {\n\n id: i64,\n\n name: String,\n\n picture: Option<String>,\n\n tags: Option<Vec<String>>,\n\n similar: Option<Vec<String>>,\n\n bio: Option<String>,\n\n created_at: String,\n\n updated_at: Option<String>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Genre {\n\n id: i64,\n\n name: String,\n\n created_at: String,\n\n updated_at: Option<String>,\n\n}\n", "file_path": "src/api/search.rs", "rank": 8, "score": 10.090322841661944 }, { "content": "use serde::{Deserialize, Serialize};\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub struct FmArtist {\n\n pub bio: String,\n\n pub tags: Vec<String>,\n\n pub similar: Vec<String>,\n\n}\n\npub async fn get_artist_info(artist: &str) -> anyhow::Result<FmArtist> {\n\n let result: FmSearchResult = reqwest::get(&format!(\"http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist={}&api_key={}&format=json\",artist, std::env!(\"FM_KEY\"))).await?\n\n .json().await?;\n\n Ok(FmArtist{\n\n bio: result.artist.bio.summary,\n\n tags: result.artist.tags.tag.into_iter().map(|t| t.name).collect::<Vec<_>>(),\n\n similar: result.artist.similar.artist.into_iter().map(|t| t.name).collect::<Vec<_>>()\n\n })\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct FmSearchResult {\n", "file_path": "src/index/fm.rs", "rank": 9, "score": 9.633892924989784 }, { "content": "\n\n#[rocket::get(\"/\")]\n\npub async fn main(pool: State<'_, sqlx::sqlite::SqlitePool>) -> Result<Json<Results>, NoContent> {\n\n let recs = sqlx::query!(\n\n r#\"\n\n select id, number, name, path, album, artist, artists, liked, duration, last_play, plays, lossless, genre, created_at, updated_at\n\n from `song`\n\n where album = 1\n\n \"#\n\n )\n\n .fetch_all(&mut pool.acquire().await.unwrap())\n\n .await.unwrap();\n\n\n\n let mut tr: Vec<Track> = vec![];\n\n\n\n for track in recs.into_iter() {\n\n let mut ar: Vec<Artist> = vec![];\n\n\n\n for artist_id in track.artists.unwrap().split(\",\").collect::<Vec<&str>>() {\n\n let artist = sqlx::query!(\n", "file_path": "src/api/search.rs", "rank": 10, "score": 9.617030997667346 }, { "content": " text: String,\n\n size: String,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Similar {\n\n artist: Vec<ArtistElement>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct ArtistElement {\n\n name: String,\n\n url: String,\n\n image: Vec<Image>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Stats {\n\n listeners: String,\n\n playcount: String,\n", "file_path": "src/index/fm.rs", "rank": 11, "score": 9.120555525106722 }, { "content": "use rocket::{State, response::status::NoContent};\n\nuse rocket_contrib::json::Json;\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Results {\n\n tracks: Vec<Track>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Track {\n\n id: i64,\n\n name: String,\n\n artist: String,\n\n path: String,\n\n plays: Option<i64>,\n\n duration: f64,\n\n liked: bool,\n\n last_play: Option<String>, // was serde_json::Value\n\n year: i64,\n", "file_path": "src/api/search.rs", "rank": 12, "score": 8.625466031983668 }, { "content": " artist: SearchResultArtist,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct SearchResultArtist {\n\n name: String,\n\n url: String,\n\n image: Vec<Image>,\n\n streamable: String,\n\n ontour: String,\n\n stats: Stats,\n\n similar: Similar,\n\n tags: Tags,\n\n bio: Bio,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Bio {\n\n links: Links,\n\n published: String,\n", "file_path": "src/index/fm.rs", "rank": 13, "score": 8.610132523981012 }, { "content": " FROM `album`\n\n\n\n where id = $1;\n\n \n\n \"#,\n\n track.album\n\n )\n\n .fetch_one(&mut pool.acquire().await.unwrap())\n\n .await\n\n {\n\n Ok(album) => Album {\n\n id: album.id.unwrap(),\n\n name: album.name,\n\n picture: album.picture.unwrap(),\n\n year: match album.year{\n\n Some(e) => e,\n\n None => 0\n\n },\n\n artist: artisto,\n\n created_at: album.created_at.to_string(),\n", "file_path": "src/api/search.rs", "rank": 14, "score": 8.390140820052878 }, { "content": "use crate::index::metadata::AudioMetadata;\n\nuse md5::{Digest, Md5};\n\nuse sqlx::Sqlite;\n\n\n\npub async fn add_song(metadata: AudioMetadata, pool: sqlx::Pool<Sqlite>) {\n\n // find or create new artist/s\n\n let artist = artist_foc(metadata.clone(), pool.clone()).await.unwrap();\n\n // find/create new album\n\n let album = album_foc(metadata.clone(), artist.clone(), pool.clone())\n\n .await\n\n .unwrap();\n\n // check for genre data, and if so, find/create.\n\n // finally, add our track\n\n let _song = song_foc(metadata, artist, album, pool).await.unwrap();\n\n}\n\n\n\nasync fn artist_foc(metadata: AudioMetadata, pool: sqlx::Pool<Sqlite>) -> anyhow::Result<Vec<i32>> {\n\n let mut artivec: Vec<i32> = vec![];\n\n for arti in metadata.artists {\n\n dbg!(&arti);\n", "file_path": "src/index/db.rs", "rank": 15, "score": 8.31086064925879 }, { "content": " genres: Vec<Option<serde_json::Value>>,\n\n href: String,\n\n id: String,\n\n images: Vec<Image>,\n\n name: String,\n\n popularity: i64,\n\n #[serde(rename = \"type\")]\n\n item_type: String,\n\n uri: String,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct ExternalUrls {\n\n spotify: String,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\npub struct Image {\n\n height: i64,\n\n url: String,\n\n width: i64,\n\n}", "file_path": "src/index/spotify.rs", "rank": 16, "score": 7.907972371240043 }, { "content": " tags: artist_tags,\n\n similar: match artist.similar{\n\n Some(e) => Some(e.split(\",\").map(|s| s.to_string()).collect::<Vec<String>>()),\n\n None => None,\n\n },\n\n bio: artist.bio,\n\n created_at: artist.created_at.to_string(),\n\n updated_at: match track.updated_at {\n\n Some(e) => Some(e.to_string()),\n\n None => None,\n\n },\n\n };\n\n ar.push(art);\n\n }\n\n\n\n let artisto = ar[0].to_owned();\n\n\n\n let album = match sqlx::query!(\n\n r#\"\n\n SELECT id, name, picture, year, created_at, updated_at\n", "file_path": "src/api/search.rs", "rank": 17, "score": 7.906133765318337 }, { "content": " r#\"\n\n select id, name, bio, picture, created_at, updated_at, similar, tags\n\n from `artist`\n\n where id = $1;\n\n \"#,\n\n artist_id\n\n )\n\n .fetch_one(&mut pool.acquire().await.unwrap())\n\n .await\n\n .unwrap();\n\n\n\n let artist_tags = match artist.tags{\n\n Some(e) => Some(e.split(\",\").map(|s| s.to_string()).collect::<Vec<String>>()),\n\n None => None,\n\n };\n\n\n\n let art = Artist {\n\n id: artist.id.unwrap(),\n\n name: artist.name,\n\n picture: artist.picture,\n", "file_path": "src/api/search.rs", "rank": 21, "score": 7.033858817308863 }, { "content": " albums: i64,\n\n artists: i64,\n\n size: i64,\n\n mount: String,\n\n}\n\n\n\n#[rocket::get(\"/info\")]\n\npub async fn info() -> Json<SystemInfo>{\n\n Json(SystemInfo{\n\n version: \"0.0.1\".to_string(),\n\n arch: host::platform().await.unwrap().architecture().as_str().to_string(),\n\n node_version: \"N/A\".to_string(),\n\n num_cpus: num_cpus::get() as i64,\n\n uptime: host::uptime().await.unwrap().get::<units::time::millisecond>() as f64,\n\n free_mem: memory::memory().await.unwrap().free().get::<units::information::byte>() as i64,\n\n id: 1,\n\n start: \"N/A\".to_string(),\n\n end: \"N/A\".to_string(),\n\n last_scan: \"N/A\".to_string(),\n\n seconds: 10.0,\n\n tracks: 0,\n\n albums: 0,\n\n artists: 0,\n\n size: 0,\n\n mount: env::var(\"MOUNT\").unwrap(),\n\n })\n\n}\n", "file_path": "src/api/system.rs", "rank": 22, "score": 7.029305433880676 }, { "content": " INSERT INTO `album` (name, artist, picture, year, created_at)\n\n VALUES ($1, $2, $3, $4, $5);\n\n select id\n\n from `album`\n\n where name = $6;\n\n \"#,\n\n metadata.album,\n\n artist[0],\n\n image_url,\n\n metadata.year,\n\n now,\n\n metadata.album\n\n )\n\n .fetch_all(&mut pool.acquire().await?)\n\n .await\n\n {\n\n Ok(e) => return Ok(e[0].id.unwrap() as i32),\n\n Err(e) => {\n\n return Err(anyhow::format_err!(e));\n\n }\n", "file_path": "src/index/db.rs", "rank": 23, "score": 6.986829552377057 }, { "content": "}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Tags {\n\n tag: Vec<Tag>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Tag {\n\n name: String,\n\n url: String,\n\n}\n", "file_path": "src/index/fm.rs", "rank": 24, "score": 6.827207217110229 }, { "content": " select id\n\n from `song`\n\n where name = $2;\n\n \"#,\n\n n,\n\n metadata.name,\n\n p,\n\n a,\n\n metadata.album_artist,\n\n v,\n\n false,\n\n d,\n\n 0,\n\n metadata.lossless,\n\n \"\",\n\n now,\n\n )\n\n .fetch_all(&mut pool.acquire().await?)\n\n .await\n\n {\n", "file_path": "src/index/db.rs", "rank": 25, "score": 6.4277728415118505 }, { "content": "use base64::encode;\n\nuse serde::{Deserialize, Serialize};\n\nuse std::env;\n\n\n\npub async fn get_artist_image(query: &str) -> anyhow::Result<String> {\n\n let client = reqwest::Client::new();\n\n let key = authorize_spotify().await?;\n\n let res: SpotifyArtistResponse = client\n\n .get(&format!(\n\n \"https://api.spotify.com/v1/search?type=artist&q={}\",\n\n query\n\n ))\n\n .bearer_auth(key)\n\n .send()\n\n .await?\n\n .json()\n\n .await?;\n\n let img = if res.artists.items.len() > 0 {\n\n if res.artists.items[0].images.len() > 0 {\n\n res.artists.items[0].images[0].clone().url\n", "file_path": "src/index/spotify.rs", "rank": 26, "score": 6.397513139684477 }, { "content": " updated_at: match track.updated_at {\n\n Some(e) => Some(e.to_string()),\n\n None => None,\n\n },\n\n artists: ar,\n\n playlists: vec![],\n\n album: album,\n\n genre: genre,\n\n })\n\n }\n\n Ok(Json(Results { tracks: tr }))\n\n}\n", "file_path": "src/api/search.rs", "rank": 27, "score": 6.294722670180907 }, { "content": "\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct SpotifyArtistResponse {\n\n artists: Artists,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Artists {\n\n href: String,\n\n items: Vec<Item>,\n\n limit: i64,\n\n next: Option<serde_json::Value>,\n\n offset: i64,\n\n previous: Option<serde_json::Value>,\n\n total: i64,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Item {\n\n external_urls: ExternalUrls,\n", "file_path": "src/index/spotify.rs", "rank": 28, "score": 6.2248122648284125 }, { "content": "## <img src=\"https://cdn.statically.io/img/raw.githubusercontent.com/w=700/kanbaru/kyoku/main/kyoku.png\" width=\"450px\">\n\nrusty music server\n\n\n\nmeant to be used with [waveline player](https://player.waveline.app) but currently not compatible.\n\n\n\nnote: this is absolutely not done by any means. anything can and will change.\n\n### API\n\n#### System\n\n|Done|Path|Description|Queries/Notes\n\n|-|-|-|-|\n\n[ ]|`GET /system/info`|Get stats about the server|N/A|\n\n\n\n#### Tracks\n\n|Done|Path|Description|Queries/Notes\n\n|-|-|-|-|\n\n[ ]|`GET /tracks`|Get information about a track|`?album=:int` - find songs where album id is the number|\n\n||||`?skip=:int&limit:int` - used for paging\n\n[ ]|`GET /tracks/:id`|Get information about a track|N/A|\n\n[ ]|`GET /tracks/:id/stream`|Stream a track|`?transcode=:bool` - transcode the song or not|\n\n[ ]|`GET /tracks/:id/like`|Get whether you liked the track|`?liked=:bool` - toggle song likage|\n\n\n\n#### Albums\n\n|Done|Path|Description|Queries/Notes\n\n|-|-|-|-|\n\n[ ]|`GET /albums/`|Get all albums|`?skip=:int`/`?index=:int` - which index to start at (used for paging)|\n\n||||`?limit=:int` - the max albums the endpoint will return, defaults to 10\n\n||||`?artist=:string` - self-explanatory\n\n[ ]|`GET /albums/:id`|Get information about an album|N/A|\n\n[ ]|`GET /albums/:id/art`|Get an album's art|N/A|\n\n\n\n#### Artist\n\n|Done|Path|Description|Queries/Notes\n\n|-|-|-|-|\n\n[ ]|`GET /artists/`|Get all artists|`?skip=:int`/`?index=:int` - which index to start at (used for paging)|\n\n||||`?limit=:int` - the max artists the endpoint will return, defaults to 10\n\n[ ]|`GET /artists/:id`|Get information about an artist|N/A|\n\n\n\n#### Search\n\n|Done|Path|Description|Queries/Notes\n\n|-|-|-|-|\n\n[ ]|`GET /search`|Get information about a track|`?q=:string` - search for your query!|\n\n||||Note: returns all categories\n\n\n\n### Licence\n\nThis software is released under the MIT licence.\n", "file_path": "readme.md", "rank": 29, "score": 6.04844601551814 }, { "content": " updated_at: match track.updated_at {\n\n Some(e) => Some(e.to_string()),\n\n None => None,\n\n },\n\n },\n\n Err(e) => {\n\n dbg!(e);\n\n return Err(NoContent)\n\n },\n\n };\n\n\n\n let genre = match sqlx::query!(\n\n r#\"\n\n SELECT id, name, created_at, updated_at\n\n FROM `album`\n\n\n\n where id = $1;\n\n \n\n \"#,\n\n track.genre\n", "file_path": "src/api/search.rs", "rank": 30, "score": 5.576012743258022 }, { "content": " Err(e) => return Err(anyhow::format_err!(e)),\n\n };\n\n }\n\n }\n\n Err(e) => return Err(anyhow::format_err!(e)),\n\n };\n\n }\n\n Ok(artivec)\n\n}\n\n\n\nasync fn album_foc(\n\n metadata: AudioMetadata,\n\n artist: Vec<i32>,\n\n pool: sqlx::Pool<Sqlite>,\n\n) -> anyhow::Result<i32> {\n\n let _ = match sqlx::query!(\n\n r#\"\n\n select id\n\n from `album`\n\n where name = $1;\n", "file_path": "src/index/db.rs", "rank": 31, "score": 5.56496984331994 }, { "content": " let _artist = match sqlx::query!(\n\n r#\"\n\n select id\n\n from `artist`\n\n where name = $1;\n\n \"#,\n\n arti\n\n )\n\n .fetch_all(&mut pool.acquire().await?)\n\n .await\n\n {\n\n Ok(e) => {\n\n if e.len() > 0 {\n\n artivec.push(e[0].id.unwrap() as i32)\n\n } else {\n\n let fm_info = crate::index::fm::get_artist_info(&metadata.album_artist).await?;\n\n let artist_image = crate::index::spotify::get_artist_image(&arti).await?;\n\n let now = chrono::offset::Utc::now().to_rfc3339();\n\n let similar = fm_info.similar.join(\",\");\n\n let tags = fm_info.tags.join(\",\");\n", "file_path": "src/index/db.rs", "rank": 32, "score": 5.264879084132643 }, { "content": " };\n\n }\n\n }\n\n Err(e) => {\n\n return Err(anyhow::format_err!(e));\n\n }\n\n };\n\n}\n\n\n\nasync fn song_foc(\n\n metadata: AudioMetadata,\n\n artist: Vec<i32>,\n\n album: i32,\n\n pool: sqlx::Pool<Sqlite>,\n\n) -> anyhow::Result<i32> {\n\n let _ = match sqlx::query!(\n\n r#\"\n\n select id\n\n from `song`\n\n where name = $1;\n", "file_path": "src/index/db.rs", "rank": 33, "score": 5.248649650998941 }, { "content": " summary: String,\n\n content: String,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Links {\n\n link: Link,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Link {\n\n #[serde(rename = \"#text\")]\n\n text: String,\n\n rel: String,\n\n href: String,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct Image {\n\n #[serde(rename = \"#text\")]\n", "file_path": "src/index/fm.rs", "rank": 34, "score": 5.125730226614481 }, { "content": " match sqlx::query!(\n\n r#\"\n\n INSERT INTO `artist` (name, bio, picture, created_at, similar, tags)\n\n VALUES($1, $2, $3, $4, $5, $6);\n\n select id\n\n from `artist`\n\n where name = $1;\n\n \"#,\n\n arti,\n\n fm_info.bio,\n\n artist_image,\n\n now,\n\n similar,\n\n tags,\n\n arti\n\n )\n\n .fetch_all(&mut pool.acquire().await?)\n\n .await\n\n {\n\n Ok(e) => artivec.push(e[0].id.unwrap() as i32),\n", "file_path": "src/index/db.rs", "rank": 35, "score": 4.512970382256912 }, { "content": " }\n\n}\n\n\n\npub async fn scan<P: AsRef<Path>>(path: P, pool:sqlx::Pool<Sqlite>) {\n\n // wait for other stuff to finish logging\n\n // will remove this sooner or later\n\n thread::sleep(time::Duration::from_millis(250));\n\n for entry in WalkDir::new(path).sort(true) {\n\n let ent = &entry.unwrap();\n\n if ent.path().is_file() {\n\n metadata::scan_file(&ent.path(), pool.clone()).await;\n\n }\n\n }\n\n}\n\n\n\npub async fn watch<P: AsRef<Path>>(path: P, pool:sqlx::Pool<Sqlite>) -> notify::Result<()> {\n\n let (tx, rx) = std::sync::mpsc::channel();\n\n\n\n // Automatically select the best implementation for your platform.\n\n // You can also access each implementation directly e.g. INotifyWatcher.\n", "file_path": "src/index/mod.rs", "rank": 36, "score": 4.327993368442222 }, { "content": " )\n\n .fetch_one(&mut pool.acquire().await.unwrap())\n\n .await{\n\n Ok(genre) => Some(Genre {\n\n id: genre.id.unwrap(),\n\n name: genre.name,\n\n created_at: genre.created_at.to_string(),\n\n updated_at: match track.updated_at {\n\n Some(e) => Some(e.to_string()),\n\n None => None,\n\n },\n\n }),\n\n Err(_) => None,\n\n };\n\n\n\n tr.push(Track {\n\n id: match track.id{\n\n Some(e) => e,\n\n None => 0\n\n },\n", "file_path": "src/api/search.rs", "rank": 37, "score": 4.18744327026525 }, { "content": "use std::env;\n\nuse rocket_contrib::json::Json;\n\nuse serde::Serialize;\n\n\n\nuse heim::{memory, host, units};\n\n\n\n#[derive(Serialize)]\n\npub struct SystemInfo {\n\n version: String,\n\n arch: String,\n\n node_version: String,\n\n num_cpus: i64,\n\n uptime: f64,\n\n free_mem: i64,\n\n id: i64,\n\n start: String,\n\n end: String,\n\n last_scan: String,\n\n seconds: f64,\n\n tracks: i64,\n", "file_path": "src/api/system.rs", "rank": 38, "score": 4.091718689830823 }, { "content": " encode(format!(\n\n \"{}:{}\",\n\n env::var(\"SPOTIFY_ID\").unwrap(),\n\n env::var(\"SPOTIFY_SECRET\").unwrap()\n\n ))\n\n ),\n\n )\n\n .send()\n\n .await?\n\n .json()\n\n .await?;\n\n Ok(resp.access_token)\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct TokenResponse {\n\n access_token: String,\n\n token_type: String,\n\n expires_in: i32,\n\n}\n", "file_path": "src/index/spotify.rs", "rank": 39, "score": 3.847697822013936 }, { "content": " \"#,\n\n metadata.album,\n\n )\n\n .fetch_all(&mut pool.acquire().await?)\n\n .await\n\n {\n\n Ok(e) => {\n\n if e.len() > 0 {\n\n return Ok(e[0].id.unwrap() as i32);\n\n } else {\n\n let image_url = match metadata.picture {\n\n Some(e) => match save_image_md5(e.bytes).await {\n\n Ok(e) => e,\n\n Err(_) => \"https://http.cat/450\".to_string(),\n\n },\n\n None => \"https://http.cat/404\".to_string(),\n\n };\n\n let now = chrono::offset::Utc::now().to_rfc3339();\n\n let _ = match sqlx::query!(\n\n r#\"\n", "file_path": "src/index/db.rs", "rank": 40, "score": 3.547478423193253 }, { "content": "use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};\n\nuse std::env;\n\n\n\npub async fn get_pool() -> anyhow::Result<SqlitePool, anyhow::Error> {\n\n let pool = SqlitePoolOptions::new()\n\n .max_connections(50)\n\n .min_connections(1)\n\n .max_lifetime(std::time::Duration::from_secs(10))\n\n .connect(&env::var(\"DATABASE_URL\")?)\n\n .await?;\n\n println!(\n\n \"Connected to the database at url {}\",\n\n &env::var(\"DATABASE_URL\")?\n\n );\n\n Ok(pool)\n\n}", "file_path": "src/db.rs", "rank": 41, "score": 3.0816816817147954 }, { "content": "pub mod system;\n\npub mod search;", "file_path": "src/api/mod.rs", "rank": 42, "score": 2.784859325711508 }, { "content": "mod api;\n\nmod db;\n\nmod index;\n\n\n\n#[tokio::main]\n\nasync fn main() -> anyhow::Result<()> {\n\n dotenv::dotenv()?;\n\n let path = std::env::var(\"MOUNT\")?;\n\n\n\n let pool = db::get_pool().await?;\n\n let p_cloned = pool.clone();\n\n\n\n // start indexing/scanning in new thread\n\n tokio::spawn(async move {\n\n index::start(path.clone(), &path, p_cloned).await;\n\n });\n\n\n\n // start up our web server\n\n // dunno if i want this in a separate thread or not\n\n rocket(pool).await?;\n", "file_path": "src/main.rs", "rank": 43, "score": 2.730662978594123 }, { "content": "mod metadata;\n\nmod db;\n\nmod fm;\n\nmod spotify;\n\n\n\nuse sqlx::Sqlite;\n\nuse notify::{RecommendedWatcher, RecursiveMode, Watcher};\n\nuse notify::event::EventKind;\n\nuse std::{path::Path, thread, time};\n\nuse jwalk::{WalkDir};\n\n\n\npub async fn start<P: AsRef<Path>>(path: P, pathstr:&str, pool:sqlx::Pool<Sqlite>) {\n\n if Path::new(&pathstr).is_file(){\n\n return println!(\"critical error !!!!!\\nthe path {} is not a folder.\",&pathstr)\n\n }\n\n println!(\"scanning folder {:?}\", &pathstr);\n\n scan(&path, pool.clone()).await;\n\n println!(\"watching folder {:?}\", pathstr);\n\n if let Err(e) = watch(path, pool).await {\n\n println!(\"error: {:?}\", e)\n", "file_path": "src/index/mod.rs", "rank": 44, "score": 2.462876037592971 }, { "content": " } else {\n\n \"https://http.cat/404.jpg\".to_string()\n\n }\n\n } else {\n\n // TODO look somewhere else for this\n\n \"https://http.cat/450.jpg\".to_string()\n\n };\n\n Ok(img)\n\n}\n\n\n\nasync fn authorize_spotify() -> anyhow::Result<String> {\n\n let client = reqwest::Client::new();\n\n let form = [(\"grant_type\", \"client_credentials\")];\n\n let resp: TokenResponse = client\n\n .post(&format!(\"https://accounts.spotify.com/api/token\"))\n\n .form(&form)\n\n .header(\n\n \"Authorization\",\n\n format!(\n\n \"Basic {}\",\n", "file_path": "src/index/spotify.rs", "rank": 45, "score": 2.2448412910947857 }, { "content": " let mut watcher: RecommendedWatcher = Watcher::new_immediate(move |res| tx.send(res).unwrap())?;\n\n\n\n // Add a path to be watched. All files and directories at that path and\n\n // below will be monitored for changes.\n\n watcher.watch(path, RecursiveMode::Recursive)?;\n\n\n\n for res in rx {\n\n match res {\n\n Ok(event) => parse_event(event, pool.clone()).await,\n\n Err(e) => println!(\"watch error: {:?}\", e),\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\nasync fn parse_event(event: notify::event::Event,pool:sqlx::Pool<Sqlite>) {\n\n match event.kind {\n\n // we sleep here until windows stops messing around with our file smh!\n\n EventKind::Create(_) => {thread::sleep(time::Duration::from_millis(75));\n\n metadata::scan_file(&event.paths[0], pool).await\n\n },\n\n EventKind::Remove(_) => println!(\"removed {}\", event.paths[0].to_str().unwrap()),\n\n EventKind::Modify(_) =>return,\n\n EventKind::Access(_) =>return,\n\n EventKind::Any => return,\n\n EventKind::Other => return,\n\n }\n\n}", "file_path": "src/index/mod.rs", "rank": 46, "score": 2.2338750999754313 }, { "content": " Ok(e) => return Ok(e[0].id.unwrap() as i32),\n\n Err(e) => {\n\n return Err(anyhow::format_err!(e));\n\n }\n\n };\n\n }\n\n }\n\n Err(e) => {\n\n return Err(anyhow::format_err!(e));\n\n }\n\n };\n\n}\n\n\n\nasync fn save_image_md5(bytes: Vec<u8>) -> anyhow::Result<String> {\n\n // create a Md5 hasher instance\n\n let hash = Md5::digest(&bytes);\n\n\n\n let dest = format! {\"./art/{:x}.png\",&hash};\n\n let mut out = tokio::fs::File::create(&dest).await?;\n\n tokio::io::copy(&mut &*bytes, &mut out).await?;\n\n Ok(dest)\n\n}\n", "file_path": "src/index/db.rs", "rank": 47, "score": 1.3235707010537687 } ]
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_commit = CommitMessage::from(existing_contents.clone());\n\n let has_bodies = existing_commit\n\n .get_body()\n\n .iter()\n\n .filter(|body| !body.is_empty())\n\n .count();\n\n\n\n let commit = match ConventionalCommit::try_from(existing_commit.clone()) {\n\n Ok(previous_conventional) => ui::ask_user(&config, Some(previous_conventional))?.into(),\n\n Err(_) if has_bodies == 0 => ui::ask_user(&config, None)?.into(),\n\n Err(_) => ui::ask_fallback(&existing_contents)?,\n\n };\n\n\n\n let mut commit_file = File::create(&buf).into_diagnostic()?;\n\n writeln!(commit_file, \"{}\", String::from(commit.clone())).into_diagnostic()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/commands/editor.rs", "rank": 6, "score": 94458.45187361688 }, { "content": "fn is_scope_in_config(\n\n config: &FastConventionalConfig,\n\n conventional_commit: &ConventionalCommit,\n\n) -> bool {\n\n match &conventional_commit.scope {\n\n None => !config.get_require_scope(),\n\n Some(scope) => {\n\n let expected_scope: String = scope.clone().into();\n\n config.get_scopes().contains(&expected_scope)\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::models::GitShortRef;\n\n use crate::FastConventionalConfig;\n\n use mit_commit::CommitMessage;\n\n\n", "file_path": "src/service/commit_validatator.rs", "rank": 7, "score": 87087.38737350915 }, { "content": "type ParserOutput<'a> = (&'a str, (&'a str, Option<&'a str>, Option<&'a str>));\n\n\n\nimpl Commit {\n\n pub fn type_index(&self, option: Vec<String>) -> usize {\n\n option\n\n .into_iter()\n\n .position(|option| self.type_slug == option.into())\n\n .unwrap_or_default()\n\n }\n\n\n\n pub fn scope_index(&self, option: Vec<String>) -> usize {\n\n self.scope.as_ref().map_or(0, |scope| {\n\n option\n\n .into_iter()\n\n .position(|option| scope.0 == option)\n\n .unwrap_or_default()\n\n })\n\n }\n\n\n\n fn parse(text: &'_ str) -> Result<ParserOutput<'_>> {\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 8, "score": 85058.7293251073 }, { "content": "fn is_type_slug_in_config(\n\n config: &FastConventionalConfig,\n\n conventional_commit: &ConventionalCommit,\n\n) -> bool {\n\n let type_slug: String = conventional_commit.type_slug.clone().into();\n\n config.get_types().contains(&type_slug)\n\n}\n\n\n", "file_path": "src/service/commit_validatator.rs", "rank": 9, "score": 84491.70553373113 }, { "content": "pub fn run(\n\n repository_path: PathBuf,\n\n revision_selection: Option<GitRevisionSelection>,\n\n config_path: PathBuf,\n\n) -> Result<()> {\n\n let config: FastConventionalConfig = config_path.try_into()?;\n\n let repository = GitRepository::try_from(repository_path)?;\n\n let commits = repository.list_commits(revision_selection)?;\n\n let (_, failed) = commit_validatator::run(&config, commits.clone());\n\n\n\n for pair in &commits {\n\n if failed.contains_key(&pair.0) {\n\n eprintln!(\"[✘] {}\", pair.1.get_subject());\n\n } else {\n\n println!(\"[✔] {}\", pair.1.get_subject());\n\n }\n\n }\n\n\n\n if failed.is_empty() {\n\n Ok(())\n", "file_path": "src/commands/validate.rs", "rank": 10, "score": 72805.27644696046 }, { "content": "pub fn run() -> Result<()> {\n\n let config = FastConventionalConfig {\n\n use_angular: Some(true),\n\n require_scope: None,\n\n types: Some(vec![\"custom_type\".to_string()]),\n\n scopes: Some(vec![\n\n \"src\".to_string(),\n\n \"actions\".to_string(),\n\n \"manpages\".to_string(),\n\n \"readme\".to_string(),\n\n \"e2e\".to_string(),\n\n \"unit\".to_string(),\n\n ]),\n\n };\n\n\n\n let example: String = config.try_into()?;\n\n\n\n println!(\"{}\", example);\n\n\n\n Ok(())\n\n}\n", "file_path": "src/commands/example.rs", "rank": 12, "score": 69444.67725467225 }, { "content": "pub fn run<'a, 'b>(\n\n config: &'a FastConventionalConfig,\n\n commit_messages: Vec<(GitShortRef, CommitMessage<'b>)>,\n\n) -> (\n\n BTreeMap<GitShortRef, CommitMessage<'b>>,\n\n BTreeMap<GitShortRef, CommitMessage<'b>>,\n\n) {\n\n commit_messages.into_iter().partition(is_valid_with(config))\n\n}\n\n\n", "file_path": "src/service/commit_validatator.rs", "rank": 13, "score": 68167.82452142783 }, { "content": "pub fn run(shell: Shell) {\n\n let mut cmd = cli::Args::command();\n\n let bin_name = cmd.get_name().to_string();\n\n generate(shell, &mut cmd, bin_name, &mut io::stdout());\n\n}\n", "file_path": "src/commands/completion.rs", "rank": 14, "score": 66444.02446750978 }, { "content": "fn uses_configured_values(\n\n config: &FastConventionalConfig,\n\n conventional_commit: &ConventionalCommit,\n\n) -> bool {\n\n is_type_slug_in_config(config, conventional_commit)\n\n && is_scope_in_config(config, conventional_commit)\n\n}\n\n\n", "file_path": "src/service/commit_validatator.rs", "rank": 15, "score": 58884.6414835528 }, { "content": "fn main() -> Result<()> {\n\n miette::set_panic_hook();\n\n\n\n let args = cli::Args::parse();\n\n\n\n match args.command {\n\n cli::Commands::Completion { shell } => {\n\n commands::completion(shell);\n\n Ok(())\n\n }\n\n cli::Commands::ExampleConfig => commands::example(),\n\n cli::Commands::Editor {\n\n commit_message_path,\n\n config_path,\n\n } => commands::editor(commit_message_path, config_path),\n\n cli::Commands::Validate {\n\n repository_path,\n\n revision_selection,\n\n config_path,\n\n } => commands::validate(repository_path, revision_selection, config_path),\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 16, "score": 34564.06065175731 }, { "content": "fn is_valid_with(\n\n config: &FastConventionalConfig,\n\n) -> impl Fn(&(GitShortRef, CommitMessage<'_>)) -> bool + '_ {\n\n |message: &(GitShortRef, CommitMessage<'_>)| -> bool {\n\n match ConventionalCommit::try_from(message.clone().1) {\n\n Ok(conventional_commit) => uses_configured_values(config, &conventional_commit),\n\n Err(_) => false,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/service/commit_validatator.rs", "rank": 17, "score": 34217.795212333775 }, { "content": "use std::str::FromStr;\n\n\n\nuse miette::Diagnostic;\n\nuse thiserror::Error;\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct RevisionSelection(String);\n\n\n\nimpl RevisionSelection {\n\n pub fn is_single_commit(&self) -> bool {\n\n !self.0.contains(\"..\")\n\n }\n\n}\n\n\n\nimpl FromStr for RevisionSelection {\n\n type Err = ParseError;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n Ok(Self(s.to_string()))\n\n }\n", "file_path": "src/models/git/revision_selection.rs", "rank": 18, "score": 28181.94434130665 }, { "content": "}\n\n\n\nimpl From<RevisionSelection> for String {\n\n fn from(r: RevisionSelection) -> Self {\n\n r.0\n\n }\n\n}\n\n\n\n#[non_exhaustive]\n\n#[derive(Error, Debug, Diagnostic, Copy, Clone)]\n\n#[error(\"This does not look like a valid git revision or range\")]\n\n#[diagnostic(\n\n code(models::git_access::revision_or_range::revision_or_range_parse_error),\n\n url(\"https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection\")\n\n)]\n\npub struct ParseError;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/models/git/revision_selection.rs", "rank": 19, "score": 28175.687751313322 }, { "content": "\n\n #[test]\n\n fn can_be_created_from_str() {\n\n assert_eq!(\n\n RevisionSelection::from_str(\"HEAD\").unwrap(),\n\n RevisionSelection(\"HEAD\".to_string())\n\n );\n\n }\n\n\n\n #[test]\n\n fn can_be_converted_to_a_str() {\n\n let selection = RevisionSelection::from_str(\"HEAD\").unwrap();\n\n let actual: String = selection.into();\n\n assert_eq!(&actual, \"HEAD\");\n\n }\n\n\n\n #[test]\n\n fn can_tell_me_it_is_a_single_commit() {\n\n let selection = RevisionSelection::from_str(\"HEAD\").unwrap();\n\n assert!(&selection.is_single_commit());\n\n }\n\n\n\n #[test]\n\n fn can_tell_me_it_is_a_range_of_commits() {\n\n let selection = RevisionSelection::from_str(\"..HEAD\").unwrap();\n\n assert!(!&selection.is_single_commit());\n\n }\n\n}\n", "file_path": "src/models/git/revision_selection.rs", "rank": 20, "score": 28174.766463814467 }, { "content": "#[derive(Clone, PartialOrd, PartialEq, Debug)]\n\npub enum Change {\n\n BreakingWithMessage(String),\n\n Compatible,\n\n BreakingWithoutMessage,\n\n}\n\n\n\nimpl Default for Change {\n\n fn default() -> Self {\n\n Self::Compatible\n\n }\n\n}\n\n\n\nimpl From<Option<String>> for Change {\n\n fn from(change: Option<String>) -> Self {\n\n match change {\n\n None => Self::Compatible,\n\n Some(text) if text.is_empty() => Self::BreakingWithoutMessage,\n\n Some(text) => Self::BreakingWithMessage(text),\n\n }\n", "file_path": "src/models/conventional_commit/change.rs", "rank": 21, "score": 28088.32588216924 }, { "content": "\n\n #[test]\n\n fn from_string_without_message() {\n\n assert_eq!(Change::from(\"\".to_string()), Change::BreakingWithoutMessage);\n\n }\n\n #[test]\n\n fn from_str_with_message() {\n\n assert_eq!(\n\n Change::from(\"Abc\"),\n\n Change::BreakingWithMessage(\"Abc\".into())\n\n );\n\n }\n\n\n\n #[test]\n\n fn from_str_without_message() {\n\n assert_eq!(Change::from(\"\"), Change::BreakingWithoutMessage);\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/change.rs", "rank": 22, "score": 28084.594876069903 }, { "content": " }\n\n}\n\n\n\nimpl From<String> for Change {\n\n fn from(value: String) -> Self {\n\n if value.is_empty() {\n\n Self::BreakingWithoutMessage\n\n } else {\n\n Self::BreakingWithMessage(value)\n\n }\n\n }\n\n}\n\n\n\nimpl From<&str> for Change {\n\n fn from(value: &str) -> Self {\n\n if value.is_empty() {\n\n Self::BreakingWithoutMessage\n\n } else {\n\n Self::BreakingWithMessage(value.to_string())\n\n }\n", "file_path": "src/models/conventional_commit/change.rs", "rank": 23, "score": 28083.791806001293 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn defaults_to_compatible() {\n\n assert_eq!(Change::default(), Change::Compatible);\n\n }\n\n\n\n #[test]\n\n fn from_option_string_with_message() {\n\n assert_eq!(\n\n Change::from(Some(\"Abc\".to_string())),\n\n Change::BreakingWithMessage(\"Abc\".into())\n\n );\n\n }\n\n\n", "file_path": "src/models/conventional_commit/change.rs", "rank": 24, "score": 28082.01074002301 }, { "content": " #[test]\n\n fn from_option_string_with_out_message() {\n\n assert_eq!(\n\n Change::from(Some(\"\".to_string())),\n\n Change::BreakingWithoutMessage\n\n );\n\n }\n\n\n\n #[test]\n\n fn from_option_string_with_none() {\n\n assert_eq!(Change::from(None), Change::Compatible);\n\n }\n\n\n\n #[test]\n\n fn from_string_with_message() {\n\n assert_eq!(\n\n Change::from(\"Abc\".to_string()),\n\n Change::BreakingWithMessage(\"Abc\".into())\n\n );\n\n }\n", "file_path": "src/models/conventional_commit/change.rs", "rank": 25, "score": 28081.02466897192 }, { "content": "#[derive(Clone, PartialOrd, PartialEq, Default, Debug)]\n\npub struct Scope(pub String);\n\n\n\nimpl From<String> for Scope {\n\n fn from(contents: String) -> Self {\n\n Self(contents)\n\n }\n\n}\n\n\n\nimpl From<&str> for Scope {\n\n fn from(contents: &str) -> Self {\n\n Self(contents.into())\n\n }\n\n}\n\n\n\nimpl From<Scope> for String {\n\n fn from(contents: Scope) -> Self {\n\n contents.0\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/scope.rs", "rank": 26, "score": 28080.30397378039 }, { "content": " assert!(*\"Other\" != *\"Hello\",);\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_str() {\n\n assert_eq!(Scope::from(\"Hello\"), Scope(\"Hello\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_string() {\n\n assert_eq!(Scope::from(\"Hello\".to_string()), Scope(\"Hello\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn can_create_string_from() {\n\n assert_eq!(\n\n String::from(Scope(\"Hello\".to_string())),\n\n \"Hello\".to_string()\n\n );\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/scope.rs", "rank": 27, "score": 28076.57092497 }, { "content": "\n\nimpl PartialEq<String> for Scope {\n\n fn eq(&self, other: &String) -> bool {\n\n &self.clone().0 == other\n\n }\n\n}\n\n\n\nimpl PartialEq<Scope> for String {\n\n fn eq(&self, other: &Scope) -> bool {\n\n &other.0 == self\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn can_be_compared_to_a_string() {\n\n assert!(*\"Hello\" == *\"Hello\",);\n", "file_path": "src/models/conventional_commit/scope.rs", "rank": 28, "score": 28076.31816560333 }, { "content": "use mit_commit::Bodies;\n\n\n\n#[derive(Clone, PartialOrd, PartialEq, Default, Debug)]\n\npub struct Body(pub(crate) String);\n\n\n\nimpl Body {\n\n pub(crate) fn is_empty(&self) -> bool {\n\n self.0.is_empty()\n\n }\n\n}\n\n\n\nimpl From<String> for Body {\n\n fn from(contents: String) -> Self {\n\n Self(contents.trim().to_string())\n\n }\n\n}\n\n\n\nimpl From<Option<String>> for Body {\n\n fn from(contents: Option<String>) -> Self {\n\n match contents {\n", "file_path": "src/models/conventional_commit/body.rs", "rank": 29, "score": 28033.38973777249 }, { "content": " None => Self::from(\"\"),\n\n Some(contents) => Self::from(contents),\n\n }\n\n }\n\n}\n\n\n\nimpl From<&str> for Body {\n\n fn from(contents: &str) -> Self {\n\n Self::from(contents.to_string())\n\n }\n\n}\n\n\n\nimpl<'a> From<&'a Body> for &'a str {\n\n fn from(contents: &'a Body) -> Self {\n\n &contents.0\n\n }\n\n}\n\n\n\nimpl From<Bodies<'_>> for Body {\n\n fn from(contents: Bodies<'_>) -> Self {\n", "file_path": "src/models/conventional_commit/body.rs", "rank": 30, "score": 28030.078781745033 }, { "content": " Self::from(contents.to_string())\n\n }\n\n}\n\n\n\nimpl From<Body> for String {\n\n fn from(contents: Body) -> Self {\n\n contents.0\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use mit_commit::Bodies;\n\n\n\n #[test]\n\n fn can_be_created_from_string() {\n\n assert_eq!(Body::from(\"Hello\".to_string()), Body(\"Hello\".to_string()));\n\n }\n\n\n", "file_path": "src/models/conventional_commit/body.rs", "rank": 31, "score": 28029.244465415282 }, { "content": " #[test]\n\n fn it_can_tell_me_if_it_is_empty() {\n\n assert!(Body::from(\"\".to_string()).is_empty());\n\n }\n\n\n\n #[test]\n\n fn it_can_tell_me_if_it_is_not_empty() {\n\n assert!(!Body::from(\"Something\".to_string()).is_empty());\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_str() {\n\n assert_eq!(Body::from(\"Hello\"), Body(\"Hello\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_option_string() {\n\n assert_eq!(\n\n Body::from(Some(\"Hello\".to_string())),\n\n Body(\"Hello\".to_string())\n", "file_path": "src/models/conventional_commit/body.rs", "rank": 32, "score": 28028.51963959212 }, { "content": " );\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_empty_option_string() {\n\n assert_eq!(Body::from(None), Body(\"\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_commit_message_bodies() {\n\n let input: Vec<mit_commit::Body<'_>> = vec![\"Hello\".to_string().into()];\n\n assert_eq!(Body::from(Bodies::from(input)), Body(\"Hello\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn can_create_string_from() {\n\n assert_eq!(String::from(Body(\"Hello\".to_string())), \"Hello\".to_string());\n\n }\n\n\n\n #[test]\n\n fn trailing_whitespace_is_trimmed() {\n\n assert_eq!(\n\n Body::from(\" Hello \"),\n\n Body(\"Hello\".to_string())\n\n );\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/body.rs", "rank": 33, "score": 28028.25000525502 }, { "content": "use serde::Deserialize;\n\nuse serde::Serialize;\n\nuse std::collections::BTreeSet;\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\nuse miette::Diagnostic;\n\nuse thiserror::Error;\n\n\n\nconst ANGULAR_TYPES: [&str; 10] = [\n\n \"feat\", \"fix\", \"docs\", \"style\", \"refactor\", \"perf\", \"test\", \"chore\", \"build\", \"ci\",\n\n];\n\n\n\n#[non_exhaustive]\n\n#[derive(Debug, PartialEq, Serialize, Deserialize, Default)]\n\npub struct FastConventionalConfig {\n\n pub(crate) use_angular: Option<bool>,\n\n pub(crate) require_scope: Option<bool>,\n\n pub(crate) types: Option<Vec<String>>,\n\n pub(crate) scopes: Option<Vec<String>>,\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 34, "score": 27587.090541255122 }, { "content": "}\n\n\n\nimpl FastConventionalConfig {\n\n pub(crate) fn get_require_scope(&self) -> bool {\n\n self.require_scope.unwrap_or(false)\n\n }\n\n}\n\n\n\nimpl FastConventionalConfig {\n\n pub(crate) fn get_scopes(&self) -> BTreeSet<String> {\n\n self.scopes\n\n .clone()\n\n .unwrap_or_default()\n\n .into_iter()\n\n .collect()\n\n }\n\n\n\n pub(crate) fn get_types(&self) -> BTreeSet<String> {\n\n let user_types: BTreeSet<String> =\n\n self.types.clone().unwrap_or_default().into_iter().collect();\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 35, "score": 27585.161191206782 }, { "content": " .map(String::from)\n\n .collect();\n\n\n\n assert_eq!(actual.get_types(), expected_types);\n\n assert_eq!(actual.get_scopes(), expected_scopes);\n\n }\n\n\n\n #[test]\n\n fn it_can_be_created_from_an_arg_matches() {\n\n let mut temp_file =\n\n tempfile::NamedTempFile::new().expect(\"failed to create temporary file\");\n\n let path = temp_file.path().to_path_buf();\n\n\n\n write!(temp_file, r#\"types: [ci]\"#).expect(\"failed to write test config\");\n\n\n\n let actual: FastConventionalConfig = path.try_into().expect(\"Yaml unexpectedly invalid\");\n\n\n\n assert_eq!(actual.get_types(), BTreeSet::from([\"ci\".to_string()]));\n\n assert_eq!(actual.get_scopes(), BTreeSet::new());\n\n }\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 36, "score": 27584.374506617303 }, { "content": " let input = r#\"types: [ci]\n\nscopes: [\"mergify\", \"just\", \"github\"]\"#;\n\n\n\n let actual: FastConventionalConfig = input.try_into().expect(\"Yaml unexpectedly invalid\");\n\n let expected_types = BTreeSet::from([\"ci\".to_string()]);\n\n let expected_scopes = BTreeSet::from([\n\n \"mergify\".to_string(),\n\n \"just\".to_string(),\n\n \"github\".to_string(),\n\n ]);\n\n\n\n assert_eq!(actual.get_types(), expected_types);\n\n assert_eq!(actual.get_scopes(), expected_scopes);\n\n }\n\n\n\n #[test]\n\n fn adds_angular_types_on_flag() {\n\n let input = r#\"use_angular: true\n\ntypes: [additional]\n\nscopes: [\"mergify\", \"just\", \"github\"]\"#;\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 37, "score": 27583.451110274415 }, { "content": " fn try_from(value: FastConventionalConfig) -> Result<Self, Self::Error> {\n\n Ok(serde_yaml::to_string(&value)?)\n\n }\n\n}\n\n\n\nimpl TryFrom<&str> for FastConventionalConfig {\n\n type Error = YamlReadError;\n\n\n\n fn try_from(filename: &str) -> Result<Self, Self::Error> {\n\n Ok(serde_yaml::from_str(filename)?)\n\n }\n\n}\n\n\n\nimpl TryFrom<PathBuf> for FastConventionalConfig {\n\n type Error = YamlReadError;\n\n\n\n fn try_from(filename: PathBuf) -> Result<Self, Self::Error> {\n\n let file = File::open(filename)?;\n\n Ok(serde_yaml::from_reader(file)?)\n\n }\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 38, "score": 27582.477234190585 }, { "content": "#[non_exhaustive]\n\n#[derive(Error, Debug, Diagnostic)]\n\n#[error(transparent)]\n\n#[diagnostic(\n\n code(models::fast_conventional_config::yaml_generate_error),\n\n url(docsrs)\n\n)]\n\npub enum YamlGenerateError {\n\n Yaml(#[from] serde_yaml::Error),\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use std::io::Write;\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn can_be_created_from_string() {\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 39, "score": 27582.461672997328 }, { "content": "}\n\n\n\n#[non_exhaustive]\n\n#[derive(Error, Debug, Diagnostic)]\n\n#[error(transparent)]\n\n#[diagnostic(code(models::fast_conventional_config::config_read_error), url(docsrs))]\n\npub enum ConfigReadError {\n\n Io(#[from] std::io::Error),\n\n Yaml(#[from] YamlReadError),\n\n}\n\n\n\n#[non_exhaustive]\n\n#[derive(Error, Debug, Diagnostic)]\n\n#[error(transparent)]\n\n#[diagnostic(code(models::fast_conventional_config::yaml_read_error), url(docsrs))]\n\npub enum YamlReadError {\n\n Io(#[from] std::io::Error),\n\n Yaml(#[from] serde_yaml::Error),\n\n}\n\n\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 40, "score": 27581.76428937964 }, { "content": "\n\n if self.use_angular == Some(true) {\n\n let angular_types: BTreeSet<String> = ANGULAR_TYPES\n\n .into_iter()\n\n .map(ToString::to_string)\n\n .collect::<_>();\n\n\n\n return angular_types\n\n .union(&user_types)\n\n .map(ToString::to_string)\n\n .collect::<_>();\n\n };\n\n\n\n user_types\n\n }\n\n}\n\n\n\nimpl TryFrom<FastConventionalConfig> for String {\n\n type Error = YamlGenerateError;\n\n\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 41, "score": 27581.470210540378 }, { "content": " #[test]\n\n fn missing_require_scope_is_false() {\n\n let actual = FastConventionalConfig::default();\n\n\n\n assert!(!actual.get_require_scope());\n\n }\n\n #[test]\n\n fn it_can_output_to_string() {\n\n let mut temp_file =\n\n tempfile::NamedTempFile::new().expect(\"failed to create temporary file\");\n\n let path = temp_file.path().to_path_buf();\n\n\n\n write!(\n\n temp_file,\n\n r#\"types: [ci]\n\nscopes: [src, fastconventional]\"#\n\n )\n\n .expect(\"failed to write test config\");\n\n\n\n let actual: FastConventionalConfig = path.try_into().expect(\"Yaml unexpectedly invalid\");\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 42, "score": 27581.212300214866 }, { "content": "\n\n let actual: FastConventionalConfig = input.try_into().expect(\"Yaml unexpectedly invalid\");\n\n let expected_types = [\n\n \"feat\",\n\n \"fix\",\n\n \"docs\",\n\n \"style\",\n\n \"refactor\",\n\n \"perf\",\n\n \"test\",\n\n \"chore\",\n\n \"build\",\n\n \"ci\",\n\n \"additional\",\n\n ]\n\n .into_iter()\n\n .map(String::from)\n\n .collect();\n\n let expected_scopes = [\"mergify\", \"just\", \"github\"]\n\n .into_iter()\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 43, "score": 27580.41272159324 }, { "content": "\n\n assert_eq!(\n\n String::try_from(actual).unwrap(),\n\n r#\"---\n\nuse_angular: ~\n\nrequire_scope: ~\n\ntypes:\n\n - ci\n\nscopes:\n\n - src\n\n - fastconventional\n\n\"#\n\n .to_string()\n\n );\n\n }\n\n}\n", "file_path": "src/models/fast_conventional_config.rs", "rank": 44, "score": 27579.593062629807 }, { "content": "#[derive(Clone, PartialOrd, PartialEq, Default, Debug)]\n\npub struct TypeSlug(String);\n\n\n\nimpl From<String> for TypeSlug {\n\n fn from(contents: String) -> Self {\n\n Self(contents)\n\n }\n\n}\n\n\n\nimpl From<&str> for TypeSlug {\n\n fn from(contents: &str) -> Self {\n\n Self(contents.to_string())\n\n }\n\n}\n\n\n\nimpl From<TypeSlug> for String {\n\n fn from(contents: TypeSlug) -> Self {\n\n contents.0\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/type_slug.rs", "rank": 45, "score": 27142.23806248446 }, { "content": "\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn can_be_created_from_str() {\n\n assert_eq!(TypeSlug::from(\"Hello\"), TypeSlug(\"Hello\".to_string()));\n\n }\n\n\n\n #[test]\n\n fn can_be_created_from_string() {\n\n assert_eq!(\n\n TypeSlug::from(\"Hello\".to_string()),\n\n TypeSlug(\"Hello\".to_string())\n\n );\n\n }\n\n #[test]\n\n fn can_create_string_from() {\n\n assert_eq!(\n\n String::from(TypeSlug(\"Hello\".to_string())),\n\n \"Hello\".to_string()\n\n );\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/type_slug.rs", "rank": 46, "score": 27141.05041524269 }, { "content": "## Enforcement Responsibilities\n\n\n\nCommunity leaders are responsible for clarifying and enforcing our\n\nstandards of acceptable behavior and will take appropriate and fair\n\ncorrective action in response to any behavior that they deem\n\ninappropriate, threatening, offensive, or harmful.\n\n\n\nCommunity leaders have the right and responsibility to remove, edit, or\n\nreject comments, commits, code, wiki edits, issues, and other\n\ncontributions that are not aligned to this Code of Conduct, and will\n\ncommunicate reasons for moderation decisions when appropriate.\n\n\n\n## Scope\n\n\n\nThis Code of Conduct applies within all community spaces, and also\n\napplies when an individual is officially representing the community in\n\npublic spaces. Examples of representing our community include using an\n\nofficial e-mail address, posting via an official social media account,\n\nor acting as an appointed representative at an online or offline event.\n\n\n\n## Enforcement\n\n\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may\n\nbe reported to the community leaders responsible for enforcement at\n\n<[email protected]>. All complaints will be reviewed and\n\ninvestigated promptly and fairly.\n\n\n\nAll community leaders are obligated to respect the privacy and security\n\nof the reporter of any incident.\n\n\n\n## Enforcement Guidelines\n\n\n\nCommunity leaders will follow these Community Impact Guidelines in\n\ndetermining the consequences for any action they deem in violation of\n\nthis Code of Conduct:\n\n\n\n### 1. Correction\n\n\n\n**Community Impact**: Use of inappropriate language or other behavior\n\ndeemed unprofessional or unwelcome in the community.\n\n\n\n**Consequence**: A private, written warning from community leaders,\n\nproviding clarity around the nature of the violation and an explanation\n\nof why the behavior was inappropriate. A public apology may be\n\nrequested.\n\n\n", "file_path": "CODE_OF_CONDUCT.md", "rank": 47, "score": 20944.362038200063 }, { "content": "### 2. Warning\n\n\n\n**Community Impact**: A violation through a single incident or series of\n\nactions.\n\n\n\n**Consequence**: A warning with consequences for continued behavior. No\n\ninteraction with the people involved, including unsolicited interaction\n\nwith those enforcing the Code of Conduct, for a specified period of\n\ntime. This includes avoiding interactions in community spaces as well as\n\nexternal channels like social media. Violating these terms may lead to a\n\ntemporary or permanent ban.\n\n\n\n### 3. Temporary Ban\n\n\n\n**Community Impact**: A serious violation of community standards,\n\nincluding sustained inappropriate behavior.\n\n\n\n**Consequence**: A temporary ban from any sort of interaction or public\n\ncommunication with the community for a specified period of time. No\n\npublic or private interaction with the people involved, including\n\nunsolicited interaction with those enforcing the Code of Conduct, is\n\nallowed during this period. Violating these terms may lead to a\n\npermanent ban.\n\n\n\n### 4. Permanent Ban\n\n\n\n**Community Impact**: Demonstrating a pattern of violation of community\n\nstandards, including sustained inappropriate behavior, harassment of an\n\nindividual, or aggression toward or disparagement of classes of\n\nindividuals.\n\n\n\n**Consequence**: A permanent ban from any sort of public interaction\n\nwithin the community.\n\n\n\n## Attribution\n\n\n\nThis Code of Conduct is adapted from the [Contributor\n\nCovenant](https://www.contributor-covenant.org), version 2.0, available\n\nat\n\n<https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.\n\n\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\n\nenforcement ladder](https://github.com/mozilla/diversity).\n\n\n\nFor answers to common questions about this code of conduct, see the FAQ\n\nat <https://www.contributor-covenant.org/faq>. Translations are\n\navailable at <https://www.contributor-covenant.org/translations>.\n", "file_path": "CODE_OF_CONDUCT.md", "rank": 48, "score": 20941.58818655579 }, { "content": "# Contributor Covenant Code of Conduct\n\n\n\n## Our Pledge\n\n\n\nWe as members, contributors, and leaders pledge to make participation in\n\nour community a harassment-free experience for everyone, regardless of\n\nage, body size, visible or invisible disability, ethnicity, sex\n\ncharacteristics, gender identity and expression, level of experience,\n\neducation, socio-economic status, nationality, personal appearance,\n\nrace, religion, or sexual identity and orientation.\n\n\n\nWe pledge to act and interact in ways that contribute to an open,\n\nwelcoming, diverse, inclusive, and healthy community.\n\n\n\n## Our Standards\n\n\n\nExamples of behavior that contributes to a positive environment for our\n\ncommunity include:\n\n\n\n- Demonstrating empathy and kindness toward other people\n\n- Being respectful of differing opinions, viewpoints, and experiences\n\n- Giving and gracefully accepting constructive feedback\n\n- Accepting responsibility and apologizing to those affected by our\n\n mistakes, and learning from the experience\n\n- Focusing on what is best not just for us as individuals, but for the\n\n overall community\n\n\n\nExamples of unacceptable behavior include:\n\n\n\n- The use of sexualized language or imagery, and sexual attention or\n\n advances of any kind\n\n- Trolling, insulting or derogatory comments, and personal or\n\n political attacks\n\n- Public or private harassment\n\n- Publishing others' private information, such as a physical or email\n\n address, without their explicit permission\n\n- Other conduct which could reasonably be considered inappropriate in\n\n a professional setting\n\n\n", "file_path": "CODE_OF_CONDUCT.md", "rank": 49, "score": 20940.295627617194 }, { "content": " subject_buffer.push_str(&selected_scope);\n\n subject_buffer.push(')');\n\n }\n\n\n\n if match conventional_commit.breaking {\n\n Change::BreakingWithMessage(_) | Change::BreakingWithoutMessage => true,\n\n Change::Compatible => false,\n\n } {\n\n subject_buffer.push('!');\n\n }\n\n\n\n subject_buffer.push_str(\": \");\n\n let subject = String::from(conventional_commit.subject);\n\n subject_buffer.push_str(&subject);\n\n\n\n let mut commit = commit.with_subject(subject_buffer.into());\n\n\n\n if !conventional_commit.body.is_empty() {\n\n let existing_subject: CommitSubject<'_> = commit.get_subject();\n\n let body = format!(\"Unused\\n\\n{}\", conventional_commit.body.0);\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 51, "score": 20.699819529702363 }, { "content": "pub mod fast_conventional_config;\n\n\n\nmod conventional_commit;\n\n\n\npub use conventional_commit::body::Body as ConventionalBody;\n\npub use conventional_commit::change::Change as ConventionalChange;\n\npub use conventional_commit::commit::Commit as ConventionalCommit;\n\npub use conventional_commit::scope::Scope as ConventionalScope;\n\npub use conventional_commit::subject::Subject as ConventionalSubject;\n\npub use git::revision_selection::RevisionSelection as GitRevisionSelection;\n\npub use git::short_ref::ShortRef as GitShortRef;\n\n\n\nmod git;\n", "file_path": "src/models/mod.rs", "rank": 52, "score": 19.700055322195446 }, { "content": "use miette::{ErrReport, IntoDiagnostic, Result};\n\nuse mit_commit::CommitMessage;\n\nuse mit_commit::Subject as CommitSubject;\n\nuse mit_commit::Trailer;\n\n\n\nuse nom::bytes::complete::take_till1;\n\nuse nom::bytes::complete::{tag, take_until1};\n\n\n\nuse nom::combinator::opt;\n\nuse nom::sequence::{delimited, pair, terminated, tuple};\n\n\n\nuse super::body::Body;\n\nuse super::change::Change;\n\nuse super::scope::Scope;\n\nuse super::subject::Subject;\n\nuse super::type_slug::TypeSlug;\n\n\n\n#[derive(Clone, PartialOrd, PartialEq, Default, Debug)]\n\npub struct Commit {\n\n pub(crate) subject: Subject,\n\n pub(crate) body: Body,\n\n pub(crate) breaking: Change,\n\n pub(crate) type_slug: TypeSlug,\n\n pub(crate) scope: Option<Scope>,\n\n}\n\n\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 53, "score": 19.37716537287347 }, { "content": " let breaking = value\n\n .get_trailers()\n\n .iter()\n\n .find(|trailer| trailer.get_key() == \"BREAKING CHANGE\")\n\n .map(Trailer::get_value)\n\n .map(|x| x.trim().to_string())\n\n .map_or(\n\n if breaking_marker.is_some() {\n\n Change::BreakingWithoutMessage\n\n } else {\n\n Change::Compatible\n\n },\n\n Change::BreakingWithMessage,\n\n );\n\n\n\n Ok(Self {\n\n subject: description.into(),\n\n body: value.get_body().into(),\n\n breaking,\n\n scope: scope.map(Into::into),\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 55, "score": 17.398025927477676 }, { "content": " use tempfile::{tempdir, TempDir};\n\n\n\n use super::*;\n\n\n\n const COMMIT_USER: &str = \"user\";\n\n const COMMIT_EMAIL: &str = \"[email protected]\";\n\n const COMMIT_MESSAGE_1: &str = \"initial\\n\\nbody\";\n\n const COMMIT_MESSAGE_2: &str = \"Message 2\";\n\n const COMMIT_MESSAGE_3: &str = \"Message 3\";\n\n\n\n pub fn repo_init() -> TempDir {\n\n let temporary_dir = tempdir().unwrap();\n\n let mut opts = Git2RepositoryInitOptions::new();\n\n opts.initial_head(\"main\");\n\n let git2_repo = Git2Repository::init_opts(temporary_dir.path(), &opts).unwrap();\n\n {\n\n let mut git2_config = git2_repo.config().unwrap();\n\n git2_config.set_str(\"user.name\", COMMIT_USER).unwrap();\n\n git2_config.set_str(\"user.email\", COMMIT_EMAIL).unwrap();\n\n let mut index = git2_repo.index().unwrap();\n", "file_path": "src/repositories/git/repository.rs", "rank": 56, "score": 14.97623391747024 }, { "content": " Commit::try_from(CommitMessage::from(\n\n \"fix: example\\n\\nBREAKING CHANGE: Some text\"\n\n ))\n\n .unwrap(),\n\n Commit {\n\n type_slug: \"fix\".into(),\n\n subject: \"example\".into(),\n\n breaking: \"Some text\".into(),\n\n ..Commit::default()\n\n }\n\n );\n\n }\n\n\n\n #[test]\n\n fn gets_scope() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix(something): example\")).unwrap(),\n\n Commit {\n\n type_slug: \"fix\".into(),\n\n subject: \"example\".into(),\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 57, "score": 13.437394396178652 }, { "content": "use std::path::PathBuf;\n\n\n\nuse git2::ObjectType as Git2ObjectType;\n\nuse git2::Oid as Git2Oid;\n\nuse git2::Repository as Git2Repository;\n\nuse git2::Sort as Git2Sort;\n\nuse git2::{Error as Git2Error, Revwalk};\n\nuse miette::Diagnostic;\n\nuse mit_commit::CommitMessage;\n\nuse thiserror::Error;\n\n\n\nuse crate::models::{GitRevisionSelection, GitShortRef};\n\n\n\npub struct Repository(Git2Repository);\n\n\n\nimpl Repository {\n\n pub(crate) fn list_commits(\n\n &self,\n\n revision_selection: Option<GitRevisionSelection>,\n\n ) -> Result<Vec<(GitShortRef, CommitMessage<'_>)>, CommitListError> {\n", "file_path": "src/repositories/git/repository.rs", "rank": 58, "score": 12.760046328041664 }, { "content": "# Configuration\n\n\n\nWe have a useful tool for outputting an example configuration tool\n\n\n\n## Binary Usage\n\n\n\n``` shell,script(name=\"help-example\",expected_exit_code=0)\n\nfast-conventional example-config --help\n\n```\n\n\n\n``` text,verify(script_name=\"help-example\",stream=stdout)\n\nfast-conventional-example-config \n\nPrint an example configuration\n\n\n\nUSAGE:\n\n fast-conventional example-config\n\n\n\nOPTIONS:\n\n -h, --help Print help information\n\n```\n\n\n\nTo generate the example\n\n\n\n``` shell,script(name=\"example-config\")\n\nfast-conventional example-config\n\n```\n\n\n\n## About the file\n\n\n\nThe file looks like this. All fields are optional.\n\n\n\n``` yaml,verify(name=\"example-config\")\n\n---\n\nuse_angular: true\n\nrequire_scope: ~\n\ntypes:\n\n - custom_type\n\nscopes:\n\n - src\n\n - actions\n\n - manpages\n\n - readme\n\n - e2e\n\n - unit\n\n\n\n```\n\n\n\nThe \"use_angular\" option will save you some typing by including angular\n\ntypes automatically.\n\n\n\nSo this\n\n\n\n``` yaml,skip()\n\n---\n\nuse_angular: true\n\n```\n\n\n\nis equivilent to\n\n\n\n``` yaml,skip()\n\ntypes:\n\n - feat\n\n - fix\n\n - docs\n\n - style\n\n - refactor\n\n - perf\n\n - test\n\n - chore\n\n - build\n\n - ci\n\n```\n", "file_path": "docs/configuration.md", "rank": 59, "score": 12.718139848404057 }, { "content": " let edited_commit = CommitMessage::from(body);\n\n\n\n commit = edited_commit.with_subject(existing_subject);\n\n }\n\n\n\n if let Change::BreakingWithMessage(message) = conventional_commit.breaking {\n\n commit = commit.add_trailer(Trailer::new(\"BREAKING CHANGE\".into(), message.into()));\n\n }\n\n\n\n commit\n\n }\n\n}\n\n\n\nimpl TryFrom<CommitMessage<'_>> for Commit {\n\n type Error = ErrReport;\n\n\n\n fn try_from(value: CommitMessage<'_>) -> Result<Self, Self::Error> {\n\n let commit_header = value.get_subject().to_string();\n\n let (description, (type_slug, scope, breaking_marker)) = Self::parse(&commit_header)?;\n\n\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 60, "score": 12.61142328383247 }, { "content": " terminated(\n\n tuple((\n\n take_till1(|x| \"(!:\".contains(x)),\n\n opt(delimited(tag(\"(\"), take_until1(\")\"), tag(\")\"))),\n\n opt(tag(\"!\")),\n\n )),\n\n pair(tag(\":\"), opt(tag(\" \"))),\n\n )(text)\n\n .map_err(nom::Err::<nom::error::Error<&str>>::to_owned)\n\n .into_diagnostic()\n\n }\n\n}\n\n\n\nimpl From<Commit> for CommitMessage<'_> {\n\n fn from(conventional_commit: Commit) -> Self {\n\n let commit = CommitMessage::default();\n\n let mut subject_buffer: String = conventional_commit.type_slug.into();\n\n\n\n if let Some(Scope(selected_scope)) = conventional_commit.scope {\n\n subject_buffer.push('(');\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 61, "score": 12.554601823765157 }, { "content": "\n\n #[test]\n\n fn break_with_message_and_bang() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\n\n \"fix!: example\\n\\nBREAKING CHANGE: Some text\"\n\n ))\n\n .unwrap(),\n\n Commit {\n\n type_slug: \"fix\".into(),\n\n subject: \"example\".into(),\n\n breaking: \"Some text\".into(),\n\n ..Commit::default()\n\n }\n\n );\n\n }\n\n\n\n #[test]\n\n fn break_with_message() {\n\n assert_eq!(\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 62, "score": 12.492020658037932 }, { "content": "# Editor\n\n\n\nMostly users don't need to interact directly with the editor, from a\n\ncommandline perspective\n\n\n\n## Binary Usage\n\n\n\n``` shell,script(name=\"help-editor\",expected_exit_code=0)\n\nfast-conventional editor --help\n\n```\n\n\n\n``` text,verify(script_name=\"help-editor\",stream=stdout)\n\nfast-conventional-editor \n\nEdit a commit message\n\n\n\nUSAGE:\n\n fast-conventional editor [OPTIONS] <COMMIT_MESSAGE_PATH>\n\n\n\nARGS:\n\n <COMMIT_MESSAGE_PATH> The name of the file that contains the commit log message\n\n\n\nOPTIONS:\n\n -c, --config <CONFIG_PATH> Configuration file [env: FAST_CONVENTIONAL_CONFIG=]\n\n [default: .fastconventional.yaml]\n\n -h, --help Print help information\n\n```\n\n\n\n## Conventional Commits\n\n\n\nGiven we have configured the tool, it looks for this in the root of the\n\ngit repository.\n\n\n\n> `.fastconventional.yaml`\n\n\n\n``` yaml,file(path=\".fastconventional.yaml\")\n\nuse_angular: true\n\ntypes: [ci]\n\nscopes: [\"mergify\", \"just\", \"github\"]\n\n```\n\n\n\nWhen we commit, git has generated this stub configuration\n\n\n\n``` text,file(path=\"commit.txt\")\n\n# Please enter the commit message for your changes. Lines starting\n\n# with '#' will be ignored, and an empty message aborts the commit.\n\n#\n\n# On branch master\n\n# Your branch is up to date with 'origin/master'.\n", "file_path": "docs/editor.md", "rank": 63, "score": 12.288629878682263 }, { "content": " CommitMessage::default().with_subject(\"fix(example): subject\".into())\n\n );\n\n }\n\n\n\n #[test]\n\n fn convert_to_commit_message_scope_breaking_with_message() {\n\n assert_eq!(\n\n CommitMessage::from(\n\n Commit::try_from(CommitMessage::from(\n\n \"fix(example): subject\\n\\nBREAKING CHANGE: Something that changed\"\n\n ))\n\n .unwrap()\n\n ),\n\n CommitMessage::default()\n\n .with_subject(\"fix(example)!: subject\".into())\n\n .add_trailer(Trailer::new(\n\n \"BREAKING CHANGE\".into(),\n\n \"Something that changed\".into(),\n\n ))\n\n );\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 64, "score": 12.168894857204585 }, { "content": "pub mod body;\n\npub mod change;\n\npub mod commit;\n\npub mod scope;\n\npub mod subject;\n\nmod type_slug;\n", "file_path": "src/models/conventional_commit/mod.rs", "rank": 65, "score": 11.956288578313945 }, { "content": " Commit::try_from(CommitMessage::from(\n\n \"fix: example\\n\\nBREAKING CHANGE: Something that changed\"\n\n ))\n\n .unwrap()\n\n ),\n\n CommitMessage::default()\n\n .with_subject(\"fix!: example\".into())\n\n .add_trailer(Trailer::new(\n\n \"BREAKING CHANGE\".into(),\n\n \"Something that changed\".into(),\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn convert_to_commit_message_scope() {\n\n assert_eq!(\n\n CommitMessage::from(\n\n Commit::try_from(CommitMessage::from(\"fix(example): subject\")).unwrap()\n\n ),\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 66, "score": 11.923674037406125 }, { "content": " #[test]\n\n fn scope_cursor_is_0_not_set() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix: example\"))\n\n .unwrap()\n\n .scope_index(vec![\"some\".into()]),\n\n 0_usize\n\n );\n\n }\n\n\n\n #[test]\n\n fn scope_cursor_is_0_when_not_found_in_config() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix(other): example\"))\n\n .unwrap()\n\n .scope_index(vec![\"some\".into()]),\n\n 0_usize\n\n );\n\n }\n\n\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 67, "score": 11.637686904561821 }, { "content": "#[error(transparent)]\n\n#[diagnostic(\n\n code(repositories::git::repository::repository_open_error),\n\n url(docsrs)\n\n)]\n\npub struct OpenError(#[from] Git2Error);\n\n\n\n#[non_exhaustive]\n\n#[derive(Error, Debug, Diagnostic)]\n\n#[error(transparent)]\n\n#[diagnostic(code(repositories::git::repository::commit_list_error), url(docsrs))]\n\npub struct CommitListError(#[from] Git2Error);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::str::FromStr;\n\n\n\n use git2::RepositoryInitOptions as Git2RepositoryInitOptions;\n\n use git2::{Repository as Git2Repository, Signature};\n\n use mit_commit::CommitMessage;\n", "file_path": "src/repositories/git/repository.rs", "rank": 68, "score": 11.526419949842637 }, { "content": "#\n\n# Changes to be committed:\n\n# new file: README.md\n\n```\n\n\n\nWe can add our conventional message using this neat UI\n\n\n\n![A terminal running the command\n\nblow](../demo.gif \"A demo of the app running\")\n\n\n\nWe can fake it using the below example simulates the steps\n\n\n\n``` shell,script(name=\"full\")\n\n{\n\n sleep 1\n\n echo -ne \"fix\\r\"\n\n sleep 1\n\n echo -ne \"github\\r\"\n\n sleep 1\n\n echo -ne \"Something that changed\\r\"\n\n sleep 1\n\n echo -ne \"the subject goes here\\r\"\n\n sleep 1\n\n echo -ne \"\\r\"\n\n} | socat - EXEC:'fast-conventional editor commit.txt',pty,setsid,ctty\n\n```\n\n\n\nNow if we look at the commit\n\n\n\n``` shell,script(name=\"cat-file\")\n\ncat commit.txt\n\n```\n\n\n\n``` text,verify(name=\"cat-file\")\n\nfix(github)!: the subject goes here\n\n\n\n\n\nBREAKING CHANGE: Something that changed\n\n```\n\n\n\nOnce you have an existing message, you can also edit it\n\n\n\n``` shell,script(name=\"editing\")\n\n{\n\n sleep 1\n\n echo -ne \"\\r\"\n\n sleep 1\n\n echo -ne \"\\r\"\n\n sleep 1\n\n echo -ne \"A better BC reason\\r\"\n\n sleep 1\n\n echo -ne \"\\r\"\n\n sleep 1\n\n echo -ne \"\\r\"\n\n} | socat - EXEC:'fast-conventional editor commit.txt',pty,setsid,ctty\n\n```\n\n\n\nNow if we look at the commit\n\n\n\n``` shell,script(name=\"cat-edited-file\")\n\ncat commit.txt\n\n```\n\n\n\n``` text,verify(name=\"cat-edited-file\")\n\nfix(github)!: the subject goes here\n\n\n\n\n\nBREAKING CHANGE: A better BC reason\n\n```\n\n\n\n## Non-conventional commits\n\n\n\nFor commits that are not conventional, but already have some body text\n\nin them, we will display a prompt saying it's not conventional, and\n\nasking the user if they want to open the default editor.\n\n\n\n## Installing\n\n\n\nOnce the binary is installed use this command to cofigure it. You could\n\nchange the alias if you prefer. I chose fci, as it is similar to the\n\n\"ci\" alias, many people use.\n\n\n\n``` shell,skip()\n\ngit config --global alias.fci '-c \"core.editor=fast-conventional editor\" commit'\n\n```\n", "file_path": "docs/editor.md", "rank": 69, "score": 11.444557920637417 }, { "content": " fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{}\", self.0)\n\n }\n\n}\n\n\n\n#[non_exhaustive]\n\n#[derive(Error, Debug, Diagnostic)]\n\n#[error(\"This does not look like a valid short reference\")]\n\n#[diagnostic(\n\n code(models::git_access::revision_or_range::revision_or_range_parse_error),\n\n url(\"https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection\")\n\n)]\n\npub struct RevisionSelectionParseError {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn can_be_created_from_str() {\n", "file_path": "src/models/git/short_ref.rs", "rank": 70, "score": 11.358724150206884 }, { "content": " .into_iter()\n\n .collect();\n\n let valid_commits: BTreeMap<GitShortRef, CommitMessage<'_>> = vec![(\n\n \"deadbeef\".into(),\n\n CommitMessage::from(\"fix: Example commit\"),\n\n )]\n\n .into_iter()\n\n .collect();\n\n assert_eq!(actual.0, valid_commits);\n\n assert_eq!(actual.1, failed_commits);\n\n }\n\n\n\n #[test]\n\n fn fails_if_commit_has_a_type_that_is_not_in_the_types_list() {\n\n let actual = run(\n\n &FastConventionalConfig {\n\n use_angular: Some(true),\n\n require_scope: None,\n\n types: None,\n\n scopes: None,\n", "file_path": "src/service/commit_validatator.rs", "rank": 71, "score": 11.299098688694704 }, { "content": "These are optional unless you set `require_scope` in the config, in other words a missing scope won't fail the validation.\n\n\n\n> `.fastconventional.yaml`\n\n``` yaml,file(path=\".fastconventional.yaml\")\n\nuse_angular: true\n\nrequire_scope: true\n\ntypes: [ci]\n\nscopes: [\"mergify\", \"just\", \"github\"]\n\n```\n\n\n\n```shell,script(name=\"make-a-commit-with-unknown-type\")\n\ngit commit --allow-empty -m \"fix: Correct the automerge settings\"\n\n```\n\n\n\n\n\n```shell,script(name=\"validate-missing-unknown-type\",expected_exit_code=1)\n\nfast-conventional validate HEAD^..HEAD\n\n```\n\n\n\n```text,verify(script_name=\"validate-missing-unknown-type\", stream=stderr)\n\n[✘] fix: Correct the automerge settings\n\nError: \n\n × Some commits failed validation\n\n\n\n```\n", "file_path": "docs/validate.md", "rank": 72, "score": 10.348577603549334 }, { "content": " .into_iter()\n\n .map(|x| x.to_string().into())\n\n .zip(mit_commits)\n\n .collect();\n\n\n\n Ok(combined_commits)\n\n }\n\n\n\n fn build_revwalk(\n\n &self,\n\n revision_selection: Option<GitRevisionSelection>,\n\n ) -> Result<Revwalk<'_>, CommitListError> {\n\n let mut git2_revwalk = self.0.revwalk()?;\n\n\n\n match revision_selection {\n\n None => {\n\n git2_revwalk.push_head()?;\n\n }\n\n Some(revision_selection) => {\n\n let selection = String::from(revision_selection);\n", "file_path": "src/repositories/git/repository.rs", "rank": 73, "score": 10.19424970888413 }, { "content": "```\n\n\n\n```text,verify(script_name=\"validate-non-conventional-commit\", stream=stderr)\n\n[✘] Non-coventional commit\n\nError: \n\n × Some commits failed validation\n\n\n\n```\n\n\n\nWe can also restrict what we are validating, in this case we limit the range to a single commit\n\n\n\n```shell,script(name=\"validate-commit-range\",expected_exit_code=0)\n\nfast-conventional validate HEAD^^..HEAD^\n\n```\n\n\n\n```text,verify(script_name=\"validate-commit-range\", stream=stdout)\n\n[✔] ci: Add pipeline\n\n```\n\n\n\nIt's also possible start from a specific commit and go back like with `git log`\n\n\n\n```shell,script(name=\"validate-single-commit\",expected_exit_code=0)\n\nfast-conventional validate HEAD^\n\n```\n\n\n\n```text,verify(script_name=\"validate-single-commit\", stream=stdout)\n\n[✔] feat: Initial Release\n\n[✔] ci: Add pipeline\n\n```\n\n\n\nWe have seen a failure because of a non-conventional commit, we also might get a failure if we use a type that isn't in the configuration file\n\n\n\n```shell,script(name=\"make-a-commit-with-unknown-type\")\n\ngit commit --allow-empty -m \"missing: Add a pipeline\"\n\n```\n\n\n\n\n\n```shell,script(name=\"validate-missing-unknown-type\",expected_exit_code=1)\n\nfast-conventional validate HEAD^..HEAD\n\n```\n\n\n\n```text,verify(script_name=\"validate-missing-unknown-type\", stream=stderr)\n\n[✘] missing: Add a pipeline\n\nError: \n\n × Some commits failed validation\n\n\n\n```\n\n\n\nYou also validate the scopes\n\n\n\n```shell,script(name=\"make-a-commit-with-unknown-type\")\n\ngit commit --allow-empty -m \"fix(invalid): Correct the automerge settings\"\n\n```\n\n\n\n\n\n```shell,script(name=\"validate-missing-unknown-type\",expected_exit_code=1)\n\nfast-conventional validate HEAD^..HEAD\n\n```\n\n\n\n```text,verify(script_name=\"validate-missing-unknown-type\", stream=stderr)\n\n[✘] fix(invalid): Correct the automerge settings\n\nError: \n\n × Some commits failed validation\n\n\n\n```\n\n\n", "file_path": "docs/validate.md", "rank": 74, "score": 10.140378474123757 }, { "content": "# Validate Commits\n\n\n\nYou can check if a commit, or a range of commits are conventional\n\n\n\n## Binary Usage\n\n\n\n``` shell,script(name=\"help-validate\",expected_exit_code=0)\n\nfast-conventional validate --help\n\n```\n\n\n\n``` text,verify(script_name=\"help-validate\",stream=stdout)\n\nfast-conventional-validate \n\nValidate a commit message is conventional\n\n\n\nUSAGE:\n\n fast-conventional validate [OPTIONS] [REVISION_SELECTION]\n\n\n\nARGS:\n\n <REVISION_SELECTION> An optional range to limit the linting\n\n\n\nOPTIONS:\n\n -c, --config <CONFIG_PATH>\n\n Configuration file [env: FAST_CONVENTIONAL_CONFIG=] [default: .fastconventional.yaml]\n\n\n\n -h, --help\n\n Print help information\n\n\n\n -r, --repository <REPOSITORY_PATH>\n\n Git repository to search in [env: FAST_CONVENTIONAL_GIT_REPOSITORY=] [default: .]\n\n```\n\n\n\n## Conventional Commits\n\n\n\nGiven we have created a git repository with all conventional commits\n\n\n\n```shell,script(name=\"initialise-repository\")\n\ngit init --template=/dev/null --quiet .\n\ngit config user.name \"Example Name\"\n\ngit config user.email \"[email protected]\"\n\ngit config commit.gpgsign false\n\ngit commit --allow-empty -m \"feat: Initial Release\"\n\ngit commit --allow-empty -m \"ci: Add pipeline\"\n\n```\n\n\n\nand given we have this config\n\n\n\n> `.fastconventional.yaml`\n\n\n\n``` yaml,file(path=\".fastconventional.yaml\")\n\nuse_angular: true\n\ntypes: [ci]\n\nscopes: [\"mergify\", \"just\", \"github\"]\n\n```\n\n\n\nWhen we validate, we get a successful status\n\n\n\n```shell,script(name=\"validate-fine\",expected_exit_code=0)\n\nfast-conventional validate\n\n```\n\n\n\nIf we add a non-conventional commit\n\n\n\n```shell,script(name=\"make-a-non-conventional-commit\")\n\ngit commit --allow-empty -m \"Non-coventional commit\"\n\n```\n\n\n\nwe get a failure\n\n\n\n```shell,script(name=\"validate-non-conventional-commit\",expected_exit_code=1)\n\nfast-conventional validate\n\n```\n\n\n\n```text,verify(script_name=\"validate-non-conventional-commit\", stream=stdout)\n\n[✔] feat: Initial Release\n\n[✔] ci: Add pipeline\n", "file_path": "docs/validate.md", "rank": 75, "score": 9.943178448497937 }, { "content": " #[test]\n\n fn fails_if_commit_is_not_conventional() {\n\n let actual = run(\n\n &FastConventionalConfig {\n\n use_angular: Some(true),\n\n require_scope: None,\n\n types: None,\n\n scopes: None,\n\n },\n\n vec![\n\n (\"cafebabe\".into(), CommitMessage::from(\"Not Conventional\")),\n\n (\n\n \"deadbeef\".into(),\n\n CommitMessage::from(\"fix: Example commit\"),\n\n ),\n\n ],\n\n );\n\n\n\n let failed_commits: BTreeMap<GitShortRef, CommitMessage<'_>> =\n\n vec![(\"cafebabe\".into(), CommitMessage::from(\"Not Conventional\"))]\n", "file_path": "src/service/commit_validatator.rs", "rank": 76, "score": 9.681481765655622 }, { "content": " \"deadbeef\".into(),\n\n CommitMessage::from(\"fix: Example commit\"),\n\n )]\n\n .into_iter()\n\n .collect();\n\n assert_eq!(actual.0, valid_commits);\n\n assert_eq!(actual.1, failed_commits);\n\n }\n\n\n\n #[test]\n\n fn fails_if_commit_has_a_scope_that_is_not_in_the_scopes_list() {\n\n let actual = run(\n\n &FastConventionalConfig {\n\n use_angular: Some(true),\n\n require_scope: None,\n\n types: None,\n\n scopes: Some(vec![\"FastConventional\".into()]),\n\n },\n\n vec![\n\n (\n", "file_path": "src/service/commit_validatator.rs", "rank": 77, "score": 9.215412854215813 }, { "content": " .into_iter()\n\n .collect();\n\n assert_eq!(actual.0, valid_commits);\n\n assert_eq!(actual.1, failed_commits);\n\n }\n\n\n\n #[test]\n\n fn it_also_fails_if_the_scope_is_missing_when_required() {\n\n let actual = run(\n\n &FastConventionalConfig {\n\n use_angular: Some(true),\n\n require_scope: Some(true),\n\n types: None,\n\n scopes: Some(vec![\"FastConventional\".into()]),\n\n },\n\n vec![\n\n (\n\n \"deadbeef\".into(),\n\n CommitMessage::from(\"fix(FastConventional): Example commit\"),\n\n ),\n", "file_path": "src/service/commit_validatator.rs", "rank": 78, "score": 8.840537959739725 }, { "content": " Commit {\n\n type_slug: \"fix\".into(),\n\n subject: \"example\".into(),\n\n ..Commit::default()\n\n }\n\n );\n\n }\n\n\n\n #[test]\n\n fn it_knows_when_something_is_a_bc_break() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix!: example\")).unwrap(),\n\n Commit {\n\n type_slug: \"fix\".into(),\n\n subject: \"example\".into(),\n\n breaking: Change::BreakingWithoutMessage,\n\n ..Commit::default()\n\n }\n\n );\n\n }\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 79, "score": 8.647190670256851 }, { "content": " /// Edit a commit message\n\n Editor {\n\n /// The name of the file that contains the commit log message\n\n #[clap()]\n\n commit_message_path: PathBuf,\n\n /// Configuration file\n\n #[clap(\n\n short = 'c',\n\n long = \"config\",\n\n env = \"FAST_CONVENTIONAL_CONFIG\",\n\n default_value = \".fastconventional.yaml\"\n\n )]\n\n config_path: PathBuf,\n\n },\n\n /// Validate a commit message is conventional\n\n Validate {\n\n /// An optional range to limit the linting\n\n #[clap()]\n\n revision_selection: Option<GitRevisionSelection>,\n\n /// Git repository to search in\n", "file_path": "src/cli.rs", "rank": 80, "score": 8.619676687277858 }, { "content": "# fast-conventional\n\n\n\nThis is the initial launching off point to other commands\n\n\n\n## Binary Usage\n\n\n\n``` shell,script(name=\"help\",expected_exit_code=0)\n\nfast-conventional --help\n\n```\n\n\n\n``` text,verify(script_name=\"help\",stream=stdout)\n\nfast-conventional 2.3.0\n\nBillie Thompson <[email protected]>\n\nMake conventional commits, faster, and consistently name scopes\n\n\n\nUSAGE:\n\n fast-conventional <SUBCOMMAND>\n\n\n\nOPTIONS:\n\n -h, --help Print help information\n\n -V, --version Print version information\n\n\n\nSUBCOMMANDS:\n\n completion Generate completion for shell\n\n editor Edit a commit message\n\n example-config Print an example configuration\n\n help Print this message or the help of the given subcommand(s)\n\n validate Validate a commit message is conventional\n\n```\n", "file_path": "docs/cli-usage.md", "rank": 81, "score": 8.52104325299768 }, { "content": "![Fast\n\nConventional](https://raw.githubusercontent.com/PurpleBooth/fast-conventional/main/logo/logo-light.svg#gh-light-mode-only)\n\n![Fast\n\nConventional](https://raw.githubusercontent.com/PurpleBooth/fast-conventional/main/logo/logo-dark.svg#gh-dark-mode-only)\n\n\n\nMake conventional commits, faster, and consistently name scopes\n\n\n\n## Usage\n\n\n\nGiven we have configured the tool, it looks for this in the root of the\n\ngit repository.\n\n\n\n> `.fastconventional.yaml`\n\n\n\n``` yaml,file(path=\".fastconventional.yaml\")\n\nuse_angular: true\n\ntypes: [ci]\n\nscopes: [\"mergify\", \"just\", \"github\"]\n\n```\n\n\n\nWhen we commit, git has generated this stub configuration\n\n\n\n``` text,file(path=\"commit.txt\")\n\n# Please enter the commit message for your changes. Lines starting\n\n# with '#' will be ignored, and an empty message aborts the commit.\n\n#\n\n# On branch master\n\n# Your branch is up to date with 'origin/master'.\n\n#\n\n# Changes to be committed:\n\n# new file: README.md\n\n```\n\n\n\nWe can add our conventional message using this neat UI\n\n\n\n![A terminal running the command\n\nblow](demo.gif \"A demo of the app running\")\n\n\n\n## Installing\n\n\n\nSee the [releases\n\npage](https://github.com/PurpleBooth/fast-conventional/releases/latest)\n\nwe build for linux and mac (all x86_64), alternatively use brew\n\n\n\n``` shell,skip()\n\nbrew install PurpleBooth/repo/fast-conventional\n\n```\n\n\n\nThis binary is designed to be run as a editor in git. To install it run\n\n\n\n``` shell,skip()\n\ngit config --global alias.fci '-c \"core.editor=fast-conventional editor\" commit'\n\n```\n\n\n\nTo trigger it when you commit run\n\n\n\n``` shell,skip()\n\ngit fci\n\n```\n\n\n\n## Further Docs\n\n\n\n- [Shell completion](./docs/completion.md)\n\n- [Configuration](./docs/configuration.md)\n\n- [Editor](./docs/editor.md)\n\n- [Validate](./docs/validate.md)\n\n- [Cli usage](./docs/cli-usage.md)\n", "file_path": "README.md", "rank": 82, "score": 8.479025830090496 }, { "content": " }\n\n\n\n #[test]\n\n fn convert_to_commit_message_scope_breaking_without_message() {\n\n assert_eq!(\n\n CommitMessage::from(\n\n Commit::try_from(CommitMessage::from(\"fix(example)!: subject\")).unwrap()\n\n ),\n\n CommitMessage::default().with_subject(\"fix(example)!: subject\".into())\n\n );\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 83, "score": 8.420402336942054 }, { "content": " scope: Some(\"something\".into()),\n\n ..Commit::default()\n\n }\n\n );\n\n }\n\n\n\n #[test]\n\n fn can_get_scope_cursor() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix(something): example\"))\n\n .unwrap()\n\n .scope_index(vec![\n\n \"some\".into(),\n\n \"something\".into(),\n\n \"somethingelse\".into(),\n\n ]),\n\n 1_usize\n\n );\n\n }\n\n\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 84, "score": 8.323154344145877 }, { "content": "use crate::models::GitRevisionSelection;\n\nuse clap::{Parser, Subcommand};\n\nuse clap_complete::Shell;\n\nuse std::path::PathBuf;\n\n\n\n#[derive(Parser)]\n\n#[clap(author, version, about)]\n\npub struct Args {\n\n #[clap(subcommand)]\n\n pub command: Commands,\n\n}\n\n\n\n#[derive(Subcommand)]\n\npub enum Commands {\n\n /// Generate completion for shell\n\n Completion {\n\n // The shell to generate for\n\n #[clap(arg_enum)]\n\n shell: Shell,\n\n },\n", "file_path": "src/cli.rs", "rank": 85, "score": 8.241220499887687 }, { "content": "use std::collections::BTreeMap;\n\n\n\nuse crate::models::GitShortRef;\n\nuse crate::{ConventionalCommit, FastConventionalConfig};\n\nuse mit_commit::CommitMessage;\n\n\n", "file_path": "src/service/commit_validatator.rs", "rank": 86, "score": 8.130451870930486 }, { "content": " #[test]\n\n fn can_get_type_cursor() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix(something): example\"))\n\n .unwrap()\n\n .type_index(vec![\"ci\".into(), \"fix\".into(), \"tests\".into()]),\n\n 1_usize\n\n );\n\n }\n\n\n\n #[test]\n\n fn type_is_0_when_not_found() {\n\n assert_eq!(\n\n Commit::try_from(CommitMessage::from(\"fix: example\"))\n\n .unwrap()\n\n .type_index(vec![\"ci\".into(), \"feat\".into(), \"tests\".into()]),\n\n 0_usize\n\n );\n\n }\n\n\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 87, "score": 8.120420442231335 }, { "content": "use miette::{IntoDiagnostic, Result};\n\nuse mit_commit::CommitMessage;\n\nuse std::fs;\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\nuse std::io::Write;\n\n\n\nuse crate::{ui, ConventionalCommit, FastConventionalConfig};\n\n\n", "file_path": "src/commands/editor.rs", "rank": 88, "score": 7.864236924432641 }, { "content": "use crate::repositories::GitRepository;\n\nuse crate::FastConventionalConfig;\n\nuse miette::{IntoDiagnostic, Result};\n\nuse std::path::PathBuf;\n\n\n\nuse crate::models::{GitRevisionSelection, GitShortRef};\n\nuse crate::service::commit_validatator;\n\nuse miette::Diagnostic;\n\nuse thiserror::Error;\n\n\n", "file_path": "src/commands/validate.rs", "rank": 89, "score": 7.8013239297306 }, { "content": "use miette::Diagnostic;\n\nuse std::fmt::{Display, Formatter};\n\nuse thiserror::Error;\n\n\n\n#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Clone)]\n\npub struct ShortRef(String);\n\n\n\nimpl From<String> for ShortRef {\n\n fn from(contents: String) -> Self {\n\n Self(contents)\n\n }\n\n}\n\n\n\nimpl From<&str> for ShortRef {\n\n fn from(contents: &str) -> Self {\n\n Self(contents.to_string())\n\n }\n\n}\n\n\n\nimpl Display for ShortRef {\n", "file_path": "src/models/git/short_ref.rs", "rank": 90, "score": 7.538689501029243 }, { "content": " vec![\n\n CommitMessage::from(COMMIT_MESSAGE_1),\n\n CommitMessage::from(COMMIT_MESSAGE_2),\n\n CommitMessage::from(COMMIT_MESSAGE_3)\n\n ]\n\n );\n\n }\n\n\n\n #[test]\n\n fn it_can_give_me_a_list_of_commits_like_git_log() {\n\n let dir = repo_init();\n\n let repo = Repository::try_from(dir.into_path()).unwrap();\n\n let commits = repo\n\n .list_commits(Some(GitRevisionSelection::from_str(\"HEAD^\").unwrap()))\n\n .unwrap()\n\n .into_iter()\n\n .map(|(_, commit_message)| commit_message)\n\n .collect::<Vec<_>>();\n\n\n\n assert_eq!(\n", "file_path": "src/repositories/git/repository.rs", "rank": 91, "score": 7.320118898096749 }, { "content": " commits,\n\n vec![\n\n CommitMessage::from(COMMIT_MESSAGE_1),\n\n CommitMessage::from(COMMIT_MESSAGE_2)\n\n ]\n\n );\n\n }\n\n\n\n #[test]\n\n fn it_can_give_me_a_commit_from_a_range() {\n\n let dir = repo_init();\n\n let repo = Repository::try_from(dir.into_path()).unwrap();\n\n let commits = repo\n\n .list_commits(Some(GitRevisionSelection::from_str(\"HEAD^..HEAD\").unwrap()))\n\n .unwrap()\n\n .into_iter()\n\n .map(|(_, commit_message)| commit_message)\n\n .collect::<Vec<_>>();\n\n\n\n assert_eq!(commits, vec![CommitMessage::from(COMMIT_MESSAGE_3)]);\n", "file_path": "src/repositories/git/repository.rs", "rank": 92, "score": 7.27845126486551 }, { "content": " }\n\n\n\n #[test]\n\n fn it_can_give_me_a_commit_from_a_range_with_the_finishing_id_missing() {\n\n let dir = repo_init();\n\n\n\n let repo = Repository::try_from(dir.into_path()).unwrap();\n\n let commits = repo\n\n .list_commits(Some(GitRevisionSelection::from_str(\"HEAD^^..\").unwrap()))\n\n .unwrap()\n\n .into_iter()\n\n .map(take_commit_message)\n\n .collect::<Vec<_>>();\n\n\n\n assert_eq!(\n\n commits,\n\n vec![\n\n CommitMessage::from(COMMIT_MESSAGE_2),\n\n CommitMessage::from(COMMIT_MESSAGE_3),\n\n ]\n\n );\n\n }\n\n}\n", "file_path": "src/repositories/git/repository.rs", "rank": 93, "score": 7.223992046000824 }, { "content": " let git2_revwalk = self.build_revwalk(revision_selection)?;\n\n\n\n let git2_references = git2_revwalk\n\n .into_iter()\n\n .collect::<Result<Vec<Git2Oid>, _>>()?;\n\n\n\n let git2_commits = git2_references\n\n .clone()\n\n .into_iter()\n\n .map(|oid| self.0.find_commit(oid))\n\n .collect::<Result<Vec<_>, _>>()?;\n\n\n\n let mit_commits = git2_commits\n\n .into_iter()\n\n .map(|message| match message.message() {\n\n None => CommitMessage::default(),\n\n Some(message) => CommitMessage::from(message.to_string()),\n\n });\n\n\n\n let combined_commits: Vec<(GitShortRef, CommitMessage<'_>)> = git2_references\n", "file_path": "src/repositories/git/repository.rs", "rank": 94, "score": 7.037587501942358 }, { "content": "mod completion;\n\nmod editor;\n\nmod example;\n\nmod validate;\n\n\n\npub use completion::run as completion;\n\npub use editor::run as editor;\n\npub use example::run as example;\n\npub use validate::run as validate;\n", "file_path": "src/commands/mod.rs", "rank": 95, "score": 7.013487973928408 }, { "content": "pub mod revision_selection;\n\npub mod short_ref;\n", "file_path": "src/models/git/mod.rs", "rank": 96, "score": 6.6540170072098155 }, { "content": " #[test]\n\n fn convert_to_commit_message_simple() {\n\n assert_eq!(\n\n CommitMessage::from(Commit::try_from(CommitMessage::from(\"fix: example\")).unwrap()),\n\n CommitMessage::default().with_subject(\"fix: example\".into())\n\n );\n\n }\n\n\n\n #[test]\n\n fn convert_to_commit_message_breaking_no_contents() {\n\n assert_eq!(\n\n CommitMessage::from(Commit::try_from(CommitMessage::from(\"fix!: example\")).unwrap()),\n\n CommitMessage::default().with_subject(\"fix!: example\".into())\n\n );\n\n }\n\n\n\n #[test]\n\n fn convert_to_commit_message_breaking_with_tag_contents() {\n\n assert_eq!(\n\n CommitMessage::from(\n", "file_path": "src/models/conventional_commit/commit.rs", "rank": 97, "score": 6.317392268521922 }, { "content": "use crate::FastConventionalConfig;\n\nuse miette::Result;\n\n\n", "file_path": "src/commands/example.rs", "rank": 98, "score": 6.314623168836384 }, { "content": "#[derive(Clone, PartialOrd, PartialEq, Default, Debug)]\n\npub struct Subject(pub(crate) String);\n\n\n\nimpl Subject {\n\n pub(crate) fn is_empty(&self) -> bool {\n\n self.0.is_empty()\n\n }\n\n}\n\n\n\nimpl From<&str> for Subject {\n\n fn from(s: &str) -> Self {\n\n Self(s.to_string())\n\n }\n\n}\n\n\n\nimpl From<String> for Subject {\n\n fn from(contents: String) -> Self {\n\n Self(contents)\n\n }\n\n}\n", "file_path": "src/models/conventional_commit/subject.rs", "rank": 99, "score": 6.22502482045901 } ]
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", "rank": 2, "score": 72310.18260069934 }, { "content": "fn say_hello(event: kubeless::Event, ctx: kubeless::Context) -> String {\n\n match event.data {\n\n Some(name) => format!(\"Hello, {}\", String::from_utf8_lossy(&name)),\n\n None => String::from(\"Hello\"),\n\n }\n\n}\n\n\n", "file_path": "hello-kubeless/src/main.rs", "rank": 3, "score": 72310.18260069934 }, { "content": "fn echo_or_panic(event: kubeless::Event, ctx: kubeless::Context) -> String {\n\n String::from_utf8_lossy(&event.data.unwrap()).to_string()\n\n}\n\n\n", "file_path": "hello-kubeless/src/main.rs", "rank": 4, "score": 72310.18260069934 }, { "content": "fn main() {\n\n kubeless::start(select_function!(say_hello, say_goodbye, echo_or_panic));\n\n}\n", "file_path": "hello-kubeless/src/main.rs", "rank": 7, "score": 17631.37024873484 }, { "content": "/// Contains information about the environment\n\npub struct Context {\n\n pub function_name: String,\n\n pub runtime: String,\n\n pub timeout: usize,\n\n pub memory_limit: usize,\n\n}\n\n\n\n/// A function callable from kubeless\n\npub type UserFunction = fn(event: Event, context: Context) -> String;\n", "file_path": "kubeless/src/types.rs", "rank": 8, "score": 16737.611971039285 }, { "content": "use bytes::Bytes;\n\n\n\n/// Contains information about the call to the user function\n\npub struct Event {\n\n /// The data passed to the user function in the request\n\n pub data: Option<Bytes>,\n\n\n\n /// TODO document\n\n pub event_id: String,\n\n\n\n /// TODO document\n\n pub event_type: String,\n\n\n\n /// TODO document\n\n pub event_time: String,\n\n\n\n /// TODO document\n\n pub event_namespace: String,\n\n}\n\n\n", "file_path": "kubeless/src/types.rs", "rank": 9, "score": 16735.01439641453 }, { "content": "# kubeless-rs #\n\n\n\n## Library ##\n\nSee [kubeless](./kubeless)\n\n\n\n## Example ##\n\nSee [hello-kubeless](./hello-kubeless)\n", "file_path": "README.md", "rank": 10, "score": 10166.331217832232 }, { "content": "# kubeless-rs #\n\n[![Crates.io](https://img.shields.io/crates/v/kubeless.svg)](https://crates.io/crates/kubeless)\n\n[![Crates.io](https://docs.rs/kubeless/badge.svg)](https://docs.rs/kubeless)\n\n\n\nA Rust library for writing [Kubeless](https://kubeless.io) functions.\n\n\n\n## Example ##\n\n```rust\n\n#[macro_use]\n\nextern crate kubeless;\n\n\n\nfn say_hello(event: kubeless::Event, ctx: kubeless::Context) -> String {\n\n match event.data {\n\n Some(name) => format!(\"Hello, {}\", String::from_utf8_lossy(&name)),\n\n None => String::from(\"Hello\"),\n\n }\n\n}\n\n\n\nfn 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\nfn main() {\n\n kubeless::start(select_function!(say_hello, say_goodbye));\n\n}\n", "file_path": "kubeless/README.md", "rank": 11, "score": 9828.87952218873 }, { "content": "#[macro_use]\n\nextern crate kubeless;\n\n\n", "file_path": "hello-kubeless/src/main.rs", "rank": 19, "score": 5.1076689453262 } ]
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 // [email protected]\n\n if let Some(at_pos) = mangled.find('@') {\n\n let (user, domain) = mangled.split_at(at_pos);\n\n Ok(format!(\"^{}(?:\\\\+.+)?{}$\", user, domain))\n\n } else {\n\n bail!(\"the address `{}` doesn't have any '@'\", addr);\n\n }\n\n}\n\n\n\npub(crate) fn run(token: &str, team_api: &TeamApi, dry_run: bool) -> Result<(), Error> {\n\n let mailgun = Mailgun::new(token, dry_run);\n\n let mailmap = team_api.get_lists()?;\n\n\n\n // Mangle all the mailing lists\n\n let lists = mangle_lists(mailmap)?;\n", "file_path": "src/mailgun/mod.rs", "rank": 0, "score": 140289.24623168792 }, { "content": "fn user_node_id(id: usize) -> String {\n\n base64::encode(&format!(\"04:User{}\", id))\n\n}\n\n\n", "file_path": "src/github/api.rs", "rank": 1, "score": 137071.7043094632 }, { "content": "fn team_node_id(id: usize) -> String {\n\n base64::encode(&format!(\"04:Team{}\", id))\n\n}\n", "file_path": "src/github/api.rs", "rank": 2, "score": 136753.09052767607 }, { "content": "fn build_route_action(member: &str) -> String {\n\n format!(\"forward(\\\"{}\\\")\", member)\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 3, "score": 98963.40542630543 }, { "content": "fn app() -> Result<(), Error> {\n\n let mut dry_run = true;\n\n let mut next_team_repo = false;\n\n let mut team_repo = None;\n\n let mut services = Vec::new();\n\n for arg in std::env::args().skip(1) {\n\n if next_team_repo {\n\n team_repo = Some(arg);\n\n next_team_repo = false;\n\n continue;\n\n }\n\n match arg.as_str() {\n\n \"--live\" => dry_run = false,\n\n \"--team-repo\" => next_team_repo = true,\n\n \"--help\" => {\n\n usage();\n\n return Ok(());\n\n }\n\n service if AVAILABLE_SERVICES.contains(&service) => services.push(service.to_string()),\n\n _ => {\n", "file_path": "src/main.rs", "rank": 4, "score": 97581.79096594386 }, { "content": "fn build_route_actions(list: &List) -> impl Iterator<Item = String> + '_ {\n\n list.members.iter().map(|member| build_route_action(member))\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 5, "score": 96615.37164344112 }, { "content": "fn sync(mailgun: &Mailgun, route: &api::Route, list: &List) -> Result<(), Error> {\n\n let before = route\n\n .actions\n\n .iter()\n\n .map(|action| extract(action, \"forward(\\\"\", \"\\\")\"))\n\n .collect::<HashSet<_>>();\n\n let after = list.members.iter().map(|s| &s[..]).collect::<HashSet<_>>();\n\n if before == after {\n\n return Ok(());\n\n }\n\n\n\n info!(\"updating list {}\", list.address);\n\n let actions = build_route_actions(list).collect::<Vec<_>>();\n\n mailgun.update_route(&route.id, list.priority, &actions)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 6, "score": 94144.3577262329 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct GraphError {\n\n message: String,\n\n}\n\n\n", "file_path": "src/github/api.rs", "rank": 7, "score": 93225.27873945826 }, { "content": "fn mangle_lists(lists: team_data::Lists) -> Result<Vec<List>, Error> {\n\n let mut result = Vec::new();\n\n\n\n for (_key, list) in lists.lists.into_iter() {\n\n let base_list = List {\n\n address: mangle_address(&list.address)?,\n\n members: Vec::new(),\n\n priority: 0,\n\n };\n\n\n\n // Mailgun only supports at most 4000 bytes of \"actions\" for each rule, and some of our\n\n // lists have so many members we're going over that limit.\n\n //\n\n // The official workaround for this, as explained in the docs [1], is to create multiple\n\n // rules, all with the same filter but each with a different set of actions. This snippet\n\n // of code implements that.\n\n //\n\n // Since all the lists have the same address, to differentiate them during the sync this\n\n // also sets the priority of the rule to the partition number.\n\n //\n", "file_path": "src/mailgun/mod.rs", "rank": 8, "score": 93077.28706272466 }, { "content": "#[derive(serde::Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct GraphPageInfo {\n\n end_cursor: Option<String>,\n\n has_next_page: bool,\n\n}\n\n\n\nimpl GraphPageInfo {\n\n fn start() -> Self {\n\n GraphPageInfo {\n\n end_cursor: None,\n\n has_next_page: true,\n\n }\n\n }\n\n}\n\n\n\n#[derive(serde::Deserialize, Debug)]\n\npub(crate) struct Team {\n\n /// The ID returned by the GitHub API can't be empty, but the None marks teams \"created\" during\n\n /// a dry run and not actually present on GitHub, so other methods can avoid acting on them.\n\n id: Option<usize>,\n\n pub(crate) name: String,\n", "file_path": "src/github/api.rs", "rank": 9, "score": 89883.41694858648 }, { "content": "fn create(mailgun: &Mailgun, list: &List) -> Result<(), Error> {\n\n info!(\"creating list {}\", list.address);\n\n\n\n let expr = format!(\"match_recipient(\\\"{}\\\")\", list.address);\n\n let actions = build_route_actions(list).collect::<Vec<_>>();\n\n mailgun.create_route(list.priority, DESCRIPTION, &expr, &actions)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 10, "score": 87309.41608052503 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct GraphResult<T> {\n\n data: Option<T>,\n\n #[serde(default)]\n\n errors: Vec<GraphError>,\n\n}\n\n\n", "file_path": "src/github/api.rs", "rank": 11, "score": 86781.33784204214 }, { "content": "fn extract<'a>(s: &'a str, prefix: &str, suffix: &str) -> &'a str {\n\n assert!(\n\n s.starts_with(prefix),\n\n \"`{}` didn't start with `{}`\",\n\n s,\n\n prefix\n\n );\n\n assert!(s.ends_with(suffix), \"`{}` didn't end with `{}`\", s, suffix);\n\n &s[prefix.len()..s.len() - suffix.len()]\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_build_route_actions() {\n\n let list = List {\n\n address: \"[email protected]\".into(),\n\n members: vec![\n", "file_path": "src/mailgun/mod.rs", "rank": 12, "score": 83071.58277432056 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct GraphNodes<T> {\n\n nodes: Vec<Option<T>>,\n\n}\n\n\n", "file_path": "src/github/api.rs", "rank": 13, "score": 67155.4820783151 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct GraphNode<T> {\n\n node: Option<T>,\n\n}\n\n\n", "file_path": "src/github/api.rs", "rank": 14, "score": 67155.4820783151 }, { "content": "#[derive(Debug, Clone)]\n\nstruct List {\n\n address: String,\n\n members: Vec<String>,\n\n priority: i32,\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 15, "score": 58773.52001341616 }, { "content": "use failure::Error;\n\nuse log::{debug, info, trace};\n\nuse std::borrow::Cow;\n\nuse std::path::PathBuf;\n\nuse std::process::Command;\n\n\n\npub(crate) enum TeamApi {\n\n Production,\n\n Local(PathBuf),\n\n}\n\n\n\nimpl TeamApi {\n\n pub(crate) fn get_teams(&self) -> Result<Vec<rust_team_data::v1::Team>, Error> {\n\n debug!(\"loading teams list from the Team API\");\n\n Ok(self\n\n .req::<rust_team_data::v1::Teams>(\"teams.json\")?\n\n .teams\n\n .into_iter()\n\n .map(|(_k, v)| v)\n\n .collect())\n", "file_path": "src/team_api.rs", "rank": 16, "score": 42239.61558786467 }, { "content": " }\n\n\n\n pub(crate) fn get_lists(&self) -> Result<rust_team_data::v1::Lists, Error> {\n\n debug!(\"loading email lists list from the Team API\");\n\n self.req::<rust_team_data::v1::Lists>(\"lists.json\")\n\n }\n\n\n\n fn req<T: serde::de::DeserializeOwned>(&self, url: &str) -> Result<T, Error> {\n\n match self {\n\n TeamApi::Production => {\n\n let base = std::env::var(\"TEAM_DATA_BASE_URL\")\n\n .map(Cow::Owned)\n\n .unwrap_or_else(|_| Cow::Borrowed(rust_team_data::v1::BASE_URL));\n\n let url = format!(\"{}/{}\", base, url);\n\n trace!(\"http request: GET {}\", url);\n\n Ok(reqwest::get(&url)?.error_for_status()?.json()?)\n\n }\n\n TeamApi::Local(ref path) => {\n\n let dest = tempfile::tempdir()?;\n\n info!(\n", "file_path": "src/team_api.rs", "rank": 17, "score": 42233.98597343971 }, { "content": " \"generating the content of the Team API from {}\",\n\n path.display()\n\n );\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"--\")\n\n .arg(\"static-api\")\n\n .arg(&dest.path())\n\n .env(\"RUST_LOG\", \"rust_team=warn\")\n\n .current_dir(path)\n\n .status()?;\n\n if status.success() {\n\n info!(\"contents of the Team API generated successfully\");\n\n let contents = std::fs::read(dest.path().join(\"v1\").join(url))?;\n\n Ok(serde_json::from_slice(&contents)?)\n\n } else {\n\n failure::bail!(\"failed to generate the contents of the Team API\");\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/team_api.rs", "rank": 18, "score": 42230.18755527253 }, { "content": " let mut result = HashMap::new();\n\n for chunk in ids.chunks(100) {\n\n let res: GraphNodes<Usernames> = self.graphql(\n\n QUERY,\n\n Params {\n\n ids: chunk.iter().map(|id| user_node_id(*id)).collect(),\n\n },\n\n )?;\n\n for node in res.nodes.into_iter().filter_map(|n| n) {\n\n result.insert(node.database_id, node.login);\n\n }\n\n }\n\n Ok(result)\n\n }\n\n\n\n pub(crate) fn org_owners(&self, org: &str) -> Result<HashSet<usize>, Error> {\n\n #[derive(serde::Deserialize, Eq, PartialEq, Hash)]\n\n struct User {\n\n id: usize,\n\n }\n", "file_path": "src/github/api.rs", "rank": 26, "score": 38988.06926054636 }, { "content": " let mut owners = HashSet::new();\n\n self.rest_paginated(\n\n &Method::GET,\n\n format!(\"orgs/{}/members?role=admin\", org),\n\n |mut resp| {\n\n let partial: Vec<User> = resp.json()?;\n\n for owner in partial {\n\n owners.insert(owner.id);\n\n }\n\n Ok(())\n\n },\n\n )?;\n\n Ok(owners)\n\n }\n\n\n\n pub(crate) fn team_memberships(\n\n &self,\n\n team: &Team,\n\n ) -> Result<HashMap<usize, TeamMember>, Error> {\n\n #[derive(serde::Deserialize)]\n", "file_path": "src/github/api.rs", "rank": 27, "score": 38985.48978847387 }, { "content": " description: &'a str,\n\n privacy: TeamPrivacy,\n\n }\n\n if let (false, Some(id)) = (self.dry_run, team.id) {\n\n self.req(Method::PATCH, &format!(\"teams/{}\", id))?\n\n .json(&Req {\n\n name,\n\n description,\n\n privacy,\n\n })\n\n .send()?\n\n .error_for_status()?;\n\n } else {\n\n debug!(\"dry: edit team {}\", name)\n\n }\n\n Ok(())\n\n }\n\n\n\n pub(crate) fn usernames(&self, ids: &[usize]) -> Result<HashMap<usize, String>, Error> {\n\n #[derive(serde::Deserialize)]\n", "file_path": "src/github/api.rs", "rank": 28, "score": 38982.21801837131 }, { "content": " }\n\n\n\n pub(crate) fn team(&self, org: &str, team: &str) -> Result<Option<Team>, Error> {\n\n let mut resp = self\n\n .req(Method::GET, &format!(\"orgs/{}/teams/{}\", org, team))?\n\n .send()?;\n\n match resp.status() {\n\n StatusCode::OK => Ok(Some(resp.json()?)),\n\n StatusCode::NOT_FOUND => Ok(None),\n\n _ => Err(resp.error_for_status().unwrap_err().into()),\n\n }\n\n }\n\n\n\n pub(crate) fn create_team(\n\n &self,\n\n org: &str,\n\n name: &str,\n\n description: &str,\n\n privacy: TeamPrivacy,\n\n ) -> Result<Team, Error> {\n", "file_path": "src/github/api.rs", "rank": 29, "score": 38981.47455871481 }, { "content": " }\n\n\n\n pub(crate) fn remove_membership(&self, team: &Team, username: &str) -> Result<(), Error> {\n\n if let (false, Some(id)) = (self.dry_run, team.id) {\n\n self.req(\n\n Method::DELETE,\n\n &format!(\"teams/{}/memberships/{}\", id, username),\n\n )?\n\n .send()?\n\n .error_for_status()?;\n\n } else {\n\n debug!(\"dry: remove membership of {}\", username);\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[derive(serde::Deserialize)]\n", "file_path": "src/github/api.rs", "rank": 30, "score": 38980.59920470588 }, { "content": " team: &Team,\n\n username: &str,\n\n role: TeamRole,\n\n ) -> Result<(), Error> {\n\n #[derive(serde::Serialize)]\n\n struct Req {\n\n role: TeamRole,\n\n }\n\n if let (false, Some(id)) = (self.dry_run, team.id) {\n\n self.req(\n\n Method::PUT,\n\n &format!(\"teams/{}/memberships/{}\", id, username),\n\n )?\n\n .json(&Req { role })\n\n .send()?\n\n .error_for_status()?;\n\n } else {\n\n debug!(\"dry: set membership of {} to {}\", username, role);\n\n }\n\n Ok(())\n", "file_path": "src/github/api.rs", "rank": 31, "score": 38980.09088070165 }, { "content": " #[derive(serde::Serialize)]\n\n struct Params<'a> {\n\n team: String,\n\n cursor: Option<&'a str>,\n\n }\n\n static QUERY: &str = \"\n\n query($team: ID!, $cursor: String) {\n\n node(id: $team) {\n\n ... on Team {\n\n members(after: $cursor) {\n\n pageInfo {\n\n endCursor\n\n hasNextPage\n\n }\n\n edges {\n\n role\n\n node {\n\n databaseId\n\n login\n\n }\n", "file_path": "src/github/api.rs", "rank": 32, "score": 38978.89012111282 }, { "content": " .error_for_status()?\n\n .json()?;\n\n if let Some(error) = res.errors.iter().next() {\n\n bail!(\"graphql error: {}\", error.message);\n\n } else if let Some(data) = res.data {\n\n Ok(data)\n\n } else {\n\n bail!(\"missing graphql data\");\n\n }\n\n }\n\n\n\n fn rest_paginated<F>(&self, method: &Method, url: String, mut f: F) -> Result<(), Error>\n\n where\n\n F: FnMut(Response) -> Result<(), Error>,\n\n {\n\n let mut next = Some(url);\n\n while let Some(next_url) = next.take() {\n\n let resp = self\n\n .req(method.clone(), &next_url)?\n\n .send()?\n", "file_path": "src/github/api.rs", "rank": 33, "score": 38978.75657495057 }, { "content": " #[serde(rename_all = \"camelCase\")]\n\n struct Usernames {\n\n database_id: usize,\n\n login: String,\n\n }\n\n #[derive(serde::Serialize)]\n\n struct Params {\n\n ids: Vec<String>,\n\n }\n\n static QUERY: &str = \"\n\n query($ids: [ID!]!) {\n\n nodes(ids: $ids) {\n\n ... on User {\n\n databaseId\n\n login\n\n }\n\n }\n\n }\n\n \";\n\n\n", "file_path": "src/github/api.rs", "rank": 34, "score": 38978.428152178 }, { "content": " #[derive(serde::Serialize)]\n\n struct Req<'a> {\n\n name: &'a str,\n\n description: &'a str,\n\n privacy: TeamPrivacy,\n\n }\n\n if self.dry_run {\n\n debug!(\"dry: created team {}/{}\", org, name);\n\n Ok(Team {\n\n // The None marks that the team is \"created\" by the dry run and doesn't actually\n\n // exists on GitHub\n\n id: None,\n\n name: name.to_string(),\n\n description: description.to_string(),\n\n privacy,\n\n })\n\n } else {\n\n Ok(self\n\n .req(Method::POST, &format!(\"orgs/{}/teams\", org))?\n\n .json(&Req {\n", "file_path": "src/github/api.rs", "rank": 35, "score": 38978.07182285729 }, { "content": " page_info = team.members.page_info;\n\n for edge in team.members.edges.into_iter() {\n\n memberships.insert(\n\n edge.node.database_id,\n\n TeamMember {\n\n id: edge.node.database_id,\n\n username: edge.node.login,\n\n role: edge.role,\n\n },\n\n );\n\n }\n\n }\n\n }\n\n }\n\n\n\n Ok(memberships)\n\n }\n\n\n\n pub(crate) fn set_membership(\n\n &self,\n", "file_path": "src/github/api.rs", "rank": 36, "score": 38977.882335499264 }, { "content": " }\n\n }\n\n }\n\n }\n\n }\n\n \";\n\n\n\n let mut memberships = HashMap::new();\n\n // Return the empty HashMap on new teams from dry runs\n\n if let Some(id) = team.id {\n\n let mut page_info = GraphPageInfo::start();\n\n while page_info.has_next_page {\n\n let res: GraphNode<RespTeam> = self.graphql(\n\n QUERY,\n\n Params {\n\n team: team_node_id(id),\n\n cursor: page_info.end_cursor.as_deref(),\n\n },\n\n )?;\n\n if let Some(team) = res.node {\n", "file_path": "src/github/api.rs", "rank": 37, "score": 38977.7402315517 }, { "content": "use failure::{bail, Error};\n\nuse hyper_old_types::header::{Link, RelationType};\n\nuse log::{debug, trace};\n\nuse reqwest::{\n\n header::{self, HeaderValue},\n\n Client, Method, RequestBuilder, Response, StatusCode,\n\n};\n\nuse std::borrow::Cow;\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::fmt;\n\n\n\npub(crate) struct GitHub {\n\n token: String,\n\n dry_run: bool,\n\n client: Client,\n\n}\n\n\n\nimpl GitHub {\n\n pub(crate) fn new(token: String, dry_run: bool) -> Self {\n\n GitHub {\n", "file_path": "src/github/api.rs", "rank": 38, "score": 38976.231901409505 }, { "content": " .error_for_status()?;\n\n\n\n // Extract the next page\n\n if let Some(links) = resp.headers().get(header::LINK) {\n\n let links: Link = links.to_str()?.parse()?;\n\n for link in links.values() {\n\n if link\n\n .rel()\n\n .map(|r| r.iter().any(|r| *r == RelationType::Next))\n\n .unwrap_or(false)\n\n {\n\n next = Some(link.link().to_string());\n\n break;\n\n }\n\n }\n\n }\n\n\n\n f(resp)?;\n\n }\n\n Ok(())\n", "file_path": "src/github/api.rs", "rank": 39, "score": 38975.55030904892 }, { "content": " pub(crate) description: String,\n\n pub(crate) privacy: TeamPrivacy,\n\n}\n\n\n\n#[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Copy, Clone)]\n\n#[serde(rename_all = \"snake_case\")]\n\npub(crate) enum TeamPrivacy {\n\n Closed,\n\n Secret,\n\n}\n\n\n\n#[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Copy, Clone)]\n\n#[serde(rename_all(serialize = \"snake_case\", deserialize = \"SCREAMING_SNAKE_CASE\"))]\n\npub(crate) enum TeamRole {\n\n Member,\n\n Maintainer,\n\n}\n\n\n\nimpl fmt::Display for TeamRole {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "src/github/api.rs", "rank": 40, "score": 38974.87467396678 }, { "content": " token,\n\n dry_run,\n\n client: Client::new(),\n\n }\n\n }\n\n\n\n fn req(&self, method: Method, url: &str) -> Result<RequestBuilder, Error> {\n\n let url = if url.starts_with(\"https://\") {\n\n Cow::Borrowed(url)\n\n } else {\n\n Cow::Owned(format!(\"https://api.github.com/{}\", url))\n\n };\n\n trace!(\"http request: {} {}\", method, url);\n\n Ok(self\n\n .client\n\n .request(method, url.as_ref())\n\n .header(\n\n header::AUTHORIZATION,\n\n HeaderValue::from_str(&format!(\"token {}\", self.token))?,\n\n )\n", "file_path": "src/github/api.rs", "rank": 41, "score": 38974.67858892121 }, { "content": " name,\n\n description,\n\n privacy,\n\n })\n\n .send()?\n\n .error_for_status()?\n\n .json()?)\n\n }\n\n }\n\n\n\n pub(crate) fn edit_team(\n\n &self,\n\n team: &Team,\n\n name: &str,\n\n description: &str,\n\n privacy: TeamPrivacy,\n\n ) -> Result<(), Error> {\n\n #[derive(serde::Serialize)]\n\n struct Req<'a> {\n\n name: &'a str,\n", "file_path": "src/github/api.rs", "rank": 42, "score": 38974.60846121054 }, { "content": " .header(\n\n header::USER_AGENT,\n\n HeaderValue::from_static(crate::USER_AGENT),\n\n ))\n\n }\n\n\n\n fn graphql<R, V>(&self, query: &str, variables: V) -> Result<R, Error>\n\n where\n\n R: serde::de::DeserializeOwned,\n\n V: serde::Serialize,\n\n {\n\n #[derive(serde::Serialize)]\n\n struct Request<'a, V> {\n\n query: &'a str,\n\n variables: V,\n\n }\n\n let res: GraphResult<R> = self\n\n .req(Method::POST, \"graphql\")?\n\n .json(&Request { query, variables })\n\n .send()?\n", "file_path": "src/github/api.rs", "rank": 43, "score": 38974.479900987564 }, { "content": " match self {\n\n TeamRole::Member => write!(f, \"member\"),\n\n TeamRole::Maintainer => write!(f, \"maintainer\"),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct TeamMember {\n\n pub(crate) id: usize,\n\n pub(crate) username: String,\n\n pub(crate) role: TeamRole,\n\n}\n\n\n", "file_path": "src/github/api.rs", "rank": 44, "score": 38973.29797595268 }, { "content": " struct RespTeam {\n\n members: RespMembers,\n\n }\n\n #[derive(serde::Deserialize)]\n\n #[serde(rename_all = \"camelCase\")]\n\n struct RespMembers {\n\n page_info: GraphPageInfo,\n\n edges: Vec<RespEdge>,\n\n }\n\n #[derive(serde::Deserialize)]\n\n struct RespEdge {\n\n role: TeamRole,\n\n node: RespNode,\n\n }\n\n #[derive(serde::Deserialize)]\n\n #[serde(rename_all = \"camelCase\")]\n\n struct RespNode {\n\n database_id: usize,\n\n login: String,\n\n }\n", "file_path": "src/github/api.rs", "rank": 45, "score": 38972.23814842602 }, { "content": "fn usage() {\n\n eprintln!(\"available services:\");\n\n for service in AVAILABLE_SERVICES {\n\n eprintln!(\" {}\", service);\n\n }\n\n eprintln!(\"available flags:\");\n\n eprintln!(\" --help Show this help message\");\n\n eprintln!(\" --live Apply the proposed changes to the services\");\n\n eprintln!(\" --team-repo <path> Path to the local team repo to use\");\n\n eprintln!(\"environment variables:\");\n\n eprintln!(\" GITHUB_TOKEN Authentication token with GitHub\");\n\n eprintln!(\" MAILGUN_API_TOKEN Authentication token with Mailgun\");\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 46, "score": 38304.82396217491 }, { "content": "fn main() {\n\n init_log();\n\n if let Err(err) = app() {\n\n error!(\"{}\", err);\n\n for cause in err.iter_causes() {\n\n error!(\"caused by: {}\", cause);\n\n }\n\n std::process::exit(1);\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 47, "score": 38304.82396217491 }, { "content": "fn init_log() {\n\n let mut env = env_logger::Builder::new();\n\n env.filter_module(\"sync_team\", log::LevelFilter::Info);\n\n if let Ok(content) = std::env::var(\"RUST_LOG\") {\n\n env.parse_filters(&content);\n\n }\n\n env.init();\n\n}\n", "file_path": "src/main.rs", "rank": 48, "score": 37101.18805777176 }, { "content": "# Team synchronization tool\n\n\n\nThis repository contains the CLI tool used to synchronize the contents of the\n\n[rust-lang/team] repository with some of the services the Rust Team uses. There\n\nis usually no need to run this tool manually, and running it requires elevated\n\nprivileges on our infrastructure.\n\n\n\n| Service name | Description | Environment variables |\n\n| --- | --- | --- |\n\n| github | Synchronize GitHub team membership | `GITHUB_TOKEN` |\n\n| mailgun | Synchronize mailing lists on Mailgun | `MAILGUN_API_TOKEN` |\n\n\n\nThe contents of this repository are available under both the MIT and Apache 2.0\n\nlicense.\n\n\n\n## Running the tool\n\n\n\nBy default the tool will run in *dry mode* on all the services we synchronize,\n\nmeaning that the changes will be previewed on the console output but no actual\n\nchange will be applied:\n\n\n\n```\n\ncargo run\n\n```\n\n\n\nOnce you're satisfied with the changes you can run the full synchronization by\n\npassing the `--live` flag:\n\n\n\n```\n\ncargo run -- --live\n\n```\n\n\n\nYou can also limit the services to synchronize on by passing a list of all the\n\nservice names you want to sync. For example, to synchronize only GitHub and\n\nMailgun you can run:\n\n\n\n```\n\ncargo run -- github mailgun\n\ncargo run -- github mailgun --live\n\n```\n\n\n\n## Using a local copy of the team repository\n\n\n\nBy default this tool works on the production dataset, pulled from\n\n[rust-lang/team]. When making changes to the tool it might be useful to test\n\nwith dummy data though. You can do that by making the changes in a local copy\n\nof the team repository and passing the `--team-repo` flag to the CLI:\n\n\n\n```\n\ncargo run -- --team-repo ~/code/rust-lang/team\n\n```\n\n\n\nWhen `--team-repo` is passed, the CLI will build the Static API in a temporary\n\ndirectory, and fetch the data from it instead of the production instance.\n\n\n\n[rust-lang/team]: https://github.com/rust-lang/team\n", "file_path": "README.md", "rank": 49, "score": 27222.059431336187 }, { "content": "mod api;\n\n\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::str;\n\n\n\nuse self::api::Mailgun;\n\nuse crate::TeamApi;\n\nuse failure::{bail, Error, ResultExt};\n\nuse log::info;\n\nuse rust_team_data::v1 as team_data;\n\n\n\nconst DESCRIPTION: &str = \"managed by an automatic script on github\";\n\n\n\n// Limit (in bytes) of the size of a Mailgun rule's actions list.\n\nconst ACTIONS_SIZE_LIMIT_BYTES: usize = 4000;\n\n\n\n#[derive(Debug, Clone)]\n", "file_path": "src/mailgun/mod.rs", "rank": 50, "score": 21210.24912390613 }, { "content": " // [1] https://documentation.mailgun.com/en/latest/user_manual.html#routes\n\n let mut current_list = base_list.clone();\n\n let mut current_actions_len = 0;\n\n let mut partitions_count = 0;\n\n for member in list.members {\n\n let action = build_route_action(&member);\n\n if current_actions_len + action.len() > ACTIONS_SIZE_LIMIT_BYTES {\n\n partitions_count += 1;\n\n result.push(current_list);\n\n\n\n current_list = base_list.clone();\n\n current_list.priority = partitions_count;\n\n current_actions_len = 0;\n\n }\n\n\n\n current_actions_len += action.len();\n\n current_list.members.push(member);\n\n }\n\n\n\n result.push(current_list);\n\n }\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 51, "score": 21196.392835176255 }, { "content": " \"duplicate address: {} (with priority {})\",\n\n list.address,\n\n list.priority\n\n );\n\n }\n\n }\n\n\n\n for route in routes {\n\n if route.description != DESCRIPTION {\n\n continue;\n\n }\n\n let address = extract(&route.expression, \"match_recipient(\\\"\", \"\\\")\");\n\n let key = (address.to_string(), route.priority);\n\n match addr2list.remove(&key) {\n\n Some(new_list) => sync(&mailgun, &route, &new_list)\n\n .with_context(|_| format!(\"failed to sync {}\", address))?,\n\n None => mailgun\n\n .delete_route(&route.id)\n\n .with_context(|_| format!(\"failed to delete {}\", address))?,\n\n }\n\n }\n\n\n\n for (_, list) in addr2list.iter() {\n\n create(&mailgun, list).with_context(|_| format!(\"failed to create {}\", list.address))?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/mailgun/mod.rs", "rank": 52, "score": 21194.871876872945 }, { "content": "\n\n let mut routes = Vec::new();\n\n let mut response = mailgun.get_routes(None)?;\n\n let mut cur = 0;\n\n while !response.items.is_empty() {\n\n cur += response.items.len();\n\n routes.extend(response.items);\n\n if cur >= response.total_count {\n\n break;\n\n }\n\n response = mailgun.get_routes(Some(cur))?;\n\n }\n\n\n\n let mut addr2list = HashMap::new();\n\n for list in &lists {\n\n if addr2list\n\n .insert((list.address.clone(), list.priority), list)\n\n .is_some()\n\n {\n\n bail!(\n", "file_path": "src/mailgun/mod.rs", "rank": 53, "score": 21193.68605811005 }, { "content": " r\"^list-name(?:\\+.+)?@example\\.com$\",\n\n mangle_address(\"[email protected]\").unwrap()\n\n );\n\n assert!(mangle_address(\"list-name.example.com\").is_err());\n\n }\n\n\n\n #[test]\n\n fn test_mangle_lists() {\n\n let original = rust_team_data::v1::Lists {\n\n lists: indexmap::indexmap![\n\n \"[email protected]\".to_string() => rust_team_data::v1::List {\n\n address: \"[email protected]\".into(),\n\n members: vec![\n\n \"[email protected]\".into(),\n\n \"[email protected]\".into(),\n\n ],\n\n },\n\n \"[email protected]\".into() => rust_team_data::v1::List {\n\n address: \"[email protected]\".into(),\n\n // Generate 300 members automatically to simulate a big list, and test whether the\n", "file_path": "src/mailgun/mod.rs", "rank": 54, "score": 21192.618926262592 }, { "content": " // partitioning mechanism works.\n\n members: (0..300).map(|i| format!(\"foo{:03}@example.com\", i)).collect(),\n\n },\n\n ],\n\n };\n\n\n\n let mangled = mangle_lists(original).unwrap();\n\n assert_eq!(4, mangled.len());\n\n\n\n let small = &mangled[0];\n\n assert_eq!(small.address, mangle_address(\"[email protected]\").unwrap());\n\n assert_eq!(small.priority, 0);\n\n assert_eq!(small.members, vec![\"[email protected]\", \"[email protected]\",]);\n\n\n\n // With ACTIONS_SIZE_LIMIT_BYTES = 4000, each list can contain at most 137 users named\n\n // `[email protected]`. If the limit is changed the numbers will need to be updated.\n\n\n\n let big_part1 = &mangled[1];\n\n assert_eq!(\n\n big_part1.address,\n", "file_path": "src/mailgun/mod.rs", "rank": 55, "score": 21191.86310798952 }, { "content": " mangle_address(\"[email protected]\").unwrap()\n\n );\n\n assert_eq!(big_part1.priority, 0);\n\n assert_eq!(\n\n big_part1.members,\n\n (0..137)\n\n .map(|i| format!(\"foo{:03}@example.com\", i))\n\n .collect::<Vec<_>>()\n\n );\n\n\n\n let big_part2 = &mangled[2];\n\n assert_eq!(\n\n big_part2.address,\n\n mangle_address(\"[email protected]\").unwrap()\n\n );\n\n assert_eq!(big_part2.priority, 1);\n\n assert_eq!(\n\n big_part2.members,\n\n (137..274)\n\n .map(|i| format!(\"foo{:03}@example.com\", i))\n", "file_path": "src/mailgun/mod.rs", "rank": 56, "score": 21191.37205453993 }, { "content": " .collect::<Vec<_>>()\n\n );\n\n\n\n let big_part3 = &mangled[3];\n\n assert_eq!(\n\n big_part3.address,\n\n mangle_address(\"[email protected]\").unwrap()\n\n );\n\n assert_eq!(big_part3.priority, 2);\n\n assert_eq!(\n\n big_part3.members,\n\n (274..300)\n\n .map(|i| format!(\"foo{:03}@example.com\", i))\n\n .collect::<Vec<_>>()\n\n );\n\n }\n\n}\n", "file_path": "src/mailgun/mod.rs", "rank": 57, "score": 21191.04289951237 }, { "content": " \"[email protected]\".into(),\n\n \"[email protected]\".into(),\n\n \"[email protected]\".into(),\n\n ],\n\n priority: 0,\n\n };\n\n\n\n assert_eq!(\n\n vec![\n\n \"forward(\\\"[email protected]\\\")\",\n\n \"forward(\\\"[email protected]\\\")\",\n\n \"forward(\\\"[email protected]\\\")\",\n\n ],\n\n build_route_actions(&list).collect::<Vec<_>>()\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_mangle_address() {\n\n assert_eq!(\n", "file_path": "src/mailgun/mod.rs", "rank": 58, "score": 21189.159390407876 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n pub(super) fn update_route(\n\n &self,\n\n id: &str,\n\n priority: i32,\n\n actions: &[String],\n\n ) -> Result<(), Error> {\n\n if self.dry_run {\n\n return Ok(());\n\n }\n\n\n\n let priority_str = priority.to_string();\n\n let mut form = vec![(\"priority\", priority_str.as_str())];\n\n for action in actions {\n\n form.push((\"action\", action.as_str()));\n\n }\n\n\n", "file_path": "src/mailgun/api.rs", "rank": 59, "score": 19258.3888709285 }, { "content": " self.request(Method::PUT, &format!(\"routes/{}\", id))\n\n .form(&form)\n\n .send()?\n\n .error_for_status()?;\n\n\n\n Ok(())\n\n }\n\n\n\n pub(super) fn delete_route(&self, id: &str) -> Result<(), Error> {\n\n info!(\"deleting route with ID {}\", id);\n\n if self.dry_run {\n\n return Ok(());\n\n }\n\n\n\n self.request(Method::DELETE, &format!(\"routes/{}\", id))\n\n .send()?\n\n .error_for_status()?;\n\n Ok(())\n\n }\n\n\n", "file_path": "src/mailgun/api.rs", "rank": 60, "score": 19256.68598772322 }, { "content": "use failure::Error;\n\nuse log::info;\n\nuse reqwest::{\n\n header::{self, HeaderValue},\n\n Client, Method, RequestBuilder,\n\n};\n\n\n\npub(super) struct Mailgun {\n\n token: String,\n\n client: Client,\n\n dry_run: bool,\n\n}\n\n\n\nimpl Mailgun {\n\n pub(super) fn new(token: &str, dry_run: bool) -> Self {\n\n Self {\n\n token: token.into(),\n\n client: Client::new(),\n\n dry_run,\n\n }\n", "file_path": "src/mailgun/api.rs", "rank": 61, "score": 19256.684061590287 }, { "content": " actions: &[String],\n\n ) -> Result<(), Error> {\n\n if self.dry_run {\n\n return Ok(());\n\n }\n\n\n\n let priority_str = priority.to_string();\n\n let mut form = vec![\n\n (\"priority\", priority_str.as_str()),\n\n (\"description\", description),\n\n (\"expression\", expression),\n\n ];\n\n for action in actions {\n\n form.push((\"action\", action.as_str()));\n\n }\n\n\n\n self.request(Method::POST, \"routes\")\n\n .form(&form)\n\n .send()?\n\n .error_for_status()?;\n", "file_path": "src/mailgun/api.rs", "rank": 62, "score": 19256.148210099498 }, { "content": " }\n\n\n\n pub(super) fn get_routes(&self, skip: Option<usize>) -> Result<RoutesResponse, Error> {\n\n let url = if let Some(skip) = skip {\n\n format!(\"routes?skip={}\", skip)\n\n } else {\n\n \"routes\".into()\n\n };\n\n Ok(self\n\n .request(Method::GET, &url)\n\n .send()?\n\n .error_for_status()?\n\n .json()?)\n\n }\n\n\n\n pub(super) fn create_route(\n\n &self,\n\n priority: i32,\n\n description: &str,\n\n expression: &str,\n", "file_path": "src/mailgun/api.rs", "rank": 63, "score": 19250.996037713936 }, { "content": " fn request(&self, method: Method, url: &str) -> RequestBuilder {\n\n let url = if url.starts_with(\"https://\") {\n\n url.into()\n\n } else {\n\n format!(\"https://api.mailgun.net/v3/{}\", url)\n\n };\n\n\n\n self.client\n\n .request(method, &url)\n\n .basic_auth(\"api\", Some(&self.token))\n\n .header(\n\n header::USER_AGENT,\n\n HeaderValue::from_static(crate::USER_AGENT),\n\n )\n\n }\n\n}\n\n\n\n#[derive(serde::Deserialize)]\n\npub(super) struct RoutesResponse {\n\n pub(super) items: Vec<Route>,\n", "file_path": "src/mailgun/api.rs", "rank": 64, "score": 19250.82711041467 }, { "content": " pub(super) total_count: usize,\n\n}\n\n\n\n#[derive(serde::Deserialize)]\n\npub(super) struct Route {\n\n pub(super) actions: Vec<String>,\n\n pub(super) expression: String,\n\n pub(super) id: String,\n\n pub(super) priority: i32,\n\n pub(super) description: serde_json::Value,\n\n}\n", "file_path": "src/mailgun/api.rs", "rank": 65, "score": 19247.566473659033 }, { "content": "mod github;\n\nmod mailgun;\n\nmod team_api;\n\n\n\nuse crate::github::SyncGitHub;\n\nuse crate::team_api::TeamApi;\n\nuse failure::{Error, ResultExt};\n\nuse log::{error, info, warn};\n\n\n\nconst AVAILABLE_SERVICES: &[&str] = &[\"github\", \"mailgun\"];\n\nconst USER_AGENT: &str = \"rust-lang teams sync (https://github.com/rust-lang/sync-team)\";\n\n\n", "file_path": "src/main.rs", "rank": 66, "score": 23.41336555379539 }, { "content": " eprintln!(\"unknown argument: {}\", arg);\n\n usage();\n\n std::process::exit(1);\n\n }\n\n }\n\n }\n\n\n\n let team_api = team_repo\n\n .map(|p| TeamApi::Local(p.into()))\n\n .unwrap_or(TeamApi::Production);\n\n\n\n if services.is_empty() {\n\n info!(\"no service to synchronize specified, defaulting to all services\");\n\n services = AVAILABLE_SERVICES\n\n .iter()\n\n .map(|s| (*s).to_string())\n\n .collect();\n\n }\n\n\n\n if dry_run {\n", "file_path": "src/main.rs", "rank": 67, "score": 13.51510111978457 }, { "content": " warn!(\"sync-team is running in dry mode, no changes will be applied.\");\n\n warn!(\"run the binary with the --live flag to apply the changes.\");\n\n }\n\n\n\n for service in services {\n\n info!(\"synchronizing {}\", service);\n\n match service.as_str() {\n\n \"github\" => {\n\n let token = std::env::var(\"GITHUB_TOKEN\")\n\n .with_context(|_| \"failed to get the GITHUB_TOKEN environment variable\")?;\n\n\n\n let sync = SyncGitHub::new(token, &team_api, dry_run)?;\n\n sync.synchronize_all()?;\n\n }\n\n \"mailgun\" => {\n\n let token = std::env::var(\"MAILGUN_API_TOKEN\")\n\n .with_context(|_| \"failed to get the MAILGUN_API_TOKEN environment variable\")?;\n\n mailgun::run(&token, &team_api, dry_run)?;\n\n }\n\n _ => panic!(\"unknown service: {}\", service),\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 68, "score": 10.914575469056327 } ]
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, $table:expr) => (crate::common::setup(crate::common::Fixture::$fixture, Some($table)));\n\n);\n\n\n\nmacro_rules! tags(\n\n ($($name:expr,)*) => (vec![$(::truetype::Tag(*$name),)*]);\n\n ($($name:expr),*) => (tags!($($name,)*));\n\n);\n\n\n\npub enum Fixture {\n\n AdobeVFPrototype,\n\n Gingham,\n", "file_path": "tests/common/mod.rs", "rank": 0, "score": 88983.48397246872 }, { "content": " OpenSans,\n\n SourceSerifPro,\n\n}\n\n\n\nimpl Fixture {\n\n pub fn path(&self) -> PathBuf {\n\n match *self {\n\n Fixture::AdobeVFPrototype => \"tests/fixtures/AdobeVFPrototype.otf\".into(),\n\n Fixture::Gingham => \"tests/fixtures/Gingham.ttf\".into(),\n\n Fixture::OpenSans => \"tests/fixtures/OpenSans-Italic.ttf\".into(),\n\n Fixture::SourceSerifPro => \"tests/fixtures/SourceSerifPro-Regular.otf\".into(),\n\n }\n\n }\n\n\n\n pub fn offset(&self, table: &str) -> u64 {\n\n match *self {\n\n Fixture::AdobeVFPrototype => match table {\n\n _ => unreachable!(),\n\n },\n\n Fixture::Gingham => match table {\n", "file_path": "tests/common/mod.rs", "rank": 1, "score": 88974.91978063229 }, { "content": " _ => unreachable!(),\n\n },\n\n Fixture::OpenSans => match table {\n\n \"GDEF\" => 206348,\n\n _ => unreachable!(),\n\n },\n\n Fixture::SourceSerifPro => match table {\n\n \"GPOS\" => 60412,\n\n \"GSUB\" => 57648,\n\n _ => unreachable!(),\n\n },\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/common/mod.rs", "rank": 2, "score": 88971.50502521606 }, { "content": "pub fn setup(fixture: Fixture, table: Option<&str>) -> File {\n\n use std::io::{Seek, SeekFrom};\n\n\n\n let mut file = ok!(File::open(fixture.path()));\n\n ok!(file.seek(SeekFrom::Start(\n\n table.map(|table| fixture.offset(table)).unwrap_or(0)\n\n )));\n\n file\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 3, "score": 83697.89945257611 }, { "content": "#[test]\n\nfn table() {\n\n let table: GlyphDefinition = ok!(Value::read(&mut setup!(OpenSans, \"GDEF\")));\n\n match &table.header {\n\n &Header::Version1(..) => {}\n\n _ => unreachable!(),\n\n }\n\n match &table.glyph_class {\n\n &Some(Class::Format2(ref table)) => {\n\n assert!(table.range_count == 1);\n\n assert!(table.ranges[0].start == 0);\n\n assert!(table.ranges[0].end == 937);\n\n }\n\n _ => unreachable!(),\n\n }\n\n assert!(table.attachments.is_none());\n\n match &table.ligatures {\n\n &Some(ref table) => assert!(table.count == 0),\n\n _ => unreachable!(),\n\n }\n\n}\n", "file_path": "tests/glyph_definition_test.rs", "rank": 4, "score": 63231.85374010904 }, { "content": "#[test]\n\nfn scripts() {\n\n let GlyphPositioning { scripts, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, \"GPOS\")));\n\n let tags = scripts\n\n .headers\n\n .iter()\n\n .map(|header| header.tag)\n\n .collect::<Vec<_>>();\n\n assert!(tags == tags![b\"DFLT\", b\"latn\"]);\n\n assert!(scripts.get(Script::Default).is_some());\n\n assert!(scripts.get(Script::Latin).is_some());\n\n let tags = scripts\n\n .records\n\n .iter()\n\n .map(|record| {\n\n record\n\n .language_headers\n\n .iter()\n\n .map(|header| header.tag)\n\n .collect::<Vec<_>>()\n\n })\n\n .collect::<Vec<_>>();\n\n assert!(tags == &[vec![], tags![b\"AZE \", b\"CRT \", b\"TRK \"]]);\n\n let record = &scripts.records[0];\n\n assert!(record.default_language.is_some());\n\n assert!(record.language_count == 0);\n\n let record = &scripts.records[1];\n\n assert!(record.language_count == 3);\n\n assert!(record.get(Language::Turkish).is_some());\n\n}\n", "file_path": "tests/glyph_positioning_test.rs", "rank": 5, "score": 62150.314042590486 }, { "content": "extern crate opentype;\n\nextern crate postscript;\n\nextern crate truetype;\n\n\n\nuse opentype::File;\n\n\n\n#[macro_use]\n\nmod common;\n\n\n\n#[test]\n", "file_path": "tests/file_test.rs", "rank": 7, "score": 38275.53922411443 }, { "content": "extern crate opentype;\n\nextern crate truetype;\n\n\n\nuse opentype::glyph_positioning::{GlyphPositioning, PairAdjustment, Table};\n\nuse opentype::layout::script::{Language, Script};\n\nuse truetype::Value;\n\n\n\n#[macro_use]\n\nmod common;\n\n\n\n#[test]\n", "file_path": "tests/glyph_positioning_test.rs", "rank": 8, "score": 37023.236613154 }, { "content": "extern crate opentype;\n\nextern crate truetype;\n\n\n\nuse opentype::glyph_definition::{GlyphDefinition, Header};\n\nuse opentype::layout::Class;\n\nuse truetype::Value;\n\n\n\n#[macro_use]\n\nmod common;\n\n\n\n#[test]\n", "file_path": "tests/glyph_definition_test.rs", "rank": 10, "score": 37017.81237881959 }, { "content": "#[test]\n\nfn ttf() {\n\n use truetype::{FontHeader, GlyphData, GlyphMapping, MaximumProfile};\n\n\n\n let mut reader = setup!(OpenSans);\n\n let file = ok!(File::read(&mut reader));\n\n let font_header = ok!(ok!(file[0].take::<_, FontHeader>(&mut reader)));\n\n let maximum_profile = ok!(ok!(file[0].take::<_, MaximumProfile>(&mut reader)));\n\n let glyph_mapping = ok!(ok!(\n\n file[0].take_given::<_, GlyphMapping>(&mut reader, (&font_header, &maximum_profile))\n\n ));\n\n let _ = ok!(ok!(\n\n file[0].take_given::<_, GlyphData>(&mut reader, &glyph_mapping)\n\n ));\n\n}\n\n\n", "file_path": "tests/file_test.rs", "rank": 11, "score": 36992.543747082 }, { "content": "#[test]\n\nfn cff() {\n\n use postscript::compact1::FontSet;\n\n\n\n let mut reader = setup!(SourceSerifPro);\n\n let file = ok!(File::read(&mut reader));\n\n let _ = ok!(ok!(file[0].take::<_, FontSet>(&mut reader)));\n\n}\n\n\n", "file_path": "tests/file_test.rs", "rank": 12, "score": 36992.543747082 }, { "content": "/// A font table.\n\npub trait Table<'l>: Sized {\n\n #[doc(hidden)]\n\n type Parameter;\n\n\n\n #[doc(hidden)]\n\n fn tag() -> Tag;\n\n\n\n #[doc(hidden)]\n\n fn take<T>(tape: &mut T, parameter: Self::Parameter) -> Result<Self>\n\n where\n\n T: Read + Seek;\n\n}\n\n\n\nmacro_rules! table {\n\n (@one $tag:expr => opentype::$kind:ident()) => (\n\n table! { @one $tag => truetype::$kind() }\n\n );\n\n (@one $tag:expr => $scope:ident::$kind:ident()) => (\n\n impl Table<'static> for $kind {\n\n type Parameter = ();\n", "file_path": "src/table.rs", "rank": 15, "score": 36305.45717060798 }, { "content": "#[test]\n\nfn variable_cff() {\n\n use opentype::GlyphSubstitution;\n\n\n\n let mut reader = setup!(AdobeVFPrototype);\n\n let file = ok!(File::read(&mut reader));\n\n let _ = ok!(ok!(file[0].take::<_, GlyphSubstitution>(&mut reader)));\n\n}\n\n\n", "file_path": "tests/file_test.rs", "rank": 18, "score": 35815.64447869197 }, { "content": "#[test]\n\nfn lookups() {\n\n let GlyphPositioning { lookups, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, \"GPOS\")));\n\n assert!(lookups.records.len() == 1);\n\n let record = &lookups.records[0];\n\n assert!(record.mark_filtering_set.is_none());\n\n assert!(record.tables.len() == 2);\n\n match &record.tables[0] {\n\n &Table::PairAdjustment(PairAdjustment::Format1(ref table)) => {\n\n assert!(table.set_count == 65);\n\n }\n\n _ => unreachable!(),\n\n }\n\n match &record.tables[1] {\n\n &Table::PairAdjustment(PairAdjustment::Format2(ref table)) => {\n\n assert!(table.class1_count == 99);\n\n assert!(table.class2_count == 95);\n\n }\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "tests/glyph_positioning_test.rs", "rank": 19, "score": 35815.64447869197 }, { "content": "#[test]\n\nfn variable_ttf() {\n\n use opentype::GlyphSubstitution;\n\n\n\n let mut reader = setup!(Gingham);\n\n let file = ok!(File::read(&mut reader));\n\n let _ = ok!(ok!(file[0].take::<_, GlyphSubstitution>(&mut reader)));\n\n}\n", "file_path": "tests/file_test.rs", "rank": 20, "score": 35815.64447869197 }, { "content": "#[test]\n\nfn features() {\n\n let GlyphPositioning { features, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, \"GPOS\")));\n\n let tags = features\n\n .headers\n\n .iter()\n\n .map(|header| header.tag)\n\n .collect::<Vec<_>>();\n\n assert!(\n\n tags == tags![\n\n b\"kern\", b\"kern\", b\"kern\", b\"kern\", b\"kern\", b\"size\", b\"size\", b\"size\", b\"size\",\n\n b\"size\",\n\n ]\n\n );\n\n let lookups = features\n\n .records\n\n .iter()\n\n .map(|record| record.lookup_count)\n\n .collect::<Vec<_>>();\n\n assert!(lookups == &[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]);\n\n}\n\n\n", "file_path": "tests/glyph_positioning_test.rs", "rank": 21, "score": 35815.64447869197 }, { "content": "use postscript;\n\nuse postscript::compact1::FontSet;\n\nuse std::io::{Read, Seek};\n\nuse truetype::{self, Result, Tag};\n\nuse truetype::{\n\n CharMapping, FontHeader, GlyphData, GlyphMapping, HorizontalHeader, HorizontalMetrics,\n\n MaximumProfile, NamingTable, PostScript, WindowsMetrics,\n\n};\n\n\n\nuse crate::{GlyphDefinition, GlyphPositioning, GlyphSubstitution};\n\n\n\n/// A font table.\n", "file_path": "src/table.rs", "rank": 22, "score": 32050.35253130393 }, { "content": " fn take<T>(tape: &mut T, parameter: Self::Parameter) -> Result<Self>\n\n where T: Read + Seek\n\n {\n\n $scope::Tape::take_given(tape, parameter)\n\n }\n\n }\n\n );\n\n ($($tag:expr => $scope:ident::$kind:ident($($parameter:tt)*),)+) => (\n\n $(table! { @one $tag => $scope::$kind($($parameter)*) })+\n\n );\n\n}\n\n\n\ntable! {\n\n b\"CFF \" => postscript::FontSet(),\n\n b\"GDEF\" => opentype::GlyphDefinition(),\n\n b\"GPOS\" => opentype::GlyphPositioning(),\n\n b\"GSUB\" => opentype::GlyphSubstitution(),\n\n b\"OS/2\" => truetype::WindowsMetrics(),\n\n b\"cmap\" => truetype::CharMapping(),\n\n b\"glyf\" => truetype::GlyphData(..),\n\n b\"head\" => truetype::FontHeader(),\n\n b\"hhea\" => truetype::HorizontalHeader(),\n\n b\"hmtx\" => truetype::HorizontalMetrics(..),\n\n b\"loca\" => truetype::GlyphMapping(..),\n\n b\"maxp\" => truetype::MaximumProfile(),\n\n b\"name\" => truetype::NamingTable(),\n\n b\"post\" => truetype::PostScript(),\n\n}\n", "file_path": "src/table.rs", "rank": 23, "score": 32047.128216633122 }, { "content": "\n\n #[inline]\n\n fn tag() -> Tag { Tag(*$tag) }\n\n\n\n #[inline]\n\n fn take<T>(tape: &mut T, _: Self::Parameter) -> Result<Self>\n\n where T: Read + Seek\n\n {\n\n $scope::Tape::take(tape)\n\n }\n\n }\n\n );\n\n (@one $tag:expr => $scope:ident::$kind:ident(..)) => (\n\n impl<'l> Table<'l> for $kind {\n\n type Parameter = <$kind as $scope::Walue<'l>>::Parameter;\n\n\n\n #[inline]\n\n fn tag() -> Tag { Tag(*$tag) }\n\n\n\n #[inline]\n", "file_path": "src/table.rs", "rank": 24, "score": 32037.123826689945 }, { "content": "//! The script list.\n\n\n\nuse truetype::Tag;\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A script list.\"]\n\n pub Scripts { // ScriptList\n\n count (u16), // ScriptCount\n\n\n\n headers (Vec<Header>) |this, tape, _| { // ScriptRecord\n\n tape.take_given(this.count as usize)\n\n },\n\n\n\n records (Vec<Record>) |this, tape, position| {\n\n jump_take!(tape, position, this.count, i => this.headers[i].offset)\n\n },\n\n }\n\n}\n\n\n", "file_path": "src/layout/script.rs", "rank": 25, "score": 29147.02868149372 }, { "content": " $(#[doc = $name] $token,)*\n\n }\n\n\n\n impl Script {\n\n /// Return the tag.\n\n pub fn tag(&self) -> Tag {\n\n use Script::*;\n\n match *self {\n\n $($token => Tag(*$tag),)*\n\n }\n\n }\n\n }\n\n\n\n impl Scripts {\n\n /// Return the record of a script if present.\n\n pub fn get(&self, script: Script) -> Option<&Record> {\n\n let tag = script.tag();\n\n for (i, header) in self.headers.iter().enumerate() {\n\n if header.tag == tag {\n\n return Some(&self.records[i]);\n", "file_path": "src/layout/script.rs", "rank": 26, "score": 29142.390303481825 }, { "content": "table! {\n\n #[doc = \"A script header.\"]\n\n #[derive(Copy)]\n\n pub Header { // ScriptRecord\n\n tag (Tag), // ScriptTag\n\n offset (u16), // Script\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A script record.\"]\n\n pub Record { // Script\n\n default_language_offset (u16), // DefaultLangSys\n\n language_count (u16), // LangSysCount\n\n\n\n language_headers (Vec<LanguageHeader>) |this, tape, _| { // LangSysRecord\n\n tape.take_given(this.language_count as usize)\n\n },\n\n\n", "file_path": "src/layout/script.rs", "rank": 27, "score": 29142.325239168404 }, { "content": "}\n\n\n\ntable! {\n\n #[doc = \"A language-system record.\"]\n\n pub LanguageRecord { // LangSys\n\n lookup_order (u16) = { 0 }, // LookupOrder\n\n required_feature_index (u16), // ReqFeatureIndex\n\n feature_count (u16), // FeatureCount\n\n\n\n feature_indices (Vec<u16>) |this, tape| { // FeatureIndex\n\n tape.take_given(this.feature_count as usize)\n\n },\n\n }\n\n}\n\n\n\nmacro_rules! implement {\n\n ($($tag:expr => $name:expr => $token:ident,)*) => (\n\n /// A script.\n\n #[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\n pub enum Script {\n", "file_path": "src/layout/script.rs", "rank": 28, "score": 29140.184660401883 }, { "content": "\n\nmacro_rules! implement {\n\n ($($tag:expr => $name:expr => $token:ident => $code:expr,)*) => (\n\n /// A language system.\n\n #[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\n pub enum Language {\n\n $(#[doc = $name] $token,)*\n\n }\n\n\n\n impl Language {\n\n /// Return the tag.\n\n pub fn tag(&self) -> Tag {\n\n use Language::*;\n\n match *self {\n\n $($token => Tag(*$tag),)*\n\n }\n\n }\n\n }\n\n\n\n impl Record {\n", "file_path": "src/layout/script.rs", "rank": 29, "score": 29137.700433347283 }, { "content": " default_language (Option<LanguageRecord>) |this, tape, position| {\n\n if this.default_language_offset != 0 {\n\n Ok(Some(jump_take!(@unwrap tape, position, this.default_language_offset)))\n\n } else {\n\n Ok(None)\n\n }\n\n },\n\n\n\n language_records (Vec<LanguageRecord>) |this, tape, position| {\n\n jump_take!(tape, position, this.language_count, i => this.language_headers[i].offset)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n #[doc = \"A language-system header.\"]\n\n pub LanguageHeader { // LangSysRecord\n\n tag (Tag), // LangSysTag\n\n offset (u16), // LangSys\n\n }\n", "file_path": "src/layout/script.rs", "rank": 30, "score": 29137.049488672033 }, { "content": " b\"MER \" => \"Meru\" => Meru => \"mer\",\n\n b\"MFE \" => \"Morisyen\" => Morisyen => \"mfe\",\n\n b\"MIN \" => \"Minangkabau\" => Minangkabau => \"min\",\n\n b\"MIZ \" => \"Mizo\" => Mizo => \"lus\",\n\n b\"MKD \" => \"Macedonian\" => Macedonian => \"mkd\",\n\n b\"MKR \" => \"Makasar\" => Makasar => \"mak\",\n\n b\"MKW \" => \"Kituba\" => Kituba => \"mkw\",\n\n b\"MLE \" => \"Male\" => Male => \"mdy\",\n\n b\"MLG \" => \"Malagasy\" => Malagasy => \"mlg\",\n\n b\"MLN \" => \"Malinke\" => Malinke => \"mlq\",\n\n b\"MLR \" => \"Malayalam Reformed\" => MalayalamReformed => \"mal\",\n\n b\"MLY \" => \"Malay\" => Malay => \"msa\",\n\n b\"MND \" => \"Mandinka\" => Mandinka => \"mnk\",\n\n b\"MNG \" => \"Mongolian\" => Mongolian => \"mon\",\n\n b\"MNI \" => \"Manipuri\" => Manipuri => \"mni\",\n\n b\"MNK \" => \"Maninka\" => Maninka => \"man, mnk, myq, mku, msc, emk, mwk, mlq\",\n\n b\"MNX \" => \"Manx\" => Manx => \"glv\",\n\n b\"MOH \" => \"Mohawk\" => Mohawk => \"moh\",\n\n b\"MOK \" => \"Moksha\" => Moksha => \"mdf\",\n\n b\"MOL \" => \"Moldavian\" => Moldavian => \"mol\",\n", "file_path": "src/layout/script.rs", "rank": 31, "score": 29135.101677355862 }, { "content": " b\"GEZ \" => \"Ge’ez\" => Geez => \"gez\",\n\n b\"GIH \" => \"Githabul\" => Githabul => \"gih\",\n\n b\"GIL \" => \"Gilyak\" => Gilyak => \"niv\",\n\n b\"GIL0\" => \"Kiribati (Gilbertese)\" => Kiribati => \"gil\",\n\n b\"GKP \" => \"Kpelle (Guinea)\" => KpelleGuinea => \"gkp\",\n\n b\"GLK \" => \"Gilaki\" => Gilaki => \"glk\",\n\n b\"GMZ \" => \"Gumuz\" => Gumuz => \"guk\",\n\n b\"GNN \" => \"Gumatj\" => Gumatj => \"gnn\",\n\n b\"GOG \" => \"Gogo\" => Gogo => \"gog\",\n\n b\"GON \" => \"Gondi\" => Gondi => \"gon\",\n\n b\"GRN \" => \"Greenlandic\" => Greenlandic => \"kal\",\n\n b\"GRO \" => \"Garo\" => Garo => \"grt\",\n\n b\"GUA \" => \"Guarani\" => Guarani => \"grn\",\n\n b\"GUC \" => \"Wayuu\" => Wayuu => \"guc\",\n\n b\"GUF \" => \"Gupapuyngu\" => Gupapuyngu => \"guf\",\n\n b\"GUJ \" => \"Gujarati\" => Gujarati => \"guj\",\n\n b\"GUZ \" => \"Gusii\" => Gusii => \"guz\",\n\n b\"HAI \" => \"Haitian (Haitian Creole)\" => Haitian => \"hat\",\n\n b\"HAL \" => \"Halam\" => Halam => \"flm\",\n\n b\"HAR \" => \"Harauti\" => Harauti => \"hoj\",\n", "file_path": "src/layout/script.rs", "rank": 32, "score": 29135.101677355862 }, { "content": " b\"IBO \" => \"Igbo\" => Igbo => \"ibo\",\n\n b\"IJO \" => \"Ijo languages\" => Ijolanguages => \"ijc\",\n\n b\"IDO \" => \"Ido\" => Ido => \"ido\",\n\n b\"ILE \" => \"Interlingue\" => Interlingue => \"ile\",\n\n b\"ILO \" => \"Ilokano\" => Ilokano => \"ilo\",\n\n b\"INA \" => \"Interlingua\" => Interlingua => \"ina\",\n\n b\"IND \" => \"Indonesian\" => Indonesian => \"ind\",\n\n b\"ING \" => \"Ingush\" => Ingush => \"inh\",\n\n b\"INU \" => \"Inuktitut\" => Inuktitut => \"iku\",\n\n b\"IPK \" => \"Inupiat\" => Inupiat => \"ipk\",\n\n b\"IPPH\" => \"Phonetic transcription, IPA\" => InternationalPhoneticAlphabet => \"\",\n\n b\"IRI \" => \"Irish\" => Irish => \"gle\",\n\n b\"IRT \" => \"Irish Traditional\" => IrishTraditional => \"gle\",\n\n b\"ISL \" => \"Icelandic\" => Icelandic => \"isl\",\n\n b\"ISM \" => \"Inari Sami\" => InariSami => \"smn\",\n\n b\"ITA \" => \"Italian\" => Italian => \"ita\",\n\n b\"IWR \" => \"Hebrew\" => Hebrew => \"heb\",\n\n b\"JAM \" => \"Jamaican Creole\" => JamaicanCreole => \"jam\",\n\n b\"JAN \" => \"Japanese\" => Japanese => \"jpn\",\n\n b\"JAV \" => \"Javanese\" => Javanese => \"jav\",\n", "file_path": "src/layout/script.rs", "rank": 33, "score": 29135.101677355862 }, { "content": " b\"YCR \" => \"Y-Cree\" => YCree => \"cre\",\n\n b\"YIC \" => \"Yi Classic\" => YiClassic => \"\",\n\n b\"YIM \" => \"Yi Modern\" => YiModern => \"iii\",\n\n b\"ZEA \" => \"Zealandic\" => Zealandic => \"zea\",\n\n b\"ZGH \" => \"Standard Morrocan Tamazigh\" => StandardMorrocanTamazigh => \"zgh\",\n\n b\"ZHA \" => \"Zhuang\" => Zhuang => \"zha\",\n\n b\"ZHH \" => \"Chinese, Hong Kong SAR\" => Chinese => \"zho\",\n\n b\"ZHP \" => \"Chinese Phonetic\" => ChinesePhonetic => \"zho\",\n\n b\"ZHS \" => \"Chinese Simplified\" => ChineseSimplified => \"zho\",\n\n b\"ZHT \" => \"Chinese Traditional\" => ChineseTraditional => \"zho\",\n\n b\"ZND \" => \"Zande\" => Zande => \"zne\",\n\n b\"ZUL \" => \"Zulu\" => Zulu => \"zul\",\n\n b\"ZZA \" => \"Zazaki\" => Zazaki => \"zza\",\n\n}\n", "file_path": "src/layout/script.rs", "rank": 34, "score": 29135.101677355862 }, { "content": " b\"PCC \" => \"Bouyei\" => Bouyei => \"pcc\",\n\n b\"PCD \" => \"Picard\" => Picard => \"pcd\",\n\n b\"PDC \" => \"Pennsylvania German\" => PennsylvaniaGerman => \"pdc\",\n\n b\"PGR \" => \"Polytonic Greek\" => PolytonicGreek => \"ell\",\n\n b\"PHK \" => \"Phake\" => Phake => \"phk\",\n\n b\"PIH \" => \"Norfolk\" => Norfolk => \"pih\",\n\n b\"PIL \" => \"Filipino\" => Filipino => \"fil\",\n\n b\"PLG \" => \"Palaung\" => Palaung => \"pce, rbb, pll\",\n\n b\"PLK \" => \"Polish\" => Polish => \"pol\",\n\n b\"PMS \" => \"Piemontese\" => Piemontese => \"pms\",\n\n b\"PNB \" => \"Western Panjabi\" => WesternPanjabi => \"pnb\",\n\n b\"POH \" => \"Pocomchi\" => Pocomchi => \"poh\",\n\n b\"PON \" => \"Pohnpeian\" => Pohnpeian => \"pon\",\n\n b\"PRO \" => \"Provencal\" => Provencal => \"pro\",\n\n b\"PTG \" => \"Portuguese\" => Portuguese => \"por\",\n\n b\"PWO \" => \"Western Pwo Karen\" => WesternPwoKaren => \"pwo\",\n\n b\"QIN \" => \"Chin\" => Chin => \"bgr, cnh, cnw, czt, sez, tcp, csy, ctd, flm, pck, tcz, zom, \\\n\n cmr, dao, hlt, cka, cnk, mrh, mwg, cbl, cnb, csh\",\n\n b\"QUC \" => \"K’iche’\" => Kiche => \"quc\",\n\n b\"QUH \" => \"Quechua (Bolivia)\" => QuechuaBolivia => \"quh\",\n", "file_path": "src/layout/script.rs", "rank": 35, "score": 29135.101677355862 }, { "content": " b\"MON \" => \"Mon\" => Mon => \"mnw\",\n\n b\"MOR \" => \"Moroccan\" => Moroccan => \"\",\n\n b\"MOS \" => \"Mossi\" => Mossi => \"mos\",\n\n b\"MRI \" => \"Maori\" => Maori => \"mri\",\n\n b\"MTH \" => \"Maithili\" => Maithili => \"mai\",\n\n b\"MTS \" => \"Maltese\" => Maltese => \"mlt\",\n\n b\"MUN \" => \"Mundari\" => Mundari => \"unr\",\n\n b\"MUS \" => \"Muscogee\" => Muscogee => \"mus\",\n\n b\"MWL \" => \"Mirandese\" => Mirandese => \"mwl\",\n\n b\"MWW \" => \"Hmong Daw\" => HmongDaw => \"mww\",\n\n b\"MYN \" => \"Mayan\" => Mayan => \"myn\",\n\n b\"MZN \" => \"Mazanderani\" => Mazanderani => \"mzn\",\n\n b\"NAG \" => \"Naga-Assamese\" => NagaAssamese => \"nag\",\n\n b\"NAH \" => \"Nahuatl\" => Nahuatl => \"nah\",\n\n b\"NAN \" => \"Nanai\" => Nanai => \"gld\",\n\n b\"NAP \" => \"Neapolitan\" => Neapolitan => \"nap\",\n\n b\"NAS \" => \"Naskapi\" => Naskapi => \"nsk\",\n\n b\"NAU \" => \"Nauruan\" => Nauruan => \"nau\",\n\n b\"NAV \" => \"Navajo\" => Navajo => \"nav\",\n\n b\"NCR \" => \"N-Cree\" => NCree => \"csw\",\n", "file_path": "src/layout/script.rs", "rank": 36, "score": 29135.101677355862 }, { "content": " }\n\n }\n\n None\n\n }\n\n }\n\n );\n\n}\n\n\n\nimplement! {\n\n b\"adlm\" => \"Adlam\" => Adlam,\n\n b\"ahom\" => \"Ahom\" => Ahom,\n\n b\"hluw\" => \"Anatolian Hieroglyphs\" => AnatolianHieroglyphs,\n\n b\"arab\" => \"Arabic\" => Arabic,\n\n b\"armn\" => \"Armenian\" => Armenian,\n\n b\"avst\" => \"Avestan\" => Avestan,\n\n b\"bali\" => \"Balinese\" => Balinese,\n\n b\"bamu\" => \"Bamum\" => Bamum,\n\n b\"bass\" => \"Bassa Vah\" => BassaVah,\n\n b\"batk\" => \"Batak\" => Batak,\n\n b\"beng\" => \"Bengali\" => Bengali,\n", "file_path": "src/layout/script.rs", "rank": 37, "score": 29135.101677355862 }, { "content": " b\"mymr\" => \"Myanmar\" => Myanmar,\n\n b\"mym2\" => \"Myanmar v2\" => MyanmarV2,\n\n b\"nbat\" => \"Nabataean\" => Nabataean,\n\n b\"newa\" => \"Newa\" => Newa,\n\n b\"talu\" => \"New Tai Lue\" => NewTaiLue,\n\n b\"nko \" => \"N’Ko\" => NKo,\n\n b\"orya\" => \"Odia (formerly Oriya)\" => Odia,\n\n b\"ory2\" => \"Odia v2 (formerly Oriya v2)\" => OdiaV2,\n\n b\"ogam\" => \"Ogham\" => Ogham,\n\n b\"olck\" => \"Ol Chiki\" => OlChiki,\n\n b\"ital\" => \"Old Italic\" => OldItalic,\n\n b\"hung\" => \"Old Hungarian\" => OldHungarian,\n\n b\"narb\" => \"Old North Arabian\" => OldNorthArabian,\n\n b\"perm\" => \"Old Permic\" => OldPermic,\n\n b\"xpeo\" => \"Old Persian Cuneiform\" => OldPersianCuneiform,\n\n b\"sarb\" => \"Old South Arabian\" => OldSouthArabian,\n\n b\"orkh\" => \"Old Turkic, Orkhon Runic\" => OldTurkic,\n\n b\"osge\" => \"Osage\" => Osage,\n\n b\"osma\" => \"Osmanya\" => Osmanya,\n\n b\"hmng\" => \"Pahawh Hmong\" => PahawhHmong,\n", "file_path": "src/layout/script.rs", "rank": 38, "score": 29135.101677355862 }, { "content": " b\"SKY \" => \"Slovak\" => Slovak => \"slk\",\n\n b\"SCS \" => \"North Slavey\" => NorthSlavey => \"scs\",\n\n b\"SLA \" => \"Slavey\" => Slavey => \"scs, xsl\",\n\n b\"SLV \" => \"Slovenian\" => Slovenian => \"slv\",\n\n b\"SML \" => \"Somali\" => Somali => \"som\",\n\n b\"SMO \" => \"Samoan\" => Samoan => \"smo\",\n\n b\"SNA \" => \"Sena\" => Sena => \"seh\",\n\n b\"SNA0\" => \"Shona\" => Shona => \"sna\",\n\n b\"SND \" => \"Sindhi\" => Sindhi => \"snd\",\n\n b\"SNH \" => \"Sinhala (Sinhalese)\" => SinhalaSinhalese => \"sin\",\n\n b\"SNK \" => \"Soninke\" => Soninke => \"snk\",\n\n b\"SOG \" => \"Sodo Gurage\" => SodoGurage => \"gru\",\n\n b\"SOP \" => \"Songe\" => Songe => \"sop\",\n\n b\"SOT \" => \"Sotho, Southern\" => SouthernSotho => \"sot\",\n\n b\"SQI \" => \"Albanian\" => Albanian => \"sqi\",\n\n b\"SRB \" => \"Serbian\" => Serbian => \"srp\",\n\n b\"SRD \" => \"Sardinian\" => Sardinian => \"srd\",\n\n b\"SRK \" => \"Saraiki\" => Saraiki => \"skr\",\n\n b\"SRR \" => \"Serer\" => Serer => \"srr\",\n\n b\"SSL \" => \"South Slavey\" => SouthSlavey => \"xsl\",\n", "file_path": "src/layout/script.rs", "rank": 39, "score": 29135.101677355862 }, { "content": " b\"SSM \" => \"Southern Sami\" => SouthernSami => \"sma\",\n\n b\"STQ \" => \"Saterland Frisian\" => SaterlandFrisian => \"stq\",\n\n b\"SUK \" => \"Sukuma\" => Sukuma => \"suk\",\n\n b\"SUN \" => \"Sundanese\" => Sundanese => \"sun\",\n\n b\"SUR \" => \"Suri\" => Suri => \"suq\",\n\n b\"SVA \" => \"Svan\" => Svan => \"sva\",\n\n b\"SVE \" => \"Swedish\" => Swedish => \"swe\",\n\n b\"SWA \" => \"Swadaya Aramaic\" => SwadayaAramaic => \"aii\",\n\n b\"SWK \" => \"Swahili\" => Swahili => \"swa\",\n\n b\"SWZ \" => \"Swati\" => Swati => \"ssw\",\n\n b\"SXT \" => \"Sutu\" => Sutu => \"ngo\",\n\n b\"SXU \" => \"Upper Saxon\" => UpperSaxon => \"sxu\",\n\n b\"SYL \" => \"Sylheti\" => Sylheti => \"syl\",\n\n b\"SYR \" => \"Syriac\" => Syriac => \"syr\",\n\n b\"SZL \" => \"Silesian\" => Silesian => \"szl\",\n\n b\"TAB \" => \"Tabasaran\" => Tabasaran => \"tab\",\n\n b\"TAJ \" => \"Tajiki\" => Tajiki => \"tgk\",\n\n b\"TAM \" => \"Tamil\" => Tamil => \"tam\",\n\n b\"TAT \" => \"Tatar\" => Tatar => \"tat\",\n\n b\"TCR \" => \"TH-Cree\" => THCree => \"cwd\",\n", "file_path": "src/layout/script.rs", "rank": 40, "score": 29135.101677355862 }, { "content": " b\"CHO \" => \"Choctaw\" => Choctaw => \"cho\",\n\n b\"CHP \" => \"Chipewyan\" => Chipewyan => \"chp\",\n\n b\"CHR \" => \"Cherokee\" => Cherokee => \"chr\",\n\n b\"CHA \" => \"Chamorro\" => Chamorro => \"cha\",\n\n b\"CHU \" => \"Chuvash\" => Chuvash => \"chv\",\n\n b\"CHY \" => \"Cheyenne\" => Cheyenne => \"chy\",\n\n b\"CGG \" => \"Chiga\" => Chiga => \"cgg\",\n\n b\"CMR \" => \"Comorian\" => Comorian => \"swb, wlc, wni, zdj\",\n\n b\"COP \" => \"Coptic\" => Coptic => \"cop\",\n\n b\"COR \" => \"Cornish\" => Cornish => \"cor\",\n\n b\"COS \" => \"Corsican\" => Corsican => \"cos\",\n\n b\"CPP \" => \"Creoles\" => Creoles => \"cpp\",\n\n b\"CRE \" => \"Cree\" => Cree => \"cre\",\n\n b\"CRR \" => \"Carrier\" => Carrier => \"crx, caf\",\n\n b\"CRT \" => \"Crimean Tatar\" => CrimeanTatar => \"crh\",\n\n b\"CSB \" => \"Kashubian\" => Kashubian => \"csb\",\n\n b\"CSL \" => \"Church Slavonic\" => ChurchSlavonic => \"chu\",\n\n b\"CSY \" => \"Czech\" => Czech => \"ces\",\n\n b\"CTG \" => \"Chittagonian\" => Chittagonian => \"ctg\",\n\n b\"CUK \" => \"San Blas Kuna\" => SanBlasKuna => \"cuk\",\n", "file_path": "src/layout/script.rs", "rank": 41, "score": 29135.101677355862 }, { "content": " b\"NDB \" => \"Ndebele\" => Ndebele => \"nbl, nde\",\n\n b\"NDC \" => \"Ndau\" => Ndau => \"ndc\",\n\n b\"NDG \" => \"Ndonga\" => Ndonga => \"ndo\",\n\n b\"NDS \" => \"Low Saxon\" => LowSaxon => \"nds\",\n\n b\"NEP \" => \"Nepali\" => Nepali => \"nep\",\n\n b\"NEW \" => \"Newari\" => Newari => \"new\",\n\n b\"NGA \" => \"Ngbaka\" => Ngbaka => \"nga\",\n\n b\"NGR \" => \"Nagari\" => Nagari => \"\",\n\n b\"NHC \" => \"Norway House Cree\" => NorwayHouseCree => \"csw\",\n\n b\"NIS \" => \"Nisi\" => Nisi => \"dap\",\n\n b\"NIU \" => \"Niuean\" => Niuean => \"niu\",\n\n b\"NKL \" => \"Nyankole\" => Nyankole => \"nyn\",\n\n b\"NKO \" => \"N’Ko\" => NKo => \"nqo\",\n\n b\"NLD \" => \"Dutch\" => Dutch => \"nld\",\n\n b\"NOE \" => \"Nimadi\" => Nimadi => \"noe\",\n\n b\"NOG \" => \"Nogai\" => Nogai => \"nog\",\n\n b\"NOR \" => \"Norwegian\" => Norwegian => \"nob\",\n\n b\"NOV \" => \"Novial\" => Novial => \"nov\",\n\n b\"NSM \" => \"Northern Sami\" => NorthernSami => \"sme\",\n\n b\"NSO \" => \"Sotho, Northern\" => NorthernSotho => \"nso\",\n", "file_path": "src/layout/script.rs", "rank": 42, "score": 29135.101677355862 }, { "content": " b\"tagb\" => \"Tagbanwa\" => Tagbanwa,\n\n b\"tale\" => \"Tai Le\" => TaiLe,\n\n b\"lana\" => \"Tai Tham (Lanna)\" => TaiTham,\n\n b\"tavt\" => \"Tai Viet\" => TaiViet,\n\n b\"takr\" => \"Takri\" => Takri,\n\n b\"taml\" => \"Tamil\" => Tamil,\n\n b\"tml2\" => \"Tamil v2\" => TamilV2,\n\n b\"tang\" => \"Tangut\" => Tangut,\n\n b\"telu\" => \"Telugu\" => Telugu,\n\n b\"tel2\" => \"Telugu v2\" => TeluguV2,\n\n b\"thaa\" => \"Thaana\" => Thaana,\n\n b\"thai\" => \"Thai\" => Thai,\n\n b\"tibt\" => \"Tibetan\" => Tibetan,\n\n b\"tfng\" => \"Tifinagh\" => Tifinagh,\n\n b\"tirh\" => \"Tirhuta\" => Tirhuta,\n\n b\"ugar\" => \"Ugaritic Cuneiform\" => UgariticCuneiform,\n\n b\"vai \" => \"Vai\" => Vai,\n\n b\"wara\" => \"Warang Citi\" => WarangCiti,\n\n b\"yi \" => \"Yi\" => Yi,\n\n}\n", "file_path": "src/layout/script.rs", "rank": 43, "score": 29135.101677355862 }, { "content": " b\"KOH \" => \"Korean Old Hangul\" => KoreanOldHangul => \"okm\",\n\n b\"KOK \" => \"Konkani\" => Konkani => \"kok\",\n\n b\"KON \" => \"Kikongo\" => Kikongo => \"ktu\",\n\n b\"KOM \" => \"Komi\" => Komi => \"kom\",\n\n b\"KON0\" => \"Kongo\" => Kongo => \"kon\",\n\n b\"KOP \" => \"Komi-Permyak\" => KomiPermyak => \"koi\",\n\n b\"KOR \" => \"Korean\" => Korean => \"kor\",\n\n b\"KOS \" => \"Kosraean\" => Kosraean => \"kos\",\n\n b\"KOZ \" => \"Komi-Zyrian\" => KomiZyrian => \"kpv\",\n\n b\"KPL \" => \"Kpelle\" => Kpelle => \"kpe\",\n\n b\"KRI \" => \"Krio\" => Krio => \"kri\",\n\n b\"KRK \" => \"Karakalpak\" => Karakalpak => \"kaa\",\n\n b\"KRL \" => \"Karelian\" => Karelian => \"krl\",\n\n b\"KRM \" => \"Karaim\" => Karaim => \"kdr\",\n\n b\"KRN \" => \"Karen\" => Karen => \"kar\",\n\n b\"KRT \" => \"Koorete\" => Koorete => \"kqy\",\n\n b\"KSH \" => \"Kashmiri\" => Kashmiri => \"kas\",\n\n b\"KSH0\" => \"Ripuarian\" => Ripuarian => \"ksh\",\n\n b\"KSI \" => \"Khasi\" => Khasi => \"kha\",\n\n b\"KSM \" => \"Kildin Sami\" => KildinSami => \"sjd\",\n", "file_path": "src/layout/script.rs", "rank": 44, "score": 29135.101677355862 }, { "content": " b\"KHM \" => \"Khmer\" => Khmer => \"khm\",\n\n b\"KHS \" => \"Khanty-Shurishkar\" => KhantyShurishkar => \"kca\",\n\n b\"KHT \" => \"Khamti Shan\" => KhamtiShan => \"kht\",\n\n b\"KHV \" => \"Khanty-Vakhi\" => KhantyVakhi => \"kca\",\n\n b\"KHW \" => \"Khowar\" => Khowar => \"khw\",\n\n b\"KIK \" => \"Kikuyu (Gikuyu)\" => Kikuyu => \"kik\",\n\n b\"KIR \" => \"Kirghiz (Kyrgyz)\" => Kirghiz => \"kir\",\n\n b\"KIS \" => \"Kisii\" => Kisii => \"kqs, kss\",\n\n b\"KIU \" => \"Kirmanjki\" => Kirmanjki => \"kiu\",\n\n b\"KJD \" => \"Southern Kiwai\" => SouthernKiwai => \"kjd\",\n\n b\"KJP \" => \"Eastern Pwo Karen\" => EasternPwoKaren => \"kjp\",\n\n b\"KKN \" => \"Kokni\" => Kokni => \"kex\",\n\n b\"KLM \" => \"Kalmyk\" => Kalmyk => \"xal\",\n\n b\"KMB \" => \"Kamba\" => Kamba => \"kam\",\n\n b\"KMN \" => \"Kumaoni\" => Kumaoni => \"kfy\",\n\n b\"KMO \" => \"Komo\" => Komo => \"kmw\",\n\n b\"KMS \" => \"Komso\" => Komso => \"kxc\",\n\n b\"KMZ \" => \"Khorasani Turkic\" => KhorasaniTurkic => \"kmz\",\n\n b\"KNR \" => \"Kanuri\" => Kanuri => \"kau\",\n\n b\"KOD \" => \"Kodagu\" => Kodagu => \"kfa\",\n", "file_path": "src/layout/script.rs", "rank": 45, "score": 29135.101677355862 }, { "content": " b\"FJI \" => \"Fijian\" => Fijian => \"fij\",\n\n b\"FLE \" => \"Dutch (Flemish)\" => DutchFlemish => \"vls\",\n\n b\"FMP \" => \"Fe’fe’\" => Fefe => \"fmp\",\n\n b\"FNE \" => \"Forest Nenets\" => ForestNenets => \"enf\",\n\n b\"FON \" => \"Fon\" => Fon => \"fon\",\n\n b\"FOS \" => \"Faroese\" => Faroese => \"fao\",\n\n b\"FRA \" => \"French\" => French => \"fra\",\n\n b\"FRC \" => \"Cajun French\" => CajunFrench => \"frc\",\n\n b\"FRI \" => \"Frisian\" => Frisian => \"fry\",\n\n b\"FRL \" => \"Friulian\" => Friulian => \"fur\",\n\n b\"FRP \" => \"Arpitan\" => Arpitan => \"frp\",\n\n b\"FTA \" => \"Futa\" => Futa => \"fuf\",\n\n b\"FUL \" => \"Fulah\" => Fulah => \"ful\",\n\n b\"FUV \" => \"Nigerian Fulfulde\" => NigerianFulfulde => \"fuv\",\n\n b\"GAD \" => \"Ga\" => Ga => \"gaa\",\n\n b\"GAE \" => \"Scottish Gaelic (Gaelic)\" => ScottishGaelic => \"gla\",\n\n b\"GAG \" => \"Gagauz\" => Gagauz => \"gag\",\n\n b\"GAL \" => \"Galician\" => Galician => \"glg\",\n\n b\"GAR \" => \"Garshuni\" => Garshuni => \"\",\n\n b\"GAW \" => \"Garhwali\" => Garhwali => \"gbm\",\n", "file_path": "src/layout/script.rs", "rank": 46, "score": 29135.101677355862 }, { "content": " b\"TDD \" => \"Dehong Dai\" => DehongDai => \"tdd\",\n\n b\"TEL \" => \"Telugu\" => Telugu => \"tel\",\n\n b\"TET \" => \"Tetum\" => Tetum => \"tet\",\n\n b\"TGL \" => \"Tagalog\" => Tagalog => \"tgl\",\n\n b\"TGN \" => \"Tongan\" => Tongan => \"ton\",\n\n b\"TGR \" => \"Tigre\" => Tigre => \"tig\",\n\n b\"TGY \" => \"Tigrinya\" => Tigrinya => \"tir\",\n\n b\"THA \" => \"Thai\" => Thai => \"tha\",\n\n b\"THT \" => \"Tahitian\" => Tahitian => \"tah\",\n\n b\"TIB \" => \"Tibetan\" => Tibetan => \"bod\",\n\n b\"TIV \" => \"Tiv\" => Tiv => \"tiv\",\n\n b\"TKM \" => \"Turkmen\" => Turkmen => \"tuk\",\n\n b\"TMH \" => \"Tamashek\" => Tamashek => \"tmh\",\n\n b\"TMN \" => \"Temne\" => Temne => \"tem\",\n\n b\"TNA \" => \"Tswana\" => Tswana => \"tsn\",\n\n b\"TNE \" => \"Tundra Nenets\" => TundraNenets => \"enh\",\n\n b\"TNG \" => \"Tonga\" => Tonga => \"toi\",\n\n b\"TOD \" => \"Todo\" => Todo => \"xal\",\n\n b\"TOD0\" => \"Toma\" => Toma => \"tod\",\n\n b\"TPI \" => \"Tok Pisin\" => TokPisin => \"tpi\",\n", "file_path": "src/layout/script.rs", "rank": 47, "score": 29135.101677355862 }, { "content": " b\"lisu\" => \"Lisu (Fraser)\" => Lisu,\n\n b\"lyci\" => \"Lycian\" => Lycian,\n\n b\"lydi\" => \"Lydian\" => Lydian,\n\n b\"mahj\" => \"Mahajani\" => Mahajani,\n\n b\"mlym\" => \"Malayalam\" => Malayalam,\n\n b\"mlm2\" => \"Malayalam v2\" => MalayalamV2,\n\n b\"mand\" => \"Mandaic, Mandaean\" => Mandaic,\n\n b\"mani\" => \"Manichaean\" => Manichaean,\n\n b\"marc\" => \"Marchen\" => Marchen,\n\n b\"math\" => \"Mathematical Alphanumeric Symbols\" => MathematicalAlphanumericSymbols,\n\n b\"mtei\" => \"Meitei Mayek (Meithei, Meetei)\" => MeiteiMayek,\n\n b\"mend\" => \"Mende Kikakui\" => MendeKikakui,\n\n b\"merc\" => \"Meroitic Cursive\" => MeroiticCursive,\n\n b\"mero\" => \"Meroitic Hieroglyphs\" => MeroiticHieroglyphs,\n\n b\"plrd\" => \"Miao\" => Miao,\n\n b\"modi\" => \"Modi\" => Modi,\n\n b\"mong\" => \"Mongolian\" => Mongolian,\n\n b\"mroo\" => \"Mro\" => Mro,\n\n b\"mult\" => \"Multani\" => Multani,\n\n b\"musc\" => \"Musical Symbols\" => MusicalSymbols,\n", "file_path": "src/layout/script.rs", "rank": 48, "score": 29135.101677355862 }, { "content": " /// Return the record of a language system if present.\n\n pub fn get(&self, language: Language) -> Option<&LanguageRecord> {\n\n let tag = language.tag();\n\n for (i, header) in self.language_headers.iter().enumerate() {\n\n if header.tag == tag {\n\n return Some(&self.language_records[i]);\n\n }\n\n }\n\n None\n\n }\n\n }\n\n );\n\n}\n\n\n\nimplement! {\n\n b\"ABA \" => \"Abaza\" => Abaza => \"abq\",\n\n b\"ABK \" => \"Abkhazian\" => Abkhazian => \"abk\",\n\n b\"ACH \" => \"Acholi\" => Acholi => \"ach\",\n\n b\"ACR \" => \"Achi\" => Achi => \"acr\",\n\n b\"ADY \" => \"Adyghe\" => Adyghe => \"ady\",\n", "file_path": "src/layout/script.rs", "rank": 49, "score": 29135.101677355862 }, { "content": " b\"BEN \" => \"Bengali\" => Bengali => \"ben\",\n\n b\"BGC \" => \"Haryanvi\" => Haryanvi => \"bgc\",\n\n b\"BGQ \" => \"Bagri\" => Bagri => \"bgq\",\n\n b\"BGR \" => \"Bulgarian\" => Bulgarian => \"bul\",\n\n b\"BHI \" => \"Bhili\" => Bhili => \"bhi, bhb\",\n\n b\"BHO \" => \"Bhojpuri\" => Bhojpuri => \"bho\",\n\n b\"BIK \" => \"Bikol\" => Bikol => \"bik, bhk, bcl, bto, cts, bln\",\n\n b\"BIL \" => \"Bilen\" => Bilen => \"byn\",\n\n b\"BIS \" => \"Bislama\" => Bislama => \"bis\",\n\n b\"BJJ \" => \"Kanauji\" => Kanauji => \"bjj\",\n\n b\"BKF \" => \"Blackfoot\" => Blackfoot => \"bla\",\n\n b\"BLI \" => \"Baluchi\" => Baluchi => \"bal\",\n\n b\"BLK \" => \"Pa’o Karen\" => PaoKaren => \"blk\",\n\n b\"BLN \" => \"Balante\" => Balante => \"bjt, ble\",\n\n b\"BLT \" => \"Balti\" => Balti => \"bft\",\n\n b\"BMB \" => \"Bambara (Bamanankan)\" => Bambara => \"bam\",\n\n b\"BML \" => \"Bamileke\" => Bamileke => \"\",\n\n b\"BOS \" => \"Bosnian\" => Bosnian => \"bos\",\n\n b\"BPY \" => \"Bishnupriya Manipuri\" => BishnupriyaManipuri => \"bpy\",\n\n b\"BRE \" => \"Breton\" => Breton => \"bre\",\n", "file_path": "src/layout/script.rs", "rank": 50, "score": 29135.101677355862 }, { "content": " b\"JBO \" => \"Lojban\" => Lojban => \"jbo\",\n\n b\"JCT \" => \"Krymchak\" => Krymchak => \"jct\",\n\n b\"JII \" => \"Yiddish\" => Yiddish => \"yid\",\n\n b\"JUD \" => \"Ladino\" => Ladino => \"lad\",\n\n b\"JUL \" => \"Jula\" => Jula => \"dyu\",\n\n b\"KAB \" => \"Kabardian\" => Kabardian => \"kbd\",\n\n b\"KAB0\" => \"Kabyle\" => Kabyle => \"kab\",\n\n b\"KAC \" => \"Kachchi\" => Kachchi => \"kfr\",\n\n b\"KAL \" => \"Kalenjin\" => Kalenjin => \"kln\",\n\n b\"KAN \" => \"Kannada\" => Kannada => \"kan\",\n\n b\"KAR \" => \"Karachay\" => Karachay => \"krc\",\n\n b\"KAT \" => \"Georgian\" => Georgian => \"kat\",\n\n b\"KAZ \" => \"Kazakh\" => Kazakh => \"kaz\",\n\n b\"KDE \" => \"Makonde\" => Makonde => \"kde\",\n\n b\"KEA \" => \"Kabuverdianu (Crioulo)\" => Kabuverdianu => \"kea\",\n\n b\"KEB \" => \"Kebena\" => Kebena => \"ktb\",\n\n b\"KEK \" => \"Kekchi\" => Kekchi => \"kek\",\n\n b\"KGE \" => \"Khutsuri Georgian\" => KhutsuriGeorgian => \"kat\",\n\n b\"KHA \" => \"Khakass\" => Khakass => \"kjh\",\n\n b\"KHK \" => \"Khanty-Kazim\" => KhantyKazim => \"kca\",\n", "file_path": "src/layout/script.rs", "rank": 51, "score": 29135.101677355862 }, { "content": " b\"bng2\" => \"Bengali v2\" => BengaliV2,\n\n b\"bhks\" => \"Bhaiksuki\" => Bhaiksuki,\n\n b\"bopo\" => \"Bopomofo\" => Bopomofo,\n\n b\"brah\" => \"Brahmi\" => Brahmi,\n\n b\"brai\" => \"Braille\" => Braille,\n\n b\"bugi\" => \"Buginese\" => Buginese,\n\n b\"buhd\" => \"Buhid\" => Buhid,\n\n b\"byzm\" => \"Byzantine Music\" => ByzantineMusic,\n\n b\"cans\" => \"Canadian Syllabics\" => CanadianSyllabics,\n\n b\"cari\" => \"Carian\" => Carian,\n\n b\"aghb\" => \"Caucasian Albanian\" => CaucasianAlbanian,\n\n b\"cakm\" => \"Chakma\" => Chakma,\n\n b\"cham\" => \"Cham\" => Cham,\n\n b\"cher\" => \"Cherokee\" => Cherokee,\n\n b\"hani\" => \"CJK Ideographic\" => CJKIdeographic,\n\n b\"copt\" => \"Coptic\" => Coptic,\n\n b\"cprt\" => \"Cypriot Syllabary\" => CypriotSyllabary,\n\n b\"cyrl\" => \"Cyrillic\" => Cyrillic,\n\n b\"DFLT\" => \"Default\" => Default,\n\n b\"dsrt\" => \"Deseret\" => Deseret,\n", "file_path": "src/layout/script.rs", "rank": 52, "score": 29135.101677355862 }, { "content": " b\"deva\" => \"Devanagari\" => Devanagari,\n\n b\"dev2\" => \"Devanagari v2\" => DevanagariV2,\n\n b\"dupl\" => \"Duployan\" => Duployan,\n\n b\"egyp\" => \"Egyptian Hieroglyphs\" => EgyptianHieroglyphs,\n\n b\"elba\" => \"Elbasan\" => Elbasan,\n\n b\"ethi\" => \"Ethiopic\" => Ethiopic,\n\n b\"geor\" => \"Georgian\" => Georgian,\n\n b\"glag\" => \"Glagolitic\" => Glagolitic,\n\n b\"goth\" => \"Gothic\" => Gothic,\n\n b\"gran\" => \"Grantha\" => Grantha,\n\n b\"grek\" => \"Greek\" => Greek,\n\n b\"gujr\" => \"Gujarati\" => Gujarati,\n\n b\"gjr2\" => \"Gujarati v2\" => GujaratiV2,\n\n b\"guru\" => \"Gurmukhi\" => Gurmukhi,\n\n b\"gur2\" => \"Gurmukhi v2\" => GurmukhiV2,\n\n b\"hang\" => \"Hangul\" => Hangul,\n\n b\"jamo\" => \"Hangul Jamo\" => HangulJamo,\n\n b\"hano\" => \"Hanunoo\" => Hanunoo,\n\n b\"hatr\" => \"Hatran\" => Hatran,\n\n b\"hebr\" => \"Hebrew\" => Hebrew,\n", "file_path": "src/layout/script.rs", "rank": 53, "score": 29135.101677355862 }, { "content": " b\"BRH \" => \"Brahui\" => Brahui => \"brh\",\n\n b\"BRI \" => \"Braj Bhasha\" => BrajBhasha => \"bra\",\n\n b\"BRM \" => \"Burmese\" => Burmese => \"mya\",\n\n b\"BRX \" => \"Bodo\" => Bodo => \"brx\",\n\n b\"BSH \" => \"Bashkir\" => Bashkir => \"bak\",\n\n b\"BSK \" => \"Burushaski\" => Burushaski => \"bsk\",\n\n b\"BTI \" => \"Beti\" => Beti => \"btb\",\n\n b\"BTS \" => \"Batak Simalungun\" => BatakSimalungun => \"bts\",\n\n b\"BUG \" => \"Bugis\" => Bugis => \"bug\",\n\n b\"BYV \" => \"Medumba\" => Medumba => \"byv\",\n\n b\"CAK \" => \"Kaqchikel\" => Kaqchikel => \"cak\",\n\n b\"CAT \" => \"Catalan\" => Catalan => \"cat\",\n\n b\"CBK \" => \"Zamboanga Chavacano\" => ZamboangaChavacano => \"cbk\",\n\n b\"CEB \" => \"Cebuano\" => Cebuano => \"ceb\",\n\n b\"CHE \" => \"Chechen\" => Chechen => \"che\",\n\n b\"CHG \" => \"Chaha Gurage\" => ChahaGurage => \"sgw\",\n\n b\"CHH \" => \"Chattisgarhi\" => Chattisgarhi => \"hne\",\n\n b\"CHI \" => \"Chichewa (Chewa, Nyanja)\" => Chichewa => \"nya\",\n\n b\"CHK \" => \"Chukchi\" => Chukchi => \"ckt\",\n\n b\"CHK0\" => \"Chuukese\" => Chuukese => \"chk\",\n", "file_path": "src/layout/script.rs", "rank": 54, "score": 29135.101677355862 }, { "content": " b\"LUO \" => \"Luo\" => Luo => \"luo\",\n\n b\"LVI \" => \"Latvian\" => Latvian => \"lav\",\n\n b\"MAD \" => \"Madura\" => Madura => \"mad\",\n\n b\"MAG \" => \"Magahi\" => Magahi => \"mag\",\n\n b\"MAH \" => \"Marshallese\" => Marshallese => \"mah\",\n\n b\"MAJ \" => \"Majang\" => Majang => \"mpe\",\n\n b\"MAK \" => \"Makhuwa\" => Makhuwa => \"vmw\",\n\n b\"MAL \" => \"Malayalam\" => Malayalam => \"mal\",\n\n b\"MAM \" => \"Mam\" => Mam => \"mam\",\n\n b\"MAN \" => \"Mansi\" => Mansi => \"mns\",\n\n b\"MAP \" => \"Mapudungun\" => Mapudungun => \"arn\",\n\n b\"MAR \" => \"Marathi\" => Marathi => \"mar\",\n\n b\"MAW \" => \"Marwari\" => Marwari => \"mwr, dhd, rwr, mve, wry, mtr, swv\",\n\n b\"MBN \" => \"Mbundu\" => Mbundu => \"kmb\",\n\n b\"MBO \" => \"Mbo\" => Mbo => \"mbo\",\n\n b\"MCH \" => \"Manchu\" => Manchu => \"mnc\",\n\n b\"MCR \" => \"Moose Cree\" => MooseCree => \"crm\",\n\n b\"MDE \" => \"Mende\" => Mende => \"men\",\n\n b\"MDR \" => \"Mandar\" => Mandar => \"mdr\",\n\n b\"MEN \" => \"Me’en\" => Meen => \"mym\",\n", "file_path": "src/layout/script.rs", "rank": 55, "score": 29135.101677355862 }, { "content": " b\"DAN \" => \"Danish\" => Danish => \"dan\",\n\n b\"DAR \" => \"Dargwa\" => Dargwa => \"dar\",\n\n b\"DAX \" => \"Dayi\" => Dayi => \"dax\",\n\n b\"DCR \" => \"Woods Cree\" => WoodsCree => \"cwd\",\n\n b\"DEU \" => \"German\" => German => \"deu\",\n\n b\"DGO \" => \"Dogri\" => Dogri => \"dgo\",\n\n b\"DGR \" => \"Dogri\" => DogriMacrolanguage => \"doi\",\n\n b\"DHG \" => \"Dhangu\" => Dhangu => \"dhg\",\n\n b\"DHV \" => \"Divehi (Dhivehi, Maldivian)\" => DivehiDeprecated => \"div\",\n\n b\"DIQ \" => \"Dimli\" => Dimli => \"diq\",\n\n b\"DIV \" => \"Divehi (Dhivehi, Maldivian)\" => Divehi => \"div\",\n\n b\"DJR \" => \"Zarma\" => Zarma => \"dje\",\n\n b\"DJR0\" => \"Djambarrpuyngu\" => Djambarrpuyngu => \"djr\",\n\n b\"DNG \" => \"Dangme\" => Dangme => \"ada\",\n\n b\"DNJ \" => \"Dan\" => Dan => \"dnj\",\n\n b\"DNK \" => \"Dinka\" => Dinka => \"din\",\n\n b\"DRI \" => \"Dari\" => Dari => \"prs\",\n\n b\"DUJ \" => \"Dhuwal\" => Dhuwal => \"duj\",\n\n b\"DUN \" => \"Dungan\" => Dungan => \"dng\",\n\n b\"DZN \" => \"Dzongkha\" => Dzongkha => \"dzo\",\n", "file_path": "src/layout/script.rs", "rank": 56, "score": 29135.101677355862 }, { "content": " b\"NTA \" => \"Northern Tai\" => NorthernTai => \"nod\",\n\n b\"NTO \" => \"Esperanto\" => Esperanto => \"epo\",\n\n b\"NYM \" => \"Nyamwezi\" => Nyamwezi => \"nym\",\n\n b\"NYN \" => \"Norwegian Nynorsk (Nynorsk, Norwegian)\" => NorwegianNynorsk => \"nno\",\n\n b\"NZA \" => \"Mbembe Tigon\" => MbembeTigon => \"nza\",\n\n b\"OCI \" => \"Occitan\" => Occitan => \"oci\",\n\n b\"OCR \" => \"Oji-Cree\" => OjiCree => \"ojs\",\n\n b\"OJB \" => \"Ojibway\" => Ojibway => \"oji\",\n\n b\"ORI \" => \"Odia (formerly Oriya)\" => Odia => \"ori\",\n\n b\"ORO \" => \"Oromo\" => Oromo => \"orm\",\n\n b\"OSS \" => \"Ossetian\" => Ossetian => \"oss\",\n\n b\"PAA \" => \"Palestinian Aramaic\" => PalestinianAramaic => \"sam\",\n\n b\"PAG \" => \"Pangasinan\" => Pangasinan => \"pag\",\n\n b\"PAL \" => \"Pali\" => Pali => \"pli\",\n\n b\"PAM \" => \"Pampangan\" => Pampangan => \"pam\",\n\n b\"PAN \" => \"Punjabi\" => Punjabi => \"pan\",\n\n b\"PAP \" => \"Palpa\" => Palpa => \"plp\",\n\n b\"PAP0\" => \"Papiamentu\" => Papiamentu => \"pap\",\n\n b\"PAS \" => \"Pashto\" => Pashto => \"pus\",\n\n b\"PAU \" => \"Palauan\" => Palauan => \"pau\",\n", "file_path": "src/layout/script.rs", "rank": 57, "score": 29135.101677355862 }, { "content": " b\"QUZ \" => \"Quechua\" => Quechua => \"quz\",\n\n b\"QVI \" => \"Quechua (Ecuador)\" => QuechuaEcuador => \"qvi\",\n\n b\"QWH \" => \"Quechua (Peru)\" => QuechuaPeru => \"qwh\",\n\n b\"RAJ \" => \"Rajasthani\" => Rajasthani => \"raj\",\n\n b\"RAR \" => \"Rarotongan\" => Rarotongan => \"rar\",\n\n b\"RBU \" => \"Russian Buriat\" => RussianBuriat => \"bxr\",\n\n b\"RCR \" => \"R-Cree\" => RCree => \"atj\",\n\n b\"REJ \" => \"Rejang\" => Rejang => \"rej\",\n\n b\"RIA \" => \"Riang\" => Riang => \"ria\",\n\n b\"RIF \" => \"Tarifit\" => Tarifit => \"rif\",\n\n b\"RIT \" => \"Ritarungo\" => Ritarungo => \"rit\",\n\n b\"RKW \" => \"Arakwal\" => Arakwal => \"rkw\",\n\n b\"RMS \" => \"Romansh\" => Romansh => \"roh\",\n\n b\"RMY \" => \"Vlax Romani\" => VlaxRomani => \"rmy\",\n\n b\"ROM \" => \"Romanian\" => Romanian => \"ron\",\n\n b\"ROY \" => \"Romany\" => Romany => \"rom\",\n\n b\"RSY \" => \"Rusyn\" => Rusyn => \"rue\",\n\n b\"RTM \" => \"Rotuman\" => Rotuman => \"rtm\",\n\n b\"RUA \" => \"Kinyarwanda\" => Kinyarwanda => \"kin\",\n\n b\"RUN \" => \"Rundi\" => Rundi => \"run\",\n", "file_path": "src/layout/script.rs", "rank": 58, "score": 29135.101677355862 }, { "content": " b\"TRK \" => \"Turkish\" => Turkish => \"tur\",\n\n b\"TSG \" => \"Tsonga\" => Tsonga => \"tso\",\n\n b\"TUA \" => \"Turoyo Aramaic\" => TuroyoAramaic => \"tru\",\n\n b\"TUM \" => \"Tulu\" => Tulu => \"tum\",\n\n b\"TUL \" => \"Tumbuka\" => Tumbuka => \"tcy\",\n\n b\"TUV \" => \"Tuvin\" => Tuvin => \"tyv\",\n\n b\"TVL \" => \"Tuvalu\" => Tuvalu => \"tvl\",\n\n b\"TWI \" => \"Twi\" => Twi => \"aka\",\n\n b\"TYZ \" => \"Tày\" => Tay => \"tyz\",\n\n b\"TZM \" => \"Tamazight\" => Tamazight => \"tzm\",\n\n b\"TZO \" => \"Tzotzil\" => Tzotzil => \"tzo\",\n\n b\"UDM \" => \"Udmurt\" => Udmurt => \"udm\",\n\n b\"UKR \" => \"Ukrainian\" => Ukrainian => \"ukr\",\n\n b\"UMB \" => \"Umbundu\" => Umbundu => \"umb\",\n\n b\"URD \" => \"Urdu\" => Urdu => \"urd\",\n\n b\"USB \" => \"Upper Sorbian\" => UpperSorbian => \"hsb\",\n\n b\"UYG \" => \"Uyghur\" => Uyghur => \"uig\",\n\n b\"UZB \" => \"Uzbek\" => Uzbek => \"uzb\",\n\n b\"VEC \" => \"Venetian\" => Venetian => \"vec\",\n\n b\"VEN \" => \"Venda\" => Venda => \"ven\",\n", "file_path": "src/layout/script.rs", "rank": 59, "score": 29135.101677355862 }, { "content": " b\"KSW \" => \"S’gaw Karen\" => SgawKaren => \"ksw\",\n\n b\"KUA \" => \"Kuanyama\" => Kuanyama => \"kua\",\n\n b\"KUI \" => \"Kui\" => Kui => \"kxu\",\n\n b\"KUL \" => \"Kulvi\" => Kulvi => \"kfx\",\n\n b\"KUM \" => \"Kumyk\" => Kumyk => \"kum\",\n\n b\"KUR \" => \"Kurdish\" => Kurdish => \"kur\",\n\n b\"KUU \" => \"Kurukh\" => Kurukh => \"kru\",\n\n b\"KUY \" => \"Kuy\" => Kuy => \"kdt\",\n\n b\"KYK \" => \"Koryak\" => Koryak => \"kpy\",\n\n b\"KYU \" => \"Western Kayah\" => WesternKayah => \"kyu\",\n\n b\"LAD \" => \"Ladin\" => Ladin => \"lld\",\n\n b\"LAH \" => \"Lahuli\" => Lahuli => \"bfu\",\n\n b\"LAK \" => \"Lak\" => Lak => \"lbe\",\n\n b\"LAM \" => \"Lambani\" => Lambani => \"lmn\",\n\n b\"LAO \" => \"Lao\" => Lao => \"lao\",\n\n b\"LAT \" => \"Latin\" => Latin => \"lat\",\n\n b\"LAZ \" => \"Laz\" => Laz => \"lzz\",\n\n b\"LCR \" => \"L-Cree\" => LCree => \"crm\",\n\n b\"LDK \" => \"Ladakhi\" => Ladakhi => \"lbj\",\n\n b\"LEZ \" => \"Lezgi\" => Lezgi => \"lez\",\n", "file_path": "src/layout/script.rs", "rank": 60, "score": 29135.101677355862 }, { "content": " b\"LIJ \" => \"Ligurian\" => Ligurian => \"lij\",\n\n b\"LIM \" => \"Limburgish\" => Limburgish => \"lim\",\n\n b\"LIN \" => \"Lingala\" => Lingala => \"lin\",\n\n b\"LIS \" => \"Lisu\" => Lisu => \"lis\",\n\n b\"LJP \" => \"Lampung\" => Lampung => \"ljp\",\n\n b\"LKI \" => \"Laki\" => Laki => \"lki\",\n\n b\"LMA \" => \"Low Mari\" => LowMari => \"mhr\",\n\n b\"LMB \" => \"Limbu\" => Limbu => \"lif\",\n\n b\"LMO \" => \"Lombard\" => Lombard => \"lmo\",\n\n b\"LMW \" => \"Lomwe\" => Lomwe => \"ngl\",\n\n b\"LOM \" => \"Loma\" => Loma => \"lom\",\n\n b\"LRC \" => \"Luri\" => Luri => \"lrc, luz, bqi, zum\",\n\n b\"LSB \" => \"Lower Sorbian\" => LowerSorbian => \"dsb\",\n\n b\"LSM \" => \"Lule Sami\" => LuleSami => \"smj\",\n\n b\"LTH \" => \"Lithuanian\" => Lithuanian => \"lit\",\n\n b\"LTZ \" => \"Luxembourgish\" => Luxembourgish => \"ltz\",\n\n b\"LUA \" => \"Luba-Lulua\" => LubaLulua => \"lua\",\n\n b\"LUB \" => \"Luba-Katanga\" => LubaKatanga => \"lub\",\n\n b\"LUG \" => \"Ganda\" => Ganda => \"lug\",\n\n b\"LUH \" => \"Luyia\" => Luyia => \"luy\",\n", "file_path": "src/layout/script.rs", "rank": 61, "score": 29135.101677355862 }, { "content": " b\"RUP \" => \"Aromanian\" => Aromanian => \"rup\",\n\n b\"RUS \" => \"Russian\" => Russian => \"rus\",\n\n b\"SAD \" => \"Sadri\" => Sadri => \"sck\",\n\n b\"SAN \" => \"Sanskrit\" => Sanskrit => \"san\",\n\n b\"SAS \" => \"Sasak\" => Sasak => \"sas\",\n\n b\"SAT \" => \"Santali\" => Santali => \"sat\",\n\n b\"SAY \" => \"Sayisi\" => Sayisi => \"chp\",\n\n b\"SCN \" => \"Sicilian\" => Sicilian => \"scn\",\n\n b\"SCO \" => \"Scots\" => Scots => \"sco\",\n\n b\"SEK \" => \"Sekota\" => Sekota => \"xan\",\n\n b\"SEL \" => \"Selkup\" => Selkup => \"sel\",\n\n b\"SGA \" => \"Old Irish\" => OldIrish => \"sga\",\n\n b\"SGO \" => \"Sango\" => Sango => \"sag\",\n\n b\"SGS \" => \"Samogitian\" => Samogitian => \"sgs\",\n\n b\"SHI \" => \"Tachelhit\" => Tachelhit => \"shi\",\n\n b\"SHN \" => \"Shan\" => Shan => \"shn\",\n\n b\"SIB \" => \"Sibe\" => Sibe => \"sjo\",\n\n b\"SID \" => \"Sidamo\" => Sidamo => \"sid\",\n\n b\"SIG \" => \"Silte Gurage\" => SilteGurage => \"xst\",\n\n b\"SKS \" => \"Skolt Sami\" => SkoltSami => \"sms\",\n", "file_path": "src/layout/script.rs", "rank": 62, "score": 29135.101677355862 }, { "content": " b\"AFK \" => \"Afrikaans\" => Afrikaans => \"afr\",\n\n b\"AFR \" => \"Afar\" => Afar => \"aar\",\n\n b\"AGW \" => \"Agaw\" => Agaw => \"ahg\",\n\n b\"AIO \" => \"Aiton\" => Aiton => \"aio\",\n\n b\"AKA \" => \"Akan\" => Akan => \"aka\",\n\n b\"ALS \" => \"Alsatian\" => Alsatian => \"gsw\",\n\n b\"ALT \" => \"Altai\" => Altai => \"atv, alt\",\n\n b\"AMH \" => \"Amharic\" => Amharic => \"amh\",\n\n b\"ANG \" => \"Anglo-Saxon\" => AngloSaxon => \"ang\",\n\n b\"APPH\" => \"Phonetic transcription, Americanist\" => AmericanistPhoneticNotation => \"\",\n\n b\"ARA \" => \"Arabic\" => Arabic => \"ara\",\n\n b\"ARG \" => \"Aragonese\" => Aragonese => \"arg\",\n\n b\"ARI \" => \"Aari\" => Aari => \"aiw\",\n\n b\"ARK \" => \"Rakhine\" => Rakhine => \"mhv, rmz, rki\",\n\n b\"ASM \" => \"Assamese\" => Assamese => \"asm\",\n\n b\"AST \" => \"Asturian\" => Asturian => \"ast\",\n\n b\"ATH \" => \"Athapaskan\" => Athapaskan => \"apk, apj, apl, apm, apw, nav, bea, sek, bcr, caf, \\\n\n crx, clc, gwi, haa, chp, dgr, scs, xsl, srs, ing, \\\n\n hoi, koy, hup, ktw, mvb, wlk, coq, ctc, gce, tol, \\\n\n tuu, kkz, tgx, tht, aht, tfn, taa, tau, tcb, kuu, \\\n", "file_path": "src/layout/script.rs", "rank": 63, "score": 29135.101677355862 }, { "content": " tce, ttm, txc\",\n\n b\"AVR \" => \"Avar\" => Avar => \"ava\",\n\n b\"AWA \" => \"Awadhi\" => Awadhi => \"awa\",\n\n b\"AYM \" => \"Aymara\" => Aymara => \"aym\",\n\n b\"AZB \" => \"Torki\" => Torki => \"azb\",\n\n b\"AZE \" => \"Azerbaijani\" => Azerbaijani => \"aze\",\n\n b\"BAD \" => \"Badaga\" => Badaga => \"bfq\",\n\n b\"BAD0\" => \"Banda\" => Banda => \"bad\",\n\n b\"BAG \" => \"Baghelkhandi\" => Baghelkhandi => \"bfy\",\n\n b\"BAL \" => \"Balkar\" => Balkar => \"krc\",\n\n b\"BAN \" => \"Balinese\" => Balinese => \"ban\",\n\n b\"BAR \" => \"Bavarian\" => Bavarian => \"bar\",\n\n b\"BAU \" => \"Baulé\" => Baule => \"bci\",\n\n b\"BBC \" => \"Batak Toba\" => BatakToba => \"bbc\",\n\n b\"BBR \" => \"Berber\" => Berber => \"\",\n\n b\"BCH \" => \"Bench\" => Bench => \"bcq\",\n\n b\"BCR \" => \"Bible Cree\" => BibleCree => \"\",\n\n b\"BDY \" => \"Bandjalang\" => Bandjalang => \"bdy\",\n\n b\"BEL \" => \"Belarussian\" => Belarussian => \"bel\",\n\n b\"BEM \" => \"Bemba\" => Bemba => \"bem\",\n", "file_path": "src/layout/script.rs", "rank": 64, "score": 29135.101677355862 }, { "content": " b\"palm\" => \"Palmyrene\" => Palmyrene,\n\n b\"pauc\" => \"Pau Cin Hau\" => PauCinHau,\n\n b\"phag\" => \"Phags-pa\" => Phagspa,\n\n b\"phnx\" => \"Phoenician\" => Phoenician,\n\n b\"phlp\" => \"Psalter Pahlavi\" => PsalterPahlavi,\n\n b\"rjng\" => \"Rejang\" => Rejang,\n\n b\"runr\" => \"Runic\" => Runic,\n\n b\"samr\" => \"Samaritan\" => Samaritan,\n\n b\"saur\" => \"Saurashtra\" => Saurashtra,\n\n b\"shrd\" => \"Sharada\" => Sharada,\n\n b\"shaw\" => \"Shavian\" => Shavian,\n\n b\"sidd\" => \"Siddham\" => Siddham,\n\n b\"sgnw\" => \"Sign Writing\" => SignWriting,\n\n b\"sinh\" => \"Sinhala\" => Sinhala,\n\n b\"sora\" => \"Sora Sompeng\" => SoraSompeng,\n\n b\"xsux\" => \"Sumero-Akkadian Cuneiform\" => SumeroAkkadianCuneiform,\n\n b\"sund\" => \"Sundanese\" => Sundanese,\n\n b\"sylo\" => \"Syloti Nagri\" => SylotiNagri,\n\n b\"syrc\" => \"Syriac\" => Syriac,\n\n b\"tglg\" => \"Tagalog\" => Tagalog,\n", "file_path": "src/layout/script.rs", "rank": 65, "score": 29135.101677355862 }, { "content": " b\"VIT \" => \"Vietnamese\" => Vietnamese => \"vie\",\n\n b\"VOL \" => \"Volapük\" => Volapuk => \"vol\",\n\n b\"VRO \" => \"Võro\" => Voro => \"vro\",\n\n b\"WA \" => \"Wa\" => Wa => \"wbm\",\n\n b\"WAG \" => \"Wagdi\" => Wagdi => \"wbr\",\n\n b\"WAR \" => \"Waray-Waray\" => WarayWaray => \"war\",\n\n b\"WCR \" => \"West-Cree\" => WestCree => \"crk\",\n\n b\"WEL \" => \"Welsh\" => Welsh => \"cym\",\n\n b\"WLN \" => \"Walloon\" => Walloon => \"wln\",\n\n b\"WLF \" => \"Wolof\" => Wolof => \"wol\",\n\n b\"WTM \" => \"Mewati\" => Mewati => \"wtm\",\n\n b\"XBD \" => \"Lü\" => Lu => \"khb\",\n\n b\"XHS \" => \"Xhosa\" => Xhosa => \"xho\",\n\n b\"XJB \" => \"Minjangbal\" => Minjangbal => \"xjb\",\n\n b\"XOG \" => \"Soga\" => Soga => \"xog\",\n\n b\"XPE \" => \"Kpelle (Liberia)\" => KpelleLiberia => \"xpe\",\n\n b\"YAK \" => \"Sakha\" => Sakha => \"sah\",\n\n b\"YAO \" => \"Yao\" => Yao => \"yao\",\n\n b\"YAP \" => \"Yapese\" => Yapese => \"yap\",\n\n b\"YBA \" => \"Yoruba\" => Yoruba => \"yor\",\n", "file_path": "src/layout/script.rs", "rank": 66, "score": 29135.101677355862 }, { "content": " b\"HAU \" => \"Hausa\" => Hausa => \"hau\",\n\n b\"HAW \" => \"Hawaiian\" => Hawaiian => \"haw\",\n\n b\"HAY \" => \"Haya\" => Haya => \"hay\",\n\n b\"HAZ \" => \"Hazaragi\" => Hazaragi => \"haz\",\n\n b\"HBN \" => \"Hammer-Banna\" => HammerBanna => \"amf\",\n\n b\"HER \" => \"Herero\" => Herero => \"her\",\n\n b\"HIL \" => \"Hiligaynon\" => Hiligaynon => \"hil\",\n\n b\"HIN \" => \"Hindi\" => Hindi => \"hin\",\n\n b\"HMA \" => \"High Mari\" => HighMari => \"mrj\",\n\n b\"HMN \" => \"Hmong\" => Hmong => \"hmn\",\n\n b\"HMO \" => \"Hiri Motu\" => HiriMotu => \"hmo\",\n\n b\"HND \" => \"Hindko\" => Hindko => \"hno, hnd\",\n\n b\"HO \" => \"Ho\" => Ho => \"hoc\",\n\n b\"HRI \" => \"Harari\" => Harari => \"har\",\n\n b\"HRV \" => \"Croatian\" => Croatian => \"hrv\",\n\n b\"HUN \" => \"Hungarian\" => Hungarian => \"hun\",\n\n b\"HYE \" => \"Armenian\" => Armenian => \"hye\",\n\n b\"HYE0\" => \"Armenian East\" => ArmenianEast => \"hye\",\n\n b\"IBA \" => \"Iban\" => Iban => \"iba\",\n\n b\"IBB \" => \"Ibibio\" => Ibibio => \"ibb\",\n", "file_path": "src/layout/script.rs", "rank": 67, "score": 29135.101677355862 }, { "content": " b\"kana\" => \"Hiragana\" => Hiragana,\n\n b\"armi\" => \"Imperial Aramaic\" => ImperialAramaic,\n\n b\"phli\" => \"Inscriptional Pahlavi\" => InscriptionalPahlavi,\n\n b\"prti\" => \"Inscriptional Parthian\" => InscriptionalParthian,\n\n b\"java\" => \"Javanese\" => Javanese,\n\n b\"kthi\" => \"Kaithi\" => Kaithi,\n\n b\"knda\" => \"Kannada\" => Kannada,\n\n b\"knd2\" => \"Kannada v2\" => KannadaV2,\n\n b\"kana\" => \"Katakana\" => Katakana,\n\n b\"kali\" => \"Kayah Li\" => KayahLi,\n\n b\"khar\" => \"Kharosthi\" => Kharosthi,\n\n b\"khmr\" => \"Khmer\" => Khmer,\n\n b\"khoj\" => \"Khojki\" => Khojki,\n\n b\"sind\" => \"Khudawadi\" => Khudawadi,\n\n b\"lao \" => \"Lao\" => Lao,\n\n b\"latn\" => \"Latin\" => Latin,\n\n b\"lepc\" => \"Lepcha\" => Lepcha,\n\n b\"limb\" => \"Limbu\" => Limbu,\n\n b\"lina\" => \"Linear A\" => LinearA,\n\n b\"linb\" => \"Linear B\" => LinearB,\n", "file_path": "src/layout/script.rs", "rank": 68, "score": 29135.101677355862 }, { "content": " b\"EBI \" => \"Ebira\" => Ebira => \"igb\",\n\n b\"ECR \" => \"Eastern Cree\" => EasternCree => \"crj, crl\",\n\n b\"EDO \" => \"Edo\" => Edo => \"bin\",\n\n b\"EFI \" => \"Efik\" => Efik => \"efi\",\n\n b\"ELL \" => \"Greek\" => Greek => \"ell\",\n\n b\"EMK \" => \"Eastern Maninkakan\" => EasternManinkakan => \"emk\",\n\n b\"ENG \" => \"English\" => English => \"eng\",\n\n b\"ERZ \" => \"Erzya\" => Erzya => \"myv\",\n\n b\"ESP \" => \"Spanish\" => Spanish => \"spa\",\n\n b\"ESU \" => \"Central Yupik\" => CentralYupik => \"esu\",\n\n b\"ETI \" => \"Estonian\" => Estonian => \"est\",\n\n b\"EUQ \" => \"Basque\" => Basque => \"eus\",\n\n b\"EVK \" => \"Evenki\" => Evenki => \"evn\",\n\n b\"EVN \" => \"Even\" => Even => \"eve\",\n\n b\"EWE \" => \"Ewe\" => Ewe => \"ewe\",\n\n b\"FAN \" => \"French Antillean\" => FrenchAntillean => \"acf\",\n\n b\"FAN0\" => \"Fang\" => Fang => \"fan\",\n\n b\"FAR \" => \"Persian\" => Persian => \"fas\",\n\n b\"FAT \" => \"Fanti\" => Fanti => \"fat\",\n\n b\"FIN \" => \"Finnish\" => Finnish => \"fin\",\n", "file_path": "src/layout/script.rs", "rank": 69, "score": 29135.101677355862 }, { "content": "//! The [common layout tables][1].\n\n//!\n\n//! [1]: https://www.microsoft.com/typography/otspec/chapter2.htm\n\n\n\nmod class;\n\nmod correction;\n\nmod coverage;\n\nmod directory;\n\n\n\npub mod feature;\n\npub mod lookup;\n\npub mod script;\n\n\n\npub use class::{Class, Class1, Class2, ClassRange};\n\npub use correction::{Correction, Device, Variation};\n\npub use coverage::{Coverage, Coverage1, Coverage2, CoverageRange};\n\npub use directory::Directory;\n\npub use feature::Features;\n\npub use lookup::Lookups;\n\npub use script::Scripts;\n", "file_path": "src/layout/mod.rs", "rank": 70, "score": 28677.647172239227 }, { "content": "//! The [common font-variation tables][1].\n\n//!\n\n//! [1]: https://www.microsoft.com/typography/otspec/otvarcommonformats.htm\n\n\n\npub mod item;\n", "file_path": "src/variation/mod.rs", "rank": 71, "score": 28671.010972636483 }, { "content": "//! The [compact file format][1] of version 2.0.\n\n//!\n\n//! [1]: https://www.microsoft.com/typography/otspec/cff2.htm\n", "file_path": "src/compact2/mod.rs", "rank": 72, "score": 28661.342652804844 }, { "content": "//! The [glyph-definition table][1].\n\n//!\n\n//! [1]: https://www.microsoft.com/typography/otspec/GDEF.htm\n\n\n\nuse truetype::{Result, Tape, Value};\n\n\n\nuse crate::layout::Class;\n\nuse crate::variation::item::Variations;\n\n\n\nmod element;\n\n\n\npub use element::*;\n\n\n\nmacro_rules! field(\n\n ($table:expr => $field:ident, $enumeration:ident::{$($variant:ident),*}) => (\n\n match $table {\n\n $($enumeration::$variant(ref table) => table.$field,)*\n\n }\n\n );\n\n ($table:expr => $field:ident($default:expr), $enumeration:ident::{$($variant:ident),*}) => (\n", "file_path": "src/glyph_definition/mod.rs", "rank": 73, "score": 27229.507706275956 }, { "content": "//! The [glyph-positioning table][1].\n\n//!\n\n//! [1]: https://www.microsoft.com/typography/otspec/gpos.htm\n\n\n\nuse truetype::{Result, Tape, Value, Walue};\n\n\n\nuse crate::layout::{Class, Coverage, Directory};\n\n\n\nmod element;\n\n\n\npub use element::*;\n\n\n\n/// A glyph-positioning table.\n\npub type GlyphPositioning = Directory<Table>;\n\n\n\n/// An inner table of a glyph-positioning table.\n\n#[derive(Clone, Debug)]\n\npub enum Table {\n\n SingleAdjustment(SingleAdjustment),\n\n PairAdjustment(PairAdjustment),\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 74, "score": 27228.679965004812 }, { "content": "//! The [glyph-substitution table][1].\n\n//!\n\n//! [1]: https://www.microsoft.com/typography/otspec/GSUB.htm\n\n\n\nuse truetype::{GlyphID, Result, Tape, Value, Walue};\n\n\n\nuse crate::layout::{Class, Coverage, Directory};\n\n\n\nmod element;\n\n\n\npub use element::*;\n\n\n\n/// A glyph-substitution table.\n\npub type GlyphSubstitution = Directory<Table>;\n\n\n\n/// An inner table of a glyph-substitution table.\n\n#[derive(Clone, Debug)]\n\npub enum Table {\n\n SingleSubstitution(SingleSubstitution),\n\n MultipleSubstitution(MultipleSubstitution),\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 75, "score": 27228.520498385693 }, { "content": "\n\n fn read<T: Tape>(tape: &mut T, kind: u16) -> Result<Self> {\n\n Ok(match kind {\n\n 1 => Table::SingleAdjustment(tape.take()?),\n\n 2 => Table::PairAdjustment(tape.take()?),\n\n 3 => Table::CursiveAttachment(tape.take()?),\n\n 4 => Table::MarkToBaseAttachment(tape.take()?),\n\n 5 => Table::MarkToLigatureAttachment(tape.take()?),\n\n 6 => Table::MarkToMarkAttachment(tape.take()?),\n\n 7 => Table::ContextPositioning(tape.take()?),\n\n 8 => Table::ChainContextPositioning(tape.take()?),\n\n 9 => Table::ExtensionPositioning(tape.take()?),\n\n _ => raise!(\"found an unknown glyph-positioning type\"),\n\n })\n\n }\n\n}\n\n\n\nimpl Value for SingleAdjustment {\n\n fn read<T: Tape>(tape: &mut T) -> Result<Self> {\n\n Ok(match tape.peek::<u16>()? {\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 76, "score": 27218.122815831604 }, { "content": " 3 => Table::AlternateSubstitution(tape.take()?),\n\n 4 => Table::LigatureSubstitution(tape.take()?),\n\n 5 => Table::ContextSubstitution(tape.take()?),\n\n 6 => Table::ChainContextSubstitution(tape.take()?),\n\n 7 => Table::ExtensionSubstitution(tape.take()?),\n\n 8 => Table::ReverseChainContextSubstitution(tape.take()?),\n\n _ => raise!(\"found an unknown glyph-substitution type\"),\n\n })\n\n }\n\n}\n\n\n\nimpl Value for SingleSubstitution {\n\n fn read<T: Tape>(tape: &mut T) -> Result<Self> {\n\n Ok(match tape.peek::<u16>()? {\n\n 1 => SingleSubstitution::Format1(tape.take()?),\n\n 2 => SingleSubstitution::Format2(tape.take()?),\n\n _ => raise!(\"found an unknown format of the single-substitution table\"),\n\n })\n\n }\n\n}\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 77, "score": 27218.039991474834 }, { "content": " match $table {\n\n $($enumeration::$variant(ref table) => table.$field,)*\n\n _ => $default,\n\n }\n\n );\n\n);\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A glyph-definition table.\"]\n\n pub GlyphDefinition {\n\n header (Header),\n\n\n\n glyph_class (Option<Class>) |this, tape, position| {\n\n jump_take_maybe!(tape, position, field!(this.header => glyph_class_offset,\n\n Header::{Version1, Version12, Version13}))\n\n },\n\n\n\n attachments (Option<Attachments>) |this, tape, position| {\n\n jump_take_maybe!(tape, position, field!(this.header => attachments_offset,\n", "file_path": "src/glyph_definition/mod.rs", "rank": 78, "score": 27217.972641382206 }, { "content": " Header::{Version13}))\n\n },\n\n }\n\n}\n\n\n\n/// The header of a glyph-definition table.\n\n#[derive(Clone, Debug)]\n\npub enum Header {\n\n /// Version 1.0.\n\n Version1(Header1),\n\n /// Version 1.2.\n\n Version12(Header12),\n\n /// Version 1.3.\n\n Version13(Header13),\n\n}\n\n\n\ntable! {\n\n #[doc = \"The header of a glyph-definition table of version 1.0.\"]\n\n #[derive(Copy)]\n\n pub Header1 {\n", "file_path": "src/glyph_definition/mod.rs", "rank": 79, "score": 27217.891107309737 }, { "content": " forward_coverages (Vec<Coverage>) |this, tape, position| {\n\n jump_take!(tape, position, this.forward_glyph_count, this.forward_coverage_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n #[doc = \"A table for other types of substitution.\"]\n\n pub ExtensionSubstitution { // ExtensionSubstFormat1\n\n format (u16) = { 1 }, // SubstFormat\n\n kind (u16), // ExtensionLookupType\n\n offset (u32), // ExtensionOffset\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting glyphs in reverse order in a chaining context.\"]\n\n pub ReverseChainContextSubstitution { // ReverseChainSingleSubstFormat1\n\n format (u16), // SubstFormat\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 80, "score": 27217.703828595288 }, { "content": " jump_take!(tape, position, this.input_glyph_count, this.input_coverage_offsets)\n\n },\n\n\n\n forward_coverages (Vec<Coverage>) |this, tape, position| {\n\n jump_take!(tape, position, this.forward_glyph_count, this.forward_coverage_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n #[doc = \"A table for other types of positioning.\"]\n\n pub ExtensionPositioning { // ExtensionPosFormat1\n\n format (u16) = { 1 }, // PosFormat\n\n kind (u16), // ExtensionLookupType\n\n offset (u32), // ExtensionOffset\n\n }\n\n}\n\n\n\nimpl Walue<'static> for Table {\n\n type Parameter = u16;\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 81, "score": 27217.52670668586 }, { "content": " AlternateSubstitution(AlternateSubstitution),\n\n LigatureSubstitution(LigatureSubstitution),\n\n ContextSubstitution(ContextSubstitution),\n\n ChainContextSubstitution(ChainContextSubstitution),\n\n ExtensionSubstitution(ExtensionSubstitution),\n\n ReverseChainContextSubstitution(ReverseChainContextSubstitution),\n\n}\n\n\n\n/// A table for substituting one glyph with one glyph.\n\n#[derive(Clone, Debug)]\n\npub enum SingleSubstitution {\n\n /// Format 1.\n\n Format1(SingleSubstitution1),\n\n /// Format 2.\n\n Format2(SingleSubstitution2),\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting one glyph with one glyph in format 1.\"]\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 82, "score": 27217.46004114673 }, { "content": " #[doc = \"A table for adjusting single glyphs in format 1.\"]\n\n pub SingleAdjustment1 { // SinglePosFormat1\n\n format (u16 ), // PosFormat\n\n coverage_offset (u16 ), // Coverage\n\n value_flags (SingleFlags), // ValueFormat\n\n\n\n value (Single) |this, tape, position| { // Value\n\n tape.take_given((position, this.value_flags))\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for adjusting single glyphs in format 2.\"]\n\n pub SingleAdjustment2 { // SinglePosFormat2\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 83, "score": 27217.46004114673 }, { "content": " jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n\n backward_coverages (Vec<Coverage>) |this, tape, position| {\n\n jump_take!(tape, position, this.backward_glyph_count, this.backward_coverage_offsets)\n\n },\n\n\n\n forward_coverages (Vec<Coverage>) |this, tape, position| {\n\n jump_take!(tape, position, this.forward_glyph_count, this.forward_coverage_offsets)\n\n },\n\n }\n\n}\n\n\n\nimpl Walue<'static> for Table {\n\n type Parameter = u16;\n\n\n\n fn read<T: Tape>(tape: &mut T, kind: u16) -> Result<Self> {\n\n Ok(match kind {\n\n 1 => Table::SingleSubstitution(tape.take()?),\n\n 2 => Table::MultipleSubstitution(tape.take()?),\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 84, "score": 27217.359013570745 }, { "content": "\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n\n sets (Vec<Rules>) |this, tape, position| {\n\n jump_take!(tape, position, this.set_count, this.set_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for positioning glyphs in a context in format 2.\"]\n\n pub ContextPositioning2 { // ContextPosFormat2\n\n format (u16), // PosFormat\n\n coverage_offset (u16), // Coverage\n\n class_offset (u16), // ClassDef\n\n set_count (u16), // PosClassSetCnt\n\n\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 85, "score": 27217.095558406185 }, { "content": " tape.take_given(this.glyph_count as usize)\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting one glyph with more than one glyph.\"]\n\n pub MultipleSubstitution { // MultipleSubstFormat1\n\n format (u16) = { 1 }, // SubstFormat\n\n coverage_offset (u16), // Coverage\n\n sequence_count (u16), // SequenceCount\n\n\n\n sequence_offsets (Vec<u16>) |this, tape, _| { // Sequence\n\n tape.take_given(this.sequence_count as usize)\n\n },\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 86, "score": 27217.095558406185 }, { "content": " },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n\n sets (Vec<Pair1s>) |this, tape, position| {\n\n jump_take_given!(tape, position, this.set_count, this.set_offsets,\n\n (position, this.value1_flags, this.value2_flags))\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for adjusting pairs of glyphs in format 2.\"]\n\n pub PairAdjustment2 { // PairPosFormat2\n\n format (u16 ), // PosFormat\n\n coverage_offset (u16 ), // Coverage\n\n value1_flags (SingleFlags), // ValueFormat1\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 87, "score": 27217.080388540882 }, { "content": " CursiveAttachment(CursiveAttachment),\n\n MarkToBaseAttachment(MarkToBaseAttachment),\n\n MarkToLigatureAttachment(MarkToLigatureAttachment),\n\n MarkToMarkAttachment(MarkToMarkAttachment),\n\n ContextPositioning(ContextPositioning),\n\n ChainContextPositioning(ChainContextPositioning),\n\n ExtensionPositioning(ExtensionPositioning),\n\n}\n\n\n\n/// A table for adjusting single glyphs.\n\n#[derive(Clone, Debug)]\n\npub enum SingleAdjustment {\n\n /// Format 1.\n\n Format1(SingleAdjustment1),\n\n /// Format 2.\n\n Format2(SingleAdjustment2),\n\n}\n\n\n\ntable! {\n\n @position\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 88, "score": 27217.080388540882 }, { "content": "pub enum ContextPositioning {\n\n /// Format 1.\n\n Format1(ContextPositioning1),\n\n /// Format 2.\n\n Format2(ContextPositioning2),\n\n /// Format 3.\n\n Format3(ContextPositioning3),\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for positioning glyphs in a context in format 1.\"]\n\n pub ContextPositioning1 { // ContextPosFormat1\n\n format (u16), // PosFormat\n\n coverage_offset (u16), // Coverage\n\n set_count (u16), // PosRuleSetCount\n\n\n\n set_offsets (Vec<u16>) |this, tape, _| { // PosRuleSet\n\n tape.take_given(this.set_count as usize)\n\n },\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 89, "score": 27217.065385614424 }, { "content": " tape.take_given(this.set_count as usize)\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n\n sets (Vec<Alternates>) |this, tape, position| {\n\n jump_take!(tape, position, this.set_count, this.set_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting multiple glyphs with one glyph.\"]\n\n pub LigatureSubstitution { // LigatureSubstFormat1\n\n format (u16) = { 1 }, // SubstFormat\n\n coverage_offset (u16), // Coverage\n\n set_count (u16), // LigSetCount\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 90, "score": 27217.065385614424 }, { "content": " jump_take!(tape, position, this.class1_offset)\n\n },\n\n\n\n class2 (Class) |this, tape, position| {\n\n jump_take!(tape, position, this.class2_offset)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for attaching cursive glyphs.\"]\n\n pub CursiveAttachment { // CursivePosFormat1\n\n format (u16) = { 1 }, // PosFormat\n\n coverage_offset (u16), // Coverage\n\n passage_count (u16), // EntryExitCount\n\n\n\n passages (Vec<Passage>) |this, tape, position| { // EntryExitRecord\n\n let mut values = Vec::with_capacity(this.passage_count as usize);\n\n for _ in 0..(this.passage_count as usize) {\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 91, "score": 27217.065385614424 }, { "content": " values.push(tape.take_given(position)?);\n\n }\n\n Ok(values)\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for attaching combining marks to base glyphs.\"]\n\n pub MarkToBaseAttachment { // MarkBasePosFormat1\n\n format (u16) = { 1 }, // PosFormat\n\n mark_coverage_offset (u16), // MarkCoverage\n\n base_coverage_offset (u16), // BaseCoverage\n\n class_count (u16), // ClassCount\n\n marks_offset (u16), // MarkArray\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 92, "score": 27217.035869675405 }, { "content": " },\n\n\n\n sets (Vec<Rules>) |this, tape, position| {\n\n jump_take!(tape, position, this.set_count, this.set_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting glyphs in a context in format 2.\"]\n\n pub ContextSubstitution2 { // ContextSubstFormat2\n\n format (u16), // SubstFormat\n\n coverage_offset (u16), // Coverage\n\n class_offset (u16), // ClassDef\n\n set_count (u16), // SubClassSetCnt\n\n\n\n set_offsets (Vec<u16>) |this, tape, _| { // SubClassSet\n\n tape.take_given(this.set_count as usize)\n\n },\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 93, "score": 27217.035869675405 }, { "content": "\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n\n sequences (Vec<Sequence>) |this, tape, position| {\n\n jump_take!(tape, position, this.sequence_count, this.sequence_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting one glyph with one of many glyphs.\"]\n\n pub AlternateSubstitution { // AlternateSubstFormat1\n\n format (u16) = { 1 }, // SubstFormat\n\n coverage_offset (u16), // Coverage\n\n set_count (u16), // AlternateSetCount\n\n\n\n set_offsets (Vec<u16>) |this, tape, _| { // AlternateSet\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 94, "score": 27217.035869675405 }, { "content": "\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n\n sets (Vec<Option<ClassRules>>) |this, tape, position| {\n\n jump_take_maybe!(tape, position, this.set_count, this.set_offsets)\n\n },\n\n }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting glyphs in a context in format 3.\"]\n\n pub ContextSubstitution3 { // ContextSubstFormat3\n\n format (u16), // SubstFormat\n\n glyph_count (u16), // GlyphCount\n\n operation_count (u16), // SubstCount\n\n\n\n coverage_offsets (Vec<u16>) |this, tape, _| { // Coverage\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 95, "score": 27217.035869675405 }, { "content": " /// Format 2.\n\n Format2(ContextSubstitution2),\n\n /// Format 3.\n\n Format3(ContextSubstitution3),\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting glyphs in a context in format 1.\"]\n\n pub ContextSubstitution1 { // ContextSubstFormat1\n\n format (u16), // SubstFormat\n\n coverage_offset (u16), // Coverage\n\n set_count (u16), // SubRuleSetCount\n\n\n\n set_offsets (Vec<u16>) |this, tape, _| { // SubRuleSet\n\n tape.take_given(this.set_count as usize)\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 96, "score": 27217.02135135907 }, { "content": " Format1(ChainContextPositioning1),\n\n /// Format 2.\n\n Format2(ChainContextPositioning2),\n\n /// Format 3.\n\n Format3(ChainContextPositioning3),\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for positioning glyphs in a chaining context in format 1.\"]\n\n pub ChainContextPositioning1 {\n\n format (u16), // PosFormat\n\n coverage_offset (u16), // Coverage\n\n set_count (u16), // ChainPosRuleSetCount\n\n\n\n set_offsets (Vec<u16>) |this, tape, _| { // ChainPosRuleSet\n\n tape.take_given(this.set_count as usize)\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n", "file_path": "src/glyph_positioning/mod.rs", "rank": 97, "score": 27217.00698937085 }, { "content": " /// Format 3.\n\n Format3(ChainContextSubstitution3),\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting glyphs in a chaining context in format 1.\"]\n\n pub ChainContextSubstitution1 { // ChainContextSubstFormat1\n\n format (u16), // SubstFormat\n\n coverage_offset (u16), // Coverage\n\n set_count (u16), // ChainSubRuleSetCount\n\n\n\n set_offsets (Vec<u16>) |this, tape, _| { // ChainSubRuleSet\n\n tape.take_given(this.set_count as usize)\n\n },\n\n\n\n coverage (Coverage) |this, tape, position| {\n\n jump_take!(tape, position, this.coverage_offset)\n\n },\n\n\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 98, "score": 27216.992781199337 }, { "content": " }\n\n}\n\n\n\ntable! {\n\n @position\n\n #[doc = \"A table for substituting glyphs in a chaining context in format 3.\"]\n\n pub ChainContextSubstitution3 { // ChainContextSubstFormat3\n\n format (u16), // SubstFormat\n\n backward_glyph_count (u16), // BacktrackGlyphCount\n\n\n\n backward_coverage_offsets (Vec<u16>) |this, tape, _| { // Coverage\n\n tape.take_given(this.backward_glyph_count as usize)\n\n },\n\n\n\n input_glyph_count (u16), // InputGlyphCount\n\n\n\n input_coverage_offsets (Vec<u16>) |this, tape, _| { // Coverage\n\n tape.take_given(this.input_glyph_count as usize)\n\n },\n\n\n", "file_path": "src/glyph_substitution/mod.rs", "rank": 99, "score": 27216.992781199337 } ]
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 terminal and log errors to stderr.\",\n\n )\n\n .optflag(\"h\", \"help\", \"\")\n\n .parse(&args[1..])\n\n .unwrap_or_else(|_| usage());\n\n if matches.opt_present(\"h\") {\n\n usage();\n\n }\n\n\n\n let daemonise = !matches.opt_present(\"d\");\n\n\n\n let conf_path = match matches.opt_str(\"c\") {\n\n Some(p) => PathBuf::from(&p),\n", "file_path": "src/main.rs", "rank": 0, "score": 78785.46538524132 }, { "content": "/// Authenticate this request and if successful return `true` (where \"success\" also includes \"the\n\n/// user didn't specify a secret for this repository\").\n\nfn authenticate(secret: &SecStr, sig: String, pl: Bytes) -> bool {\n\n // We've already checked the key length when creating the config, so the unwrap() is safe.\n\n let mut mac = Hmac::<Sha1>::new_varkey(secret.unsecure()).unwrap();\n\n mac.input(&*pl);\n\n match hex::decode(sig) {\n\n Ok(d) => mac.verify(&d).is_ok(),\n\n Err(_) => false,\n\n }\n\n}\n\n\n\n/// Parse `pl` into JSON, and return `(<JSON as a String>, <repo owner>, <repo name>)`.\n\nasync fn parse(req: Request<Body>) -> Result<(Bytes, String, String, String), ()> {\n\n let pl = hyper::body::to_bytes(req.into_body())\n\n .await\n\n .map_err(|_| ())?;\n\n\n\n // The body sent by GitHub starts \"payload=\" before then containing JSON encoded using the URL\n\n // percent format.\n\n\n\n // First check that the string really does begin \"payload=\".\n", "file_path": "src/httpserver.rs", "rank": 1, "score": 78298.25010970459 }, { "content": "fn progname() -> String {\n\n match current_exe() {\n\n Ok(p) => p\n\n .file_name()\n\n .map(|x| x.to_str().unwrap_or(\"snare\"))\n\n .unwrap_or(\"snare\")\n\n .to_owned(),\n\n Err(_) => \"snare\".to_owned(),\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 2, "score": 77738.2804416621 }, { "content": "/// Is `n` a valid GitHub ownername? If this function returns `true` then it is guaranteed that `n`\n\n/// is safe to use in file system paths.\n\nfn valid_github_ownername(n: &str) -> bool {\n\n // You can see the rules by going to https://github.com/join, typing in something incorrect and\n\n // then being told the rules.\n\n\n\n // Owner names must be at least one, and at most 39, characters long.\n\n if n.is_empty() || n.len() > 39 {\n\n return false;\n\n }\n\n\n\n // Owner names cannot start or end with a hyphen.\n\n if n.starts_with('-') || n.ends_with('-') {\n\n return false;\n\n }\n\n\n\n // Owner names cannot contain double hypens.\n\n if n.contains(\"--\") {\n\n return false;\n\n }\n\n\n\n // All characters must be [a-zA-Z0-9-].\n\n n.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')\n\n}\n\n\n", "file_path": "src/httpserver.rs", "rank": 3, "score": 65009.067524695805 }, { "content": "/// Is `n` a valid GitHub repository name? If this function returns `true` then it is guaranteed that `n`\n\n/// is safe to use in filesystem paths.\n\nfn valid_github_reponame(n: &str) -> bool {\n\n // You can see the rules by going to https://github.com/new, typing in something incorrect and\n\n // then being told the rules.\n\n\n\n // A repository name must be at least 1, at most 100, characters long.\n\n if n.is_empty() || n.len() > 100 {\n\n return false;\n\n }\n\n\n\n // GitHub disallows repository names \".\" and \"..\"\n\n if n == \".\" || n == \"..\" {\n\n return false;\n\n }\n\n\n\n // All characters must be [a-zA-Z0-9-.]\n\n n.chars()\n\n .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/httpserver.rs", "rank": 4, "score": 65009.067524695805 }, { "content": "/// Is `t` a valid GitHub event type? If this function returns `true` then it is guaranteed that `t`\n\n/// is safe to use in file system paths.\n\nfn valid_github_event(t: &str) -> bool {\n\n // All current event types are [a-z_] https://developer.github.com/webhooks/\n\n !t.is_empty() && t.chars().all(|c| c.is_ascii_lowercase() || c == '_')\n\n}\n\n\n", "file_path": "src/httpserver.rs", "rank": 5, "score": 65008.959602568706 }, { "content": "/// Take a quoted string from the config file and unescape it (i.e. strip the start and end quote\n\n/// (\") characters and process any escape characters in the string.)\n\nfn unescape_str(us: &str) -> String {\n\n // The regex in config.l should have guaranteed that strings start and finish with a\n\n // quote character.\n\n debug_assert!(us.starts_with('\"') && us.ends_with('\"'));\n\n let mut s = String::new();\n\n // We iterate over all characters except the opening and closing quote characters.\n\n let mut i = '\"'.len_utf8();\n\n while i < us.len() - '\"'.len_utf8() {\n\n let c = us[i..].chars().next().unwrap();\n\n if c == '\\\\' {\n\n // The regex in config.l should have guaranteed that there are no unescaped quote (\")\n\n // characters, but we check here just to be sure.\n\n debug_assert!(i < us.len() - '\"'.len_utf8());\n\n i += 1;\n\n let c2 = us[i..].chars().next().unwrap();\n\n debug_assert!(c2 == '\"' || c2 == '\\\\');\n\n s.push(c2);\n\n i += c2.len_utf8();\n\n } else {\n\n s.push(c);\n", "file_path": "src/config.rs", "rank": 6, "score": 65003.82911064309 }, { "content": "/// Exit with a fatal error.\n\nfn fatal(daemonised: bool, msg: &str) -> ! {\n\n if daemonised {\n\n // We know that `%s` and `<can't represent as CString>` are both valid C strings, and\n\n // that neither unwrap() can fail.\n\n let fmt = CString::new(\"%s\").unwrap();\n\n let msg = CString::new(msg)\n\n .unwrap_or_else(|_| CString::new(\"<can't represent as CString>\").unwrap());\n\n unsafe {\n\n syslog(LOG_CRIT, fmt.as_ptr(), msg.as_ptr());\n\n }\n\n } else {\n\n eprintln!(\"{}\", msg);\n\n }\n\n process::exit(1);\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 7, "score": 62787.471562221035 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n rerun_except(&[\"snare.1\", \"snare.conf.5\", \"snare.conf.example\"])?;\n\n let lex_rule_ids_map = CTParserBuilder::<u8>::new_with_storaget()\n\n .yacckind(YaccKind::Grmtools)\n\n .process_file_in_src(\"config.y\")?;\n\n LexerBuilder::new()\n\n .rule_ids_map(lex_rule_ids_map)\n\n .process_file_in_src(\"config.l\")?;\n\n\n\n Ok(())\n\n}\n", "file_path": "build.rs", "rank": 8, "score": 58183.26371055911 }, { "content": "/// Extract the string 'def' from \"X-Hub-Signature: abc=def\"\n\nfn get_hub_sig(req: &Request<Body>) -> Option<String> {\n\n req.headers()\n\n .get(\"X-Hub-Signature\")\n\n .and_then(|s| match s.to_str() {\n\n Ok(s) => Some(s),\n\n Err(_) => None,\n\n })\n\n .and_then(|s| s.split('=').nth(1))\n\n .map(|s| s.to_owned())\n\n}\n\n\n", "file_path": "src/httpserver.rs", "rank": 9, "score": 55875.86726867077 }, { "content": "fn replace(s: &str, modifiers: HashMap<char, &str>) -> String {\n\n // Except in the presence of '%%'s, the output string will be at least as long as the input\n\n // string, so starting at that capacity is a reasonable heuristic.\n\n let mut n = String::with_capacity(s.len());\n\n let mut i = 0;\n\n while i < s.len() {\n\n if s[i..].starts_with('%') {\n\n let mdf = s[i + 1..].chars().next().unwrap(); // modifier\n\n n.push_str(modifiers.get(&mdf).unwrap());\n\n i += 1 + mdf.len_utf8();\n\n } else {\n\n let c = s[i..].chars().next().unwrap();\n\n n.push(c);\n\n i += c.len_utf8();\n\n }\n\n }\n\n n\n\n}\n\n\n", "file_path": "src/jobrunner.rs", "rank": 10, "score": 52878.787248628156 }, { "content": "struct Job {\n\n /// Set to `false` if this is a normal command and `true` if it is an error command.\n\n is_errorcmd: bool,\n\n /// The repo identifier. This is used to determine if a given repository already has jobs\n\n /// running or not. Typically of the form \"provider/owner/repo\".\n\n repo_id: String,\n\n /// The event type.\n\n event_type: String,\n\n /// The repository owner's name.\n\n owner: String,\n\n /// The repository name.\n\n repo: String,\n\n /// What time must this Job have completed by? If it exceeds this time, it will be terminated.\n\n finish_by: Instant,\n\n /// The child process itself.\n\n child: Child,\n\n /// This TempDir will be dropped, and its file system contents removed, when this Job is dropped.\n\n tempdir: TempDir,\n\n /// We are responsible for manually cleaning up the JSON file stored in `json_path`.\n\n json_path: PathBuf,\n\n /// The temporary file to which we write combined stderr/stdout.\n\n stderrout: NamedTempFile,\n\n /// Has the child process's stderr been closed?\n\n stderr_hup: bool,\n\n /// Has the child process's stdout been closed?\n\n stdout_hup: bool,\n\n /// The `RepoConfig` for this job.\n\n rconf: RepoConfig,\n\n}\n\n\n", "file_path": "src/jobrunner.rs", "rank": 11, "score": 45177.37539136655 }, { "content": "struct JobRunner {\n\n snare: Arc<Snare>,\n\n /// The shell used to run jobs.\n\n shell: String,\n\n /// The maximum number of jobs we will run at any one point. Note that this may not necessarily\n\n /// be the same value as snare.conf.maxjobs.\n\n maxjobs: usize,\n\n /// The running jobs, with `0..num_running` entries.\n\n running: Vec<Option<Job>>,\n\n /// How many `Some` entries are there in `self.running`?\n\n num_running: usize,\n\n /// The running jobs, with `0..2 *num_running + 1` entries. Each pair of entries are (stderr,\n\n /// stdout) for the corresponding `running` `Job` (i.e. `running[0]` has its stderr entry at\n\n /// `pollfds[0]` and stdout entry at `pollfds[1]`). The `+ 1` entry is the event file\n\n /// descriptor that allows the HTTP server thread to wake up the JobRunner thread.\n\n pollfds: Vec<PollFd>,\n\n}\n\n\n\nimpl JobRunner {\n\n fn new(snare: Arc<Snare>) -> Result<Self, Box<dyn Error>> {\n", "file_path": "src/jobrunner.rs", "rank": 12, "score": 43718.72906098752 }, { "content": "/// Return an error message pinpointing `span` as the culprit.\n\nfn error_at_span(lexer: &dyn NonStreamingLexer<StorageT>, span: Span, msg: &str) -> String {\n\n let ((line_off, col), _) = lexer.line_col(span);\n\n let code = lexer\n\n .span_lines_str(span)\n\n .split('\\n')\n\n .next()\n\n .unwrap()\n\n .trim();\n\n format!(\n\n \"Line {}, column {}:\\n {}\\n{}\",\n\n line_off,\n\n col,\n\n code.trim(),\n\n msg\n\n )\n\n}\n\n\n\n/// The configuration for a given repository.\n\npub struct RepoConfig {\n\n pub cmd: Option<String>,\n", "file_path": "src/config.rs", "rank": 13, "score": 43648.804401530506 }, { "content": "/// Exit with a fatal error, printing the contents of `err`.\n\nfn fatal_err<E: Into<Box<dyn Error>> + Display>(daemonised: bool, msg: &str, err: E) -> ! {\n\n fatal(daemonised, &format!(\"{}: {}\", msg, err));\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 14, "score": 42021.71176789989 }, { "content": "/// Print out program usage then exit. This function must not be called after daemonisation.\n\nfn usage() -> ! {\n\n eprintln!(\"Usage: {} [-c <config-path>] [-d]\", progname());\n\n process::exit(1)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 40399.057815697495 }, { "content": "/// Take the string `raw_cmd` and return a string with the following replaced:\n\n/// * `%e` with `event_type`\n\n/// * `%o` with `owner`\n\n/// * `%r` with `repo`\n\n/// * `%j` with `json_path`\n\n///\n\n/// Note that `raw_cmd` *must* have been validated by config::GitHub::verify_cmd_str or undefined\n\n/// behaviour will occur.\n\nfn cmd_replace(\n\n raw_cmd: &str,\n\n event_type: &str,\n\n owner: &str,\n\n repo: &str,\n\n json_path: &str,\n\n) -> String {\n\n let modifiers = [\n\n ('e', event_type),\n\n ('o', owner),\n\n ('r', repo),\n\n ('j', json_path),\n\n ('%', \"%\"),\n\n ]\n\n .iter()\n\n .cloned()\n\n .collect();\n\n replace(raw_cmd, modifiers)\n\n}\n\n\n", "file_path": "src/jobrunner.rs", "rank": 16, "score": 39004.94830215596 }, { "content": "/// Take the string `raw_errorcmd` and return a string with the following replaced:\n\n/// * `%e` with `event_type`\n\n/// * `%o` with `owner`\n\n/// * `%r` with `repo`\n\n/// * `%j` with `json_path`\n\n/// * `%s` with `stderrout_path`\n\n///\n\n/// Note that `raw_cmd` *must* have been validated by config::GitHub::verify_errorcmd_str or\n\n/// undefined behaviour will occur.\n\nfn errorcmd_replace(\n\n raw_errorcmd: &str,\n\n event_type: &str,\n\n owner: &str,\n\n repo: &str,\n\n json_path: &str,\n\n stderrout_path: &str,\n\n) -> String {\n\n let modifiers = [\n\n ('e', event_type),\n\n ('o', owner),\n\n ('r', repo),\n\n ('j', json_path),\n\n ('s', stderrout_path),\n\n ('%', \"%\"),\n\n ]\n\n .iter()\n\n .cloned()\n\n .collect();\n\n replace(raw_errorcmd, modifiers)\n\n}\n\n\n", "file_path": "src/jobrunner.rs", "rank": 17, "score": 39004.76089265094 }, { "content": "/// If the config specified a 'user' then switch to that and update $HOME and $USER appropriately.\n\n/// This function must not be called after daemonisation.\n\nfn change_user(conf: &Config) {\n\n match conf.user {\n\n Some(ref user) => match get_user_by_name(&user) {\n\n Some(u) => {\n\n let gid = Gid::from_raw(u.primary_group_id());\n\n if let Err(e) = setresgid(gid, gid, gid) {\n\n fatal_err(false, &format!(\"Can't switch to group '{}'\", user), e);\n\n }\n\n let uid = Uid::from_raw(u.uid());\n\n if let Err(e) = setresuid(uid, uid, uid) {\n\n fatal_err(false, &format!(\"Can't switch to user '{}'\", user), e);\n\n }\n\n env::set_var(\"HOME\", u.home_dir());\n\n env::set_var(\"USER\", user);\n\n }\n\n None => fatal(false, &format!(\"Unknown user '{}'\", user)),\n\n },\n\n None => {\n\n if Uid::current().is_root() {\n\n fatal(\n\n false,\n\n \"The 'user' option must be set if snare is run as root\",\n\n );\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 18, "score": 33291.4307982264 }, { "content": "/// Try to find a `snare.conf` file.\n\nfn search_snare_conf() -> Option<PathBuf> {\n\n let p = PathBuf::from(SNARE_CONF_PATH);\n\n if p.is_file() {\n\n return Some(p);\n\n }\n\n None\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 19, "score": 31381.023879636556 }, { "content": "fn set_nonblock(fd: RawFd) -> Result<(), Box<dyn Error>> {\n\n let mut flags = fcntl(fd, FcntlArg::F_GETFL)?;\n\n flags |= OFlag::O_NONBLOCK.bits();\n\n fcntl(\n\n fd,\n\n FcntlArg::F_SETFL(unsafe { OFlag::from_bits_unchecked(flags) }),\n\n )?;\n\n Ok(())\n\n}\n\n\n\npub(crate) fn attend(snare: Arc<Snare>) -> Result<(), Box<dyn Error>> {\n\n let mut rn = JobRunner::new(snare)?;\n\n thread::spawn(move || rn.attend());\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n", "file_path": "src/jobrunner.rs", "rank": 26, "score": 25301.17103524688 }, { "content": "## Breaking changes\n\n\n\n* The `github`-block level `reposdir` option has been removed. The more\n\n flexible `match`-block level `cmd` has been introduced. In essence:\n\n\n\n ```\n\n github {\n\n reposdir = \"/path/to/prps\";\n\n ...\n\n }\n\n ```\n\n\n\n should be changed to:\n\n\n\n ```\n\n github {\n\n match \".*\" {\n\n cmd = \"/path/to/reposdir/%o/%r %e %j\";\n\n }\n\n }\n\n ```\n\n\n\n `snare` informs users whose config contains `repodir` how to update it.\n\n\n\n\n\n## Minor changes\n\n\n\n* `snare` now validates input derived from the webhook request so that it is\n\n safe to pass to the shell: GitHub owners, repositories, and events are all\n\n guaranteed to satisfy the regular expression `[a-zA-Z0-9._-]+` and not to be\n\n the strings `.` or `..`.\n\n\n\n* String escapes (e.g. `\"\\\"\"`) are now properly processed (previously they were\n\n ignored).\n\n\n\n\n\n# snare 0.1.0 (2020-02-13)\n\n\n\nFirst release.\n", "file_path": "CHANGES.md", "rank": 27, "score": 15615.670138256311 }, { "content": "# snare\n\n\n\n`snare` is a GitHub webhooks daemon. When `snare` receives a webhook event from\n\na given repository, it authenticates the request, and then executes a\n\nuser-defined \"per-repo program\" with information about the webhook event.\n\n\n\n\n\n## Install\n\n\n\n`snare` requires rustc-1.40.0 or greater.\n\n\n\nTo install `snare` on a per-user basis, use `cargo install snare`.\n\n\n\nTo install `snare` globally and/or for packaging purposes, download the latest\n\nstable version from [`snare`'s homepage](https://tratt.net/laurie/src/snare/).\n\nYou may use `cargo` to build snare locally or you may use the `Makefile` to\n\nbuild and install `snare` in traditional Unix fashion. `make install` defaults\n\nto installing in `/usr/local`: you can override this by setting the `PREFIX`\n\nvariable to another path (e.g. `PREFIX=/opt/local make`).\n\n\n\n\n\n## Quick setup\n\n\n\n`snare` has the following command-line format:\n\n\n\n```\n\nUsage: snare [-c <config-path>] [-d]\n\n```\n\n\n\nwhere:\n\n\n\n * `-c <config-path>` is a path to a `snare.conf` configuration file. If not\n\n specified, `snare` will assume the configuration file is located at\n\n `/etc/snare/snare.conf`.\n\n * `-d` tells `snare` *not* to daemonise: in other words, `snare` stays in the\n\n foreground. This can be useful for debugging.\n\n\n\nThe [man page for snare](https://softdevteam.github.io/snare/snare.1.html) contains\n\nmore details.\n\n\n\nThe minimal recommended configuration file is:\n\n\n\n```\n\nlisten = \"<ip-address>:<port>\";\n\n\n\ngithub {\n\n match \".*\" {\n\n cmd = \"/path/to/prps/%o/%r %e %j\";\n\n errorcmd = \"cat %s | mailx -s \\\"snare error: github.com/%o/%r\\\" [email protected]\";\n\n secret = \"<secret>\";\n\n }\n\n}\n\n```\n\n\n\nwhere:\n\n\n\n * `ip-address` is either an IPv4 or IPv6 address and `port` a port on which an\n\n HTTP server will listen.\n\n * `cmd` is the command that will be executed when a webhook is received. In\n\n this case, `/path/to/prps` is a path to a directory where per-repo programs\n\n are stored. For a repository `repo` owned by `owner` the command:\n\n\n\n ```\n\n /path/to/prps/<owner>/<repo> <event> <path-to-github-json>\n", "file_path": "README.md", "rank": 28, "score": 15615.612238838186 }, { "content": "# A GitHub URL either https or git.\n\nREPO_URL=\"[email protected]:owner/repo.git\"\n\n\n\nif [ \"$1\" != \"push\" ]; then\n\n exit 0\n\nfi\n\n\n\nref=`jq .ref \"$2\" | tr -d '\\\"'`\n\nif [ \"$ref\" != \"refs/heads/master\" ]; then\n\n exit 0\n\nfi\n\n\n\nrepo_fullname=`jq .repository.full_name \"$2\" | tr -d '\\\"'`\n\nrepo_url=`jq .repository.html_url \"$2\" | tr -d '\\\"'`\n\nbefore_hash=`jq .before \"$2\" | tr -d '\\\"'`\n\nafter_hash=`jq .after \"$2\" | tr -d '\\\"'`\n\n\n\ngit clone \"$REPO_URL\" repo\n\ncd repo\n\nfor email in `echo \"$EMAILS\"`; do\n\n git log --reverse -p \"$before_hash..$after_hash\" | mail -s \"Push to $repo_fullname\" \"$email\"\n\ndone\n\n```\n\n\n\nwhere [`jq`](https://stedolan.github.io/jq/) is a command-line JSON processor.\n\nDepending on your needs, you can make this type of script arbitrarily more\n\ncomplex and powerful (e.g. not cloning afresh on each pull).\n\n\n\nNote that this program is deliberately untrusting of external input: it is\n\ncareful to quote all arguments obtained from JSON; and it uses a fixed\n\ndirectory name (`repo`) rather than use a file name from JSON that might\n\ninclude characters (e.g. `../..`) that would cause the script to leak data\n\nabout other parts of the file system.\n\n\n\n\n\n## Integration with GitHub\n\n\n\n`snare` runs an HTTP server which GitHub can send webhook requests to.\n\nConfiguring a webhook for a given GitHub repository is relatively simple: go to\n\nthat repository, then `Settings > Webhooks > Add webhook`. For `payload`,\n\nspecify `http://yourmachine.com:port/`, specify a `secret` (which you will then\n\nreuse as the `secret` in `snare.conf`) and then choose which events you wish\n\nGitHub to deliver. For example, the default `Just the push event` works well\n\nwith the email diff sending per-repo program above, but you can specify\n\nwhichever events you wish.\n\n\n\n\n\n## HTTPS/TLS\n\n\n\n`snare` runs an HTTP server. If you wish, as is recommended, to send your\n\nwebhooks over an encrypted connection, you will need to run a proxy in front of\n\nsnare e.g.\n\n[nginx](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/) or\n\n[relayd](https://man.openbsd.org/relayd.8).\n", "file_path": "README.md", "rank": 29, "score": 15614.262650696828 }, { "content": "## Commands\n\n\n\n`snare` can be used to run any command runnable from the Unix shell. The\n\n\"per-repo program\" model as documented above is one common way of doing this.\n\nFor example, `snare`'s GitHub\n\nrepository is\n\n[`https://github.com/softdevteam/snare`](https://github.com/softdevteam/snare).\n\nIf we set up a web hook up for that repository that notifies us of pull request\n\nevents, then with the above `snare.conf`, the command:\n\n\n\n```sh\n\n/path/to/prps/softdevteam/snare pull_request /path/to/json\n\n```\n\n\n\nwill be executed, where: `pull_request` is the name of the GitHub event; and\n\n`/path/to/json` is a path to a file containing the complete GitHub JSON for\n\nthat event. The `softdevteam/snare` program can then execute whatever it wants.\n\nIn order to work out precisely what event has happened, you will need to read\n\n[GitHub's webhooks documentation](https://developer.github.com/webhooks/).\n\n\n\n\n\n## Example per-repo program\n\n\n\nUsers can write per-repo programs in whatever system/language they wish, so\n\nlong as the matching file is marked as executable. The following simple example\n\nuses shell script to send a list of commits and diffs to the address specified\n\nin `$EMAIL` on each `push` to master. It works for any public GitHub\n\nrepository:\n\n\n\n```sh\n\n#! /bin/sh\n\n\n\nset -euf\n\n\n\n# A list of email addresses separated by spaces.\n\nEMAILS=\"[email protected] [email protected]\"\n", "file_path": "README.md", "rank": 30, "score": 15613.904507918603 }, { "content": "# snare 0.4.0 (2020-05-13)\n\n\n\n## Breaking changes\n\n\n\n* The `email` option in `match` blocks has been replaced by the more generic\n\n `errorcmd`. To obtain the previous behaviour:\n\n\n\n ```\n\n email = \"[email protected]\";\n\n ```\n\n\n\n should be changed to something like:\n\n\n\n ```\n\n errorcmd = \"cat %s | mailx -s \\\"snare error: github.com/%o/%r\\\" [email protected]\";\n\n ```\n\n\n\n This assumes that the `mailx` command is installed on your machine. As this\n\n example may suggest, `errorcmd` is much more flexible than `email`. The\n\n syntax of `errorcmd` is the same as `cmd` with the addition that `%s` is\n\n expanded to the path of the failed job's combined stderr / stdout.\n\n\n\n `snare` informs users whose config contains `email` how to update to\n\n `errorcmd` to obtain the previous behaviour.\n\n\n\n## Minor changes\n\n\n\n* After daemonisation, all errors are now sent to syslog (previously a few\n\n errors could still be sent to stderr).\n\n\n\n* Fix bug in parsing string escapes, where one character too many was\n\n consumed after `\\\"`.\n\n\n\n* Use SIGCHLD to listen for child process exit, so that `snare` does not have\n\n to be woken up as often.\n\n\n\n\n\n\n\n# snare 0.3.0 (2020-03-08)\n\n\n\n## Breaking changes\n\n\n\n* `snare` now only searches for a configuration file at\n\n `/etc/snare/snare.conf`; as before, you can specify an alternative location\n\n for `snare.conf` via the `-c` option.\n\n\n\n* `snare` always changes its CWD to `/` (previously CWD was only altered if a\n\n `user` was specified).\n\n\n\n\n\n## Minor changes\n\n\n\n* When a command fails, the email sent now contains the owner and repository\n\n name in the subject.\n\n\n\n\n\n# snare 0.2.0 (2020-03-02)\n\n\n", "file_path": "CHANGES.md", "rank": 31, "score": 15613.566045941358 }, { "content": " ```\n\n\n\n will be run. The file `<repo>` must be executable. Note that commands are\n\n run with their current working directory set to a temporary directory to\n\n which they can freely write and which will be automatically removed when\n\n they have completed.\n\n * `errorcmd` is the command that will be run when a `cmd` exits\n\n unsuccessfully. In this example, an email is sent to `[email protected]`\n\n with a body consisting of the comined stedrr/stdout. This assumes that you\n\n have installed, set-up, and enabled a suitable `sendmail` clone.\n\n * `secret` is the GitHub secret used to sign the webhook request and thus\n\n allowing `snare` to tell the difference between genuine webhook requests\n\n and those from malfeasants.\n\n\n\nThe [man page for\n\nsnare.conf](https://softdevteam.github.io/snare/snare.conf.5.html) contains the\n\ncomplete list of configuration options.\n\n\n\n\n", "file_path": "README.md", "rank": 32, "score": 15612.23907213886 }, { "content": "\n\n /// Return a `RepoConfig` for `owner/repo`. Note that if the user reloads the config later,\n\n /// then a given repository might have two or more `RepoConfig`s with internal settings, so\n\n /// they should not be mixed. We return the repository's secret as a separate member as it is\n\n /// relatively costly to clone, and we also prefer not to duplicate it repeatedly throughout\n\n /// the heap.\n\n pub fn repoconfig<'a>(&'a self, owner: &str, repo: &str) -> (RepoConfig, Option<&'a SecStr>) {\n\n let s = format!(\"{}/{}\", owner, repo);\n\n let mut cmd = None;\n\n let mut errorcmd = None;\n\n let mut queuekind = None;\n\n let mut secret = None;\n\n let mut timeout = None;\n\n for m in &self.matches {\n\n if m.re.is_match(&s) {\n\n if let Some(ref c) = m.cmd {\n\n cmd = Some(c.clone());\n\n }\n\n if let Some(ref e) = m.errorcmd {\n\n errorcmd = Some(e.clone());\n", "file_path": "src/config.rs", "rank": 33, "score": 16.46933546532388 }, { "content": " *res.status_mut() = StatusCode::UNAUTHORIZED;\n\n return Ok(res);\n\n }\n\n (None, None) => (),\n\n }\n\n\n\n if event_type == \"ping\" {\n\n *res.status_mut() = StatusCode::OK;\n\n return Ok(res);\n\n }\n\n\n\n let repo_id = format!(\"github/{}/{}\", owner, repo);\n\n let qj = QueueJob::new(repo_id, owner, repo, req_time, event_type, json_str, rconf);\n\n (*snare.queue.lock().unwrap()).push_back(qj);\n\n *res.status_mut() = StatusCode::OK;\n\n // If the write fails, it almost certainly means that the pipe is full i.e. the runner\n\n // thread will be notified anyway. If something else happens to have gone wrong, then\n\n // we (and the OS) are probably in deep trouble anyway...\n\n nix::unistd::write(snare.event_write_fd, &[0]).ok();\n\n Ok(res)\n\n}\n\n\n\n/// Extract the string 'def' from \"X-Hub-Signature: abc=def\"\n", "file_path": "src/httpserver.rs", "rank": 34, "score": 15.867502956878763 }, { "content": " i += c.len_utf8();\n\n }\n\n }\n\n s\n\n}\n\n\n\npub struct Match {\n\n /// The regular expression to match against full owner/repo names.\n\n re: Regex,\n\n /// The command to run (note that this contains escape characters such as %o and %r).\n\n cmd: Option<String>,\n\n /// An optional command to run when an error occurs (note that this contains escape characters\n\n /// such as %o and %r).\n\n errorcmd: Option<String>,\n\n /// The queue kind.\n\n queuekind: Option<QueueKind>,\n\n /// The GitHub secret used to validate requests.\n\n secret: Option<SecStr>,\n\n /// The maximum time to allow a command to run for before it is terminated (in seconds).\n\n timeout: Option<u64>,\n", "file_path": "src/config.rs", "rank": 35, "score": 14.37295323173848 }, { "content": " let (rconf, secret) = conf.github.repoconfig(&owner, &repo);\n\n\n\n match (secret, sig) {\n\n (Some(secret), Some(sig)) => {\n\n if !authenticate(secret, sig, pl) {\n\n snare.error(&format!(\"Authentication failed for {}/{}.\", owner, repo));\n\n *res.status_mut() = StatusCode::UNAUTHORIZED;\n\n return Ok(res);\n\n }\n\n }\n\n (Some(_), None) => {\n\n snare.error(&format!(\"Request was unsigned for {}/{}.\", owner, repo));\n\n *res.status_mut() = StatusCode::UNAUTHORIZED;\n\n return Ok(res);\n\n }\n\n (None, Some(_)) => {\n\n snare.error(&format!(\n\n \"Request was signed but no secret was specified for {}/{}.\",\n\n owner, repo\n\n ));\n", "file_path": "src/httpserver.rs", "rank": 36, "score": 14.319595440583523 }, { "content": " // that, assuming `Instant` is a `u64`, this could only happen with an\n\n // uptime of over 500,000,000 years. This seems adequately long that I'm\n\n // happy to take the risk on the unwrap().\n\n let finish_by = Instant::now()\n\n .checked_add(Duration::from_millis(\n\n qj.rconf.timeout.saturating_mul(1000),\n\n ))\n\n .unwrap();\n\n\n\n return Ok(Job {\n\n is_errorcmd: false,\n\n repo_id: qj.repo_id,\n\n event_type: qj.event_type,\n\n owner: qj.owner,\n\n repo: qj.repo,\n\n finish_by,\n\n child,\n\n tempdir,\n\n json_path,\n\n stderrout,\n", "file_path": "src/jobrunner.rs", "rank": 37, "score": 14.054060228532753 }, { "content": " pub matches: Vec<Match>,\n\n}\n\n\n\nimpl GitHub {\n\n fn parse(\n\n lexer: &dyn NonStreamingLexer<StorageT>,\n\n options: Vec<config_ast::ProviderOption>,\n\n ast_matches: Vec<config_ast::Match>,\n\n ) -> Result<Self, String> {\n\n let mut matches = vec![Match::default()];\n\n\n\n if let Some(config_ast::ProviderOption::ReposDir(span)) = options.get(0) {\n\n return Err(error_at_span(lexer, *span, \"Replace:\\n GitHub { reposdir = \\\"/path/to/reposdir\\\"; }\\nwith:\\n GitHub {\\n match \\\".*\\\" {\\n cmd = \\\"/path/to/reposdir/%o/%r %e %j\\\";\\n }\\n }\"));\n\n }\n\n\n\n for m in ast_matches {\n\n let re_str = format!(\"^{}$\", unescape_str(lexer.span_str(m.re)));\n\n let re = match Regex::new(&re_str) {\n\n Ok(re) => re,\n\n Err(e) => {\n", "file_path": "src/config.rs", "rank": 38, "score": 13.828712631306308 }, { "content": " }\n\n }\n\n }\n\n\n\n /// Try to pop all jobs on the queue: returns `true` if it was able to do so successfully or\n\n /// `false` otherwise.\n\n fn try_pop_queue(&mut self) -> bool {\n\n let snare = Arc::clone(&self.snare);\n\n let mut queue = snare.queue.lock().unwrap();\n\n loop {\n\n if self.num_running == self.maxjobs && !queue.is_empty() {\n\n return false;\n\n }\n\n let pjob = queue.pop(|repo_id| {\n\n self.running.iter().any(|jobslot| {\n\n if let Some(job) = jobslot {\n\n repo_id == job.repo_id\n\n } else {\n\n false\n\n }\n", "file_path": "src/jobrunner.rs", "rank": 39, "score": 13.342999607920888 }, { "content": "use std::{convert::Infallible, sync::Arc, time::Instant};\n\n\n\nuse crypto_mac::Mac;\n\nuse hex;\n\nuse hmac::Hmac;\n\nuse hyper::service::{make_service_fn, service_fn};\n\nuse hyper::{self, body::Bytes, server::conn::AddrIncoming, Body, Request, Response, StatusCode};\n\nuse json;\n\nuse percent_encoding::percent_decode;\n\nuse secstr::SecStr;\n\nuse sha1::Sha1;\n\n\n\nuse crate::{queue::QueueJob, Snare};\n\n\n\npub(crate) async fn serve(server: hyper::server::Builder<AddrIncoming>, snare: Arc<Snare>) {\n\n let make_svc = make_service_fn(|_| {\n\n let snare = Arc::clone(&snare);\n\n async { Ok::<_, Infallible>(service_fn(move |req| handle(req, Arc::clone(&snare)))) }\n\n });\n\n\n", "file_path": "src/httpserver.rs", "rank": 40, "score": 13.229183532325681 }, { "content": " /// that it can be put back in the queue and retried later. If `Err(None)` is returned then the\n\n /// job could not be run (either because there is no command, or because there was a permanent\n\n /// error, and the user was appropriately notified) and the job is consumed.\n\n fn try_job(&mut self, qj: QueueJob) -> Result<Job, Option<QueueJob>> {\n\n let raw_cmd = match &qj.rconf.cmd {\n\n Some(c) => c,\n\n None => {\n\n // There is no command to run.\n\n return Err(None);\n\n }\n\n };\n\n\n\n // Write the JSON to an unnamed temporary file.\n\n let json_path = match NamedTempFile::new() {\n\n Ok(tfile) => match tfile.into_temp_path().keep() {\n\n Ok(p) => {\n\n if let Err(e) = fs::write(&p, qj.json_str.as_bytes()) {\n\n self.snare.error_err(\"Couldn't write JSON file.\", e);\n\n remove_file(p).ok();\n\n return Err(Some(qj));\n", "file_path": "src/jobrunner.rs", "rank": 41, "score": 12.77091401943018 }, { "content": "}\n\n\n\nimpl Default for Match {\n\n fn default() -> Self {\n\n // We know that this Regex is valid so the unwrap() is safe.\n\n let re = Regex::new(\".*\").unwrap();\n\n Match {\n\n re,\n\n cmd: None,\n\n errorcmd: None,\n\n queuekind: Some(QueueKind::Sequential),\n\n secret: None,\n\n timeout: Some(DEFAULT_TIMEOUT),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 42, "score": 12.366505691610971 }, { "content": "use lrpar::Span;\n\n\n\npub enum TopLevelOption {\n\n GitHub(Span, Vec<ProviderOption>, Vec<Match>),\n\n Listen(Span),\n\n MaxJobs(Span),\n\n User(Span),\n\n}\n\n\n\npub enum ProviderOption {\n\n ReposDir(Span),\n\n}\n\n\n\npub struct Match {\n\n pub re: Span,\n\n pub options: Vec<PerRepoOption>,\n\n}\n\n\n\npub enum PerRepoOption {\n\n Cmd(Span),\n", "file_path": "src/config_ast.rs", "rank": 43, "score": 11.370327165391451 }, { "content": " // `check_queue` serves two subtly different purposes:\n\n // * Has the event pipe told us there are new jobs in the queue?\n\n // * Are there jobs in the queue from a previous round that we couldn't run yet?\n\n let mut check_queue = false;\n\n // A scratch buffer used to read from files.\n\n let mut buf = Box::new([0; READBUF]);\n\n // The earliest finish_by time of any running process (i.e. the process that will timeout\n\n // the soonest).\n\n let mut next_finish_by: Option<Instant> = None;\n\n loop {\n\n // If there are jobs on the queue we haven't been able to run for temporary reasons,\n\n // then wait a short amount of time and try again.\n\n let mut timeout = if check_queue { WAIT_TIMEOUT * 1000 } else { -1 };\n\n // If any processes will exceed their timeout then, if that's shorter than the above\n\n // timeout, only wait for enough time to pass before we need to send them SIGTERM.\n\n if let Some(fby) = next_finish_by {\n\n let fby_timeout = fby.saturating_duration_since(Instant::now());\n\n if timeout == -1\n\n || fby_timeout < Duration::from_millis(timeout.try_into().unwrap_or(0))\n\n {\n", "file_path": "src/jobrunner.rs", "rank": 44, "score": 11.309243551310805 }, { "content": " pub errorcmd: Option<String>,\n\n pub queuekind: QueueKind,\n\n pub timeout: u64,\n\n}\n\n\n\n#[derive(Clone, Copy)]\n\npub enum QueueKind {\n\n Evict,\n\n Parallel,\n\n Sequential,\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_verify_cmd_string() {\n\n assert!(GitHub::verify_cmd_str(\"\").is_ok());\n\n assert!(GitHub::verify_cmd_str(\"a\").is_ok());\n", "file_path": "src/config.rs", "rank": 45, "score": 10.835687581817709 }, { "content": " let cmd = cmd_replace(\n\n raw_cmd,\n\n &qj.event_type,\n\n &qj.owner,\n\n &qj.repo,\n\n &json_path_str,\n\n );\n\n let child = match Command::new(&self.shell)\n\n .arg(\"-c\")\n\n .arg(cmd)\n\n .current_dir(tempdir.path())\n\n .stderr(process::Stdio::piped())\n\n .stdout(process::Stdio::piped())\n\n .stdin(process::Stdio::null())\n\n .spawn()\n\n {\n\n Ok(c) => c,\n\n Err(e) => {\n\n self.snare.error_err(\"Can't spawn command: {:?}\", e);\n\n return Err(None);\n", "file_path": "src/jobrunner.rs", "rank": 46, "score": 10.618849798697552 }, { "content": " job.rconf.errorcmd.as_ref().unwrap()\n\n ));\n\n } else if let Some(errorchild) = self.run_errorcmd(&job) {\n\n let mut job = &mut self.running[i].as_mut().unwrap();\n\n job.child = errorchild;\n\n job.is_errorcmd = true;\n\n continue;\n\n }\n\n }\n\n remove_file(&self.running[i].as_ref().unwrap().json_path).ok();\n\n self.running[i] = None;\n\n self.num_running -= 1;\n\n self.update_pollfds();\n\n }\n\n }\n\n }\n\n\n\n // Has the HTTP server told us that we should check for new jobs and/or SIGCHLD/SIGHUP\n\n // has been received?\n\n match self.pollfds[self.maxjobs * 2].revents() {\n", "file_path": "src/jobrunner.rs", "rank": 47, "score": 10.538313088560727 }, { "content": " /// message) if it was unable to do so.\n\n pub fn from_path(conf_path: &PathBuf) -> Result<Self, String> {\n\n let input = match read_to_string(conf_path) {\n\n Ok(s) => s,\n\n Err(e) => return Err(format!(\"Can't read {:?}: {}\", conf_path, e)),\n\n };\n\n\n\n let lexerdef = config_l::lexerdef();\n\n let lexer = lexerdef.lexer(&input);\n\n let (astopt, errs) = config_y::parse(&lexer);\n\n if !errs.is_empty() {\n\n let msgs = errs\n\n .iter()\n\n .map(|e| e.pp(&lexer, &config_y::token_epp))\n\n .collect::<Vec<_>>();\n\n return Err(msgs.join(\"\\n\"));\n\n }\n\n let mut github = None;\n\n let mut listen = None;\n\n let mut maxjobs = None;\n", "file_path": "src/config.rs", "rank": 48, "score": 10.443656241359452 }, { "content": " if pl.len() < 8 {\n\n return Err(());\n\n }\n\n match std::str::from_utf8(&pl[..8]) {\n\n Ok(s) if s == \"payload=\" => (),\n\n _ => return Err(()),\n\n }\n\n\n\n // Decode the JSON and extract the owner and repo.\n\n let json_str = percent_decode(&pl[8..])\n\n .decode_utf8()\n\n .map_err(|_| ())?\n\n .into_owned();\n\n let jv = json::parse(&json_str).map_err(|_| ())?;\n\n let owner_json = &jv[\"repository\"][\"owner\"][\"login\"];\n\n let repo_json = &jv[\"repository\"][\"name\"];\n\n match (owner_json.as_str(), repo_json.as_str()) {\n\n (Some(o), Some(r)) => Ok((pl, json_str, o.to_owned(), r.to_owned())),\n\n _ => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/httpserver.rs", "rank": 49, "score": 10.390389153385557 }, { "content": "\n\n let (pl, json_str, owner, repo) = match parse(req).await {\n\n Ok((pl, j, o, r)) => (pl, j, o, r),\n\n Err(_) => {\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n\n return Ok(res);\n\n }\n\n };\n\n\n\n if !valid_github_ownername(&owner) {\n\n snare.error(&format!(\"Invalid GitHub owner '{}'.\", &owner));\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n\n return Ok(res);\n\n } else if !valid_github_reponame(&repo) {\n\n snare.error(&format!(\"Invalid GitHub repository '{}'.\", &repo));\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n\n return Ok(res);\n\n }\n\n\n\n let conf = snare.conf.lock().unwrap();\n", "file_path": "src/httpserver.rs", "rank": 50, "score": 10.140904355086679 }, { "content": " // jobs.\n\n self.running.truncate(new_maxjobs);\n\n self.pollfds.truncate(new_maxjobs * 2 + 1);\n\n self.maxjobs = new_maxjobs;\n\n self.update_pollfds();\n\n }\n\n }\n\n\n\n /// If the user has specified an email address, send the contents of\n\n fn run_errorcmd(&self, job: &Job) -> Option<Child> {\n\n if let Some(raw_errorcmd) = &job.rconf.errorcmd {\n\n let errorcmd = errorcmd_replace(\n\n raw_errorcmd,\n\n &job.event_type,\n\n &job.owner,\n\n &job.repo,\n\n &job.json_path.as_os_str().to_str().unwrap(),\n\n &job.stderrout.path().as_os_str().to_str().unwrap(),\n\n );\n\n match Command::new(&self.shell)\n", "file_path": "src/jobrunner.rs", "rank": 51, "score": 10.027720368441342 }, { "content": " Some(flags) if flags == PollFlags::POLLIN => {\n\n check_queue = true;\n\n // It's fine for us to drain the event pipe completely: we'll process all the\n\n // events it contains.\n\n loop {\n\n match nix::unistd::read(self.snare.event_read_fd, &mut *buf) {\n\n Ok(0) | Err(_) => break,\n\n Ok(_) => (),\n\n }\n\n }\n\n }\n\n _ => (),\n\n }\n\n\n\n // Should we check the queue? This could be because we were previously unable to empty\n\n // it fully, or because the HTTP server has told us that there might be new jobs.\n\n // However, it's only worth us checking the queue (which requires a lock) if there's\n\n // space for us to run further jobs.\n\n if check_queue && self.num_running < self.maxjobs {\n\n check_queue = !self.try_pop_queue();\n", "file_path": "src/jobrunner.rs", "rank": 52, "score": 9.982235070251678 }, { "content": "//! snare is a GitHub webhooks daemon. Architecturally it is split in two:\n\n//! * The `httpserver` listens for incoming hooks, checks that they're valid, and adds them to a\n\n//! `Queue`.\n\n//! * The `jobrunner` pops elements from the `Queue` and runs them in parallel.\n\n//! These two components run as two different threads: the `httpserver` writes a solitary byte to\n\n//! an \"event pipe\" to wake up the `jobrunner` when the queue has new elements. We also wake up the\n\n//! `jobrunner` on SIGHUP and SIGCHLD.\n\n\n\nmod config;\n\nmod config_ast;\n\nmod httpserver;\n\nmod jobrunner;\n\nmod queue;\n\n\n\nuse std::{\n\n env::{self, current_exe, set_current_dir},\n\n error::Error,\n\n ffi::CString,\n\n fmt::Display,\n\n os::unix::io::RawFd,\n", "file_path": "src/main.rs", "rank": 53, "score": 9.207970814349807 }, { "content": " let shell = env::var(\"SHELL\")?;\n\n let maxjobs = snare.conf.lock().unwrap().maxjobs;\n\n assert!(maxjobs <= (std::usize::MAX - 1) / 2);\n\n let mut running = Vec::with_capacity(maxjobs);\n\n running.resize_with(maxjobs, || None);\n\n let mut pollfds = Vec::with_capacity(maxjobs * 2 + 1);\n\n pollfds.resize_with(maxjobs * 2 + 1, || PollFd::new(-1, PollFlags::empty()));\n\n Ok(JobRunner {\n\n snare,\n\n shell,\n\n maxjobs,\n\n running,\n\n num_running: 0,\n\n pollfds,\n\n })\n\n }\n\n\n\n /// Listen for new jobs on the queue and then run them.\n\n fn attend(&mut self) {\n\n self.update_pollfds();\n", "file_path": "src/jobrunner.rs", "rank": 54, "score": 9.053587441182811 }, { "content": "use queue::Queue;\n\n\n\n/// Default location of `snare.conf`.\n\nconst SNARE_CONF_PATH: &str = \"/etc/snare/snare.conf\";\n\n\n\npub(crate) struct Snare {\n\n /// Are we currently running as a daemon?\n\n daemonised: bool,\n\n /// The location of snare.conf; this file will be reloaded if SIGHUP is received.\n\n conf_path: PathBuf,\n\n /// The current configuration: note that this can change at any point due to SIGHUP. All calls\n\n /// to `conf.lock().unwrap()` are considered safe since the only way this can fail is if the\n\n /// other thread has `panic`ed, at which point we're already doomed.\n\n conf: Mutex<Config>,\n\n /// The current queue of incoming jobs. All calls to `queue.lock().unwrap()` are considered\n\n /// safe since the only way this can fail is if the other thread has `panic`ed, at which point\n\n /// we're already doomed.\n\n queue: Mutex<Queue>,\n\n /// The read end of the pipe used by the httpserver and the SIGHUP handler to wake up the job\n\n /// runner thread.\n", "file_path": "src/main.rs", "rank": 55, "score": 8.01278949841442 }, { "content": " if let Err(e) = server.serve(make_svc).await {\n\n snare.fatal_err(\"Couldn't start HTTP server\", e);\n\n }\n\n}\n\n\n\nasync fn handle(req: Request<Body>, snare: Arc<Snare>) -> Result<Response<Body>, Infallible> {\n\n let mut res = Response::new(Body::empty());\n\n let req_time = Instant::now();\n\n let event_type = match req.headers().get(\"X-GitHub-Event\") {\n\n Some(hv) => match hv.to_str() {\n\n Ok(s) => {\n\n if !valid_github_event(s) {\n\n snare.error(&format!(\"Invalid GitHub event type '{}'.\", s));\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n\n return Ok(res);\n\n }\n\n s.to_owned()\n\n }\n\n Err(_) => {\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n", "file_path": "src/httpserver.rs", "rank": 56, "score": 7.914094287175402 }, { "content": " }\n\n config_ast::PerRepoOption::Queue(span, qkind) => {\n\n if queuekind.is_some() {\n\n return Err(error_at_span(\n\n lexer,\n\n span,\n\n \"Mustn't specify 'queue' more than once\",\n\n ));\n\n }\n\n queuekind = Some(match qkind {\n\n config_ast::QueueKind::Evict => QueueKind::Evict,\n\n config_ast::QueueKind::Parallel => QueueKind::Parallel,\n\n config_ast::QueueKind::Sequential => QueueKind::Sequential,\n\n });\n\n }\n\n config_ast::PerRepoOption::Secret(span) => {\n\n if secret.is_some() {\n\n return Err(error_at_span(\n\n lexer,\n\n span,\n", "file_path": "src/config.rs", "rank": 57, "score": 7.889421096590556 }, { "content": " })\n\n });\n\n match pjob {\n\n Some(qj) => {\n\n debug_assert!(self.num_running < self.maxjobs);\n\n match self.try_job(qj) {\n\n Ok(j) => {\n\n // The unwrap is safe since we've already checked that there's room to\n\n // run at least 1 job.\n\n let i = self.running.iter().position(|x| x.is_none()).unwrap();\n\n self.running[i] = Some(j);\n\n self.num_running += 1;\n\n self.update_pollfds();\n\n }\n\n Err(Some(qj)) => {\n\n // The job couldn't be run for temporary reasons: we'll retry later.\n\n queue.push_front(qj);\n\n return false;\n\n }\n\n Err(None) => {\n", "file_path": "src/jobrunner.rs", "rank": 58, "score": 7.8628628362824955 }, { "content": "mod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn github_event() {\n\n assert!(!valid_github_event(\"\"));\n\n assert!(valid_github_event(\"a\"));\n\n assert!(valid_github_event(\"check_run\"));\n\n assert!(!valid_github_event(\"check-run\"));\n\n assert!(!valid_github_event(\"check-run2\"));\n\n\n\n let mut s = String::new();\n\n for i in 0..255 {\n\n let c = char::from(i);\n\n if c.is_ascii_lowercase() || c == '_' {\n\n continue;\n\n }\n\n s.clear();\n\n s.push(c);\n\n assert!(!valid_github_event(&s));\n", "file_path": "src/httpserver.rs", "rank": 59, "score": 7.757405263438287 }, { "content": " fn test_unescape_string() {\n\n assert_eq!(unescape_str(\"\\\"\\\"\"), \"\");\n\n assert_eq!(unescape_str(\"\\\"a\\\"\"), \"a\");\n\n assert_eq!(unescape_str(\"\\\"a\\\\\\\"\\\"\"), \"a\\\"\");\n\n assert_eq!(unescape_str(\"\\\"a\\\\\\\"b\\\"\"), \"a\\\"b\");\n\n assert_eq!(unescape_str(\"\\\"\\\\\\\\\\\"\"), \"\\\\\");\n\n }\n\n\n\n #[test]\n\n fn test_example_conf() {\n\n let mut p = PathBuf::new();\n\n p.push(env!(\"CARGO_MANIFEST_DIR\"));\n\n p.push(\"snare.conf.example\");\n\n match Config::from_path(&p) {\n\n Ok(_) => (),\n\n Err(e) => panic!(\"{:?}\", e),\n\n }\n\n }\n\n}\n", "file_path": "src/config.rs", "rank": 60, "score": 7.675077007723699 }, { "content": "use std::{fs::read_to_string, net::SocketAddr, path::PathBuf, process, str::FromStr};\n\n\n\nuse crypto_mac::{InvalidKeyLength, Mac};\n\nuse hmac::Hmac;\n\nuse lrlex::lrlex_mod;\n\nuse lrpar::{lrpar_mod, NonStreamingLexer, Span};\n\nuse regex::Regex;\n\nuse secstr::SecStr;\n\nuse sha1::Sha1;\n\n\n\nuse crate::config_ast;\n\n\n", "file_path": "src/config.rs", "rank": 61, "score": 7.6609901155022335 }, { "content": " // `Some(_)` and the unwrap thus safe.\n\n let mut exited = false;\n\n let mut exited_success = false;\n\n match self.running[i].as_mut().unwrap().child.try_wait() {\n\n Ok(Some(status)) => {\n\n exited = true;\n\n exited_success = status.success();\n\n }\n\n Err(_) => {\n\n exited = true;\n\n exited_success = false;\n\n }\n\n Ok(None) => (),\n\n }\n\n if exited {\n\n if !exited_success {\n\n let job = &self.running[i].as_ref().unwrap();\n\n if job.is_errorcmd {\n\n self.snare.error(&format!(\n\n \"errorcmd exited unsuccessfully: {}\",\n", "file_path": "src/jobrunner.rs", "rank": 62, "score": 7.610562426448807 }, { "content": "};\n\n\n\nuse libc::c_int;\n\nuse nix::{\n\n fcntl::{fcntl, FcntlArg, OFlag},\n\n poll::{poll, PollFd, PollFlags},\n\n sys::signal::{kill, Signal},\n\n unistd::Pid,\n\n};\n\nuse tempfile::{tempdir, NamedTempFile, TempDir};\n\n\n\nuse crate::{config::RepoConfig, queue::QueueJob, Snare};\n\n\n\n/// The size of the temporary read buffer in bytes. Should be >= PIPE_BUF for performance reasons.\n\nconst READBUF: usize = 8 * 1024;\n\n/// Maximum time to wait in `poll` (in seconds) while waiting for child processes to terminate\n\n/// and/or because there are jobs on the queue that we haven't been able to run yet.\n\nconst WAIT_TIMEOUT: i32 = 1;\n\n\n", "file_path": "src/jobrunner.rs", "rank": 63, "score": 7.460983064240094 }, { "content": " return Err(error_at_span(\n\n lexer,\n\n m.re,\n\n &format!(\"Regular expression error: {}\", e),\n\n ))\n\n }\n\n };\n\n let mut cmd = None;\n\n let mut errorcmd = None;\n\n let mut queuekind = None;\n\n let mut secret = None;\n\n let mut timeout = None;\n\n for opt in m.options {\n\n match opt {\n\n config_ast::PerRepoOption::Cmd(span) => {\n\n if cmd.is_some() {\n\n return Err(error_at_span(\n\n lexer,\n\n span,\n\n \"Mustn't specify 'cmd' more than once\",\n", "file_path": "src/config.rs", "rank": 64, "score": 7.301301624647651 }, { "content": " stderr_hup: false,\n\n stdout_hup: false,\n\n rconf: qj.rconf,\n\n });\n\n }\n\n }\n\n }\n\n }\n\n\n\n Err(Some(qj))\n\n }\n\n\n\n /// After a job has been inserted / removed from `self.running`, this function must be called\n\n /// so that `poll()` is called with up-to-date file descriptors.\n\n fn update_pollfds(&mut self) {\n\n for (i, jobslot) in self.running.iter().enumerate() {\n\n let (stderr_fd, stdout_fd) = if let Some(job) = jobslot {\n\n // Since we've asked for stderr/stdout to be captured, the unwrap()s should be\n\n // safe, though the Rust docs are slightly vague on this.\n\n let stderr_fd = if job.stderr_hup {\n", "file_path": "src/jobrunner.rs", "rank": 65, "score": 7.104910907802009 }, { "content": " unsafe {\n\n openlog(progname, LOG_CONS, LOG_DAEMON);\n\n }\n\n\n\n let (event_read_fd, event_write_fd) = match pipe2(OFlag::O_NONBLOCK) {\n\n Ok(p) => p,\n\n Err(e) => fatal_err(daemonise, \"Can't create pipe\", e),\n\n };\n\n let sighup_occurred = Arc::new(AtomicBool::new(false));\n\n {\n\n let sighup_occurred = Arc::clone(&sighup_occurred);\n\n if let Err(e) = unsafe {\n\n signal_hook::register(signal_hook::SIGHUP, move || {\n\n // All functions called in this function must be signal safe. See signal(3).\n\n sighup_occurred.store(true, Ordering::Relaxed);\n\n nix::unistd::write(event_write_fd, &[0]).ok();\n\n })\n\n } {\n\n fatal_err(daemonise, \"Can't install SIGHUP handler\", e);\n\n }\n", "file_path": "src/main.rs", "rank": 66, "score": 6.846607503075214 }, { "content": " assert!(!valid_github_ownername(\n\n \"-23456789012345678901234567890123456780\"\n\n ));\n\n\n\n assert!(valid_github_ownername(\"a-b\"));\n\n assert!(!valid_github_ownername(\"a--b\"));\n\n\n\n assert!(valid_github_ownername(\"A\"));\n\n\n\n let mut s = String::new();\n\n for i in 0..255 {\n\n let c = char::from(i);\n\n if c.is_ascii_alphanumeric() {\n\n continue;\n\n }\n\n s.clear();\n\n s.push(c);\n\n assert!(!valid_github_ownername(&s));\n\n }\n\n }\n", "file_path": "src/httpserver.rs", "rank": 67, "score": 6.834214463594774 }, { "content": " }\n\n }\n\n\n\n /// Log `msg` as an error.\n\n ///\n\n /// # Panics\n\n ///\n\n /// If `msg` contains a `NUL` byte.\n\n fn error(&self, msg: &str) {\n\n if self.daemonised {\n\n // We know that `%s` and `<can't represent as CString>` are both valid C strings, and\n\n // that neither unwrap() can fail.\n\n let fmt = CString::new(\"%s\").unwrap();\n\n let msg = CString::new(msg)\n\n .unwrap_or_else(|_| CString::new(\"<can't represent as CString>\").unwrap());\n\n unsafe {\n\n syslog(LOG_ERR, fmt.as_ptr(), msg.as_ptr());\n\n }\n\n } else {\n\n eprintln!(\"{}\", msg);\n", "file_path": "src/main.rs", "rank": 68, "score": 6.45549663720554 }, { "content": " match jobrunner::attend(Arc::clone(&snare)) {\n\n Ok(x) => x,\n\n Err(e) => snare.fatal_err(\"Couldn't start runner thread\", e),\n\n }\n\n\n\n let mut rt = match Runtime::new() {\n\n Ok(rt) => rt,\n\n Err(e) => snare.fatal_err(\"Couldn't start tokio runtime.\", e),\n\n };\n\n rt.block_on(async {\n\n let server = match Server::try_bind(&snare.conf.lock().unwrap().listen) {\n\n Ok(s) => s,\n\n Err(e) => snare.fatal_err(\"Couldn't bind to address\", e),\n\n };\n\n\n\n httpserver::serve(server, Arc::clone(&snare)).await;\n\n });\n\n}\n", "file_path": "src/main.rs", "rank": 69, "score": 6.279582867092202 }, { "content": " Email(Span),\n\n ErrorCmd(Span),\n\n Queue(Span, QueueKind),\n\n Secret(Span),\n\n Timeout(Span),\n\n}\n\n\n\npub enum QueueKind {\n\n Evict,\n\n Parallel,\n\n Sequential,\n\n}\n", "file_path": "src/config_ast.rs", "rank": 70, "score": 6.197896136164298 }, { "content": " fn check_for_sighup(&mut self) {\n\n self.snare.check_for_sighup();\n\n\n\n let new_maxjobs = self.snare.conf.lock().unwrap().maxjobs;\n\n if new_maxjobs > self.maxjobs {\n\n // The user now wants to allow more jobs which we can do simply and safely -- even if\n\n // there are jobs running -- by extending self.running and self.pollfds with blank\n\n // entries.\n\n self.running.resize_with(new_maxjobs, || None);\n\n self.pollfds\n\n .resize_with(new_maxjobs * 2 + 1, || PollFd::new(-1, PollFlags::empty()));\n\n self.maxjobs = new_maxjobs;\n\n self.update_pollfds();\n\n } else if new_maxjobs < self.maxjobs && self.num_running == 0 {\n\n // The user wants to allow fewer jobs. This is somewhat hard because we may be running\n\n // jobs, and possibly more than the user now wants us to be running. We could be clever\n\n // and compact self.running and self.pollfds, though that may still not drop the number\n\n // of jobs down enough. We currently do the laziest thing: we wait until there are no\n\n // running jobs and then truncate self.running and self.pollfds. If there are always\n\n // running jobs then this means we will never reduce the number of maximum possible\n", "file_path": "src/jobrunner.rs", "rank": 71, "score": 5.816041712266 }, { "content": " }\n\n if flags.contains(PollFlags::POLLHUP) {\n\n self.running[i].as_mut().unwrap().stderr_hup = true;\n\n self.update_pollfds();\n\n }\n\n }\n\n // stdout\n\n if let Some(flags) = self.pollfds[i * 2 + 1].revents() {\n\n if flags.contains(PollFlags::POLLIN) {\n\n if let Ok(j) = self.running[i]\n\n .as_mut()\n\n .unwrap()\n\n .child\n\n .stdout\n\n .as_mut()\n\n .unwrap()\n\n .read(&mut *buf)\n\n {\n\n self.running[i]\n\n .as_mut()\n", "file_path": "src/jobrunner.rs", "rank": 72, "score": 5.749859193247507 }, { "content": " if let Err(e) = unsafe {\n\n signal_hook::register(signal_hook::SIGCHLD, move || {\n\n // All functions called in this function must be signal safe. See signal(3).\n\n nix::unistd::write(event_write_fd, &[0]).ok();\n\n })\n\n } {\n\n fatal_err(daemonise, \"Can't install SIGCHLD handler\", e);\n\n }\n\n }\n\n\n\n let snare = Arc::new(Snare {\n\n daemonised: daemonise,\n\n conf_path,\n\n conf: Mutex::new(conf),\n\n queue: Mutex::new(Queue::new()),\n\n event_read_fd,\n\n event_write_fd,\n\n sighup_occurred,\n\n });\n\n\n", "file_path": "src/main.rs", "rank": 73, "score": 5.71452864386692 }, { "content": "\n\n #[test]\n\n fn github_reponame() {\n\n assert!(!valid_github_reponame(\"\"));\n\n assert!(!valid_github_reponame(\".\"));\n\n assert!(!valid_github_reponame(\"..\"));\n\n assert!(valid_github_reponame(\"...\"));\n\n\n\n assert!(valid_github_reponame(\"a\"));\n\n assert!(valid_github_reponame(\"-\"));\n\n assert!(valid_github_reponame(\"_\"));\n\n assert!(valid_github_reponame(\"-.-\"));\n\n\n\n let mut s = String::new();\n\n for i in 0..255 {\n\n let c = char::from(i);\n\n if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {\n\n continue;\n\n }\n\n s.clear();\n\n s.push(c);\n\n assert!(!valid_github_reponame(&s));\n\n }\n\n }\n\n}\n", "file_path": "src/httpserver.rs", "rank": 74, "score": 5.688467276588327 }, { "content": " event_read_fd: RawFd,\n\n /// The write end of the pipe used by the httpserver and the SIGHUP handler to wake up the job\n\n /// runner thread.\n\n event_write_fd: RawFd,\n\n /// Has a SIGHUP event occurred? If so, the jobrunner will process it, and set this to false in\n\n /// case future SIGHUP events are detected.\n\n sighup_occurred: Arc<AtomicBool>,\n\n}\n\n\n\nimpl Snare {\n\n /// Check to see if we've received a SIGHUP since the last check. If so, we will try reloading\n\n /// the snare.conf file specified when we started. **Note that another thread may have called\n\n /// this function and caused the config to have changed.**\n\n fn check_for_sighup(&self) {\n\n if self.sighup_occurred.load(Ordering::Relaxed) {\n\n match Config::from_path(&self.conf_path) {\n\n Ok(conf) => *self.conf.lock().unwrap() = conf,\n\n Err(msg) => self.error(&msg),\n\n }\n\n self.sighup_occurred.store(false, Ordering::Relaxed);\n", "file_path": "src/main.rs", "rank": 75, "score": 5.634905000158087 }, { "content": " path::PathBuf,\n\n process,\n\n sync::{\n\n atomic::{AtomicBool, Ordering},\n\n Arc, Mutex,\n\n },\n\n};\n\n\n\nuse getopts::Options;\n\nuse hyper::Server;\n\nuse libc::{c_char, openlog, syslog, LOG_CONS, LOG_CRIT, LOG_DAEMON, LOG_ERR};\n\nuse nix::{\n\n fcntl::OFlag,\n\n unistd::{daemon, pipe2, setresgid, setresuid, Gid, Uid},\n\n};\n\nuse signal_hook;\n\nuse tokio::runtime::Runtime;\n\nuse users::{get_user_by_name, os::unix::UserExt};\n\n\n\nuse config::Config;\n", "file_path": "src/main.rs", "rank": 76, "score": 5.471342747090236 }, { "content": " }\n\n\n\n fn verify_str(s: &str, modifiers: &[char]) -> Result<(), String> {\n\n let mut i = 0;\n\n while i < s.len() {\n\n if s[i..].starts_with('%') {\n\n if i + 1 == s.len() {\n\n return Err(\"Cannot end command string with a single '%'.\".to_owned());\n\n }\n\n let c = s[i + 1..].chars().next().unwrap();\n\n if !modifiers.contains(&c) {\n\n return Err(format!(\"Unknown '%' modifier '{}.\", c));\n\n }\n\n i += 2;\n\n } else {\n\n i += 1;\n\n }\n\n }\n\n Ok(())\n\n }\n", "file_path": "src/config.rs", "rank": 77, "score": 5.387005683490531 }, { "content": " re,\n\n cmd,\n\n errorcmd,\n\n queuekind,\n\n secret,\n\n timeout,\n\n });\n\n }\n\n\n\n Ok(GitHub { matches })\n\n }\n\n\n\n /// Verify that the `cmd` string is valid, returning `Ok())` if so or `Err(String)` if not.\n\n fn verify_cmd_str(cmd: &str) -> Result<(), String> {\n\n GitHub::verify_str(cmd, &['e', 'o', 'r', 'j', '%'])\n\n }\n\n\n\n /// Verify that the `errorcmd` string is valid, returning `Ok())` if so or `Err(String)` if not.\n\n fn verify_errorcmd_str(errorcmd: &str) -> Result<(), String> {\n\n GitHub::verify_str(errorcmd, &['e', 'o', 'r', 'j', 's', '%'])\n", "file_path": "src/config.rs", "rank": 78, "score": 5.370365336679164 }, { "content": " // The job couldn't be run for permanent reasons: it has been consumed\n\n // and can't be rerun. Perhaps surprisingly, this is equivalent to the\n\n // job having run successfully: since it hasn't been put back on the\n\n // queue, there's no need to tell the caller that we couldn't pop all\n\n // the jobs on the queue.\n\n }\n\n }\n\n }\n\n None => {\n\n // We weren't able to pop any jobs from the queue, but that doesn't mean that\n\n // the queue is necessarily empty: there may be `QueueKind::Sequential` jobs in\n\n // it which can't be popped until others with the same path have completed.\n\n return queue.is_empty();\n\n }\n\n }\n\n }\n\n }\n\n\n\n /// Try starting the `QueueJob` `qj` running, returning `Ok(Job)` upon success. If for\n\n /// temporary reasons that is not possible, the job is returned via `Err(Some(QueueJob))` so\n", "file_path": "src/jobrunner.rs", "rank": 79, "score": 5.272174886839389 }, { "content": " None => search_snare_conf().unwrap_or_else(|| fatal(false, \"Can't find snare.conf\")),\n\n };\n\n let conf = Config::from_path(&conf_path).unwrap_or_else(|m| fatal(false, &m));\n\n\n\n change_user(&conf);\n\n\n\n set_current_dir(\"/\").unwrap_or_else(|_| fatal(false, \"Can't chdir to '/'\"));\n\n if daemonise {\n\n if let Err(e) = daemon(true, false) {\n\n fatal_err(false, \"Couldn't daemonise: {}\", e);\n\n }\n\n }\n\n\n\n // openlog's first argument `ident` is incompletely specified, but in practise we have to\n\n // assume that syslog merely stores a pointer to the string (i.e. it doesn't copy the string).\n\n // We thus deliberately leak memory here in order that the pointer always points to valid\n\n // memory. The unwrap() here is ugly, but if it fails, it means we've run out of memory, so\n\n // it's neither likely to fail nor, if it does, can we do anything to clear up from it.\n\n let progname =\n\n Box::into_raw(CString::new(progname()).unwrap().into_boxed_c_str()) as *const c_char;\n", "file_path": "src/main.rs", "rank": 80, "score": 5.263670384408608 }, { "content": " if let Some(Job {\n\n finish_by,\n\n ref child,\n\n ..\n\n }) = self.running[i]\n\n {\n\n if finish_by <= Instant::now() {\n\n kill(Pid::from_raw(child.id() as i32), Signal::SIGTERM).ok();\n\n } else if next_finish_by.is_none() || Some(finish_by) < next_finish_by {\n\n next_finish_by = Some(finish_by);\n\n }\n\n }\n\n\n\n if let Some(Job {\n\n stderr_hup: true,\n\n stdout_hup: true,\n\n ..\n\n }) = self.running[i]\n\n {\n\n // In the below, we know from the `let Some(_)` that `self.running[i]` is\n", "file_path": "src/jobrunner.rs", "rank": 81, "score": 5.201977326950473 }, { "content": " let mut user = None;\n\n match astopt {\n\n Some(Ok(opts)) => {\n\n for opt in opts {\n\n match opt {\n\n config_ast::TopLevelOption::GitHub(span, options, matches) => {\n\n if github.is_some() {\n\n return Err(error_at_span(\n\n &lexer,\n\n span,\n\n \"Mustn't specify 'github' more than once\",\n\n ));\n\n }\n\n github = Some(GitHub::parse(&lexer, options, matches)?);\n\n }\n\n config_ast::TopLevelOption::Listen(span) => {\n\n if listen.is_some() {\n\n return Err(error_at_span(\n\n &lexer,\n\n span,\n", "file_path": "src/config.rs", "rank": 82, "score": 4.992395077333576 }, { "content": " \"Mustn't specify 'maxjobs' more than once\",\n\n ));\n\n }\n\n let maxjobs_str = lexer.span_str(span);\n\n match maxjobs_str.parse() {\n\n Ok(0) => {\n\n return Err(error_at_span(\n\n &lexer,\n\n span,\n\n \"Must allow at least 1 job\",\n\n ))\n\n }\n\n Ok(x) if x > (std::usize::MAX - 1) / 2 => {\n\n return Err(error_at_span(\n\n &lexer,\n\n span,\n\n &format!(\n\n \"Maximum number of jobs is {}\",\n\n (std::usize::MAX - 1) / 2\n\n ),\n", "file_path": "src/config.rs", "rank": 83, "score": 4.95123712589201 }, { "content": "//! The job runner. This is a single thread which runs multiple commands as child processes. There\n\n//! are two types of commands: \"normal\" and \"error\" commands. Error commands are only executed if a\n\n//! normal command fails. For normal commands, we track stderr/stdout and exit status; for error\n\n//! commands we track only exit status.\n\n\n\n#![allow(clippy::cognitive_complexity)]\n\n\n\nuse std::{\n\n collections::HashMap,\n\n convert::TryInto,\n\n env,\n\n error::Error,\n\n fs::{self, remove_file},\n\n io::{Read, Write},\n\n os::unix::io::{AsRawFd, RawFd},\n\n path::PathBuf,\n\n process::{self, Child, Command},\n\n sync::Arc,\n\n thread,\n\n time::{Duration, Instant},\n", "file_path": "src/jobrunner.rs", "rank": 84, "score": 4.9442189095355955 }, { "content": " .unwrap()\n\n .stderrout\n\n .as_file_mut()\n\n .write_all(&buf[0..j])\n\n .ok();\n\n }\n\n }\n\n if flags.contains(PollFlags::POLLHUP) {\n\n self.running[i].as_mut().unwrap().stdout_hup = true;\n\n self.update_pollfds();\n\n }\n\n }\n\n }\n\n\n\n // Iterate over the running jobs and:\n\n // * If any jobs have exceeded their timeout, send them SIGTERM.\n\n // * If there are jobs whose stderr/stdout have closed, keep waiting on them until\n\n // they exit.\n\n next_finish_by = None;\n\n for i in 0..self.running.len() {\n", "file_path": "src/jobrunner.rs", "rank": 85, "score": 4.813998497954416 }, { "content": " \"Mustn't specify 'secret' more than once\",\n\n ));\n\n }\n\n let sec_str = unescape_str(lexer.span_str(span));\n\n\n\n // Looking at the Hmac code, it seems that a key can't actually be of an\n\n // invalid length despite the API suggesting that it can be... We're\n\n // conservative and assume that it really is possible to have an invalid\n\n // length key.\n\n match Hmac::<Sha1>::new_varkey(sec_str.as_bytes()) {\n\n Ok(_) => (),\n\n Err(InvalidKeyLength) => {\n\n return Err(error_at_span(lexer, span, \"Invalid secret key length\"))\n\n }\n\n }\n\n secret = Some(SecStr::from(sec_str));\n\n }\n\n config_ast::PerRepoOption::Timeout(span) => {\n\n if timeout.is_some() {\n\n return Err(error_at_span(\n", "file_path": "src/config.rs", "rank": 86, "score": 4.731809548732462 }, { "content": " return Ok(res);\n\n }\n\n },\n\n None => {\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n\n return Ok(res);\n\n }\n\n };\n\n\n\n // Extract the string 'def' from \"X-Hub-Signature: abc=def\" if the header is present.\n\n let sig = if req.headers().contains_key(\"X-Hub-Signature\") {\n\n if let Some(sig) = get_hub_sig(&req) {\n\n Some(sig)\n\n } else {\n\n *res.status_mut() = StatusCode::BAD_REQUEST;\n\n return Ok(res);\n\n }\n\n } else {\n\n None\n\n };\n", "file_path": "src/httpserver.rs", "rank": 87, "score": 4.642344831290843 }, { "content": " }\n\n if let Some(q) = m.queuekind {\n\n queuekind = Some(q);\n\n }\n\n if let Some(ref s) = m.secret {\n\n secret = Some(s);\n\n }\n\n if let Some(t) = m.timeout {\n\n timeout = Some(t)\n\n }\n\n }\n\n }\n\n // Since we know that Matches::default() provides a default queuekind and timeout, both\n\n // unwraps() are safe.\n\n (\n\n RepoConfig {\n\n cmd,\n\n errorcmd,\n\n queuekind: queuekind.unwrap(),\n\n timeout: timeout.unwrap(),\n\n },\n\n secret,\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 88, "score": 4.5507842001179934 }, { "content": " }\n\n p\n\n }\n\n Err(e) => {\n\n self.snare.error_err(\"Couldn't create temporary file.\", e);\n\n return Err(Some(qj));\n\n }\n\n },\n\n Err(e) => {\n\n self.snare.error_err(\"Couldn't create temporary file.\", e);\n\n return Err(Some(qj));\n\n }\n\n };\n\n\n\n // We combine the child process's stderr/stdout and write them to an unnamed temporary\n\n // file `stderrout_file`.\n\n if let Ok(tempdir) = tempdir() {\n\n if let Ok(stderrout) = NamedTempFile::new() {\n\n if set_nonblock(stderrout.as_file().as_raw_fd()).is_ok() {\n\n if let Some(json_path_str) = json_path.to_str() {\n", "file_path": "src/jobrunner.rs", "rank": 89, "score": 4.49862347889617 }, { "content": " timeout = fby_timeout\n\n .as_millis()\n\n .try_into()\n\n .unwrap_or(c_int::max_value());\n\n }\n\n }\n\n poll(&mut self.pollfds, timeout).ok();\n\n\n\n self.check_for_sighup();\n\n\n\n // See if any of our active jobs have events. Knowing when a pipe is actually closed is\n\n // surprisingly hard. https://www.greenend.org.uk/rjk/tech/poll.html has an interesting\n\n // suggestion which we adapt slightly here.\n\n //\n\n // This `for` loop has various unwrap() calls. If `flags[i * 2]` or `flags[i * 2 + 1]`\n\n // is `Some(_)`, then `self.running[i]` is `Some(_)`, so the\n\n // `self.running.as_mut.unwrap()`s are safe. Since we asked for stderr/stdout to be\n\n // captured, `std[err|out].as_mut().unwrap()` should also be safe (though the Rust docs\n\n // are a little vague on this).\n\n for i in 0..self.maxjobs {\n", "file_path": "src/jobrunner.rs", "rank": 90, "score": 4.474594759236029 }, { "content": "use cfgrammar::yacc::YaccKind;\n\nuse lrlex::LexerBuilder;\n\nuse lrpar::CTParserBuilder;\n\nuse rerun_except::rerun_except;\n\n\n", "file_path": "build.rs", "rank": 91, "score": 3.7254540878121287 }, { "content": " // stderr\n\n if let Some(flags) = self.pollfds[i * 2].revents() {\n\n if flags.contains(PollFlags::POLLIN) {\n\n if let Ok(j) = self.running[i]\n\n .as_mut()\n\n .unwrap()\n\n .child\n\n .stderr\n\n .as_mut()\n\n .unwrap()\n\n .read(&mut *buf)\n\n {\n\n self.running[i]\n\n .as_mut()\n\n .unwrap()\n\n .stderrout\n\n .as_file_mut()\n\n .write_all(&buf[0..j])\n\n .ok();\n\n }\n", "file_path": "src/jobrunner.rs", "rank": 92, "score": 3.5900041002300815 }, { "content": " lexer,\n\n span,\n\n \"Mustn't specify 'timeout' more than once\",\n\n ));\n\n }\n\n let t = match lexer.span_str(span).parse() {\n\n Ok(t) => t,\n\n Err(e) => {\n\n return Err(error_at_span(\n\n lexer,\n\n span,\n\n &format!(\"Invalid timeout: {}\", e),\n\n ))\n\n }\n\n };\n\n timeout = Some(t);\n\n }\n\n }\n\n }\n\n matches.push(Match {\n", "file_path": "src/config.rs", "rank": 93, "score": 3.2979418956591653 }, { "content": " -1\n\n } else {\n\n job.child.stderr.as_ref().unwrap().as_raw_fd()\n\n };\n\n let stdout_fd = if job.stdout_hup {\n\n -1\n\n } else {\n\n job.child.stdout.as_ref().unwrap().as_raw_fd()\n\n };\n\n (stderr_fd, stdout_fd)\n\n } else {\n\n (-1, -1)\n\n };\n\n self.pollfds[i * 2] = PollFd::new(stderr_fd, PollFlags::POLLIN);\n\n self.pollfds[i * 2 + 1] = PollFd::new(stdout_fd, PollFlags::POLLIN);\n\n }\n\n self.pollfds[self.maxjobs * 2] = PollFd::new(self.snare.event_read_fd, PollFlags::POLLIN);\n\n }\n\n\n\n /// If SIGHUP has been received, reload the config, and update self.maxjobs if possible.\n", "file_path": "src/jobrunner.rs", "rank": 94, "score": 2.864350644257135 }, { "content": " ));\n\n }\n\n let cmd_str = unescape_str(lexer.span_str(span));\n\n GitHub::verify_cmd_str(&cmd_str)?;\n\n cmd = Some(cmd_str);\n\n }\n\n config_ast::PerRepoOption::Email(span) => {\n\n return Err(error_at_span(lexer, span, \"Replace:\\n email = \\\"[email protected]\\\"; }\\nwith:\\n error_cmd = \\\"cat %f | mailx -s \\\\\\\"snare error: github.com/%o/%r\\\\\\\" [email protected]\\\";\"));\n\n }\n\n config_ast::PerRepoOption::ErrorCmd(span) => {\n\n if errorcmd.is_some() {\n\n return Err(error_at_span(\n\n lexer,\n\n span,\n\n \"Mustn't specify 'error_cmd' more than once\",\n\n ));\n\n }\n\n let errorcmd_str = unescape_str(lexer.span_str(span));\n\n GitHub::verify_errorcmd_str(&errorcmd_str)?;\n\n errorcmd = Some(errorcmd_str);\n", "file_path": "src/config.rs", "rank": 95, "score": 2.1646655514610083 }, { "content": " }\n\n }\n\n _ => process::exit(1),\n\n }\n\n let maxjobs = maxjobs.unwrap_or_else(num_cpus::get);\n\n let listen = listen.ok_or_else(|| \"A 'listen' address must be specified\".to_owned())?;\n\n let github = github.ok_or_else(|| {\n\n \"A GitHub block with at least a 'cmd' option must be specified\".to_owned()\n\n })?;\n\n\n\n Ok(Config {\n\n listen,\n\n maxjobs,\n\n github,\n\n user,\n\n })\n\n }\n\n}\n\n\n\npub struct GitHub {\n", "file_path": "src/config.rs", "rank": 96, "score": 2.1254136701852273 }, { "content": " \"Mustn't specify 'listen' more than once\",\n\n ));\n\n }\n\n let listen_str = unescape_str(lexer.span_str(span));\n\n match SocketAddr::from_str(&listen_str) {\n\n Ok(l) => listen = Some(l),\n\n Err(e) => {\n\n return Err(error_at_span(\n\n &lexer,\n\n span,\n\n &format!(\"Invalid listen address '{}': {}\", listen_str, e),\n\n ));\n\n }\n\n }\n\n }\n\n config_ast::TopLevelOption::MaxJobs(span) => {\n\n if maxjobs.is_some() {\n\n return Err(error_at_span(\n\n &lexer,\n\n span,\n", "file_path": "src/config.rs", "rank": 97, "score": 1.9015001898526087 }, { "content": " assert!(GitHub::verify_cmd_str(\"%% %e %o %r %j %%\").is_ok());\n\n assert!(GitHub::verify_cmd_str(\"%%\").is_ok());\n\n assert!(GitHub::verify_cmd_str(\"%\").is_err());\n\n assert!(GitHub::verify_cmd_str(\"a%\").is_err());\n\n assert!(GitHub::verify_cmd_str(\"%a\").is_err());\n\n assert!(GitHub::verify_cmd_str(\"%s\").is_err());\n\n }\n\n\n\n #[test]\n\n fn test_verify_errorcmd_string() {\n\n assert!(GitHub::verify_errorcmd_str(\"\").is_ok());\n\n assert!(GitHub::verify_errorcmd_str(\"a\").is_ok());\n\n assert!(GitHub::verify_errorcmd_str(\"%% %e %o %r %j %s %%\").is_ok());\n\n assert!(GitHub::verify_errorcmd_str(\"%%\").is_ok());\n\n assert!(GitHub::verify_errorcmd_str(\"%\").is_err());\n\n assert!(GitHub::verify_errorcmd_str(\"a%\").is_err());\n\n assert!(GitHub::verify_errorcmd_str(\"%a\").is_err());\n\n }\n\n\n\n #[test]\n", "file_path": "src/config.rs", "rank": 98, "score": 1.3367056897074385 } ]
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": "retired/rusty/scalyc/src/main.rs", "rank": 0, "score": 274672.1493086737 }, { "content": "class VarString;\n\n\n", "file_path": "retired/scalypp/LetString.h", "rank": 1, "score": 227995.90704380325 }, { "content": "class string : public Object {\n\npublic:\n\n string();\n\n string(const char c);\n\n string(const char* theString);\n\n string(string* theString);\n\n string(VarString* theString);\n\n string(size_t theLength);\n\n char* getNativeString() const;\n\n size_t getLength();\n\n char charAt(size_t i);\n\n bool equals(const char* theString);\n\n bool notEquals(const char* theString);\n\n bool equals(string* theString);\n\n bool notEquals(string* theString);\n\n bool equals(VarString* theString);\n\n bool notEquals(VarString* theString);\n\n _Array<string>& Split(_Page* _rp, char c);\n\n\n\nprivate:\n", "file_path": "retired/scalypp/LetString.h", "rank": 2, "score": 196065.20044637928 }, { "content": "class VarString : public Object {\n\npublic:\n\n VarString();\n\n VarString(const char* theString);\n\n VarString(VarString* theString);\n\n VarString(string* theString);\n\n VarString(size_t theLength);\n\n VarString(size_t theLength, size_t theCapacity);\n\n VarString(char c);\n\n char* getNativeString() const;\n\n size_t getLength();\n\n char operator [](size_t i);\n\n void append(char c);\n\n void append(const char* theString);\n\n void append(VarString* theString);\n\n void append(string* theString);\n\n bool operator == (const char* theString);\n\n bool equals(const char* theString);\n\n bool equals(string* theString);\n\n bool operator != (const char* theString);\n", "file_path": "retired/scalypp/VarString.h", "rank": 3, "score": 178344.62929469984 }, { "content": "struct StringToken {\n\n String value;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 4, "score": 174380.40541738636 }, { "content": "class Initializer;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 5, "score": 174372.9419892483 }, { "content": "class StringLiteral;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 6, "score": 173864.4778293974 }, { "content": "struct Region {\n\n Page* page;\n\n\n\n static Region create_from_page(Page* page) {\n\n auto bucket = Bucket::get(page);\n\n switch (bucket->tag) {\n\n case Bucket::Heap:\n\n return Region {\n\n .page = bucket->heap.allocate_page(),\n\n };\n\n case Bucket::Stack:\n\n auto our_page_address = StackBucket::new_page(page);\n\n return Region {\n\n .page = our_page_address\n\n };\n\n }\n\n };\n\n\n\n static Region create(Region& region) {\n\n return Region::create_from_page(region.page);\n", "file_path": "runtime/memory/Region.cpp", "rank": 7, "score": 172807.38511144085 }, { "content": "struct Page {\n\n void* next_object;\n\n Page* current_page;\n\n Page* next_page;\n\n List<Page*> exclusive_pages;\n\n\n\n void reset() {\n\n this->current_page = nullptr;\n\n this->next_page = nullptr;\n\n this->next_object = this + 1;\n\n this->exclusive_pages = List<Page*> { .head = nullptr };\n\n }\n\n\n\n void clear() {\n\n this->deallocate_extensions();\n\n this->reset();\n\n }\n\n\n\n bool is_oversized() {\n\n return this->next_object == nullptr;\n", "file_path": "runtime/memory/Page.cpp", "rank": 8, "score": 172675.29015174508 }, { "content": " class Lexer\n\n {\n\n public Token token;\n\n char? character;\n\n CharEnumerator chars;\n\n public ulong previous_line;\n\n public ulong previous_column;\n\n public ulong line;\n\n public ulong column;\n\n\n\n public Lexer(string deck)\n\n {\n\n token = new EmptyToken();\n\n chars = deck.GetEnumerator();\n\n character = null;\n\n previous_line = 1;\n\n previous_column = 0;\n\n line = 1;\n\n column = 0;\n\n read_character();\n", "file_path": "retired/runtime/Lexer.cs", "rank": 9, "score": 171330.3993834105 }, { "content": "struct UseSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 10, "score": 170574.48468272676 }, { "content": "struct MutableSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 11, "score": 170567.96625222408 }, { "content": "struct ExtendSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 12, "score": 170567.96625222408 }, { "content": "struct ExtendsSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 13, "score": 170567.96625222408 }, { "content": "struct NamespaceSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 14, "score": 170564.78022728066 }, { "content": "struct VectorSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 15, "score": 170545.86125918166 }, { "content": "struct LetSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 16, "score": 170542.71643085973 }, { "content": "struct SetSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 17, "score": 170539.5716443457 }, { "content": "struct VarSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 18, "score": 170526.9873813191 }, { "content": "class MutableDeclaration;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 19, "score": 170052.03866423512 }, { "content": "class BindingInitializer;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 20, "score": 170039.374088212 }, { "content": "class IdentifierInitializer;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 21, "score": 170039.374088212 }, { "content": "class AdditionalInitializer;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 22, "score": 170039.374088212 }, { "content": "class VarParameter;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 23, "score": 170011.05979333015 }, { "content": "struct ClassSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 24, "score": 169709.1423759821 }, { "content": " class Parser\n\n {\n\n Lexer lexer;\n\n string file_name = \"\";\n\n HashSet<string> keywords = new HashSet<string>(new string[] {\n\n \"as\",\n\n \"break\",\n\n \"catch\",\n\n \"case\",\n\n \"continue\",\n\n \"define\",\n\n \"default\",\n\n \"delegate\",\n\n \"drop\",\n\n \"else\",\n\n \"extends\",\n\n \"extern\",\n\n \"for\",\n\n \"function\",\n\n \"if\",\n", "file_path": "retired/runtime/Parser.cs", "rank": 25, "score": 166469.49260518514 }, { "content": "struct ParameterSetSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 26, "score": 166458.80073621063 }, { "content": "struct Lexer : Object {\n\n Token* token;\n\n char* character;\n\n StringIterator chars;\n\n size_t previous_position;\n\n size_t position;\n\n\n\n Lexer(String& deck) {\n\n token = new(alignof(Token), Page::get(this)->allocate_exclusive_page()) Token();\n\n token->tag = Token::Empty;\n\n character = nullptr;\n\n chars = StringIterator::create(deck);\n\n previous_position = 0,\n\n position = 0,\n\n read_character();\n\n skip_whitespace(true);\n\n }\n\n\n\n void read_character() {\n\n this->character = chars.next();\n", "file_path": "compiler/Lexer.cpp", "rank": 27, "score": 162506.35788541904 }, { "content": "struct UseSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n NameSyntax* name;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 28, "score": 161948.5145425476 }, { "content": "struct MutableSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n BindingSyntax* binding;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 29, "score": 161942.18895910657 }, { "content": "struct ExtendsSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n Vector<ExtendSyntax>* extensions;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 30, "score": 161942.18895910657 }, { "content": "struct ExtendSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n TypeSpecSyntax* spec;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 31, "score": 161942.18895910657 }, { "content": "struct NamespaceSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n BodySyntax* body;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 32, "score": 161939.0971923666 }, { "content": "struct VectorSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n Vector<ElementSyntax>* elements;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 33, "score": 161920.73793989324 }, { "content": "struct LetSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n BindingSyntax* binding;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 34, "score": 161917.68615097718 }, { "content": "struct SetSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n OperationSyntax* target;\n\n OperationSyntax* source;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 35, "score": 161914.63440263216 }, { "content": "struct VarSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n BindingSyntax* binding;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 36, "score": 161902.42244366658 }, { "content": "struct ClassSyntax : Object {\n\n size_t start;\n\n size_t end;\n\n StructureSyntax* structure;\n\n BodySyntax* body;\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 37, "score": 161108.77329438503 }, { "content": "struct String : Object {\n\n char* data;\n\n\n\n static String* create(Page* _rp, const char* data, size_t length) {\n\n char length_array[PACKED_SIZE];\n\n auto rest = length;\n\n\n\n size_t counter = 0;\n\n while (rest >= 0x80) {\n\n length_array[counter] = (char)rest | 0x80;\n\n rest >>= 7;\n\n counter += 1;\n\n }\n\n\n\n length_array[counter] = (char)rest;\n\n auto overall_length = counter + 1 + length;\n\n auto pointer = _rp->allocate_raw(overall_length, 1);\n\n memcpy(pointer, length_array, counter + 1);\n\n memcpy((char*)pointer + counter + 1, data, length);\n\n\n", "file_path": "runtime/containers/String.cpp", "rank": 38, "score": 160843.18082471562 }, { "content": "#[test]\n\nfn test_hash_set() {\n\n use containers::String;\n\n use memory::Heap;\n\n use memory::Page;\n\n use memory::Region;\n\n use memory::StackBucket;\n\n let mut heap = Heap::create();\n\n let root_stack_bucket = StackBucket::create(&mut heap);\n\n let root_page = Page::get(root_stack_bucket as usize);\n\n let _r = Region::create_from_page(root_page);\n\n let keywords = HashSet::from_vector(\n\n &_r,\n\n _r.page,\n\n Ref::new(\n\n _r.page,\n\n Vector::from_raw_array(\n\n _r.page,\n\n &[\n\n String::from_string_slice(_r.page, \"using\"),\n\n String::from_string_slice(_r.page, \"namespace\"),\n", "file_path": "retired/rusty/scaly/src/containers/hashset.rs", "rank": 39, "score": 158734.2998903866 }, { "content": "struct ParameterSetSyntax : Object {\n\n enum {\n\n Parameters,\n\n Type,\n\n } tag;\n\n union {\n\n ParametersSyntax parametersSyntax;\n\n TypeSyntax typeSyntax;\n\n };\n\n\n\n};\n\n\n", "file_path": "compiler/Parser.cpp", "rank": 40, "score": 158068.38357544728 }, { "content": "class StringLiteral : public Literal {\n\npublic:\n\n StringLiteral(string* theString);\n\n string* value;\n\n\n\n virtual bool _isStringLiteral();\n\n};\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 41, "score": 157840.4640042358 }, { "content": "struct Parser : Object {\n\n Lexer lexer;\n\n String file_name;\n\n HashSet<String> keywords;\n\n\n\n Parser(String& deck)\n\n : lexer(*new(alignof(Lexer), Page::get(this)) Lexer(deck)),\n\n file_name(*String::from_c_string(Page::get(this), \"\"))\n\n {\n\n auto r = Region::create_from_page(Page::get(this));\n\n Array<String>& array = *Array<String>::create(r.page);\n\n array.add(*String::from_c_string(r.page, \"as\"));\n\n array.add(*String::from_c_string(r.page, \"break\"));\n\n array.add(*String::from_c_string(r.page, \"catch\"));\n\n array.add(*String::from_c_string(r.page, \"case\"));\n\n array.add(*String::from_c_string(r.page, \"continue\"));\n\n array.add(*String::from_c_string(r.page, \"define\"));\n\n array.add(*String::from_c_string(r.page, \"default\"));\n\n array.add(*String::from_c_string(r.page, \"delegate\"));\n\n array.add(*String::from_c_string(r.page, \"drop\"));\n", "file_path": "compiler/Parser.cpp", "rank": 42, "score": 157645.45110719372 }, { "content": "struct HashSet : Object {\n\n size_t length;\n\n Vector<List<Slot<T>>>* slots;\n\n Page* slots_page;\n\n\n\n static HashSet<T>* create(Page* _rp) {\n\n return new(alignof(HashSet<T>), _rp) HashSet<T> {\n\n .length = 0,\n\n .slots = nullptr,\n\n };\n\n }\n\n\n\n static HashSet<T>* from_vector(Page* _rp, Vector<T>& vector) {\n\n auto hash_set = create(_rp);\n\n if (vector.length > 0)\n\n {\n\n hash_set->reallocate(vector.length);\n\n for (size_t i = 0; i < vector.length; i++) {\n\n hash_set->add_internal(*(vector[i]));\n\n }\n", "file_path": "runtime/containers/HashSet.cpp", "rank": 43, "score": 156402.35762041013 }, { "content": "class MutableDeclaration : public Declaration {\n\npublic:\n\n MutableDeclaration(BindingInitializer* initializer, Position* start, Position* end);\n\n virtual void accept(Visitor* visitor);\n\n BindingInitializer* initializer;\n\n\n\n virtual bool _isMutableDeclaration();\n\n};\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 44, "score": 154247.12401463604 }, { "content": "class Initializer : public SyntaxNode {\n\npublic:\n\n Initializer(Expression* expression, Position* start, Position* end);\n\n virtual void accept(Visitor* visitor);\n\n Expression* expression;\n\n\n\n virtual bool _isInitializer();\n\n};\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 45, "score": 154235.1872661389 }, { "content": "class VarParameter : public Parameter {\n\npublic:\n\n VarParameter(string* name, Type* parameterType, Position* start, Position* end);\n\n virtual void accept(Visitor* visitor);\n\n string* name;\n\n Type* parameterType;\n\n\n\n virtual bool _isVarParameter();\n\n};\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 46, "score": 154208.50018113412 }, { "content": "class Lexer : public Object {\n\npublic:\n\n Token* token; bool whitespaceSkipped;\n\n string* text;\n\n size_t position;\n\n size_t end;\n\n size_t previousLine; size_t previousColumn;\n\n size_t line;\n\n size_t column;\n\n Lexer(string* theText);\n\n virtual void advance();\n\n virtual Identifier* scanIdentifier(_Page* _rp);\n\n virtual Operator* scanOperator(_Page* _rp, bool includeDots);\n\n virtual Token* scanStringLiteral(_Page* _rp);\n\n virtual Token* scanCharacterLiteral(_Page* _rp);\n\n virtual NumericLiteral* scanNumericLiteral(_Page* _rp);\n\n virtual bool skipWhitespace();\n\n virtual void handleSingleLineComment();\n\n virtual void handleMultiLineComment();\n\n virtual bool parseKeyword(string* fixedString);\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 47, "score": 152577.68085669974 }, { "content": "class AdditionalInitializer : public SyntaxNode {\n\npublic:\n\n AdditionalInitializer(IdentifierInitializer* pattern, Position* start, Position* end);\n\n virtual void accept(Visitor* visitor);\n\n IdentifierInitializer* pattern;\n\n\n\n virtual bool _isAdditionalInitializer();\n\n};\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 48, "score": 150607.0252830532 }, { "content": "class BindingInitializer : public SyntaxNode {\n\npublic:\n\n BindingInitializer(IdentifierInitializer* initializer, _Array<AdditionalInitializer>* additionalInitializers, Position* start, Position* end);\n\n virtual void accept(Visitor* visitor);\n\n IdentifierInitializer* initializer;\n\n _Array<AdditionalInitializer>* additionalInitializers;\n\n\n\n virtual bool _isBindingInitializer();\n\n};\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 49, "score": 150607.0252830532 }, { "content": "class IdentifierInitializer : public SyntaxNode {\n\npublic:\n\n IdentifierInitializer(IdentifierPattern* pattern, Initializer* initializer, Position* start, Position* end);\n\n virtual void accept(Visitor* visitor);\n\n IdentifierPattern* pattern;\n\n Initializer* initializer;\n\n\n\n virtual bool _isIdentifierInitializer();\n\n};\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 50, "score": 150607.0252830532 }, { "content": "class Parser : public Object {\n\npublic:\n\n Parser(string* theFileName, string* text);\n\n virtual _Result<Module, ParserError> parseModule(_Page* _rp, _Page* _ep);\n\n virtual _Array<Statement>* parseStatementList(_Page* _rp);\n\n virtual Statement* parseStatement(_Page* _rp);\n\n virtual Declaration* parseDeclaration(_Page* _rp);\n\n virtual ConstantDeclaration* parseConstantDeclaration(_Page* _rp);\n\n virtual MutableDeclaration* parseMutableDeclaration(_Page* _rp);\n\n virtual BindingInitializer* parseBindingInitializer(_Page* _rp);\n\n virtual _Array<IdentifierInitializer>* parseIdentifierInitializerList(_Page* _rp);\n\n virtual IdentifierInitializer* parseIdentifierInitializer(_Page* _rp);\n\n virtual Initializer* parseInitializer(_Page* _rp);\n\n virtual _Array<AdditionalInitializer>* parseAdditionalInitializerList(_Page* _rp);\n\n virtual AdditionalInitializer* parseAdditionalInitializer(_Page* _rp);\n\n virtual Pattern* parsePattern(_Page* _rp);\n\n virtual IdentifierPattern* parseIdentifierPattern(_Page* _rp);\n\n virtual TypeAnnotation* parseTypeAnnotation(_Page* _rp);\n\n virtual Type* parseType(_Page* _rp);\n\n virtual _Array<TypePostfix>* parseTypePostfixList(_Page* _rp);\n", "file_path": "retired/scalycpp/Parser.h", "rank": 51, "score": 147806.10071025713 }, { "content": "pub trait Stream: Disposable {\n\n fn read_byte(&mut self) -> Result<i32, IoError>;\n\n fn write_byte(&mut self, u8) -> Result<(), IoError>;\n\n}\n\n\n\npub struct Disposer {\n\n pub stream: *mut Stream\n\n}\n\n\n\nimpl Drop for Disposer {\n\n fn drop(&mut self) {\n\n unsafe { (*self.stream).dispose() }\n\n }\n\n}\n\n\n", "file_path": "retired/rusty/scaly/src/io/stream.rs", "rank": 52, "score": 147155.50444803556 }, { "content": "// FNV-1a hash\n\npub fn hash(data: *const u8, length: usize) -> usize {\n\n let bytes = unsafe { std::slice::from_raw_parts(data, length) };\n\n let mut hash: u64 = 0xcbf29ce484222325;\n\n for byte in bytes.iter() {\n\n hash = hash ^ (*byte as u64);\n\n hash = hash.wrapping_mul(0x100000001b3);\n\n }\n\n hash as usize\n\n}\n\n\n", "file_path": "retired/rusty/scaly/src/containers/hashset.rs", "rank": 53, "score": 142090.0952592658 }, { "content": "class _Region {\n\npublic:\n\n _Region();\n\n _Page* get();\n\n ~_Region();\n\n};\n\n\n\n}\n\n\n\n#endif // __Scaly_Region__\n", "file_path": "retired/scalypp/Region.h", "rank": 54, "score": 140469.49468856602 }, { "content": "class _Page {\n\npublic:\n\n void reset();\n\n void clear();\n\n void* allocateObject(size_t size);\n\n _Page* allocateExclusivePage();\n\n static void forget(_Page* page);\n\n void deallocateExtensions();\n\n bool reclaimArray(void* address);\n\n static _Page* getPage(void* address);\n\n bool extend(void* address, size_t size);\n\n bool isOversized();\n\n\n\nprivate:\n\n _Page* allocateExtensionPage();\n\n _Page** getExtensionPageLocation();\n\n bool deallocateExclusivePage(_Page* page);\n\n void* getNextObject();\n\n void setNextObject(void* object);\n\n _Page** getNextExclusivePageLocation();\n", "file_path": "retired/scalypp/Page.h", "rank": 55, "score": 140326.85731585318 }, { "content": "struct StringIterator {\n\n char* current;\n\n char* last;\n\n\n\n static StringIterator create(String string) {\n\n auto buffer = string.get_buffer();\n\n return StringIterator {\n\n .current = (char*)buffer,\n\n .last = (char*)buffer + string.get_length() };\n\n }\n\n\n\n char* next() {\n\n if (this->current == last) {\n\n return nullptr;\n\n } else {\n\n auto ret = this->current;\n\n this->current++;\n\n return ret;\n\n }\n\n }\n\n};\n\n\n\n}", "file_path": "runtime/containers/String.cpp", "rank": 56, "score": 135772.3225070207 }, { "content": "class ClassMember;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 57, "score": 132948.52021123574 }, { "content": "class ClassBody;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 58, "score": 132948.52021123574 }, { "content": "class ClassDeclaration;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 59, "score": 132948.52021123574 }, { "content": "#[test]\n\nfn test_vector() {\n\n use containers::{Ref, String};\n\n use io::Console;\n\n use memory::{Heap, Page, Region, StackBucket};\n\n let mut heap = Heap::create();\n\n let root_stack_bucket = StackBucket::create(&mut heap);\n\n let root_page = Page::get(root_stack_bucket as usize);\n\n let r = Region::create_from_page(root_page);\n\n let _r_1 = Region::create(&r);\n\n let vector = Ref::new(\n\n _r_1.page,\n\n Vector::from_raw_array(\n\n _r_1.page,\n\n &[\n\n String::from_string_slice(_r_1.page, \"using\"),\n\n String::from_string_slice(_r_1.page, \"namespace\"),\n\n String::from_string_slice(_r_1.page, \"typedef\"),\n\n ],\n\n ),\n\n );\n\n Console::write(&_r_1, vector[0]);\n\n Console::write(&_r_1, vector[1]);\n\n Console::write(&_r_1, vector[2]);\n\n}\n", "file_path": "retired/rusty/scaly/src/containers/vector.rs", "rank": 60, "score": 131527.31676273214 }, { "content": "#[test]\n\nfn test_string() {\n\n use memory::Heap;\n\n use memory::Page;\n\n use memory::StackBucket;\n\n let mut heap = Heap::create();\n\n let root_stack_bucket = StackBucket::create(&mut heap);\n\n {\n\n let root_page = Page::get(root_stack_bucket as usize);\n\n let string = String::new(root_page, \"Hello world!\");\n\n let length = string.get_length();\n\n assert_eq!(length, 12);\n\n let long_string = String::new(root_page, \"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\");\n\n assert_eq!(long_string.get_length(), 130);\n\n let c_string = long_string.to_c_string(root_page);\n\n let _string_c = String::from_c_string(root_page, c_string);\n\n\n\n let semi = String::new(root_page, \";\");\n\n let dot = String::new(root_page, \".\");\n\n assert_eq!(semi.equals(&dot), false);\n\n let semi2 = String::new(root_page, \";\");\n\n assert_eq!(semi.equals(&semi2), true);\n\n }\n\n}\n", "file_path": "retired/rusty/scaly/src/containers/string.rs", "rank": 61, "score": 131386.20799247103 }, { "content": "class Operator;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 62, "score": 129150.53234939848 }, { "content": "class Token;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 63, "score": 129150.53234939848 }, { "content": "class Identifier;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 64, "score": 129150.53234939848 }, { "content": "class Position;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 65, "score": 129150.53234939848 }, { "content": "class Punctuation;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 66, "score": 129150.53234939848 }, { "content": "class Literal;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 67, "score": 129150.53234939848 }, { "content": "struct HexToken {\n\n String value;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 68, "score": 126711.58048466335 }, { "content": "struct LiteralToken {\n\n enum {\n\n String,\n\n Fragment,\n\n Integer,\n\n Boolean,\n\n FloatingPoint,\n\n Hex,\n\n } tag;\n\n union {\n\n StringToken stringToken;\n\n FragmentToken fragmentToken;\n\n IntegerToken integerToken;\n\n BooleanToken booleanToken;\n\n FloatingPointToken floatingPointToken;\n\n HexToken hexToken;\n\n\n\n };\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 69, "score": 126711.58048466335 }, { "content": "struct ColonToken {};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 70, "score": 126711.58048466335 }, { "content": "struct FragmentToken {\n\n String value;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 71, "score": 126711.58048466335 }, { "content": "struct IntegerToken {\n\n String value;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 72, "score": 126711.58048466335 }, { "content": "struct InvalidToken {};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 73, "score": 126711.58048466335 }, { "content": "struct BooleanToken {\n\n bool value;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 74, "score": 126711.58048466335 }, { "content": "struct PunctuationToken {\n\n String sign;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 75, "score": 126711.58048466335 }, { "content": "struct IdentifierToken {\n\n String name;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 76, "score": 126711.58048466335 }, { "content": "struct AttributeToken {\n\n String name;\n\n};\n\n\n", "file_path": "compiler/Lexer.cpp", "rank": 77, "score": 126711.58048466335 }, { "content": "struct EmptyToken {};\n", "file_path": "compiler/Lexer.cpp", "rank": 78, "score": 126711.58048466335 }, { "content": "struct StringBuilder : Object {\n\n Array<char> buffer;\n\n\n\n static StringBuilder* create(Page* _rp) {\n\n return new(alignof(StringBuilder), _rp) StringBuilder {\n\n .buffer = scaly::containers::Array<char>{\n\n .length = 0,\n\n .vector = nullptr,\n\n },\n\n };\n\n }\n\n\n\n static StringBuilder* from_character(Page* _rp, char character) {\n\n auto string_builder = StringBuilder::create(_rp);\n\n string_builder->append_character(character);\n\n return string_builder;\n\n }\n\n\n\n void append_character(char character) {\n\n this->buffer.add(character);\n", "file_path": "runtime/containers/StringBuilder.cpp", "rank": 79, "score": 126637.93276601106 }, { "content": "class PostfixOperator;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 80, "score": 126195.65289667441 }, { "content": "class PrefixOperator;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 81, "score": 126195.65289667441 }, { "content": "class NumericLiteral;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 82, "score": 126195.65289667441 }, { "content": "class EofToken;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 83, "score": 126195.65289667441 }, { "content": "class InvalidToken;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 84, "score": 126195.65289667441 }, { "content": "class CharacterLiteral;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 85, "score": 126195.65289667441 }, { "content": "class BinaryOperator;\n\n\n", "file_path": "retired/scalycpp/Lexer.h", "rank": 86, "score": 126195.65289667441 }, { "content": "struct AsSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 87, "score": 125588.29116638232 }, { "content": "struct IfSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 88, "score": 125588.29116638232 }, { "content": "struct ForSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 89, "score": 125588.29116638232 }, { "content": "struct WhileSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 90, "score": 125588.29116638232 }, { "content": "struct IsSyntax; \n", "file_path": "compiler/Parser.cpp", "rank": 91, "score": 125588.29116638232 }, { "content": "class Type;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 92, "score": 125068.02203630417 }, { "content": "class Pattern;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 93, "score": 125068.02203630417 }, { "content": "class Module;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 94, "score": 125068.02203630417 }, { "content": "class Root;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 95, "score": 125068.02203630417 }, { "content": "class Pointer;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 96, "score": 125068.02203630417 }, { "content": "class Declaration;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 97, "score": 125068.02203630417 }, { "content": "class Program;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 98, "score": 125068.02203630417 }, { "content": "class Statement;\n\n\n", "file_path": "retired/scalycpp/Parser.h", "rank": 99, "score": 125068.02203630417 } ]
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 can fold over a `&T` value where `T: Fold`, in which case\n\n /// you get back a `T`, not a `&T`).\n\n type Result: Fold;\n\n\n\n /// Apply the given folder `folder` to `self`; `binders` is the\n\n /// number of binders that are in scope when beginning the\n\n /// folder. Typically `binders` starts as 0, but is adjusted when\n\n /// we encounter `Binders<T>` in the IR or other similar\n\n /// constructs.\n\n fn fold_with(&self, folder: &mut dyn Folder, binders: usize) -> Fallible<Self::Result>;\n\n}\n\n\n\nimpl<'a, T: Fold> Fold for &'a T {\n\n type Result = T::Result;\n\n fn fold_with(&self, folder: &mut dyn Folder, binders: usize) -> Fallible<Self::Result> {\n\n (**self).fold_with(folder, binders)\n", "file_path": "src/fold.rs", "rank": 0, "score": 146861.3336781139 }, { "content": " trait Foo<T> where forall<U> Self: Bar<U>, Self: Copy { }\n", "file_path": "src/rules/wf/test.rs", "rank": 1, "score": 136628.44148289156 }, { "content": " trait Foo<T> where forall<U> Self: Bar<U> { }\n", "file_path": "src/rules/wf/test.rs", "rank": 2, "score": 123664.73365742063 }, { "content": "#[bench]\n\nfn cycley_slg(b: &mut Bencher) {\n\n run_bench(\n\n CYCLEY,\n\n SolverChoice::SLG {\n\n max_size: 20,\n\n },\n\n CYCLEY_GOAL,\n\n b,\n\n \"Unique\"\n\n );\n\n}\n", "file_path": "src/solve/test/bench.rs", "rank": 3, "score": 120116.39068973047 }, { "content": "#[test]\n\nfn concrete_impl_and_blanket_impl() {\n\n lowering_success! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 4, "score": 118020.67852643065 }, { "content": "#[test]\n\nfn negation_free_vars() {\n\n test! {\n\n program {\n\n struct Vec<T> {}\n\n struct i32 {}\n\n struct u32 {}\n", "file_path": "src/solve/test.rs", "rank": 5, "score": 109169.51649122775 }, { "content": "#[test]\n\nfn two_blanket_impls() {\n\n lowering_error! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 6, "score": 109137.18241740382 }, { "content": "#[test]\n\nfn overlapping_negative_impls() {\n\n lowering_success! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 7, "score": 109137.18241740382 }, { "content": "#[test]\n\nfn negative_impl() {\n\n lowering_error! {\n\n program {\n", "file_path": "src/ir/lowering/test.rs", "rank": 8, "score": 109137.18241740382 }, { "content": "#[test]\n\nfn two_impls_for_same_type() {\n\n lowering_error! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 9, "score": 109137.18241740382 }, { "content": "#[test]\n\nfn multiple_nonoverlapping_impls() {\n\n lowering_success! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 10, "score": 109137.18241740382 }, { "content": "#[test]\n\nfn auto_trait_with_impls() {\n\n test! {\n\n program {\n\n #[auto] trait Send { }\n\n\n\n struct i32 { }\n\n struct f32 { }\n\n struct Vec<T> { }\n\n\n\n impl<T> Send for Vec<T> where T: Send { }\n\n impl !Send for i32 { }\n\n }\n\n\n\n goal {\n\n i32: Send\n\n } yields {\n\n \"No possible solution\"\n\n }\n\n\n\n goal {\n", "file_path": "src/solve/test.rs", "rank": 11, "score": 109137.18241740382 }, { "content": "#[test]\n\nfn local_impl_allowed_for_traits() {\n\n test! {\n\n program {\n\n extern trait ExternalTrait { }\n", "file_path": "src/solve/test.rs", "rank": 12, "score": 106434.17347316898 }, { "content": "#[test]\n\nfn overlapping_negative_positive_impls() {\n\n lowering_error! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 13, "score": 106434.17347316898 }, { "content": "#[test]\n\nfn auto_trait_without_impls() {\n\n test! {\n\n program {\n\n #[auto] trait Send { }\n\n\n\n struct i32 { }\n\n\n\n struct Useless<T> { }\n\n\n\n struct Data<T> {\n\n data: T\n\n }\n\n }\n\n\n\n goal {\n\n i32: Send\n\n } yields {\n\n \"Unique\"\n\n }\n\n\n", "file_path": "src/solve/test.rs", "rank": 14, "score": 106434.17347316898 }, { "content": "fn params(impl_datum: &ImplDatum) -> &[Parameter] {\n\n &impl_datum.binders.value.trait_ref.trait_ref().parameters\n\n}\n", "file_path": "src/coherence/solve.rs", "rank": 15, "score": 103995.68407315042 }, { "content": "// FIXME This should be an error\n\n// We currently assume a closed universe always, but overlaps checking should\n\n// assume an open universe - what if a client implemented both Bar and Baz\n\n//\n\n// In other words, this should have the same behavior as the two_blanket_impls\n\n// test.\n\nfn two_blanket_impls_open_ended() {\n\n lowering_success! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 16, "score": 103921.27375923013 }, { "content": "#[test]\n\nfn basic_region_constraint_from_positive_impl() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 17, "score": 101568.48593547806 }, { "content": " trait Bar<T> where forall<U> Self: Foo<T> { }\n\n\n\n impl<T, U> Foo<T> for U where U: Copy { }\n\n impl<T, U> Bar<T> for U where U: Foo<T> { }\n\n }\n\n }\n\n}\n", "file_path": "src/rules/wf/test.rs", "rank": 18, "score": 101545.06601840389 }, { "content": " trait A where Self: B, Self: Copy {}\n", "file_path": "src/rules/wf/test.rs", "rank": 19, "score": 79192.31539281245 }, { "content": " trait Debug {}\n\n struct Foo<T> {}\n\n struct Bar {}\n\n struct Baz {}\n\n\n\n impl Display for Bar {}\n\n impl Display for Baz {}\n\n\n\n impl<T> Debug for Foo<T> where T: Display {}\n\n }\n\n\n\n goal {\n\n exists<T> {\n\n T: Debug\n\n }\n\n } yields {\n\n \"Ambiguous; definite substitution for<?U0> { [?0 := Foo<?0>] }\"\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/solve/test.rs", "rank": 20, "score": 76923.77119283681 }, { "content": " trait DropOuter<'a> { type Item<U> where U: Sized; }\n\n impl<'a, T> DropOuter<'a> for T { type Item<U> = T; }\n\n\n\n struct Unit { }\n\n struct Ref<'a, T> { }\n\n }\n\n\n\n goal {\n\n forall<T> {\n\n for<'a> <Unit as DropOuter<'a>>::Item<T>: Eq<Unit>\n\n }\n\n } yields {\n\n \"No possible solution\"\n\n }\n\n\n\n goal {\n\n forall<T> {\n\n if (T: Sized) {\n\n for<'a> <Unit as DropOuter<'a>>::Item<T>: Eq<Unit>\n\n }\n", "file_path": "src/solve/test.rs", "rank": 21, "score": 73919.92217843025 }, { "content": "#[test]\n\nfn ordering() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 22, "score": 73861.87744311281 }, { "content": "fn main() {\n\n lalrpop::process_root().unwrap();\n\n}\n\n\n", "file_path": "chalk-parse/build.rs", "rank": 23, "score": 73861.87744311281 }, { "content": "#[test]\n\nfn inscope() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 24, "score": 73861.87744311281 }, { "content": "#[test]\n\n#[should_panic]\n\nfn overflow() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 25, "score": 73861.87744311281 }, { "content": "// Test that we properly detect failure even if there are applicable impls at\n\n// the top level, if we can't find anything to fill in those impls with\n\nfn deep_failure() {\n\n test! {\n\n program {\n\n struct Foo<T> {}\n", "file_path": "src/solve/test.rs", "rank": 26, "score": 72312.05063837458 }, { "content": "#[test]\n\nfn simple_negation() {\n\n test! {\n\n program {\n\n struct i32 {}\n", "file_path": "src/solve/test.rs", "rank": 27, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn clauses_in_if_goals() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 28, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn truncate_types() {\n\n let mut table = InferenceTable::new();\n\n let environment0 = &Environment::new();\n\n let _u1 = table.new_universe();\n\n\n\n // Vec<Vec<Vec<Vec<T>>>>\n\n let ty0 = ty!(apply (item 0)\n\n (apply (item 0)\n\n (apply (item 0)\n\n (apply (item 0)\n\n (apply (skol 1))))));\n\n\n\n // test: no truncation with size 5\n\n let Truncated {\n\n overflow,\n\n value: ty_no_overflow,\n\n } = truncate(&mut table, 5, &ty0);\n\n assert!(!overflow);\n\n assert_eq!(ty0, ty_no_overflow);\n\n\n", "file_path": "src/solve/truncate.rs", "rank": 29, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn normalize_gat1() {\n\n test! {\n\n program {\n\n struct Vec<T> { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 30, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn truncate_normalizes() {\n\n let mut table = InferenceTable::new();\n\n\n\n let environment0 = &Environment::new();\n\n let u1 = table.new_universe();\n\n\n\n // ty0 = Vec<Vec<X>>\n\n let v0 = table.new_variable(u1);\n\n let ty0 = ty!(apply (item 0)\n\n (apply (item 0)\n\n (var 0)));\n\n\n\n // ty1 = Vec<Vec<T>>\n\n let ty1 = ty!(apply (item 0)\n\n (apply (item 0)\n\n (apply (skol 1))));\n\n\n\n // test: truncating *before* unifying has no effect\n\n assert!(!truncate(&mut table, 3, &ty0).overflow);\n\n\n", "file_path": "src/solve/truncate.rs", "rank": 31, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn overflow_universe() {\n\n test! {\n\n program {\n\n struct Foo { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 32, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn cycle_no_solution() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 33, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn struct_wf() {\n\n test! {\n\n program {\n\n struct Foo<T> where T: Eq { }\n\n struct Bar { }\n\n struct Baz { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 34, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn partial_overlap_3() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 35, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn forall_equality() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 36, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn coinductive_semantics() {\n\n test! {\n\n program {\n\n #[auto] trait Send { }\n\n\n\n struct i32 { }\n\n\n\n struct Ptr<T> { }\n\n impl<T> Send for Ptr<T> where T: Send { }\n\n\n\n struct List<T> {\n\n data: T,\n\n next: Ptr<List<T>>\n\n }\n\n }\n\n\n\n goal {\n\n forall<T> {\n\n List<T>: Send\n\n }\n", "file_path": "src/solve/test.rs", "rank": 37, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn infer() {\n\n let mut table = InferenceTable::new();\n\n let environment0 = Environment::new();\n\n let a = table.new_variable(U0).to_ty();\n\n let b = table.new_variable(U0).to_ty();\n\n table\n\n .unify(&environment0, &a, &ty!(apply (item 0) (expr b)))\n\n .unwrap();\n\n assert_eq!(table.normalize(&a), ty!(apply (item 0) (expr b)));\n\n table\n\n .unify(&environment0, &b, &ty!(apply (item 1)))\n\n .unwrap();\n\n assert_eq!(table.normalize(&a), ty!(apply (item 0) (apply (item 1))));\n\n}\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 38, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn multiple_parameters() {\n\n lowering_error! {\n\n program {\n", "file_path": "src/coherence/test.rs", "rank": 39, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn negation_quantifiers() {\n\n test! {\n\n program {\n\n struct i32 {}\n\n struct u32 {}\n\n }\n\n\n\n goal {\n\n not {\n\n forall<T, U> {\n\n T = U\n\n }\n\n }\n\n } yields {\n\n \"Unique\"\n\n }\n\n\n\n goal {\n\n not {\n\n exists<T, U> {\n", "file_path": "src/solve/test.rs", "rank": 40, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn projection_from_env() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 41, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn flounder() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 42, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn deep_negation() {\n\n test! {\n\n program {\n\n struct Foo<T> {}\n", "file_path": "src/solve/test.rs", "rank": 43, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn where_clause_trumps() {\n\n test! {\n\n program {\n\n struct Foo { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 44, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn prove_clone() {\n\n test! {\n\n program {\n\n struct Foo { }\n\n struct Bar { }\n\n struct Vec<T> { }\n", "file_path": "src/solve/test.rs", "rank": 45, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn deref_goal() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 46, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn inner_cycle() {\n\n // Interesting test that shows why recursive solver needs to run\n\n // to an inner fixed point during iteration. Here, the first\n\n // round, we get that `?T: A` has a unique sol'n `?T = i32`. On\n\n // the second round, we ought to get ambiguous: but if we don't\n\n // run the `?T: B` to a fixed point, it will terminate with `?T =\n\n // i32`, leading to an (incorrect) unique solution.\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 47, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn implied_bounds() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 48, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn contradiction() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 49, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn unselected_projection() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 50, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn prove_forall() {\n\n test! {\n\n program {\n\n struct Foo { }\n\n struct Vec<T> { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 51, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn mixed_semantics() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 52, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn not_trait() {\n\n lowering_error! {\n\n program {\n\n struct Foo { }\n", "file_path": "src/ir/lowering/test.rs", "rank": 53, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn partial_overlap_1() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 54, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn partial_overlap_2() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 55, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn definite_guidance() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 56, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn quantified_types() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 57, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn fundamental_types() {\n\n // NOTE: These tests need to have both Internal and External structs since chalk will attempt\n\n // to enumerate all of them.\n\n\n\n // This first test is a sanity check to make sure `Box` isn't a special case.\n\n // By testing this, we ensure that adding the #[fundamental] attribute does in fact\n\n // change behaviour\n\n test! {\n\n program {\n\n extern struct Box<T> { }\n\n\n\n extern struct External { }\n\n struct Internal { }\n\n }\n\n\n\n // Without fundamental, Box should behave like a regular extern type\n\n goal { forall<T> { not { IsLocal(Box<T>) } } } yields { \"Unique\" }\n\n goal { forall<T> { IsLocal(Box<T>) } } yields { \"No possible solution\" }\n\n goal { forall<T> { IsExternal(Box<T>) } } yields { \"Unique\" }\n\n goal { forall<T> { IsDeeplyExternal(Box<T>) } } yields { \"No possible solution\" }\n", "file_path": "src/solve/test.rs", "rank": 58, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn region_equality() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 59, "score": 72307.0217159586 }, { "content": "// Test that we infer a unique solution even if it requires multiple levels of\n\n// search to do so\n\nfn deep_success() {\n\n test! {\n\n program {\n\n struct Foo<T> {}\n\n struct ImplsBaz {}\n", "file_path": "src/solve/test.rs", "rank": 60, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn forall_projection() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 61, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn higher_ranked() {\n\n test! {\n\n program {\n\n struct u8 { }\n\n struct SomeType<T> { }\n", "file_path": "src/solve/test.rs", "rank": 62, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn equality_binder() {\n\n test! {\n\n program {\n\n struct Ref<'a, T> { }\n\n }\n\n\n\n // Check that `'a` (here, `'?0`) is not unified\n\n // with `'!1`, because they belong to incompatible\n\n // universes.\n\n goal {\n\n forall<T> {\n\n exists<'a> {\n\n for<'c> Ref<'c, T> = Ref<'a, T>\n\n }\n\n }\n\n } yields {\n\n \"Unique; for<?U1> { \\\n\n substitution [?0 := '?0], \\\n\n lifetime constraints [InEnvironment { environment: Env([]), goal: '!2 == '?0 }] \\\n\n }\"\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/solve/test.rs", "rank": 63, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn normalize_under_binder() {\n\n test! {\n\n program {\n\n struct Ref<'a, T> { }\n\n struct I32 { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 64, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn normalize_basic() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 65, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn generic_trait() {\n\n test! {\n\n program {\n\n struct Int { }\n\n struct Uint { }\n\n\n", "file_path": "src/solve/test.rs", "rank": 66, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn prove_infer() {\n\n test! {\n\n program {\n\n struct Foo { }\n\n struct Bar { }\n", "file_path": "src/solve/test.rs", "rank": 67, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn normalize_gat2() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 68, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn suggested_subst() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 69, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn basic() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 70, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn implied_from_env() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 71, "score": 72307.0217159586 }, { "content": "#[test]\n\nfn cached_answers_2() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 72, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn cached_answers_1() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 73, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn quantify_bound() {\n\n let mut table = make_table();\n\n let environment0 = Environment::new();\n\n\n\n let v0 = table.new_variable(U0).to_ty();\n\n let v1 = table.new_variable(U1).to_ty();\n\n let v2a = table.new_variable(U2).to_ty();\n\n let v2b = table.new_variable(U2).to_ty();\n\n\n\n table\n\n .unify(\n\n &environment0,\n\n &v2b,\n\n &ty!(apply (item 1) (expr v1) (expr v0)),\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(\n\n table\n\n .canonicalize(&ty!(apply (item 0) (expr v2b) (expr v2a) (expr v1) (expr v0)))\n", "file_path": "src/solve/infer/test.rs", "rank": 74, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn universe_promote() {\n\n // exists(A -> forall(X -> exists(B -> A = foo(B), A = foo(i32)))) ---> OK\n\n let mut table = InferenceTable::new();\n\n let environment0 = Environment::new();\n\n let a = table.new_variable(U0).to_ty();\n\n let b = table.new_variable(U1).to_ty();\n\n table\n\n .unify(&environment0, &a, &ty!(apply (item 0) (expr b)))\n\n .unwrap();\n\n table\n\n .unify(&environment0, &a, &ty!(apply (item 0) (apply (item 1))))\n\n .unwrap();\n\n}\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 75, "score": 70867.2762356716 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn example_2_1_EWFS() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 76, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn universe_error() {\n\n // exists(A -> forall(X -> A = X)) ---> error\n\n let mut table = InferenceTable::new();\n\n let environment0 = Environment::new();\n\n let a = table.new_variable(U0).to_ty();\n\n table\n\n .unify(&environment0, &a, &ty!(apply (skol 1)))\n\n .unwrap_err();\n\n}\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 77, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn cycle_error() {\n\n // exists(A -> A = foo A) ---> error\n\n let mut table = InferenceTable::new();\n\n let environment0 = Environment::new();\n\n let a = table.new_variable(U0).to_ty();\n\n table\n\n .unify(&environment0, &a, &ty!(apply (item 0) (expr a)))\n\n .unwrap_err();\n\n\n\n // exists(A -> A = for<'a> A)\n\n table\n\n .unify(&environment0, &a, &ty!(for_all 1 (var 1)))\n\n .unwrap_err();\n\n}\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 78, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn subgoal_abstraction() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 79, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn cycle_many_solutions() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 80, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn cached_answers_3() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 81, "score": 70867.2762356716 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn example_2_3_EWFS() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 82, "score": 70867.2762356716 }, { "content": "fn run_bench(\n\n program_text: &str,\n\n solver_choice: SolverChoice,\n\n goal_text: &str,\n\n bencher: &mut Bencher,\n\n expected: &str\n\n) {\n\n let program = Arc::new(parse_and_lower_program(program_text, solver_choice).unwrap());\n\n let env = Arc::new(program.environment());\n\n ir::tls::set_current_program(&program, || {\n\n let goal = parse_and_lower_goal(&program, goal_text).unwrap();\n\n let peeled_goal = goal.into_peeled_goal();\n\n\n\n // Execute once to get an expected result.\n\n let result = solver_choice.solve_root_goal(&env, &peeled_goal);\n\n\n\n // Check expectation.\n\n assert_result(&result, expected);\n\n\n\n // Then do it many times to measure time.\n\n bencher.iter(|| solver_choice.solve_root_goal(&env, &peeled_goal));\n\n });\n\n}\n\n\n\nconst CYCLEY: &str = \"\n", "file_path": "src/solve/test/bench.rs", "rank": 83, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn projection_eq() {\n\n // exists(A -> A = Item0<<A as Item1>::foo>)\n\n // ^^^^^^^^^^^^ Can A repeat here? For now,\n\n // we say no, but it's an interesting question.\n\n let mut table = InferenceTable::new();\n\n let environment0 = Environment::new();\n\n let a = table.new_variable(U0).to_ty();\n\n\n\n // expect an error (\"cycle during unification\")\n\n table\n\n .unify(\n\n &environment0,\n\n &a,\n\n &ty!(apply (item 0) (projection (item 1) (expr a))),\n\n )\n\n .unwrap_err();\n\n}\n\n\n\nconst U0: UniverseIndex = UniverseIndex { counter: 0 };\n\nconst U1: UniverseIndex = UniverseIndex { counter: 1 };\n\nconst U2: UniverseIndex = UniverseIndex { counter: 2 };\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 84, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn cycle_unique_solution() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 85, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn infinite_recursion() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 86, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn negative_loop() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 87, "score": 70867.2762356716 }, { "content": "/// Helper function\n\nfn into_ex_clause(\n\n result: UnificationResult,\n\n ex_clause: &mut ExClause<SlgContext>,\n\n) {\n\n ex_clause\n\n .subgoals\n\n .extend(result.goals.into_iter().casted().map(Literal::Positive));\n\n ex_clause.constraints.extend(result.constraints);\n\n}\n\n\n\nimpl Substitution {\n\n fn may_invalidate(&self, subst: &Canonical<Substitution>) -> bool {\n\n self.parameters\n\n .iter()\n\n .zip(&subst.value.parameters)\n\n .any(|(new, current)| MayInvalidate.aggregate_parameters(new, current))\n\n }\n\n}\n\n\n", "file_path": "src/solve/slg/implementation.rs", "rank": 88, "score": 70867.2762356716 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn example_2_2_EWFS() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 89, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn only_draw_so_many() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 90, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn multiple_ambiguous_cycles() {\n\n test! {\n\n program {\n", "file_path": "src/solve/test.rs", "rank": 91, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn cycle_indirect() {\n\n // exists(A -> A = foo B, A = B) ---> error\n\n let mut table = InferenceTable::new();\n\n let environment0 = Environment::new();\n\n let a = table.new_variable(U0).to_ty();\n\n let b = table.new_variable(U0).to_ty();\n\n table\n\n .unify(&environment0, &a, &ty!(apply (item 0) (expr b)))\n\n .unwrap();\n\n table.unify(&environment0, &a, &b).unwrap_err();\n\n}\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 92, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn breadth_first() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 93, "score": 70867.2762356716 }, { "content": "#[test]\n\nfn quantify_simple() {\n\n let mut table = make_table();\n\n let _ = table.new_variable(U0);\n\n let _ = table.new_variable(U1);\n\n let _ = table.new_variable(U2);\n\n\n\n assert_eq!(\n\n table\n\n .canonicalize(&ty!(apply (item 0) (var 2) (var 1) (var 0)))\n\n .quantified,\n\n Canonical {\n\n value: ty!(apply (item 0) (var 0) (var 1) (var 2)),\n\n binders: vec![\n\n ParameterKind::Ty(U2),\n\n ParameterKind::Ty(U1),\n\n ParameterKind::Ty(U0),\n\n ],\n\n }\n\n );\n\n}\n\n\n", "file_path": "src/solve/infer/test.rs", "rank": 94, "score": 70867.2762356716 }, { "content": "#[test]\n\n#[allow(non_snake_case)]\n\nfn example_3_3_EWFS() {\n\n test! {\n\n program {\n", "file_path": "src/solve/slg/test.rs", "rank": 95, "score": 70867.2762356716 }, { "content": "use fallible::*;\n\nuse fold::{DefaultTypeFolder, Fold, IdentityExistentialFolder, UniversalFolder};\n\nuse ir::*;\n\n\n\nuse super::InferenceTable;\n\n\n\nimpl InferenceTable {\n\n crate fn u_canonicalize<T: Fold>(&mut self, value0: &Canonical<T>) -> UCanonicalized<T::Result> {\n\n debug!(\"u_canonicalize({:#?})\", value0);\n\n\n\n // First, find all the universes that appear in `value`.\n\n let mut universes = UniverseMap::new();\n\n value0\n\n .value\n\n .fold_with(\n\n &mut UCollector {\n\n universes: &mut universes,\n\n },\n\n 0,\n\n )\n", "file_path": "src/solve/infer/ucanonicalize.rs", "rank": 97, "score": 30.402465966966243 }, { "content": "use cast::Cast;\n\nuse fallible::*;\n\nuse fold::{DefaultTypeFolder, ExistentialFolder, Fold, UniversalFolder};\n\nuse std::sync::Arc;\n\nuse zip::{Zip, Zipper};\n\n\n\nuse super::*;\n\nuse super::var::*;\n\n\n\nimpl InferenceTable {\n\n crate fn unify<T>(\n\n &mut self,\n\n environment: &Arc<Environment>,\n\n a: &T,\n\n b: &T,\n\n ) -> Fallible<UnificationResult>\n\n where\n\n T: ?Sized + Zip,\n\n {\n\n debug_heading!(\n", "file_path": "src/solve/infer/unify.rs", "rank": 98, "score": 27.551156041359956 }, { "content": " binders: self_binders.clone(),\n\n value: value,\n\n })\n\n }\n\n}\n\n\n\nimpl Fold for Lifetime {\n\n type Result = Self;\n\n fn fold_with(&self, folder: &mut dyn Folder, binders: usize) -> Fallible<Self::Result> {\n\n folder.fold_lifetime(self, binders)\n\n }\n\n}\n\n\n\ncrate fn super_fold_lifetime(\n\n folder: &mut dyn Folder,\n\n lifetime: &Lifetime,\n\n binders: usize,\n\n) -> Fallible<Lifetime> {\n\n match *lifetime {\n\n Lifetime::Var(depth) => if depth >= binders {\n", "file_path": "src/fold.rs", "rank": 99, "score": 27.400964979972027 } ]
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 )\n\n}\n\n\n\nimpl ControllerOverseer {\n\n fn replace_last_stack(\n\n &mut self,\n\n stack: &[FxIndexMap<Token, FrameData>],\n\n ) -> Arc<[FxIndexMap<Token, FrameData>]> {\n\n let last: Arc<[_]> = stack.into();\n", "file_path": "src/controller.rs", "rank": 1, "score": 71457.7059699306 }, { "content": "#[test]\n\nfn mix() {\n\n let source = include_str!(\"fortytwo.badder\");\n\n let ast = Parser::parse_str(source).expect(\"parse\");\n\n let result = Interpreter::default().evaluate(&ast).expect(\"interpret\");\n\n assert_eq!(result, 42);\n\n}\n", "file_path": "tests/mix.rs", "rank": 3, "score": 58180.00712503105 }, { "content": "#[test]\n\nfn src_ordering() {\n\n assert!(SourceRef((1, 2), (1, 3)) < SourceRef((2, 2), (2, 3)));\n\n assert!(SourceRef((1, 2), (1, 3)) < SourceRef((1, 3), (1, 4)));\n\n assert!(SourceRef((1, 2), (1, 3)) < SourceRef((1, 2), (1, 4)));\n\n assert!(SourceRef((1, 2), (1, 3)) < SourceRef((1, 2), (2, 0)));\n\n}\n", "file_path": "src/common.rs", "rank": 5, "score": 49307.49390482284 }, { "content": "fn convert_signed_index(mut i: i32, length: usize) -> usize {\n\n if length == 0 {\n\n return max(i, 0) as usize;\n\n }\n\n\n\n let len = length as i32;\n\n if i < 0 {\n\n i = (len + i % len) % len;\n\n }\n\n i as usize\n\n}\n\n\n\nimpl Default for Interpreter<NoOverseer> {\n\n fn default() -> Interpreter<NoOverseer> {\n\n Interpreter::new(50, NoOverseer)\n\n }\n\n}\n\n\n\nimpl<O: Overseer> Interpreter<O> {\n\n pub fn new(max_stack_len: usize, overseer: O) -> Interpreter<O> {\n", "file_path": "src/lib.rs", "rank": 7, "score": 44576.21869999577 }, { "content": "#[inline]\n\nfn junkspace(c: char) -> bool {\n\n c.is_whitespace() && c != '\\n'\n\n}\n\n\n\nimpl<'a> Lexer<'a> {\n\n pub fn new(code: &'a str) -> Lexer<'a> {\n\n let mut chars = code.chars().peekable();\n\n let first = chars.next();\n\n Lexer {\n\n chars,\n\n current_char: first,\n\n newline: true,\n\n line_num: 1,\n\n char_num: 1,\n\n }\n\n }\n\n\n\n fn next_char(&mut self) -> Option<char> {\n\n self.newline = self.current_char == Some('\\n');\n\n self.current_char = self.chars.next();\n", "file_path": "src/lexer.rs", "rank": 8, "score": 36535.48502237799 }, { "content": "#[inline]\n\nfn bool_to_num(b: bool) -> Int {\n\n if b {\n\n 1\n\n } else {\n\n 0\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 9, "score": 34326.589045626104 }, { "content": "#[inline]\n\nfn id_char(c: char) -> bool {\n\n c.is_alphanumeric() || c == '_'\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 10, "score": 34326.589045626104 }, { "content": "#[inline]\n\nfn id_to_seq_id(id: &Token) -> Token {\n\n match *id {\n\n Id(ref id) => Id((id.to_string() + \"[]\").into()),\n\n _ => panic!(\"id_to_seq_id() called on non-Id token\"),\n\n }\n\n}\n\n\n\n/// A token that's allowed that wouldn't normaly be\n", "file_path": "src/parser.rs", "rank": 11, "score": 30707.429119362278 }, { "content": "use badder_lang::*;\n\n\n\n#[test]\n", "file_path": "tests/mix.rs", "rank": 19, "score": 26725.153577413323 }, { "content": "fn parent_error<T, S: Into<String>>(desc: S) -> Result<T, InterpreterUpFlow> {\n\n Err(Error(\n\n BadderError::at(UNKNOWN_SRC_REF).describe(Stage::Interpreter, desc.into()),\n\n ))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 24, "score": 22367.087735708345 }, { "content": " src = SourceRef((5, 13), (5, 14))\n\n );\n\n\n\n // `else`\n\n let ast = next.expect(\"else\");\n\n let ast = *expect_ast!(ast = Ast::Line(0, ast, ..), src = SourceRef((6, 1), (6, 5)));\n\n let (_, _, next) = expect_if_ast!(ast, src = SourceRef((6, 1), (6, 5)));\n\n assert_eq!(next, None);\n\n }\n\n\n\n #[test]\n\n fn fun_src_ref() {\n\n let _ = env_logger::try_init();\n\n\n\n let ast = Parser::parse_str(\n\n &vec![\n\n \"fun double(x)\",\n\n \" return x * 2 # used return to test it, also this comment\",\n\n \"double(2.double())\",\n\n ]\n", "file_path": "src/parser.rs", "rank": 25, "score": 14594.337322783458 }, { "content": " }};\n\n }\n\n\n\n #[test]\n\n fn seq_src_ref() {\n\n let _ = env_logger::try_init();\n\n\n\n let mut ast = Parser::parse_str(\"seq some_id[] = 1345, 2\").unwrap();\n\n\n\n ast = *expect_ast!(\n\n ast = Ast::Line(0, ast, ..),\n\n src = SourceRef((1, 1), (1, 24))\n\n );\n\n ast = *expect_ast!(\n\n ast = Ast::AssignSeq(_, ast, ..),\n\n src = SourceRef((1, 1), (1, 24))\n\n );\n\n let seq_ast: Vec<Ast> =\n\n expect_ast!(ast = Ast::Seq(ast, ..), src = SourceRef((1, 17), (1, 24)));\n\n\n", "file_path": "src/parser.rs", "rank": 26, "score": 14593.263000379542 }, { "content": "\n\n// reproductions of encountered issues/bugs\n\n#[cfg(test)]\n\nmod issues {\n\n use super::*;\n\n\n\n #[test]\n\n fn variable_in_funtion_loop() {\n\n assert_program!(\"fun some_func()\";\n\n \" var count\";\n\n \" for i in 1,2,3\";\n\n \" count += i\";\n\n \" count\";\n\n \"loop\";\n\n \" if 1\";\n\n \" some_func()\";\n\n \" break\";\n\n \"1\" => 1);\n\n }\n\n\n", "file_path": "src/lib.rs", "rank": 27, "score": 14593.206775165958 }, { "content": " /// Modifies the pause time, the duration the interpreter will block for\n\n /// before non-trivial AST interpretation waiting for a #unpause() or #cancel() call\n\n /// after the duration execution will continue automatically\n\n pub fn set_pause_duration(&mut self, pause_time: Duration) {\n\n self.pause_time = pause_time;\n\n // ignore errors to allow setting pause_time before execution\n\n let _ = self.overseer_pause.update(self.pause_time);\n\n }\n\n\n\n pub fn pause_duration(&self) -> Duration {\n\n self.pause_time\n\n }\n\n\n\n /// Unblocks current waiting phase's execution, if it is blocked.\n\n /// Requires a recent (in terms of set pause_time) call to #refresh() to be valid\n\n pub fn unpause(&mut self) {\n\n if let Some(Phase {\n\n id,\n\n unpaused: false,\n\n ..\n", "file_path": "src/controller.rs", "rank": 28, "score": 14592.885638111835 }, { "content": " _ => (),\n\n }\n\n recv = self.from_controller.try_recv();\n\n }\n\n\n\n let pause_time = *self.pause_time.latest();\n\n if send_time.elapsed() >= pause_time {\n\n Ok(())\n\n } else {\n\n // block until result received\n\n debug!(\"ControllerOverseer waiting: {:?} {:?}\", ast.src(), ast);\n\n\n\n let mut elapsed = send_time.elapsed();\n\n while elapsed < pause_time {\n\n match self.from_controller.recv_timeout(pause_time - elapsed) {\n\n Ok(Ok(i)) => {\n\n if i == id {\n\n return Ok(());\n\n }\n\n }\n", "file_path": "src/controller.rs", "rank": 29, "score": 14592.66883377875 }, { "content": " assert_eq!(seq_ast.len(), 2);\n\n assert_src_eq!(seq_ast[0], SourceRef((1, 25), (1, 29)));\n\n assert_src_eq!(seq_ast[1], SourceRef((1, 31), (1, 32)));\n\n }\n\n\n\n #[test]\n\n fn assign_var() {\n\n let _ = env_logger::try_init();\n\n\n\n let ast = Parser::parse_str(&vec![\"var abc\", \"var bcd\"].join(\"\\n\")).unwrap();\n\n\n\n let (ast, next) = expect_line_pair!(ast);\n\n\n\n // `var abc`\n\n let ast = *expect_ast!(ast = Ast::Line(0, ast, ..), src = SourceRef((1, 1), (1, 8)));\n\n let ast = *expect_ast!(\n\n ast = Ast::Assign(_, ast, ..),\n\n src = SourceRef((1, 1), (1, 8))\n\n );\n\n expect_ast!(ast = Ast::Num(ast, ..), src = SourceRef((1, 1), (1, 8)));\n", "file_path": "src/parser.rs", "rank": 30, "score": 14592.168068834355 }, { "content": "\n\n // `var bcd`\n\n let ast = *expect_ast!(\n\n next = Ast::Line(0, next, ..),\n\n src = SourceRef((2, 1), (2, 8))\n\n );\n\n let ast = *expect_ast!(\n\n ast = Ast::Assign(_, ast, ..),\n\n src = SourceRef((2, 1), (2, 8))\n\n );\n\n expect_ast!(ast = Ast::Num(ast, ..), src = SourceRef((2, 1), (2, 8)));\n\n }\n\n\n\n #[test]\n\n fn if_else_src_ref() {\n\n let _ = env_logger::try_init();\n\n\n\n let ast = Parser::parse_str(\n\n &vec![\n\n \"var a = 123\",\n", "file_path": "src/parser.rs", "rank": 31, "score": 14591.506351284037 }, { "content": "impl ExternalCall {\n\n pub fn id_str(&self) -> &str {\n\n match self.id {\n\n Token::Id(ref s) => s,\n\n _ => unreachable!(),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Default)]\n\npub struct RunStats {\n\n /// source_ref -> evaluation count\n\n pub eval_counts: IndexMap<SourceRef, usize>,\n\n last_phase: Option<u64>,\n\n}\n\n\n\nimpl RunStats {\n\n fn consider(&mut self, phase: &Phase) {\n\n if phase.kind != PhaseKind::Assignment {\n\n if let Some(id) = self.last_phase {\n", "file_path": "src/controller.rs", "rank": 32, "score": 14591.085834839616 }, { "content": " if id != phase.id {\n\n *(self.eval_counts.entry(phase.src).or_insert(0)) += 1;\n\n }\n\n } else {\n\n *(self.eval_counts.entry(phase.src).or_insert(0)) += 1;\n\n }\n\n\n\n self.last_phase = Some(phase.id);\n\n }\n\n }\n\n}\n", "file_path": "src/controller.rs", "rank": 33, "score": 14590.87603541665 }, { "content": "\n\n fn lines_while<F>(&mut self, predicate: F) -> Res<Option<Ast>>\n\n where\n\n F: Fn(&Ast) -> bool,\n\n {\n\n self.lines_while_allowing(0, predicate, &vec![].into())\n\n }\n\n\n\n pub fn parse(&mut self) -> Res<Ast> {\n\n let lines = self.lines_while(|_| true)?;\n\n Ok(lines.unwrap_or(Ast::Empty(self.current_src_ref)))\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct AssignId {\n\n pub id: SmolStr,\n\n pub kind: AssignIdKind,\n\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n", "file_path": "src/parser.rs", "rank": 34, "score": 14590.721203573783 }, { "content": " )\n\n } else {\n\n let src = src.up_to(self.current_src_ref);\n\n Ast::AssignSeq(seq_id, Ast::Seq(vec![], src).into(), src)\n\n })\n\n }\n\n\n\n fn line_expr(&mut self, scope: usize, guests: Rc<[TokenGuest]>) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n\n\n if guests.allow(&self.current_token, scope) {\n\n if let Some(token) = self.consume_any_maybe(&[Break, Continue])? {\n\n return Ok(Ast::LoopNav(token, src));\n\n }\n\n if self.consume_maybe(Return)?.is_some() {\n\n let expr = {\n\n if self.consume_maybe(Eol)?.is_none() {\n\n let return_expr = self.expr()?;\n\n self.consume(Eol)?;\n\n return_expr\n", "file_path": "src/parser.rs", "rank": 35, "score": 14590.093359480352 }, { "content": " \"var out\";\n\n \"if 1\";\n\n \" fun number(b, c)\";\n\n \" b + c\";\n\n \" out = number(2)\";\n\n \"out\" => 2);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod loops {\n\n use super::*;\n\n\n\n #[test]\n\n fn loop_and_break() {\n\n assert_program!(\"var x = 1\";\n\n \"loop\";\n\n \" x *= 2\";\n\n \" if x > 10\";\n\n \" break\";\n", "file_path": "src/lib.rs", "rank": 36, "score": 14590.083781164858 }, { "content": " Ast::ForIn(ref idx_id, ref item_id, ref list_expr, ref block, src) => self.eval_for_in(\n\n idx_id,\n\n item_id,\n\n list_expr,\n\n block,\n\n src,\n\n current_scope,\n\n stack_key,\n\n ),\n\n Ast::LoopNav(ref token, ..) => {\n\n let loop_token = Id(\"#loop\".into());\n\n if highest_frame_idx!(&loop_token).is_some() {\n\n match *token {\n\n Break => Err(LoopBreak),\n\n Continue => Err(LoopContinue),\n\n _ => parent_error(format!(\"Unknown loop nav `{:?}`\", token)),\n\n }\n\n } else {\n\n parent_error(format!(\"Invalid use of loop nav `{:?}`\", token))\n\n }\n", "file_path": "src/lib.rs", "rank": 37, "score": 14590.039377428911 }, { "content": " if let Some(line) = self.unused_lines.pop() {\n\n // must match scope, otherwise could be a valid else for a parent if\n\n if line.is_else_line() && line.line_scope() == Some(scope) {\n\n return Ok(Ast::if_else(expr, block.unwrap(), line, is_else, src));\n\n }\n\n self.unused_lines.push(line);\n\n }\n\n Ok(Ast::just_if(expr, block.unwrap(), is_else, src))\n\n }\n\n\n\n // loop\n\n // line+\n\n fn line_loop(&mut self, scope: usize, guests: Rc<[TokenGuest]>) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n let (while_expr, for_stuff) = {\n\n if self.consume_maybe(While)?.is_some() {\n\n (self.expr()?, None)\n\n } else if self.consume_maybe(For)?.is_some() {\n\n let mut idx_id = Some(self.consume(ID_TOKEN)?);\n\n let item_id = match self.consume_maybe(Comma)? {\n", "file_path": "src/parser.rs", "rank": 38, "score": 14589.958958137615 }, { "content": "\n\n let mut src = self.current_src_ref;\n\n let mut scope = 0;\n\n while let Some(token) = self.consume_any_maybe(&[Eol, Indent(0)])? {\n\n match token {\n\n Indent(x) => scope = x,\n\n Eol => {\n\n scope = 0;\n\n src = self.current_src_ref;\n\n } // reset scope, and skip empty lines\n\n _ => unreachable!(),\n\n };\n\n }\n\n Ok(match self.line_expr(scope, allow)? {\n\n Ast::Empty(s) => Ast::Empty(s),\n\n ast => {\n\n let ast_src = ast.src();\n\n Ast::Line(scope, ast.into(), src.up_to_end_of(ast_src))\n\n }\n\n })\n", "file_path": "src/parser.rs", "rank": 39, "score": 14589.886939413213 }, { "content": " Err(err) => Err(err),\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[macro_use]\n\nmod util {\n\n use super::*;\n\n use std::{\n\n sync::mpsc,\n\n thread,\n\n time::{Duration, Instant},\n\n };\n\n\n\n fn eval_within(code: &str, timeout: Duration) -> Res<Int> {\n\n let (sender, receiver) = mpsc::channel();\n\n let before_parse = Instant::now();\n\n debug!(\"parsing...\");\n\n let code: Ast = Parser::parse_str(code)?;\n", "file_path": "src/lib.rs", "rank": 40, "score": 14589.872330012926 }, { "content": " Not,\n\n self.compared()?.into(),\n\n src.up_to_end_of(self.current_src_ref),\n\n ))\n\n } else {\n\n self.compared()\n\n }\n\n }\n\n\n\n fn anded(&mut self) -> Res<Ast> {\n\n let mut out = self.inversed()?;\n\n while self.consume_maybe(And)?.is_some() {\n\n out = Ast::bin_op(And, out, self.inversed()?);\n\n out.validate_bin_op()?;\n\n }\n\n Ok(out)\n\n }\n\n\n\n fn ored(&mut self) -> Res<Ast> {\n\n let mut out = self.anded()?;\n", "file_path": "src/parser.rs", "rank": 41, "score": 14589.760058343132 }, { "content": " self.current_src_ref = src_ref;\n\n\n\n self.previous_token = Some(token);\n\n Ok(&self.current_token)\n\n }\n\n\n\n fn parse_fail_help(&self) -> Option<Cow<'static, str>> {\n\n let prev_help: Option<Cow<'static, str>> = match (&self.previous_token, &self.current_token)\n\n {\n\n (&Some(Pls), &Pls) => Some(\"`++` is not an operator, did you mean `+= 1`?\".into()),\n\n (&Some(Is), &Is) => Some(\"try using just `is`, without stammering.\".into()),\n\n (&Some(Is), token) if token.is_binary_op() => {\n\n Some(format!(\"try using just `is` or `{:?}`.\", token).into())\n\n }\n\n _ => None,\n\n };\n\n\n\n if prev_help.is_some() {\n\n return prev_help;\n\n }\n", "file_path": "src/parser.rs", "rank": 42, "score": 14589.731807738706 }, { "content": " fn compared(&mut self) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n let mut out = self.added()?;\n\n if self.consume_maybe(Is)?.is_some() {\n\n if self.consume_maybe(Not)?.is_some() {\n\n let is = Ast::bin_op(Is, out, self.added()?);\n\n out = Ast::LeftUnaryOp(Not, is.into(), src.up_to_end_of(self.current_src_ref));\n\n } else {\n\n out = Ast::bin_op(Is, out, self.added()?);\n\n }\n\n } else if let Some(token) = self.consume_any_maybe(&[Gt, Lt, GtEq, LtEq])? {\n\n out = Ast::bin_op(token, out, self.added()?);\n\n }\n\n Ok(out)\n\n }\n\n\n\n fn inversed(&mut self) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n if self.consume_maybe(Not)?.is_some() {\n\n Ok(Ast::LeftUnaryOp(\n", "file_path": "src/parser.rs", "rank": 43, "score": 14589.660649013491 }, { "content": " pub fn src(&self) -> SourceRef {\n\n use crate::Ast::*;\n\n match *self {\n\n Num(.., src)\n\n | BinOp(.., src)\n\n | LeftUnaryOp(.., src)\n\n | Assign(.., src)\n\n | Reassign(.., src)\n\n | Refer(.., src)\n\n | If(.., src)\n\n | While(.., src)\n\n | ForIn(.., src)\n\n | LoopNav(.., src)\n\n | AssignFun(.., src)\n\n | Return(.., src)\n\n | Call(.., src)\n\n | Seq(.., src)\n\n | AssignSeq(.., src)\n\n | ReferSeq(.., src)\n\n | ReferSeqIndex(.., src)\n", "file_path": "src/parser.rs", "rank": 44, "score": 14589.63305653103 }, { "content": " ]\n\n .join(\"\\n\"),\n\n )\n\n .expect_err(\"parse\");\n\n\n\n println!(\"Got error: {:?}\", err);\n\n\n\n assert_eq!(err.src, SourceRef((3, 4), (3, 24)));\n\n assert!(err.description.contains(\"var do_scan = \"));\n\n assert!(err.description.contains(\"do_scan is 1 or do_scan is 2\"));\n\n }\n\n}\n\n\n\n// reproductions of encountered issues/bugs\n\n#[cfg(test)]\n\nmod issues {\n\n use super::*;\n\n\n\n #[test]\n\n fn else_after_var() {\n", "file_path": "src/parser.rs", "rank": 45, "score": 14589.030566666552 }, { "content": " let ast = *expect_ast!(\n\n next = Ast::Line(0, next, ..),\n\n src = SourceRef((3, 1), (3, 19))\n\n );\n\n let ast = expect_ast!(\n\n ast = Ast::Call(_, ast, ..),\n\n src = SourceRef((3, 1), (3, 19))\n\n )\n\n .remove(0);\n\n let ast = expect_ast!(\n\n ast = Ast::Call(_, ast, ..),\n\n src = SourceRef((3, 8), (3, 18))\n\n )\n\n .remove(0);\n\n expect_ast!(ast = Ast::Num(Num(2), ..), src = SourceRef((3, 8), (3, 9)));\n\n }\n\n\n\n #[test]\n\n fn parse_error() {\n\n let _ = env_logger::try_init();\n", "file_path": "src/parser.rs", "rank": 46, "score": 14588.979966460545 }, { "content": " }\n\n Ok(out)\n\n }\n\n\n\n fn signed(&mut self) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n if self.current_token == Sub {\n\n self.next_token()?;\n\n let negated = self.dotcall()?;\n\n let src = src.up_to_end_of(self.current_src_ref);\n\n return Ok(if let Ast::Num(Num(n), _) = negated {\n\n // Simplify AST for negated number literals\n\n Ast::Num(Num(-n), src)\n\n } else {\n\n Ast::LeftUnaryOp(Sub, negated.into(), src)\n\n });\n\n }\n\n self.dotcall()\n\n }\n\n\n", "file_path": "src/parser.rs", "rank": 47, "score": 14588.852988455345 }, { "content": " if src_eq!($left, $right) {\n\n assert_eq!($left.src(), $right);\n\n }\n\n }};\n\n }\n\n\n\n /// Bit dodgy as you need to use the `$ast` ident in the pattern\n\n macro_rules! expect_ast {\n\n ($ast:ident = $pat:pat) => {\n\n match $ast {\n\n $pat => $ast,\n\n _ => panic!(\"Unexpected {}\", $ast.debug_string()),\n\n }\n\n };\n\n ($ast:ident = $pat:pat,src = $src:expr) => {{\n\n let src_eq = src_eq!($ast, $src);\n\n #[allow(clippy::match_ref_pats)]\n\n let out = match $ast {\n\n $pat => $ast,\n\n _ => panic!(\"Unexpected {}\", $ast.debug_string()),\n", "file_path": "src/parser.rs", "rank": 48, "score": 14588.847813322653 }, { "content": " // refer to seq index\n\n let index_expr = self.expr()?;\n\n let src = src.up_to_end_of(self.current_src_ref);\n\n self.consume(ClsSqr)?;\n\n Ast::ReferSeqIndex(id_to_seq_id(&id), index_expr.into(), src)\n\n } else {\n\n // refer to an id\n\n Ast::Refer(id, src)\n\n }\n\n }\n\n }\n\n }\n\n })\n\n }\n\n\n\n fn dotcall(&mut self) -> Res<Ast> {\n\n let mut out = self.num()?;\n\n while self.consume_maybe(Dot)?.is_some() {\n\n let fun_id = self.consume(ID_TOKEN)?;\n\n out = self.fun_call(Some(out), fun_id)?;\n", "file_path": "src/parser.rs", "rank": 49, "score": 14588.819926473763 }, { "content": " \"nums[].add(5000)\";\n\n \"nums[3]\" => 5000);\n\n }\n\n\n\n #[test]\n\n fn seq_add_literal() {\n\n assert_program!(\"add((5,4,3,2), 5000)\" => 0);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod list_functions {\n\n use super::*;\n\n\n\n #[test]\n\n fn def_seq_function() {\n\n assert_program!(\"fun count_number_of(list[], num)\";\n\n \" var count\";\n\n \" for n in list[]\";\n\n \" if n is num\";\n", "file_path": "src/lib.rs", "rank": 50, "score": 14588.754053933177 }, { "content": " msg.push_str(&format!(\n\n \"\\n\\nTry using a variable `var {id} = {call}`\\nthen `{id} is {n} {op} {id} is {rhs}`\",\n\n id = fun_var_name,\n\n call = fun_call,\n\n n = n,\n\n op = and_or,\n\n rhs = rhs,\n\n ));\n\n }\n\n }\n\n\n\n return Err(BadderError::at(src).describe(Stage::Parser, msg));\n\n }\n\n Ok(())\n\n }\n\n _ => Ok(()),\n\n }\n\n }\n\n}\n\n\n\n#[inline]\n", "file_path": "src/parser.rs", "rank": 51, "score": 14588.647214807872 }, { "content": "\n\n if self.consume_maybe(Comma)?.is_none() {\n\n break;\n\n }\n\n }\n\n let src = src.up_to_end_of(self.current_src_ref);\n\n self.consume(ClsBrace)?;\n\n for arg in &args {\n\n match *arg {\n\n Ast::Seq(..) | Ast::ReferSeq(..) => signature += \"s\",\n\n _ => signature += \"v\",\n\n }\n\n }\n\n signature += \")\";\n\n Ok(Ast::Call(Id(signature.into()), args, src))\n\n }\n\n\n\n fn num(&mut self) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n Ok({\n", "file_path": "src/parser.rs", "rank": 52, "score": 14588.644331910193 }, { "content": " } else {\n\n Ast::num(0, self.current_src_ref)\n\n }\n\n };\n\n let src = src.up_to_end_of(expr.src());\n\n return Ok(Ast::Return(expr.into(), src));\n\n }\n\n }\n\n\n\n // var id = expr\n\n if self.consume_maybe(Var)?.is_some() {\n\n let id = self.consume(ID_TOKEN)?;\n\n if self.consume_maybe(Ass)?.is_none() {\n\n let src = src.up_to(self.current_src_ref);\n\n self.consume_any(&[Ass, Eol, Eof])?;\n\n return Ok(Ast::Assign(id, Ast::Num(Num(0), src).into(), src));\n\n }\n\n let expr = self.expr()?;\n\n let expr_src = expr.src();\n\n self.consume_any(&[Eol, Eof])?;\n", "file_path": "src/parser.rs", "rank": 53, "score": 14588.600059660545 }, { "content": "\n\n let stack = {\n\n // kerfuffle to avoid cloning the stack when it hasn't changed\n\n if let Some(last) = self.last_stack_copy.take() {\n\n if &*last == stack {\n\n self.last_stack_copy = Some(Arc::clone(&last));\n\n last\n\n } else {\n\n self.replace_last_stack(stack)\n\n }\n\n } else {\n\n self.replace_last_stack(stack)\n\n }\n\n };\n\n\n\n trace!(\"ControllerOverseer sending: {:?} {:?}\", ast.src(), ast);\n\n self.to_controller\n\n .send(OverseerUpdate::Phase(Phase {\n\n id,\n\n src: ast.src(),\n", "file_path": "src/controller.rs", "rank": 54, "score": 14588.56751009107 }, { "content": "\n\n // If expr\n\n // line+\n\n fn line_if_else(&mut self, scope: usize, mut guests: Rc<[TokenGuest]>) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n let (expr, is_else) = {\n\n if self.consume_maybe(If)?.is_some() {\n\n (self.expr()?, false)\n\n } else {\n\n let src = src.up_to_end_of(self.current_src_ref);\n\n self.consume(Else)?;\n\n (\n\n self.consume_maybe(If)?\n\n .map(|_| self.expr())\n\n .unwrap_or_else(|| Ok(Ast::Num(Num(1), src)))?,\n\n true,\n\n )\n\n }\n\n };\n\n self.consume(Eol)?;\n", "file_path": "src/parser.rs", "rank": 55, "score": 14588.542154368653 }, { "content": " Some(_) => self.consume(ID_TOKEN)?,\n\n _ => idx_id.take().unwrap(),\n\n };\n\n\n\n self.consume(In)?;\n\n let (list, _) = self.list()?;\n\n (\n\n Ast::Empty(src.up_to_end_of(self.current_src_ref)),\n\n Some((idx_id, item_id, list)),\n\n )\n\n } else {\n\n self.consume(Loop)?;\n\n (Ast::num(1, src.up_to_end_of(self.current_src_ref)), None)\n\n }\n\n };\n\n self.consume(Eol)?;\n\n let loop_allow = {\n\n if guests.allow(&Break, scope) && guests.allow(&Continue, scope) {\n\n guests\n\n } else {\n", "file_path": "src/parser.rs", "rank": 56, "score": 14588.419793855812 }, { "content": " called_from: Vec::new(), // unknown\n\n kind: PhaseKind::from(ast),\n\n unpaused: false,\n\n time: send_time,\n\n stack,\n\n }))\n\n .expect(\"send\");\n\n\n\n let mut recv = self.from_controller.try_recv();\n\n while recv != Err(TryRecvError::Empty) {\n\n match recv {\n\n Ok(Ok(i)) => {\n\n if i == id {\n\n return Ok(());\n\n }\n\n }\n\n Ok(Err(_)) | Err(TryRecvError::Disconnected) => {\n\n debug!(\"ControllerOverseer cancelling: {:?} {:?}\", ast.src(), ast);\n\n return Err(());\n\n }\n", "file_path": "src/controller.rs", "rank": 57, "score": 14588.368215074313 }, { "content": " Ok(if let Some((idx_id, item_id, list)) = for_stuff {\n\n let src = src.up_to_end_of(list.src());\n\n Ast::ForIn(idx_id, item_id, list.into(), block.unwrap().into(), src)\n\n } else {\n\n let src = src.up_to_end_of(while_expr.src());\n\n Ast::While(while_expr.into(), block.unwrap().into(), src)\n\n })\n\n }\n\n\n\n // fun id()\n\n // line+\n\n fn line_fun(&mut self, scope: usize) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n self.consume(Fun)?;\n\n let id_name = ID_TOKEN;\n\n let id = self.consume(id_name.clone())?;\n\n self.consume(OpnBrace)?;\n\n let mut signature = String::new();\n\n match id {\n\n Id(fun_name) => signature = signature + &fun_name + \"(\",\n", "file_path": "src/parser.rs", "rank": 58, "score": 14588.341613076345 }, { "content": " }\n\n }\n\n\n\n pub fn parse_id<A: Into<SmolStr>>(id: A) -> Token {\n\n let id = id.into();\n\n match id.as_ref() {\n\n \"var\" => Var,\n\n \"if\" => If,\n\n \"else\" => Else,\n\n \"not\" => Not,\n\n \"is\" => Is,\n\n \"and\" => And,\n\n \"or\" => Or,\n\n \"loop\" => Loop,\n\n \"while\" => While,\n\n \"for\" => For,\n\n \"in\" => In,\n\n \"break\" => Break,\n\n \"continue\" => Continue,\n\n \"fun\" => Fun,\n", "file_path": "src/lexer.rs", "rank": 59, "score": 14588.327682836727 }, { "content": " }\n\n let mut exprs = vec![self.expr()?];\n\n while self.consume_maybe(Comma)?.is_some() {\n\n exprs.push(self.expr()?);\n\n }\n\n let has_commas = exprs.len() > 1;\n\n Ok((Ast::Seq(exprs, src.up_to(self.current_src_ref)), has_commas))\n\n }\n\n\n\n // seq id[] = expr,expr,\n\n fn line_seq(&mut self) -> Res<Ast> {\n\n let src = self.current_src_ref;\n\n self.consume(Seq)?;\n\n let seq_id = id_to_seq_id(&self.consume(ID_TOKEN)?);\n\n self.consume(Square)?;\n\n Ok(if self.consume_maybe(Ass)?.is_some() {\n\n Ast::AssignSeq(\n\n seq_id,\n\n self.list()?.0.into(),\n\n src.up_to(self.current_src_ref),\n", "file_path": "src/parser.rs", "rank": 60, "score": 14588.279038802422 }, { "content": " let mut extended =\n\n vec![(Break, scope + 1..).into(), (Continue, scope + 1..).into()];\n\n extended.extend_from_slice(&*guests);\n\n extended.into()\n\n }\n\n };\n\n let block = self.lines_while_allowing(\n\n scope + 1,\n\n |l| match *l {\n\n Ast::Line(line_scope, ..) => line_scope > scope,\n\n _ => false,\n\n },\n\n &loop_allow,\n\n )?;\n\n if block.is_none() {\n\n return Err(BadderError::at(src.up_to_next_line()).describe(\n\n Stage::Parser,\n\n \"Expected line after `loop,while,for` with exactly +1 indent\",\n\n ));\n\n }\n", "file_path": "src/parser.rs", "rank": 61, "score": 14588.278425558237 }, { "content": " }\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Checks for correct indent from one line to the next\n\n /// indentation should only increase by exactly 1 after an if,loop,for,while,fun\n\n #[inline]\n\n fn check_scope_change(line1: &Ast, line2: &Ast) -> Res<()> {\n\n if let (&Ast::Line(prev_scope, ref prev_expr, ..), &Ast::Line(scope, _, src)) =\n\n (line1, line2)\n\n {\n\n if scope > prev_scope {\n\n match **prev_expr {\n\n Ast::If(..) | Ast::While(..) | Ast::ForIn(..) | Ast::AssignFun(..)\n\n if scope == prev_scope + 1 => {}\n\n\n\n Ast::If(..) | Ast::While(..) | Ast::ForIn(..) | Ast::AssignFun(..) => {\n\n let indent_src_ref = src.with_char_end(((src.0).0, scope * 4 + 1));\n\n return Err(BadderError::at(indent_src_ref).describe(\n", "file_path": "src/parser.rs", "rank": 62, "score": 14588.276913537795 }, { "content": " Stage::Parser,\n\n \"Incorrect indentation, exactly +1 indent must used after a line \\\n\n starting with `if,loop,for,while,fun`\",\n\n ));\n\n }\n\n\n\n _ => {\n\n let indent_src_ref = src.with_char_end(((src.0).0, scope * 4 + 1));\n\n return Err(BadderError::at(indent_src_ref).describe(\n\n Stage::Parser,\n\n \"Incorrect indentation, +1 indent can only occur after a line \\\n\n starting with `if,loop,for,while,fun`\",\n\n ));\n\n }\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n", "file_path": "src/parser.rs", "rank": 63, "score": 14588.200533444551 }, { "content": "use super::*;\n\nuse std::{\n\n sync::mpsc::{self, RecvTimeoutError, TryRecvError},\n\n thread,\n\n time::*,\n\n u32, u64,\n\n};\n\n\n\nconst STACK_SIZE: usize = 8 * 1024 * 1024;\n\nconst BADDER_STACK_LEN: usize = 200;\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Phase {\n\n pub id: u64,\n\n pub time: Instant,\n\n pub src: SourceRef,\n\n /// most recent function call ref relavant to this Ast, empty => top level code\n\n pub called_from: Vec<SourceRef>,\n\n kind: PhaseKind,\n\n unpaused: bool,\n", "file_path": "src/controller.rs", "rank": 64, "score": 14588.126538313787 }, { "content": "\n\n #[test]\n\n fn braces_usage_in_fn_args_dotcall() {\n\n assert_program!(\n\n \"fun foo(n)\";\n\n \" n\";\n\n \"((3 + 5) / 2).foo()\" => 4);\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod fitness {\n\n use super::*;\n\n\n\n #[test]\n\n fn long_program() {\n\n assert_program!(\"var init\";\n\n \"fun inc()\";\n\n &\" init += 1\\n\".repeat(10_000);\n\n \"inc()\";\n", "file_path": "src/lib.rs", "rank": 65, "score": 14588.105681770508 }, { "content": " #[inline]\n\n fn refresh_overseer_updates(&mut self) -> bool {\n\n let mut change = false;\n\n while let Ok(update) = self.from_overseer.try_recv() {\n\n debug_assert!(\n\n self.current_external_call.is_none(),\n\n \"Update received during external call: {:?}\\nupdate: {:?}\",\n\n self.current_external_call,\n\n update,\n\n );\n\n\n\n match update {\n\n OverseerUpdate::Phase(mut phase) => {\n\n phase.called_from = self.current_call_info();\n\n if phase.kind == PhaseKind::FunctionCall {\n\n self.fun_call_history.push(phase.src)\n\n }\n\n if !self.cancelled {\n\n self.run_stats.consider(&phase);\n\n }\n", "file_path": "src/controller.rs", "rank": 66, "score": 14588.1015450767 }, { "content": " .into_iter()\n\n .collect()\n\n );\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod helpful_error {\n\n use super::*;\n\n\n\n #[test]\n\n fn reversed_greater_or_equal() {\n\n let _ = env_logger::try_init();\n\n\n\n let err = Parser::parse_str(\n\n &vec![\n\n \"if 12 => 11\", // `=>` misspelled\n\n \" 0\",\n\n ]\n\n .join(\"\\n\"),\n", "file_path": "src/parser.rs", "rank": 67, "score": 14587.903654675012 }, { "content": " pub fn debug_string(&self) -> String {\n\n match *self {\n\n ref pair @ Ast::LinePair(..) => {\n\n let mut next = pair;\n\n let mut out = String::new();\n\n while let Ast::LinePair(ref l1, ref l2, ..) = *next {\n\n out = out + &l1.debug_string() + \"\\n\";\n\n next = l2;\n\n }\n\n out + &next.debug_string()\n\n }\n\n Ast::Line(scope, ref expr, src, ..) => {\n\n format!(\n\n \"{:3}:-{}{}> {}\",\n\n (src.0).0,\n\n scope,\n\n \"-\".repeat(scope),\n\n expr.debug_string()\n\n )\n\n }\n", "file_path": "src/parser.rs", "rank": 68, "score": 14587.892636783363 }, { "content": " src,\n\n })) => {\n\n if src == UNKNOWN_SRC_REF {\n\n Err(Error(\n\n BadderError::at(ast.src()).describe(stage, description),\n\n ))\n\n } else {\n\n Err(Error(BadderError::at(src).describe(stage, description)))\n\n }\n\n }\n\n x => x,\n\n }\n\n }\n\n\n\n fn eval_seq(\n\n &mut self,\n\n list: &Ast,\n\n current_scope: usize,\n\n stack_key: StackKey,\n\n ) -> Result<Vec<(Int, IntFlag)>, InterpreterUpFlow> {\n", "file_path": "src/lib.rs", "rank": 69, "score": 14587.795162967963 }, { "content": " let _ = env_logger::try_init();\n\n Parser::parse_str(\n\n &vec![\n\n \"if 1\",\n\n \" if 1\",\n\n \" 0\",\n\n \" var foo = 123\",\n\n \" else\",\n\n \" fail()\",\n\n ]\n\n .join(\"\\n\"),\n\n )\n\n .expect_err(\"did not fail parse\");\n\n }\n\n\n\n #[test]\n\n fn return_in_function_body_with_loops() {\n\n let _ = env_logger::try_init();\n\n Parser::parse_str(\n\n &vec![\n", "file_path": "src/parser.rs", "rank": 70, "score": 14587.733415460543 }, { "content": " }) = self.current_phase\n\n {\n\n // ignore errors as send can happen after execution finishes\n\n let _ = self.to_overseer.send(Ok(id));\n\n self.current_phase.as_mut().unwrap().unpaused = true;\n\n }\n\n }\n\n\n\n /// Requests any current executing interpreter be cancelled\n\n pub fn cancel(&mut self) {\n\n if !self.cancelled {\n\n self.cancelled = true;\n\n self.fun_call_history.clear();\n\n let _ = self.to_overseer.send(Err(()));\n\n }\n\n }\n\n\n\n /// Returns current execution phase, requires a recent (in terms of set pause_time)\n\n /// call to #refresh() to be valid\n\n pub fn current_phase(&self) -> Option<Phase> {\n", "file_path": "src/controller.rs", "rank": 71, "score": 14587.561272289435 }, { "content": " self.consume_any(&[Eol, Eof])?;\n\n // v *= expr -> v = v * expr\n\n return Ok(Ast::Reassign(id, Ast::bin_op(*op, refer, expr).into(), src));\n\n }\n\n if peek == OpnSqr {\n\n // ReferSeqIndex|ReassignSeqIndex\n\n let mut out = self.num()?;\n\n if self.consume_maybe(Ass)?.is_some() {\n\n let expr = self.expr()?;\n\n out = match out {\n\n Ast::ReferSeqIndex(id, idx, src) => {\n\n let src = src.up_to_end_of(expr.src());\n\n Ast::ReassignSeqIndex(id, idx, expr.into(), src)\n\n }\n\n _ => {\n\n return Err(BadderError::at(src.up_to_end_of(self.current_src_ref))\n\n .describe(\n\n Stage::Parser,\n\n format!(\"expecting seq index ref id[expr], got {:?}\", out),\n\n ));\n", "file_path": "src/parser.rs", "rank": 72, "score": 14587.52811890615 }, { "content": " return Ok(0);\n\n }\n\n let loop_token = Id(\"#loop\".into());\n\n self.stack[current_scope].insert(loop_token.clone(), LoopMarker);\n\n let mut index = 0;\n\n while index < list.len() {\n\n let mut frame = IndexMap::default();\n\n if let Some(ref id) = *idx_id {\n\n frame.insert(id.clone(), Value(index as i32, NO_FLAG, src));\n\n }\n\n let (v, flag) = list[index];\n\n frame.insert(item_id.clone(), Value(v, flag, src));\n\n self.stack.push(frame);\n\n let eval = self.eval(block, current_scope + 1, stack_key);\n\n self.stack.pop();\n\n match eval {\n\n Err(LoopBreak) => break,\n\n Ok(_) | Err(Flagged(..)) | Err(LoopContinue) => (),\n\n err @ Err(_) => return err,\n\n };\n", "file_path": "src/lib.rs", "rank": 73, "score": 14587.427750409368 }, { "content": "pub enum AssignIdKind {\n\n Var,\n\n Fun,\n\n Seq,\n\n}\n\nimpl AssignIdKind {\n\n fn try_from(token: &Token) -> Option<Self> {\n\n Some(match token {\n\n Token::Var => AssignIdKind::Var,\n\n Token::Seq => AssignIdKind::Seq,\n\n Token::Fun => AssignIdKind::Fun,\n\n _ => return None,\n\n })\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(clippy::cognitive_complexity)]\n\nmod parser_test {\n\n use super::*;\n", "file_path": "src/parser.rs", "rank": 74, "score": 14587.425864647788 }, { "content": " fn lines_while_allowing<F>(\n\n &mut self,\n\n first_line_scope: usize,\n\n predicate: F,\n\n allow: &Rc<[TokenGuest]>,\n\n ) -> Res<Option<Ast>>\n\n where\n\n F: Fn(&Ast) -> bool,\n\n {\n\n let mut all = vec![];\n\n let mut line = self.indented_line(Rc::clone(allow))?;\n\n\n\n while match line {\n\n Ast::Empty(..) => false,\n\n ref l => predicate(l),\n\n } {\n\n if all.is_empty() {\n\n Self::check_line_has_scope(&line, first_line_scope)?;\n\n }\n\n if let (line, Some(prev_line)) = (&line, all.last()) {\n", "file_path": "src/parser.rs", "rank": 75, "score": 14587.41493874989 }, { "content": " }\n\n }\n\n return Ok((Token::parse_id(id), src_ref.up_to(self.cursor())));\n\n }\n\n\n\n self.next_char();\n\n if let OpAss(_) = peek {\n\n self.next_char();\n\n }\n\n if peek == GtEq || peek == LtEq || peek == Square {\n\n self.next_char();\n\n }\n\n\n\n Ok((peek, src_ref.up_to(self.cursor())))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod lexer_test {\n\n use super::*;\n", "file_path": "src/lexer.rs", "rank": 76, "score": 14587.3320846159 }, { "content": " fn listref_no_edge_cases(&mut self) -> Res<Result<Option<Ast>, ListParseEdgeCase>> {\n\n self._listref(false)\n\n }\n\n\n\n /// Returns (ast, literal-has-commas)\n\n fn list(&mut self) -> Res<(Ast, bool)> {\n\n let src = self.current_src_ref;\n\n match self.listref()? {\n\n Ok(Some(list)) => return Ok((list, true)),\n\n Err(ListParseEdgeCase::DotCall(..)) => {\n\n // functions cannot (yet) return seqs so this can't work\n\n return Err(BadderError::at(self.current_src_ref).describe(\n\n Stage::Parser,\n\n format!(\n\n \"Expected sequence reference/literal got `{}`\",\n\n self.current_token.long_debug()\n\n ),\n\n ));\n\n }\n\n Ok(None) => (),\n", "file_path": "src/parser.rs", "rank": 77, "score": 14587.261604592923 }, { "content": " }\n\n\n\n fn fun_call(&mut self, left: Option<Ast>, id: Token) -> Res<Ast> {\n\n // function call\n\n let src = left.as_ref().map(Ast::src).unwrap_or(self.current_src_ref);\n\n self.consume(OpnBrace)?;\n\n let mut args: Vec<_> = left.into_iter().collect();\n\n let mut signature = String::new();\n\n match id {\n\n Id(name) => signature = signature + &name + \"(\",\n\n _ => panic!(\"fun_call passed in non-Id id\"),\n\n }\n\n while self.current_token != ClsBrace {\n\n match self.listref_no_edge_cases()? {\n\n Ok(Some(list)) => args.push(list),\n\n Ok(None) => args.push(self.expr()?),\n\n Err(ListParseEdgeCase::DotCall(..)) => {\n\n panic!(\"Internal error: Unexpected DotCall edge case\");\n\n }\n\n }\n", "file_path": "src/parser.rs", "rank": 78, "score": 14587.216909545194 }, { "content": " return false;\n\n }\n\n\n\n if let Some(Phase { time, unpaused, .. }) = self.current_phase {\n\n !unpaused && time.elapsed() < self.pause_time\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n /// Communicate with the current execution\n\n /// populates #result & #current_phase if available\n\n /// Returns if a change has taken place\n\n pub fn refresh(&mut self) -> bool {\n\n if self.result.is_some() {\n\n return false;\n\n }\n\n\n\n if let Ok(result) = self.execution_result.try_recv() {\n\n self.result = Some(result);\n", "file_path": "src/controller.rs", "rank": 79, "score": 14587.209396855302 }, { "content": " src = SourceRef((3, 1), (3, 11))\n\n );\n\n let ast = *expect_ast!(\n\n ast = Ast::Reassign(_, ast, ..),\n\n src = SourceRef((3, 5), (3, 11))\n\n );\n\n let (left, right) = expect_bin_op!(ast, src = SourceRef((3, 5), (3, 11)));\n\n expect_ast!(left = Ast::Refer(..), src = SourceRef((3, 5), (3, 6)));\n\n expect_ast!(\n\n right = Ast::Num(Num(2), ..),\n\n src = SourceRef((3, 10), (3, 11))\n\n );\n\n\n\n // `else if a > 50`\n\n let ast = next.expect(\"else\");\n\n let ast = *expect_ast!(\n\n ast = Ast::Line(0, ast, ..),\n\n src = SourceRef((4, 1), (4, 15))\n\n );\n\n let (expr, block, next) = expect_if_ast!(ast, src = SourceRef((4, 1), (4, 15)));\n", "file_path": "src/parser.rs", "rank": 80, "score": 14587.055521477065 }, { "content": " match $ast {\n\n Ast::BinOp(_, left, right, src) => {\n\n assert_eq!(src, $src);\n\n (*left, *right)\n\n }\n\n _ => panic!(\"Unexpected {}\", $ast.debug_string()),\n\n }\n\n }};\n\n }\n\n\n\n macro_rules! expect_if_ast {\n\n ($ast:ident,src = $src:expr) => {{\n\n src_eq!($ast, $src); // just print\n\n match $ast {\n\n Ast::If(expr, block, elif, _, src) => {\n\n assert_eq!(src, $src);\n\n (*expr, block.as_ref().clone(), elif.map(|boxed| *boxed))\n\n }\n\n _ => panic!(\"Unexpected {}\", $ast.debug_string()),\n\n }\n", "file_path": "src/parser.rs", "rank": 81, "score": 14586.988599701348 }, { "content": " pub fn just_if(expr: Ast, block: Ast, is_else: bool, if_start: SourceRef) -> Ast {\n\n let src = if_start.up_to_end_of(expr.src());\n\n Ast::If(expr.into(), block.into(), None, is_else, src)\n\n }\n\n\n\n pub fn if_else(expr: Ast, block: Ast, else_if: Ast, is_else: bool, if_start: SourceRef) -> Ast {\n\n let src = if_start.up_to_end_of(expr.src());\n\n Ast::If(\n\n expr.into(),\n\n block.into(),\n\n Some(else_if.into()),\n\n is_else,\n\n src,\n\n )\n\n }\n\n\n\n pub fn num(n: Int, src: SourceRef) -> Ast {\n\n Ast::Num(Num(n), src)\n\n }\n\n\n", "file_path": "src/parser.rs", "rank": 82, "score": 14586.983920530594 }, { "content": " let mut lexer = Lexer::new(code);\n\n let mut ids = FxHashSet::default();\n\n let mut last_token = None;\n\n loop {\n\n match (last_token, lexer.next_token()?) {\n\n (Some(kind), (Id(id), ..)) => {\n\n ids.insert(AssignId { id, kind });\n\n }\n\n (_, (Eof, ..)) => break,\n\n (_, (token, ..)) => last_token = AssignIdKind::try_from(&token),\n\n }\n\n }\n\n Ok(ids)\n\n }\n\n\n\n fn next_token(&mut self) -> Res<&Token> {\n\n let (mut token, src_ref) = self.lexer.next_token()?;\n\n trace!(\"{:?} @{:?}\", token, src_ref);\n\n\n\n ::std::mem::swap(&mut self.current_token, &mut token);\n", "file_path": "src/parser.rs", "rank": 83, "score": 14586.955970221095 }, { "content": " src = SourceRef((1, 1), (1, 12))\n\n );\n\n expect_ast!(ast = Ast::Num(ast, ..), src = SourceRef((1, 9), (1, 12)));\n\n\n\n // `if a > 100`\n\n let ast = *expect_ast!(\n\n next = Ast::Line(0, next, ..),\n\n src = SourceRef((2, 1), (2, 11))\n\n );\n\n let (expr, block, next) = expect_if_ast!(ast, src = SourceRef((2, 1), (2, 11)));\n\n let (left, right) = expect_bin_op!(expr, src = SourceRef((2, 4), (2, 11)));\n\n expect_ast!(left = Ast::Refer(..), src = SourceRef((2, 4), (2, 5)));\n\n expect_ast!(\n\n right = Ast::Num(Num(100), ..),\n\n src = SourceRef((2, 8), (2, 11))\n\n );\n\n\n\n // ` a *= 2` -> ` a = a * 2`\n\n let ast = *expect_ast!(\n\n block = Ast::Line(1, block, ..),\n", "file_path": "src/parser.rs", "rank": 84, "score": 14586.952785119443 }, { "content": " let (left, right) = expect_bin_op!(expr, src = SourceRef((4, 9), (4, 15)));\n\n expect_ast!(left = Ast::Refer(..), src = SourceRef((4, 9), (4, 10)));\n\n expect_ast!(\n\n right = Ast::Num(Num(50), ..),\n\n src = SourceRef((4, 13), (4, 15))\n\n );\n\n\n\n // ` a = a / 3`\n\n let ast = *expect_ast!(\n\n block = Ast::Line(1, block, ..),\n\n src = SourceRef((5, 1), (5, 14))\n\n );\n\n let ast = *expect_ast!(\n\n ast = Ast::Reassign(_, ast, ..),\n\n src = SourceRef((5, 5), (5, 14))\n\n );\n\n let (left, right) = expect_bin_op!(ast, src = SourceRef((5, 9), (5, 14)));\n\n expect_ast!(left = Ast::Refer(..), src = SourceRef((5, 9), (5, 10)));\n\n expect_ast!(\n\n right = Ast::Num(Num(3), ..),\n", "file_path": "src/parser.rs", "rank": 85, "score": 14586.898001120153 }, { "content": " \"x\" => 16);\n\n }\n\n\n\n #[test]\n\n fn loop_continue_break() {\n\n assert_program!(\"var x = 1\";\n\n \"loop\";\n\n \" x -= 1\";\n\n \" if x <= -5\";\n\n \" x *= -3\";\n\n \" continue\";\n\n \" if x > 10\";\n\n \" break\";\n\n \"x\" => 14);\n\n }\n\n\n\n #[test]\n\n fn while_loop() {\n\n assert_program!(\"var x = 1\";\n\n \"while x < 50\";\n", "file_path": "src/lib.rs", "rank": 86, "score": 14586.894996859726 }, { "content": " pub stack: Arc<[FxIndexMap<Token, FrameData>]>,\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum PhaseKind {\n\n FunctionCall,\n\n Assignment,\n\n Other,\n\n}\n\n\n\nimpl PhaseKind {\n\n fn from(ast: &Ast) -> PhaseKind {\n\n match *ast {\n\n Ast::Call(..) => PhaseKind::FunctionCall,\n\n Ast::Assign(..) | Ast::AssignFun(..) | Ast::AssignSeq(..) => PhaseKind::Assignment,\n\n\n\n _ => PhaseKind::Other,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n", "file_path": "src/controller.rs", "rank": 87, "score": 14586.872462244612 }, { "content": " 1 => \", try removing 1 space.\",\n\n 3 => \", try removing 3 spaces.\",\n\n _ => \", try removing 2 spaces.\",\n\n };\n\n\n\n return Err(BadderError::at(src_ref.up_to(self.cursor())).describe(\n\n Stage::Lexer,\n\n format!(\"Invalid indent must be multiple of 4 spaces{}\", hint),\n\n ));\n\n }\n\n return Ok((Indent(spaces / 4), src_ref.up_to(self.cursor())));\n\n }\n\n\n\n let c = self.current_char.unwrap();\n\n\n\n if let Num(_) = peek {\n\n let mut number_str = c.to_string();\n\n while let Some(c) = self.next_char() {\n\n if c.is_digit(10) {\n\n number_str.push(c);\n", "file_path": "src/lexer.rs", "rank": 88, "score": 14586.87078691047 }, { "content": " Ok(Err(_)) | Err(RecvTimeoutError::Disconnected) => {\n\n debug!(\"ControllerOverseer cancelling: {:?} {:?}\", ast.src(), ast);\n\n return Err(());\n\n }\n\n _ => (),\n\n };\n\n\n\n elapsed = send_time.elapsed();\n\n }\n\n Ok(())\n\n }\n\n }\n\n\n\n fn oversee_after(&mut self, _stack: &[FxIndexMap<Token, FrameData>], ast: &Ast) {\n\n if let Ast::Call(ref id, ..) = *ast {\n\n let _ = self\n\n .to_controller\n\n .send(OverseerUpdate::FinishedFunCall(id.clone()));\n\n }\n\n }\n", "file_path": "src/controller.rs", "rank": 89, "score": 14586.839640914563 }, { "content": " } else {\n\n break;\n\n }\n\n }\n\n let src_ref = src_ref.up_to(self.cursor());\n\n return match number_str.parse() {\n\n Ok(n) => Ok((Num(n), src_ref)),\n\n Err(e) => Err(BadderError::at(src_ref)\n\n .describe(Stage::Lexer, format!(\"could not parse number: {}\", e))),\n\n };\n\n }\n\n\n\n // non-digit as here\n\n if let Id(_) = peek {\n\n let mut id = c.to_string();\n\n while let Some(c) = self.next_char() {\n\n if id_char(c) {\n\n id.push(c);\n\n } else {\n\n break;\n", "file_path": "src/lexer.rs", "rank": 90, "score": 14586.831169270541 }, { "content": " assert!(err_lower.contains(substring_lower.as_str()),\n\n \"Substring:`{}` not in error: `{:?}`\", $sub, err);\n\n )+\n\n };\n\n ($( $code:expr );+ =>X $( $sub:expr ),+; src = $src_ref:expr ) => {\n\n let mut code = String::new();\n\n $(\n\n code = code + $code + \"\\n\";\n\n )+\n\n let err = util::error(&code);\n\n let err_lower = err.description.to_lowercase();\n\n $(\n\n let substring_lower = $sub.to_lowercase();\n\n assert!(err_lower.contains(substring_lower.as_str()),\n\n \"Substring:`{}` not in error: `{:?}`\", $sub, err);\n\n )+\n\n assert_eq!(err.src, $src_ref);\n\n };\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 91, "score": 14586.829080200308 }, { "content": " .join(\"\\n\"),\n\n )\n\n .unwrap();\n\n\n\n let (ast, next) = expect_line_pair!(ast);\n\n\n\n let ast = *expect_ast!(\n\n ast = Ast::Line(0, ast, ..),\n\n src = SourceRef((1, 1), (1, 14))\n\n );\n\n let ast = &*expect_ast!(\n\n ast = Ast::AssignFun(.., ast, _),\n\n src = SourceRef((1, 1), (1, 14))\n\n );\n\n let ast = &**expect_ast!(\n\n ast = &Ast::Line(1, ref ast, ..),\n\n src = SourceRef((2, 1), (2, 17))\n\n );\n\n expect_ast!(ast = &Ast::Return(ref ast, ..), src = SourceRef((2, 5), (2, 17)));\n\n\n", "file_path": "src/parser.rs", "rank": 92, "score": 14586.807906400372 }, { "content": " \"error did not suggest `is` or `>`\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn not_greater_than() {\n\n let _ = env_logger::try_init();\n\n\n\n let err = Parser::parse_str(&vec![\"12 not > 11\"].join(\"\\n\")).expect_err(\"parse\");\n\n\n\n println!(\"Got error: {:?}\", err);\n\n\n\n assert_eq!(err.src, SourceRef((1, 4), (1, 7)));\n\n assert!(\n\n err.description.contains(\"`<=`\"),\n\n \"error did not suggest `<=`\"\n\n );\n\n }\n\n\n\n #[test]\n", "file_path": "src/parser.rs", "rank": 93, "score": 14586.763812033994 }, { "content": "\n\nimpl Ast {\n\n pub fn bin_op<A: Into<Box<Ast>>>(token: Token, left: A, right: A) -> Ast {\n\n let left = left.into();\n\n let right = right.into();\n\n let src = left.src().up_to_end_of(right.src());\n\n\n\n Ast::BinOp(token, left, right, src)\n\n }\n\n\n\n pub fn line_pair<A: Into<Box<Ast>>>(before: A, after: A) -> Ast {\n\n let line = before.into();\n\n if let Ast::LinePair(..) = *line {\n\n panic!(\"LinePair left val must not be a LinePair\");\n\n }\n\n let after = after.into();\n\n let src = line.src().up_to_end_of(after.src());\n\n Ast::LinePair(line, after, src)\n\n }\n\n\n", "file_path": "src/parser.rs", "rank": 94, "score": 14586.753915285404 }, { "content": "\n\n #[test]\n\n fn variable_is_1_or_2() {\n\n let _ = env_logger::try_init();\n\n\n\n let err = Parser::parse_str(&vec![\"var scan = 1\", \"if scan is 1 or 2\", \" 0\"].join(\"\\n\"))\n\n .expect_err(\"parse\");\n\n\n\n println!(\"Got error: {:?}\", err);\n\n\n\n assert_eq!(err.src, SourceRef((2, 4), (2, 18)));\n\n assert!(err.description.contains(\"`scan is 1 or scan is 2`\"));\n\n }\n\n\n\n #[test]\n\n fn argless_fun_call_is_1_or_2() {\n\n let _ = env_logger::try_init();\n\n\n\n let err = Parser::parse_str(\n\n &vec![\"fun do_scan()\", \" 2\", \"if do_scan() is 1 or 2\", \" 0\"].join(\"\\n\"),\n", "file_path": "src/parser.rs", "rank": 95, "score": 14586.668279557949 }, { "content": " Indent(usize),\n\n Loop,\n\n While,\n\n For,\n\n In,\n\n Break,\n\n Continue,\n\n Fun,\n\n Return,\n\n Comma,\n\n Dot,\n\n Seq,\n\n}\n\n\n\nuse crate::lexer::Token::*;\n\n\n\nimpl fmt::Debug for Token {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match *self {\n\n Num(x) => write!(f, \"{}\", x),\n", "file_path": "src/lexer.rs", "rank": 96, "score": 14586.624007083183 }, { "content": " \"init\" => 10_000, debug_parse = false); // debug parse output is 10000 lines\n\n }\n\n\n\n #[test]\n\n fn recursive_overflow() {\n\n assert_program!(\"fun rec()\";\n\n \" rec()\";\n\n \"rec()\" =>X \"stack overflow\"; src = SourceRef((2,5), (2,10)));\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod core_lib {\n\n use super::*;\n\n\n\n #[test]\n\n fn seq_size() {\n\n assert_program!(\"seq nums[] = 1,2,3,4,5,4,3,2,1\";\n\n \"size(nums[])\"; // simple call style\n\n \"nums[].size()\" => 9);\n", "file_path": "src/lib.rs", "rank": 97, "score": 14586.50851367555 }, { "content": " };\n\n if !src_eq {\n\n assert!(false, \"Unexpected SourceRef\");\n\n }\n\n out\n\n }};\n\n }\n\n\n\n macro_rules! expect_line_pair {\n\n ($ast:ident) => {\n\n match $ast {\n\n Ast::LinePair(l1, l2, ..) => (*l1, *l2),\n\n _ => panic!(\"Unexpected {}\", $ast.debug_string()),\n\n }\n\n };\n\n }\n\n\n\n macro_rules! expect_bin_op {\n\n ($ast:ident,src = $src:expr) => {{\n\n src_eq!($ast, $src); // just print\n", "file_path": "src/parser.rs", "rank": 98, "score": 14586.50624978901 }, { "content": " .oversee(&self.stack, defer_ast, defer_scope, defer_key)\n\n .is_err()\n\n {\n\n return Err(Error(\n\n BadderError::at(defer_ast.src()).describe(Stage::Interpreter, \"cancelled\"),\n\n ));\n\n }\n\n\n\n // all builtins are core lib for seq, ie first arg is a seq\n\n match args[0] {\n\n Ast::ReferSeq(ref id, ..) => {\n\n if let Some(idx) = self.highest_frame_idx(id, current_scope, stack_key) {\n\n let (mut idx, mut id) = (idx, id.clone());\n\n while let Ref(n_idx, ref n_id) = self.stack[idx][&id] {\n\n idx = n_idx;\n\n id = n_id.clone();\n\n }\n\n match self.stack[idx].get_mut(&id) {\n\n Some(&mut Sequence(ref mut v, ..)) => match builtin {\n\n Builtin::Size => Ok(v.len() as i32),\n", "file_path": "src/lib.rs", "rank": 99, "score": 14586.47701167693 } ]
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 = Path::new(prefix.as_ref());\n\n let file_name_prefix = prefix.file_name().unwrap_or_else(|| OsStr::new(\"\"));\n\n let dir = prefix.parent().unwrap(); // TODO\n\n (dir.to_owned(), file_name_prefix.to_owned())\n\n }\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 75255.03930534009 }, { "content": "pub fn verify_checksum(buf: &[u8], expect: u32) -> Result<(), Error> {\n\n let found = checksum(buf);\n\n if expect == found {\n\n Ok(())\n\n } else {\n\n Err(Error::ChecksumMismatch { expect, found })\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 1, "score": 65633.8163567706 }, { "content": "fn main() -> Result<()> {\n\n // re-run conditions\n\n println!(\"cargo:rerun-if-changed={}\", PROTOBUF_FILE_WO_SERDE);\n\n println!(\"cargo:rerun-if-changed={}\", PROTOBUF_FILE_W_SERDE);\n\n println!(\"cargo:rerun-if-env-changed={}\", BUILD_METHOD_ENV);\n\n\n\n #[cfg(feature = \"generate_protobuf_src\")]\n\n {\n\n let build_method = guess_build_method()?;\n\n\n\n match build_method {\n\n None => {}\n\n Some(BuildMethod::Url(url)) => build_by_url(&url)?,\n\n Some(BuildMethod::SrcDir(dir)) => build_by_src_dir(dir)?,\n\n Some(BuildMethod::SrcFile(file)) => build_by_src_file(file)?,\n\n Some(BuildMethod::InstallPrefix(prefix)) => build_by_install_prefix(prefix)?,\n\n }\n\n }\n\n\n\n Ok(())\n", "file_path": "build.rs", "rank": 2, "score": 55911.61465363482 }, { "content": "#[test]\n\nfn event_writer() -> Result<()> {\n\n // download image files\n\n let images = IMAGE_URLS\n\n .iter()\n\n .cloned()\n\n .map(|url| {\n\n println!(\"downloading {}\", url);\n\n let mut bytes = vec![];\n\n io::copy(&mut ureq::get(url).call()?.into_reader(), &mut bytes)?;\n\n let image = image::load_from_memory(bytes.as_ref())?;\n\n Ok(image)\n\n })\n\n .collect::<Result<Vec<_>>>()?;\n\n\n\n // init writer\n\n let prefix = DATA_DIR\n\n .join(\"blocking-event-writer-log-dir\")\n\n .join(\"test\")\n\n .into_os_string()\n\n .into_string()\n", "file_path": "tests/summary.rs", "rank": 3, "score": 52694.100350607536 }, { "content": "#[test]\n\nfn indexer_iter_test() -> Result<()> {\n\n tfrecord::indexer::load_paths([&*INPUT_TFRECORD_PATH], Default::default())\n\n .map(|index| {\n\n let example: Example = index?.load()?;\n\n anyhow::Ok(example)\n\n })\n\n .enumerate()\n\n .map(|(index, example)| anyhow::Ok((index, example?)))\n\n .try_for_each(|args| {\n\n let (example_index, example) = args?;\n\n\n\n // enumerate features in an example\n\n for (feature_index, (name, feature)) in example.into_iter().enumerate() {\n\n print!(\"{}\\t{}\\t{}\\t\", example_index, feature_index, name);\n\n\n\n use FeatureKind as F;\n\n match feature.into_kinds() {\n\n Some(F::Bytes(value)) => {\n\n eprintln!(\"bytes\\t{}\", value.len());\n\n }\n", "file_path": "tests/indexer.rs", "rank": 4, "score": 51290.95620315898 }, { "content": "fn main() -> Result<()> {\n\n // download and decode data set\n\n let (images, labels) = mnist_loader::load_mnist()?;\n\n\n\n // writer to tfrecord file\n\n let mut writer: ExampleWriter<_> = RecordWriter::create(OUTPUT_FILE)?;\n\n\n\n for (image, label) in izip!(images, labels) {\n\n // build example\n\n let image_feature = Feature::from_f32_iter(image.into_iter().map(|pixel| pixel as f32));\n\n let label_feature = Feature::from_i64_list(vec![label as i64]);\n\n\n\n let example = vec![\n\n (\"image\".into(), image_feature),\n\n (\"label\".into(), label_feature),\n\n ]\n\n .into_iter()\n\n .collect::<Example>();\n\n\n\n // append to file\n", "file_path": "examples/save_mnist_to_tfrecord.rs", "rank": 5, "score": 51290.95620315898 }, { "content": "fn main() -> Result<()> {\n\n let Args {\n\n event: event_file,\n\n tags: query_tags,\n\n output: output_dir,\n\n } = Args::from_args();\n\n let reader = EventIter::open(&event_file, Default::default())?;\n\n std::fs::create_dir_all(&output_dir)?;\n\n\n\n let history: Vec<TagData> = reader\n\n .into_iter()\n\n .map(|result| -> Result<_> {\n\n let event = result?;\n\n let tag = match event.what {\n\n Some(What::Summary(Summary { value })) => {\n\n let val = &value[0];\n\n match val.value {\n\n Some(SimpleValue(value)) => Some(TagData {\n\n step: event.step,\n\n tag: val.tag.clone(),\n", "file_path": "examples/event_reader/main.rs", "rank": 6, "score": 51290.95620315898 }, { "content": "pub fn main() -> Result<()> {\n\n // download image files\n\n let images = download_images()?;\n\n\n\n // initialize writer\n\n let mut writer = EventWriter::from_prefix(get_path_prefix(), \"\", Default::default())?;\n\n let mut rng = rand::thread_rng();\n\n\n\n // loop\n\n for step in 0..30 {\n\n println!(\"step: {}\", step);\n\n\n\n // scalar\n\n {\n\n let value: f32 = (step as f32 * PI / 8.0).sin();\n\n writer.write_scalar(\"scalar\", step, value)?;\n\n }\n\n\n\n // histogram\n\n {\n", "file_path": "examples/tensorboard.rs", "rank": 7, "score": 51290.53905161626 }, { "content": "fn main() -> Result<(), Error> {\n\n // use init pattern to construct the tfrecord reader\n\n let reader = ExampleIter::open(&*INPUT_TFRECORD_PATH, Default::default())?;\n\n\n\n // print header\n\n println!(\"example_no\\tfeature_no\\tname\\ttype\\tsize\");\n\n\n\n // enumerate examples\n\n for (example_index, result) in reader.enumerate() {\n\n let example = result?;\n\n\n\n // enumerate features in an example\n\n for (feature_index, (name, feature)) in example.into_iter().enumerate() {\n\n print!(\"{}\\t{}\\t{}\\t\", example_index, feature_index, name);\n\n\n\n use FeatureKind as F;\n\n match feature.into_kinds() {\n\n Some(F::Bytes(list)) => {\n\n println!(\"bytes\\t{}\", list.len());\n\n }\n", "file_path": "examples/tfrecord_info.rs", "rank": 8, "score": 49887.39490416771 }, { "content": "fn download_images() -> Result<Vec<DynamicImage>> {\n\n println!(\"downloading images...\");\n\n IMAGE_URLS\n\n .iter()\n\n .cloned()\n\n .map(|url| {\n\n let mut bytes = vec![];\n\n io::copy(&mut ureq::get(url).call()?.into_reader(), &mut bytes)?;\n\n let image = image::load_from_memory(bytes.as_ref())?;\n\n Ok(image)\n\n })\n\n .collect::<Result<Vec<_>>>()\n\n}\n", "file_path": "examples/tensorboard.rs", "rank": 9, "score": 46194.231368224755 }, { "content": "use std::{\n\n borrow::Cow,\n\n ffi::{OsStr, OsString},\n\n path::{Path, PathBuf, MAIN_SEPARATOR},\n\n};\n\n\n\nuse crate::error::Error;\n\nuse crc::Crc;\n\n\n", "file_path": "src/utils.rs", "rank": 10, "score": 38163.3925287048 }, { "content": "/// Write the raw record bytes to a generic writer.\n\npub fn try_write_record<W>(writer: &mut W, bytes: Vec<u8>) -> Result<()>\n\nwhere\n\n W: Write,\n\n{\n\n // write data size\n\n {\n\n let len = bytes.len();\n\n let len_buf = len.to_le_bytes();\n\n let cksum = crate::utils::checksum(&len_buf);\n\n let cksum_buf = cksum.to_le_bytes();\n\n\n\n writer.write_all(&len_buf)?;\n\n writer.write_all(&cksum_buf)?;\n\n }\n\n\n\n // write data\n\n {\n\n let cksum = crate::utils::checksum(&bytes);\n\n let cksum_buf = cksum.to_le_bytes();\n\n\n\n writer.write_all(bytes.as_slice())?;\n\n writer.write_all(&cksum_buf)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/io/sync.rs", "rank": 11, "score": 35052.14194574155 }, { "content": "fn skip_or_check<R>(reader: &mut R, len: usize, check_integrity: bool) -> Result<()>\n\nwhere\n\n R: Read + Seek,\n\n{\n\n if check_integrity {\n\n crate::io::sync::try_read_record_data(reader, len, check_integrity)?;\n\n } else {\n\n reader.seek(SeekFrom::Current(len as i64))?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/indexer/sync.rs", "rank": 12, "score": 35052.14194574155 }, { "content": "fn read_record_at<R>(reader: &mut R, offset: u64, len: usize) -> Result<Vec<u8>>\n\nwhere\n\n R: Read + Seek,\n\n{\n\n reader.seek(SeekFrom::Start(offset))?;\n\n let bytes = crate::io::sync::try_read_record_data(reader, len, false)?;\n\n Ok(bytes)\n\n}\n\n\n", "file_path": "src/indexer/sync.rs", "rank": 13, "score": 33308.76006229695 }, { "content": "/// Try to read the record length from a generic reader.\n\n///\n\n/// It is internally called by [try_read_record]. It returns `Ok(None)` if reaching the end of file.\n\npub fn try_read_len<R>(reader: &mut R, check_integrity: bool) -> Result<Option<usize>>\n\nwhere\n\n R: Read,\n\n{\n\n let len_buf = {\n\n let len_buf = [0u8; std::mem::size_of::<u64>()];\n\n let len_buf = try_read_exact(reader, len_buf)?;\n\n match len_buf {\n\n Some(buf) => buf,\n\n None => return Ok(None),\n\n }\n\n };\n\n let len = u64::from_le_bytes(len_buf);\n\n let expect_cksum = {\n\n let mut buf = [0; std::mem::size_of::<u32>()];\n\n reader.read_exact(&mut buf)?;\n\n u32::from_le_bytes(buf)\n\n };\n\n\n\n if check_integrity {\n\n crate::utils::verify_checksum(&len_buf, expect_cksum)?;\n\n }\n\n\n\n Ok(Some(len as usize))\n\n}\n\n\n", "file_path": "src/io/sync.rs", "rank": 14, "score": 33174.48235377026 }, { "content": "fn try_read_exact<R, B>(reader: &mut R, mut buf: B) -> Result<Option<B>>\n\nwhere\n\n R: Read,\n\n B: AsMut<[u8]>,\n\n{\n\n let as_mut = buf.as_mut();\n\n let mut offset = 0;\n\n let len = as_mut.len();\n\n\n\n loop {\n\n match reader.read(&mut as_mut[offset..]) {\n\n Ok(0) => {\n\n if offset == len {\n\n return Ok(Some(buf));\n\n } else if offset == 0 {\n\n return Ok(None);\n\n } else {\n\n return Err(Error::UnexpectedEof);\n\n }\n\n }\n", "file_path": "src/io/sync.rs", "rank": 15, "score": 32667.324106942142 }, { "content": "/// Try to extract raw bytes of a record from a generic reader.\n\n///\n\n/// It reads the record length and data from a generic reader,\n\n/// and verifies the checksum if requested.\n\n/// If the end of file is reached, it returns `Ok(None)`.\n\npub fn try_read_record<R>(reader: &mut R, check_integrity: bool) -> Result<Option<Vec<u8>>>\n\nwhere\n\n R: Read,\n\n{\n\n let len = match try_read_len(reader, check_integrity)? {\n\n Some(len) => len,\n\n None => return Ok(None),\n\n };\n\n let data = try_read_record_data(reader, len, check_integrity)?;\n\n Ok(Some(data))\n\n}\n\n\n", "file_path": "src/io/sync.rs", "rank": 16, "score": 32062.05330360141 }, { "content": "/// Read the record raw bytes with given length from a generic reader.\n\n///\n\n/// It is internally called by [try_read_record].\n\npub fn try_read_record_data<R>(reader: &mut R, len: usize, check_integrity: bool) -> Result<Vec<u8>>\n\nwhere\n\n R: Read,\n\n{\n\n let buf = {\n\n let mut buf = vec![0u8; len];\n\n reader.read_exact(&mut buf)?;\n\n buf\n\n };\n\n let expect_cksum = {\n\n let mut buf = [0; std::mem::size_of::<u32>()];\n\n reader.read_exact(&mut buf)?;\n\n u32::from_le_bytes(buf)\n\n };\n\n\n\n if check_integrity {\n\n crate::utils::verify_checksum(&buf, expect_cksum)?;\n\n }\n\n Ok(buf)\n\n}\n\n\n", "file_path": "src/io/sync.rs", "rank": 17, "score": 30483.39471262772 }, { "content": "pub fn checksum(buf: &[u8]) -> u32 {\n\n const CASTAGNOLI: Crc<u32> = Crc::<u32>::new(&crc::CRC_32_ISCSI);\n\n let cksum = CASTAGNOLI.checksum(buf);\n\n ((cksum >> 15) | (cksum << 17)).wrapping_add(0xa282ead8u32)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 18, "score": 30359.467697024684 }, { "content": "use super::RecordReaderConfig;\n\nuse crate::{\n\n error::{Error, Result},\n\n protobuf::{Event, Example},\n\n record::Record,\n\n};\n\nuse async_std::{fs::File, io::BufReader, path::Path};\n\nuse futures::{\n\n io::AsyncRead,\n\n stream::{BoxStream, Stream, StreamExt},\n\n};\n\nuse pin_project::pin_project;\n\nuse std::{\n\n marker::PhantomData,\n\n pin::Pin,\n\n task::{Context, Poll},\n\n};\n\n\n\npub type BytesStream<R> = RecordStream<Vec<u8>, R>;\n\npub type ExampleStream<R> = RecordStream<Example, R>;\n", "file_path": "src/record_reader/async.rs", "rank": 22, "score": 17.797751429191482 }, { "content": "use super::{Position, RecordIndex, RecordIndexerConfig};\n\nuse crate::{\n\n error::{Error, Result},\n\n record::Record,\n\n utils,\n\n};\n\nuse itertools::Itertools as _;\n\nuse std::{\n\n borrow::Cow,\n\n fs::File,\n\n io::{prelude::*, BufReader, SeekFrom},\n\n path::{Path, PathBuf},\n\n sync::Arc,\n\n};\n\n\n\nimpl RecordIndex {\n\n pub fn load<T>(&self) -> Result<T>\n\n where\n\n T: Record,\n\n {\n", "file_path": "src/indexer/sync.rs", "rank": 23, "score": 17.729235758250447 }, { "content": "//! TFRecord data reader.\n\n//!\n\n//! The [RecordIter] iterator reads records from a file.\n\n//!\n\n//! The [RecordStream] reads records from a file and can cooperated with future's [stream](futures::stream) API..\n\n\n\n#[cfg(feature = \"async\")]\n\nmod r#async;\n\n#[cfg(feature = \"async\")]\n\npub use r#async::*;\n\n\n\nmod sync;\n\npub use sync::*;\n\n\n\n/// Configuration for record reader.\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct RecordReaderConfig {\n\n pub check_integrity: bool,\n\n}\n\n\n\nimpl Default for RecordReaderConfig {\n\n fn default() -> Self {\n\n Self {\n\n check_integrity: true,\n\n }\n\n }\n\n}\n", "file_path": "src/record_reader/mod.rs", "rank": 24, "score": 14.05644337648671 }, { "content": "use std::{borrow::Cow, cmp, iter, ops::Neg};\n\n\n\nuse crate::{\n\n ensure_argument,\n\n error::{Error, Result},\n\n protobuf::HistogramProto,\n\n};\n\nuse itertools::{chain, izip};\n\nuse noisy_float::prelude::*;\n\nuse num_traits::{NumCast, ToPrimitive};\n\n\n\nimpl HistogramProto {\n\n /// Create a histogram with bucket limits.\n\n ///\n\n /// The `bucket_limit` must be an ordered sequence of finite values.\n\n /// Otherwise it returns an error. The range of each bucket is defined by\n\n ///\n\n /// - i == 0: [f64::MIN]..`limit[0]`\n\n /// - i > 0: `limit[i-1]`..`limit[i]`\n\n pub fn new<'a, L>(bucket_limit: L) -> Result<Self>\n", "file_path": "src/protobuf_ext/histogram_ext.rs", "rank": 25, "score": 13.555520087957975 }, { "content": "#![cfg(all(feature = \"async\"))]\n\n\n\nmod common;\n\n\n\nuse common::*;\n\nuse futures::stream::{StreamExt as _, TryStreamExt as _};\n\nuse tfrecord::{Example, FeatureKind};\n\n\n\n#[async_std::test]\n\nasync fn indexer_stream_test() -> Result<()> {\n\n tfrecord::indexer::load_paths_async([&*INPUT_TFRECORD_PATH], Default::default())\n\n .and_then(|index| async move {\n\n let example: Example = index.load_async().await?;\n\n Ok(example)\n\n })\n\n .enumerate()\n\n .map(|(index, example)| anyhow::Ok((index, example?)))\n\n .try_for_each(|(example_index, example)| async move {\n\n // enumerate features in an example\n\n for (feature_index, (name, feature)) in example.into_iter().enumerate() {\n", "file_path": "tests/indexer_async.rs", "rank": 26, "score": 13.547144640285696 }, { "content": "use super::IntoHistogram;\n\nuse crate::{\n\n error::Error,\n\n protobuf::{\n\n summary::{value, Audio, Image, Value},\n\n Summary, TensorProto,\n\n },\n\n protobuf_ext::IntoImageList,\n\n};\n\n\n\nimpl Summary {\n\n /// Build a scalar summary.\n\n pub fn from_scalar(tag: impl ToString, value: f32) -> Result<Summary, Error> {\n\n let summary = Summary {\n\n value: vec![Value {\n\n node_name: \"\".into(),\n\n tag: tag.to_string(),\n\n metadata: None,\n\n value: Some(value::Value::SimpleValue(value)),\n\n }],\n", "file_path": "src/protobuf_ext/summary_ext.rs", "rank": 27, "score": 13.31031719514166 }, { "content": "use crate::{\n\n error::{Error, Result},\n\n protobuf::summary::Image,\n\n};\n\n\n\n/// Enumerations of color spaces in [Image](crate::protobuf::summary::Image)'s colorspace field.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\n#[repr(i32)]\n\npub enum ColorSpace {\n\n Luma = 1,\n\n LumaA = 2,\n\n Rgb = 3,\n\n Rgba = 4,\n\n DigitalYuv = 5,\n\n Bgra = 6,\n\n}\n\n\n\nimpl ColorSpace {\n\n /// Get number of channels for the color space.\n\n pub fn num_channels(&self) -> usize {\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 28, "score": 12.600974344454443 }, { "content": "#![cfg(feature = \"async\")]\n\n\n\nmod common;\n\n\n\nuse common::*;\n\nuse futures::stream::TryStreamExt as _;\n\nuse tfrecord::{BytesAsyncWriter, BytesStream, Example, ExampleAsyncWriter, ExampleStream};\n\n\n\n#[async_std::test]\n\nasync fn stream_test() {\n\n // bytes\n\n {\n\n let stream = BytesStream::open(&*INPUT_TFRECORD_PATH, Default::default())\n\n .await\n\n .unwrap();\n\n stream.try_collect::<Vec<Vec<u8>>>().await.unwrap();\n\n }\n\n\n\n // examples\n\n {\n", "file_path": "tests/example_async.rs", "rank": 29, "score": 12.58971803897213 }, { "content": "use super::EventWriterConfig;\n\nuse crate::{\n\n error::{Error, Result},\n\n event::EventMeta,\n\n protobuf::{\n\n summary::{Audio, Image},\n\n Event, Summary, TensorProto,\n\n },\n\n protobuf_ext::{IntoHistogram, IntoImageList},\n\n record_writer::RecordAsyncWriter,\n\n};\n\nuse async_std::{fs::File, io::BufWriter, path::Path};\n\nuse futures::io::AsyncWrite;\n\nuse std::{borrow::Cow, convert::TryInto, string::ToString};\n\n\n\n/// The event writer.\n\n///\n\n/// It provies `write_scalar`, `write_image` methods, etc.\n\n///\n\n/// It can be built from a writer using [from_writer](EventAsyncWriter::from_writer), or write a new file\n", "file_path": "src/event_writer/async.rs", "rank": 30, "score": 12.099527787985703 }, { "content": "use std::mem;\n\n\n\nuse crate::error::{Error, Result};\n\nuse futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};\n\n\n\n/// Try to extract raw bytes of a record from a generic reader.\n\n///\n\n/// It reads the record length and data from a generic reader,\n\n/// and verifies the checksum if requested.\n\n/// If the end of file is reached, it returns `Ok(None)`.\n\npub async fn try_read_record<R>(reader: &mut R, check_integrity: bool) -> Result<Option<Vec<u8>>>\n\nwhere\n\n R: AsyncRead + Unpin,\n\n{\n\n let len = match try_read_len(reader, check_integrity).await? {\n\n Some(len) => len,\n\n None => return Ok(None),\n\n };\n\n let data = try_read_record_data(reader, len, check_integrity).await?;\n\n Ok(Some(data))\n", "file_path": "src/io/async.rs", "rank": 31, "score": 11.851543580518669 }, { "content": "use crate::{\n\n error::{Error, Result},\n\n protobuf::Example,\n\n record::Record,\n\n};\n\nuse async_std::{fs::File, io::BufWriter, path::Path};\n\nuse futures::{\n\n io::{AsyncWrite, AsyncWriteExt as _},\n\n sink,\n\n sink::Sink,\n\n};\n\nuse std::marker::PhantomData;\n\n\n\n/// Alias to [RecordAsyncWriter] which input record type [Vec<u8>](Vec).\n\npub type BytesAsyncWriter<W> = RecordAsyncWriter<Vec<u8>, W>;\n\n\n\n/// Alias to [RecordAsyncWriter] which input record type [Example].\n\npub type ExampleAsyncWriter<W> = RecordAsyncWriter<Example, W>;\n\n\n\n/// The record writer.\n", "file_path": "src/record_writer/async.rs", "rank": 32, "score": 11.748792811397582 }, { "content": "//! Error types and error handling utilities.\n\n\n\nuse std::{borrow::Cow, convert::Infallible};\n\n\n\n/// The result with error type defaults to [Error].\n\npub type Result<T, E = Error> = std::result::Result<T, E>;\n\n\n\n/// The error type for this crate.\n\n#[derive(Debug, thiserror::Error)]\n\npub enum Error {\n\n #[error(\"checksum mismatch error: expect {expect:#010x}, but found {found:#010x}\")]\n\n ChecksumMismatch { expect: u32, found: u32 },\n\n #[error(\"unexpected end of file\")]\n\n UnexpectedEof,\n\n #[error(\"errored to decode example: {0}\")]\n\n ExampleDecodeError(prost::DecodeError),\n\n #[error(\"errored to encode example: {0}\")]\n\n ExampleEncodeError(prost::EncodeError),\n\n #[error(\"I/O error: {0}\")]\n\n IoError(std::io::Error),\n", "file_path": "src/error.rs", "rank": 33, "score": 11.535752746221304 }, { "content": "impl<T> RecordStream<T, BufReader<File>>\n\nwhere\n\n T: Record,\n\n{\n\n /// Load records from a file.\n\n pub async fn open<P>(path: P, config: RecordReaderConfig) -> Result<Self>\n\n where\n\n T: Record,\n\n P: AsRef<Path>,\n\n {\n\n let reader = BufReader::new(File::open(path).await?);\n\n let reader = Self::from_reader(reader, config);\n\n Ok(reader)\n\n }\n\n}\n\n\n\nimpl<T, R> Stream for RecordStream<T, R>\n\nwhere\n\n T: Record,\n\n R: AsyncRead,\n\n{\n\n type Item = Result<T>;\n\n\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {\n\n self.project().stream.poll_next(cx)\n\n }\n\n}\n", "file_path": "src/record_reader/async.rs", "rank": 34, "score": 11.366423017502214 }, { "content": "\n\n#[cfg(feature = \"with-image\")]\n\nmod with_image {\n\n use super::*;\n\n use crate::{error::Error, protobuf::summary::Image};\n\n use image::{\n\n codecs::png::PngEncoder, flat::SampleLayout, ColorType, DynamicImage, FlatSamples,\n\n ImageBuffer, ImageEncoder as _, Pixel,\n\n };\n\n use std::{io::Cursor, ops::Deref};\n\n\n\n impl TryFrom<ColorType> for ColorSpace {\n\n type Error = Error;\n\n\n\n fn try_from(from: ColorType) -> Result<Self, Self::Error> {\n\n let color_space = match from {\n\n ColorType::L8 => ColorSpace::Luma,\n\n ColorType::La8 => ColorSpace::LumaA,\n\n ColorType::Rgb8 => ColorSpace::Rgb,\n\n ColorType::Rgba8 => ColorSpace::Rgba,\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 35, "score": 11.297637117173938 }, { "content": " {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n HistogramProto::try_from_iter(self.iter().cloned())\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"with-image\")]\n\nmod with_image {\n\n use super::*;\n\n use image::{DynamicImage, ImageBuffer, Pixel};\n\n use std::ops::Deref;\n\n\n\n // DynamicImage to histogram\n\n impl IntoHistogram for &DynamicImage {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n use DynamicImage::*;\n\n let histogram = match self {\n\n ImageLuma8(buffer) => buffer.try_into_histogram()?,\n\n ImageLumaA8(buffer) => buffer.try_into_histogram()?,\n", "file_path": "src/protobuf_ext/histogram_ext.rs", "rank": 36, "score": 11.136927242822894 }, { "content": "use crate::error::{Error, Result};\n\nuse std::io::prelude::*;\n\n\n\n/// Try to extract raw bytes of a record from a generic reader.\n\n///\n\n/// It reads the record length and data from a generic reader,\n\n/// and verifies the checksum if requested.\n\n/// If the end of file is reached, it returns `Ok(None)`.\n", "file_path": "src/io/sync.rs", "rank": 37, "score": 11.12626740444646 }, { "content": "\n\n impl TchTensorAsImageList {\n\n pub fn new(\n\n color_space: ColorSpace,\n\n order: TchChannelOrder,\n\n tensor: Tensor,\n\n ) -> Result<Self, Error> {\n\n Ok(Self {\n\n color_space,\n\n order,\n\n tensor,\n\n })\n\n }\n\n }\n\n\n\n impl IntoImageList for TchTensorAsImageList {\n\n fn into_image_list(self) -> Result<Vec<Image>> {\n\n use TchChannelOrder as O;\n\n\n\n let Self {\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 38, "score": 10.981940701105529 }, { "content": "pub type EventStream<R> = RecordStream<Event, R>;\n\n\n\n/// Stream of record `T` from reader `R`.\n\n#[pin_project]\n\npub struct RecordStream<T, R>\n\nwhere\n\n T: Record,\n\n R: AsyncRead,\n\n{\n\n #[pin]\n\n stream: BoxStream<'static, Result<T, Error>>,\n\n _phantom: PhantomData<R>,\n\n}\n\n\n\nimpl<T, R> RecordStream<T, R>\n\nwhere\n\n T: Record,\n\n R: AsyncRead,\n\n{\n\n /// Load records from a reader type with [AsyncRead] trait.\n", "file_path": "src/record_reader/async.rs", "rank": 39, "score": 10.912596514830575 }, { "content": "//! Summary record writer.\n\n\n\nmod sync;\n\npub use sync::*;\n\n\n\n#[cfg(feature = \"async\")]\n\nmod r#async;\n\n#[cfg(feature = \"async\")]\n\npub use r#async::*;\n\n\n\nuse crate::{error::Error, utils};\n\nuse std::{\n\n borrow::Cow,\n\n ffi::{OsStr, OsString},\n\n path::PathBuf,\n\n string::ToString,\n\n time::SystemTime,\n\n};\n\n\n\n/// The event writer initializer.\n", "file_path": "src/event_writer/mod.rs", "rank": 40, "score": 10.873697701286138 }, { "content": "use futures::stream::TryStreamExt;\n\nuse once_cell::sync::Lazy;\n\nuse std::{\n\n fs::{self, File},\n\n io::{self, prelude::*, BufWriter},\n\n path::{Path, PathBuf},\n\n};\n\nuse tfrecord::{Error, ExampleStream, FeatureKind};\n\n\n\nstatic INPUT_TFRECORD_PATH: Lazy<PathBuf> = Lazy::new(|| {\n\n (move || {\n\n let url = include_str!(\"../tests/tfrecord_link.txt\");\n\n let path = DATA_DIR.join(\"input.tfrecord\");\n\n let mut writer = BufWriter::new(File::create(&path)?);\n\n io::copy(&mut ureq::get(url).call()?.into_reader(), &mut writer)?;\n\n writer.flush()?;\n\n anyhow::Ok(path)\n\n })()\n\n .unwrap()\n\n});\n", "file_path": "examples/tfrecord_info_async.rs", "rank": 41, "score": 10.871685368969496 }, { "content": "use crate::protobuf::{Example, Feature, Features};\n\nuse std::collections::HashMap;\n\n\n\nimpl Example {\n\n pub fn into_vec(self) -> Vec<(String, Feature)> {\n\n self.into_iter().collect()\n\n }\n\n\n\n pub fn into_hash_map(self) -> HashMap<String, Feature> {\n\n self.into_iter().collect()\n\n }\n\n\n\n #[allow(clippy::should_implement_trait)]\n\n pub fn into_iter(self) -> impl Iterator<Item = (String, Feature)> {\n\n self.features\n\n .into_iter()\n\n .flat_map(|features| features.feature)\n\n }\n\n\n\n pub fn empty() -> Self {\n", "file_path": "src/protobuf_ext/example_ext.rs", "rank": 42, "score": 10.665762298591648 }, { "content": "\n\n impl<P, C> IntoHistogram for ImageBuffer<P, C>\n\n where\n\n P: 'static + Pixel,\n\n P::Subpixel: 'static,\n\n C: Deref<Target = [P::Subpixel]>,\n\n P::Subpixel: ToPrimitive,\n\n {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n (&self).try_into_histogram()\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"with-ndarray\")]\n\nmod with_ndarray {\n\n use super::*;\n\n use ndarray::{ArrayBase, Data, Dimension, RawData};\n\n\n\n impl<S, D> IntoHistogram for &ArrayBase<S, D>\n", "file_path": "src/protobuf_ext/histogram_ext.rs", "rank": 43, "score": 10.577152255073038 }, { "content": " Ok(())\n\n }\n\n\n\n // pub fn write_graph<>(&mut self, tag: impl ToString, event_meta: EventMeta) -> Result<(), Error>\n\n //\n\n // {\n\n // todo!();\n\n // }\n\n\n\n /// Write a custom event.\n\n pub fn write_event(&mut self, event: Event) -> Result<()> {\n\n self.events_writer.send(event)?;\n\n if self.auto_flush {\n\n self.events_writer.flush()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Flush this output stream.\n\n pub fn flush(&mut self) -> Result<()> {\n\n self.events_writer.flush()?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/event_writer/sync.rs", "rank": 44, "score": 10.559600911264914 }, { "content": " unreachable!();\n\n }\n\n}\n\n\n\n#[cfg(feature = \"with-tch\")]\n\nimpl From<tch::TchError> for Error {\n\n fn from(error: tch::TchError) -> Self {\n\n Self::TchError(error)\n\n }\n\n}\n\n\n\nmacro_rules! ensure_argument {\n\n ($cond:expr, $($arg:tt) *) => {\n\n if !$cond {\n\n return Err(crate::error::Error::invalid_argument(format!( $($arg)* )));\n\n }\n\n };\n\n}\n\npub(crate) use ensure_argument;\n", "file_path": "src/error.rs", "rank": 45, "score": 10.381994031930445 }, { "content": "use super::EventWriterConfig;\n\nuse crate::{\n\n error::{Error, Result},\n\n event::EventMeta,\n\n protobuf::{\n\n summary::{Audio, Image},\n\n Event, Summary, TensorProto,\n\n },\n\n protobuf_ext::{IntoHistogram, IntoImageList},\n\n record_writer::RecordWriter,\n\n};\n\nuse std::{\n\n borrow::Cow,\n\n convert::TryInto,\n\n fs,\n\n fs::File,\n\n io::{BufWriter, Write},\n\n path::Path,\n\n string::ToString,\n\n};\n", "file_path": "src/event_writer/sync.rs", "rank": 46, "score": 10.282938268977185 }, { "content": " P: 'static + Pixel<Subpixel = u8>,\n\n C: Deref<Target = [P::Subpixel]> + AsRef<[P::Subpixel]>,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: &ImageBuffer<P, C>) -> Result<Self, Self::Error> {\n\n Self::try_from(from.as_flat_samples())\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"with-tch\")]\n\npub use with_tch::*;\n\n#[cfg(feature = \"with-tch\")]\n\nmod with_tch {\n\n use super::*;\n\n use crate::{\n\n error::{ensure_argument, Error},\n\n protobuf::summary::Image,\n\n };\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 47, "score": 10.221732783530472 }, { "content": "impl<T, R> Iterator for RecordIter<T, R>\n\nwhere\n\n T: Record,\n\n R: Read,\n\n{\n\n type Item = Result<T>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let reader = self.reader.as_mut()?;\n\n let bytes: Option<Result<_>> =\n\n crate::io::sync::try_read_record(reader, self.check_integrity).transpose();\n\n\n\n if bytes.is_none() {\n\n self.reader = None;\n\n }\n\n let record = bytes?.and_then(T::from_bytes);\n\n Some(record)\n\n }\n\n}\n", "file_path": "src/record_reader/sync.rs", "rank": 48, "score": 10.177963595678818 }, { "content": " pub fn from_reader(reader: R, config: RecordReaderConfig) -> Self\n\n where\n\n R: 'static + Unpin + Send,\n\n {\n\n let RecordReaderConfig { check_integrity } = config;\n\n\n\n let stream = futures::stream::try_unfold(reader, move |mut reader| async move {\n\n let bytes = crate::io::r#async::try_read_record(&mut reader, check_integrity).await?;\n\n let record = bytes.map(T::from_bytes).transpose()?;\n\n Ok(record.map(|record| (record, reader)))\n\n })\n\n .boxed();\n\n\n\n Self {\n\n stream,\n\n _phantom: PhantomData,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/record_reader/async.rs", "rank": 49, "score": 10.056577690754757 }, { "content": "/// Write the raw record bytes to a generic writer.\n\npub async fn try_write_record<W>(writer: &mut W, bytes: Vec<u8>) -> Result<()>\n\nwhere\n\n W: AsyncWrite + Unpin,\n\n{\n\n // write data size\n\n {\n\n let len = bytes.len();\n\n let len_buf = len.to_le_bytes();\n\n let cksum = crate::utils::checksum(&len_buf);\n\n let cksum_buf = cksum.to_le_bytes();\n\n\n\n writer.write_all(&len_buf).await?;\n\n writer.write_all(&cksum_buf).await?;\n\n }\n\n\n\n // write data\n\n {\n\n let cksum = crate::utils::checksum(&bytes);\n\n let cksum_buf = cksum.to_le_bytes();\n", "file_path": "src/io/async.rs", "rank": 50, "score": 10.031051410677277 }, { "content": " T: Record,\n\n W: Write,\n\n{\n\n /// Build a writer from a writer with [Write] trait.\n\n pub fn from_writer(writer: W) -> Result<Self> {\n\n Ok(Self {\n\n writer,\n\n _phantom: PhantomData,\n\n })\n\n }\n\n\n\n /// Write a record.\n\n ///\n\n /// The method is enabled if the underlying writer implements [Write].\n\n pub fn send(&mut self, record: T) -> Result<()> {\n\n let bytes = T::to_bytes(record)?;\n\n crate::io::sync::try_write_record(&mut self.writer, bytes)?;\n\n Ok(())\n\n }\n\n\n\n /// Flush the output stream.\n\n pub fn flush(&mut self) -> Result<()> {\n\n self.writer.flush()?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/record_writer/sync.rs", "rank": 51, "score": 9.899448850518713 }, { "content": " Ok(())\n\n }\n\n\n\n /// Flush the output stream asynchronously.\n\n pub async fn flush(&mut self) -> Result<()> {\n\n self.writer.flush().await?;\n\n Ok(())\n\n }\n\n\n\n /// Convert into a [Sink].\n\n pub fn into_sink(self) -> impl Sink<T, Error = Error> {\n\n sink::unfold(self, |mut writer, record| async move {\n\n writer.send(record).await?;\n\n Ok(writer)\n\n })\n\n }\n\n}\n", "file_path": "src/record_writer/async.rs", "rank": 52, "score": 9.819612347166062 }, { "content": " use image::{flat::SampleLayout, DynamicImage, FlatSamples, ImageBuffer, Pixel, Primitive};\n\n use std::ops::Deref;\n\n\n\n impl<T> TryFrom<&FlatSamples<&[T]>> for TensorProto\n\n where\n\n T: TensorProtoElement,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: &FlatSamples<&[T]>) -> Result<Self, Self::Error> {\n\n let FlatSamples {\n\n layout:\n\n SampleLayout {\n\n width,\n\n height,\n\n channels,\n\n ..\n\n },\n\n ..\n\n } = *from;\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 53, "score": 9.815652256642238 }, { "content": " }\n\n}\n\n\n\nimpl<T, W> RecordAsyncWriter<T, W>\n\nwhere\n\n T: Record,\n\n W: AsyncWrite + Unpin,\n\n{\n\n /// Build a writer from a writer with [AsyncWrite] trait.\n\n pub fn from_writer(writer: W) -> Result<Self> {\n\n Ok(Self {\n\n writer,\n\n _phantom: PhantomData,\n\n })\n\n }\n\n\n\n /// Write a record.\n\n pub async fn send(&mut self, record: T) -> Result<()> {\n\n let bytes = T::to_bytes(record)?;\n\n crate::io::r#async::try_write_record(&mut self.writer, bytes).await?;\n", "file_path": "src/record_writer/async.rs", "rank": 54, "score": 9.539039382796744 }, { "content": "use super::RecordReaderConfig;\n\nuse crate::{\n\n error::Result,\n\n protobuf::{Event, Example},\n\n record::Record,\n\n};\n\nuse std::{\n\n fs::File,\n\n io::{prelude::*, BufReader},\n\n marker::PhantomData,\n\n path::Path,\n\n};\n\n\n\npub type BytesIter<R> = RecordIter<Vec<u8>, R>;\n\npub type ExampleIter<R> = RecordIter<Example, R>;\n\npub type EventIter<R> = RecordIter<Event, R>;\n\n\n\n/// Iterator of record `T` from reader `R`.\n\npub struct RecordIter<T, R>\n\nwhere\n", "file_path": "src/record_reader/sync.rs", "rank": 55, "score": 9.441248969556613 }, { "content": " \"the color space and channel size mismatch\"\n\n );\n\n\n\n Ok(Self {\n\n color_space,\n\n order,\n\n tensor,\n\n })\n\n }\n\n }\n\n\n\n // to Image\n\n impl TryFrom<TchTensorAsImage> for Image {\n\n type Error = Error;\n\n\n\n fn try_from(from: TchTensorAsImage) -> Result<Self, Self::Error> {\n\n use TchChannelOrder as O;\n\n\n\n // CHW to HWC\n\n let hwc_tensor = match from.order {\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 56, "score": 9.432731933225698 }, { "content": "static DATA_DIR: Lazy<&Path> = Lazy::new(|| {\n\n let path = Path::new(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/test_data\"));\n\n fs::create_dir_all(path).unwrap();\n\n path\n\n});\n\n\n\n#[async_std::main]\n\npub async fn main() -> Result<(), Error> {\n\n // use init pattern to construct the tfrecord stream\n\n let stream = ExampleStream::open(&*INPUT_TFRECORD_PATH, Default::default()).await?;\n\n\n\n // print header\n\n println!(\"example_no\\tfeature_no\\tname\\ttype\\tsize\");\n\n\n\n // enumerate examples\n\n stream\n\n .try_fold(0, |example_index, example| {\n\n async move {\n\n // enumerate features in an example\n\n for (feature_index, (name, feature)) in example.into_iter().enumerate() {\n", "file_path": "examples/tfrecord_info_async.rs", "rank": 57, "score": 9.365035010765045 }, { "content": " P: 'static + Pixel<Subpixel = T>,\n\n C: Deref<Target = [P::Subpixel]> + AsRef<[P::Subpixel]>,\n\n T: 'static + TensorProtoElement + Primitive,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: ImageBuffer<P, C>) -> Result<Self, Self::Error> {\n\n Self::try_from(&from)\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"with-ndarray\")]\n\nmod with_ndarray {\n\n use super::*;\n\n use ndarray::{ArrayBase, Data, Dimension, RawData};\n\n\n\n impl<S, D, T> From<&ArrayBase<S, D>> for TensorProto\n\n where\n\n D: Dimension,\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 58, "score": 9.149932072374634 }, { "content": "\n\n impl_to_le_bytes!(u8, DataType::DtUint8);\n\n impl_to_le_bytes!(u16, DataType::DtUint16);\n\n impl_to_le_bytes!(u32, DataType::DtUint32);\n\n impl_to_le_bytes!(u64, DataType::DtUint64);\n\n impl_to_le_bytes!(i8, DataType::DtInt8);\n\n impl_to_le_bytes!(i16, DataType::DtInt16);\n\n impl_to_le_bytes!(i32, DataType::DtInt32);\n\n impl_to_le_bytes!(i64, DataType::DtInt64);\n\n impl_to_le_bytes!(f32, DataType::DtFloat);\n\n impl_to_le_bytes!(f64, DataType::DtDouble);\n\n}\n\n\n\npub use to_shape::*;\n\nmod to_shape {\n\n use super::*;\n\n use num::Unsigned;\n\n use num_traits::{NumCast, ToPrimitive};\n\n\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 59, "score": 9.115752645577283 }, { "content": "//! Summary and event types.\n\n\n\nuse crate::protobuf::{event::What, Event, Summary};\n\nuse std::time::SystemTime;\n\n\n\n/// [Event] metadata.\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct EventMeta {\n\n /// The wall clock time in microseconds.\n\n ///\n\n /// If the field is set to `None`, it sets to current EPOCH time when the event is built.\n\n pub wall_time: Option<f64>,\n\n /// The global step.\n\n pub step: i64,\n\n}\n\n\n\nimpl EventMeta {\n\n /// Create from a global step and a wall time.\n\n pub fn new(step: i64, wall_time: f64) -> Self {\n\n Self {\n", "file_path": "src/event.rs", "rank": 60, "score": 8.905407977338083 }, { "content": "\n\n fn try_from(from: FlatSamples<Vec<T>>) -> Result<Self, Self::Error> {\n\n Self::try_from(&from)\n\n }\n\n }\n\n\n\n // DynamicImage to tensor\n\n\n\n impl TryFrom<&DynamicImage> for TensorProto {\n\n type Error = Error;\n\n\n\n fn try_from(from: &DynamicImage) -> Result<Self, Self::Error> {\n\n use DynamicImage::*;\n\n let tensor = match from {\n\n ImageLuma8(buffer) => Self::try_from(buffer)?,\n\n ImageLumaA8(buffer) => Self::try_from(buffer)?,\n\n ImageRgb8(buffer) => Self::try_from(buffer)?,\n\n ImageRgba8(buffer) => Self::try_from(buffer)?,\n\n ImageLuma16(buffer) => Self::try_from(buffer)?,\n\n ImageLumaA16(buffer) => Self::try_from(buffer)?,\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 61, "score": 8.859534237699052 }, { "content": " where\n\n T: ToPrimitive,\n\n {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n HistogramProto::try_from_iter(self)\n\n }\n\n }\n\n\n\n impl<T> IntoHistogram for Vec<T>\n\n where\n\n T: ToPrimitive,\n\n {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n HistogramProto::try_from_iter(self)\n\n }\n\n }\n\n\n\n impl<T> IntoHistogram for &Vec<T>\n\n where\n\n T: ToPrimitive + Clone,\n", "file_path": "src/protobuf_ext/histogram_ext.rs", "rank": 62, "score": 8.643639699416248 }, { "content": "# tfrecord\n\n\n\n\\[ [API doc](https://docs.rs/tfrecord/) | [crates.io](https://crates.io/crates/tfrecord/) \\]\n\n\n\nThe crate provides readers/writers for TensorFlow TFRecord data format. It has the following features.\n\n\n\n- Provide both high level `Example` type as well as low level `Vec<u8>` bytes de/serialization.\n\n- Support **async/await** syntax. It's easy to work with [futures-rs](https://github.com/rust-lang/futures-rs).\n\n- Interoperability with [serde](https://crates.io/crates/serde), [image](https://crates.io/crates/image), [ndarray](https://crates.io/crates/ndarray) and [tch](https://crates.io/crates/tch).\n\n- Support TensorBoard! ([exampe code](examples/tensorboard.rs))\n\n\n\n## License\n\n\n\nMIT license. See [LICENSE](LICENSE) file for full license.\n", "file_path": "README.md", "rank": 63, "score": 8.624109421283086 }, { "content": "use crate::{error::Result, protobuf::Example, record::Record};\n\nuse std::{\n\n fs::File,\n\n io::{BufWriter, Write},\n\n marker::PhantomData,\n\n path::Path,\n\n};\n\n\n\n/// Alias to [RecordWriter] which input record type [Vec<u8>](Vec).\n\npub type BytesWriter<W> = RecordWriter<Vec<u8>, W>;\n\n\n\n/// Alias to [RecordWriter] which input record type [Example].\n\npub type ExampleWriter<W> = RecordWriter<Example, W>;\n\n\n\n/// The record writer.\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct RecordWriter<T, W>\n\nwhere\n\n T: Record,\n\n{\n", "file_path": "src/record_writer/sync.rs", "rank": 64, "score": 8.613998925381921 }, { "content": "mod utils;\n\n\n\n// re-exports\n\n\n\npub use error::*;\n\npub use event::*;\n\npub use event_writer::*;\n\npub use protobuf::{Event, Example, Feature, HistogramProto, Summary};\n\npub use protobuf_ext::*;\n\npub use record::*;\n\npub use record_reader::*;\n\npub use record_writer::*;\n", "file_path": "src/lib.rs", "rank": 65, "score": 8.504062778211363 }, { "content": " image: impl TryInto<Image, Error = impl Into<Error>>,\n\n ) -> Result<()> {\n\n let summary = Summary::from_image(tag, image)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event)?;\n\n if self.auto_flush {\n\n self.events_writer.flush()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write a summary with multiple images.\n\n pub fn write_image_list(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n images: impl IntoImageList,\n\n ) -> Result<()> {\n\n let summary = Summary::from_image_list(tag, images)?;\n\n let event = event_meta.into().build_with_summary(summary);\n", "file_path": "src/event_writer/sync.rs", "rank": 66, "score": 8.467680816076538 }, { "content": " let mut buf = [0; mem::size_of::<u32>()];\n\n reader.read_exact(&mut buf).await?;\n\n u32::from_le_bytes(buf)\n\n };\n\n\n\n if check_integrity {\n\n crate::utils::verify_checksum(&len_buf, expect_cksum)?;\n\n }\n\n\n\n Ok(Some(len as usize))\n\n}\n\n\n\n/// Read the record raw bytes with given length from a generic reader.\n\n///\n\n/// It is internally called by [try_read_record].\n\npub async fn try_read_record_data<R>(\n\n reader: &mut R,\n\n len: usize,\n\n check_integrity: bool,\n\n) -> Result<Vec<u8>>\n", "file_path": "src/io/async.rs", "rank": 67, "score": 8.421726041962522 }, { "content": "//! Marker traits.\n\n\n\nuse crate::{\n\n error::Error,\n\n protobuf::{Event, Example},\n\n};\n\nuse prost::Message as _;\n\n\n\n/// Mark types the is serailized to or deserialized from TFRecord format.\n", "file_path": "src/record.rs", "rank": 69, "score": 8.359177102381482 }, { "content": " ColorType::L16 => ColorSpace::Luma,\n\n ColorType::La16 => ColorSpace::LumaA,\n\n ColorType::Rgb16 => ColorSpace::Rgb,\n\n ColorType::Rgba16 => ColorSpace::Rgba,\n\n _ => {\n\n return Err(Error::conversion(\"color space is not supported\"));\n\n }\n\n };\n\n Ok(color_space)\n\n }\n\n }\n\n\n\n // DynamicImage to image\n\n\n\n impl TryFrom<&DynamicImage> for Image {\n\n type Error = Error;\n\n\n\n fn try_from(from: &DynamicImage) -> Result<Self, Self::Error> {\n\n use DynamicImage::*;\n\n let image = match from {\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 70, "score": 8.348728099381463 }, { "content": "\n\n/// The event writer.\n\n///\n\n/// It provies `write_scalar`, `write_image` methods, etc.\n\n///\n\n/// It can be built from a writer using [from_writer](EventWriter::from_writer), or write a new file\n\n/// specified by path prefix using [from_writer](EventWriter::from_prefix).\n\n\n\n#[cfg_attr(\n\n feature = \"tch\",\n\n doc = r##\"\n\n```rust\n\n# fn main() -> anyhow::Result<()> {\n\nuse anyhow::Result;\n\nuse std::time::SystemTime;\n\nuse tch::{kind::FLOAT_CPU, Tensor};\n\nuse tfrecord::EventWriter;\n\n\n\nlet mut writer = EventWriter::from_prefix(\"log_dir/myprefix-\", \"\", Default::default()).unwrap();\n\n\n", "file_path": "src/event_writer/sync.rs", "rank": 71, "score": 8.344263163699887 }, { "content": "use anyhow::Result;\n\nuse csv::Writer;\n\nuse indexmap::IndexSet;\n\nuse serde::Serialize;\n\nuse std::path::PathBuf;\n\nuse structopt::StructOpt;\n\nuse tfrecord::{\n\n protobuf::{event::What, summary::value::Value::SimpleValue, Summary},\n\n EventIter,\n\n};\n\n\n\n#[derive(StructOpt)]\n", "file_path": "examples/event_reader/main.rs", "rank": 72, "score": 8.306428900942445 }, { "content": " &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n audio: impl TryInto<Audio, Error = impl Into<Error>>,\n\n ) -> Result<()> {\n\n let summary = Summary::from_audio(tag, audio)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event).await?;\n\n if self.auto_flush {\n\n self.events_writer.flush().await?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write a custom event asynchronously.\n\n pub async fn write_event(&mut self, event: Event) -> Result<()> {\n\n self.events_writer.send(event).await?;\n\n if self.auto_flush {\n\n self.events_writer.flush().await?;\n\n }\n", "file_path": "src/event_writer/async.rs", "rank": 73, "score": 8.236722113826481 }, { "content": " ) -> Result<()> {\n\n let summary = Summary::from_histogram(tag, histogram)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event).await?;\n\n if self.auto_flush {\n\n self.events_writer.flush().await?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write a tensor summary asynchronously.\n\n pub async fn write_tensor(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n tensor: impl TryInto<TensorProto, Error = impl Into<Error>>,\n\n ) -> Result<()> {\n\n let summary = Summary::from_tensor(tag, tensor)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event).await?;\n", "file_path": "src/event_writer/async.rs", "rank": 74, "score": 8.146662656338243 }, { "content": "impl Record for Example {\n\n fn from_bytes(bytes: Vec<u8>) -> Result<Self, Error> {\n\n let example = Example::decode(bytes.as_ref())?;\n\n Ok(example)\n\n }\n\n\n\n fn to_bytes(record: Self) -> Result<Vec<u8>, Error> {\n\n let mut bytes = vec![];\n\n Example::encode(&record, &mut bytes)?;\n\n Ok(bytes)\n\n }\n\n}\n\n\n\nimpl Record for Event {\n\n fn from_bytes(bytes: Vec<u8>) -> Result<Self, Error> {\n\n let example = Event::decode(bytes.as_ref())?;\n\n Ok(example)\n\n }\n\n\n\n fn to_bytes(record: Self) -> Result<Vec<u8>, Error> {\n\n let mut bytes = vec![];\n\n Event::encode(&record, &mut bytes)?;\n\n Ok(bytes)\n\n }\n\n}\n", "file_path": "src/record.rs", "rank": 75, "score": 8.075389678963568 }, { "content": "use crate::{\n\n ensure_argument,\n\n error::Error,\n\n protobuf::{tensor_shape_proto::Dim, DataType, TensorProto, TensorShapeProto},\n\n};\n\nuse integer_encoding::VarInt;\n\n\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 76, "score": 8.050789736508781 }, { "content": "use crate::protobuf::{feature::Kind, BytesList, Feature, FloatList, Int64List};\n\nuse std::borrow::Cow;\n\n\n\n/// Enumeration of feature kinds returned from [Feature::into_kinds()]\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum FeatureKind {\n\n Bytes(Vec<Vec<u8>>),\n\n F32(Vec<f32>),\n\n I64(Vec<i64>),\n\n}\n\n\n\nimpl Feature {\n\n pub fn into_kinds(self) -> Option<FeatureKind> {\n\n match self.kind {\n\n Some(Kind::BytesList(BytesList { value })) => Some(FeatureKind::Bytes(value)),\n\n Some(Kind::FloatList(FloatList { value })) => Some(FeatureKind::F32(value)),\n\n Some(Kind::Int64List(Int64List { value })) => Some(FeatureKind::I64(value)),\n\n None => None,\n\n }\n\n }\n", "file_path": "src/protobuf_ext/feature_ext.rs", "rank": 77, "score": 8.049026244389852 }, { "content": " Ok(())\n\n }\n\n\n\n /// Flush this output stream asynchronously.\n\n pub async fn flush(&mut self) -> Result<()> {\n\n self.events_writer.flush().await?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/event_writer/async.rs", "rank": 78, "score": 7.930736084066239 }, { "content": " #[error(\"conversion error: {desc:}\")]\n\n ConversionError { desc: Cow<'static, str> },\n\n #[error(\"invalid arguments: {desc:}\")]\n\n InvalidArgumentsError { desc: Cow<'static, str> },\n\n #[cfg(feature = \"with-tch\")]\n\n #[error(\"tch error: {0}\")]\n\n TchError(tch::TchError),\n\n}\n\n\n\nimpl Error {\n\n #[allow(dead_code)]\n\n pub(crate) fn conversion(desc: impl Into<Cow<'static, str>>) -> Self {\n\n Self::ConversionError { desc: desc.into() }\n\n }\n\n\n\n pub(crate) fn invalid_argument(desc: impl Into<Cow<'static, str>>) -> Self {\n\n Self::ConversionError { desc: desc.into() }\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 79, "score": 7.912264680080172 }, { "content": " }\n\n\n\n impl<T> TryFrom<&FlatSamples<&Vec<T>>> for TensorProto\n\n where\n\n T: TensorProtoElement,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: &FlatSamples<&Vec<T>>) -> Result<Self, Self::Error> {\n\n Self::try_from(&from.as_ref())\n\n }\n\n }\n\n\n\n impl<T> TryFrom<FlatSamples<&Vec<T>>> for TensorProto\n\n where\n\n T: TensorProtoElement,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: FlatSamples<&Vec<T>>) -> Result<Self, Self::Error> {\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 80, "score": 7.904450993135752 }, { "content": " /// Build a tensor summary.\n\n pub fn from_tensor(\n\n tag: impl ToString,\n\n tensor: impl TryInto<TensorProto, Error = impl Into<Error>>,\n\n ) -> Result<Summary, Error> {\n\n let summary = Summary {\n\n value: vec![Value {\n\n node_name: \"\".into(),\n\n tag: tag.to_string(),\n\n metadata: None,\n\n value: Some(value::Value::Tensor(tensor.try_into().map_err(Into::into)?)),\n\n }],\n\n };\n\n Ok(summary)\n\n }\n\n\n\n /// Build an image summary.\n\n pub fn from_image(\n\n tag: impl ToString,\n\n image: impl TryInto<Image, Error = impl Into<Error>>,\n", "file_path": "src/protobuf_ext/summary_ext.rs", "rank": 81, "score": 7.8526709917350175 }, { "content": " ) -> Result<Summary, Error> {\n\n let summary = Summary {\n\n value: vec![Value {\n\n node_name: \"\".into(),\n\n tag: tag.to_string(),\n\n metadata: None,\n\n value: Some(value::Value::Image(image.try_into().map_err(Into::into)?)),\n\n }],\n\n };\n\n Ok(summary)\n\n }\n\n\n\n /// Build a summary with multiple images.\n\n pub fn from_image_list(\n\n tag: impl ToString,\n\n images: impl IntoImageList,\n\n ) -> Result<Summary, Error> {\n\n let image_protos = images.into_image_list()?;\n\n\n\n let values: Vec<_> = image_protos\n", "file_path": "src/protobuf_ext/summary_ext.rs", "rank": 82, "score": 7.8257167124318 }, { "content": " pub fn write_tensor(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n tensor: impl TryInto<TensorProto, Error = impl Into<Error>>,\n\n ) -> Result<()> {\n\n let summary = Summary::from_tensor(tag, tensor)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event)?;\n\n if self.auto_flush {\n\n self.events_writer.flush()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write an image summary.\n\n pub fn write_image(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n", "file_path": "src/event_writer/sync.rs", "rank": 83, "score": 7.7919739375068335 }, { "content": " &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n value: f32,\n\n ) -> Result<()> {\n\n let summary = Summary::from_scalar(tag, value)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event).await?;\n\n if self.auto_flush {\n\n self.events_writer.flush().await?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write a histogram summary asynchronously.\n\n pub async fn write_histogram(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n histogram: impl IntoHistogram,\n", "file_path": "src/event_writer/async.rs", "rank": 84, "score": 7.695883723371766 }, { "content": "pub use anyhow::{ensure, format_err, Error, Result};\n\n\n\nuse once_cell::sync::Lazy;\n\nuse std::{\n\n fs,\n\n fs::File,\n\n io,\n\n io::{prelude::*, BufWriter},\n\n path::{Path, PathBuf},\n\n};\n\n\n\n#[allow(dead_code)]\n\npub static IMAGE_URLS: Lazy<Vec<String>> = Lazy::new(|| {\n\n (move || -> Result<_> {\n\n let path = concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/tests/image_links.txt\");\n\n let lines: Vec<_> = fs::read_to_string(path)?\n\n .lines()\n\n .map(|line| line.to_string())\n\n .collect();\n\n Ok(lines)\n", "file_path": "tests/common.rs", "rank": 85, "score": 7.663944011153751 }, { "content": " Ok(())\n\n }\n\n\n\n /// Write a histogram summary.\n\n pub fn write_histogram(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n histogram: impl IntoHistogram,\n\n ) -> Result<()> {\n\n let summary = Summary::from_histogram(tag, histogram)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event)?;\n\n if self.auto_flush {\n\n self.events_writer.flush()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write a tensor summary.\n", "file_path": "src/event_writer/sync.rs", "rank": 86, "score": 7.576596900696962 }, { "content": " self.events_writer.send(event)?;\n\n if self.auto_flush {\n\n self.events_writer.flush()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write an audio summary.\n\n pub fn write_audio(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n audio: impl TryInto<Audio, Error = impl Into<Error>>,\n\n ) -> Result<()> {\n\n let summary = Summary::from_audio(tag, audio)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event)?;\n\n if self.auto_flush {\n\n self.events_writer.flush()?;\n\n }\n", "file_path": "src/event_writer/sync.rs", "rank": 87, "score": 7.546373933791319 }, { "content": "//! TFRecord data writer.\n\n//!\n\n//! It provides several writers to serialize [Record](crate::record::Record)\n\n//! types.\n\n//!\n\n//! | Writer | Record type |\n\n//! | -------------------------------------------|---------------------------------|\n\n//! | [BytesWriter](sync::BytesWriter) | [Vec<u8>](Vec) |\n\n//! | [ExampleWriter](sync::ExampleWriter) | [Example](crate::Example) |\n\n//! | [RecordWriter](sync::RecordWriter) | Type that implements [Record](crate::record::Record) |\n\n//!\n\n//! The asynchronous counterparts are named in `AsyncWriter` suffix.\n\n//!\n\n//! | Writer | Record type |\n\n//! | ------------------------------------------------------|---------------------------------|\n\n//! | [BytesAsyncWriter](async::BytesAsyncWriter) | [Vec<u8>](Vec) |\n\n//! | [ExampleAsyncWriter](async::ExampleAsyncWriter) | [Example](crate::Example) |\n\n//! | [RecordAsyncWriter](async::RecordAsyncWriter) | Type that implements [Record](crate::record::Record) |\n\n\n\n#[cfg(feature = \"async\")]\n\nmod r#async;\n\n#[cfg(feature = \"async\")]\n\npub use r#async::*;\n\n\n\nmod sync;\n\npub use sync::*;\n", "file_path": "src/record_writer/mod.rs", "rank": 88, "score": 7.541770028327277 }, { "content": " encoded_image_string,\n\n })\n\n }\n\n }\n\n\n\n impl<B> TryFrom<FlatSamples<B>> for Image\n\n where\n\n B: AsRef<[u8]>,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: FlatSamples<B>) -> Result<Self, Self::Error> {\n\n Self::try_from(&from)\n\n }\n\n }\n\n\n\n // ImageBuffer to image\n\n\n\n impl<P, C> TryFrom<&ImageBuffer<P, C>> for Image\n\n where\n", "file_path": "src/protobuf_ext/image_ext.rs", "rank": 89, "score": 7.502740475295689 }, { "content": " if self.auto_flush {\n\n self.events_writer.flush().await?;\n\n }\n\n Ok(())\n\n }\n\n\n\n /// Write an image summary asynchronously.\n\n pub async fn write_image(\n\n &mut self,\n\n tag: impl ToString,\n\n event_meta: impl Into<EventMeta>,\n\n image: impl TryInto<Image, Error = impl Into<Error>>,\n\n ) -> Result<()> {\n\n let summary = Summary::from_image(tag, image)?;\n\n let event = event_meta.into().build_with_summary(summary);\n\n self.events_writer.send(event).await?;\n\n if self.auto_flush {\n\n self.events_writer.flush().await?;\n\n }\n\n Ok(())\n", "file_path": "src/event_writer/async.rs", "rank": 90, "score": 7.478076985178463 }, { "content": "}\n\n\n\n#[cfg(feature = \"generate_protobuf_src\")]\n\nuse codegen::*;\n\n\n\n#[cfg(feature = \"generate_protobuf_src\")]\n\nmod codegen {\n\n use super::*;\n\n use anyhow::{bail, format_err, Context, Error, Result};\n\n use flate2::read::GzDecoder;\n\n use once_cell::sync::Lazy;\n\n use std::{\n\n env::VarError,\n\n fs::{self, File},\n\n io::{self, BufReader, BufWriter},\n\n path::{Path, PathBuf},\n\n };\n\n use tar::Archive;\n\n\n\n static OUT_DIR: Lazy<PathBuf> = Lazy::new(|| PathBuf::from(env::var(\"OUT_DIR\").unwrap()));\n", "file_path": "build.rs", "rank": 91, "score": 7.474423808669556 }, { "content": " };\n\n Ok(summary)\n\n }\n\n\n\n /// Build a histogram summary.\n\n pub fn from_histogram(\n\n tag: impl ToString,\n\n histogram: impl IntoHistogram,\n\n ) -> Result<Summary, Error> {\n\n let summary = Summary {\n\n value: vec![Value {\n\n node_name: \"\".into(),\n\n tag: tag.to_string(),\n\n metadata: None,\n\n value: Some(value::Value::Histo(histogram.try_into_histogram()?)),\n\n }],\n\n };\n\n Ok(summary)\n\n }\n\n\n", "file_path": "src/protobuf_ext/summary_ext.rs", "rank": 92, "score": 7.453178594818347 }, { "content": " name: \"\".into(),\n\n }\n\n })\n\n .collect()\n\n }\n\n }\n\n\n\n impl<S> IntoShape for &S\n\n where\n\n S: IntoShape,\n\n {\n\n fn to_shape(&self) -> Vec<Dim> {\n\n (*self).to_shape()\n\n }\n\n }\n\n}\n\n\n\n#[cfg(feature = \"with-image\")]\n\nmod with_image {\n\n use super::*;\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 93, "score": 7.409254390136201 }, { "content": " where\n\n S: RawData<Elem = f64> + Data,\n\n D: Dimension,\n\n {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n Ok(self.iter().cloned().collect())\n\n }\n\n }\n\n\n\n impl<S, D> IntoHistogram for ArrayBase<S, D>\n\n where\n\n S: RawData<Elem = f64> + Data,\n\n D: Dimension,\n\n {\n\n fn try_into_histogram(self) -> Result<HistogramProto> {\n\n (&self).try_into_histogram()\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/protobuf_ext/histogram_ext.rs", "rank": 94, "score": 7.390952648689591 }, { "content": "use anyhow::{ensure, Result};\n\nuse flate2::read::GzDecoder;\n\nuse itertools::izip;\n\nuse packed_struct::prelude::*;\n\nuse packed_struct_codegen::PackedStruct;\n\nuse std::io::{self, prelude::*, Cursor};\n\nuse tfrecord::{Example, ExampleWriter, Feature, RecordWriter};\n\n\n\nconst IMAGES_URL: &str = \"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\";\n\nconst LABELS_URL: &str = \"http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\";\n\nconst OUTPUT_FILE: &str = \"mnist.tfrecord\";\n\n\n", "file_path": "examples/save_mnist_to_tfrecord.rs", "rank": 95, "score": 7.370611048204157 }, { "content": " .into_iter()\n\n .enumerate()\n\n .map(|(index, image_proto)| Value {\n\n node_name: \"\".into(),\n\n tag: format!(\"{}/image/{}\", tag.to_string(), index),\n\n metadata: None,\n\n value: Some(value::Value::Image(image_proto)),\n\n })\n\n .collect();\n\n\n\n let summary = Summary { value: values };\n\n Ok(summary)\n\n }\n\n\n\n /// Build an audio summary.\n\n pub fn from_audio(\n\n tag: impl ToString,\n\n audio: impl TryInto<Audio, Error = impl Into<Error>>,\n\n ) -> Result<Summary, Error> {\n\n let summary = Summary {\n", "file_path": "src/protobuf_ext/summary_ext.rs", "rank": 96, "score": 7.3399792178062135 }, { "content": "#![cfg(all(\n\n feature = \"async\",\n\n feature = \"summary\",\n\n feature = \"with-image\",\n\n feature = \"with-tch\",\n\n feature = \"with-ndarray\"\n\n))]\n\n\n\nmod common;\n\n\n\nuse common::*;\n\nuse rand::seq::SliceRandom;\n\nuse rand_distr::Distribution;\n\nuse tfrecord::{EventMeta, EventWriter};\n\n\n\n#[async_std::test]\n\nasync fn async_event_writer() -> Result<()> {\n\n // download image files\n\n // ureq blocks the thread so let's wrap in spawn_blocking\n\n let images = async_std::task::spawn_blocking(|| {\n", "file_path": "tests/summary_async.rs", "rank": 97, "score": 7.321733810219115 }, { "content": " Self::try_from(&from)\n\n }\n\n }\n\n\n\n impl<T> TryFrom<&FlatSamples<Vec<T>>> for TensorProto\n\n where\n\n T: TensorProtoElement,\n\n {\n\n type Error = Error;\n\n\n\n fn try_from(from: &FlatSamples<Vec<T>>) -> Result<Self, Self::Error> {\n\n Self::try_from(&from.as_ref())\n\n }\n\n }\n\n\n\n impl<T> TryFrom<FlatSamples<Vec<T>>> for TensorProto\n\n where\n\n T: TensorProtoElement,\n\n {\n\n type Error = Error;\n", "file_path": "src/protobuf_ext/tensor_ext.rs", "rank": 98, "score": 7.215296388001292 }, { "content": " let src_file = download_tensorflow(url)?;\n\n build_by_src_file(&src_file)\n\n .with_context(|| format!(\"remove {} and try again\", src_file.display()))?;\n\n Ok(())\n\n }\n\n\n\n pub fn build_by_src_dir(src_dir: impl AsRef<Path>) -> Result<()> {\n\n let src_dir = src_dir.as_ref();\n\n\n\n // re-run if the dir changes\n\n println!(\"cargo:rerun-if-changed={}\", src_dir.display());\n\n\n\n compile_protobuf(src_dir)?;\n\n Ok(())\n\n }\n\n\n\n pub fn build_by_src_file(src_file: impl AsRef<Path>) -> Result<()> {\n\n let src_file = src_file.as_ref();\n\n\n\n // re-run if the dir changes\n", "file_path": "build.rs", "rank": 99, "score": 7.214860471345067 } ]
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 Counter,\n\n input_count: usize,\n\n output_count: usize,\n\n ) -> Genome;\n\n}\n\n\n\npub struct NetworkEnv;\n\n\n\nimpl Environment for NetworkEnv {\n\n fn fitness_type() -> FitnessType {\n\n panic!()\n", "file_path": "src/lib.rs", "rank": 0, "score": 45840.22464472488 }, { "content": "// Uses a taylor series expansion of 1/(1 + e ^ (- a * x))\n\n// TODO: Use a more efficient approximation algorithm, and/or a lookup table. \n\n// We don't need exact values.\n\n//\n\n// https://www.wolframalpha.com/input/?i=1%2F(1%2Be%5E(-ax))\n\npub fn activation_function(x: f64) -> f64 {\n\n let a = SIGMOID_COEFFICIENT;\n\n let terms = vec![\n\n 0.5,\n\n (a * x) / 4.0,\n\n -1.0 * (a.powi(3) * x.powi(3)) / 48.0,\n\n (a.powi(5) * x.powi(5)) / 480.0,\n\n ];\n\n \n\n terms.into_iter().sum()\n\n}\n\n\n\n\n", "file_path": "src/perceptron.rs", "rank": 1, "score": 44050.718253280786 }, { "content": "fn main() {\n\n let test_cases = vec![\n\n (vec![0, 0], vec![1]),\n\n (vec![0, 1], vec![0]),\n\n (vec![1, 0], vec![0]),\n\n (vec![1, 1], vec![1]),\n\n ];\n\n}\n", "file_path": "tests/xor.rs", "rank": 2, "score": 31254.556347371836 }, { "content": "struct Perceptron {\n\n inputs: Vec<usize>,\n\n outputs: Vec<usize>\n\n previous_value: f64,\n\n id: usize,\n\n}\n\n\n\n\n\n\n", "file_path": "src/network.rs", "rank": 3, "score": 31254.556347371836 }, { "content": "#[derive(Debug)]\n\nstruct CrossIter<'a> {\n\n first: GenomeIter<'a>,\n\n second: GenomeIter<'a>,\n\n\n\n first_peek: Option<&'a ConnectionGene>,\n\n second_peek: Option<&'a ConnectionGene>,\n\n}\n\n\n", "file_path": "src/genome.rs", "rank": 4, "score": 28362.11624317376 }, { "content": "pub trait NeuralNetwork {\n\n type Options;\n\n\n\n fn build(genome: &Genome, options: &Self::Options) -> Self;\n\n\n\n fn activate(inputs: &Vec<f64>, output_count: usize) -> Vec<f64>;\n\n}\n\n\n\npub struct PerceptronNetwork {\n\n nodes: Vec<Perceptron>,\n\n options: PerceptronOptions\n\n}\n\n\n\npub struct PerceptronOptions {\n\n max_steps: u64,\n\n}\n\n\n", "file_path": "src/network.rs", "rank": 5, "score": 26374.627565664192 }, { "content": " let input_node_index = rng.gen_range(0, nodes.len());\n\n let input_node = nodes.remove(input_node_index);\n\n\n\n let output_node = *rng.choose(&nodes).unwrap();\n\n\n\n let innovation = counter.new_connection(input_node, output_node);\n\n\n\n ConnectionGene {\n\n input_node,\n\n output_node,\n\n weight: Self::new_weight(&mut rng),\n\n enabled: true,\n\n innovation,\n\n }\n\n }\n\n\n\n fn mutate_add_node(&self, counter: &mut Counter) -> Vec<ConnectionGene> {\n\n let (innovation, new_node) = counter.new_split(self.input_node, self.output_node);\n\n\n\n let new_gene = ConnectionGene {\n", "file_path": "src/genome.rs", "rank": 13, "score": 8.84621655326023 }, { "content": " assert_eq!(\n\n start.innovation, 100,\n\n \"One of the nodes must be a new innovation number.\"\n\n );\n\n } else if end.weight == 1.0 {\n\n assert_eq!(\n\n start.weight, gene.weight,\n\n \"Original weight was not preserved.\"\n\n );\n\n assert_eq!(\n\n start.innovation, gene.innovation,\n\n \"Original innovation was not preserved or is backwards.\"\n\n );\n\n assert_eq!(\n\n end.innovation, 100,\n\n \"One of the nodes must be a new innovation number.\"\n\n );\n\n } else {\n\n panic!(\"At least one connection must have a weight of 1.0\");\n\n }\n", "file_path": "src/genome.rs", "rank": 14, "score": 8.338833355275817 }, { "content": "\n\n assert_eq!(\n\n start.input_node, gene.input_node,\n\n \"Input node doesn't match.\"\n\n );\n\n assert_eq!(\n\n end.output_node, gene.output_node,\n\n \"Output node doesn't match.\"\n\n );\n\n assert_eq!(start.enabled && end.enabled, true, \"A node is disabled.\");\n\n assert_eq!(start.output_node, 100, \"The new node must have a new id.\");\n\n if start.weight == 1.0 {\n\n assert_eq!(\n\n end.weight, gene.weight,\n\n \"Original weight was not preserved.\"\n\n );\n\n assert_eq!(\n\n end.innovation, gene.innovation,\n\n \"Original innovation was not preserved or is backwards.\"\n\n );\n", "file_path": "src/genome.rs", "rank": 15, "score": 8.215603289867285 }, { "content": "\n\nconst SIGMOID_COEFFICIENT: f64 = 4.9;\n\n\n\nuse petgraph::graphmap::DiGraphMap;\n\nuse petgraph::{Graph, Direction};\n\nuse petgraph::visit::{self, DfsEvent, EdgeRef};\n\nuse std::ops::Range;\n\nuse std::collections::HashMap;\n\nuse genome::ConnectionGene;\n\n\n\npub struct NeuralNetwork {\n\n graph: Graph<usize, f64>,\n\n input_ids: Range<usize>,\n\n}\n\n\n\nimpl NeuralNetwork {\n\n\n\n pub fn new(inputs: usize, connections: &[ConnectionGene]) -> NeuralNetwork {\n\n let input_ids = 0 .. inputs;\n\n\n", "file_path": "src/perceptron.rs", "rank": 16, "score": 8.12305906037169 }, { "content": " input_node: new_node,\n\n output_node: self.output_node,\n\n weight: 1.0,\n\n enabled: true,\n\n innovation,\n\n };\n\n\n\n let old_gene = ConnectionGene {\n\n input_node: self.input_node,\n\n output_node: new_node,\n\n weight: self.weight,\n\n enabled: true,\n\n innovation: self.innovation,\n\n };\n\n\n\n vec![old_gene, new_gene]\n\n }\n\n\n\n pub fn new_weight<R: Rng>(rng: &mut R) -> f64 {\n\n rng.gen_range(-1.0, 1.0)\n", "file_path": "src/genome.rs", "rank": 17, "score": 8.055535540877383 }, { "content": " ret\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Genome {\n\n genes: Vec<ConnectionGene>,\n\n}\n\n\n\nimpl Genome {\n\n pub fn new() -> Genome {\n\n Genome { genes: Vec::new() }\n\n }\n\n\n\n pub fn with_capacity(capacity: usize) -> Genome {\n\n Genome {\n\n genes: Vec::with_capacity(capacity),\n\n }\n\n }\n\n\n", "file_path": "src/genome.rs", "rank": 19, "score": 7.579387537090171 }, { "content": "\n\n pub fn get_nodes(&self) -> Vec<usize> {\n\n let mut ret = Vec::new();\n\n for gene in self.genes.iter() {\n\n if !ret.contains(&gene.input_node) {\n\n ret.push(gene.input_node);\n\n }\n\n\n\n if !ret.contains(&gene.output_node) {\n\n ret.push(gene.output_node);\n\n }\n\n }\n\n\n\n ret\n\n }\n\n\n\n // TODO: Test this.\n\n pub fn mutate<R: Rng>(&self, mut rng: &mut R, mut counter: &mut Counter) -> Genome {\n\n let mut copied_genes = self.genes.clone();\n\n\n", "file_path": "src/genome.rs", "rank": 20, "score": 7.554250138607433 }, { "content": "extern crate itertools;\n\nextern crate rand;\n\nextern crate petgraph;\n\n\n\npub mod genome;\n\npub mod population;\n\npub mod util;\n\npub mod perceptron;\n\n\n\nuse genome::{ConnectionGene, Genome};\n\nuse itertools::{EitherOrBoth, Itertools};\n\nuse population::Counter;\n\nuse rand::Rng;\n\nuse perceptron::NeuralNetwork;\n\n\n\npub struct Organism {\n\n genes: Genome,\n\n brain: NeuralNetwork,\n\n fitness: f64,\n\n}\n", "file_path": "src/lib.rs", "rank": 21, "score": 6.290504011539097 }, { "content": " let mut counter = Counter::from_id(100);\n\n let output_genes = gene.mutate_add_node(&mut counter);\n\n println!(\"Output: {:#?}\\n\", output_genes);\n\n\n\n assert_eq!(output_genes.len(), 2, \"Wrong number of output genes.\");\n\n\n\n let out1 = output_genes[0].clone();\n\n let out2 = output_genes[1].clone();\n\n\n\n let start;\n\n let end;\n\n if out1.output_node == out2.input_node {\n\n start = out1;\n\n end = out2;\n\n } else if out2.output_node == out1.input_node {\n\n start = out2;\n\n end = out1;\n\n } else {\n\n panic!(\"The genes don't have any inputs/outputs in common\");\n\n }\n", "file_path": "src/genome.rs", "rank": 22, "score": 6.261838329595412 }, { "content": " }\n\n }\n\n\n\n // This ensures the random genomes define every input/output node id.\n\n #[test]\n\n fn test_new_random_node_ids() {\n\n let mut rng = test_util::new_rng(None);\n\n\n\n for inputs in 1..10 {\n\n for outputs in 1..10 {\n\n println!(\"Testing {} inputs and {} outputs.\", inputs, outputs);\n\n\n\n let mut counter = Counter::new();\n\n let genome = NetworkEnv::random_genome(&mut rng, &mut counter, inputs, outputs);\n\n\n\n let nodes = genome.get_nodes();\n\n\n\n for id in 0..(inputs + outputs) {\n\n assert!(\n\n nodes.contains(&id),\n", "file_path": "src/lib.rs", "rank": 23, "score": 6.046998370933398 }, { "content": " output_node: output,\n\n weight: ConnectionGene::new_weight(&mut rng),\n\n enabled: true,\n\n innovation,\n\n };\n\n\n\n genes.push(gene);\n\n }\n\n\n\n Genome::from_genes(genes)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use std::cmp;\n\n use util::test_util;\n\n\n\n // This ensures the random genomes have the absolute minimum number of connections\n", "file_path": "src/lib.rs", "rank": 24, "score": 5.852910464825795 }, { "content": " graph: full_graph,\n\n input_ids,\n\n }\n\n }\n\n\n\n pub fn compute(&self, inputs: &[f64]) -> HashMap<usize, f64> {\n\n // Using all dangling nodes (nodes with no output connections), we ensure\n\n // that the depth first search will visit every node in the graph.\n\n let dangling_nodes: Vec<_> = self.graph.externals(Direction::Outgoing).collect();\n\n\n\n let mut values = HashMap::new();\n\n for (&value, index) in inputs.iter().zip(self.input_ids.clone()) {\n\n values.insert(index, value);\n\n }\n\n\n\n // We're going to first reverse the direction of all the edges, so that\n\n // nodes point toward the inputs they need. By doing a depth-first search\n\n // of this, we can ensure that we get a chance to compute the value of a\n\n // node before using it.\n\n visit::depth_first_search(&self.graph, dangling_nodes.clone(), |event| {\n", "file_path": "src/perceptron.rs", "rank": 25, "score": 5.665528839940967 }, { "content": "\n\n pub fn mutate_change_weight<R: Rng>(&self, mut rng: &mut R) -> ConnectionGene {\n\n let mut ret = self.clone();\n\n\n\n if rng.gen_range(0.0, 1.0) < CHANCE_TO_NUDGE_WEIGHT {\n\n ret.weight += Self::new_weight(&mut rng) / 2.0;\n\n } else {\n\n ret.weight = Self::new_weight(&mut rng);\n\n }\n\n\n\n ret\n\n }\n\n\n\n fn mutate_add_connection<R: Rng>(\n\n mut rng: &mut R,\n\n counter: &mut Counter,\n\n parent: &Genome,\n\n ) -> ConnectionGene {\n\n let mut nodes = parent.get_nodes();\n\n\n", "file_path": "src/genome.rs", "rank": 26, "score": 5.457451538515327 }, { "content": "use rand::Rng;\n\nuse std::cmp::Ordering;\n\nuse std::slice;\n\n\n\nuse population::Counter;\n\n\n", "file_path": "src/genome.rs", "rank": 28, "score": 5.303479719017004 }, { "content": " };\n\n\n\n rng.shuffle(&mut inputs);\n\n rng.shuffle(&mut outputs);\n\n\n\n let mut genes = Vec::new();\n\n for zip in inputs.into_iter().zip_longest(outputs.into_iter()) {\n\n let (input, output) = match zip {\n\n EitherOrBoth::Both(input, output) => (input, output),\n\n EitherOrBoth::Left(input) => (input, *rng.choose(&remainder).unwrap()),\n\n EitherOrBoth::Right(output) => (*rng.choose(&remainder).unwrap(), output),\n\n };\n\n\n\n // If two genomes would make a new connection between the same two\n\n // nodes during an evolution step, they must share the same innovation\n\n // number.\n\n let innovation = counter.new_connection(input, output);\n\n\n\n let gene = ConnectionGene {\n\n input_node: input,\n", "file_path": "src/lib.rs", "rank": 29, "score": 5.22412431348665 }, { "content": " innovation: 5,\n\n },\n\n ConnectionGene {\n\n input_node: 5,\n\n output_node: 6,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 6,\n\n },\n\n ConnectionGene {\n\n input_node: 6,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 7,\n\n },\n\n ConnectionGene {\n\n input_node: 3,\n\n output_node: 5,\n\n weight: 0.0,\n", "file_path": "src/genome.rs", "rank": 30, "score": 5.159063205248227 }, { "content": " innovation: 7,\n\n },\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 8,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 8,\n\n },\n\n ConnectionGene {\n\n input_node: 3,\n\n output_node: 5,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 9,\n\n },\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 6,\n\n weight: 0.0,\n", "file_path": "src/genome.rs", "rank": 31, "score": 5.159063205248227 }, { "content": " enabled: true,\n\n innovation: 3,\n\n },\n\n ConnectionGene {\n\n input_node: 2,\n\n output_node: 5,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 4,\n\n },\n\n ConnectionGene {\n\n input_node: 5,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 5,\n\n },\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 8,\n", "file_path": "src/genome.rs", "rank": 32, "score": 5.118710791139984 }, { "content": " ConnectionGene {\n\n input_node: 2,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: false,\n\n innovation: 2,\n\n },\n\n ConnectionGene {\n\n input_node: 3,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 3,\n\n },\n\n ConnectionGene {\n\n input_node: 2,\n\n output_node: 5,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 4,\n", "file_path": "src/genome.rs", "rank": 33, "score": 5.079022694771188 }, { "content": " input_node: 1,\n\n output_node: 2,\n\n weight: 0.0,\n\n enabled: false,\n\n innovation: 1,\n\n }];\n\n\n\n let in2 = vec![ConnectionGene {\n\n input_node: 1,\n\n output_node: 2,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 1,\n\n }];\n\n\n\n let mut rng = test_util::new_rng(None);\n\n\n\n do_test_random_choice_of_enabled(&in1, &in2, &mut rng);\n\n do_test_random_choice_of_enabled(&in2, &in1, &mut rng);\n\n\n", "file_path": "src/genome.rs", "rank": 34, "score": 5.054269472096272 }, { "content": " pub fn from_genes(genes: Vec<ConnectionGene>) -> Genome {\n\n Genome { genes }\n\n }\n\n\n\n pub fn len(&self) -> usize {\n\n self.genes.len()\n\n }\n\n\n\n pub fn add(&mut self, gene: ConnectionGene) {\n\n self.genes.push(gene);\n\n self.genes.sort_by_key(|gene| gene.innovation);\n\n }\n\n\n\n pub fn get_genes(&self) -> &Vec<ConnectionGene> {\n\n &self.genes\n\n }\n\n\n\n pub fn iter(&self) -> GenomeIter {\n\n self.genes.iter()\n\n }\n", "file_path": "src/genome.rs", "rank": 35, "score": 5.043381543966565 }, { "content": " enabled: true,\n\n innovation: 9,\n\n },\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 6,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 10,\n\n },\n\n ];\n\n\n\n let third = vec![\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 1,\n\n },\n", "file_path": "src/genome.rs", "rank": 36, "score": 5.0372658719445695 }, { "content": " weight: 0.0,\n\n enabled: true,\n\n innovation: 8,\n\n },\n\n ];\n\n\n\n let second = vec![\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 1,\n\n },\n\n ConnectionGene {\n\n input_node: 2,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: false,\n\n innovation: 2,\n", "file_path": "src/genome.rs", "rank": 37, "score": 4.9906517647141495 }, { "content": " }\n\n\n\n fn input_count(&self) -> usize {\n\n 10\n\n }\n\n\n\n fn output_count(&self) -> usize {\n\n 4\n\n }\n\n\n\n fn calc_fitness(&self, _: &Organism) -> f64 {\n\n panic!()\n\n }\n\n\n\n fn random_genome<R: Rng>(\n\n mut rng: &mut R,\n\n counter: &mut Counter,\n\n input_count: usize,\n\n output_count: usize,\n\n ) -> Genome {\n", "file_path": "src/lib.rs", "rank": 38, "score": 4.957599981694773 }, { "content": " let output_gene =\n\n ConnectionGene::mutate_add_connection(&mut rng, &mut counter, &parent);\n\n println!(\"output gene: {:#?}\\n\", output_gene);\n\n\n\n assert!(\n\n nodes.contains(&output_gene.input_node),\n\n \"Input node ID doesn't exist. Node ids: {:?}\",\n\n nodes\n\n );\n\n assert!(\n\n nodes.contains(&output_gene.output_node),\n\n \"Output node ID doesn't exist. Node ids: {:?}\",\n\n nodes\n\n );\n\n\n\n assert_eq!(output_gene.enabled, true, \"Output gene is disabled.\");\n\n assert_eq!(\n\n output_gene.innovation, 100,\n\n \"Output gene has incorrect innovation number (expected 100)\"\n\n );\n", "file_path": "src/genome.rs", "rank": 39, "score": 4.855082112996949 }, { "content": " },\n\n ConnectionGene {\n\n input_node: 3,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 3,\n\n },\n\n ConnectionGene {\n\n input_node: 2,\n\n output_node: 5,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 4,\n\n },\n\n ConnectionGene {\n\n input_node: 5,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n", "file_path": "src/genome.rs", "rank": 40, "score": 4.761030684525881 }, { "content": " ) {\n\n let first = vec![\n\n ConnectionGene {\n\n input_node: 1,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 1,\n\n },\n\n ConnectionGene {\n\n input_node: 2,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: false,\n\n innovation: 2,\n\n },\n\n ConnectionGene {\n\n input_node: 3,\n\n output_node: 4,\n\n weight: 0.0,\n", "file_path": "src/genome.rs", "rank": 41, "score": 4.761030684525881 }, { "content": " },\n\n ConnectionGene {\n\n input_node: 5,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 5,\n\n },\n\n ConnectionGene {\n\n input_node: 5,\n\n output_node: 6,\n\n weight: 0.0,\n\n enabled: true,\n\n innovation: 6,\n\n },\n\n ConnectionGene {\n\n input_node: 6,\n\n output_node: 4,\n\n weight: 0.0,\n\n enabled: true,\n", "file_path": "src/genome.rs", "rank": 42, "score": 4.761030684525881 }, { "content": " // required to define every input/output node id.\n\n #[test]\n\n fn test_new_random_minimum_length() {\n\n let mut rng = test_util::new_rng(None);\n\n\n\n for inputs in 1..10 {\n\n for outputs in 1..10 {\n\n println!(\"Testing {} inputs and {} outputs.\", inputs, outputs);\n\n let minimum_length = cmp::max(inputs, outputs);\n\n\n\n let mut counter = Counter::new();\n\n let genome = NetworkEnv::random_genome(&mut rng, &mut counter, inputs, outputs);\n\n\n\n assert_eq!(\n\n genome.len(),\n\n minimum_length,\n\n \"Genome is not minimal: {:#?}\",\n\n genome\n\n );\n\n }\n", "file_path": "src/lib.rs", "rank": 43, "score": 4.660315198606148 }, { "content": " mut counter: &mut Counter,\n\n parent: &Genome,\n\n ) -> Vec<ConnectionGene> {\n\n if !self.enabled {\n\n return Vec::new();\n\n }\n\n\n\n if rng.gen_range(0.0, 1.0) < CHANCE_TO_MUTATE_WEIGHTS {\n\n vec![self.mutate_change_weight(&mut rng)]\n\n } else {\n\n if rng.gen_range(0.0, 1.0) < CHANCE_TO_ADD_CONNECTION {\n\n vec![\n\n self.clone(),\n\n Self::mutate_add_connection(&mut rng, &mut counter, &parent),\n\n ]\n\n } else {\n\n self.mutate_add_node(&mut counter)\n\n }\n\n }\n\n }\n", "file_path": "src/genome.rs", "rank": 44, "score": 4.504266182006985 }, { "content": "#[cfg(test)]\n\npub mod test_util {\n\n\n\n use rand::{self, SeedableRng, XorShiftRng};\n\n\n\n pub fn new_rng(maybe_seed: Option<u8>) -> XorShiftRng {\n\n let seed = maybe_seed.unwrap_or_else(|| rand::random());\n\n\n\n println!(\n\n \"\n\nTo reproduce this test, replace:\n\n\\tlet mut rng = test_util::new_rng(None)\n\nwith:\n\n\\tlet mut rng = test_util::new_rng(Some({}))\n\nDon't forget to put the None back when you're done!\n\n\",\n\n seed\n\n );\n\n\n\n XorShiftRng::from_seed([seed.into(), 1, 1, 1])\n\n }\n\n\n\n}\n", "file_path": "src/util.rs", "rank": 45, "score": 4.241750247914632 }, { "content": " // We need to supply at least enough connections to define each input\n\n // and output node.\n\n //\n\n // This code sets up a pair of iterators over the possible input node\n\n // id's and output node id's in a random order. Then, it zips them together,\n\n // and uses the zipped pairs as connection values. This will uniquely connect\n\n // an input and an output.\n\n //\n\n // Any excess (because the inputs and outputs are a different size) are\n\n // chosen randomly from the appropriate input/output ids.\n\n //\n\n // This process ensures that each input and output have been used at least\n\n // once, and that the minimum number of connections are made.\n\n let mut inputs: Vec<usize> = (0..input_count).collect();\n\n let mut outputs: Vec<usize> = (0..output_count).map(|x| x + input_count).collect();\n\n\n\n let remainder = if inputs > outputs {\n\n inputs.clone()\n\n } else {\n\n outputs.clone()\n", "file_path": "src/lib.rs", "rank": 46, "score": 4.195262311193239 }, { "content": " }\n\n }\n\n\n\n #[test]\n\n fn test_add_connection() {\n\n let (test1, test2, test3) = paper_crossover_example();\n\n\n\n let mut rng = test_util::new_rng(Some(212));\n\n\n\n do_test_add_connection(test1, &mut rng);\n\n do_test_add_connection(test2, &mut rng);\n\n do_test_add_connection(test3, &mut rng);\n\n }\n\n\n\n fn do_test_add_connection(test_genome: Vec<ConnectionGene>, mut rng: &mut XorShiftRng) {\n\n let parent = Genome::from_genes(test_genome);\n\n let nodes = parent.get_nodes();\n\n\n\n for _ in 0..100 {\n\n let mut counter = Counter::from_id(100);\n", "file_path": "src/genome.rs", "rank": 47, "score": 3.7715645649414475 }, { "content": " // First, find all the nodes we need.\n\n let mut graph = DiGraphMap::new();\n\n for conn in connections {\n\n if conn.enabled {\n\n graph.add_node(conn.input_node);\n\n graph.add_node(conn.output_node);\n\n }\n\n }\n\n\n\n // Add each connection.\n\n for conn in connections {\n\n if conn.enabled {\n\n graph.add_edge(conn.input_node, conn.output_node, conn.weight);\n\n }\n\n }\n\n\n\n // Turn it into a full graph. \n\n let full_graph = graph.into_graph();\n\n\n\n NeuralNetwork {\n", "file_path": "src/perceptron.rs", "rank": 48, "score": 3.495306721679025 }, { "content": "\n\npub struct Species {\n\n members: Vec<Organism>,\n\n}\n\n\n\npub enum FitnessType {\n\n Maximize,\n\n Minimize,\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 49, "score": 2.792739005525566 }, { "content": " let gene_index = rng.gen_range(0, self.genes.len());\n\n let old_gene: ConnectionGene = copied_genes.remove(gene_index);\n\n let mutated_genes: Vec<ConnectionGene> = old_gene.mutate(&mut rng, &mut counter, &self);\n\n\n\n copied_genes.extend(mutated_genes);\n\n Genome::from_genes(copied_genes)\n\n }\n\n\n\n // Do a crossover mutation of the two genomes, where:\n\n //\n\n // fitness(self) <ordering> fitness(other)\n\n //\n\n pub fn crossover<R: Rng>(&self, other: &Genome, order: Ordering, mut rng: &mut R) -> Genome {\n\n let mut ret = Genome::new();\n\n\n\n for gene_match in CrossIter::new(&self, &other) {\n\n match gene_match {\n\n GeneMatch::Pair(self_gene, other_gene) => {\n\n let gene = self_gene.crossover(other_gene, &mut rng);\n\n ret.add(gene);\n", "file_path": "src/genome.rs", "rank": 50, "score": 2.730569002115176 }, { "content": " assert!(nodes.contains(&i), \"Node id not found: {}\", i);\n\n }\n\n\n\n assert!(nodes.contains(&8), \"Node id not found: 8\");\n\n\n\n assert_eq!(nodes.len(), 6);\n\n }\n\n\n\n #[test]\n\n fn test_add_node() {\n\n let (test1, test2, test3) = paper_crossover_example();\n\n\n\n do_test_add_node(test1);\n\n do_test_add_node(test2);\n\n do_test_add_node(test3);\n\n }\n\n\n\n fn do_test_add_node(test_genes: Vec<ConnectionGene>) {\n\n for gene in test_genes {\n\n println!(\"Testing gene: {:#?}\", gene);\n", "file_path": "src/genome.rs", "rank": 51, "score": 2.7238196705096223 }, { "content": " enabled: true,\n\n innovation: 10,\n\n },\n\n ];\n\n\n\n (first, second, third)\n\n }\n\n\n\n}\n", "file_path": "src/genome.rs", "rank": 52, "score": 2.3430645842986593 }, { "content": " // Save this value.\n\n values.insert(self.graph[id], value);\n\n },\n\n\n\n // Ignore edges.\n\n _ => ()\n\n }\n\n });\n\n \n\n values\n\n }\n\n}\n\n\n\n\n\n// Uses a taylor series expansion of 1/(1 + e ^ (- a * x))\n\n// TODO: Use a more efficient approximation algorithm, and/or a lookup table. \n\n// We don't need exact values.\n\n//\n\n// https://www.wolframalpha.com/input/?i=1%2F(1%2Be%5E(-ax))\n", "file_path": "src/perceptron.rs", "rank": 53, "score": 2.119680425651409 }, { "content": "mod test {\n\n use super::*;\n\n use rand::XorShiftRng;\n\n use util::test_util;\n\n\n\n #[test]\n\n fn test_from_genes() {\n\n let (test1, test2, test3) = paper_crossover_example();\n\n\n\n do_test_from_genes(test1);\n\n do_test_from_genes(test2);\n\n do_test_from_genes(test3);\n\n }\n\n\n\n fn do_test_from_genes(test_genes: Vec<ConnectionGene>) {\n\n let genome = Genome::from_genes(test_genes.clone());\n\n assert_eq!(genome.get_genes(), &test_genes);\n\n }\n\n\n\n #[test]\n", "file_path": "src/genome.rs", "rank": 54, "score": 2.107345669369641 }, { "content": " (None, Some(_)) => Some(GeneMatch::ExcessSecond(self.second_peek.take().unwrap())),\n\n\n\n (Some(better), Some(worse)) => match better.innovation.cmp(&worse.innovation) {\n\n // If they're equal, they're a pair.\n\n Ordering::Equal => Some(GeneMatch::Pair(\n\n self.first_peek.take().unwrap(),\n\n self.second_peek.take().unwrap(),\n\n )),\n\n\n\n // A disjoint gene. Return the one with the lower innovation number.\n\n Ordering::Less => Some(GeneMatch::DisjointFirst(self.first_peek.take().unwrap())),\n\n Ordering::Greater => {\n\n Some(GeneMatch::DisjointSecond(self.second_peek.take().unwrap()))\n\n }\n\n },\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/genome.rs", "rank": 55, "score": 1.7900550977084329 }, { "content": " let (test1, test2, test3) = paper_crossover_example();\n\n\n\n do_test_genome_len(test1);\n\n do_test_genome_len(test2);\n\n do_test_genome_len(test3);\n\n }\n\n\n\n fn do_test_genome_len(test_genes: Vec<ConnectionGene>) {\n\n let genome = Genome::from_genes(test_genes.clone());\n\n assert_eq!(genome.len(), test_genes.len());\n\n }\n\n\n\n #[test]\n\n fn test_get_nodes() {\n\n let (genes, _, _) = paper_crossover_example();\n\n\n\n let genome = Genome::from_genes(genes);\n\n let nodes = genome.get_nodes();\n\n\n\n for i in 1..6 {\n", "file_path": "src/genome.rs", "rank": 56, "score": 1.7876257068344619 }, { "content": " match event {\n\n // When we find a node, give it a dummy value.\n\n DfsEvent::Discover(id, _) => {\n\n values.insert(self.graph[id], 0.0);\n\n },\n\n DfsEvent::Finish(id, _) => {\n\n // Sum up the values of all the inputs to this node.\n\n let total = self.graph.edges_directed(id, Direction::Incoming)\n\n .map(|edge| {\n\n let source = edge.source();\n\n let id = self.graph[source];\n\n let value = values[&id];\n\n let weight = edge.weight();\n\n weight * value\n\n })\n\n .sum();\n\n\n\n // Apply the activation function.\n\n let value = activation_function(total);\n\n\n", "file_path": "src/perceptron.rs", "rank": 57, "score": 1.4529618533702484 }, { "content": "\n\n if true_output_found && false_output_found {\n\n break;\n\n }\n\n }\n\n\n\n assert!(\n\n true_output_found && false_output_found,\n\n \"true found: {}\\nfalse_found: {}\",\n\n true_output_found,\n\n false_output_found\n\n );\n\n }\n\n\n\n // This is the same example the paper uses on p109, but gene #5 is not disabled\n\n // in either parent. This method isn't testing the randomness.\n\n fn paper_crossover_example() -> (\n\n Vec<ConnectionGene>,\n\n Vec<ConnectionGene>,\n\n Vec<ConnectionGene>,\n", "file_path": "src/genome.rs", "rank": 58, "score": 1.1410107187037761 }, { "content": "impl<'a> Iterator for CrossIter<'a> {\n\n type Item = GeneMatch<'a>;\n\n\n\n fn next(&mut self) -> Option<GeneMatch<'a>> {\n\n if self.first_peek.is_none() {\n\n self.first_peek = self.first.next();\n\n }\n\n\n\n if self.second_peek.is_none() {\n\n self.second_peek = self.second.next();\n\n }\n\n\n\n let first_peek = self.first_peek;\n\n let second_peek = self.second_peek;\n\n match (first_peek, second_peek) {\n\n // No more genes to iterate.\n\n (None, None) => None,\n\n\n\n // An excess gene.\n\n (Some(_), None) => Some(GeneMatch::ExcessFirst(self.first_peek.take().unwrap())),\n", "file_path": "src/genome.rs", "rank": 59, "score": 1.0773353113825506 }, { "content": " }\n\n\n\n pub fn crossover<R: Rng>(&self, other: &ConnectionGene, rng: &mut R) -> ConnectionGene {\n\n let mut ret;\n\n if rng.gen::<bool>() {\n\n ret = self.clone();\n\n } else {\n\n ret = other.clone();\n\n }\n\n\n\n if !self.enabled || !other.enabled {\n\n // 75% chance of being disabled if either parent is disabled.\n\n // (that includes if they're both disabled! TODO: Remove that;\n\n // if both parents agree, the child should keep that. Random\n\n // disabled/enabled flips should be a separate mutation.)\n\n ret.enabled = !(rng.gen_range(0.0, 1.0) < CHANCE_TO_INHERIT_DISABLED);\n\n } else {\n\n ret.enabled = true;\n\n }\n\n\n", "file_path": "src/genome.rs", "rank": 60, "score": 1.0336183716992942 }, { "content": " fn test_add_gene() {\n\n let (test1, test2, test3) = paper_crossover_example();\n\n\n\n do_test_add_gene(test1);\n\n do_test_add_gene(test2);\n\n do_test_add_gene(test3);\n\n }\n\n\n\n fn do_test_add_gene(test_genes: Vec<ConnectionGene>) {\n\n let mut genome = Genome::new();\n\n\n\n for gene in test_genes.iter() {\n\n genome.add(gene.clone());\n\n }\n\n\n\n assert_eq!(genome.get_genes(), &test_genes);\n\n }\n\n\n\n #[test]\n\n fn test_genome_len() {\n", "file_path": "src/genome.rs", "rank": 61, "score": 0.988686749637286 }, { "content": " out: Vec<ConnectionGene>,\n\n order: Ordering,\n\n ) {\n\n println!(\n\n \"input: {:#?}\\n{:#?}\\noutput: {:#?}\\norder: {:?}\",\n\n &in1, &in2, &out, order\n\n );\n\n\n\n let mut rng = test_util::new_rng(None);\n\n\n\n let genome1 = Genome::from_genes(in1.clone());\n\n let genome2 = Genome::from_genes(in2.clone());\n\n let output_genome = genome1.crossover(&genome2, order, &mut rng);\n\n\n\n assert_eq!(output_genome.get_genes(), &out);\n\n }\n\n\n\n #[test]\n\n fn test_random_choice_of_enabled() {\n\n let in1 = vec![ConnectionGene {\n", "file_path": "src/genome.rs", "rank": 62, "score": 0.988686749637286 } ]
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_transform<D: UserDataType>(self_: &mut B2body<D>, position: B2vec2, angle: f32) {\n\n\tlet world = upgrade(&self_.m_world);\n\n\tb2_assert(world.borrow().is_locked() == false);\n\n\tif world.borrow().is_locked() == true {\n\n\t\treturn;\n\n\t}\n\n\n\n\tself_.m_xf.q.set(angle);\n\n\tself_.m_xf.p = position;\n\n\n\n\tself_.m_sweep.c = b2_mul_transform_by_vec2(self_.m_xf, self_.m_sweep.local_center);\n\n\tself_.m_sweep.a = angle;\n\n\n\n\tself_.m_sweep.c0 = self_.m_sweep.c;\n\n\tself_.m_sweep.a0 = angle;\n\n\n\n\tlet contact_manager = world.borrow().m_contact_manager.clone();\n\n\tlet broad_phase_rc = contact_manager.borrow().m_broad_phase.clone();\n\n\tlet mut broad_phase = broad_phase_rc.borrow_mut();\n\n\tfor f in self_.m_fixture_list.iter() {\n\n\t\tf.borrow_mut()\n\n\t\t\t.synchronize(&mut broad_phase, self_.m_xf, self_.m_xf);\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 1, "score": 287069.79051235993 }, { "content": "fn synchronize_fixtures_internal<D: UserDataType>(self_: &mut B2body<D>, world: &B2world<D>) {\n\n\tlet contact_manager = world.m_contact_manager.clone();\n\n\tlet broad_phase_rc = contact_manager.borrow().m_broad_phase.clone();\n\n\tlet mut broad_phase = broad_phase_rc.borrow_mut();\n\n\n\n\tif self_.m_flags.contains(BodyFlags::E_AWAKE_FLAG) {\n\n\t\tlet mut xf1 = B2Transform::default();\n\n\t\txf1.q.set(self_.m_sweep.a0);\n\n\t\txf1.p = self_.m_sweep.c0 - b2_mul_rot_by_vec2(xf1.q, self_.m_sweep.local_center);\n\n\n\n\t\tfor f in self_.m_fixture_list.iter() {\n\n\t\t\tf.borrow_mut()\n\n\t\t\t\t.synchronize(&mut broad_phase, xf1, self_.m_xf);\n\n\t\t}\n\n\t} else {\n\n\t\tfor f in self_.m_fixture_list.iter() {\n\n\t\t\tf.borrow_mut()\n\n\t\t\t\t.synchronize(&mut broad_phase, self_.m_xf, self_.m_xf);\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 2, "score": 285073.39804909367 }, { "content": "pub fn create_fixture<D: UserDataType>(self_: BodyPtr<D>, def: &B2fixtureDef<D>) -> FixturePtr<D> {\n\n\tlet mut self_mut = self_.borrow_mut();\n\n\tlet world = upgrade(&self_mut.m_world);\n\n\tb2_assert(world.borrow().is_locked() == false);\n\n\tif world.borrow().is_locked() == true {\n\n\t\tpanic!();\n\n\t}\n\n\n\n\tlet fixture: FixturePtr<D> = Rc::new(RefCell::new(B2fixture::default()));\n\n\t{\n\n\t\tlet mut fixture_mut = fixture.borrow_mut();\n\n\t\tB2fixture::create(&mut fixture_mut, self_.clone(), def);\n\n\t}\n\n\n\n\tif self_mut.m_flags.contains(BodyFlags::E_ENABLED_FLAG) {\n\n\t\tlet broad_phase = world\n\n\t\t\t.borrow()\n\n\t\t\t.m_contact_manager\n\n\t\t\t.borrow()\n\n\t\t\t.m_broad_phase\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 3, "score": 267604.5629732922 }, { "content": "pub fn b2_body<D: UserDataType>(bd: &B2bodyDef<D>, world: B2worldPtr<D>) -> B2body<D> {\n\n\tb2_assert(bd.position.is_valid());\n\n\tb2_assert(bd.linear_velocity.is_valid());\n\n\tb2_assert(b2_is_valid(bd.angle));\n\n\tb2_assert(b2_is_valid(bd.angular_velocity));\n\n\tb2_assert(b2_is_valid(bd.angular_damping) && bd.angular_damping >= 0.0);\n\n\tb2_assert(b2_is_valid(bd.linear_damping) && bd.linear_damping >= 0.0);\n\n\n\n\tlet mut m_flags = BodyFlags::default();\n\n\n\n\tif bd.bullet {\n\n\t\tm_flags.insert(BodyFlags::E_BULLET_FLAG);\n\n\t}\n\n\tif bd.fixed_rotation {\n\n\t\tm_flags |= BodyFlags::E_FIXED_ROTATION_FLAG;\n\n\t}\n\n\tif bd.allow_sleep {\n\n\t\tm_flags |= BodyFlags::E_AUTO_SLEEP_FLAG;\n\n\t}\n\n\tif bd.awake && bd.body_type != B2bodyType::B2StaticBody {\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 4, "score": 250389.75667546625 }, { "content": "struct B2fixtureVisitorContext<D: UserDataType> {\n\n\tpub(crate) body: BodyWeakPtr<D>,\n\n}\n\n\n\nimpl<'de, U: UserDataType> DeserializeSeed<'de> for B2fixtureVisitorContext<U> {\n\n\ttype Value = ();\n\n\n\n\tfn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>\n\n\twhere\n\n\t\tD: Deserializer<'de>,\n\n\t{\n\n\t\t#[derive(Deserialize)]\n\n\t\t#[serde(field_identifier, rename_all = \"lowercase\")]\n\n\t\t#[derive(EnumVariantNames)]\n\n\t\tenum Field {\n\n\t\t\tm_friction,\n\n\t\t\tm_restitution,\n\n\t\t\tm_density,\n\n\t\t\tm_is_sensor,\n\n\t\t\tm_filter,\n", "file_path": "src/serialize_b2_fixture.rs", "rank": 6, "score": 239618.1885752479 }, { "content": "pub fn synchronize_fixtures<D: UserDataType>(self_: &mut B2body<D>) {\n\n\tlet world = upgrade(&self_.m_world);\n\n\tsynchronize_fixtures_internal(self_, &*world.borrow());\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 7, "score": 234294.1382714335 }, { "content": "pub fn reset_mass_data<D: UserDataType>(self_: &mut B2body<D>) {\n\n\t// Compute mass data from shapes. Each shape has its own density.\n\n\tself_.m_mass = 0.0;\n\n\tself_.m_inv_mass = 0.0;\n\n\tself_.m_i = 0.0;\n\n\tself_.m_inv_i = 0.0;\n\n\tself_.m_sweep.local_center.set_zero();\n\n\n\n\t// Static and kinematic bodies have zero mass.\n\n\tif self_.m_type == B2bodyType::B2StaticBody || self_.m_type == B2bodyType::B2KinematicBody {\n\n\t\tself_.m_sweep.c0 = self_.m_xf.p;\n\n\t\tself_.m_sweep.c = self_.m_xf.p;\n\n\t\tself_.m_sweep.a0 = self_.m_sweep.a;\n\n\t\treturn;\n\n\t}\n\n\n\n\tb2_assert(self_.m_type == B2bodyType::B2DynamicBody);\n\n\n\n\t// Accumulate mass over all fixtures.\n\n\tlet mut local_center = B2vec2::zero();\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 8, "score": 231116.67171224343 }, { "content": "/// Called for each fixture found in the query AABB.\n\n/// @return false to terminate the query.\n\npub trait B2queryCallback<D: UserDataType>: FnMut(\n\n\t/*fixture:*/ FixturePtr<D>\n\n) -> bool {}\n\nimpl<F, D: UserDataType> B2queryCallback<D> for F where F: FnMut(FixturePtr<D>) -> bool {}\n\n\n", "file_path": "src/b2_world_callbacks.rs", "rank": 9, "score": 227891.28905860946 }, { "content": "/// Called for each fixture found in the query. You control how the ray cast\n\n/// proceeds by returning a f32:\n\n/// return -1: ignore this fixture and continue\n\n/// return 0: terminate the ray cast\n\n/// return fraction: clip the ray to this point\n\n/// return 1: don't clip the ray and continue\n\n/// * `fixture` - the fixture hit by the ray\n\n/// * `point` - the point of initial intersection\n\n/// * `normal` - the normal vector at the point of intersection\n\n/// * `fraction` - the fraction along the ray at the point of intersection\n\n/// @return -1 to filter, 0 to terminate, fraction to clip the ray for\n\n/// closest hit, 1 to continue\n\npub trait B2rayCastCallback<D:UserDataType>: FnMut(\t\n\n\t/*fixture:*/ FixturePtr<D>,\n\n\t/*point:*/ B2vec2,\n\n\t/*normal:*/ B2vec2,\n\n\t/*fraction:*/ f32) -> f32 {}\n\n\n\nimpl<F, D: UserDataType> B2rayCastCallback<D> for F where\n\n\tF: FnMut(FixturePtr<D>, B2vec2, B2vec2, f32) -> f32\n\n{}\n", "file_path": "src/b2_world_callbacks.rs", "rank": 10, "score": 225491.4920418682 }, { "content": "pub fn set_fixed_rotation<D: UserDataType>(self_: &mut B2body<D>, flag: bool) {\n\n\tlet status: bool = self_.m_flags.contains(BodyFlags::E_FIXED_ROTATION_FLAG);\n\n\tif status == flag {\n\n\t\treturn;\n\n\t}\n\n\n\n\tself_.m_flags.set(BodyFlags::E_FIXED_ROTATION_FLAG, flag);\n\n\n\n\tself_.m_angular_velocity = 0.0;\n\n\n\n\tself_.reset_mass_data();\n\n}\n\n\n\n//pub fn dump<D: UserDataType>(self_: &B2body<D>) {\n\n\t// i32 body_index = m_island_index;\n\n\n\n\t// b2Log(\"{\\n\");\n\n\t// b2Log(\" let mut bd = B2bodyDef::default();\\n\");\n\n\t// b2Log(\" bd.type = B2bodyType(%d);\\n\",self_.m_type);\n\n\t// b2Log(\" bd.position.set(%.15lef, %.15lef);\\n\", m_xf.p.x, m_xf.p.y);\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 11, "score": 222252.99510393068 }, { "content": "pub fn set_mass_data<D: UserDataType>(self_: &mut B2body<D>, mass_data: &B2massData) {\n\n\tlet world = upgrade(&self_.m_world);\n\n\tb2_assert(world.borrow().is_locked() == false);\n\n\tif world.borrow().is_locked() == true {\n\n\t\treturn;\n\n\t}\n\n\n\n\tif self_.m_type != B2bodyType::B2DynamicBody {\n\n\t\treturn;\n\n\t}\n\n\n\n\tself_.m_inv_mass = 0.0;\n\n\tself_.m_i = 0.0;\n\n\tself_.m_inv_i = 0.0;\n\n\n\n\tself_.m_mass = mass_data.mass;\n\n\tif self_.m_mass <= 0.0 {\n\n\t\tself_.m_mass = 1.0;\n\n\t}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 12, "score": 216599.1288516486 }, { "content": "pub fn set_enabled<D: UserDataType>(self_: BodyPtr<D>, flag: bool) {\n\n\tlet world;\n\n\tlet m_fixture_list;\n\n\tlet broad_phase_rc;\n\n\tlet mut broad_phase;\n\n\tlet m_xf;\n\n\tlet m_contact_list;\n\n\t{\n\n\t\tlet mut self_ = self_.borrow_mut();\n\n\n\n\t\tworld = upgrade(&self_.m_world);\n\n\t\tlet contact_manager = world.borrow().m_contact_manager.clone();\n\n\t\tbroad_phase_rc = contact_manager.borrow().m_broad_phase.clone();\n\n\t\tbroad_phase = broad_phase_rc.borrow_mut();\n\n\t\tb2_assert(world.borrow().is_locked() == false);\n\n\t\tif world.borrow().is_locked() == true {\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\tself_.m_flags.set(BodyFlags::E_ENABLED_FLAG, flag);\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 13, "score": 211324.52372110198 }, { "content": "#[derive(Deserialize)]\n\n#[serde(field_identifier, rename_all = \"lowercase\")]\n\n#[derive(EnumString, EnumVariantNames, AsRefStr)]\n\nenum Field {\n\n\tbase,\n\n\tm_centroid,\n\n\tm_count,\n\n\tm_vertices,\n\n\tm_normals,\n\n}\n\n\n\nimpl Serialize for B2polygonShape\n\n{\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n\t\tlet mut state = serializer.serialize_struct(B2polygonShape::STRUCT_NAME, 19)?;\n\n\t\tstate.serialize_field(Field::base.as_ref(), &self.base)?;\n\n\t\tstate.serialize_field(Field::m_centroid.as_ref(), &self.m_centroid)?;\n\n\t\tstate.serialize_field(\"m_count\", &self.m_count)?;\n\n\t\t{\n\n\t\t\tstruct VerticesContext;\n", "file_path": "src/shapes/serialize_b2_polygon_shape.rs", "rank": 14, "score": 208306.47696220363 }, { "content": "pub fn b2_fixture_refilter<T:UserDataType>(this: &mut B2fixture<T>) {\n\n\tif this.m_body.is_none()\n\n\t{\n\n\t\treturn;\n\n\t}\n\n\n\n\tlet m_body = upgrade_opt(&this.m_body);\n\n\n\n\t// Flag associated contacts for filtering.\n\n\tfor edge in m_body.borrow().get_contact_list().iter()\n\n\t{\n\n\t\tlet contact = edge.borrow().contact.upgrade().unwrap();\n\n\t\tlet mut contact = contact.borrow_mut();\n\n\t\tlet fixture_a = contact.get_base().get_fixture_a();\n\n\t\tlet fixture_b = contact.get_base().get_fixture_b();\n\n\t\tif ptr::eq(&*fixture_a.borrow(),this) || ptr::eq(&*fixture_b.borrow(),this)\n\n\t\t{\n\n\t\t\tcontact.get_base_mut().flag_for_filtering();\n\n\t\t}\n\n\t}\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 15, "score": 198722.6153281005 }, { "content": "pub fn set_type<D: UserDataType>(self_: BodyPtr<D>, body_type: B2bodyType) {\n\n\tlet world;\n\n\tlet m_contact_list;\n\n\t{\n\n\t\tlet mut self_ = self_.borrow_mut();\n\n\t\tworld = upgrade(&self_.m_world);\n\n\t\tb2_assert(world.borrow().is_locked() == false);\n\n\t\tif world.borrow().is_locked() == true {\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\tif self_.m_type == body_type {\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\tself_.m_type = body_type;\n\n\n\n\t\tself_.reset_mass_data();\n\n\n\n\t\tif self_.m_type == B2bodyType::B2StaticBody {\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 16, "score": 197738.6063771585 }, { "content": "pub fn b2_fixture_destroy_proxies<T:UserDataType>(this: &mut B2fixture<T>, broad_phase: &mut B2broadPhase<FixtureProxyPtr<T>>) {\n\n\t// destroy proxies in the broad-phase.\n\n\tfor i in 0..this.m_proxy_count\n\n\t{\n\n\t\tlet mut proxy = this.m_proxies[i as usize].as_ref().borrow_mut();\n\n\t\tbroad_phase.destroy_proxy(proxy.proxy_id);\n\n\t\tproxy.proxy_id = E_NULL_PROXY;\n\n\t}\n\n\n\n\tthis.m_proxy_count = 0;\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 17, "score": 190288.30135674347 }, { "content": "pub fn b2_fixture_set_sensor<T:UserDataType>(this: &mut B2fixture<T>, sensor: bool) {\n\n\tif sensor != this.m_is_sensor\n\n\t{\n\n\t\tthis.m_body.as_ref().unwrap().upgrade().unwrap().borrow_mut().set_awake(true);\n\n\t\tthis.m_is_sensor = sensor;\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 18, "score": 188341.98998943562 }, { "content": "#[cfg(feature = \"serde_support\")]\n\npub trait UserDataType: Default + Clone + Serialize + DeserializeOwned + 'static {\n\n type Fixture: Default + Clone + Serialize + DeserializeOwned + std::fmt::Debug;\n\n type Body: Default + Clone + Serialize + DeserializeOwned + PartialEq + std::fmt::Debug;\n\n type Joint: Default + Clone + Serialize + DeserializeOwned + std::fmt::Debug;\n\n}\n\n\n\n//--------------------------------------------------------------------------------------------------\n\n/// Global tuning constants based on meters-kilograms-seconds (MKS) units.\n\n\n\n// Collision\n\n\n\n/// The maximum number of contact points between two convex shapes. Do\n\n/// not change this value.\n\npub const B2_MAX_MANIFOLD_POINTS: usize = 2;\n\n\n\n/// This is used to fatten AABBs in the dynamic tree. This allows proxies\n\n/// to move by a small amount without triggering a tree adjustment.\n\n/// This is in meters.\n\npub const B2_AABB_EXTENSION: f32 = 0.1 * B2_LENGTH_UNITS_PER_METER;\n\n\n", "file_path": "src/b2_settings.rs", "rank": 19, "score": 187616.08477693965 }, { "content": "pub fn b2_fixture_set_filter_data<T:UserDataType>(this: &mut B2fixture<T>, filter: B2filter) {\n\n\tthis.m_filter = filter;\n\n\n\n\tthis.refilter();\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 20, "score": 186042.28592381277 }, { "content": "/// Utility to compute rotational stiffness values frequency and damping ratio\n\npub fn b2_angular_stiffness<D: UserDataType>(stiffness: &mut f32, damping: &mut f32,\n\n\tfrequency_hertz: f32, damping_ratio: f32,\n\n\tbody_a: BodyPtr<D>, body_b: BodyPtr<D>)\n\n{\n\n\tprivate::b2_angular_stiffness(stiffness, damping, frequency_hertz, damping_ratio, body_a, body_b);\n\n}\n\n\n\n\n\n/// The base joint class. Joints are used to constraint two bodies together in\n\n/// various fashions. Some joints also feature limits and motors.\n\nimpl<D: UserDataType> B2joint<D> {\n\n\t/// Get the type of the concrete joint.\n\n\tpub fn get_type(&self) -> B2jointType {\n\n\t\treturn self.m_type;\n\n\t}\n\n\n\n\t/// Get the first body attached to this joint.\n\n\tpub fn get_body_a(&self) -> BodyPtr<D> {\n\n\t\treturn self.m_body_a.clone();\n\n\t}\n", "file_path": "src/b2_joint.rs", "rank": 21, "score": 174809.02478276895 }, { "content": "/// Utility to compute linear stiffness values from frequency and damping ratio\n\npub fn b2_linear_stiffness<D: UserDataType>(stiffness: &mut f32, damping: &mut f32,\n\n\tfrequency_hertz: f32, damping_ratio: f32,\n\n\tbody_a: BodyPtr<D>, body_b: BodyPtr<D>)\n\n{\n\n\tprivate::b2_linear_stiffness(stiffness, damping, frequency_hertz, damping_ratio, body_a, body_b);\n\n}\n\n\n", "file_path": "src/b2_joint.rs", "rank": 22, "score": 174809.02478276895 }, { "content": "pub fn should_collide<D: UserDataType>(self_: &B2body<D>, other: BodyPtr<D>) -> bool {\n\n\t// At least one body should be dynamic.\n\n\tif self_.m_type != B2bodyType::B2DynamicBody\n\n\t\t&& other.borrow().m_type != B2bodyType::B2DynamicBody\n\n\t{\n\n\t\treturn false;\n\n\t}\n\n\n\n\t// Does a joint prevent collision?\n\n\tfor jn_ in self_.m_joint_list.iter() {\n\n\t\tlet jn = jn_.borrow();\n\n\t\tlet jn_other = upgrade(&jn.other);\n\n\t\tif Rc::ptr_eq(&jn_other, &other) {\n\n\t\t\tif upgrade(&jn.joint)\n\n\t\t\t\t.borrow()\n\n\t\t\t\t.get_base()\n\n\t\t\t\t.get_collide_connected()\n\n\t\t\t\t== false\n\n\t\t\t{\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\treturn true;\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 23, "score": 173921.02263256582 }, { "content": "pub fn destroy_fixture<D: UserDataType>(self_: BodyPtr<D>, fixture: FixturePtr<D>) {\n\n\tlet world;\n\n\tlet m_contact_list;\n\n\tlet m_fixture_count;\n\n\t{\n\n\t\tlet self_ = self_.borrow();\n\n\t\tworld = upgrade(&self_.m_world.clone());\n\n\t\tm_contact_list = self_.m_contact_list.clone();\n\n\t\tm_fixture_count = self_.m_fixture_count;\n\n\t}\n\n\n\n\tb2_assert(world.borrow().is_locked() == false);\n\n\tif world.borrow().is_locked() == true {\n\n\t\treturn;\n\n\t}\n\n\n\n\tb2_assert(ptr::eq(\n\n\t\tupgrade_opt(&fixture.borrow().m_body).as_ref(),\n\n\t\tself_.as_ref(),\n\n\t));\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 24, "score": 169927.37963990725 }, { "content": "pub fn b2_fixture_dump<T:UserDataType>(_this: &B2fixture<T>, _body_index: i32) {\n\n\t//TODO_humman\n\n\t\n\n\t// b2Log(\" B2fixtureDef fd;\\n\");\n\n\t// b2Log(\" fd.friction = %.15lef;\\n\", m_friction);\n\n\t// b2Log(\" fd.restitution = %.15lef;\\n\", m_restitution);\n\n\t// b2Log(\" fd.density = %.15lef;\\n\", m_density);\n\n\t// b2Log(\" fd.is_sensor = bool(%d);\\n\", m_is_sensor);\n\n\t// b2Log(\" fd.filter.category_bits = uint16(%d);\\n\", m_filter.category_bits);\n\n\t// b2Log(\" fd.filter.mask_bits = uint16(%d);\\n\", m_filter.mask_bits);\n\n\t// b2Log(\" fd.filter.group_index = int16(%d);\\n\", m_filter.group_index);\n\n\n\n\t// switch (m_shape.m_type)\n\n\t// {\n\n\t// case B2ShapeType::ECircle:\n\n\t// \t{\n\n\t// \t\tB2circleShape* s = (B2circleShape*)m_shape;\n\n\t// \t\tb2Log(\" B2circleShape shape;\\n\");\n\n\t// \t\tb2Log(\" shape.m_radius = %.15lef;\\n\", s->m_radius);\n\n\t// \t\tb2Log(\" shape.m_p.set(%.15lef, %.15lef);\\n\", s->m_p.x, s->m_p.y);\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 25, "score": 164057.30965954153 }, { "content": "pub fn b2_contact_destroy<D: UserDataType>(self_: &dyn B2contactDynTrait<D>) {\n\n\tlet contact_base = self_.get_base();\n\n\n\n\tlet fixture_a = contact_base.m_fixture_a.borrow();\n\n\tlet fixture_b = contact_base.m_fixture_b.borrow();\n\n\n\n\tif contact_base.m_manifold.point_count > 0\n\n\t\t&& fixture_a.is_sensor() == false\n\n\t\t&& fixture_b.is_sensor() == false\n\n\t{\n\n\t\tfixture_a.get_body().borrow_mut().set_awake(true);\n\n\t\tfixture_b.get_body().borrow_mut().set_awake(true);\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_contact.rs", "rank": 26, "score": 161876.44473649407 }, { "content": "/// Joints and fixtures are destroyed when their associated\n\n/// body is destroyed. Implement this listener so that you\n\n/// may nullify references to these joints and shapes.\n\npub trait B2destructionListener<D: UserDataType> {\n\n\t/// Called when any joint is about to be destroyed due\n\n\t/// to the destruction of one of its attached bodies.\n\n\tfn say_goodbye_joint(&mut self, joint: B2jointPtr<D>);\n\n\n\n\t/// Called when any fixture is about to be destroyed due\n\n\t/// to the destruction of its parent body.\n\n\tfn say_goodbye_fixture(&mut self, fixture: FixturePtr<D>);\n\n}\n\n\n", "file_path": "src/b2_world_callbacks.rs", "rank": 27, "score": 155335.65570308483 }, { "content": "/// Implement this class to get contact information. You can use these results for\n\n/// things like sounds and game logic. You can also get contact results by\n\n/// traversing the contact lists after the time step. However, you might miss\n\n/// some contacts because continuous physics leads to sub-stepping.\n\n/// Additionally you may receive multiple callbacks for the same contact in a\n\n/// single time step.\n\n/// You should strive to make your callbacks efficient because there may be\n\n/// many callbacks per time step.\n\n/// @warning You cannot create/destroy Box2D entities inside these callbacks.\n\npub trait B2contactListener<D: UserDataType> {\n\n\t/// Called when two fixtures begin to touch.\n\n\tfn begin_contact(&mut self, contact: &mut dyn B2contactDynTrait<D>) {\n\n\t\tb2_not_used(contact);\n\n\t}\n\n\n\n\t/// Called when two fixtures cease to touch.\n\n\tfn end_contact(&mut self, contact: &mut dyn B2contactDynTrait<D>) {\n\n\t\tb2_not_used(contact);\n\n\t}\n\n\n\n\t/// This is called after a contact is updated. This allows you to inspect a\n\n\t/// contact before it goes to the solver. If you are careful, you can modify the\n\n\t/// contact manifold (e.g. disable contact).\n\n\t/// A copy of the old manifold is provided so that you can detect changes.\n\n\t/// Note: this is called only for awake bodies.\n\n\t/// Note: this is called even when the number of contact points is zero.\n\n\t/// Note: this is not called for sensors.\n\n\t/// Note: if you set the number of contact points to zero, you will not\n\n\t/// get an end_contact callback. However, you may get a begin_contact callback\n", "file_path": "src/b2_world_callbacks.rs", "rank": 28, "score": 155334.51049994017 }, { "content": "/// Implement this class to provide collision filtering. In other words, you can implement\n\n/// this class if you want finer control over contact creation.\n\npub trait B2contactFilter<D: UserDataType> {\n\n\t/// Return true if contact calculations should be performed between these two shapes.\n\n\t/// @warning for performance reasons this is only called when the AABBs begin to overlap.\n\n\tfn should_collide(&self, fixture_a: FixturePtr<D>, fixture_b: FixturePtr<D>) -> bool {\n\n\t\treturn private::should_collide(fixture_a, fixture_b);\n\n\t}\n\n}\n\n\n\npub struct B2contactFilterDefault;\n\n\n\nimpl<D: UserDataType> B2contactFilter<D> for B2contactFilterDefault {}\n\n\n\n/// Contact impulses for reporting. Impulses are used instead of forces because\n\n/// sub-step forces may approach infinity for rigid body collisions. These\n\n/// match up one-to-one with the contact points in B2manifold.\n\n#[derive(Default, Copy, Clone, Debug)]\n\npub struct B2contactImpulse {\n\n\tpub normal_impulses: [f32; B2_MAX_MANIFOLD_POINTS],\n\n\tpub tangent_impulses: [f32; B2_MAX_MANIFOLD_POINTS],\n\n\tpub count: i32,\n\n}\n\n\n", "file_path": "src/b2_world_callbacks.rs", "rank": 29, "score": 155331.064216887 }, { "content": "// pub trait QueryCallback {\n\n// \tfn query_callback(&mut self, proxy_id: i32) -> bool;\n\n// }\n\npub trait QueryCallback: FnMut(i32) -> bool {}\n\nimpl <F> QueryCallback for F where F: FnMut(i32) -> bool {}\n\n\n", "file_path": "src/b2_dynamic_tree.rs", "rank": 30, "score": 153893.7219762283 }, { "content": "pub fn b2_contact_manager_find_new_contacts<D: UserDataType>(this: &mut B2contactManager<D>) {\n\n\tlet broad_phase = this.m_broad_phase.clone();\n\n\tbroad_phase.borrow_mut().update_pairs(this);\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_contact_manager.rs", "rank": 31, "score": 150755.7807860661 }, { "content": "pub fn b2_shape_dyn_trait_compute_mass(this: &B2edgeShape, mass_data: &mut B2massData, density: f32) {\n\n\tb2_not_used(density);\n\n\n\n\tmass_data.mass = 0.0;\n\n\tmass_data.center = 0.5 * (this.m_vertex1 + this.m_vertex2);\n\n\tmass_data.i = 0.0;\n\n}\n", "file_path": "src/private/collision/b2_edge_shape.rs", "rank": 32, "score": 147733.3797760065 }, { "content": "pub fn b2_shape_dyn_trait_compute_mass(this: &B2polygonShape, mass_data: &mut B2massData, density: f32) {\n\n\t// Polygon mass, centroid, and inertia.\n\n\t// Let rho be the polygon density in mass per unit area.\n\n\t// Then:\n\n\t// mass = rho * i32(d_a)\n\n\t// centroid.x = (1/mass) * rho * i32(x * d_a)\n\n\t// centroid.y = (1/mass) * rho * i32(y * d_a)\n\n\t// i = rho * i32((x*x + y*y) * d_a)\n\n\t//\n\n\t// We can compute these integrals by summing all the integrals\n\n\t// for each triangle of the polygon. To evaluate the integral\n\n\t// for a single triangle, we make a change of variables to\n\n\t// the (u,v) coordinates of the triangle:\n\n\t// x = x0 + e1x * u + e2x * v\n\n\t// y = y0 + e1y * u + e2y * v\n\n\t// where 0 <= u && 0 <= v && u + v <= 1.\n\n\t//\n\n\t// We integrate u from [0,1-v] and then v from [0,1].\n\n\t// We also need to use the Jacobian of the transformation:\n\n\t// D = cross(e1, e2)\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 33, "score": 147733.3797760065 }, { "content": "pub fn b2_shape_dyn_trait_compute_mass(_this: &B2chainShape, mass_data: &mut B2massData, density: f32) {\n\n\tb2_not_used(density);\n\n\n\n\tmass_data.mass = 0.0;\n\n\tmass_data.center.set_zero();\n\n\tmass_data.i = 0.0;\n\n}\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 34, "score": 147733.3797760065 }, { "content": "// pub trait RayCastCallback {\n\n// \tfn ray_cast_callback(&mut self, input: &B2rayCastInput, proxy_id: i32) -> f32;\n\n// }\n\npub trait RayCastCallback: FnMut(&B2rayCastInput, i32) -> f32 {}\n\nimpl <F> RayCastCallback for F where F: FnMut(&B2rayCastInput, i32) -> f32 {}\n\n\n\nmod inline {\n\n\tuse super::*;\n\n\n\n\tpub fn get_user_data<UserDataType: Clone + Default>(\n\n\t\tthis: &B2dynamicTree<UserDataType>,\n\n\t\tproxy_id: i32,\n\n\t) -> Option<UserDataType> {\n\n\t\t//b2_assert(0 <= proxy_id && proxy_id < this.m_nodeCapacity);\n\n\t\treturn this.m_nodes[proxy_id as usize].user_data.clone();\n\n\t}\n\n\n\n\tpub fn was_moved<UserDataType: Clone + Default>(\n\n\t\tthis: &B2dynamicTree<UserDataType>,\n\n\t\tproxy_id: i32,\n\n\t) -> bool {\n\n\t\t//b2_assert(0 <= proxy_id && proxy_id < this.m_nodeCapacity);\n\n\t\treturn this.m_nodes[proxy_id as usize].moved;\n", "file_path": "src/b2_dynamic_tree.rs", "rank": 35, "score": 144204.55959240158 }, { "content": "pub fn create_fixture_by_shape<D: UserDataType>(\n\n\tself_: BodyPtr<D>,\n\n\tshape: ShapeDefPtr,\n\n\tdensity: f32,\n\n) -> FixturePtr<D> {\n\n\tlet mut def = B2fixtureDef::default();\n\n\tdef.shape = Some(shape);\n\n\tdef.density = density;\n\n\n\n\treturn create_fixture(self_, &def);\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 36, "score": 140539.36664321044 }, { "content": "// solve a line segment using barycentric coordinates.\n\n//\n\n// p = a1 * w1 + a2 * w2\n\n// a1 + a2 = 1\n\n//\n\n// The vector from the origin to the closest point on the line is\n\n// perpendicular to the line.\n\n// e12 = w2 - w1\n\n// dot(p, e) = 0\n\n// a1 * dot(w1, e) + a2 * dot(w2, e) = 0\n\n//\n\n// 2-by-2 linear system\n\n// [1 1 ][a1] = [1]\n\n// [w1.e12 w2.e12][a2] = [0]\n\n//\n\n// Define\n\n// d12_1 = dot(w2, e12)\n\n// d12_2 = -dot(w1, e12)\n\n// d12 = d12_1 + d12_2\n\n//\n\n// Solution\n\n// a1 = d12_1 / d12\n\n// a2 = d12_2 / d12\n\nfn b2_simplex_solve2(this: &mut B2simplex) {\n\n\tlet w1: B2vec2 = this.m_v[0].w;\n\n\tlet w2: B2vec2 = this.m_v[1].w;\n\n\tlet e12: B2vec2 = w2 - w1;\n\n\n\n\t// w1 region\n\n\tlet d12_2: f32 = -b2_dot(w1, e12);\n\n\tif d12_2 <= 0.0 {\n\n\t\t// a2 <= 0, so we clamp it to 0\n\n\t\tthis.m_v[0].a = 1.0;\n\n\t\tthis.m_count = 1;\n\n\t\treturn;\n\n\t}\n\n\n\n\t// w2 region\n\n\tlet d12_1: f32 = b2_dot(w2, e12);\n\n\tif d12_1 <= 0.0 {\n\n\t\t// a1 <= 0, so we clamp it to 0\n\n\t\tthis.m_v[1].a = 1.0;\n\n\t\tthis.m_count = 1;\n", "file_path": "src/private/collision/b2_distance.rs", "rank": 37, "score": 137813.1915879937 }, { "content": "// Possible regions:\n\n// - points[2]\n\n// - edge points[0]-points[2]\n\n// - edge points[1]-points[2]\n\n// - inside the triangle\n\nfn b2_simplex_solve3(this: &mut B2simplex) {\n\n\tlet w1: B2vec2 = this.m_v[0].w;\n\n\tlet w2: B2vec2 = this.m_v[1].w;\n\n\tlet w3: B2vec2 = this.m_v[2].w;\n\n\n\n\t// Edge12\n\n\t// [1 1 ][a1] = [1]\n\n\t// [w1.e12 w2.e12][a2] = [0]\n\n\t// a3 = 0\n\n\tlet e12: B2vec2 = w2 - w1;\n\n\tlet w1e12: f32 = b2_dot(w1, e12);\n\n\tlet w2e12: f32 = b2_dot(w2, e12);\n\n\tlet d12_1: f32 = w2e12;\n\n\tlet d12_2: f32 = -w1e12;\n\n\n\n\t// Edge13\n\n\t// [1 1 ][a1] = [1]\n\n\t// [w1.e13 w3.e13][a3] = [0]\n\n\t// a2 = 0\n\n\tlet e13: B2vec2 = w3 - w1;\n", "file_path": "src/private/collision/b2_distance.rs", "rank": 38, "score": 137809.6846026872 }, { "content": "pub fn b2_fixture_default<T:UserDataType>() -> B2fixture<T> {\n\n\treturn B2fixture::<T> {\n\n\t\tm_user_data: None,\n\n\t\tm_body: None,\n\n\t\tm_next: None,\n\n\t\tm_proxies: Vec::default(),\n\n\t\tm_proxy_count:0,\n\n\t\tm_shape: None,\n\n\t\tm_density: 0.0,\n\n\t\tm_filter: B2filter::default(),\n\n\t\tm_friction: 0.0,\n\n\t\tm_is_sensor: false,\n\n\t\tm_restitution: 0.0,\n\n\t};\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 39, "score": 135968.33759020397 }, { "content": "pub fn b2_chain_shape_clear(this: &mut B2chainShape) {\n\n\tthis.m_vertices.clear();\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 40, "score": 129965.06784131899 }, { "content": "/// Compute the upper bound on time before two shapes penetrate. Time is represented as\n\n/// a fraction between [0,t_max]. This uses a swept separating axis and may miss some intermediate,\n\n/// non-tunneling collisions. If you change the time interval, you should call this function\n\n/// again.\n\n/// Note: use b2Distance to compute the contact point and normal at the time of impact.\n\npub fn b2_time_of_impact(output: &mut B2toioutput, input: &B2toiinput) {\n\n\tprivate::b2_time_of_impact(output, input);\n\n}\n", "file_path": "src/b2_time_of_impact.rs", "rank": 41, "score": 127963.49203922151 }, { "content": "pub trait AddPairTrait<UserDataType> {\n\n\tfn add_pair(\n\n\t\t&mut self,\n\n\t\tproxy_user_data_a: Option<UserDataType>,\n\n\t\tproxy_user_data_b: Option<UserDataType>,\n\n\t);\n\n}\n\n\n\nmod inline {\n\n\tuse super::*;\n\n\n\n\tpub fn get_user_data<UserDataType: Default + Clone>(\n\n\t\tthis: &B2broadPhase<UserDataType>,\n\n\t\tproxy_id: i32,\n\n\t) -> Option<UserDataType> {\n\n\t\treturn this.m_tree.get_user_data(proxy_id);\n\n\t}\n\n\n\n\tpub fn test_overlap<T: Default + Clone>(\n\n\t\tthis: &B2broadPhase<T>,\n", "file_path": "src/b2_broad_phase.rs", "rank": 42, "score": 126861.01568104434 }, { "content": "pub trait B2contactDynTrait<D: UserDataType> {\n\n\tfn get_base<'a>(&'a self) -> &'a B2contact<D>;\n\n\tfn get_base_mut<'a>(&'a mut self) -> &'a mut B2contact<D>;\n\n\t/// evaluate this contact with your own manifold and transforms.\n\n\tfn evaluate(&self, manifold: &mut B2manifold, xf_a: &B2Transform, xf_b: &B2Transform);\n\n}\n\n\n\nimpl<D:UserDataType> LinkedListNode<dyn B2contactDynTrait<D>> for dyn B2contactDynTrait<D>\n\n{ \t\n\n\tfn get_next(&self) -> Option<Rc<RefCell<dyn B2contactDynTrait<D>>>>\n\n\t{\n\n\t\treturn self.get_base().m_next.clone();\n\n\t}\n\n\tfn set_next(&mut self, value: Option<Rc<RefCell<dyn B2contactDynTrait<D>>>>)\n\n\t{\n\n\t\tself.get_base_mut().m_next = value;\n\n\t}\n\n\tfn take_next(&mut self) -> Option<Rc<RefCell<dyn B2contactDynTrait<D>>>> {\n\n\t\treturn self.get_base_mut().m_next.take();\n\n\t}\n", "file_path": "src/b2_contact.rs", "rank": 43, "score": 125649.10709475834 }, { "content": "// This is the top level collision call for the time step. Here\n\n// all the narrow phase collision is processed for the world\n\n// contact list.\n\npub fn b2_contact_manager_collide<D: UserDataType>(self_: B2contactManagerPtr<D>) {\n\n\tlet mut contacts_to_destroy = Vec::<ContactPtr<D>>::new();\n\n\n\n\tlet (m_contact_list, m_broad_phase, m_contact_filter,m_contact_listener) = {\n\n\t\tlet self_ = self_.borrow();\n\n\t\t//assert!(self_.m_contact_count==self_.m_contact_list.len());\n\n\t\t(self_.m_contact_list.clone(),self_.m_broad_phase.clone(),self_.m_contact_filter.clone(),self_.m_contact_listener.clone())\n\n\t};\n\n\n\n\t// update awake contacts.\n\n\tfor c in m_contact_list.iter() {\n\n\t\tlet fixture_a = c.borrow().get_base().get_fixture_a();\n\n\t\tlet fixture_b = c.borrow().get_base().get_fixture_b();\n\n\t\tlet index_a: i32 = c.borrow().get_base().get_child_index_a();\n\n\t\tlet index_b: i32 = c.borrow().get_base().get_child_index_b();\n\n\t\tlet body_a = fixture_a.borrow().get_body();\n\n\t\tlet body_b = fixture_b.borrow().get_body();\n\n\t\t// Is this contact flagged for filtering?\n\n\t\tif c.borrow()\n\n\t\t\t.get_base()\n", "file_path": "src/private/dynamics/b2_contact_manager.rs", "rank": 44, "score": 125285.73389983513 }, { "content": "// CCD via the local separating axis method. This seeks progression\n\n// by computing the largest time at which separation is maintained.\n\npub fn b2_time_of_impact(output: &mut B2toioutput, input: &B2toiinput) {\n\n\tlet timer = B2timer::default();\n\n\n\n\tB2_TOI_CALLS.fetch_add(1, Ordering::SeqCst);\n\n\n\n\toutput.state = B2toioutputState::EUnknown;\n\n\toutput.t = input.t_max;\n\n\n\n\tlet proxy_a: &B2distanceProxy = &input.proxy_a;\n\n\tlet proxy_b: &B2distanceProxy = &input.proxy_b;\n\n\n\n\tlet mut sweep_a: B2Sweep = input.sweep_a;\n\n\tlet mut sweep_b: B2Sweep = input.sweep_b;\n\n\n\n\t// Large rotations can make the root finder fail, so we normalize the\n\n\t// sweep angles.\n\n\tsweep_a.normalize();\n\n\tsweep_b.normalize();\n\n\n\n\tlet t_max: f32 = input.t_max;\n", "file_path": "src/private/collision/b2_time_of_impact.rs", "rank": 45, "score": 125194.01004403192 }, { "content": "pub fn b2_polygon_shape_set(this: &mut B2polygonShape, vertices: &[B2vec2]) {\n\n\tlet count = vertices.len();\n\n\tb2_assert(3 <= count && count <= B2_MAX_POLYGON_VERTICES);\n\n\tif count < 3 {\n\n\t\tb2_polygon_shape_set_as_box(this, 1.0, 1.0);\n\n\t\treturn;\n\n\t}\n\n\tlet mut n: usize = b2_min(count, B2_MAX_POLYGON_VERTICES);\n\n\n\n\t// Perform welding and copy vertices into local buffer.\n\n\tlet mut ps = <[B2vec2; B2_MAX_POLYGON_VERTICES]>::default();\n\n\tlet mut temp_count: usize = 0;\n\n\tfor i in 0..n {\n\n\t\tlet v: B2vec2 = vertices[i];\n\n\n\n\t\tlet mut unique: bool = true;\n\n\t\tfor j in 0..temp_count {\n\n\t\t\tif b2_distance_vec2_squared(v, ps[j as usize])\n\n\t\t\t\t< ((0.5 * B2_LINEAR_SLOP) * (0.5 * B2_LINEAR_SLOP))\n\n\t\t\t{\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 46, "score": 123883.8243477833 }, { "content": "enum B2separationFunctionType {\n\n\tEPoints,\n\n\tEFaceA,\n\n\tEFaceB,\n\n}\n\n\n", "file_path": "src/private/collision/b2_time_of_impact.rs", "rank": 47, "score": 122678.2100219377 }, { "content": "pub fn b2_chain_shape_create_loop(this: &mut B2chainShape, vertices: &[B2vec2]) {\n\n\tlet count = vertices.len();\n\n\tb2_assert(this.m_vertices.len() == 0);\n\n\tb2_assert(count >= 3);\n\n\tif count < 3 {\n\n\t\treturn;\n\n\t}\n\n\n\n\tfor i in 1..count {\n\n\t\tlet v1: B2vec2 = vertices[i - 1];\n\n\t\tlet v2: B2vec2 = vertices[i];\n\n\t\t// If the code crashes here, it means your vertices are too close together.\n\n\t\tb2_assert(b2_distance_vec2_squared(v1, v2) > B2_LINEAR_SLOP * B2_LINEAR_SLOP);\n\n\t}\n\n\n\n\tthis.m_vertices = Vec::from([vertices, &[vertices[0]]].concat());\n\n\tthis.m_prev_vertex = this.m_vertices[this.m_vertices.len() - 2];\n\n\tthis.m_next_vertex = this.m_vertices[1];\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 48, "score": 122618.38966649081 }, { "content": "pub fn set_vertices(this: &mut B2distanceProxy, vertices: &[B2vec2], radius: f32) {\n\n\tthis.m_vertices = Vec::from(vertices);\n\n\tthis.m_radius = radius;\n\n}\n\n\n", "file_path": "src/private/collision/b2_distance.rs", "rank": 49, "score": 122191.9810308723 }, { "content": "// Return true if contact calculations should be performed between these two shapes.\n\n// If you implement your own collision filter you may want to build from this implementation.\n\npub fn should_collide<D:UserDataType>(fixture_a: FixturePtr<D>, fixture_b: FixturePtr<D>) -> bool\n\n{\n\n\tlet filter_a = fixture_a.borrow().get_filter_data();\n\n\tlet filter_b = fixture_b.borrow().get_filter_data();\n\n\n\n\tif filter_a.group_index == filter_b.group_index && filter_a.group_index != 0\n\n\t{\n\n\t\treturn filter_a.group_index > 0;\n\n\t}\n\n\n\n\tlet collide:bool = (filter_a.mask_bits & filter_b.category_bits) != 0 && (filter_a.category_bits & filter_b.mask_bits) != 0;\n\n\treturn collide;\n\n}\n", "file_path": "src/private/dynamics/b2_world_callbacks.rs", "rank": 50, "score": 121395.26876069677 }, { "content": "/// Perform a linear shape cast of shape b moving and shape A fixed. Determines the hit point, normal, and translation fraction.\n\npub fn b2_shape_cast(output: &mut B2shapeCastOutput, input: B2shapeCastInput) -> bool {\n\n return private::b2_shape_cast(output, input);\n\n}\n\n\n\nmod inline {\n\n use super::*;\n\n\n\n pub fn get_vertex_count(this: &B2distanceProxy) -> usize {\n\n return this.m_vertices.len();\n\n }\n\n\n\n pub fn get_vertex(this: &B2distanceProxy, index: usize) -> B2vec2 {\n\n b2_assert(index < this.m_vertices.len());\n\n return this.m_vertices[index];\n\n }\n\n\n\n pub fn get_support(this: &B2distanceProxy, d: B2vec2) -> usize {\n\n let mut best_index: usize = 0;\n\n let mut best_value: f32 = b2_dot(this.m_vertices[0], d);\n\n for i in 1..this.m_vertices.len() {\n", "file_path": "src/b2_distance.rs", "rank": 51, "score": 121070.71472001317 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\nenum B2ePAxisType {\n\n\tEUnknown,\n\n\tEEdgeA,\n\n\tEEdgeB,\n\n}\n\n\n\nimpl Default for B2ePAxisType {\n\n\tfn default() -> Self {\n\n\t\treturn B2ePAxisType::EUnknown;\n\n\t}\n\n}\n\n\n\n// This structure is used to keep track of the best separating axis.\n", "file_path": "src/private/collision/b2_collide_edge.rs", "rank": 52, "score": 121025.07251993503 }, { "content": "pub fn rebuild_bottom_up<T: Clone + Default>(this: &mut B2dynamicTree<T>) {\n\n\tlet mut nodes = Vec::<i32>::new();\n\n\tnodes.resize(this.m_node_count as usize, -1);\n\n\tlet mut count: i32 = 0;\n\n\n\n\t//parent_or_next = parent\n\n\n\n\t// Build array of leaves. Free the rest.\n\n\tfor i in 0..this.m_node_capacity {\n\n\t\tif this.m_nodes[i as usize].height < 0 {\n\n\t\t\t// free node in pool\n\n\t\t\tcontinue;\n\n\t\t}\n\n\n\n\t\tif this.m_nodes[i as usize].is_leaf() {\n\n\t\t\tthis.m_nodes[i as usize].parent_or_next = B2_NULL_NODE;\n\n\t\t\tnodes[count as usize] = i;\n\n\t\t\tcount += 1;\n\n\t\t} else {\n\n\t\t\tthis.free_node(i);\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 53, "score": 120881.79533462369 }, { "content": "pub trait B2jointTraitDyn<D: UserDataType>: ToDerivedJoint<D> {\n\n\tfn get_base(&self) -> &B2joint<D>;\n\n\tfn get_base_mut(&mut self) -> &mut B2joint<D>;\n\n\t/// Get the anchor point on body_a in world coordinates.\n\n\tfn get_anchor_a(&self) -> B2vec2;\n\n\n\n\t/// Get the anchor point on body_b in world coordinates.\n\n\tfn get_anchor_b(&self) -> B2vec2;\n\n\n\n\t/// Get the reaction force on body_b at the joint anchor in Newtons.\n\n\tfn get_reaction_force(&self, inv_dt: f32) -> B2vec2;\n\n\n\n\t/// Get the reaction torque on body_b in n*m.\n\n\tfn get_reaction_torque(&self, inv_dt: f32) -> f32;\n\n\n\n\t/// dump this joint to the log file.\n\n\tfn dump(&self) {\n\n\t\t//b2Log(\"// dump is not supported for this joint type.\\n\");\n\n\t}\n\n\n", "file_path": "src/b2_joint.rs", "rank": 54, "score": 119449.93840228551 }, { "content": "// GJK-raycast\n\n// Algorithm by Gino van den Bergen.\n\n// \"Smooth Mesh Contacts with GJK\" in Game Physics Pearls. 2010\n\npub fn b2_shape_cast(output: &mut B2shapeCastOutput, input: B2shapeCastInput) -> bool {\n\n\toutput.iterations = 0;\n\n\toutput.lambda = 1.0;\n\n\toutput.normal.set_zero();\n\n\toutput.point.set_zero();\n\n\n\n\tlet proxy_a: &B2distanceProxy = &input.proxy_a;\n\n\tlet proxy_b: &B2distanceProxy = &input.proxy_b;\n\n\n\n\tlet radius_a: f32 = b2_max(proxy_a.m_radius, B2_POLYGON_RADIUS);\n\n\tlet radius_b: f32 = b2_max(proxy_b.m_radius, B2_POLYGON_RADIUS);\n\n\tlet radius: f32 = radius_a + radius_b;\n\n\n\n\tlet xf_a: B2Transform = input.transform_a;\n\n\tlet xf_b: B2Transform = input.transform_b;\n\n\n\n\tlet r: B2vec2 = input.translation_b;\n\n\tlet mut n = B2vec2::zero();\n\n\tlet mut lambda: f32 = 0.0;\n\n\n", "file_path": "src/private/collision/b2_distance.rs", "rank": 55, "score": 118665.23015041571 }, { "content": "pub fn compute_mass(this: &B2circleShape, mass_data: &mut B2massData, density: f32) {\n\n\tmass_data.mass = density * B2_PI * this.base.m_radius * this.base.m_radius;\n\n\tmass_data.center = this.m_p;\n\n\n\n\t// inertia about the local origin\n\n\tmass_data.i = mass_data.mass\n\n\t\t* (0.5 * this.base.m_radius * this.base.m_radius + b2_dot(this.m_p, this.m_p));\n\n}\n", "file_path": "src/private/collision/b2_circle_shape.rs", "rank": 56, "score": 118393.42269653446 }, { "content": "pub fn b2_set_two_sided(this: &mut B2edgeShape, v1: B2vec2, v2: B2vec2) {\n\n\tthis.m_vertex1 = v1;\n\n\tthis.m_vertex2 = v2;\n\n\tthis.m_one_sided = false;\n\n}\n\n\n", "file_path": "src/private/collision/b2_edge_shape.rs", "rank": 57, "score": 118393.42269653446 }, { "content": "// Allocate a node from the pool. Grow the pool if necessary.\n\npub fn allocate_node<T: Clone + Default>(this: &mut B2dynamicTree<T>) -> i32 {\n\n\t// Expand the node pool as needed.\n\n\tif this.m_free_list == B2_NULL_NODE {\n\n\t\tb2_assert(this.m_node_count == this.m_node_capacity);\n\n\n\n\t\t// The free list is empty. Rebuild a bigger pool.\n\n\t\tthis.m_node_capacity *= 2;\n\n\t\tthis.m_nodes\n\n\t\t\t.resize(this.m_node_capacity as usize, B2treeNode::<T>::default());\n\n\n\n\t\t// Build a linked list for the free list. The parent\n\n\t\t// pointer becomes the \"next\" pointer.\n\n\t\tfor i in this.m_node_count..this.m_node_capacity - 1 {\n\n\t\t\tthis.m_nodes[i as usize].parent_or_next = i + 1; //next\n\n\t\t\tthis.m_nodes[i as usize].height = -1;\n\n\t\t}\n\n\t\tthis.m_nodes[(this.m_node_capacity - 1) as usize].parent_or_next = B2_NULL_NODE; //next\n\n\t\tthis.m_nodes[(this.m_node_capacity - 1) as usize].height = -1;\n\n\t\tthis.m_free_list = this.m_node_count;\n\n\t}\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 58, "score": 118247.13397088528 }, { "content": "pub fn b2_polygon_shape_set_as_box(this: &mut B2polygonShape, hx: f32, hy: f32) {\n\n\tthis.m_count = 4;\n\n\tthis.m_vertices[0].set(-hx, -hy);\n\n\tthis.m_vertices[1].set(hx, -hy);\n\n\tthis.m_vertices[2].set(hx, hy);\n\n\tthis.m_vertices[3].set(-hx, hy);\n\n\tthis.m_normals[0].set(0.0, -1.0);\n\n\tthis.m_normals[1].set(1.0, 0.0);\n\n\tthis.m_normals[2].set(0.0, 1.0);\n\n\tthis.m_normals[3].set(-1.0, 0.0);\n\n\tthis.m_centroid.set_zero();\n\n}\n\n\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 59, "score": 117210.87608373372 }, { "content": "pub trait ToDerivedJoint<D: UserDataType> {\n\n\tfn as_derived(&self) -> JointAsDerived<D>;\n\n\tfn as_derived_mut(&mut self) -> JointAsDerivedMut<D>;\n\n}\n\n\n\npub enum JointAsDerived<'a, D: UserDataType> {\n\n\tEDistanceJoint(&'a B2distanceJoint<D>),\n\n\tEFrictionJoint(&'a B2frictionJoint<D>),\n\n\tEGearJoint(&'a B2gearJoint<D>),\n\n\tEMouseJoint(&'a B2mouseJoint<D>),\n\n\tEMotorJoint(&'a B2motorJoint<D>),\n\n\tEPulleyJoint(&'a B2pulleyJoint<D>),\n\n\tERevoluteJoint(&'a B2revoluteJoint<D>),\n\n\tERopeJoint(&'a B2ropeJoint<D>),\n\n\tEPrismaticJoint(&'a B2prismaticJoint<D>),\n\n\tEWeldJoint(&'a B2weldJoint<D>),\n\n\tEWheelJoint(&'a B2wheelJoint<D>),\n\n}\n\n\n\npub enum JointAsDerivedMut<'a, D: UserDataType> {\n", "file_path": "src/b2_joint.rs", "rank": 60, "score": 116321.08907419685 }, { "content": "// Perform a left or right rotation if node A is imbalanced.\n\n// Returns the new root index.\n\npub fn balance<T: Clone + Default>(this: &mut B2dynamicTree<T>, i_a: i32) -> i32 {\n\n\tb2_assert(i_a != B2_NULL_NODE);\n\n\n\n\tlet mut a = this.m_nodes[i_a as usize].clone();\n\n\tif a.is_leaf() || a.height < 2 {\n\n\t\treturn i_a;\n\n\t}\n\n\n\n\tlet i_b: i32 = a.child1;\n\n\tlet i_c: i32 = a.child2;\n\n\tb2_assert(0 <= i_b && i_b < this.m_node_capacity);\n\n\tb2_assert(0 <= i_c && i_c < this.m_node_capacity);\n\n\n\n\t//TODO_humman заменить clone на get_five_mut(A b c f G D E)\n\n\tlet mut b = this.m_nodes[i_b as usize].clone();\n\n\tlet mut c = this.m_nodes[i_c as usize].clone();\n\n\n\n\tlet balance: i32 = c.height - b.height;\n\n\n\n\t//parent_or_next = parent\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 61, "score": 115740.75951792873 }, { "content": "pub fn remove_leaf<T: Clone + Default>(this: &mut B2dynamicTree<T>, leaf: i32) {\n\n\tif leaf == this.m_root {\n\n\t\tthis.m_root = B2_NULL_NODE;\n\n\t\treturn;\n\n\t}\n\n\n\n\tlet parent: i32 = this.m_nodes[leaf as usize].parent_or_next; //parent_or_next = parent\n\n\tlet grand_parent: i32 = this.m_nodes[parent as usize].parent_or_next; //parent_or_next = parent\n\n\tlet sibling: i32;\n\n\tif this.m_nodes[parent as usize].child1 == leaf {\n\n\t\tsibling = this.m_nodes[parent as usize].child2;\n\n\t} else {\n\n\t\tsibling = this.m_nodes[parent as usize].child1;\n\n\t}\n\n\n\n\tif grand_parent != B2_NULL_NODE {\n\n\t\t// destroy parent and connect sibling to grandParent.\n\n\t\tif this.m_nodes[grand_parent as usize].child1 == parent {\n\n\t\t\tthis.m_nodes[grand_parent as usize].child1 = sibling;\n\n\t\t} else {\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 62, "score": 115732.83512301135 }, { "content": "pub fn insert_leaf<T: Clone + Default>(this: &mut B2dynamicTree<T>, leaf: i32) {\n\n\tthis.m_insertion_count += 1;\n\n\n\n\tif this.m_root == B2_NULL_NODE {\n\n\t\tthis.m_root = leaf;\n\n\t\tthis.m_nodes[this.m_root as usize].parent_or_next = B2_NULL_NODE; //parent_or_next = parent\n\n\t\treturn;\n\n\t}\n\n\n\n\t// Find the best sibling for this node\n\n\tlet leaf_aabb: B2AABB = this.m_nodes[leaf as usize].aabb;\n\n\tlet mut index: i32 = this.m_root;\n\n\twhile this.m_nodes[index as usize].is_leaf() == false {\n\n\t\tlet child1: i32 = this.m_nodes[index as usize].child1;\n\n\t\tlet child2: i32 = this.m_nodes[index as usize].child2;\n\n\n\n\t\tlet area: f32 = this.m_nodes[index as usize].aabb.get_perimeter();\n\n\n\n\t\tlet mut combined_aabb = B2AABB::default();\n\n\t\tcombined_aabb.combine_two(this.m_nodes[index as usize].aabb, leaf_aabb);\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 63, "score": 115732.83512301135 }, { "content": "#[cfg(not(feature = \"serde_support\"))]\n\npub trait UserDataType: Default + Clone + 'static {\n\n type Fixture: Default + Clone + std::fmt::Debug;\n\n type Body: Default + Clone + PartialEq + std::fmt::Debug;\n\n type Joint: Default + Clone + std::fmt::Debug;\n\n}\n\n\n", "file_path": "src/b2_settings.rs", "rank": 64, "score": 115197.45028474707 }, { "content": "pub fn b2_chain_shape_get_child_edge(this: &B2chainShape, edge: &mut B2edgeShape, index: usize) {\n\n\tb2_assert(index < this.m_vertices.len() - 1);\n\n\tedge.base.m_type = B2ShapeType::EEdge;\n\n\tedge.base.m_radius = this.base.m_radius;\n\n\n\n\tedge.m_vertex1 = this.m_vertices[index + 0];\n\n\tedge.m_vertex2 = this.m_vertices[index + 1];\n\n\tedge.m_one_sided = true;\n\n\n\n\tif index > 0 {\n\n\t\tedge.m_vertex0 = this.m_vertices[index - 1];\n\n\t} else {\n\n\t\tedge.m_vertex0 = this.m_prev_vertex;\n\n\t}\n\n\n\n\tif index < this.m_vertices.len() - 2 {\n\n\t\tedge.m_vertex3 = this.m_vertices[index + 2];\n\n\t} else {\n\n\t\tedge.m_vertex3 = this.m_next_vertex;\n\n\t}\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 65, "score": 114959.2085033672 }, { "content": "// Return a node to the pool.\n\npub fn free_node<T: Clone + Default>(this: &mut B2dynamicTree<T>, node_id: i32) {\n\n\tb2_assert(0 <= node_id && node_id < this.m_node_capacity);\n\n\tb2_assert(0 < this.m_node_count);\n\n\tthis.m_nodes[node_id as usize].parent_or_next = this.m_free_list; //next\n\n\tthis.m_nodes[node_id as usize].height = -1;\n\n\tthis.m_free_list = node_id;\n\n\tthis.m_node_count -= 1;\n\n}\n\n\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 66, "score": 114555.52331571933 }, { "content": "pub fn destroy_proxy<T: Clone + Default>(this: &mut B2dynamicTree<T>, proxy_id: i32) {\n\n\tb2_assert(0 <= proxy_id && proxy_id < this.m_node_capacity);\n\n\tb2_assert(this.m_nodes[proxy_id as usize].is_leaf());\n\n\n\n\tremove_leaf(this, proxy_id);\n\n\tfree_node(this, proxy_id);\n\n}\n\n\n", "file_path": "src/private/collision/b2_dynamic_tree.rs", "rank": 67, "score": 114550.28851021058 }, { "content": "// From Real-time Collision Detection, p179.\n\npub fn b2_aabb_ray_cast(this: B2AABB, output: &mut B2rayCastOutput, input: &B2rayCastInput) -> bool {\n\n\tlet mut tmin: f32 = -B2_MAX_FLOAT;\n\n\tlet mut tmax: f32 = B2_MAX_FLOAT;\n\n\n\n\tlet p: B2vec2 = input.p1;\n\n\tlet d: B2vec2 = input.p2 - input.p1;\n\n\tlet abs_d: B2vec2 = b2_abs_vec2(d);\n\n\n\n\tlet mut normal = B2vec2 { x: 0.0, y: 0.0 };\n\n\n\n\tfor i in 0..2 {\n\n\t\tif abs_d.get(i) < B2_EPSILON {\n\n\t\t\t// Parallel.\n\n\t\t\tif p.get(i) < this.lower_bound.get(i) || this.upper_bound.get(i) < p.get(i) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tlet inv_d: f32 = 1.0 / d.get(i);\n\n\t\t\tlet mut t1: f32 = (this.lower_bound.get(i) - p.get(i)) * inv_d;\n\n\t\t\tlet mut t2: f32 = (this.upper_bound.get(i) - p.get(i)) * inv_d;\n", "file_path": "src/private/collision/b2_collision.rs", "rank": 68, "score": 112517.29145318663 }, { "content": "/// Compute the point states given two manifolds. The states pertain to the transition from manifold1\n\n/// to manifold2. So state1 is either persist or remove while state2 is either add or persist.\n\npub fn b2_get_point_states(\n\n state1: &mut [B2pointState; B2_MAX_MANIFOLD_POINTS],\n\n state2: &mut [B2pointState; B2_MAX_MANIFOLD_POINTS],\n\n manifold1: &B2manifold,\n\n manifold2: &B2manifold,\n\n) {\n\n private::b2_collision::b2_get_point_states(state1, state2, manifold1, manifold2);\n\n}\n\n\n\n/// Used for computing contact manifolds.\n\n#[derive(Clone, Default, Copy, Debug)]\n\npub struct B2clipVertex {\n\n pub v: B2vec2,\n\n pub id: B2contactId,\n\n}\n\n\n\n/// Ray-cast input data. The ray extends from p1 to p1 + max_fraction * (p2 - p1).\n\n#[derive(Clone, Copy, Debug)]\n\npub struct B2rayCastInput {\n\n pub p1: B2vec2,\n", "file_path": "src/b2_collision.rs", "rank": 69, "score": 111264.4139483302 }, { "content": "pub fn b2_broad_phase_touch_proxy<T: Default + Clone>(this: &mut B2broadPhase<T>, proxy_id: i32) {\n\n\tthis.buffer_move(proxy_id);\n\n}\n\n\n", "file_path": "src/private/collision/b2_broad_phase.rs", "rank": 70, "score": 111225.93056210942 }, { "content": "pub fn b2_broad_phase_buffer_move<T: Default + Clone>(this: &mut B2broadPhase<T>, proxy_id: i32) {\n\n\tif this.m_move_count == this.m_move_capacity {\n\n\t\tthis.m_move_capacity *= 2;\n\n\t\tthis.m_move_buffer\n\n\t\t\t.resize_with(this.m_move_capacity as usize, Default::default);\n\n\t}\n\n\n\n\tthis.m_move_buffer[this.m_move_count as usize] = proxy_id;\n\n\tthis.m_move_count += 1;\n\n}\n\n\n", "file_path": "src/private/collision/b2_broad_phase.rs", "rank": 71, "score": 111225.93056210942 }, { "content": "pub fn b2_broad_phase_destroy_proxy<T: Default + Clone>(this: &mut B2broadPhase<T>, proxy_id: i32) {\n\n\tthis.un_buffer_move(proxy_id);\n\n\tthis.m_proxy_count -= 1;\n\n\tthis.m_tree.destroy_proxy(proxy_id);\n\n}\n\n\n", "file_path": "src/private/collision/b2_broad_phase.rs", "rank": 72, "score": 111225.93056210942 }, { "content": "pub fn b2_chain_shape_create_chain(this: &mut B2chainShape, vertices: &[B2vec2], prev_vertex: B2vec2, next_vertex: B2vec2) {\n\n\tlet count = vertices.len();\n\n\tb2_assert(this.m_vertices.len() == 0);\n\n\tb2_assert(count >= 2);\n\n\tfor i in 1..count {\n\n\t\t// If the code crashes here, it means your vertices are too close together.\n\n\t\tb2_assert(\n\n\t\t\tb2_distance_vec2_squared(vertices[i - 1], vertices[i])\n\n\t\t\t\t> B2_LINEAR_SLOP * B2_LINEAR_SLOP,\n\n\t\t);\n\n\t}\n\n\n\n\tthis.m_vertices = Vec::from(vertices);\n\n\n\n\tthis.m_prev_vertex = prev_vertex;\n\n\tthis.m_next_vertex = next_vertex;\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 73, "score": 110186.473852074 }, { "content": "pub fn b2_broad_phase_un_buffer_move<T: Default + Clone>(this: &mut B2broadPhase<T>, proxy_id: i32) {\n\n\tfor i in 0..this.m_move_count {\n\n\t\tif this.m_move_buffer[i as usize] == proxy_id {\n\n\t\t\tthis.m_move_buffer[i as usize] = E_NULL_PROXY;\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/private/collision/b2_broad_phase.rs", "rank": 74, "score": 110186.473852074 }, { "content": "pub fn b2_set_one_sided(this: &mut B2edgeShape, v0: B2vec2, v1: B2vec2, v2: B2vec2, v3: B2vec2) {\n\n\tthis.m_vertex0 = v0;\n\n\tthis.m_vertex1 = v1;\n\n\tthis.m_vertex2 = v2;\n\n\tthis.m_vertex3 = v3;\n\n\tthis.m_one_sided = true;\n\n}\n\n\n", "file_path": "src/private/collision/b2_edge_shape.rs", "rank": 75, "score": 108851.66713257419 }, { "content": "pub fn b2_get_point_states(\n\n\tstate1: &mut [B2pointState; B2_MAX_MANIFOLD_POINTS],\n\n\tstate2: &mut [B2pointState; B2_MAX_MANIFOLD_POINTS],\n\n\tmanifold1: &B2manifold,\n\n\tmanifold2: &B2manifold,\n\n) {\n\n\tfor i in 0..B2_MAX_MANIFOLD_POINTS {\n\n\t\tstate1[i] = B2pointState::B2NullState;\n\n\t\tstate2[i] = B2pointState::B2NullState;\n\n\t}\n\n\n\n\t// Detect persists and removes.\n\n\tfor i in 0..manifold1.point_count {\n\n\t\tlet id: B2contactId = manifold1.points[i].id;\n\n\n\n\t\tstate1[i] = B2pointState::B2RemoveState;\n\n\n\n\t\tfor j in 0..manifold2.point_count {\n\n\t\t\t\n\n\t\t\t\tif manifold2.points[j].id.cf == id.cf {\n", "file_path": "src/private/collision/b2_collision.rs", "rank": 76, "score": 107910.66041406002 }, { "content": "pub fn b2_world_manifold_initialize(\n\n\tthis: &mut B2worldManifold,\n\n\tmanifold: &B2manifold,\n\n\txf_a: B2Transform,\n\n\tradius_a: f32,\n\n\txf_b: B2Transform,\n\n\tradius_b: f32,\n\n) {\n\n\tif manifold.point_count == 0 {\n\n\t\treturn;\n\n\t}\n\n\n\n\tmatch manifold.manifold_type {\n\n\t\tB2manifoldType::ECircles => {\n\n\t\t\tthis.normal.set(1.0, 0.0);\n\n\t\t\tlet point_a: B2vec2 = b2_mul_transform_by_vec2(xf_a, manifold.local_point);\n\n\t\t\tlet point_b: B2vec2 = b2_mul_transform_by_vec2(xf_b, manifold.points[0].local_point);\n\n\t\t\tif b2_distance_vec2_squared(point_a, point_b) > B2_EPSILON * B2_EPSILON {\n\n\t\t\t\tthis.normal = point_b - point_a;\n\n\t\t\t\tthis.normal.normalize();\n", "file_path": "src/private/collision/b2_collision.rs", "rank": 77, "score": 107386.0051938579 }, { "content": "// This is called from B2dynamicTree::query when we are gathering pairs.\n\npub fn b2_broad_phase_query_callback(this: &mut B2broadPhasePairs, m_query_proxy_id: i32, proxy_id: i32, moved:bool) -> bool {\n\n\t// A proxy cannot form a pair with itself.\n\n\tif proxy_id == m_query_proxy_id {\n\n\t\treturn true;\n\n\t}\n\n\n\n\t//moved to closure\n\n\t//let moved: bool = this.m_tree.WasMoved(proxy_id);\n\n\tif moved && proxy_id > m_query_proxy_id {\n\n\t\t// Both proxies are moving. Avoid duplicate pairs.\n\n\t\treturn true;\n\n\t}\n\n\n\n\t// Grow the pair buffer as needed.\n\n\tif this.m_pair_count == this.m_pair_capacity {\n\n\t\tthis.m_pair_capacity = this.m_pair_capacity + (this.m_pair_capacity >> 1);\n\n\t\tthis.m_pair_buffer\n\n\t\t\t.resize_with(this.m_pair_capacity as usize, Default::default);\n\n\t}\n\n\n\n\tthis.m_pair_buffer[this.m_pair_count as usize].proxy_id_a = b2_min(proxy_id, m_query_proxy_id);\n\n\tthis.m_pair_buffer[this.m_pair_count as usize].proxy_id_b = b2_max(proxy_id, m_query_proxy_id);\n\n\tthis.m_pair_count += 1;\n\n\n\n\treturn true;\n\n}\n", "file_path": "src/private/collision/b2_broad_phase.rs", "rank": 78, "score": 107252.74706049394 }, { "content": "pub fn b2_polygon_shape_set_as_box_angle(\n\n\tthis: &mut B2polygonShape,\n\n\thx: f32,\n\n\thy: f32,\n\n\tcenter: B2vec2,\n\n\tangle: f32,\n\n) {\n\n\tthis.m_count = 4;\n\n\tthis.m_vertices[0].set(-hx, -hy);\n\n\tthis.m_vertices[1].set(hx, -hy);\n\n\tthis.m_vertices[2].set(hx, hy);\n\n\tthis.m_vertices[3].set(-hx, hy);\n\n\tthis.m_normals[0].set(0.0, -1.0);\n\n\tthis.m_normals[1].set(1.0, 0.0);\n\n\tthis.m_normals[2].set(0.0, 1.0);\n\n\tthis.m_normals[3].set(-1.0, 0.0);\n\n\tthis.m_centroid = center;\n\n\n\n\tlet xf = B2Transform {\n\n\t\tp: center,\n\n\t\tq: B2Rot::new(angle),\n\n\t};\n\n\n\n\t// Transform vertices and normals.\n\n\tfor i in 0..this.m_count {\n\n\t\tthis.m_vertices[i] = b2_mul_transform_by_vec2(xf, this.m_vertices[i]);\n\n\t\tthis.m_normals[i] = b2_mul_rot_by_vec2(xf.q, this.m_normals[i]);\n\n\t}\n\n}\n\n\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 79, "score": 103348.63670009532 }, { "content": "pub fn b2_shape_dyn_trait_clone(this: &B2polygonShape) -> Box<dyn B2shapeDynTrait> {\n\n\treturn Box::new(B2polygonShape::clone(&this));\n\n}\n\n\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 80, "score": 103185.19803496503 }, { "content": "pub fn b2_shape_dyn_trait_clone(this: &B2edgeShape) -> Box<dyn B2shapeDynTrait> {\n\n\treturn Box::new(B2edgeShape::clone(&this));\n\n}\n\n\n", "file_path": "src/private/collision/b2_edge_shape.rs", "rank": 81, "score": 103185.19803496503 }, { "content": "pub fn b2_shape_dyn_trait_clone(this: &B2chainShape) -> Box<dyn B2shapeDynTrait> {\n\n\treturn Box::new(B2chainShape::clone(&this));\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 82, "score": 103185.19803496503 }, { "content": "// p = p1 + t * d\n\n// v = v1 + s * e\n\n// p1 + t * d = v1 + s * e\n\n// s * e - t * d = p1 - v1\n\npub fn b2_shape_dyn_trait_ray_cast(\n\n\tthis: &B2edgeShape,\n\n\toutput: &mut B2rayCastOutput,\n\n\tinput: &B2rayCastInput,\n\n\txf: B2Transform,\n\n\tchild_index: usize,\n\n) -> bool {\n\n\tb2_not_used(child_index);\n\n\n\n\t// Put the ray into the edge's frame of reference.\n\n\tlet p1: B2vec2 = b2_mul_t_rot_by_vec2(xf.q, input.p1 - xf.p);\n\n\tlet p2: B2vec2 = b2_mul_t_rot_by_vec2(xf.q, input.p2 - xf.p);\n\n\tlet d: B2vec2 = p2 - p1;\n\n\n\n\tlet v1: B2vec2 = this.m_vertex1;\n\n\tlet v2: B2vec2 = this.m_vertex2;\n\n\tlet e: B2vec2 = v2 - v1;\n\n\t// Normal points to the right, looking from v1 at v2\n\n\tlet mut normal = B2vec2 { x: e.y, y: -e.x };\n\n\tnormal.normalize();\n", "file_path": "src/private/collision/b2_edge_shape.rs", "rank": 83, "score": 103175.00571223102 }, { "content": "pub fn b2_shape_dyn_trait_compute_aabb(\n\n\tthis: &B2chainShape,\n\n\taabb: &mut B2AABB,\n\n\txf: B2Transform,\n\n\tchild_index: usize,\n\n) {\n\n\tb2_assert(child_index < this.m_vertices.len());\n\n\n\n\tlet i1: usize = child_index;\n\n\tlet mut i2: usize = child_index + 1;\n\n\tif i2 == this.m_vertices.len() {\n\n\t\ti2 = 0;\n\n\t}\n\n\n\n\tlet v1: B2vec2 = b2_mul_transform_by_vec2(xf, this.m_vertices[i1]);\n\n\tlet v2: B2vec2 = b2_mul_transform_by_vec2(xf, this.m_vertices[i2]);\n\n\n\n\tlet lower: B2vec2 = b2_min_vec2(v1, v2);\n\n\tlet upper: B2vec2 = b2_max_vec2(v1, v2);\n\n\n\n\tlet r = B2vec2::new(this.base.m_radius, this.base.m_radius);\n\n\taabb.lower_bound = lower - r;\n\n\taabb.upper_bound = upper + r;\n\n\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 84, "score": 103175.00571223102 }, { "content": "pub fn b2_shape_dyn_trait_compute_aabb(\n\n\tthis: &B2edgeShape,\n\n\taabb: &mut B2AABB,\n\n\txf: B2Transform,\n\n\tchild_index: usize,\n\n) {\n\n\tb2_not_used(child_index);\n\n\n\n\tlet v1: B2vec2 = b2_mul_transform_by_vec2(xf, this.m_vertex1);\n\n\tlet v2: B2vec2 = b2_mul_transform_by_vec2(xf, this.m_vertex2);\n\n\n\n\tlet lower: B2vec2 = b2_min_vec2(v1, v2);\n\n\tlet upper: B2vec2 = b2_max_vec2(v1, v2);\n\n\n\n\tlet r = B2vec2 {\n\n\t\tx: this.base.m_radius,\n\n\t\ty: this.base.m_radius,\n\n\t};\n\n\taabb.lower_bound = lower - r;\n\n\taabb.upper_bound = upper + r;\n\n}\n\n\n", "file_path": "src/private/collision/b2_edge_shape.rs", "rank": 85, "score": 103175.00571223102 }, { "content": "pub fn b2_shape_dyn_trait_ray_cast(\n\n\tthis: &B2chainShape,\n\n\toutput: &mut B2rayCastOutput,\n\n\tinput: &B2rayCastInput,\n\n\txf: B2Transform,\n\n\tchild_index: usize,\n\n) -> bool {\n\n\tb2_assert(child_index < this.m_vertices.len());\n\n\n\n\tlet mut edge_shape = B2edgeShape::default();\n\n\n\n\tlet i1: usize = child_index;\n\n\tlet mut i2: usize = child_index + 1;\n\n\tif i2 == this.m_vertices.len() {\n\n\t\ti2 = 0;\n\n\t}\n\n\n\n\tedge_shape.m_vertex1 = this.m_vertices[i1];\n\n\tedge_shape.m_vertex2 = this.m_vertices[i2];\n\n\n\n\treturn edge_shape.ray_cast(output, &input, xf, 0);\n\n}\n\n\n", "file_path": "src/private/collision/b2_chain_shape.rs", "rank": 86, "score": 103175.00571223102 }, { "content": "pub fn b2_shape_dyn_trait_ray_cast(\n\n\tthis: &B2polygonShape,\n\n\toutput: &mut B2rayCastOutput,\n\n\tinput: &B2rayCastInput,\n\n\txf: B2Transform,\n\n\tchild_index: usize,\n\n) -> bool {\n\n\tb2_not_used(child_index);\n\n\n\n\t// Put the ray into the polygon's frame of reference.\n\n\tlet p1: B2vec2 = b2_mul_t_rot_by_vec2(xf.q, input.p1 - xf.p);\n\n\tlet p2: B2vec2 = b2_mul_t_rot_by_vec2(xf.q, input.p2 - xf.p);\n\n\tlet d: B2vec2 = p2 - p1;\n\n\n\n\tlet (mut lower, mut upper) = (0.032, input.max_fraction);\n\n\n\n\tlet mut index: i32 = -1;\n\n\n\n\tfor i in 0..this.m_count {\n\n\t\t// p = p1 + a * d\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 87, "score": 103175.00571223102 }, { "content": "pub fn b2_shape_dyn_trait_compute_aabb(\n\n\tthis: &B2polygonShape,\n\n\taabb: &mut B2AABB,\n\n\txf: B2Transform,\n\n\tchild_index: usize,\n\n) {\n\n\tb2_not_used(child_index);\n\n\n\n\tlet mut lower: B2vec2 = b2_mul_transform_by_vec2(xf, this.m_vertices[0]);\n\n\tlet mut upper: B2vec2 = lower;\n\n\n\n\tfor i in 1..this.m_count {\n\n\t\tlet v: B2vec2 = b2_mul_transform_by_vec2(xf, this.m_vertices[i]);\n\n\t\tlower = b2_min_vec2(lower, v);\n\n\t\tupper = b2_max_vec2(upper, v);\n\n\t}\n\n\n\n\tlet r = B2vec2::new(this.base.m_radius, this.base.m_radius);\n\n\taabb.lower_bound = lower - r;\n\n\taabb.upper_bound = upper + r;\n\n}\n\n\n", "file_path": "src/private/collision/b2_polygon_shape.rs", "rank": 88, "score": 103175.00571223102 }, { "content": "pub fn b2_fixture_synchronize<T:UserDataType>(\n\n\tthis: &mut B2fixture<T>,\n\n\tbroad_phase: &mut B2broadPhase<FixtureProxyPtr<T>>,\n\n\ttransform1: B2Transform,\n\n\ttransform2: B2Transform,\n\n) {\n\n\tif this.m_proxy_count == 0\n\n\t{\n\n\t\treturn;\n\n\t}\n\n\n\n\tfor i in 0..this.m_proxy_count\n\n\t{\n\n\t\tlet mut proxy = this.m_proxies[i as usize].as_ref().borrow_mut();\n\n\n\n\t\t// Compute an AABB that covers the swept shape (may miss some rotation effect).\n\n\t\tlet mut aabb1 = B2AABB::default();\n\n\t\tlet mut aabb2 = B2AABB::default();\n\n\t\tthis.m_shape.as_ref().unwrap().compute_aabb(&mut aabb1, transform1, proxy.child_index as usize);\n\n\t\tthis.m_shape.as_ref().unwrap().compute_aabb(&mut aabb2, transform2, proxy.child_index as usize);\n\n\t\tproxy.aabb.combine_two(aabb1, aabb2);\n\n\n\n\t\tlet displacement: B2vec2 = aabb2.get_center() - aabb1.get_center();\n\n\n\n\t\tbroad_phase.move_proxy(proxy.proxy_id, proxy.aabb, displacement);\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 89, "score": 102204.2094940332 }, { "content": "pub fn b2_fixture_create<T:UserDataType>(\n\n\tthis: &mut B2fixture<T>,\n\n\tbody: BodyPtr<T>,\n\n\tdef: &B2fixtureDef<T>,\n\n) {\n\n\tthis.m_user_data = def.user_data.clone();\n\n\tthis.m_friction = def.friction;\n\n\tthis.m_restitution = def.restitution;\n\n\n\n\tthis.m_body = Some(Rc::downgrade(&body));\n\n\tthis.m_next = None;\n\n\n\n\tthis.m_filter = def.filter;\n\n\n\n\tthis.m_is_sensor = def.is_sensor;\n\n\n\n\tthis.m_shape = Some(def.shape.as_ref().unwrap().borrow().clone_rc());\n\n\n\n\t// Reserve proxy space\n\n\tlet child_count: i32 = this.m_shape.as_ref().unwrap().get_child_count() as i32;\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 90, "score": 102204.2094940332 }, { "content": "pub fn b2_contact_new<D: UserDataType>(\n\n\tf_a: FixturePtr<D>,\n\n\tindex_a: i32,\n\n\tf_b: FixturePtr<D>,\n\n\tindex_b: i32,\n\n) -> B2contact<D> {\n\n\treturn B2contact {\n\n\t\tm_flags: ContactFlags::E_ENABLED_FLAG,\n\n\n\n\t\tm_fixture_a: f_a.clone(),\n\n\t\tm_fixture_b: f_b.clone(),\n\n\n\n\t\tm_index_a: index_a,\n\n\t\tm_index_b: index_b,\n\n\n\n\t\tm_manifold: B2manifold {\n\n\t\t\tpoint_count: 0,\n\n\t\t\t..Default::default()\n\n\t\t},\n\n\n", "file_path": "src/private/dynamics/b2_contact.rs", "rank": 91, "score": 101351.04432666786 }, { "content": "pub fn b2_contact_create<D: UserDataType>(\n\n\tcontact_manager: &B2contactManager<D>,\n\n\tfixture_a: FixturePtr<D>,\n\n\tindex_a: i32,\n\n\tfixture_b: FixturePtr<D>,\n\n\tindex_b: i32,\n\n) -> ContactPtr<D> {\n\n\n\n\tlet type1: B2ShapeType = fixture_a.borrow().get_type();\n\n\tlet type2: B2ShapeType = fixture_b.borrow().get_type();\n\n\n\n\tlet s_register = &contact_manager.m_registers.s_registers[type1 as usize][type2 as usize];\n\n\n\n\tlet create_fcn = s_register.create_fcn.unwrap();\n\n\n\n\tif s_register.primary {\n\n\t\treturn create_fcn(fixture_a, index_a, fixture_b, index_b);\n\n\t} else {\n\n\t\treturn create_fcn(fixture_b, index_b, fixture_a, index_a);\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_contact.rs", "rank": 92, "score": 101351.04432666786 }, { "content": "// update the contact manifold and touching status.\n\n// Note: do not assume the fixture AABBs are overlapping or are valid.\n\npub fn b2_contact_update<D: UserDataType>(\n\n\tthis_dyn: &mut dyn B2contactDynTrait<D>,\n\n\tlistener: Option<B2contactListenerPtr<D>>\n\n) {\n\n\t{\n\n\t\tlet this = this_dyn.get_base_mut();\n\n\t\t// Re-enable this contact.\n\n\t\tthis.m_flags |= ContactFlags::E_ENABLED_FLAG;\n\n\t}\n\n\n\n\tlet old_manifold: B2manifold;\n\n\n\n\tlet was_touching: bool;\n\n\n\n\tlet sensor_a: bool;\n\n\tlet sensor_b: bool;\n\n\tlet sensor: bool;\n\n\n\n\tlet body_a: BodyPtr<D>;\n\n\tlet body_b: BodyPtr<D>;\n", "file_path": "src/private/dynamics/b2_contact.rs", "rank": 93, "score": 101351.04432666786 }, { "content": "pub fn b2_fixture_create_proxies<T:UserDataType>(\n\n\tthis_ptr: FixturePtr<T>,\n\n\tbroad_phase: &mut B2broadPhase<FixtureProxyPtr<T>>,\n\n\txf: &B2Transform,\n\n) {\n\n\tlet mut this = this_ptr.as_ref().borrow_mut();\n\n\tb2_assert(this.m_proxy_count == 0);\n\n\n\n\t// create proxies in the broad-phase.\n\n\tthis.m_proxy_count = this.m_shape.as_ref().unwrap().get_child_count() as i32;\n\n\n\n\tfor i in 0..this.m_proxy_count\n\n\t{\n\n\t\tlet mut proxy = this.m_proxies[i as usize].as_ref().borrow_mut();\n\n\t\tthis.m_shape.as_ref().unwrap().compute_aabb(&mut proxy.aabb, *xf, i as usize);\n\n\t\tproxy.proxy_id = broad_phase.create_proxy(proxy.aabb, &this.m_proxies[i as usize]);\n\n\t\tproxy.fixture = Some(Rc::downgrade(&this_ptr));\n\n\t\tproxy.child_index = i;\n\n\t}\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_fixture.rs", "rank": 94, "score": 100797.09477184757 }, { "content": "pub fn b2_broad_phase_b2_broad_phase<UserDataType: Default + Clone>() -> B2broadPhase<UserDataType> {\n\n\tlet m_proxy_count: i32 = 0;\n\n\n\n\tlet m_pair_capacity: i32 = 16;\n\n\tlet m_pair_count: i32 = 0;\n\n\tlet mut m_pair_buffer = Vec::<B2pair>::new();\n\n\tm_pair_buffer.resize_with(m_pair_capacity as usize, Default::default);\n\n\n\n\tlet m_move_capacity: i32 = 16;\n\n\tlet m_move_count: i32 = 0;\n\n\tlet mut m_move_buffer = Vec::<i32>::new();\n\n\tm_move_buffer.resize_with(m_move_capacity as usize, Default::default);\n\n\n\n\treturn B2broadPhase::<UserDataType> {\n\n\t\tm_tree: B2dynamicTree::<UserDataType>::new(),\n\n\t\tm_proxy_count,\n\n\t\tm_move_buffer,\n\n\t\tm_move_capacity,\n\n\t\tm_move_count,\n\n\t\tpairs: B2broadPhasePairs {\n\n\t\t\tm_pair_buffer,\n\n\t\t\tm_pair_capacity,\n\n\t\t\tm_pair_count,\n\n\t\t},\n\n\t};\n\n}\n\n\n", "file_path": "src/private/collision/b2_broad_phase.rs", "rank": 95, "score": 98967.95393101533 }, { "content": "pub fn b2_contact_manager_destroy<D: UserDataType>(\n\n\tself_: &mut B2contactManager<D>,\n\n\tc: ContactPtr<D>,\n\n) {\n\n\n\n\t// if self_.m_contact_count!=self_.m_contact_list.len()\n\n\t// {\n\n\t// \tprintln!(\"m_contact_count={0}, m_contact_list.len={1}\",self_.m_contact_count, self_.m_contact_list.len());\n\n\t// }\n\n\t\n\n\t// println!(\"m_contact_count={0}, m_contact_list.len={1}\",self_.m_contact_count, self_.m_contact_list.len());\n\n\n\n\t//assert!(self_.m_contact_count>=1);\n\n\t//assert!(self_.m_contact_count==self_.m_contact_list.len());\n\n\n\n\tlet fixture_a = c.borrow().get_base().get_fixture_a();\n\n\tlet fixture_b = c.borrow().get_base().get_fixture_b();\n\n\tlet body_a = fixture_a.borrow().get_body();\n\n\tlet body_b = fixture_b.borrow().get_body();\n\n\n", "file_path": "src/private/dynamics/b2_contact_manager.rs", "rank": 96, "score": 98586.57629069514 }, { "content": "pub fn b2_contact_manager_add_pair<D: UserDataType>(\n\n\tthis: &mut B2contactManager<D>,\n\n\tproxy_user_data_a: Option<FixtureProxyPtr<D>>,\n\n\tproxy_user_data_b: Option<FixtureProxyPtr<D>>,\n\n) {\n\n\n\n\t\n\n\t//assert!(this.m_contact_count==this.m_contact_list.len());\n\n\n\n\tlet proxy_a = proxy_user_data_a;\n\n\tlet proxy_b = proxy_user_data_b;\n\n\n\n\tlet fixture_a = upgrade(proxy_a.as_ref().unwrap().borrow().fixture.as_ref().unwrap());\n\n\tlet fixture_b = upgrade(proxy_b.as_ref().unwrap().borrow().fixture.as_ref().unwrap());\n\n\n\n\tlet index_a: i32 = proxy_a.as_ref().unwrap().borrow().child_index;\n\n\tlet index_b: i32 = proxy_b.as_ref().unwrap().borrow().child_index;\n\n\n\n\tlet body_a = fixture_a.borrow().get_body();\n\n\tlet body_b = fixture_b.borrow().get_body();\n", "file_path": "src/private/dynamics/b2_contact_manager.rs", "rank": 97, "score": 97276.39059444652 }, { "content": "pub fn clone(this: &B2circleShape) -> Box<dyn B2shapeDynTrait> {\n\n\treturn Box::new(B2circleShape::clone(&this));\n\n}\n\n\n", "file_path": "src/private/collision/b2_circle_shape.rs", "rank": 98, "score": 96406.12126290386 }, { "content": "/// \"Next Largest Power of 2\n\n/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm\n\n/// that recursively \"folds\" the upper bits into the lower bits. This process yields a bit vector with\n\n/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next\n\n/// largest power of 2. For a 32-bit value:\"\n\npub fn b2_next_power_of_two(v: u32) -> u32 {\n\n let mut x: u32 = v;\n\n x |= x >> 1;\n\n x |= x >> 2;\n\n x |= x >> 4;\n\n x |= x >> 8;\n\n x |= x >> 16;\n\n return x + 1;\n\n}\n\n\n", "file_path": "src/b2_math.rs", "rank": 99, "score": 95566.24449048642 } ]
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 {\n\n use super::*;\n\n\n\n #[test]\n\n fn get_statements() {\n\n let tree = parse_sql(\"\n\n CREATE INDEX guess_user_id ON guesses(user_id);\n\n CREATE INDEX guess_round_id ON guesses(round_id);\n\n CREATE INDEX round_game_id ON rounds(game_id);\n\n \").unwrap();\n\n let statements = tree.statements();\n\n\n", "file_path": "src/sql.rs", "rank": 3, "score": 106487.97678544893 }, { "content": "fn text_provider(input: &str) -> impl TextProvider<'_> {\n\n |node: Node<'_>| std::iter::once(input[node.byte_range()].as_bytes())\n\n}\n\n\n\npub struct ParsedSql<'a> {\n\n pub source: &'a str,\n\n pub tree: Tree,\n\n}\n\n\n\nimpl<'a> TextProvider<'a> for ParsedSql<'a> {\n\n type I = std::iter::Once<&'a [u8]>;\n\n\n\n fn text(&mut self, node: Node<'_>) -> Self::I {\n\n std::iter::once(self.source[node.byte_range()].as_bytes())\n\n }\n\n}\n\n\n\nimpl<'a> ParsedSql<'a> {\n\n pub fn statements(&self) -> Vec<Node<'_>> {\n\n let statements_query = tree_sitter_query!(\"(sql_stmt_list (sql_stmt) @stmt)\");\n", "file_path": "src/sql.rs", "rank": 5, "score": 93841.29175772588 }, { "content": "fn starts_with(item: &str, input: &str) -> bool {\n\n input.len() <= item.len() && item[..input.len()].eq_ignore_ascii_case(input)\n\n}\n\n\n", "file_path": "src/completions.rs", "rank": 6, "score": 83247.3524817086 }, { "content": "/// Turn highlights into ANSI sequences. Accepts highlights in any language, but the name order\n\n/// needs to match.\n\npub fn to_ansi(\n\n source: &[u8],\n\n highlights: impl Iterator<Item = Result<HighlightEvent, HighlightError>>,\n\n) -> anyhow::Result<String> {\n\n let mut buf = Buffer::ansi();\n\n\n\n let mut keyword = ColorSpec::new();\n\n keyword.set_fg(Some(Color::Blue)).set_bold(true);\n\n let mut number = ColorSpec::new();\n\n number.set_fg(Some(Color::Yellow)).set_bold(true);\n\n let mut string = ColorSpec::new();\n\n string.set_fg(Some(Color::Magenta)).set_bold(true);\n\n let mut comment = ColorSpec::new();\n\n comment.set_fg(Some(Color::Green)).set_bold(true);\n\n\n\n for event in highlights {\n\n match event? {\n\n HighlightEvent::HighlightStart(Highlight(style)) => match style {\n\n 0 => buf.set_color(&keyword)?,\n\n 1 => buf.set_color(&number)?,\n", "file_path": "src/highlight.rs", "rank": 7, "score": 80940.81726365777 }, { "content": "fn text_provider(input: &str) -> impl TextProvider<'_> {\n\n |node: Node<'_>| std::iter::once(input[node.byte_range()].as_bytes())\n\n}\n\n\n\nconst INITIAL_KEYWORDS: [&str; 15] = [\n\n \"SELECT\", \"DELETE\", \"CREATE\", \"DROP\", \"ATTACH\", \"DETACH\", \"EXPLAIN\", \"PRAGMA\", \"WITH\",\n\n \"UPDATE\", \"ALTER\", \"BEGIN\", \"END\", \"COMMIT\", \"ROLLBACK\",\n\n];\n\n\n", "file_path": "src/completions.rs", "rank": 8, "score": 79602.3981940207 }, { "content": "fn match_case<'i>(item: &'i str, input: &str) -> Cow<'i, str> {\n\n if input.chars().all(|c| c.is_ascii_lowercase()) {\n\n item.to_ascii_lowercase().into()\n\n } else {\n\n item.into()\n\n }\n\n}\n\n\n", "file_path": "src/completions.rs", "rank": 9, "score": 70887.12247661188 }, { "content": "#[derive(Debug)]\n\nstruct QueryNames<'a> {\n\n ctes: HashMap<&'a str, Vec<String>>,\n\n table_aliases: HashMap<&'a str, &'a str>,\n\n}\n\n\n\npub struct Completions {\n\n connection: Rc<Connection>,\n\n}\n\n\n\nimpl Completions {\n\n pub fn new(connection: Rc<Connection>) -> Self {\n\n Self { connection }\n\n }\n\n\n\n /// Maybe cache this later\n\n fn get_table_names(&self) -> Vec<String> {\n\n let mut stmt = self\n\n .connection\n\n .prepare_cached(\"SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name ASC\")\n\n .unwrap();\n", "file_path": "src/completions.rs", "rank": 10, "score": 51659.56443509806 }, { "content": "struct App {\n\n rl: Editor<EditorHelper>,\n\n conn: Rc<Connection>,\n\n output_target: OutputTarget,\n\n output_mode: OutputMode,\n\n}\n\n\n\nimpl App {\n\n fn run(&mut self) -> anyhow::Result<()> {\n\n let prompt = format!(\n\n \"{}> \",\n\n self.rl.helper().unwrap().name().unwrap_or(\":memory:\")\n\n );\n\n loop {\n\n let readline = self.rl.readline(&prompt);\n\n match readline {\n\n Ok(line) => {\n\n self.rl.add_history_entry(line.as_str());\n\n if let Err(err) = self.execute(line.as_str()) {\n\n println!(\"Error: {:?}\", err);\n", "file_path": "src/main.rs", "rank": 11, "score": 35245.28923832785 }, { "content": "#[derive(Parser)]\n\nstruct Opts {\n\n /// Filename of the database to open. If omitted, sqc opens a temporary in-memory database.\n\n filename: Option<PathBuf>,\n\n /// Queries to execute on the database. If omitted, sqc enters interactive mode.\n\n queries: Vec<String>,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 12, "score": 35245.28923832785 }, { "content": "fn main() -> anyhow::Result<()> {\n\n let opts = Opts::parse();\n\n let dirs = ProjectDirs::from(\"\", \"sqc\", \"sqc\");\n\n let history_path = dirs\n\n .as_ref()\n\n .map(|dirs| dirs.data_dir().join(\"history.txt\"));\n\n\n\n if let Some(dirs) = &dirs {\n\n let _ = std::fs::create_dir_all(dirs.data_dir());\n\n }\n\n\n\n let conn = Rc::new(match &opts.filename {\n\n Some(filename) => Connection::open(&filename)?,\n\n None => Connection::open_in_memory()?,\n\n });\n\n\n\n rusqlite::vtab::csvtab::load_module(&conn)?;\n\n\n\n let completions = Completions::new(Rc::clone(&conn));\n\n\n", "file_path": "src/main.rs", "rank": 13, "score": 26991.966780993702 }, { "content": " }\n\n\n\n pub fn highlight(&self, sql: &str) -> anyhow::Result<String> {\n\n let mut highlighter = self.highlighter.borrow_mut();\n\n let highlights = highlighter.highlight(&self.sql_config, sql.as_bytes(), None, |_| None)?;\n\n to_ansi(sql.as_bytes(), highlights)\n\n }\n\n}\n\n\n\nimpl Default for SqlHighlighter {\n\n fn default() -> Self {\n\n Self::new()\n\n }\n\n}\n\n\n\n/// Turn highlights into ANSI sequences. Accepts highlights in any language, but the name order\n\n/// needs to match.\n", "file_path": "src/highlight.rs", "rank": 14, "score": 21760.398853960025 }, { "content": " highlighter: RefCell<Highlighter>,\n\n sql_config: HighlightConfiguration,\n\n}\n\n\n\nimpl SqlHighlighter {\n\n pub fn new() -> Self {\n\n let highlighter = Highlighter::new();\n\n let mut sql_config = HighlightConfiguration::new(\n\n tree_sitter_sqlite::language(),\n\n include_str!(\"../queries/highlights.scm\"),\n\n \"\",\n\n \"\",\n\n )\n\n .unwrap();\n\n sql_config.configure(&QUERY_NAMES);\n\n\n\n Self {\n\n highlighter: RefCell::new(highlighter),\n\n sql_config,\n\n }\n", "file_path": "src/highlight.rs", "rank": 15, "score": 21758.3867735337 }, { "content": "//! Format SQL strings with highlighting.\n\n\n\nuse std::cell::RefCell;\n\nuse std::io::Write;\n\nuse termcolor::{Buffer, Color, ColorSpec, WriteColor};\n\nuse tree_sitter_highlight::{\n\n Error as HighlightError, Highlight, HighlightConfiguration, HighlightEvent, Highlighter,\n\n};\n\n\n\nconst QUERY_NAMES: [&str; 7] = [\n\n \"keyword\",\n\n \"number\",\n\n \"string\",\n\n \"constant\",\n\n \"comment\",\n\n \"operator\",\n\n \"punctuation\",\n\n];\n\n\n\npub struct SqlHighlighter {\n", "file_path": "src/highlight.rs", "rank": 16, "score": 21757.940656501338 }, { "content": " 2 => buf.set_color(&string)?,\n\n 4 => buf.set_color(&comment)?,\n\n _ => (),\n\n },\n\n HighlightEvent::Source { start, end } => buf.write_all(&source[start..end])?,\n\n HighlightEvent::HighlightEnd => buf.reset()?,\n\n }\n\n }\n\n\n\n Ok(String::from_utf8(buf.into_inner())?)\n\n}\n", "file_path": "src/highlight.rs", "rank": 17, "score": 21749.352727869424 }, { "content": " let mut cursor = QueryCursor::new();\n\n let mut nodes = vec![];\n\n for stmt in cursor.matches(\n\n statements_query,\n\n self.tree.root_node(),\n\n text_provider(self.source),\n\n ) {\n\n nodes.push(stmt.captures[0].node);\n\n }\n\n nodes\n\n }\n\n}\n\n\n", "file_path": "src/sql.rs", "rank": 18, "score": 21748.49501725316 }, { "content": " assert_eq!(\n\n statements.into_iter().map(|node| &tree.source[node.byte_range()]).collect::<Vec<_>>(),\n\n vec![\n\n \"CREATE INDEX guess_user_id ON guesses(user_id)\",\n\n \"CREATE INDEX guess_round_id ON guesses(round_id)\",\n\n \"CREATE INDEX round_game_id ON rounds(game_id)\",\n\n ],\n\n );\n\n }\n\n}\n", "file_path": "src/sql.rs", "rank": 19, "score": 21747.44180058611 }, { "content": "use tree_sitter::{Node, Parser, QueryCursor, TextProvider, Tree};\n\n\n", "file_path": "src/sql.rs", "rank": 20, "score": 21745.298104236586 }, { "content": " highlighter: Default::default(),\n\n }\n\n }\n\n\n\n pub fn name(&self) -> Option<&str> {\n\n self.name.as_deref()\n\n }\n\n}\n\n\n\nimpl Highlighter for EditorHelper {\n\n fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {\n\n match self.highlighter.highlight(line) {\n\n Ok(highlighted) => highlighted.into(),\n\n Err(_) => line.into(),\n\n }\n\n }\n\n\n\n fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {\n\n use std::io::Write;\n\n use termcolor::{Buffer, Color, ColorSpec, WriteColor};\n", "file_path": "src/input.rs", "rank": 32, "score": 18.97638528201866 }, { "content": " let mut rows_stmt = self.conn.prepare(&format!(\"SELECT * FROM {}\", &name))?;\n\n\n\n let mut output_rows =\n\n SqlOutput::new(&rows_stmt, highlighter, &mut output).with_table_name(name);\n\n\n\n let mut rows_query = rows_stmt.query([])?;\n\n while let Some(row) = rows_query.next()? {\n\n output_rows.add_row(row)?;\n\n }\n\n output_rows.finish()?;\n\n\n\n opt_row = tables_query.next()?;\n\n }\n\n\n\n writeln!(&mut output, \"{}\", highlighter.highlight(\"COMMIT;\")?)?;\n\n Ok(())\n\n }\n\n\n\n /// Execute an UPDATE, DELETE or INSERT query.\n\n fn execute_update_query(&mut self, sql: &str) -> anyhow::Result<()> {\n", "file_path": "src/main.rs", "rank": 33, "score": 16.43752009069478 }, { "content": " } else {\n\n anyhow::bail!(\"table {} does not exist\", table_name);\n\n };\n\n\n\n let value_ref = row.get_ref(0)?;\n\n let sql = if let ValueRef::Text(text) = value_ref {\n\n std::str::from_utf8(text)?\n\n } else {\n\n anyhow::bail!(\"sqlite_schema table does not contain `text` for some reason?\");\n\n };\n\n\n\n let highlighter = &self.rl.helper().unwrap().highlighter;\n\n let formatted = sqlformat::format(sql, &Default::default(), Default::default());\n\n\n\n let mut output = self.output_target.start();\n\n let highlighted = if output.supports_color() {\n\n highlighter.highlight(&formatted)?\n\n } else {\n\n formatted\n\n };\n", "file_path": "src/main.rs", "rank": 34, "score": 15.419933903029438 }, { "content": " writeln!(&mut output, \"{}\", highlighted)?;\n\n\n\n Ok(())\n\n }\n\n\n\n fn execute_dump(&mut self, filter: Option<&str>) -> anyhow::Result<()> {\n\n let mut output = self.output_target.start();\n\n\n\n let mut tables_stmt = self.conn.prepare_cached(\n\n \"SELECT name, sql FROM sqlite_schema WHERE type = 'table' AND tbl_name LIKE ?\",\n\n )?;\n\n let mut tables_query = tables_stmt.query([filter\n\n .map(|name| format!(\"%{}%\", name))\n\n .unwrap_or_else(|| \"%\".to_string())])?;\n\n let mut opt_row = if let Some(row) = tables_query.next()? {\n\n Some(row)\n\n } else {\n\n anyhow::bail!(\"no results for {}\", filter.unwrap_or(\"\"));\n\n };\n\n\n", "file_path": "src/main.rs", "rank": 35, "score": 14.937583175357178 }, { "content": " self.output_mode = mode\n\n .parse()\n\n .map_err(|_| anyhow::Error::msg(\"unknown mode\"))?;\n\n Ok(())\n\n }\n\n [\".output\"] => {\n\n self.output_target =\n\n OutputTarget::Stdout(StandardStream::stdout(ColorChoice::Auto));\n\n Ok(())\n\n }\n\n [\".output\", filename] => {\n\n self.output_target = OutputTarget::File(std::fs::File::create(filename)?);\n\n Ok(())\n\n }\n\n [\".schema\"] => anyhow::bail!(\"provide a table name\"),\n\n [\".schema\", table_name] => self.execute_schema(table_name),\n\n [\".parse\"] => anyhow::bail!(\"provide a query to parse\"),\n\n [\".parse\", sql] => {\n\n let tree = crate::sql::parse_sql(sql)?;\n\n writeln!(\n", "file_path": "src/main.rs", "rank": 36, "score": 13.986312206215601 }, { "content": "\n\n let mut stmt = self\n\n .conn\n\n .prepare(\"SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name ASC\")?;\n\n let tables = stmt.query_map([], |row| row.get::<_, String>(0))?;\n\n for table in tables {\n\n writeln!(&mut output, \"{}\", table?)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n /// Execute a .schema command.\n\n fn execute_schema(&mut self, table_name: &str) -> anyhow::Result<()> {\n\n let mut stmt = self\n\n .conn\n\n .prepare(\"SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?\")?;\n\n let mut query = stmt.query([table_name])?;\n\n let row = if let Some(row) = query.next()? {\n\n row\n", "file_path": "src/main.rs", "rank": 37, "score": 13.850956564411433 }, { "content": "use crate::completions::Completions;\n\nuse crate::highlight::SqlHighlighter;\n\nuse rustyline::completion::Completer;\n\nuse rustyline::highlight::Highlighter;\n\nuse rustyline::hint::Hinter;\n\nuse rustyline::validate::Validator;\n\nuse rustyline::{Context, Helper};\n\nuse std::borrow::Cow;\n\n\n\npub struct EditorHelper {\n\n name: Option<String>,\n\n completions: Completions,\n\n pub highlighter: SqlHighlighter,\n\n}\n\n\n\nimpl EditorHelper {\n\n pub fn new(name: Option<String>, completions: Completions) -> Self {\n\n Self {\n\n name,\n\n completions,\n", "file_path": "src/input.rs", "rank": 38, "score": 13.806966933733746 }, { "content": " Ok(())\n\n }\n\n\n\n /// Execute a SELECT query.\n\n fn execute_select_query(&mut self, sql: &str) -> anyhow::Result<()> {\n\n let mut stmt = self.conn.prepare(sql)?;\n\n if stmt.parameter_count() > 0 {\n\n anyhow::bail!(\"cannot run queries that require bind parameters\");\n\n }\n\n\n\n let highlighter = &self.rl.helper().unwrap().highlighter;\n\n let mut output = self.output_target.start();\n\n let mut output_rows = self\n\n .output_mode\n\n .output_rows(&stmt, highlighter, &mut output);\n\n\n\n let mut query = stmt.query([])?;\n\n while let Some(row) = query.next()? {\n\n output_rows.add_row(row)?;\n\n }\n\n output_rows.finish()?;\n\n\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 39, "score": 13.538483939296864 }, { "content": " }\n\n 1 => {\n\n if let [table, alias] = m.captures {\n\n table_aliases.insert(\n\n &tree.source[alias.node.byte_range()],\n\n &tree.source[table.node.byte_range()],\n\n );\n\n }\n\n }\n\n _ => unreachable!(),\n\n }\n\n }\n\n QueryNames {\n\n ctes,\n\n table_aliases,\n\n }\n\n }\n\n\n\n pub fn get_completions(&self, sql: &str, pos: usize) -> Vec<(usize, String)> {\n\n let tree = parse_sql(sql).unwrap();\n", "file_path": "src/completions.rs", "rank": 40, "score": 12.783789926501228 }, { "content": " let highlighter = &self.rl.helper().unwrap().highlighter;\n\n writeln!(\n\n &mut output,\n\n \"{}\",\n\n highlighter.highlight(\"PRAGMA foreign_keys=OFF;\")?\n\n )?;\n\n writeln!(\n\n &mut output,\n\n \"{}\",\n\n highlighter.highlight(\"BEGIN TRANSACTION;\")?\n\n )?;\n\n\n\n while let Some(row) = opt_row {\n\n let name: String = row.get_unwrap(0);\n\n let sql: String = row.get_unwrap(1);\n\n\n\n let mut formatted = sqlformat::format(&sql, &Default::default(), Default::default());\n\n formatted.push(';');\n\n writeln!(&mut output, \"{}\", highlighter.highlight(&formatted)?)?;\n\n\n", "file_path": "src/main.rs", "rank": 41, "score": 12.170765450197434 }, { "content": " }\n\n }\n\n Err(ReadlineError::Interrupted) => continue,\n\n Err(ReadlineError::Eof) => break,\n\n Err(err) => {\n\n println!(\"Error: {:?}\", err);\n\n break;\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n fn execute(&mut self, request: &str) -> anyhow::Result<()> {\n\n if request.starts_with('.') {\n\n let parts = request.splitn(2, ' ').collect::<Vec<_>>();\n\n match &parts[..] {\n\n [\".tables\"] => self.execute_tables(),\n\n [\".mode\"] => anyhow::bail!(\"provide an output mode\"),\n\n [\".mode\", mode] => {\n", "file_path": "src/main.rs", "rank": 42, "score": 11.007534789061108 }, { "content": "use clap::Parser;\n\nuse directories::ProjectDirs;\n\nuse rusqlite::types::ValueRef;\n\nuse rusqlite::Connection;\n\nuse rustyline::error::ReadlineError;\n\nuse rustyline::Editor;\n\nuse std::path::PathBuf;\n\nuse std::rc::Rc;\n\nuse termcolor::{ColorChoice, StandardStream};\n\n\n\n#[macro_use]\n\nmod macros;\n\nmod completions;\n\nmod highlight;\n\nmod input;\n\nmod output;\n\nmod sql;\n\n\n\nuse completions::Completions;\n\nuse input::EditorHelper;\n\nuse output::{OutputMode, OutputRows, OutputTarget, SqlOutput};\n\n\n", "file_path": "src/main.rs", "rank": 43, "score": 11.006229406877033 }, { "content": "\n\n let mut grey = ColorSpec::new();\n\n grey.set_fg(Some(Color::Ansi256(8))).set_bold(true);\n\n let mut buf = Buffer::ansi();\n\n let _ = buf.set_color(&grey);\n\n let _ = buf.write_all(hint.as_bytes());\n\n let _ = buf.reset();\n\n\n\n String::from_utf8(buf.into_inner())\n\n .map(Cow::Owned)\n\n .unwrap_or(Cow::Borrowed(hint))\n\n }\n\n\n\n fn highlight_char(&self, line: &str, _pos: usize) -> bool {\n\n !line.starts_with('.')\n\n }\n\n}\n\n\n\nimpl Completer for EditorHelper {\n\n type Candidate = String;\n", "file_path": "src/input.rs", "rank": 44, "score": 10.935049148413215 }, { "content": " let tables = stmt\n\n .query_map([], |row| row.get(0))\n\n .unwrap()\n\n .collect::<Result<Vec<String>, _>>();\n\n\n\n tables.unwrap()\n\n }\n\n\n\n fn parse_names<'a>(&self, tree: &ParsedSql<'a>) -> QueryNames<'a> {\n\n let query = tree_sitter_query!(\"\n\n (with_clause (WITH) (common_table_expression (identifier) @cte-name (AS) (select_stmt) @cte)) @whole-cte\n\n (table_or_subquery (identifier) @table (identifier) @table-alias)\n\n \");\n\n let mut cursor = QueryCursor::new();\n\n let mut ctes = HashMap::new();\n\n let mut table_aliases = HashMap::new();\n\n let mut cte_prefix = String::new();\n\n for m in cursor.matches(query, tree.tree.root_node(), text_provider(tree.source)) {\n\n match m.pattern_index {\n\n 0 => {\n", "file_path": "src/completions.rs", "rank": 45, "score": 9.726698724585102 }, { "content": " // Handle the start of a statement.\n\n match (parent, prev) {\n\n (Some(parent), None) => match (node.kind(), parent.kind()) {\n\n (\"ERROR\", \"sql_stmt_list\") => {\n\n return INITIAL_KEYWORDS\n\n .into_iter()\n\n .filter(|item| starts_with(item, content))\n\n .map(|item| {\n\n (node.start_byte(), format!(\"{} \", match_case(item, content)))\n\n })\n\n .collect();\n\n }\n\n (\"identifier\", \"table_or_subquery\") => {\n\n let cte_names = names.ctes.keys().map(ToString::to_string);\n\n let alias_names = names.table_aliases.keys().map(ToString::to_string);\n\n return self\n\n .get_table_names()\n\n .into_iter()\n\n .chain(cte_names)\n\n .chain(alias_names)\n", "file_path": "src/completions.rs", "rank": 46, "score": 9.359881791771054 }, { "content": "\n\n fn complete(\n\n &self,\n\n line: &str,\n\n pos: usize,\n\n _ctx: &Context<'_>,\n\n ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {\n\n let results = self.completions.get_completions(line, pos);\n\n if let Some(first) = results.get(0) {\n\n Ok((first.0, results.into_iter().map(|item| item.1).collect()))\n\n } else {\n\n Ok((0, vec![]))\n\n }\n\n }\n\n}\n\n\n\nimpl Hinter for EditorHelper {\n\n type Hint = String;\n\n\n\n fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<Self::Hint> {\n", "file_path": "src/input.rs", "rank": 47, "score": 9.108342508079552 }, { "content": " let mut column_names = vec![];\n\n let whole = &tree.source[m.captures[0].node.byte_range()];\n\n let expr = &tree.source[m.captures[2].node.byte_range()];\n\n match self.connection.prepare(&format!(\"{} {}\", cte_prefix, expr)) {\n\n Ok(stmt) => {\n\n column_names = stmt\n\n .column_names()\n\n .into_iter()\n\n .map(ToOwned::to_owned)\n\n .collect::<Vec<_>>();\n\n }\n\n Err(_) => {\n\n // Ignore\n\n }\n\n }\n\n ctes.insert(&tree.source[m.captures[1].node.byte_range()], column_names);\n\n if !cte_prefix.is_empty() {\n\n cte_prefix += \", \";\n\n }\n\n cte_prefix += whole;\n", "file_path": "src/completions.rs", "rank": 48, "score": 8.647501765964991 }, { "content": " \"create_index_stmt\"\n\n | \"create_table_stmt\"\n\n | \"create_trigger_stmt\"\n\n | \"create_view_stmt\"\n\n | \"create_virtual_table_stmt\"\n\n | \"drop_index_stmt\"\n\n | \"drop_table_stmt\"\n\n | \"drop_trigger_stmt\"\n\n | \"drop_view_stmt\",\n\n ) => self.execute_silent_query(sql)?,\n\n Some(_) | None => self.execute_select_query(sql)?,\n\n }\n\n }\n\n Ok(())\n\n }\n\n }\n\n\n\n /// Execute a .tables command.\n\n fn execute_tables(&mut self) -> anyhow::Result<()> {\n\n let mut output = self.output_target.start();\n", "file_path": "src/main.rs", "rank": 49, "score": 8.537552332976896 }, { "content": " self.output_target.start(),\n\n \"{}\",\n\n tree.tree.root_node().to_sexp()\n\n )?;\n\n Ok(())\n\n }\n\n [\".dump\"] => self.execute_dump(None),\n\n [\".dump\", filter] => self.execute_dump(Some(filter)),\n\n _ => anyhow::bail!(\"unknown dot command\"),\n\n }\n\n } else {\n\n let tree = crate::sql::parse_sql(request)?;\n\n for stmt_node in tree.statements() {\n\n let sql = &request[stmt_node.byte_range()];\n\n let kind = stmt_node.child(0).map(|node| node.kind());\n\n match kind {\n\n Some(\"update_stmt\" | \"delete_stmt\" | \"insert_stmt\") => {\n\n self.execute_update_query(sql)?\n\n }\n\n Some(\n", "file_path": "src/main.rs", "rank": 50, "score": 7.6128495573021935 }, { "content": " let mut rl = Editor::new();\n\n rl.set_helper(Some(EditorHelper::new(\n\n opts.filename\n\n .and_then(|f| f.file_name().map(|os| os.to_string_lossy().to_string())),\n\n completions,\n\n )));\n\n\n\n let mut app = App {\n\n rl,\n\n conn,\n\n output_target: OutputTarget::Stdout(StandardStream::stdout(ColorChoice::Auto)),\n\n output_mode: OutputMode::Table,\n\n };\n\n\n\n if opts.queries.is_empty() {\n\n if let Some(path) = &history_path {\n\n let _ = app.rl.load_history(path);\n\n } else {\n\n eprintln!(\"Warning: could not load shell history: home directory not found\");\n\n }\n", "file_path": "src/main.rs", "rank": 51, "score": 6.777849524455368 }, { "content": " let mut stmt = self.conn.prepare(sql)?;\n\n if stmt.parameter_count() > 0 {\n\n anyhow::bail!(\"cannot run queries that require bind parameters\");\n\n }\n\n\n\n let changes = stmt.execute([])?;\n\n println!(\"{} changes\", changes);\n\n\n\n Ok(())\n\n }\n\n\n\n /// Execute a query that does not return anything.\n\n fn execute_silent_query(&mut self, sql: &str) -> anyhow::Result<()> {\n\n let mut stmt = self.conn.prepare(sql)?;\n\n if stmt.parameter_count() > 0 {\n\n anyhow::bail!(\"cannot run queries that require bind parameters\");\n\n }\n\n\n\n let _ = stmt.execute([])?;\n\n\n", "file_path": "src/main.rs", "rank": 52, "score": 6.163903451455177 }, { "content": "use crate::sql::{parse_sql, ParsedSql};\n\nuse rusqlite::Connection;\n\nuse std::borrow::Cow;\n\nuse std::collections::HashMap;\n\nuse std::rc::Rc;\n\nuse tree_sitter::{Node, QueryCursor, TextProvider};\n\n\n", "file_path": "src/completions.rs", "rank": 53, "score": 5.2539951122542154 }, { "content": " let names = self.parse_names(&tree);\n\n let root = tree.tree.root_node();\n\n let max_lookbehind = 5.min(pos);\n\n let relevant_node = (0..max_lookbehind).find_map(|offset| {\n\n if let Some(node) = root.descendant_for_byte_range(pos - offset, pos - offset) {\n\n if node.kind() == \"sql_stmt_list\" {\n\n None\n\n } else {\n\n Some(node)\n\n }\n\n } else {\n\n None\n\n }\n\n });\n\n\n\n if let Some(node) = relevant_node {\n\n let parent = node.parent();\n\n let prev = node.prev_sibling();\n\n let content = &sql[node.byte_range()];\n\n\n", "file_path": "src/completions.rs", "rank": 54, "score": 5.077987948930657 }, { "content": "// Based on https://docs.rs/once_cell/1.8.0/once_cell/#lazily-compiled-regex\n\nmacro_rules! tree_sitter_query {\n\n ($query:literal $(,)?) => {{\n\n use once_cell::sync::OnceCell;\n\n use tree_sitter::Query;\n\n\n\n static QUERY: OnceCell<Query> = OnceCell::new();\n\n QUERY.get_or_init(|| Query::new(tree_sitter_sqlite::language(), $query).unwrap())\n\n }};\n\n}\n", "file_path": "src/macros.rs", "rank": 55, "score": 5.042998481697797 }, { "content": "# sqc\n\nA SQLite CLI with syntax highlighting and pretty tables by default.\n\n\n\nThis is not a full replacement for the official SQLite CLI.\n\nI use it for just querying and updating databases, and use the official one if I need to do something more advanced.\n\n\n\n## License\n\nLicensed under either of Apache License, Version 2.0 or MIT license at your option.\n", "file_path": "README.md", "rank": 56, "score": 4.970977261785086 }, { "content": " self.completions\n\n .get_completions(line, pos)\n\n .into_iter()\n\n .next()\n\n .map(|mut item| item.1.split_off(pos - item.0))\n\n }\n\n}\n\n\n\nimpl Validator for EditorHelper {}\n\n\n\nimpl Helper for EditorHelper {}\n", "file_path": "src/input.rs", "rank": 57, "score": 3.9433452453473423 }, { "content": " .filter(|item| starts_with(item, content))\n\n .map(|item| (node.start_byte(), format!(\"{} \", item)))\n\n .collect();\n\n }\n\n (_left, _right) => {\n\n // Nice for debugging\n\n // return vec![(node.end_byte(), format!(\" -> {} {}\", left, right))]\n\n }\n\n },\n\n (Some(parent), Some(prev)) => match (node.kind(), parent.kind(), prev.kind()) {\n\n (_left, _mid, _right) => {\n\n // return vec![(node.end_byte(), format!(\" -> {} {} {}\", left, mid, right))]\n\n }\n\n },\n\n (None, Some(_prev)) => (),\n\n (None, None) => (),\n\n }\n\n }\n\n\n\n Default::default()\n\n }\n\n}\n", "file_path": "src/completions.rs", "rank": 58, "score": 3.5004119461268277 }, { "content": " app.run()?;\n\n if let Some(path) = &history_path {\n\n let _ = app.rl.save_history(path);\n\n }\n\n } else {\n\n for query in opts.queries {\n\n app.execute(&query)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 59, "score": 1.8653399464549982 } ]
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.67311653402 }, { "content": "pub fn matching_pair_direction(c: char) -> Option<bool> {\n\n Some(match c {\n\n '{' => true,\n\n '}' => false,\n\n '(' => true,\n\n ')' => false,\n\n '[' => true,\n\n ']' => false,\n\n _ => return None,\n\n })\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 1, "score": 226925.5000011528 }, { "content": "/// Attempts to detect the indentation style used in a document.\n\n///\n\n/// Returns the indentation style if the auto-detect confidence is\n\n/// reasonably high, otherwise returns `None`.\n\npub fn auto_detect_indent_style(document_text: &Rope) -> Option<IndentStyle> {\n\n // Build a histogram of the indentation *increases* between\n\n // subsequent lines, ignoring lines that are all whitespace.\n\n //\n\n // Index 0 is for tabs, the rest are 1-8 spaces.\n\n let histogram: [usize; 9] = {\n\n let mut histogram = [0; 9];\n\n let mut prev_line_is_tabs = false;\n\n let mut prev_line_leading_count = 0usize;\n\n\n\n // Loop through the lines, checking for and recording indentation\n\n // increases as we go.\n\n let offset = document_text.offset_of_line(\n\n document_text.line_of_offset(document_text.len()).min(1000),\n\n );\n\n 'outer: for line in document_text.lines(..offset) {\n\n let mut c_iter = line.chars();\n\n\n\n // Is first character a tab or space?\n\n let is_tabs = match c_iter.next() {\n", "file_path": "lapce-core/src/indent.rs", "rank": 2, "score": 220904.42412382338 }, { "content": "fn language_id_from_path(path: &Path) -> Option<&str> {\n\n Some(match path.extension()?.to_str()? {\n\n \"rs\" => \"rust\",\n\n \"go\" => \"go\",\n\n _ => return None,\n\n })\n\n}\n\n\n", "file_path": "lapce-proxy/src/buffer.rs", "rank": 3, "score": 204761.49093139256 }, { "content": "pub fn has_unmatched_pair(line: &str) -> bool {\n\n let mut count = HashMap::new();\n\n let mut pair_first = HashMap::new();\n\n for c in line.chars().rev() {\n\n if let Some(left) = matching_pair_direction(c) {\n\n let key = if left { c } else { matching_char(c).unwrap() };\n\n let pair_count = *count.get(&key).unwrap_or(&0i32);\n\n pair_first.entry(key).or_insert(left);\n\n if left {\n\n count.insert(key, pair_count - 1);\n\n } else {\n\n count.insert(key, pair_count + 1);\n\n }\n\n }\n\n }\n\n for (_, pair_count) in count.iter() {\n\n if *pair_count < 0 {\n\n return true;\n\n }\n\n }\n\n for (_, left) in pair_first.iter() {\n\n if *left {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 4, "score": 201168.44038827735 }, { "content": "pub fn get_change_for_sync_kind(\n\n sync_kind: TextDocumentSyncKind,\n\n buffer: &Buffer,\n\n content_change: &TextDocumentContentChangeEvent,\n\n) -> Option<Vec<TextDocumentContentChangeEvent>> {\n\n match sync_kind {\n\n TextDocumentSyncKind::None => None,\n\n TextDocumentSyncKind::Full => {\n\n let text_document_content_change_event =\n\n TextDocumentContentChangeEvent {\n\n range: None,\n\n range_length: None,\n\n text: buffer.get_document(),\n\n };\n\n Some(vec![text_document_content_change_event])\n\n }\n\n TextDocumentSyncKind::Incremental => Some(vec![content_change.clone()]),\n\n }\n\n}\n\n\n", "file_path": "lapce-proxy/src/lsp.rs", "rank": 5, "score": 193088.95864690008 }, { "content": "#[allow(dead_code)]\n\nfn language_id_from_path(path: &str) -> Option<&str> {\n\n let path_buf = PathBuf::from_str(path).ok()?;\n\n Some(match path_buf.extension()?.to_str()? {\n\n \"rs\" => \"rust\",\n\n \"go\" => \"go\",\n\n _ => return None,\n\n })\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 6, "score": 189206.07724404693 }, { "content": "/// Returns the modification timestamp for the file at a given path,\n\n/// if present.\n\npub fn get_mod_time<P: AsRef<Path>>(path: P) -> Option<SystemTime> {\n\n File::open(path)\n\n .and_then(|f| f.metadata())\n\n .and_then(|meta| meta.modified())\n\n .ok()\n\n}\n", "file_path": "lapce-proxy/src/buffer.rs", "rank": 7, "score": 186386.03657120757 }, { "content": "/// Parse the given markdown into renderable druid rich text with the given style information\n\nfn parse_markdown(text: &str, style: &HoverTextStyle) -> MarkdownText {\n\n use pulldown_cmark::{Event, Options, Parser};\n\n\n\n let mut builder = RichTextBuilder::new();\n\n\n\n // Our position within the text\n\n let mut pos = 0;\n\n\n\n // TODO: (minor): This could use a smallvec since most tags are probably not that nested\n\n // Stores the current tags (like italics/bold/strikethrough) so that they can be nested\n\n let mut tag_stack = Vec::new();\n\n\n\n let mut code_block_indices = Vec::new();\n\n\n\n // Construct the markdown parser. We enable most of the options in order to provide the most\n\n // compatibility that pulldown_cmark allows.\n\n let parser = Parser::new_ext(\n\n text,\n\n Options::ENABLE_TABLES\n\n | Options::ENABLE_FOOTNOTES\n", "file_path": "lapce-data/src/hover.rs", "rank": 8, "score": 186338.01152476136 }, { "content": "pub fn file_svg_new(path: &Path) -> Svg {\n\n let extension = path\n\n .extension()\n\n .and_then(|s| s.to_str())\n\n .unwrap_or(\"\")\n\n .to_lowercase();\n\n let file_type = match path.file_name().and_then(|f| f.to_str()).unwrap_or(\"\") {\n\n \"LICENSE\" => \"license\",\n\n _ => match extension.as_str() {\n\n \"rs\" => \"rust\",\n\n \"md\" => \"markdown\",\n\n \"cxx\" | \"cc\" | \"c++\" => \"cpp\",\n\n s => s,\n\n },\n\n };\n\n get_svg(&format!(\"file_type_{}.svg\", file_type))\n\n .unwrap_or_else(|| get_svg(\"default_file.svg\").unwrap())\n\n}\n\n\n", "file_path": "lapce-ui/src/svg.rs", "rank": 9, "score": 184631.4764490457 }, { "content": "pub fn previous_has_unmatched_pair(line: &str, col: usize) -> bool {\n\n let mut count = HashMap::new();\n\n let mut pair_first = HashMap::new();\n\n for c in line[..col].chars().rev() {\n\n if let Some(left) = matching_pair_direction(c) {\n\n let key = if left { c } else { matching_char(c).unwrap() };\n\n let pair_count = *count.get(&key).unwrap_or(&0i32);\n\n pair_first.entry(key).or_insert(left);\n\n if left {\n\n count.insert(key, pair_count - 1);\n\n } else {\n\n count.insert(key, pair_count + 1);\n\n }\n\n }\n\n }\n\n for (_, pair_count) in count.iter() {\n\n if *pair_count < 0 {\n\n return true;\n\n }\n\n }\n\n for (_, left) in pair_first.iter() {\n\n if *left {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 10, "score": 180980.42888955338 }, { "content": "pub fn next_has_unmatched_pair(line: &str, col: usize) -> bool {\n\n let mut count = HashMap::new();\n\n for c in line[col..].chars() {\n\n if let Some(left) = matching_pair_direction(c) {\n\n let key = if left { c } else { matching_char(c).unwrap() };\n\n count.entry(key).or_insert(0i32);\n\n if left {\n\n count.insert(key, count.get(&key).unwrap_or(&0i32) - 1);\n\n } else {\n\n count.insert(key, count.get(&key).unwrap_or(&0i32) + 1);\n\n }\n\n }\n\n }\n\n for (_, pair_count) in count.iter() {\n\n if *pair_count > 0 {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 11, "score": 180980.42888955338 }, { "content": "pub fn line_styles(\n\n text: &Rope,\n\n line: usize,\n\n styles: &Spans<Style>,\n\n) -> Vec<LineStyle> {\n\n let start_offset = text.offset_of_line(line);\n\n let end_offset = text.offset_of_line(line + 1);\n\n let line_styles: Vec<LineStyle> = styles\n\n .iter_chunks(start_offset..end_offset)\n\n .filter_map(|(iv, style)| {\n\n let start = iv.start();\n\n let end = iv.end();\n\n if start > end_offset || end < start_offset {\n\n None\n\n } else {\n\n let start = if start > start_offset {\n\n start - start_offset\n\n } else {\n\n 0\n\n };\n", "file_path": "lapce-core/src/style.rs", "rank": 12, "score": 177596.60867829534 }, { "content": "fn rope_diff(\n\n left_rope: Rope,\n\n right_rope: Rope,\n\n rev: u64,\n\n atomic_rev: Arc<AtomicU64>,\n\n) -> Option<Vec<DiffLines>> {\n\n let left_lines = left_rope.lines(..).collect::<Vec<Cow<str>>>();\n\n let right_lines = right_rope.lines(..).collect::<Vec<Cow<str>>>();\n\n\n\n let left_count = left_lines.len();\n\n let right_count = right_lines.len();\n\n let min_count = cmp::min(left_count, right_count);\n\n\n\n let leading_equals = left_lines\n\n .iter()\n\n .zip(right_lines.iter())\n\n .take_while(|p| p.0 == p.1)\n\n .count();\n\n let trailing_equals = left_lines\n\n .iter()\n", "file_path": "lapce-data/src/buffer.rs", "rank": 13, "score": 176589.64503279427 }, { "content": "pub fn matching_char(c: char) -> Option<char> {\n\n Some(match c {\n\n '{' => '}',\n\n '}' => '{',\n\n '(' => ')',\n\n ')' => '(',\n\n '[' => ']',\n\n ']' => '[',\n\n _ => return None,\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_lens() {\n\n let lens = Syntax::lens_from_normal_lines(5, 25, 2, &[4]);\n\n assert_eq!(5, lens.len());\n", "file_path": "lapce-core/src/syntax.rs", "rank": 14, "score": 176335.43100119452 }, { "content": "pub fn matching_char(c: char) -> Option<char> {\n\n Some(match c {\n\n '{' => '}',\n\n '}' => '{',\n\n '(' => ')',\n\n ')' => '(',\n\n '[' => ']',\n\n ']' => '[',\n\n _ => return None,\n\n })\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct DiffHunk {\n\n pub old_start: u32,\n\n pub old_lines: u32,\n\n pub new_start: u32,\n\n pub new_lines: u32,\n\n pub header: String,\n\n}\n", "file_path": "lapce-data/src/buffer.rs", "rank": 15, "score": 176008.42853174318 }, { "content": "#[inline]\n\npub fn char_is_whitespace(ch: char) -> bool {\n\n // TODO: this is a naive binary categorization of whitespace\n\n // characters. For display, word wrapping, etc. we'll need a better\n\n // categorization based on e.g. breaking vs non-breaking spaces\n\n // and whether they're zero-width or not.\n\n match ch {\n\n //'\\u{1680}' | // Ogham Space Mark (here for completeness, but usually displayed as a dash, not as whitespace)\n\n '\\u{0009}' | // Character Tabulation\n\n '\\u{0020}' | // Space\n\n '\\u{00A0}' | // No-break Space\n\n '\\u{180E}' | // Mongolian Vowel Separator\n\n '\\u{202F}' | // Narrow No-break Space\n\n '\\u{205F}' | // Medium Mathematical Space\n\n '\\u{3000}' | // Ideographic Space\n\n '\\u{FEFF}' // Zero Width No-break Space\n\n => true,\n\n\n\n // En Quad, Em Quad, En Space, Em Space, Three-per-em Space,\n\n // Four-per-em Space, Six-per-em Space, Figure Space,\n\n // Punctuation Space, Thin Space, Hair Space, Zero Width Space.\n\n ch if ('\\u{2000}' ..= '\\u{200B}').contains(&ch) => true,\n\n\n\n _ => false,\n\n }\n\n}\n", "file_path": "lapce-core/src/chars.rs", "rank": 16, "score": 166172.8490962241 }, { "content": "fn load_plugin(path: &Path) -> Result<PluginDescription> {\n\n let mut file = fs::File::open(&path)?;\n\n let mut contents = String::new();\n\n file.read_to_string(&mut contents)?;\n\n let mut plugin: PluginDescription = toml::from_str(&contents)?;\n\n plugin.dir = Some(path.parent().unwrap().canonicalize()?);\n\n plugin.wasm = path\n\n .parent()\n\n .unwrap()\n\n .join(&plugin.wasm)\n\n .canonicalize()?\n\n .to_str()\n\n .ok_or_else(|| anyhow!(\"path can't to string\"))?\n\n .to_string();\n\n Ok(plugin)\n\n}\n", "file_path": "lapce-proxy/src/plugin.rs", "rank": 17, "score": 163821.78117939594 }, { "content": "#[inline]\n\npub fn char_is_line_ending(ch: char) -> bool {\n\n matches!(ch, '\\u{000A}')\n\n}\n\n\n\n/// Determine whether a character qualifies as (non-line-break)\n\n/// whitespace.\n", "file_path": "lapce-core/src/chars.rs", "rank": 18, "score": 162675.72367292547 }, { "content": "#[cfg(not(windows))]\n\npub fn path_from_url(url: &Url) -> PathBuf {\n\n PathBuf::from(url.path())\n\n}\n", "file_path": "lapce-data/src/proxy.rs", "rank": 19, "score": 153193.72744931604 }, { "content": "#[derive(Debug)]\n\nstruct LocalScope<'a> {\n\n inherits: bool,\n\n range: ops::Range<usize>,\n\n local_defs: Vec<LocalDef<'a>>,\n\n}\n\n\n", "file_path": "lapce-core/src/style.rs", "rank": 20, "score": 151276.01883031454 }, { "content": "#[derive(Debug)]\n\nstruct LocalDef<'a> {\n\n name: &'a str,\n\n value_range: ops::Range<usize>,\n\n highlight: Option<Highlight>,\n\n}\n\n\n", "file_path": "lapce-core/src/style.rs", "rank": 21, "score": 151276.01883031454 }, { "content": "pub fn char_width(c: char) -> usize {\n\n if c == '\\t' {\n\n return 8;\n\n }\n\n if c.is_emoji_modifier_base() || c.is_emoji_modifier() {\n\n // treat modifier sequences as double wide\n\n return 2;\n\n }\n\n c.width().unwrap_or(0)\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 22, "score": 146738.10137314713 }, { "content": "fn number_from_id(id: &Id) -> u64 {\n\n match *id {\n\n Id::Num(n) => n as u64,\n\n Id::Str(ref s) => s\n\n .parse::<u64>()\n\n .expect(\"failed to convert string id to u64\"),\n\n _ => panic!(\"unexpected value for id: None\"),\n\n }\n\n}\n\n\n", "file_path": "lapce-proxy/src/lsp.rs", "rank": 23, "score": 144075.6876834028 }, { "content": "#[allow(dead_code)]\n\nfn number_from_id(id: &Id) -> u64 {\n\n match *id {\n\n Id::Num(n) => n as u64,\n\n Id::Str(ref s) => s\n\n .parse::<u64>()\n\n .expect(\"failed to convert string id to u64\"),\n\n _ => panic!(\"unexpected value for id: None\"),\n\n }\n\n}\n", "file_path": "lapce-ui/src/lsp.rs", "rank": 24, "score": 144075.6876834028 }, { "content": "#[allow(dead_code)]\n\nfn number_from_id(id: &Id) -> u64 {\n\n match *id {\n\n Id::Num(n) => n as u64,\n\n Id::Str(ref s) => s\n\n .parse::<u64>()\n\n .expect(\"failed to convert string id to u64\"),\n\n _ => panic!(\"unexpected value for id: None\"),\n\n }\n\n}\n", "file_path": "lapce-data/src/lsp.rs", "rank": 25, "score": 144075.6876834028 }, { "content": "pub fn build_window(data: &LapceWindowData) -> impl Widget<LapceData> {\n\n LapceWindowNew::new(data).lens(LapceWindowLens(data.window_id))\n\n}\n\n\n", "file_path": "lapce-ui/src/app.rs", "rank": 26, "score": 143972.9639769644 }, { "content": "fn injection_for_match<'a>(\n\n config: &HighlightConfiguration,\n\n query: &'a Query,\n\n query_match: &QueryMatch<'a, 'a>,\n\n source: &'a [u8],\n\n) -> (Option<&'a str>, Option<Node<'a>>, bool) {\n\n let content_capture_index = config.injection_content_capture_index;\n\n let language_capture_index = config.injection_language_capture_index;\n\n\n\n let mut language_name = None;\n\n let mut content_node = None;\n\n for capture in query_match.captures {\n\n let index = Some(capture.index);\n\n if index == language_capture_index {\n\n language_name = capture.node.utf8_text(source).ok();\n\n } else if index == content_capture_index {\n\n content_node = Some(capture.node);\n\n }\n\n }\n\n\n", "file_path": "lapce-core/src/style.rs", "rank": 27, "score": 143348.13904555078 }, { "content": "pub fn wasi_write_object(wasi_env: &WasiEnv, object: &(impl Serialize + ?Sized)) {\n\n wasi_write_string(wasi_env, &serde_json::to_string(&object).unwrap());\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub enum PluginRequest {}\n\n\n\npub struct PluginHandler {\n\n #[allow(dead_code)]\n\n dispatcher: Dispatcher,\n\n}\n\n\n", "file_path": "lapce-proxy/src/plugin.rs", "rank": 28, "score": 138436.45815997495 }, { "content": "pub fn get_word_property(codepoint: char) -> WordProperty {\n\n if codepoint <= ' ' {\n\n if codepoint == '\\r' {\n\n return WordProperty::Cr;\n\n }\n\n if codepoint == '\\n' {\n\n return WordProperty::Lf;\n\n }\n\n return WordProperty::Space;\n\n } else if codepoint <= '\\u{3f}' {\n\n if (0xfc00fffe00000000u64 >> (codepoint as u32)) & 1 != 0 {\n\n return WordProperty::Punctuation;\n\n }\n\n } else if codepoint <= '\\u{7f}' {\n\n // Hardcoded: @[\\]^`{|}~\n\n if (0x7800000178000001u64 >> ((codepoint as u32) & 0x3f)) & 1 != 0 {\n\n return WordProperty::Punctuation;\n\n }\n\n }\n\n WordProperty::Other\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 29, "score": 136256.94569145134 }, { "content": "fn get_document_content_changes(\n\n delta: &RopeDelta,\n\n buffer: &Buffer,\n\n) -> Option<TextDocumentContentChangeEvent> {\n\n let (interval, _) = delta.summary();\n\n let (start, end) = interval.start_end();\n\n\n\n // TODO: Handle more trivial cases like typing when there's a selection or transpose\n\n if let Some(node) = delta.as_simple_insert() {\n\n let text = String::from(node);\n\n\n\n let (start, end) = interval.start_end();\n\n let text_document_content_change_event = TextDocumentContentChangeEvent {\n\n range: Some(Range {\n\n start: buffer.offset_to_position(start),\n\n end: buffer.offset_to_position(end),\n\n }),\n\n range_length: Some((end - start) as u32),\n\n text,\n\n };\n", "file_path": "lapce-proxy/src/buffer.rs", "rank": 30, "score": 135989.40465342157 }, { "content": "fn file_get_head(workspace_path: &Path, path: &Path) -> Result<(String, String)> {\n\n let repo = Repository::open(\n\n workspace_path\n\n .to_str()\n\n .ok_or_else(|| anyhow!(\"can't to str\"))?,\n\n )?;\n\n let head = repo.head()?;\n\n let tree = head.peel_to_tree()?;\n\n let tree_entry = tree.get_path(path.strip_prefix(workspace_path)?)?;\n\n let blob = repo.find_blob(tree_entry.id())?;\n\n let id = blob.id().to_string();\n\n let content = std::str::from_utf8(blob.content())\n\n .with_context(|| \"content bytes to string\")?\n\n .to_string();\n\n Ok((id, content))\n\n}\n\n\n", "file_path": "lapce-proxy/src/dispatch.rs", "rank": 31, "score": 132244.64560773334 }, { "content": "pub fn str_col(s: &str, tab_width: usize) -> usize {\n\n let mut total_width = 0;\n\n\n\n for c in s.chars() {\n\n let width = if c == '\\t' {\n\n tab_width - total_width % tab_width\n\n } else {\n\n char_width(c)\n\n };\n\n\n\n total_width += width;\n\n }\n\n\n\n total_width\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 32, "score": 131844.0372782215 }, { "content": "fn find_all_plugins() -> Vec<PathBuf> {\n\n let mut plugin_paths = Vec::new();\n\n let home = home_dir().unwrap();\n\n let path = home.join(\".lapce\").join(\"plugins\");\n\n let _ = path.read_dir().map(|dir| {\n\n dir.flat_map(|item| item.map(|p| p.path()).ok())\n\n .map(|dir| dir.join(\"plugin.toml\"))\n\n .filter(|f| f.exists())\n\n .for_each(|f| plugin_paths.push(f))\n\n });\n\n plugin_paths\n\n}\n\n\n", "file_path": "lapce-proxy/src/plugin.rs", "rank": 33, "score": 128781.6038365735 }, { "content": "pub fn launch() {\n\n let mut log_dispatch = fern::Dispatch::new()\n\n .format(|out, message, record| {\n\n out.finish(format_args!(\n\n \"{}[{}][{}] {}\",\n\n chrono::Local::now().format(\"[%Y-%m-%d][%H:%M:%S]\"),\n\n record.target(),\n\n record.level(),\n\n message\n\n ))\n\n })\n\n .level(log::LevelFilter::Off)\n\n .level_for(\"piet_wgpu\", log::LevelFilter::Info);\n\n\n\n if let Some(log_file) = Config::log_file().and_then(|f| fern::log_file(f).ok()) {\n\n log_dispatch = log_dispatch.chain(log_file);\n\n }\n\n\n\n log_dispatch = override_log_levels(log_dispatch);\n\n let _ = log_dispatch.apply();\n", "file_path": "lapce-ui/src/app.rs", "rank": 34, "score": 128534.47973471932 }, { "content": "pub fn mainloop() {\n\n let (sender, receiver) = lapce_rpc::stdio();\n\n let dispatcher = Dispatcher::new(sender);\n\n let _ = dispatcher.mainloop(receiver);\n\n}\n", "file_path": "lapce-proxy/src/lib.rs", "rank": 35, "score": 128534.47973471932 }, { "content": "pub fn completion_svg(\n\n kind: Option<CompletionItemKind>,\n\n config: &Config,\n\n) -> Option<(Svg, Option<Color>)> {\n\n let kind = kind?;\n\n let kind_str = match kind {\n\n CompletionItemKind::Method => \"method\",\n\n CompletionItemKind::Function => \"method\",\n\n CompletionItemKind::Enum => \"enum\",\n\n CompletionItemKind::EnumMember => \"enum-member\",\n\n CompletionItemKind::Class => \"class\",\n\n CompletionItemKind::Variable => \"variable\",\n\n CompletionItemKind::Struct => \"structure\",\n\n CompletionItemKind::Keyword => \"keyword\",\n\n CompletionItemKind::Constant => \"constant\",\n\n CompletionItemKind::Property => \"property\",\n\n CompletionItemKind::Field => \"field\",\n\n CompletionItemKind::Interface => \"interface\",\n\n CompletionItemKind::Snippet => \"snippet\",\n\n CompletionItemKind::Module => \"namespace\",\n", "file_path": "lapce-ui/src/svg.rs", "rank": 36, "score": 125425.81597462385 }, { "content": "pub fn get_item_children(\n\n i: usize,\n\n index: usize,\n\n item: &FileNodeItem,\n\n) -> (usize, Option<&FileNodeItem>) {\n\n if i == index {\n\n return (i, Some(item));\n\n }\n\n let mut i = i;\n\n if item.open {\n\n for child in item.sorted_children() {\n\n let count = child.children_open_count;\n\n if i + count + 1 >= index {\n\n let (new_index, node) = get_item_children(i + 1, index, child);\n\n if new_index == index {\n\n return (new_index, node);\n\n }\n\n }\n\n i += count + 1;\n\n }\n\n }\n\n (i, None)\n\n}\n\n\n", "file_path": "lapce-ui/src/explorer.rs", "rank": 37, "score": 122545.45275859325 }, { "content": "pub fn split_content_widget(\n\n content: &SplitContent,\n\n data: &LapceTabData,\n\n) -> Box<dyn Widget<LapceTabData>> {\n\n match content {\n\n SplitContent::EditorTab(widget_id) => {\n\n let editor_tab_data =\n\n data.main_split.editor_tabs.get(widget_id).unwrap();\n\n let mut editor_tab = LapceEditorTab::new(editor_tab_data.widget_id);\n\n for child in editor_tab_data.children.iter() {\n\n match child {\n\n EditorTabChild::Editor(view_id, find_view_id) => {\n\n let editor =\n\n LapceEditorView::new(*view_id, *find_view_id).boxed();\n\n editor_tab = editor_tab.with_child(editor);\n\n }\n\n }\n\n }\n\n editor_tab.boxed()\n\n }\n", "file_path": "lapce-ui/src/split.rs", "rank": 38, "score": 122545.45275859325 }, { "content": "pub fn split_data_widget(\n\n split_data: &SplitData,\n\n data: &LapceTabData,\n\n) -> LapceSplitNew {\n\n let mut split =\n\n LapceSplitNew::new(split_data.widget_id).direction(split_data.direction);\n\n for child in split_data.children.iter() {\n\n let child = split_content_widget(child, data);\n\n split = split.with_flex_child(child, None, 1.0);\n\n }\n\n split\n\n}\n\n\n", "file_path": "lapce-ui/src/split.rs", "rank": 39, "score": 122545.45275859325 }, { "content": "pub fn get_item_children(\n\n i: usize,\n\n index: usize,\n\n item: &FileNodeItem,\n\n) -> (usize, Option<&FileNodeItem>) {\n\n if i == index {\n\n return (i, Some(item));\n\n }\n\n let mut i = i;\n\n if item.open {\n\n for child in item.sorted_children() {\n\n let count = child.children_open_count;\n\n if i + count + 1 >= index {\n\n let (new_index, node) = get_item_children(i + 1, index, child);\n\n if new_index == index {\n\n return (new_index, node);\n\n }\n\n }\n\n i += count + 1;\n\n }\n\n }\n\n (i, None)\n\n}\n\n\n", "file_path": "lapce-data/src/explorer.rs", "rank": 40, "score": 122545.45275859325 }, { "content": "pub fn paint_key(\n\n ctx: &mut PaintCtx,\n\n text: &str,\n\n origin: Point,\n\n config: &Config,\n\n) -> (Rect, PietTextLayout, Point) {\n\n let text_layout = ctx\n\n .text()\n\n .new_text_layout(text.to_string())\n\n .font(FontFamily::SYSTEM_UI, 13.0)\n\n .text_color(\n\n config\n\n .get_color_unchecked(LapceTheme::EDITOR_FOREGROUND)\n\n .clone(),\n\n )\n\n .build()\n\n .unwrap();\n\n let text_size = text_layout.size();\n\n let text_layout_point = origin + (5.0, -(text_size.height / 2.0));\n\n let rect = Size::new(text_size.width, 0.0)\n", "file_path": "lapce-data/src/keypress/mod.rs", "rank": 41, "score": 122545.45275859325 }, { "content": "pub fn get_item_children_mut(\n\n i: usize,\n\n index: usize,\n\n item: &mut FileNodeItem,\n\n) -> (usize, Option<&mut FileNodeItem>) {\n\n if i == index {\n\n return (i, Some(item));\n\n }\n\n let mut i = i;\n\n if item.open {\n\n for child in item.sorted_children_mut() {\n\n let count = child.children_open_count;\n\n if i + count + 1 >= index {\n\n let (new_index, node) = get_item_children_mut(i + 1, index, child);\n\n if new_index == index {\n\n return (new_index, node);\n\n }\n\n }\n\n i += count + 1;\n\n }\n", "file_path": "lapce-ui/src/explorer.rs", "rank": 42, "score": 119869.1312535546 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn paint_file_node_item(\n\n ctx: &mut PaintCtx,\n\n item: &FileNodeItem,\n\n min: usize,\n\n max: usize,\n\n line_height: f64,\n\n width: f64,\n\n level: usize,\n\n current: usize,\n\n active: Option<&Path>,\n\n hovered: Option<usize>,\n\n config: &Config,\n\n toggle_rects: &mut HashMap<usize, Rect>,\n\n) -> usize {\n\n if current > max {\n\n return current;\n\n }\n\n if current + item.children_open_count < min {\n\n return current + item.children_open_count;\n\n }\n", "file_path": "lapce-ui/src/explorer.rs", "rank": 43, "score": 119869.1312535546 }, { "content": "pub fn get_item_children_mut(\n\n i: usize,\n\n index: usize,\n\n item: &mut FileNodeItem,\n\n) -> (usize, Option<&mut FileNodeItem>) {\n\n if i == index {\n\n return (i, Some(item));\n\n }\n\n let mut i = i;\n\n if item.open {\n\n for child in item.sorted_children_mut() {\n\n let count = child.children_open_count;\n\n if i + count + 1 >= index {\n\n let (new_index, node) = get_item_children_mut(i + 1, index, child);\n\n if new_index == index {\n\n return (new_index, node);\n\n }\n\n }\n\n i += count + 1;\n\n }\n\n }\n\n (i, None)\n\n}\n", "file_path": "lapce-data/src/explorer.rs", "rank": 44, "score": 119869.1312535546 }, { "content": "pub fn logo_svg() -> Svg {\n\n let name = \"lapce_logo\";\n\n let mut svgs = SVG_STORE.svgs.lock();\n\n if !svgs.contains_key(name) {\n\n let svg = Svg::from_str(LOGO).ok();\n\n svgs.insert(name.to_string(), svg);\n\n }\n\n svgs.get(name).cloned().unwrap().unwrap()\n\n}\n\n\n", "file_path": "lapce-ui/src/svg.rs", "rank": 45, "score": 118944.90377658496 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn paint_file_node_item_by_index(\n\n ctx: &mut PaintCtx,\n\n item: &FileNodeItem,\n\n min: usize,\n\n max: usize,\n\n line_height: f64,\n\n width: f64,\n\n level: usize,\n\n current: usize,\n\n active: usize,\n\n hovered: Option<usize>,\n\n config: &Config,\n\n toggle_rects: &mut HashMap<usize, Rect>,\n\n) -> usize {\n\n if current > max {\n\n return current;\n\n }\n\n if current + item.children_open_count < min {\n\n return current + item.children_open_count;\n\n }\n", "file_path": "lapce-ui/src/picker.rs", "rank": 46, "score": 117375.91199355076 }, { "content": "pub fn editor_tab_child_widget(\n\n child: &EditorTabChild,\n\n) -> Box<dyn Widget<LapceTabData>> {\n\n match child {\n\n EditorTabChild::Editor(view_id, find_view_id) => {\n\n LapceEditorView::new(*view_id, *find_view_id).boxed()\n\n }\n\n }\n\n}\n\n\n\nimpl LapceEditorView {\n\n pub fn new(\n\n view_id: WidgetId,\n\n find_view_id: Option<WidgetId>,\n\n ) -> LapceEditorView {\n\n let header = LapceEditorHeader::new(view_id);\n\n let editor = LapceEditorContainer::new(view_id);\n\n let find =\n\n find_view_id.map(|id| WidgetPod::new(FindBox::new(id, view_id)).boxed());\n\n Self {\n", "file_path": "lapce-ui/src/editor/view.rs", "rank": 47, "score": 117375.91199355076 }, { "content": "fn git_diff_new(workspace_path: &Path) -> Option<DiffInfo> {\n\n let repo = Repository::open(workspace_path.to_str()?).ok()?;\n\n let head = repo.head().ok()?;\n\n let name = head.shorthand()?.to_string();\n\n\n\n let mut branches = Vec::new();\n\n for branch in repo.branches(None).ok()? {\n\n branches.push(branch.ok()?.0.name().ok()??.to_string());\n\n }\n\n\n\n let mut deltas = Vec::new();\n\n let mut diff_options = DiffOptions::new();\n\n let diff = repo\n\n .diff_index_to_workdir(None, Some(diff_options.include_untracked(true)))\n\n .ok()?;\n\n for delta in diff.deltas() {\n\n if let Some(delta) = git_delta_format(workspace_path, &delta) {\n\n deltas.push(delta);\n\n }\n\n }\n", "file_path": "lapce-proxy/src/dispatch.rs", "rank": 48, "score": 116987.34228368988 }, { "content": "fn empty_editor_commands(modal: bool, has_workspace: bool) -> Vec<LapceCommandNew> {\n\n if !has_workspace {\n\n vec![\n\n LapceCommandNew {\n\n cmd: LapceWorkbenchCommand::PaletteCommand.to_string(),\n\n data: None,\n\n palette_desc: Some(\"Show All Commands\".to_string()),\n\n target: CommandTarget::Workbench,\n\n },\n\n if modal {\n\n LapceCommandNew {\n\n cmd: LapceWorkbenchCommand::DisableModal.to_string(),\n\n data: None,\n\n palette_desc: LapceWorkbenchCommand::DisableModal\n\n .get_message()\n\n .map(|m| m.to_string()),\n\n target: CommandTarget::Workbench,\n\n }\n\n } else {\n\n LapceCommandNew {\n", "file_path": "lapce-ui/src/split.rs", "rank": 49, "score": 116872.08726489753 }, { "content": "#[allow(dead_code)]\n\nfn buffer_diff(\n\n left_rope: Rope,\n\n right_rope: Rope,\n\n rev: u64,\n\n atomic_rev: Arc<AtomicU64>,\n\n) -> Option<Vec<DiffLines>> {\n\n let mut changes = Vec::new();\n\n let left_str = &left_rope.slice_to_cow(0..left_rope.len());\n\n let right_str = &right_rope.slice_to_cow(0..right_rope.len());\n\n let mut left_line = 0;\n\n let mut right_line = 0;\n\n for diff in diff::lines(left_str, right_str) {\n\n if atomic_rev.load(atomic::Ordering::Acquire) != rev {\n\n return None;\n\n }\n\n match diff {\n\n diff::Result::Left(_) => {\n\n match changes.last_mut() {\n\n Some(DiffLines::Left(r)) => r.end = left_line + 1,\n\n _ => changes.push(DiffLines::Left(left_line..left_line + 1)),\n", "file_path": "lapce-data/src/buffer.rs", "rank": 50, "score": 116621.85869894689 }, { "content": "#[derive(Clone)]\n\nstruct Revision {\n\n max_undo_so_far: usize,\n\n edit: Contents,\n\n}\n\n\n\n#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]\n\npub enum LocalBufferKind {\n\n Search,\n\n SourceControl,\n\n Empty,\n\n FilePicker,\n\n Keymap,\n\n Settings,\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\n\npub enum BufferContent {\n\n File(PathBuf),\n\n Local(LocalBufferKind),\n\n Value(String),\n", "file_path": "lapce-data/src/buffer.rs", "rank": 51, "score": 115981.17130826258 }, { "content": "#[allow(dead_code)]\n\nfn str_is_pair_left(c: &str) -> bool {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n if matching_pair_direction(c).unwrap_or(false) {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/data.rs", "rank": 52, "score": 115318.22439369487 }, { "content": "#[allow(dead_code)]\n\nfn str_is_pair_right(c: &str) -> bool {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n return !matching_pair_direction(c).unwrap_or(true);\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/editor.rs", "rank": 53, "score": 115318.22439369487 }, { "content": "#[allow(dead_code)]\n\nfn str_is_pair_right(c: &str) -> bool {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n return !matching_pair_direction(c).unwrap_or(true);\n\n }\n\n false\n\n}\n", "file_path": "lapce-ui/src/editor.rs", "rank": 54, "score": 115318.22439369487 }, { "content": "fn str_is_pair_left(c: &str) -> bool {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n if matching_pair_direction(c).unwrap_or(false) {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/editor.rs", "rank": 55, "score": 115318.22439369487 }, { "content": "#[allow(dead_code)]\n\nfn str_is_pair_right(c: &str) -> bool {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n return !matching_pair_direction(c).unwrap_or(true);\n\n }\n\n false\n\n}\n\n\n", "file_path": "lapce-data/src/data.rs", "rank": 56, "score": 115318.22439369487 }, { "content": "pub fn stdio_transport<W, R>(\n\n mut writer: W,\n\n writer_receiver: Receiver<Value>,\n\n mut reader: R,\n\n reader_sender: Sender<Value>,\n\n) where\n\n W: 'static + Write + Send,\n\n R: 'static + BufRead + Send,\n\n{\n\n thread::spawn(move || -> Result<()> {\n\n writer_receiver\n\n .into_iter()\n\n .try_for_each(|it| write_msg(&mut writer, &it))?;\n\n Ok(())\n\n });\n\n thread::spawn(move || -> Result<()> {\n\n loop {\n\n let msg = read_msg(&mut reader)?;\n\n reader_sender.send(msg)?;\n\n }\n\n });\n\n}\n\n\n", "file_path": "lapce-rpc/src/stdio.rs", "rank": 57, "score": 113180.59245431561 }, { "content": "/// Decides whether newlines should be added after a specific markdown tag\n\nfn should_add_newline_after_tag(tag: &Tag) -> bool {\n\n !matches!(\n\n tag,\n\n Tag::Emphasis | Tag::Strong | Tag::Strikethrough | Tag::Link(..)\n\n )\n\n}\n", "file_path": "lapce-data/src/hover.rs", "rank": 58, "score": 112821.85709980223 }, { "content": "pub trait BufferDataListener {\n\n fn should_apply_edit(&self) -> bool;\n\n\n\n fn on_edit_applied(&mut self, buffer: &BufferData, delta: &RopeDelta);\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct BufferData {\n\n pub(super) id: BufferId,\n\n pub(super) rope: Rope,\n\n pub(super) content: BufferContent,\n\n\n\n pub(super) max_len: usize,\n\n pub(super) max_len_line: usize,\n\n pub(super) num_lines: usize,\n\n\n\n pub(super) rev: u64,\n\n pub(super) atomic_rev: Arc<AtomicU64>,\n\n pub(super) dirty: bool,\n\n\n", "file_path": "lapce-data/src/buffer/data.rs", "rank": 59, "score": 111935.88648695424 }, { "content": "#[allow(dead_code)]\n\nstruct EditorTextLayout {\n\n layout: TextLayout<String>,\n\n text: String,\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct HighlightTextLayout {\n\n pub layout: PietTextLayout,\n\n pub text: String,\n\n pub highlights: Vec<(usize, usize, String)>,\n\n}\n\n\n", "file_path": "lapce-ui/src/editor.rs", "rank": 60, "score": 109912.47444986041 }, { "content": "fn shuffle(\n\n text: &Rope,\n\n tombstones: &Rope,\n\n old_deletes_from_union: &Subset,\n\n new_deletes_from_union: &Subset,\n\n) -> (Rope, Rope) {\n\n // Delta that deletes the right bits from the text\n\n let del_delta = Delta::synthesize(\n\n tombstones,\n\n old_deletes_from_union,\n\n new_deletes_from_union,\n\n );\n\n let new_text = del_delta.apply(text);\n\n (\n\n new_text,\n\n shuffle_tombstones(\n\n text,\n\n tombstones,\n\n old_deletes_from_union,\n\n new_deletes_from_union,\n", "file_path": "lapce-data/src/buffer.rs", "rank": 61, "score": 107359.00958183862 }, { "content": "struct HighlightIterLayer<'a> {\n\n _tree: Tree,\n\n cursor: QueryCursor,\n\n captures: iter::Peekable<QueryCaptures<'a, 'a, &'a [u8]>>,\n\n config: &'a HighlightConfiguration,\n\n highlight_end_stack: Vec<usize>,\n\n scope_stack: Vec<LocalScope<'a>>,\n\n ranges: Vec<Range>,\n\n depth: usize,\n\n}\n\n\n\nimpl Highlight {\n\n pub fn str(&self) -> &str {\n\n SCOPES[self.0]\n\n }\n\n}\n\n\n\nimpl Highlighter {\n\n pub fn new() -> Self {\n\n Highlighter {\n", "file_path": "lapce-core/src/style.rs", "rank": 62, "score": 107197.88990877027 }, { "content": "pub fn keybinding_to_string(keypress: &KeyPress) -> String {\n\n let mut keymap_str = \"\".to_string();\n\n if keypress.mods.ctrl() {\n\n keymap_str += \"Ctrl+\";\n\n }\n\n if keypress.mods.alt() {\n\n keymap_str += \"Alt+\";\n\n }\n\n if keypress.mods.meta() {\n\n let keyname = match std::env::consts::OS {\n\n \"macos\" => \"Cmd\",\n\n \"windows\" => \"Win\",\n\n _ => \"Meta\",\n\n };\n\n keymap_str += keyname;\n\n keymap_str += \"+\";\n\n }\n\n if keypress.mods.shift() {\n\n keymap_str += \"Shift+\";\n\n }\n\n keymap_str += &keypress.key.to_string();\n\n keymap_str\n\n}\n", "file_path": "lapce-data/src/split.rs", "rank": 63, "score": 105681.4804573534 }, { "content": "pub fn keybinding_to_string(keypress: &KeyPress) -> String {\n\n let mut keymap_str = \"\".to_string();\n\n if keypress.mods.ctrl() {\n\n keymap_str += \"Ctrl+\";\n\n }\n\n if keypress.mods.alt() {\n\n keymap_str += \"Alt+\";\n\n }\n\n if keypress.mods.meta() {\n\n let keyname = match std::env::consts::OS {\n\n \"macos\" => \"Cmd\",\n\n \"windows\" => \"Win\",\n\n _ => \"Meta\",\n\n };\n\n keymap_str += keyname;\n\n keymap_str += \"+\";\n\n }\n\n if keypress.mods.shift() {\n\n keymap_str += \"Shift+\";\n\n }\n\n keymap_str += &keypress.key.to_string();\n\n keymap_str\n\n}\n", "file_path": "lapce-ui/src/split.rs", "rank": 64, "score": 105681.4804573534 }, { "content": "pub fn stdio() -> (Sender<Value>, Receiver<Value>) {\n\n let stdout = stdout();\n\n let stdin = BufReader::new(stdin());\n\n let (writer_sender, writer_receiver) = crossbeam_channel::unbounded();\n\n let (reader_sender, reader_receiver) = crossbeam_channel::unbounded();\n\n stdio::stdio_transport(stdout, writer_receiver, stdin, reader_sender);\n\n (writer_sender, reader_receiver)\n\n}\n\n\n", "file_path": "lapce-rpc/src/lib.rs", "rank": 65, "score": 105665.83255713152 }, { "content": "struct HighlightIter<'a, F>\n\nwhere\n\n F: FnMut(&str) -> Option<&'a HighlightConfiguration> + 'a,\n\n{\n\n tree: Tree,\n\n source: &'a [u8],\n\n byte_offset: usize,\n\n highlighter: &'a mut Highlighter,\n\n injection_callback: F,\n\n cancellation_flag: Option<&'a AtomicUsize>,\n\n layers: Vec<HighlightIterLayer<'a>>,\n\n iter_count: usize,\n\n next_event: Option<HighlightEvent>,\n\n last_highlight_range: Option<(usize, usize, usize)>,\n\n}\n\n\n", "file_path": "lapce-core/src/style.rs", "rank": 66, "score": 105010.032557145 }, { "content": "fn shuffle_tombstones(\n\n text: &Rope,\n\n tombstones: &Rope,\n\n old_deletes_from_union: &Subset,\n\n new_deletes_from_union: &Subset,\n\n) -> Rope {\n\n // Taking the complement of deletes_from_union leads to an interleaving valid for swapped text and tombstones,\n\n // allowing us to use the same method to insert the text into the tombstones.\n\n let inverse_tombstones_map = old_deletes_from_union.complement();\n\n let move_delta = Delta::synthesize(\n\n text,\n\n &inverse_tombstones_map,\n\n &new_deletes_from_union.complement(),\n\n );\n\n move_delta.apply(tombstones)\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 67, "score": 104005.88447257047 }, { "content": "pub fn get_svg(name: &str) -> Option<Svg> {\n\n SVG_STORE.get_svg(name)\n\n}\n\n\n", "file_path": "lapce-ui/src/svg.rs", "rank": 68, "score": 103337.54648058627 }, { "content": "pub fn new_problem_panel(data: &ProblemData) -> LapcePanel {\n\n LapcePanel::new(\n\n PanelKind::Problem,\n\n data.widget_id,\n\n data.split_id,\n\n SplitDirection::Vertical,\n\n PanelHeaderKind::Simple(\"Problem\".to_string()),\n\n vec![\n\n (\n\n data.error_widget_id,\n\n PanelHeaderKind::Simple(\"Errors\".to_string()),\n\n ProblemContent::new(DiagnosticSeverity::Error).boxed(),\n\n None,\n\n ),\n\n (\n\n data.warning_widget_id,\n\n PanelHeaderKind::Simple(\"Warnings\".to_string()),\n\n ProblemContent::new(DiagnosticSeverity::Warning).boxed(),\n\n None,\n\n ),\n", "file_path": "lapce-ui/src/problem.rs", "rank": 69, "score": 101458.30515727424 }, { "content": "fn git_delta_format(\n\n workspace_path: &Path,\n\n delta: &git2::DiffDelta,\n\n) -> Option<(git2::Delta, git2::Oid, PathBuf)> {\n\n match delta.status() {\n\n git2::Delta::Added | git2::Delta::Untracked => Some((\n\n git2::Delta::Added,\n\n delta.new_file().id(),\n\n delta.new_file().path().map(|p| workspace_path.join(p))?,\n\n )),\n\n git2::Delta::Deleted => Some((\n\n git2::Delta::Deleted,\n\n delta.old_file().id(),\n\n delta.old_file().path().map(|p| workspace_path.join(p))?,\n\n )),\n\n git2::Delta::Modified => Some((\n\n git2::Delta::Modified,\n\n delta.new_file().id(),\n\n delta.new_file().path().map(|p| workspace_path.join(p))?,\n\n )),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "lapce-proxy/src/dispatch.rs", "rank": 70, "score": 101315.11811929435 }, { "content": "#[allow(dead_code)]\n\nfn set_locale_environment() {\n\n let locale = locale_config::Locale::global_default()\n\n .to_string()\n\n .replace('-', \"_\");\n\n std::env::set_var(\"LC_ALL\", locale + \".UTF-8\");\n\n}\n", "file_path": "lapce-proxy/src/terminal.rs", "rank": 71, "score": 101310.5709010358 }, { "content": "fn format_semantic_styles(\n\n buffer: &Buffer,\n\n semantic_tokens_provider: &Option<SemanticTokensServerCapabilities>,\n\n value: Value,\n\n) -> Option<Vec<LineStyle>> {\n\n let semantic_tokens: SemanticTokens = serde_json::from_value(value).ok()?;\n\n let semantic_tokens_provider = semantic_tokens_provider.as_ref()?;\n\n let semantic_lengends = semantic_tokens_lengend(semantic_tokens_provider);\n\n\n\n let mut highlights = Vec::new();\n\n let mut line = 0;\n\n let mut start = 0;\n\n let mut last_start = 0;\n\n for semantic_token in &semantic_tokens.data {\n\n if semantic_token.delta_line > 0 {\n\n line += semantic_token.delta_line as usize;\n\n start = buffer.offset_of_line(line);\n\n }\n\n start += semantic_token.delta_start as usize;\n\n let end = start + semantic_token.length as usize;\n", "file_path": "lapce-proxy/src/lsp.rs", "rank": 72, "score": 101177.71782110498 }, { "content": "#[allow(dead_code)]\n\nfn semantic_tokens_lengend(\n\n semantic_tokens_provider: &SemanticTokensServerCapabilities,\n\n) -> SemanticTokensLegend {\n\n match semantic_tokens_provider {\n\n SemanticTokensServerCapabilities::SemanticTokensOptions(options) => {\n\n options.legend.clone()\n\n }\n\n SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(\n\n options,\n\n ) => options.semantic_tokens_options.legend.clone(),\n\n }\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 73, "score": 100908.4003179399 }, { "content": "fn classify_boundary_initial(\n\n prev: WordProperty,\n\n next: WordProperty,\n\n) -> WordBoundary {\n\n #[allow(clippy::match_single_binding)]\n\n match (prev, next) {\n\n // (Lf, Other) => Start,\n\n // (Other, Lf) => End,\n\n // (Lf, Space) => Interior,\n\n // (Lf, Punctuation) => Interior,\n\n // (Space, Lf) => Interior,\n\n // (Punctuation, Lf) => Interior,\n\n // (Space, Punctuation) => Interior,\n\n // (Punctuation, Space) => Interior,\n\n _ => classify_boundary(prev, next),\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq)]\n\npub enum WordProperty {\n\n Cr,\n\n Lf,\n\n Space,\n\n Punctuation,\n\n Other, // includes letters and all of non-ascii unicode\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 74, "score": 100908.4003179399 }, { "content": "pub fn lapce_internal_commands() -> IndexMap<String, LapceCommandNew> {\n\n let mut commands = IndexMap::new();\n\n\n\n for c in LapceWorkbenchCommand::iter() {\n\n let command = LapceCommandNew {\n\n cmd: c.to_string(),\n\n data: None,\n\n palette_desc: c.get_message().map(|m| m.to_string()),\n\n target: CommandTarget::Workbench,\n\n };\n\n commands.insert(command.cmd.clone(), command);\n\n }\n\n\n\n for c in LapceCommand::iter() {\n\n let command = LapceCommandNew {\n\n cmd: c.to_string(),\n\n data: None,\n\n palette_desc: c.get_message().map(|m| m.to_string()),\n\n target: CommandTarget::Focus,\n\n };\n", "file_path": "lapce-data/src/command.rs", "rank": 75, "score": 99537.33367942102 }, { "content": "pub fn new_search_panel(data: &LapceTabData) -> LapcePanel {\n\n let editor_data = data\n\n .main_split\n\n .editors\n\n .get(&data.search.editor_view_id)\n\n .unwrap();\n\n let input = LapceEditorView::new(editor_data.view_id, None)\n\n .hide_header()\n\n .hide_gutter()\n\n .padding((15.0, 15.0));\n\n let split = LapceSplitNew::new(data.search.split_id)\n\n .horizontal()\n\n .with_child(input.boxed(), None, 100.0)\n\n .with_flex_child(\n\n LapceScrollNew::new(SearchContent::new().boxed())\n\n .vertical()\n\n .boxed(),\n\n None,\n\n 1.0,\n\n );\n", "file_path": "lapce-ui/src/search.rs", "rank": 76, "score": 99537.33367942102 }, { "content": "pub fn symbol_svg_new(kind: &SymbolKind) -> Option<Svg> {\n\n let kind_str = match kind {\n\n SymbolKind::Array => \"array\",\n\n SymbolKind::Boolean => \"boolean\",\n\n SymbolKind::Class => \"class\",\n\n SymbolKind::Constant => \"constant\",\n\n SymbolKind::EnumMember => \"enum-member\",\n\n SymbolKind::Enum => \"enum\",\n\n SymbolKind::Event => \"event\",\n\n SymbolKind::Field => \"field\",\n\n SymbolKind::File => \"file\",\n\n SymbolKind::Interface => \"interface\",\n\n SymbolKind::Key => \"key\",\n\n SymbolKind::Function => \"method\",\n\n SymbolKind::Method => \"method\",\n\n SymbolKind::Object => \"namespace\",\n\n SymbolKind::Namespace => \"namespace\",\n\n SymbolKind::Number => \"numeric\",\n\n SymbolKind::Operator => \"operator\",\n\n SymbolKind::TypeParameter => \"parameter\",\n\n SymbolKind::Property => \"property\",\n\n SymbolKind::String => \"string\",\n\n SymbolKind::Struct => \"structure\",\n\n SymbolKind::Variable => \"variable\",\n\n _ => return None,\n\n };\n\n\n\n get_svg(&format!(\"symbol-{}.svg\", kind_str))\n\n}\n\n\n", "file_path": "lapce-ui/src/svg.rs", "rank": 77, "score": 99114.3711805071 }, { "content": "pub fn wasi_write_string(wasi_env: &WasiEnv, buf: &str) {\n\n let mut state = wasi_env.state();\n\n let wasi_file = state.fs.stdin_mut().unwrap().as_mut().unwrap();\n\n writeln!(wasi_file, \"{}\\r\", buf).unwrap();\n\n}\n\n\n", "file_path": "lapce-proxy/src/plugin.rs", "rank": 78, "score": 97193.39970265389 }, { "content": "pub fn wasi_read_string(wasi_env: &WasiEnv) -> Result<String> {\n\n let mut state = wasi_env.state();\n\n let wasi_file = state\n\n .fs\n\n .stdout_mut()?\n\n .as_mut()\n\n .ok_or_else(|| anyhow!(\"can't get stdout\"))?;\n\n let mut buf = String::new();\n\n wasi_file.read_to_string(&mut buf)?;\n\n Ok(buf)\n\n}\n\n\n", "file_path": "lapce-proxy/src/plugin.rs", "rank": 79, "score": 97193.39970265389 }, { "content": "pub fn new_source_control_panel(data: &LapceTabData) -> LapcePanel {\n\n let editor_data = data\n\n .main_split\n\n .editors\n\n .get(&data.source_control.editor_view_id)\n\n .unwrap();\n\n let input = LapceEditorView::new(editor_data.view_id, None)\n\n .hide_header()\n\n .hide_gutter()\n\n .set_placeholder(\"Commit Message\".to_string())\n\n .padding((15.0, 15.0));\n\n let content = SourceControlFileList::new(data.source_control.file_list_id);\n\n LapcePanel::new(\n\n PanelKind::SourceControl,\n\n data.source_control.widget_id,\n\n data.source_control.split_id,\n\n data.source_control.split_direction,\n\n PanelHeaderKind::Simple(\"Source Control\".to_string()),\n\n vec![\n\n (\n", "file_path": "lapce-ui/src/source_control.rs", "rank": 80, "score": 96022.52159316704 }, { "content": "fn get_workspace_edit_changes_edits<'a>(\n\n url: &Url,\n\n workspace_edit: &'a WorkspaceEdit,\n\n) -> Option<Vec<&'a TextEdit>> {\n\n let changes = workspace_edit.changes.as_ref()?;\n\n changes.get(url).map(|c| c.iter().collect())\n\n}\n\n\n", "file_path": "lapce-ui/src/editor.rs", "rank": 81, "score": 93855.36829801415 }, { "content": "fn get_workspace_edit_document_changes_edits<'a>(\n\n url: &Url,\n\n workspace_edit: &'a WorkspaceEdit,\n\n) -> Option<Vec<&'a TextEdit>> {\n\n let changes = workspace_edit.document_changes.as_ref()?;\n\n match changes {\n\n DocumentChanges::Edits(edits) => {\n\n for edit in edits {\n\n if &edit.text_document.uri == url {\n\n let e = edit\n\n .edits\n\n .iter()\n\n .filter_map(|e| match e {\n\n lsp_types::OneOf::Left(edit) => Some(edit),\n\n lsp_types::OneOf::Right(_) => None,\n\n })\n\n .collect();\n\n return Some(e);\n\n }\n\n }\n\n None\n\n }\n\n DocumentChanges::Operations(_) => None,\n\n }\n\n}\n\n\n", "file_path": "lapce-ui/src/editor.rs", "rank": 82, "score": 91358.40063680541 }, { "content": "pub fn remove_n_at<T>(v: &mut Vec<T>, index: usize, n: usize) {\n\n match n.cmp(&1) {\n\n Ordering::Equal => {\n\n v.remove(index);\n\n }\n\n Ordering::Greater => {\n\n v.drain(index..index + n);\n\n }\n\n _ => (),\n\n };\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::movement::Movement;\n\n\n\n #[test]\n\n fn test_wrapping() {\n\n // Move by 1 position\n\n // List length of 1\n", "file_path": "lapce-data/src/movement.rs", "rank": 83, "score": 90735.33571717053 }, { "content": "pub fn read_message<T: BufRead>(reader: &mut T) -> Result<String> {\n\n let mut buffer = String::new();\n\n let mut content_length: Option<usize> = None;\n\n\n\n loop {\n\n buffer.clear();\n\n let _result = reader.read_line(&mut buffer);\n\n // eprin\n\n match &buffer {\n\n s if s.trim().is_empty() => break,\n\n s => {\n\n match parse_header(s)? {\n\n LspHeader::ContentLength(len) => content_length = Some(len),\n\n LspHeader::ContentType => (),\n\n };\n\n }\n\n };\n\n }\n\n\n\n let content_length = content_length\n\n .ok_or_else(|| anyhow!(\"missing content-length header: {}\", buffer))?;\n\n\n\n let mut body_buffer = vec![0; content_length];\n\n reader.read_exact(&mut body_buffer)?;\n\n\n\n let body = String::from_utf8(body_buffer)?;\n\n Ok(body)\n\n}\n\n\n", "file_path": "lapce-proxy/src/lsp.rs", "rank": 84, "score": 89829.40327229636 }, { "content": "pub fn read_message<T: BufRead>(reader: &mut T) -> Result<String> {\n\n let mut buffer = String::new();\n\n let mut content_length: Option<usize> = None;\n\n\n\n loop {\n\n buffer.clear();\n\n let _result = reader.read_line(&mut buffer);\n\n // eprin\n\n match &buffer {\n\n s if s.trim().is_empty() => break,\n\n s => {\n\n match parse_header(s)? {\n\n LspHeader::ContentLength(len) => content_length = Some(len),\n\n LspHeader::ContentType => (),\n\n };\n\n }\n\n };\n\n }\n\n\n\n let content_length = content_length\n\n .ok_or_else(|| anyhow!(\"missing content-length header: {}\", buffer))?;\n\n\n\n let mut body_buffer = vec![0; content_length];\n\n reader.read_exact(&mut body_buffer)?;\n\n\n\n let body = String::from_utf8(body_buffer)?;\n\n Ok(body)\n\n}\n\n\n", "file_path": "lapce-data/src/lsp.rs", "rank": 85, "score": 89829.40327229636 }, { "content": "pub fn read_message<T: BufRead>(reader: &mut T) -> Result<String> {\n\n let mut buffer = String::new();\n\n let mut content_length: Option<usize> = None;\n\n\n\n loop {\n\n buffer.clear();\n\n let _result = reader.read_line(&mut buffer);\n\n // eprin\n\n match &buffer {\n\n s if s.trim().is_empty() => break,\n\n s => {\n\n match parse_header(s)? {\n\n LspHeader::ContentLength(len) => content_length = Some(len),\n\n LspHeader::ContentType => (),\n\n };\n\n }\n\n };\n\n }\n\n\n\n let content_length = content_length\n\n .ok_or_else(|| anyhow!(\"missing content-length header: {}\", buffer))?;\n\n\n\n let mut body_buffer = vec![0; content_length];\n\n reader.read_exact(&mut body_buffer)?;\n\n\n\n let body = String::from_utf8(body_buffer)?;\n\n Ok(body)\n\n}\n\n\n", "file_path": "lapce-ui/src/lsp.rs", "rank": 86, "score": 89829.40327229636 }, { "content": "pub fn wasi_read_object<T: DeserializeOwned>(wasi_env: &WasiEnv) -> Result<T> {\n\n let json = wasi_read_string(wasi_env)?;\n\n Ok(serde_json::from_str(&json)?)\n\n}\n\n\n", "file_path": "lapce-proxy/src/plugin.rs", "rank": 87, "score": 88157.99923206857 }, { "content": "fn str_matching_pair(c: &str) -> Option<char> {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n return matching_char(c);\n\n }\n\n None\n\n}\n\n\n", "file_path": "lapce-data/src/editor.rs", "rank": 88, "score": 87192.24563442299 }, { "content": "#[allow(dead_code)]\n\nfn str_matching_pair(c: &str) -> Option<char> {\n\n if c.chars().count() == 1 {\n\n let c = c.chars().next().unwrap();\n\n return matching_char(c);\n\n }\n\n None\n\n}\n\n\n", "file_path": "lapce-data/src/data.rs", "rank": 89, "score": 87192.24563442299 }, { "content": "fn html_escape(c: u8) -> Option<&'static [u8]> {\n\n match c as char {\n\n '>' => Some(b\"&gt;\"),\n\n '<' => Some(b\"&lt;\"),\n\n '&' => Some(b\"&amp;\"),\n\n '\\'' => Some(b\"&#39;\"),\n\n '\"' => Some(b\"&quot;\"),\n\n _ => None,\n\n }\n\n}\n", "file_path": "lapce-core/src/style.rs", "rank": 90, "score": 86041.79860144964 }, { "content": "fn outdent_one_line<'s, 'b, L: BufferDataListener>(\n\n buffer: &EditableBufferData<'b, L>,\n\n offset: usize,\n\n indent: &'s str,\n\n tab_width: usize,\n\n) -> Option<(Selection, &'s str)> {\n\n let (_, col) = buffer.offset_to_line_col(offset, tab_width);\n\n if col == 0 {\n\n return None;\n\n }\n\n\n\n let start = if indent.starts_with('\\t') {\n\n offset - 1\n\n } else {\n\n let r = col % indent.len();\n\n let r = if r == 0 { indent.len() } else { r };\n\n offset - r\n\n };\n\n\n\n Some((Selection::region(start, offset), \"\"))\n", "file_path": "lapce-data/src/editor/commands/outdent_line.rs", "rank": 91, "score": 78398.86857618744 }, { "content": "fn indent_one_line<'s, 'b, L: BufferDataListener>(\n\n buffer: &EditableBufferData<'b, L>,\n\n offset: usize,\n\n indent: &'s str,\n\n tab_width: usize,\n\n) -> Option<(Selection, &'s str)> {\n\n Some(indentation::create_edit(buffer, offset, indent, tab_width))\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::editor::commands::{test::MockEditor, EditCommandKind};\n\n\n\n #[test]\n\n fn indent_single_line() {\n\n let mut editor = MockEditor::new(\"line\\n<$0>foo</$0>\\nthird line\");\n\n\n\n editor.command(EditCommandKind::IndentLine { selection: None });\n\n\n\n assert_eq!(\"line\\n <$0>foo</$0>\\nthird line\", editor.state());\n", "file_path": "lapce-data/src/editor/commands/indent_line.rs", "rank": 92, "score": 78398.86857618744 }, { "content": "fn shrink_and_clear<T>(vec: &mut Vec<T>, capacity: usize) {\n\n if vec.len() > capacity {\n\n vec.truncate(capacity);\n\n vec.shrink_to_fit();\n\n }\n\n vec.clear();\n\n}\n\n\n", "file_path": "lapce-core/src/style.rs", "rank": 93, "score": 77755.93551024943 }, { "content": "fn classify_boundary(prev: WordProperty, next: WordProperty) -> WordBoundary {\n\n use self::WordBoundary::*;\n\n use self::WordProperty::*;\n\n match (prev, next) {\n\n (Lf, Lf) => Start,\n\n (Lf, Space) => Interior,\n\n (Cr, Lf) => Interior,\n\n (Space, Lf) => Interior,\n\n (Space, Cr) => Interior,\n\n (Space, Space) => Interior,\n\n (_, Space) => End,\n\n (Space, _) => Start,\n\n (Lf, _) => Start,\n\n (_, Cr) => End,\n\n (_, Lf) => End,\n\n (Punctuation, Other) => Both,\n\n (Other, Punctuation) => Both,\n\n _ => Interior,\n\n }\n\n}\n\n\n", "file_path": "lapce-data/src/buffer.rs", "rank": 94, "score": 77358.15572402741 }, { "content": "#[allow(dead_code)]\n\nfn iter_diff<I, T>(left: I, right: I) -> Vec<DiffResult<T>>\n\nwhere\n\n I: Clone + Iterator<Item = T> + DoubleEndedIterator,\n\n T: PartialEq,\n\n{\n\n let left_count = left.clone().count();\n\n let right_count = right.clone().count();\n\n let min_count = cmp::min(left_count, right_count);\n\n\n\n let leading_equals = left\n\n .clone()\n\n .zip(right.clone())\n\n .take_while(|p| p.0 == p.1)\n\n .count();\n\n let trailing_equals = left\n\n .clone()\n\n .rev()\n\n .zip(right.clone().rev())\n\n .take(min_count - leading_equals)\n\n .take_while(|p| p.0 == p.1)\n", "file_path": "lapce-data/src/buffer.rs", "rank": 95, "score": 76147.52120769903 }, { "content": "struct Writing {\n\n source: Cow<'static, [u8]>,\n\n written: usize,\n\n}\n\n\n\nimpl Writing {\n\n #[inline]\n\n fn new(c: Cow<'static, [u8]>) -> Writing {\n\n Writing {\n\n source: c,\n\n written: 0,\n\n }\n\n }\n\n\n\n #[inline]\n\n fn advance(&mut self, n: usize) {\n\n self.written += n;\n\n }\n\n\n\n #[inline]\n", "file_path": "lapce-proxy/src/terminal.rs", "rank": 96, "score": 73764.9568270382 }, { "content": "struct SshRemote {\n\n user: String,\n\n host: String,\n\n}\n\n\n\nimpl SshRemote {\n\n #[cfg(target_os = \"windows\")]\n\n const SSH_ARGS: &'static [&'static str] = &[\"-o\", \"ConnectTimeout=15\"];\n\n\n\n #[cfg(not(target_os = \"windows\"))]\n\n const SSH_ARGS: &'static [&'static str] = &[\n\n \"-o\",\n\n \"ControlMaster=auto\",\n\n \"-o\",\n\n \"ControlPath=~/.ssh/cm-%r@%h:%p\",\n\n \"-o\",\n\n \"ControlPersist=30m\",\n\n \"-o\",\n\n \"ConnectTimeout=15\",\n\n ];\n", "file_path": "lapce-data/src/proxy.rs", "rank": 97, "score": 72075.46552764322 }, { "content": "#[derive(Debug)]\n\nstruct WslDistro {\n\n pub name: String,\n\n pub default: bool,\n\n}\n\n\n\nimpl WslDistro {\n\n fn all() -> Result<Vec<WslDistro>> {\n\n let cmd = new_command(\"wsl\")\n\n .arg(\"-l\")\n\n .arg(\"-v\")\n\n .stdout(Stdio::piped())\n\n .output()?;\n\n\n\n if !cmd.status.success() {\n\n return Err(anyhow!(\"failed to execute `wsl -l -v`\"));\n\n }\n\n\n\n let distros = String::from_utf16(bytemuck::cast_slice(&cmd.stdout))?\n\n .lines()\n\n .skip(1)\n", "file_path": "lapce-data/src/proxy.rs", "rank": 98, "score": 72075.46552764322 } ]
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(field) => match (field.as_str(), val) {\n\n (\"uuid\", Value::String(uuid)) => Ok(Record::Int(parse_uuid(uuid.as_ref())?)),\n\n (\"named-uuid\", Value::String(uuid_name)) => Ok(Record::String(uuid_name)),\n\n (\"set\", Value::Array(atoms)) => {\n\n let elems: Result<Vec<Record>, String> =\n\n atoms.into_iter().map(record_from_val).collect();\n\n Ok(Record::Array(CollectionKind::Set, elems?))\n\n }\n\n (\"map\", Value::Array(pairs)) => {\n\n let elems: Result<Vec<(Record, Record)>, String> =\n\n pairs.into_iter().map(pair_from_val).collect();\n\n Ok(Record::Array(\n\n CollectionKind::Map,\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 0, "score": 459457.4597070372 }, { "content": "pub fn record_insert_or_update<V>(writer: &mut dyn Write, name: &str, value: V) -> IOResult<()>\n\nwhere\n\n V: Display,\n\n{\n\n write!(writer, \"insert_or_update {}[{}]\", name, value)\n\n}\n\n\n\nimpl<W, I> CommandRecorder<W, I>\n\nwhere\n\n W: Write,\n\n I: Deref<Target = dyn DDlogInventory + Send + Sync>,\n\n{\n\n fn do_record_updates<It, U, F>(&self, updates: It, mut record: F) -> Result<(), String>\n\n where\n\n W: Write,\n\n It: Iterator<Item = U>,\n\n F: FnMut(&dyn DDlogInventory, &mut W, &U) -> IOResult<()>,\n\n {\n\n let mut writer = self.writer.lock().unwrap();\n\n let inventory = &*self.inventory;\n", "file_path": "rust/template/differential_datalog/src/replay.rs", "rank": 1, "score": 448454.10994034266 }, { "content": "fn row_from_obj(val: Value) -> Result<Vec<(Name, Record)>, String> {\n\n match val {\n\n Value::Object(m) => m\n\n .into_iter()\n\n .map(|(field, val)| Ok((Cow::from(field), record_from_val(val)?)))\n\n .collect(),\n\n _ => Err(format!(\"\\\"row\\\" is not an object in {}\", val)),\n\n }\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 2, "score": 446576.9956466523 }, { "content": "fn record_from_val(v: Value) -> Result<Record, String> {\n\n match v {\n\n // <string>\n\n Value::String(s) => Ok(Record::String(s)),\n\n // <number>\n\n Value::Number(ref n) if n.is_u64() => Ok(Record::Int(BigInt::from(n.as_u64().unwrap()))),\n\n // <boolean>\n\n Value::Bool(b) => Ok(Record::Bool(b)),\n\n // <uuid>, <named-uuid>, <set>, <map>\n\n Value::Array(v) => record_from_array(v),\n\n _ => Err(format!(\"unexpected value {}\", v)),\n\n }\n\n}\n\n\n\n/*\n\n * Functions to convert DDlog Records to JSON\n\n */\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 3, "score": 416201.1721796088 }, { "content": "fn run(hddlog: HDDlog, print_deltas: bool) -> Result<(), String> {\n\n let upds = Arc::new(Mutex::new(Vec::new()));\n\n let start_time = Instant::now();\n\n interact(|cmd, interactive| {\n\n handle_cmd(\n\n start_time,\n\n &hddlog,\n\n print_deltas,\n\n interactive,\n\n &mut upds.lock().unwrap(),\n\n cmd,\n\n )\n\n })?;\n\n\n\n hddlog.stop()\n\n}\n\n\n", "file_path": "rust/template/src/main.rs", "rank": 5, "score": 412822.1522906051 }, { "content": "pub fn record_insert<V>(writer: &mut dyn Write, name: &str, value: V) -> IOResult<()>\n\nwhere\n\n V: Display,\n\n{\n\n write!(writer, \"insert {}[{}]\", name, value)\n\n}\n\n\n", "file_path": "rust/template/differential_datalog/src/replay.rs", "rank": 6, "score": 410641.67512379866 }, { "content": "fn apply_updates(hddlog: &HDDlog, upds: &mut Vec<Update<DDValue>>) -> Response<()> {\n\n if !upds.is_empty() {\n\n hddlog.apply_updates(&mut upds.drain(..))\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "rust/template/src/main.rs", "rank": 7, "score": 398893.62682555744 }, { "content": "fn into_insert_str(prog: &HDDlog, table: *const c_char, rec: &Record) -> Result<CString, String> {\n\n let table_str: &str = unsafe { CStr::from_ptr(table) }\n\n .to_str()\n\n .map_err(|e| format!(\"{}\", e))?;\n\n record_into_insert_str(rec.clone(), table_str)\n\n .map(|s| unsafe { CString::from_vec_unchecked(s.into_bytes()) })\n\n}\n\n\n\n#[no_mangle]\n\npub unsafe extern \"C\" fn ddlog_into_osvdb_delete_str(\n\n prog: *const HDDlog,\n\n table: *const c_char,\n\n rec: *const Record,\n\n json: *mut *mut c_char,\n\n) -> c_int {\n\n if prog.is_null() || table.is_null() {\n\n return -1;\n\n };\n\n let rec = match rec.as_ref() {\n\n Some(record) => record,\n", "file_path": "rust/template/src/ovsdb_api.rs", "rank": 8, "score": 385267.4621546023 }, { "content": "fn into_update_str(prog: &HDDlog, table: *const c_char, rec: &Record) -> Result<CString, String> {\n\n let table_str: &str = unsafe { CStr::from_ptr(table) }\n\n .to_str()\n\n .map_err(|e| format!(\"{}\", e))?;\n\n record_into_update_str(rec.clone(), table_str)\n\n .map(|s| unsafe { CString::from_vec_unchecked(s.into_bytes()) })\n\n}\n\n\n\n#[no_mangle]\n\npub unsafe extern \"C\" fn ddlog_dump_ovsdb_output_table(\n\n prog: *const HDDlog,\n\n delta: *const DeltaMap<DDValue>,\n\n module: *const c_char,\n\n table: *const c_char,\n\n json: *mut *mut c_char,\n\n) -> c_int {\n\n if json.is_null() || prog.is_null() || delta.is_null() || module.is_null() || table.is_null() {\n\n return -1;\n\n };\n\n let prog = sync::Arc::from_raw(prog);\n", "file_path": "rust/template/src/ovsdb_api.rs", "rank": 9, "score": 385200.5661402745 }, { "content": "fn pair_from_val(pair: Value) -> Result<(Record, Record), String> {\n\n match pair {\n\n Value::Array(mut v) => {\n\n if v.len() != 2 {\n\n return Err(format!(\"key-value pair must be of length 2: {:?}\", v));\n\n };\n\n let val = v.remove(1);\n\n let key = v.remove(0);\n\n Ok((record_from_val(key)?, record_from_val(val)?))\n\n }\n\n _ => Err(format!(\"invalid key-value pair {}\", pair)),\n\n }\n\n}\n\n\n\n/*\n\n {\n\n \"interfaces\": [ \"named-uuid\", \"rowe82c26a4_bbf4_4e84_87fd_2107d5998a12\"],\n\n \"name\": \"br0\"\n\n }\n\n*/\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 10, "score": 382642.33171008877 }, { "content": "#[allow(clippy::redundant_closure)]\n\nfn main() -> Result<(), String> {\n\n let parser = opts! {\n\n synopsis \"DDlog CLI interface.\";\n\n auto_shorts false;\n\n opt store:bool=true, desc:\"Do not store output relation state. 'dump' and 'dump <table>' commands will produce no output.\"; // --no-store\n\n opt delta:bool=true, desc:\"Do not record changes. 'commit dump_changes' will produce no output.\"; // --no-delta\n\n opt init_snapshot:bool=true, desc:\"Do not dump initial output snapshot.\"; // --no-init-snapshot\n\n opt print:bool=true, desc:\"Backwards compatibility. The value of this flag is ignored.\"; // --no-print\n\n opt workers:usize=1, short:'w', desc:\"The number of worker threads. Default is 1.\"; // --workers or -w\n\n opt idle_merge_effort:Option<isize>, desc:\"Set Differential Dataflow's 'idle_merge_effort' parameter. This flag takes precedence over the '$DIFFERENTIAL_EAGER_MERGE' environment variable.\";\n\n opt profile_timely:bool=false, desc:\"Use external Timely Dataflow profiler.\";\n\n opt profile_differential:bool=false, desc:\"Use external Differential Dataflow profiler. Implies '--profile-timely'\";\n\n opt self_profiler:bool, desc:\"Enable DDlog internal profiler. This option is mutually exclusive with '--profile-timely'.\";\n\n opt timely_profiler_socket:Option<String>, desc:\"Socket address to send Timely Dataflow profiling events. Default (if '--profile-timely' is specified) is '127.0.0.1:51317'. Implies '--profile-timely'.\";\n\n opt timely_trace_dir:Option<String>, desc:\"Path to a directory to store Timely Dataflow profiling events, e.g., './timely_trace'. Implies '--profile-timely'.\";\n\n opt differential_profiler_socket:Option<String>, desc:\"Socket address to send Differential Dataflow profiling events. Default (if '--profile-differential' is specified is '127.0.0.1:51318'. Implies '--profile-differential'.\";\n\n opt differential_trace_dir:Option<String>, desc:\"Path to a directory to store Differential Dataflow profiling events, e.g., './differential_trace'. Implies '--profile-differential'.\";\n\n opt ddshow:bool=false, desc:\"Start 'ddshow' profiler on sockets specified by '--timely-profiler-socket' and (optionally) '--differential-profiler-socket' options. Implies '--timely-profiler'.\";\n\n };\n\n let (mut args, rest) = parser.parse_or_exit();\n", "file_path": "rust/template/src/main.rs", "rank": 11, "score": 377881.05400264356 }, { "content": "fn struct_into_obj(fields: Vec<(Name, Record)>) -> Result<Value, String> {\n\n let fields: Result<Map<String, Value>, String> = fields\n\n .into_iter()\n\n .filter(|(f, _)| f != \"uuid_name\" && f != \"_uuid\")\n\n .map(|(f, v)| record_into_field(v).map(|fld| (field_name(f), fld)))\n\n .collect();\n\n Ok(Value::Object(fields?))\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 12, "score": 371668.04367217503 }, { "content": "pub fn record_into_insert_str(rec: Record, table: &str) -> Result<String, String> {\n\n let opt_uuid_name = match rec {\n\n Record::NamedStruct(_, ref fields) => fields\n\n .iter()\n\n .find(|(f, _)| f == \"uuid_name\")\n\n .map(|(_, val)| val.clone()),\n\n _ => {\n\n return Err(format!(\n\n \"Cannot convert record to insert command: {:?}\",\n\n rec\n\n ))\n\n }\n\n };\n\n let opt_uuid = match rec {\n\n Record::NamedStruct(_, ref fields) => fields\n\n .iter()\n\n .find(|(f, _)| f == \"_uuid\")\n\n .map(|(_, val)| val.clone()),\n\n _ => {\n\n return Err(format!(\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 13, "score": 370362.84814707236 }, { "content": "pub fn record_into_update_str(rec: Record, table: &str) -> Result<String, String> {\n\n let uuid = match rec {\n\n Record::NamedStruct(_, ref fields) => fields\n\n .iter()\n\n .find(|(f, _)| f == \"_uuid\")\n\n .ok_or_else(|| \"Record does not have _uuid field\".to_string())?\n\n .1\n\n .clone(),\n\n _ => {\n\n return Err(format!(\n\n \"Cannot convert record to update command: {:?}\",\n\n rec\n\n ))\n\n }\n\n };\n\n let mut m = Map::new();\n\n m.insert(\"op\".to_owned(), Value::String(\"update\".to_owned()));\n\n m.insert(\"table\".to_owned(), Value::String(table.to_owned()));\n\n m.insert(\"where\".to_owned(), uuid_condition(&uuid)?);\n\n m.insert(\"row\".to_owned(), record_into_row(rec)?);\n\n Ok(Value::Object(m).to_string())\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 14, "score": 370291.53439809737 }, { "content": "pub fn record_delete<V>(writer: &mut dyn Write, name: &str, value: V) -> IOResult<()>\n\nwhere\n\n V: Display,\n\n{\n\n write!(writer, \"delete {}[{}]\", name, value)\n\n}\n\n\n", "file_path": "rust/template/differential_datalog/src/replay.rs", "rank": 15, "score": 367700.174479467 }, { "content": "pub fn decode(s: &String) -> ddlog_std::Result<ddlog_std::Vec<u8>, String> {\n\n match b64decode(s) {\n\n Ok(r) => ddlog_std::Result::Ok {\n\n res: ddlog_std::Vec::from(r),\n\n },\n\n Err(e) => match (e) {\n\n b64DecodeError::InvalidByte(p, b) => ddlog_std::Result::Err {\n\n err: format!(\"Invalid byte {} at position {}\", b, p),\n\n },\n\n b64DecodeError::InvalidLength => ddlog_std::Result::Err {\n\n err: format!(\"Invalid length\"),\n\n },\n\n b64DecodeError::InvalidLastSymbol(p, b) => ddlog_std::Result::Err {\n\n err: format!(\"Invalid last byte {} at position {}\", b, p),\n\n },\n\n },\n\n }\n\n}\n", "file_path": "lib/base64.rs", "rank": 16, "score": 367534.76395441557 }, { "content": "/// Add a trait bound to every generic, skipping the addition if the generic\n\n/// already has the required trait bound\n\nfn add_trait_bounds(mut generics: Generics, bounds: Vec<TypeParamBound>) -> Generics {\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(ref mut type_param) = *param {\n\n for bound in bounds.iter() {\n\n if !type_param\n\n .bounds\n\n .iter()\n\n .any(|type_bound| type_bound == bound)\n\n {\n\n type_param.bounds.push(bound.clone());\n\n }\n\n }\n\n }\n\n }\n\n\n\n generics\n\n}\n\n\n", "file_path": "rust/template/ddlog_derive/src/lib.rs", "rank": 17, "score": 361418.10054390796 }, { "content": "pub fn mutator_inner(mut input: DeriveInput) -> Result<TokenStream> {\n\n // The name of the struct\n\n let struct_ident = input.ident;\n\n\n\n // Make sure every generic is able to be mutated by `Record`\n\n // The redundant clone circumvents mutating the collection we're iterating over\n\n #[allow(clippy::redundant_clone)]\n\n for generic in input\n\n .generics\n\n .clone()\n\n .type_params()\n\n .map(|param| &param.ident)\n\n {\n\n input\n\n .generics\n\n .make_where_clause()\n\n .predicates\n\n .push(parse_quote! {\n\n ::differential_datalog::record::Record: ::differential_datalog::record::Mutator<#generic>\n\n });\n", "file_path": "rust/template/ddlog_derive/src/mutator.rs", "rank": 19, "score": 351297.0628972444 }, { "content": "pub fn into_record_inner(input: DeriveInput) -> Result<TokenStream> {\n\n // The name of the struct\n\n let struct_ident = input.ident;\n\n\n\n // Use the given rename provided by `#[ddlog(rename = \"...\")]` or `#[ddlog(into_record = \"...\")]`\n\n // as the name of the record, defaulting to the struct's ident if none is given\n\n let struct_record_name = get_rename(\"IntoRecord\", \"into_record\", input.attrs.iter())?\n\n .unwrap_or_else(|| struct_ident.to_string());\n\n\n\n // Add the required trait bounds\n\n let generics = add_trait_bounds(\n\n input.generics,\n\n vec![\n\n parse_quote!(::differential_datalog::record::IntoRecord),\n\n parse_quote!(::core::clone::Clone),\n\n ],\n\n );\n\n let generics = generics.split_for_impl();\n\n\n\n match input.data {\n", "file_path": "rust/template/ddlog_derive/src/into_record.rs", "rank": 20, "score": 345110.1648184633 }, { "content": "pub fn from_record_inner(input: DeriveInput) -> Result<TokenStream> {\n\n // The name of the struct\n\n let struct_ident = input.ident;\n\n\n\n // Use the given rename provided by `#[ddlog(rename = \"...\")]` or `#[ddlog(from_record = \"...\")]`\n\n // as the name of the record, defaulting to the struct's ident if none is given\n\n let struct_record_name = get_rename(\"FromRecord\", \"from_record\", input.attrs.iter())?\n\n .unwrap_or_else(|| struct_ident.to_string());\n\n\n\n // Add the required trait bounds\n\n let generics = add_trait_bounds(\n\n input.generics,\n\n vec![\n\n parse_quote!(::differential_datalog::record::FromRecord),\n\n parse_quote!(::core::marker::Sized),\n\n parse_quote!(::core::default::Default),\n\n parse_quote!(serde::de::DeserializeOwned),\n\n ],\n\n );\n\n let generics = generics.split_for_impl();\n", "file_path": "rust/template/ddlog_derive/src/from_record.rs", "rank": 21, "score": 345110.1648184633 }, { "content": "pub fn from_utf8(v: &[u8]) -> Result<String, String> {\n\n res2std(str::from_utf8(v).map(|s| s.to_string()))\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 22, "score": 340165.1147791442 }, { "content": "pub fn from_utf16(v: &[u16]) -> Result<String, String> {\n\n res2std(String::from_utf16(v).map(|s| s.to_string()))\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 23, "score": 340165.1147791442 }, { "content": "pub fn vec_truncate<T>(vec: &mut Vec<T>, new_len: &std_usize) {\n\n vec.vec.truncate(*new_len as usize)\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 24, "score": 335685.05934248166 }, { "content": "fn record_into_field(rec: Record) -> Result<Value, String> {\n\n match rec {\n\n Record::Bool(b) => Ok(Value::Bool(b)),\n\n Record::String(s) => Ok(Value::String(s)),\n\n Record::Int(i) => {\n\n if i.is_positive() {\n\n match i.to_u64() {\n\n Some(v) => Ok(Value::Number(Number::from(v))),\n\n None => {\n\n let uuid = uuid_from_int(&i)?;\n\n Ok(Value::Array(vec![\n\n Value::String(\"uuid\".to_owned()),\n\n Value::String(uuid),\n\n ]))\n\n }\n\n }\n\n } else {\n\n i.to_i64()\n\n .ok_or_else(|| format!(\"Cannot convert BigInt {} to i64\", i))\n\n .map(|x| Value::Number(Number::from(x)))\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 25, "score": 331539.3047744285 }, { "content": "fn record_into_row(rec: Record) -> Result<Value, String> {\n\n match rec {\n\n Record::NamedStruct(_, fields) => struct_into_obj(fields),\n\n _ => Err(format!(\"Cannot convert record to <row>: {:?}\", rec)),\n\n }\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 26, "score": 331539.3047744285 }, { "content": "pub fn map_insert<K: Ord, V>(m: &mut Map<K, V>, k: K, v: V) {\n\n m.x.insert(k, v);\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 27, "score": 331022.1070159289 }, { "content": "pub fn record_into_delete_str(rec: Record, table: &str) -> Result<String, String> {\n\n let uuid = match rec {\n\n Record::NamedStruct(_, fields) => {\n\n fields\n\n .into_iter()\n\n .find(|(f, _)| f == \"_uuid\")\n\n .ok_or_else(|| \"Record does not have _uuid field\".to_string())?\n\n .1\n\n }\n\n _ => {\n\n return Err(format!(\n\n \"Cannot convert record to delete command: {:?}\",\n\n rec\n\n ))\n\n }\n\n };\n\n let mut m = Map::new();\n\n m.insert(\"op\".to_owned(), Value::String(\"delete\".to_owned()));\n\n m.insert(\"table\".to_owned(), Value::String(table.to_owned()));\n\n m.insert(\"where\".to_owned(), uuid_condition(&uuid)?);\n\n Ok(Value::Object(m).to_string())\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 28, "score": 323876.58932274685 }, { "content": "fn handler(command: Command, interactive: bool) -> (Result<(), String>, bool) {\n\n match command {\n\n Command::Exit => (Ok(()), false),\n\n _ => (Err(\"unexpected command\".to_string()), interactive),\n\n }\n\n}\n\n\n", "file_path": "rust/template/tests/interact_exit.rs", "rank": 29, "score": 323855.1808187296 }, { "content": "pub fn string_split(string: &String, sep: &String) -> Vec<String> {\n\n Vec {\n\n vec: string.split(sep).map(|x| x.to_owned()).collect(),\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 30, "score": 321145.0164013383 }, { "content": "fn handler(command: Command, interactive: bool) -> (Result<(), String>, bool) {\n\n match command {\n\n // We return `true` (\"continue\") on this path and verify that we\n\n // actually hit the exit command (i.e., we don't exit when\n\n // returning an error.\n\n Command::Dump(_) => (Err(\"unexpected dump command\".to_string()), true),\n\n Command::Exit => (Ok(()), false),\n\n _ => (Err(\"unexpected command\".to_string()), interactive),\n\n }\n\n}\n\n\n", "file_path": "rust/template/tests/interact_dump_error.rs", "rank": 31, "score": 320798.62880666746 }, { "content": "fn handler(command: Command, interactive: bool) -> (Result<(), String>, bool) {\n\n match command {\n\n Command::Clear(_) => (Err(\"unexpected clear command\".to_string()), true),\n\n Command::Exit => (Ok(()), false),\n\n _ => (Err(\"unexpected command\".to_string()), interactive),\n\n }\n\n}\n\n\n", "file_path": "rust/template/tests/interact_clear_error.rs", "rank": 32, "score": 320798.62880666746 }, { "content": "fn uuid_condition(uuid: &Record) -> Result<Value, String> {\n\n match uuid {\n\n Record::Int(uuid) => Ok(Value::Array(vec![Value::Array(vec![\n\n Value::String(\"_uuid\".to_owned()),\n\n Value::String(\"==\".to_owned()),\n\n Value::Array(vec![\n\n Value::String(\"uuid\".to_owned()),\n\n Value::String(uuid_from_int(uuid)?),\n\n ]),\n\n ])])),\n\n x => Err(format!(\"invalid uuid value {:?}\", x)),\n\n }\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 33, "score": 318946.0306695917 }, { "content": "pub fn map_insert_imm<K: Ord, V>(mut m: Map<K, V>, k: K, v: V) -> Map<K, V> {\n\n m.insert(k, v);\n\n m\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 34, "score": 318286.0166809076 }, { "content": "pub fn _from_json_value<T: DeserializeOwned>(val: JsonValue) -> ddlog_std::Result<T, String> {\n\n res2std(serde_json::from_value(serde_json::value::Value::from(val)))\n\n}\n\n\n", "file_path": "lib/json.rs", "rank": 35, "score": 318269.0387301324 }, { "content": "pub fn cmds_from_table_updates_str(prefix: &str, s: &str) -> Result<Vec<UpdCmd>, String> {\n\n if let Value::Object(json_val) = serde_json::from_str(s).map_err(|e| e.to_string())? {\n\n cmds_from_table_updates(prefix, json_val)\n\n } else {\n\n Err(format!(\"JSON value is not an object: {}\", s))\n\n }\n\n}\n\n\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 36, "score": 318139.98945508315 }, { "content": "pub fn string_join(strings: &Vec<String>, sep: &String) -> String {\n\n strings.join(sep.as_str())\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 37, "score": 315796.588832713 }, { "content": "#[allow(clippy::ptr_arg)]\n\npub fn string_append(mut s1: String, s2: &String) -> String {\n\n s1.push_str(s2.as_str());\n\n s1\n\n}\n\n\n\n/// Used to implement fields with `deserialize_from_array` attribute.\n\n/// Generates a module with `serialize` and `deserialize` methods.\n\n/// Takes the name of the module to generate, key type (`ktype`),\n\n/// value type (`vtype`), and a function that extracts key from array\n\n/// element of type `vtype`.\n\n///\n\n/// Example:\n\n/// ```\n\n/// ddlog_rt::deserialize_map_from_array!(__serdejson_test_StructWithMap_f,u64,StructWithKey,key_structWithKey);\n\n/// ````\n\n#[macro_export]\n\nmacro_rules! deserialize_map_from_array {\n\n ( $modname:ident, $ktype:ty, $vtype:ty, $kfunc:path ) => {\n\n mod $modname {\n\n use super::*;\n", "file_path": "lib/ddlog_rt.rs", "rank": 38, "score": 313628.4662454638 }, { "content": "pub fn vec_resize<T: Clone>(vec: &mut Vec<T>, new_len: &std_usize, value: &T) {\n\n vec.resize(*new_len as usize, value)\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 39, "score": 313505.8035325996 }, { "content": "pub fn vec_update_nth<T>(vec: &mut Vec<T>, idx: &std_usize, value: T) -> bool {\n\n if (*idx as usize) < vec.len() {\n\n vec[*idx as usize] = value;\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 40, "score": 313442.5961482056 }, { "content": "pub fn vec_reverse<X: Clone>(v: &mut Vec<X>) {\n\n v.reverse();\n\n}\n\n\n\n// Set\n\n\n\n#[derive(Eq, Ord, Clone, Hash, PartialEq, PartialOrd, Default)]\n\npub struct Set<T: Ord> {\n\n pub x: BTreeSet<T>,\n\n}\n\n\n\nimpl<T: Ord + Serialize> Serialize for Set<T> {\n\n fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n self.x.serialize(serializer)\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 41, "score": 313363.68647786486 }, { "content": "pub fn string_to_bytes(s: &String) -> Vec<u8> {\n\n Vec::from(s.as_bytes())\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 42, "score": 304241.38374504296 }, { "content": "/// Use the given rename provided by `#[ddlog(rename = \"...\")]` or `#[ddlog(into_record = \"...\")]`\n\n/// as the name of the variant, defaulting to the variant's ident if none is given\n\nfn rename_variant<'a, I>(ident: &Ident, record_name: &str, attrs: I) -> Result<String>\n\nwhere\n\n I: Iterator<Item = &'a Attribute> + 'a,\n\n{\n\n Ok(get_rename(\"IntoRecord\", \"into_record\", attrs)?\n\n .unwrap_or_else(|| format!(\"{}::{}\", record_name, ident)))\n\n}\n\n\n", "file_path": "rust/template/ddlog_derive/src/into_record.rs", "rank": 43, "score": 303529.69209063845 }, { "content": "pub fn vec_sort<T: Ord>(vec: &mut Vec<T>) {\n\n vec.as_mut_slice().sort();\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 44, "score": 302781.7986747426 }, { "content": "pub fn string2time(s: &String) -> ddlog_std::Result<Time, String> {\n\n time_parse(s, &default_time_format.to_string())\n\n}\n\n\n\nimpl FromRecordInner for Time {\n\n fn from_record_inner(val: &record::Record) -> ::std::result::Result<Self, String> {\n\n match (val) {\n\n record::Record::String(s) => {\n\n match (::chrono::NaiveTime::parse_from_str(s, &default_time_format.to_string())) {\n\n Ok(t) => Ok(TimeWrapper { val: t }),\n\n Err(e) => Err(format!(\"{}\", e)),\n\n }\n\n }\n\n _ => Err(String::from(\"Unexpected type\")),\n\n }\n\n }\n\n}\n\n\n\nimpl IntoRecord for Time {\n\n fn into_record(self) -> record::Record {\n", "file_path": "lib/time.rs", "rank": 45, "score": 302652.069718819 }, { "content": "pub fn string2date(s: &String) -> ddlog_std::Result<Date, String> {\n\n date_parse(s, &default_date_format.to_string())\n\n}\n\n\n\nimpl IntoRecord for Date {\n\n fn into_record(self) -> record::Record {\n\n record::Record::String(date2string(&self))\n\n }\n\n}\n\n\n\nimpl record::Mutator<Date> for record::Record {\n\n fn mutate(&self, t: &mut Date) -> ::std::result::Result<(), String> {\n\n *t = Date::from_record(self)?;\n\n Ok(())\n\n }\n\n}\n\n\n\n//////////////////////////////////////// DateTime //////////////////////////////////////\n\n\n\nconst defaultDateTimeFormat: &str = \"%Y-%m-%dT%T\";\n\n\n", "file_path": "lib/time.rs", "rank": 46, "score": 302652.069718819 }, { "content": "pub fn run(ddlog: HDDlog, dataset: Vec<Update<DDValue>>) -> HDDlog {\n\n ddlog\n\n .transaction_start()\n\n .expect(\"failed to start transaction\");\n\n ddlog\n\n .apply_updates(&mut dataset.into_iter())\n\n .expect(\"failed to give transaction input\");\n\n ddlog\n\n .transaction_commit()\n\n .expect(\"failed to commit transaction\");\n\n\n\n ddlog\n\n}\n", "file_path": "rust/ddlog_benches/src/lib.rs", "rank": 47, "score": 301443.5459986273 }, { "content": "pub fn string2datetime(s: &String) -> ddlog_std::Result<DateTime, String> {\n\n datetime_parse(s, &String::from(defaultDateTimeFormat))\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 48, "score": 299356.7205065134 }, { "content": "pub fn url_parse(s: &String) -> ddlog_std::Result<Url, String> {\n\n match ::url::Url::parse(s) {\n\n Ok(url) => ddlog_std::Result::Ok { res: Url { url } },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/url.rs", "rank": 49, "score": 299356.7205065134 }, { "content": "/// Use in generated Rust code to implement string concatenation (`++`)\n\npub fn string_append_str(mut s1: String, s2: &str) -> String {\n\n s1.push_str(s2);\n\n s1\n\n}\n\n\n\n/// Use in generated Rust code to implement string concatenation (`++`)\n", "file_path": "lib/ddlog_rt.rs", "rank": 50, "score": 299247.22856095736 }, { "content": "pub fn group_to_vec<K, V: Ord + Clone>(g: &Group<K, V>) -> Vec<V> {\n\n let mut res = Vec::with_capacity(g.size() as usize);\n\n for v in g.val_iter() {\n\n vec_push(&mut res, v);\n\n }\n\n res\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 51, "score": 298531.10284129076 }, { "content": "pub fn date_format(d: &Date, format: &String) -> ddlog_std::Result<String, String> {\n\n result_from_delayed_format(d.val.format(format), format)\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 52, "score": 297849.2921778446 }, { "content": "pub fn time_parse(s: &String, format: &String) -> ddlog_std::Result<Time, String> {\n\n match (::chrono::NaiveTime::parse_from_str(s, format)) {\n\n Ok(t) => ddlog_std::Result::Ok {\n\n res: TimeWrapper { val: t },\n\n },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 53, "score": 297849.2921778446 }, { "content": "pub fn date_parse(s: &String, format: &String) -> ddlog_std::Result<Date, String> {\n\n match (::chrono::NaiveDate::parse_from_str(s, format)) {\n\n Ok(d) => ddlog_std::Result::Ok {\n\n res: DateWrapper { val: d },\n\n },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 54, "score": 297849.2921778446 }, { "content": "pub fn time_format(t: &Time, format: &String) -> ddlog_std::Result<String, String> {\n\n result_from_delayed_format(t.val.format(format), format)\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 55, "score": 297849.2921778446 }, { "content": "pub fn vec_sort_imm<T: Ord>(mut vec: Vec<T>) -> Vec<T> {\n\n vec.vec.sort();\n\n vec\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 56, "score": 296591.3856654926 }, { "content": "pub fn vec_append<T: Clone>(vec: &mut Vec<T>, other: &Vec<T>) {\n\n vec.extend_from_slice(other.as_slice());\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 57, "score": 295276.53208672086 }, { "content": "pub fn datetime_parse(s: &String, format: &String) -> ddlog_std::Result<DateTime, String> {\n\n let prim = ::chrono::NaiveDateTime::parse_from_str(s, format);\n\n match (prim) {\n\n Ok(res) => {\n\n let dt = DateTime {\n\n date: DateWrapper { val: res.date() },\n\n time: TimeWrapper { val: res.time() },\n\n };\n\n ddlog_std::Result::Ok { res: dt }\n\n }\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 58, "score": 294980.4931427459 }, { "content": "pub fn datetime_format(d: &DateTime, format: &String) -> ddlog_std::Result<String, String> {\n\n let dt = ::chrono::NaiveDateTime::new((*d).date.val, (*d).time.val);\n\n result_from_delayed_format(dt.format(format), format)\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 59, "score": 294980.4931427459 }, { "content": "pub fn vec_push<T>(vec: &mut Vec<T>, elem: T) {\n\n vec.push(elem);\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 60, "score": 294864.5577888483 }, { "content": "pub fn ipv4_from_str(s: &String) -> ddlog_std::Result<Ipv4Addr, String> {\n\n ddlog_std::res2std(::std::net::Ipv4Addr::from_str(&*s).map(Ipv4Addr))\n\n}\n\n\n", "file_path": "lib/net/ipv4.rs", "rank": 61, "score": 293077.6202449837 }, { "content": "pub fn ipv6_from_str(s: &String) -> ddlog_std::Result<Ipv6Addr, String> {\n\n ddlog_std::res2std(::std::net::Ipv6Addr::from_str(&*s).map(Ipv6Addr::new))\n\n}\n\n\n", "file_path": "lib/net/ipv6.rs", "rank": 62, "score": 293077.6202449837 }, { "content": "pub fn encode_utf16(s: &String) -> Vec<u16> {\n\n s.encode_utf16().collect()\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 63, "score": 291994.25129668077 }, { "content": "pub fn parse_f(s: &String) -> ddlog_std::Result<OrderedFloat<f32>, String> {\n\n match (s.parse::<f32>()) {\n\n Ok(res) => ddlog_std::Result::Ok {\n\n res: OrderedFloat::<f32>(res),\n\n },\n\n Err(err) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", err),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/fp.rs", "rank": 64, "score": 291222.4843882285 }, { "content": "pub fn parse_d(s: &String) -> ddlog_std::Result<OrderedFloat<f64>, String> {\n\n match (s.parse::<f64>()) {\n\n Ok(res) => ddlog_std::Result::Ok {\n\n res: OrderedFloat::<f64>(res),\n\n },\n\n Err(err) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", err),\n\n },\n\n }\n\n}\n", "file_path": "lib/fp.rs", "rank": 65, "score": 291222.48438822856 }, { "content": "pub fn format_ddlog_str(s: &str, f: &mut fmt::Formatter) -> fmt::Result {\n\n //write!(f, \"{:?}\", s),\n\n f.write_char('\"')?;\n\n let mut from = 0;\n\n for (i, c) in s.char_indices() {\n\n let esc = c.escape_debug();\n\n if esc.len() != 1 && c != '\\'' {\n\n f.write_str(&s[from..i])?;\n\n for c in esc {\n\n f.write_char(c)?;\n\n }\n\n from = i + c.len_utf8();\n\n }\n\n }\n\n f.write_str(&s[from..])?;\n\n f.write_char('\"')\n\n}\n\n\n\n/// `enum Record` represents an arbitrary DDlog value.\n\n///\n", "file_path": "rust/template/differential_datalog/src/record/mod.rs", "rank": 66, "score": 290773.7968184045 }, { "content": "fn main() {\n\n // The fields of struct records with the same names & types are compatible\n\n let mut foo = Foo {\n\n a: 10,\n\n b: \"Something\".to_owned(),\n\n c: 20,\n\n };\n\n let bar = Bar {\n\n a: 100,\n\n b: \"Nothing\".to_owned(),\n\n };\n\n\n\n bar.into_record().mutate(&mut foo).unwrap();\n\n assert_eq!(\n\n foo,\n\n Foo {\n\n a: 100,\n\n b: \"Nothing\".to_owned(),\n\n c: 20,\n\n },\n", "file_path": "rust/template/ddlog_derive/tests/ui/pass/nominal_typing.rs", "rank": 67, "score": 290694.52314337326 }, { "content": "pub fn tz_datetime_parse(s: &String, format: &String) -> ddlog_std::Result<TzDateTime, String> {\n\n match (::chrono::DateTime::parse_from_str(s, format)) {\n\n Ok(dt) => ddlog_std::Result::Ok {\n\n res: TzDateTime { val: dt },\n\n },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 68, "score": 289495.66328920785 }, { "content": "pub fn tz_datetime_parse_from_rfc3339(s: &String) -> ddlog_std::Result<TzDateTime, String> {\n\n match (::chrono::DateTime::parse_from_rfc3339(s)) {\n\n Ok(dt) => ddlog_std::Result::Ok {\n\n res: TzDateTime { val: dt },\n\n },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 69, "score": 287181.46831769205 }, { "content": "pub fn tz_datetime_parse_from_rfc2822(s: &String) -> ddlog_std::Result<TzDateTime, String> {\n\n match (::chrono::DateTime::parse_from_rfc2822(s)) {\n\n Ok(dt) => ddlog_std::Result::Ok {\n\n res: TzDateTime { val: dt },\n\n },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n\nimpl FromRecordInner for TzDateTime {\n\n fn from_record_inner(val: &record::Record) -> ::std::result::Result<Self, String> {\n\n match (val) {\n\n record::Record::String(s) => match (::chrono::DateTime::parse_from_rfc3339(s)) {\n\n Ok(dt) => Ok(TzDateTime { val: dt }),\n\n Err(e) => Err(format!(\"{}\", e)),\n\n },\n\n _ => Err(String::from(\"Unexpected type\")),\n\n }\n", "file_path": "lib/time.rs", "rank": 70, "score": 287181.46831769205 }, { "content": "pub fn vec_pop<X: Ord + Clone>(v: &mut Vec<X>) -> Option<X> {\n\n option2std(v.pop())\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 71, "score": 287141.47143499256 }, { "content": "pub fn tz_datetime_format(dt: &TzDateTime, format: &String) -> ddlog_std::Result<String, String> {\n\n result_from_delayed_format(dt.val.format(format), format)\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 72, "score": 286871.9598725251 }, { "content": "pub fn join(url: &Url, other: &String) -> ddlog_std::Result<Url, String> {\n\n match url.url.join(other.as_str()) {\n\n Ok(url) => ddlog_std::Result::Ok { res: Url { url } },\n\n Err(e) => ddlog_std::Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/url.rs", "rank": 73, "score": 286785.66551405156 }, { "content": "pub fn encode(s: &ddlog_std::Vec<u8>) -> String {\n\n b64encode(&s.vec)\n\n}\n\n\n", "file_path": "lib/base64.rs", "rank": 74, "score": 285867.11653749074 }, { "content": "pub fn vec_swap_nth<T: Clone>(vec: &mut Vec<T>, idx: &std_usize, value: &mut T) -> bool {\n\n if (*idx as usize) < vec.len() {\n\n mem::swap(&mut vec[*idx as usize], value);\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 75, "score": 283735.1169360884 }, { "content": "pub fn to_json_string<T: serde::Serialize>(x: &T) -> ddlog_std::Result<String, String> {\n\n res2std(serde_json::to_string(x))\n\n}\n\n\n", "file_path": "lib/json.rs", "rank": 76, "score": 282879.9170478993 }, { "content": "pub fn map_values<K: Ord, V: Clone>(map: &Map<K, V>) -> Vec<V> {\n\n Vec {\n\n vec: map.x.values().cloned().collect(),\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 77, "score": 282470.0936674592 }, { "content": "/// Run a test of the `interact` function. The function reads from the\n\n/// processes stdin and so we spin up a dedicated process for it (and\n\n/// require the caller to effectively be a dedicated integration test).\n\npub fn run_interact_test<F>(input: &[u8], callback: F) -> Result<(), String>\n\nwhere\n\n F: Fn(Command, bool) -> (Result<(), String>, bool),\n\n{\n\n if var_os(CHILD_MARKER).is_none() {\n\n let path = current_exe().unwrap();\n\n let mut child = Process::new(&path)\n\n .arg(\"--nocapture\")\n\n .env_clear()\n\n .env(CHILD_MARKER, \"true\")\n\n .stdin(Stdio::piped())\n\n .spawn()\n\n .unwrap();\n\n\n\n child.stdin.as_mut().unwrap().write_all(input).unwrap();\n\n\n\n let status = child.wait().unwrap();\n\n if status.success() {\n\n Ok(())\n\n } else {\n", "file_path": "rust/template/tests/common/mod.rs", "rank": 78, "score": 281816.7350036143 }, { "content": "/// Get the a rename from the current attributes, returning `Some` with the contents as a\n\n/// string literal if there is one and `None` otherwise\n\n///\n\n/// `macro_name` should be the name of the derive macro this is being called for, it's\n\n/// used for error reporting and `specific_attr` should be the derive-specific attribute's\n\n/// name, most likely `from_record` or `into_record`.\n\n///\n\n/// If more than one matching attributes are found, an error will be returned for the user, ex.\n\n///\n\n/// ```compile_fail\n\n/// #[derive(FromRecord)]\n\n/// #[ddlog(rename = \"Bar\")]\n\n/// #[ddlog(from_record = \"Baz\")]\n\n/// struct Foo {}\n\n/// ```\n\n///\n\n/// This errors because `rename` and `from_record` conflict for `from_record` implementations.\n\n///\n\n/// Additionally, unrecognized idents within the `ddlog` attribute will receive errors, such as\n\n/// `#[ddlog(non_existant = \"...\")]` and values given to attributes that are not string literals\n\n/// will also error out, like `#[ddlog(rename = 123)]`\n\n///\n\nfn get_rename<'a, I>(macro_name: &str, specific_attr: &str, attrs: I) -> Result<Option<String>>\n\nwhere\n\n I: Iterator<Item = &'a Attribute> + 'a,\n\n{\n\n let mut renames = attrs\n\n .filter(|attr| attr.path.is_ident(\"ddlog\"))\n\n .map(|attr| attr.parse_args::<MetaNameValue>())\n\n .filter_map(|attr| match attr {\n\n Ok(attr) => {\n\n if attr.path.is_ident(\"rename\") || attr.path.is_ident(specific_attr) {\n\n Some(Ok((attr.span(), attr.lit)))\n\n\n\n // Ignore correct idents that aren't for the current derive\n\n } else if attr.path.is_ident(\"from_record\") || attr.path.is_ident(\"into_record\") {\n\n None\n\n\n\n // Unrecognized idents within the ddlog attribute will be an error\n\n } else {\n\n Some(Err(Error::new_spanned(\n\n attr.path,\n", "file_path": "rust/template/ddlog_derive/src/lib.rs", "rank": 79, "score": 280344.2928506151 }, { "content": "pub fn map_union<K: Ord + Clone, V: Clone>(mut m1: Map<K, V>, mut m2: Map<K, V>) -> Map<K, V> {\n\n m1.x.append(&mut m2.x);\n\n m1\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 80, "score": 277181.50844071247 }, { "content": "pub fn group_first<K, V: Clone>(g: &Group<K, V>) -> V {\n\n g.first()\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 81, "score": 274812.87806845346 }, { "content": "pub fn parse_str(s: &String) -> ddlog_std::Result<Uuid, Error> {\n\n ddlog_std::res2std(::uuid::Uuid::parse_str(&s).map(Uuid::new))\n\n}\n\n\n", "file_path": "lib/uuid.rs", "rank": 82, "score": 273355.4344499659 }, { "content": "pub fn init_config(config: Config) -> HDDlog {\n\n let (ddlog, _) =\n\n benchmarks_ddlog::run_with_config(config, false).expect(\"failed to create DDlog instance\");\n\n ddlog\n\n}\n\n\n", "file_path": "rust/ddlog_benches/src/lib.rs", "rank": 83, "score": 273013.9937697614 }, { "content": "pub fn from_bytes(b: &ddlog_std::Vec<u8>) -> ddlog_std::Result<Uuid, Error> {\n\n ddlog_std::res2std(::uuid::Uuid::from_slice(&**b).map(Uuid::new))\n\n}\n\n\n", "file_path": "lib/uuid.rs", "rank": 84, "score": 270254.4052884396 }, { "content": "pub fn map_keys<K: Ord + Clone, V>(map: &Map<K, V>) -> Vec<K> {\n\n Vec {\n\n vec: map.x.keys().cloned().collect(),\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 85, "score": 267913.9948675732 }, { "content": "pub fn vec_sort_by<A, B: Ord>(v: &mut ddlog_std::Vec<A>, f: &Box<dyn Closure<*const A, B>>) {\n\n v.sort_unstable_by_key(|x| f.call(x))\n\n}\n\n\n", "file_path": "lib/vec.rs", "rank": 86, "score": 266263.46280048473 }, { "content": "fn uuid_from_int(i: &BigInt) -> Result<String, String> {\n\n Ok(uuid_from_u128(\n\n i.to_u128()\n\n .ok_or_else(|| format!(\"uuid {} is not a u128\", i))?,\n\n ))\n\n}\n", "file_path": "rust/template/ovsdb/lib.rs", "rank": 87, "score": 265390.9428878958 }, { "content": "pub fn map_remove<K: Ord + Clone, V: Clone>(m: &mut Map<K, V>, k: &K) -> Option<V> {\n\n option2std(m.x.remove(k))\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 88, "score": 265384.17052359896 }, { "content": "pub fn date_option_to_result(r: Option<::chrono::NaiveDate>) -> ddlog_std::Result<Date, String> {\n\n match (r) {\n\n Some(d) => ddlog_std::Result::Ok {\n\n res: DateWrapper { val: d },\n\n },\n\n None => ddlog_std::Result::Err {\n\n err: \"Invalid date\".to_string(),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 89, "score": 264993.2509042192 }, { "content": "pub fn time_option_to_result(r: Option<::chrono::NaiveTime>) -> ddlog_std::Result<Time, String> {\n\n match (r) {\n\n Some(res) => ddlog_std::Result::Ok {\n\n res: TimeWrapper { val: res },\n\n },\n\n None => ddlog_std::Result::Err {\n\n err: \"illegal time value\".to_string(),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 90, "score": 264993.2509042192 }, { "content": "pub fn set_insert<X: Ord>(s: &mut Set<X>, v: X) {\n\n s.x.insert(v);\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 91, "score": 261608.8868764594 }, { "content": "pub trait RelationCallback: Fn(RelId, &DDValue, Weight) + Send + Sync {\n\n fn clone_boxed(&self) -> Box<dyn RelationCallback>;\n\n}\n\n\n\nimpl<T> RelationCallback for T\n\nwhere\n\n T: Fn(RelId, &DDValue, Weight) + Clone + Send + Sync + ?Sized + 'static,\n\n{\n\n fn clone_boxed(&self) -> Box<dyn RelationCallback> {\n\n Box::new(self.clone())\n\n }\n\n}\n\n\n\nimpl Clone for Box<dyn RelationCallback> {\n\n fn clone(&self) -> Self {\n\n self.clone_boxed()\n\n }\n\n}\n\n\n\n/// Caching mode for input relations only\n", "file_path": "rust/template/differential_datalog/src/program/mod.rs", "rank": 92, "score": 255865.61828763795 }, { "content": "/// Convert Rust result type to DDlog's std::Result\n\npub fn res2std<T, E: Display>(res: StdResult<T, E>) -> Result<T, String> {\n\n match res {\n\n Ok(res) => Result::Ok { res },\n\n Err(e) => Result::Err {\n\n err: format!(\"{}\", e),\n\n },\n\n }\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 93, "score": 255076.9312756781 }, { "content": "pub fn try_from_yo(year: &i32, ordinal: &u16) -> ddlog_std::Result<Date, String> {\n\n date_option_to_result(::chrono::NaiveDate::from_yo_opt(*year, *ordinal as u32))\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 94, "score": 254686.4979054256 }, { "content": "pub fn try_from_hms(h: &u8, m: &u8, s: &u8) -> ddlog_std::Result<Time, String> {\n\n time_option_to_result(::chrono::NaiveTime::from_hms_opt(\n\n *h as u32, *m as u32, *s as u32,\n\n ))\n\n}\n\n\n", "file_path": "lib/time.rs", "rank": 95, "score": 250716.00466863858 }, { "content": "pub fn string_reverse(s: &String) -> String {\n\n s.chars().rev().collect()\n\n}\n\n\n\n// Hashing\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 96, "score": 248398.1489671935 }, { "content": "pub fn string_to_lowercase(s: &String) -> String {\n\n s.to_lowercase()\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 97, "score": 248398.1489671935 }, { "content": "pub fn string_to_uppercase(s: &String) -> String {\n\n s.to_uppercase()\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 98, "score": 248398.1489671935 }, { "content": "pub fn string_trim(s: &String) -> String {\n\n s.trim().to_string()\n\n}\n\n\n", "file_path": "lib/ddlog_std.rs", "rank": 99, "score": 248398.1489671935 } ]
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 the code is compiled optimized.\n\n///\n\n/// The `release` macro uses the [`Verbosity`] crate to determine when and what to evaluate.\n\n///\n\n/// _\\* See the [`Verbosity`] crate to learn how to set the verbosity level._\n\n///\n\n/// ## Anatomy of the `release!` macro\n\n///\n\n/// Input consists of an optional intended verbosity level, defaulting to `terse`\n\n/// if it is not specifically provided. The remainder of the macro input expects\n\n/// an expression and then an optional semicolon terminator.\n\n///\n\n/// ### Examples\n\n///\n\n/// * Evaluates when `default`, which is `terse`\n", "file_path": "src/lib.rs", "rank": 2, "score": 225455.52828695934 }, { "content": "#[cfg(feature = \"debug\")]\n\n#[proc_macro]\n\npub fn debug(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as debug_macro::DebugMacro).into_token_stream().into()\n\n}\n\n\n\n/// Conditionally prints to `io::stdout` when the code is compiled unoptimized\n\n/// with debug assertions, otherwise does not include the message. _a new line is appended_\n\n///\n\n/// ## Anatomy of the `debugln!` macro\n\n///\n\n/// `debug!` accepts the same input as the `std` library [`println!`] macro.\n\n///\n\n/// ### Example\n\n///\n\n/// Printing a line to `io::stdout`\n\n///\n\n/// ```no_run\n\n/// # use::cli_toolbox::debugln;\n\n/// debugln! { \"DBG: debugging information - {}\", 42 }\n\n/// ```\n\n///\n\n/// ## Panics\n\n///\n\n/// Just like the [`println!`] macros used to write the output, this also panics if\n\n/// writing to `io::stdout` fails.\n\n///\n\n/// [`println!`]: <https://doc.rust-lang.org/std/macro.println.html>\n", "file_path": "src/lib.rs", "rank": 3, "score": 225308.58125228313 }, { "content": "#[doc = include_str!(\"docs/report_macro_anatomy_doc.md\")]\n\n#[cfg(feature = \"report\")]\n\n#[proc_macro]\n\npub fn report(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as report_macro::ReportMacro).into_token_stream().into()\n\n}\n\n\n\n/// Conditionally prints to `io::stdout` or `io::stderr` when intended verbosity matches\n\n/// active verbosity,<br/>appends a new line.\n\n///\n\n#[doc = include_str!(\"docs/report_macro_doc.md\")]\n\n///\n\n/// ## Anatomy of the `reportln!` macro\n\n///\n", "file_path": "src/lib.rs", "rank": 4, "score": 222688.62189167354 }, { "content": "fn verbosity_keyword_peek2(input: ParseStream) -> bool {\n\n input.peek2(kw::err) ||\n\n input.peek2(kw::terse) ||\n\n input.peek2(kw::verbose)\n\n}\n", "file_path": "src/report_macro/parse.rs", "rank": 5, "score": 207442.15272518978 }, { "content": "#[cfg(any(feature = \"eval\", feature = \"release\"))]\n\npub fn tokenize_verbosity_expression(verbosity: Verbosity, expr: &Expr) -> TokenStream {\n\n let verbosity_check = if verbosity == Verbosity::Terse {\n\n quote! { verbosity::Verbosity::is_terse() }\n\n } else {\n\n quote! { verbosity::Verbosity::is_verbose() }\n\n };\n\n\n\n quote! { if #verbosity_check { #expr; } }\n\n}\n\n\n", "file_path": "src/common/tokenize.rs", "rank": 6, "score": 207275.87051070147 }, { "content": "#[test]\n\nfn when_message_with_method_to_call_arg_should_output() {\n\n #[cfg(debug_assertions)]\n\n struct Foo { bar: usize }\n\n\n\n #[cfg(debug_assertions)]\n\n impl Foo {\n\n fn method_to_call(&self) -> usize { self.bar }\n\n }\n\n\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n #[cfg(debug_assertions)]\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", sut.method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 7, "score": 205190.65004072717 }, { "content": "#[cfg(any(feature = \"eval\", feature = \"release\"))]\n\npub fn tokenize_expression(terse: &Option<Expr>, verbose: &Option<Expr>) -> TokenStream {\n\n match (terse, verbose) {\n\n (Some(terse), None) =>\n\n tokenize_verbosity_expression(Verbosity::Terse, terse),\n\n (None, Some(verbose)) =>\n\n tokenize_verbosity_expression(Verbosity::Verbose, verbose),\n\n (Some(terse), Some(verbose)) => {\n\n let terse = tokenize_verbosity_expression(Verbosity::Terse, terse);\n\n let verbose = tokenize_verbosity_expression(Verbosity::Verbose, verbose);\n\n\n\n quote! {\n\n match verbosity::Verbosity::level() {\n\n verbosity::Verbosity::Terse => #terse,\n\n verbosity::Verbosity::Verbose => #verbose,\n\n verbosity::Verbosity::Quite => {}\n\n }\n\n }\n\n }\n\n (None, None) => TokenStream::new()\n\n }\n\n}\n\n\n", "file_path": "src/common/tokenize.rs", "rank": 9, "score": 199035.60395070494 }, { "content": "#[test]\n\nfn when_message_with_method_to_call_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n struct Foo {\n\n bar: usize,\n\n }\n\n\n\n impl Foo {\n\n fn method_to_call(&self) -> usize { self.bar }\n\n }\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", sut.method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 10, "score": 194218.28600833873 }, { "content": "#[test]\n\nfn when_message_with_method_to_call_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n struct Foo { bar: usize }\n\n\n\n impl Foo {\n\n fn method_to_call(&self) -> usize { self.bar }\n\n }\n\n\n\n let expected_stdout = \"\";\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", sut.method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 11, "score": 194218.28600833876 }, { "content": "#[test]\n\nfn when_message_with_method_to_call_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n struct Foo {\n\n bar: usize,\n\n }\n\n\n\n impl Foo {\n\n fn method_to_call(&self) -> usize { self.bar }\n\n }\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", sut.method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 12, "score": 194218.28600833873 }, { "content": "fn parse_verbosity(input: ParseStream) -> syn::Result<(bool, Verbosity)> {\n\n let mut std_err = false;\n\n let verbosity;\n\n let span = input.span();\n\n\n\n if input.peek(Token![@]) && verbosity_keyword_peek2(input) {\n\n <Token![@]>::parse(input)?;\n\n\n\n if input.peek(kw::err) {\n\n <kw::err>::parse(input)?;\n\n <Token![-]>::parse(input)?;\n\n\n\n std_err = true;\n\n }\n\n\n\n if input.peek(kw::terse) {\n\n <kw::terse>::parse(input)?;\n\n\n\n verbosity = Verbosity::Terse;\n\n } else if input.peek(kw::verbose) {\n", "file_path": "src/report_macro/parse.rs", "rank": 13, "score": 185760.76156118422 }, { "content": "#[test]\n\nfn when_message_with_unary_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", -(-42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 15, "score": 180343.84343287488 }, { "content": "#[test]\n\nfn when_message_with_path_arg_should_output() {\n\n #[cfg(debug_assertions)]\n\n mod foo { pub mod bar { pub const VALUE: usize = 42; }}\n\n \n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", foo::bar::VALUE }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 16, "score": 180343.84343287488 }, { "content": "#[test]\n\nfn when_message_with_cast_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", 42_isize as usize }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 17, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_reference_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n #[cfg(debug_assertions)]\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", &sut }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 18, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_tuple_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: (42, 42, 42)\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", (42, 42, 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 19, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_unsafe_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", unsafe { unsafe_method_to_call() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n #[cfg(debug_assertions)]\n\n unsafe fn unsafe_method_to_call() -> usize { 42 }\n\n}\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 20, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_paren_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", (21 + 21) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 21, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_array_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: [42, 42, 42]\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", [42, 42, 42] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 22, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_try_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let actual_stdout = inner().unwrap();\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n\n\n fn inner() -> Result<String, ()> {\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", method_to_try()? }\n\n };\n\n\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n return Ok(actual_stdout);\n\n\n\n #[cfg(debug_assertions)]\n\n fn method_to_try() -> Result<usize, ()> { Ok(42) }\n\n }\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 23, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_block_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", { 42 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 24, "score": 180343.84343287488 }, { "content": "#[test]\n\nfn when_message_with_range_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: ..42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", ..42 }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 25, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_repeat_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: [42, 42, 42]\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {:?}\", [42; 3] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 26, "score": 180343.84343287488 }, { "content": "#[test]\n\nfn when_message_with_match_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n #[cfg(debug_assertions)]\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", match sut { 42 => sut, _ => unreachable!() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 27, "score": 180343.84343287488 }, { "content": "#[test]\n\nfn when_message_with_field_arg_should_output() {\n\n #[cfg(debug_assertions)]\n\n struct Foo { bar: usize }\n\n\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n #[cfg(debug_assertions)]\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", sut.bar }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 28, "score": 180343.84343287488 }, { "content": "#[test]\n\nfn when_message_with_index_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n #[cfg(debug_assertions)]\n\n let sut = [42; 3];\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", sut[1] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 29, "score": 180343.84343287486 }, { "content": "#[test]\n\nfn when_message_with_call_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n #[cfg(debug_assertions)]\n\n fn method_to_call() -> usize { 42 }\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 30, "score": 180257.26541573546 }, { "content": "fn tokenize_debug_message_macro(message: &Message) -> TokenStream {\n\n let message = message.build_message(false);\n\n\n\n quote! {\n\n #[cfg(debug_assertions)]\n\n { #message; }\n\n }\n\n}", "file_path": "src/debug_macro/tokenize.rs", "rank": 31, "score": 177399.93314592203 }, { "content": "#[doc = include_str!(\"docs/report_macro_anatomy_doc.md\")]\n\n#[cfg(feature = \"report\")]\n\n#[proc_macro]\n\npub fn reportln(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as report_macro::ReportLnMacro).into_token_stream().into()\n\n}\n", "file_path": "src/lib.rs", "rank": 33, "score": 173974.53982340253 }, { "content": "#[cfg(feature = \"debug\")]\n\n#[proc_macro]\n\npub fn debugln(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as debug_macro::DebugLnMacro).into_token_stream().into()\n\n}\n\n\n\n/// Conditionally evaluates expressions when intended verbosity matches active verbosity.\n\n/// \n\n/// The `eval` macro uses the [`Verbosity`] crate to determine when and what to evaluate.\n\n/// \n\n/// _\\* See the [`Verbosity`] crate to learn how to set the verbosity level._\n\n///\n\n/// ## Anatomy of the `eval!` macro\n\n///\n\n/// Input consists of an optional intended verbosity level, defaulting to `terse`\n\n/// if it is not specifically provided. The remainder of the macro input expects\n\n/// an expression and then an optional semicolon terminator.\n\n///\n\n/// ### Examples\n\n///\n\n/// * Evaluates when `default`, which is `terse`\n\n/// ```no_run\n", "file_path": "src/lib.rs", "rank": 34, "score": 173972.66723692548 }, { "content": "#[cfg(feature = \"release\")]\n\n#[proc_macro]\n\npub fn release(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as release_macro::Release).into_token_stream().into()\n\n}\n\n\n\n/// Conditionally prints to `io::stdout` or `io::stderr` when intended verbosity matches\n\n/// active verbosity,<br/>does not append a new line.\n\n///\n\n#[doc = include_str!(\"docs/report_macro_doc.md\")]\n\n///\n\n/// ## Anatomy of the `report!` macro\n\n///\n", "file_path": "src/lib.rs", "rank": 35, "score": 173969.34562354087 }, { "content": "#[test]\n\nfn when_message_with_unary_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", -(-42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 36, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_reference_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", &sut }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 37, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_block_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", { 42 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 38, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_array_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n \n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", [42, 42, 42] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 39, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_cast_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", 42_isize as usize }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 40, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_unsafe_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", unsafe { unsafe_method_to_call() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n unsafe fn unsafe_method_to_call() -> usize { 42 }\n\n}\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 41, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_field_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n struct Foo {\n\n bar: usize,\n\n }\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", sut.bar }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 42, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_repeat_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: [42, 42, 42]\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", [42; 3] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 43, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_block_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", { 42 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 44, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_path_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n mod foo { pub mod bar { pub const VALUE: usize = 42; } }\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", foo::bar::VALUE }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 45, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_try_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let actual_stdout = inner().unwrap();\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n\n\n fn inner() -> Result<String, ()> {\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", method_to_try()? }\n\n };\n\n\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n return Ok(actual_stdout);\n\n\n\n fn method_to_try() -> Result<usize, ()> { Ok(42) }\n\n }\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 46, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_match_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", match sut { 42 => sut, _ => unreachable!() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 47, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_cast_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", 42_isize as usize }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 48, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_index_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n let sut = [42; 3];\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", sut[1] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 49, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_paren_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", (21 + 21) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 50, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_unary_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", -(-42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 51, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_match_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", match sut { 42 => sut, _ => unreachable!() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 52, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_array_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: [42, 42, 42]\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", [42, 42, 42] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 53, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_unsafe_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", unsafe { unsafe_method_to_call() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n unsafe fn unsafe_method_to_call() -> usize { 42 }\n\n}\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 54, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_reference_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", &sut }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 55, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_range_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: ..42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", ..42 }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 56, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_unsafe_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", unsafe { unsafe_method_to_call() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n unsafe fn unsafe_method_to_call() -> usize { 42 }\n\n}\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 57, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_try_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let actual_stdout = inner().unwrap();\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n\n\n fn inner() -> Result<String, ()> {\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", method_to_try()? }\n\n };\n\n\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n return Ok(actual_stdout);\n\n\n\n fn method_to_try() -> Result<usize, ()> { Ok(42) }\n\n }\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 58, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_tuple_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: (42, 42, 42)\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", (42, 42, 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 59, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_field_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n struct Foo { bar: usize }\n\n\n\n let expected_stdout = \"\";\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", sut.bar }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 60, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_range_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", ..42 }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 61, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_unary_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", -(-42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 62, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_reference_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", &sut }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 63, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_repeat_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", [42; 3] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 64, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_paren_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", (21 + 21) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 65, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_tuple_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: (42, 42, 42)\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", (42, 42, 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 66, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_try_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let actual_stdout = inner().unwrap();\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n\n\n fn inner() -> Result<String, ()> {\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", method_to_try()? }\n\n };\n\n\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n return Ok(actual_stdout);\n\n\n\n fn method_to_try() -> Result<usize, ()> { Ok(42) }\n\n }\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 67, "score": 170327.83846937725 }, { "content": "#[test]\n\nfn when_message_with_path_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n mod foo { pub mod bar { pub const VALUE: usize = 42; }}\n\n \n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", foo::bar::VALUE }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 68, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_tuple_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {:?}\", (42, 42, 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 69, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_range_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: ..42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", ..42 }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 70, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_index_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n let sut = [42; 3];\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", sut[1] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 71, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_cast_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", 42_isize as usize }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 72, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_repeat_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: [42, 42, 42]\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {:?}\", [42; 3] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 73, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_array_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: [42, 42, 42]\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {:?}\", [42, 42, 42] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 74, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_field_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n struct Foo {\n\n bar: usize,\n\n }\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n let sut = Foo { bar: 42 };\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", sut.bar }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 75, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_path_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n mod foo { pub mod bar { pub const VALUE: usize = 42; } }\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", foo::bar::VALUE }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 76, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_match_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n let sut = 42;\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", match sut { 42 => sut, _ => unreachable!() } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 77, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_paren_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", (21 + 21) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 78, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_index_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n let sut = [42; 3];\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", sut[1] }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 79, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_block_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", { 42 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 80, "score": 170327.83846937728 }, { "content": "#[test]\n\nfn when_message_with_call_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n fn method_to_call() -> usize { 42 }\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 81, "score": 170245.4539550308 }, { "content": "#[test]\n\nfn when_message_with_call_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n fn method_to_call() -> usize { 42 }\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 82, "score": 170245.4539550308 }, { "content": "#[test]\n\nfn when_message_with_call_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", method_to_call() }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n\n\n fn method_to_call() -> usize { 42 }\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 83, "score": 170245.4539550308 }, { "content": "#[cfg(feature = \"trace\")]\n\n#[inline]\n\npub fn trace_source(input: ParseStream) -> ParseStream {\n\n println!(\"SOURCE: {}\", input);\n\n input\n\n}\n\n\n\n#[cfg(not(feature = \"trace\"))]\n\n#[inline]\n\npub const fn trace_source(input: ParseStream) -> ParseStream { input }\n", "file_path": "src/common/tracing.rs", "rank": 84, "score": 161326.6227734795 }, { "content": "#[test]\n\nfn when_message_with_macro_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", format!(\"{}\", 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 87, "score": 157904.2903302056 }, { "content": "struct ReportMessage {\n\n message: Message,\n\n std_err: bool,\n\n verbosity: Verbosity,\n\n}\n\n\n\n#[cfg(all(debug_assertions, feature = \"trace\"))]\n\nimpl Display for ReportMessage {\n\n fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {\n\n write!(fmt, \"{{ message: {}, std_err: {}}}\", self.message, self.std_err)\n\n }\n\n}\n\n\n\npub struct ReportMacro {\n\n terse: Option<ReportMessage>,\n\n verbose: Option<ReportMessage>,\n\n}\n\n\n\n#[cfg(all(debug_assertions, feature = \"trace\"))]\n\nimpl Display for ReportMacro {\n", "file_path": "src/report_macro/mod.rs", "rank": 88, "score": 157541.9513680583 }, { "content": "#[cfg(debug_assertions)]\n\nfn check_answer(proposed_answer: u32) -> Result<(), &'static str> {\n\n if proposed_answer == THE_ULTIMATE_ANSWER {\n\n Ok(())\n\n } else {\n\n Err(\"i think not!\")\n\n }\n\n}\n", "file_path": "examples/cli-debugging.rs", "rank": 89, "score": 156612.4399971639 }, { "content": "#[test]\n\nfn when_message_with_if_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", if true { 42 } else { 0 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 90, "score": 154099.631344083 }, { "content": "#[test]\n\nfn when_message_with_literal_arg_should_output() {\n\n expect! { expected_stdout = \"\", \"DBG: debugging output: 42\" }\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n debug! { \"DBG: debugging output: {}\", 42 }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/debug_macro_message_argument_tests.rs", "rank": 92, "score": 150797.7290162322 }, { "content": "#[test]\n\nfn when_message_with_macro_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", format!(\"{}\", 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 93, "score": 149473.42754420548 }, { "content": "#[test]\n\nfn when_message_with_macro_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", format!(\"{}\", 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 94, "score": 149473.42754420545 }, { "content": "#[test]\n\nfn when_message_with_macro_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", format!(\"{}\", 42) }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 95, "score": 149473.42754420545 }, { "content": "fn tokenize_report_macro(\n\n terse: &Option<ReportMessage>, verbose: &Option<ReportMessage>,\n\n) -> TokenStream {\n\n match (terse, verbose) {\n\n (Some(terse), None) =>\n\n quote! { #terse },\n\n (None, Some(verbose)) =>\n\n quote! { #verbose },\n\n (Some(terse), Some(verbose)) => {\n\n let terse = terse.message.build_message(terse.std_err);\n\n let verbose = verbose.message.build_message(verbose.std_err);\n\n\n\n quote! {\n\n match verbosity::Verbosity::level() {\n\n verbosity::Verbosity::Terse => #terse,\n\n verbosity::Verbosity::Verbose => #verbose,\n\n verbosity::Verbosity::Quite => {}\n\n }\n\n }\n\n }\n\n (None, None) => TokenStream::new()\n\n }\n\n}\n", "file_path": "src/report_macro/tokenize.rs", "rank": 96, "score": 145498.25326954058 }, { "content": "#[test]\n\nfn when_message_with_if_arg_should_output() {\n\n Verbosity::Quite.set_as_global();\n\n\n\n let expected_stdout = \"\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { \"terse output: {}\", if true { 42 } else { 0 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_quite_verbosity.rs", "rank": 97, "score": 145157.7792800054 }, { "content": "#[test]\n\nfn when_message_with_if_arg_should_output() {\n\n Verbosity::Terse.set_as_global();\n\n\n\n let expected_stdout = \"terse output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @terse \"terse output: {}\", if true { 42 } else { 0 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_terse_verbosity.rs", "rank": 98, "score": 145157.7792800054 }, { "content": "#[test]\n\nfn when_message_with_if_arg_should_output() {\n\n Verbosity::Verbose.set_as_global();\n\n\n\n let expected_stdout = \"verbose output: 42\";\n\n\n\n let (actual_stdout, actual_stderr) = capture! {\n\n report! { @verbose \"verbose output: {}\", if true { 42 } else { 0 } }\n\n };\n\n\n\n assert_eq!(expected_stdout, actual_stdout);\n\n assert_eq!(EXPECTED_BLANK_STD_ERR, actual_stderr);\n\n}\n\n\n", "file_path": "tests/report_macro_message_argument_tests_verbose_verbosity.rs", "rank": 99, "score": 145157.7792800054 } ]
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 let symbols = BufReader::new(symbols.unwrap());\n\n\n\n for line in symbols.lines() {\n\n let line = line.unwrap();\n\n let parts: Vec<&str> = line.split_whitespace().collect();\n\n if parts.get(2) == Some(&name) {\n\n return Some(parts[0].to_string());\n\n }\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "src/common/bpf.rs", "rank": 0, "score": 275398.1696466253 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn key_to_value(index: u64) -> Option<u64> {\n\n let index = index;\n\n if index < 100 {\n\n Some(index)\n\n } else if index < 190 {\n\n Some((index - 90) * 10 + 9)\n\n } else if index < 280 {\n\n Some((index - 180) * 100 + 99)\n\n } else if index < 370 {\n\n Some((index - 270) * 1_000 + 999)\n\n } else if index < 460 {\n\n Some((index - 360) * 10_000 + 9999)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n// TODO: a result is probably more appropriate\n", "file_path": "src/common/bpf.rs", "rank": 1, "score": 262658.8953604528 }, { "content": "fn parse_proc_stat(line: &str) -> HashMap<CpuStatistic, u64> {\n\n let mut result = HashMap::new();\n\n for (id, part) in line.split_whitespace().enumerate() {\n\n match id {\n\n 0 => {\n\n if part != \"cpu\" {\n\n return result;\n\n }\n\n }\n\n 1 => {\n\n result.insert(CpuStatistic::UsageUser, part.parse().unwrap_or(0));\n\n }\n\n 2 => {\n\n result.insert(CpuStatistic::UsageNice, part.parse().unwrap_or(0));\n\n }\n\n 3 => {\n\n result.insert(CpuStatistic::UsageSystem, part.parse().unwrap_or(0));\n\n }\n\n 4 => {\n\n result.insert(CpuStatistic::UsageIdle, part.parse().unwrap_or(0));\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 2, "score": 248506.44246482552 }, { "content": "pub fn nanos_per_tick() -> u64 {\n\n let ticks_per_second = sysconf::raw::sysconf(sysconf::raw::SysconfVariable::ScClkTck)\n\n .expect(\"Failed to get Clock Ticks per Second\") as u64;\n\n SECOND / ticks_per_second\n\n}\n\n\n\n#[async_trait]\n\nimpl Sampler for Cpu {\n\n type Statistic = CpuStatistic;\n\n\n\n fn new(common: Common) -> Result<Self, anyhow::Error> {\n\n let statistics = common.config().samplers().cpu().statistics();\n\n #[allow(unused_mut)]\n\n let mut sampler = Self {\n\n common,\n\n cpus: HashSet::new(),\n\n cstates: HashMap::new(),\n\n cstate_files: HashMap::new(),\n\n perf: None,\n\n tick_duration: nanos_per_tick(),\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 3, "score": 228145.98349727798 }, { "content": "#[allow(dead_code)]\n\nfn path_match(lib_name: &str, path: &Path) -> bool {\n\n if let Some(file_name) = path.file_name() {\n\n if let Some(file_str) = file_name.to_str() {\n\n let parts: Vec<&str> = file_str.split('.').collect();\n\n if parts.len() < 2 {\n\n return false;\n\n }\n\n let mut stem_str: String = parts[0].to_string();\n\n let mut ext_str: String = parts[1].to_string();\n\n let end_index = parts.len() - 1;\n\n if parts[end_index] == \"so\" {\n\n stem_str = parts[..end_index].join(\".\");\n\n ext_str = \"so\".into();\n\n }\n\n let to_test = match stem_str.starts_with(\"lib\") {\n\n true => stem_str[3..].into(),\n\n false => stem_str,\n\n };\n\n return to_test.eq(lib_name) && \"so\".eq(&ext_str[..]);\n\n }\n", "file_path": "src/samplers/usercall/mod.rs", "rank": 4, "score": 225251.55976586536 }, { "content": "fn parse_frequency(line: &str) -> Option<f64> {\n\n let mut split = line.split_whitespace();\n\n if split.next() == Some(\"cpu\") && split.next() == Some(\"MHz\") {\n\n split.last().map(|v| v.parse().unwrap_or(0.0) * 1_000_000.0)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_parse_proc_stat() {\n\n let result = parse_proc_stat(\"cpu 131586 0 53564 8246483 35015 350665 4288 5632 0 0\");\n\n assert_eq!(result.len(), 9);\n\n assert_eq!(result.get(&CpuStatistic::UsageUser), Some(&131586));\n\n assert_eq!(result.get(&CpuStatistic::UsageNice), Some(&0));\n\n assert_eq!(result.get(&CpuStatistic::UsageSystem), Some(&53564));\n\n }\n\n\n\n #[test]\n\n fn test_parse_frequency() {\n\n let result = parse_frequency(\"cpu MHz : 1979.685\");\n\n assert_eq!(result, Some(1_979_685_000.0));\n\n }\n\n}\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 5, "score": 213026.31820186478 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn parse_string(x: &[u8]) -> String {\n\n match x.iter().position(|&r| r == 0) {\n\n Some(zero_pos) => String::from_utf8_lossy(&x[0..zero_pos]).to_string(),\n\n None => String::from_utf8_lossy(x).to_string(),\n\n }\n\n}\n", "file_path": "src/common/bpf.rs", "rank": 6, "score": 200363.6945224519 }, { "content": "pub fn nanos_per_tick() -> u64 {\n\n let ticks_per_second = sysconf::raw::sysconf(sysconf::raw::SysconfVariable::ScClkTck)\n\n .expect(\"Failed to get Clock Ticks per Second\") as u64;\n\n SECOND / ticks_per_second\n\n}\n\n\n\npub struct Rezolus {\n\n common: Common,\n\n nanos_per_tick: u64,\n\n proc_stat: Option<File>,\n\n proc_statm: Option<File>,\n\n statistics: Vec<RezolusStatistic>,\n\n}\n\n\n\n#[async_trait]\n\nimpl Sampler for Rezolus {\n\n type Statistic = RezolusStatistic;\n\n\n\n fn new(common: Common) -> Result<Self, anyhow::Error> {\n\n let statistics = common.config().samplers().rezolus().statistics();\n", "file_path": "src/samplers/rezolus/mod.rs", "rank": 7, "score": 194213.37042249428 }, { "content": "pub fn nanos_per_tick() -> u64 {\n\n let ticks_per_second = sysconf::raw::sysconf(sysconf::raw::SysconfVariable::ScClkTck)\n\n .expect(\"Failed to get Clock Ticks per Second\") as u64;\n\n SECOND / ticks_per_second\n\n}\n\n\n\npub struct Process {\n\n common: Common,\n\n nanos_per_tick: u64,\n\n pid: Option<u32>,\n\n proc_stat: Option<File>,\n\n proc_statm: Option<File>,\n\n statistics: Vec<ProcessStatistic>,\n\n}\n\n\n\n#[async_trait]\n\nimpl Sampler for Process {\n\n type Statistic = ProcessStatistic;\n\n\n\n fn new(common: Common) -> Result<Self, anyhow::Error> {\n", "file_path": "src/samplers/process/mod.rs", "rank": 8, "score": 194213.3704224943 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn parse_u64(x: Vec<u8>) -> u64 {\n\n let mut v = [0_u8; 8];\n\n for (i, byte) in v.iter_mut().enumerate() {\n\n *byte = *x.get(i).unwrap_or(&0);\n\n }\n\n\n\n u64::from_ne_bytes(v)\n\n}\n\n\n", "file_path": "src/common/bpf.rs", "rank": 10, "score": 191961.44911400462 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn bpf_hash_char_to_map(table: &bcc::table::Table) -> std::collections::HashMap<String, u64> {\n\n let mut map = std::collections::HashMap::new();\n\n\n\n for e in table.iter() {\n\n let key = parse_string(&e.key);\n\n let value = parse_u64(e.value);\n\n map.insert(key, value);\n\n }\n\n\n\n map\n\n}\n\n\n", "file_path": "src/common/bpf.rs", "rank": 11, "score": 188325.41807535157 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn map_from_table(table: &mut bcc::table::Table) -> std::collections::HashMap<u64, u32> {\n\n use std::collections::HashMap;\n\n\n\n let mut current = HashMap::new();\n\n\n\n trace!(\"transferring data to userspace\");\n\n for (id, mut entry) in table.iter().enumerate() {\n\n let mut key = [0; 4];\n\n if key.len() != entry.key.len() {\n\n // log and skip processing if the key length is unexpected\n\n debug!(\n\n \"unexpected length of the entry's key, entry id: {} key length: {}\",\n\n id,\n\n entry.key.len()\n\n );\n\n continue;\n\n }\n\n key.copy_from_slice(&entry.key);\n\n let key = u32::from_ne_bytes(key);\n\n\n", "file_path": "src/common/bpf.rs", "rank": 12, "score": 178126.0651108607 }, { "content": "fn default_reading_suffix() -> String {\n\n \"count\".to_string()\n\n}\n\n\n", "file_path": "src/config/general.rs", "rank": 13, "score": 154412.0575611398 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn perf_table_to_map(table: &bcc::table::Table) -> std::collections::HashMap<u32, u64> {\n\n let mut map = std::collections::HashMap::new();\n\n\n\n for entry in table.iter() {\n\n let key = parse_u32(entry.key);\n\n let value = parse_u64(entry.value);\n\n\n\n map.insert(key, value);\n\n }\n\n\n\n map\n\n}\n\n\n", "file_path": "src/common/bpf.rs", "rank": 14, "score": 141731.54308533727 }, { "content": "#include <uapi/linux/ptrace.h>\n\nstruct key_t {\n\n char c[80];\n\n};\n\nBPF_HASH(counts, struct key_t);\n\n\n\n\"#;\n\n\n\nmacro_rules! probe_template {\n\n () => {\n\n r#\"\n\n\n\nint probe_{}(void *ctx) {{\n\n struct key_t key = {{.c = \"{}\"}};\n\n u64 zero = 0, *val;\n\n val = counts.lookup_or_init(&key, &zero);\n\n (*val)++;\n\n return 0;\n\n}}\n\n\"#\n\n };\n\n}\n\n\n\n/// Determines if a path is a match for the given lib_name\n\n///\n\n/// This custom logic is necessary because of the common convention of versioning linux libraries by\n\n/// appending the version number to the library file name. I.E. the file /usr/lib/libkrb5.so.3.3\n\n/// results in an extension of '3' with a naive parsing of the file extension. This is what Path\n\n/// and PathBuf would return for the extension.\n", "file_path": "src/samplers/usercall/mod.rs", "rank": 15, "score": 140228.436326818 }, { "content": "#[cfg(feature = \"bpf\")]\n\npub fn parse_u32(x: Vec<u8>) -> u32 {\n\n let mut v = [0_u8; 4];\n\n for (i, byte) in v.iter_mut().enumerate() {\n\n *byte = *x.get(i).unwrap_or(&0);\n\n }\n\n\n\n u32::from_ne_bytes(v)\n\n}\n\n\n", "file_path": "src/common/bpf.rs", "rank": 17, "score": 131426.18357807852 }, { "content": "fn default_timeout() -> u64 {\n\n 200\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\n#[serde(deny_unknown_fields)]\n\npub struct HttpConfig {\n\n counters: Vec<String>,\n\n #[serde(default)]\n\n enabled: bool,\n\n gauges: Vec<String>,\n\n #[serde(default)]\n\n interval: Option<usize>,\n\n #[serde(default)]\n\n passthrough: bool,\n\n #[serde(default = \"crate::common::default_percentiles\")]\n\n percentiles: Vec<f64>,\n\n url: Option<String>,\n\n // http request timeout in milliseconds\n\n #[serde(default = \"default_timeout\")]\n", "file_path": "src/samplers/http/config.rs", "rank": 18, "score": 117772.14711403404 }, { "content": " u64 id;\n", "file_path": "src/samplers/scheduler/bpf.c", "rank": 19, "score": 103668.40682905546 }, { "content": " char name[TASK_COMM_LEN];\n", "file_path": "src/samplers/disk/bpf.c", "rank": 20, "score": 103644.87850368663 }, { "content": "fn default_statistics() -> Vec<CpuStatistic> {\n\n CpuStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for CpuConfig {\n\n type Statistic = CpuStatistic;\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn perf_events(&self) -> bool {\n\n self.perf_events\n", "file_path": "src/samplers/cpu/config.rs", "rank": 21, "score": 98138.47240583636 }, { "content": "/// Value types may be used to store the primary value for a metric. For example\n\n/// counter readings, gauge readings, or buckets values from underlying\n\n/// distributions. Lower precision atomics help reduce in-memory representation\n\n/// for stored values and streaming summaries, but are unable to represent large\n\n/// counter and gauge values.\n\npub trait Value: Atomic + Arithmetic + Default {}\n\n\n\nimpl Value for AtomicU8 {}\n\nimpl Value for AtomicU16 {}\n\nimpl Value for AtomicU32 {}\n\nimpl Value for AtomicU64 {}\n", "file_path": "src/metrics/traits/value.rs", "rank": 22, "score": 95861.36784364154 }, { "content": "pub trait SamplerConfig {\n\n type Statistic;\n\n fn bpf(&self) -> bool {\n\n false\n\n }\n\n fn enabled(&self) -> bool {\n\n false\n\n }\n\n fn interval(&self) -> Option<usize>;\n\n fn percentiles(&self) -> &[f64];\n\n fn perf_events(&self) -> bool {\n\n false\n\n }\n\n fn statistics(&self) -> Vec<<Self as config::SamplerConfig>::Statistic>;\n\n}\n", "file_path": "src/config/mod.rs", "rank": 23, "score": 94758.97867883998 }, { "content": "#[async_trait]\n\npub trait Sampler: Sized + Send {\n\n type Statistic: Statistic;\n\n\n\n /// Create a new instance of the sampler\n\n fn new(common: Common) -> Result<Self, anyhow::Error>;\n\n\n\n /// Access common fields shared between samplers\n\n fn common(&self) -> &Common;\n\n fn common_mut(&mut self) -> &mut Common;\n\n\n\n fn spawn(common: Common);\n\n\n\n /// Run the sampler and write new observations to the metrics library and\n\n /// wait until next sample interval\n\n async fn sample(&mut self) -> Result<(), std::io::Error>;\n\n\n\n fn interval(&self) -> usize {\n\n self.sampler_config()\n\n .interval()\n\n .unwrap_or_else(|| self.general_config().interval())\n", "file_path": "src/samplers/mod.rs", "rank": 24, "score": 87858.87378396612 }, { "content": "fn default_ntptimeval() -> libc::ntptimeval {\n\n libc::ntptimeval {\n\n time: libc::timeval {\n\n tv_sec: 0,\n\n tv_usec: 0,\n\n },\n\n maxerror: 0,\n\n esterror: 0,\n\n tai: 0,\n\n __glibc_reserved1: 0,\n\n __glibc_reserved2: 0,\n\n __glibc_reserved3: 0,\n\n __glibc_reserved4: 0,\n\n }\n\n}\n", "file_path": "src/samplers/ntp/mod.rs", "rank": 25, "score": 86662.3679959852 }, { "content": "impl From<Output> for ApproxOutput {\n\n fn from(output: Output) -> Self {\n\n match output {\n\n Output::Reading => Self::Reading,\n\n Output::Percentile(percentile) => {\n\n Self::Percentile((percentile * 1000000.0).ceil() as u64)\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl From<ApproxOutput> for Output {\n\n fn from(output: ApproxOutput) -> Self {\n\n match output {\n\n ApproxOutput::Reading => Self::Reading,\n\n ApproxOutput::Percentile(percentile) => Self::Percentile(percentile as f64 / 1000000.0),\n\n }\n\n }\n\n}\n", "file_path": "src/metrics/outputs/mod.rs", "rank": 26, "score": 76814.9836187798 }, { "content": "// Copyright 2020 Twitter, Inc.\n\n// Licensed under the Apache License, Version 2.0\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n\n\n// Internal representation which approximates the percentile\n\n#[derive(PartialEq, Eq, Hash, Copy, Clone)]\n\npub enum ApproxOutput {\n\n Reading,\n\n Percentile(u64),\n\n}\n\n\n\n/// Defines an output that should be reported in a snapshot for a statistic\n\n#[derive(Copy, Clone)]\n\npub enum Output {\n\n /// A counter or gauge reading\n\n Reading,\n\n /// A percentile from a statistic summary\n\n Percentile(f64),\n\n}\n\n\n", "file_path": "src/metrics/outputs/mod.rs", "rank": 27, "score": 76810.77858484264 }, { "content": " for cpu in &self.cpus {\n\n if !self.cstate_files.contains_key(cpu) {\n\n self.cstate_files.insert(cpu.to_string(), HashMap::new());\n\n }\n\n if let Some(cpuidle_files) = self.cstate_files.get_mut(cpu) {\n\n for (cpuidle_name, state) in &self.cstates {\n\n if !cpuidle_files.contains_key(cpuidle_name) {\n\n let time_file = format!(\n\n \"/sys/devices/system/cpu/{}/cpuidle/{}/time\",\n\n cpu, cpuidle_name\n\n );\n\n let file = File::open(time_file).await?;\n\n cpuidle_files.insert(cpuidle_name.to_string(), file);\n\n }\n\n if let Some(file) = cpuidle_files.get_mut(cpuidle_name) {\n\n file.seek(SeekFrom::Start(0)).await?;\n\n let mut reader = BufReader::new(file);\n\n if let Ok(time) = reader.read_u64().await {\n\n if let Some(state) = state.split('-').next() {\n\n let metric = match CState::from_str(state) {\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 28, "score": 76515.03353089864 }, { "content": " let name_file = format!(\n\n \"/sys/devices/system/cpu/{}/cpuidle/{}/name\",\n\n cpu, cpuidle_name\n\n );\n\n let mut name_file = File::open(name_file).await?;\n\n let mut name_content = Vec::new();\n\n name_file.read_to_end(&mut name_content).await?;\n\n if let Ok(name_string) = std::str::from_utf8(&name_content) {\n\n if let Some(Ok(state)) =\n\n name_string.split_whitespace().next().map(|v| v.parse())\n\n {\n\n self.cstates.insert(cpuidle_name, state);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 29, "score": 76507.71028534217 }, { "content": " }\n\n\n\n Ok(())\n\n }\n\n\n\n async fn sample_cpuinfo(&mut self) -> Result<(), std::io::Error> {\n\n if self.proc_cpuinfo.is_none() {\n\n let file = File::open(\"/proc/cpuinfo\").await?;\n\n self.proc_cpuinfo = Some(file);\n\n }\n\n\n\n if let Some(file) = &mut self.proc_cpuinfo {\n\n file.seek(SeekFrom::Start(0)).await?;\n\n let mut reader = BufReader::new(file);\n\n let mut buf = String::new();\n\n let mut result = Vec::new();\n\n while reader.read_line(&mut buf).await? > 0 {\n\n if let Some(freq) = parse_frequency(&buf) {\n\n result.push(freq.ceil() as u64);\n\n }\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 30, "score": 76506.73280321728 }, { "content": "use crate::config::SamplerConfig;\n\nuse crate::samplers::Common;\n\nuse crate::*;\n\n\n\nmod config;\n\nmod stat;\n\n\n\npub use config::*;\n\npub use stat::*;\n\n\n\n#[allow(dead_code)]\n\npub struct Cpu {\n\n common: Common,\n\n cpus: HashSet<String>,\n\n cstates: HashMap<String, String>,\n\n cstate_files: HashMap<String, HashMap<String, File>>,\n\n perf: Option<Arc<Mutex<BPF>>>,\n\n tick_duration: u64,\n\n proc_cpuinfo: Option<File>,\n\n proc_stat: Option<File>,\n\n statistics: Vec<CpuStatistic>,\n\n}\n\n\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 31, "score": 76504.72610905627 }, { "content": "// Copyright 2019 Twitter, Inc.\n\n// Licensed under the Apache License, Version 2.0\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n\n\nuse std::collections::{HashMap, HashSet};\n\nuse std::io::SeekFrom;\n\nuse std::str::FromStr;\n\nuse std::sync::{Arc, Mutex};\n\n\n\nuse async_trait::async_trait;\n\n#[cfg(feature = \"bpf\")]\n\nuse bcc::perf_event::{Event, SoftwareEvent};\n\n#[cfg(feature = \"bpf\")]\n\nuse bcc::{PerfEvent, PerfEventArray};\n\nuse regex::Regex;\n\nuse tokio::fs::File;\n\nuse tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, BufReader};\n\n\n\nuse crate::common::bpf::BPF;\n\nuse crate::common::*;\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 32, "score": 76501.22831256651 }, { "content": " fatal!(\"failed to initialize perf bpf for cpu\");\n\n } else {\n\n error!(\"failed to initialize perf bpf for cpu\");\n\n }\n\n }\n\n }\n\n self.perf = Some(Arc::new(Mutex::new(BPF { inner: bpf })));\n\n } else if !self.common().config().general().fault_tolerant() {\n\n fatal!(\"failed to initialize perf bpf\");\n\n } else {\n\n error!(\"failed to initialize perf bpf. skipping cpu perf telemetry\");\n\n }\n\n Ok(())\n\n }\n\n\n\n async fn sample_cpu_usage(&mut self) -> Result<(), std::io::Error> {\n\n if self.proc_stat.is_none() {\n\n let file = File::open(\"/proc/stat\").await?;\n\n self.proc_stat = Some(file);\n\n }\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 33, "score": 76500.5080609598 }, { "content": " if let Ok(table) = &(*bpf).inner.table(stat.table().unwrap()) {\n\n let map = crate::common::bpf::perf_table_to_map(table);\n\n let mut total = 0;\n\n for (_cpu, count) in map.iter() {\n\n total += count;\n\n }\n\n let _ = self.metrics().record_counter(stat, time, total);\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n\n\n async fn sample_cstates(&mut self) -> Result<(), std::io::Error> {\n\n let mut result = HashMap::<CpuStatistic, u64>::new();\n\n\n\n // populate the cpu cache if empty\n\n if self.cpus.is_empty() {\n\n let cpu_regex = Regex::new(r\"^cpu\\d+$\").unwrap();\n\n let mut cpu_dir = tokio::fs::read_dir(\"/sys/devices/system/cpu\").await?;\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 34, "score": 76500.35434947614 }, { "content": "\n\n if let Some(file) = &mut self.proc_stat {\n\n file.seek(SeekFrom::Start(0)).await?;\n\n\n\n let mut reader = BufReader::new(file);\n\n let mut result = HashMap::new();\n\n let mut buf = String::new();\n\n while reader.read_line(&mut buf).await? > 0 {\n\n result.extend(parse_proc_stat(&buf));\n\n buf.clear();\n\n }\n\n\n\n let time = Instant::now();\n\n for stat in self.sampler_config().statistics() {\n\n if let Some(value) = result.get(&stat) {\n\n let _ = self\n\n .metrics()\n\n .record_counter(&stat, time, value * self.tick_duration);\n\n }\n\n }\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 35, "score": 76499.4334903073 }, { "content": " 1000 / interval\n\n };\n\n\n\n let code = format!(\n\n \"{}\\n{}\",\n\n format!(\"#define NUM_CPU {}\", cpus),\n\n include_str!(\"perf.c\").to_string()\n\n );\n\n let mut perf_array_attached = false;\n\n if let Ok(mut bpf) = bcc::BPF::new(&code) {\n\n for statistic in &self.statistics {\n\n if let Some(table) = statistic.table() {\n\n if let Some(event) = statistic.event() {\n\n perf_array_attached = true;\n\n if PerfEventArray::new()\n\n .table(&format!(\"{}_array\", table))\n\n .event(event)\n\n .attach(&mut bpf)\n\n .is_err()\n\n {\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 36, "score": 76498.04590592548 }, { "content": " while let Some(cpu_entry) = cpu_dir.next_entry().await? {\n\n if let Ok(cpu_name) = cpu_entry.file_name().into_string() {\n\n if cpu_regex.is_match(&cpu_name) {\n\n self.cpus.insert(cpu_name.to_string());\n\n }\n\n }\n\n }\n\n }\n\n\n\n // populate the cstate cache if empty\n\n if self.cstates.is_empty() {\n\n let state_regex = Regex::new(r\"^state\\d+$\").unwrap();\n\n for cpu in &self.cpus {\n\n // iterate through all cpuidle states\n\n let cpuidle_dir = format!(\"/sys/devices/system/cpu/{}/cpuidle\", cpu);\n\n let mut cpuidle_dir = tokio::fs::read_dir(cpuidle_dir).await?;\n\n while let Some(cpuidle_entry) = cpuidle_dir.next_entry().await? {\n\n if let Ok(cpuidle_name) = cpuidle_entry.file_name().into_string() {\n\n if state_regex.is_match(&cpuidle_name) {\n\n // get the name of the state\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 37, "score": 76494.80967052504 }, { "content": "\n\n // delay by half the sample interval so that we land between perf\n\n // counter updates\n\n std::thread::sleep(std::time::Duration::from_micros(\n\n (1000 * sampler.interval()) as u64 / 2,\n\n ));\n\n\n\n Ok(sampler)\n\n }\n\n\n\n fn spawn(common: Common) {\n\n if common.config().samplers().cpu().enabled() {\n\n if let Ok(mut cpu) = Cpu::new(common.clone()) {\n\n common.runtime().spawn(async move {\n\n loop {\n\n let _ = cpu.sample().await;\n\n }\n\n });\n\n } else if !common.config.fault_tolerant() {\n\n fatal!(\"failed to initialize cpu sampler\");\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 38, "score": 76492.85159133683 }, { "content": " let r = self.sample_cpu_usage().await;\n\n self.map_result(r)?;\n\n\n\n let r = self.sample_cstates().await;\n\n self.map_result(r)?;\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Cpu {\n\n #[cfg(feature = \"bpf\")]\n\n fn initialize_bpf_perf(&mut self) -> Result<(), std::io::Error> {\n\n let cpus = crate::common::hardware_threads().unwrap();\n\n let interval = self.interval() as u64;\n\n let frequency = if interval > 1000 {\n\n 1\n\n } else if interval == 0 {\n\n 1\n\n } else {\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 39, "score": 76491.6022941454 }, { "content": " } else {\n\n error!(\"failed to initialize cpu sampler\");\n\n }\n\n }\n\n }\n\n\n\n fn common(&self) -> &Common {\n\n &self.common\n\n }\n\n\n\n fn common_mut(&mut self) -> &mut Common {\n\n &mut self.common\n\n }\n\n\n\n fn sampler_config(&self) -> &dyn SamplerConfig<Statistic = Self::Statistic> {\n\n self.common.config().samplers().cpu()\n\n }\n\n\n\n async fn sample(&mut self) -> Result<(), std::io::Error> {\n\n if let Some(ref mut delay) = self.delay() {\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 40, "score": 76489.3185384823 }, { "content": " if !self.common().config().general().fault_tolerant() {\n\n fatal!(\"failed to initialize perf bpf for event: {:?}\", event);\n\n } else {\n\n error!(\"failed to initialize perf bpf for event: {:?}\", event);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n debug!(\"attaching software event to drive perf counter sampling\");\n\n // if none of the perf array was attached, we do not need to attach the perf event.\n\n if perf_array_attached {\n\n if PerfEvent::new()\n\n .handler(\"do_count\")\n\n .event(Event::Software(SoftwareEvent::CpuClock))\n\n .sample_frequency(Some(frequency))\n\n .attach(&mut bpf)\n\n .is_err()\n\n {\n\n if !self.common().config().general().fault_tolerant() {\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 41, "score": 76485.50709164601 }, { "content": " Ok(CState::C0) => CpuStatistic::CstateC0Time,\n\n Ok(CState::C1) => CpuStatistic::CstateC1Time,\n\n Ok(CState::C1E) => CpuStatistic::CstateC1ETime,\n\n Ok(CState::C2) => CpuStatistic::CstateC2Time,\n\n Ok(CState::C3) => CpuStatistic::CstateC3Time,\n\n Ok(CState::C6) => CpuStatistic::CstateC6Time,\n\n Ok(CState::C7) => CpuStatistic::CstateC7Time,\n\n Ok(CState::C8) => CpuStatistic::CstateC8Time,\n\n _ => continue,\n\n };\n\n let counter = result.entry(metric).or_insert(0);\n\n *counter += time * MICROSECOND;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n let time = Instant::now();\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 42, "score": 76484.33069897055 }, { "content": " }\n\n 6 => {\n\n result.insert(CpuStatistic::UsageIrq, part.parse().unwrap_or(0));\n\n }\n\n 7 => {\n\n result.insert(CpuStatistic::UsageSoftirq, part.parse().unwrap_or(0));\n\n }\n\n 8 => {\n\n result.insert(CpuStatistic::UsageSteal, part.parse().unwrap_or(0));\n\n }\n\n 9 => {\n\n result.insert(CpuStatistic::UsageGuest, part.parse().unwrap_or(0));\n\n }\n\n 10 => {\n\n result.insert(CpuStatistic::UsageGuestNice, part.parse().unwrap_or(0));\n\n }\n\n _ => {}\n\n }\n\n }\n\n result\n\n}\n\n\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 43, "score": 76483.73223212024 }, { "content": " buf.clear();\n\n }\n\n\n\n let time = Instant::now();\n\n for frequency in result {\n\n let _ = self\n\n .metrics()\n\n .record_gauge(&CpuStatistic::Frequency, time, frequency);\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n #[cfg(feature = \"bpf\")]\n\n fn sample_bpf_perf_counters(&self) -> Result<(), std::io::Error> {\n\n if let Some(ref bpf) = self.perf {\n\n let bpf = bpf.lock().unwrap();\n\n let time = Instant::now();\n\n for stat in self.statistics.iter().filter(|s| s.table().is_some()) {\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 44, "score": 76481.48095548684 }, { "content": " for stat in &self.statistics {\n\n if let Some(value) = result.get(stat) {\n\n let _ = self.metrics().record_counter(stat, time, *value);\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 45, "score": 76478.19162437423 }, { "content": " proc_cpuinfo: None,\n\n proc_stat: None,\n\n statistics,\n\n };\n\n\n\n if sampler.sampler_config().enabled() {\n\n sampler.register();\n\n }\n\n\n\n // we initialize perf last so we can delay\n\n if sampler.sampler_config().enabled() && sampler.sampler_config().perf_events() {\n\n #[cfg(feature = \"bpf\")]\n\n {\n\n if let Err(e) = sampler.initialize_bpf_perf() {\n\n if !sampler.common().config().general().fault_tolerant() {\n\n return Err(format_err!(\"bpf perf init failure: {}\", e));\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 46, "score": 76477.66234532408 }, { "content": " delay.tick().await;\n\n }\n\n\n\n if !self.sampler_config().enabled() {\n\n return Ok(());\n\n }\n\n\n\n debug!(\"sampling\");\n\n\n\n // we do perf sampling first, since it is time critical to keep it\n\n // between underlying counter updates\n\n #[cfg(feature = \"bpf\")]\n\n {\n\n let r = self.sample_bpf_perf_counters();\n\n self.map_result(r)?;\n\n }\n\n\n\n let r = self.sample_cpuinfo().await;\n\n self.map_result(r)?;\n\n\n", "file_path": "src/samplers/cpu/mod.rs", "rank": 47, "score": 76477.4793557142 }, { "content": "struct key_t {\n\n char c[80];\n", "file_path": "src/samplers/krb5kdc/bpf.c", "rank": 48, "score": 71907.85450218504 }, { "content": "static void add_value(u64* val, u64 delta) {\n\n if (val)\n\n lock_xadd(val, delta);\n", "file_path": "src/samplers/tcp/bpf.c", "rank": 49, "score": 69703.88291424034 }, { "content": " int target_cpu;\n", "file_path": "src/samplers/scheduler/bpf.c", "rank": 50, "score": 69442.72624841025 }, { "content": "int trace_open_return(struct pt_regs *ctx)\n\n{\n\n return trace_return(ctx, 2);\n", "file_path": "src/samplers/ext4/bpf.c", "rank": 51, "score": 67658.3388878795 }, { "content": "int trace_open_return(struct pt_regs *ctx)\n\n{\n\n return trace_return(ctx, 2);\n", "file_path": "src/samplers/xfs/bpf.c", "rank": 52, "score": 67658.3388878795 }, { "content": "int trace_read_return(struct pt_regs *ctx)\n\n{\n\n return trace_return(ctx, 0);\n", "file_path": "src/samplers/ext4/bpf.c", "rank": 53, "score": 67643.47729366485 }, { "content": "int trace_read_return(struct pt_regs *ctx)\n\n{\n\n return trace_return(ctx, 0);\n", "file_path": "src/samplers/xfs/bpf.c", "rank": 54, "score": 67643.47729366485 }, { "content": "int trace_read_entry(struct pt_regs *ctx, struct kiocb *iocb)\n\n{\n\n u32 pid = bpf_get_current_pid_tgid();\n\n struct file *fp = iocb->ki_filp;\n\n if ((u64)fp->f_op == EXT4_FILE_OPERATIONS)\n\n return 0;\n\n u64 ts = bpf_ktime_get_ns();\n\n start.update(&pid, &ts);\n\n return 0;\n", "file_path": "src/samplers/ext4/bpf.c", "rank": 55, "score": 67643.47729366485 }, { "content": "#define OP_NAME_LEN 8\n\n\n", "file_path": "src/samplers/xfs/bpf.c", "rank": 56, "score": 67636.20346765824 }, { "content": "#define OP_NAME_LEN 8\n\n\n", "file_path": "src/samplers/ext4/bpf.c", "rank": 57, "score": 67636.20346765824 }, { "content": "int trace_wake_up_new_task(struct pt_regs *ctx, struct task_struct *p)\n\n{\n\n return trace_enqueue(p->tgid, p->pid);\n", "file_path": "src/samplers/scheduler/bpf.c", "rank": 58, "score": 65721.00311538034 }, { "content": "/// A trait that is used to track primitive types that correspond to supported\n\n/// atomic types.\n\npub trait Primitive:\n\n Ord + Indexing + Copy + From<u8> + Sub<Self, Output = Self> + FloatConvert\n\n{\n\n}\n\n\n\nimpl Primitive for u8 {}\n\nimpl Primitive for u16 {}\n\nimpl Primitive for u32 {}\n\nimpl Primitive for u64 {}\n", "file_path": "src/metrics/traits/primitive.rs", "rank": 59, "score": 60498.11412298071 }, { "content": "/// A statistic represents a named entity that has associated measurements which\n\n/// are recorded and metrics which are reported. This trait defines a set of\n\n/// methods which uniquely identify the statistic, help the metrics library\n\n/// track it appropriately, and allow including metadata in the exposition\n\n/// format.\n\npub trait Statistic {\n\n /// The name is used to lookup the channel for the statistic and should be\n\n /// unique for each statistic. This field is used to hash the statistic in\n\n /// the core structure.\n\n fn name(&self) -> &str;\n\n /// Indicates which source type the statistic tracks.\n\n fn source(&self) -> Source;\n\n /// Optionally, specify a summary builder which configures a summary\n\n /// aggregation for producing additional metrics such as percentiles.\n\n fn summary(&self) -> Option<Summary> {\n\n None\n\n }\n\n}\n\n\n\nimpl Hash for dyn Statistic {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n self.name().to_string().hash(state);\n\n }\n\n}\n\n\n\nimpl PartialEq for dyn Statistic {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.name() == other.name()\n\n }\n\n}\n\n\n\nimpl Eq for dyn Statistic {}\n", "file_path": "src/metrics/traits/statistic.rs", "rank": 60, "score": 60497.464684544655 }, { "content": "fn default_threads() -> usize {\n\n 1\n\n}\n\n\n", "file_path": "src/config/general.rs", "rank": 61, "score": 59222.2948036321 }, { "content": "pub trait FloatConvert {\n\n fn to_float(self) -> f64;\n\n fn from_float(value: f64) -> Self;\n\n}\n\n\n\nimpl FloatConvert for u64 {\n\n fn to_float(self) -> f64 {\n\n self as f64\n\n }\n\n fn from_float(value: f64) -> Self {\n\n value as Self\n\n }\n\n}\n\n\n\nimpl FloatConvert for u32 {\n\n fn to_float(self) -> f64 {\n\n self as f64\n\n }\n\n fn from_float(value: f64) -> Self {\n\n value as Self\n", "file_path": "src/metrics/traits/float_convert.rs", "rank": 62, "score": 58212.575112665 }, { "content": "fn default_window() -> AtomicUsize {\n\n AtomicUsize::new(60)\n\n}\n\n\n", "file_path": "src/config/general.rs", "rank": 63, "score": 58052.17496819681 }, { "content": "fn default_interval() -> AtomicUsize {\n\n AtomicUsize::new(1000)\n\n}\n\n\n", "file_path": "src/config/general.rs", "rank": 64, "score": 58052.17496819681 }, { "content": "fn default_logging_level() -> Level {\n\n Level::Info\n\n}\n", "file_path": "src/config/general.rs", "rank": 65, "score": 58052.17496819681 }, { "content": "fn default_interval() -> AtomicUsize {\n\n AtomicUsize::new(500)\n\n}\n\n\n\n#[cfg(feature = \"push_kafka\")]\n\nimpl Kafka {\n\n pub fn enabled(&self) -> bool {\n\n self.enabled.load(Ordering::Relaxed)\n\n }\n\n\n\n pub fn interval(&self) -> usize {\n\n self.interval.load(Ordering::Relaxed)\n\n }\n\n\n\n pub fn hosts(&self) -> Vec<String> {\n\n self.hosts.clone()\n\n }\n\n\n\n pub fn topic(&self) -> Option<String> {\n\n self.topic.clone()\n\n }\n\n}\n", "file_path": "src/config/exposition/kafka.rs", "rank": 66, "score": 56953.440689116556 }, { "content": "fn default_fault_tolerant() -> AtomicBool {\n\n AtomicBool::new(true)\n\n}\n\n\n", "file_path": "src/config/general.rs", "rank": 67, "score": 56953.440689116556 }, { "content": "fn default_enabled() -> AtomicBool {\n\n AtomicBool::new(false)\n\n}\n\n\n", "file_path": "src/config/exposition/kafka.rs", "rank": 68, "score": 56953.440689116556 }, { "content": "fn default_statistics() -> Vec<SchedulerStatistic> {\n\n SchedulerStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for SchedulerConfig {\n\n type Statistic = SchedulerStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/scheduler/config.rs", "rank": 69, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<XfsStatistic> {\n\n XfsStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for XfsConfig {\n\n type Statistic = XfsStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/xfs/config.rs", "rank": 70, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<NtpStatistic> {\n\n NtpStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for NtpConfig {\n\n type Statistic = NtpStatistic;\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n\n let mut enabled = Vec::new();\n\n for statistic in self.statistics.iter() {\n\n enabled.push(*statistic);\n\n }\n\n enabled\n\n }\n\n}\n", "file_path": "src/samplers/ntp/config.rs", "rank": 71, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<DiskStatistic> {\n\n DiskStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for DiskConfig {\n\n type Statistic = DiskStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/disk/config.rs", "rank": 72, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<MemoryStatistic> {\n\n MemoryStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for MemoryConfig {\n\n type Statistic = MemoryStatistic;\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n\n self.statistics.clone()\n\n }\n\n}\n", "file_path": "src/samplers/memory/config.rs", "rank": 73, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<ProcessStatistic> {\n\n ProcessStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for ProcessConfig {\n\n type Statistic = ProcessStatistic;\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n", "file_path": "src/samplers/process/config.rs", "rank": 74, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<Krb5kdcStatistic> {\n\n Krb5kdcStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for Krb5kdcConfig {\n\n type Statistic = Krb5kdcStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/krb5kdc/config.rs", "rank": 75, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<NetworkStatistic> {\n\n NetworkStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for NetworkConfig {\n\n type Statistic = NetworkStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/network/config.rs", "rank": 76, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<UdpStatistic> {\n\n UdpStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for UdpConfig {\n\n type Statistic = UdpStatistic;\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n\n self.statistics.clone()\n\n }\n\n}\n", "file_path": "src/samplers/udp/config.rs", "rank": 77, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<TcpStatistic> {\n\n TcpStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for TcpConfig {\n\n type Statistic = TcpStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/tcp/config.rs", "rank": 78, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<RezolusStatistic> {\n\n RezolusStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for RezolusConfig {\n\n type Statistic = RezolusStatistic;\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n\n self.statistics.clone()\n\n }\n\n}\n", "file_path": "src/samplers/rezolus/config.rs", "rank": 79, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<Ext4Statistic> {\n\n Ext4Statistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for Ext4Config {\n\n type Statistic = Ext4Statistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/ext4/config.rs", "rank": 80, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<SoftnetStatistic> {\n\n SoftnetStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for SoftnetConfig {\n\n type Statistic = SoftnetStatistic;\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n\n self.statistics.clone()\n\n }\n\n}\n", "file_path": "src/samplers/softnet/config.rs", "rank": 81, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<InterruptStatistic> {\n\n InterruptStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for InterruptConfig {\n\n type Statistic = InterruptStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/interrupt/config.rs", "rank": 82, "score": 53453.96599724794 }, { "content": "fn default_statistics() -> Vec<NvidiaConfigStatistic> {\n\n NvidiaConfigStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for NvidiaConfig {\n\n type Statistic = NvidiaStatistic;\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n\n &self.percentiles\n\n }\n\n\n\n fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> {\n", "file_path": "src/samplers/nvidia/config.rs", "rank": 83, "score": 52479.71432633161 }, { "content": "fn default_statistics() -> Vec<PageCacheStatistic> {\n\n PageCacheStatistic::iter().collect()\n\n}\n\n\n\nimpl SamplerConfig for PageCacheConfig {\n\n type Statistic = PageCacheStatistic;\n\n\n\n fn bpf(&self) -> bool {\n\n self.bpf\n\n }\n\n\n\n fn enabled(&self) -> bool {\n\n self.enabled\n\n }\n\n\n\n fn interval(&self) -> Option<usize> {\n\n self.interval\n\n }\n\n\n\n fn percentiles(&self) -> &[f64] {\n", "file_path": "src/samplers/page_cache/config.rs", "rank": 84, "score": 51559.91583205892 }, { "content": "/// Count types are used internally for some types of summary datastructures,\n\n/// such as heatmaps. The selected atomic is used as the internal counter width.\n\n/// A well matched type would be large enough to hold maximum number of\n\n/// observations that would fall into the same bucket in a heatmap. Using types\n\n/// that are oversized will result in higher memory utilization for heatmap\n\n/// summaries, but has no effect on basic counter/gauge values or streaming\n\n/// summary sizes.\n\npub trait Count: Atomic + Default + AtomicCounter {}\n\n\n\nimpl Count for AtomicU8 {}\n\nimpl Count for AtomicU16 {}\n\nimpl Count for AtomicU32 {}\n\nimpl Count for AtomicU64 {}\n", "file_path": "src/metrics/traits/count.rs", "rank": 85, "score": 49863.97082495776 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // get config\n\n let config = Arc::new(Config::new());\n\n\n\n // initialize logging\n\n Logger::new()\n\n .label(common::NAME)\n\n .level(config.logging())\n\n .init()\n\n .expect(\"Failed to initialize logger\");\n\n\n\n info!(\"----------\");\n\n info!(\"{} {}\", common::NAME, common::VERSION);\n\n info!(\"----------\");\n\n debug!(\"host cores: {}\", hardware_threads().unwrap_or(1));\n\n\n\n let runnable = Arc::new(AtomicBool::new(true));\n\n let r = runnable.clone();\n\n\n\n // initialize signal handler\n", "file_path": "src/main.rs", "rank": 86, "score": 47403.34526659925 }, { "content": "static unsigned int value_to_index2(unsigned int value) {\n\n unsigned int index = 460;\n\n if (value < 100) {\n\n // 0-99 => [0..100)\n\n // 0 => 0\n\n // 99 => 99\n\n index = value;\n\n } else if (value < 1000) {\n\n // 100-999 => [100..190)\n\n // 100 => 100\n\n // 999 => 189\n\n index = 90 + value / 10;\n\n } else if (value < 10000) {\n\n // 1_000-9_999 => [190..280)\n\n // 1000 => 190\n\n // 9999 => 279\n\n index = 180 + value / 100;\n\n } else if (value < 100000) {\n\n // 10_000-99_999 => [280..370)\n\n // 10000 => 280\n\n // 99999 => 369\n\n index = 270 + value / 1000;\n\n } else if (value < 1000000) {\n\n // 100_000-999_999 => [370..460)\n\n // 100000 => 370\n\n // 999999 => 459\n\n index = 360 + value / 10000;\n\n } else {\n\n index = 460;\n\n }\n\n return index;\n", "file_path": "src/common/value_to_index2.c", "rank": 87, "score": 45907.16296241149 }, { "content": "\n\n#[cfg(feature = \"bpf\")]\n\nimpl Probe {\n\n // try to attach to a bpf instance.\n\n #[allow(unused_assignments)]\n\n pub fn try_attach_to_bpf(&self, bpf: &mut bcc::BPF) -> Result<(), anyhow::Error> {\n\n match self.probe_type {\n\n ProbeType::Kernel => match self.probe_location {\n\n ProbeLocation::Entry => bcc::Kprobe::new()\n\n .handler(&self.handler)\n\n .function(&self.name)\n\n .attach(bpf)?,\n\n ProbeLocation::Return => bcc::Kretprobe::new()\n\n .handler(&self.handler)\n\n .function(&self.name)\n\n .attach(bpf)?,\n\n },\n\n ProbeType::User => {\n\n match &self.binary_path {\n\n Some(path) => match self.probe_location {\n", "file_path": "src/common/bpf.rs", "rank": 88, "score": 40703.588310877174 }, { "content": " let mut value = [0; 8];\n\n if value.len() != entry.value.len() {\n\n // log and skip processing if the value length is unexpected\n\n debug!(\n\n \"unexpected length of the entry's value, entry id: {} value length: {}\",\n\n id,\n\n entry.value.len()\n\n );\n\n continue;\n\n }\n\n value.copy_from_slice(&entry.value);\n\n let value = u64::from_ne_bytes(value);\n\n\n\n if let Some(key) = key_to_value(key as u64) {\n\n current.insert(key, value as u32);\n\n }\n\n\n\n // clear the source counter\n\n let _ = table.set(&mut entry.key, &mut [0_u8; 8]);\n\n }\n\n current\n\n}\n\n\n", "file_path": "src/common/bpf.rs", "rank": 89, "score": 40702.386664558064 }, { "content": "}\n\n\n\n#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]\n\n#[cfg(feature = \"bpf\")]\n\npub enum ProbeLocation {\n\n Entry,\n\n Return,\n\n}\n\n\n\n// Define a probe.\n\n#[derive(Clone, Debug, Eq, PartialEq, Hash)]\n\n#[cfg(feature = \"bpf\")]\n\npub struct Probe {\n\n pub name: String, // name of the function to probe\n\n pub handler: String, // name of the probe handler\n\n pub probe_type: ProbeType, // function type, kernel, user or tracepoint.\n\n pub probe_location: ProbeLocation, // probe location, at entry or at return.\n\n pub binary_path: Option<String>, // required for user probe only.\n\n pub sub_system: Option<String>, // required for tracepoint only.\n\n}\n", "file_path": "src/common/bpf.rs", "rank": 90, "score": 40699.263152136096 }, { "content": " ProbeLocation::Entry => bcc::Uprobe::new()\n\n .handler(&self.handler)\n\n .binary(&path)\n\n .symbol(&self.name)\n\n .attach(bpf)?,\n\n ProbeLocation::Return => bcc::Uretprobe::new()\n\n .handler(&self.handler)\n\n .binary(&path)\n\n .symbol(&self.name)\n\n .attach(bpf)?,\n\n },\n\n None => {\n\n return Err(anyhow!(\n\n \"failed to attach {}, binary_path is required for user probe\",\n\n &self.name\n\n ));\n\n }\n\n };\n\n }\n\n ProbeType::Tracepoint => match &self.sub_system {\n", "file_path": "src/common/bpf.rs", "rank": 91, "score": 40696.77428882932 }, { "content": "// Copyright 2019 Twitter, Inc.\n\n// Licensed under the Apache License, Version 2.0\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n\n\n#[cfg(feature = \"bpf\")]\n\n#[allow(clippy::upper_case_acronyms)]\n\npub struct BPF {\n\n pub inner: bcc::BPF,\n\n}\n\n\n\n#[cfg(not(feature = \"bpf\"))]\n\n#[allow(clippy::upper_case_acronyms)]\n\npub struct BPF {}\n\n\n\n#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]\n\n#[cfg(feature = \"bpf\")]\n\npub enum ProbeType {\n\n Kernel,\n\n User,\n\n Tracepoint,\n", "file_path": "src/common/bpf.rs", "rank": 92, "score": 40695.03076768084 }, { "content": " Some(sb_system) => bcc::Tracepoint::new()\n\n .handler(&self.handler)\n\n .subsystem(&sb_system)\n\n .tracepoint(&self.name)\n\n .attach(bpf)?,\n\n None => {\n\n return Err(anyhow!(\n\n \"failed to attach {}, sub_system is required for tracepoint\",\n\n &self.name\n\n ));\n\n }\n\n },\n\n };\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(feature = \"bpf\")]\n", "file_path": "src/common/bpf.rs", "rank": 93, "score": 40691.79611913213 }, { "content": "// Copyright 2020 Twitter, Inc.\n\n// Licensed under the Apache License, Version 2.0\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n\n\nuse rustcommon_atomics::*;\n\n\n\n/// Value types may be used to store the primary value for a metric. For example\n\n/// counter readings, gauge readings, or buckets values from underlying\n\n/// distributions. Lower precision atomics help reduce in-memory representation\n\n/// for stored values and streaming summaries, but are unable to represent large\n\n/// counter and gauge values.\n", "file_path": "src/metrics/traits/value.rs", "rank": 94, "score": 40135.640480075395 }, { "content": "// Copyright 2019 Twitter, Inc.\n\n// Licensed under the Apache License, Version 2.0\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n\n\nuse core::str::FromStr;\n\n\n\n#[cfg(feature = \"bpf\")]\n\nuse bcc::perf_event::*;\n\n\n\nuse crate::metrics::*;\n\nuse serde_derive::{Deserialize, Serialize};\n\nuse strum_macros::{EnumIter, EnumString, IntoStaticStr};\n\n\n\n#[derive(\n\n Clone,\n\n Copy,\n\n Debug,\n\n Deserialize,\n\n EnumIter,\n\n EnumString,\n", "file_path": "src/samplers/cpu/stat.rs", "rank": 95, "score": 39849.71272692224 }, { "content": "\n\nimpl CpuStatistic {\n\n #[cfg(feature = \"bpf\")]\n\n pub fn event(self) -> Option<Event> {\n\n match self {\n\n Self::BpuBranches => Some(Event::Hardware(HardwareEvent::BranchInstructions)),\n\n Self::BpuMiss => Some(Event::Hardware(HardwareEvent::BranchMisses)),\n\n Self::CacheAccess => Some(Event::Hardware(HardwareEvent::CacheReferences)),\n\n Self::CacheMiss => Some(Event::Hardware(HardwareEvent::CacheMisses)),\n\n Self::Cycles => Some(Event::Hardware(HardwareEvent::CpuCycles)),\n\n Self::DtlbLoadMiss => Some(Event::HardwareCache(\n\n CacheId::DTLB,\n\n CacheOp::Read,\n\n CacheResult::Miss,\n\n )),\n\n Self::DtlbLoadAccess => Some(Event::HardwareCache(\n\n CacheId::DTLB,\n\n CacheOp::Read,\n\n CacheResult::Access,\n\n )),\n", "file_path": "src/samplers/cpu/stat.rs", "rank": 96, "score": 39849.183611219 }, { "content": " #[strum(serialize = \"cpu/cstate/c7/time\")]\n\n CstateC7Time,\n\n #[strum(serialize = \"cpu/cstate/c8/time\")]\n\n CstateC8Time,\n\n #[strum(serialize = \"cpu/frequency\")]\n\n Frequency,\n\n}\n\n\n\nimpl Statistic for CpuStatistic {\n\n fn name(&self) -> &str {\n\n (*self).into()\n\n }\n\n\n\n fn source(&self) -> Source {\n\n match self {\n\n Self::Frequency => Source::Gauge,\n\n _ => Source::Counter,\n\n }\n\n }\n\n}\n", "file_path": "src/samplers/cpu/stat.rs", "rank": 97, "score": 39845.305483513854 } ]
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 cx.span_err(lit.span, MSG);\n\n Err(())\n\n },\n\n },\n\n _ => {\n\n cx.span_err(expr.span, MSG);\n\n Err(())\n\n },\n\n }\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 0, "score": 201231.54772634793 }, { "content": "#[inline(always)]\n\npub fn unpack(delta: u8) -> (State, Action) {\n\n (\n\n // State is stored in bottom 4 bits\n\n unsafe { core::mem::transmute(delta & 0x0f) },\n\n // Action is stored in top 4 bits\n\n unsafe { core::mem::transmute(delta >> 4) },\n\n )\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{unpack, Action, State};\n\n #[test]\n\n fn unpack_state_action() {\n\n match unpack(0xee) {\n\n (State::SosPmApcString, Action::Unhook) => (),\n\n _ => panic!(\"unpack failed\"),\n\n }\n\n\n\n match unpack(0x0f) {\n", "file_path": "src/definitions.rs", "rank": 2, "score": 199664.95566702902 }, { "content": "#[inline]\n\n#[allow(dead_code)]\n\npub fn pack(state: State, action: Action) -> u8 {\n\n ((action as u8) << 4) | (state as u8)\n\n}\n\n\n\n/// Convert a u8 to a state and action\n\n///\n\n/// # Unsafety\n\n///\n\n/// If this function is called with a byte that wasn't encoded with the `pack`\n\n/// function in this module, there is no guarantee that a valid state and action\n\n/// can be produced.\n\n#[inline]\n\npub unsafe fn unpack(val: u8) -> (State, Action) {\n\n (\n\n // State is stored in bottom 4 bits\n\n mem::transmute(val & 0x0f),\n\n // Action is stored in top 4 bits\n\n mem::transmute(val >> 4),\n\n )\n\n}\n", "file_path": "utf8parse/src/types.rs", "rank": 3, "score": 195679.76342367486 }, { "content": "fn state_from_expr(expr: P<Expr>, cx: &mut ExtCtxt) -> Result<State, ()> {\n\n let s = match expr.node {\n\n ExprKind::Path(ref _qself, ref path) => path.to_string(),\n\n _ => {\n\n cx.span_err(expr.span, \"expected State\");\n\n return Err(());\n\n },\n\n };\n\n\n\n state_from_str(&s).map_err(|_| {\n\n cx.span_err(expr.span, \"expected State\");\n\n })\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 4, "score": 180308.63224020757 }, { "content": "fn input_mapping_from_arm(arm: Arm, cx: &mut ExtCtxt) -> Result<InputMapping, ()> {\n\n let Arm { pats, body, .. } = arm;\n\n\n\n let input = InputDefinition::from_pat(&pats[0], cx)?;\n\n let transition = Transition::from_expr(&body, cx)?;\n\n\n\n Ok(InputMapping { input, transition })\n\n}\n\n\n\n/// What happens when certain input is received\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 6, "score": 169312.61084955165 }, { "content": "pub fn register(registry: &mut Registry) {\n\n registry.add_macro(\"utf8_state_table\", expand_state_table);\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 9, "score": 134338.26565698488 }, { "content": "fn build_table_ast(cx: &mut ExtCtxt, sp: Span, table: [[u8; 256]; 8]) -> P<ast::Expr> {\n\n let table = table\n\n .iter()\n\n .map(|list| {\n\n let exprs = list.iter().map(|num| cx.expr_u8(sp, *num)).collect();\n\n cx.expr_vec(sp, exprs)\n\n })\n\n .collect();\n\n\n\n cx.expr_vec(sp, table)\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 11, "score": 131941.56140445755 }, { "content": "struct VtUtf8Receiver<'a, P: Perform>(&'a mut P, &'a mut State);\n\n\n\nimpl<'a, P: Perform> utf8::Receiver for VtUtf8Receiver<'a, P> {\n\n fn codepoint(&mut self, c: char) {\n\n self.0.print(c);\n\n *self.1 = State::Ground;\n\n }\n\n\n\n fn invalid_sequence(&mut self) {\n\n self.0.print('�');\n\n *self.1 = State::Ground;\n\n }\n\n}\n\n\n\n/// Parser for raw _VTE_ protocol which delegates actions to a [`Perform`]\n\n///\n\n/// [`Perform`]: trait.Perform.html\n\n#[derive(Default)]\n\npub struct Parser {\n\n state: State,\n", "file_path": "src/lib.rs", "rank": 12, "score": 105149.64076554876 }, { "content": "fn expand_state_table<'cx>(\n\n cx: &'cx mut ExtCtxt,\n\n sp: Span,\n\n args: &[TokenTree],\n\n) -> Box<dyn MacResult + 'cx> {\n\n macro_rules! ptry {\n\n ($pres:expr) => {\n\n match $pres {\n\n Ok(val) => val,\n\n Err(mut err) => {\n\n err.emit();\n\n return DummyResult::any(sp);\n\n },\n\n }\n\n };\n\n }\n\n\n\n // Parse the lookup spec\n\n let mut parser: Parser = cx.new_parser_from_tts(args);\n\n let definitions = ptry!(parse_table_definition_list(&mut parser));\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 13, "score": 100704.10249409723 }, { "content": "fn parse_table_input_mappings<'a>(parser: &mut Parser<'a>) -> PResult<'a, Vec<Arm>> {\n\n // Must start on open brace\n\n parser.expect(&Token::OpenDelim(DelimToken::Brace))?;\n\n\n\n let mut arms: Vec<Arm> = Vec::new();\n\n while parser.token != Token::CloseDelim(DelimToken::Brace) {\n\n match parser.parse_arm() {\n\n Ok(arm) => arms.push(arm),\n\n Err(e) => {\n\n // Recover by skipping to the end of the block.\n\n return Err(e);\n\n },\n\n }\n\n }\n\n\n\n // Consume the closing brace\n\n parser.bump();\n\n Ok(arms)\n\n}\n\n\n\n/// Expressions describing state transitions and actions\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 15, "score": 97419.29160986189 }, { "content": "fn action_from_str<S>(s: &S) -> Result<Action, ()>\n\nwhere\n\n S: AsRef<str>,\n\n{\n\n Ok(match s.as_ref() {\n\n \"Action::InvalidSequence\" => Action::InvalidSequence,\n\n \"Action::EmitByte\" => Action::EmitByte,\n\n \"Action::SetByte1\" => Action::SetByte1,\n\n \"Action::SetByte2\" => Action::SetByte2,\n\n \"Action::SetByte2Top\" => Action::SetByte2Top,\n\n \"Action::SetByte3\" => Action::SetByte3,\n\n \"Action::SetByte3Top\" => Action::SetByte3Top,\n\n \"Action::SetByte4\" => Action::SetByte4,\n\n _ => return Err(()),\n\n })\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 18, "score": 94256.15725943007 }, { "content": "fn parse_table_definition<'a>(parser: &mut Parser<'a>) -> PResult<'a, TableDefinitionExprs> {\n\n let state_expr = parser.parse_expr()?;\n\n parser.expect(&Token::FatArrow)?;\n\n let mappings = parse_table_input_mappings(parser)?;\n\n\n\n Ok(TableDefinitionExprs { state_expr, mapping_arms: mappings })\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 20, "score": 94029.43119164807 }, { "content": "fn state_from_str<S>(s: &S) -> Result<State, ()>\n\nwhere\n\n S: AsRef<str>,\n\n{\n\n Ok(match s.as_ref() {\n\n \"State::Ground\" => State::Ground,\n\n \"State::Tail3\" => State::Tail3,\n\n \"State::Tail2\" => State::Tail2,\n\n \"State::Tail1\" => State::Tail1,\n\n \"State::U3_2_e0\" => State::U3_2_e0,\n\n \"State::U3_2_ed\" => State::U3_2_ed,\n\n \"State::Utf8_4_3_f0\" => State::Utf8_4_3_f0,\n\n \"State::Utf8_4_3_f4\" => State::Utf8_4_3_f4,\n\n _ => return Err(()),\n\n })\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 22, "score": 93705.00728216334 }, { "content": "#[derive(Debug)]\n\nenum InputDefinition {\n\n Specific(u8),\n\n Range { start: u8, end: u8 },\n\n}\n\n\n\nimpl InputDefinition {\n\n fn from_pat(pat: &Pat, cx: &mut ExtCtxt) -> Result<InputDefinition, ()> {\n\n Ok(match pat.node {\n\n PatKind::Lit(ref lit_expr) => {\n\n InputDefinition::Specific(u8_lit_from_expr(&lit_expr, cx)?)\n\n },\n\n PatKind::Range(ref start_expr, ref end_expr) => InputDefinition::Range {\n\n start: u8_lit_from_expr(start_expr, cx)?,\n\n end: u8_lit_from_expr(end_expr, cx)?,\n\n },\n\n _ => {\n\n cx.span_err(pat.span, \"expected literal or range expression\");\n\n return Err(());\n\n },\n\n })\n\n }\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 24, "score": 92964.41428309263 }, { "content": "#[derive(Debug)]\n\nstruct TableDefinitionExprs {\n\n state_expr: P<Expr>,\n\n mapping_arms: Vec<Arm>,\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 26, "score": 88954.21975643409 }, { "content": "fn build_state_tables<T>(defs: T) -> [[u8; 256]; 8]\n\nwhere\n\n T: AsRef<[TableDefinition]>,\n\n{\n\n let mut result = [[0u8; 256]; 8];\n\n\n\n for def in defs.as_ref() {\n\n let state = def.state;\n\n let state = state as u8;\n\n let transitions = &mut result[state as usize];\n\n\n\n for mapping in &def.mappings {\n\n let trans = mapping.transition.pack_u8();\n\n match mapping.input {\n\n InputDefinition::Specific(idx) => {\n\n transitions[idx as usize] = trans;\n\n },\n\n InputDefinition::Range { start, end } => {\n\n for idx in start..end {\n\n transitions[idx as usize] = trans;\n\n }\n\n transitions[end as usize] = trans;\n\n },\n\n }\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 28, "score": 81195.65942232686 }, { "content": "#[derive(Copy, Clone)]\n\nenum Transition {\n\n State(State),\n\n Action(Action),\n\n StateAction(State, Action),\n\n}\n\n\n\nimpl fmt::Debug for Transition {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n Transition::State(state) => write!(f, \"State({:?})\", state)?,\n\n Transition::Action(action) => write!(f, \"Action({:?})\", action)?,\n\n Transition::StateAction(state, action) => {\n\n write!(f, \"StateAction({:?}, {:?})\", state, action)?;\n\n },\n\n }\n\n\n\n write!(f, \" -> {:?}\", self.pack_u8())\n\n }\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 30, "score": 72784.02545419303 }, { "content": "#[derive(Debug)]\n\nstruct InputMapping {\n\n input: InputDefinition,\n\n transition: Transition,\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 32, "score": 69423.72151415823 }, { "content": "#[derive(Debug)]\n\nstruct TableDefinition {\n\n state: State,\n\n mappings: Vec<InputMapping>,\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 34, "score": 69075.82976467497 }, { "content": "fn parse_raw_definitions(\n\n definitions: Vec<TableDefinitionExprs>,\n\n cx: &mut ExtCtxt,\n\n) -> Result<Vec<TableDefinition>, ()> {\n\n let mut out = Vec::new();\n\n\n\n for raw in definitions {\n\n let TableDefinitionExprs { state_expr, mapping_arms } = raw;\n\n let state = state_from_expr(state_expr, cx)?;\n\n\n\n let mut mappings = Vec::new();\n\n for arm in mapping_arms {\n\n mappings.push(input_mapping_from_arm(arm, cx)?);\n\n }\n\n\n\n out.push(TableDefinition { state, mappings })\n\n }\n\n\n\n Ok(out)\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 36, "score": 62306.09846160344 }, { "content": "fn parse_table_definition_list<'a>(\n\n parser: &mut Parser<'a>,\n\n) -> PResult<'a, Vec<TableDefinitionExprs>> {\n\n let mut definitions = Vec::new();\n\n while parser.token != Token::Eof {\n\n definitions.push(parse_table_definition(parser)?);\n\n parser.eat(&Token::Comma);\n\n }\n\n\n\n Ok(definitions)\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 38, "score": 58560.53723839401 }, { "content": "/// A type implementing Perform that just logs actions\n\nstruct Log;\n\n\n\nimpl vte::Perform for Log {\n\n fn print(&mut self, c: char) {\n\n println!(\"[print] {:?}\", c);\n\n }\n\n\n\n fn execute(&mut self, byte: u8) {\n\n println!(\"[execute] {:02x}\", byte);\n\n }\n\n\n\n fn hook(&mut self, params: &[i64], intermediates: &[u8], ignore: bool, c: char) {\n\n println!(\n\n \"[hook] params={:?}, intermediates={:?}, ignore={:?}, char={:?}\",\n\n params, intermediates, ignore, c\n\n );\n\n }\n\n\n\n fn put(&mut self, byte: u8) {\n\n println!(\"[put] {:02x}\", byte);\n", "file_path": "examples/parselog.rs", "rank": 39, "score": 50189.50647864086 }, { "content": "/// Performs actions requested by the Parser\n\n///\n\n/// Actions in this case mean, for example, handling a CSI escape sequence describing cursor\n\n/// movement, or simply printing characters to the screen.\n\n///\n\n/// The methods on this type correspond to actions described in\n\n/// http://vt100.net/emu/dec_ansi_parser. I've done my best to describe them in\n\n/// a useful way in my own words for completeness, but the site should be\n\n/// referenced if something isn't clear. If the site disappears at some point in\n\n/// the future, consider checking archive.org.\n\npub trait Perform {\n\n /// Draw a character to the screen and update states\n\n fn print(&mut self, _: char);\n\n\n\n /// Execute a C0 or C1 control function\n\n fn execute(&mut self, byte: u8);\n\n\n\n /// Invoked when a final character arrives in first part of device control string\n\n ///\n\n /// The control function should be determined from the private marker, final character, and\n\n /// execute with a parameter list. A handler should be selected for remaining characters in the\n\n /// string; the handler function should subsequently be called by `put` for every character in\n\n /// the control string.\n\n ///\n\n /// The `ignore` flag indicates that more than two intermediates arrived and\n\n /// subsequent characters were ignored.\n\n fn hook(&mut self, params: &[i64], intermediates: &[u8], ignore: bool, _: char);\n\n\n\n /// Pass bytes as part of a device control string to the handle chosen in `hook`. C0 controls\n\n /// will also be passed to the handler.\n", "file_path": "src/lib.rs", "rank": 40, "score": 46987.734978876586 }, { "content": "/// Handles codepoint and invalid sequence events from the parser.\n\npub trait Receiver {\n\n /// Called whenever a codepoint is parsed successfully\n\n fn codepoint(&mut self, _: char);\n\n\n\n /// Called when an invalid_sequence is detected\n\n fn invalid_sequence(&mut self);\n\n}\n\n\n\n/// A parser for Utf8 Characters\n\n///\n\n/// Repeatedly call `advance` with bytes to emit Utf8 characters\n\n#[derive(Default)]\n\npub struct Parser {\n\n point: u32,\n\n state: State,\n\n}\n\n\n\n/// Continuation bytes are masked with this value.\n\nconst CONTINUATION_MASK: u8 = 0b0011_1111;\n\n\n", "file_path": "utf8parse/src/lib.rs", "rank": 41, "score": 45700.9635618507 }, { "content": "fn main() {\n\n let input = io::stdin();\n\n let mut handle = input.lock();\n\n\n\n let mut statemachine = vte::Parser::new();\n\n let mut parser = Log;\n\n\n\n let mut buf = [0; 2048];\n\n\n\n loop {\n\n match handle.read(&mut buf) {\n\n Ok(0) => break,\n\n Ok(n) => {\n\n for byte in &buf[..n] {\n\n statemachine.advance(&mut parser, *byte);\n\n }\n\n },\n\n Err(err) => {\n\n println!(\"err: {}\", err);\n\n break;\n\n },\n\n }\n\n }\n\n}\n", "file_path": "examples/parselog.rs", "rank": 42, "score": 45308.4515411734 }, { "content": "fn main() {\n\n // Expand VT parser state table\n\n let mut registry = syntex::Registry::new();\n\n ext::vt::register(&mut registry);\n\n let src = &Path::new(\"../src/table.rs.in\");\n\n let dst = &Path::new(\"../src/table.rs\");\n\n registry.expand(\"vt_state_table\", src, dst).expect(\"expand vt_stable_table ok\");\n\n\n\n // Expand UTF8 parser state table\n\n let mut registry = syntex::Registry::new();\n\n ext::utf8::register(&mut registry);\n\n let src = &Path::new(\"../utf8parse/src/table.rs.in\");\n\n let dst = &Path::new(\"../utf8parse/src/table.rs\");\n\n registry.expand(\"utf8_state_table\", src, dst).expect(\"expand utf8_stable_table ok\");\n\n}\n", "file_path": "codegen/src/main.rs", "rank": 43, "score": 43946.233916000056 }, { "content": "#[derive(Debug, PartialEq)]\n\nstruct StringWrapper(String);\n\n\n\nimpl Receiver for StringWrapper {\n\n fn codepoint(&mut self, c: char) {\n\n self.0.push(c);\n\n }\n\n\n\n fn invalid_sequence(&mut self) {}\n\n}\n\n\n", "file_path": "utf8parse/tests/utf-8-demo.rs", "rank": 44, "score": 43039.70707979653 }, { "content": "#[test]\n\nfn utf8parse_test() {\n\n let mut parser = Parser::new();\n\n\n\n // utf8parse implementation\n\n let mut actual = StringWrapper(String::new());\n\n\n\n for byte in UTF8_DEMO {\n\n parser.advance(&mut actual, *byte)\n\n }\n\n\n\n // standard library implementation\n\n let expected = String::from_utf8_lossy(UTF8_DEMO).to_string();\n\n\n\n assert_eq!(actual.0, expected);\n\n}\n", "file_path": "utf8parse/tests/utf-8-demo.rs", "rank": 45, "score": 41611.59951694531 }, { "content": "\n\nimpl Default for State {\n\n fn default() -> State {\n\n State::Ground\n\n }\n\n}\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug, Clone, Copy)]\n\npub enum Action {\n\n None = 0,\n\n Clear = 1,\n\n Collect = 2,\n\n CsiDispatch = 3,\n\n EscDispatch = 4,\n\n Execute = 5,\n\n Hook = 6,\n\n Ignore = 7,\n\n OscEnd = 8,\n\n OscPut = 9,\n", "file_path": "src/definitions.rs", "rank": 46, "score": 28112.10477169781 }, { "content": " (State::Utf8, Action::None) => (),\n\n _ => panic!(\"unpack failed\"),\n\n }\n\n\n\n match unpack(0xff) {\n\n (State::Utf8, Action::BeginUtf8) => (),\n\n _ => panic!(\"unpack failed\"),\n\n }\n\n }\n\n}\n", "file_path": "src/definitions.rs", "rank": 47, "score": 28109.121184199244 }, { "content": " OscStart = 10,\n\n Param = 11,\n\n Print = 12,\n\n Put = 13,\n\n Unhook = 14,\n\n BeginUtf8 = 15,\n\n}\n\n\n\n/// Unpack a u8 into a State and Action\n\n///\n\n/// The implementation of this assumes that there are *precisely* 16 variants for both Action and\n\n/// State. Furthermore, it assumes that the enums are tag-only; that is, there is no data in any\n\n/// variant.\n\n///\n\n/// Bad things will happen if those invariants are violated.\n\n#[inline(always)]\n", "file_path": "src/definitions.rs", "rank": 48, "score": 28105.152157257467 }, { "content": "#[allow(dead_code)]\n\n#[derive(Debug, Copy, Clone)]\n\npub enum State {\n\n Anywhere = 0,\n\n CsiEntry = 1,\n\n CsiIgnore = 2,\n\n CsiIntermediate = 3,\n\n CsiParam = 4,\n\n DcsEntry = 5,\n\n DcsIgnore = 6,\n\n DcsIntermediate = 7,\n\n DcsParam = 8,\n\n DcsPassthrough = 9,\n\n Escape = 10,\n\n EscapeIntermediate = 11,\n\n Ground = 12,\n\n OscString = 13,\n\n SosPmApcString = 14,\n\n Utf8 = 15,\n\n}\n", "file_path": "src/definitions.rs", "rank": 49, "score": 28103.664526754073 }, { "content": "pub mod utf8;\n\npub mod vt;\n", "file_path": "codegen/src/ext/mod.rs", "rank": 50, "score": 25817.544041026937 }, { "content": "impl Transition {\n\n // State is stored in the top 4 bits\n\n fn pack_u8(self) -> u8 {\n\n match self {\n\n Transition::State(state) => pack(state, Action::InvalidSequence),\n\n Transition::Action(action) => pack(State::Ground, action),\n\n Transition::StateAction(state, action) => pack(state, action),\n\n }\n\n }\n\n}\n\n\n\nimpl Transition {\n\n fn from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<Transition, ()> {\n\n match expr.node {\n\n ExprKind::Tup(ref tup_exprs) => {\n\n let mut action = None;\n\n let mut state = None;\n\n\n\n for tup_expr in tup_exprs {\n\n if let ExprKind::Path(_, ref path) = tup_expr.node {\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 52, "score": 32.19011556083309 }, { "content": " let path_str = path.to_string();\n\n if path_str.starts_with('A') {\n\n action = Some(action_from_str(&path_str).map_err(|_| {\n\n cx.span_err(expr.span, \"invalid action\");\n\n })?);\n\n } else {\n\n state = Some(state_from_str(&path_str).map_err(|_| {\n\n cx.span_err(expr.span, \"invalid state\");\n\n })?);\n\n }\n\n }\n\n }\n\n\n\n match (action, state) {\n\n (Some(action), Some(state)) => Ok(Transition::StateAction(state, action)),\n\n (None, Some(state)) => Ok(Transition::State(state)),\n\n (Some(action), None) => Ok(Transition::Action(action)),\n\n _ => {\n\n cx.span_err(expr.span, \"expected Action and/or State\");\n\n Err(())\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 54, "score": 31.895913831842694 }, { "content": " },\n\n }\n\n },\n\n ExprKind::Path(_, ref path) => {\n\n // Path can be Action or State\n\n let path_str = path.to_string();\n\n\n\n if path_str.starts_with('A') {\n\n let action = action_from_str(&path_str).map_err(|_| {\n\n cx.span_err(expr.span, \"invalid action\");\n\n })?;\n\n Ok(Transition::Action(action))\n\n } else {\n\n let state = state_from_str(&path_str).map_err(|_| {\n\n cx.span_err(expr.span, \"invalid state\");\n\n })?;\n\n\n\n Ok(Transition::State(state))\n\n }\n\n },\n\n _ => {\n\n cx.span_err(expr.span, \"expected Action and/or State\");\n\n Err(())\n\n },\n\n }\n\n }\n\n}\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 56, "score": 29.90396545101522 }, { "content": "//! Macro expansion for the utf8 parser state table\n\nuse std::fmt;\n\n\n\nuse syntex::Registry;\n\n\n\nuse syntex_syntax::ast::{self, Arm, Expr, ExprKind, LitKind, Pat, PatKind};\n\nuse syntex_syntax::codemap::Span;\n\nuse syntex_syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult};\n\nuse syntex_syntax::ext::build::AstBuilder;\n\nuse syntex_syntax::parse::parser::Parser;\n\nuse syntex_syntax::parse::token::{DelimToken, Token};\n\nuse syntex_syntax::parse::PResult;\n\nuse syntex_syntax::ptr::P;\n\nuse syntex_syntax::tokenstream::TokenTree;\n\n\n\n#[path = \"../../../utf8parse/src/types.rs\"]\n\nmod types;\n\n\n\nuse self::types::{pack, Action, State};\n\n\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 58, "score": 21.045780879354528 }, { "content": " where\n\n P: Perform,\n\n {\n\n let mut receiver = VtUtf8Receiver(performer, &mut self.state);\n\n let utf8_parser = &mut self.utf8_parser;\n\n utf8_parser.advance(&mut receiver, byte);\n\n }\n\n\n\n #[inline]\n\n fn perform_state_change<P>(&mut self, performer: &mut P, state: State, action: Action, byte: u8)\n\n where\n\n P: Perform,\n\n {\n\n macro_rules! maybe_action {\n\n ($action:expr, $arg:expr) => {\n\n match $action {\n\n Action::None => (),\n\n action => {\n\n self.perform_action(performer, action, $arg);\n\n },\n", "file_path": "src/lib.rs", "rank": 60, "score": 17.751207425785978 }, { "content": " 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8,\n\n ],\n\n];\n\n\n\npub static ENTRY_ACTIONS: &[Action] = &[\n\n Action::None, // State::Anywhere\n\n Action::Clear, // State::CsiEntry\n\n Action::None, // State::CsiIgnore\n\n Action::None, // State::CsiIntermediate\n\n Action::None, // State::CsiParam\n\n Action::Clear, // State::DcsEntry\n\n Action::None, // State::DcsIgnore\n\n Action::None, // State::DcsIntermediate\n\n Action::None, // State::DcsParam\n\n Action::Hook, // State::DcsPassthrough\n\n Action::Clear, // State::Escape\n\n Action::None, // State::EscapeIntermediate\n\n Action::None, // State::Ground\n\n Action::OscStart, // State::OscString\n", "file_path": "src/table.rs", "rank": 61, "score": 17.063017408424997 }, { "content": "impl Parser {\n\n /// Create a new Parser\n\n pub fn new() -> Parser {\n\n Parser { point: 0, state: State::Ground }\n\n }\n\n\n\n /// Advance the parser\n\n ///\n\n /// The provider receiver will be called whenever a codepoint is completed or an invalid\n\n /// sequence is detected.\n\n pub fn advance<R>(&mut self, receiver: &mut R, byte: u8)\n\n where\n\n R: Receiver,\n\n {\n\n let cur = self.state as usize;\n\n let change = TRANSITIONS[cur][byte as usize];\n\n let (state, action) = unsafe { unpack(change) };\n\n\n\n self.perform_action(receiver, byte, action);\n\n self.state = state;\n", "file_path": "utf8parse/src/lib.rs", "rank": 62, "score": 16.216758610442785 }, { "content": "mod definitions;\n\nmod table;\n\n\n\nuse definitions::{unpack, Action, State};\n\nuse table::{ENTRY_ACTIONS, EXIT_ACTIONS, STATE_CHANGE};\n\n\n\nimpl State {\n\n /// Get exit action for this state\n\n #[inline(always)]\n\n pub fn exit_action(self) -> Action {\n\n unsafe { *EXIT_ACTIONS.get_unchecked(self as usize) }\n\n }\n\n\n\n /// Get entry action for this state\n\n #[inline(always)]\n\n pub fn entry_action(self) -> Action {\n\n unsafe { *ENTRY_ACTIONS.get_unchecked(self as usize) }\n\n }\n\n}\n\n\n\nconst MAX_INTERMEDIATES: usize = 2;\n\n#[cfg(any(feature = \"no_std\", test))]\n\nconst MAX_OSC_RAW: usize = 1024;\n\nconst MAX_PARAMS: usize = 16;\n\n\n", "file_path": "src/lib.rs", "rank": 63, "score": 15.609257947240813 }, { "content": " let definitions = match parse_raw_definitions(definitions, cx) {\n\n Ok(definitions) => definitions,\n\n Err(_) => return DummyResult::any(sp),\n\n };\n\n\n\n let table = build_state_tables(&definitions);\n\n let ast = build_table_ast(cx, sp, table);\n\n\n\n MacEager::expr(ast)\n\n}\n", "file_path": "codegen/src/ext/utf8.rs", "rank": 64, "score": 14.497572259042744 }, { "content": " Action::None, // State::SosPmApcString\n\n Action::None,\n\n];\n\n// State::Utf8\n\n\n\npub static EXIT_ACTIONS: &[Action] = &[\n\n Action::None, // State::Anywhere\n\n Action::None, // State::CsiEntry\n\n Action::None, // State::CsiIgnore\n\n Action::None, // State::CsiIntermediate\n\n Action::None, // State::CsiParam\n\n Action::None, // State::DcsEntry\n\n Action::None, // State::DcsIgnore\n\n Action::None, // State::DcsIntermediate\n\n Action::None, // State::DcsParam\n\n Action::Unhook, // State::DcsPassthrough\n\n Action::None, // State::Escape\n\n Action::None, // State::EscapeIntermediate\n\n Action::None, // State::Ground\n\n Action::OscEnd, // State::OscString\n\n Action::None, // State::SosPmApcString\n\n Action::None,\n\n]; // State::Utf8\n", "file_path": "src/table.rs", "rank": 65, "score": 14.086121515263551 }, { "content": "//! A table-driven UTF-8 Parser\n\n//!\n\n//! This module implements a table-driven UTF-8 parser which should\n\n//! theoretically contain the minimal number of branches (1). The only branch is\n\n//! on the `Action` returned from unpacking a transition.\n\n#![no_std]\n\n\n\nuse core::char;\n\n\n\nmod table;\n\nmod types;\n\n\n\nuse table::TRANSITIONS;\n\nuse types::{unpack, Action, State};\n\n\n\n/// Handles codepoint and invalid sequence events from the parser.\n", "file_path": "utf8parse/src/lib.rs", "rank": 66, "score": 13.524225186542207 }, { "content": " for param in dispatcher.params.iter() {\n\n assert_eq!(param.len(), 0);\n\n }\n\n }\n\n\n\n #[test]\n\n fn parse_csi_max_params() {\n\n use crate::MAX_PARAMS;\n\n\n\n static INPUT: &[u8] = b\"\\x1b[1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;p\";\n\n\n\n // Create dispatcher and check state\n\n let mut dispatcher = CsiDispatcher::default();\n\n assert!(!dispatcher.dispatched_csi);\n\n\n\n // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in INPUT {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n", "file_path": "src/lib.rs", "rank": 67, "score": 13.446673354437092 }, { "content": " // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in INPUT {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n assert!(dispatcher.dispatched_dcs);\n\n assert_eq!(dispatcher.params, vec![0, 1]);\n\n assert_eq!(dispatcher.c, Some('|'));\n\n assert_eq!(dispatcher.s, b\"17/ab\".to_vec());\n\n }\n\n\n\n #[test]\n\n fn exceed_max_buffer_size() {\n\n static NUM_BYTES: usize = MAX_OSC_RAW + 100;\n\n static INPUT_START: &[u8] = &[0x1b, b']', b'5', b'2', b';', b's'];\n\n static INPUT_END: &[u8] = &[b'\\x07'];\n\n\n\n let mut dispatcher = OscDispatcher::default();\n\n let mut parser = Parser::new();\n", "file_path": "src/lib.rs", "rank": 68, "score": 12.536205067552412 }, { "content": "\n\n // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in INPUT {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n // Check that flag is set and thus osc_dispatch assertions ran.\n\n assert_eq!(dispatcher.params[0], &[b'2']);\n\n assert_eq!(dispatcher.params[1], &INPUT[5..(INPUT.len() - 1)]);\n\n }\n\n\n\n #[test]\n\n fn parse_dcs() {\n\n static INPUT: &[u8] =\n\n &[0x1b, 0x50, 0x30, 0x3b, 0x31, 0x7c, 0x31, 0x37, 0x2f, 0x61, 0x62, 0x9c];\n\n\n\n // Create dispatcher and check state\n\n let mut dispatcher = DcsDispatcher::default();\n\n\n", "file_path": "src/lib.rs", "rank": 69, "score": 12.345835848469271 }, { "content": "\n\n #[test]\n\n fn parse_osc_max_params() {\n\n use crate::MAX_PARAMS;\n\n\n\n static INPUT: &[u8] = b\"\\x1b];;;;;;;;;;;;;;;;;\\x1b\";\n\n\n\n // Create dispatcher and check state\n\n let mut dispatcher = OscDispatcher::default();\n\n assert_eq!(dispatcher.dispatched_osc, false);\n\n\n\n // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in INPUT {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n // Check that flag is set and thus osc_dispatch assertions ran.\n\n assert!(dispatcher.dispatched_osc);\n\n assert_eq!(dispatcher.params.len(), MAX_PARAMS);\n", "file_path": "src/lib.rs", "rank": 70, "score": 12.200428024633988 }, { "content": "//! Types supporting the UTF-8 parser\n\n#![allow(non_camel_case_types)]\n\nuse core::mem;\n\n\n\n/// States the parser can be in.\n\n///\n\n/// There is a state for each initial input of the 3 and 4 byte sequences since\n\n/// the following bytes are subject to different conditions than a tail byte.\n\n#[allow(dead_code)]\n\n#[derive(Debug, Copy, Clone)]\n\npub enum State {\n\n /// Ground state; expect anything\n\n Ground = 0,\n\n /// 3 tail bytes\n\n Tail3 = 1,\n\n /// 2 tail bytes\n\n Tail2 = 2,\n\n /// 1 tail byte\n\n Tail1 = 3,\n\n /// UTF8-3 starting with E0\n", "file_path": "utf8parse/src/types.rs", "rank": 71, "score": 12.081297724269689 }, { "content": "\n\n #[inline]\n\n fn params(&self) -> &[i64] {\n\n &self.params[..self.num_params]\n\n }\n\n\n\n #[inline]\n\n fn intermediates(&self) -> &[u8] {\n\n &self.intermediates[..self.intermediate_idx]\n\n }\n\n\n\n /// Advance the parser state\n\n ///\n\n /// Requires a [`Perform`] in case `byte` triggers an action\n\n ///\n\n /// [`Perform`]: trait.Perform.html\n\n #[inline]\n\n pub fn advance<P: Perform>(&mut self, performer: &mut P, byte: u8) {\n\n // Utf8 characters are handled out-of-band.\n\n if let State::Utf8 = self.state {\n", "file_path": "src/lib.rs", "rank": 72, "score": 11.91341743044648 }, { "content": " U3_2_e0 = 4,\n\n /// UTF8-3 starting with ED\n\n U3_2_ed = 5,\n\n /// UTF8-4 starting with F0\n\n Utf8_4_3_f0 = 6,\n\n /// UTF8-4 starting with F4\n\n Utf8_4_3_f4 = 7,\n\n}\n\n\n\nimpl Default for State {\n\n fn default() -> State {\n\n State::Ground\n\n }\n\n}\n\n\n\n/// Action to take when receiving a byte\n\n#[allow(dead_code)]\n\n#[derive(Debug, Copy, Clone)]\n\npub enum Action {\n\n /// Unexpected byte; sequence is invalid\n", "file_path": "utf8parse/src/types.rs", "rank": 73, "score": 11.775711549036515 }, { "content": " /// subsequent characters were ignored.\n\n fn esc_dispatch(&mut self, params: &[i64], intermediates: &[u8], ignore: bool, byte: u8);\n\n}\n\n\n\n#[cfg(all(test, feature = \"no_std\"))]\n\n#[macro_use]\n\nextern crate std;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use core::i64;\n\n use std::vec::Vec;\n\n\n\n static OSC_BYTES: &[u8] = &[\n\n 0x1b, 0x5d, // Begin OSC\n\n b'2', b';', b'j', b'w', b'i', b'l', b'm', b'@', b'j', b'w', b'i', b'l', b'm', b'-', b'd',\n\n b'e', b's', b'k', b':', b' ', b'~', b'/', b'c', b'o', b'd', b'e', b'/', b'a', b'l', b'a',\n\n b'c', b'r', b'i', b't', b't', b'y', 0x07, // End OSC\n", "file_path": "src/lib.rs", "rank": 74, "score": 11.7559430610578 }, { "content": " }\n\n };\n\n }\n\n\n\n match state {\n\n State::Anywhere => {\n\n // Just run the action\n\n self.perform_action(performer, action, byte);\n\n },\n\n state => {\n\n // Exit action for previous state\n\n let exit_action = self.state.exit_action();\n\n maybe_action!(exit_action, byte);\n\n\n\n // Transition action\n\n maybe_action!(action, byte);\n\n\n\n // Entry action for new state\n\n maybe_action!(state.entry_action(), byte);\n\n\n", "file_path": "src/lib.rs", "rank": 75, "score": 11.449852204664793 }, { "content": " #[test]\n\n fn parse_semi_set_underline() {\n\n // Create dispatcher and check state\n\n let mut dispatcher = CsiDispatcher::default();\n\n\n\n // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in b\"\\x1b[;4m\" {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n // Check that flag is set and thus osc_dispatch assertions ran.\n\n assert_eq!(dispatcher.params[0], &[0, 4]);\n\n }\n\n\n\n #[test]\n\n fn parse_long_csi_param() {\n\n // The important part is the parameter, which is (i64::MAX + 1)\n\n static INPUT: &[u8] = b\"\\x1b[9223372036854775808m\";\n\n\n", "file_path": "src/lib.rs", "rank": 76, "score": 11.338059662460454 }, { "content": " self.process_utf8(performer, byte);\n\n return;\n\n }\n\n\n\n // Handle state changes in the anywhere state before evaluating changes\n\n // for current state.\n\n let mut change = STATE_CHANGE[State::Anywhere as usize][byte as usize];\n\n\n\n if change == 0 {\n\n change = STATE_CHANGE[self.state as usize][byte as usize];\n\n }\n\n\n\n // Unpack into a state and action\n\n let (state, action) = unpack(change);\n\n\n\n self.perform_state_change(performer, state, action, byte);\n\n }\n\n\n\n #[inline]\n\n fn process_utf8<P>(&mut self, performer: &mut P, byte: u8)\n", "file_path": "src/lib.rs", "rank": 77, "score": 10.984323597924307 }, { "content": " ];\n\n\n\n #[derive(Default)]\n\n struct OscDispatcher {\n\n dispatched_osc: bool,\n\n params: Vec<Vec<u8>>,\n\n }\n\n\n\n // All empty bodies except osc_dispatch\n\n impl Perform for OscDispatcher {\n\n fn print(&mut self, _: char) {}\n\n\n\n fn execute(&mut self, _byte: u8) {}\n\n\n\n fn hook(&mut self, _params: &[i64], _intermediates: &[u8], _ignore: bool, _: char) {}\n\n\n\n fn put(&mut self, _byte: u8) {}\n\n\n\n fn unhook(&mut self) {}\n\n\n", "file_path": "src/lib.rs", "rank": 78, "score": 10.621841161441155 }, { "content": "#![allow(dead_code)]\n\n\n\nuse std::path::Path;\n\n\n\nuse syntex;\n\n\n\nmod ext;\n\n\n", "file_path": "codegen/src/main.rs", "rank": 79, "score": 10.048986664925387 }, { "content": " let num_params = self.osc_num_params;\n\n let params = &slices[..num_params] as *const [MaybeUninit<&[u8]>] as *const [&[u8]];\n\n performer.osc_dispatch(&*params);\n\n }\n\n }\n\n\n\n #[inline]\n\n fn perform_action<P: Perform>(&mut self, performer: &mut P, action: Action, byte: u8) {\n\n match action {\n\n Action::Print => performer.print(byte as char),\n\n Action::Execute => performer.execute(byte),\n\n Action::Hook => {\n\n self.params[self.num_params] = self.param;\n\n self.num_params += 1;\n\n\n\n performer.hook(self.params(), self.intermediates(), self.ignoring, byte as char);\n\n },\n\n Action::Put => performer.put(byte),\n\n Action::OscStart => {\n\n self.osc_raw.clear();\n", "file_path": "src/lib.rs", "rank": 80, "score": 9.804296570460986 }, { "content": " }\n\n\n\n fn perform_action<R>(&mut self, receiver: &mut R, byte: u8, action: Action)\n\n where\n\n R: Receiver,\n\n {\n\n match action {\n\n Action::InvalidSequence => {\n\n self.point = 0;\n\n receiver.invalid_sequence();\n\n },\n\n Action::EmitByte => {\n\n receiver.codepoint(byte as char);\n\n },\n\n Action::SetByte1 => {\n\n let point = self.point | ((byte & CONTINUATION_MASK) as u32);\n\n let c = unsafe { char::from_u32_unchecked(point) };\n\n self.point = 0;\n\n\n\n receiver.codepoint(c);\n", "file_path": "utf8parse/src/lib.rs", "rank": 81, "score": 9.801132222762577 }, { "content": "//! Parse input from stdin and log actions on stdout\n\nuse std::io::{self, Read};\n\n\n\nuse vte;\n\n\n\n/// A type implementing Perform that just logs actions\n", "file_path": "examples/parselog.rs", "rank": 82, "score": 9.177080146750539 }, { "content": " let mut dispatcher = CsiDispatcher::default();\n\n\n\n let mut parser = Parser::new();\n\n for byte in INPUT {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n assert_eq!(dispatcher.params[0], &[i64::MAX as i64]);\n\n }\n\n\n\n #[test]\n\n fn parse_osc_with_utf8_arguments() {\n\n static INPUT: &[u8] = &[\n\n 0x0d, 0x1b, 0x5d, 0x32, 0x3b, 0x65, 0x63, 0x68, 0x6f, 0x20, 0x27, 0xc2, 0xaf, 0x5c,\n\n 0x5f, 0x28, 0xe3, 0x83, 0x84, 0x29, 0x5f, 0x2f, 0xc2, 0xaf, 0x27, 0x20, 0x26, 0x26,\n\n 0x20, 0x73, 0x6c, 0x65, 0x65, 0x70, 0x20, 0x31, 0x07,\n\n ];\n\n\n\n // Create dispatcher and check state\n\n let mut dispatcher = OscDispatcher { params: vec![], dispatched_osc: false };\n", "file_path": "src/lib.rs", "rank": 83, "score": 9.12402276611482 }, { "content": " _byte: u8,\n\n ) {\n\n }\n\n }\n\n\n\n #[derive(Default)]\n\n struct CsiDispatcher {\n\n dispatched_csi: bool,\n\n params: Vec<Vec<i64>>,\n\n }\n\n\n\n impl Perform for CsiDispatcher {\n\n fn print(&mut self, _: char) {}\n\n\n\n fn execute(&mut self, _byte: u8) {}\n\n\n\n fn hook(&mut self, _params: &[i64], _intermediates: &[u8], _ignore: bool, _: char) {}\n\n\n\n fn put(&mut self, _byte: u8) {}\n\n\n", "file_path": "src/lib.rs", "rank": 84, "score": 8.630967536292859 }, { "content": "/// UTF8-tail = %x80-BF\n\n/// ```\n\n///\n\n/// Not specifying an action in this table is equivalent to specifying\n\n/// Action::InvalidSequence. Not specifying a state is equivalent to specifying\n\n/// state::ground.\n\npub static TRANSITIONS: [[u8; 256]; 8] = [\n\n [\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8,\n\n 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 16u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n", "file_path": "utf8parse/src/table.rs", "rank": 85, "score": 8.482163593451535 }, { "content": " struct DcsDispatcher {\n\n dispatched_dcs: bool,\n\n params: Vec<i64>,\n\n c: Option<char>,\n\n s: Vec<u8>,\n\n }\n\n\n\n impl Perform for DcsDispatcher {\n\n fn print(&mut self, _: char) {}\n\n\n\n fn execute(&mut self, _byte: u8) {}\n\n\n\n fn hook(&mut self, params: &[i64], _intermediates: &[u8], _ignore: bool, c: char) {\n\n self.c = Some(c);\n\n self.params = params.to_vec();\n\n }\n\n\n\n fn put(&mut self, byte: u8) {\n\n self.s.push(byte);\n\n }\n", "file_path": "src/lib.rs", "rank": 86, "score": 8.43138569000213 }, { "content": "//! Parser for implementing virtual terminal emulators\n\n//!\n\n//! [`Parser`] is implemented according to [Paul Williams' ANSI parser\n\n//! state machine]. The state machine doesn't assign meaning to the parsed data\n\n//! and is thus not itself sufficient for writing a terminal emulator. Instead,\n\n//! it is expected that an implementation of [`Perform`] is provided which does\n\n//! something useful with the parsed data. The [`Parser`] handles the book\n\n//! keeping, and the [`Perform`] gets to simply handle actions.\n\n//!\n\n//! # Examples\n\n//!\n\n//! For an example of using the [`Parser`] please see the examples folder. The example included\n\n//! there simply logs all the actions [`Perform`] does. One quick thing to see it in action is to\n\n//! pipe `vim` into it\n\n//!\n\n//! ```sh\n\n//! cargo build --release --example parselog\n\n//! vim | target/release/examples/parselog\n\n//! ```\n\n//!\n", "file_path": "src/lib.rs", "rank": 87, "score": 8.26593840693285 }, { "content": "/// This is the state change table. It's indexed first by current state and then by the next\n\n/// character in the pty stream.\n\nuse crate::definitions::Action;\n\n\n\npub static STATE_CHANGE: [[u8; 256]; 16] = [\n\n // Beginning of UTF-8 2 byte sequence\n\n // Beginning of UTF-8 3 byte sequence\n\n // Beginning of UTF-8 4 byte sequence\n\n [\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 92u8, 0u8, 92u8, 10u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n\n 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,\n", "file_path": "src/table.rs", "rank": 88, "score": 8.092224491393592 }, { "content": " _ignore: bool,\n\n _byte: u8,\n\n ) {\n\n }\n\n }\n\n\n\n #[test]\n\n fn parse_osc() {\n\n // Create dispatcher and check state\n\n let mut dispatcher = OscDispatcher::default();\n\n assert_eq!(dispatcher.dispatched_osc, false);\n\n\n\n // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in OSC_BYTES {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n // Check that flag is set and thus osc_dispatch assertions ran.\n\n assert!(dispatcher.dispatched_osc);\n", "file_path": "src/lib.rs", "rank": 89, "score": 8.08501392217632 }, { "content": "use utf8parse::{Parser, Receiver};\n\n\n\nstatic UTF8_DEMO: &[u8] = include_bytes!(\"UTF-8-demo.txt\");\n\n\n\n#[derive(Debug, PartialEq)]\n", "file_path": "utf8parse/tests/utf-8-demo.rs", "rank": 90, "score": 7.694083438934376 }, { "content": "//! Just type `:q` to exit.\n\n//!\n\n//! # Differences from original state machine description\n\n//!\n\n//! * UTF-8 Support for Input\n\n//! * OSC Strings can be terminated by 0x07\n\n//! * Only supports 7-bit codes. Some 8-bit codes are still supported, but they no longer work in\n\n//! all states.\n\n//!\n\n//! [`Parser`]: struct.Parser.html\n\n//! [`Perform`]: trait.Perform.html\n\n//! [Paul Williams' ANSI parser state machine]: https://vt100.net/emu/dec_ansi_parser\n\n#![cfg_attr(feature = \"no_std\", no_std)]\n\n\n\nuse core::mem::MaybeUninit;\n\n\n\n#[cfg(feature = \"no_std\")]\n\nuse arrayvec::ArrayVec;\n\nuse utf8parse as utf8;\n\n\n", "file_path": "src/lib.rs", "rank": 91, "score": 7.093587415985727 }, { "content": " // Assume the new state\n\n self.state = state;\n\n },\n\n }\n\n }\n\n\n\n /// Separate method for osc_dispatch that borrows self as read-only\n\n ///\n\n /// The aliasing is needed here for multiple slices into self.osc_raw\n\n #[inline]\n\n fn osc_dispatch<P: Perform>(&self, performer: &mut P) {\n\n let mut slices: [MaybeUninit<&[u8]>; MAX_PARAMS] =\n\n unsafe { MaybeUninit::uninit().assume_init() };\n\n\n\n for (i, slice) in slices.iter_mut().enumerate().take(self.osc_num_params) {\n\n let indices = self.osc_params[i];\n\n *slice = MaybeUninit::new(&self.osc_raw[indices.0..indices.1]);\n\n }\n\n\n\n unsafe {\n", "file_path": "src/lib.rs", "rank": 92, "score": 7.061683147507676 }, { "content": "\n\n fn unhook(&mut self) {\n\n self.dispatched_dcs = true;\n\n }\n\n\n\n fn osc_dispatch(&mut self, _params: &[&[u8]]) {}\n\n\n\n fn csi_dispatch(\n\n &mut self,\n\n _params: &[i64],\n\n _intermediates: &[u8],\n\n _ignore: bool,\n\n _c: char,\n\n ) {\n\n }\n\n\n\n fn esc_dispatch(\n\n &mut self,\n\n _params: &[i64],\n\n _intermediates: &[u8],\n", "file_path": "src/lib.rs", "rank": 93, "score": 6.603018251400583 }, { "content": " fn unhook(&mut self) {}\n\n\n\n fn osc_dispatch(&mut self, _params: &[&[u8]]) {}\n\n\n\n fn csi_dispatch(&mut self, params: &[i64], _intermediates: &[u8], _ignore: bool, _c: char) {\n\n self.dispatched_csi = true;\n\n self.params.push(params.to_vec());\n\n }\n\n\n\n fn esc_dispatch(\n\n &mut self,\n\n _params: &[i64],\n\n _intermediates: &[u8],\n\n _ignore: bool,\n\n _byte: u8,\n\n ) {\n\n }\n\n }\n\n\n\n #[derive(Default)]\n", "file_path": "src/lib.rs", "rank": 94, "score": 6.491854063963654 }, { "content": " fn osc_dispatch(&mut self, params: &[&[u8]]) {\n\n // Set a flag so we know these assertions all run\n\n self.dispatched_osc = true;\n\n self.params = params.iter().map(|p| p.to_vec()).collect();\n\n }\n\n\n\n fn csi_dispatch(\n\n &mut self,\n\n _params: &[i64],\n\n _intermediates: &[u8],\n\n _ignore: bool,\n\n _c: char,\n\n ) {\n\n }\n\n\n\n fn esc_dispatch(\n\n &mut self,\n\n _params: &[i64],\n\n _intermediates: &[u8],\n\n _ignore: bool,\n", "file_path": "src/lib.rs", "rank": 95, "score": 6.012349698912272 }, { "content": " }\n\n\n\n fn unhook(&mut self) {\n\n println!(\"[unhook]\");\n\n }\n\n\n\n fn osc_dispatch(&mut self, params: &[&[u8]]) {\n\n println!(\"[osc_dispatch] params={:?}\", params);\n\n }\n\n\n\n fn csi_dispatch(&mut self, params: &[i64], intermediates: &[u8], ignore: bool, c: char) {\n\n println!(\n\n \"[csi_dispatch] params={:?}, intermediates={:?}, ignore={:?}, char={:?}\",\n\n params, intermediates, ignore, c\n\n );\n\n }\n\n\n\n fn esc_dispatch(&mut self, params: &[i64], intermediates: &[u8], ignore: bool, byte: u8) {\n\n println!(\n\n \"[esc_dispatch] params={:?}, intermediates={:?}, ignore={:?}, byte={:02x}\",\n\n params, intermediates, ignore, byte\n\n );\n\n }\n\n}\n\n\n", "file_path": "examples/parselog.rs", "rank": 96, "score": 5.989774655668131 }, { "content": " intermediates: [u8; MAX_INTERMEDIATES],\n\n intermediate_idx: usize,\n\n params: [i64; MAX_PARAMS],\n\n param: i64,\n\n num_params: usize,\n\n #[cfg(feature = \"no_std\")]\n\n osc_raw: ArrayVec<[u8; MAX_OSC_RAW]>,\n\n #[cfg(not(feature = \"no_std\"))]\n\n osc_raw: Vec<u8>,\n\n osc_params: [(usize, usize); MAX_PARAMS],\n\n osc_num_params: usize,\n\n ignoring: bool,\n\n utf8_parser: utf8::Parser,\n\n}\n\n\n\nimpl Parser {\n\n /// Create a new Parser\n\n pub fn new() -> Parser {\n\n Parser::default()\n\n }\n", "file_path": "src/lib.rs", "rank": 97, "score": 5.9837586951344095 }, { "content": " assert_eq!(dispatcher.params.len(), 2);\n\n assert_eq!(dispatcher.params[0], &OSC_BYTES[2..3]);\n\n assert_eq!(dispatcher.params[1], &OSC_BYTES[4..(OSC_BYTES.len() - 1)]);\n\n }\n\n\n\n #[test]\n\n fn parse_empty_osc() {\n\n // Create dispatcher and check state\n\n let mut dispatcher = OscDispatcher::default();\n\n assert_eq!(dispatcher.dispatched_osc, false);\n\n\n\n // Run parser using OSC_BYTES\n\n let mut parser = Parser::new();\n\n for byte in &[0x1b, 0x5d, 0x07] {\n\n parser.advance(&mut dispatcher, *byte);\n\n }\n\n\n\n // Check that flag is set and thus osc_dispatch assertions ran.\n\n assert!(dispatcher.dispatched_osc);\n\n }\n", "file_path": "src/lib.rs", "rank": 98, "score": 5.719269203655373 }, { "content": " fn put(&mut self, byte: u8);\n\n\n\n /// Called when a device control string is terminated\n\n ///\n\n /// The previously selected handler should be notified that the DCS has\n\n /// terminated.\n\n fn unhook(&mut self);\n\n\n\n /// Dispatch an operating system command\n\n fn osc_dispatch(&mut self, params: &[&[u8]]);\n\n\n\n /// A final character has arrived for a CSI sequence\n\n ///\n\n /// The `ignore` flag indicates that more than two intermediates arrived and\n\n /// subsequent characters were ignored.\n\n fn csi_dispatch(&mut self, params: &[i64], intermediates: &[u8], ignore: bool, _: char);\n\n\n\n /// The final character of an escape sequence has arrived.\n\n ///\n\n /// The `ignore` flag indicates that more than two intermediates arrived and\n", "file_path": "src/lib.rs", "rank": 99, "score": 5.619215311223257 } ]
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.rs", "rank": 0, "score": 103091.71057563458 }, { "content": "fn display_vm_status(vm: &AoVM, vm_bak: &AoVM) {\n\n println!(\"\\n[VM Status]\");\n\n\n\n compare_disp!(PC, vm, vm_bak, pc);\n\n println!();\n\n compare_disp!(CA, vm, vm_bak, ca);\n\n println!();\n\n\n\n compare_disp!(DP, vm, vm_bak, dp);\n\n print!(\", \");\n\n compare_disp!(DSB, vm, vm_bak, dsb);\n\n print!(\", \");\n\n compare_disp!(DST, vm, vm_bak, ds.len());\n\n println!();\n\n\n\n print!(\"DS: \");\n\n for i in 0..vm.ds.len() {\n\n if i == vm.dsb as usize {\n\n if vm.dsb != vm_bak.dsb {\n\n print!(\"\\x1b[38;5;208m{{\\x1b[0m\");\n", "file_path": "examples/single_step.rs", "rank": 1, "score": 98958.20239915841 }, { "content": "pub trait AoOpcode: Display + Serializable {\n\n fn execute(&self, vm: &mut AoVM) -> AoStatus;\n\n}\n\n\n\nmacro_rules! impl_disp {\n\n ( $t:ty, $d:expr ) => {\n\n impl Display for $t {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, $d)\n\n }\n\n }\n\n };\n\n ( $t:ty, $d:expr, $($f:ident),* ) => {\n\n impl Display for $t {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, $d, $(self.$f),*)\n\n }\n\n }\n\n };\n\n ( $t:ty, $f:ident, $mt:expr, $mf:expr) => {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 2, "score": 60173.220131856026 }, { "content": "pub fn create_opcode_by_id(id: u8) -> Option<Box<dyn AoOpcode>> {\n\n match id {\n\n 0x00 => Some(Box::new(Nop)),\n\n\n\n 0x10 => Some(Box::new(Call { addr: 0 })),\n\n 0x11 => Some(Box::new(Ret)),\n\n 0x12 => Some(Box::new(Jmp { addr: 0 })),\n\n 0x13 => Some(Box::new(Jt { addr: 0 })),\n\n 0x14 => Some(Box::new(Jf { addr: 0 })),\n\n\n\n 0x20 => Some(Box::new(Mov {\n\n src: AoArg::CA,\n\n dst: AoArg::CA,\n\n })),\n\n 0x21 => Some(Box::new(Int { id: 0 })),\n\n 0x22 => Some(Box::new(Push { src: AoArg::CA })),\n\n 0x23 => Some(Box::new(Pop { to_ca: false })),\n\n\n\n 0x30 => Some(Box::new(Add { src: AoArg::CA })),\n\n 0x31 => Some(Box::new(Sub { src: AoArg::CA })),\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 3, "score": 44933.76988034649 }, { "content": "fn main() {\n\n let mut vm = AoVM::default();\n\n let program = ao_program![\n\n push dsb\n\n push \"Hello Aoi!\"\n\n cnf 1\n\n int 1\n\n ];\n\n\n\n // run\n\n let status = vm.run(&program);\n\n if let AoStatus::Exit = status {\n\n println!(\"\\nProcess finished.\");\n\n } else {\n\n eprintln!(\"\\nProcess terminated: {}.\", status);\n\n }\n\n println!();\n\n}\n", "file_path": "examples/hello_aoi.rs", "rank": 4, "score": 36655.501656083994 }, { "content": "fn main() {\n\n let mut vm = AoVM::default();\n\n\n\n // calculate 1 + 2 + ... + 10\n\n let program = ao_program![\n\n // a = 1\n\n /* 0 */ push 1\n\n // b = 0\n\n /* 1 */ push 0\n\n // while a <= 10 {\n\n /* 2 */ arg 0\n\n /* 3 */ mov ca,ds\n\n /* 4 */ le 10\n\n /* 5 */ jf 15\n\n // b = a + b\n\n /* 6 */ mov ca,ds\n\n /* 7 */ arg 1\n\n /* 8 */ add ds\n\n /* 9 */ mov ds,ca\n\n // a = a + 1\n", "file_path": "examples/single_step.rs", "rank": 5, "score": 36655.501656083994 }, { "content": "fn main() {\n\n let mut vm = AoVM::default();\n\n let program = ao_program![\n\n // arr = [ 3, 19, 5, 15, 1, 4, 16, 8 ]\n\n /* 0 */ mov mp,0\n\n /* 1 */ mov mem,3\n\n /* 2 */ mov mp,1\n\n /* 3 */ mov mem,19\n\n /* 4 */ mov mp,2\n\n /* 5 */ mov mem,5\n\n /* 6 */ mov mp,3\n\n /* 7 */ mov mem,15\n\n /* 8 */ mov mp,4\n\n /* 9 */ mov mem,1\n\n /* 10 */ mov mp,5\n\n /* 11 */ mov mem,4\n\n /* 12 */ mov mp,6\n\n /* 13 */ mov mem,16\n\n /* 14 */ mov mp,7\n\n /* 15 */ mov mem,8\n", "file_path": "examples/bubble_sort.rs", "rank": 6, "score": 36655.501656083994 }, { "content": "pub trait Serializable {\n\n fn get_id(&self) -> u8;\n\n fn get_args(&self) -> OpcodeArgType;\n\n fn set_args(&mut self, args: OpcodeArgType);\n\n}\n\n\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 7, "score": 34797.27768901359 }, { "content": "pub mod memory;\n\n\n\nuse super::AoOpcode;\n\nuse super::AoStatus;\n\nuse super::AoType;\n\nuse memory::Memory;\n\n\n\n/// Aoi VM.\n\npub struct AoVM {\n\n pub pc: u32,\n\n pub dp: u32,\n\n pub mp: u32,\n\n pub cs: Vec<u32>,\n\n\n\n pub dsb: u32,\n\n pub ca: AoType,\n\n\n\n pub ds: Vec<AoType>,\n\n pub mem: Memory,\n\n\n", "file_path": "src/runtime/vm/mod.rs", "rank": 8, "score": 25177.976005701283 }, { "content": "\n\n /// Go one step in the program.\n\n pub fn step(&mut self, program: &[Box<dyn AoOpcode>]) -> AoStatus {\n\n if self.pc < program.len() as u32 {\n\n let current = self.pc as usize;\n\n self.pc += 1;\n\n program[current].execute(self)\n\n } else {\n\n AoStatus::Exit\n\n }\n\n }\n\n\n\n /// Reset the VM.\n\n pub fn reset(&mut self) {\n\n self.pc = 0;\n\n self.dp = 0;\n\n self.mp = 0;\n\n self.cs.clear();\n\n\n\n self.dsb = 0;\n\n self.ca = AoType::default();\n\n\n\n self.ds.clear();\n\n self.mem = Memory::new();\n\n }\n\n}\n", "file_path": "src/runtime/vm/mod.rs", "rank": 9, "score": 25176.970621073615 }, { "content": " /// let mut vm = AoVM::default();\n\n /// vm.push(AoType::AoInt(1));\n\n /// assert_eq!(vm.ds.len(), 1);\n\n /// assert_eq!(vm.ds[0], AoType::AoInt(1));\n\n /// ```\n\n pub fn push(&mut self, value: AoType) -> bool {\n\n if self.ds.len() > 1000000 {\n\n return false;\n\n }\n\n\n\n self.ds.push(value);\n\n true\n\n }\n\n\n\n /// Pop a value from the data stack.\n\n ///\n\n /// # Examples\n\n /// ```\n\n /// use aoi::runtime::vm::AoVM;\n\n /// use aoi::runtime::types::AoType;\n", "file_path": "src/runtime/vm/mod.rs", "rank": 10, "score": 25171.100288255886 }, { "content": "}\n\n\n\nimpl Memory {\n\n pub fn new() -> Self {\n\n Memory {\n\n sections: Vec::with_capacity(256),\n\n }\n\n }\n\n\n\n pub fn get(&self, index: u32) -> AoType {\n\n let section_index = ((index >> 24) & 0xFF) as usize;\n\n if section_index >= self.sections.len() {\n\n AoType::default()\n\n } else {\n\n let section = self.sections[section_index].as_ref().unwrap();\n\n section.get(index)\n\n }\n\n }\n\n\n\n pub fn set(&mut self, index: u32, value: AoType) {\n", "file_path": "src/runtime/vm/memory.rs", "rank": 11, "score": 25170.122377506006 }, { "content": " AoType::AoFloat(v) => println!(\"{}\", v),\n\n AoType::AoString(v) => println!(\"{}\", v),\n\n _ => (),\n\n }\n\n None\n\n }\n\n _ => None,\n\n }\n\n }\n\n\n\n /// Create a new AoVM.\n\n pub fn new(int: fn(u8, Vec<AoType>) -> Option<AoType>) -> AoVM {\n\n AoVM {\n\n pc: 0,\n\n dp: 0,\n\n mp: 0,\n\n cs: Vec::new(),\n\n\n\n dsb: 0,\n\n ca: AoType::default(),\n", "file_path": "src/runtime/vm/mod.rs", "rank": 12, "score": 25169.606086281863 }, { "content": "\n\n ds: Vec::new(),\n\n mem: Memory::new(),\n\n\n\n interrupt: int,\n\n }\n\n }\n\n\n\n /// Create a new AoVM with default interrupt.\n\n pub fn default() -> AoVM {\n\n AoVM::new(AoVM::default_interrupt)\n\n }\n\n\n\n /// Push a value to the data stack.\n\n ///\n\n /// # Examples\n\n /// ```\n\n /// use aoi::runtime::vm::AoVM;\n\n /// use aoi::runtime::types::AoType;\n\n ///\n", "file_path": "src/runtime/vm/mod.rs", "rank": 13, "score": 25167.48035191819 }, { "content": " /// let mut vm = AoVM::default();\n\n /// vm.push(AoType::AoInt(1));\n\n /// vm.push(AoType::AoInt(2));\n\n ///\n\n /// assert_eq!(*vm.peek().unwrap(), AoType::AoInt(2));\n\n /// ```\n\n pub fn peek(&self) -> Option<&AoType> {\n\n self.ds.last()\n\n }\n\n\n\n /// Use the VM to execute a program.\n\n pub fn run(&mut self, program: &[Box<dyn AoOpcode>]) -> AoStatus {\n\n loop {\n\n let status = self.step(program);\n\n match status {\n\n AoStatus::Ok => (),\n\n _ => return status,\n\n }\n\n }\n\n }\n", "file_path": "src/runtime/vm/mod.rs", "rank": 14, "score": 25166.49172373565 }, { "content": "\n\n fn set(&mut self, index: u32, value: AoType) {\n\n let page_index = ((index >> 16) & 0xFF) as usize;\n\n while page_index >= self.pages.len() {\n\n self.pages.push(None);\n\n }\n\n\n\n if self.pages[page_index].is_none() {\n\n self.pages[page_index] = Some(Box::new(Page::new()));\n\n }\n\n self.pages[page_index]\n\n .as_mut()\n\n .unwrap()\n\n .set((index & 0xFFFF) as u16, value);\n\n }\n\n}\n\n\n\n#[derive(Default)]\n\npub struct Memory {\n\n sections: Vec<Option<Box<Section>>>,\n", "file_path": "src/runtime/vm/memory.rs", "rank": 15, "score": 25166.365578291363 }, { "content": " ///\n\n /// let mut vm = AoVM::default();\n\n /// vm.push(AoType::AoInt(1));\n\n /// vm.push(AoType::AoInt(2));\n\n ///\n\n /// assert_eq!(vm.pop().unwrap(), AoType::AoInt(2));\n\n /// assert_eq!(vm.pop().unwrap(), AoType::AoInt(1));\n\n /// assert_eq!(vm.pop(), None);\n\n /// ```\n\n pub fn pop(&mut self) -> Option<AoType> {\n\n self.ds.pop()\n\n }\n\n\n\n /// Get the value at the top of the data stack.\n\n ///\n\n /// # Examples\n\n /// ```\n\n /// use aoi::runtime::vm::AoVM;\n\n /// use aoi::runtime::types::AoType;\n\n ///\n", "file_path": "src/runtime/vm/mod.rs", "rank": 16, "score": 25166.128899907802 }, { "content": " pub interrupt: fn(u8, Vec<AoType>) -> Option<AoType>,\n\n}\n\n\n\nimpl AoVM {\n\n fn default_interrupt(id: u8, args: Vec<AoType>) -> Option<AoType> {\n\n match id {\n\n 1 => {\n\n match &args[0] {\n\n AoType::AoBool(v) => print!(\"{}\", v),\n\n AoType::AoInt(v) => print!(\"{}\", v),\n\n AoType::AoFloat(v) => print!(\"{}\", v),\n\n AoType::AoString(v) => print!(\"{}\", v),\n\n _ => (),\n\n }\n\n None\n\n }\n\n 2 => {\n\n match &args[0] {\n\n AoType::AoBool(v) => println!(\"{}\", v),\n\n AoType::AoInt(v) => println!(\"{}\", v),\n", "file_path": "src/runtime/vm/mod.rs", "rank": 17, "score": 25164.787042708238 }, { "content": "\n\n fn set(&mut self, index: u16, value: AoType) {\n\n let chip_index = (index >> 8) as usize;\n\n while chip_index >= self.chips.len() {\n\n self.chips.push(None);\n\n }\n\n\n\n if self.chips[chip_index].is_none() {\n\n self.chips[chip_index] = Some(Box::new(Chip::new()));\n\n }\n\n self.chips[chip_index]\n\n .as_mut()\n\n .unwrap()\n\n .set((index & 0xFF) as u8, value);\n\n }\n\n}\n\n\n", "file_path": "src/runtime/vm/memory.rs", "rank": 18, "score": 25164.028803984813 }, { "content": " let section_index = ((index >> 24) & 0xFF) as usize;\n\n while section_index >= self.sections.len() {\n\n self.sections.push(None);\n\n }\n\n\n\n if self.sections[section_index].is_none() {\n\n self.sections[section_index] = Some(Box::new(Section::new()));\n\n }\n\n self.sections[section_index]\n\n .as_mut()\n\n .unwrap()\n\n .set(index & 0xFFFFFF, value);\n\n }\n\n}\n", "file_path": "src/runtime/vm/memory.rs", "rank": 19, "score": 25162.373708281382 }, { "content": "use crate::AoType;\n\n\n", "file_path": "src/runtime/vm/memory.rs", "rank": 20, "score": 25157.71844209869 }, { "content": "struct Chip {\n\n data: Vec<AoType>,\n\n}\n\n\n\nimpl Chip {\n\n fn new() -> Chip {\n\n Chip {\n\n data: Vec::with_capacity(256),\n\n }\n\n }\n\n\n\n fn get(&self, index: u8) -> AoType {\n\n if index as usize >= self.data.len() {\n\n AoType::default()\n\n } else {\n\n self.data[index as usize].clone()\n\n }\n\n }\n\n\n\n fn set(&mut self, index: u8, value: AoType) {\n\n while index as usize >= self.data.len() {\n\n self.data.push(AoType::default());\n\n }\n\n self.data[index as usize] = value;\n\n }\n\n}\n\n\n", "file_path": "src/runtime/vm/memory.rs", "rank": 21, "score": 23896.75292599173 }, { "content": "struct Page {\n\n chips: Vec<Option<Box<Chip>>>,\n\n}\n\n\n\nimpl Page {\n\n fn new() -> Page {\n\n Page {\n\n chips: Vec::with_capacity(256),\n\n }\n\n }\n\n\n\n fn get(&self, index: u16) -> AoType {\n\n let chip_index = (index >> 8) as usize;\n\n if chip_index >= self.chips.len() {\n\n AoType::default()\n\n } else {\n\n let chip = self.chips[chip_index].as_ref().unwrap();\n\n chip.get((index & 0xff) as u8)\n\n }\n\n }\n", "file_path": "src/runtime/vm/memory.rs", "rank": 22, "score": 23896.75292599173 }, { "content": "struct Section {\n\n pages: Vec<Option<Box<Page>>>,\n\n}\n\n\n\nimpl Section {\n\n fn new() -> Section {\n\n Section {\n\n pages: Vec::with_capacity(256),\n\n }\n\n }\n\n\n\n fn get(&self, index: u32) -> AoType {\n\n let page_index = ((index >> 16) & 0xFF) as usize;\n\n if page_index >= self.pages.len() {\n\n AoType::default()\n\n } else {\n\n let page = self.pages[page_index].as_ref().unwrap();\n\n page.get((index & 0xFFFF) as u16)\n\n }\n\n }\n", "file_path": "src/runtime/vm/memory.rs", "rank": 23, "score": 23896.75292599173 }, { "content": " match self.dst.set_value(vm, self.src.get_value(vm)) {\n\n AoStatus::Ok => (),\n\n err => return err,\n\n }\n\n});\n\n\n\nopcode!(Int, 0x21, \"int {}\", u8 id, (&self, vm) {\n\n if self.id == 0 {\n\n return AoStatus::Exit;\n\n }\n\n\n\n let mut args: Vec<AoType> = Vec::new();\n\n for arg in vm.ds[vm.dsb as usize..].iter() {\n\n args.push(arg.clone());\n\n }\n\n\n\n if let Some(value) = (vm.interrupt)(self.id, args) {\n\n vm.ca = value;\n\n };\n\n\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 30, "score": 20.514569751286523 }, { "content": " };\n\n ( $at:ident, $rt:ty ) => {\n\n impl From<$rt> for AoType {\n\n fn from(t: $rt) -> AoType {\n\n AoType::$at(t)\n\n }\n\n }\n\n };\n\n}\n\n\n\nimpl_from!(AoBool, bool);\n\nimpl_from!(AoInt, i32);\n\nimpl_from!(AoFloat, f32);\n\nimpl_from!(AoPtr, u32);\n\nimpl_from!(AoString, String);\n\nimpl_from!(AoString, &str);\n", "file_path": "src/runtime/types/mod.rs", "rank": 31, "score": 20.439212758278313 }, { "content": "use crate::AoStatus;\n\nuse crate::AoType;\n\n\n\npub(super) struct AoTypeBinOper {\n\n name: &'static str,\n\n\n\n bool_oper: Option<fn(bool, bool) -> bool>,\n\n int_oper: Option<fn(i32, i32) -> i32>,\n\n float_oper: Option<fn(f32, f32) -> f32>,\n\n ptr_oper: Option<fn(u32, u32) -> u32>,\n\n string_oper: Option<fn(&String, &String) -> String>,\n\n}\n\n\n\nimpl AoTypeBinOper {\n\n pub fn apply(&self, left: AoType, right: AoType) -> AoStatus {\n\n match (&left, &right) {\n\n (AoType::AoBool(l), AoType::AoBool(r)) => {\n\n if let Some(res) = self.bool_oper.map(|oper| oper(*l, *r)) {\n\n return AoStatus::Return(AoType::AoBool(res));\n\n }\n", "file_path": "src/runtime/types/bin_oper.rs", "rank": 32, "score": 19.72312738847761 }, { "content": " return AoStatus::CallStackUnderflow;\n\n }\n\n\n\n let dsb = vm.dsb - 1;\n\n if let AoType::AoPtr(ptr) = vm.ds[dsb as usize] {\n\n vm.dsb = ptr;\n\n vm.ds.resize_with(dsb as usize, AoType::default);\n\n vm.pc = vm.cs.pop().unwrap();\n\n } else {\n\n return AoStatus::BadDataStack;\n\n }\n\n});\n\n\n\nopcode!(Jmp, 0x12, \"jmp {}\", u32 addr, (&self, vm) {\n\n vm.pc = self.addr;\n\n});\n\n\n\nopcode!(Jt, 0x13, \"jt {}\", u32 addr, (&self, vm) {\n\n if match vm.ca {\n\n AoType::AoBool(b) => b,\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 34, "score": 19.358908910042572 }, { "content": " /* 10 */ arg 0\n\n /* 11 */ mov ca,ds\n\n /* 12 */ inc\n\n /* 13 */ mov ds,ca\n\n // }\n\n /* 14 */ jmp 2\n\n // println b\n\n /* 15 */ push dsb\n\n /* 16 */ arg 1\n\n /* 17 */ push ds\n\n /* 18 */ cnf 1\n\n /* 19 */ int 2\n\n ];\n\n\n\n // run\n\n let mut vm_bak = clone_vm_status(&vm);\n\n loop {\n\n if vm.pc as usize >= program.len() {\n\n println!(\"\\nProcess finished.\");\n\n break;\n", "file_path": "examples/single_step.rs", "rank": 36, "score": 18.472077522260864 }, { "content": " let dsb = vm.dsb - 1;\n\n if let AoType::AoPtr(ptr) = vm.ds[dsb as usize] {\n\n vm.dsb = ptr;\n\n vm.ds.resize_with(dsb as usize, AoType::default);\n\n } else {\n\n return AoStatus::BadDataStack;\n\n }\n\n});\n\n\n\nopcode!(Push, 0x22, \"push {}\", src, (&self, vm) {\n\n if !vm.push(self.src.get_value(vm)) {\n\n return AoStatus::DataStackOverflow;\n\n }\n\n});\n\n\n\nopcode!(Pop, 0x23, \"pop ca\", \"pop\", bool to_ca, (&self, vm) {\n\n let value = vm.pop();\n\n if let Some(value) = value {\n\n if self.to_ca {\n\n vm.ca = value;\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 37, "score": 18.214040706621546 }, { "content": "mod bin_oper;\n\n\n\nuse std::fmt::Display;\n\nuse std::ops::*;\n\n\n\nuse super::AoStatus;\n\nuse bin_oper::*;\n\n\n\n/// The data type of the AOI virtual machine.\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum AoType {\n\n /// Boolean\n\n AoBool(bool),\n\n /// Integer, i32 in rust\n\n AoInt(i32),\n\n /// Float, f32 in rust\n\n AoFloat(f32),\n\n /// Pointer\n\n AoPtr(u32),\n\n /// String\n", "file_path": "src/runtime/types/mod.rs", "rank": 38, "score": 18.201711274834445 }, { "content": " };\n\n});\n\n\n\nopcode!(Isp, 0x6B, \"isp\", (&self, vm) {\n\n vm.ca = if let AoType::AoPtr(_) = &vm.ca {\n\n AoType::AoBool(true)\n\n } else {\n\n AoType::AoBool(false)\n\n };\n\n});\n\n\n\nopcode!(Iss, 0x6C, \"iss\", (&self, vm) {\n\n vm.ca = if let AoType::AoString(_) = &vm.ca {\n\n AoType::AoBool(true)\n\n } else {\n\n AoType::AoBool(false)\n\n };\n\n});\n\n\n\nopcode!(Arg, 0x70, \"arg {}\", u32 offset, (&self, vm) {\n\n vm.dp = vm.dsb + self.offset;\n\n});\n\n\n\nopcode!(Cnf, 0x71, \"cnf {}\", u32 argc, (&self, vm) {\n\n vm.dsb = vm.ds.len() as u32 - self.argc;\n\n});\n\n\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 40, "score": 17.06637196455579 }, { "content": " AoType::AoPtr(p) => vm.ca = AoType::AoInt(*p as i32),\n\n AoType::AoString(s) => vm.ca = AoType::AoInt(s.parse::<i32>().unwrap_or(0)),\n\n }\n\n});\n\n\n\nopcode!(Csf, 0x62, \"csf\", (&self, vm) {\n\n match &vm.ca {\n\n AoType::AoBool(b) => vm.ca = AoType::AoFloat(if *b { 1.0 } else { 0.0 }),\n\n AoType::AoInt(i) => vm.ca = AoType::AoFloat(*i as f32),\n\n AoType::AoFloat(_) => (),\n\n AoType::AoPtr(p) => vm.ca = AoType::AoFloat(*p as f32),\n\n AoType::AoString(s) => vm.ca = AoType::AoFloat(s.parse::<f32>().unwrap_or(0.0)),\n\n }\n\n});\n\n\n\nopcode!(Csp, 0x63, \"csp\", (&self, vm) {\n\n match &vm.ca {\n\n AoType::AoBool(b) => vm.ca = AoType::AoPtr(if *b { 1 } else { 0 }),\n\n AoType::AoInt(i) => vm.ca = AoType::AoPtr(*i as u32),\n\n AoType::AoFloat(f) => vm.ca = AoType::AoPtr(*f as u32),\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 42, "score": 15.860544842034619 }, { "content": " // if (arr[j + 1] < arr[j]) {\n\n /* 33 */ arg 2\n\n /* 34 */ mov ca,ds\n\n /* 35 */ csp\n\n /* 36 */ mov mp,ca\n\n /* 37 */ push mem\n\n /* 38 */ add 1\n\n /* 39 */ mov mp,ca\n\n /* 40 */ push mem\n\n /* 41 */ mov ca,dst\n\n /* 42 */ sub 2\n\n /* 43 */ mov dp,ca\n\n /* 44 */ pop ca\n\n /* 45 */ lt ds\n\n /* 46 */ pop\n\n /* 47 */ jf 69\n\n // tmp = arr[j + 1];\n\n /* 48 */ arg 2\n\n /* 49 */ mov ca,ds\n\n /* 50 */ add 1\n", "file_path": "examples/bubble_sort.rs", "rank": 43, "score": 15.710397089599038 }, { "content": " fn deserialize_arg(bin: &[u8], offset: &mut usize) -> Option<AoArg> {\n\n *offset += 1;\n\n match bin[*offset - 1] {\n\n 0x01 => Some(AoArg::PC),\n\n 0x02 => Some(AoArg::DP),\n\n 0x03 => Some(AoArg::MP),\n\n 0x11 => Some(AoArg::DSB),\n\n 0x12 => Some(AoArg::DST),\n\n 0x21 => Some(AoArg::CA),\n\n 0xE1 => Some(AoArg::DS),\n\n 0xE2 => Some(AoArg::MEM),\n\n 0xFF => Some(AoArg::Imm(\n\n AoAsmSerializer::deserialize_type(bin, offset).unwrap(),\n\n )),\n\n _ => None,\n\n }\n\n }\n\n\n\n fn deserialize_opcode(bin: &[u8], offset: &mut usize) -> Option<Box<dyn AoOpcode>> {\n\n *offset += 1;\n", "file_path": "src/serialization.rs", "rank": 44, "score": 15.491684397421574 }, { "content": " return res;\n\n }\n\n});\n\n\n\nopcode!(Shr, 0x38, \"shr {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() >> self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n\n});\n\n\n\nopcode!(And, 0x40, \"and {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n if let (AoType::AoBool(l), AoType::AoBool(r)) = (&left, &right) {\n\n vm.ca = AoType::AoBool(*l && *r);\n\n } else {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 45, "score": 14.391132241992114 }, { "content": " }\n\n print!(\"\\x1b[2J\"); // clear screen\n\n print!(\"\\x1b[H\"); // move cursor to top-left\n\n println!(\"{}: {}\", vm.pc, program[vm.pc as usize]);\n\n\n\n let status = vm.step(&program);\n\n match status {\n\n AoStatus::Ok => (),\n\n AoStatus::Exit => {\n\n println!(\"\\nProcess finished.\");\n\n break;\n\n }\n\n _ => {\n\n eprintln!(\"\\nProcess terminated: {}.\", status);\n\n break;\n\n }\n\n }\n\n display_vm_status(&vm, &vm_bak);\n\n vm_bak = clone_vm_status(&vm);\n\n std::io::stdin().read_line(&mut String::new()).unwrap();\n", "file_path": "examples/single_step.rs", "rank": 46, "score": 14.169588781479405 }, { "content": " AoType::AoInt(i) => i != 0,\n\n AoType::AoFloat(f) => f != 0.0,\n\n _ => false,\n\n } {\n\n vm.pc = self.addr;\n\n }\n\n});\n\n\n\nopcode!(Jf, 0x14, \"jf {}\", u32 addr, (&self, vm) {\n\n if !match vm.ca {\n\n AoType::AoBool(b) => b,\n\n AoType::AoInt(i) => i != 0,\n\n AoType::AoFloat(f) => f != 0.0,\n\n _ => false,\n\n } {\n\n vm.pc = self.addr;\n\n }\n\n});\n\n\n\nopcode!(Mov, 0x20, \"mov {},{}\", dst, src, (&self, vm) {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 47, "score": 14.008083654357847 }, { "content": " vm.ca = AoType::AoBool(left > right);\n\n }\n\n (AoType::AoFloat(left), AoType::AoFloat(right)) => {\n\n vm.ca = AoType::AoBool(left > right);\n\n }\n\n (AoType::AoString(left), AoType::AoString(right)) => {\n\n vm.ca = AoType::AoBool(left > right);\n\n }\n\n _ => return AoStatus::InvalidOperation(format!(\"{} > {}\", left, right)),\n\n }\n\n});\n\n\n\nopcode!(Lt, 0x53, \"lt {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n match (&left, &right) {\n\n (AoType::AoBool(left), AoType::AoBool(right)) => {\n\n vm.ca = AoType::AoBool(left < right);\n\n }\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 48, "score": 13.779201990628353 }, { "content": " }\n\n };\n\n ( $t:tt, $c:expr, $mt:expr, $mf:expr, bool $f:ident, (&$s:ident, $v:ident) $e:block ) => {\n\n #[derive(Clone)]\n\n pub struct $t {\n\n pub $f: bool,\n\n }\n\n impl_disp!($t, $f, $mt, $mf);\n\n impl_ao_opcode!( $t, (&$s, $v) { $e });\n\n impl Serializable for $t {\n\n fn get_id(&self) -> u8 {\n\n $c\n\n }\n\n fn get_args(&self) -> OpcodeArgType {\n\n OpcodeArgType::bool(self.$f.clone())\n\n }\n\n fn set_args(&mut self, args: OpcodeArgType){\n\n if let OpcodeArgType::bool($f) = args {\n\n self.$f = $f;\n\n }\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 49, "score": 13.725711385025559 }, { "content": " }\n\n (AoType::AoFloat(left), AoType::AoFloat(right)) => {\n\n vm.ca = AoType::AoBool(left != right);\n\n }\n\n (AoType::AoString(left), AoType::AoString(right)) => {\n\n vm.ca = AoType::AoBool(left != right);\n\n }\n\n _ => vm.ca = AoType::AoBool(true),\n\n }\n\n});\n\n\n\nopcode!(Gt, 0x52, \"gt {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n match (&left, &right) {\n\n (AoType::AoBool(left), AoType::AoBool(right)) => {\n\n vm.ca = AoType::AoBool(left > right);\n\n }\n\n (AoType::AoInt(left), AoType::AoInt(right)) => {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 50, "score": 13.644029396444951 }, { "content": " (AoType::AoFloat(left), AoType::AoFloat(right)) => {\n\n vm.ca = AoType::AoBool(left == right);\n\n }\n\n (AoType::AoString(left), AoType::AoString(right)) => {\n\n vm.ca = AoType::AoBool(left == right);\n\n }\n\n _ => vm.ca = AoType::AoBool(false),\n\n }\n\n});\n\n\n\nopcode!(Neq, 0x51, \"neq {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n match (left, right) {\n\n (AoType::AoBool(left), AoType::AoBool(right)) => {\n\n vm.ca = AoType::AoBool(left != right);\n\n }\n\n (AoType::AoInt(left), AoType::AoInt(right)) => {\n\n vm.ca = AoType::AoBool(left != right);\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 51, "score": 13.605080375176605 }, { "content": " vm.ca = AoType::AoBool(*l ^ *r);\n\n } else {\n\n return AoStatus::InvalidOperation(format!(\"{} ^ {}\", left, right));\n\n }\n\n});\n\n\n\nopcode!(Not, 0x43, \"not\", (&self, vm) {\n\n if let AoType::AoBool(b) = vm.ca {\n\n vm.ca = AoType::AoBool(!b);\n\n } else {\n\n return AoStatus::InvalidOperation(format!(\"!{}\", vm.ca));\n\n }\n\n});\n\n\n\nopcode!(Band, 0x44, \"band {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() & self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 52, "score": 13.407336031938964 }, { "content": " AoType::AoPtr(_) => (),\n\n AoType::AoString(s) => vm.ca = AoType::AoPtr(s.parse::<u32>().unwrap_or(0)),\n\n }\n\n});\n\n\n\nopcode!(Css, 0x64, \"css\", (&self, vm) {\n\n match &vm.ca {\n\n AoType::AoBool(b) => vm.ca = AoType::AoString(if *b {\n\n \"true\".to_string()\n\n } else {\n\n \"false\".to_string()\n\n }),\n\n AoType::AoInt(i) => vm.ca = AoType::AoString(i.to_string()),\n\n AoType::AoFloat(f) => vm.ca = AoType::AoString(f.to_string()),\n\n AoType::AoPtr(p) => vm.ca = AoType::AoString(p.to_string()),\n\n AoType::AoString(_) => (),\n\n }\n\n});\n\n\n\nopcode!(Isb, 0x68, \"isb\", (&self, vm) {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 53, "score": 13.245528248269329 }, { "content": "use std::fmt::Display;\n\n\n\nuse super::AoArg;\n\nuse crate::AoStatus;\n\nuse crate::AoType;\n\nuse crate::AoVM;\n\n\n\n#[allow(non_camel_case_types)]\n\npub enum OpcodeArgType {\n\n NoArg,\n\n u8(u8),\n\n u32(u32),\n\n bool(bool),\n\n AoArg(AoArg),\n\n AoArg2(AoArg, AoArg),\n\n}\n\n\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 54, "score": 13.135665070596502 }, { "content": " (AoType::AoInt(left), AoType::AoInt(right)) => {\n\n vm.ca = AoType::AoBool(left < right);\n\n }\n\n (AoType::AoFloat(left), AoType::AoFloat(right)) => {\n\n vm.ca = AoType::AoBool(left < right);\n\n }\n\n (AoType::AoString(left), AoType::AoString(right)) => {\n\n vm.ca = AoType::AoBool(left < right);\n\n }\n\n _ => return AoStatus::InvalidOperation(format!(\"{} < {}\", left, right)),\n\n }\n\n});\n\n\n\nopcode!(Ge, 0x54, \"ge {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n match (&left, &right) {\n\n (AoType::AoBool(left), AoType::AoBool(right)) => {\n\n vm.ca = AoType::AoBool(left >= right);\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 55, "score": 13.132176280639055 }, { "content": " }\n\n (AoType::AoInt(left), AoType::AoInt(right)) => {\n\n vm.ca = AoType::AoBool(left >= right);\n\n }\n\n (AoType::AoFloat(left), AoType::AoFloat(right)) => {\n\n vm.ca = AoType::AoBool(left >= right);\n\n }\n\n (AoType::AoString(left), AoType::AoString(right)) => {\n\n vm.ca = AoType::AoBool(left >= right);\n\n }\n\n _ => return AoStatus::InvalidOperation(format!(\"{} >= {}\", left, right)),\n\n }\n\n});\n\n\n\nopcode!(Le, 0x55, \"le {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n match (&left, &right) {\n\n (AoType::AoBool(left), AoType::AoBool(right)) => {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 56, "score": 13.066586978632815 }, { "content": " /* 85 */ lt ds\n\n /* 86 */ jf 103\n\n // print(arr[i] + \", \");\n\n /* 87 */ push dsb\n\n /* 88 */ arg 1\n\n /* 89 */ mov ca,ds\n\n /* 90 */ csp\n\n /* 91 */ mov mp,ca\n\n /* 92 */ mov ca,mem\n\n /* 93 */ css\n\n /* 94 */ add \", \"\n\n /* 95 */ push ca\n\n /* 96 */ cnf 1\n\n /* 97 */ int 1\n\n // }\n\n /* 98 */ arg 1\n\n /* 99 */ mov ca,ds\n\n /* 100 */ add 1\n\n /* 101 */ mov ds,ca\n\n /* 102 */ jmp 82\n", "file_path": "examples/bubble_sort.rs", "rank": 57, "score": 12.962772695742654 }, { "content": " /* 51 */ csp\n\n /* 52 */ mov mp,ca\n\n /* 53 */ push mem\n\n // arr[j + 1] = arr[j];\n\n /* 54 */ arg 2\n\n /* 55 */ mov ca,ds\n\n /* 56 */ csp\n\n /* 57 */ mov mp,ca\n\n /* 58 */ push mem\n\n /* 59 */ add 1\n\n /* 60 */ mov mp,ca\n\n /* 61 */ pop ca\n\n /* 62 */ mov mem,ca\n\n // arr[j] = tmp;\n\n /* 63 */ arg 2\n\n /* 64 */ mov ca,ds\n\n /* 65 */ csp\n\n /* 66 */ mov mp,ca\n\n /* 67 */ pop ca\n\n /* 68 */ mov mem,ca\n", "file_path": "examples/bubble_sort.rs", "rank": 58, "score": 12.941672106196672 }, { "content": " /// The call stack is empty.\n\n CallStackUnderflow,\n\n /// The data stack is full.\n\n DataStackOverflow,\n\n /// The data stack is empty.\n\n DataStackUnderflow,\n\n\n\n /// Try to set the type-restricted register to a different type value.\n\n SetValueInvalidType(String),\n\n /// Try to write to a read-only register or immediate value.\n\n SetValueInvalidTarget(String),\n\n\n\n /// Attempt to perform an incompatible operation between two types.\n\n InvalidOperation(String),\n\n\n\n /// Internal error.\n\n InternalError,\n\n}\n\n\n\nimpl Display for AoStatus {\n", "file_path": "src/runtime/status.rs", "rank": 59, "score": 12.937128001851297 }, { "content": " return AoStatus::InvalidOperation(format!(\"{} && {}\", left, right));\n\n }\n\n});\n\n\n\nopcode!(Or, 0x41, \"or {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n if let (AoType::AoBool(l), AoType::AoBool(r)) = (&left, &right) {\n\n vm.ca = AoType::AoBool(*l || *r);\n\n } else {\n\n return AoStatus::InvalidOperation(format!(\"{} || {}\", left, right));\n\n }\n\n});\n\n\n\nopcode!(Xor, 0x42, \"xor {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n if let (AoType::AoBool(l), AoType::AoBool(r)) = (&left, &right) {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 60, "score": 12.657874802541187 }, { "content": "use crate::opcodes::*;\n\nuse crate::AoArg;\n\nuse crate::AoProgram;\n\nuse crate::AoType;\n\n\n\n/// Serializer for serializing and deserializing the Aoi assembly.\n\npub enum AoAsmSerializer {}\n\n\n\nimpl AoAsmSerializer {\n\n fn serialize_type(value: &AoType) -> Vec<u8> {\n\n let mut result = Vec::new();\n\n match value {\n\n AoType::AoBool(value) => {\n\n result.push(0x01);\n\n result.push(if *value { 0x01 } else { 0x00 });\n\n }\n\n AoType::AoInt(value) => {\n\n result.push(0x02);\n\n result.extend_from_slice(&value.to_le_bytes());\n\n }\n", "file_path": "src/serialization.rs", "rank": 61, "score": 12.534824817845038 }, { "content": " }\n\n});\n\n\n\nopcode!(Bor, 0x45, \"bor {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() | self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n\n});\n\n\n\nopcode!(Bxor, 0x46, \"bxor {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() ^ self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n\n});\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 62, "score": 12.52330696840592 }, { "content": "\n\nopcode!(Bnot, 0x47, \"bnot\", (&self, vm) {\n\n if let AoType::AoInt(i) = vm.ca {\n\n vm.ca = AoType::AoInt(!i);\n\n } else {\n\n return AoStatus::InvalidOperation(format!(\"~{}\", vm.ca));\n\n }\n\n});\n\n\n\nopcode!(Equ, 0x50, \"equ {}\", src, (&self, vm) {\n\n let left = vm.ca.clone();\n\n let right = self.src.get_value(vm);\n\n\n\n match (left, right) {\n\n (AoType::AoBool(left), AoType::AoBool(right)) => {\n\n vm.ca = AoType::AoBool(left == right);\n\n }\n\n (AoType::AoInt(left), AoType::AoInt(right)) => {\n\n vm.ca = AoType::AoBool(left == right);\n\n }\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 63, "score": 12.515976508875706 }, { "content": " return res;\n\n }\n\n});\n\n\n\nopcode!(Mul, 0x32, \"mul {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() * self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n\n});\n\n\n\nopcode!(Div, 0x33, \"div {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() / self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 64, "score": 12.459531755573979 }, { "content": " };\n\n\n\n ( mov $dst:ident,$src:ident ) => {\n\n Box::new(opcodes::Mov {\n\n dst: AoArgLowerCase::$dst.to_aoarg(),\n\n src: AoArgLowerCase::$src.to_aoarg(),\n\n })\n\n };\n\n ( mov dp,$val:literal ) => {\n\n Box::new(opcodes::Mov {\n\n dst: AoArg::DP,\n\n src: AoArg::from($val as u32),\n\n })\n\n };\n\n ( mov mp,$val:literal ) => {\n\n Box::new(opcodes::Mov {\n\n dst: AoArg::MP,\n\n src: AoArg::from($val as u32),\n\n })\n\n };\n", "file_path": "src/runtime/opcode/macros.rs", "rank": 65, "score": 12.344305649520406 }, { "content": " }\n\n } else {\n\n return AoStatus::DataStackUnderflow;\n\n }\n\n});\n\n\n\nopcode!(Add, 0x30, \"add {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() + self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n\n});\n\n\n\nopcode!(Sub, 0x31, \"sub {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() - self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 66, "score": 12.272538593862123 }, { "content": " }\n\n});\n\n\n\nopcode!(Dec, 0x36, \"dec\", (&self, vm) {\n\n match vm.ca {\n\n AoType::AoInt(i) => {\n\n vm.ca = AoType::AoInt(i - 1);\n\n }\n\n AoType::AoFloat(f) => {\n\n vm.ca = AoType::AoFloat(f - 1.0);\n\n }\n\n _ => return AoStatus::InvalidOperation(format!(\"dec {}\", vm.ca)),\n\n }\n\n});\n\n\n\nopcode!(Shl, 0x37, \"shl {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() << self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 67, "score": 12.243063244932738 }, { "content": " AoArg::PC => {\n\n result.push(0x01);\n\n }\n\n AoArg::DP => {\n\n result.push(0x02);\n\n }\n\n AoArg::MP => {\n\n result.push(0x03);\n\n }\n\n AoArg::DSB => {\n\n result.push(0x11);\n\n }\n\n AoArg::DST => {\n\n result.push(0x12);\n\n }\n\n AoArg::CA => {\n\n result.push(0x21);\n\n }\n\n AoArg::DS => {\n\n result.push(0xE1);\n", "file_path": "src/serialization.rs", "rank": 68, "score": 12.213389164947742 }, { "content": "});\n\n\n\nopcode!(Rem, 0x34, \"rem {}\", src, (&self, vm) {\n\n let res = vm.ca.clone() % self.src.get_value(vm);\n\n if let AoStatus::Return(value) = res {\n\n vm.ca = value;\n\n } else {\n\n return res;\n\n }\n\n});\n\n\n\nopcode!(Inc, 0x35, \"inc\", (&self, vm) {\n\n match vm.ca {\n\n AoType::AoInt(i) => {\n\n vm.ca = AoType::AoInt(i + 1);\n\n }\n\n AoType::AoFloat(f) => {\n\n vm.ca = AoType::AoFloat(f + 1.0);\n\n }\n\n _ => return AoStatus::InvalidOperation(format!(\"inc {}\", vm.ca)),\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 69, "score": 12.174832663350589 }, { "content": " vm.ca = AoType::AoBool(left <= right);\n\n }\n\n (AoType::AoInt(left), AoType::AoInt(right)) => {\n\n vm.ca = AoType::AoBool(left <= right);\n\n }\n\n (AoType::AoFloat(left), AoType::AoFloat(right)) => {\n\n vm.ca = AoType::AoBool(left <= right);\n\n }\n\n (AoType::AoString(left), AoType::AoString(right)) => {\n\n vm.ca = AoType::AoBool(left <= right);\n\n }\n\n _ => return AoStatus::InvalidOperation(format!(\"{} <= {}\", left, right)),\n\n }\n\n});\n\n\n\nopcode!(Csi, 0x61, \"csi\", (&self, vm) {\n\n match &vm.ca {\n\n AoType::AoBool(b) => vm.ca = AoType::AoInt(if *b { 1 } else { 0 }),\n\n AoType::AoInt(_) => (),\n\n AoType::AoFloat(f) => vm.ca = AoType::AoInt(*f as i32),\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 70, "score": 12.172073902508398 }, { "content": " AoString(String),\n\n}\n\n\n\nimpl AoType {\n\n /// Create a default AoType.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use aoi::runtime::types::AoType;\n\n ///\n\n /// assert_eq!(AoType::default(), AoType::AoInt(0));\n\n /// ```\n\n pub fn default() -> AoType {\n\n AoType::AoInt(0)\n\n }\n\n}\n\n\n\nimpl Display for AoType {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n", "file_path": "src/runtime/types/mod.rs", "rank": 71, "score": 11.624794170508089 }, { "content": " };\n\n ( $t:tt, $c:expr, $d:expr, $ft:tt $f:ident, (&$s:ident, $v:ident) $e:block ) => {\n\n #[derive(Clone)]\n\n pub struct $t {\n\n pub $f: $ft,\n\n }\n\n impl_disp!($t, $d, $f);\n\n impl_ao_opcode!( $t, (&$s, $v) { $e });\n\n impl Serializable for $t {\n\n fn get_id(&self) -> u8 {\n\n $c\n\n }\n\n fn get_args(&self) -> OpcodeArgType {\n\n OpcodeArgType::$ft(self.$f.clone())\n\n }\n\n fn set_args(&mut self, args: OpcodeArgType) {\n\n if let OpcodeArgType::$ft($f) = args {\n\n self.$f = $f;\n\n }\n\n }\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 72, "score": 11.086307399964664 }, { "content": "pub mod opcode;\n\npub mod status;\n\npub mod types;\n\npub mod vm;\n\n\n\npub use opcode::*;\n\npub use status::AoStatus;\n\npub use types::AoType;\n\npub use vm::AoVM;\n", "file_path": "src/runtime/mod.rs", "rank": 73, "score": 10.65752544524627 }, { "content": " }\n\n }\n\n };\n\n ( $t:tt, $c:expr, $d:expr, $f1:ident, $f2:ident, (&$s:ident, $v:ident) $e:block ) => {\n\n #[derive(Clone)]\n\n pub struct $t {\n\n pub $f1: AoArg,\n\n pub $f2: AoArg,\n\n }\n\n impl_disp!($t, $d, $f1, $f2);\n\n impl_ao_opcode!( $t, (&$s, $v) { $e });\n\n impl Serializable for $t {\n\n fn get_id(&self) -> u8 {\n\n $c\n\n }\n\n fn get_args(&self) -> OpcodeArgType {\n\n OpcodeArgType::AoArg2(self.$f1.clone(), self.$f2.clone())\n\n }\n\n fn set_args(&mut self, args: OpcodeArgType){\n\n if let OpcodeArgType::AoArg2($f1, $f2) = args {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 74, "score": 10.623939885796151 }, { "content": " )))\n\n }\n\n 0x04 => {\n\n *offset += 5;\n\n Some(AoType::AoPtr(u32::from_le_bytes(\n\n bin[*offset - 4..*offset].try_into().unwrap(),\n\n )))\n\n }\n\n 0x05 => {\n\n let str_len =\n\n u32::from_le_bytes(bin[*offset + 1..*offset + 5].try_into().unwrap()) as usize;\n\n *offset += 5 + str_len;\n\n Some(AoType::AoString(\n\n String::from_utf8(bin[*offset - str_len..*offset].to_vec()).unwrap(),\n\n ))\n\n }\n\n _ => None,\n\n }\n\n }\n\n\n", "file_path": "src/serialization.rs", "rank": 75, "score": 9.960292706670327 }, { "content": " vm.ca = if let AoType::AoBool(_) = &vm.ca {\n\n AoType::AoBool(true)\n\n } else {\n\n AoType::AoBool(false)\n\n };\n\n});\n\n\n\nopcode!(Isi, 0x69, \"isi\", (&self, vm) {\n\n vm.ca = if let AoType::AoInt(_) = &vm.ca {\n\n AoType::AoBool(true)\n\n } else {\n\n AoType::AoBool(false)\n\n };\n\n});\n\n\n\nopcode!(Isf, 0x6A, \"isf\", (&self, vm) {\n\n vm.ca = if let AoType::AoFloat(_) = &vm.ca {\n\n AoType::AoBool(true)\n\n } else {\n\n AoType::AoBool(false)\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 76, "score": 9.878318149036046 }, { "content": " let opcode = create_opcode_by_id(bin[*offset - 1]);\n\n opcode.as_ref()?;\n\n let mut opcode = opcode.unwrap();\n\n\n\n match opcode.get_args() {\n\n OpcodeArgType::NoArg => (),\n\n OpcodeArgType::u8(_) => {\n\n *offset += 1;\n\n opcode.set_args(OpcodeArgType::u8(bin[*offset - 1]));\n\n }\n\n OpcodeArgType::u32(_) => {\n\n *offset += 4;\n\n opcode.set_args(OpcodeArgType::u32(u32::from_le_bytes(\n\n bin[*offset - 4..*offset].try_into().unwrap(),\n\n )));\n\n }\n\n OpcodeArgType::bool(_) => {\n\n *offset += 1;\n\n opcode.set_args(OpcodeArgType::bool(bin[*offset - 1] != 0x00));\n\n }\n", "file_path": "src/serialization.rs", "rank": 77, "score": 9.671008373250954 }, { "content": " }\n\n result\n\n }\n\n\n\n fn deserialize_type(bin: &[u8], offset: &mut usize) -> Option<AoType> {\n\n match bin[*offset] {\n\n 0x01 => {\n\n *offset += 2;\n\n Some(AoType::AoBool(bin[*offset - 1] != 0x00))\n\n }\n\n 0x02 => {\n\n *offset += 5;\n\n Some(AoType::AoInt(i32::from_le_bytes(\n\n bin[*offset - 4..*offset].try_into().unwrap(),\n\n )))\n\n }\n\n 0x03 => {\n\n *offset += 5;\n\n Some(AoType::AoFloat(f32::from_le_bytes(\n\n bin[*offset - 4..*offset].try_into().unwrap(),\n", "file_path": "src/serialization.rs", "rank": 78, "score": 9.635374557990001 }, { "content": "\n\nmacro_rules! opcode {\n\n ( $t:tt, $c:expr, $d:expr, (&$s:ident, $v:ident) $e:block ) => {\n\n #[derive(Clone)]\n\n pub struct $t;\n\n impl_disp!($t, $d);\n\n impl_ao_opcode!( $t, (&$s, $v) { $e });\n\n impl Serializable for $t {\n\n fn get_id(&self) -> u8 {\n\n $c\n\n }\n\n fn get_args(&self) -> OpcodeArgType {\n\n OpcodeArgType::NoArg\n\n }\n\n fn set_args(&mut self, _: OpcodeArgType) {\n\n }\n\n }\n\n };\n\n ( $t:tt, $c:expr, $d:expr, $f:ident, (&$s:ident, $v:ident) $e:block ) => {\n\n opcode!($t, $c, $d, AoArg $f, (&$s, $v) $e);\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 79, "score": 9.437056569070993 }, { "content": " impl Display for $t {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n if self.$f {\n\n write!(f, $mt)\n\n } else {\n\n write!(f, $mf)\n\n }\n\n }\n\n }\n\n };\n\n}\n\n\n\nmacro_rules! impl_ao_opcode {\n\n ( $t:tt, (&$s:ident, $v:ident) $e:block ) => {\n\n #[allow(unused_variables)]\n\n impl AoOpcode for $t {\n\n fn execute(&$s, $v: &mut AoVM) -> AoStatus { $e AoStatus::Ok }\n\n }\n\n };\n\n}\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 80, "score": 9.297804675100824 }, { "content": "use std::cmp::PartialEq;\n\nuse std::fmt::Display;\n\n\n\nuse super::AoType;\n\n\n\n/// Status in the runtime.\n\n#[derive(Debug, PartialEq)]\n\npub enum AoStatus {\n\n /// The program is running or the operation executed successfully.\n\n Ok,\n\n /// The program is finished.\n\n Exit,\n\n /// The operation returned a value.\n\n Return(AoType),\n\n\n\n /// The data stack not match the expected type.\n\n BadDataStack,\n\n\n\n /// The call stack is full.\n\n CallStackOverflow,\n", "file_path": "src/runtime/status.rs", "rank": 81, "score": 9.11081484512875 }, { "content": " AoType::AoFloat(value) => {\n\n result.push(0x03);\n\n result.extend_from_slice(&value.to_le_bytes());\n\n }\n\n AoType::AoPtr(value) => {\n\n result.push(0x04);\n\n result.extend_from_slice(&value.to_le_bytes());\n\n }\n\n AoType::AoString(value) => {\n\n result.push(0x05);\n\n result.extend_from_slice(&(value.len() as u32).to_le_bytes());\n\n result.extend_from_slice(value.as_bytes());\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn serialize_arg(value: &AoArg) -> Vec<u8> {\n\n let mut result = Vec::new();\n\n match value {\n", "file_path": "src/serialization.rs", "rank": 82, "score": 9.044072553950675 }, { "content": " }\n\n AoArg::MEM => {\n\n result.push(0xE2);\n\n }\n\n AoArg::Imm(value) => {\n\n result.push(0xFF);\n\n result.extend_from_slice(&AoAsmSerializer::serialize_type(value));\n\n }\n\n }\n\n result\n\n }\n\n\n\n fn serialize_opcode(opcode: &dyn AoOpcode) -> Vec<u8> {\n\n let mut result = vec![opcode.get_id()];\n\n match opcode.get_args() {\n\n OpcodeArgType::NoArg => (),\n\n OpcodeArgType::u8(value) => {\n\n result.extend_from_slice(value.to_le_bytes().as_ref());\n\n }\n\n OpcodeArgType::u32(value) => {\n", "file_path": "src/serialization.rs", "rank": 83, "score": 8.654584189936227 }, { "content": " self.$f1 = $f1;\n\n self.$f2 = $f2;\n\n }\n\n }\n\n }\n\n };\n\n}\n\n\n\nopcode!(Nop, 0x00, \"nop\", (&self, _vm) {});\n\n\n\nopcode!(Call, 0x10, \"call {}\", u32 addr, (&self, vm) {\n\n if vm.cs.len() >= 100000 {\n\n return AoStatus::CallStackOverflow;\n\n }\n\n vm.cs.push(vm.pc);\n\n vm.pc = self.addr;\n\n});\n\n\n\nopcode!(Ret, 0x11, \"ret\", (&self, vm) {\n\n if vm.cs.is_empty() {\n", "file_path": "src/runtime/opcode/opcodes.rs", "rank": 84, "score": 8.06878629776282 }, { "content": " OpcodeArgType::AoArg(_) => {\n\n let value = AoAsmSerializer::deserialize_arg(bin, offset).unwrap();\n\n opcode.set_args(OpcodeArgType::AoArg(value));\n\n }\n\n OpcodeArgType::AoArg2(_, _) => {\n\n let value1 = AoAsmSerializer::deserialize_arg(bin, offset).unwrap();\n\n let value2 = AoAsmSerializer::deserialize_arg(bin, offset).unwrap();\n\n opcode.set_args(OpcodeArgType::AoArg2(value1, value2));\n\n }\n\n }\n\n\n\n Some(opcode)\n\n }\n\n\n\n pub fn deserialize(value: &[u8]) -> Option<AoProgram> {\n\n let mut result = Vec::new();\n\n let mut offset = 0;\n\n while offset < value.len() {\n\n let opcode = AoAsmSerializer::deserialize_opcode(value, &mut offset);\n\n if let Some(opcode) = opcode {\n\n result.push(opcode);\n\n } else {\n\n return None;\n\n }\n\n }\n\n Some(result)\n\n }\n\n}\n", "file_path": "src/serialization.rs", "rank": 85, "score": 7.859438779164061 }, { "content": " } else {\n\n print!(\"{{\");\n\n }\n\n }\n\n if i >= vm_bak.ds.len() || vm.ds[i] != vm_bak.ds[i] {\n\n print!(\"\\x1b[38;5;208m[{}]\\x1b[0m\", vm.ds[i]);\n\n } else {\n\n print!(\"[{}]\", vm.ds[i]);\n\n }\n\n }\n\n println!(\"}}\");\n\n}\n\n\n", "file_path": "examples/single_step.rs", "rank": 86, "score": 7.614178939749854 }, { "content": " // }\n\n // }\n\n /* 69 */ arg 2\n\n /* 70 */ mov ca,ds\n\n /* 71 */ add 1\n\n /* 72 */ mov ds,ca\n\n /* 73 */ jmp 25\n\n /* 74 */ pop\n\n // }\n\n /* 75 */ arg 1\n\n /* 76 */ mov ca,ds\n\n /* 77 */ add 1\n\n /* 78 */ mov ds,ca\n\n /* 79 */ jmp 18\n\n /* 80 */ pop\n\n // for (i = 0; i < len; i++) {\n\n /* 81 */ push 0\n\n /* 82 */ arg 1\n\n /* 83 */ mov ca,ds\n\n /* 84 */ arg 0\n", "file_path": "examples/bubble_sort.rs", "rank": 87, "score": 7.294144892236947 }, { "content": "}\n\n\n\nimpl_oper!(Add, add, BIN_OPER_ADD);\n\nimpl_oper!(Sub, sub, BIN_OPER_SUB);\n\nimpl_oper!(Mul, mul, BIN_OPER_MUL);\n\nimpl_oper!(Div, div, BIN_OPER_DIV);\n\nimpl_oper!(Rem, rem, BIN_OPER_REM);\n\nimpl_oper!(BitAnd, bitand, BIN_OPER_BAND);\n\nimpl_oper!(BitOr, bitor, BIN_OPER_BOR);\n\nimpl_oper!(BitXor, bitxor, BIN_OPER_BXOR);\n\nimpl_oper!(Shl, shl, BIN_OPER_SHL);\n\nimpl_oper!(Shr, shr, BIN_OPER_SHR);\n\n\n\nmacro_rules! impl_from {\n\n ( $at:ident, &str ) => {\n\n impl From<&str> for AoType {\n\n fn from(t: &str) -> AoType {\n\n AoType::$at(t.to_string())\n\n }\n\n }\n", "file_path": "src/runtime/types/mod.rs", "rank": 88, "score": 7.195166885285529 }, { "content": " match self {\n\n AoType::AoBool(v) => write!(f, \"{}\", v),\n\n AoType::AoInt(v) => write!(f, \"{}\", v),\n\n AoType::AoFloat(v) => write!(f, \"{}f\", v),\n\n AoType::AoPtr(v) => write!(f, \"{}p\", v),\n\n AoType::AoString(v) => write!(f, \"\\\"{}\\\"\", v),\n\n }\n\n }\n\n}\n\n\n\nmacro_rules! impl_oper {\n\n ( $tr:ident, $fn:ident, $op:ident ) => {\n\n impl $tr for AoType {\n\n type Output = AoStatus;\n\n\n\n fn $fn(self, other: AoType) -> AoStatus {\n\n $op.apply(self, other)\n\n }\n\n }\n\n };\n", "file_path": "src/runtime/types/mod.rs", "rank": 89, "score": 7.178230743840972 }, { "content": "mod macros;\n\n\n\npub mod args;\n\npub mod opcodes;\n\n\n\npub use args::{AoArg, AoArgLowerCase};\n\npub use opcodes::AoOpcode;\n", "file_path": "src/runtime/opcode/mod.rs", "rank": 90, "score": 6.7172440580900545 }, { "content": "pub mod runtime;\n\npub mod serialization;\n\n\n\npub use runtime::*;\n\npub use serialization::AoAsmSerializer;\n\n\n\npub type AoProgram = Vec<Box<dyn runtime::opcode::AoOpcode>>;\n", "file_path": "src/lib.rs", "rank": 91, "score": 6.714036880130758 }, { "content": " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match self {\n\n AoStatus::Ok => write!(f, \"Ok\"),\n\n AoStatus::Exit => write!(f, \"Exit\"),\n\n AoStatus::Return(v) => write!(f, \"Return({})\", v),\n\n\n\n AoStatus::BadDataStack => write!(f, \"Bad Data Stack\"),\n\n\n\n AoStatus::CallStackOverflow => write!(f, \"Call Stack Overflow\"),\n\n AoStatus::CallStackUnderflow => write!(f, \"Call Stack Underflow\"),\n\n AoStatus::DataStackOverflow => write!(f, \"Data Stack Overflow\"),\n\n AoStatus::DataStackUnderflow => write!(f, \"Data Stack Underflow\"),\n\n\n\n AoStatus::SetValueInvalidType(v) => write!(f, \"Set Value Invalid Type({})\", v),\n\n AoStatus::SetValueInvalidTarget(v) => {\n\n write!(f, \"Set Value Invalid Target({})\", v)\n\n }\n\n\n\n AoStatus::InvalidOperation(v) => write!(f, \"Invalid Operation({})\", v),\n\n\n\n AoStatus::InternalError => write!(f, \"Internal Error\"),\n\n }\n\n }\n\n}\n", "file_path": "src/runtime/status.rs", "rank": 92, "score": 6.705363272224082 }, { "content": " // len = 8\n\n /* 16 */ push 8\n\n // for (i = 0; i + 1 < len; i++) {\n\n /* 17 */ push 0\n\n /* 18 */ arg 1\n\n /* 19 */ mov ca,ds\n\n /* 20 */ add 1\n\n /* 21 */ arg 0\n\n /* 22 */ lt ds\n\n /* 23 */ jf 80\n\n // for (j = 0; j + 1 + i < len; j++) {\n\n /* 24 */ push 0\n\n /* 25 */ arg 2\n\n /* 26 */ mov ca,ds\n\n /* 27 */ add 1\n\n /* 28 */ arg 1\n\n /* 29 */ add ds\n\n /* 30 */ arg 0\n\n /* 31 */ lt ds\n\n /* 32 */ jf 74\n", "file_path": "examples/bubble_sort.rs", "rank": 93, "score": 6.503688827159609 }, { "content": " result.extend_from_slice(value.to_le_bytes().as_ref());\n\n }\n\n OpcodeArgType::bool(value) => {\n\n result.push(if value { 0x01 } else { 0x00 });\n\n }\n\n OpcodeArgType::AoArg(value) => {\n\n result.extend_from_slice(&AoAsmSerializer::serialize_arg(&value));\n\n }\n\n OpcodeArgType::AoArg2(value1, value2) => {\n\n result.extend_from_slice(&AoAsmSerializer::serialize_arg(&value1));\n\n result.extend_from_slice(&AoAsmSerializer::serialize_arg(&value2));\n\n }\n\n }\n\n result\n\n }\n\n\n\n pub fn serialize(asm: &[Box<dyn AoOpcode>]) -> Vec<u8> {\n\n let mut result = Vec::new();\n\n for opcode in asm {\n\n result.extend_from_slice(&AoAsmSerializer::serialize_opcode(opcode.as_ref()));\n", "file_path": "src/serialization.rs", "rank": 94, "score": 6.222230935898764 }, { "content": ");\n\n\n\nbop!(BIN_OPER_SHR, >>,\n\n int_oper: op!(>>),\n\n);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n macro_rules! test_op {\n\n ( $op:ident, $lv:expr, $rv:expr, $res:expr ) => {\n\n test_op!(\n\n $op,\n\n AoString,\n\n $lv.to_string(),\n\n $rv.to_string(),\n\n $res.to_string()\n\n );\n\n };\n", "file_path": "src/runtime/types/bin_oper.rs", "rank": 95, "score": 5.209212541705025 }, { "content": " ( mov $dst:ident,$val:literal ) => {\n\n Box::new(opcodes::Mov {\n\n dst: AoArgLowerCase::$dst.to_aoarg(),\n\n src: AoArg::from($val),\n\n })\n\n };\n\n ( int $id:literal ) => {\n\n Box::new(opcodes::Int { id: $id as u8 })\n\n };\n\n ( push $src:ident ) => {\n\n Box::new(opcodes::Push {\n\n src: AoArgLowerCase::$src.to_aoarg(),\n\n })\n\n };\n\n ( push $val:literal ) => {\n\n Box::new(opcodes::Push {\n\n src: AoArg::from($val),\n\n })\n\n };\n\n ( pop ) => {\n", "file_path": "src/runtime/opcode/macros.rs", "rank": 96, "score": 5.058752960145869 }, { "content": " Box::new(opcodes::Pop { to_ca: false })\n\n };\n\n ( pop ca ) => {\n\n Box::new(opcodes::Pop { to_ca: true })\n\n };\n\n\n\n ( add $src:ident ) => {\n\n Box::new(opcodes::Add {\n\n src: AoArgLowerCase::$src.to_aoarg(),\n\n })\n\n };\n\n ( add $val:literal ) => {\n\n Box::new(opcodes::Add {\n\n src: AoArg::from($val),\n\n })\n\n };\n\n ( sub $src:ident ) => {\n\n Box::new(opcodes::Sub {\n\n src: AoArgLowerCase::$src.to_aoarg(),\n\n })\n", "file_path": "src/runtime/opcode/macros.rs", "rank": 97, "score": 4.9741472546421095 }, { "content": " }\n\n (AoType::AoPtr(l), AoType::AoPtr(r)) => {\n\n if let Some(res) = self.ptr_oper.map(|oper| oper(*l, *r)) {\n\n return AoStatus::Return(AoType::AoPtr(res));\n\n }\n\n }\n\n (AoType::AoPtr(l), AoType::AoInt(r)) => {\n\n if let Some(res) = self.ptr_oper.map(|oper| oper(*l, *r as u32)) {\n\n return AoStatus::Return(AoType::AoPtr(res));\n\n }\n\n }\n\n (AoType::AoInt(l), AoType::AoPtr(r)) => {\n\n if let Some(res) = self.int_oper.map(|oper| oper(*l, *r as i32)) {\n\n return AoStatus::Return(AoType::AoInt(res));\n\n }\n\n }\n\n (AoType::AoString(l), AoType::AoString(r)) => {\n\n if let Some(res) = self.string_oper.map(|oper| oper(l, r)) {\n\n return AoStatus::Return(AoType::AoString(res));\n\n }\n", "file_path": "src/runtime/types/bin_oper.rs", "rank": 98, "score": 4.753900869013007 }, { "content": " }\n\n _ => (),\n\n };\n\n AoStatus::InvalidOperation(format!(\"{} {} {}\", left, self.name, right))\n\n }\n\n}\n\n\n\nstatic BIN_OPER_NONE: AoTypeBinOper = AoTypeBinOper {\n\n name: \"\",\n\n bool_oper: None,\n\n int_oper: None,\n\n float_oper: None,\n\n ptr_oper: None,\n\n string_oper: None,\n\n};\n\n\n\nmacro_rules! bop {\n\n ( $name:ident, $dname:tt, $( $fname:ident : $fvalue:expr ),*, ) => {\n\n #[allow(clippy::needless_update)]\n\n pub(super) static $name: AoTypeBinOper = AoTypeBinOper {\n", "file_path": "src/runtime/types/bin_oper.rs", "rank": 99, "score": 4.0654697828982265 } ]
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<TokenStream>>>()?;\n\n let result = quote! {{\n\n let x = |output: &mut ::std::fmt::Formatter| -> ::std::fmt::Result {\n\n use ::std::fmt;\n\n use ::std::write;\n\n\n\n #(#nodes)*\n\n Ok(())\n\n };\n\n\n\n ::minihtml::Html(x)\n\n }};\n\n Ok(result)\n\n}\n\n\n", "file_path": "codegen/src/lib.rs", "rank": 3, "score": 41612.305671160924 }, { "content": "#[proc_macro_hack::proc_macro_hack]\n\npub fn html(input: pm1::TokenStream) -> pm1::TokenStream {\n\n html_impl(input.into())\n\n .unwrap_or_else(|err| err.to_compile_error())\n\n .into()\n\n}\n\n\n", "file_path": "codegen/src/lib.rs", "rank": 4, "score": 40112.9421774597 }, { "content": "fn write_node(node: parse::HtmlNode) -> syn::Result<TokenStream> {\n\n Ok(match node {\n\n parse::HtmlNode::Arbitrary(_, expr) => {\n\n quote! {\n\n ::minihtml::ToHtmlNode::fmt(#expr, output)?;\n\n }\n\n }\n\n parse::HtmlNode::Element(element) => {\n\n let element_name = element.name.as_ref();\n\n let write_attrs = write_el_attrs(&element)?;\n\n let write_child = match element.children {\n\n Some(inner_nodes) => {\n\n let inner_nodes = inner_nodes\n\n .nodes\n\n .into_iter()\n\n .map(write_node)\n\n .collect::<syn::Result<Vec<_>>>()?;\n\n quote! {\n\n write!(output, \">\")?;\n\n #(#inner_nodes)*\n", "file_path": "codegen/src/lib.rs", "rank": 5, "score": 39527.10613572103 }, { "content": "fn write_el_attrs(element: &parse::HtmlElement) -> syn::Result<TokenStream> {\n\n let mut static_attrs = HashMap::new();\n\n let mut dyn_attrs = vec![];\n\n for attr in element.attributes.iter().flat_map(|(_, attr)| attr) {\n\n match attr {\n\n parse::Attribute::Static(attr) => {\n\n if static_attrs.contains_key(attr.name.as_ref()) {\n\n return Err(syn::Error::new(\n\n attr.span(),\n\n &format!(\"Duplicate attribute \\\"{}\\\"\", &attr.name.name),\n\n ))?;\n\n }\n\n static_attrs.insert(\n\n attr.name.as_ref().to_string(),\n\n attr.value\n\n .as_ref()\n\n .map_or_else(|| quote!(true), |(_, expr)| quote!(#expr)),\n\n );\n\n }\n\n parse::Attribute::Dyn(attr) => {\n", "file_path": "codegen/src/lib.rs", "rank": 6, "score": 38577.07831059852 }, { "content": "#[test]\n\nfn test_basic() {\n\n let variable = \"quz qux\";\n\n let is_enabled = false;\n\n let ret: String = html_string! {\n\n html {\n\n head {\n\n title { +\"Test title\" };\n\n }\n\n body {\n\n img(src = \"https://example.com\");\n\n div(class = \"foo bar\") { +variable };\n\n button(disabled = !is_enabled) { +\"the button\" }\n\n }\n\n }\n\n };\n\n\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n assert_eq!(ret.as_str(), \"<html>\\\n\n <head>\\\n\n <title>Test title</title>\\\n\n </head>\\\n\n <body>\\\n\n <img src=\\\"https://example.com\\\"/>\\\n\n <div class=\\\"foo bar\\\">quz qux</div>\\\n\n <button disabled>the button</button>\\\n\n </body>\\\n\n </html>\");\n\n}\n", "file_path": "tests/basic.rs", "rank": 7, "score": 29917.996532972247 }, { "content": "fn ctx<D: fmt::Display>(d: D) -> impl Fn(syn::Error) -> syn::Error {\n\n move |err| syn::Error::new(err.span(), format!(\"{}: {}\", &d, err))\n\n}\n\n\n", "file_path": "codegen/src/lib.rs", "rank": 8, "score": 25826.180286314677 }, { "content": "use std::cmp::PartialEq;\n\nuse std::hash::{Hash, Hasher};\n\n\n\nuse proc_macro2::Span;\n\nuse syn::parse::{Parse, ParseStream};\n\nuse syn::spanned::Spanned;\n\n\n\n#[cfg_attr(test, derive(Debug))]\n\npub struct Hyphenated {\n\n pub name: String,\n\n span: Span,\n\n}\n\n\n\nimpl AsRef<str> for Hyphenated {\n\n fn as_ref(&self) -> &str {\n\n self.name.as_str()\n\n }\n\n}\n\n\n\nimpl PartialEq<Hyphenated> for Hyphenated {\n", "file_path": "codegen/src/parse/name.rs", "rank": 10, "score": 19412.664107390705 }, { "content": " fn eq(&self, other: &Self) -> bool {\n\n &self.name == &other.name\n\n }\n\n}\n\n\n\nimpl Eq for Hyphenated {}\n\n\n\nimpl Hash for Hyphenated {\n\n fn hash<H>(&self, state: &mut H)\n\n where\n\n H: Hasher,\n\n {\n\n self.name.hash(state)\n\n }\n\n}\n\n\n\nimpl Parse for Hyphenated {\n\n fn parse(input: ParseStream) -> syn::parse::Result<Self> {\n\n let first = input.parse::<syn::Ident>()?;\n\n let mut name = first.to_string();\n", "file_path": "codegen/src/parse/name.rs", "rank": 11, "score": 19412.27857029635 }, { "content": "mod tests {\n\n use super::*;\n\n use proc_quote::quote;\n\n\n\n #[test]\n\n fn parse_simple_ident() {\n\n let parsed = syn::parse2::<Hyphenated>(quote!(abc)).unwrap();\n\n assert_eq!(parsed.name.as_str(), \"abc\");\n\n }\n\n\n\n #[test]\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n fn parse_hyphenated_ident() {\n\n let parsed = syn::parse2::<Hyphenated>(quote!(abc - def-ghi)).unwrap();\n\n assert_eq!(parsed.name.as_str(), \"abc-def-ghi\");\n\n }\n\n\n\n #[test]\n\n fn parse_alphanum() {\n\n let parsed = syn::parse2::<Hyphenated>(quote!(abc - de0 - g2i)).unwrap();\n\n assert_eq!(parsed.name.as_str(), \"abc-de0-g2i\");\n\n }\n\n}\n", "file_path": "codegen/src/parse/name.rs", "rank": 12, "score": 19410.020353238735 }, { "content": " let mut span = first.span();\n\n while input.peek(syn::Token![-]) {\n\n let hyphen = input.parse::<syn::Token![-]>().unwrap();\n\n name.push('-');\n\n span = span.join(hyphen.span()).unwrap_or(span);\n\n let ident = input.parse::<syn::Ident>()?;\n\n name.push_str(&ident.to_string());\n\n span = span.join(ident.span()).unwrap_or(span);\n\n }\n\n Ok(Hyphenated { name, span })\n\n }\n\n}\n\n\n\nimpl Spanned for Hyphenated {\n\n fn span(&self) -> Span {\n\n self.span\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "codegen/src/parse/name.rs", "rank": 13, "score": 19409.912787833266 }, { "content": "use std::fmt;\n\n\n\nuse super::{Escaped, NoSpecial, Result, ToHtmlAttr, ToHtmlNode, ToWholeHtmlAttr};\n\n\n\nimpl<T: ToHtmlNode + ?Sized> ToHtmlNode for &T {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result {\n\n ToHtmlNode::fmt(&**self, f)\n\n }\n\n}\n\n\n\nimpl<T: ToHtmlAttr + ?Sized> ToHtmlAttr for &T {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result {\n\n ToHtmlAttr::fmt(&**self, f)\n\n }\n\n}\n\n\n\nimpl ToHtmlNode for str {\n\n #[inline]\n", "file_path": "src/primitives.rs", "rank": 15, "score": 9.142783047703588 }, { "content": " fn fmt(&self, f: &mut fmt::Formatter) -> Result {\n\n write!(f, \"{}\", Escaped(self.as_ref()))\n\n }\n\n}\n\n\n\nimpl ToHtmlAttr for str {\n\n #[inline]\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result {\n\n write!(f, \"{}\", Escaped(self.as_ref()))\n\n }\n\n}\n\n\n\nimpl ToWholeHtmlAttr for bool {\n\n #[inline]\n\n fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result {\n\n if *self {\n\n write!(f, \" {}\", name.0)?;\n\n }\n\n Ok(())\n\n }\n", "file_path": "src/primitives.rs", "rank": 17, "score": 8.264391958744943 }, { "content": " }\n\n };\n\n}\n\n\n\nmod name;\n\npub use name::*;\n\n\n\nmod attr;\n\npub use attr::*;\n\n\n\nmod element;\n\npub use element::*;\n\n\n\nmod id_class;\n\npub use id_class::*;\n\n\n\npub struct HtmlNodes {\n\n pub nodes: Vec<HtmlNode>,\n\n span: Span,\n\n}\n", "file_path": "codegen/src/parse/mod.rs", "rank": 19, "score": 7.066368052754898 }, { "content": " pub name: ClassName,\n\n}\n\n\n\nimpl Parse for DotClass {\n\n fn parse(input: ParseStream) -> syn::parse::Result<Self> {\n\n Ok(Self {\n\n dot: input.parse()?,\n\n name: input.parse()?,\n\n })\n\n }\n\n}\n\n\n\nimpl_span!(DotClass = name << dot);\n\n\n\npub type IdName = super::Hyphenated;\n\npub type ClassName = super::Hyphenated;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use proc_quote::quote;\n", "file_path": "codegen/src/parse/id_class.rs", "rank": 20, "score": 6.62402844651975 }, { "content": "use syn::parse::{Parse, ParseStream};\n\n\n\npub struct HashId {\n\n pub hash: syn::Token![#],\n\n pub name: IdName,\n\n}\n\n\n\nimpl Parse for HashId {\n\n fn parse(input: ParseStream) -> syn::parse::Result<Self> {\n\n Ok(Self {\n\n hash: input.parse()?,\n\n name: input.parse()?,\n\n })\n\n }\n\n}\n\n\n\nimpl_span!(HashId = name << hash);\n\n\n\npub struct DotClass {\n\n pub dot: syn::Token![.],\n", "file_path": "codegen/src/parse/id_class.rs", "rank": 21, "score": 6.620969295002688 }, { "content": "}\n\n\n\nimpl<T: ToHtmlAttr> ToWholeHtmlAttr for Option<T> {\n\n #[inline]\n\n fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result {\n\n if let Some(value) = self {\n\n write!(f, \" {}=\\\"\", name.0)?;\n\n ToHtmlAttr::fmt(value, f)?;\n\n write!(f, \"\\\"\")?;\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/primitives.rs", "rank": 22, "score": 6.615957067511457 }, { "content": "use proc_macro2::Span;\n\nuse syn::parse::{Parse, ParseStream};\n\nuse syn::punctuated::Punctuated;\n\nuse syn::spanned::Spanned;\n\n\n\nuse super::{Attribute, DotClass, HashId, HtmlNodes};\n\n\n\npub struct HtmlElement {\n\n pub name: ElementName,\n\n pub classes: Vec<DotClass>,\n\n pub id: Option<HashId>,\n\n pub attributes: Option<(syn::token::Paren, Punctuated<Attribute, syn::Token![,]>)>,\n\n pub children: Option<HtmlNodes>,\n\n span: Span,\n\n}\n\n\n\nimpl Parse for HtmlElement {\n\n fn parse(input: ParseStream) -> syn::parse::Result<Self> {\n\n use crate::ctx;\n\n\n", "file_path": "codegen/src/parse/element.rs", "rank": 23, "score": 6.54447826991038 }, { "content": "use std::fmt;\n\n\n\nuse super::{Result, ToHtmlAttr};\n\n\n\n/// Concatenates hardcoded and dynamic classes.\n\n///\n\n/// The first field is a user-provided value.\n\n/// The second field is a static str from the macro.\n\npub struct ClassConcat<A>(pub A, pub &'static str)\n\nwhere\n\n A: AsRef<str>;\n\n\n\nimpl<A> ToHtmlAttr for ClassConcat<A>\n\nwhere\n\n A: AsRef<str>,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter) -> Result {\n\n write!(f, \"{}\", self.1)?;\n\n let str = self.0.as_ref();\n\n if str.len() > 0 {\n\n write!(f, \" {}\", str)?;\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/hc.rs", "rank": 24, "score": 6.413199969774874 }, { "content": " let mut span = self.name.span();\n\n span = self.dyn_.span().join(span).unwrap_or(span);\n\n if let Some((eq, expr)) = &self.value {\n\n span = span.join(eq.span()).unwrap_or(span);\n\n span = span.join(expr.span()).unwrap_or(span);\n\n }\n\n span\n\n }\n\n}\n\n\n\npub type AttributeName = super::Hyphenated;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use matches2::unwrap_match;\n\n use proc_quote::quote;\n\n\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "codegen/src/parse/attr.rs", "rank": 25, "score": 5.655069972849322 }, { "content": " attributes,\n\n children,\n\n span,\n\n })\n\n }\n\n}\n\n\n\nimpl Spanned for HtmlElement {\n\n fn span(&self) -> Span {\n\n self.span\n\n }\n\n}\n\n\n\npub type ElementName = super::Hyphenated;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n // use matches2::unwrap_match;\n\n use proc_quote::quote;\n\n\n", "file_path": "codegen/src/parse/element.rs", "rank": 26, "score": 4.865572976568462 }, { "content": " pub dyn_: syn::Token![dyn],\n\n pub name: syn::Expr,\n\n pub value: Option<(syn::Token![=], syn::Expr)>,\n\n}\n\n\n\nimpl Parse for DynAttribute {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n let dyn_ = input.parse()?;\n\n let name = input.parse()?;\n\n let value = if input.peek(syn::Token![=]) {\n\n Some((input.parse()?, input.parse()?))\n\n } else {\n\n None\n\n };\n\n Ok(DynAttribute { dyn_, name, value })\n\n }\n\n}\n\n\n\nimpl Spanned for DynAttribute {\n\n fn span(&self) -> Span {\n", "file_path": "codegen/src/parse/attr.rs", "rank": 28, "score": 4.669703697062906 }, { "content": "impl Spanned for Attribute {\n\n fn span(&self) -> Span {\n\n match self {\n\n Self::Static(sa) => sa.span(),\n\n Self::Dyn(dyn_) => dyn_.span(),\n\n }\n\n }\n\n}\n\n\n\n#[cfg_attr(test, derive(Debug))]\n\npub struct StaticAttribute {\n\n pub name: AttributeName,\n\n pub value: Option<(syn::Token![=], syn::Expr)>,\n\n}\n\n\n\nimpl Parse for StaticAttribute {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n let name = input.parse()?;\n\n let value = if input.peek(syn::Token![=]) {\n\n Some((input.parse().unwrap(), input.parse()?))\n", "file_path": "codegen/src/parse/attr.rs", "rank": 29, "score": 4.521612257829566 }, { "content": "use proc_macro2::Span;\n\nuse syn::parse::{Parse, ParseStream};\n\nuse syn::spanned::Spanned;\n\n\n\n#[cfg_attr(test, derive(Debug))]\n\npub enum Attribute {\n\n Static(StaticAttribute),\n\n Dyn(DynAttribute),\n\n}\n\n\n\nimpl Parse for Attribute {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n if input.peek(syn::Token![dyn]) {\n\n Ok(Self::Dyn(input.parse()?))\n\n } else {\n\n Ok(Self::Static(input.parse()?))\n\n }\n\n }\n\n}\n\n\n", "file_path": "codegen/src/parse/attr.rs", "rank": 30, "score": 4.0942405292753525 }, { "content": " } else {\n\n None\n\n };\n\n Ok(Self { name, value })\n\n }\n\n}\n\n\n\nimpl Spanned for StaticAttribute {\n\n fn span(&self) -> Span {\n\n let mut span = self.name.span();\n\n if let Some((eq, expr)) = &self.value {\n\n span = span.join(eq.span()).unwrap_or(span);\n\n span = span.join(expr.span()).unwrap_or(span);\n\n }\n\n span\n\n }\n\n}\n\n\n\n#[cfg_attr(test, derive(Debug))]\n\npub struct DynAttribute {\n", "file_path": "codegen/src/parse/attr.rs", "rank": 31, "score": 4.019811263551262 }, { "content": " let name: ElementName = input.parse().map_err(ctx(\"Parsing element name\"))?;\n\n let mut span = name.span();\n\n\n\n let mut classes = vec![];\n\n let mut id = None;\n\n loop {\n\n if input.peek(syn::Token![.]) {\n\n let class: DotClass = input.parse()?;\n\n span = span.join(class.span()).unwrap_or(span);\n\n classes.push(class);\n\n } else if input.peek(syn::Token![#]) {\n\n if id.is_some() {\n\n return Err(input.error(\"An element may only have one ID\"))?;\n\n }\n\n let hi: HashId = input.parse().map_err(ctx(\"Parsing element ID\"))?;\n\n span = span.join(hi.span()).unwrap_or(span);\n\n id = Some(hi);\n\n } else if input.peek(syn::token::Paren)\n\n || input.peek(syn::token::Brace)\n\n || input.peek(syn::Token![;])\n", "file_path": "codegen/src/parse/element.rs", "rank": 32, "score": 3.2401836106442623 }, { "content": "use proc_macro2::Span;\n\nuse syn::parse::{Parse, ParseStream};\n\nuse syn::spanned::Spanned;\n\n\n\nuse crate::ctx;\n\n\n\nmacro_rules! impl_span {\n\n ($target:ty = $main:ident $(<< $front:ident)* $(>> $back:ident)*) => {\n\n impl ::syn::spanned::Spanned for $target {\n\n fn span(&self) -> proc_macro2::Span {\n\n use ::syn::spanned::Spanned;\n\n let mut span = Spanned::span(&self.$main);\n\n $(\n\n span = Spanned::span(&self.$front).join(span).unwrap_or(span);\n\n )*\n\n $(\n\n span = span.join(Spanned::span(&self.$back)).unwrap_or(span);\n\n )*\n\n span\n\n }\n", "file_path": "codegen/src/parse/mod.rs", "rank": 33, "score": 3.173445102949057 }, { "content": "\n\n use super::*;\n\n\n\n #[test]\n\n fn parse_hash_id() {\n\n let hash = quote![#];\n\n\n\n let parsed = syn::parse2::<HashId>(quote!(#hash abc-def)).unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"abc-def\");\n\n }\n\n\n\n #[test]\n\n fn parse_dot_class() {\n\n let parsed = syn::parse2::<DotClass>(quote!(.abc-def)).unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"abc-def\");\n\n }\n\n}\n", "file_path": "codegen/src/parse/id_class.rs", "rank": 34, "score": 2.7347832979463123 }, { "content": "\n\nimpl Parse for HtmlNodes {\n\n fn parse(input: ParseStream) -> syn::parse::Result<Self> {\n\n let mut span = input.cursor().span();\n\n let mut nodes = vec![];\n\n while !input.is_empty() {\n\n let node = input\n\n .parse::<HtmlNode>()\n\n .map_err(ctx(\"Parsing HtmlNode in node list\"))?;\n\n span = span.join(node.span()).unwrap_or(span);\n\n nodes.push(node);\n\n }\n\n Ok(Self { nodes, span })\n\n }\n\n}\n\n\n\nimpl Spanned for HtmlNodes {\n\n fn span(&self) -> Span {\n\n self.span\n\n }\n", "file_path": "codegen/src/parse/mod.rs", "rank": 35, "score": 2.6414531759180546 }, { "content": "extern crate proc_macro as pm1;\n\n\n\nuse std::collections::HashMap;\n\nuse std::fmt;\n\n\n\nuse proc_macro2::TokenStream;\n\nuse proc_quote::quote;\n\nuse syn::spanned::Spanned;\n\n\n\nmod parse;\n\n\n\n#[proc_macro_hack::proc_macro_hack]\n", "file_path": "codegen/src/lib.rs", "rank": 36, "score": 2.6253096868799144 }, { "content": " let name = &(#name);\n\n debug_assert!(match name {\n\n #(#static_names)|* => false,\n\n _ => true,\n\n }, \"The dynamic attribute {} duplicates a hardcoded attribute\", name);\n\n ::minihtml::ToWholeHtmlAttr::fmt(\n\n &(#value),\n\n ::minihtml::NoSpecial::debug_checked(name),\n\n output\n\n )?;\n\n }\n\n }));\n\n\n\n Ok(quote!(#(#attrs)*))\n\n}\n", "file_path": "codegen/src/lib.rs", "rank": 37, "score": 2.423095115285745 }, { "content": " .classes\n\n .iter()\n\n .map(|class| class.name.as_ref())\n\n .join(\" \");\n\n if static_attrs.contains_key(\"class\") {\n\n let dy = static_attrs\n\n .get_mut(\"class\")\n\n .expect(\"Checked in the condition above\");\n\n *dy = quote! {\n\n ::minihtml::hc::ClassConcat(#dy, #static_classes_joined)\n\n };\n\n } else {\n\n static_attrs.insert(\n\n \"class\".to_string(),\n\n quote! {\n\n ::minihtml::NoSpecial(#static_classes_joined)\n\n },\n\n );\n\n }\n\n }\n", "file_path": "codegen/src/lib.rs", "rank": 38, "score": 2.378760529090397 }, { "content": "\n\n let attrs = static_attrs\n\n .iter()\n\n .map(|(name, value)| {\n\n quote! {\n\n ::minihtml::ToWholeHtmlAttr::fmt(\n\n &(#value),\n\n ::minihtml::NoSpecial(#name),\n\n output\n\n )?;\n\n }\n\n })\n\n .chain(dyn_attrs.iter().map(|attr| {\n\n let name = &attr.name;\n\n let value = match &attr.value {\n\n Some((_, value)) => quote!(#value),\n\n None => quote!(true),\n\n };\n\n let static_names = static_attrs.iter().map(|(name, _)| name);\n\n quote! {\n", "file_path": "codegen/src/lib.rs", "rank": 39, "score": 2.332038350756867 }, { "content": "use minihtml::html_string;\n\n\n\n#[test]\n", "file_path": "tests/basic.rs", "rank": 40, "score": 2.3313443015507405 }, { "content": " dyn_attrs.push(attr);\n\n }\n\n }\n\n }\n\n\n\n if let Some(id) = &element.id {\n\n if static_attrs.contains_key(\"id\") {\n\n return Err(syn::Error::new(\n\n id.span(),\n\n \"Duplicate definition of attribute \\\"id\\\"\",\n\n ));\n\n }\n\n let id = id.name.as_ref();\n\n static_attrs.insert(\"id\".to_string(), quote!(#id));\n\n }\n\n\n\n if element.classes.len() > 0 {\n\n use itertools::Itertools;\n\n\n\n let static_classes_joined = element\n", "file_path": "codegen/src/lib.rs", "rank": 41, "score": 2.1658550790281583 }, { "content": " use super::*;\n\n\n\n #[test]\n\n fn test_empty_single() {\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo\n\n })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(parsed.classes.len(), 0);\n\n assert!(parsed.id.is_none());\n\n assert!(parsed.attributes.is_none());\n\n assert!(parsed.children.is_none());\n\n }\n\n\n\n #[test]\n\n fn test_empty_single_semi() {\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo;\n\n })\n", "file_path": "codegen/src/parse/element.rs", "rank": 42, "score": 2.006378960883143 }, { "content": " write!(output, concat!(\"</\", #element_name, \">\"))?;\n\n }\n\n }\n\n None => quote! {\n\n write!(output, \"/>\")?;\n\n },\n\n };\n\n quote! {\n\n write!(output, concat!(\"<\", #element_name))?;\n\n #write_attrs\n\n #write_child\n\n }\n\n }\n\n })\n\n}\n\n\n", "file_path": "codegen/src/lib.rs", "rank": 43, "score": 1.9901409783457935 }, { "content": " assert_eq!(quote!(#name).to_string(), quote!(a + b).to_string());\n\n let (_, value) = value.unwrap();\n\n assert_eq!(quote!(#value).to_string(), quote!(c + d).to_string());\n\n }\n\n\n\n #[test]\n\n fn parse_dyn_without_value() {\n\n let parsed = syn::parse2::<Attribute>(quote!(dyn a + b)).unwrap();\n\n let DynAttribute { name, value, .. } = unwrap_match!(parsed, Attribute::Dyn(x) => x);\n\n assert_eq!(quote!(#name).to_string(), quote!(a + b).to_string());\n\n assert!(value.is_none());\n\n }\n\n}\n", "file_path": "codegen/src/parse/attr.rs", "rank": 44, "score": 1.7498638823051536 }, { "content": "}\n\n\n\npub enum HtmlNode {\n\n Arbitrary(syn::Token![+], syn::Expr),\n\n Element(HtmlElement),\n\n}\n\n\n\nimpl Parse for HtmlNode {\n\n fn parse(input: ParseStream) -> syn::parse::Result<Self> {\n\n let ret = if input.peek(syn::Token![+]) {\n\n let plus: syn::Token![+] = input.parse().unwrap();\n\n let expr: syn::Expr = input\n\n .parse()\n\n .map_err(ctx(\"Parsing arbitrary HTML node expression\"))?;\n\n if input.peek(syn::Token![;]) {\n\n input.parse::<syn::Token![;]>().unwrap();\n\n }\n\n HtmlNode::Arbitrary(plus, expr)\n\n } else {\n\n HtmlNode::Element(input.parse().map_err(ctx(\"Parsing HTML element node\"))?)\n", "file_path": "codegen/src/parse/mod.rs", "rank": 45, "score": 1.7175282989412075 }, { "content": " assert_eq!(\n\n parsed\n\n .classes\n\n .iter()\n\n .map(|class| class.name.as_ref().to_string())\n\n .collect::<Vec<String>>(),\n\n vec![\"de-f\".to_string(), \"gh-i\".to_string()]\n\n );\n\n assert_eq!(parsed.id.unwrap().name.as_ref(), \"ab-c\");\n\n assert!(parsed.attributes.is_none());\n\n assert!(parsed.children.is_none());\n\n }\n\n}\n", "file_path": "codegen/src/parse/element.rs", "rank": 46, "score": 1.6821918286506523 }, { "content": " })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(parsed.classes.len(), 0);\n\n assert_eq!(parsed.id.unwrap().name.as_ref(), \"ab-c\");\n\n assert!(parsed.attributes.is_none());\n\n assert!(parsed.children.is_none());\n\n }\n\n\n\n #[test]\n\n fn test_classes() {\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo.de-f.gh-i;\n\n })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(\n\n parsed\n\n .classes\n", "file_path": "codegen/src/parse/element.rs", "rank": 47, "score": 1.6487634617795286 }, { "content": " };\n\n Ok(ret)\n\n }\n\n}\n\n\n\nimpl Spanned for HtmlNode {\n\n fn span(&self) -> Span {\n\n match self {\n\n Self::Arbitrary(add, expr) => {\n\n let mut span = expr.span();\n\n span = add.span().join(span).unwrap_or(span);\n\n span\n\n }\n\n Self::Element(el) => el.span(),\n\n }\n\n }\n\n}\n", "file_path": "codegen/src/parse/mod.rs", "rank": 48, "score": 1.4654603145185274 }, { "content": " fn parse_static_with_value() {\n\n let parsed = syn::parse2::<Attribute>(quote!(a - b - c = 3)).unwrap();\n\n let attr = unwrap_match!(parsed, Attribute::Static(x) => x);\n\n assert_eq!(attr.name.as_ref(), \"a-b-c\");\n\n let value = attr.value.unwrap().1;\n\n assert_eq!(quote!(#value).to_string(), quote!(3).to_string());\n\n }\n\n\n\n #[test]\n\n fn parse_static_without_value() {\n\n let parsed = syn::parse2::<Attribute>(quote!(a - b - c)).unwrap();\n\n let attr = unwrap_match!(parsed, Attribute::Static(x) => x);\n\n assert_eq!(attr.name.as_ref(), \"a-b-c\");\n\n assert!(attr.value.is_none());\n\n }\n\n\n\n #[test]\n\n fn parse_dyn_with_value() {\n\n let parsed = syn::parse2::<Attribute>(quote!(dyn a+b = c+d)).unwrap();\n\n let DynAttribute { name, value, .. } = unwrap_match!(parsed, Attribute::Dyn(x) => x);\n", "file_path": "codegen/src/parse/attr.rs", "rank": 49, "score": 1.4316377982464248 }, { "content": " .iter()\n\n .map(|class| class.name.as_ref().to_string())\n\n .collect::<Vec<String>>(),\n\n vec![\"de-f\".to_string(), \"gh-i\".to_string()]\n\n );\n\n assert!(parsed.id.is_none());\n\n assert!(parsed.attributes.is_none());\n\n assert!(parsed.children.is_none());\n\n }\n\n\n\n #[test]\n\n fn test_classes_num() {\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo.de-f0.gh-i;\n\n })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(\n\n parsed\n", "file_path": "codegen/src/parse/element.rs", "rank": 50, "score": 1.3652979416458457 }, { "content": " .classes\n\n .iter()\n\n .map(|class| class.name.as_ref().to_string())\n\n .collect::<Vec<String>>(),\n\n vec![\"de-f0\".to_string(), \"gh-i\".to_string()]\n\n );\n\n assert!(parsed.id.is_none());\n\n assert!(parsed.attributes.is_none());\n\n assert!(parsed.children.is_none());\n\n }\n\n\n\n #[test]\n\n fn test_id_classes_mixed() {\n\n let hash = quote![#];\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo .de-f #hash ab-c .gh-i;\n\n })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n", "file_path": "codegen/src/parse/element.rs", "rank": 51, "score": 1.3295184094693928 }, { "content": " .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(parsed.classes.len(), 0);\n\n assert!(parsed.id.is_none());\n\n assert!(parsed.attributes.is_none());\n\n assert!(parsed.children.is_none());\n\n }\n\n\n\n #[test]\n\n fn test_empty_block() {\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo {}\n\n })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(parsed.classes.len(), 0);\n\n assert!(parsed.id.is_none());\n\n assert!(parsed.attributes.is_none());\n\n assert_eq!(parsed.children.unwrap().nodes.into_iter().count(), 0);\n\n }\n", "file_path": "codegen/src/parse/element.rs", "rank": 52, "score": 1.2633050750704964 }, { "content": " };\n\n\n\n let children = if input.peek(syn::token::Brace) {\n\n let inner;\n\n let _token = syn::braced!(inner in input);\n\n let nodes: HtmlNodes = inner.parse().map_err(ctx(\"Parsing inner elements\"))?;\n\n span = span.join(nodes.span()).unwrap_or(span);\n\n Some(nodes)\n\n } else {\n\n None\n\n };\n\n\n\n if input.peek(syn::Token![;]) {\n\n input.parse::<syn::Token![;]>().unwrap();\n\n }\n\n\n\n Ok(HtmlElement {\n\n name,\n\n classes,\n\n id,\n", "file_path": "codegen/src/parse/element.rs", "rank": 53, "score": 0.9573829981415827 }, { "content": "\n\n #[test]\n\n fn test_empty_block_semi() {\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo {};\n\n })\n\n .unwrap();\n\n assert_eq!(parsed.name.as_ref(), \"foo\");\n\n assert_eq!(parsed.classes.len(), 0);\n\n assert!(parsed.id.is_none());\n\n assert!(parsed.attributes.is_none());\n\n assert_eq!(parsed.children.unwrap().nodes.into_iter().count(), 0);\n\n }\n\n\n\n #[test]\n\n fn test_id() {\n\n let hash = quote![#];\n\n #[cfg_attr(rustfmt, rustfmt_skip)]\n\n let parsed = syn::parse2::<HtmlElement>(quote! {\n\n foo #hash ab-c;\n", "file_path": "codegen/src/parse/element.rs", "rank": 54, "score": 0.8318058703118334 } ]
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/tests/ecommerce.rs", "rank": 0, "score": 27865.721598858294 }, { "content": "pub fn using_store<T, F>(store_id: usize, f: F) -> T where F: (FnOnce(&mut Store) -> T) {\n\n STORES.with(|cell| {\n\n let stores = &mut *cell.borrow_mut();\n\n let store = stores.get_mut(&store_id).unwrap();\n\n f(store)\n\n })\n\n}\n\n\n\n\n", "file_path": "rust/core/src/lib.rs", "rank": 1, "score": 25288.473066732666 }, { "content": "pub fn using_results<T, F>(store_id: usize, f: F) -> T where F: (FnOnce(&mut Vec<SearchResult>) -> T) {\n\n RESULTS.with(|cell| {\n\n let buffers = &mut *cell.borrow_mut();\n\n let buffer = buffers.get_mut(&store_id).unwrap();\n\n f(buffer)\n\n })\n\n}\n", "file_path": "rust/core/src/lib.rs", "rank": 2, "score": 24170.720667263566 }, { "content": "pub fn hit_matches(query: &TextRef, hit: &Hit) -> bool {\n\n if query.is_empty() { return true; }\n\n if hit.rmatches.len() == 0 { return false; }\n\n if hit.rmatches.len() == 1 && hit.qmatches.len() == 1 && query.words.len() > 1 {\n\n let rmatch = &hit.rmatches[0];\n\n let qmatch = &hit.qmatches[0];\n\n let first_half = (qmatch.word_len() * 2) < rmatch.word_len();\n\n if !rmatch.fin && first_half { return false; }\n\n }\n\n true\n\n}\n", "file_path": "rust/core/src/search/filter.rs", "rank": 4, "score": 13112.298560517052 }, { "content": "pub fn score(query: &TextRef, hit: &mut Hit) {\n\n let (rmatches, qmatches) = text_match(&hit.title, &query);\n\n hit.rmatches = rmatches;\n\n hit.qmatches = qmatches;\n\n\n\n hit.scores[ScoreType::Chars] = score_chars_up(hit);\n\n hit.scores[ScoreType::Words] = score_words_up(hit);\n\n hit.scores[ScoreType::Tails] = score_tails_down(hit);\n\n hit.scores[ScoreType::Trans] = score_trans_down(hit);\n\n hit.scores[ScoreType::Fin] = score_fin_up(hit);\n\n hit.scores[ScoreType::Offset] = score_offset_down(hit);\n\n hit.scores[ScoreType::Rating] = score_rating_up(hit);\n\n hit.scores[ScoreType::WordLen] = score_word_len_down(hit);\n\n hit.scores[ScoreType::CharLen] = score_char_len_down(hit);\n\n}\n\n\n\n\n", "file_path": "rust/core/src/search/score.rs", "rank": 5, "score": 13112.298560517052 }, { "content": " offset: 0,\n\n slice: (0, size),\n\n subslice: (0, size),\n\n func: false,\n\n typos: 0.0,\n\n fin: false,\n\n };\n\n (rmatch, qmatch)\n\n }\n\n\n\n #[test]\n\n fn highlight_basic() {\n\n let lang = Lang::new();\n\n let record = Record::new(10, \"metal detector\", 0, &lang);\n\n\n\n let mut hit = Hit::from_record(&record);\n\n let (rmatch, qmatch) = mock_match(1, 6);\n\n hit.rmatches.push(rmatch);\n\n hit.qmatches.push(qmatch);\n\n\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 9, "score": 8.52360804717484 }, { "content": " let record = Record::new(10, \"Passstraße\", 0, &lang);\n\n\n\n let mut hit = Hit::from_record(&record);\n\n let (rmatch, qmatch) = mock_match(0, 9);\n\n hit.rmatches.push(rmatch);\n\n hit.qmatches.push(qmatch);\n\n\n\n let expected = \"[Passstraß]e\";\n\n let received = highlight(&hit, (L, R));\n\n\n\n assert_eq!(&received, expected);\n\n }\n\n}\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 10, "score": 8.146236045812882 }, { "content": "mod tests {\n\n use crate::matching::WordMatch;\n\n use crate::store::Record;\n\n use crate::search::Hit;\n\n use crate::lang::{Lang, lang_german, lang_portuguese};\n\n use super::highlight;\n\n\n\n const L: &[char] = &['['];\n\n const R: &[char] = &[']'];\n\n\n\n fn mock_match(offset: usize, size: usize) -> (WordMatch, WordMatch) {\n\n let rmatch = WordMatch {\n\n offset: offset,\n\n slice: (0, size),\n\n subslice: (0, size),\n\n func: false,\n\n typos: 0.0,\n\n fin: false,\n\n };\n\n let qmatch = WordMatch {\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 11, "score": 7.96579347937123 }, { "content": "use std::default::Default;\n\nuse crate::tokenization::TextRef;\n\nuse crate::matching::WordMatch;\n\nuse crate::store::Record;\n\nuse super::score::Scores;\n\n\n\n\n\n#[derive(Debug)]\n\npub struct Hit<'a> {\n\n pub id: usize,\n\n pub title: TextRef<'a>,\n\n pub rating: usize,\n\n pub rmatches: Vec<WordMatch>,\n\n pub qmatches: Vec<WordMatch>,\n\n pub scores: Scores,\n\n}\n\n\n\n\n\nimpl<'a> Hit<'a> {\n\n pub fn from_record(record: &'a Record) -> Hit<'a> {\n", "file_path": "rust/core/src/search/hit.rs", "rank": 12, "score": 7.907973489740805 }, { "content": "use std::cmp::Ordering;\n\nuse std::cell::RefCell;\n\n\n\nuse Ordering::{\n\n Less,\n\n Equal,\n\n Greater,\n\n};\n\n\n\n\n\nconst DEFAULT_CAPACITY: usize = 20;\n\n\n\n\n", "file_path": "rust/core/src/matching/jaccard/mod.rs", "rank": 14, "score": 7.692673931986922 }, { "content": " }\n\n\n\n #[test]\n\n fn highlight_multichar_dividers() {\n\n let lang = Lang::new();\n\n let record = Record::new(10, \"metal detector\", 0, &lang);\n\n\n\n let mut hit = Hit::from_record(&record);\n\n let (rmatch, qmatch) = mock_match(1, 6);\n\n hit.rmatches.push(rmatch);\n\n hit.qmatches.push(qmatch);\n\n\n\n let l: &[char] = &['{', '{'];\n\n let r: &[char] = &['}', '}'];\n\n\n\n let expected = \"metal {{detect}}or\";\n\n let received = highlight(&hit, (l, r));\n\n\n\n assert_eq!(&received, expected);\n\n }\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 15, "score": 7.651638710583693 }, { "content": "\n\n #[test]\n\n fn highlight_utf_padded() {\n\n let lang = lang_german();\n\n let record = Record::new(10, \"Passstraße\", 0, &lang);\n\n\n\n let mut hit = Hit::from_record(&record);\n\n let (rmatch, qmatch) = mock_match(0, 9);\n\n hit.rmatches.push(rmatch);\n\n hit.qmatches.push(qmatch);\n\n\n\n let expected = \"[Passstraß]e\";\n\n let received = highlight(&hit, (L, R));\n\n\n\n assert_eq!(&received, expected);\n\n }\n\n\n\n #[test]\n\n fn highlight_utf_nfd() {\n\n let lang = lang_portuguese();\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 16, "score": 7.401966952857579 }, { "content": "use crate::tokenization::{Word, WordView};\n\nuse super::WordMatch;\n\nuse super::damlev::DamerauLevenshtein;\n\nuse super::jaccard::Jaccard;\n\n\n\n\n\nconst LENGTH_THRESHOLD: f64 = 0.26;\n\nconst JACCARD_THRESHOLD: f64 = 0.51;\n\nconst DAMLEV_THRESHOLD: f64 = 0.21;\n\n\n\nthread_local! {\n\n static DAMLEV: DamerauLevenshtein = DamerauLevenshtein::new();\n\n static JACCARD: Jaccard<char> = Jaccard::new();\n\n}\n\n\n\n\n", "file_path": "rust/core/src/matching/word.rs", "rank": 18, "score": 7.260489556863924 }, { "content": " let expected = \"metal [detect]or\";\n\n let received = highlight(&hit, (L, R));\n\n\n\n assert_eq!(&received, expected);\n\n }\n\n\n\n #[test]\n\n fn highlight_stripped() {\n\n let lang = Lang::new();\n\n let record = Record::new(10, \"'metal' mailbox!\", 0, &lang);\n\n\n\n let mut hit = Hit::from_record(&record);\n\n let (rmatch, qmatch) = mock_match(0, 5);\n\n hit.rmatches.push(rmatch);\n\n hit.qmatches.push(qmatch);\n\n\n\n let expected = \"'[metal]' mailbox!\";\n\n let received = highlight(&hit, (L, R));\n\n\n\n assert_eq!(&received, expected);\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 19, "score": 7.123057854981115 }, { "content": "mod record;\n\nmod store;\n\nmod trigram_index;\n\n\n\npub use record::Record;\n\npub use store::Store;\n\npub use trigram_index::TrigramIndex;\n\n\n\npub static DEFAULT_LIMIT: usize = 10;\n", "file_path": "rust/core/src/store/mod.rs", "rank": 20, "score": 6.935078686491968 }, { "content": "#![allow(dead_code)]\n\n\n\nuse rust_stemmers::{Algorithm, Stemmer};\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n\nuse CharClass::{\n\n Consonant,\n\n Vowel,\n\n};\n\n\n\nuse PartOfSpeech::{\n\n Preposition,\n\n Conjunction,\n\n Particle,\n\n};\n\n\n\n\n\nconst FUNCTION_WORDS: &[(PartOfSpeech, &'static str)] = &[\n", "file_path": "rust/core/src/lang/lang_russian.rs", "rank": 21, "score": 6.831053206387765 }, { "content": "#![allow(dead_code)]\n\n\n\nuse rust_stemmers::{Algorithm, Stemmer};\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n\nuse CharClass::{\n\n Consonant,\n\n};\n\n\n\nuse PartOfSpeech::{\n\n Article,\n\n Preposition,\n\n Conjunction,\n\n Particle,\n\n};\n\n\n\n\n\nconst FUNCTION_WORDS: &[(PartOfSpeech, &'static str)] = &[\n", "file_path": "rust/core/src/lang/lang_german.rs", "rank": 22, "score": 6.831053206387765 }, { "content": "#![allow(dead_code)]\n\n\n\nuse rust_stemmers::{Algorithm, Stemmer};\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n\nuse PartOfSpeech::{\n\n Article,\n\n Preposition,\n\n Conjunction,\n\n Particle,\n\n};\n\n\n\nuse CharClass::{\n\n Consonant,\n\n Vowel,\n\n};\n\n\n\nconst FUNCTION_WORDS: &[(PartOfSpeech, &'static str)] = &[\n", "file_path": "rust/core/src/lang/lang_french.rs", "rank": 23, "score": 6.784693904961439 }, { "content": "#![allow(dead_code)]\n\n\n\nuse rust_stemmers::{Algorithm, Stemmer};\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n\nuse PartOfSpeech::{\n\n Article,\n\n Preposition,\n\n Conjunction,\n\n Particle,\n\n};\n\n\n\n\n\nconst FUNCTION_WORDS: &[(PartOfSpeech, &'static str)] = &[\n\n (Article, \"a\"),\n\n (Article, \"an\"),\n\n (Article, \"the\"),\n\n\n", "file_path": "rust/core/src/lang/lang_english.rs", "rank": 24, "score": 6.7023009040785935 }, { "content": "#![allow(dead_code)]\n\n\n\nuse rust_stemmers::{Algorithm, Stemmer};\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n\nuse PartOfSpeech::{\n\n Article,\n\n Preposition,\n\n Conjunction,\n\n};\n\n\n\n\n\nconst FUNCTION_WORDS: &[(PartOfSpeech, &'static str)] = &[\n\n (Article, \"o\"),\n\n (Article, \"a\"),\n\n (Article, \"os\"),\n\n (Article, \"as\"),\n\n (Article, \"um\"),\n", "file_path": "rust/core/src/lang/lang_portuguese.rs", "rank": 25, "score": 6.557240681799133 }, { "content": "#![allow(dead_code)]\n\n\n\nuse rust_stemmers::{Algorithm, Stemmer};\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n\nuse PartOfSpeech::{\n\n Article,\n\n Preposition,\n\n Conjunction,\n\n};\n\n\n\n\n\nconst FUNCTION_WORDS: &[(PartOfSpeech, &'static str)] = &[\n\n (Article, \"el\"),\n\n (Article, \"la\"),\n\n (Article, \"los\"),\n\n (Article, \"las\"),\n\n (Article, \"un\"),\n", "file_path": "rust/core/src/lang/lang_spanish.rs", "rank": 26, "score": 6.419656750137687 }, { "content": "#![cfg(test)]\n\n#![allow(non_snake_case)]\n\n\n\nuse std::cell::RefCell;\n\nuse std::fs;\n\nuse serde_json::Value;\n\nuse regex::Regex;\n\nuse lucid_suggest_core::{Store, Record, tokenize_query, lang_english, SearchResult};\n\n\n\n\n\nthread_local! {\n\n static STORE: RefCell<Option<Store>> = RefCell::new(None);\n\n}\n\n\n\n\n", "file_path": "rust/core/tests/ecommerce.rs", "rank": 27, "score": 6.419656750137687 }, { "content": " Hit {\n\n id: record.id,\n\n title: record.title.to_ref(),\n\n rating: record.rating,\n\n scores: Default::default(),\n\n rmatches: Vec::new(),\n\n qmatches: Vec::new(),\n\n }\n\n }\n\n}\n", "file_path": "rust/core/src/search/hit.rs", "rank": 28, "score": 6.112839901136941 }, { "content": " (Vowel, 'о'),\n\n (Vowel, 'у'),\n\n (Vowel, 'ы'),\n\n (Vowel, 'э'),\n\n (Vowel, 'ю'),\n\n (Vowel, 'я'),\n\n];\n\n\n\n\n\nconst UTF_COMPOSE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Ё\", \"Ё\"),\n\n (\"ё\", \"ё\"),\n\n];\n\n\n\n\n\nconst UTF_REDUCE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Ё\", \"Е\"),\n\n (\"ё\", \"е\"),\n\n];\n\n\n\n\n", "file_path": "rust/core/src/lang/lang_russian.rs", "rank": 29, "score": 4.756712039293195 }, { "content": " (Particle, \"on\"),\n\n (Particle, \"to\"),\n\n (Particle, \"oh\"),\n\n];\n\n\n\n\n\nconst CHAR_CLASSES: &[(CharClass, char)] = &[];\n\n\n\n\n\nconst UTF_COMPOSE_MAP: &[(&'static str, &'static str)] = &[];\n\n\n\n\n\nconst UTF_REDUCE_MAP: &[(&'static str, &'static str)] = &[];\n\n\n\n\n", "file_path": "rust/core/src/lang/lang_english.rs", "rank": 30, "score": 4.668311599731105 }, { "content": "use criterion::{criterion_group, criterion_main, Criterion, black_box};\n\nuse std::fs;\n\nuse std::cmp::min;\n\nuse rand::prelude::*;\n\nuse rand::distributions::WeightedIndex;\n\nuse lucid_suggest_core::{Word, Store, Record, Lang, TextOwn, tokenize_query, lang_english};\n\n\n\n\n", "file_path": "rust/core/benches/search.rs", "rank": 31, "score": 4.585974699076333 }, { "content": "use std::fmt;\n\nuse super::Lang;\n\n\n\n\n", "file_path": "rust/core/src/lang/char_class.rs", "rank": 32, "score": 4.5799536653278885 }, { "content": "use crate::tokenization::Text;\n\nuse crate::search::Hit;\n\n\n\n\n", "file_path": "rust/core/src/search/highlight.rs", "rank": 33, "score": 4.468304466928456 }, { "content": "use std::cmp::Ordering;\n\nuse crate::search::Hit;\n\n\n\n\n", "file_path": "rust/core/src/search/sort.rs", "rank": 34, "score": 4.468304466928456 }, { "content": "use crate::tokenization::TextRef;\n\nuse crate::search::Hit;\n\n\n", "file_path": "rust/core/src/search/filter.rs", "rank": 35, "score": 4.414496607334032 }, { "content": " *char_offset += splitted.len();\n\n *word_offset += 1;\n\n\n\n Some(splitted)\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::assert_debug_snapshot;\n\n use crate::utils::to_vec;\n\n use crate::lang::{Lang, CharClass};\n\n use super::super::word_shape::WordShape;\n\n\n\n use CharClass::{\n\n Whitespace,\n\n Punctuation,\n\n };\n\n\n", "file_path": "rust/core/src/tokenization/word_split.rs", "rank": 36, "score": 4.393049226870266 }, { "content": "mod constants;\n\nmod char_class;\n\nmod normalize;\n\nmod pos;\n\nmod lang;\n\nmod lang_basic;\n\nmod lang_english;\n\nmod lang_french;\n\nmod lang_german;\n\nmod lang_portuguese;\n\nmod lang_russian;\n\nmod lang_spanish;\n\n\n\npub use char_class::{CharClass, CharPattern};\n\npub use pos::PartOfSpeech;\n\npub use lang::Lang;\n\npub use lang_basic::lang_basic;\n\npub use lang_german::lang_german;\n\npub use lang_english::lang_english;\n\npub use lang_french::lang_french;\n\npub use lang_spanish::lang_spanish;\n\npub use lang_portuguese::lang_portuguese;\n\npub use lang_russian::lang_russian;\n", "file_path": "rust/core/src/lang/mod.rs", "rank": 37, "score": 4.337510985460123 }, { "content": "mod matrix;\n\n\n\nuse std::f64;\n\nuse fnv::{FnvHashMap as HashMap};\n\nuse std::cell::RefCell;\n\nuse crate::lang::CharClass;\n\nuse crate::tokenization::{Word, WordView};\n\nuse matrix::DistMatrix;\n\n\n\n\n\nconst DEFAULT_CAPACITY: usize = 20;\n\n\n\nconst COST_TRANS: f64 = 0.5;\n\nconst COST_DOUBLE: f64 = 0.5;\n\nconst COST_VOWEL: f64 = 0.5;\n\nconst COST_NOTALPHA: f64 = 0.5;\n\nconst COST_CONSONANT: f64 = 1.0;\n\nconst COST_DEFAULT: f64 = 1.0;\n\n\n\n\n", "file_path": "rust/core/src/matching/damlev/mod.rs", "rank": 38, "score": 4.316010647394466 }, { "content": "use wasm_bindgen::prelude::*;\n\nuse lucid_suggest_core as core;\n\n\n\n\n\n#[wasm_bindgen]\n", "file_path": "rust/wasm/src/lib.rs", "rank": 39, "score": 4.310677220646241 }, { "content": "mod word;\n\nmod word_shape;\n\nmod word_split;\n\nmod word_view;\n\nmod text;\n\n\n\nuse crate::lang::{Lang, CharClass};\n\npub use word::Word;\n\npub use word_view::WordView;\n\npub use word_shape::WordShape;\n\npub use text::{Text, TextOwn, TextRef};\n\n\n\n\n", "file_path": "rust/core/src/tokenization/mod.rs", "rank": 40, "score": 4.310402501624383 }, { "content": "mod utils;\n\n\n\nmod matching;\n\npub mod tokenization;\n\n\n\nmod store;\n\nmod search;\n\npub mod lang;\n\n\n\nuse std::cell::RefCell;\n\nuse fnv::{FnvHashMap as HashMap};\n\n\n\npub use tokenization::{Word, WordShape, WordView, Text, TextOwn, TextRef, tokenize_query};\n\npub use store::{Record, Store, DEFAULT_LIMIT};\n\npub use search::{SearchResult};\n\npub use lang::Lang;\n\npub use lang::{\n\n lang_german,\n\n lang_english,\n\n lang_french,\n", "file_path": "rust/core/src/lib.rs", "rank": 41, "score": 4.2911291505057765 }, { "content": "#![allow(dead_code)]\n\n\n\nuse super::Lang;\n\nuse super::constants::CHAR_CLASSES_LATIN;\n\n\n", "file_path": "rust/core/src/lang/lang_basic.rs", "rank": 42, "score": 4.260577449697436 }, { "content": " (\"ö\", \"ö\"),\n\n (\"ü\", \"ü\"),\n\n];\n\n\n\nconst UTF_REDUCE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"ẞ\", \"SS\"), // eszett\n\n (\"ß\", \"ss\"),\n\n (\"Ä\", \"A\"), // umlauts\n\n (\"Ö\", \"O\"),\n\n (\"Ü\", \"U\"),\n\n (\"ä\", \"a\"),\n\n (\"ö\", \"o\"),\n\n (\"ü\", \"u\"),\n\n];\n\n\n\n\n", "file_path": "rust/core/src/lang/lang_german.rs", "rank": 43, "score": 4.23164604165164 }, { "content": " let chars = &text.chars[word.slice.0 .. word.slice.1];\n\n for gram in chars.trigrams() {\n\n grams.push(gram);\n\n }\n\n }\n\n grams.sort_unstable();\n\n grams.dedup();\n\n grams\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::{assert_debug_snapshot, assert_snapshot};\n\n use crate::lang::Lang;\n\n use crate::tokenization::tokenize_query;\n\n use super::Record;\n\n use super::TrigramIndex;\n\n\n", "file_path": "rust/core/src/store/trigram_index.rs", "rank": 44, "score": 4.230808030717018 }, { "content": " }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::assert_debug_snapshot;\n\n use crate::utils::to_vec;\n\n use crate::lang::{Lang, CharClass, PartOfSpeech, lang_english};\n\n use super::{Word, WordShape};\n\n\n\n use CharClass::{\n\n Whitespace,\n\n Punctuation,\n\n };\n\n\n\n #[test]\n\n fn word_dist_basic() {\n\n let mut w1 = WordShape::new(7);\n\n let mut w2 = WordShape::new(5);\n", "file_path": "rust/core/src/tokenization/word_shape.rs", "rank": 45, "score": 4.21136660404517 }, { "content": "mod hit;\n\nmod score;\n\nmod result;\n\nmod filter;\n\nmod sort;\n\nmod highlight;\n\n\n\nuse crate::utils::LimitSort;\n\nuse crate::tokenization::TextRef;\n\nuse crate::store::Store;\n\npub use hit::Hit;\n\npub use result::SearchResult;\n\n\n\n\n\nimpl Store {\n\n pub fn search<'a>(\n\n &'a self,\n\n query: &'a TextRef<'a>,\n\n ) -> Vec<SearchResult> {\n\n let dividers = self.dividers();\n", "file_path": "rust/core/src/search/mod.rs", "rank": 46, "score": 4.21136660404517 }, { "content": "\n\n\n\nconst UTF_REDUCE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Á\", \"A\"), // acute accent\n\n (\"É\", \"E\"),\n\n (\"Í\", \"I\"),\n\n (\"Ó\", \"O\"),\n\n (\"Ú\", \"U\"),\n\n (\"á\", \"a\"),\n\n (\"é\", \"e\"),\n\n (\"í\", \"i\"),\n\n (\"ó\", \"o\"),\n\n (\"ú\", \"u\"),\n\n (\"Ñ\", \"N\"), // tilde\n\n (\"ñ\", \"n\"),\n\n (\"Ü\", \"U\"), // diaeresis\n\n (\"ü\", \"u\"),\n\n];\n\n\n\n\n", "file_path": "rust/core/src/lang/lang_spanish.rs", "rank": 47, "score": 4.184649608180889 }, { "content": "use criterion::{criterion_group, criterion_main, Criterion};\n\nuse lucid_suggest_core::{Record, lang_english};\n\n\n", "file_path": "rust/core/benches/tokenize.rs", "rank": 48, "score": 4.163792177366963 }, { "content": "use std::fmt;\n\nuse crate::utils::to_vec;\n\nuse crate::lang::{Lang, CharPattern, CharClass};\n\nuse super::word::Word;\n\nuse super::word_shape::WordShape;\n\nuse super::word_view::WordView;\n\n\n\n\n\n#[derive(PartialEq)]\n\npub struct Text<W, T, C> where\n\n W: AsRef<[WordShape]>,\n\n T: AsRef<[char]>,\n\n C: AsRef<[CharClass]>\n\n{\n\n pub words: W,\n\n pub source: T,\n\n pub chars: T,\n\n pub classes: C,\n\n}\n\n\n", "file_path": "rust/core/src/tokenization/text.rs", "rank": 49, "score": 4.153025647252363 }, { "content": "mod damlev;\n\nmod jaccard;\n\nmod word;\n\nmod word_match;\n\nmod text;\n\n\n\npub use word_match::WordMatch;\n\npub use word::word_match;\n\npub use text::text_match;\n", "file_path": "rust/core/src/matching/mod.rs", "rank": 50, "score": 4.1271906683971595 }, { "content": "use std::cmp::Ordering;\n\n\n\n\n", "file_path": "rust/core/src/utils/limitsort.rs", "rank": 51, "score": 3.997710283133555 }, { "content": "\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::assert_debug_snapshot;\n\n use crate::utils::to_vec;\n\n use crate::lang::{Lang, CharClass, PartOfSpeech, lang_english, lang_portuguese, lang_german};\n\n use super::{WordShape, Text};\n\n\n\n use CharClass::{\n\n Whitespace,\n\n Punctuation,\n\n };\n\n\n\n #[test]\n\n fn text_normalize_nfd() {\n\n let lang = lang_portuguese();\n\n let text = Text::from_str(\"Conceição\").normalize(&lang);\n\n assert_debug_snapshot!((&text.source, &text.chars, &text.words[0]));\n\n }\n\n\n", "file_path": "rust/core/src/tokenization/text.rs", "rank": 52, "score": 3.9912777694265977 }, { "content": "use crate::tokenization::{Word, TextRef};\n\nuse crate::matching::text_match;\n\nuse crate::search::Hit;\n\n\n\n\n\npub const SCORES_SIZE: usize = 9;\n\n\n\n\n\npub enum ScoreType {\n\n Chars = 0,\n\n Words = 1,\n\n Tails = 2,\n\n Trans = 3,\n\n Fin = 4,\n\n Offset = 5,\n\n Rating = 6,\n\n WordLen = 7,\n\n CharLen = 8,\n\n}\n\n\n", "file_path": "rust/core/src/search/score.rs", "rank": 53, "score": 3.949337916084246 }, { "content": " r2.rating\n\n .cmp(&r1.rating)\n\n .then_with(|| r1.title.chars.cmp(&r2.title.chars))\n\n },\n\n )\n\n .map(|r| r.ix)\n\n .collect::<Vec<_>>();\n\n\n\n *top_ixs = Some(ixs.clone());\n\n ixs\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::assert_debug_snapshot;\n\n use crate::tokenization::tokenize_query;\n\n use crate::lang::{Lang, lang_english, lang_german};\n\n use crate::store::{Store, Record};\n", "file_path": "rust/core/src/search/mod.rs", "rank": 54, "score": 3.932797315432021 }, { "content": " (\"Ì\", \"Ì\"),\n\n (\"Ò\", \"Ò\"),\n\n (\"Ù\", \"Ù\"),\n\n (\"à\", \"à\"),\n\n (\"è\", \"è\"),\n\n (\"ì\", \"ì\"),\n\n (\"ò\", \"ò\"),\n\n (\"ù\", \"ù\"),\n\n];\n\n\n\n\n\nconst UTF_REDUCE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Ç\", \"C\"), // cedilla\n\n (\"ç\", \"c\"),\n\n (\"Á\", \"A\"), // acute accent\n\n (\"É\", \"E\"),\n\n (\"Í\", \"I\"),\n\n (\"Ó\", \"O\"),\n\n (\"Ú\", \"U\"),\n\n (\"á\", \"a\"),\n", "file_path": "rust/core/src/lang/lang_portuguese.rs", "rank": 55, "score": 3.9232229865803117 }, { "content": " }\n\n\n\n Some(gram)\n\n }\n\n\n\n #[inline]\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n\n let len = self.word.len();\n\n (len, Some(len))\n\n }\n\n}\n\n\n\nimpl<'a> ExactSizeIterator for TrigramIter<'a> { }\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::assert_debug_snapshot;\n\n use crate::utils::to_vec;\n\n use super::Trigrams;\n", "file_path": "rust/core/src/utils/trigrams.rs", "rank": 56, "score": 3.921175424229073 }, { "content": "use crate::lang::{PartOfSpeech};\n\n\n", "file_path": "rust/core/src/tokenization/word.rs", "rank": 57, "score": 3.912379821592263 }, { "content": "#![macro_use]\n\n\n\nmod trigrams;\n\nmod limitsort;\n\nmod fading_windows;\n\n\n\npub use trigrams::{Trigrams, TrigramIter};\n\npub use limitsort::{LimitSort, LimitSortIter};\n\npub use fading_windows::FadingWindows;\n\n\n\n\n\nmacro_rules! min {\n\n ($x: expr) => ($x);\n\n ($x: expr, $($z: expr),+) => (::std::cmp::min($x, min!($($z),*)));\n\n}\n\n\n\n\n\nmacro_rules! max {\n\n ($x: expr) => ($x);\n\n ($x: expr, $($z: expr),+) => (::std::cmp::max($x, max!($($z),*)));\n\n}\n\n\n\n\n", "file_path": "rust/core/src/utils/mod.rs", "rank": 58, "score": 3.9118141236092487 }, { "content": "use fnv::{FnvHashMap as HashMap};\n\nuse crate::utils::{Trigrams, LimitSort};\n\nuse crate::tokenization::{Word, TextRef};\n\nuse super::Record;\n\n\n\n\n\npub struct TrigramIndex {\n\n len: usize,\n\n dict: HashMap<[char; 3], Vec<usize>>,\n\n counts: Vec<usize>,\n\n}\n\n\n\n\n\nimpl TrigramIndex {\n\n pub fn new() -> Self {\n\n Self {\n\n len: 0,\n\n dict: HashMap::default(),\n\n counts: Vec::new(),\n\n }\n", "file_path": "rust/core/src/store/trigram_index.rs", "rank": 59, "score": 3.8910536524652115 }, { "content": " (Vowel, 'ÿ'),\n\n // cedilla\n\n (Consonant, 'Ç'),\n\n (Consonant, 'ç'),\n\n // tilde\n\n (Consonant, 'Ñ'),\n\n (Consonant, 'ñ'),\n\n // ligatures\n\n (Vowel, 'Æ'),\n\n (Vowel, 'æ'),\n\n (Vowel, 'Œ'),\n\n (Vowel, 'œ'),\n\n (Vowel, 'Ø'),\n\n (Vowel, 'ø'),\n\n];\n\n\n\n\n\nconst UTF_COMPOSE_MAP: &[(&'static str, &'static str)] = &[\n\n // acute accent\n\n (\"É\", \"É\"),\n", "file_path": "rust/core/src/lang/lang_french.rs", "rank": 60, "score": 3.8431913920727867 }, { "content": " (\"Ë\", \"Ë\"),\n\n (\"Ï\", \"Ï\"),\n\n (\"Ü\", \"Ü\"),\n\n (\"Ÿ\", \"Ÿ\"),\n\n (\"ë\", \"ë\"),\n\n (\"ï\", \"ï\"),\n\n (\"ü\", \"ü\"),\n\n (\"ÿ\", \"ÿ\"),\n\n // cedilla\n\n (\"Ç\", \"Ç\"),\n\n (\"ç\", \"ç\"),\n\n // tilde\n\n (\"Ñ\", \"Ñ\"),\n\n (\"ñ\", \"ñ\"),\n\n];\n\n\n\n\n\nconst UTF_REDUCE_MAP: &[(&'static str, &'static str)] = &[\n\n // acute accent\n\n (\"É\", \"E\"),\n", "file_path": "rust/core/src/lang/lang_french.rs", "rank": 61, "score": 3.8431913920727867 }, { "content": "use crate::lang::{Lang, CharClass, CharPattern, PartOfSpeech};\n\nuse super::word::Word;\n\nuse super::word_view::WordView;\n\nuse super::word_split::WordSplit;\n\nuse super::text::Text;\n\n\n\n\n\n#[derive(PartialEq, Debug, Clone)]\n\npub struct WordShape {\n\n pub offset: usize,\n\n pub slice: (usize, usize),\n\n pub stem: usize,\n\n pub pos: Option<PartOfSpeech>,\n\n pub fin: bool,\n\n}\n\n\n\n\n\nimpl Word for WordShape {\n\n #[inline] fn offset(&self) -> usize { self.offset }\n\n #[inline] fn slice(&self) -> (usize, usize) { self.slice }\n", "file_path": "rust/core/src/tokenization/word_shape.rs", "rank": 62, "score": 3.8407381130309446 }, { "content": "const appSveltePath = path.join(projectRoot, \"src\", \"App.svelte\")\n", "file_path": "examples/browser-svelte/scripts/setupTypeScript.js", "rank": 63, "score": 3.8306159605931507 }, { "content": " }\n\n }\n\n\n\n Some((&window[..1], &window[..1]))\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use fnv::{FnvHashMap as HashMap};\n\n use insta::assert_debug_snapshot;\n\n use crate::utils::{to_vec, to_str};\n\n use super::Normalize;\n\n\n\n fn normalize<'a>(word: &'a [char]) -> (Vec<String>, Vec<String>) {\n\n let mut norm_map = HashMap::default();\n\n norm_map.insert(to_vec(\"ó\"), to_vec(\"o\"));\n\n norm_map.insert(to_vec(\"ó\"), to_vec(\"o\"));\n\n let mut source = Vec::new();\n", "file_path": "rust/core/src/lang/normalize.rs", "rank": 64, "score": 3.8300736586636197 }, { "content": "use std::cell::RefCell;\n\nuse fnv::{FnvHashMap as HashMap};\n\nuse rust_stemmers::Stemmer;\n\nuse crate::utils::to_vec;\n\nuse super::{CharClass, PartOfSpeech};\n\nuse super::normalize::Normalize;\n\n\n\nconst BUFFER_CAPACITY: usize = 20;\n\n\n\n\n\npub struct Lang {\n\n stemmer: Option<Stemmer>,\n\n char_map: HashMap<char, CharClass>,\n\n pos_map: HashMap<Vec<char>, PartOfSpeech>,\n\n compose_map: HashMap<Vec<char>, Vec<char>>,\n\n reduce_map: HashMap<Vec<char>, Vec<char>>,\n\n stem_buffer: RefCell<String>,\n\n norm_buffer1: RefCell<Vec<char>>,\n\n norm_buffer2: RefCell<Vec<char>>,\n\n}\n", "file_path": "rust/core/src/lang/lang.rs", "rank": 65, "score": 3.8211417969648847 }, { "content": " typos: f64\n\n ) -> (Self, Self) {\n\n debug_assert!(rword.slice.0 + rslice <= rword.slice.1, \"Record match subslice is too long\");\n\n debug_assert!(qword.slice.0 + qslice <= qword.slice.1, \"Query match subslice is too long\");\n\n let fin = qword.fin || rword.len() == rslice;\n\n let rmatch = WordMatch {\n\n offset: rword.offset,\n\n slice: rword.slice,\n\n subslice: (0, rslice),\n\n func: rword.is_function(),\n\n typos,\n\n fin,\n\n };\n\n let qmatch = WordMatch {\n\n offset: qword.offset,\n\n slice: qword.slice,\n\n subslice: (0, qslice),\n\n func: qword.is_function(),\n\n typos,\n\n fin,\n", "file_path": "rust/core/src/matching/word_match.rs", "rank": 66, "score": 3.7864652224005093 }, { "content": "use crate::lang::{CharClass, PartOfSpeech};\n\nuse super::text::Text;\n\nuse super::word::Word;\n\nuse super::word_shape::WordShape;\n\n\n\n\n\n#[derive(PartialEq, Debug, Clone)]\n\npub struct WordView<'a> {\n\n pub offset: usize,\n\n pub slice: (usize, usize),\n\n pub stem: usize,\n\n pub pos: Option<PartOfSpeech>,\n\n pub fin: bool,\n\n source: &'a [char],\n\n chars: &'a [char],\n\n classes: &'a [CharClass],\n\n}\n\n\n\n\n\nimpl<'a> Word for WordView<'a> {\n", "file_path": "rust/core/src/tokenization/word_view.rs", "rank": 67, "score": 3.7516793373408546 }, { "content": " };\n\n (rmatch, qmatch)\n\n }\n\n\n\n pub fn word_len(&self) -> usize {\n\n let (left, right) = self.slice;\n\n return right - left;\n\n }\n\n\n\n pub fn match_len(&self) -> usize {\n\n let (left, right) = self.subslice;\n\n return right - left;\n\n }\n\n\n\n pub fn split(&self, w1: &WordView, w2: &WordView) -> Option<(Self, Self)> {\n\n debug_assert!(w2.slice.0 > w1.slice.0, \"Invalid word order in match split\");\n\n debug_assert!(w1.offset == self.offset || w2.offset == self.offset, \"Invalid word offsets in match split\");\n\n if w1.slice.0 + self.subslice.1 <= w2.slice.0 {\n\n return None;\n\n }\n", "file_path": "rust/core/src/matching/word_match.rs", "rank": 68, "score": 3.676018708684847 }, { "content": "use std::cell::RefCell;\n\nuse crate::utils::to_vec;\n\nuse crate::lang::Lang;\n\nuse super::{Record, TrigramIndex, DEFAULT_LIMIT};\n\n\n\n\n\npub struct Store {\n\n pub next_ix: usize,\n\n pub records: Vec<Record>,\n\n pub limit: usize,\n\n pub lang: Lang,\n\n pub dividers: (Vec<char>, Vec<char>),\n\n pub index: RefCell<TrigramIndex>,\n\n pub top_ixs: RefCell<Option<Vec<usize>>>,\n\n}\n\n\n\n\n\nimpl Store {\n\n pub fn new() -> Self {\n\n Self {\n", "file_path": "rust/core/src/store/store.rs", "rank": 69, "score": 3.658086741926772 }, { "content": "\n\nconst CHAR_CLASSES: &[(CharClass, char)] = &[];\n\n\n\n\n\nconst UTF_COMPOSE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Á\", \"Á\"), // acute accent\n\n (\"É\", \"É\"),\n\n (\"Í\", \"Í\"),\n\n (\"Ó\", \"Ó\"),\n\n (\"Ú\", \"Ú\"),\n\n (\"á\", \"á\"),\n\n (\"é\", \"é\"),\n\n (\"í\", \"í\"),\n\n (\"ó\", \"ó\"),\n\n (\"ú\", \"ú\"),\n\n (\"Ñ\", \"Ñ\"), // tilde\n\n (\"ñ\", \"ñ\"),\n\n (\"Ü\", \"Ü\"), // diaeresis\n\n (\"ü\", \"ü\"),\n\n];\n", "file_path": "rust/core/src/lang/lang_spanish.rs", "rank": 70, "score": 3.621558008250459 }, { "content": " (Particle, \"eben\"),\n\n (Particle, \"etwas\"),\n\n (Particle, \"nur\"),\n\n (Particle, \"ruhig\"),\n\n (Particle, \"shon\"),\n\n (Particle, \"zwar\"),\n\n (Particle, \"soweiso\"),\n\n];\n\n\n\n\n\nconst CHAR_CLASSES: &[(CharClass, char)] = &[\n\n (Consonant, 'ß'),\n\n];\n\n\n\n\n\nconst UTF_COMPOSE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Ä\", \"Ä\"),\n\n (\"Ö\", \"Ö\"),\n\n (\"Ü\", \"Ü\"),\n\n (\"ä\", \"ä\"),\n", "file_path": "rust/core/src/lang/lang_german.rs", "rank": 71, "score": 3.587080722858135 }, { "content": "\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use insta::assert_debug_snapshot;\n\n use crate::utils::to_vec;\n\n use super::super::{CharClass, PartOfSpeech};\n\n use super::Lang;\n\n\n\n fn get_lang() -> Lang {\n\n let mut lang = Lang::new();\n\n lang.add_unicode_composition(\"ó\", \"ó\");\n\n lang.add_unicode_reduction(\"ó\", \"o\");\n\n lang.add_unicode_reduction(\"õ\", \"oo\");\n\n lang.add_pos(\"fóo\", PartOfSpeech::Particle);\n\n lang.add_char_class('x', CharClass::Consonant);\n\n lang.add_char_class('y', CharClass::Vowel);\n\n lang\n\n }\n\n\n", "file_path": "rust/core/src/lang/lang.rs", "rank": 72, "score": 3.5865090488093045 }, { "content": "use super::CharClass;\n\nuse CharClass::{Consonant, Vowel};\n\n\n\npub const CHAR_CLASSES_LATIN: &[(CharClass, char)] = &[\n\n (Consonant, 'b'),\n\n (Consonant, 'c'),\n\n (Consonant, 'd'),\n\n (Consonant, 'f'),\n\n (Consonant, 'g'),\n\n (Consonant, 'h'),\n\n (Consonant, 'j'),\n\n (Consonant, 'k'),\n\n (Consonant, 'l'),\n\n (Consonant, 'm'),\n\n (Consonant, 'n'),\n\n (Consonant, 'p'),\n\n (Consonant, 'q'),\n\n (Consonant, 'r'),\n\n (Consonant, 's'),\n\n (Consonant, 't'),\n", "file_path": "rust/core/src/lang/constants.rs", "rank": 73, "score": 3.457012205539432 }, { "content": "use crate::lang::{Lang, CharPattern};\n\nuse super::word::Word;\n\nuse super::word_shape::WordShape;\n\n\n\n\n\npub struct WordSplit<'a, 'b, P: CharPattern> {\n\n word: &'a WordShape,\n\n lang: &'a Lang,\n\n chars: &'a [char],\n\n pattern: &'b P,\n\n word_offset: usize,\n\n char_offset: usize,\n\n}\n\n\n\n\n\nimpl<'a, 'b, P: CharPattern> WordSplit<'a, 'b, P> {\n\n pub fn new(\n\n word: &'a WordShape,\n\n chars: &'a [char],\n\n pattern: &'b P,\n", "file_path": "rust/core/src/tokenization/word_split.rs", "rank": 74, "score": 3.453295768368754 }, { "content": " lang_portuguese,\n\n lang_russian,\n\n lang_spanish,\n\n};\n\n\n\n\n\nthread_local! {\n\n static STORES: RefCell<HashMap<usize, Store>> = RefCell::new(HashMap::default());\n\n static RESULTS: RefCell<HashMap<usize, Vec<SearchResult>>> = RefCell::new(HashMap::default());\n\n}\n\n\n\n\n", "file_path": "rust/core/src/lib.rs", "rank": 75, "score": 3.362971928062552 }, { "content": " // (Conjunction, \"no entanto\"),\n\n // (Conjunction, \"ora ... ora\"),\n\n // (Conjunction, \"ou ... ou\"),\n\n // (Conjunction, \"por conseguinte\"),\n\n // (Conjunction, \"por isso\"),\n\n // (Conjunction, \"quer ... quer\"),\n\n // (Conjunction, \"sempre que\"),\n\n // (Conjunction, \"tanto ... como\"),\n\n // (Conjunction, \"visto que\"),\n\n];\n\n\n\n\n\nconst CHAR_CLASSES: &[(CharClass, char)] = &[];\n\n\n\n\n\nconst UTF_COMPOSE_MAP: &[(&'static str, &'static str)] = &[\n\n (\"Ç\", \"Ç\"), // cedilla\n\n (\"ç\", \"ç\"),\n\n (\"Á\", \"Á\"), // acute accent\n\n (\"É\", \"É\"),\n", "file_path": "rust/core/src/lang/lang_portuguese.rs", "rank": 76, "score": 3.165219603692848 }, { "content": "use crate::tokenization::{TextOwn, tokenize_record};\n\nuse crate::lang::Lang;\n\n\n\n\n\n#[derive(Debug)]\n\npub struct Record {\n\n pub ix: usize,\n\n pub id: usize,\n\n pub title: TextOwn,\n\n pub rating: usize,\n\n}\n\n\n\n\n\nimpl Record {\n\n pub fn new(id: usize, source: &str, rating: usize, lang: &Lang) -> Record {\n\n Record {\n\n ix: 0,\n\n id,\n\n title: tokenize_record(source, lang),\n\n rating,\n\n }\n\n }\n\n}\n", "file_path": "rust/core/src/store/record.rs", "rank": 77, "score": 3.003789044102516 }, { "content": " use super::{PartOfSpeech, CharClass};\n\n use super::{lang_english, UTF_COMPOSE_MAP, UTF_REDUCE_MAP};\n\n\n\n #[test]\n\n fn stem() {\n\n let lang = lang_english();\n\n let w = to_vec(\"universe\");\n\n assert_eq!(lang.stem(&w), 7);\n\n }\n\n\n\n #[test]\n\n fn get_pos() {\n\n let lang = lang_english();\n\n let w1 = to_vec(\"universe\");\n\n let w2 = to_vec(\"the\");\n\n assert_eq!(lang.get_pos(&w1), None);\n\n assert_eq!(lang.get_pos(&w2), Some(PartOfSpeech::Article));\n\n }\n\n\n\n #[test]\n", "file_path": "rust/core/src/lang/lang_english.rs", "rank": 78, "score": 2.8408456074087245 }, { "content": " use super::{PartOfSpeech, CharClass};\n\n use super::{lang_russian, UTF_COMPOSE_MAP, UTF_REDUCE_MAP};\n\n\n\n #[test]\n\n pub fn stem() {\n\n let lang = lang_russian();\n\n let w = to_vec(\"важный\");\n\n assert_eq!(lang.stem(&w), 4);\n\n }\n\n\n\n #[test]\n\n pub fn get_pos() {\n\n let lang = lang_russian();\n\n let w1 = to_vec(\"важный\");\n\n let w2 = to_vec(\"ведь\");\n\n assert_eq!(lang.get_pos(&w1), None);\n\n assert_eq!(lang.get_pos(&w2), Some(PartOfSpeech::Particle));\n\n }\n\n\n\n #[test]\n", "file_path": "rust/core/src/lang/lang_russian.rs", "rank": 79, "score": 2.8408456074087245 }, { "content": " 1.0 - self.similarity(slice1, slice2)\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::Jaccard;\n\n\n\n\n\n fn round2(x: f64) -> f64 {\n\n (x * 100.0).round() / 100.0\n\n }\n\n\n\n\n\n #[test]\n\n fn empty_both() {\n\n let jaccard = Jaccard::new();\n\n let s1: &[usize] = &[];\n\n let s2: &[usize] = &[];\n", "file_path": "rust/core/src/matching/jaccard/mod.rs", "rank": 80, "score": 2.82644127523331 }, { "content": "// using_store(|store| {\n\n// let query = tokenize_query(\"greenpink\", &store.lang);\n\n// let hits = store.search(&query.to_ref());\n\n// dbg!(&hits);\n\n// // assert_hit_match(&hits[0], r\"<vin>\");\n\n// });\n\n// }\n\n\n\n\n\n// // TODO fix\n\n// /**\n\n// * When typing \"babule\" most proper records are lost\n\n// * in trigram index due to char transposition.\n\n// */\n\n// #[test]\n\n// fn ecommerce_case__bauble() {\n\n// using_store(|store| {\n\n// let query = tokenize_query(\"babule\", &store.lang);\n\n// let hits = store.search(&query.to_ref());\n\n// dbg!(&hits);\n\n// // assert_all_match(&hits[..5], r\"<bauble>\");\n\n// });\n\n// }\n", "file_path": "rust/core/tests/ecommerce.rs", "rank": 81, "score": 2.8189999823182355 }, { "content": "use fnv::{FnvHashMap as HashMap};\n\nuse crate::utils::FadingWindows;\n\n\n\nconst NORM_MAX_PATTERN_LEN: usize = 2;\n\n\n\n\n\npub struct Normalize<'a> {\n\n windows: FadingWindows<'a, char>,\n\n map: &'a HashMap<Vec<char>, Vec<char>>,\n\n skip: usize,\n\n}\n\n\n\n\n\nimpl<'a> Normalize<'a> {\n\n pub fn new(source: &'a [char], map: &'a HashMap<Vec<char>, Vec<char>>) -> Self {\n\n Self {\n\n windows: FadingWindows::new(source, NORM_MAX_PATTERN_LEN),\n\n map,\n\n skip: 0,\n\n }\n", "file_path": "rust/core/src/lang/normalize.rs", "rank": 82, "score": 2.7974877716946485 }, { "content": "# LucidSuggest example for browser using plain JavaScript\n\n\n\n## Try it\n\n\n\n```bash\n\n$ npm install\n\n$ npm run build\n\n$ npm run dev-server\n\n```\n\n\n\nThen open http://localhost:8000/index.html\n", "file_path": "examples/browser-plain/README.md", "rank": 83, "score": 2.7835186896427175 }, { "content": " use super::{PartOfSpeech, CharClass};\n\n use super::{lang_french, UTF_COMPOSE_MAP, UTF_REDUCE_MAP};\n\n\n\n #[test]\n\n pub fn stem() {\n\n let lang = lang_french();\n\n let w = to_vec(\"université\");\n\n assert_eq!(lang.stem(&w), 7);\n\n }\n\n\n\n #[test]\n\n pub fn get_pos() {\n\n let lang = lang_french();\n\n let w1 = to_vec(\"université\");\n\n let w2 = to_vec(\"les\");\n\n assert_eq!(lang.get_pos(&w1), None);\n\n assert_eq!(lang.get_pos(&w2), Some(PartOfSpeech::Article));\n\n }\n\n\n\n #[test]\n", "file_path": "rust/core/src/lang/lang_french.rs", "rank": 84, "score": 2.776301400338405 }, { "content": " use super::{PartOfSpeech, CharClass};\n\n use super::{lang_portuguese, UTF_COMPOSE_MAP, UTF_REDUCE_MAP};\n\n\n\n #[test]\n\n pub fn stem() {\n\n let lang = lang_portuguese();\n\n let w = to_vec(\"quilométricas\");\n\n assert_eq!(lang.stem(&w), 9);\n\n }\n\n\n\n #[test]\n\n pub fn get_pos() {\n\n let lang = lang_portuguese();\n\n let w1 = to_vec(\"quilométricas\");\n\n let w2 = to_vec(\"uma\");\n\n assert_eq!(lang.get_pos(&w1), None);\n\n assert_eq!(lang.get_pos(&w2), Some(PartOfSpeech::Article));\n\n }\n\n\n\n #[test]\n", "file_path": "rust/core/src/lang/lang_portuguese.rs", "rank": 85, "score": 2.776301400338405 }, { "content": " use super::{PartOfSpeech, CharClass};\n\n use super::{lang_german, UTF_COMPOSE_MAP, UTF_REDUCE_MAP};\n\n\n\n #[test]\n\n pub fn stem() {\n\n let lang = lang_german();\n\n let w = to_vec(\"singen\");\n\n assert_eq!(lang.stem(&w), 4);\n\n }\n\n\n\n #[test]\n\n pub fn get_pos() {\n\n let lang = lang_german();\n\n let w1 = to_vec(\"singen\");\n\n let w2 = to_vec(\"das\");\n\n assert_eq!(lang.get_pos(&w1), None);\n\n assert_eq!(lang.get_pos(&w2), Some(PartOfSpeech::Article));\n\n }\n\n\n\n #[test]\n", "file_path": "rust/core/src/lang/lang_german.rs", "rank": 86, "score": 2.776301400338405 }, { "content": " use super::{PartOfSpeech, CharClass};\n\n use super::{lang_spanish, UTF_COMPOSE_MAP, UTF_REDUCE_MAP};\n\n\n\n #[test]\n\n pub fn stem() {\n\n let lang = lang_spanish();\n\n let w = to_vec(\"torniquete\");\n\n assert_eq!(lang.stem(&w), 9);\n\n }\n\n\n\n #[test]\n\n pub fn get_pos() {\n\n let lang = lang_spanish();\n\n let w1 = to_vec(\"torniquete\");\n\n let w2 = to_vec(\"una\");\n\n assert_eq!(lang.get_pos(&w1), None);\n\n assert_eq!(lang.get_pos(&w2), Some(PartOfSpeech::Article));\n\n }\n\n\n\n #[test]\n", "file_path": "rust/core/src/lang/lang_spanish.rs", "rank": 87, "score": 2.776301400338405 }, { "content": "## Record type\n\n\n\nAn object stored in `LucidSuggest` instance and matched with a query by it's `search` method.\n\n\n\nProperties:\n\n\n\n| Name | Type | Description |\n\n| :----- | :------------------- | :------------------------------------------------------------------ |\n\n| id | `number` | Unique non-negative integer identifier. |\n\n| title | `string` | Text used for fulltext search. |\n\n| rating | `number | undefined` | Matching tie breaker: records with greater rating are ranked higher |\n\n\n\n**Note:** use priority, product popularity, or term frequency as `rating` to improve overall scoring.\n\n\n\n\n\n## Hit type\n\n\n\nAn object containing information on a record-query match, including the record itself.\n\n\n\nProperties:\n\n\n\n| Name | Type | Description |\n\n| :----- | :----------------------- | :--------------------------------------------------------------------- |\n\n| title | `string` | The record title highlighted with default `[ ]`. Useful for debugging. |\n\n| chunks | `HighlightedTextChunk[]` | An object representation of the matched title. |\n\n| record | `Record` | The original record linked. |\n\n\n\nAn example of record structure:\n\n```javascript\n\n{\n\n title: '[Electr]ic toothbrush',\n\n chunks: [\n\n {text: 'Electr', highlight: true},\n\n {text: 'ic toothbrush', highlight: false},\n\n ],\n\n record: {\n\n id: 1,\n\n title: \"Electric Toothbrush\",\n\n },\n\n}\n\n```\n\n\n\n\n", "file_path": "javascript/REFERENCE.md", "rank": 88, "score": 2.5667357559839976 }, { "content": "\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::FadingWindows;\n\n\n\n #[test]\n\n fn fading_windows_empty() {\n\n let input: [usize; 0] = [];\n\n for size in 0 .. 4 {\n\n let output = FadingWindows::new(&input, size).collect::<Vec<_>>();\n\n let expect: Vec<&[usize]> = Vec::new();\n\n assert_eq!(output, expect);\n\n }\n\n }\n\n\n\n\n\n #[test]\n\n fn fading_windows_singleton() {\n\n let input: [usize; 1] = [10];\n", "file_path": "rust/core/src/utils/fading_windows.rs", "rank": 89, "score": 2.2954862968383742 }, { "content": "## Fulltext search features\n\n\n\nWhen an exact match is unavailable, the best possible partial matches are returned:\n\n```javascript\n\nawait suggest.search(\"plastic toothbrush\")\n\n// returns:\n\n// [\n\n// Hit { title: \"Electric [Toothbrush]\" }\n\n// ]\n\n```\n\n\n\nSearch as you type, results are provided from the first letter:\n\n```javascript\n\nawait suggest.search(\"c\")\n\n// returns:\n\n// [\n\n// Hit { title: \"Lightning to USB-C [C]able\" }\n\n// ]\n\n```\n\n\n\nSearch algorithm is resilient to different kinds of typos:\n\n```javascript\n\nawait suggest.search(\"alkln\")\n\n// returns:\n\n// [\n\n// Hit { title: \"AA [Alkalin]e Batteries\" }\n\n// ]\n\n```\n\n\n\n```javascript\n\nawait suggest.search(\"tooth brush\")\n\n// returns:\n\n// [\n\n// Hit { title: \"Electric [Toothbrush]\" }\n\n// ]\n\n```\n\n\n\nStemming is used to handle different word forms:\n\n```javascript\n\nawait suggest.search(\"battery\")\n\n// returns:\n\n// [\n\n// Hit { title: \"AA Alkaline [Batteri]es\" }\n\n// ]\n\n```\n\n\n\nFunction words (articles, prepositions, etc.) receive special treatment, so they don't occupy top positions every time you start typing a word:\n\n```javascript\n\nawait suggest.search(\"to\")\n\n// returns:\n\n// [\n\n// Hit { title: \"Electric [To]othbrush\" },\n\n// Hit { title: \"Lightning [to] USB-C Cable\" },\n\n// ]\n\n```\n\n\n\n## Rating\n\n\n\nOptional `rating` field can be used as a tie breaker: records with greater `rating` are ranked higher. Use priority, product popularity, or term frequency as `rating` to improve overall scoring.\n\n\n\nFor example, let's use state population as `rating`:\n\n```javascript\n\nsuggest.addRecords([\n\n {id: 1, rating: 3000, title: \"Nevada\"},\n\n {id: 2, rating: 8900, title: \"New Jersey\"},\n\n {id: 3, rating: 19500, title: \"New York\"},\n\n])\n\n```\n\n\n\n```javascript\n\nawait suggest.search(\"ne\")\n\n// returns:\n\n// [\n\n// Hit { title: \"[Ne]w York\" },\n\n// Hit { title: \"[Ne]w Jersey\" },\n\n// Hit { title: \"[Ne]vada\" },\n\n// ]\n\n```\n\n\n\n\n", "file_path": "javascript/README.md", "rank": 90, "score": 2.2810096216870654 }, { "content": "*Looking for a shareable component template? Go here --> [sveltejs/component-template](https://github.com/sveltejs/component-template)*\n\n\n\n---\n\n\n\n# svelte app\n\n\n\nThis is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.\n\n\n\nTo create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):\n\n\n\n```bash\n\nnpx degit sveltejs/template svelte-app\n\ncd svelte-app\n\n```\n\n\n\n*Note that you will need to have [Node.js](https://nodejs.org) installed.*\n\n\n\n\n\n## Get started\n\n\n\nInstall the dependencies...\n\n\n\n```bash\n\ncd svelte-app\n\nnpm install\n\n```\n\n\n\n...then start [Rollup](https://rollupjs.org):\n\n\n\n```bash\n\nnpm run dev\n\n```\n\n\n\nNavigate to [localhost:5000](http://localhost:5000). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.\n\n\n\nBy default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.\n\n\n\nIf you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.\n\n\n\n## Building and running in production mode\n\n\n\nTo create an optimised version of the app:\n\n\n\n```bash\n\nnpm run build\n\n```\n\n\n\nYou can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).\n\n\n\n\n", "file_path": "examples/browser-svelte/README.md", "rank": 91, "score": 2.225616080385429 }, { "content": "## Single-page app mode\n\n\n\nBy default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.\n\n\n\nIf you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `\"start\"` command in package.json:\n\n\n\n```js\n\n\"start\": \"sirv public --single\"\n\n```\n\n\n\n## Using TypeScript\n\n\n\nThis template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:\n\n\n\n```bash\n\nnode scripts/setupTypeScript.js\n\n```\n\n\n\nOr remove the script via:\n\n\n\n```bash\n\nrm scripts/setupTypeScript.js\n\n```\n\n\n\n## Deploying to the web\n\n\n\n### With [Vercel](https://vercel.com)\n\n\n\nInstall `vercel` if you haven't already:\n\n\n\n```bash\n\nnpm install -g vercel\n\n```\n\n\n\nThen, from within your project folder:\n\n\n\n```bash\n\ncd public\n\nvercel deploy --name my-project\n\n```\n\n\n\n### With [surge](https://surge.sh/)\n\n\n\nInstall `surge` if you haven't already:\n\n\n\n```bash\n\nnpm install -g surge\n\n```\n\n\n\nThen, from within your project folder:\n\n\n\n```bash\n\nnpm run build\n\nsurge public my-project.surge.sh\n\n```\n", "file_path": "examples/browser-svelte/README.md", "rank": 92, "score": 2.2013110040557438 }, { "content": "use std::cmp::min;\n\n\n\n\n\n#[derive(Debug)]\n\npub struct FadingWindows<'a, T: 'a> {\n\n v: &'a [T],\n\n size: usize,\n\n}\n\n\n\nimpl<'a, T: 'a> FadingWindows<'a, T> {\n\n pub fn new(v: &'a [T], size: usize) -> Self {\n\n if size == 0 && v.len() > 0 {\n\n panic!(\"Can't have zero window size with nonempty slice\");\n\n }\n\n Self { v, size }\n\n }\n\n}\n\n\n\nimpl<'a, T> Iterator for FadingWindows<'a, T> {\n\n type Item = &'a [T];\n", "file_path": "rust/core/src/utils/fading_windows.rs", "rank": 93, "score": 2.1602185760892914 }, { "content": "use std::fmt;\n\n\n\n\n\npub struct DistMatrix {\n\n size: usize,\n\n raw: Vec<f64>,\n\n}\n\n\n\n\n\nimpl DistMatrix {\n\n pub fn new(size: usize) -> Self {\n\n let raw = vec![0.0; size * size];\n\n let mut matrix = Self { size, raw };\n\n matrix.init();\n\n matrix\n\n }\n\n\n\n pub fn prepare(&mut self, coefs1: &[f64], coefs2: &[f64]) {\n\n let size = max!(coefs1.len() + 2, coefs2.len() + 2);\n\n if size > self.size {\n", "file_path": "rust/core/src/matching/damlev/matrix.rs", "rank": 94, "score": 2.08644880250454 }, { "content": "use crate::tokenization::{Word, WordView};\n\n\n\n\n\n#[derive(Clone, PartialEq, Debug)]\n\npub struct WordMatch {\n\n pub offset: usize,\n\n pub slice: (usize, usize),\n\n pub subslice: (usize, usize),\n\n pub typos: f64,\n\n pub func: bool,\n\n pub fin: bool,\n\n}\n\n\n\n\n\nimpl WordMatch {\n\n pub fn new_pair(\n\n rword: &WordView,\n\n qword: &WordView,\n\n rslice: usize,\n\n qslice: usize,\n", "file_path": "rust/core/src/matching/word_match.rs", "rank": 95, "score": 2.0400057363724002 }, { "content": "## Supported languages\n\n\n\n| Language | Module |\n\n| :--------- | :----------------- |\n\n| German | `lucid-suggest/de` |\n\n| English | `lucid-suggest/en` |\n\n| French | `lucid-suggest/fr` |\n\n| Spanish | `lucid-suggest/es` |\n\n| Portuguese | `lucid-suggest/pt` |\n\n| Russian | `lucid-suggest/ru` |\n\n\n\n\n\n## Bundle sizes\n\n\n\nNote that base64-encoded Wasm source constitutes the bulk of a bundle. Minifiers don't affect it, but gzip compresses it well.\n\n\n\n| lang | size | gzipped |\n\n| :--- | ---: | ------: |\n\n| de | 200K | 79K |\n\n| en | 202K | 80K |\n\n| es | 205K | 80K |\n\n| es | 208K | 82K |\n\n| pt | 205K | 81K |\n\n| ru | 202K | 79K |\n\n\n\n\n\n## Performance\n\n\n\nLucidSuggest works best with shorter sentences, like shopping items or book titles. Using longer texts, like articles or movie descriptions, may lead to performance regressions and generally poor user experience.\n\n\n\nLucidSuggest can handle large dataset. For example, for 10000 records, each containing 4-8 common English words, you can expect a typical search to take about 1 ms, so you can simply call it at every keystroke without using throttling or Web Workers.\n\n\n\nBelow are the detailed performance measurements, obtained using Node.js 14.3, Intel Core i7 (I7-9750H) 2.6 GHz.\n\n\n\nSearching:\n\n\n\n| | 2-4 words | 4-8 words |\n\n| --------------: | --------: | --------: |\n\n| 100 records | 0.09 ms | 0.24 ms |\n\n| 1000 records | 0.27 ms | 0.48 ms |\n\n| 10 000 records | 0.45 ms | 0.68 ms |\n\n| 100 000 records | 1.40 ms | 2.00 ms |\n\n\n\nIndexing:\n\n\n\n| | 2-4 words | 4-8 words |\n\n| --------------: | --------: | --------: |\n\n| 100 records | 1 ms | 2 ms |\n\n| 1000 records | 11 ms | 16 ms |\n\n| 10 000 records | 88 ms | 160 ms |\n\n| 100 000 records | 810 ms | 1900 ms |\n", "file_path": "javascript/README.md", "rank": 96, "score": 2.0348366589288185 }, { "content": " fn split_typos(typos: f64, len1: usize, len2: usize) -> (f64, f64) {\n\n if len1 == 0 { return (0.0, typos); }\n\n if len2 == 0 { return (typos, 0.0); }\n\n let len1 = len1 as f64;\n\n let len2 = len2 as f64;\n\n let split1 = (typos * len1 * 10.0 / (len1 + len2)).ceil() / 10.0;\n\n let split2 = ((typos - split1) * 10.0).round() / 10.0;\n\n (split1, split2)\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{WordMatch};\n\n\n\n fn test_split_typos(\n\n len1: usize,\n\n len2: usize,\n\n sample: &[(f64, f64, f64)],\n", "file_path": "rust/core/src/matching/word_match.rs", "rank": 97, "score": 1.974092606815209 }, { "content": "# LucidSuggest Quickstart\n\n\n\nAutocomplete engine that works out of the box. Fast, simple, built with Rust.\n\n\n\nCheck out [live demo](http://lucid-search.io.s3-website.eu-central-1.amazonaws.com/demo/index.html).\n\n\n\nRead [JavaScript docs](http://github.com/thaumant/lucid-suggest/blob/master/javascript/README.md).\n\n\n\n# Dev & Build from source\n\n\n\n```sh\n\ncd javascript\n\nnpm install\n\nmake\n\n```\n\n\n\nensure rustup is [installed](https://rustup.rs/)\n\n\n\n```\n\ncurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\n\nsource $HOME/.cargo/env\n\nrustup show\n\n\n\n```\n\n\n\nensure wasm-pack is [installed](https://rustwasm.github.io/wasm-pack/installer/):\n\n\n\n```\n\nwasm-pack -V\n\n```\n\n\n\nThe makefile uses rollup, so to execute rollup it's handy to have nodejs installed so you can do:\n\n\n\n```\n\nnpx rollup ....\n\n```\n\n\n\n```\n\n# Using Ubuntu\n\ncurl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -\n\nsudo apt-get install -y nodejs\n\n````\n\n\n", "file_path": "README.md", "rank": 98, "score": 1.869947551840926 }, { "content": "## Getting started (Nodejs/Deno)\n\n\n\n\n\nInitialize:\n\n```javascript\n\nimport { LucidSuggest } from 'lucid-suggest/en' // nodejs\n\n// or\n\nimport { LucidSuggest } from 'https://raw.githubusercontent.com/DougAnderson444/deno-autosuggest/master/javascript/en.js' // Deno\n\n\n\nconst suggest = new LucidSuggest()\n\nsuggest.addRecords([\n\n {id: 1, title: \"Electric Toothbrush\"},\n\n {id: 2, title: \"Lightning to USB-C Cable\"},\n\n {id: 3, title: \"AA Alkaline Batteries\"},\n\n])\n\n```\n\n\n\nSearch:\n\n```javascript\n\nawait suggest.search(\"batteries\")\n\n// returns:\n\n// [\n\n// Hit {\n\n// record: { id: 3, title: \"AA Alkaline Batteries\" },\n\n// chunks: [\n\n// { text: \"AA Alkaline \", highlight: false },\n\n// { text: \"Batteries\", highlight: true }\n\n// ]\n\n// }\n\n// ]\n\n```\n\n\n\n\n\n## Rendering results\n\n\n\nBy default LucidSuggest highlights hit titles using `[ ]`.\n\nThe easiest way to change it is to use `highlight` helper function:\n\n\n\n```javascript\n\nimport {LucidSuggest, highlight} from 'lucid-suggest'\n\n\n\nconst suggest = new LucidSuggest()\n\nconst hits = await suggest.search(\"to\")\n\n\n\nhits.map(hit => ({\n\n value: hit.record.id.toString(),\n\n label: highlight(hit, '<strong>', '</strong>')\n\n}))\n\n// returns:\n\n// [\n\n// {value: \"1\", label: \"Electric <strong>To</strong>othbrush\"},\n\n// {value: \"2\", label: \"Lightning <strong>to</strong> USB-C Cable\"},\n\n// ]\n\n```\n\n\n\nOr you can directly operate on chunks of a highlighted text,\n\nwhich can come in handy if you need a more complex render logic:\n\n\n\n```javascript\n\nconst hits = await suggest.search(\"to\")\n\nhits.map(hit => ({\n\n value: hit.record.id.toString(),\n\n label: hit.chunks\n\n .map(c => c.highlight ? `<strong>${c.text}</strong>` : c.text)\n\n .join('')\n\n}))\n\n// returns:\n\n// [\n\n// {value: \"1\", label: \"Electric <strong>To</strong>othbrush\"},\n\n// {value: \"2\", label: \"Lightning <strong>to</strong> USB-C Cable\"},\n\n// ]\n\n```\n\n\n\nFor examples of rendering in React or Vue, see [Resources](#resources) section.\n\n\n", "file_path": "javascript/README.md", "rank": 99, "score": 1.352514307226505 } ]
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 mut [u8]) -> Result<&'a str, ()>\n\nwhere\n\n T: Serialize + ?Sized,\n\n{\n\n let mut cursor = Cursor::new(buffer);\n\n value.serialize(&mut cursor)?;\n\n Ok(cursor.finish())\n\n}\n\n\n\n// IMPLEMENTATION DETAIL\n\n// fast path: these don't contain unicode\n", "file_path": "ujson/src/ser.rs", "rank": 1, "score": 161123.28702404792 }, { "content": "fn our_nl_addr() -> ipv6::Addr {\n\n EXTENDED_ADDRESS.into_link_local_address()\n\n}\n\n\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 2, "score": 155527.42727700353 }, { "content": "/// Deserializes `T` from the given `bytes`\n\npub fn from_bytes<T>(bytes: &[u8]) -> Result<T, ()>\n\nwhere\n\n T: Deserialize,\n\n{\n\n let mut cursor = Cursor::new(bytes);\n\n cursor.parse_whitespace();\n\n let x = T::deserialize(&mut cursor)?;\n\n cursor.finish()?;\n\n Ok(x)\n\n}\n\n\n", "file_path": "ujson/src/de.rs", "rank": 3, "score": 154937.76206109492 }, { "content": "#[derive(uDeserialize, uSerialize)]\n\nstruct Payload {\n\n led: bool,\n\n}\n\n\n", "file_path": "firmware/examples/ipv6.rs", "rank": 4, "score": 154035.2785168066 }, { "content": "#[derive(uDeserialize, uSerialize)]\n\nstruct Payload {\n\n led: bool,\n\n}\n\n\n", "file_path": "firmware/examples/ipv4.rs", "rank": 5, "score": 153768.63556346073 }, { "content": "#[doc(hidden)]\n\npub fn field_name(ident: &[u8], cursor: &mut Cursor<'_>) -> Result<(), ()> {\n\n cursor.push_byte(b'\"')?;\n\n cursor.push(ident)?;\n\n cursor.push_byte(b'\"')\n\n}\n\n\n", "file_path": "ujson/src/ser.rs", "rank": 6, "score": 150785.7162982265 }, { "content": "#[derive(uDeserialize, uSerialize)]\n\nstruct Payload {\n\n led: bool,\n\n}\n\n\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 7, "score": 118824.74036749318 }, { "content": "// main logic\n\nfn run(mut ethernet: Ethernet, mut led: Led) -> Option<!> {\n\n let mut cache = FnvIndexMap::new();\n\n let mut buf = [0; BUF_SZ as usize];\n\n let mut extra_buf = [0; BUF_SZ as usize];\n\n\n\n loop {\n\n let packet = if let Some(packet) = ethernet\n\n .next_packet()\n\n .map_err(|_| error!(\"Enc28j60::next_packet failed\"))\n\n .ok()?\n\n {\n\n if usize(packet.len()) > usize::from(BUF_SZ) {\n\n error!(\"packet too big for our buffer\");\n\n\n\n packet\n\n .ignore()\n\n .map_err(|_| error!(\"Packet::ignore failed\"))\n\n .ok()?;\n\n\n\n continue;\n", "file_path": "firmware/examples/ipv6.rs", "rank": 8, "score": 117706.02925526585 }, { "content": "// main logic\n\nfn run(mut ethernet: Ethernet, mut led: Led) -> Option<!> {\n\n let mut cache = FnvIndexMap::new();\n\n let mut buf = [0; BUF_SZ];\n\n let mut extra_buf = [0; BUF_SZ];\n\n loop {\n\n let packet = if let Some(packet) = ethernet\n\n .next_packet()\n\n .map_err(|_| error!(\"Enc28j60::next_packet failed\"))\n\n .ok()?\n\n {\n\n if usize(packet.len()) > buf.len() {\n\n error!(\"packet too big for our buffer\");\n\n\n\n packet\n\n .ignore()\n\n .map_err(|_| error!(\"Packet::ignore failed\"))\n\n .ok()?;\n\n\n\n continue;\n\n } else {\n", "file_path": "firmware/examples/ipv4.rs", "rank": 9, "score": 117507.30530864856 }, { "content": "pub fn fatal() -> ! {\n\n interrupt::disable();\n\n\n\n // (I wish this board had more than one LED)\n\n error!(\"fatal error\");\n\n\n\n loop {}\n\n}\n", "file_path": "firmware/src/lib.rs", "rank": 10, "score": 106289.23488342276 }, { "content": "pub fn init_mrf24j40(\n\n core: cortex_m::Peripherals,\n\n device: stm32f103xx::Peripherals,\n\n) -> (Radio, Led) {\n\n let mut rcc = device.RCC.constrain();\n\n let mut afio = device.AFIO.constrain(&mut rcc.apb2);\n\n let mut flash = device.FLASH.constrain();\n\n let mut gpioa = device.GPIOA.split(&mut rcc.apb2);\n\n\n\n let clocks = rcc.cfgr.freeze(&mut flash.acr);\n\n\n\n // LED\n\n let mut gpioc = device.GPIOC.split(&mut rcc.apb2);\n\n let mut led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh);\n\n // turn the LED off during initialization\n\n led.set_high();\n\n\n\n // SPI\n\n let mut ncs = gpioa.pa4.into_push_pull_output(&mut gpioa.crl);\n\n ncs.set_high();\n", "file_path": "firmware/src/lib.rs", "rank": 11, "score": 103281.47514841688 }, { "content": "pub fn init_enc28j60(\n\n core: cortex_m::Peripherals,\n\n device: stm32f103xx::Peripherals,\n\n) -> (Ethernet, Led) {\n\n let mut rcc = device.RCC.constrain();\n\n let mut afio = device.AFIO.constrain(&mut rcc.apb2);\n\n let mut flash = device.FLASH.constrain();\n\n let mut gpioa = device.GPIOA.split(&mut rcc.apb2);\n\n\n\n let clocks = rcc.cfgr.freeze(&mut flash.acr);\n\n\n\n // LED\n\n let mut gpioc = device.GPIOC.split(&mut rcc.apb2);\n\n let mut led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh);\n\n // turn the LED off during initialization\n\n led.set_high();\n\n\n\n // SPI\n\n let mut ncs = gpioa.pa4.into_push_pull_output(&mut gpioa.crl);\n\n ncs.set_high();\n", "file_path": "firmware/src/lib.rs", "rank": 12, "score": 103281.47514841688 }, { "content": "// Helper\n\nstruct PtrReader<'a>(&'a [u8]);\n\n\n\nimpl<'a> PtrReader<'a> {\n\n fn try_read_u8(&mut self) -> ::core::option::Option<u8> {\n\n if self.0.len() > 0 {\n\n Some(unsafe { self.read_u8() })\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n unsafe fn read_u8(&mut self) -> u8 {\n\n let byte = *self.0.gu(0);\n\n self.0 = self.0.rf(1..);\n\n byte\n\n }\n\n\n\n unsafe fn read_u16(&mut self) -> u16 {\n\n let halfword = NE::read_u16(self.0.rt(..2));\n\n self.0 = self.0.rf(2..);\n", "file_path": "src/coap.rs", "rank": 13, "score": 98968.28972009072 }, { "content": "struct State {\n\n led: bool,\n\n}\n\n\n", "file_path": "firmware/examples/ipv6.rs", "rank": 14, "score": 94423.88344246318 }, { "content": "struct State {\n\n led: bool,\n\n}\n\n\n", "file_path": "firmware/examples/ipv4.rs", "rank": 15, "score": 94157.2404891173 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n info!(\"Initializing ..\");\n\n\n\n let core = cortex_m::Peripherals::take().unwrap_or_else(|| {\n\n error!(\"cortex_m::Peripherals::take failed\");\n\n\n\n blue_pill::fatal();\n\n });\n\n\n\n let device = stm32f103xx::Peripherals::take().unwrap_or_else(|| {\n\n error!(\"stm32f103xx::Peripherals::take failed\");\n\n\n\n blue_pill::fatal();\n\n });\n\n\n\n let (mut ethernet, led) = blue_pill::init_enc28j60(core, device);\n\n\n\n ethernet.accept(&[Packet::Multicast]).unwrap_or_else(|_| {\n\n error!(\"receive filter configuration failed\");\n\n\n", "file_path": "firmware/examples/ipv6.rs", "rank": 16, "score": 92696.44254745243 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n info!(\"Initializing ..\");\n\n\n\n let core = cortex_m::Peripherals::take().unwrap_or_else(|| {\n\n error!(\"cortex_m::Peripherals::take failed\");\n\n\n\n blue_pill::fatal();\n\n });\n\n\n\n let device = stm32f103xx::Peripherals::take().unwrap_or_else(|| {\n\n error!(\"stm32f103xx::Peripherals::take failed\");\n\n\n\n blue_pill::fatal();\n\n });\n\n\n\n let (ethernet, led) = blue_pill::init_enc28j60(core, device);\n\n\n\n info!(\"Done with initialization\");\n\n\n\n run(ethernet, led).unwrap_or_else(|| {\n\n error!(\"`run` failed\");\n\n\n\n blue_pill::fatal()\n\n });\n\n}\n\n\n\nconst BUF_SZ: usize = 256;\n\n\n", "file_path": "firmware/examples/ipv4.rs", "rank": 17, "score": 92429.79959410656 }, { "content": "fn run(mut radio: Radio, mut led: Led) -> Option<!> {\n\n let mut cache = FnvIndexMap::new();\n\n let mut buf = [0; BUF_SZ as usize];\n\n let mut extra_buf = [0; BUF_SZ as usize];\n\n\n\n loop {\n\n let rx = radio\n\n .receive(OwningSliceTo(&mut buf, BUF_SZ))\n\n .map_err(|_| error!(\"Mrf24j40::receive failed\"))\n\n .ok()?;\n\n\n\n info!(\"new packet\");\n\n\n\n match on_new_frame(\n\n &State {\n\n led: led.is_set_low(),\n\n },\n\n rx.frame,\n\n &mut extra_buf,\n\n &mut cache,\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 18, "score": 91464.2815707733 }, { "content": "struct OptionsMut<'a> {\n\n opts: &'a mut [u8],\n\n}\n\n\n\nimpl<'a> OptionsMut<'a> {\n\n fn new(opts: &'a mut [u8]) -> Self {\n\n OptionsMut { opts }\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for OptionsMut<'a> {\n\n type Item = OptionMut<'a>;\n\n\n\n fn next(&mut self) -> Option<OptionMut<'a>> {\n\n if self.opts.is_empty() {\n\n None\n\n } else {\n\n unsafe {\n\n let ty = OptionType::from(*self.opts.gu(0));\n\n let len = 8 * usize::from(*self.opts.gu(1));\n", "file_path": "src/icmpv6.rs", "rank": 19, "score": 91290.79000190456 }, { "content": "struct OptionMut<'a> {\n\n pub ty: OptionType,\n\n pub contents: &'a mut [u8],\n\n}\n\n\n\nimpl<'a> Options<'a> {\n\n // NOTE: Caller must ensure that `are_valid` returns `true` before using this as an iterator\n\n unsafe fn new(opts: &'a [u8]) -> Self {\n\n Options { opts }\n\n }\n\n\n\n fn are_valid(mut opts: &'a [u8]) -> bool {\n\n if opts.is_empty() {\n\n return true;\n\n }\n\n\n\n loop {\n\n if opts.len() < 2 {\n\n // not big enough to contain the Type and Length\n\n return false;\n", "file_path": "src/icmpv6.rs", "rank": 20, "score": 91290.79000190456 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/arp.rs", "rank": 21, "score": 89630.66949484724 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/ipv4.rs", "rank": 22, "score": 89157.01942216646 }, { "content": "// IO-less / \"pure\" logic (NB logging does IO but it's easy to remove using `GLOBAL_LOGGER`)\n\nfn on_new_frame<'a>(\n\n state: &State,\n\n bytes: OwningSliceTo<&'a mut [u8; BUF_SZ as usize], u8>,\n\n extra_buf: &'a mut [u8; BUF_SZ as usize],\n\n cache: &mut FnvIndexMap<ipv6::Addr, ieee802154::Addr, CACHE_SIZE>,\n\n) -> Action<'a> {\n\n let mut mac = if let Ok(f) = ieee802154::Frame::parse(bytes) {\n\n info!(\"valid MAC frame\");\n\n\n\n f\n\n } else {\n\n error!(\"invalid MAC frame\");\n\n\n\n return Action::Nop;\n\n };\n\n\n\n if mac.get_type() != ieee802154::Type::Data {\n\n info!(\"not a data frame\");\n\n\n\n return Action::Nop;\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 23, "score": 86532.80938373512 }, { "content": "// IO-less / \"pure\" logic (NB logging does IO but it's easy to remove using `GLOBAL_LOGGER`)\n\nfn on_new_packet<'a>(\n\n state: &State,\n\n bytes: OwningSliceTo<&'a mut [u8; BUF_SZ as usize], u8>,\n\n extra_buf: &'a mut [u8; BUF_SZ as usize],\n\n cache: &mut FnvIndexMap<ipv6::Addr, mac::Addr, CACHE_SIZE>,\n\n) -> Action<'a> {\n\n let mut eth = if let Ok(f) = ether::Frame::parse(bytes) {\n\n info!(\"valid Ethernet frame\");\n\n\n\n f\n\n } else {\n\n error!(\"invalid Ethernet frame\");\n\n\n\n return Action::Nop;\n\n };\n\n\n\n let src_ll_addr = eth.get_source();\n\n let dest_ll_addr = eth.get_destination();\n\n\n\n if src_ll_addr.is_multicast() {\n", "file_path": "firmware/examples/ipv6.rs", "rank": 24, "score": 86085.89120722907 }, { "content": "fn on_coap_request<'a>(\n\n state: &State,\n\n req: coap::Message<&[u8]>,\n\n mut resp: coap::Message<&'a mut [u8], coap::Unset>,\n\n change: &mut Option<bool>,\n\n) -> coap::Message<&'a mut [u8]> {\n\n let code = req.get_code();\n\n\n\n resp.set_message_id(req.get_message_id());\n\n resp.set_type(if req.get_type() == coap::Type::Confirmable {\n\n coap::Type::Acknowledgement\n\n } else {\n\n coap::Type::NonConfirmable\n\n });\n\n\n\n if code == coap::Method::Get.into() {\n\n info!(\"CoAP: GET request\");\n\n\n\n let mut opts = req.options();\n\n while let Some(opt) = opts.next() {\n", "file_path": "firmware/examples/ipv6.rs", "rank": 25, "score": 86081.73171166162 }, { "content": "// IO-less / \"pure\" logic (NB logging does IO but it's easy to remove using `GLOBAL_LOGGER`)\n\nfn on_new_packet<'a>(\n\n state: &State,\n\n bytes: &'a mut [u8],\n\n cache: &mut FnvIndexMap<ipv4::Addr, mac::Addr, CACHE_SIZE>,\n\n extra_buf: &'a mut [u8],\n\n) -> Action<'a> {\n\n let mut eth = if let Ok(f) = ether::Frame::parse(bytes) {\n\n info!(\"valid Ethernet frame\");\n\n f\n\n } else {\n\n error!(\"not a valid Ethernet frame\");\n\n return Action::Nop;\n\n };\n\n\n\n let src_mac = eth.get_source();\n\n\n\n match eth.get_type() {\n\n ether::Type::Arp => {\n\n info!(\"EtherType: ARP\");\n\n\n", "file_path": "firmware/examples/ipv4.rs", "rank": 26, "score": 85831.66106434505 }, { "content": "fn on_coap_request<'a>(\n\n state: &State,\n\n req: coap::Message<&[u8]>,\n\n mut resp: coap::Message<&'a mut [u8], coap::Unset>,\n\n change: &mut Option<bool>,\n\n) -> coap::Message<&'a mut [u8]> {\n\n let code = req.get_code();\n\n\n\n resp.set_message_id(req.get_message_id());\n\n resp.set_type(if req.get_type() == coap::Type::Confirmable {\n\n coap::Type::Acknowledgement\n\n } else {\n\n coap::Type::NonConfirmable\n\n });\n\n\n\n if code == coap::Method::Get.into() {\n\n info!(\"CoAP: GET request\");\n\n\n\n let mut opts = req.options();\n\n while let Some(opt) = opts.next() {\n", "file_path": "firmware/examples/ipv4.rs", "rank": 27, "score": 85827.5015687776 }, { "content": "#[proc_macro_derive(uDeserialize)]\n\npub fn deserialize(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let error = quote!(compile_error!(\n\n \"`#[derive(uSerialize)]` can only be used on `struct`s with named fields\"\n\n ))\n\n .into();\n\n\n\n match input.data {\n\n Data::Struct(s) => {\n\n let ident = input.ident;\n\n\n\n let fields = match s.fields {\n\n Fields::Named(fields) => fields.named,\n\n _ => return error,\n\n };\n\n\n\n if fields.is_empty() {\n\n return error;\n\n }\n\n\n", "file_path": "ujson/macros/src/lib.rs", "rank": 28, "score": 79498.43596682958 }, { "content": "#[proc_macro_derive(uSerialize)]\n\npub fn serialize(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let error = quote!(compile_error!(\n\n \"`#[derive(uSerialize)]` can only be used on `struct`s with named fields\"\n\n ))\n\n .into();\n\n\n\n match input.data {\n\n Data::Struct(s) => {\n\n let ident = input.ident;\n\n\n\n let fields = match s.fields {\n\n Fields::Named(fields) => fields.named,\n\n _ => return error,\n\n };\n\n\n\n if fields.is_empty() {\n\n return error;\n\n }\n\n\n", "file_path": "ujson/macros/src/lib.rs", "rank": 29, "score": 79498.43596682958 }, { "content": "#[panic_handler]\n\nfn panic(_: &PanicInfo) -> ! {\n\n // uncomment to debug link errors\n\n // nop();\n\n extern \"C\" {\n\n #[link_name = \"This crate contains at least one panicking branch\"]\n\n fn panic() -> !;\n\n }\n\n\n\n unsafe { panic() }\n\n}\n\n\n", "file_path": "panic-never/src/lib.rs", "rank": 30, "score": 64895.502924705375 }, { "content": "#[test]\n\nfn coap4() {\n\n static PAYLOAD: &[u8] = b\"Hello\";\n\n\n\n let buffer: &mut [u8] = &mut [0; 256];\n\n\n\n let mut m = ether::Frame::new(buffer);\n\n m.set_source(mac::Addr::BROADCAST);\n\n m.set_destination(mac::Addr::BROADCAST);\n\n\n\n m.ipv4(|ip| {\n\n ip.set_source(ipv4::Addr::UNSPECIFIED);\n\n ip.set_destination(ipv4::Addr::UNSPECIFIED);\n\n\n\n ip.udp(|udp| {\n\n udp.set_source(coap::PORT);\n\n udp.set_destination(coap::PORT);\n\n\n\n udp.coap(0, |mut coap| {\n\n coap.set_code(coap::Response::Content);\n\n coap.set_payload(PAYLOAD)\n", "file_path": "tests/roundtrip.rs", "rank": 31, "score": 59300.95966500118 }, { "content": "struct State {\n\n led: bool,\n\n}\n\n\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 32, "score": 59213.34529314973 }, { "content": "// See Section 4.6 of RFC 2461\n\nstruct Options<'a> {\n\n opts: &'a [u8],\n\n}\n\n\n", "file_path": "src/icmpv6.rs", "rank": 33, "score": 57487.35064735723 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n info!(\"Initializing ..\");\n\n\n\n let core = cortex_m::Peripherals::take().unwrap_or_else(|| {\n\n error!(\"cortex_m::Peripherals::take failed\");\n\n\n\n blue_pill::fatal();\n\n });\n\n\n\n let device = stm32f103xx::Peripherals::take().unwrap_or_else(|| {\n\n error!(\"stm32f103xx::Peripherals::take failed\");\n\n\n\n blue_pill::fatal();\n\n });\n\n\n\n let (radio, led) = blue_pill::init_mrf24j40(core, device);\n\n\n\n info!(\"Done with initialization\");\n\n\n\n // NOTE as per RFC6775 we don't need to do Duplicate Address Detection since we are using an\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 34, "score": 57485.90439813899 }, { "content": "#[test]\n\nfn array() {\n\n #[derive(uSerialize)]\n\n struct X {\n\n x: [u8; 33],\n\n }\n\n\n\n assert_eq!(\n\n ujson::write(&X { x: [0; 33] }, &mut [0; 128]).unwrap(),\n\n \"{\\\"x\\\":[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]}\"\n\n );\n\n}\n", "file_path": "ujson/tests/serialize.rs", "rank": 35, "score": 57485.90439813899 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n info!(\"Hello, world!\");\n\n\n\n loop {}\n\n}\n", "file_path": "firmware/examples/hello.rs", "rank": 36, "score": 57485.90439813899 }, { "content": "#[test]\n\nfn two_fields() {\n\n #[derive(uDeserialize, Debug, PartialEq)]\n\n struct Pair {\n\n x: u8,\n\n y: u16,\n\n }\n\n\n\n assert_eq!(\n\n ujson::from_bytes::<Pair>(\"{\\\"x\\\":0,\\\"y\\\":1}\".as_bytes()).unwrap(),\n\n Pair { x: 0, y: 1 }\n\n );\n\n\n\n // reverse order\n\n assert_eq!(\n\n ujson::from_bytes::<Pair>(\"{\\\"y\\\":0,\\\"x\\\":1}\".as_bytes()).unwrap(),\n\n Pair { y: 0, x: 1 }\n\n );\n\n}\n", "file_path": "ujson/tests/deserialize.rs", "rank": 37, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/iphc.rs", "rank": 38, "score": 55839.83868620518 }, { "content": "#[test]\n\nfn one_field() {\n\n #[derive(uSerialize)]\n\n struct Led {\n\n led: bool,\n\n }\n\n\n\n assert_eq!(\n\n ujson::write(&Led { led: true }, &mut [0; 16]).unwrap(),\n\n \"{\\\"led\\\":true}\"\n\n );\n\n}\n\n\n", "file_path": "ujson/tests/serialize.rs", "rank": 39, "score": 55839.83868620518 }, { "content": "#[test]\n\nfn two_fields() {\n\n #[derive(uSerialize)]\n\n struct Pair {\n\n x: u8,\n\n y: u16,\n\n }\n\n\n\n assert_eq!(\n\n ujson::write(&Pair { x: 0, y: 42 }, &mut [0; 16]).unwrap(),\n\n \"{\\\"x\\\":0,\\\"y\\\":42}\"\n\n );\n\n}\n\n\n", "file_path": "ujson/tests/serialize.rs", "rank": 40, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/ieee802154.rs", "rank": 41, "score": 55839.83868620518 }, { "content": "#[test]\n\nfn one_field() {\n\n #[derive(uDeserialize, Debug, PartialEq)]\n\n struct Led {\n\n led: bool,\n\n }\n\n\n\n assert_eq!(\n\n ujson::from_bytes::<Led>(\"{\\\"led\\\":true}\".as_bytes()).unwrap(),\n\n Led { led: true }\n\n );\n\n\n\n assert_eq!(\n\n ujson::from_bytes::<Led>(\"{\\\"led\\\":false}\".as_bytes()).unwrap(),\n\n Led { led: false }\n\n );\n\n\n\n // with whitespace\n\n assert_eq!(\n\n ujson::from_bytes::<Led>(\"{ \\\"led\\\" : true }\".as_bytes()).unwrap(),\n\n Led { led: true }\n\n );\n\n}\n\n\n", "file_path": "ujson/tests/deserialize.rs", "rank": 42, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/icmpv6.rs", "rank": 43, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/ether.rs", "rank": 44, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/nhc.rs", "rank": 45, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/icmp.rs", "rank": 46, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/udp.rs", "rank": 47, "score": 55839.83868620518 }, { "content": "#[allow(dead_code)]\n\n#[inline(never)]\n\nfn nop() -> ! {\n\n loop {\n\n asm::nop();\n\n }\n\n}\n", "file_path": "panic-never/src/lib.rs", "rank": 48, "score": 55839.83868620518 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n loop {}\n\n}\n", "file_path": "panic-never/examples/coap.rs", "rank": 49, "score": 55839.83868620518 }, { "content": "struct OptionRef<'a> {\n\n pub ty: OptionType,\n\n pub contents: &'a [u8],\n\n}\n\n\n", "file_path": "src/icmpv6.rs", "rank": 50, "score": 55659.9821866795 }, { "content": "/// Types that can be serialized into JSON\n\npub trait Serialize {\n\n // IMPLEMENTATION DETAIL\n\n #[doc(hidden)]\n\n fn serialize(&self, cursor: &mut Cursor<'_>) -> Result<(), ()>;\n\n}\n\n\n\nimpl Serialize for bool {\n\n fn serialize(&self, cursor: &mut Cursor<'_>) -> Result<(), ()> {\n\n cursor.push(if *self { b\"true\" } else { b\"false\" })\n\n }\n\n}\n\n\n\nunsafe fn uninitialized<T>() -> T {\n\n MaybeUninit::uninit().assume_init()\n\n}\n\n\n\nmacro_rules! unsigned {\n\n ($(($uN:ty, $N:expr),)+) => {\n\n $(\n\n impl Serialize for $uN {\n", "file_path": "ujson/src/ser.rs", "rank": 51, "score": 53783.508776809686 }, { "content": "pub trait UxxExt {\n\n type Half;\n\n\n\n fn low(self) -> Self::Half;\n\n fn high(self) -> Self::Half;\n\n}\n\n\n\nimpl UxxExt for u16 {\n\n type Half = u8;\n\n\n\n fn low(self) -> u8 {\n\n let mask = (1 << 8) - 1;\n\n (self & mask) as u8\n\n }\n\n\n\n fn high(self) -> u8 {\n\n (self >> 8) as u8\n\n }\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 52, "score": 53778.914050606414 }, { "content": "/// IMPLEMENTATION DETAIL\n\npub trait UncheckedIndex {\n\n type T;\n\n\n\n // get_unchecked\n\n unsafe fn gu(&self, i: usize) -> &Self::T;\n\n // get_unchecked_mut\n\n unsafe fn gum(&mut self, i: usize) -> &mut Self::T;\n\n unsafe fn r(&self, r: Range<usize>) -> &Self;\n\n unsafe fn rm(&mut self, r: Range<usize>) -> &mut Self;\n\n unsafe fn rt(&self, r: RangeTo<usize>) -> &Self;\n\n unsafe fn rtm(&mut self, r: RangeTo<usize>) -> &mut Self;\n\n unsafe fn rf(&self, r: RangeFrom<usize>) -> &Self;\n\n unsafe fn rfm(&mut self, r: RangeFrom<usize>) -> &mut Self;\n\n}\n\n\n\nimpl<T> UncheckedIndex for [T] {\n\n type T = T;\n\n\n\n unsafe fn gu(&self, at: usize) -> &T {\n\n debug_assert!(at < self.len());\n", "file_path": "src/traits.rs", "rank": 53, "score": 53778.914050606414 }, { "content": "fn on_coap_request<'a>(\n\n state: &State,\n\n req: coap::Message<&[u8]>,\n\n mut resp: coap::Message<&'a mut [u8], coap::Unset>,\n\n change: &mut Option<bool>,\n\n) -> coap::Message<&'a mut [u8]> {\n\n let code = req.get_code();\n\n\n\n resp.set_message_id(req.get_message_id());\n\n resp.set_type(if req.get_type() == coap::Type::Confirmable {\n\n coap::Type::Acknowledgement\n\n } else {\n\n coap::Type::NonConfirmable\n\n });\n\n\n\n if code == coap::Method::Get.into() {\n\n info!(\"CoAP: GET request\");\n\n\n\n let mut opts = req.options();\n\n while let Some(opt) = opts.next() {\n", "file_path": "firmware/examples/sixlowpan.rs", "rank": 54, "score": 52510.32083281633 }, { "content": "pub trait SliceExt {\n\n unsafe fn slice(&self, start: usize, len: usize) -> &Self;\n\n unsafe fn slice_mut(&mut self, start: usize, len: usize) -> &mut Self;\n\n}\n\n\n\nimpl<T> SliceExt for [T] {\n\n unsafe fn slice(&self, start: usize, len: usize) -> &[T] {\n\n debug_assert!(dbg!(start) < dbg!(self.len()) && dbg!(len) <= self.len() - start);\n\n\n\n slice::from_raw_parts(self.as_ptr().add(start), len)\n\n }\n\n\n\n unsafe fn slice_mut(&mut self, start: usize, len: usize) -> &mut [T] {\n\n debug_assert!(dbg!(start) < dbg!(self.len()) && dbg!(len) <= self.len() - start);\n\n\n\n slice::from_raw_parts_mut(self.as_mut_ptr().add(start), len)\n\n }\n\n}\n", "file_path": "ujson/src/traits.rs", "rank": 55, "score": 52270.78118383376 }, { "content": "// [Type State] EchoReply or EchoRequest\n\npub trait Echo: 'static {}\n\n\n\nimpl Echo for EchoReply {}\n\nimpl Echo for EchoRequest {}\n", "file_path": "src/sealed.rs", "rank": 56, "score": 51183.92233948743 }, { "content": "pub trait TryInto<T> {\n\n type Error;\n\n fn try_into(self) -> Result<T, Self::Error>;\n\n}\n\n\n\nimpl<T, U> TryInto<U> for T\n\nwhere\n\n U: TryFrom<T>,\n\n{\n\n type Error = U::Error;\n\n\n\n fn try_into(self) -> Result<U, U::Error> {\n\n U::try_from(self)\n\n }\n\n}\n", "file_path": "src/traits.rs", "rank": 57, "score": 51179.45521511676 }, { "content": "/// Types that can be deserialized into JSON\n\npub trait Deserialize: Sized {\n\n // IMPLEMENTATION DETAIL\n\n #[doc(hidden)]\n\n fn deserialize(cursor: &mut Cursor<'_>) -> Result<Self, ()>;\n\n}\n\n\n\nimpl Deserialize for bool {\n\n fn deserialize(cursor: &mut Cursor<'_>) -> Result<Self, ()> {\n\n match cursor.peek() {\n\n Some(b't') => cursor.parse_ident(b\"true\").map(|_| true),\n\n Some(b'f') => cursor.parse_ident(b\"false\").map(|_| false),\n\n _ => Err(()),\n\n }\n\n }\n\n}\n\n\n\nmacro_rules! unsigned {\n\n ($($uN:ty),+) => {\n\n $(\n\n impl Deserialize for $uN {\n", "file_path": "ujson/src/de.rs", "rank": 58, "score": 49675.91707454736 }, { "content": "pub trait TryFrom<T>: Sized {\n\n type Error;\n\n\n\n fn try_from(value: T) -> Result<Self, Self::Error>;\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 59, "score": 47673.20711127248 }, { "content": "//! Formatting helpers\n\n\n\nuse core::fmt;\n\n\n\npub struct Display<T>(pub T);\n\n\n\nimpl<T> fmt::Debug for Display<T>\n\nwhere\n\n T: fmt::Display,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", self.0)\n\n }\n\n}\n\n\n\npub struct Hex(pub u16);\n\n\n\nimpl fmt::Debug for Hex {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"0x{:04x}\", self.0)\n", "file_path": "src/fmt.rs", "rank": 60, "score": 39557.29256380086 }, { "content": " }\n\n}\n\n\n\npub struct Quoted<T>(pub T);\n\n\n\nimpl<T> fmt::Debug for Quoted<T>\n\nwhere\n\n T: fmt::Display,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"\\\"{}\\\"\", self.0)\n\n }\n\n}\n", "file_path": "src/fmt.rs", "rank": 61, "score": 39544.30468337778 }, { "content": "//! MAC: Medium Access Control\n\n\n\nuse core::fmt;\n\n\n\nuse hash32_derive::Hash32;\n\n\n\nuse crate::ipv6;\n\n\n\n/// MAC address\n\n#[derive(Clone, Copy, Eq, Hash32, PartialEq)]\n\npub struct Addr(pub [u8; 6]);\n\n\n\nimpl Addr {\n\n /// Broadcast address\n\n pub const BROADCAST: Self = Addr([0xff; 6]);\n\n\n\n /// Is this a unicast address?\n\n pub fn is_unicast(&self) -> bool {\n\n !self.is_broadcast() && !self.is_multicast()\n\n }\n", "file_path": "src/mac.rs", "rank": 62, "score": 39522.387459221856 }, { "content": " self.0[0] == 0x33 && self.0[1] == 0x33\n\n }\n\n\n\n /// Converts this MAC address into a link-local IPv6 address using the EUI-64 format (see\n\n /// RFC2464)\n\n pub fn into_link_local_address(self) -> ipv6::Addr {\n\n let mut bytes = [0; 16];\n\n\n\n bytes[0] = 0xfe;\n\n bytes[1] = 0x80;\n\n\n\n bytes[8..].copy_from_slice(&self.eui_64());\n\n\n\n ipv6::Addr(bytes)\n\n }\n\n\n\n fn eui_64(self) -> [u8; 8] {\n\n let mut bytes = [0; 8];\n\n\n\n bytes[..3].copy_from_slice(&self.0[..3]);\n", "file_path": "src/mac.rs", "rank": 63, "score": 39520.22712083314 }, { "content": " // toggle the Universal/Local (U/L) bit\n\n bytes[0] ^= 1 << 1;\n\n\n\n bytes[3] = 0xff;\n\n bytes[4] = 0xfe;\n\n\n\n bytes[5..].copy_from_slice(&self.0[3..]);\n\n\n\n bytes\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Addr {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n struct Hex<'a>(&'a [u8; 6]);\n\n\n\n impl<'a> fmt::Debug for Hex<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n use core::fmt::Write;\n\n\n", "file_path": "src/mac.rs", "rank": 64, "score": 39516.36422380884 }, { "content": "\n\n /// Is this the broadcast address?\n\n pub fn is_broadcast(&self) -> bool {\n\n *self == Self::BROADCAST\n\n }\n\n\n\n /// Is this a multicast address?\n\n ///\n\n /// NOTE `Addr::BROADCAST.is_multicast()` returns `false`\n\n pub fn is_multicast(&self) -> bool {\n\n !self.is_broadcast() && self.0[0] & 1 == 1\n\n }\n\n\n\n /// Is this an IPv4 multicast address?\n\n pub fn is_ipv4_multicast(&self) -> bool {\n\n self.0[0] == 0x01 && self.0[1] == 0x00 && self.0[2] == 0x5e && self.0[3] >> 7 == 0\n\n }\n\n\n\n /// Is this an IPv6 multicast address?\n\n pub fn is_ipv6_multicast(&self) -> bool {\n", "file_path": "src/mac.rs", "rank": 65, "score": 39504.37039601396 }, { "content": "}\n\n\n\nimpl fmt::Display for Addr {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n let mut is_first = true;\n\n for byte in &self.0 {\n\n if is_first {\n\n is_first = false;\n\n } else {\n\n f.write_str(\":\")?;\n\n }\n\n\n\n write!(f, \"{:02x}\", byte)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "src/mac.rs", "rank": 66, "score": 39504.19990174657 }, { "content": " let mut is_first = true;\n\n\n\n f.write_char('[')?;\n\n for byte in self.0.iter() {\n\n if is_first {\n\n is_first = false;\n\n } else {\n\n f.write_str(\", \")?;\n\n }\n\n\n\n write!(f, \"0x{:02x}\", byte)?;\n\n }\n\n f.write_char(']')?;\n\n\n\n Ok(())\n\n }\n\n }\n\n\n\n f.debug_tuple(\"mac::Addr\").field(&Hex(&self.0)).finish()\n\n }\n", "file_path": "src/mac.rs", "rank": 67, "score": 39501.711828591855 }, { "content": " use super::Addr;\n\n\n\n #[test]\n\n fn eui_64() {\n\n assert_eq!(\n\n Addr([0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE]).eui_64(),\n\n [0x36, 0x56, 0x78, 0xFF, 0xFE, 0x9A, 0xBC, 0xDE]\n\n );\n\n }\n\n}\n", "file_path": "src/mac.rs", "rank": 68, "score": 39494.87943926834 }, { "content": " unsafe { ipv4::Addr(*(self.as_slice().as_ptr().add(TPA.start) as *const _)) }\n\n }\n\n\n\n /// Is this an ARP probe?\n\n pub fn is_a_probe(&self) -> bool {\n\n self.get_spa() == ipv4::Addr::UNSPECIFIED\n\n }\n\n}\n\n\n\nimpl<B> Packet<B, Ethernet, Ipv4>\n\nwhere\n\n B: AsSlice<Element = u8> + AsMutSlice<Element = u8>,\n\n{\n\n /* Setters */\n\n /// Sets the SHA (Sender Hardware Address) field of the payload\n\n pub fn set_sha(&mut self, sha: mac::Addr) {\n\n unsafe {\n\n self.as_mut_slice().rm(SHA).copy_from_slice(&sha.0);\n\n }\n\n }\n", "file_path": "src/arp.rs", "rank": 69, "score": 39322.43008735317 }, { "content": " #[derive(Clone, Copy, Debug, PartialEq)]\n\n pub enum Operation {\n\n /// Request operation\n\n Request = 1,\n\n /// Reply operation\n\n Reply = 2,\n\n }\n\n);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use rand::{self, RngCore};\n\n\n\n use crate::{arp, ether, ipv4, mac};\n\n\n\n const SIZE: usize = 46;\n\n\n\n const BYTES: &[u8; SIZE] = &[\n\n 255, 255, 255, 255, 255, 255, // eth: destination\n\n 120, 68, 118, 217, 106, 124, // eth: source\n", "file_path": "src/arp.rs", "rank": 70, "score": 39314.48185662101 }, { "content": " /* Miscellaneous */\n\n /// Interprets this packet as `Packet<Ethernet, Ipv4>`\n\n pub fn downcast(self) -> Result<Packet<B>, Self> {\n\n TryInto::try_into(self)\n\n }\n\n}\n\n\n\nimpl<B> Packet<B, Unknown, Unknown>\n\nwhere\n\n B: AsSlice<Element = u8>,\n\n{\n\n /// Parses bytes into an ARP packet\n\n pub fn parse(bytes: B) -> Result<Self, B> {\n\n if bytes.as_slice().len() < usize(HEADER_SIZE) {\n\n // too small; header doesn't fit\n\n return Err(bytes);\n\n }\n\n\n\n let p = Packet {\n\n buffer: bytes,\n", "file_path": "src/arp.rs", "rank": 71, "score": 39313.66480352597 }, { "content": " NE::read_u16(&self.header_()[OPER]).into()\n\n }\n\n\n\n /// View into the payload\n\n ///\n\n /// NOTE this may contain padding bytes at the end\n\n pub fn payload(&self) -> &[u8] {\n\n unsafe { self.as_slice().rf(PAYLOAD) }\n\n }\n\n\n\n /// Returns the canonical length of this packet\n\n ///\n\n /// This ignores padding bytes, if any\n\n pub fn len(&self) -> u8 {\n\n HEADER_SIZE + 2 * (self.get_hlen() + self.get_plen())\n\n }\n\n\n\n /* Miscellaneous */\n\n /// Frees the underlying buffer\n\n pub fn free(self) -> B {\n", "file_path": "src/arp.rs", "rank": 72, "score": 39313.65426926419 }, { "content": "where\n\n B: AsSlice<Element = u8> + AsMutSlice<Element = u8> + Truncate<u8>,\n\n{\n\n /* Constructors */\n\n /// Transforms the given buffer into an ARP packet\n\n ///\n\n /// This function populates the following header fields:\n\n ///\n\n /// - HTYPE = Ethernet\n\n /// - PTYPE = IPv4\n\n /// - HLEN = 6\n\n /// - PLEN = 4\n\n /// - OPER = Request\n\n pub fn new(buffer: B) -> Self {\n\n let len = HEADER_SIZE + 20;\n\n assert!(buffer.as_slice().len() >= usize(len));\n\n\n\n let mut packet: Packet<B, Unknown, Unknown> = Packet {\n\n buffer,\n\n _htype: PhantomData,\n", "file_path": "src/arp.rs", "rank": 73, "score": 39313.179646314544 }, { "content": " B: AsSlice<Element = u8>,\n\n{\n\n /* Getters */\n\n /// Returns the SHA (Sender Hardware Address) field of the payload\n\n pub fn get_sha(&self) -> mac::Addr {\n\n unsafe { mac::Addr(*(self.as_slice().as_ptr().add(SHA.start) as *const _)) }\n\n }\n\n\n\n /// Returns the SPA (Sender Protocol Address) field of the payload\n\n pub fn get_spa(&self) -> ipv4::Addr {\n\n unsafe { ipv4::Addr(*(self.as_slice().as_ptr().add(SPA.start) as *const _)) }\n\n }\n\n\n\n /// Returns the THA (Target Hardware Address) field of the payload\n\n pub fn get_tha(&self) -> mac::Addr {\n\n unsafe { mac::Addr(*(self.as_slice().as_ptr().add(THA.start) as *const _)) }\n\n }\n\n\n\n /// Returns the TPA (Target Protocol Address) field of the payload\n\n pub fn get_tpa(&self) -> ipv4::Addr {\n", "file_path": "src/arp.rs", "rank": 74, "score": 39312.45190560489 }, { "content": " fn construct() {\n\n // NOTE start with randomized array to make sure we set *everything* correctly\n\n let mut array: [u8; SIZE] = [0; SIZE];\n\n rand::thread_rng().fill_bytes(&mut array);\n\n\n\n let mut eth = ether::Frame::new(&mut array[..]);\n\n\n\n eth.set_destination(mac::Addr::BROADCAST);\n\n eth.set_source(SENDER_MAC);\n\n\n\n eth.arp(|arp| {\n\n arp.set_oper(arp::Operation::Reply);\n\n arp.set_sha(SENDER_MAC);\n\n arp.set_spa(SENDER_IP);\n\n arp.set_tha(TARGET_MAC);\n\n arp.set_tpa(TARGET_IP);\n\n });\n\n\n\n // ignore the padding\n\n assert_eq!(eth.as_bytes(), &BYTES[..SIZE - 4]);\n", "file_path": "src/arp.rs", "rank": 75, "score": 39310.62939852678 }, { "content": " B: Clone + AsSlice<Element = u8>,\n\n{\n\n fn clone(&self) -> Self {\n\n Packet {\n\n buffer: self.buffer.clone(),\n\n _htype: PhantomData,\n\n _ptype: PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<B, H, P> Copy for Packet<B, H, P> where B: Copy + AsSlice<Element = u8> {}\n\n\n\nimpl<B> fmt::Debug for Packet<B, Ethernet, Ipv4>\n\nwhere\n\n B: AsSlice<Element = u8>,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"arp::Packet\")\n\n .field(\"oper\", &self.get_oper())\n", "file_path": "src/arp.rs", "rank": 76, "score": 39310.6113630831 }, { "content": " /// Sets the OPER (OPERation) field of the header\n\n pub fn set_oper(&mut self, oper: Operation) {\n\n NE::write_u16(&mut self.as_mut_slice()[OPER], oper.into())\n\n }\n\n\n\n /// Mutable view into the payload\n\n ///\n\n /// NOTE this may contain padding bytes at the end\n\n pub fn payload_mut(&mut self) -> &mut [u8] {\n\n &mut self.as_mut_slice()[PAYLOAD]\n\n }\n\n\n\n /* Private */\n\n fn as_mut_slice(&mut self) -> &mut [u8] {\n\n self.buffer.as_mut_slice()\n\n }\n\n}\n\n\n\nimpl<B, H, P> Clone for Packet<B, H, P>\n\nwhere\n", "file_path": "src/arp.rs", "rank": 77, "score": 39309.596578832236 }, { "content": "{\n\n /* Setters */\n\n /// Sets the HTYPE (Hardware TYPE) field of the header\n\n pub fn set_htype(&mut self, htype: HardwareType) {\n\n NE::write_u16(&mut self.as_mut_slice()[HTYPE], htype.into());\n\n }\n\n\n\n /// Sets the PTYPE (Protocol TYPE) field of the header\n\n pub fn set_ptype(&mut self, ptype: ether::Type) {\n\n NE::write_u16(&mut self.as_mut_slice()[PTYPE], ptype.into());\n\n }\n\n}\n\n\n\nimpl<B> TryFrom<Packet<B, Unknown, Unknown>> for Packet<B, Ethernet, Ipv4>\n\nwhere\n\n B: AsSlice<Element = u8>,\n\n{\n\n type Error = Packet<B, Unknown, Unknown>;\n\n\n\n fn try_from(p: Packet<B, Unknown, Unknown>) -> Result<Self, Packet<B, Unknown, Unknown>> {\n", "file_path": "src/arp.rs", "rank": 78, "score": 39309.380534048985 }, { "content": "//! ARP: Address Resolution Protocol\n\n//!\n\n//! # References\n\n//!\n\n//! - [RFC 826: An Ethernet Address Resolution Protocol][rfc]\n\n//!\n\n//! [rfc]: https://tools.ietf.org/html/rfc826\n\n\n\nuse core::fmt;\n\nuse core::marker::PhantomData;\n\nuse core::ops::{Range, RangeFrom};\n\n\n\nuse as_slice::{AsMutSlice, AsSlice};\n\nuse byteorder::{ByteOrder, NetworkEndian as NE};\n\nuse cast::usize;\n\nuse owning_slice::Truncate;\n\n\n\nuse crate::{\n\n ether, ipv4, mac,\n\n traits::{TryFrom, TryInto, UncheckedIndex},\n", "file_path": "src/arp.rs", "rank": 79, "score": 39308.73924326613 }, { "content": "\n\n /// Sets the SPA (Sender Protocol Address) field of the payload\n\n pub fn set_spa(&mut self, spa: ipv4::Addr) {\n\n unsafe {\n\n self.as_mut_slice().rm(SPA).copy_from_slice(&spa.0);\n\n }\n\n }\n\n\n\n /// Sets the THA (Target Hardware Address) field of the payload\n\n pub fn set_tha(&mut self, tha: mac::Addr) {\n\n unsafe {\n\n self.as_mut_slice().rm(THA).copy_from_slice(&tha.0);\n\n }\n\n }\n\n\n\n /// Sets the TPA (Target Protocol Address) field of the payload\n\n pub fn set_tpa(&mut self, tpa: ipv4::Addr) {\n\n unsafe {\n\n self.as_mut_slice().rm(TPA).copy_from_slice(&tpa.0);\n\n }\n", "file_path": "src/arp.rs", "rank": 80, "score": 39307.09513944047 }, { "content": " self.buffer\n\n }\n\n\n\n /* Private */\n\n fn header_(&self) -> &[u8; 8] {\n\n debug_assert!(self.as_slice().len() >= 8);\n\n\n\n unsafe { &*(self.as_slice().as_ptr() as *const _) }\n\n }\n\n\n\n fn as_slice(&self) -> &[u8] {\n\n self.buffer.as_slice()\n\n }\n\n}\n\n\n\nimpl<B, H, P> Packet<B, H, P>\n\nwhere\n\n B: AsSlice<Element = u8> + AsMutSlice<Element = u8>,\n\n{\n\n /* Setters */\n", "file_path": "src/arp.rs", "rank": 81, "score": 39306.27973707154 }, { "content": " Unknown,\n\n};\n\n\n\n/* Packet structure */\n\nconst HTYPE: Range<usize> = 0..2;\n\nconst PTYPE: Range<usize> = 2..4;\n\nconst HLEN: usize = 4;\n\nconst PLEN: usize = 5;\n\nconst OPER: Range<usize> = 6..8;\n\nconst PAYLOAD: RangeFrom<usize> = 8..;\n\n\n\n/// Size of the ARP header\n\npub const HEADER_SIZE: u8 = PAYLOAD.start as u8;\n\n\n\n// NOTE Use only for Packet<_, Ethernet, Ipv4>\n\nconst SHA: Range<usize> = 8..14;\n\nconst SPA: Range<usize> = 14..18;\n\nconst THA: Range<usize> = 18..24;\n\nconst TPA: Range<usize> = 24..28;\n\n\n", "file_path": "src/arp.rs", "rank": 82, "score": 39303.68978920679 }, { "content": "/// [Type state] The Ethernet hardware type\n\npub enum Ethernet {}\n\n\n\n/// [Type state] The IPv4 protocol type\n\npub enum Ipv4 {}\n\n\n\n/// ARP packet\n\npub struct Packet<BUFFER, HTYPE = Ethernet, PTYPE = Ipv4>\n\nwhere\n\n BUFFER: AsSlice<Element = u8>,\n\n HTYPE: 'static,\n\n PTYPE: 'static,\n\n{\n\n buffer: BUFFER,\n\n _htype: PhantomData<HTYPE>,\n\n _ptype: PhantomData<PTYPE>,\n\n}\n\n\n\n/* Ethernet - Ipv4 */\n\nimpl<B> Packet<B, Ethernet, Ipv4>\n", "file_path": "src/arp.rs", "rank": 83, "score": 39303.47112060545 }, { "content": " _htype: PhantomData,\n\n _ptype: PhantomData,\n\n };\n\n\n\n let hlen = p.get_hlen();\n\n let plen = p.get_plen();\n\n\n\n let payload_len = 2 * (usize(hlen) + usize(plen));\n\n if p.as_slice().len() < usize(HEADER_SIZE) + payload_len {\n\n // too small; payload doesn't fit\n\n Err(p.buffer)\n\n } else {\n\n Ok(p)\n\n }\n\n }\n\n}\n\n\n\nimpl<B> Packet<B, Unknown, Unknown>\n\nwhere\n\n B: AsSlice<Element = u8> + AsMutSlice<Element = u8>,\n", "file_path": "src/arp.rs", "rank": 84, "score": 39303.38573087764 }, { "content": " B: AsSlice<Element = u8>,\n\n{\n\n /* Getters */\n\n // htype: covered by the generic impl\n\n // ptype: covered by the generic impl\n\n // hlen: covered by the generic impl\n\n // plen: covered by the generic impl\n\n // oper: covered by the generic impl\n\n\n\n /// Returns the SHA (Sender Hardware Address) field of the payload\n\n pub fn get_sha(&self) -> &[u8] {\n\n let end = usize(self.get_hlen());\n\n\n\n unsafe { self.payload().rt(..end) }\n\n }\n\n\n\n /// Returns the SPA (Sender Protocol Address) field of the payload\n\n pub fn get_spa(&self) -> &[u8] {\n\n let start = usize(self.get_hlen());\n\n let end = start + usize(self.get_plen());\n", "file_path": "src/arp.rs", "rank": 85, "score": 39303.15055364332 }, { "content": " 8, 6, // eth: type\n\n 0, 1, // arp: HTYPE\n\n 8, 0, // arp: PTYPE\n\n 6, // arp: HLEN\n\n 4, // arp: PLEN\n\n 0, 2, // arp: OPER\n\n 120, 68, 118, 217, 106, 124, // arp: SHA\n\n 192, 168, 1, 1, // arp: SPA\n\n 32, 24, 3, 1, 0, 0, // arp: THA\n\n 192, 168, 1, 33, // arp: TPA\n\n 0, 0, 0, 0, // eth: padding\n\n ];\n\n\n\n const SENDER_MAC: mac::Addr = mac::Addr([0x78, 0x44, 0x76, 0xd9, 0x6a, 0x7c]);\n\n const SENDER_IP: ipv4::Addr = ipv4::Addr([192, 168, 1, 1]);\n\n\n\n const TARGET_MAC: mac::Addr = mac::Addr([0x20, 0x18, 0x03, 0x01, 0x00, 0x00]);\n\n const TARGET_IP: ipv4::Addr = ipv4::Addr([192, 168, 1, 33]);\n\n\n\n #[test]\n", "file_path": "src/arp.rs", "rank": 86, "score": 39303.13268306053 }, { "content": " _ptype: PhantomData,\n\n };\n\n\n\n packet.buffer.truncate(len);\n\n packet.set_htype(HardwareType::Ethernet);\n\n packet.set_ptype(ether::Type::Ipv4);\n\n packet.buffer.as_mut_slice()[HLEN] = 6;\n\n packet.buffer.as_mut_slice()[PLEN] = 4;\n\n packet.set_oper(Operation::Request);\n\n\n\n Packet {\n\n buffer: packet.buffer,\n\n _htype: PhantomData,\n\n _ptype: PhantomData,\n\n }\n\n }\n\n}\n\n\n\nimpl<B> Packet<B, Ethernet, Ipv4>\n\nwhere\n", "file_path": "src/arp.rs", "rank": 87, "score": 39301.81787367961 }, { "content": " }\n\n\n\n /* Miscellaneous */\n\n /// ARP announcement\n\n ///\n\n /// Shortcut for setting these fields\n\n ///\n\n /// - OPER = Request\n\n /// - SPA = TPA = addr\n\n /// - THA = 00:00:00:00:00:00\n\n pub fn announce(&mut self, addr: ipv4::Addr) {\n\n self.set_oper(Operation::Request);\n\n\n\n self.set_spa(addr);\n\n\n\n self.set_tha(mac::Addr([0; 6]));\n\n self.set_tpa(addr);\n\n }\n\n\n\n /// ARP probe\n", "file_path": "src/arp.rs", "rank": 88, "score": 39301.634190263234 }, { "content": " }\n\n\n\n #[test]\n\n fn parse() {\n\n let eth = ether::Frame::parse(&BYTES[..]).unwrap();\n\n let packet = arp::Packet::parse(eth.payload()).unwrap();\n\n\n\n assert_eq!(packet.get_htype(), arp::HardwareType::Ethernet);\n\n assert_eq!(packet.get_ptype(), ether::Type::Ipv4);\n\n assert_eq!(packet.get_hlen(), 6);\n\n assert_eq!(packet.get_plen(), 4);\n\n assert_eq!(packet.get_oper(), arp::Operation::Reply);\n\n assert_eq!(packet.get_sha(), &SENDER_MAC.0);\n\n assert_eq!(packet.get_spa(), &SENDER_IP.0);\n\n assert_eq!(packet.get_tha(), &TARGET_MAC.0);\n\n assert_eq!(packet.get_tpa(), &TARGET_IP.0);\n\n }\n\n}\n", "file_path": "src/arp.rs", "rank": 89, "score": 39301.21582028975 }, { "content": "{\n\n /* Getters */\n\n /// Returns the HTYPE (Hardware TYPE) field of the header\n\n pub fn get_htype(&self) -> HardwareType {\n\n if typeid!(H == Ethernet) {\n\n HardwareType::Ethernet\n\n } else {\n\n NE::read_u16(&self.header_()[HTYPE]).into()\n\n }\n\n }\n\n\n\n /// Returns the PTYPE (Protocol TYPE) field of the header\n\n pub fn get_ptype(&self) -> ether::Type {\n\n if typeid!(P == Ipv4) {\n\n ether::Type::Ipv4\n\n } else {\n\n NE::read_u16(&self.header_()[PTYPE]).into()\n\n }\n\n }\n\n\n", "file_path": "src/arp.rs", "rank": 90, "score": 39300.06827416592 }, { "content": " .field(\"sha\", &self.get_sha())\n\n .field(\"spa\", &self.get_spa())\n\n .field(\"tha\", &self.get_tha())\n\n .field(\"tpa\", &self.get_tpa())\n\n .finish()\n\n }\n\n}\n\n\n\nimpl<B> fmt::Debug for Packet<B, Unknown, Unknown>\n\nwhere\n\n B: AsSlice<Element = u8>,\n\n{\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"arp::Packet\")\n\n .field(\"htype\", &self.get_htype())\n\n .field(\"ptype\", &self.get_ptype())\n\n .field(\"hlen\", &self.get_hlen())\n\n .field(\"plen\", &self.get_plen())\n\n .field(\"oper\", &self.get_oper())\n\n .field(\"sha\", &self.get_sha())\n", "file_path": "src/arp.rs", "rank": 91, "score": 39299.313559808994 }, { "content": " ///\n\n /// Shortcut for setting these fields\n\n ///\n\n /// - OPER = Request\n\n /// - SPA = 0.0.0.0\n\n /// - THA = 00:00:00:00:00:00\n\n /// - TPA = addr\n\n pub fn probe(&mut self, addr: ipv4::Addr) {\n\n self.set_oper(Operation::Request);\n\n\n\n self.set_spa(ipv4::Addr::UNSPECIFIED);\n\n\n\n self.set_tha(mac::Addr([0; 6]));\n\n self.set_tpa(addr);\n\n }\n\n}\n\n\n\n/* Unknown - Unknown */\n\nimpl<B> Packet<B, Unknown, Unknown>\n\nwhere\n", "file_path": "src/arp.rs", "rank": 92, "score": 39298.49476335874 }, { "content": "\n\n unsafe { self.payload().r(start..end) }\n\n }\n\n\n\n /// Returns the THA (Target Hardware Address) field of the payload\n\n pub fn get_tha(&self) -> &[u8] {\n\n let start = usize(self.get_hlen()) + usize(self.get_plen());\n\n let end = start + usize(self.get_hlen());\n\n\n\n unsafe { self.payload().r(start..end) }\n\n }\n\n\n\n /// Returns the TPA (Target Protocol Address) field of the payload\n\n pub fn get_tpa(&self) -> &[u8] {\n\n let start = 2 * usize(self.get_hlen()) + usize(self.get_plen());\n\n let end = start + usize(self.get_plen());\n\n\n\n unsafe { self.payload().r(start..end) }\n\n }\n\n\n", "file_path": "src/arp.rs", "rank": 93, "score": 39297.59225710777 }, { "content": " if p.get_htype() == HardwareType::Ethernet\n\n && p.get_ptype() == ether::Type::Ipv4\n\n && p.get_hlen() == 6\n\n && p.get_plen() == 4\n\n {\n\n Ok(Packet {\n\n buffer: p.buffer,\n\n _htype: PhantomData,\n\n _ptype: PhantomData,\n\n })\n\n } else {\n\n Err(p)\n\n }\n\n }\n\n}\n\n\n\n/* HTYPE - PTYPE */\n\nimpl<B, H, P> Packet<B, H, P>\n\nwhere\n\n B: AsSlice<Element = u8>,\n", "file_path": "src/arp.rs", "rank": 94, "score": 39294.881477904186 }, { "content": " .field(\"spa\", &self.get_spa())\n\n .field(\"tha\", &self.get_tha())\n\n .field(\"tpa\", &self.get_tpa())\n\n .finish()\n\n }\n\n}\n\n\n\nfull_range!(\n\n u16,\n\n /// Hardware type\n\n #[derive(Clone, Copy, Debug, PartialEq)]\n\n pub enum HardwareType {\n\n /// Ethernet\n\n Ethernet = 1,\n\n }\n\n);\n\n\n\nfull_range!(\n\n u16,\n\n /// ARP operation\n", "file_path": "src/arp.rs", "rank": 95, "score": 39293.226178242796 }, { "content": " /// Returns the HLEN (Hardware LENgth) field of the header\n\n pub fn get_hlen(&self) -> u8 {\n\n if typeid!(H == Ethernet) {\n\n 6\n\n } else {\n\n self.header_()[HLEN]\n\n }\n\n }\n\n\n\n /// Returns the PLEN (Protocol LENgth) field of the header\n\n pub fn get_plen(&self) -> u8 {\n\n if typeid!(P == Ipv4) {\n\n 4\n\n } else {\n\n self.header_()[PLEN]\n\n }\n\n }\n\n\n\n /// Returns the OPER (OPERation) field of the header\n\n pub fn get_oper(&self) -> Operation {\n", "file_path": "src/arp.rs", "rank": 96, "score": 39287.23049989986 }, { "content": " if target_ll_addr.is_some() { 1 } else { 0 },\n\n );\n\n\n\n f(&mut message);\n\n\n\n if let Some(target_ll_addr) = target_ll_addr {\n\n unsafe {\n\n message.set_target_mac_addr(target_ll_addr);\n\n }\n\n }\n\n\n\n message.update_checksum(src, dest);\n\n\n\n let len = message.as_bytes().len() as u16;\n\n self.truncate(len);\n\n }\n\n\n\n /// Fills the payload with a UDP packet\n\n pub fn udp(&mut self, f: impl FnOnce(&mut udp::Packet<&mut [u8]>)) {\n\n let src = self.get_source();\n", "file_path": "src/ipv6.rs", "rank": 97, "score": 39062.633361717235 }, { "content": " }\n\n}\n\n\n\nimpl<B> Packet<B>\n\nwhere\n\n B: AsMutSlice<Element = u8> + Truncate<u16>,\n\n{\n\n /// Fills the payload with a Neighbor Advertisement ICMPv6 message\n\n pub fn neighbor_advertisement(\n\n &mut self,\n\n target_ll_addr: Option<mac::Addr>,\n\n f: impl FnOnce(&mut icmpv6::Message<&mut [u8], icmpv6::NeighborAdvertisement>),\n\n ) {\n\n let src = self.get_source();\n\n let dest = self.get_destination();\n\n\n\n self.set_next_header(NextHeader::Ipv6Icmp);\n\n\n\n let mut message = icmpv6::Message::neighbor_advertisement(\n\n self.payload_mut(),\n", "file_path": "src/ipv6.rs", "rank": 98, "score": 39061.31183061127 }, { "content": " let dest = self.get_destination();\n\n\n\n self.set_next_header(NextHeader::Udp);\n\n\n\n let mut packet = udp::Packet::new(self.payload_mut());\n\n\n\n f(&mut packet);\n\n\n\n packet.update_ipv6_checksum(src, dest);\n\n\n\n let len = packet.as_bytes().len() as u16;\n\n self.truncate(len);\n\n }\n\n\n\n /// Truncates the *payload* to the specified length\n\n pub fn truncate(&mut self, len: u16) {\n\n if self.get_length() > len {\n\n unsafe { self.set_length(len) }\n\n self.buffer.truncate(len + u16(HEADER_SIZE));\n\n }\n", "file_path": "src/ipv6.rs", "rank": 99, "score": 39059.67907825911 } ]
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(parser_settings: &mut parser::ParserSettings,\n\n context: &mut builder::Context,\n\n module_provider: &mut builder::ModuleProvider) -> Result<(LLVMValueRef, bool), FilerError> {\n\n let path = match env::var(\"KALEIDOSCOPE_PATH\") {\n\n Ok(path) => path,\n\n Err(_) => \"stdlib\".to_string()\n\n };\n\n let path = Path::new(&path).join(\"stdlib.ks\");\n\n\n\n Ok(try!(load_ks(path, parser_settings, context, module_provider)))\n\n}\n\n\n", "file_path": "src/filer.rs", "rank": 1, "score": 345144.5270034064 }, { "content": "pub fn load_ks<P: AsRef<Path>>(path: P,\n\n parser_settings: &mut parser::ParserSettings,\n\n context: &mut builder::Context,\n\n module_provider: &mut builder::ModuleProvider) -> Result<(LLVMValueRef, bool), FilerError> {\n\n let mut f = try!(File::open(path));\n\n let mut buf = String::new();\n\n try!(f.read_to_string(&mut buf));\n\n\n\n let tokens = lexer::tokenize(&buf);\n\n\n\n let (ast, rest) = try!(parser::parse(tokens.as_slice(), vec![].as_slice(), parser_settings));\n\n if !rest.is_empty() {\n\n return Err(FilerError::Build(format!(\"Not complete expression: {:?}\", rest)));\n\n }\n\n\n\n Ok(try!(ast.codegen(context, module_provider)))\n\n}\n\n\n", "file_path": "src/filer.rs", "rank": 2, "score": 294425.1153381388 }, { "content": "//< lexer-tokenize\n\npub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "src/lexer.rs", "rank": 3, "score": 290792.91828921734 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/4/src/lexer.rs", "rank": 4, "score": 285950.9927485349 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/3/src/lexer.rs", "rank": 5, "score": 285950.9927485349 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/1/src/lexer.rs", "rank": 6, "score": 285950.9927485349 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/6/src/lexer.rs", "rank": 7, "score": 285950.9927485349 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/5/src/lexer.rs", "rank": 8, "score": 285950.9927485349 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/0/src/lexer.rs", "rank": 9, "score": 285950.9927485349 }, { "content": "pub fn tokenize(input: &str) -> Vec<Token> {\n\n // regex for commentaries (start with #, end with the line end)\n\n let comment_re = regex!(r\"(?m)#.*\\n\");\n\n // remove commentaries from the input stream\n\n let preprocessed = comment_re.replace_all(input, \"\\n\");\n\n\n\n let mut result = Vec::new();\n\n\n\n // regex for token, just union of straightforward regexes for different token types\n\n // operators are parsed the same way as identifier and separated later\n\n let token_re = regex!(concat!(\n\n r\"(?P<ident>\\p{Alphabetic}\\w*)|\",\n\n r\"(?P<number>\\d+\\.?\\d*)|\",\n\n r\"(?P<delimiter>;)|\",\n\n r\"(?P<oppar>\\()|\",\n\n r\"(?P<clpar>\\))|\",\n\n r\"(?P<comma>,)|\",\n\n r\"(?P<operator>\\S)\"));\n\n\n\n for cap in token_re.captures_iter(preprocessed.as_str()) {\n", "file_path": "chapters/2/src/lexer.rs", "rank": 10, "score": 285950.9927485349 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n\n\n 'main: loop {\n\n print!(\"> \");\n\n stdout.flush().unwrap();\n\n input.clear();\n\n stdin.read_line(&mut input).ok().expect(\"Failed to read line\");\n\n if input.as_str() == \".quit\\n\" {\n\n break;\n\n }\n\n\n\n loop {\n\n let tokens = tokenize(input.as_str());\n\n if stage == Tokens {\n\n println!(\"{:?}\", tokens);\n\n continue 'main\n\n }\n\n }\n\n }\n\n}\n", "file_path": "chapters/0/src/driver.rs", "rank": 12, "score": 278652.45588643337 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n let mut parser_settings = default_parser_settings();\n\n let mut ir_container : Box<JITter> = if stage == Exec {\n\n target::initilalize_native_target();\n\n target::initilalize_native_asm_printer();\n\n jitter::init();\n\n Box::new(\n\n jitter::MCJITter::new(\"main\")\n\n )\n\n } else {\n\n Box::new(\n\n builder::SimpleModuleProvider::new(\"main\")\n\n )\n\n };\n\n\n\n let mut builder_context = builder::Context::new();\n\n\n", "file_path": "chapters/4/src/driver.rs", "rank": 13, "score": 278652.45588643337 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n let mut parser_settings = default_parser_settings();\n\n let mut ir_container : Box<JITter> = if stage == Exec {\n\n target::initilalize_native_target();\n\n target::initilalize_native_asm_printer();\n\n jitter::init();\n\n Box::new(\n\n jitter::MCJITter::new(\"main\")\n\n )\n\n } else {\n\n Box::new(\n\n builder::SimpleModuleProvider::new(\"main\")\n\n )\n\n };\n\n\n\n let mut builder_context = builder::Context::new();\n\n\n", "file_path": "chapters/6/src/driver.rs", "rank": 14, "score": 278652.45588643337 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n let mut parser_settings = default_parser_settings();\n\n let mut ir_container : Box<JITter> = if stage == Exec {\n\n target::initilalize_native_target();\n\n target::initilalize_native_asm_printer();\n\n jitter::init();\n\n Box::new(\n\n jitter::MCJITter::new(\"main\")\n\n )\n\n } else {\n\n Box::new(\n\n builder::SimpleModuleProvider::new(\"main\")\n\n )\n\n };\n\n\n\n let mut builder_context = builder::Context::new();\n\n\n", "file_path": "chapters/3/src/driver.rs", "rank": 15, "score": 278652.45588643337 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n let mut parser_settings = default_parser_settings();\n\n let mut ir_container : Box<JITter> = if stage == Exec {\n\n target::initilalize_native_target();\n\n target::initilalize_native_asm_printer();\n\n jitter::init();\n\n Box::new(\n\n jitter::MCJITter::new(\"main\")\n\n )\n\n } else {\n\n Box::new(\n\n builder::SimpleModuleProvider::new(\"main\")\n\n )\n\n };\n\n\n\n let mut builder_context = builder::Context::new();\n\n\n", "file_path": "chapters/5/src/driver.rs", "rank": 16, "score": 278652.45588643337 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n let mut parser_settings = default_parser_settings();\n\n let mut ir_container = builder::SimpleModuleProvider::new(\"main\");\n\n let mut builder_context = builder::Context::new();\n\n\n\n\n\n 'main: loop {\n\n print!(\"> \");\n\n stdout.flush().unwrap();\n\n input.clear();\n\n stdin.read_line(&mut input).ok().expect(\"Failed to read line\");\n\n if input.as_str() == \".quit\\n\" {\n\n break;\n\n }\n\n\n\n // the constructed AST\n\n let mut ast = Vec::new();\n", "file_path": "chapters/2/src/driver.rs", "rank": 17, "score": 278652.45588643337 }, { "content": "pub fn main_loop(stage: Stage) {\n\n let stdin = io::stdin();\n\n let mut stdout = io::stdout();\n\n let mut input = String::new();\n\n let mut parser_settings = default_parser_settings();\n\n\n\n 'main: loop {\n\n print!(\"> \");\n\n stdout.flush().unwrap();\n\n input.clear();\n\n stdin.read_line(&mut input).ok().expect(\"Failed to read line\");\n\n if input.as_str() == \".quit\\n\" {\n\n break;\n\n }\n\n\n\n // the constructed AST\n\n let mut ast = Vec::new();\n\n // tokens left from the previous lines\n\n let mut prev = Vec::new();\n\n loop {\n", "file_path": "chapters/1/src/driver.rs", "rank": 18, "score": 278652.45588643337 }, { "content": "//< parser-parse parser-parse-sign\n\npub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n//> parser-parse-sign\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n", "file_path": "src/parser.rs", "rank": 19, "score": 278585.97814706364 }, { "content": "pub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n\n Def => parse_function(&mut rest, settings),\n", "file_path": "chapters/1/src/parser.rs", "rank": 20, "score": 274732.62094214564 }, { "content": "pub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n\n Def => parse_function(&mut rest, settings),\n", "file_path": "chapters/5/src/parser.rs", "rank": 21, "score": 274732.62094214564 }, { "content": "pub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n\n Def => parse_function(&mut rest, settings),\n", "file_path": "chapters/3/src/parser.rs", "rank": 22, "score": 274732.6209421456 }, { "content": "pub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n\n Def => parse_function(&mut rest, settings),\n", "file_path": "chapters/4/src/parser.rs", "rank": 23, "score": 274732.6209421456 }, { "content": "pub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n\n Def => parse_function(&mut rest, settings),\n", "file_path": "chapters/2/src/parser.rs", "rank": 24, "score": 274732.62094214564 }, { "content": "pub fn parse(tokens : &[Token], parsed_tree : &[ASTNode], settings : &mut ParserSettings) -> ParsingResult\n\n{\n\n let mut rest = tokens.to_vec();\n\n // we read tokens from the end of the vector\n\n // using it as a stack\n\n rest.reverse();\n\n\n\n // we will add new AST nodes to already parsed ones\n\n let mut ast = parsed_tree.to_vec();\n\n\n\n loop {\n\n // look at the current token and determine what to parse\n\n // based on its value\n\n let cur_token =\n\n match rest.last() {\n\n Some(token) => token.clone(),\n\n None => break\n\n };\n\n let result = match cur_token {\n\n Def => parse_function(&mut rest, settings),\n", "file_path": "chapters/6/src/parser.rs", "rank": 25, "score": 274732.62094214564 }, { "content": "fn parse_loop_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![For];\n\n let var_name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"expected identifier after for\");\n\n\n\n expect_token!(\n\n [Operator(op), Operator(op.clone()), {\n\n if op.as_str() != \"=\" {\n\n return error(\"expected '=' after for\")\n\n }\n\n }] <= tokens,\n\n parsed_tokens, \"expected '=' after for\");\n\n\n\n let start_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Comma, Comma, ()] <= tokens,\n\n parsed_tokens, \"expected ',' after for start value\");\n", "file_path": "src/parser.rs", "rank": 26, "score": 268225.6937439211 }, { "content": "//< parser-parse-expression\n\nfn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]\n\n//> ch-1 ch-4 parser-parse-expression\n\n , ftype: Normal\n\n//< ch-1 ch-4 parser-parse-expression\n\n/*j*/ };\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n//> parser-parse-expression\n\n//< if-parser for-parser mutable-var-parser\n\n\n", "file_path": "src/parser.rs", "rank": 27, "score": 268126.0325637181 }, { "content": "fn parse_loop_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![For];\n\n let var_name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"expected identifier after for\");\n\n\n\n expect_token!(\n\n [Operator(op), Operator(op.clone()), {\n\n if op.as_str() != \"=\" {\n\n return error(\"expected '=' after for\")\n\n }\n\n }] <= tokens,\n\n parsed_tokens, \"expected '=' after for\");\n\n\n\n let start_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Comma, Comma, ()] <= tokens,\n\n parsed_tokens, \"expected ',' after for start value\");\n", "file_path": "chapters/4/src/parser.rs", "rank": 28, "score": 264540.18629023375 }, { "content": "fn parse_loop_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![For];\n\n let var_name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"expected identifier after for\");\n\n\n\n expect_token!(\n\n [Operator(op), Operator(op.clone()), {\n\n if op.as_str() != \"=\" {\n\n return error(\"expected '=' after for\")\n\n }\n\n }] <= tokens,\n\n parsed_tokens, \"expected '=' after for\");\n\n\n\n let start_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Comma, Comma, ()] <= tokens,\n\n parsed_tokens, \"expected ',' after for start value\");\n", "file_path": "chapters/6/src/parser.rs", "rank": 29, "score": 264540.18629023375 }, { "content": "fn parse_loop_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![For];\n\n let var_name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"expected identifier after for\");\n\n\n\n expect_token!(\n\n [Operator(op), Operator(op.clone()), {\n\n if op.as_str() != \"=\" {\n\n return error(\"expected '=' after for\")\n\n }\n\n }] <= tokens,\n\n parsed_tokens, \"expected '=' after for\");\n\n\n\n let start_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Comma, Comma, ()] <= tokens,\n\n parsed_tokens, \"expected ',' after for start value\");\n", "file_path": "chapters/5/src/parser.rs", "rank": 30, "score": 264540.18629023375 }, { "content": "fn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]};\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 31, "score": 264434.3524376431 }, { "content": "fn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]};\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 32, "score": 264434.3524376431 }, { "content": "fn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]\n\n , ftype: Normal};\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 33, "score": 264434.3524376431 }, { "content": "fn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]};\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 34, "score": 264434.3524376431 }, { "content": "fn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]};\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 35, "score": 264434.3524376431 }, { "content": "fn parse_expression(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n let mut parsed_tokens = Vec::new();\n\n let expression = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n let prototype = Prototype{name: \"\".to_string(), args: vec![]\n\n , ftype: Normal};\n\n let lambda = Function{prototype: prototype, body: expression};\n\n Good(FunctionNode(lambda), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 36, "score": 264434.3524376431 }, { "content": "//< parser-parse-expr\n\nfn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n//> parser-parse-expr\n\n\n", "file_path": "src/parser.rs", "rank": 37, "score": 243996.24327738537 }, { "content": "//< parser-parse-extern\n\nfn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n//> parser-parse-extern\n\n\n", "file_path": "src/parser.rs", "rank": 38, "score": 241060.86152555718 }, { "content": "//< parser-parse-function ops-parse-func\n\nfn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n//> ch-1 ch-4 parser-parse-function\n\n\n\n match prototype.ftype {\n\n BinaryOp(ref symbol, precedence) => {\n\n settings.operator_precedence.insert(symbol.clone(), precedence);\n\n },\n\n _ => ()\n\n };\n\n\n\n//< ch-1 ch-4 parser-parse-function\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n//> parser-parse-function ops-parse-func\n\n\n", "file_path": "src/parser.rs", "rank": 39, "score": 241060.76442411292 }, { "content": "//< parser-parse-parenthesis-expr\n\nfn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n//> parser-parse-parenthesis-expr\n\n\n", "file_path": "src/parser.rs", "rank": 40, "score": 240821.29699639423 }, { "content": "//< parser-parse-ident-expr\n\nfn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n//> parser-parse-ident-expr\n\n\n", "file_path": "src/parser.rs", "rank": 41, "score": 240821.29699639423 }, { "content": "//< parser-parse-literal-expr\n\nfn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n//> parser-parse-literal-expr\n\n\n", "file_path": "src/parser.rs", "rank": 42, "score": 240821.2969963942 }, { "content": "//< parser-parse-primary-expr unary-parse-expr\n\nfn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n//> ch-1 parser-parse-primary-expr\n\n Some(&If) => parse_conditional_expr(tokens, settings),\n\n//> if-parser\n\n Some(&For) => parse_loop_expr(tokens, settings),\n\n//> ch-4 ch-5 for-parser unary-parse-expr\n\n Some(&Var) => parse_var_expr(tokens, settings),\n\n//< ch-5 unary-parse-expr\n\n Some(&Operator(_)) => parse_unary_expr(tokens, settings),\n\n//< ch-1 ch-4 parser-parse-primary-expr if-parser for-parser\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n//> parser-parse-primary-expr if-parser for-parser unary-parse-expr mutable-var-parser\n\n\n", "file_path": "src/parser.rs", "rank": 43, "score": 240821.2013689272 }, { "content": "fn parse_var_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Var];\n\n let mut vars = Vec::new();\n\n\n\n loop {\n\n let var_name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"expected identifier list after var\");\n\n\n\n let init_expr = expect_token!(\n\n [Operator(op), Operator(op.clone()), {\n\n if op.as_str() != \"=\" {\n\n return error(\"expected '=' in variable initialization\")\n\n }\n\n parse_try!(parse_expr, tokens, settings, parsed_tokens)\n\n }]\n\n else {LiteralExpr(0.0)}\n\n <= tokens, parsed_tokens);\n\n\n", "file_path": "src/parser.rs", "rank": 44, "score": 240817.06485541802 }, { "content": "fn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 45, "score": 240817.06485541802 }, { "content": "fn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 46, "score": 240817.064855418 }, { "content": "fn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 47, "score": 240817.064855418 }, { "content": "fn parse_conditional_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![If];\n\n let cond_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Then, Then, ()] <= tokens,\n\n parsed_tokens, \"expected then\");\n\n let then_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Else, Else, ()] <= tokens,\n\n parsed_tokens, \"expected else\");\n\n let else_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(ConditionalExpr{cond_expr: box cond_expr, then_expr: box then_expr, else_expr: box else_expr}, parsed_tokens)\n\n}\n\n//> if-parser\n\n//< for-parser\n\n\n", "file_path": "src/parser.rs", "rank": 48, "score": 240817.06485541802 }, { "content": "fn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 49, "score": 240817.064855418 }, { "content": "fn parse_unary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Operator(name), Operator(name.clone()), name] <= tokens,\n\n parsed_tokens, \"unary operator expected\");\n\n\n\n let operand = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(UnaryExpr(name, box operand), parsed_tokens)\n\n}\n\n//> ch-5 ch-6 unary-parse-expr\n", "file_path": "src/parser.rs", "rank": 50, "score": 240817.06485541805 }, { "content": "fn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 51, "score": 240817.06485541802 }, { "content": "fn parse_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n let lhs = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n let expr = parse_try!(parse_binary_expr, tokens, settings, parsed_tokens, 0, &lhs);\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 52, "score": 240817.06485541802 }, { "content": "fn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 53, "score": 237996.98922174308 }, { "content": "fn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 54, "score": 237996.98922174308 }, { "content": "fn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 55, "score": 237996.98922174308 }, { "content": "fn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n\n\n match prototype.ftype {\n\n BinaryOp(ref symbol, precedence) => {\n\n settings.operator_precedence.insert(symbol.clone(), precedence);\n\n },\n\n _ => ()\n\n };\n\n\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 56, "score": 237996.98922174308 }, { "content": "fn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 57, "score": 237996.98922174308 }, { "content": "fn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 58, "score": 237996.98922174308 }, { "content": "fn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n\n\n match prototype.ftype {\n\n BinaryOp(ref symbol, precedence) => {\n\n settings.operator_precedence.insert(symbol.clone(), precedence);\n\n },\n\n _ => ()\n\n };\n\n\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 59, "score": 237996.98922174308 }, { "content": "fn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 60, "score": 237996.98922174308 }, { "content": "fn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 61, "score": 237996.98922174308 }, { "content": "fn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 62, "score": 237996.98922174308 }, { "content": "fn parse_extern(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Extern token\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Extern];\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n Good(ExternNode(prototype), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 63, "score": 237996.98922174308 }, { "content": "fn parse_function(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<ASTNode> {\n\n // eat Def token\n\n tokens.pop();\n\n let mut parsed_tokens = vec!(Def);\n\n let prototype = parse_try!(parse_prototype, tokens, settings, parsed_tokens);\n\n let body = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(FunctionNode(Function{prototype: prototype, body: body}), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 64, "score": 237996.98922174308 }, { "content": "fn parse_conditional_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![If];\n\n let cond_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Then, Then, ()] <= tokens,\n\n parsed_tokens, \"expected then\");\n\n let then_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Else, Else, ()] <= tokens,\n\n parsed_tokens, \"expected else\");\n\n let else_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(ConditionalExpr{cond_expr: box cond_expr, then_expr: box then_expr, else_expr: box else_expr}, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 65, "score": 237762.97569942902 }, { "content": "fn parse_conditional_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![If];\n\n let cond_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Then, Then, ()] <= tokens,\n\n parsed_tokens, \"expected then\");\n\n let then_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Else, Else, ()] <= tokens,\n\n parsed_tokens, \"expected else\");\n\n let else_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(ConditionalExpr{cond_expr: box cond_expr, then_expr: box then_expr, else_expr: box else_expr}, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 66, "score": 237762.97569942905 }, { "content": "fn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 67, "score": 237762.97569942905 }, { "content": "fn parse_var_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![Var];\n\n let mut vars = Vec::new();\n\n\n\n loop {\n\n let var_name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"expected identifier list after var\");\n\n\n\n let init_expr = expect_token!(\n\n [Operator(op), Operator(op.clone()), {\n\n if op.as_str() != \"=\" {\n\n return error(\"expected '=' in variable initialization\")\n\n }\n\n parse_try!(parse_expr, tokens, settings, parsed_tokens)\n\n }]\n\n else {LiteralExpr(0.0)}\n\n <= tokens, parsed_tokens);\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 68, "score": 237762.97569942905 }, { "content": "fn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 69, "score": 237762.97569942905 }, { "content": "fn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 70, "score": 237762.97569942902 }, { "content": "fn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 71, "score": 237762.975699429 }, { "content": "fn parse_unary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Operator(name), Operator(name.clone()), name] <= tokens,\n\n parsed_tokens, \"unary operator expected\");\n\n\n\n let operand = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(UnaryExpr(name, box operand), parsed_tokens)\n\n}\n", "file_path": "chapters/5/src/parser.rs", "rank": 72, "score": 237762.97569942902 }, { "content": "fn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n Some(&If) => parse_conditional_expr(tokens, settings),\n\n Some(&For) => parse_loop_expr(tokens, settings),\n\n Some(&Var) => parse_var_expr(tokens, settings),\n\n Some(&Operator(_)) => parse_unary_expr(tokens, settings),\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 73, "score": 237762.97569942905 }, { "content": "fn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n Some(&If) => parse_conditional_expr(tokens, settings),\n\n Some(&For) => parse_loop_expr(tokens, settings),\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 74, "score": 237762.975699429 }, { "content": "fn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 75, "score": 237762.97569942905 }, { "content": "fn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 76, "score": 237762.97569942905 }, { "content": "fn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 77, "score": 237762.975699429 }, { "content": "fn parse_unary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Operator(name), Operator(name.clone()), name] <= tokens,\n\n parsed_tokens, \"unary operator expected\");\n\n\n\n let operand = parse_try!(parse_primary_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(UnaryExpr(name, box operand), parsed_tokens)\n\n}\n", "file_path": "chapters/6/src/parser.rs", "rank": 78, "score": 237762.97569942905 }, { "content": "fn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 79, "score": 237762.97569942905 }, { "content": "fn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n Some(&If) => parse_conditional_expr(tokens, settings),\n\n Some(&For) => parse_loop_expr(tokens, settings),\n\n Some(&Operator(_)) => parse_unary_expr(tokens, settings),\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 80, "score": 237762.97569942902 }, { "content": "fn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/4/src/parser.rs", "rank": 81, "score": 237762.97569942902 }, { "content": "fn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 82, "score": 237762.97569942905 }, { "content": "fn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 83, "score": 237762.975699429 }, { "content": "fn parse_conditional_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n tokens.pop();\n\n let mut parsed_tokens = vec![If];\n\n let cond_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Then, Then, ()] <= tokens,\n\n parsed_tokens, \"expected then\");\n\n let then_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [Else, Else, ()] <= tokens,\n\n parsed_tokens, \"expected else\");\n\n let else_expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n Good(ConditionalExpr{cond_expr: box cond_expr, then_expr: box then_expr, else_expr: box else_expr}, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 84, "score": 237762.97569942905 }, { "content": "fn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 85, "score": 237762.97569942905 }, { "content": "fn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/2/src/parser.rs", "rank": 86, "score": 237762.97569942905 }, { "content": "fn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 87, "score": 237762.975699429 }, { "content": "fn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/5/src/parser.rs", "rank": 88, "score": 237762.97569942902 }, { "content": "fn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 89, "score": 237762.97569942905 }, { "content": "fn parse_literal_expr(tokens : &mut Vec<Token>, _settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let value = expect_token!(\n\n [Number(val), Number(val), val] <= tokens,\n\n parsed_tokens, \"literal expected\");\n\n\n\n Good(LiteralExpr(value), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 90, "score": 237762.97569942902 }, { "content": "fn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/1/src/parser.rs", "rank": 91, "score": 237762.97569942905 }, { "content": "fn parse_primary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n match tokens.last() {\n\n Some(&Ident(_)) => parse_ident_expr(tokens, settings),\n\n Some(&Number(_)) => parse_literal_expr(tokens, settings),\n\n Some(&OpeningParenthesis) => parse_parenthesis_expr(tokens, settings),\n\n None => return NotComplete,\n\n _ => error(\"unknow token when expecting an expression\")\n\n }\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 92, "score": 237762.97569942902 }, { "content": "fn parse_parenthesis_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n // eat the opening parenthesis\n\n tokens.pop();\n\n let mut parsed_tokens = vec![OpeningParenthesis];\n\n\n\n let expr = parse_try!(parse_expr, tokens, settings, parsed_tokens);\n\n\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, ()] <= tokens,\n\n parsed_tokens, \"')' expected\");\n\n\n\n Good(expr, parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/3/src/parser.rs", "rank": 93, "score": 237762.975699429 }, { "content": "fn parse_ident_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings) -> PartParsingResult<Expression> {\n\n let mut parsed_tokens = Vec::new();\n\n\n\n let name = expect_token!(\n\n [Ident(name), Ident(name.clone()), name] <= tokens,\n\n parsed_tokens, \"identificator expected\");\n\n\n\n expect_token!(\n\n [OpeningParenthesis, OpeningParenthesis, ()]\n\n else {return Good(VariableExpr(name), parsed_tokens)}\n\n <= tokens, parsed_tokens);\n\n\n\n let mut args = Vec::new();\n\n loop {\n\n expect_token!(\n\n [ClosingParenthesis, ClosingParenthesis, break;\n\n Comma, Comma, continue]\n\n else {\n\n args.push(parse_try!(parse_expr, tokens, settings, parsed_tokens));\n\n }\n\n <= tokens, parsed_tokens);\n\n }\n\n\n\n Good(CallExpr(name, args), parsed_tokens)\n\n}\n\n\n", "file_path": "chapters/6/src/parser.rs", "rank": 94, "score": 237762.97569942905 }, { "content": "//< parser-parse-binary-expr\n\nfn parse_binary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings, expr_precedence : i32, lhs : &Expression) -> PartParsingResult<Expression> {\n\n // start with LHS value\n\n let mut result = lhs.clone();\n\n let mut parsed_tokens = Vec::new();\n\n\n\n loop {\n\n // continue until the current token is not an operator\n\n // or it is an operator with precedence lesser than expr_precedence\n\n let (operator, precedence) = match tokens.last() {\n\n Some(&Operator(ref op)) => match settings.operator_precedence.get(op) {\n\n Some(pr) if *pr >= expr_precedence => (op.clone(), *pr),\n\n None => return error(\"unknown operator found\"),\n\n _ => break\n\n },\n\n _ => break\n\n };\n\n tokens.pop();\n\n parsed_tokens.push(Operator(operator.clone()));\n\n\n\n // parse primary RHS expression\n", "file_path": "src/parser.rs", "rank": 95, "score": 230299.32241794118 }, { "content": "fn parse_binary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings, expr_precedence : i32, lhs : &Expression) -> PartParsingResult<Expression> {\n\n // start with LHS value\n\n let mut result = lhs.clone();\n\n let mut parsed_tokens = Vec::new();\n\n\n\n loop {\n\n // continue until the current token is not an operator\n\n // or it is an operator with precedence lesser than expr_precedence\n\n let (operator, precedence) = match tokens.last() {\n\n Some(&Operator(ref op)) => match settings.operator_precedence.get(op) {\n\n Some(pr) if *pr >= expr_precedence => (op.clone(), *pr),\n\n None => return error(\"unknown operator found\"),\n\n _ => break\n\n },\n\n _ => break\n\n };\n\n tokens.pop();\n\n parsed_tokens.push(Operator(operator.clone()));\n\n\n\n // parse primary RHS expression\n", "file_path": "chapters/2/src/parser.rs", "rank": 96, "score": 227722.42504975168 }, { "content": "fn parse_binary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings, expr_precedence : i32, lhs : &Expression) -> PartParsingResult<Expression> {\n\n // start with LHS value\n\n let mut result = lhs.clone();\n\n let mut parsed_tokens = Vec::new();\n\n\n\n loop {\n\n // continue until the current token is not an operator\n\n // or it is an operator with precedence lesser than expr_precedence\n\n let (operator, precedence) = match tokens.last() {\n\n Some(&Operator(ref op)) => match settings.operator_precedence.get(op) {\n\n Some(pr) if *pr >= expr_precedence => (op.clone(), *pr),\n\n None => return error(\"unknown operator found\"),\n\n _ => break\n\n },\n\n _ => break\n\n };\n\n tokens.pop();\n\n parsed_tokens.push(Operator(operator.clone()));\n\n\n\n // parse primary RHS expression\n", "file_path": "chapters/6/src/parser.rs", "rank": 97, "score": 227722.4250497517 }, { "content": "fn parse_binary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings, expr_precedence : i32, lhs : &Expression) -> PartParsingResult<Expression> {\n\n // start with LHS value\n\n let mut result = lhs.clone();\n\n let mut parsed_tokens = Vec::new();\n\n\n\n loop {\n\n // continue until the current token is not an operator\n\n // or it is an operator with precedence lesser than expr_precedence\n\n let (operator, precedence) = match tokens.last() {\n\n Some(&Operator(ref op)) => match settings.operator_precedence.get(op) {\n\n Some(pr) if *pr >= expr_precedence => (op.clone(), *pr),\n\n None => return error(\"unknown operator found\"),\n\n _ => break\n\n },\n\n _ => break\n\n };\n\n tokens.pop();\n\n parsed_tokens.push(Operator(operator.clone()));\n\n\n\n // parse primary RHS expression\n", "file_path": "chapters/1/src/parser.rs", "rank": 98, "score": 227722.4250497517 }, { "content": "fn parse_binary_expr(tokens : &mut Vec<Token>, settings : &mut ParserSettings, expr_precedence : i32, lhs : &Expression) -> PartParsingResult<Expression> {\n\n // start with LHS value\n\n let mut result = lhs.clone();\n\n let mut parsed_tokens = Vec::new();\n\n\n\n loop {\n\n // continue until the current token is not an operator\n\n // or it is an operator with precedence lesser than expr_precedence\n\n let (operator, precedence) = match tokens.last() {\n\n Some(&Operator(ref op)) => match settings.operator_precedence.get(op) {\n\n Some(pr) if *pr >= expr_precedence => (op.clone(), *pr),\n\n None => return error(\"unknown operator found\"),\n\n _ => break\n\n },\n\n _ => break\n\n };\n\n tokens.pop();\n\n parsed_tokens.push(Operator(operator.clone()));\n\n\n\n // parse primary RHS expression\n", "file_path": "chapters/5/src/parser.rs", "rank": 99, "score": 227722.42504975168 } ]
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(&contents[..])?;\n\n Ok(v)\n\n}\n\n\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 0, "score": 357007.5994039497 }, { "content": "pub fn lookup_regex_for_format_str(date_format: &str) -> Result<Regex, failure::Error> {\n\n match FORMAT_REGEX_MAPPING.get(date_format) {\n\n Some(r) => Ok(r.clone()),\n\n None => date_format_str_to_regex(date_format),\n\n }\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 1, "score": 333798.09363363177 }, { "content": "// 46.72.213.133 - - [12/Dec/2015:18:39:27 +0100]\n\n// DD/MMM/YYYY:hh:mm:ss\n\npub fn parse_full_timestamp(input: &str, regex: &Regex) -> Result<(i64, bool), failure::Error> {\n\n match regex.find(input) {\n\n Some(mat) => {\n\n let parser = nom::sequence::tuple((\n\n two_digits,\n\n take1,\n\n parse_short_month,\n\n take1,\n\n four_digits,\n\n take1,\n\n two_digits,\n\n take1,\n\n two_digits,\n\n take1,\n\n two_digits,\n\n take1,\n\n timezone_parser,\n\n ));\n\n let mapped = map(parser, |r| (r.0, r.2, r.4, r.6, r.8, r.10, r.12));\n\n match mapped(mat.as_str()) {\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 3, "score": 305155.0055752543 }, { "content": "pub fn read_filter_options(f: &mut fs::File) -> Result<DltFilterConfig, 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: DltFilterConfig = serde_json::from_str(&contents[..])?;\n\n Ok(v)\n\n}\n", "file_path": "application/apps/indexer/dlt/src/filtering.rs", "rank": 4, "score": 297354.0143499545 }, { "content": "pub fn report_error_ln<'a, S: Into<Cow<'a, str>>>(text: S, line_nr: Option<usize>) {\n\n eprintln!(\"{}\", create_incident(Severity::ERROR, text, line_nr))\n\n}\n", "file_path": "application/apps/indexer/indexer_base/src/error_reporter.rs", "rank": 5, "score": 296341.30345330207 }, { "content": "pub fn read_concat_options(f: &mut fs::File) -> Result<Vec<ConcatItemOptions>, 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\n\n let v: Vec<ConcatItemOptions> = serde_json::from_str(&contents[..])?; //.expect(\"could not parse concat item file\");\n\n Ok(v)\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct ConcatenatorInput {\n\n path: String,\n\n tag: String,\n\n}\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct ConcatenatorResult {\n\n pub file_cnt: usize,\n\n pub line_cnt: usize,\n\n pub byte_cnt: usize,\n\n}\n", "file_path": "application/apps/indexer/merging/src/concatenator.rs", "rank": 6, "score": 291345.0166905758 }, { "content": "pub fn read_merge_options(f: &mut fs::File) -> Result<Vec<MergeItemOptions>, 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\n\n let v: Vec<MergeItemOptions> = serde_json::from_str(&contents[..])?; //.expect(\"could not parse merge item file\");\n\n Ok(v)\n\n}\n\n\n\npub struct MergerInput {\n\n path: PathBuf,\n\n offset: Option<i64>,\n\n year: Option<i32>,\n\n format: String,\n\n tag: String,\n\n}\n\npub struct TimedLineIter<'a> {\n\n reader: BufReader<fs::File>,\n\n tag: &'a str,\n\n regex: Regex,\n", "file_path": "application/apps/indexer/merging/src/merger.rs", "rank": 7, "score": 291345.0166905758 }, { "content": "pub fn report_warning_ln<'a, S: Into<Cow<'a, str>>>(text: S, line_nr: Option<usize>) {\n\n eprintln!(\"{}\", create_incident(Severity::WARNING, text, line_nr))\n\n}\n", "file_path": "application/apps/indexer/indexer_base/src/error_reporter.rs", "rank": 8, "score": 283283.9668517071 }, { "content": "/// find out how often a format string matches a timestamp in a file\n\npub fn match_format_string_in_file(\n\n format_expr: &str,\n\n file_name: &str,\n\n max_lines: i64,\n\n) -> Result<FormatStringMatches, failure::Error> {\n\n let regex = lookup_regex_for_format_str(format_expr)?;\n\n let path = PathBuf::from(file_name);\n\n let f: fs::File = fs::File::open(path)?;\n\n let mut reader: BufReader<&std::fs::File> = BufReader::new(&f);\n\n let mut buf = vec![];\n\n let mut inspected_lines = 0usize;\n\n let mut matched_lines = 0usize;\n\n let mut processed_bytes = 0;\n\n while let Ok(len) = reader.read_until(b'\\n', &mut buf) {\n\n if len == 0 {\n\n break; // file is done\n\n }\n\n let s = unsafe { std::str::from_utf8_unchecked(&buf) };\n\n if !s.trim().is_empty() {\n\n inspected_lines += 1;\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 10, "score": 277455.9319782044 }, { "content": "/// check a new format expression that was not precompiled\n\npub fn line_matching_format_expression(\n\n format_expr: &str,\n\n line: &str,\n\n) -> Result<bool, failure::Error> {\n\n let regex = lookup_regex_for_format_str(format_expr)?;\n\n let res = regex.is_match(line);\n\n Ok(res)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 11, "score": 277451.7639752991 }, { "content": "fn date_format_str_to_regex(date_format: &str) -> Result<Regex, failure::Error> {\n\n if date_format.is_empty() {\n\n return Err(failure::err_msg(\"cannot construct regex from empty string\"));\n\n }\n\n let format_pieces = date_expression(date_format);\n\n match format_pieces {\n\n Ok(r) => {\n\n if r.1.is_empty() {\n\n return Err(failure::err_msg(\n\n \"could not create regex, problems with format pieces\",\n\n ));\n\n }\n\n let s = r.1.iter().fold(String::from(r\"\"), |mut acc, x| {\n\n let part = format_piece_as_regex_string(x);\n\n acc.push_str(part.as_str());\n\n acc\n\n });\n\n\n\n return match Regex::new(s.as_str()) {\n\n Ok(regex) => Ok(regex),\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 12, "score": 275323.4939155331 }, { "content": "pub fn date_expression(input: &str) -> IResult<&str, Vec<FormatPiece>> {\n\n let parser = fold_many0(\n\n any_date_format,\n\n (String::from(\"\"), Vec::new()),\n\n |mut acc: (String, Vec<_>), item| {\n\n match item {\n\n FormatPiece::SeperatorChar(c) => acc.0.push_str(&escape_metacharacters(c)),\n\n _ => {\n\n if !acc.0.is_empty() {\n\n acc.1.push(FormatPiece::Seperator(acc.0));\n\n acc.0 = String::from(\"\")\n\n }\n\n acc.1.push(item)\n\n }\n\n };\n\n acc\n\n },\n\n );\n\n map(parser, |p: (String, Vec<FormatPiece>)| {\n\n if !p.0.is_empty() {\n\n let mut res_vec = p.1;\n\n res_vec.push(FormatPiece::Seperator(p.0));\n\n return res_vec;\n\n }\n\n p.1\n\n })(input)\n\n}\n\n\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 13, "score": 270889.53931912995 }, { "content": "pub fn report_error<'a, S: Into<Cow<'a, str>>>(text: S) {\n\n eprintln!(\"{}\", create_incident(Severity::ERROR, text, None))\n\n}\n", "file_path": "application/apps/indexer/indexer_base/src/error_reporter.rs", "rank": 14, "score": 254689.72042721836 }, { "content": "pub fn detect_timestamp_format_in_file(path: &Path) -> Result<String, failure::Error> {\n\n let f: fs::File = fs::File::open(path)?;\n\n let mut reader: BufReader<&std::fs::File> = BufReader::new(&f);\n\n\n\n let mut buf = vec![];\n\n let mut inspected_lines = 0;\n\n let mut matched_format: BTreeMap<String, usize> = BTreeMap::default();\n\n let mut last_match: Option<String> = None;\n\n\n\n while let Ok(len) = reader.read_until(b'\\n', &mut buf) {\n\n if len == 0 {\n\n break; // file is done\n\n }\n\n let s = unsafe { std::str::from_utf8_unchecked(&buf) }.trim();\n\n if !s.is_empty() {\n\n if let Ok(format) = detect_timeformat_in_string(s, last_match.as_ref()) {\n\n last_match = Some(format.clone());\n\n *matched_format.entry(format).or_insert(0) += 1;\n\n }\n\n inspected_lines += 1;\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 15, "score": 246136.9833443475 }, { "content": "pub fn report_warning<'a, S: Into<Cow<'a, str>>>(text: S) {\n\n let incident = Incident::new(Severity::WARNING, text, None);\n\n eprintln!(\n\n \"{}\",\n\n serde_json::to_string(&incident).unwrap_or_else(|_| \"\".to_string())\n\n )\n\n}\n", "file_path": "application/apps/indexer/indexer_base/src/error_reporter.rs", "rank": 16, "score": 242227.66145608912 }, { "content": "pub fn dlt_zero_terminated_string(s: &[u8], size: usize) -> IResult<&[u8], &str> {\n\n let (rest_with_null, content_without_null) = take_while_m_n(0, size, is_not_null)(s)?;\n\n let res_str = match nom::lib::std::str::from_utf8(content_without_null) {\n\n Ok(content) => content,\n\n Err(e) => {\n\n let (valid, _) = content_without_null.split_at(e.valid_up_to());\n\n unsafe { nom::lib::std::str::from_utf8_unchecked(valid) }\n\n }\n\n };\n\n let missing = size - content_without_null.len();\n\n let (rest, _) = take(missing)(rest_with_null)?;\n\n Ok((rest, res_str))\n\n}\n\n\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 18, "score": 240531.65886052395 }, { "content": "fn many_spaces(input: &str) -> IResult<&str, char> {\n\n map(many1(nom::character::complete::char(' ')), |_| ' ')(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 19, "score": 234419.66667864486 }, { "content": "fn escape_metacharacters(c: char) -> Cow<'static, str> {\n\n match c {\n\n ' ' => r\"\\s?\",\n\n '.' => r\"\\.\",\n\n '|' => r\"\\|\",\n\n '?' => r\"\\?\",\n\n '+' => r\"\\+\",\n\n '(' => r\"\\(\",\n\n ')' => r\"\\)\",\n\n '[' => r\"\\[\",\n\n '{' => r\"\\{\",\n\n '^' => r\"\\^\",\n\n '$' => r\"\\$\",\n\n '*' => r\"\\*\",\n\n _ => return c.to_string().into(),\n\n }\n\n .into()\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 20, "score": 230044.6011633568 }, { "content": "fn any_date_format(input: &str) -> IResult<&str, FormatPiece> {\n\n nom::branch::alt((\n\n days,\n\n month_short,\n\n month,\n\n year,\n\n year_short,\n\n hours,\n\n minutes,\n\n absolute_millis,\n\n seconds,\n\n fraction,\n\n am_pm,\n\n timezone,\n\n seperator,\n\n ))(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 21, "score": 227881.56042134477 }, { "content": "pub fn concat_files_use_config_file(\n\n config_path: &PathBuf,\n\n out_path: &PathBuf,\n\n append: bool,\n\n update_channel: mpsc::Sender<IndexingResults<ConcatenatorResult>>,\n\n shutdown_rx: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), failure::Error> {\n\n let mut concat_option_file = fs::File::open(config_path)?;\n\n let dir_name = config_path\n\n .parent()\n\n .ok_or_else(|| failure::err_msg(\"could not find directory of config file\"))?;\n\n let options: Vec<ConcatItemOptions> = read_concat_options(&mut concat_option_file)?;\n\n let inputs: Vec<ConcatenatorInput> = options\n\n .into_iter()\n\n .map(|o: ConcatItemOptions| ConcatenatorInput {\n\n path: PathBuf::from(&dir_name)\n\n .join(o.path)\n\n .to_str()\n\n .unwrap()\n\n .to_string(),\n\n tag: o.tag,\n\n })\n\n .collect();\n\n concat_files(inputs, &out_path, append, update_channel, shutdown_rx)\n\n}\n", "file_path": "application/apps/indexer/merging/src/concatenator.rs", "rank": 23, "score": 220696.7203904295 }, { "content": "#[inline]\n\npub fn is_not_null(chr: u8) -> bool {\n\n chr != 0x0\n\n}\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 24, "score": 219052.22380957624 }, { "content": "fn seperator(input: &str) -> IResult<&str, FormatPiece> {\n\n map(\n\n nom::branch::alt((many_spaces, nom::character::complete::anychar)),\n\n FormatPiece::SeperatorChar,\n\n )(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 25, "score": 217418.326353165 }, { "content": "fn hours(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(HOURS_FORMAT_TAG), |_| FormatPiece::Hour)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 26, "score": 217418.326353165 }, { "content": "fn seconds(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(SECONDS_FORMAT_TAG), |_| FormatPiece::Second)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 27, "score": 217418.326353165 }, { "content": "fn days(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(DAY_FORMAT_TAG), |_| FormatPiece::Day)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 28, "score": 217418.326353165 }, { "content": "fn month(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(MONTH_FORMAT_TAG), |_| FormatPiece::Month)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 29, "score": 217418.326353165 }, { "content": "fn am_pm(input: &str) -> IResult<&str, FormatPiece> {\n\n map(nom::character::complete::char(AM_PM_TAG), |_| {\n\n FormatPiece::AmPm\n\n })(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 30, "score": 217418.326353165 }, { "content": "fn fraction(input: &str) -> IResult<&str, FormatPiece> {\n\n map(nom::character::complete::char(FRACTION_FORMAT_CHAR), |_| {\n\n FormatPiece::Fraction\n\n })(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 31, "score": 217418.326353165 }, { "content": "fn minutes(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(MINUTES_FORMAT_TAG), |_| FormatPiece::Minute)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 32, "score": 217418.326353165 }, { "content": "fn timezone(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(TIMEZONE_FORMAT_TAG), |_| FormatPiece::TimeZone)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 33, "score": 217418.326353165 }, { "content": "fn year(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(YEAR_FORMAT_TAG), |_| FormatPiece::Year)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 34, "score": 217418.326353165 }, { "content": "fn absolute_millis(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(\"sss\"), |_| FormatPiece::AbsoluteMilliseconds)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 35, "score": 215700.63622453494 }, { "content": "fn month_short(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(MONTH_FORMAT_SHORT_NAME_TAG), |_| FormatPiece::MonthName)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 36, "score": 215700.63622453494 }, { "content": "fn year_short(input: &str) -> IResult<&str, FormatPiece> {\n\n map(tag(YEAR_SHORT_FORMAT_TAG), |_| FormatPiece::YearShort)(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 37, "score": 215700.63622453494 }, { "content": "pub fn init_logging() -> Result<(), std::io::Error> {\n\n // log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Trace))?;\n\n let home_dir = dirs::home_dir().expect(\"we need to have access to home-dir\");\n\n let log_path = home_dir.join(\".chipmunk\").join(\"chipmunk.indexer.log\");\n\n let appender_name = \"indexer-root\";\n\n let logfile = FileAppender::builder()\n\n .encoder(Box::new(PatternEncoder::new(\"{d} - {l}:: {m}\\n\")))\n\n .build(log_path)?;\n\n\n\n let config = Config::builder()\n\n .appender(Appender::builder().build(appender_name, Box::new(logfile)))\n\n .build(\n\n Root::builder()\n\n .appender(appender_name)\n\n .build(LevelFilter::Trace),\n\n )\n\n .unwrap();\n\n\n\n log4rs::init_config(config).unwrap();\n\n trace!(\"logging initialized\");\n\n Ok(())\n\n}\n\n\n", "file_path": "application/apps/indexer-neon/native/src/lib.rs", "rank": 39, "score": 209226.20784043288 }, { "content": "fn maybe_parse_ecu_id(a: bool) -> impl Fn(&[u8]) -> IResult<&[u8], Option<&str>> {\n\n fn parse_ecu_id_to_option(input: &[u8]) -> IResult<&[u8], Option<&str>> {\n\n map(parse_ecu_id, Some)(input)\n\n }\n\n fn parse_nothing_str(input: &[u8]) -> IResult<&[u8], Option<&str>> {\n\n Ok((input, None))\n\n }\n\n if a {\n\n parse_ecu_id_to_option\n\n } else {\n\n parse_nothing_str\n\n }\n\n}\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 40, "score": 207238.97214055178 }, { "content": "fn parse_timezone(input: &str) -> Result<i64, failure::Error> {\n\n match timezone_parser(input) {\n\n Ok((_, res)) => Ok(res),\n\n Err(e) => Err(failure::err_msg(format!(\"error parsing timezone: {:?}\", e))),\n\n }\n\n}\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use pretty_assertions::assert_eq;\n\n use proptest::prelude::*;\n\n\n\n static VALID_TIMESTAMP_FORMAT: &str = \"[+-]{1}[0-9]{2}[0-5]{1}[0-9]{1}\";\n\n\n\n proptest! {\n\n #[test]\n\n fn offset_from_timezone_in_ms_doesnt_crash(s in \"\\\\PC*\") {\n\n let _ = parse_timezone(&s);\n\n }\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 41, "score": 204398.9136727181 }, { "content": "fn parse_from_month(mmm: &str) -> Result<u32, failure::Error> {\n\n match mmm {\n\n \"Jan\" => Ok(1),\n\n \"Feb\" => Ok(2),\n\n \"Mar\" => Ok(3),\n\n \"Apr\" => Ok(4),\n\n \"May\" => Ok(5),\n\n \"Jun\" => Ok(6),\n\n \"Jul\" => Ok(7),\n\n \"Aug\" => Ok(8),\n\n \"Sep\" => Ok(9),\n\n \"Oct\" => Ok(10),\n\n \"Nov\" => Ok(11),\n\n \"Dec\" => Ok(12),\n\n _ => Err(failure::err_msg(format!(\"could not parse month {:?}\", mmm))),\n\n }\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 42, "score": 204398.9136727181 }, { "content": "pub fn zero_terminated_string(raw: &[u8]) -> Result<String, Error> {\n\n let nul_range_end = raw\n\n .iter()\n\n .position(|&c| c == b'\\0')\n\n .unwrap_or_else(|| raw.len()); // default to length if no `\\0` present\n\n str::from_utf8(&raw[0..nul_range_end])\n\n .map(|v| v.to_owned())\n\n .map_err(|e| {\n\n report_warning(format!(\"Invalid zero_terminated_string: {}\", e));\n\n Error::new(io::ErrorKind::Other, e)\n\n })\n\n}\n\n\n\npub const LEVEL_FATAL: u8 = 0x1;\n\npub const LEVEL_ERROR: u8 = 0x2;\n\npub const LEVEL_WARN: u8 = 0x3;\n\npub const LEVEL_INFO: u8 = 0x4;\n\npub const LEVEL_DEBUG: u8 = 0x5;\n\npub const LEVEL_VERBOSE: u8 = 0x6;\n\n\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 43, "score": 202566.77707743697 }, { "content": "pub fn calculate_all_headers_length(header_type: u8) -> usize {\n\n let mut length = calculate_standard_header_length(header_type);\n\n if (header_type & WITH_EXTENDED_HEADER_FLAG) != 0 {\n\n length += EXTENDED_HEADER_LENGTH;\n\n }\n\n length\n\n}\n\n\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 45, "score": 196310.72550390003 }, { "content": "pub fn calculate_standard_header_length(header_type: u8) -> usize {\n\n let mut length = HEADER_MIN_LENGTH;\n\n if (header_type & WITH_ECU_ID_FLAG) != 0 {\n\n length += 4;\n\n }\n\n if (header_type & WITH_SESSION_ID_FLAG) != 0 {\n\n length += 4;\n\n }\n\n if (header_type & WITH_TIMESTAMP_FLAG) != 0 {\n\n length += 4;\n\n }\n\n length\n\n}\n\n\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 47, "score": 194481.8327093071 }, { "content": "pub fn fixed_point_value_width(v: &FixedPointValue) -> usize {\n\n match v {\n\n FixedPointValue::I32(_) => 4,\n\n FixedPointValue::I64(_) => 8,\n\n }\n\n}\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Value {\n\n Bool(bool),\n\n U8(u8),\n\n U16(u16),\n\n U32(u32),\n\n U64(u64),\n\n U128(u128),\n\n I8(i8),\n\n I16(i16),\n\n I32(i32),\n\n I64(i64),\n\n I128(i128),\n\n F32(f32),\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 48, "score": 194481.8327093071 }, { "content": "fn create_incident<'a, S: Into<Cow<'a, str>>>(\n\n severity: Severity,\n\n text: S,\n\n line_nr: Option<usize>,\n\n) -> String {\n\n let incident = Incident::new(severity, text, line_nr);\n\n serde_json::to_string(&incident).unwrap_or_else(|_| \"\".to_string())\n\n}\n", "file_path": "application/apps/indexer/indexer_base/src/error_reporter.rs", "rank": 49, "score": 190936.68438094878 }, { "content": "fn detect_timestamp_format_in_file(mut cx: FunctionContext) -> JsResult<JsValue> {\n\n let file_name: String = cx.argument::<JsString>(0)?.value();\n\n let (tx, rx): (\n\n Sender<IndexingResults<TimestampFormatResult>>,\n\n Receiver<IndexingResults<TimestampFormatResult>>,\n\n ) = std::sync::mpsc::channel();\n\n let items: Vec<DiscoverItem> = vec![DiscoverItem {\n\n path: file_name.clone(),\n\n }];\n\n let err_timestamp_result = TimestampFormatResult {\n\n path: file_name,\n\n format: None,\n\n min_time: None,\n\n max_time: None,\n\n };\n\n let js_err_value = neon_serde::to_value(&mut cx, &err_timestamp_result)?;\n\n match timespan_in_files(items, &tx) {\n\n Ok(()) => (),\n\n Err(_e) => {\n\n return Ok(js_err_value);\n", "file_path": "application/apps/indexer-neon/native/src/lib.rs", "rank": 50, "score": 183629.98498028712 }, { "content": "fn take1(s: &str) -> IResult<&str, &str> {\n\n take(1usize)(s)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 51, "score": 179236.02701550123 }, { "content": "fn take4(s: &str) -> IResult<&str, &str> {\n\n take(4usize)(s)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 52, "score": 179236.02701550123 }, { "content": "fn take2(s: &str) -> IResult<&str, &str> {\n\n take(2usize)(s)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 53, "score": 179236.02701550123 }, { "content": "fn parse_benchmark(c: &mut Criterion) {\n\n let inputs = [\n\n \"2019-05-02 00:06:26.506 abc\",\n\n \"2019-05-02T01:36:36.506 abc\",\n\n \"05-02 23:46:46.506 abc\",\n\n \"05-02T12:56:56.506 abc\",\n\n \"05-02-2019 12:16:06.506 abc\",\n\n \"05-02-2019T12:26:36.506 abc\",\n\n \"02/May/2019:12:36:36 abc\",\n\n \"02/May/2019T12:36:36 abc\",\n\n \"some stuff before: 05-02-2019T12:36:36.506 0 0.764564113869644\",\n\n \"non matching line 02-02-2019 12_36_379 bllllllllllah\",\n\n ];\n\n c.bench_function(\"detect_timeformat_in_string\", move |b| {\n\n for input in inputs.iter() {\n\n b.iter(|| detect_timeformat_in_string(input, None))\n\n }\n\n });\n\n c.bench_function(\"detect_timestamp_in_string multiple inputs\", move |b| {\n\n for input in inputs.iter() {\n", "file_path": "application/apps/indexer/processor/benches/parse_benchmarks.rs", "rank": 54, "score": 173805.76077364758 }, { "content": "fn dlt_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"format header\", |b| {\n\n let timestamp = dlt::dlt::DltTimeStamp {\n\n seconds: 0x4DC9_2C26,\n\n microseconds: 0x000C_A2D8,\n\n };\n\n b.iter(|| format!(\"{}\", timestamp))\n\n });\n\n c.bench_function(\"format message\", |b| {\n\n let timestamp = DltTimeStamp {\n\n seconds: 0x4DC9_2C26,\n\n microseconds: 0x000C_A2D8,\n\n };\n\n let storage_header = StorageHeader {\n\n timestamp,\n\n ecu_id: \"abc\".to_string(),\n\n };\n\n let header: StandardHeader = StandardHeader {\n\n version: 1,\n\n has_extended_header: true,\n", "file_path": "application/apps/indexer/dlt/benches/dlt_benchmarks.rs", "rank": 55, "score": 173805.76077364758 }, { "content": "fn dlt_parse_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"zero_termitated_string broken input\", |b| {\n\n let mut buf = BytesMut::with_capacity(4);\n\n let broken = vec![0x41, 0, 146, 150];\n\n buf.extend_from_slice(&broken);\n\n b.iter(|| dlt::dlt_parse::dlt_zero_terminated_string(&buf, 4))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, dlt_benchmark, dlt_parse_benchmark);\n\ncriterion_main!(benches);\n", "file_path": "application/apps/indexer/dlt/benches/dlt_benchmarks.rs", "rank": 56, "score": 172497.30366331787 }, { "content": "/// find out the lower and upper timestamp of a file\n\npub fn timespan_in_files(\n\n items: Vec<DiscoverItem>,\n\n update_channel: &mpsc::Sender<IndexingResults<TimestampFormatResult>>,\n\n) -> Result<(), failure::Error> {\n\n for item in items {\n\n let file_path = path::PathBuf::from(&item.path);\n\n match detect_timestamp_format_in_file(&file_path) {\n\n Ok(format_expr) => {\n\n let regex = lookup_regex_for_format_str(&format_expr)?;\n\n let f: fs::File = fs::File::open(file_path)?;\n\n let mut min_timestamp = std::i64::MAX;\n\n let mut max_timestamp = 0i64;\n\n let file_size = f.metadata()?.len();\n\n let min_buf_size = std::cmp::min(file_size, 256 * 1024); // 256k\n\n let lines_to_scan = 1000usize;\n\n let _line_cnt = match scan_lines(\n\n &f,\n\n &regex,\n\n &mut min_timestamp,\n\n &mut max_timestamp,\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 57, "score": 170518.885199159 }, { "content": "pub fn concat_files(\n\n concat_inputs: Vec<ConcatenatorInput>,\n\n out_path: &PathBuf,\n\n append: bool,\n\n update_channel: mpsc::Sender<IndexingResults<ConcatenatorResult>>,\n\n shutdown_rx: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), failure::Error> {\n\n let file_cnt = concat_inputs.len();\n\n trace!(\"concat_files called with {} files\", file_cnt);\n\n let mut line_nr = 0;\n\n let out_file: std::fs::File = if append {\n\n std::fs::OpenOptions::new()\n\n .append(true)\n\n .create(true)\n\n .open(out_path)?\n\n } else {\n\n std::fs::File::create(&out_path).unwrap()\n\n };\n\n let mut buf_writer = BufWriter::with_capacity(10 * 1024 * 1024, out_file);\n\n let mut processed_bytes = 0;\n", "file_path": "application/apps/indexer/merging/src/concatenator.rs", "rank": 58, "score": 170518.885199159 }, { "content": "pub fn index_file(\n\n config: IndexingConfig,\n\n initial_line_nr: usize,\n\n timestamps: bool,\n\n source_file_size: Option<usize>,\n\n update_channel: mpsc::Sender<ChunkResults>,\n\n shutdown_receiver: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), Error> {\n\n trace!(\"called index_file for file: {:?}\", config.in_file);\n\n let start = Instant::now();\n\n let (out_file, current_out_file_size) =\n\n utils::get_out_file_and_size(config.append, &config.out_path)?;\n\n\n\n let mut chunk_count = 0usize;\n\n let mut last_byte_index = 0usize;\n\n let mut chunk_factory =\n\n ChunkFactory::new(config.chunk_size, config.to_stdout, current_out_file_size);\n\n\n\n let mut reader = BufReader::new(config.in_file);\n\n let mut line_nr = initial_line_nr;\n", "file_path": "application/apps/indexer/processor/src/processor.rs", "rank": 59, "score": 170518.885199159 }, { "content": "/// Trys to detect a valid timestamp in a string\n\n/// Returns the a tuple of\n\n/// * the timestamp as posix timestamp\n\n/// * if the year was missing\n\n/// (we assume the current year (local time) if true)\n\n/// * the format string that was used\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input` - A string slice that should be parsed\n\npub fn detect_timestamp_in_string(\n\n input: &str,\n\n offset: Option<i64>,\n\n) -> Result<(i64, bool, String), failure::Error> {\n\n let trimmed = input.trim();\n\n for format in AVAILABLE_FORMATS.iter() {\n\n let regex = &FORMAT_REGEX_MAPPING[format];\n\n if regex.is_match(trimmed) {\n\n if let Ok((timestamp, year_missing)) =\n\n extract_posix_timestamp(trimmed, regex, None, offset)\n\n {\n\n return Ok((timestamp, year_missing, (*format).to_string()));\n\n }\n\n }\n\n }\n\n Err(failure::err_msg(\"try to detect timestamp but no match\"))\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 60, "score": 169155.51082503333 }, { "content": "/// Trys to detect a valid time-format in a string\n\n/// Returns the found format if any\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input` - A string slice that should be examined\n\npub fn detect_timeformat_in_string(\n\n input: &str,\n\n last_match: Option<&String>,\n\n) -> Result<String, failure::Error> {\n\n let trimmed = input.trim();\n\n // if we already had a match, try this first\n\n if let Some(last) = last_match {\n\n let l: &str = last.as_ref();\n\n if let Some(regex) = FORMAT_REGEX_MAPPING.get(l) {\n\n if regex.is_match(trimmed) {\n\n return Ok(last.clone());\n\n }\n\n }\n\n }\n\n for format in AVAILABLE_FORMATS.iter() {\n\n let regex = &FORMAT_REGEX_MAPPING[format];\n\n // println!(\"check with regex: {}\", regex.to_string());\n\n if regex.is_match(trimmed) {\n\n return Ok((*format).to_string());\n\n }\n\n }\n\n Err(failure::err_msg(format!(\n\n \"no timestamp match found in {}\",\n\n input\n\n )))\n\n}\n\n\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 62, "score": 169150.72967028673 }, { "content": "#[allow(dead_code)]\n\n#[inline]\n\npub fn create_message_line(\n\n out_buffer: &mut dyn std::io::Write,\n\n msg: Message,\n\n) -> std::io::Result<()> {\n\n // Messages without extended header (non-verbose) are unimplemented\n\n if let Some(ext) = msg.extended_header {\n\n let _level = match ext.message_type {\n\n MessageType::Log(level) => level.into(),\n\n MessageType::ApplicationTrace(_) | MessageType::NetworkTrace(_) => log::Level::Trace,\n\n // Ignore everything else\n\n _ => return Ok(()),\n\n };\n\n\n\n // dest.reserve(1024); // TODO reserve correct amount\n\n // Format message: Join arguments as strings\n\n if let Payload::Verbose(arguments) = msg.payload {\n\n // Format tag by concatenating ecu_id, application_id and context_id\n\n write!(\n\n out_buffer,\n\n \"{}{}{}-{}\",\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 63, "score": 169150.599347757 }, { "content": "pub fn create_index_and_mapping(\n\n config: IndexingConfig,\n\n parse_timestamps: bool,\n\n source_file_size: Option<usize>,\n\n update_channel: mpsc::Sender<ChunkResults>,\n\n shutdown_receiver: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), Error> {\n\n let initial_line_nr = match utils::next_line_nr(config.out_path) {\n\n Ok(nr) => nr,\n\n Err(e) => {\n\n let c = format!(\n\n \"could not determine last line number of {:?} ({})\",\n\n config.out_path, e\n\n );\n\n let _ = update_channel.send(Err(Notification {\n\n severity: Severity::ERROR,\n\n content: c.clone(),\n\n line: None,\n\n }));\n\n return Err(err_msg(c));\n", "file_path": "application/apps/indexer/processor/src/processor.rs", "rank": 64, "score": 169145.86554511703 }, { "content": "// return the timestamp and wether the year was missing\n\npub fn extract_posix_timestamp(\n\n line: &str,\n\n regex: &Regex,\n\n year: Option<i32>,\n\n time_offset: Option<i64>,\n\n) -> Result<(i64, bool), failure::Error> {\n\n let caps = regex\n\n .captures(line)\n\n .ok_or_else(|| failure::err_msg(\"no captures in regex\"))?;\n\n /* only one matched group in addition to the full match */\n\n if caps.len() == 1 + 1 {\n\n if let Some(abs_ms_capt) = caps.name(ABSOLUTE_MS_GROUP) {\n\n let absolute_ms: i64 = abs_ms_capt.as_str().parse()?;\n\n return Ok((absolute_ms - time_offset.unwrap_or(0), false));\n\n }\n\n }\n\n let day_capt = caps\n\n .name(DAY_GROUP)\n\n .ok_or_else(|| failure::err_msg(\"no group for days found in regex\"))?;\n\n let day: u32 = day_capt.as_str().parse()?;\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 65, "score": 169145.86554511703 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn line_to_timed_line(\n\n line: &str,\n\n original_line_length: usize,\n\n tag: &str,\n\n regex: &Regex,\n\n year: Option<i32>,\n\n time_offset: Option<i64>,\n\n line_nr: usize,\n\n reporter: &mut Reporter,\n\n) -> Result<TimedLine, failure::Error> {\n\n match extract_posix_timestamp(line, regex, year, time_offset) {\n\n Ok((posix_timestamp, year_was_missing)) => Ok(TimedLine {\n\n timestamp: posix_timestamp,\n\n content: line.to_string(),\n\n tag: tag.to_string(),\n\n original_length: original_line_length,\n\n year_was_missing,\n\n line_nr,\n\n }),\n\n Err(e) => {\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 66, "score": 169145.86554511703 }, { "content": "fn read_one_dlt_message<T: Read>(\n\n reader: &mut ReduxReader<T, MinBuffered>,\n\n filter_config: Option<&filtering::ProcessedDltFilterConfig>,\n\n index: usize,\n\n processed_bytes: usize,\n\n update_channel: mpsc::Sender<ChunkResults>,\n\n) -> Result<Option<(usize, Option<dlt::Message>)>, Error> {\n\n loop {\n\n match reader.fill_buf() {\n\n Ok(content) => {\n\n if content.is_empty() {\n\n return Ok(None);\n\n }\n\n let available = content.len();\n\n\n\n let res: nom::IResult<&[u8], Option<dlt::Message>> = dlt_message(\n\n content,\n\n filter_config,\n\n index,\n\n processed_bytes,\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 67, "score": 168332.09883130604 }, { "content": "/// create index for a dlt file\n\n/// source_file_size: if progress updates should be made, add this value\n\npub fn index_dlt_file(\n\n config: IndexingConfig,\n\n dlt_filter: Option<filtering::DltFilterConfig>,\n\n initial_line_nr: usize,\n\n source_file_size: Option<usize>,\n\n update_channel: mpsc::Sender<ChunkResults>,\n\n shutdown_receiver: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), Error> {\n\n trace!(\"index_dlt_file\");\n\n let (out_file, current_out_file_size) =\n\n utils::get_out_file_and_size(config.append, &config.out_path)?;\n\n\n\n let mut chunk_count = 0usize;\n\n let mut last_byte_index = 0usize;\n\n let mut chunk_factory =\n\n ChunkFactory::new(config.chunk_size, config.to_stdout, current_out_file_size);\n\n\n\n let mut reader = ReduxReader::with_capacity(10 * 1024 * 1024, config.in_file)\n\n .set_policy(MinBuffered(10 * 1024));\n\n let mut line_nr = initial_line_nr;\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 69, "score": 167806.06095540017 }, { "content": "fn read_one_dlt_message_info<T: Read>(\n\n reader: &mut ReduxReader<T, MinBuffered>,\n\n index: Option<usize>,\n\n update_channel: Option<mpsc::Sender<StatisticsResults>>,\n\n) -> Result<Option<(usize, StatisticRowInfo)>, Error> {\n\n loop {\n\n match reader.fill_buf() {\n\n Ok(content) => {\n\n if content.is_empty() {\n\n return Ok(None);\n\n }\n\n let available = content.len();\n\n let res: nom::IResult<&[u8], StatisticRowInfo> =\n\n dlt_app_id_context_id(content, index, update_channel.clone());\n\n match res {\n\n Ok(r) => {\n\n let consumed = available - r.0.len();\n\n break Ok(Some((consumed, r.1)));\n\n }\n\n e => match e {\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 70, "score": 167238.7707981133 }, { "content": "pub fn create_index_and_mapping_dlt(\n\n config: IndexingConfig,\n\n source_file_size: Option<usize>,\n\n filter_conf: Option<filtering::DltFilterConfig>,\n\n update_channel: mpsc::Sender<ChunkResults>,\n\n shutdown_receiver: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), Error> {\n\n trace!(\"create_index_and_mapping_dlt\");\n\n match utils::next_line_nr(config.out_path) {\n\n Ok(initial_line_nr) => index_dlt_file(\n\n config,\n\n filter_conf,\n\n initial_line_nr,\n\n source_file_size,\n\n update_channel,\n\n shutdown_receiver,\n\n ),\n\n Err(e) => {\n\n let content = format!(\n\n \"could not determine last line number of {:?} ({})\",\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 71, "score": 166498.2805633043 }, { "content": "#[allow(dead_code)]\n\npub fn get_dlt_file_info(\n\n in_file: &fs::File,\n\n source_file_size: usize,\n\n update_channel: mpsc::Sender<StatisticsResults>,\n\n shutdown_receiver: Option<mpsc::Receiver<()>>,\n\n) -> Result<(), Error> {\n\n let mut reader =\n\n ReduxReader::with_capacity(10 * 1024 * 1024, in_file).set_policy(MinBuffered(10 * 1024));\n\n\n\n let mut app_ids: IdMap = FxHashMap::default();\n\n let mut context_ids: IdMap = FxHashMap::default();\n\n let mut ecu_ids: IdMap = FxHashMap::default();\n\n let mut index = 0usize;\n\n let mut processed_bytes = 0usize;\n\n loop {\n\n match read_one_dlt_message_info(&mut reader, Some(index), Some(update_channel.clone())) {\n\n Ok(Some((\n\n consumed,\n\n StatisticRowInfo {\n\n app_id_context_id: Some((app_id, context_id)),\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 72, "score": 166498.2805633043 }, { "content": "/// should parse timezone string, valid formats are\n\n/// +hh:mm, +hhmm, or +hh\n\n/// -hh:mm, -hhmm, or -hh\n\n/// results in the offset in milliseconds\n\nfn timezone_parser(input: &str) -> IResult<&str, i64> {\n\n let timezone_sign = map(nom::branch::alt((char('+'), char('-'))), |c| c == '+');\n\n fn timezone_count(input: &str) -> IResult<&str, i64> {\n\n let (rest, r) = nom::bytes::complete::take(2usize)(input)?;\n\n let second = map_res(digit1, |s: &str| s.parse::<i64>())(r)?;\n\n Ok((rest, second.1))\n\n }\n\n fn timezone_minutes(input: &str) -> IResult<&str, i64> {\n\n nom::sequence::preceded(opt(char(':')), timezone_count)(input)\n\n }\n\n let parser = nom::sequence::tuple((timezone_sign, timezone_count, opt(timezone_minutes)));\n\n map(parser, |(positiv, hour, min): (bool, i64, Option<i64>)| {\n\n let absolute = 1000 * (3600 * hour + 60 * min.unwrap_or(0));\n\n (if positiv { 1 } else { -1 }) * absolute\n\n })(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 73, "score": 163913.8446383274 }, { "content": "fn four_digits(input: &str) -> IResult<&str, u32> {\n\n map_res(take4, |s: &str| s.parse())(input)\n\n}\n\n\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 74, "score": 163910.11300802312 }, { "content": "fn two_digits(input: &str) -> IResult<&str, u32> {\n\n map_res(take2, |s: &str| s.parse())(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 75, "score": 163910.11300802312 }, { "content": "fn update() -> Result<bool> {\n\n let updater = get_updater_path();\n\n let updater_path = Path::new(&updater);\n\n\n\n if !updater_path.exists() {\n\n error!(\n\n \"File of updater {} doesn't exist\",\n\n updater_path.to_string_lossy()\n\n );\n\n return Ok(false);\n\n }\n\n\n\n trace!(\"Starting updater: {}\", updater);\n\n let app = get_app_path_str()?;\n\n let tgz = get_app_updating_tgz_path_str();\n\n if app == \"\" || tgz == \"\" {\n\n error!(\n\n \"Fail to start update because some path isn't detected. app: {}, tgz: {}\",\n\n app, tgz\n\n );\n", "file_path": "application/apps/launcher/src/main.rs", "rank": 76, "score": 163053.67345848022 }, { "content": "fn parse_short_month(input: &str) -> IResult<&str, u32> {\n\n map_res(take(3usize), |s: &str| match s {\n\n \"Jan\" => Ok(1),\n\n \"Feb\" => Ok(2),\n\n \"Mar\" => Ok(3),\n\n \"Apr\" => Ok(4),\n\n \"May\" => Ok(5),\n\n \"Jun\" => Ok(6),\n\n \"Jul\" => Ok(7),\n\n \"Aug\" => Ok(8),\n\n \"Sep\" => Ok(9),\n\n \"Oct\" => Ok(10),\n\n \"Nov\" => Ok(11),\n\n \"Dec\" => Ok(12),\n\n _ => Err(failure::err_msg(format!(\"could not parse month {:?}\", s))),\n\n })(input)\n\n}\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 77, "score": 162816.9751611089 }, { "content": "fn named_group(regex: &str, capture_id: &str) -> String {\n\n format!(r\"(?P<{}>{})\", capture_id, regex)\n\n}\n\n\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 78, "score": 162816.9751611089 }, { "content": "#[cfg(target_os = \"windows\")]\n\nfn spawn(exe: &str, args: &[&str]) -> Result<Child> {\n\n const DETACHED_PROCESS: u32 = 0x00000008;\n\n const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;\n\n Command::new(exe)\n\n .args(args)\n\n .creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)\n\n .spawn()\n\n}\n\n\n", "file_path": "application/apps/launcher/src/main.rs", "rank": 79, "score": 161153.59473995288 }, { "content": "fn spawn(exe: &str, args: &[&str]) -> Result<Child> {\n\n Command::new(exe).args(args).spawn()\n\n}\n\n\n", "file_path": "application/apps/updater/src/main.rs", "rank": 80, "score": 161153.59473995288 }, { "content": "/// a DLT message looks like this: [standard-header][extended-header][payload]\n\n/// if stored, an additional header is placed BEFORE all of this [storage-header][...]\n\n/// example: 444C5401 262CC94D D8A20C00 45435500 3500001F 45435500 3F88623A 16014150 5000434F 4E001100 00000472 656D6F\n\n/// --------------------------------------------\n\n/// storage-header: 444C5401 262CC94D D8A20C00 45435500\n\n/// 444C5401 = DLT + 0x01 (DLT Pattern)\n\n/// timestamp_sec: 262CC94D = 0x4DC92C26\n\n/// timestamp_us: D8A20C00 = 0x000CA2D8\n\n/// ecu-id: 45435500 = b\"ECU\\0\"\n\n///\n\n/// 3500001F 45435500 3F88623A 16014150 5000434F 4E001100 00000472 656D6F (31 byte)\n\n/// --------------------------------------------\n\n/// header: 35 00 001F 45435500 3F88623A\n\n/// header type = 0x35 = 0b0011 0101\n\n/// UEH: 1 - > using extended header\n\n/// MSBF: 0 - > little endian\n\n/// WEID: 1 - > with ecu id\n\n/// WSID: 0 - > no session id\n\n/// WTMS: 1 - > with timestamp\n\n/// message counter = 0x00 = 0\n\n/// length = 001F = 31\n\n/// ecu-id = 45435500 = \"ECU \"\n\n/// timestamp = 3F88623A = 106590265.0 ms since ECU startup (~30 h)\n\n/// --------------------------------------------\n\n/// extended header: 16014150 5000434F 4E00\n\n/// message-info MSIN = 0x16 = 0b0001 0110\n\n/// 0 -> non-verbose\n\n/// 011 (MSTP Message Type) = 0x3 = Dlt Control Message\n\n/// 0001 (MTIN Message Type Info) = 0x1 = Request Control Message\n\n/// number of arguments NOAR = 0x01\n\n/// application id = 41505000 = \"APP \"\n\n/// context id = 434F4E00 = \"CON \"\n\n/// --------------------------------------------\n\n/// payload: 1100 00000472 656D6F\n\n///\n\npub fn dlt_message<'a>(\n\n input: &'a [u8],\n\n filter_config_opt: Option<&filtering::ProcessedDltFilterConfig>,\n\n index: usize,\n\n _processed_bytes: usize,\n\n update_channel: Option<mpsc::Sender<ChunkResults>>,\n\n) -> IResult<&'a [u8], Option<dlt::Message>> {\n\n // println!(\"parsing dlt_message {:?}[{}]\", index, processed_bytes);\n\n let (after_storage_header, storage_header) =\n\n dlt_storage_header(input, Some(index), update_channel.as_ref())?;\n\n let (after_storage_and_normal_header, header) = dlt_standard_header(after_storage_header)?;\n\n // let (after_storage_and_normal_header, (storage_header, header)) =\n\n // tuple((dlt_storage_header, dlt_standard_header))(input)?;\n\n\n\n // println!(\"parsing 2...let's validate the payload length\");\n\n let payload_length =\n\n match validated_payload_length(&header, Some(index), update_channel.as_ref()) {\n\n Some(length) => length,\n\n None => {\n\n return Ok((after_storage_and_normal_header, None));\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 81, "score": 160176.2348499811 }, { "content": "pub fn dlt_app_id_context_id<T>(\n\n input: &[u8],\n\n index: Option<usize>,\n\n update_channel: Option<mpsc::Sender<IndexingResults<T>>>,\n\n) -> IResult<&[u8], StatisticRowInfo> {\n\n let update_channel_ref = update_channel.as_ref();\n\n let (after_storage_header, _) = dlt_skip_storage_header(input, index, update_channel_ref)?;\n\n let (after_storage_and_normal_header, header) = dlt_standard_header(after_storage_header)?;\n\n\n\n let payload_length = match validated_payload_length(&header, index, update_channel_ref) {\n\n Some(length) => length,\n\n None => {\n\n return Ok((\n\n after_storage_and_normal_header,\n\n StatisticRowInfo {\n\n app_id_context_id: None,\n\n ecu_id: header.ecu_id,\n\n level: None,\n\n },\n\n ));\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 82, "score": 155003.4324518926 }, { "content": "fn maybe_parse_u32(a: bool) -> impl Fn(&[u8]) -> IResult<&[u8], Option<u32>> {\n\n fn parse_u32_to_option(input: &[u8]) -> IResult<&[u8], Option<u32>> {\n\n map(streaming::be_u32, Some)(input)\n\n }\n\n fn parse_nothing_u32(input: &[u8]) -> IResult<&[u8], Option<u32>> {\n\n Ok((input, None))\n\n }\n\n if a {\n\n parse_u32_to_option\n\n } else {\n\n parse_nothing_u32\n\n }\n\n}\n\n\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 83, "score": 146365.78663522052 }, { "content": "pub fn posix_timestamp_as_string(timestamp_ms: i64) -> String {\n\n match NaiveDateTime::from_timestamp_opt(\n\n (timestamp_ms as f64 / 1000.0) as i64,\n\n (timestamp_ms as f64 % 1000.0) as u32 * 1000,\n\n ) {\n\n Some(naive_datetime_max) => {\n\n let t: DateTime<Utc> = DateTime::from_utc(naive_datetime_max, Utc);\n\n format!(\"{}\", t)\n\n }\n\n None => format!(\"could not parse: {}\", timestamp_ms),\n\n }\n\n}\n\n#[derive(Debug, PartialEq, Eq, Hash, Clone)]\n\npub enum FormatPiece {\n\n Day,\n\n Month,\n\n MonthName,\n\n Year,\n\n YearShort,\n\n Hour,\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 84, "score": 143388.46593135124 }, { "content": "fn format_piece_as_regex_string(p: &FormatPiece) -> String {\n\n match p {\n\n FormatPiece::Day => named_group(r\"([0-2]\\d|3[01])\", DAY_GROUP),\n\n FormatPiece::Month => named_group(r\"(0?\\d|1[0-2])\", MONTH_GROUP),\n\n FormatPiece::MonthName => named_group(\n\n r\"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\",\n\n MONTH_SHORT_NAME_GROUP,\n\n ),\n\n FormatPiece::Year => named_group(r\"[0-2]\\d{3}\", YEAR_GROUP),\n\n FormatPiece::YearShort => named_group(r\"\\d{2}\", YEAR_SHORT_GROUP),\n\n FormatPiece::Hour => named_group(r\"(0?\\d|1\\d|2[0-3])\", HOUR_GROUP),\n\n FormatPiece::Minute => named_group(r\"[0-5]\\d\", MINUTE_GROUP),\n\n FormatPiece::Second => named_group(r\"[0-5]\\d\", SECONDS_GROUP),\n\n FormatPiece::Fraction => named_group(r\"\\d+\", FRACTION_GROUP),\n\n FormatPiece::AmPm => named_group(r\"(AM|PM)\", AM_PM_GROUP),\n\n FormatPiece::TimeZone => named_group(r\"[\\+\\-](0\\d|1[0-4]):?(00|30|45)\", TIMEZONE_GROUP),\n\n FormatPiece::AbsoluteMilliseconds => named_group(r\"\\d+\", ABSOLUTE_MS_GROUP),\n\n FormatPiece::SeperatorChar(c) => {\n\n let mut s = String::from(\"\");\n\n s.push(*c);\n", "file_path": "application/apps/indexer/processor/src/parse.rs", "rank": 85, "score": 140276.40795068798 }, { "content": "pub fn u8_to_log_level(v: u8) -> Option<LogLevel> {\n\n match v {\n\n LEVEL_FATAL => Some(LogLevel::Fatal),\n\n LEVEL_ERROR => Some(LogLevel::Error),\n\n LEVEL_WARN => Some(LogLevel::Warn),\n\n LEVEL_INFO => Some(LogLevel::Info),\n\n LEVEL_DEBUG => Some(LogLevel::Debug),\n\n LEVEL_VERBOSE => Some(LogLevel::Verbose),\n\n _ => None,\n\n }\n\n}\n\nimpl TryFrom<u8> for LogLevel {\n\n type Error = Error;\n\n fn try_from(message_info: u8) -> Result<LogLevel, Error> {\n\n let raw = message_info >> 4;\n\n let level = u8_to_log_level(raw);\n\n match level {\n\n Some(n) => Ok(n),\n\n None => Ok(LogLevel::Invalid(raw)),\n\n }\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 86, "score": 139413.47361096152 }, { "content": "pub fn process_filter_config(cfg: DltFilterConfig) -> ProcessedDltFilterConfig {\n\n ProcessedDltFilterConfig {\n\n min_log_level: cfg.min_log_level.and_then(dlt::u8_to_log_level),\n\n app_ids: cfg.app_ids.map(HashSet::from_iter),\n\n ecu_ids: cfg.ecu_ids.map(HashSet::from_iter),\n\n context_ids: cfg.context_ids.map(HashSet::from_iter),\n\n }\n\n}\n\n\n", "file_path": "application/apps/indexer/dlt/src/filtering.rs", "rank": 87, "score": 138678.26991269132 }, { "content": "fn parse_ecu_id(input: &[u8]) -> IResult<&[u8], &str> {\n\n dlt_zero_terminated_string(input, 4)\n\n}\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 88, "score": 138199.62166272444 }, { "content": "pub fn unsigned_strategy() -> impl Strategy<Value = TypeInfoKind> {\n\n (any::<TypeLength>(), any::<bool>()).prop_filter_map(\n\n \"only permit fixed point for 32 and 64 bit\",\n\n |(width, fp)| {\n\n if fp && !(width == TypeLength::BitLength32 || width == TypeLength::BitLength64) {\n\n None\n\n } else {\n\n Some(TypeInfoKind::Unsigned(width, fp))\n\n }\n\n },\n\n )\n\n}\n\n#[derive(Debug, Clone, PartialEq, Arbitrary)]\n\npub enum TypeInfoKind {\n\n Bool,\n\n #[proptest(strategy = \"signed_strategy()\")]\n\n Signed(TypeLength, bool), // FIXP\n\n #[proptest(strategy = \"unsigned_strategy()\")]\n\n Unsigned(TypeLength, bool), // FIXP\n\n Float(FloatWidth),\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 89, "score": 138195.16698514903 }, { "content": "pub fn signed_strategy() -> impl Strategy<Value = TypeInfoKind> {\n\n (any::<TypeLength>(), any::<bool>()).prop_filter_map(\n\n \"only permit fixed point for 32 and 64 bit\",\n\n |(width, fp)| {\n\n if fp && !(width == TypeLength::BitLength32 || width == TypeLength::BitLength64) {\n\n None\n\n } else {\n\n Some(TypeInfoKind::Signed(width, fp))\n\n }\n\n },\n\n )\n\n}\n", "file_path": "application/apps/indexer/dlt/src/dlt.rs", "rank": 90, "score": 138195.16698514903 }, { "content": "fn get_app_updating_tgz_path_str() -> String {\n\n let home_dir = dirs::home_dir();\n\n let downloads = format!(\n\n \"{}/.chipmunk/downloads\",\n\n home_dir.unwrap().as_path().to_str().unwrap()\n\n );\n\n let downloads_path = Path::new(&downloads);\n\n let mut maxunixts = 0;\n\n let mut target: String = String::from(\"\");\n\n for entry in downloads_path\n\n .read_dir()\n\n .expect(\"Fail read downloads folder\")\n\n {\n\n if let Ok(entry) = entry {\n\n let path_buf = entry.path();\n\n let path = Path::new(&path_buf);\n\n if let Some(ext) = path.extension() {\n\n if path.is_file() && ext == \"tgz\" {\n\n let metadata = std::fs::metadata(&path).unwrap();\n\n if let Ok(time) = metadata.modified() {\n", "file_path": "application/apps/launcher/src/main.rs", "rank": 91, "score": 137270.8225320232 }, { "content": "fn merge_files(mut cx: FunctionContext) -> JsResult<JsNumber> {\n\n let merge_config_file_name = cx.argument::<JsString>(0)?.value();\n\n let out_path = path::PathBuf::from(cx.argument::<JsString>(1)?.value().as_str());\n\n let chunk_size = cx.argument::<JsNumber>(2)?.value() as usize;\n\n let append: bool = cx.argument::<JsBoolean>(3)?.value();\n\n let stdout: bool = cx.argument::<JsBoolean>(4)?.value();\n\n let status_updates: bool = cx.argument::<JsBoolean>(5)?.value();\n\n let merger = merging::merger::Merger {\n\n chunk_size, // used for mapping line numbers to byte positions\n\n };\n\n let config_path = path::PathBuf::from(merge_config_file_name);\n\n let merged_lines = match merger.merge_files_use_config_file(\n\n &config_path,\n\n &out_path,\n\n append,\n\n stdout,\n\n status_updates,\n\n ) {\n\n Ok(cnt) => cnt,\n\n Err(e) => {\n", "file_path": "application/apps/indexer-neon/native/src/lib.rs", "rank": 92, "score": 135913.94123383582 }, { "content": "/// Trys to detect a valid timestamp in a string\n\n/// Returns the a tuple of\n\n/// * the timestamp as posix timestamp\n\n/// * if the year was missing\n\n/// (we assume the current year (local time) if true)\n\n/// * the format string that was used\n\n///\n\n/// # Arguments\n\n///\n\n/// * `input` - A string slice that should be parsed\n\nfn detect_timestamp_in_string(mut cx: FunctionContext) -> JsResult<JsNumber> {\n\n let input: String = cx.argument::<JsString>(0)?.value();\n\n match parse::detect_timestamp_in_string(input.as_str(), None) {\n\n Ok((timestamp, _, _)) => Ok(cx.number((timestamp) as f64)),\n\n Err(e) => cx.throw_type_error(format!(\"{}\", e)),\n\n }\n\n}\n", "file_path": "application/apps/indexer-neon/native/src/lib.rs", "rank": 93, "score": 134785.2871520586 }, { "content": "/// get the path of the\n\nfn get_app_path_str() -> Result<String> {\n\n let launcher = std::env::current_exe()?;\n\n let launcher_str = launcher\n\n .to_str()\n\n .ok_or_else(|| Error::new(ErrorKind::Other, \"could not convert path to string\"))?;\n\n let launcher_path = Path::new(&launcher);\n\n if cfg!(target_os = \"macos\") {\n\n let re = Regex::new(r\"chipmunk\\.app.*\").unwrap();\n\n let cropped = re.replace_all(launcher_str, \"chipmunk.app\").to_string();\n\n trace!(\"cropped: {}\", cropped);\n\n let cropped_path = Path::new(&cropped);\n\n if !cropped_path.exists() {\n\n error!(\"Fail to find application by next path: {:?}\", cropped_path);\n\n trace!(\"Closing launcher\");\n\n std::process::exit(1);\n\n }\n\n Ok(cropped)\n\n } else {\n\n let parrent_path = launcher_path\n\n .parent()\n\n .ok_or_else(|| Error::new(ErrorKind::Other, \"no parent found\"))?\n\n .to_string_lossy();\n\n if cfg!(target_os = \"windows\") {\n\n Ok(format!(\"{}\\\\app.exe\", parrent_path))\n\n } else {\n\n Ok(format!(\"{}/app\", parrent_path))\n\n }\n\n }\n\n}\n\n\n", "file_path": "application/apps/launcher/src/main.rs", "rank": 94, "score": 134098.83518798498 }, { "content": "pub fn serialize_chunks(chunks: &[Chunk], out_file_name: &std::path::Path) -> Result<()> {\n\n // Serialize it to a JSON string.\n\n let j = serde_json::to_string(chunks)?;\n\n fs::write(out_file_name, j).expect(\"Unable to write file\");\n\n Ok(())\n\n}\n\npub struct ChunkFactory {\n\n pub chunk_size: usize, // how many lines in one chunk?\n\n pub to_stdout: bool, // write chunks to stdout\n\n pub start_of_chunk_byte_index: usize,\n\n last_line_current_chunk: usize,\n\n current_byte_index: usize,\n\n lines_in_chunk: usize,\n\n}\n\n\n\nimpl ChunkFactory {\n\n pub fn new(\n\n chunk_size: usize,\n\n to_stdout: bool,\n\n start_of_chunk_byte_index: usize,\n", "file_path": "application/apps/indexer/indexer_base/src/chunks.rs", "rank": 95, "score": 126591.99801930742 }, { "content": "fn add_for_level(level: Option<dlt::LogLevel>, ids: &mut IdMap, id: String) {\n\n if let Some(n) = ids.get_mut(&id) {\n\n match level {\n\n Some(dlt::LogLevel::Fatal) => {\n\n *n = LevelDistribution {\n\n log_fatal: n.log_fatal + 1,\n\n ..*n\n\n }\n\n }\n\n Some(dlt::LogLevel::Error) => {\n\n *n = LevelDistribution {\n\n log_error: n.log_error + 1,\n\n ..*n\n\n }\n\n }\n\n Some(dlt::LogLevel::Warn) => {\n\n *n = LevelDistribution {\n\n log_warning: n.log_warning + 1,\n\n ..*n\n\n }\n", "file_path": "application/apps/indexer/dlt/src/dlt_parse.rs", "rank": 96, "score": 122553.20196669766 }, { "content": "export const CRegCarrets = /[\\n\\r]/gi;\n", "file_path": "application/electron/src/consts/regs.ts", "rank": 97, "score": 109580.10880315967 }, { "content": "export const CRegCloseCarret = /(\\r?\\n|\\r)$/gi;\n", "file_path": "application/electron/src/consts/regs.ts", "rank": 98, "score": 108270.50922178233 } ]
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_boot_info: &'static seL4_BootInfo) -> Result<(), TopLevelError> {\n\n let (mut allocator, mut device_allocator) = micro_alloc::bootstrap_allocators(&raw_boot_info)?;\n\n let (root_cnode, local_slots) = root_cnode(&raw_boot_info);\n\n let (root_vspace_slots, local_slots): (LocalCNodeSlots<U100>, _) = local_slots.alloc();\n\n let BootInfo {\n\n mut root_vspace,\n\n asid_control,\n\n user_image,\n\n root_tcb,\n\n mut irq_control,\n\n ..\n\n } = BootInfo::wrap(\n\n &raw_boot_info,\n\n allocator\n\n .get_untyped::<U13>()\n\n .expect(\"Initial untyped retrieval failure\"),\n\n root_vspace_slots,\n\n );\n\n let uts = alloc::ut_buddy(\n\n allocator\n", "file_path": "qemu-test/test-project/root-task/src/uart.rs", "rank": 3, "score": 210133.85784221452 }, { "content": "#[test]\n\nfn single_resource() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(10);\n\n\n\n smart_alloc!(|slot_please: cslots| {\n\n slot_please;\n\n let gamma = consume_slot(slot_please);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(8, cslots.capacity);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 4, "score": 205174.31484958142 }, { "content": "#[cfg(test_case = \"uart\")]\n\npub fn run(raw_boot_info: &'static selfe_sys::seL4_BootInfo) {\n\n uart::run(raw_boot_info).expect(\"run\");\n\n unsafe {\n\n loop {\n\n selfe_sys::seL4_Yield();\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum TopLevelError {\n\n AllocError(AllocError),\n\n IPCError(IPCError),\n\n MultiConsumerError(MultiConsumerError),\n\n VSpaceError(VSpaceError),\n\n SeL4Error(SeL4Error),\n\n IRQError(IRQError),\n\n FaultManagementError(FaultManagementError),\n\n ProcessSetupError(ProcessSetupError),\n\n ThreadSetupError(ThreadSetupError),\n", "file_path": "qemu-test/test-project/root-task/src/main.rs", "rank": 5, "score": 200581.16722892458 }, { "content": "#[test]\n\nfn single_resources_nested() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(10);\n\n\n\n smart_alloc!(|outer_slot_please: cslots| {\n\n outer_slot_please;\n\n let gamma = consume_slot(outer_slot_please);\n\n let cslots_inner = CNodeSlots::new(5);\n\n smart_alloc! {|inner_slot_please: cslots_inner| {\n\n let delta = inner_slot_please;\n\n let epsilon = consume_slot(inner_slot_please);\n\n let alpha = 3;\n\n let psi = consume_slot(outer_slot_please);\n\n }};\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(7, cslots.capacity);\n\n assert_eq!(1, delta.capacity);\n\n assert_eq!(1, epsilon);\n\n assert_eq!(1, psi);\n\n assert_eq!(3, cslots_inner.capacity);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 6, "score": 200099.8091535678 }, { "content": "#[test]\n\nfn single_resource_kinded() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(10);\n\n\n\n smart_alloc!(|slot_please: cslots<CNodeSlots>| {\n\n slot_please;\n\n let gamma = consume_slot(slot_please);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(8, cslots.capacity);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 7, "score": 200099.8091535678 }, { "content": "#[test]\n\nfn single_resources_deeply_nested() -> Result<(), ()> {\n\n let cslots_crust = CNodeSlots::new(5);\n\n let cslots_mantle = CNodeSlots::new(5);\n\n let cslots_core = CNodeSlots::new(5);\n\n\n\n smart_alloc!(|crust: cslots_crust| {\n\n let beta = crust;\n\n // Note that by some quirk, curly brackets\n\n // are necessary for nested invocations to be\n\n // able to access resources declared in higher scopes.\n\n //\n\n // By some other quirk, rustfmt doesn't work with\n\n // curly bracket based macro invocation, so weigh\n\n // your choice wisely.\n\n smart_alloc! {|mantle: cslots_mantle| {\n\n let gamma = crust;\n\n let delta = mantle;\n\n smart_alloc!{|core: cslots_core| {\n\n let epsilon = crust;\n\n let zeta = mantle;\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 8, "score": 195356.78067814524 }, { "content": "#[test]\n\nfn two_resources_second_kinded() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(5);\n\n let untypeds = UntypedBuddy::new(5);\n\n\n\n smart_alloc!(|c: cslots, u: untypeds<UntypedBuddy>| {\n\n c;\n\n let gamma = consume_slot(c);\n\n let eta = consume_untyped(u);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(2, cslots.capacity);\n\n assert_eq!(4, untypeds.capacity);\n\n assert_eq!(1, eta);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 9, "score": 195356.78067814524 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_result_ok() -> Result<(), ()> {\n\n Ok(())\n\n}\n\n\n", "file_path": "ferros-test/examples/minimal/src/main.rs", "rank": 10, "score": 195241.9152984092 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_result_ok() -> Result<(), ()> {\n\n Ok(())\n\n}\n\n\n", "file_path": "ferros-test/examples/mock/src/lib.rs", "rank": 11, "score": 195241.9152984092 }, { "content": "/// Parse \"U5\" into `5usize`\n\nfn parse_typenum_unsigned(ident: &Ident) -> Result<usize, ParseError> {\n\n let err_fn = || {\n\n ParseError::InvalidArgumentType {\n\n msg: \"Could not parse type argument as a typenum unsigned type-level literal (e.g. U5, U1024)\".to_string(),\n\n span: ident.span(),\n\n }\n\n };\n\n let mut s = ident.to_string();\n\n if s.len() < 2 {\n\n return Err(err_fn());\n\n }\n\n let unsigned = s.split_off(1);\n\n if &s != \"U\" {\n\n return Err(err_fn());\n\n }\n\n unsigned.parse().map_err(|_e| err_fn())\n\n}\n\n\n\nimpl UserTestFnOutput {\n\n fn parse(return_type: &ReturnType) -> Result<Self, ParseError> {\n", "file_path": "ferros-test/test-macro-impl/src/parse.rs", "rank": 12, "score": 194328.53295207085 }, { "content": "#[ferros_test::ferros_test]\n\npub fn self_hosted_mem_mgmt(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_cnode, child_slots) = retype_cnode::<U14>(ut, slots)?;\n\n\n\n let ut12: LocalCap<Untyped<U12>> = ut;\n\n\n\n smart_alloc! {|slots_c: child_slots| {\n\n let cap_transfer_slots: LocalCap<CNodeSlotsData<U1024, role::Child>> = slots_c;\n\n let (cnode_for_child, slots_for_child):(_, ChildCap<CNodeSlotsData<U2048, role::Child>>) =\n\n child_cnode.generate_self_reference(&root_cnode, slots_c)?;\n", "file_path": "qemu-test/test-project/root-task/src/self_hosted_mem_mgmt.rs", "rank": 13, "score": 191810.83816727716 }, { "content": "#[test]\n\nfn two_resources_second_kinded_unordered() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(5);\n\n let untypeds = UntypedBuddy::new(5);\n\n\n\n smart_alloc!(|u: untypeds, c: cslots<CNodeSlots>| {\n\n c;\n\n let gamma = consume_slot(c);\n\n let eta = consume_untyped(u);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(2, cslots.capacity);\n\n assert_eq!(4, untypeds.capacity);\n\n assert_eq!(1, eta);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 14, "score": 190913.77750771187 }, { "content": "pub trait TestReporter {\n\n fn report(&mut self, test_name: &'static str, outcome: TestOutcome);\n\n\n\n fn summary(&mut self, passed: u32, failed: u32);\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum TestSetupError {\n\n InitialUntypedNotFound { bit_size: usize },\n\n AllocError(AllocError),\n\n SeL4Error(SeL4Error),\n\n VSpaceError(VSpaceError),\n\n}\n\n\n\nimpl From<AllocError> for TestSetupError {\n\n fn from(e: AllocError) -> Self {\n\n TestSetupError::AllocError(e)\n\n }\n\n}\n\n\n", "file_path": "src/test_support/types.rs", "rank": 15, "score": 189765.2952408142 }, { "content": "#[test]\n\nfn two_resources_custom_request_id_both_kinded() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(5);\n\n let untypeds = UntypedBuddy::new(5);\n\n\n\n smart_alloc!(|c: cslots<CNodeSlots>, u: untypeds<UntypedBuddy>| {\n\n c;\n\n let gamma = consume_slot(c);\n\n let eta = consume_untyped(u);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(2, cslots.capacity);\n\n assert_eq!(4, untypeds.capacity);\n\n assert_eq!(1, eta);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 16, "score": 186743.20478419852 }, { "content": "#[test]\n\nfn two_resources_custom_request_id_unkinded() -> Result<(), ()> {\n\n let alpha = 1;\n\n let cslots = CNodeSlots::new(5);\n\n let untypeds = UntypedBuddy::new(5);\n\n\n\n smart_alloc!(|s: cslots, u: untypeds| {\n\n let alpha_prime = alpha;\n\n s;\n\n let gamma = consume_slot(s);\n\n let eta = consume_untyped(u);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(1, alpha_prime);\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(2, cslots.capacity);\n\n assert_eq!(4, untypeds.capacity);\n\n assert_eq!(1, eta);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 17, "score": 186743.20478419852 }, { "content": "#[ferros_test::ferros_test]\n\npub fn stack_setup() -> Result<(), super::TopLevelError> {\n\n match test_stack_setup() {\n\n Ok(_) => Ok(()),\n\n Err(e) => {\n\n debug_println!(\"{:?}\", e);\n\n Err(super::TopLevelError::TestAssertionFailure(\n\n \"stack setup trouble\",\n\n ))\n\n }\n\n }\n\n}\n", "file_path": "qemu-test/test-project/root-task/src/stack_setup.rs", "rank": 18, "score": 186687.98327284385 }, { "content": "#[test]\n\nfn two_resources_custom_request_id_first_kinded() -> Result<(), ()> {\n\n let cslots = CNodeSlots::new(5);\n\n let untypeds = UntypedBuddy::new(5);\n\n\n\n smart_alloc!(|slot_please: cslots<CNodeSlots>, ut_please: untypeds| {\n\n slot_please;\n\n let gamma = consume_slot(slot_please);\n\n let eta = consume_untyped(ut_please);\n\n let alpha = 3;\n\n });\n\n\n\n assert_eq!(3, alpha);\n\n assert_eq!(1, gamma);\n\n assert_eq!(2, cslots.capacity);\n\n assert_eq!(4, untypeds.capacity);\n\n assert_eq!(1, eta);\n\n Ok(())\n\n}\n\n\n", "file_path": "smart_alloc/tests/integration.rs", "rank": 19, "score": 182820.75103935075 }, { "content": "#[ferros_test::ferros_test]\n\npub fn root_task_runs() -> Result<(), super::TopLevelError> {\n\n Ok(())\n\n}\n", "file_path": "qemu-test/test-project/root-task/src/root_task_runs.rs", "rank": 20, "score": 181147.2068733928 }, { "content": "fn extract_expected_resources<'a>(\n\n args: impl IntoIterator<Item = &'a FnArg>,\n\n) -> Result<Vec<Param>, ParseError> {\n\n args.into_iter().map(Param::parse).collect()\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/parse.rs", "rank": 21, "score": 173088.63824436965 }, { "content": "fn validate_param_collection(params: &[Param]) -> Result<(), ParseError> {\n\n let mut scratch_count = 0;\n\n let mut irq_control_count = 0;\n\n for p in params {\n\n match p.kind {\n\n ParamKind::VSpaceScratch => {\n\n scratch_count += 1;\n\n if scratch_count > 1 {\n\n return Err(ParseError::ArgumentConstraint {\n\n msg: \"Only a single scratch argument may be specified.\",\n\n span: p.original_ident.span(),\n\n });\n\n }\n\n }\n\n ParamKind::IRQControl => {\n\n irq_control_count += 1;\n\n if irq_control_count > 1 {\n\n return Err(ParseError::ArgumentConstraint {\n\n msg: \"Only a single IRQControl argument may be specified.\",\n\n span: p.original_ident.span(),\n", "file_path": "ferros-test/test-macro-impl/src/parse.rs", "rank": 22, "score": 171435.2810423977 }, { "content": "fn gensym(name_hint: &'static str) -> Ident {\n\n let id = IDENT_ID.fetch_add(1, Ordering::SeqCst);\n\n syn::Ident::new(\n\n &format!(\"__smart_alloc_{}_{}\", name_hint, id),\n\n Span::call_site(),\n\n )\n\n}\n\n\n\nimpl Fold for IdTracker {\n\n fn fold_block(&mut self, i: Block) -> Block {\n\n let brace_token = i.brace_token;\n\n let visitor = self;\n\n let expand = |st: Stmt| -> Vec<Stmt> {\n\n match st {\n\n s @ Stmt::Local(_) => vec![visitor.fold_stmt(s)],\n\n s @ Stmt::Expr(_) => vec![visitor.fold_stmt(s)],\n\n s @ Stmt::Semi(_, _) => vec![visitor.fold_stmt(s)],\n\n Stmt::Item(i) => {\n\n if let SynItem::Macro(item_macro) = i {\n\n // Manually invoke nested smart_alloc invocations\n", "file_path": "smart_alloc/src/lib.rs", "rank": 23, "score": 168623.13251520367 }, { "content": "#[ferros_test::ferros_test]\n\npub fn wutbuddy(\n\n local_slots: LocalCNodeSlots<U64>,\n\n local_ut: LocalCap<Untyped<U13>>,\n\n) -> Result<(), TopLevelError> {\n\n let mut wut = weak_ut_buddy(local_ut.weaken());\n\n let (strong_slot, local_slots) = local_slots.alloc();\n\n let mut weak_slots = local_slots.weaken();\n\n let weak_12 = wut.alloc(&mut weak_slots, 12)?;\n\n\n\n // Did we get a thing of the right size?\n\n assert_eq!(weak_12.size_bits(), 12);\n\n\n\n // Can we actually use it as that size?\n\n let _ = weak_12.retype::<Page<page_state::Unmapped>>(&mut weak_slots)?;\n\n\n\n let ut12 = wut.alloc_strong::<U12>(&mut weak_slots)?;\n\n\n\n // Same story with the strong untyped.\n\n let _ = ut12.retype::<Page<page_state::Unmapped>, role::Local>(strong_slot)?;\n\n Ok(())\n\n}\n", "file_path": "qemu-test/test-project/root-task/src/wutbuddy.rs", "rank": 24, "score": 166419.10051994954 }, { "content": "pub fn yield_forever() -> ! {\n\n unsafe {\n\n loop {\n\n seL4_Yield();\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum ProcessSetupError {\n\n ProcessParameterTooBigForStack,\n\n ProcessParameterHandoffSizeMismatch,\n\n NotEnoughCNodeSlots,\n\n ParentMappedMemoryRegionASIDShouldNotMatchChildVSpaceASID,\n\n VSpaceError(VSpaceError),\n\n SeL4Error(SeL4Error),\n\n ElfParseError(&'static str),\n\n}\n\n\n\nimpl From<VSpaceError> for ProcessSetupError {\n", "file_path": "src/userland/process/mod.rs", "rank": 25, "score": 166261.0985832638 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_result_err() -> Result<(), ()> {\n\n Err(())\n\n}\n\n\n", "file_path": "ferros-test/examples/mock/src/lib.rs", "rank": 26, "score": 162742.29890931342 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_result_err() -> Result<(), ()> {\n\n Err(())\n\n}\n\n\n", "file_path": "ferros-test/examples/minimal/src/main.rs", "rank": 27, "score": 162742.29890931342 }, { "content": "#[proc_macro_attribute]\n\npub fn ferros_test(attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let syn_content = match SynContent::parse(attr.into(), item.into()) {\n\n Ok(c) => c,\n\n Err(e) => return e.to_compile_error().into(),\n\n };\n\n let model = match TestModel::parse(syn_content) {\n\n Ok(m) => m,\n\n Err(e) => return e.to_compile_error().into(),\n\n };\n\n model\n\n .generate_runnable_test(codegen::UuidGenerator::default())\n\n .into_token_stream()\n\n .into()\n\n}\n", "file_path": "ferros-test/test-macro-impl/src/lib.rs", "rank": 28, "score": 162387.30696227282 }, { "content": "/// Pause duration field when sending pause frames\n\ntype PauseDuration = U32;\n\n\n", "file_path": "examples/system/imx6-hal/src/enet/mod.rs", "rank": 29, "score": 162261.183192607 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_testoutcome_success() -> TestOutcome {\n\n TestOutcome::Success\n\n}\n\n\n", "file_path": "ferros-test/examples/mock/src/lib.rs", "rank": 30, "score": 161751.24850634416 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_testoutcome_success() -> TestOutcome {\n\n TestOutcome::Success\n\n}\n\n\n", "file_path": "ferros-test/examples/minimal/src/main.rs", "rank": 31, "score": 161751.24850634416 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_testoutcome_failure() -> TestOutcome {\n\n TestOutcome::Failure\n\n}\n\n\n", "file_path": "ferros-test/examples/mock/src/lib.rs", "rank": 32, "score": 161751.24850634416 }, { "content": "#[ferros_test]\n\nfn zero_parameters_returns_testoutcome_failure() -> TestOutcome {\n\n TestOutcome::Failure\n\n}\n\n\n", "file_path": "ferros-test/examples/minimal/src/main.rs", "rank": 33, "score": 161751.24850634416 }, { "content": "fn run(raw_bootinfo: &'static selfe_sys::seL4_BootInfo) -> Result<(), TopLevelError> {\n\n log::set_logger(&LOGGER).map(|()| log::set_max_level(DebugLogger::max_log_level_from_env()))?;\n\n log::debug!(\n\n \"[root-task] Initializing version={} profile={}\",\n\n built_info::PKG_VERSION,\n\n built_info::PROFILE,\n\n );\n\n\n\n let (allocator, mut dev_allocator) = micro_alloc::bootstrap_allocators(raw_bootinfo)?;\n\n let mut allocator = WUTBuddy::from(allocator);\n\n\n\n let (root_cnode, local_slots) = root_cnode(raw_bootinfo);\n\n let (root_vspace_slots, local_slots): (LocalCNodeSlots<U100>, _) = local_slots.alloc();\n\n let (ut_slots, local_slots): (LocalCNodeSlots<U100>, _) = local_slots.alloc();\n\n let mut ut_slots = ut_slots.weaken();\n\n\n\n let BootInfo {\n\n mut root_vspace,\n\n asid_control,\n\n user_image,\n", "file_path": "examples/system/root-task/src/main.rs", "rank": 34, "score": 160892.51660377547 }, { "content": "fn run(raw_bootinfo: &'static selfe_sys::seL4_BootInfo) -> Result<(), TopLevelError> {\n\n let (allocator, mut dev_allocator) = micro_alloc::bootstrap_allocators(&raw_bootinfo)?;\n\n let mut allocator = WUTBuddy::from(allocator);\n\n\n\n let (root_cnode, local_slots) = root_cnode(&raw_bootinfo);\n\n let (root_vspace_slots, local_slots): (LocalCNodeSlots<U100>, _) = local_slots.alloc();\n\n let (ut_slots, local_slots): (LocalCNodeSlots<U100>, _) = local_slots.alloc();\n\n let mut ut_slots = ut_slots.weaken();\n\n\n\n let BootInfo {\n\n mut root_vspace,\n\n asid_control,\n\n user_image,\n\n root_tcb,\n\n ..\n\n } = BootInfo::wrap(\n\n &raw_bootinfo,\n\n allocator.alloc_strong::<U16>(&mut ut_slots)?,\n\n root_vspace_slots,\n\n );\n", "file_path": "examples/simple/root-task/src/main.rs", "rank": 35, "score": 160892.51660377547 }, { "content": "/// Given PathArguments like `<a::b::T<Foo>, U, V>`, extracts `T<Foo>`\n\nfn extract_first_arg_type_path_last_segment(\n\n arguments: &PathArguments,\n\n) -> Result<&PathSegment, ParseError> {\n\n const EXPECTED: &str =\n\n \"Expected a ferros type argument (e.g. `Unsigned<U5>`, `ASIDPool<U1024>`)\";\n\n if let PathArguments::AngleBracketed(abga) = arguments {\n\n let gen_arg = abga\n\n .args\n\n .first()\n\n .ok_or_else(|| ParseError::InvalidArgumentType {\n\n msg: \"test function argument's generic parameter must not be empty\".to_string(),\n\n span: abga.span(),\n\n })?\n\n .into_value();\n\n if let GenericArgument::Type(Type::Path(type_path)) = gen_arg {\n\n Ok(type_path\n\n .path\n\n .segments\n\n .last()\n\n .ok_or_else(|| ParseError::InvalidArgumentType {\n", "file_path": "ferros-test/test-macro-impl/src/parse.rs", "rank": 36, "score": 160787.83937821692 }, { "content": "#[ferros_test::ferros_test]\n\npub fn polling_consumer(\n\n local_slots: LocalCNodeSlots<U66536>,\n\n local_ut: LocalCap<Untyped<U27>>,\n\n asid_pool: LocalCap<ASIDPool<U4>>,\n\n local_mapped_region: MappedMemoryRegion<U19, shared_status::Exclusive>,\n\n local_vspace_scratch: &mut ScratchRegion,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (consumer_asid, asid_pool) = asid_pool.alloc();\n\n let (producer_asid, asid_pool) = asid_pool.alloc();\n\n\n\n let (consumer_cnode, consumer_slots) = retype_cnode::<U12>(ut, slots)?;\n\n let (producer_cnode, producer_slots) = retype_cnode::<U12>(ut, slots)?;\n\n\n\n // vspace setup\n", "file_path": "qemu-test/test-project/root-task/src/polling_consumer.rs", "rank": 37, "score": 160517.5229645123 }, { "content": "#[ferros_test::ferros_test]\n\npub fn fault_pair(\n\n local_slots: LocalCNodeSlots<U33768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U2>>,\n\n local_mapped_region: MappedMemoryRegion<U18, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (mischief_maker_asid, asid_pool) = asid_pool.alloc();\n\n let mischief_maker_root = retype(ut, slots)?;\n\n let mischief_maker_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let mischief_maker_vspace_ut: LocalCap<Untyped<U15>> = ut;\n\n let mut mischief_maker_vspace = VSpace::new(\n\n mischief_maker_root,\n\n mischief_maker_asid,\n\n mischief_maker_vspace_slots.weaken(),\n", "file_path": "qemu-test/test-project/root-task/src/fault_pair.rs", "rank": 38, "score": 160517.5229645123 }, { "content": "#[ferros_test::ferros_test]\n\npub fn reuse_slots(\n\n local_slots: LocalCNodeSlots<U100>,\n\n ut_20: LocalCap<Untyped<U20>>,\n\n) -> Result<(), TopLevelError> {\n\n let (slots, local_slots) = local_slots.alloc();\n\n let (ut_a, ut_b, ut_c, ut_18) = ut_20.quarter(slots)?;\n\n let (slots, mut local_slots) = local_slots.alloc();\n\n let (ut_d, ut_e, ut_f, _ut_g) = ut_18.quarter(slots)?;\n\n\n\n let track = core::cell::Cell::new(0);\n\n let track_ref = &track;\n\n\n\n // TODO - check correct reuse following inner error\n\n local_slots.with_temporary(move |inner_slots| -> Result<(), SeL4Error> {\n\n let (slots, _inner_slots) = inner_slots.alloc();\n\n let (_a, _b) = ut_a.split(slots)?;\n\n track_ref.set(track_ref.get() + 1);\n\n Ok(())\n\n })??;\n\n\n", "file_path": "qemu-test/test-project/root-task/src/reuse_slots.rs", "rank": 39, "score": 160517.5229645123 }, { "content": "#[ferros_test::ferros_test]\n\npub fn reuse_untyped(\n\n mut prime_ut: LocalCap<Untyped<U27>>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n slot_a: LocalCNodeSlots<U2>,\n\n slot_b: LocalCNodeSlots<U2>,\n\n slot_c: LocalCNodeSlots<U2>,\n\n slot_d: LocalCNodeSlots<U2>,\n\n slot_e: LocalCNodeSlots<U2>,\n\n slot_f: LocalCNodeSlots<U2>,\n\n slot_g: LocalCNodeSlots<U2>,\n\n) -> Result<(), TopLevelError> {\n\n let track = core::cell::Cell::new(0);\n\n let track_ref = &track;\n\n // TODO - check correct reuse following inner error\n\n\n\n prime_ut.with_temporary(&root_cnode, move |inner_ut| -> Result<(), SeL4Error> {\n\n let (_a, _b) = inner_ut.split(slot_a)?;\n\n track_ref.set(track_ref.get() + 1);\n\n Ok(())\n\n })??;\n", "file_path": "qemu-test/test-project/root-task/src/reuse_untyped.rs", "rank": 40, "score": 160517.5229645123 }, { "content": "fn call_fn_under_test(\n\n fn_under_test_ident: Ident,\n\n fn_under_test_output: UserTestFnOutput,\n\n param_ids: impl Iterator<Item = Ident>,\n\n) -> Block {\n\n let mut args = syn::punctuated::Punctuated::new();\n\n for id in param_ids {\n\n args.push(Expr::Path(single_segment_exprpath(id)))\n\n }\n\n let call = ExprCall {\n\n attrs: Vec::new(),\n\n func: Box::new(Expr::Path(single_segment_exprpath(fn_under_test_ident))),\n\n paren_token: syn::token::Paren::default(),\n\n args,\n\n };\n\n match fn_under_test_output {\n\n UserTestFnOutput::Unit => parse_quote! { {\n\n #call;\n\n ferros::test_support::TestOutcome::Success\n\n } },\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 41, "score": 159498.23096592058 }, { "content": "/// Meant to take PathArguments like <typenum::U5> and turn it into 5usize\n\nfn extract_first_argument_as_unsigned(arguments: &PathArguments) -> Result<usize, ParseError> {\n\n let segment = extract_first_arg_type_path_last_segment(arguments)?;\n\n parse_typenum_unsigned(&segment.ident)\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/parse.rs", "rank": 42, "score": 159478.29505465578 }, { "content": "#[ferros_test::ferros_test]\n\npub fn fault_or_message_handler(\n\n mut outer_slots: LocalCNodeSlots<U32768>,\n\n mut outer_ut: LocalCap<Untyped<U21>>,\n\n mut asid_pool: LocalCap<ASIDPool<U512>>,\n\n mut irq_control: LocalCap<IRQControl>,\n\n mut local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n for c in [\n\n Command::ReportTrue,\n\n Command::ReportFalse,\n\n Command::ThrowFault,\n\n Command::ReportTrue,\n\n Command::ThrowFault,\n\n Command::ReportFalse,\n\n ]\n\n .iter()\n\n .cycle()\n", "file_path": "qemu-test/test-project/root-task/src/fault_or_message_handler.rs", "rank": 43, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn shared_page_queue(\n\n local_slots: LocalCNodeSlots<U33768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U2>>,\n\n local_mapped_region: MappedMemoryRegion<U18, shared_status::Exclusive>,\n\n local_vspace_scratch: &mut ScratchRegion,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_a_asid, asid_pool) = asid_pool.alloc();\n\n let (child_b_asid, _asid_pool) = asid_pool.alloc();\n\n\n\n let consumer_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let consumer_vspace_ut: LocalCap<Untyped<U15>> = ut;\n\n let mut consumer_vspace = VSpace::new(\n\n retype(ut, slots)?,\n", "file_path": "qemu-test/test-project/root-task/src/shared_page_queue.rs", "rank": 44, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn grandkid_process_runs(\n\n local_slots: LocalCNodeSlots<U33768>,\n\n local_ut: LocalCap<Untyped<U27>>,\n\n asid_pool: LocalCap<ASIDPool<U6>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_cnode, child_slots) = retype_cnode::<U20>(ut, slots)?;\n\n\n\n let (child_asid, asid_pool) = asid_pool.alloc();\n\n let child_root = retype(ut, slots)?;\n\n let child_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n // NOTE: this needs to be big enough to map in entire root task. That\n\n // could grow if you add more tests elsewhere.\n\n let child_vspace_ut: LocalCap<Untyped<U16>> = ut;\n", "file_path": "qemu-test/test-project/root-task/src/grandkid_process_runs.rs", "rank": 45, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn elf_process_runs(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n stack_mem: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n mut local_vspace_scratch: &mut ScratchRegion,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n let archive_slice: &[u8] = unsafe {\n\n core::slice::from_raw_parts(\n\n &crate::_selfe_arc_data_start,\n\n &crate::_selfe_arc_data_end as *const _ as usize\n\n - &crate::_selfe_arc_data_start as *const _ as usize,\n\n )\n\n };\n\n\n", "file_path": "qemu-test/test-project/root-task/src/elf_process_runs.rs", "rank": 46, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn child_process_runs(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_cnode, child_slots) = retype_cnode::<U12>(ut, slots)?;\n\n let (child_fault_source_slot, _child_slots) = child_slots.alloc();\n\n let (fault_source, outcome_sender, handler) =\n\n fault_or_message_channel(&root_cnode, ut, slots, child_fault_source_slot, slots)?;\n\n let params = ProcParams {\n\n value: 42,\n\n outcome_sender,\n\n };\n", "file_path": "qemu-test/test-project/root-task/src/child_process_runs.rs", "rank": 47, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn irq_control_manipulation(\n\n cnode_slots: LocalCNodeSlots<U24>,\n\n weak_slots: LocalCNodeSlots<U24>,\n\n mut irq_control: LocalCap<IRQControl>,\n\n) -> Result<(), super::TopLevelError> {\n\n const TOP_LEVEL_CLAIM: u16 = 20;\n\n const COLLECTION_CLAIM_A: u16 = 30;\n\n const COLLECTION_CLAIM_B: u16 = 50;\n\n const NEVER_HANDLED: u16 = 70;\n\n let mut weak_slots = weak_slots.weaken();\n\n smart_alloc! { |slots: cnode_slots<CNodeSlots>| {\n\n\n\n if let Ok(_) = irq_control.create_weak_handler(slots, MaxIRQCount::U16) {\n\n return Err(TopLevelError::TestAssertionFailure(\"Should not be able to make an IRQ handler >= the declared max count\"));\n\n }\n\n if let Err(_) = irq_control.create_weak_handler(slots, TOP_LEVEL_CLAIM) {\n\n return Err(TopLevelError::TestAssertionFailure(\"Should be able to make a handler for an unclaimed IRQ\"));\n\n }\n\n if let Ok(_) = irq_control.create_weak_handler(slots, TOP_LEVEL_CLAIM) {\n\n return Err(TopLevelError::TestAssertionFailure(\"Should not be able to make a handler for a previous claimed IRQ\"));\n", "file_path": "qemu-test/test-project/root-task/src/irq_control_manipulation.rs", "rank": 48, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn call_and_response_loop(\n\n local_slots: LocalCNodeSlots<U33768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U2>>,\n\n local_mapped_region: MappedMemoryRegion<U18, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (caller_asid, asid_pool) = asid_pool.alloc();\n\n let (responder_asid, _asid_pool) = asid_pool.alloc();\n\n let caller_root = retype(ut, slots)?;\n\n let caller_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let caller_vspace_ut: LocalCap<Untyped<U15>> = ut;\n\n\n\n let mut caller_vspace = VSpace::new(\n\n caller_root,\n", "file_path": "qemu-test/test-project/root-task/src/call_and_response_loop.rs", "rank": 49, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn double_door_backpressure(\n\n local_slots: LocalCNodeSlots<U66536>,\n\n local_ut: LocalCap<Untyped<U27>>,\n\n asid_pool: LocalCap<ASIDPool<U4>>,\n\n local_mapped_region: MappedMemoryRegion<U19, shared_status::Exclusive>,\n\n local_vspace_scratch: &mut ScratchRegion,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (consumer_asid, asid_pool) = asid_pool.alloc();\n\n let (producer_a_asid, asid_pool) = asid_pool.alloc();\n\n let (producer_b_asid, asid_pool) = asid_pool.alloc();\n\n let (waker_asid, _asid_pool) = asid_pool.alloc();\n\n\n\n let (consumer_cnode, consumer_slots) = retype_cnode::<U12>(ut, slots)?;\n\n let (producer_a_cnode, producer_a_slots) = retype_cnode::<U12>(ut, slots)?;\n", "file_path": "qemu-test/test-project/root-task/src/double_door_backpressure.rs", "rank": 50, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn memory_read_protection(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_asid, _asid_pool) = asid_pool.alloc();\n\n let child_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let child_vspace_ut: LocalCap<Untyped<U15>> = ut;\n\n let mut child_vspace = VSpace::new(\n\n retype(ut, slots)?,\n\n child_asid,\n\n child_vspace_slots.weaken(),\n\n child_vspace_ut.weaken(),\n", "file_path": "qemu-test/test-project/root-task/src/memory_read_protection.rs", "rank": 51, "score": 155217.23696541018 }, { "content": "#[ferros_test::ferros_test]\n\npub fn child_thread_runs(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n stack_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n ipc_buffer_region: MappedMemoryRegion<U12, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n vspace_paging_root: &LocalCap<ferros::arch::PagingRoot>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_cnode, child_slots) = retype_cnode::<U12>(ut, slots)?;\n\n let (child_fault_source_slot, _child_slots) = child_slots.alloc();\n\n let (fault_source, outcome_sender, handler) =\n\n fault_or_message_channel(&root_cnode, ut, slots, child_fault_source_slot, slots)?;\n\n let params = ProcParams {\n\n value: 42,\n", "file_path": "qemu-test/test-project/root-task/src/child_thread_runs.rs", "rank": 52, "score": 155217.23696541018 }, { "content": "fn run_test_decl() -> FnDecl {\n\n let mut run_test_inputs = syn::punctuated::Punctuated::new();\n\n run_test_inputs.push(parse_quote!(\n\n slots: ferros::cap::LocalCNodeSlots<ferros::test_support::MaxTestCNodeSlots>\n\n ));\n\n run_test_inputs.push(parse_quote!(\n\n untyped:\n\n ferros::cap::LocalCap<ferros::cap::Untyped<ferros::test_support::MaxTestUntypedSize>>\n\n ));\n\n run_test_inputs.push(parse_quote!(\n\n asid_pool:\n\n ferros::cap::LocalCap<ferros::cap::ASIDPool<ferros::test_support::MaxTestASIDPoolSize>>\n\n ));\n\n run_test_inputs.push(parse_quote!(scratch: &mut ferros::vspace::ScratchRegion));\n\n run_test_inputs.push(parse_quote!(\n\n mapped_memory_region:\n\n ferros::vspace::MappedMemoryRegion<\n\n ferros::test_support::MaxMappedMemoryRegionBitSize,\n\n ferros::vspace::shared_status::Exclusive,\n\n >\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 53, "score": 151132.26284211758 }, { "content": "#[ferros_test::ferros_test]\n\npub fn child_process_cap_management(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_asid, _asid_pool) = asid_pool.alloc();\n\n let (child_cnode, child_slots) = retype_cnode::<U12>(ut, slots)?;\n\n\n\n let ut5: LocalCap<Untyped<U5>> = ut;\n\n\n\n let child_root = retype(ut, slots)?;\n\n let child_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let child_vspace_ut: LocalCap<Untyped<U15>> = ut;\n", "file_path": "qemu-test/test-project/root-task/src/child_process_cap_management.rs", "rank": 54, "score": 150428.9630032832 }, { "content": "#[cfg(feature = \"sel4_start_main\")]\n\n#[doc(hidden)]\n\npub fn sel4_start_main(tests: &[&ferros::test_support::RunTest]) {\n\n let raw_boot_info = unsafe { &*selfe_start::BOOTINFO };\n\n let allocator = ferros::alloc::micro_alloc::Allocator::bootstrap(raw_boot_info)\n\n .expect(\"Test allocator setup failure\");\n\n let (mut resources, reporter) =\n\n ferros::test_support::Resources::with_debug_reporting(raw_boot_info, allocator)\n\n .expect(\"Test resource setup failure\");\n\n\n\n ferros::test_support::execute_tests(reporter, resources.as_mut_ref(), tests)\n\n .expect(\"Test execution failure\");\n\n\n\n let suspend_error =\n\n unsafe { ::selfe_sys::seL4_TCB_Suspend(::selfe_sys::seL4_CapInitThreadTCB as usize) };\n\n if suspend_error != 0 {\n\n use core::fmt::Write;\n\n writeln!(\n\n selfe_start::DebugOutHandle,\n\n \"Error suspending root task thread: {}\",\n\n suspend_error\n\n )\n", "file_path": "ferros-test/src/lib.rs", "rank": 55, "score": 150411.91355086202 }, { "content": "#[ferros_test::ferros_test]\n\npub fn dont_tread_on_me<'a, 'b, 'c>(\n\n local_slots: LocalCNodeSlots<U42768>,\n\n local_ut: LocalCap<Untyped<U27>>,\n\n asid_pool: LocalCap<ASIDPool<U2>>,\n\n local_mapped_region: MappedMemoryRegion<U18, shared_status::Exclusive>,\n\n mut local_vspace_scratch: &mut ScratchRegion,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (proc1_cspace, proc1_slots) = retype_cnode::<U8>(ut, slots)?;\n\n let (proc2_cspace, proc2_slots) = retype_cnode::<U8>(ut, slots)?;\n\n });\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (proc1_asid, asid_pool) = asid_pool.alloc();\n\n let (proc2_asid, _asid_pool) = asid_pool.alloc();\n\n\n", "file_path": "qemu-test/test-project/root-task/src/dont_tread_on_me.rs", "rank": 56, "score": 148180.57528661942 }, { "content": "fn macro_name_matches(item_macro: &ItemMacro, target: &'static str) -> bool {\n\n if let Some(end) = item_macro.mac.path.segments.last() {\n\n end.value().ident == Ident::new(target, Span::call_site())\n\n } else {\n\n false\n\n }\n\n}\n", "file_path": "smart_alloc/src/lib.rs", "rank": 57, "score": 145790.9982740456 }, { "content": "pub trait CapType {}\n\n\n\npub type LocalCap<T> = Cap<T, role::Local>;\n\npub type ChildCap<T> = Cap<T, role::Child>;\n\n\n\nimpl<CT: CapType, Role: CNodeRole> Cap<CT, Role>\n\nwhere\n\n CT: PhantomCap,\n\n{\n\n // TODO most of this should only happen in the bootstrap adapter\n\n // TODO - Make even more private!\n\n pub(crate) fn wrap_cptr(cptr: usize) -> Cap<CT, Role> {\n\n Cap {\n\n cptr,\n\n cap_data: PhantomCap::phantom_instance(),\n\n _role: PhantomData,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/cap/mod.rs", "rank": 58, "score": 145306.5150912839 }, { "content": "#[ferros_test::ferros_test]\n\npub fn memory_write_protection<'a, 'b, 'c>(\n\n local_slots: LocalCNodeSlots<U33768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_asid, _asid_pool) = asid_pool.alloc();\n\n let child_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let child_vspace_ut: LocalCap<Untyped<U15>> = ut;\n\n let mut child_vspace = VSpace::new(\n\n retype(ut, slots)?,\n\n child_asid,\n\n child_vspace_slots.weaken(),\n\n child_vspace_ut.weaken(),\n", "file_path": "qemu-test/test-project/root-task/src/memory_write_protection.rs", "rank": 59, "score": 142880.2892875173 }, { "content": "#[ferros_test::ferros_test]\n\npub fn weak_elf_process_runs<'a, 'b, 'c>(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n stack_mem: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n mut local_vspace_scratch: &mut ScratchRegion,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n let archive_slice: &[u8] = unsafe {\n\n core::slice::from_raw_parts(\n\n &crate::_selfe_arc_data_start,\n\n &crate::_selfe_arc_data_end as *const _ as usize\n\n - &crate::_selfe_arc_data_start as *const _ as usize,\n\n )\n\n };\n\n\n", "file_path": "qemu-test/test-project/root-task/src/weak_elf.rs", "rank": 60, "score": 142880.2892875173 }, { "content": "#[ferros_test::ferros_test]\n\npub fn over_register_size_params<'a, 'b, 'c>(\n\n local_slots: LocalCNodeSlots<U32768>,\n\n local_ut: LocalCap<Untyped<U20>>,\n\n asid_pool: LocalCap<ASIDPool<U1>>,\n\n local_mapped_region: MappedMemoryRegion<U17, shared_status::Exclusive>,\n\n root_cnode: &LocalCap<LocalCNode>,\n\n user_image: &UserImage<role::Local>,\n\n tpa: &LocalCap<ThreadPriorityAuthority>,\n\n) -> Result<(), TopLevelError> {\n\n let uts = ut_buddy(local_ut);\n\n\n\n smart_alloc!(|slots: local_slots, ut: uts| {\n\n let (child_asid, _asid_pool) = asid_pool.alloc();\n\n let child_vspace_slots: LocalCNodeSlots<U1024> = slots;\n\n let child_vspace_ut: LocalCap<Untyped<U15>> = ut;\n\n let mut child_vspace = VSpace::new(\n\n retype(ut, slots)?,\n\n child_asid,\n\n child_vspace_slots.weaken(),\n\n child_vspace_ut.weaken(),\n", "file_path": "qemu-test/test-project/root-task/src/over_register_size_params.rs", "rank": 61, "score": 142880.2892875173 }, { "content": "fn parse_fnarg_to_intermediate(arg: &FnArg) -> Result<IntermediateResource, Error> {\n\n let (request_pat, resource_ty) = match arg {\n\n FnArg::Captured(ArgCaptured { pat, ty, .. }) => (pat, ty),\n\n FnArg::Inferred(inf) => {\n\n return Err(Error::MissingResourceId {\n\n request_id: format!(\"{:?}\", inf),\n\n span: inf.span(),\n\n })\n\n }\n\n FnArg::SelfRef(_) | FnArg::SelfValue(_) => {\n\n return Err(Error::InvalidRequestId {\n\n id: \"self\".to_string(),\n\n span: arg.span(),\n\n })\n\n }\n\n FnArg::Ignored(_) => {\n\n return Err(Error::InvalidRequestId {\n\n id: \"_\".to_string(),\n\n span: arg.span(),\n\n })\n", "file_path": "smart_alloc/src/lib.rs", "rank": 62, "score": 142767.90903845322 }, { "content": "#[ferros_test]\n\nfn vspacescratch_parameter(scratch: &mut ScratchRegion) {}\n\n\n", "file_path": "ferros-test/examples/minimal/src/main.rs", "rank": 63, "score": 141717.6027311745 }, { "content": "#[ferros_test]\n\nfn vspacescratch_parameter(scratch: &mut ScratchRegion) {}\n\n\n", "file_path": "ferros-test/examples/mock/src/lib.rs", "rank": 64, "score": 141717.6027311745 }, { "content": "pub trait IdGenerator {\n\n fn gen(&mut self, name_hint: &'static str) -> String;\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, Default)]\n\npub struct UuidGenerator;\n\n\n\nimpl IdGenerator for UuidGenerator {\n\n fn gen(&mut self, name_hint: &'static str) -> String {\n\n format!(\n\n \"__ferros_test_{}_{}\",\n\n name_hint,\n\n uuid::Uuid::new_v4().to_simple()\n\n )\n\n }\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 65, "score": 141265.95076918326 }, { "content": " pub trait SealedCapType {}\n\n impl<BitSize: typenum::Unsigned, Kind: MemoryKind> SealedCapType for Untyped<BitSize, Kind> {}\n\n impl<Role: CNodeRole> SealedCapType for CNode<Role> {}\n\n impl<Size: Unsigned, Role: CNodeRole> SealedCapType for CNodeSlotsData<Size, Role> {}\n\n impl SealedCapType for ThreadControlBlock {}\n\n impl SealedCapType for ThreadPriorityAuthority {}\n\n impl SealedCapType for Endpoint {}\n\n impl SealedCapType for FaultReplyEndpoint {}\n\n impl SealedCapType for Notification {}\n\n impl<FreeSlots: Unsigned> SealedCapType for ASIDPool<FreeSlots> {}\n\n impl SealedCapType for IRQControl {}\n\n impl<IRQ: Unsigned, SetState: IRQSetState> SealedCapType for IRQHandler<IRQ, SetState> where\n\n IRQ: IsLess<MaxIRQCount, Output = True>\n\n {\n\n }\n\n impl<State: PageState> SealedCapType for Page<State> {}\n\n\n\n /*\n\n Cross Arch things:\n\n\n", "file_path": "src/cap/mod.rs", "rank": 66, "score": 141202.70378440025 }, { "content": "/// A version of retype that concretely specifies the required untyped size,\n\n/// to work well with type inference.\n\npub fn retype<TargetCapType: CapType, TargetRole: CNodeRole>(\n\n untyped: LocalCap<Untyped<TargetCapType::SizeBits, memory_kind::General>>,\n\n dest_slot: CNodeSlot<TargetRole>,\n\n) -> Result<Cap<TargetCapType, TargetRole>, SeL4Error>\n\nwhere\n\n TargetCapType: DirectRetype,\n\n TargetCapType: PhantomCap,\n\n TargetCapType::SizeBits: IsGreaterOrEqual<TargetCapType::SizeBits, Output = True>,\n\n{\n\n untyped.retype(dest_slot)\n\n}\n\n\n", "file_path": "src/cap/untyped.rs", "rank": 67, "score": 139079.87634523722 }, { "content": "fn parse_localcap_param_kind(\n\n arguments: &PathArguments,\n\n arg_kind: ArgKind,\n\n) -> Result<ParamKind, ParseError> {\n\n let segment = extract_first_arg_type_path_last_segment(arguments)?;\n\n let type_name = segment.ident.to_string();\n\n match type_name.as_ref() {\n\n \"Untyped\" => Ok(ParamKind::Untyped {\n\n bits: extract_first_argument_as_unsigned(&segment.arguments)?,\n\n }),\n\n \"ASIDPool\" => Ok(ParamKind::ASIDPool {\n\n count: extract_first_argument_as_unsigned(&segment.arguments)?,\n\n }),\n\n \"IRQControl\" => Ok(ParamKind::IRQControl),\n\n \"ThreadPriorityAuthority\" => {\n\n if arg_kind == ArgKind::Ref {\n\n Ok(ParamKind::ThreadPriorityAuthority)\n\n } else {\n\n Err(ParseError::InvalidArgumentType {msg: format!(\"{} is only available as a type parameter of &LocalCap<>, not an owned LocalCap<>\", &type_name),\n\n span: segment.span() })\n", "file_path": "ferros-test/test-macro-impl/src/parse.rs", "rank": 68, "score": 138435.34389596293 }, { "content": "fn process_test_execution(model: TestModel, _fn_under_test_ident: Ident) -> Block {\n\n assert_eq!(model.execution_context, TestExecutionContext::Process);\n\n // TODO - produce a Proc/ThreadParams structure and RetypeForSetup impl\n\n // TODO - if Process, generate a test thread entry point function\n\n unimplemented!()\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 69, "score": 137229.71666174664 }, { "content": "// of random things in the bootinfo.\n\n// TODO: ideally, this should only be callable once in the process. Is that possible?\n\npub fn root_cnode(\n\n bootinfo: &'static seL4_BootInfo,\n\n) -> (\n\n LocalCap<LocalCNode>,\n\n LocalCNodeSlots<RootCNodeAvailableSlots>,\n\n) {\n\n (\n\n Cap {\n\n cptr: seL4_CapInitThreadCNode as usize,\n\n _role: PhantomData,\n\n cap_data: CNode {\n\n radix: 19,\n\n _role: PhantomData,\n\n },\n\n },\n\n CNodeSlots::internal_new(seL4_CapInitThreadCNode as usize, bootinfo.empty.start),\n\n )\n\n}\n\n\n\n/// Encapsulate the user image information found in bootinfo\n", "file_path": "src/bootstrap.rs", "rank": 70, "score": 134437.79155545792 }, { "content": "fn local_test_execution<G: IdGenerator>(\n\n model: TestModel,\n\n id_generator: &mut G,\n\n fn_under_test_ident: Ident,\n\n) -> Block {\n\n assert_eq!(model.execution_context, TestExecutionContext::Local);\n\n let (mut alloc_block, allocated_params) = local_allocations(id_generator, &model.resources);\n\n let call_block = call_fn_under_test(\n\n fn_under_test_ident,\n\n model.fn_under_test_output,\n\n allocated_params.into_iter().map(|p| p.output_ident),\n\n );\n\n alloc_block.stmts.extend(call_block.stmts);\n\n alloc_block\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 71, "score": 134023.86593474288 }, { "content": "fn parse_resource_kind(ident: Ident) -> Result<ResKind, Error> {\n\n let raw_kind = ident.to_string();\n\n match raw_kind.as_ref() {\n\n RESOURCE_TYPE_HINT_CSLOTS => Ok(ResKind::CNodeSlots),\n\n RESOURCE_TYPE_HINT_UNTYPED => Ok(ResKind::Untyped),\n\n _ => Err(Error::InvalidResourceKind {\n\n found: raw_kind,\n\n span: ident.span(),\n\n }),\n\n }\n\n}\n\n\n", "file_path": "smart_alloc/src/lib.rs", "rank": 72, "score": 133182.9367223008 }, { "content": "fn smart_alloc_impl(tokens: TokenStream2) -> Result<TokenStream2, Error> {\n\n let mut output_tokens = TokenStream2::new();\n\n output_tokens.append_all(smart_alloc_structured(tokens)?);\n\n Ok(output_tokens)\n\n}\n\n\n", "file_path": "smart_alloc/src/lib.rs", "rank": 73, "score": 130439.5658043967 }, { "content": "fn local_allocations<G: IdGenerator>(\n\n id_generator: &mut G,\n\n params: &[Param],\n\n) -> (Block, Vec<AllocatedParam>) {\n\n let mut allocated_params = Vec::new();\n\n let mut stmts = Vec::new();\n\n // Available ids provided as parameters by the enclosing function\n\n // These need to match the inputs declared by `run_test_decl`\n\n let slots = Ident::new(\"slots\", Span::call_site());\n\n let untyped = Ident::new(\"untyped\", Span::call_site());\n\n let asid_pool = Ident::new(\"asid_pool\", Span::call_site());\n\n let scratch = Ident::new(\"scratch\", Span::call_site());\n\n let local_cnode = Ident::new(\"local_cnode\", Span::call_site());\n\n let thread_authority = Ident::new(\"thread_authority\", Span::call_site());\n\n let vspace_paging_root = Ident::new(\"vspace_paging_root\", Span::call_site());\n\n let user_image = Ident::new(\"user_image\", Span::call_site());\n\n let ut_buddy_instance = Ident::new(\"ut_buddy_instance\", Span::call_site());\n\n let mapped_memory_region = Ident::new(\"mapped_memory_region\", Span::call_site());\n\n let irq_control = Ident::new(\"irq_control\", Span::call_site());\n\n let is_untyped = |p: &Param| {\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 74, "score": 130402.35217640338 }, { "content": "/// Embed the given resources into a selfe-arc. If any code generation is required,\n\n/// put it into the file at `codegen_path`.\n\npub fn embed_resources<'a, P: AsRef<Path>, I: IntoIterator<Item = &'a dyn Resource>>(\n\n codegen_path: P,\n\n resources: I,\n\n) {\n\n let mut code = \"\".to_owned();\n\n let mut arc_params: Vec<(String, PathBuf)> = Vec::new();\n\n\n\n for res in resources.into_iter() {\n\n code += &res.codegen();\n\n code += \"\\n\";\n\n\n\n arc_params.push((res.image_name().to_owned(), res.path().to_owned()));\n\n }\n\n\n\n let p = codegen_path.as_ref();\n\n let _f = fs::write(p, code).expect(\"Unable to write generated code for resources\");\n\n\n\n selfe_arc::build::link_with_archive(arc_params.iter().map(|(a, b)| (a.as_str(), b.as_path())));\n\n}\n\n\n", "file_path": "ferros-build/src/lib.rs", "rank": 75, "score": 130216.09289429052 }, { "content": "/// A `Maps` implementor is a paging layer that maps granules of type\n\n/// `LowerLevel`. If this layer isn't present for the incoming address,\n\n/// `MappingError::Overflow` should be returned, as this signals to\n\n/// the caller—the layer above—that it needs to create a new object at\n\n/// this layer and then attempt again to map the `item`.\n\n///\n\n/// N.B. A \"Granule\" is \"one of the constituent members of a layer\", or\n\n/// \"the level one level down from the current level\".\n\npub trait Maps<LowerLevel: CapType> {\n\n /// Map the level/layer down relative to this layer.\n\n /// E.G. for a PageTable, this would map a Page.\n\n /// E.G. for a PageDirectory, this would map a PageTable.\n\n fn map_granule(\n\n &mut self,\n\n item: &LocalCap<LowerLevel>,\n\n addr: usize,\n\n root: &mut LocalCap<PagingRoot>,\n\n rights: CapRights,\n\n vm_attributes: arch::VMAttributes,\n\n ) -> Result<(), MappingError>;\n\n}\n\n\n\n#[derive(Debug)]\n\n/// The error type returned when there is in an error in the\n\n/// construction of any of the intermediate layers of the paging\n\n/// structure.\n\npub enum MappingError {\n\n /// Overflow is the special variant that signals to the caller\n", "file_path": "src/vspace/mod.rs", "rank": 76, "score": 129146.6229077649 }, { "content": "/// Number of bytes in buffer before transmission begins\n\ntype StrFwdBytes = U128;\n", "file_path": "examples/system/imx6-hal/src/enet/mod.rs", "rank": 77, "score": 129121.34386763559 }, { "content": "/// Use `BootInfo` to bootstrap both the device and general allocators.\n\npub fn bootstrap_allocators(\n\n bootinfo: &'static seL4_BootInfo,\n\n) -> Result<(Allocator, DeviceAllocator), Error> {\n\n let mut general_uts = ArrayVec::new();\n\n let mut device_uts: ArrayVec<[LocalCap<WUntyped<memory_kind::Device>>; MAX_DEVICE_UTS]> =\n\n ArrayVec::new();\n\n\n\n for i in 0..(bootinfo.untyped.end - bootinfo.untyped.start) {\n\n let cptr = (bootinfo.untyped.start + i) as usize;\n\n let ut = &bootinfo.untypedList[i as usize];\n\n if ut.isDevice == 1 {\n\n match device_uts.try_push(Cap {\n\n cptr,\n\n cap_data: WUntyped {\n\n size_bits: ut.sizeBits,\n\n kind: memory_kind::Device { paddr: ut.paddr },\n\n },\n\n _role: PhantomData,\n\n }) {\n\n Ok(()) => (),\n", "file_path": "src/alloc/micro_alloc.rs", "rank": 78, "score": 128774.57267682582 }, { "content": "type StrFwd = op!(StrFwdBytes / U64);\n\n\n", "file_path": "examples/system/imx6-hal/src/enet/mod.rs", "rank": 79, "score": 128222.72279190134 }, { "content": "#[inline(always)]\n\npub fn nop() {\n\n #[cfg(any(target_arch = \"arm\", target_arch = \"aarch32\"))]\n\n unsafe {\n\n asm!(\"nop\", options(nomem, nostack))\n\n }\n\n}\n", "file_path": "examples/system/imx6-hal/src/asm.rs", "rank": 80, "score": 126222.77897483417 }, { "content": "/// Only supports establishing two child processes where one process will be\n\n/// watching for faults on the other. Requires a separate input signature if we\n\n/// want the local/current thread to be the watcher due to our consuming full\n\n/// instances of the local scratch CNode and the destination CNodes separately\n\n/// in this function.\n\npub fn setup_fault_endpoint_pair(\n\n local_cnode: &LocalCap<LocalCNode>,\n\n untyped: LocalCap<Untyped<<Endpoint as DirectRetype>::SizeBits>>,\n\n endpoint_slot: LocalCNodeSlot,\n\n fault_source_slot: ChildCNodeSlot,\n\n fault_sink_slot: ChildCNodeSlot,\n\n) -> Result<(FaultSource<role::Child>, FaultSink<role::Child>), FaultManagementError> {\n\n let setup = FaultSinkSetup::new(local_cnode, untyped, endpoint_slot, fault_sink_slot)?;\n\n let fault_source = setup.add_fault_source(local_cnode, fault_source_slot, Badge::from(0))?;\n\n Ok((fault_source, setup.sink()))\n\n}\n\n\n\n/// The side of a fault endpoint that sends fault messages\n\n#[derive(Debug)]\n\npub struct FaultSource<Role: CNodeRole> {\n\n pub(crate) endpoint: Cap<Endpoint, Role>,\n\n}\n\n\n\n/// The side of a fault endpoint that receives fault messages\n\n#[derive(Debug)]\n", "file_path": "src/userland/fault.rs", "rank": 81, "score": 126222.77897483417 }, { "content": "fn child_run(params: ChildParams<role::Local>) -> Result<(), TopLevelError> {\n\n let ChildParams {\n\n mut cnode,\n\n cnode_slots,\n\n untyped,\n\n asid_pool,\n\n user_image,\n\n mapped_region,\n\n thread_priority_authority,\n\n outcome_sender,\n\n } = params;\n\n\n\n let uts = ut_buddy(untyped);\n\n\n\n // Clean/invalidate the entire region\n\n mapped_region.flush();\n\n mapped_region\n\n .flush_range(mapped_region.vaddr(), mapped_region.size_bytes())\n\n .unwrap();\n\n\n", "file_path": "qemu-test/test-project/root-task/src/grandkid_process_runs.rs", "rank": 82, "score": 123614.8578943899 }, { "content": "fn single_segment_exprpath(ident: Ident) -> ExprPath {\n\n ExprPath {\n\n attrs: Vec::new(),\n\n qself: None,\n\n path: single_segment_path(ident),\n\n }\n\n}\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 83, "score": 123163.81049562077 }, { "content": "/// Iterate over segments of the given address range that fit into a page\n\n/// For example, iterate_by_page(0x0abc, 0x4abc) will yield:\n\n/// 0x0abc, 0x1000\n\n/// 0x1000, 0x2000\n\n/// 0x2000, 0x3000\n\n/// 0x3000, 0x4000\n\n/// 0x4000, 0x4abc\n\nfn iterate_by_page(start: usize, end: usize) -> impl Iterator<Item = (usize, usize)> {\n\n ByPageIterator { next: start, end }\n\n}\n\n\n\nimpl VSpace<vspace_state::Imaged, role::Local> {\n\n /// Unmap a region.\n\n pub fn unmap_region<SizeBits: Unsigned, SS: SharedStatus>(\n\n &mut self,\n\n region: MappedMemoryRegion<SizeBits, SS>,\n\n ) -> Result<UnmappedMemoryRegion<SizeBits, SS>, VSpaceError>\n\n where\n\n SizeBits: IsGreaterOrEqual<PageBits>,\n\n SizeBits: Sub<PageBits>,\n\n <SizeBits as Sub<PageBits>>::Output: Unsigned,\n\n <SizeBits as Sub<PageBits>>::Output: _Pow,\n\n Pow<<SizeBits as Sub<PageBits>>::Output>: Unsigned,\n\n {\n\n self.weak_unmap_region(region.weaken())\n\n .and_then(|r| r.as_strong::<SizeBits>())\n\n }\n", "file_path": "src/vspace/mod.rs", "rank": 84, "score": 121564.97595158796 }, { "content": "fn single_segment_path(ident: Ident) -> syn::Path {\n\n let mut segments = syn::punctuated::Punctuated::new();\n\n segments.push(parse_quote!(#ident));\n\n syn::Path {\n\n leading_colon: None,\n\n segments,\n\n }\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 85, "score": 121528.15822272171 }, { "content": "/// A version of retype_cnode that concretely specifies the required untyped\n\n/// size, to work well with type inference.\n\npub fn retype_cnode<ChildRadix: Unsigned>(\n\n untyped: LocalCap<Untyped<Sum<ChildRadix, CNodeSlotBits>, memory_kind::General>>,\n\n local_slots: LocalCNodeSlots<U2>,\n\n) -> Result<\n\n (\n\n LocalCap<ChildCNode>,\n\n ChildCNodeSlots<Diff<Pow<ChildRadix>, U1>>,\n\n ),\n\n SeL4Error,\n\n>\n\nwhere\n\n ChildRadix: _Pow,\n\n Pow<ChildRadix>: Unsigned,\n\n\n\n Pow<ChildRadix>: Sub<U1>,\n\n Diff<Pow<ChildRadix>, U1>: Unsigned,\n\n\n\n ChildRadix: Add<CNodeSlotBits>,\n\n Sum<ChildRadix, CNodeSlotBits>: Unsigned,\n\n Sum<ChildRadix, CNodeSlotBits>: IsGreaterOrEqual<Sum<ChildRadix, CNodeSlotBits>>,\n", "file_path": "src/cap/untyped.rs", "rank": 86, "score": 114935.0509021174 }, { "content": "/// Make a new UTBuddy by wrapping an untyped.\n\npub fn ut_buddy<BitSize: Unsigned>(\n\n ut: LocalCap<Untyped<BitSize>>,\n\n) -> UTBuddy<OneHotUList<Diff<BitSize, U4>>>\n\nwhere\n\n BitSize: Sub<U4>,\n\n Diff<BitSize, U4>: _OneHotUList,\n\n OneHotUList<Diff<BitSize, U4>>: UList,\n\n{\n\n let mut pool = make_pool();\n\n pool[BitSize::USIZE - MinUntypedSize::USIZE].push(ut.cptr);\n\n\n\n UTBuddy {\n\n _pool_sizes: PhantomData,\n\n pool,\n\n }\n\n}\n\n\n\nimpl<PoolSizes: UList> UTBuddy<PoolSizes> {\n\n pub fn alloc<BitSize: Unsigned, NumSplits: Unsigned>(\n\n mut self,\n", "file_path": "src/alloc/ut_buddy.rs", "rank": 87, "score": 112700.42663175552 }, { "content": "fn main() {\n\n println!(\"cargo:rerun-if-env-changed=TEST_CASE\");\n\n\n\n let test_case = match env::var(\"TEST_CASE\") {\n\n Ok(val) => val,\n\n Err(_) => \"root_task_runs\".to_string(),\n\n };\n\n\n\n println!(\"cargo:rustc-cfg=test_case=\\\"{}\\\"\", test_case);\n\n\n\n let out_dir = Path::new(&std::env::var_os(\"OUT_DIR\").unwrap()).to_owned();\n\n let bin_dir = out_dir.join(\"..\").join(\"..\").join(\"..\");\n\n let resources = out_dir.join(\"resources.rs\");\n\n\n\n let elf_proc = ElfResource {\n\n path: bin_dir.join(\"elf-process\"),\n\n image_name: \"elf-process\".to_owned(),\n\n type_name: \"ElfProcess\".to_owned(),\n\n stack_size_bits: None,\n\n };\n\n\n\n embed_resources(&resources, vec![&elf_proc as &dyn Resource]);\n\n}\n", "file_path": "qemu-test/test-project/root-task/build.rs", "rank": 88, "score": 111430.41842632114 }, { "content": "#[cfg(test_case = \"uart\")]\n\nfn main() {\n\n debug_println!(\"Starting the test!\");\n\n let bootinfo = unsafe { &*selfe_start::BOOTINFO };\n\n run(bootinfo);\n\n}\n\n\n", "file_path": "qemu-test/test-project/root-task/src/main.rs", "rank": 89, "score": 109225.36489806799 }, { "content": "/// Marker trait for CapType implementing structs that can\n\n/// be deleted.\n\n/// TODO - Delible is presently not used for anything important, and represents\n\n/// a risk of invalidating key immutability assumptions. Consider removing it.\n\npub trait Delible {}\n\n\n\n#[derive(Debug)]\n\npub struct Cap<CT: CapType, Role: CNodeRole> {\n\n pub cptr: usize,\n\n // TODO: put this back to pub(super)\n\n pub(crate) cap_data: CT,\n\n pub(crate) _role: PhantomData<Role>,\n\n}\n\n\n", "file_path": "src/cap/mod.rs", "rank": 90, "score": 108875.52647329144 }, { "content": "/// Marker trait for CapType implementing structs that can\n\n/// be moved from one location to another.\n\n/// TODO - Review all of the CapType structs and apply where necessary\n\npub trait Movable {}\n\n\n", "file_path": "src/cap/mod.rs", "rank": 91, "score": 108872.72316384428 }, { "content": "/// Make a weak ut buddy around a weak untyped.\n\npub fn weak_ut_buddy<Role: CNodeRole>(\n\n ut: Cap<WUntyped<memory_kind::General>, Role>,\n\n) -> WUTBuddy<Role> {\n\n let mut pool = make_pool();\n\n pool[usize::from(ut.cap_data.size_bits) - MinUntypedSize::USIZE].push(ut.cptr);\n\n WUTBuddy {\n\n pool,\n\n _role: PhantomData,\n\n }\n\n}\n\n\n\n/// The error returned when using the runtime-checked (weak)\n\n/// realization of a ut buddy.\n\n#[derive(Debug)]\n\npub enum UTBuddyError {\n\n /// The requested size exceeds max untyped size for this\n\n /// architecture.\n\n RequestedSizeExceedsMax(u8),\n\n /// There are not enough CNode slots to do the requisite\n\n /// splitting.\n", "file_path": "src/alloc/ut_buddy.rs", "rank": 92, "score": 108638.42782089346 }, { "content": "fn run_qemu_test<F>(\n\n test_case: &str,\n\n pass_line: Regex,\n\n fail_line: Regex,\n\n ready_line_and_func: Option<(Regex, F)>,\n\n serial_override: Option<&str>,\n\n test_platform: TestPlatform,\n\n) where\n\n F: Fn(),\n\n{\n\n let rust_identifier_regex: Regex =\n\n Regex::new(\"(^[a-zA-Z][a-zA-Z0-9_]*$)|(^_[a-zA-Z0-9_]+$)\").unwrap();\n\n let is_rust_id = |s| rust_identifier_regex.is_match(s);\n\n if !is_rust_id(test_case) {\n\n panic!(\n\n \"Invalid test case test_case {}. Test case name must be a valid rust identifier\",\n\n test_case\n\n );\n\n }\n\n\n", "file_path": "qemu-test/src/main.rs", "rank": 93, "score": 108590.88623657066 }, { "content": "fn main() {}\n\n\n\nuse lazy_static::lazy_static;\n\nuse regex::Regex;\n\nuse rexpect::process::signal::Signal;\n\nuse rexpect::session::spawn_command;\n\nuse std::io::{self, Write};\n\nuse std::process::Command;\n\nuse std::sync::Mutex;\n\n\n\nlazy_static! {\n\n static ref SEQUENTIAL_TEST_MUTEX: Mutex<()> = Mutex::new(());\n\n}\n\nmacro_rules! sequential_test {\n\n (fn $name:ident() $body:block) => {\n\n #[test]\n\n fn $name() {\n\n let _guard = $crate::SEQUENTIAL_TEST_MUTEX.lock();\n\n {\n\n $body\n", "file_path": "qemu-test/src/main.rs", "rank": 94, "score": 108026.3465196818 }, { "content": "#[inline]\n\nfn unchecked_raw_ipc_buffer<'a>() -> &'a mut seL4_IPCBuffer {\n\n unsafe { &mut *seL4_GetIPCBuffer() }\n\n}\n\n\n\npub(crate) fn type_length_in_words<T>() -> usize {\n\n let t_bytes = core::mem::size_of::<T>();\n\n let usize_bytes = core::mem::size_of::<usize>();\n\n if t_bytes == 0 {\n\n return 0;\n\n }\n\n if t_bytes < usize_bytes {\n\n return 1;\n\n }\n\n let words = t_bytes / usize_bytes;\n\n let rem = t_bytes % usize_bytes;\n\n if rem > 0 {\n\n words + 1\n\n } else {\n\n words\n\n }\n\n}\n\n\n", "file_path": "src/userland/ipc.rs", "rank": 95, "score": 107034.45763653485 }, { "content": "/// A resource that can be embedded in a ferros binary\n\npub trait Resource {\n\n fn path(&self) -> &Path;\n\n /// The name this will get in the embedded selfe-arc\n\n fn image_name(&self) -> &str;\n\n fn codegen(&self) -> String;\n\n}\n\n\n\n/// A data file resource\n\npub struct DataResource {\n\n pub path: PathBuf,\n\n pub image_name: String,\n\n}\n\n\n\nimpl Resource for DataResource {\n\n fn path(&self) -> &Path {\n\n &self.path\n\n }\n\n\n\n fn image_name(&self) -> &str {\n\n &self.image_name\n", "file_path": "ferros-build/src/lib.rs", "rank": 96, "score": 106539.28899185159 }, { "content": "/// Marker trait for CapType implementing structs to indicate that\n\n/// instances of this type of capability can be copied and aliased safely\n\n/// when done through the use of this API\n\npub trait CopyAliasable {\n\n type CopyOutput: CapType + for<'a> From<&'a Self>;\n\n}\n\n\n", "file_path": "src/cap/mod.rs", "rank": 97, "score": 105944.04587250017 }, { "content": "/// Marker trait for CapType implementing structs to indicate that\n\n/// this type of capability can be generated directly\n\n/// from retyping an Untyped\n\npub trait DirectRetype {\n\n type SizeBits: Unsigned;\n\n fn sel4_type_id() -> usize;\n\n}\n\n\n", "file_path": "src/cap/mod.rs", "rank": 98, "score": 105939.89541136213 }, { "content": " pub trait SealedRole {}\n\n impl private::SealedRole for role::Local {}\n\n impl private::SealedRole for role::Child {}\n\n\n", "file_path": "src/cap/mod.rs", "rank": 99, "score": 105934.39374150908 } ]
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_COLS_SPARSE_I64 + TEST_COLS_SPARSE_STRING {\n\n let block : Block;\n\n let block_type : BlockType;\n\n\n\n match col_no {\n\n 0 => {\n\n block = Block::Int64Dense(Int64DenseBlock{\n\n data: (0..TEST_ROWS_PER_PACKAGE).into_iter().map(|x| pseudo_ts + x as u64 * 1000 ).collect()\n\n });\n\n block_type = BlockType::Int64Dense;\n\n },\n\n 1 => {\n", "file_path": "src/main.rs", "rank": 6, "score": 120074.08870902914 }, { "content": "fn read_block(path : &String) -> Block {\n\n println!(\"Reading block {}\", path);\n\n\n\n let file = File::open(path).unwrap();\n\n let mut buf_reader = BufReader::new(file);\n\n let mut buf: Vec<u8> = Vec::new();\n\n buf_reader.read_to_end(&mut buf).unwrap();\n\n\n\n deserialize(&buf[..]).unwrap()\n\n}\n\n\n\n\n\nimpl Manager {\n\n pub fn new(db_home:String) -> Manager {\n\n Manager { db_home: db_home, catalog: Catalog::new(), current_partition: Partition::new() }\n\n }\n\n\n\n pub fn add_column(&mut self, data_type: BlockType, name: String) {\n\n ensure_partition_is_current(&self.catalog, &mut self.current_partition);\n\n\n", "file_path": "src/manager.rs", "rank": 7, "score": 118396.11437879401 }, { "content": "#[test]\n\nfn it_inserts_and_dumps_and_compacts_data_smoke_test() {\n\n let mut manager = Manager::new(String::from(\"/tmp/hyena\"));\n\n\n\n manager.catalog.add_column(BlockType::Int64Dense, String::from(\"ts\"));\n\n manager.catalog.add_column(BlockType::Int64Dense, String::from(\"source\"));\n\n manager.catalog.add_column(BlockType::Int32Sparse, String::from(\"pattern_id\"));\n\n manager.catalog.add_column(BlockType::String, String::from(\"p1\"));\n\n manager.catalog.add_column(BlockType::String, String::from(\"p2\"));\n\n manager.catalog.add_column(BlockType::String, String::from(\"p3\"));\n\n\n\n manager.store_catalog();\n\n\n\n let base_ts = 1495493600 as u64 * 1000000;\n\n let insert_msg = InsertMessage {\n\n row_count: 4,\n\n col_count: 6,\n\n col_types: vec![(0, BlockType::Int64Dense), (1, BlockType::Int64Dense), (2, BlockType::Int32Sparse), (3, BlockType::String), (4, BlockType::String), (5, BlockType::String)],\n\n blocks: vec![\n\n Block::Int64Dense(Int64DenseBlock{\n\n data: vec![base_ts, base_ts+1000, base_ts+2000, base_ts+3000]\n", "file_path": "src/manager.rs", "rank": 9, "score": 109025.03969633099 }, { "content": "pub fn start_endpoint(manager : &mut Manager) {\n\n let mut socket = Socket::new(Protocol::Rep).unwrap();\n\n let mut endpoint = socket.bind(&format!(\"ipc://{}\", HYENA_SOCKET_PATH)).unwrap();\n\n let mut perms = metadata(HYENA_SOCKET_PATH).unwrap().permissions();\n\n perms.set_mode(0o775);\n\n set_permissions(HYENA_SOCKET_PATH, perms).unwrap();\n\n let mut last_flush = None::<Instant>;\n\n let mut rows_inserted = 0_usize;\n\n\n\n while true {\n\n println!(\"Waiting for message...\");\n\n\n\n let mut buf: Vec<u8> = Vec::new();\n\n socket.read_to_end(&mut buf).unwrap();\n\n\n\n// println!(\"Received buffer: {:?}\", buf);\n\n\n\n let req : ApiMessage = deserialize(&buf[..]).unwrap();\n\n\n\n match req.op_type {\n", "file_path": "src/nanomsg_endpoint.rs", "rank": 10, "score": 108864.98369153461 }, { "content": "// This is not utf-8 aware\n\nfn strings_ne_match(s1 : &[u8], op : &ScanComparison, s2 : &[u8]) -> bool {\n\n for i in 0..cmp::min(s1.len(), s2.len()) {\n\n if s1[i] == s2[i] {\n\n // just continue\n\n } else {\n\n match op {\n\n &ScanComparison::LtEq => return s1[i] < s2[i],\n\n &ScanComparison::Lt => return s1[i] < s2[i],\n\n &ScanComparison::Gt => return s1[i] > s2[i],\n\n &ScanComparison::GtEq => return s1[i] > s2[i],\n\n //_ => println!(\"Only <, <=, >=, > matches are handled here...\"); return false\n\n _ => return false\n\n }\n\n }\n\n }\n\n\n\n // The shorter string was a substring of the longer one...\n\n match op {\n\n &ScanComparison::LtEq => return s1.len() < s2.len(),\n\n &ScanComparison::Lt => return s1.len() < s2.len(),\n", "file_path": "src/int_blocks.rs", "rank": 11, "score": 107219.19330800163 }, { "content": "#[test]\n\nfn delete_string_block() {\n\n let mut input_block = StringBlock::new();\n\n input_block.append(1, \"foo\".as_bytes());\n\n input_block.append(2, \"bar\".as_bytes());\n\n input_block.append(13, \"snafu\".as_bytes());\n\n\n\n\n\n let mut expected_block = StringBlock::new();\n\n expected_block.append(1, \"foo\".as_bytes());\n\n expected_block.append(13, \"snafu\".as_bytes());\n\n\n\n let offsets = vec![2,3,6];\n\n input_block.delete(&offsets);\n\n\n\n assert_eq!(expected_block, input_block);\n\n}\n\n\n\n\n", "file_path": "src/int_blocks.rs", "rank": 13, "score": 105098.00195866817 }, { "content": "#[test]\n\nfn upsert_string_block() {\n\n let mut input_block = StringBlock::new();\n\n input_block.append(1, \"foo\".as_bytes());\n\n input_block.append(2, \"bar\".as_bytes());\n\n input_block.append(13, \"snafu\".as_bytes());\n\n\n\n let mut upsert_data = StringBlock::new();\n\n upsert_data.append(0, \"a0\".as_bytes());\n\n upsert_data.append(1, \"b1\".as_bytes());\n\n upsert_data.append(3, \"c2\".as_bytes());\n\n\n\n\n\n let mut expected_block = StringBlock::new();\n\n expected_block.append(0, \"a0\".as_bytes());\n\n expected_block.append(1, \"b1\".as_bytes());\n\n expected_block.append(2, \"bar\".as_bytes());\n\n expected_block.append(3, \"c2\".as_bytes());\n\n expected_block.append(13, \"snafu\".as_bytes());\n\n\n\n let offsets = vec![0,2,3];\n\n input_block.upsert(&upsert_data);\n\n\n\n assert_eq!(expected_block, input_block);\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 14, "score": 105036.86268580364 }, { "content": "fn prepare_fake_data(manager : &mut Manager) {\n\n let create_duration = Instant::now();\n\n\n\n let mut cur_ts : u64 = 149500000;\n\n\n\n let mut total_count : usize = 0;\n\n\n\n for iter in 0..100 {\n\n let msg = create_message(cur_ts + iter*17);\n\n total_count += msg.row_count as usize;\n\n manager.insert(&msg);\n\n }\n\n\n\n manager.store_catalog();\n\n manager.dump_in_mem_partition();\n\n\n\n println!(\"Creating {} records took {:?}\", total_count, create_duration.elapsed());\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 15, "score": 103995.92843383367 }, { "content": "fn prepare_demo_scan(manager : &mut Manager) {\n\n\n\n let scan_duration = Instant::now();\n\n\n\n let mut total_matched = 0;\n\n let mut total_materialized = 0;\n\n\n\n for part_info in &manager.catalog.available_partitions {\n\n let scanned_block = manager.load_block(&part_info, 7);\n\n let mut consumer = BlockScanConsumer{matching_offsets : Vec::new()};\n\n scanned_block.scan(ScanComparison::LtEq, &(1363258435234989944 as u64), &mut consumer);\n\n\n\n let mut scan_msg = ScanResultMessage::new();\n\n let mut cache = BlockCache::new(part_info);\n\n consumer.materialize(&manager, &mut cache, &vec![0,1,3,4,5,24], &mut scan_msg);\n\n\n\n total_materialized += scan_msg.row_count;\n\n total_matched += consumer.matching_offsets.len();\n\n }\n\n println!(\"Scanning and matching/materializing {}/{} elements took {:?}\", total_matched, total_materialized, scan_duration.elapsed());\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 16, "score": 103626.40481494738 }, { "content": "#[test]\n\nfn multi_upsert_string_block() {\n\n let mut input_block = StringBlock::new();\n\n input_block.append(1, \"foo\".as_bytes());\n\n input_block.append(2, \"bar\".as_bytes());\n\n input_block.append(13, \"snafu\".as_bytes());\n\n\n\n\n\n let mut expected_block = StringBlock::new();\n\n expected_block.append(0, \"lol\".as_bytes());\n\n expected_block.append(1, \"foo\".as_bytes());\n\n expected_block.append(2, \"lol\".as_bytes());\n\n expected_block.append(3, \"lol\".as_bytes());\n\n expected_block.append(13, \"snafu\".as_bytes());\n\n\n\n let offsets = vec![0,2,3];\n\n input_block.multi_upsert(&offsets, \"lol\".as_bytes());\n\n\n\n assert_eq!(expected_block, input_block);\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 17, "score": 100740.54437695371 }, { "content": "fn save_data<T: Serialize>(path : &String, data : &T) {\n\n let mut file = File::create(path).expect(\"Unable to create file\");\n\n\n\n let bytes:Vec<u8> = serialize(data, Infinite).unwrap();\n\n file.write_all(&bytes).unwrap();\n\n}\n\n\n", "file_path": "src/manager.rs", "rank": 18, "score": 100547.53808262343 }, { "content": "fn prepare_catalog(manager : &mut Manager) {\n\n manager.catalog.add_column(BlockType::Int64Dense, String::from(\"ts\"));\n\n manager.catalog.add_column(BlockType::Int64Dense, String::from(\"source\"));\n\n for x in 0..TEST_COLS_SPARSE_I64 {\n\n manager.catalog.add_column(BlockType::Int64Sparse, format!(\"col_{}\", x));\n\n }\n\n for x in 0..TEST_COLS_SPARSE_STRING {\n\n manager.catalog.add_column(BlockType::String, format!(\"col_s{}\", x));\n\n }\n\n\n\n println!(\"Following columns are defined\");\n\n for col in manager.catalog.columns.iter_mut() {\n\n println!(\"Column: {} of type {:?}\", col.name, col.data_type);\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 19, "score": 88446.62363612032 }, { "content": "#[test]\n\nfn string_block() {\n\n let mut expected_block = StringBlock {\n\n index_data: vec![\n\n (0, 0), // foo\n\n (1, 3), // bar\n\n (2, 6), // \"\"\n\n (3, 6), // snafu\n\n ],\n\n str_data: \"foobarsnafu\".as_bytes().to_vec()\n\n };\n\n\n\n let mut str_block = StringBlock::new();\n\n str_block.append(0, \"foo\".as_bytes());\n\n str_block.append(1, \"bar\".as_bytes());\n\n str_block.append(2, \"\".as_bytes());\n\n str_block.append(3, \"snafu\".as_bytes());\n\n\n\n assert_eq!(expected_block, str_block);\n\n\n\n let mut consumer = BlockScanConsumer::new();\n", "file_path": "src/int_blocks.rs", "rank": 20, "score": 87964.38720215231 }, { "content": "#[test]\n\nfn it_merges_consumers() {\n\n let consumers = vec![\n\n BlockScanConsumer {\n\n matching_offsets: vec![101,102,103,510,512,514]\n\n },\n\n BlockScanConsumer{\n\n matching_offsets: vec![0,1,101,514,515]\n\n },\n\n BlockScanConsumer{\n\n matching_offsets: vec![513]\n\n },\n\n BlockScanConsumer{\n\n matching_offsets: vec![]\n\n }\n\n ];\n\n\n\n assert_eq!(\n\n BlockScanConsumer{\n\n matching_offsets: vec![0,1,101,102,103,510,512,513,514,515]\n\n },\n", "file_path": "src/scan.rs", "rank": 21, "score": 86606.39098902149 }, { "content": "#[test]\n\nfn delete_sparse_block() {\n\n let mut input_block = Int32SparseBlock {\n\n data: vec![\n\n (1, 100),\n\n (2, 200),\n\n (3, 300),\n\n (6, 600),\n\n (8, 800),\n\n (11, 1100)\n\n ]\n\n };\n\n\n\n let mut expected_block = Int32SparseBlock {\n\n data: vec![\n\n (1, 100),\n\n (8, 800),\n\n (11, 1100)\n\n ]\n\n };\n\n\n\n let offsets = vec![2,3,6];\n\n input_block.delete(&offsets);\n\n\n\n assert_eq!(expected_block, input_block);\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 23, "score": 84586.8006836428 }, { "content": "#[test]\n\nfn it_filters_sparse_block() {\n\n let mut data_block = Int64SparseBlock {\n\n data: vec![\n\n (1, 100),\n\n (2, 200),\n\n (3, 300),\n\n (6, 600),\n\n (8, 800),\n\n (11, 1100)\n\n ]\n\n };\n\n\n\n let scan_consumer = BlockScanConsumer {\n\n matching_offsets: vec![2,3,4,11]\n\n };\n\n\n\n // The offsets are now changed to be with order of scan consumer\n\n\n\n let expected_output = Int64SparseBlock {\n\n data: vec![\n", "file_path": "src/int_blocks.rs", "rank": 24, "score": 84556.17098627193 }, { "content": "#[test]\n\nfn upsert_sparse_block() {\n\n let mut input_block = Int32SparseBlock {\n\n data: vec![\n\n (1, 100),\n\n (8, 800),\n\n (11, 1100)\n\n ]\n\n };\n\n\n\n let mut expected_block = Int32SparseBlock {\n\n data: vec![\n\n (1, 101),\n\n (2, 202),\n\n (8, 800),\n\n (11, 1100),\n\n ]\n\n };\n\n\n\n let upsert_data = Int32SparseBlock {\n\n data: vec![\n", "file_path": "src/int_blocks.rs", "rank": 25, "score": 84525.6614107783 }, { "content": "#[test]\n\nfn multi_upsert_sparse_block() {\n\n let mut input_block = Int32SparseBlock {\n\n data: vec![\n\n (1, 100),\n\n (8, 800),\n\n (11, 1100)\n\n ]\n\n };\n\n\n\n let mut expected_block = Int32SparseBlock {\n\n data: vec![\n\n (0, 9999),\n\n (1, 9999),\n\n (2, 9999),\n\n (8, 800),\n\n (11, 1100),\n\n (12, 9999)\n\n ]\n\n };\n\n\n\n let offsets = vec![0,1,2,12];\n\n input_block.multi_upsert(&offsets, 9999);\n\n\n\n assert_eq!(expected_block, input_block);\n\n\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 26, "score": 81338.35944612685 }, { "content": "fn create_test_catalog<'a>() -> Manager {\n\n let mut manager = Manager::new(String::from(\"/tmp/hyena\"));\n\n\n\n manager.catalog.add_column(BlockType::Int64Dense, String::from(\"ts\"));\n\n manager.catalog.add_column(BlockType::Int64Dense, String::from(\"source\"));\n\n manager.catalog.add_column(BlockType::Int64Sparse, String::from(\"int_01\"));\n\n manager.catalog.add_column(BlockType::Int32Sparse, String::from(\"int_02\"));\n\n manager.catalog.add_column(BlockType::String, String::from(\"str\"));\n\n\n\n manager.store_catalog();\n\n\n\n manager\n\n}\n\n\n\n//#[test]\n\n//fn it_saves_and_loads_catalog() {\n\n// let manager = create_catalog();\n\n//\n\n// let manager2 = &mut Manager::new(String::from(\"/tmp/hyena\"));\n\n// manager2.reload_catalog();\n", "file_path": "src/manager.rs", "rank": 27, "score": 80967.38067787337 }, { "content": "pub trait Movable {\n\n fn move_data(&mut self, target : &mut Block, scan_consumer : &BlockScanConsumer);\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\n\npub enum Block {\n\n Int64Dense(Int64DenseBlock),\n\n Int64Sparse(Int64SparseBlock),\n\n Int32Sparse(Int32SparseBlock),\n\n Int16Sparse(Int16SparseBlock),\n\n Int8Sparse(Int8SparseBlock),\n\n StringBlock(StringBlock)\n\n}\n\n\n\nimpl Block {\n\n pub fn create_block(block_type: &BlockType) -> Block {\n\n match block_type {\n\n &BlockType::Int64Dense => Block::Int64Dense(Int64DenseBlock { data: Vec::new() }),\n\n &BlockType::Int64Sparse => Block::Int64Sparse(Int64SparseBlock { data: Vec::new() }),\n\n &BlockType::Int32Sparse => Block::Int32Sparse(Int32SparseBlock { data: Vec::new() }),\n", "file_path": "src/int_blocks.rs", "rank": 28, "score": 79981.6662168969 }, { "content": "pub trait Deletable {\n\n fn delete(&mut self, offsets : &Vec<u32>);\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 29, "score": 79913.47483224701 }, { "content": "pub trait Scannable<T> {\n\n fn scan(&self, op : ScanComparison, val : &T, scan_consumer : &mut BlockScanConsumer);\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 30, "score": 73989.8558227605 }, { "content": "pub trait Upsertable<T> {\n\n fn multi_upsert(&mut self, offsets : &Vec<u32>, val : &T);\n\n fn upsert(&mut self, data : &Block);\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 31, "score": 73864.42294069662 }, { "content": "fn ensure_partition_is_current(catalog: &Catalog, part: &mut Partition) {\n\n if part.blocks.len() < catalog.columns.len() {\n\n for block_no in part.blocks.len()..catalog.columns.len() {\n\n part.blocks.push(Block::create_block(&catalog.columns[block_no].data_type));\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/manager.rs", "rank": 32, "score": 67784.27960741398 }, { "content": "fn main() {\n\n\n\n let mut manager = Manager::new(String::from(\"/tmp/hyena\"));\n\n\n\n// prepare_catalog(&mut manager);\n\n// prepare_fake_data(&mut manager);\n\n\n\n manager.reload_catalog();\n\n\n\n for part in &manager.catalog.available_partitions {\n\n println!(\"Partition: {} for range [{} - {}]\", part.id, part.min_ts, part.max_ts);\n\n }\n\n // prepare_demo_scan(&mut manager);\n\n\n\n start_endpoint(&mut manager);\n\n\n\n\n\n}\n", "file_path": "src/main.rs", "rank": 34, "score": 42045.559229124214 }, { "content": "use catalog::PartitionInfo;\n\nuse api::{ScanResultMessage, ScanFilter, ScanComparison};\n\nuse catalog::Catalog;\n\nuse manager::{Manager, BlockCache};\n\n\n\n\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]\n\npub struct BlockScanConsumer {\n\n pub matching_offsets : Vec<u32>\n\n}\n\n\n\n\n\nimpl BlockScanConsumer {\n\n pub fn new() -> BlockScanConsumer {\n\n BlockScanConsumer { matching_offsets: Vec::new() }\n\n }\n\n\n\n pub fn merge_or_scans(scans : &Vec<BlockScanConsumer>) -> BlockScanConsumer {\n\n let mut new_matching_offsets : Vec<u32> = Vec::new();\n", "file_path": "src/scan.rs", "rank": 35, "score": 26222.132268711335 }, { "content": " iterators[consumer_index] += 1;\n\n }\n\n }\n\n }\n\n\n\n BlockScanConsumer { matching_offsets: new_matching_offsets }\n\n }\n\n\n\n pub fn materialize(&self, manager : &Manager, block_cache: &mut BlockCache, projection : &Vec<u32>, msg : &mut ScanResultMessage) {\n\n // This should work only on empty message (different implementation is of course possible,\n\n // if you think it would make sense to merge results)\n\n assert_eq!(msg.row_count, 0);\n\n\n\n msg.row_count = self.matching_offsets.len() as u32;\n\n msg.col_count = projection.len() as u32;\n\n\n\n for col_index in projection {\n\n let column = &manager.catalog.columns[*col_index as usize];\n\n msg.col_types.push((*col_index, column.data_type.to_owned()));\n\n\n", "file_path": "src/scan.rs", "rank": 36, "score": 26217.899794077857 }, { "content": " if best_offset >= min_offset && best_offset != u32::max_value() {\n\n new_matching_offsets.push(best_offset);\n\n iterators[best_consumer_index] += 1;\n\n\n\n min_offset = best_offset + 1; // we are looking for next minimum value\n\n } else {\n\n// fail!(\"Ooopsie\");\n\n }\n\n\n\n if iterators[best_consumer_index] == offset_sets[best_consumer_index].len() {\n\n closed_iterators_count += 1;\n\n }\n\n }\n\n\n\n BlockScanConsumer { matching_offsets: new_matching_offsets }\n\n }\n\n\n\n pub fn merge_and_scans(scans : &Vec<BlockScanConsumer>) -> BlockScanConsumer {\n\n let mut new_matching_offsets : Vec<u32> = Vec::new();\n\n\n", "file_path": "src/scan.rs", "rank": 37, "score": 26199.478925638854 }, { "content": "\n\n let mut offset_sets:Vec<&Vec<u32>> = Vec::new();\n\n\n\n for scan in scans {\n\n offset_sets.push(&scan.matching_offsets);\n\n }\n\n\n\n let mut iterators:Vec<usize> = vec![0; offset_sets.len()];\n\n\n\n let mut min_offset:u32 = 0;\n\n\n\n let mut closed_iterators_count = 0;\n\n\n\n while closed_iterators_count < iterators.len() {\n\n // Find the smallest having value equal to cur_min_offset or greater\n\n closed_iterators_count = 0;\n\n\n\n let mut best_consumer_index = 0;\n\n let mut best_offset = u32::max_value();\n\n\n", "file_path": "src/scan.rs", "rank": 38, "score": 26197.46734934925 }, { "content": " let mut offset_sets:Vec<&Vec<u32>> = Vec::new();\n\n\n\n for scan in scans {\n\n offset_sets.push(&scan.matching_offsets);\n\n }\n\n\n\n let mut iterators:Vec<usize> = vec![0; offset_sets.len()];\n\n\n\n let mut min_offset:u32 = 0;\n\n\n\n let mut closed_iterators_count = 0;\n\n\n\n while closed_iterators_count == 0 {\n\n for consumer_index in 0..iterators.len() {\n\n if iterators[consumer_index] >= offset_sets[consumer_index].len() {\n\n closed_iterators_count += 1;\n\n }\n\n }\n\n\n\n if closed_iterators_count > 0 { break; }\n", "file_path": "src/scan.rs", "rank": 39, "score": 26196.54221093825 }, { "content": " BlockScanConsumer::merge_or_scans(&consumers)\n\n );\n\n\n\n assert_eq!(\n\n BlockScanConsumer{\n\n matching_offsets: vec![]\n\n },\n\n BlockScanConsumer::merge_and_scans(&consumers)\n\n );\n\n\n\n let consumers2 = vec![\n\n BlockScanConsumer {\n\n matching_offsets: vec![101,102,103,510,512,514]\n\n },\n\n BlockScanConsumer{\n\n matching_offsets: vec![0,1,101,102,514,515]\n\n },\n\n BlockScanConsumer{\n\n matching_offsets: vec![101,102,514]\n\n }\n", "file_path": "src/scan.rs", "rank": 40, "score": 26196.246881937695 }, { "content": " // Fetch block from disk\n\n let block_maybe = block_cache.cached_block_maybe(*col_index);\n\n match block_maybe {\n\n None => {\n\n let block = manager.load_block(&block_cache.partition_info, *col_index);\n\n msg.blocks.push(block.consume(self));\n\n },\n\n Some(ref x) => {\n\n msg.blocks.push(x.consume(self));\n\n }\n\n };\n\n\n\n }\n\n }\n\n\n\n}\n\n\n\n\n\n#[test]\n", "file_path": "src/scan.rs", "rank": 41, "score": 26195.64732225028 }, { "content": " ];\n\n\n\n assert_eq!(\n\n BlockScanConsumer{\n\n matching_offsets: vec![101,102,514]\n\n },\n\n BlockScanConsumer::merge_and_scans(&consumers2)\n\n );\n\n\n\n}", "file_path": "src/scan.rs", "rank": 42, "score": 26194.61283550132 }, { "content": "\n\n // Get the largest offset in current iteration\n\n //let max_offset_value = iterators.iter().enumerate().map(|(consumer_index, consumer_position)| offset_sets[consumer_index][consumer_position]).max();\n\n let max_offset_value = iterators.iter().enumerate().map(|(consumer_index, consumer_position)| offset_sets[consumer_index][*consumer_position]).max().unwrap();\n\n\n\n // Iterate all others until they match the max (or to next item)\n\n let mut matching_count = 0;\n\n for consumer_index in 0..iterators.len() {\n\n while iterators[consumer_index] < offset_sets[consumer_index].len() && offset_sets[consumer_index][iterators[consumer_index]] < max_offset_value {\n\n iterators[consumer_index] += 1;\n\n }\n\n if iterators[consumer_index] < offset_sets[consumer_index].len() && offset_sets[consumer_index][iterators[consumer_index]] == max_offset_value {\n\n matching_count += 1;\n\n }\n\n }\n\n\n\n if matching_count == iterators.len() {\n\n new_matching_offsets.push(max_offset_value);\n\n // increment all iterators\n\n for consumer_index in 0..iterators.len() {\n", "file_path": "src/scan.rs", "rank": 43, "score": 26185.3223079664 }, { "content": " for consumer_index in 0..iterators.len() {\n\n // Make sure the lagging ones are moved forward\n\n while iterators[consumer_index] < offset_sets[consumer_index].len() && offset_sets[consumer_index][iterators[consumer_index]] < min_offset {\n\n iterators[consumer_index] += 1;\n\n }\n\n\n\n let consumer_position = iterators[consumer_index];\n\n if consumer_position < offset_sets[consumer_index].len() {\n\n // Make sure the lagging ones are moved forward\n\n let potential_offset = offset_sets[consumer_index][consumer_position];\n\n\n\n if potential_offset < best_offset {\n\n best_offset = potential_offset;\n\n best_consumer_index = consumer_index;\n\n }\n\n } else {\n\n closed_iterators_count += 1;\n\n }\n\n }\n\n\n", "file_path": "src/scan.rs", "rank": 44, "score": 26182.729709782452 }, { "content": "//\n\n// assert_eq!(manager2.catalog, manager.catalog);\n\n//}\n\n\n\n//#[test]\n\n//fn it_inserts_and_dumps_data_smoke_test() {\n\n// let mut manager = create_test_catalog();\n\n//\n\n// let base_ts = 1495493600 as u64 * 1000000;\n\n// let insert_msg = InsertMessage {\n\n// row_count: 4,\n\n// col_count: 5,\n\n// col_types: vec![(0, BlockType::Int64Dense), (1, BlockType::Int64Dense), (2, BlockType::Int64Sparse), (3, BlockType::Int32Sparse), (4, BlockType::String)],\n\n// blocks: vec![\n\n// Block::Int64Dense(Int64DenseBlock{\n\n// data: vec![base_ts, base_ts+1000, base_ts+2000, base_ts+3000]\n\n// }),\n\n// Block::Int64Dense(Int64DenseBlock{\n\n// data: vec![0, 0, 1, 2]\n\n// }),\n", "file_path": "src/manager.rs", "rank": 58, "score": 25324.444871106305 }, { "content": " ];\n\n\n\n let req = DataCompactionRequest {\n\n partition_id: part_info.id,\n\n filters: filter,\n\n renamed_columns: vec![(4, 5)],\n\n dropped_columns: vec![3],\n\n upserted_data: PartialInsertMessage {\n\n col_count: 1,\n\n col_types: vec![(2, BlockType::Int32Sparse)],\n\n blocks: vec![\n\n Block::Int32Sparse(Int32SparseBlock{\n\n data: vec![(0, 101)]\n\n }),\n\n ]\n\n }\n\n };\n\n\n\n handle_data_compaction(&manager, &req);\n\n\n", "file_path": "src/manager.rs", "rank": 59, "score": 25321.911625817957 }, { "content": "use catalog::Catalog;\n\nuse catalog::BlockType;\n\nuse catalog::PartitionInfo;\n\nuse partition::{Partition, PartitionMetadata};\n\nuse int_blocks::{Block, Int32SparseBlock, Int64DenseBlock, Int64SparseBlock, StringBlock};\n\nuse api::{InsertMessage, DataCompactionRequest, ScanFilter, ScanComparison, PartialInsertMessage, handle_data_compaction};\n\n\n\nuse bincode::{serialize, deserialize, Infinite};\n\nuse serde::ser::{Serialize};\n\nuse std::fs;\n\nuse std::error::Error;\n\nuse std::io::prelude::*;\n\nuse std::fs::File;\n\nuse std::path::Path;\n\nuse std::io::BufReader;\n\n\n\npub struct Manager {\n\n pub db_home: String,\n\n pub catalog: Catalog,\n\n pub current_partition: Partition\n", "file_path": "src/manager.rs", "rank": 60, "score": 25320.649806848316 }, { "content": " };\n\n\n\n manager.insert(&insert_msg);\n\n manager.dump_in_mem_partition();\n\n\n\n let part_info = &manager.catalog.available_partitions[0];\n\n\n\n let filter = vec![\n\n ScanFilter {\n\n column: 2,\n\n op: ScanComparison::Eq,\n\n val: 100,\n\n str_val: vec![]\n\n },\n\n ScanFilter {\n\n column: 3,\n\n op: ScanComparison::Eq,\n\n val: 0,\n\n str_val: \"foo\".as_bytes().to_vec()\n\n }\n", "file_path": "src/manager.rs", "rank": 61, "score": 25319.19935448877 }, { "content": " location: String::from(\"dupa\")\n\n };\n\n pi\n\n }\n\n\n\n pub fn insert(&mut self, msg : &InsertMessage) {\n\n println!(\"Inserting a message of {} records\", msg.row_count);\n\n\n\n // TODO: validate columns - their types and if they exist\n\n\n\n // TODO: for sparse sets we could add assertion that order of offsets is monotonically growing\n\n\n\n ensure_partition_is_current(&self.catalog, &mut self.current_partition);\n\n\n\n let current_offset = self.current_partition.blocks[0].len();\n\n\n\n for col_no in 0..msg.col_count {\n\n let catalog_col_no = msg.col_types[col_no as usize].0;\n\n let input_block = &msg.blocks[col_no as usize];\n\n let output_block = &mut self.current_partition.blocks[catalog_col_no as usize];\n", "file_path": "src/manager.rs", "rank": 62, "score": 25316.671741478676 }, { "content": "}\n\n\n\n// To be used only within extremely limited context\n\npub struct BlockCache {\n\n pub partition_info : PartitionInfo,\n\n pub cache:Vec<(u32, Block)>\n\n}\n\n\n\nimpl BlockCache {\n\n pub fn new(partition_info : &PartitionInfo) -> BlockCache {\n\n BlockCache {\n\n partition_info: (partition_info.to_owned()),\n\n cache: Vec::new()\n\n }\n\n }\n\n\n\n pub fn cache_block(&mut self, block : Block, block_index: u32) {\n\n self.cache.push((block_index, block));\n\n }\n\n\n", "file_path": "src/manager.rs", "rank": 63, "score": 25315.177448903498 }, { "content": " println!(\"Adding column <{}> of type {:?}\", name, data_type);\n\n let col = self.catalog.add_column(data_type, name);\n\n self.current_partition.blocks.push(Block::create_block(&col.data_type));\n\n }\n\n\n\n pub fn find_partition_info(&self, partition_id: u64) -> PartitionInfo {\n\n for part in &self.catalog.available_partitions {\n\n if part.id == partition_id {\n\n return part.to_owned();\n\n }\n\n }\n\n\n\n println!(\"Could not find partition_id {}\", partition_id);\n\n\n\n // FIXME -> RESULT\n\n// fail!(\"NOPE\");\n\n let pi = PartitionInfo{\n\n min_ts: 0,\n\n max_ts: 0,\n\n id: 0,\n", "file_path": "src/manager.rs", "rank": 64, "score": 25313.137359762586 }, { "content": "\n\n // Now we need to scan and see if anything was changed\n\n assert_eq!(\n\n Block::Int32Sparse(Int32SparseBlock{\n\n data: vec![(0, 100), (1, 101), (2, 100), (3, 101)]\n\n }),\n\n manager.load_block(part_info, 2)\n\n );\n\n\n\n assert_eq!(\n\n Block::StringBlock(StringBlock{\n\n index_data: vec![(2,0)],\n\n str_data: \"bar\".as_bytes().to_vec()\n\n }),\n\n manager.load_block(part_info, 3)\n\n );\n\n\n\n assert_eq!(\n\n Block::StringBlock(StringBlock{\n\n index_data: vec![(0,0),(2,1)],\n", "file_path": "src/manager.rs", "rank": 65, "score": 25311.66971816267 }, { "content": " let min_ts = metadata.min_ts / 1000000;\n\n\n\n for i in vec![10000000, 100000, 100] {\n\n let ts = (min_ts / i)*i;\n\n partition_file_name += &format!(\"{}/\", ts);\n\n }\n\n\n\n partition_file_name += &metadata.min_ts.to_string();\n\n\n\n partition_file_name\n\n }\n\n\n\n pub fn reload_catalog(&mut self) {\n\n if Path::new(&self.catalog_path()).exists() {\n\n let file = File::open(self.catalog_path()).unwrap();\n\n let mut buf_reader = BufReader::new(file);\n\n let mut buf: Vec<u8> = Vec::new();\n\n buf_reader.read_to_end(&mut buf).unwrap();\n\n\n\n self.catalog = deserialize(&buf[..]).unwrap();\n", "file_path": "src/manager.rs", "rank": 66, "score": 25311.614101754214 }, { "content": "\n\n if Path::new(&block_path).exists() {\n\n read_block(&block_path)\n\n } else {\n\n // Lets return empty block (which should be the same as if the block does not exist)\n\n let data_type = &self.catalog.columns[block_index as usize].data_type;\n\n Block::create_block(data_type)\n\n }\n\n }\n\n\n\n pub fn dump_in_mem_partition(&mut self) {\n\n if self.current_partition.blocks.is_empty() {\n\n println!(\"Cannot dump empty partition\");\n\n return\n\n }\n\n\n\n println!(\"Dumping in memory partition having {} records\", self.current_partition.blocks[0].len());\n\n self.current_partition.prepare();\n\n let stored_path = self.store_partition(&self.current_partition);\n\n self.catalog.available_partitions.push(PartitionInfo {\n", "file_path": "src/manager.rs", "rank": 67, "score": 25311.476603395935 }, { "content": " pub fn cached_block_maybe<'a>(&'a self, block_index: u32) -> Option<&'a Block> {\n\n for tuple in &self.cache {\n\n let cached_index = tuple.0;\n\n let ref cached_block = tuple.1;\n\n if block_index == cached_index {\n\n return Option::from(cached_block);\n\n }\n\n }\n\n Option::None\n\n }\n\n\n\n// fn fetch_block(&'a self, block_index : u32) -> Block {\n\n// manager.load_block(&self.partition_info, block_index)\n\n// }\n\n\n\n// pub fn get_cached_or_load(&mut self, manager : &Manager, block_index : u32) -> &Block {\n\n// let block_option = self.find_cached_block(block_index);\n\n//\n\n// match block_option {\n\n// None => {\n", "file_path": "src/manager.rs", "rank": 68, "score": 25310.13323293712 }, { "content": "// Block::Int64Sparse(Int64SparseBlock{\n\n// data: vec![(0, 100), (1, 200)]\n\n// }),\n\n// Block::Int32Sparse(Int32SparseBlock{\n\n// data: vec![(2, 300), (3, 400)]\n\n// }),\n\n// Block::StringBlock(StringBlock{\n\n// index_data: vec![(1,0),(2,3)],\n\n// str_data: \"foobar\".as_bytes().to_vec()\n\n// })\n\n// ]\n\n// };\n\n//\n\n// manager.insert(&insert_msg);\n\n//\n\n// manager.dump_in_mem_partition();\n\n//}\n\n\n", "file_path": "src/manager.rs", "rank": 69, "score": 25309.97361242178 }, { "content": " str_data: \"ac\".as_bytes().to_vec()\n\n }),\n\n manager.load_block(part_info, 4)\n\n );\n\n\n\n assert_eq!(\n\n Block::StringBlock(StringBlock{\n\n index_data: vec![(1,0),(3,1)],\n\n str_data: \"bd\".as_bytes().to_vec()\n\n }),\n\n manager.load_block(part_info, 5)\n\n );\n\n}\n", "file_path": "src/manager.rs", "rank": 70, "score": 25309.308581710236 }, { "content": "\n\n match input_block {\n\n &Block::Int64Dense(ref in_block) => {\n\n match output_block {\n\n &mut Block::Int64Dense(ref mut out_block) => {\n\n assert_eq!(in_block.data.len(), msg.row_count as usize);\n\n out_block.data.extend(&in_block.data);\n\n },\n\n _ => panic!(\"Non matching blocks\")\n\n }\n\n },\n\n &Block::Int64Sparse(ref in_block) => {\n\n match output_block {\n\n &mut Block::Int64Sparse(ref mut out_block) => {\n\n for pair in &in_block.data {\n\n assert!(pair.0 < msg.row_count);\n\n\n\n out_block.data.push((pair.0 + current_offset as u32, pair.1));\n\n }\n\n },\n", "file_path": "src/manager.rs", "rank": 71, "score": 25308.532411160282 }, { "content": "\n\n out_block.data.push((pair.0 + current_offset as u32, pair.1));\n\n }\n\n },\n\n _ => panic!(\"Non matching blocks\")\n\n }\n\n },\n\n &Block::Int8Sparse(ref in_block) => {\n\n match output_block {\n\n &mut Block::Int8Sparse(ref mut out_block) => {\n\n for pair in &in_block.data {\n\n assert!(pair.0 < msg.row_count);\n\n\n\n out_block.data.push((pair.0 + current_offset as u32, pair.1));\n\n }\n\n },\n\n _ => panic!(\"Non matching blocks\")\n\n }\n\n },\n\n &Block::StringBlock(ref in_block) => {\n", "file_path": "src/manager.rs", "rank": 72, "score": 25307.258418549292 }, { "content": " panic!(\"Non matching blocks\");\n\n }\n\n }\n\n },\n\n }\n\n }\n\n\n\n if self.current_partition.blocks[0].len() > 200000 {\n\n self.dump_in_mem_partition();\n\n }\n\n }\n\n\n\n pub fn catalog_path(&self) -> String {\n\n let catalog_file_name = self.db_home.to_owned() + \"/catalog.bin\";\n\n catalog_file_name\n\n }\n\n\n\n pub fn partition_path(&self, metadata : &PartitionMetadata) -> String {\n\n let mut partition_file_name = self.db_home.to_owned() + \"/partitions/\";\n\n\n", "file_path": "src/manager.rs", "rank": 73, "score": 25306.515764942516 }, { "content": " }),\n\n Block::Int64Dense(Int64DenseBlock{\n\n data: vec![0, 0, 0, 0]\n\n }),\n\n Block::Int32Sparse(Int32SparseBlock{\n\n data: vec![(0, 100), (1, 100), (2, 100), (3, 100)]\n\n }),\n\n Block::StringBlock(StringBlock{\n\n index_data: vec![(1,0),(2,3),(3,6)],\n\n str_data: \"foobarfoo\".as_bytes().to_vec()\n\n }),\n\n Block::StringBlock(StringBlock{\n\n index_data: vec![(0,0),(1,1),(2,2),(3,3)],\n\n str_data: \"abcd\".as_bytes().to_vec()\n\n }),\n\n Block::StringBlock(StringBlock{\n\n index_data: vec![],\n\n str_data: \"\".as_bytes().to_vec()\n\n })\n\n ]\n", "file_path": "src/manager.rs", "rank": 74, "score": 25305.412735542286 }, { "content": " match output_block {\n\n &mut Block::StringBlock(ref mut out_block) => {\n\n for (index, pair) in in_block.index_data.iter().enumerate() {\n\n assert!(pair.0 < msg.row_count);\n\n\n\n let offset = pair.0;\n\n let position = pair.1;\n\n\n\n out_block.index_data.push((pair.0 + current_offset as u32, out_block.str_data.len()));\n\n\n\n let end_position = if index < in_block.index_data.len()-1 {\n\n in_block.index_data[index+1].1\n\n } else {\n\n in_block.str_data.len()\n\n };\n\n\n\n out_block.str_data.extend(&in_block.str_data[position..end_position])\n\n }\n\n },\n\n _ => {\n", "file_path": "src/manager.rs", "rank": 75, "score": 25305.317982072724 }, { "content": " _ => panic!(\"Non matching blocks\")\n\n }\n\n },\n\n &Block::Int32Sparse(ref in_block) => {\n\n match output_block {\n\n &mut Block::Int32Sparse(ref mut out_block) => {\n\n for pair in &in_block.data {\n\n assert!(pair.0 < msg.row_count);\n\n\n\n out_block.data.push((pair.0 + current_offset as u32, pair.1));\n\n }\n\n },\n\n _ => panic!(\"Non matching blocks\")\n\n }\n\n },\n\n &Block::Int16Sparse(ref in_block) => {\n\n match output_block {\n\n &mut Block::Int16Sparse(ref mut out_block) => {\n\n for pair in &in_block.data {\n\n assert!(pair.0 < msg.row_count);\n", "file_path": "src/manager.rs", "rank": 76, "score": 25305.05471509706 }, { "content": " } else {\n\n println!(\"Catalog does not exist. Skipping loading it.\");\n\n }\n\n }\n\n\n\n pub fn store_catalog(&self) {\n\n println!(\"Saving catalog\");\n\n fs::create_dir_all(&self.db_home);\n\n\n\n save_data(&self.catalog_path(), &self.catalog);\n\n }\n\n\n\n pub fn store_partition(&self, part : &Partition) -> String {\n\n let part_path = self.partition_path(&part.metadata);\n\n\n\n fs::create_dir_all(&part_path);\n\n\n\n save_data(&format!(\"{}/metadata.bin\", part_path), &part.metadata);\n\n for block_index in &part.metadata.existing_blocks {\n\n save_data(&format!(\"{}/block_{}.bin\", part_path, block_index), &part.blocks[*block_index as usize]);\n", "file_path": "src/manager.rs", "rank": 77, "score": 25302.248554070804 }, { "content": " }\n\n\n\n // metadata\n\n // each non-empty block\n\n\n\n println!(\"Saved partition: {}\", part_path);\n\n\n\n part_path\n\n }\n\n\n\n pub fn save_block(&self, pinfo : &PartitionInfo, block : &Block, block_index : u32) {\n\n let part_path = &pinfo.location;\n\n let block_path = format!(\"{}/block_{}.bin\", part_path, block_index);\n\n\n\n save_data(&block_path, block);\n\n }\n\n\n\n pub fn load_block(&self, pinfo : &PartitionInfo, block_index : u32) -> Block {\n\n let part_path = &pinfo.location;\n\n let block_path = format!(\"{}/block_{}.bin\", part_path, block_index);\n", "file_path": "src/manager.rs", "rank": 78, "score": 25300.98440143531 }, { "content": "// let block = manager.load_block(&self.partition_info, block_index);\n\n// self.cache.push((block_index, &block));\n\n// return &block;\n\n// }\n\n// Some(ref x) => {\n\n// return x;\n\n// }\n\n// }\n\n// }\n\n}\n\n\n", "file_path": "src/manager.rs", "rank": 79, "score": 25300.50404282418 }, { "content": " min_ts: self.current_partition.metadata.min_ts,\n\n max_ts: self.current_partition.metadata.max_ts,\n\n id: self.current_partition.metadata.id,\n\n location: stored_path\n\n });\n\n\n\n self.store_catalog();\n\n\n\n self.current_partition = Partition::new();\n\n }\n\n\n\n}\n\n\n\n\n\n\n", "file_path": "src/manager.rs", "rank": 80, "score": 25297.42516758222 }, { "content": "\n\n pub fn transpose_offsets(&mut self, new_offsets : &Vec<u32>) {\n\n for i in 0..new_offsets.len() {\n\n let record = &mut self.data[i];\n\n record.0 = new_offsets[i];\n\n }\n\n }\n\n\n\n pub fn move_data(&mut self, target : &mut TSparseBlock<T>, scan_consumer : &BlockScanConsumer) {\n\n let mut temp_block = self.filter_scan_results(scan_consumer);\n\n temp_block.transpose_offsets(&scan_consumer.matching_offsets);\n\n target.upsert(&temp_block);\n\n self.delete(&scan_consumer.matching_offsets);\n\n }\n\n\n\n // Put specific value to multiple columns\n\n pub fn multi_upsert(&mut self, offsets: &Vec<u32>, v: T) {\n\n let mut indexes:Vec<usize> = Vec::new();\n\n\n\n let mut offsets_index = 0 as usize;\n", "file_path": "src/int_blocks.rs", "rank": 81, "score": 22242.452249419075 }, { "content": " }\n\n pub fn encapsulate_in_block(self) -> Block {\n\n Block::Int16Sparse(self)\n\n }\n\n}\n\n\n\nimpl Int8SparseBlock {\n\n pub fn new() -> Int8SparseBlock {\n\n Int8SparseBlock { data: Vec::new() }\n\n }\n\n pub fn encapsulate_in_block(self) -> Block {\n\n Block::Int8Sparse(self)\n\n }\n\n}\n\n\n\nimpl Scannable<u64> for Int64DenseBlock {\n\n fn scan(&self, op : ScanComparison, val : &u64, scan_consumer : &mut BlockScanConsumer) {\n\n for (offset_usize, value) in self.data.iter().enumerate() {\n\n let offset = offset_usize as u32;\n\n match op {\n", "file_path": "src/int_blocks.rs", "rank": 82, "score": 22242.362040751486 }, { "content": " out_block\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\n\npub struct TSparseBlock<T:Clone> {\n\n pub data : Vec<(u32,T)>\n\n}\n\n\n\nimpl<T : Clone> TSparseBlock<T> {\n\n pub fn append(&mut self, o: u32, v: T) {\n\n self.data.push((o, v));\n\n }\n\n\n\n pub fn delete(&mut self, offsets: &Vec<u32>) {\n\n let mut indexes:Vec<usize> = Vec::new();\n\n\n\n let mut offsets_index = 0 as usize;\n\n let mut data_index = 0 as usize;\n\n\n", "file_path": "src/int_blocks.rs", "rank": 83, "score": 22240.7376912184 }, { "content": " }\n\n }\n\n\n\n self.index_data = new_index_data;\n\n self.str_data = new_str_data;\n\n }\n\n\n\n pub fn transpose_offsets(&mut self, new_offsets : &Vec<u32>) {\n\n for i in 0..new_offsets.len() {\n\n let record = &mut self.index_data[i];\n\n record.0 = new_offsets[i];\n\n }\n\n }\n\n\n\n pub fn move_data(&mut self, target : &mut StringBlock, scan_consumer : &BlockScanConsumer) {\n\n let mut temp_block = self.filter_scan_results(scan_consumer);\n\n temp_block.transpose_offsets(&scan_consumer.matching_offsets);\n\n\n\n target.upsert(&temp_block);\n\n self.delete(&scan_consumer.matching_offsets);\n", "file_path": "src/int_blocks.rs", "rank": 84, "score": 22239.844301348545 }, { "content": "impl Scannable<u64> for Block {\n\n fn scan(&self, op : ScanComparison, val : &u64, scan_consumer : &mut BlockScanConsumer) {\n\n match self {\n\n &Block::Int64Dense(ref b) => b.scan(op, val, scan_consumer),\n\n &Block::Int64Sparse(ref b) => b.scan(op, val, scan_consumer),\n\n &Block::Int32Sparse(ref b) => b.scan(op, &(*val as u32), scan_consumer),\n\n &Block::Int16Sparse(ref b) => b.scan(op, &(*val as u16), scan_consumer),\n\n &Block::Int8Sparse(ref b) => b.scan(op, &(*val as u8), scan_consumer),\n\n _ => panic!(\"Unrecognized u64 block type\")\n\n }\n\n }\n\n}\n\n\n\nimpl Upsertable<u64> for Block {\n\n fn multi_upsert(&mut self, offsets : &Vec<u32>, val : &u64) {\n\n match self {\n\n &mut Block::Int64Sparse(ref mut b) => b.multi_upsert(offsets, *val),\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n", "file_path": "src/int_blocks.rs", "rank": 85, "score": 22239.573597137674 }, { "content": "impl Scannable<u16> for Block {\n\n fn scan(&self, op: ScanComparison, val: &u16, scan_consumer: &mut BlockScanConsumer) {\n\n match self {\n\n &Block::Int16Sparse(ref b) => b.scan(op, val, scan_consumer),\n\n _ => println!(\"Unrecognized u16 block type\")\n\n }\n\n }\n\n}\n\n\n\nimpl Upsertable<u16> for Block {\n\n fn multi_upsert(&mut self, offsets : &Vec<u32>, val : &u16) {\n\n match self {\n\n &mut Block::Int16Sparse(ref mut b) => b.multi_upsert(offsets, *val),\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n\n\n\n fn upsert(&mut self, data : &Block) {\n\n match self {\n\n &mut Block::Int16Sparse(ref mut b) => match data {\n", "file_path": "src/int_blocks.rs", "rank": 86, "score": 22239.114812268508 }, { "content": " &ScanComparison::Gt => return s1.len() > s2.len(),\n\n &ScanComparison::GtEq => return s1.len() > s2.len(),\n\n _ => return false\n\n// _ => println!(\"Only <, <=, >=, > matches are handled here...\")\n\n }\n\n}\n\n\n\nimpl Scannable<String> for StringBlock {\n\n\n\n /// Screams naiive!\n\n fn scan(&self, op : ScanComparison, str_val : &String, scan_consumer : &mut BlockScanConsumer) {\n\n let mut prev_offset = 0 as u32;\n\n let mut prev_position = 0 as usize;\n\n let val = str_val.as_bytes();\n\n let mut index = 0;\n\n\n\n for &(offset_usize, position) in self.index_data.iter() {\n\n let size = position - prev_position;\n\n let offset = offset_usize as u32;\n\n\n", "file_path": "src/int_blocks.rs", "rank": 87, "score": 22239.11349759862 }, { "content": "\n\n return out_block;\n\n }\n\n}\n\n\n\n// As of now this is byte array essentially\n\n#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\n\npub struct StringBlock {\n\n // Pair: offset, start position in array; the end position might be implied\n\n pub index_data : Vec<(u32, usize)>,\n\n pub str_data : Vec<u8>\n\n}\n\n\n\nimpl StringBlock {\n\n pub fn new() -> StringBlock {\n\n StringBlock{ index_data: Vec::new(), str_data: Vec::new() }\n\n }\n\n\n\n pub fn delete(&mut self, offsets: &Vec<u32>) {\n\n // Because the structure is bit more complex here, lets just be naive and rewrite the str_data while updating index data?\n", "file_path": "src/int_blocks.rs", "rank": 88, "score": 22239.022849648874 }, { "content": "\n\n fn upsert(&mut self, data : &Block) {\n\n match self {\n\n &mut Block::Int64Sparse(ref mut b) => match data {\n\n &Block::Int64Sparse(ref c) => b.upsert(c),\n\n _ => panic!(\"Wrong block\")\n\n },\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n\n}\n\n\n\nimpl Scannable<u32> for Block {\n\n fn scan(&self, op: ScanComparison, val: &u32, scan_consumer: &mut BlockScanConsumer) {\n\n match self {\n\n &Block::Int32Sparse(ref b) => b.scan(op, val, scan_consumer),\n\n _ => println!(\"Unrecognized u32 block type\")\n\n }\n\n }\n\n}\n", "file_path": "src/int_blocks.rs", "rank": 89, "score": 22238.12210471934 }, { "content": " &Block::Int16Sparse(ref c) => b.upsert(c),\n\n _ => panic!(\"Wrong block type\")\n\n },\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n\n}\n\n\n\nimpl Scannable<u8> for Block {\n\n fn scan(&self, op: ScanComparison, val: &u8, scan_consumer: &mut BlockScanConsumer) {\n\n match self {\n\n &Block::Int8Sparse(ref b) => b.scan(op, val, scan_consumer),\n\n _ => println!(\"Unrecognized u8 block type\")\n\n }\n\n }\n\n}\n\n\n\nimpl Upsertable<u8> for Block {\n\n fn multi_upsert(&mut self, offsets : &Vec<u32>, val : &u8) {\n\n match self {\n", "file_path": "src/int_blocks.rs", "rank": 90, "score": 22236.884914493054 }, { "content": " &mut Block::Int8Sparse(ref mut b) => b.multi_upsert(offsets, *val),\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n\n\n\n fn upsert(&mut self, data : &Block) {\n\n match self {\n\n &mut Block::Int8Sparse(ref mut b) => match data {\n\n &Block::Int8Sparse(ref c) => b.upsert(c),\n\n _ => panic!(\"Wrong block type\")\n\n },\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\n\npub struct Int64DenseBlock {\n\n pub data : Vec<u64>\n\n}\n", "file_path": "src/int_blocks.rs", "rank": 91, "score": 22236.006006891934 }, { "content": " ScanComparison::LtEq => if value <= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Eq => if value == val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::GtEq => if value >= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Gt => if value > val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::NotEq => if value != val { scan_consumer.matching_offsets.push(offset) },\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Scannable<u32> for Int32SparseBlock {\n\n fn scan(&self, op : ScanComparison, val : &u32, scan_consumer : &mut BlockScanConsumer) {\n\n for &(offset, value_ref) in self.data.iter() {\n\n let value = &value_ref;\n\n match op {\n\n ScanComparison::Lt => if value < val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::LtEq => if value <= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Eq => if value == val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::GtEq => if value >= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Gt => if value > val { scan_consumer.matching_offsets.push(offset) },\n", "file_path": "src/int_blocks.rs", "rank": 92, "score": 22235.937467684234 }, { "content": " let size = self.str_data.len() - prev_position;\n\n let offset = prev_offset;\n\n let position = self.str_data.len();\n\n\n\n match op {\n\n ScanComparison::Eq => if size == val.len() && val == &self.str_data[prev_position..position] { scan_consumer.matching_offsets.push(prev_offset) },\n\n ScanComparison::NotEq => if size != val.len() || val != &self.str_data[prev_position..position] { scan_consumer.matching_offsets.push(prev_offset) },\n\n _ => if strings_ne_match(&self.str_data[prev_position..position], &op, val) { scan_consumer.matching_offsets.push(prev_offset) }\n\n }\n\n }\n\n\n\n }\n\n}\n\n\n\nimpl Scannable<u64> for Int64SparseBlock {\n\n fn scan(&self, op : ScanComparison, val : &u64, scan_consumer : &mut BlockScanConsumer) {\n\n for &(offset, value_ref) in self.data.iter() {\n\n let value = &value_ref;\n\n match op {\n\n ScanComparison::Lt => if value < val { scan_consumer.matching_offsets.push(offset) },\n", "file_path": "src/int_blocks.rs", "rank": 93, "score": 22235.577115721357 }, { "content": " &mut Block::Int16Sparse(ref mut c) => b.move_data(c, scan_consumer),\n\n _ => panic!(\"Not matching block types\")\n\n },\n\n &mut Block::Int8Sparse(ref mut b) => match target {\n\n &mut Block::Int8Sparse(ref mut c) => b.move_data(c, scan_consumer),\n\n _ => panic!(\"Not matching block types\")\n\n },\n\n _ => panic!(\"I don't know how to handle such block type\")\n\n }\n\n }\n\n}\n\n\n\nimpl Scannable<String> for Block {\n\n fn scan(&self, op: ScanComparison, val: &String, scan_consumer: &mut BlockScanConsumer) {\n\n match self {\n\n &Block::StringBlock(ref b) => b.scan(op, val, scan_consumer),\n\n _ => panic!(\"Wrong block type for String scan\")\n\n }\n\n }\n\n}\n", "file_path": "src/int_blocks.rs", "rank": 94, "score": 22235.311944880377 }, { "content": "}\n\n\n\nimpl Scannable<u8> for Int8SparseBlock {\n\n fn scan(&self, op : ScanComparison, val : &u8, scan_consumer : &mut BlockScanConsumer) {\n\n for &(offset, value_ref) in self.data.iter() {\n\n let value = &value_ref;\n\n match op {\n\n ScanComparison::Lt => if value < val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::LtEq => if value <= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Eq => if value == val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::GtEq => if value >= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Gt => if value > val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::NotEq => if value != val { scan_consumer.matching_offsets.push(offset) },\n\n }\n\n }\n\n }\n\n}\n\n\n\n\n", "file_path": "src/int_blocks.rs", "rank": 95, "score": 22235.29885452238 }, { "content": "\n\nimpl Int64DenseBlock {\n\n pub fn new() -> Int64DenseBlock {\n\n Int64DenseBlock { data: Vec::new() }\n\n }\n\n\n\n pub fn append(&mut self, v: u64) {\n\n self.data.push(v);\n\n }\n\n\n\n pub fn encapsulate_in_block(self) -> Block {\n\n Block::Int64Dense(self)\n\n }\n\n\n\n pub fn filter_scan_results(&self, scan_consumer : &BlockScanConsumer) -> Int64DenseBlock {\n\n let mut out_block = Int64DenseBlock::new();\n\n\n\n for index in &scan_consumer.matching_offsets {\n\n out_block.data.push(self.data[*index as usize]);\n\n }\n", "file_path": "src/int_blocks.rs", "rank": 96, "score": 22234.99800439197 }, { "content": " ScanComparison::NotEq => if value != val { scan_consumer.matching_offsets.push(offset) },\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Scannable<u16> for Int16SparseBlock {\n\n fn scan(&self, op : ScanComparison, val : &u16, scan_consumer : &mut BlockScanConsumer) {\n\n for &(offset, value_ref) in self.data.iter() {\n\n let value = &value_ref;\n\n match op {\n\n ScanComparison::Lt => if value < val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::LtEq => if value <= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Eq => if value == val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::GtEq => if value >= val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::Gt => if value > val { scan_consumer.matching_offsets.push(offset) },\n\n ScanComparison::NotEq => if value != val { scan_consumer.matching_offsets.push(offset) },\n\n }\n\n }\n\n }\n", "file_path": "src/int_blocks.rs", "rank": 97, "score": 22234.75648422312 }, { "content": "\n\nimpl Upsertable<String> for Block {\n\n fn multi_upsert(&mut self, offsets : &Vec<u32>, val : &String) {\n\n match self {\n\n &mut Block::StringBlock(ref mut b) => b.multi_upsert(offsets, val.as_bytes()),\n\n _ => panic!(\"Wrong block type for String scan\")\n\n }\n\n }\n\n\n\n fn upsert(&mut self, data : &Block) {\n\n match self {\n\n &mut Block::StringBlock(ref mut b) => match data {\n\n &Block::StringBlock(ref c) => b.upsert(c),\n\n _ => panic!(\"Wrong block type\")\n\n },\n\n _ => panic!(\"Wrong block type\")\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/int_blocks.rs", "rank": 98, "score": 22234.517001614044 }, { "content": " str_block.scan(ScanComparison::Eq, &String::from(\"bar\"), &mut consumer);\n\n assert_eq!(consumer.matching_offsets, vec![1]);\n\n\n\n consumer = BlockScanConsumer::new();\n\n str_block.scan(ScanComparison::NotEq, &String::from(\"bar\"), &mut consumer);\n\n assert_eq!(consumer.matching_offsets, vec![0,2,3]);\n\n\n\n consumer = BlockScanConsumer::new();\n\n str_block.scan(ScanComparison::Eq, &String::from(\"snafu\"), &mut consumer);\n\n assert_eq!(consumer.matching_offsets, vec![3]);\n\n}\n\n\n\n\n", "file_path": "src/int_blocks.rs", "rank": 99, "score": 22233.353144265486 } ]
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 = style.border_color(&ui.theme);\n\n widget::BorderedRectangle::new(dim)\n\n .middle_of(button_id)\n\n .graphics_for(button_id)\n\n .color(color)\n\n .border(border)\n\n .border_color(border_color)\n\n .set(rectangle_id, ui);\n\n}*/\n\n\n\n/*fn label(button_id: widget::Id, label_id: widget::Id,\n\n label: &str, style: &Style, ui: &mut UiCell)\n\n{\n\n unimplemented!()\n", "file_path": "carbide_core/src/widget/old/button.rs", "rank": 0, "score": 305777.80792378815 }, { "content": "fn move_mouse_to_widget(widget_id: widget::Id, ui: &mut Ui) {\n\n ui.xy_of(widget_id).map(|point| {\n\n let abs_xy = to_window_coordinates(point, ui);\n\n move_mouse_to_abs_coordinates(abs_xy[0], abs_xy[1], ui);\n\n });\n\n}\n\n\n", "file_path": "carbide_core/tests/ui.rs", "rank": 1, "score": 295418.70549915056 }, { "content": "pub fn is_over_widget(widget: &graph::Container, point: Point, _: &Theme) -> widget::IsOver {\n\n widget\n\n .unique_widget_state::<RoundedRectangle>()\n\n .map(|widget| widget.state.ids.polygon.into())\n\n .unwrap_or_else(|| widget.rect.is_over(point).into())\n\n}*/\n", "file_path": "carbide_core/src/widget/old/rounded_rectangle.rs", "rank": 2, "score": 294728.6887240579 }, { "content": "pub trait Action: Fn(&mut Environment) + DynClone {}\n\n\n\nimpl<I> Action for I where I: Fn(&mut Environment) + Clone {}\n\n\n\ndyn_clone::clone_trait_object!(Action);\n\n\n\n#[derive(Clone, Widget)]\n\n#[carbide_exclude(MouseEvent, KeyboardEvent, Layout)]\n\npub struct PlainButton {\n\n id: Id,\n\n #[state]\n\n focus: FocusState,\n\n child: Box<dyn Widget>,\n\n position: Position,\n\n dimension: Dimension,\n\n click: Box<dyn Action>,\n\n click_outside: Box<dyn Action>,\n\n #[state]\n\n is_hovered: BoolState,\n\n #[state]\n", "file_path": "carbide_controls/src/plain/plain_button.rs", "rank": 3, "score": 285123.7498648057 }, { "content": "/// Traits required by render that may be used as a graph node identifier.\n\n///\n\n/// This trait has a blanket implementation for all render that satisfy the bounds.\n\npub trait NodeId: 'static + Copy + Clone + PartialEq + Eq + Hash + Send {}\n\n\n\nimpl<T> NodeId for T where T: 'static + Copy + Clone + PartialEq + Eq + Hash + Send {}\n\n\n\n/// Stores the layout of all nodes within the graph.\n\n///\n\n/// All positions are relative to the centre of the `Graph` widget.\n\n///\n\n/// Nodes can be moved by \n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct Layout<NI>\n\nwhere\n\n NI: Eq + Hash,\n\n{\n\n map: HashMap<NI, Point>,\n\n}\n\n\n\nimpl<NI> Deref for Layout<NI>\n\nwhere\n\n NI: NodeId,\n", "file_path": "carbide_core/src/widget/old/graph/mod.rs", "rank": 4, "score": 284953.93804964307 }, { "content": "/// `EnvPoint` must be implemented for any type that is used as a 2D point within the\n\n/// EnvelopeEditor.\n\npub trait EnvelopePoint: Clone + PartialEq {\n\n /// A value on the X-axis of the envelope.\n\n type X: Float + ToString;\n\n /// A value on the Y-axis of the envelope.\n\n type Y: Float + ToString;\n\n /// Return the X value.\n\n fn get_x(&self) -> Self::X;\n\n /// Return the Y value.\n\n fn get_y(&self) -> Self::Y;\n\n /// Set the X value.\n\n fn set_x(&mut self, _x: Self::X);\n\n /// Set the Y value.\n\n fn set_y(&mut self, _y: Self::Y);\n\n /// Return the bezier curve depth (-1. to 1.) for the next interpolation.\n\n fn get_curve(&self) -> f32 { 1.0 }\n\n /// Set the bezier curve depth (-1. to 1.) for the next interpolation.\n\n fn set_curve(&mut self, _curve: f32) {}\n\n /// Create a new EnvPoint.\n\n fn new(_x: Self::X, _y: Self::Y) -> Self;\n\n}\n", "file_path": "carbide_core/src/widget/old/envelope_editor.rs", "rank": 5, "score": 258941.2845771939 }, { "content": "pub fn tessellate(shape: &mut dyn Shape, rectangle: &Rect, path: &dyn Fn(&mut Builder, &Rect)) {\n\n match shape.get_shape_style() {\n\n ShapeStyle::Default | ShapeStyle::Fill => {\n\n fill(path, shape, rectangle);\n\n }\n\n ShapeStyle::Stroke => {\n\n stroke(path, shape, rectangle);\n\n }\n\n ShapeStyle::FillAndStroke => {\n\n fill(path, shape, rectangle);\n\n stroke(path, shape, rectangle);\n\n }\n\n }\n\n}\n\n\n", "file_path": "carbide_core/src/widget/shape/mod.rs", "rank": 6, "score": 241756.83580462652 }, { "content": "pub fn fill(path: &dyn Fn(&mut Builder, &Rect), shape: &mut dyn Shape, rectangle: &Rect) {\n\n let position = shape.position();\n\n let dimension = shape.dimension();\n\n let triangle_store = shape.get_triangle_store_mut();\n\n\n\n if dimension != triangle_store.latest_fill_dimensions {\n\n let mut builder = Path::builder();\n\n\n\n // Let the caller decide the geometry\n\n path(&mut builder, rectangle);\n\n\n\n let path = builder.build();\n\n\n\n let mut geometry: VertexBuffers<Position, u16> = VertexBuffers::new();\n\n\n\n let mut tessellator = FillTessellator::new();\n\n\n\n let fill_options = FillOptions::default();\n\n\n\n {\n", "file_path": "carbide_core/src/widget/shape/mod.rs", "rank": 7, "score": 241756.83580462652 }, { "content": "pub fn stroke(path: &dyn Fn(&mut Builder, &Rect), shape: &mut dyn Shape, rectangle: &Rect) {\n\n let position = shape.position();\n\n let dimension = shape.dimension();\n\n let line_width = shape.get_stroke_style().get_line_width() as f32;\n\n let triangle_store = shape.get_triangle_store_mut();\n\n\n\n if dimension != triangle_store.latest_stroke_dimensions {\n\n let mut builder = Path::builder();\n\n\n\n // Let the caller decide the geometry\n\n path(&mut builder, &rectangle);\n\n\n\n let path = builder.build();\n\n\n\n let mut geometry: VertexBuffers<Position, u16> = VertexBuffers::new();\n\n\n\n let mut tessellator = StrokeTessellator::new();\n\n\n\n let mut stroke_options = StrokeOptions::default();\n\n stroke_options.line_width = line_width * 2.0;\n", "file_path": "carbide_core/src/widget/shape/mod.rs", "rank": 8, "score": 241756.8358046265 }, { "content": "pub trait Delegate<T: StateContract, W: Widget>: Fn(TState<T>, UsizeState) -> W + Clone {}\n\n\n\nimpl<I, T: StateContract, W: Widget> Delegate<T, W> for I where I: Fn(TState<T>, UsizeState) -> W + Clone {}\n\n\n\n#[derive(Clone, Widget)]\n\npub struct ForEach<T, U, W> where T: StateContract, W: Widget + Clone, U: Delegate<T, W> {\n\n id: Uuid,\n\n position: Position,\n\n dimension: Dimension,\n\n\n\n #[state] model: TState<Vec<T>>,\n\n delegate: U,\n\n\n\n children: Vec<Box<dyn Widget>>,\n\n #[state] index_offset: UsizeState,\n\n phantom: PhantomData<W>,\n\n}\n\n\n\nimpl<T: StateContract + 'static, W: Widget + Clone + 'static, U: Delegate<T, W>> ForEach<T, U, W> {\n\n pub fn new<K: Into<TState<Vec<T>>>>(model: K, delegate: U) -> Box<Self> {\n", "file_path": "carbide_core/src/widget/foreach.rs", "rank": 9, "score": 236924.420896734 }, { "content": "pub trait Shape: Widget + 'static {\n\n fn get_triangle_store_mut(&mut self) -> &mut TriangleStore;\n\n fn get_stroke_style(&self) -> StrokeStyle;\n\n fn get_shape_style(&self) -> ShapeStyle;\n\n // Todo: add primitives to before and after the shape.\n\n fn triangles(&mut self, env: &mut Environment) -> Vec<Triangle<Position>> {\n\n let mut primitives = vec![];\n\n self.get_primitives(&mut primitives, env);\n\n if primitives.len() >= 1 {\n\n match primitives.remove(0).kind {\n\n PrimitiveKind::TrianglesSingleColor { triangles, .. } => triangles,\n\n _ => {\n\n panic!(\"Can only return triangles of PrimitiveKind::TrianglesSingleColor. This error might happen if you use a rectangle with content.\")\n\n }\n\n }\n\n } else {\n\n vec![]\n\n }\n\n }\n\n}\n\n\n\ndyn_clone::clone_trait_object!(Shape);\n\nimpl Widget for Box<dyn Shape> {}\n\n\n\nimpl Debug for dyn Shape {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"Shape: {}\", self.id())\n\n }\n\n}\n\n\n", "file_path": "carbide_core/src/widget/shape/mod.rs", "rank": 10, "score": 236835.2883295271 }, { "content": "pub trait WidgetExt: Widget + Sized + 'static {\n\n fn frame<K1: Into<F64State>, K2: Into<F64State>>(self, width: K1, height: K2) -> Box<Frame> {\n\n Frame::init(width.into(), height.into(), Box::new(self))\n\n }\n\n\n\n fn rotation_3d_effect<K1: Into<F64State>, K2: Into<F64State>>(self, x: K1, y: K2) -> Box<Rotation3DEffect> {\n\n Rotation3DEffect::new(Box::new(self), x.into(), y.into())\n\n }\n\n\n\n fn rotation_effect<K1: Into<F64State>>(self, rotation: K1) -> Box<Transform> {\n\n Transform::rotation(Box::new(self), rotation)\n\n }\n\n\n\n fn scale_effect<K1: Into<F64State>>(self, scale: K1) -> Box<Transform> {\n\n Transform::scale(Box::new(self), scale)\n\n }\n\n\n\n fn scale_effect_non_uniform<K1: Into<TState<Dimension>>>(self, scale: K1) -> Box<Transform> {\n\n Transform::scale_non_uniform(Box::new(self), scale)\n\n }\n", "file_path": "carbide_core/src/widget/common/widget_ext.rs", "rank": 11, "score": 233250.58360249604 }, { "content": "// Draw the Ui.\n\nfn set_widgets(ref mut ui: carbide_core::UiCell, ids: &mut Ids) {\n\n use carbide_core::{color, widget, Colorable, Labelable, OldWidget, Positionable, Sizeable};\n\n\n\n // Construct our main `Canvas` tree.\n\n widget::Canvas::new()\n\n .flow_down(&[\n\n (\n\n ids.header,\n\n widget::Canvas::new().color(color::BLUE).pad_bottom(20.0),\n\n ),\n\n (\n\n ids.body,\n\n widget::Canvas::new().length(300.0).flow_right(&[\n\n (\n\n ids.left_column,\n\n widget::Canvas::new().color(color::LIGHT_ORANGE).pad(20.0),\n\n ),\n\n (\n\n ids.middle_column,\n\n widget::Canvas::new().color(color::ORANGE),\n", "file_path": "backends/carbide_glium/examples/canvas.rs", "rank": 12, "score": 231819.41936101572 }, { "content": "/// Set all `Widget`s within the User Interface.\n\n///\n\n/// The first time this gets called, each `Widget`'s `State` will be initialised and cached within\n\n/// the `Ui` at their given indices. Every other time this get called, the `Widget`s will avoid any\n\n/// allocations by updating the pre-existing cached state. A new graphical `Element` is only\n\n/// retrieved from a `Widget` in the case that it's `State` has changed in some way.\n\nfn set_widgets(ui: &mut carbide_core::UiCell, app: &mut DemoApp, ids: &mut Ids) {\n\n use carbide_core::{\n\n color, widget, Borderable, Colorable, Labelable, OldWidget, Positionable, Sizeable,\n\n };\n\n\n\n // We can use this `Canvas` as a parent Widget upon which we can place other widgets.\n\n widget::Canvas::new()\n\n .border(app.border_width)\n\n .pad(30.0)\n\n .color(app.bg_color)\n\n .scroll_kids()\n\n .set(ids.canvas, ui);\n\n widget::Scrollbar::x_axis(ids.canvas)\n\n .auto_hide(true)\n\n .set(ids.canvas_y_scrollbar, ui);\n\n widget::Scrollbar::y_axis(ids.canvas)\n\n .auto_hide(true)\n\n .set(ids.canvas_x_scrollbar, ui);\n\n\n\n // Text example.\n", "file_path": "backends/carbide_glium/examples/old_demo.rs", "rank": 13, "score": 230520.69259987044 }, { "content": "pub trait StateContract: Clone + Debug {}\n\n\n\nimpl<T> StateContract for T where T: Clone + Debug {}\n", "file_path": "carbide_core/src/state/mod.rs", "rank": 14, "score": 228079.49127339918 }, { "content": "fn set_widgets(ui: &mut carbide_core::UiCell, ids: &Ids, graph: &mut MyGraph, layout: &mut Layout) {\n\n /////////////////\n\n ///// GRAPH /////\n\n /////////////////\n\n //\n\n // Set the `Graph` widget.\n\n //\n\n // This returns a session on which we can begin setting nodes and edges.\n\n //\n\n // The session is used in multiple stages:\n\n //\n\n // 1. `Nodes` for setting a node widget for each node.\n\n // 2. `Edges` for setting an edge widget for each edge.\n\n // 3. `Final` for optionally displaying zoom percentage and cam position.\n\n\n\n let session = {\n\n // An identifier for each node in the graph.\n\n let node_indices = graph.node_indices();\n\n // Describe each edge in the graph as NodeSocket -> NodeSocket.\n\n let edges = graph.raw_edges().iter().map(|e| {\n", "file_path": "backends/carbide_glium/examples/graph.rs", "rank": 15, "score": 227440.96950436346 }, { "content": "fn press_mouse_button(button: MouseButton, ui: &mut Ui) {\n\n let event = Input::Press(Button::Mouse(button));\n\n ui.handle_event(event);\n\n}\n\n\n", "file_path": "carbide_core/tests/ui.rs", "rank": 16, "score": 223475.32099665503 }, { "content": "fn release_mouse_button(button: MouseButton, ui: &mut Ui) {\n\n let event = Input::Release(Button::Mouse(button));\n\n ui.handle_event(event);\n\n}\n\n\n", "file_path": "carbide_core/tests/ui.rs", "rank": 17, "score": 223475.32099665503 }, { "content": "// The position of the socket at the given index.\n\nfn socket_position(index: usize, start_pos: Point, step: [Scalar; 2]) -> Point {\n\n let x = start_pos[0] + step[0] * index as Scalar;\n\n let y = start_pos[1] + step[1] * index as Scalar;\n\n [x, y]\n\n}\n\n\n", "file_path": "carbide_core/src/widget/old/graph/node.rs", "rank": 18, "score": 218993.3631569178 }, { "content": "// The implementation for `Widget`.\n\npub fn impl_widget(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {\n\n let struct_ident = &ast.ident;\n\n let generics = &ast.generics;\n\n let wheres = &ast.generics.where_clause;\n\n\n\n let struct_attributes: HashSet<DeriveType> = parse_attributes(&ast.attrs);\n\n\n\n // Ensure we are deriving for a struct.\n\n let body = match ast.data {\n\n syn::Data::Struct(ref body) => body,\n\n _ => panic!(\"Widget can only be derived on a struct\"),\n\n };\n\n\n\n let named = match &body.fields {\n\n Fields::Named(n) => n,\n\n Fields::Unnamed(_) => {\n\n panic!(\"Unnamed field structs not supported for derive macro Widget\")\n\n }\n\n Fields::Unit => {\n\n panic!(\"Widget can only be implemented on named field structs and not unit structs\")\n", "file_path": "carbide_derive/src/widget.rs", "rank": 19, "score": 215664.25866907873 }, { "content": "/// The eight triangles that describe a rectangular border.\n\n///\n\n/// `rect` specifies the outer rectangle and `border` specifies the thickness of the border.\n\n///\n\n/// Returns `None` if `border` is less than or equal to `0`.\n\npub fn border_triangles(rect: Rect, border: Scalar) -> Option<[Triangle<Point>; 8]> {\n\n if border <= 0.0 {\n\n return None;\n\n }\n\n\n\n // Pad the edges so that the line does not exceed the bounding rect.\n\n let (l, r, b, t) = rect.l_r_b_t();\n\n let l_pad = l + border;\n\n let r_pad = r - border;\n\n let b_pad = b + border;\n\n let t_pad = t - border;\n\n\n\n // The four quads that make up the border.\n\n let r1 = [[l, t], [r_pad, t], [r_pad, t_pad], [l, t_pad]];\n\n let r2 = [[r_pad, t], [r, t], [r, b_pad], [r_pad, b_pad]];\n\n let r3 = [[l_pad, b_pad], [r, b_pad], [r, b], [l_pad, b]];\n\n let r4 = [[l, t_pad], [l_pad, t_pad], [l_pad, b], [l, b]];\n\n\n\n let (r1a, r1b) = widget::triangles::from_quad(r1);\n\n let (r2a, r2b) = widget::triangles::from_quad(r2);\n\n let (r3a, r3b) = widget::triangles::from_quad(r3);\n\n let (r4a, r4b) = widget::triangles::from_quad(r4);\n\n\n\n Some([r1a, r1b, r2a, r2b, r3a, r3b, r4a, r4b])\n\n}\n\n\n", "file_path": "carbide_core/src/widget/old/bordered_rectangle.rs", "rank": 20, "score": 215510.27633726542 }, { "content": "/// Compares two iterators to see if they yield the same thing.\n\npub fn iter_eq<A, B>(mut a: A, mut b: B) -> bool\n\n where\n\n A: Iterator,\n\n B: Iterator<Item=A::Item>,\n\n A::Item: PartialEq,\n\n{\n\n loop {\n\n match (a.next(), b.next()) {\n\n (None, None) => return true,\n\n (maybe_a, maybe_b) => {\n\n if maybe_a != maybe_b {\n\n return false;\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "carbide_core/src/utils.rs", "rank": 21, "score": 211453.3335515914 }, { "content": "#[proc_macro_derive(Widget, attributes(state, carbide_derive, carbide_exclude))]\n\npub fn widget(input: TokenStream) -> TokenStream {\n\n impl_derive(input, widget::impl_widget)\n\n}\n\n\n", "file_path": "carbide_derive/src/lib.rs", "rank": 22, "score": 209361.28064307134 }, { "content": "/// Default glium `DrawParameters` with alpha blending enabled.\n\npub fn draw_parameters() -> glium::DrawParameters<'static> {\n\n let blend = glium::Blend::alpha_blending();\n\n glium::DrawParameters {\n\n multisampling: true,\n\n blend: blend,\n\n ..Default::default()\n\n }\n\n}\n\n\n", "file_path": "backends/carbide_glium/src/lib.rs", "rank": 23, "score": 209167.7462804548 }, { "content": "fn draw_heart<GS: GlobalStateContract>(_: OldRect, mut context: Context) -> Context {\n\n context.move_to(75.0, 40.0);\n\n context.bezier_curve_to(Position::new(75.0, 37.0), Position::new(70.0, 25.0), Position::new(50.0, 25.0));\n\n context.bezier_curve_to(Position::new(20.0, 25.0), Position::new(20.0, 62.5), Position::new(20.0, 62.5));\n\n context.bezier_curve_to(Position::new(20.0, 80.0), Position::new(40.0, 102.0), Position::new(75.0, 120.0));\n\n context.bezier_curve_to(Position::new(110.0, 102.0), Position::new(130.0, 80.0), Position::new(130.0, 62.5));\n\n context.bezier_curve_to(Position::new(130.0, 62.5), Position::new(130.0, 25.0), Position::new(100.0, 25.0));\n\n context.bezier_curve_to(Position::new(85.0, 25.0), Position::new(75.0, 37.0), Position::new(75.0, 40.0));\n\n context.close_path();\n\n context.set_fill_style(EnvironmentColor::Accent);\n\n context.fill();\n\n\n\n context\n\n}\n", "file_path": "backends/carbide_wgpu/examples/hello_wgpu.rs", "rank": 24, "score": 207573.20299749228 }, { "content": "/// Produce an iterator yielding the outer points of a rounded rectangle.\n\n///\n\n/// - `rect` describes the location and dimensions\n\n/// - `radius` describes the radius of the corner circles.\n\n/// - `corner_resolution` the number of lines used to draw each corner.\n\npub fn points(rect: Rect, radius: Scalar, corner_resolution: usize) -> Points {\n\n let (r, t) = (rect.x.end, rect.y.end);\n\n // First corner is the top right corner.\n\n let radius_2 = radius * 2.0;\n\n let corner_rect = Rect {\n\n x: Range { start: r - radius_2, end: r },\n\n y: Range { start: t - radius_2, end: t },\n\n };\n\n let corner = Circumference::new_section(corner_rect, corner_resolution, CORNER_RADIANS);\n\n Points {\n\n rect,\n\n corner_rect,\n\n corner_index: 0,\n\n corner_resolution,\n\n corner_points: corner,\n\n }\n\n}\n\n\n\nimpl Iterator for Points {\n\n type Item = Point;\n", "file_path": "carbide_core/src/widget/old/rounded_rectangle.rs", "rank": 25, "score": 206401.38398403133 }, { "content": "// The implementation for `WidgetStyle_`.\n\n//\n\n// The same as `WidgetStyle` but only for use within the carbide crate itself.\n\npub fn impl_widget_style_(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {\n\n // let crate_tokens = syn::Ident::from(syn::token::CapSelf::default());\n\n let crate_tokens = None;\n\n let params = params(ast).unwrap();\n\n let impl_tokens = impl_tokens(&params, crate_tokens);\n\n let dummy_const = &params.dummy_const;\n\n quote! {\n\n #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]\n\n const #dummy_const: () = {\n\n #impl_tokens\n\n };\n\n }\n\n}\n\n\n", "file_path": "carbide_derive/src/style.rs", "rank": 26, "score": 200319.96712942395 }, { "content": "// The implementation for `WidgetCommon_`.\n\n//\n\n// The same as `WidgetCommon` but only for use within the carbide crate itself.\n\npub fn impl_widget_common_(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {\n\n let ident = &ast.ident;\n\n let common_field = common_builder_field(ast).unwrap();\n\n let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();\n\n let dummy_const = syn::Ident::new(\n\n &format!(\"_IMPL_WIDGET_COMMON_FOR_{}\", ident),\n\n proc_macro2::Span::call_site(),\n\n );\n\n\n\n let impl_item = quote! {\n\n impl #impl_generics ::widget::Common for #ident #ty_generics #where_clause {\n\n fn common(&self) -> &::widget::CommonBuilder {\n\n &self.#common_field\n\n }\n\n fn common_mut(&mut self) -> &mut ::widget::CommonBuilder {\n\n &mut self.#common_field\n\n }\n\n }\n\n };\n\n\n\n quote! {\n\n #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]\n\n const #dummy_const: () = {\n\n #impl_item\n\n };\n\n }\n\n}\n\n\n", "file_path": "carbide_derive/src/common.rs", "rank": 27, "score": 200319.96712942395 }, { "content": "// The implementation for `WidgetStyle`.\n\n//\n\n// This generates an accessor method for every field in the struct\n\npub fn impl_widget_style(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {\n\n let crate_tokens = Some(syn::Ident::new(\"_carbide\", proc_macro2::Span::call_site()));\n\n let params = params(ast).unwrap();\n\n let impl_tokens = impl_tokens(&params, crate_tokens);\n\n let dummy_const = &params.dummy_const;\n\n quote! {\n\n #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]\n\n const #dummy_const: () = {\n\n extern crate carbide_core as _carbide;\n\n #impl_tokens\n\n };\n\n }\n\n}\n\n\n", "file_path": "carbide_derive/src/style.rs", "rank": 28, "score": 200319.2583197576 }, { "content": "// The implementation for `WidgetCommon`.\n\npub fn impl_widget_common(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {\n\n let ident = &ast.ident;\n\n let common_field = common_builder_field(ast).unwrap();\n\n let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();\n\n let dummy_const = syn::Ident::new(\n\n &format!(\"_IMPL_WIDGET_COMMON_FOR_{}\", ident),\n\n proc_macro2::Span::call_site(),\n\n );\n\n\n\n let impl_item = quote! {\n\n impl #impl_generics _carbide::widget::Common for #ident #ty_generics #where_clause {\n\n fn common(&self) -> &_carbide::widget::CommonBuilder {\n\n &self.#common_field\n\n }\n\n fn common_mut(&mut self) -> &mut _carbide::widget::CommonBuilder {\n\n &mut self.#common_field\n\n }\n\n }\n\n };\n\n\n\n quote! {\n\n #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]\n\n const #dummy_const: () = {\n\n extern crate carbide_core as _carbide;\n\n #impl_item\n\n };\n\n }\n\n}\n\n\n", "file_path": "carbide_derive/src/common.rs", "rank": 29, "score": 200314.09949578042 }, { "content": "pub fn new_diffuse(\n\n device: &Device,\n\n image: &Image,\n\n atlas_cache_tex: &Texture,\n\n layout: &BindGroupLayout,\n\n) -> DiffuseBindGroup {\n\n device.create_bind_group(&wgpu::BindGroupDescriptor {\n\n layout,\n\n entries: &[\n\n wgpu::BindGroupEntry {\n\n binding: 0,\n\n resource: wgpu::BindingResource::TextureView(&image.texture.view),\n\n },\n\n wgpu::BindGroupEntry {\n\n binding: 1,\n\n resource: wgpu::BindingResource::Sampler(&image.texture.sampler),\n\n },\n\n wgpu::BindGroupEntry {\n\n binding: 2,\n\n resource: wgpu::BindingResource::TextureView(\n\n &atlas_cache_tex.create_view(&wgpu::TextureViewDescriptor::default()),\n\n ),\n\n },\n\n ],\n\n label: Some(\"diffuse_bind_group\"),\n\n })\n\n}\n", "file_path": "backends/carbide_wgpu/src/diffuse_bind_group.rs", "rank": 30, "score": 194322.57625160489 }, { "content": "pub trait MapMut<FROM: StateContract + 'static, TO: StateContract + 'static>:\n\nfor<'a> Fn(&'a mut FROM) -> &'a mut TO + DynClone\n\n{}\n\n\n\nimpl<T, FROM: StateContract + 'static, TO: StateContract + 'static> Map<FROM, TO> for T where\n\n T: for<'a> Fn(&'a FROM) -> &'a TO + DynClone\n\n{}\n\n\n\nimpl<T, FROM: StateContract + 'static, TO: StateContract + 'static> MapMut<FROM, TO> for T where\n\n T: for<'a> Fn(&'a mut FROM) -> &'a mut TO + DynClone\n\n{}\n\n\n\ndyn_clone::clone_trait_object!(<FROM: StateContract + 'static, TO: StateContract + 'static> Map<FROM, TO>);\n\ndyn_clone::clone_trait_object!(<FROM: StateContract + 'static, TO: StateContract + 'static> MapMut<FROM, TO>);\n\n*/", "file_path": "carbide_core/src/state/map_state.rs", "rank": 31, "score": 193510.6810467622 }, { "content": "///\n\n/// Returns `None` if there is no node for the given `Id` or if the `socket_index` is out of range.\n\npub fn socket_rect(\n\n node_id: widget::Id,\n\n socket_type: SocketType,\n\n socket_index: usize,\n\n ui: &Ui,\n\n) -> Option<Rect> {\n\n ui.widget_graph()\n\n .widget(node_id)\n\n .and_then(|container| {\n\n let unique = container.state_and_style::<State, Style>();\n\n let &graph::UniqueWidgetState { ref state, ref style } = match unique {\n\n None => return None,\n\n Some(unique) => unique,\n\n };\n\n let rect = container.rect;\n\n let border = style.border(&ui.theme);\n\n let socket_length = style.socket_length(&ui.theme);\n\n\n\n let (n_sockets, layout) = match socket_type {\n\n SocketType::Input => (state.inputs, style.input_socket_layout(&ui.theme)),\n", "file_path": "carbide_core/src/widget/old/graph/node.rs", "rank": 32, "score": 191647.44464953875 }, { "content": "pub trait Widget: Event + Layout + Render + Focusable + DynClone {}\n\n\n\n//impl<S, T> Widget<S> for T where T: Event<S> + Layout<S> + Render<S> + DynClone {}\n\n\n\nimpl Widget for Box<dyn Widget> {}\n\n\n\ndyn_clone::clone_trait_object!(Widget);\n\n\n\n//This does not currently work with intellisense\n\n//impl<T> WidgetExt for T where T: Widget + 'static {}\n\n\n\nimpl<T: Widget + ?Sized> CommonWidget for Box<T> {\n\n fn id(&self) -> Id {\n\n self.deref().id()\n\n }\n\n\n\n fn set_id(&mut self, id: Id) {\n\n self.deref_mut().set_id(id);\n\n }\n\n\n", "file_path": "carbide_core/src/widget/common/widget.rs", "rank": 33, "score": 191017.60447996517 }, { "content": "pub trait State<T>: DynClone + Debug\n\n where\n\n T: StateContract,\n\n{\n\n /// This should take the state from the environment to hold locally in the implementer.\n\n /// Other implementations could also take copies of global_state, and apply mappings to other\n\n /// states.\n\n /// This will always be the first thing called for the states of a widget when retrieving an\n\n /// event. This makes sure the local and other states are always up to date when recieving\n\n /// an event.\n\n fn capture_state(&mut self, env: &mut Environment);\n\n\n\n /// This releases local state from the widget back into the environment. This is called\n\n /// after the event has been processed in a widget, but before the children of the widget\n\n /// has is being processed. This makes sure the state is always available for the widget\n\n /// being processed.\n\n fn release_state(&mut self, env: &mut Environment);\n\n\n\n /// This retrieves a immutable reference to the value contained in the state.\n\n /// This type implements deref to get a reference to the actual value. The valueRef\n", "file_path": "carbide_core/src/state/state.rs", "rank": 34, "score": 189204.05503754847 }, { "content": "/// An iterator yielding triangles for a rounded border.\n\n///\n\n/// Clamps the thickness of the border to half the smallest dimension of the rectangle to\n\n/// ensure the bounds of the `rect` are not exceeded.\n\npub fn rounded_border_triangles(\n\n rect: Rect,\n\n thickness: Scalar,\n\n radius: Scalar,\n\n corner_resolution: usize,\n\n) -> RoundedBorderTriangles {\n\n RoundedBorderTriangles::new(rect, thickness, radius, corner_resolution)\n\n}\n\n\n\n/// An iterator yielding triangles for a rounded border.\n\n#[derive(Clone)]\n\npub struct RoundedBorderTriangles {\n\n outer: widget::old::rounded_rectangle::Points,\n\n inner: widget::old::rounded_rectangle::Points,\n\n outer_end: Option<Point>,\n\n inner_end: Option<Point>,\n\n last_points: [Point; 2],\n\n is_next_outer: bool,\n\n}\n\n\n", "file_path": "carbide_core/src/widget/old/bordered_rectangle.rs", "rank": 35, "score": 188823.1373024727 }, { "content": "// Declare the `WidgetId`s and instantiate the widgets.\n\nfn set_ui(ref mut ui: carbide_core::UiCell, list: &mut [bool], ids: &Ids) {\n\n use carbide_core::{widget, Colorable, Labelable, OldWidget, Positionable, Sizeable};\n\n\n\n widget::Canvas::new()\n\n .color(carbide_core::color::DARK_CHARCOAL)\n\n .set(ids.canvas, ui);\n\n\n\n let (mut items, scrollbar) = widget::List::flow_down(list.len())\n\n .item_size(50.0)\n\n .scrollbar_on_top()\n\n .middle_of(ids.canvas)\n\n .wh_of(ids.canvas)\n\n .set(ids.list, ui);\n\n\n\n while let Some(item) = items.next(ui) {\n\n let i = item.i;\n\n let label = format!(\"item {}: {}\", i, list[i]);\n\n let toggle = widget::Toggle::new(list[i])\n\n .label(&label)\n\n .label_color(carbide_core::color::WHITE)\n", "file_path": "backends/carbide_glium/examples/list.rs", "rank": 36, "score": 187986.82438497135 }, { "content": "pub trait TextSpanGenerator: DynClone + Debug {\n\n fn generate(&self, string: &str, style: &TextStyle, env: &mut Environment) -> Vec<TextSpan>;\n\n}\n\n\n\ndyn_clone::clone_trait_object!(TextSpanGenerator);\n\n\n\n#[derive(Debug, Clone)]\n\npub struct NoStyleTextSpanGenerator;\n\n\n\nimpl TextSpanGenerator for NoStyleTextSpanGenerator {\n\n fn generate(&self, string: &str, style: &TextStyle, env: &mut Environment) -> Vec<TextSpan> {\n\n TextSpan::new(string, style, env)\n\n }\n\n}\n", "file_path": "carbide_core/src/text/text_span_generator.rs", "rank": 37, "score": 184662.93544599932 }, { "content": "// Declare the `WidgetId`s and instantiate the widgets.\n\nfn set_ui(ref mut ui: carbide_core::UiCell, ids: &Ids, demo_text: &mut String) {\n\n use carbide_core::{color, widget, Colorable, OldWidget, Positionable, Sizeable};\n\n\n\n widget::Canvas::new()\n\n .scroll_kids_vertically()\n\n .color(color::DARK_CHARCOAL)\n\n .set(ids.canvas, ui);\n\n\n\n for edit in widget::TextEdit::new(demo_text)\n\n .color(color::WHITE)\n\n .padded_w_of(ids.canvas, 20.0)\n\n .mid_top_of(ids.canvas)\n\n .center_justify()\n\n .line_spacing(2.5)\n\n //.restrict_to_height(false) // Let the height grow infinitely and scroll.\n\n .set(ids.text_edit, ui)\n\n {\n\n *demo_text = edit;\n\n }\n\n\n\n widget::Scrollbar::y_axis(ids.canvas)\n\n .auto_hide(true)\n\n .set(ids.scrollbar, ui);\n\n}\n", "file_path": "backends/carbide_glium/examples/text_edit.rs", "rank": 38, "score": 184209.72073409305 }, { "content": "/// The way in which the `List`'s items are sized. E.g. `Fired` or `Dynamic`.\n\npub trait ItemSize: Sized + Clone + Copy {\n\n\n\n // /// Update the `List` widget.\n\n /*fn update_list<D>(List<D, Self>, widget::UpdateArgs<List<D, Self>>)\n\n -> <List<D, Self> as OldWidget>::Event\n\n where D: Direction;\n\n\n\n /// Set the size for the given item `widget` and return it.\n\n fn size_item<W, D>(&self, widget: W, breadth: Scalar) -> W\n\n where W: OldWidget,\n\n D: Direction;*/\n\n}\n\n\n\n/// Unique styling for the `List`.\n\n#[derive(Copy, Clone, Debug, Default, PartialEq, WidgetStyle_)]\n\npub struct Style {\n\n /// The width of the scrollbar if it is visible.\n\n #[carbide(default = \"None\")]\n\n pub scrollbar_thickness: Option<Option<Scalar>>,\n\n /// The color of the scrollbar if it is visible.\n", "file_path": "carbide_core/src/widget/old/list.rs", "rank": 39, "score": 183828.5794155963 }, { "content": "// This will return the texture description of the secondary image. This is used as a copy destination\n\n// when for example applying a filter.\n\npub fn secondary_render_tex_desc([width, height]: [u32; 2]) -> wgpu::TextureDescriptor<'static> {\n\n let depth_or_array_layers = 1;\n\n let texture_extent = wgpu::Extent3d {\n\n width,\n\n height,\n\n depth_or_array_layers,\n\n };\n\n wgpu::TextureDescriptor {\n\n label: Some(\"carbide_wgpu_secondary_render_tex\"),\n\n size: texture_extent,\n\n mip_level_count: 1,\n\n sample_count: 1,\n\n dimension: wgpu::TextureDimension::D2,\n\n format: TextureFormat::Bgra8UnormSrgb,\n\n usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,\n\n }\n\n}\n\n\n", "file_path": "backends/carbide_wgpu/src/renderer.rs", "rank": 40, "score": 182159.0008476983 }, { "content": "pub fn main_render_tex_desc([width, height]: [u32; 2]) -> wgpu::TextureDescriptor<'static> {\n\n let depth_or_array_layers = 1;\n\n let texture_extent = wgpu::Extent3d {\n\n width,\n\n height,\n\n depth_or_array_layers,\n\n };\n\n wgpu::TextureDescriptor {\n\n label: Some(\"carbide_wgpu_main_render_tex\"),\n\n size: texture_extent,\n\n mip_level_count: 1,\n\n sample_count: 1,\n\n dimension: wgpu::TextureDimension::D2,\n\n format: TextureFormat::Bgra8UnormSrgb,\n\n usage: wgpu::TextureUsages::RENDER_ATTACHMENT | TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,\n\n }\n\n}\n\n\n", "file_path": "backends/carbide_wgpu/src/renderer.rs", "rank": 41, "score": 182153.8586893641 }, { "content": "pub fn atlas_cache_tex_desc([width, height]: [u32; 2]) -> wgpu::TextureDescriptor<'static> {\n\n let depth_or_array_layers = 1;\n\n let texture_extent = wgpu::Extent3d {\n\n width,\n\n height,\n\n depth_or_array_layers,\n\n };\n\n wgpu::TextureDescriptor {\n\n label: Some(\"carbide_wgpu_atlas_cache_texture\"),\n\n size: texture_extent,\n\n mip_level_count: 1,\n\n sample_count: 1,\n\n dimension: wgpu::TextureDimension::D2,\n\n format: TextureFormat::Rgba8UnormSrgb,\n\n usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,\n\n }\n\n}\n", "file_path": "backends/carbide_wgpu/src/renderer.rs", "rank": 42, "score": 182153.8586893641 }, { "content": "#[derive(Default)]\n\nstruct TypeWidgetIds {\n\n // The index of the next `widget::Id` to use for this type.\n\n next_index: usize,\n\n // The list of widget IDs.\n\n widget_ids: Vec<widget::Id>,\n\n}\n\n\n\nimpl TypeWidgetIds {\n\n // Return the next `widget::Id` for a widget of the given type.\n\n //\n\n // If there are no more `Id`s available for the type, a new one will be generated from the\n\n // given `widget::id::Generator`.\n\n fn next_id(&mut self, generator: &mut widget::old::id::Generator) -> widget::Id {\n\n loop {\n\n match self.widget_ids.get(self.next_index).map(|&id| id) {\n\n None => self.widget_ids.push(generator.next()),\n\n Some(id) => {\n\n self.next_index += 1;\n\n break id;\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\n// A mapping from render to their list of IDs.\n", "file_path": "carbide_core/src/widget/old/graph/mod.rs", "rank": 43, "score": 181557.73827301373 }, { "content": "fn set_ui(ref mut ui: carbide_core::UiCell, ids: &Ids) {\n\n use carbide_core::widget::{Canvas, Circle, Ellipse, Line, PointPath, Polygon, Rectangle};\n\n use carbide_core::{OldWidget, Positionable};\n\n use std::iter::once;\n\n\n\n // The background canvas upon which we'll place our widgets.\n\n Canvas::new().pad(80.0).set(ids.canvas, ui);\n\n\n\n Line::centred([-40.0, -40.0], [40.0, 40.0])\n\n .top_left_of(ids.canvas)\n\n .set(ids.line, ui);\n\n\n\n let left = [-40.0, -40.0];\n\n let top = [0.0, 40.0];\n\n let right = [40.0, -40.0];\n\n let points = once(left).chain(once(top)).chain(once(right));\n\n PointPath::centred(points)\n\n .down(80.0)\n\n .set(ids.point_path, ui);\n\n\n", "file_path": "backends/carbide_glium/examples/primitives.rs", "rank": 44, "score": 176555.74767134298 }, { "content": "#[derive(Default)]\n\nstruct WidgetIdMap<NI>\n\nwhere\n\n NI: NodeId,\n\n{\n\n // A map from render to their available `widget::Id`s\n\n type_widget_ids: HashMap<TypeId, TypeWidgetIds>,\n\n // A map from node IDs to their `widget::Id`.\n\n //\n\n // This is cleared at the end of each `Widget::update` and filled during the `Node`\n\n // instantiation phase.\n\n node_widget_ids: HashMap<NI, widget::Id>,\n\n}\n\n\n\nimpl<NI> WidgetIdMap<NI>\n\nwhere\n\n NI: NodeId,\n\n{\n\n // Resets the index for every `TypeWidgetIds` list to `0`.\n\n //\n\n // This should be called at the beginning of the `Graph` update to ensure each widget\n", "file_path": "carbide_core/src/widget/old/graph/mod.rs", "rank": 45, "score": 176300.6906218084 }, { "content": "#[proc_macro_derive(WidgetStyle_, attributes(carbide, default))]\n\npub fn widget_style_(input: TokenStream) -> TokenStream {\n\n impl_derive(input, style::impl_widget_style_)\n\n}\n\n\n", "file_path": "carbide_derive/src/lib.rs", "rank": 46, "score": 175947.88289854705 }, { "content": "#[proc_macro_derive(WidgetStyle, attributes(carbide, default))]\n\npub fn widget_style(input: TokenStream) -> TokenStream {\n\n impl_derive(input, style::impl_widget_style)\n\n}\n\n\n\n// The implementation for the `WidgetStyle_` trait derivation (aka `carbide_core::widget::Style`).\n\n//\n\n// Note that this is identical to the `WidgetStyle_` trait, but only for use within the carbide\n\n// crate itself.\n", "file_path": "carbide_derive/src/lib.rs", "rank": 47, "score": 175947.88289854705 }, { "content": "#[proc_macro_derive(WidgetCommon, attributes(carbide, common_builder))]\n\npub fn widget_common(input: TokenStream) -> TokenStream {\n\n impl_derive(input, common::impl_widget_common)\n\n}\n\n\n\n// The implementation for the `WidgetCommon_` trait derivation (aka `carbide_core::widget::Common`).\n\n//\n\n// Note that this is identical to the `WidgetCommon` trait, but only for use within the carbide\n\n// crate itself.\n", "file_path": "carbide_derive/src/lib.rs", "rank": 48, "score": 175942.3439112849 }, { "content": "#[proc_macro_derive(WidgetCommon_, attributes(carbide, common_builder))]\n\npub fn widget_common_(input: TokenStream) -> TokenStream {\n\n impl_derive(input, common::impl_widget_common_)\n\n}\n\n\n\n// The implementation for the `WidgetStyle` trait derivation (aka `carbide_core::widget::Style`).\n", "file_path": "carbide_derive/src/lib.rs", "rank": 49, "score": 175942.3439112849 }, { "content": "/// Types used as vertices that make up a list of triangles.\n\npub trait Vertex: Clone + Copy + PartialEq {\n\n /// The x y location of the vertex.\n\n fn point(&self) -> Position;\n\n /// Add the given vector onto the position of self and return the result.\n\n fn add_vertex(self, other: Position) -> Self;\n\n fn offset(&mut self, other: Position);\n\n}\n\n\n\nimpl Vertex for Position {\n\n fn point(&self) -> Position {\n\n *self\n\n }\n\n\n\n fn add_vertex(self, add: Position) -> Self {\n\n self + add\n\n }\n\n\n\n fn offset(&mut self, other: Position) {\n\n *self = *self + other;\n\n }\n", "file_path": "carbide_core/src/draw/shape/vertex.rs", "rank": 50, "score": 174645.51481309137 }, { "content": "/// Bezier estimation function based on an iterative approach. This function\n\n/// will fail if multiple y values can be had for a single x. This excludes some input,\n\n/// but the input is not validated.\n\npub fn cubic_bezier(x: f64, p1: Position, p2: Position) -> f64 {\n\n let precision = 0.001;\n\n let mut start = 0.0;\n\n let mut end = 1.0;\n\n loop {\n\n let midpoint = (start + end) / 2.0;\n\n let estimate = cubic_helper(p1.x, p2.x, midpoint);\n\n if (x - estimate).abs() < precision {\n\n return cubic_helper(p1.y, p2.y, midpoint);\n\n }\n\n if estimate < x {\n\n start = midpoint;\n\n } else {\n\n end = midpoint;\n\n }\n\n }\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 51, "score": 174628.7297551026 }, { "content": "fn test() {\n\n use ui::UiBuilder;\n\n use widget::{self, OldWidget};\n\n\n\n widget_ids! {\n\n /// Testing generated Ids doc comments.\n\n #[derive(Clone)]\n\n pub struct Ids {\n\n button,\n\n toggles[],\n\n }\n\n }\n\n\n\n let mut ui = UiBuilder::new([800.0, 600.0]).build();\n\n let mut ids = Ids::new(ui.widget_id_generator());\n\n\n\n for _ in 0..10 {\n\n let ref mut ui = ui.set_widgets();\n\n\n\n // Single button index.\n\n widget::Button::new().set(ids.button, ui);\n\n\n\n // Lazily generated toggle indices.\n\n ids.toggles.resize(5, &mut ui.widget_id_generator());\n\n for &id in ids.toggles.iter() {\n\n widget::Toggle::new(true).set(id, ui);\n\n }\n\n }\n\n}*/\n\n/*\n", "file_path": "carbide_core/src/widget/old/id.rs", "rank": 52, "score": 169358.99175308328 }, { "content": "/// Calculate the default height for the **TitleBar**'s rect.\n\npub fn calc_height(font_size: FontSize) -> Scalar {\n\n font_size as Scalar + LABEL_PADDING * 2.0\n\n}\n\n\n\n\n\n/*impl<'a> OldWidget for TitleBar<'a> {\n\n type State = State;\n\n type Style = Style;\n\n type Event = ();\n\n\n\n fn init_state(&self, id_gen: widget::id::Generator) -> Self::State {\n\n State {\n\n ids: Ids::new(id_gen),\n\n }\n\n }\n\n\n\n fn style(&self) -> Self::Style {\n\n self.style.clone()\n\n }\n\n\n", "file_path": "carbide_core/src/widget/old/title_bar.rs", "rank": 53, "score": 168493.23155172754 }, { "content": "fn set_ui(ref mut ui: carbide_core::UiCell, ids: &Ids, fonts: &Fonts) {\n\n use carbide_core::{color, widget, Colorable, OldWidget, Positionable, Sizeable};\n\n\n\n // Our `Canvas` tree, upon which we will place our text widgets.\n\n widget::Canvas::new()\n\n .flow_right(&[\n\n (ids.left_col, widget::Canvas::new().color(color::BLACK)),\n\n (\n\n ids.middle_col,\n\n widget::Canvas::new().color(color::DARK_CHARCOAL),\n\n ),\n\n (ids.right_col, widget::Canvas::new().color(color::CHARCOAL)),\n\n ])\n\n .set(ids.master, ui);\n\n\n\n const DEMO_TEXT: &'static str = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. \\\n\n Mauris aliquet porttitor tellus vel euismod. Integer lobortis volutpat bibendum. Nulla \\\n\n finibus odio nec elit condimentum, rhoncus fermentum purus lacinia. Interdum et malesuada \\\n\n fames ac ante ipsum primis in faucibus. Cras rhoncus nisi nec dolor bibendum pellentesque. \\\n\n Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\\n", "file_path": "backends/carbide_glium/examples/text.rs", "rank": 54, "score": 168290.60772116226 }, { "content": "/// Simplify the constructor for a `Primitive`.\n\npub fn new_primitive(kind: PrimitiveKind, rect: Rect) -> Primitive {\n\n Primitive { kind, rect }\n\n}\n", "file_path": "carbide_core/src/render/util.rs", "rank": 55, "score": 168217.36243067504 }, { "content": "// Pushes an event onto the given global input with a default drag threshold.\n\nfn push_event(input: &mut input::Global, event: event::Event) {\n\n input.push_event(event);\n\n}\n\n\n", "file_path": "carbide_core/tests/widget_input.rs", "rank": 56, "score": 165800.89971344633 }, { "content": "#[test]\n\n#[allow(unused_variables)]\n\nfn test_invocation_variations() {\n\n use ui::UiBuilder;\n\n\n\n widget_ids! { struct A { foo, bar } }\n\n widget_ids! { pub struct B { foo, bar } }\n\n widget_ids! { struct C { foo, bar, } }\n\n widget_ids! { pub struct D { foo, bar, } }\n\n widget_ids! { struct E { foo[], bar } }\n\n widget_ids! { pub struct F { foo, bar[] } }\n\n widget_ids! { struct G { foo[], bar, } }\n\n widget_ids! { pub struct H { foo, bar[], } }\n\n\n\n let mut ui = UiBuilder::new([800.0, 600.0]).build();\n\n let mut ui = ui.set_widgets();\n\n let a = A::new(ui.widget_id_generator());\n\n let b = B::new(ui.widget_id_generator());\n\n let c = C::new(ui.widget_id_generator());\n\n let d = D::new(ui.widget_id_generator());\n\n let e = E::new(ui.widget_id_generator());\n\n let f = F::new(ui.widget_id_generator());\n\n let g = G::new(ui.widget_id_generator());\n\n let h = H::new(ui.widget_id_generator());\n\n}\n\n*/", "file_path": "carbide_core/src/widget/old/id.rs", "rank": 57, "score": 163030.599708851 }, { "content": "/// Returns `Borrowed` `elems` if `elems` contains the same elements as yielded by `new_elems`.\n\n///\n\n/// Allocates a new `Vec<T>` and returns `Owned` if either the number of elements or the elements\n\n/// themselves differ.\n\npub fn write_if_different<T, I>(elems: &[T], new_elems: I) -> Cow<[T]>\n\n where\n\n T: PartialEq + Clone,\n\n I: IntoIterator<Item=T>,\n\n{\n\n match iter_diff(elems.iter(), new_elems.into_iter()) {\n\n Some(IterDiff::FirstMismatch(i, mismatch)) => {\n\n Cow::Owned(elems[0..i].iter().cloned().chain(mismatch).collect())\n\n }\n\n Some(IterDiff::Longer(remaining)) => {\n\n Cow::Owned(elems.iter().cloned().chain(remaining).collect())\n\n }\n\n Some(IterDiff::Shorter(num_new_elems)) => {\n\n Cow::Owned(elems.iter().cloned().take(num_new_elems).collect())\n\n }\n\n None => Cow::Borrowed(elems),\n\n }\n\n}\n\n\n", "file_path": "carbide_core/src/utils.rs", "rank": 58, "score": 162202.57432276156 }, { "content": "fn to_window_coordinates(xy: Point, ui: &Ui) -> Point {\n\n let x = (ui.win_w / 2.0) + xy[0];\n\n let y = (ui.win_h / 2.0) - xy[1];\n\n [x, y]\n\n}\n\n\n", "file_path": "carbide_core/tests/ui.rs", "rank": 59, "score": 160383.18212731509 }, { "content": "/// Create a radial gradient.\n\npub fn radial(\n\n start: (f64, f64),\n\n start_r: f64,\n\n end: (f64, f64),\n\n end_r: f64,\n\n colors: Vec<(f64, Color)>,\n\n) -> Gradient {\n\n Gradient::Radial(start, start_r, end, end_r, colors)\n\n}\n\n\n\n/// Built-in colors.\n\n///\n\n/// These colors come from the\n\n/// [Tango palette](http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines) which provides\n\n/// aesthetically reasonable defaults for colors. Each color also comes with a light and dark\n\n/// version.\n\n\n\nmacro_rules! make_color {\n\n ($r:expr, $g:expr, $b:expr) => {\n\n Color::Rgba($r as f32 / 255.0, $g as f32 / 255.0, $b as f32 / 255.0, 1.0)\n", "file_path": "carbide_core/src/color.rs", "rank": 60, "score": 158437.3297747586 }, { "content": "pub trait Map<FROM: StateContract + 'static, TO: StateContract + 'static>:\n\nfor<'a> Fn(&'a FROM) -> &'a TO + DynClone\n\n{}\n\n\n", "file_path": "carbide_core/src/state/map_state.rs", "rank": 61, "score": 155059.35198260823 }, { "content": "// A wrapper around an owned glyph cache, providing `Debug` and `Deref` impls.\n\nstruct GlyphCache(RustTypeGlyphCache<'static>);\n\n\n", "file_path": "carbide_core/src/mesh/mesh.rs", "rank": 62, "score": 154021.52333486264 }, { "content": "pub fn init_logger() {\n\n env_logger::init();\n\n}", "file_path": "backends/carbide_wgpu/src/lib.rs", "rank": 63, "score": 153950.09977112792 }, { "content": "pub fn main() {\n\n const WIDTH: u32 = carbide_example_shared::WIN_W;\n\n const HEIGHT: u32 = carbide_example_shared::WIN_H;\n\n\n\n // Construct the window.\n\n let mut window: PistonWindow =\n\n WindowSettings::new(\"All Widgets - Piston Backend\", [WIDTH, HEIGHT])\n\n .graphics_api(OpenGL::V3_2) // If not working, try `OpenGL::V2_1`.\n\n .samples(4)\n\n .exit_on_esc(true)\n\n .vsync(true)\n\n .build()\n\n .unwrap();\n\n\n\n // construct our `Ui`.\n\n let mut ui = carbide_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64])\n\n .theme(carbide_example_shared::theme())\n\n .build();\n\n\n\n // Add a `Font` to the `Ui`'s `font::Map` from file.\n", "file_path": "backends/carbide_piston/examples/all_piston_window.rs", "rank": 64, "score": 153950.09977112792 }, { "content": "/// Return the optimal uncompressed float format for the text texture given the version.\n\npub fn text_texture_uncompressed_float_format(\n\n opengl_version: &glium::Version,\n\n) -> glium::texture::UncompressedFloatFormat {\n\n match *opengl_version {\n\n // If the version is greater than or equal to GL 3.0 or GLes 3.0, we can use the `U8` format.\n\n glium::Version(_, major, _) if major >= 3 => glium::texture::UncompressedFloatFormat::U8,\n\n // Otherwise, we must use the `U8U8U8` format to support older versions.\n\n _ => glium::texture::UncompressedFloatFormat::U8U8U8,\n\n }\n\n}\n\n\n", "file_path": "backends/carbide_glium/src/lib.rs", "rank": 65, "score": 147950.75096016593 }, { "content": "fn left_click_mouse(ui: &mut Ui) {\n\n press_mouse_button(MouseButton::Left, ui);\n\n release_mouse_button(MouseButton::Left, ui);\n\n}\n\n\n", "file_path": "carbide_core/tests/ui.rs", "rank": 66, "score": 145392.48663476214 }, { "content": "/// Produce a gray based on the input. 0.0 is white, 1.0 is black.\n\npub fn grayscale(p: f32) -> Color {\n\n Color::Hsla(0.0, 0.0, 1.0 - p, 1.0)\n\n}\n\n\n", "file_path": "carbide_core/src/color.rs", "rank": 67, "score": 143763.3224054274 }, { "content": "/// Produce a gray based on the input. 0.0 is white, 1.0 is black.\n\npub fn greyscale(p: f32) -> Color {\n\n Color::Hsla(0.0, 0.0, 1.0 - p, 1.0)\n\n}\n\n\n", "file_path": "carbide_core/src/color.rs", "rank": 68, "score": 143763.3224054274 }, { "content": "pub fn run<B: Backend>(\n\n event_loop: EventLoop<()>,\n\n mut aux: SimpleUiAux<B>,\n\n ids: carbide_example_shared::Ids,\n\n mut app: carbide_example_shared::DemoApp,\n\n mut factory: Factory<B>,\n\n mut families: Families<B>,\n\n window: Window,\n\n mut graph: Option<Graph<B, SimpleUiAux<B>>>,\n\n) {\n\n event_loop.run(move |event, _, control_flow| {\n\n if let Some(event) = convert_event(event.clone(), &window) {\n\n aux.ui.handle_event(event);\n\n }\n\n\n\n // Update widgets if any event has happened\n\n if aux.ui.global_input().events().next().is_some() {\n\n let mut ui = aux.ui.set_widgets();\n\n carbide_example_shared::gui(&mut ui, &ids, &mut app);\n\n }\n", "file_path": "backends/carbide_rendy/examples/all_winit_rendy.rs", "rank": 69, "score": 142676.62944971782 }, { "content": "pub fn create_render_pass_commands<'a>(\n\n default_bind_group: &'a wgpu::BindGroup,\n\n bind_groups: &'a mut HashMap<Id, DiffuseBindGroup>,\n\n uniform_bind_groups: &mut Vec<wgpu::BindGroup>,\n\n image_map: &'a ImageMap<Image>,\n\n mesh: &'a Mesh,\n\n device: &'a Device,\n\n atlas_tex: &'a Texture,\n\n bind_group_layout: &'a BindGroupLayout,\n\n uniform_bind_group_layout: &'a BindGroupLayout,\n\n carbide_to_wgpu_matrix: Matrix4<f32>,\n\n) -> Vec<RenderPass<'a>> {\n\n bind_groups.retain(|k, _| image_map.contains_key(k));\n\n\n\n for (id, img) in image_map.iter() {\n\n // If we already have a bind group for this image move on.\n\n if bind_groups.contains_key(id) {\n\n continue;\n\n }\n\n\n", "file_path": "backends/carbide_wgpu/src/render_pass_command.rs", "rank": 70, "score": 142307.4403834918 }, { "content": "pub fn inverse(input: f64, curve: fn(f64) -> f64) -> f64 {\n\n 1.0 - curve(1.0 - input)\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 71, "score": 142255.4566202563 }, { "content": "#[inline]\n\npub fn f32_to_byte(c: f32) -> u8 {\n\n (c * 255.0) as u8\n\n}\n\n\n", "file_path": "carbide_core/src/color.rs", "rank": 72, "score": 141672.6554923812 }, { "content": "fn animation_ball(curve: fn(f64) -> f64, window: &Window) -> Box<dyn Widget> {\n\n let state = animation_position_state(curve, window);\n\n HStack::new(vec![\n\n Circle::new()\n\n .fill(EnvironmentColor::Accent)\n\n .stroke(EnvironmentColor::Label)\n\n .frame(30, 30)\n\n .offset(state, 0.0),\n\n Spacer::new(),\n\n ])\n\n}\n", "file_path": "backends/carbide_wgpu/examples/animations.rs", "rank": 73, "score": 138836.47174273466 }, { "content": "pub fn ease_in_out(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.42, 0.0), Position::new(0.58, 1.0))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 74, "score": 137763.9735944654 }, { "content": "/// Get a suitable string from the value, its max and the pixel range.\n\npub fn val_to_string<T: ToString + NumCast>(\n\n val: T,\n\n max: T,\n\n val_rng: T,\n\n pixel_range: usize,\n\n) -> String {\n\n let mut s = val.to_string();\n\n let decimal = s.chars().position(|ch| ch == '.');\n\n match decimal {\n\n None => s,\n\n Some(idx) => {\n\n // Find the minimum string length by determing\n\n // what power of ten both the max and range are.\n\n let val_rng_f: f64 = NumCast::from(val_rng).unwrap();\n\n let max_f: f64 = NumCast::from(max).unwrap();\n\n let mut n: f64 = 0.0;\n\n let mut pow_ten = 0.0;\n\n while pow_ten < val_rng_f || pow_ten < max_f {\n\n pow_ten = (10.0).powf(n);\n\n n += 1.0\n", "file_path": "carbide_core/src/utils.rs", "rank": 75, "score": 137763.9735944654 }, { "content": "pub fn bounce_in(input: f64) -> f64 {\n\n inverse(input, bounce_helper)\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 76, "score": 137763.9735944654 }, { "content": "pub fn ease_out(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.0, 0.0), Position::new(0.58, 1.0))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 77, "score": 137763.9735944654 }, { "content": "pub fn elastic_in_out(input: f64) -> f64 {\n\n elastic_in_out_helper(input, 0.4)\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 78, "score": 137763.9735944654 }, { "content": "pub fn ease(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.25, 0.1), Position::new(0.25, 1.0))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 79, "score": 137763.9735944654 }, { "content": "pub fn bounce_out(input: f64) -> f64 {\n\n bounce_helper(input)\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 80, "score": 137763.9735944654 }, { "content": "pub fn linear(input: f64) -> f64 {\n\n input\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 81, "score": 137763.9735944654 }, { "content": "pub fn elastic_in(input: f64) -> f64 {\n\n elastic_helper(input, 0.4)\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 82, "score": 137763.9735944654 }, { "content": "pub fn bounce_in_out(input: f64) -> f64 {\n\n if input < 0.5 {\n\n (1.0 - bounce_helper(1.0 - input * 2.0)) * 0.5\n\n } else {\n\n bounce_helper(input * 2.0 - 1.0) * 0.5 + 0.5\n\n }\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 83, "score": 137763.9735944654 }, { "content": "pub fn ease_in(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.42, 0.0), Position::new(1.0, 1.0))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 84, "score": 137763.9735944654 }, { "content": "pub fn elastic_out(input: f64) -> f64 {\n\n inverse(input, elastic_in)\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 85, "score": 137763.9735944654 }, { "content": "pub trait CommonWidget {\n\n fn id(&self) -> Id;\n\n fn set_id(&mut self, id: Id);\n\n fn flag(&self) -> Flags {\n\n Flags::EMPTY\n\n }\n\n\n\n /// Get the logical children. This means for example for a vstack with a foreach,\n\n /// the children of the foreach is retrieved.\n\n fn children(&self) -> WidgetIter;\n\n fn children_mut(&mut self) -> WidgetIterMut;\n\n\n\n /// Get the direct children. This means for example for a vstack with a foreach,\n\n /// the foreach widget is retrieved.\n\n fn children_direct(&mut self) -> WidgetIterMut;\n\n fn children_direct_rev(&mut self) -> WidgetIterMut;\n\n\n\n fn position(&self) -> Position;\n\n fn set_position(&mut self, position: Position);\n\n\n", "file_path": "carbide_core/src/widget/common/common_widget.rs", "rank": 86, "score": 136828.01847720178 }, { "content": "/// Modulo float.\n\npub fn fmod(f: f32, n: i32) -> f32 {\n\n let i = f.floor() as i32;\n\n modulo(i, n) as f32 + f - i as f32\n\n}\n\n\n\n/// The modulo function.\n", "file_path": "carbide_core/src/utils.rs", "rank": 87, "score": 136558.8977127625 }, { "content": "pub fn ease_in_sine(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.47, 0.0), Position::new(0.745, 0.715))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 88, "score": 135934.35822194687 }, { "content": "pub fn ease_in_circ(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.6, 0.04), Position::new(0.98, 0.335))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 89, "score": 135934.35822194687 }, { "content": "pub fn ease_in_to_linear(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.67, 0.03), Position::new(0.65, 0.09))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 90, "score": 135934.35822194687 }, { "content": "pub fn linear_to_ease_out(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.35, 0.91), Position::new(0.33, 0.97))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 91, "score": 135934.35822194687 }, { "content": "pub fn ease_in_cubic(input: f64) -> f64 {\n\n cubic_bezier(\n\n input,\n\n Position::new(0.55, 0.055),\n\n Position::new(0.675, 0.19),\n\n )\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 92, "score": 135934.35822194687 }, { "content": "pub fn format_is_srgb(format: Format) -> bool {\n\n use vulkano::format::Format::*;\n\n match format {\n\n R8Srgb |\n\n R8G8Srgb |\n\n R8G8B8Srgb |\n\n B8G8R8Srgb |\n\n R8G8B8A8Srgb |\n\n B8G8R8A8Srgb |\n\n A8B8G8R8SrgbPack32 |\n\n BC1_RGBSrgbBlock |\n\n BC1_RGBASrgbBlock |\n\n BC2SrgbBlock |\n\n BC3SrgbBlock |\n\n BC7SrgbBlock |\n\n ETC2_R8G8B8SrgbBlock |\n\n ETC2_R8G8B8A1SrgbBlock |\n\n ETC2_R8G8B8A8SrgbBlock |\n\n ASTC_4x4SrgbBlock |\n\n ASTC_5x4SrgbBlock |\n", "file_path": "backends/carbide_vulkano/examples/support/mod.rs", "rank": 93, "score": 135934.35822194687 }, { "content": "pub fn ease_in_quart(input: f64) -> f64 {\n\n cubic_bezier(\n\n input,\n\n Position::new(0.895, 0.03),\n\n Position::new(0.685, 0.22),\n\n )\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 94, "score": 135934.35822194687 }, { "content": "pub fn ease_in_quad(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.55, 0.085), Position::new(0.68, 0.53))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 95, "score": 135934.35822194687 }, { "content": "pub fn ease_in_back(input: f64) -> f64 {\n\n cubic_bezier(\n\n input,\n\n Position::new(0.6, -0.28),\n\n Position::new(0.735, 0.045),\n\n )\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 96, "score": 135934.35822194687 }, { "content": "pub fn ease_out_sine(input: f64) -> f64 {\n\n cubic_bezier(input, Position::new(0.39, 0.575), Position::new(0.565, 1.0))\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 97, "score": 135934.35822194687 }, { "content": "pub fn ease_in_quint(input: f64) -> f64 {\n\n cubic_bezier(\n\n input,\n\n Position::new(0.755, 0.05),\n\n Position::new(0.855, 0.06),\n\n )\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 98, "score": 135934.35822194687 }, { "content": "pub fn ease_in_expo(input: f64) -> f64 {\n\n cubic_bezier(\n\n input,\n\n Position::new(0.95, 0.05),\n\n Position::new(0.795, 0.035),\n\n )\n\n}\n\n\n", "file_path": "carbide_core/src/state/animation_curve.rs", "rank": 99, "score": 135934.35822194687 } ]
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) data-topic=(topic) data-tailer=(tailer_id) {\n\n \"Tailing recent messages...\"\n\n }\n\n };\n\n layout::panel(panel_head, panel_body)\n\n}\n\n\n", "file_path": "src/web_server/pages/topic.rs", "rank": 0, "score": 240633.73765516217 }, { "content": "#[get(\"/api/clusters/<cluster_id>/topics\")]\n\npub fn cluster_topics(cluster_id: ClusterId, cache: State<Cache>) -> String {\n\n let brokers = cache.brokers.get(&cluster_id);\n\n if brokers.is_none() {\n\n // TODO: Improve here\n\n return empty();\n\n }\n\n\n\n let result_data = cache\n\n .topics\n\n .filter_clone(|&(ref c, _)| c == &cluster_id)\n\n .into_iter()\n\n .map(|((_, topic_name), partitions)| {\n\n let metrics = cache\n\n .metrics\n\n .get(&(cluster_id.clone(), topic_name.to_owned()))\n\n .unwrap_or_default()\n\n .aggregate_broker_metrics();\n\n TopicDetails {\n\n topic_name,\n\n partition_count: partitions.len(),\n", "file_path": "src/web_server/api.rs", "rank": 1, "score": 215442.98595547327 }, { "content": "#[get(\"/api/clusters/<cluster_id>/topics/<topic_name>/groups\")]\n\npub fn topic_groups(cluster_id: ClusterId, topic_name: &RawStr, cache: State<Cache>) -> String {\n\n let brokers = cache.brokers.get(&cluster_id);\n\n if brokers.is_none() {\n\n // TODO: Improve here\n\n return empty();\n\n }\n\n\n\n let groups = build_group_list(cache.inner(), |c, _| c == &cluster_id);\n\n\n\n let mut result_data = Vec::with_capacity(groups.len());\n\n for ((_cluster_id, group_name), info) in groups {\n\n if !info.topics.contains(&topic_name.to_string()) {\n\n continue;\n\n }\n\n result_data.push(json!((\n\n group_name,\n\n info.state,\n\n info.members,\n\n info.topics.len()\n\n )));\n\n }\n\n\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 2, "score": 206026.03471598972 }, { "content": "#[get(\"/api/clusters/<cluster_id>/topics/<topic_name>/topology\")]\n\npub fn topic_topology(cluster_id: ClusterId, topic_name: &RawStr, cache: State<Cache>) -> String {\n\n let partitions = cache\n\n .topics\n\n .get(&(cluster_id.to_owned(), topic_name.to_string()));\n\n if partitions.is_none() {\n\n return empty();\n\n }\n\n\n\n let topic_metrics = cache\n\n .metrics\n\n .get(&(cluster_id.clone(), topic_name.to_string()))\n\n .unwrap_or_default();\n\n let partitions = partitions.unwrap();\n\n\n\n let mut result_data = Vec::with_capacity(partitions.len());\n\n for p in partitions {\n\n let partition_metrics = topic_metrics\n\n .brokers\n\n .get(&p.leader)\n\n .and_then(|broker_metrics| broker_metrics.partitions.get(p.id as usize))\n", "file_path": "src/web_server/api.rs", "rank": 3, "score": 206026.03471598972 }, { "content": "fn consumer_groups_table(cluster_id: &ClusterId, topic_name: &str) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/topics/{}/groups\", cluster_id, topic_name);\n\n layout::datatable_ajax(\n\n \"groups-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Group name\" } th { \"Status\" } th { \"Registered members\" } th { \"Stored topic offsets\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/topic.rs", "rank": 4, "score": 201227.1443297015 }, { "content": "#[get(\"/api/clusters/<cluster_id>/brokers\")]\n\npub fn brokers(cluster_id: ClusterId, cache: State<Cache>) -> String {\n\n let brokers = cache.brokers.get(&cluster_id);\n\n if brokers.is_none() {\n\n // TODO: Improve here\n\n return empty();\n\n }\n\n\n\n let brokers = brokers.unwrap();\n\n let broker_metrics = cache\n\n .metrics\n\n .get(&(cluster_id.to_owned(), \"__TOTAL__\".to_owned()))\n\n .unwrap_or_default();\n\n let mut result_data = Vec::with_capacity(brokers.len());\n\n for broker in brokers {\n\n let metric = broker_metrics\n\n .brokers\n\n .get(&broker.id)\n\n .cloned()\n\n .unwrap_or_default();\n\n result_data.push(json!((\n", "file_path": "src/web_server/api.rs", "rank": 5, "score": 194531.8741340096 }, { "content": "#[get(\"/api/clusters/<cluster_id>/groups\")]\n\npub fn cluster_groups(cluster_id: ClusterId, cache: State<Cache>) -> String {\n\n let brokers = cache.brokers.get(&cluster_id);\n\n if brokers.is_none() {\n\n // TODO: Improve here\n\n return empty();\n\n }\n\n\n\n let groups = build_group_list(cache.inner(), |c, _| c == &cluster_id);\n\n\n\n let mut result_data = Vec::with_capacity(groups.len());\n\n for ((_cluster_id, group_name), info) in groups {\n\n result_data.push(json!((\n\n group_name,\n\n info.state,\n\n info.members,\n\n info.topics.len()\n\n )));\n\n }\n\n\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 6, "score": 192121.42131665658 }, { "content": "#[get(\"/clusters/<cluster_id>\")]\n\npub fn cluster_page(cluster_id: ClusterId, cache: State<Cache>, config: State<Config>) -> Markup {\n\n if cache.brokers.get(&cluster_id).is_none() {\n\n return pages::warning_page(\n\n &format!(\"Cluster: {}\", cluster_id),\n\n \"The specified cluster doesn't exist.\",\n\n );\n\n }\n\n\n\n let cluster_config = config.clusters.get(&cluster_id);\n\n let content = html! {\n\n h3 style=\"margin-top: 0px\" { \"Information\" }\n\n dl class=\"dl-horizontal\" {\n\n dt { \"Cluster name: \" } dd { (cluster_id.name()) }\n\n @if cluster_config.is_some() {\n\n dt { \"Bootstrap list: \" } dd { (cluster_config.unwrap().broker_list.join(\", \")) }\n\n dt { \"Zookeeper: \" } dd { (cluster_config.unwrap().zookeeper) }\n\n } @else {\n\n dt { \"Bootstrap list: \" } dd { \"Cluster configuration is missing\" }\n\n dt { \"Zookeeper: \" } dd { \"Cluster configuration is missing\" }\n\n }\n", "file_path": "src/web_server/pages/cluster.rs", "rank": 7, "score": 191927.59386161744 }, { "content": "fn topic_table(cluster_id: &ClusterId) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/topics\", cluster_id);\n\n layout::datatable_ajax(\n\n \"topics-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Topic name\" } th { \"#Partitions\" } th { \"Status\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\" title=\"Average over the last 15 minutes\" { \"Byte rate\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\" title=\"Average over the last 15 minutes\" { \"Msg rate\" }\n\n }\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/cluster.rs", "rank": 8, "score": 188070.50635305376 }, { "content": "fn topic_table(cluster_id: &ClusterId, topic_name: &str) -> PreEscaped<String> {\n\n let api_url = format!(\n\n \"/api/clusters/{}/topics/{}/topology\",\n\n cluster_id, topic_name\n\n );\n\n layout::datatable_ajax(\n\n \"topology-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Id\" } th { \"Size\" } th { \"Leader\" } th { \"Replicas\" } th { \"ISR\" } th { \"Status\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/topic.rs", "rank": 9, "score": 187180.5176427202 }, { "content": "#[get(\"/api/clusters/<cluster_id>/groups/<group_name>/members\")]\n\npub fn group_members(cluster_id: ClusterId, group_name: &RawStr, cache: State<Cache>) -> String {\n\n let group = cache\n\n .groups\n\n .get(&(cluster_id.clone(), group_name.to_string()));\n\n if group.is_none() {\n\n // TODO: Improve here\n\n return empty();\n\n }\n\n\n\n let group = group.unwrap();\n\n\n\n let mut result_data = Vec::with_capacity(group.members.len());\n\n for member in group.members {\n\n let assigns = member\n\n .assignments\n\n .iter()\n\n .map(|assign| {\n\n format!(\n\n \"{}/{}\",\n\n assign.topic,\n", "file_path": "src/web_server/api.rs", "rank": 10, "score": 175594.27885891282 }, { "content": "#[get(\"/api/clusters/<cluster_id>/groups/<group_name>/offsets\")]\n\npub fn group_offsets(cluster_id: ClusterId, group_name: &RawStr, cache: State<Cache>) -> String {\n\n let offsets = cache.offsets_by_cluster_group(&cluster_id, group_name.as_str());\n\n\n\n let wms = time!(\"fetching wms\", fetch_watermarks(&cluster_id, &offsets));\n\n let wms = match wms {\n\n Ok(wms) => wms,\n\n Err(e) => {\n\n error!(\"Error while fetching watermarks: {}\", e);\n\n return empty();\n\n }\n\n };\n\n\n\n let mut result_data = Vec::with_capacity(offsets.len());\n\n for ((_cluster_id, _group, topic), partitions) in offsets {\n\n for (partition_id, &curr_offset) in partitions.iter().enumerate() {\n\n let (low, high) = match wms.get(&(topic.clone(), partition_id as i32)) {\n\n Some(&Ok((low_mark, high_mark))) => (low_mark, high_mark),\n\n _ => (-1, -1),\n\n };\n\n let (lag_shown, percentage_shown) = match (high - low, high - curr_offset) {\n", "file_path": "src/web_server/api.rs", "rank": 11, "score": 175594.27885891282 }, { "content": "fn broker_table(cluster_id: &ClusterId) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/brokers\", cluster_id);\n\n layout::datatable_ajax(\n\n \"brokers-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Broker id\" } th { \"Hostname\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\"\n\n title=\"Total average over the last 15 minutes\" { \"Total byte rate\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\"\n\n title=\"Total average over the last 15 minutes\" { \"Total msg rate\" }\n\n }\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/cluster.rs", "rank": 12, "score": 164128.22167389988 }, { "content": "fn groups_table(cluster_id: &ClusterId) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/groups\", cluster_id);\n\n layout::datatable_ajax(\n\n \"groups-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Group name\" } th { \"Status\" } th { \"Registered members\" } th { \"Stored topic offsets\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/cluster.rs", "rank": 13, "score": 164128.22167389988 }, { "content": "fn reassignment_table(cluster_id: &ClusterId) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/reassignment\", cluster_id);\n\n layout::datatable_ajax(\n\n \"reassignment-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Topic\" } th { \"Partition\" } th { \"Reassigned replicas\" } th { \"Replica sizes\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/cluster.rs", "rank": 14, "score": 164128.22167389988 }, { "content": "#[get(\"/api/internals/live_consumers\")]\n\npub fn live_consumers(live_consumers: State<LiveConsumerStore>) -> String {\n\n let result_data = live_consumers\n\n .consumers()\n\n .iter()\n\n .map(|consumer| {\n\n (\n\n consumer.id(),\n\n consumer.cluster_id().to_owned(),\n\n consumer.topic().to_owned(),\n\n consumer.last_poll().elapsed().as_secs(),\n\n )\n\n })\n\n .collect::<Vec<_>>();\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 15, "score": 163695.59252722887 }, { "content": "pub fn read_config(path: &str) -> Result<Config> {\n\n let mut f = File::open(path).chain_err(|| \"Unable to open configuration file\")?;;\n\n let mut s = String::new();\n\n f.read_to_string(&mut s)\n\n .chain_err(|| \"Unable to read configuration file\")?;\n\n\n\n let mut config: Config =\n\n serde_yaml::from_str(&s).chain_err(|| \"Unable to parse configuration file\")?;\n\n\n\n for (cluster_id, cluster) in &mut config.clusters {\n\n cluster.cluster_id = Some(cluster_id.clone());\n\n }\n\n\n\n info!(\"Configuration: {:?}\", config);\n\n\n\n Ok(config)\n\n}\n", "file_path": "src/config.rs", "rank": 17, "score": 153307.80020139064 }, { "content": "fn group_offsets_table(cluster_id: &ClusterId, group_name: &str) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/groups/{}/offsets\", cluster_id, group_name);\n\n layout::datatable_ajax(\n\n \"group-offsets-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Topic\" } th { \"Partition\" } th { \"Size\" } th { \"Low mark\" } th { \"High mark\" }\n\n th { \"Current offset\" } th { \"Lag\" } th { \"Lag %\" }} },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/group.rs", "rank": 18, "score": 148967.7947975431 }, { "content": "fn group_members_table(cluster_id: &ClusterId, group_name: &str) -> PreEscaped<String> {\n\n let api_url = format!(\"/api/clusters/{}/groups/{}/members\", cluster_id, group_name);\n\n layout::datatable_ajax(\n\n \"group-members-ajax\",\n\n &api_url,\n\n cluster_id.name(),\n\n html! { tr { th { \"Member id\" } th { \"Client id\" } th { \"Hostname\" } th { \"Assignments\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/group.rs", "rank": 19, "score": 148967.7947975431 }, { "content": "#[get(\"/api/search/topic?<search..>\")]\n\npub fn topic_search(search: OmnisearchFormParams, cache: State<Cache>) -> String {\n\n let topics = if search.regex {\n\n Regex::new(&search.string)\n\n .map(|r| cache.topics.filter_clone(|&(_, ref name)| r.is_match(name)))\n\n .unwrap_or_default()\n\n } else {\n\n cache\n\n .topics\n\n .filter_clone(|&(_, ref name)| name.contains(&search.string))\n\n };\n\n\n\n let mut result_data = Vec::new();\n\n for ((cluster_id, topic_name), partitions) in topics {\n\n let metrics = cache\n\n .metrics\n\n .get(&(cluster_id.clone(), topic_name.clone()))\n\n .unwrap_or_default()\n\n .aggregate_broker_metrics();\n\n let errors = partitions.iter().find(|p| p.error.is_some());\n\n result_data.push(json!((\n", "file_path": "src/web_server/api.rs", "rank": 20, "score": 142201.81039014674 }, { "content": "#[get(\"/api/search/consumer?<search..>\")]\n\npub fn consumer_search(search: OmnisearchFormParams, cache: State<Cache>) -> String {\n\n let groups = if search.regex {\n\n Regex::new(&search.string)\n\n .map(|r| build_group_list(&cache, |_, g| r.is_match(g)))\n\n .unwrap_or_default()\n\n } else {\n\n build_group_list(&cache, |_, g| g.contains(&search.string))\n\n };\n\n\n\n let mut result_data = Vec::with_capacity(groups.len());\n\n for ((cluster_id, group_name), info) in groups {\n\n result_data.push(json!((\n\n cluster_id,\n\n group_name,\n\n info.state,\n\n info.members,\n\n info.topics.len()\n\n )));\n\n }\n\n\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 21, "score": 141854.16402357988 }, { "content": "#[get(\"/clusters/<cluster_id>/topics/<topic_name>\")]\n\npub fn topic_page(\n\n cluster_id: ClusterId,\n\n topic_name: &RawStr,\n\n cache: State<Cache>,\n\n config: State<Config>,\n\n) -> Markup {\n\n let partitions = match cache\n\n .topics\n\n .get(&(cluster_id.clone(), topic_name.to_string()))\n\n {\n\n Some(partitions) => partitions,\n\n None => {\n\n return pages::warning_page(\n\n &format!(\"Topic: {}\", cluster_id),\n\n \"The specified cluster doesn't exist.\",\n\n )\n\n }\n\n };\n\n\n\n let cluster_config = config.clusters.get(&cluster_id).unwrap();\n", "file_path": "src/web_server/pages/topic.rs", "rank": 22, "score": 137143.3757950014 }, { "content": "#[get(\"/clusters/<cluster_id>/groups/<group_name>\")]\n\npub fn group_page(cluster_id: ClusterId, group_name: &RawStr, cache: State<Cache>) -> Markup {\n\n if cache.brokers.get(&cluster_id).is_none() {\n\n return pages::warning_page(group_name, \"The specified cluster doesn't exist.\");\n\n }\n\n\n\n let group_state = match cache\n\n .groups\n\n .get(&(cluster_id.to_owned(), group_name.to_string()))\n\n {\n\n Some(group) => group.state,\n\n None => \"Not registered\".to_string(),\n\n };\n\n\n\n let cluster_link = format!(\"/clusters/{}/\", cluster_id.name());\n\n let content = html! {\n\n h3 style=\"margin-top: 0px\" { \"Information\" }\n\n dl class=\"dl-horizontal\" {\n\n dt { \"Cluster name:\" } dd { a href=(cluster_link) { (cluster_id) } }\n\n dt { \"Group name: \" } dd { (group_name) }\n\n dt { \"Group state: \" } dd { (group_state) }\n\n }\n\n h3 { \"Members\" }\n\n div { (group_members_table(&cluster_id, group_name)) }\n\n h3 { \"Offsets\" }\n\n div { (group_offsets_table(&cluster_id, group_name)) }\n\n };\n\n\n\n layout::page(&format!(\"Group: {}\", group_name), content)\n\n}\n", "file_path": "src/web_server/pages/group.rs", "rank": 23, "score": 136031.25285799644 }, { "content": "pub fn read_string(rdr: &mut Cursor<&[u8]>) -> Result<String> {\n\n read_str(rdr).map(str::to_string)\n\n}\n\n\n\n// GZip compression fairing\n\npub struct GZip;\n\n\n\nimpl fairing::Fairing for GZip {\n\n fn info(&self) -> fairing::Info {\n\n fairing::Info {\n\n name: \"GZip compression\",\n\n kind: fairing::Kind::Response,\n\n }\n\n }\n\n\n\n fn on_response(&self, request: &Request, response: &mut Response) {\n\n use flate2::{Compression, FlateReadExt};\n\n use std::io::{Cursor, Read};\n\n let headers = request.headers();\n\n if headers\n", "file_path": "src/utils.rs", "rank": 24, "score": 135740.48433461477 }, { "content": "pub fn panel(heading: PreEscaped<String>, body: PreEscaped<String>) -> PreEscaped<String> {\n\n html! {\n\n div class=\"panel panel-default\" {\n\n div class=\"panel-heading\" {\n\n (heading)\n\n div class=\"pull-right\" {\n\n div class=\"btn-group\" {\n\n button id=\"tailer_button_label\" type=\"button\"\n\n class=\"btn btn-default btn-xs dropdown-toggle\" data-toggle=\"dropdown\" {\n\n \"Topic tailer: active\" span class=\"caret\" {}\n\n }\n\n ul class=\"dropdown-menu pull-right\" role=\"menu\" {\n\n li id=\"start_tailer_button\" { a href=\"#\" { \"Start\" } }\n\n li id=\"stop_tailer_button\" { a href=\"#\" { \"Stop\" } }\n\n // li a href=\"#\" \"Action\"\n\n // li a href=\"#\" \"Action\"\n\n // li class=\"divider\" {}\n\n // li a href=\"#\" \"Action\"\n\n }\n\n }\n\n }\n\n }\n\n div class=\"panel-body\" { (body) }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/view/layout.rs", "rank": 25, "score": 135270.98622850073 }, { "content": "pub fn run_server(executor: &ThreadPoolExecutor, cache: Cache, config: &Config) -> Result<()> {\n\n let version = option_env!(\"CARGO_PKG_VERSION\").unwrap_or(\"?\");\n\n info!(\n\n \"Starting kafka-view v{}, listening on {}:{}.\",\n\n version, config.listen_host, config.listen_port\n\n );\n\n\n\n let rocket_env = rocket::config::Environment::active()\n\n .chain_err(|| \"Invalid ROCKET_ENV environment variable\")?;\n\n let rocket_config = rocket::config::Config::build(rocket_env)\n\n .address(config.listen_host.to_owned())\n\n .port(config.listen_port)\n\n .workers(4)\n\n .finalize()\n\n .chain_err(|| \"Invalid rocket configuration\")?;\n\n\n\n rocket::custom(rocket_config)\n\n .attach(GZip)\n\n .attach(RequestLogger)\n\n .manage(cache)\n", "file_path": "src/web_server/server.rs", "rank": 26, "score": 134906.12562007096 }, { "content": "pub fn run_offset_consumer(\n\n cluster_id: &ClusterId,\n\n cluster_config: &ClusterConfig,\n\n config: &Config,\n\n cache: &Cache,\n\n) -> Result<()> {\n\n let start_position = cache.internal_offsets.get(cluster_id);\n\n let consumer = create_consumer(\n\n &cluster_config.bootstrap_servers(),\n\n &config.consumer_offsets_group_id,\n\n start_position,\n\n )\n\n .chain_err(|| format!(\"Failed to create offset consumer for {}\", cluster_id))?;\n\n\n\n let cluster_id_clone = cluster_id.clone();\n\n let cache_alias = cache.alias();\n\n let _ = thread::Builder::new()\n\n .name(\"offset-consumer\".to_owned())\n\n .spawn(move || {\n\n if let Err(e) = consume_offset_topic(cluster_id_clone, consumer, &cache_alias) {\n\n format_error_chain!(e);\n\n }\n\n })\n\n .chain_err(|| \"Failed to start offset consumer thread\")?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/offsets.rs", "rank": 27, "score": 133423.4532146908 }, { "content": "fn graph_link(graph_url: &str, topic: &str) -> PreEscaped<String> {\n\n let url = graph_url.replace(\"{%s}\", topic);\n\n html! {\n\n a href=(url) { \"link\" }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/pages/topic.rs", "rank": 28, "score": 133328.73569684726 }, { "content": "#[get(\"/api/internals/cache/offsets\")]\n\npub fn cache_offsets(cache: State<Cache>) -> String {\n\n let result_data = cache.offsets.lock_iter(|offsets_cache_entry| {\n\n offsets_cache_entry\n\n .map(\n\n |(&(ref cluster_id, ref group_name, ref topic_id), partitions)| {\n\n (\n\n cluster_id.clone(),\n\n group_name.clone(),\n\n topic_id.clone(),\n\n format!(\"{:?}\", partitions),\n\n )\n\n },\n\n )\n\n .collect::<Vec<_>>()\n\n });\n\n\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 29, "score": 132092.067483065 }, { "content": "#[get(\"/api/internals/cache/metrics\")]\n\npub fn cache_metrics(cache: State<Cache>) -> String {\n\n let result_data = cache.metrics.lock_iter(|metrics_cache_entry| {\n\n metrics_cache_entry\n\n .map(|(&(ref cluster_id, ref topic_id), metrics)| {\n\n (cluster_id.clone(), topic_id.clone(), metrics.brokers.len())\n\n })\n\n .collect::<Vec<_>>()\n\n });\n\n\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 30, "score": 132092.067483065 }, { "content": "#[get(\"/api/internals/cache/brokers\")]\n\npub fn cache_brokers(cache: State<Cache>) -> String {\n\n let result_data = cache.brokers.lock_iter(|brokers_cache_entry| {\n\n brokers_cache_entry\n\n .map(|(cluster_id, brokers)| {\n\n (\n\n cluster_id.clone(),\n\n brokers.iter().map(|b| b.id).collect::<Vec<_>>(),\n\n )\n\n })\n\n .collect::<Vec<_>>()\n\n });\n\n\n\n json!({ \"data\": result_data }).to_string()\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 31, "score": 132092.067483065 }, { "content": "pub fn notification(n_type: &str, content: PreEscaped<String>) -> PreEscaped<String> {\n\n let alert_class = format!(\"alert alert-{}\", n_type);\n\n html! {\n\n div class=(alert_class) {\n\n (content)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/view/layout.rs", "rank": 32, "score": 131395.55565414077 }, { "content": "pub fn page(page_title: &str, page_content: PreEscaped<String>) -> PreEscaped<String> {\n\n html! {\n\n (maud::DOCTYPE)\n\n html {\n\n (html_head(page_title))\n\n body { (body(page_title, page_content)) }\n\n }\n\n }\n\n}\n", "file_path": "src/web_server/view/layout.rs", "rank": 33, "score": 128210.01634196485 }, { "content": "#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq)]\n\nstruct WrappedKey(String, String);\n\n\n\nimpl WrappedKey {\n\n fn new<'de, K>(cache_name: String, key: &'de K) -> WrappedKey\n\n where\n\n K: Serialize + Deserialize<'de>,\n\n {\n\n WrappedKey(cache_name, serde_json::to_string(key).unwrap()) //TODO: error handling\n\n }\n\n\n\n pub fn cache_name(&self) -> &str {\n\n &self.0\n\n }\n\n\n\n pub fn serialized_key(&self) -> &str {\n\n &self.1\n\n }\n\n}\n\n\n\n//\n", "file_path": "src/cache.rs", "rank": 34, "score": 128001.64285851922 }, { "content": "#[get(\"/topics\")]\n\npub fn topic_search() -> Markup {\n\n topic_search_p(OmnisearchFormParams {\n\n string: \"\".to_owned(),\n\n regex: false,\n\n })\n\n}\n\n\n", "file_path": "src/web_server/pages/omnisearch.rs", "rank": 35, "score": 122871.8981499468 }, { "content": "#[get(\"/consumers\")]\n\npub fn consumer_search() -> Markup {\n\n consumer_search_p(OmnisearchFormParams {\n\n string: \"\".to_owned(),\n\n regex: false,\n\n })\n\n}\n\n\n", "file_path": "src/web_server/pages/omnisearch.rs", "rank": 36, "score": 122459.80559157554 }, { "content": "#[get(\"/internals/live_consumers\")]\n\npub fn live_consumers_page() -> Markup {\n\n let content = html! {\n\n h3 style=\"margin-top: 0px\" { \"Active instances\" }\n\n div { (live_consumers_table()) }\n\n };\n\n layout::page(\"Live consumers\", content)\n\n}\n", "file_path": "src/web_server/pages/internals.rs", "rank": 37, "score": 120063.09089919165 }, { "content": "fn live_consumers_table() -> PreEscaped<String> {\n\n layout::datatable_ajax(\n\n \"internals-live-consumers-ajax\",\n\n \"/api/internals/live_consumers\",\n\n \"\",\n\n html! { tr { th { \"Id\" } th { \"Cluster id\" } th { \"Topic name\" } th { \"Last poll\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/internals.rs", "rank": 38, "score": 117904.24483511026 }, { "content": "type ClusterGroupOffsets = ((ClusterId, String, TopicName), Vec<i64>);\n\n\n", "file_path": "src/web_server/api.rs", "rank": 39, "score": 114776.89164727755 }, { "content": "fn consume_offset_topic(\n\n cluster_id: ClusterId,\n\n consumer: StreamConsumer<EmptyConsumerContext>,\n\n cache: &Cache,\n\n) -> Result<()> {\n\n let mut local_cache = HashMap::new();\n\n let mut last_dump = Instant::now();\n\n\n\n debug!(\"Starting offset consumer loop for {:?}\", cluster_id);\n\n\n\n for message in consumer.start_with(Duration::from_millis(200), true).wait() {\n\n match message {\n\n Ok(Ok(m)) => {\n\n let key = m.key().unwrap_or(&[]);\n\n let payload = m.payload().unwrap_or(&[]);\n\n match parse_message(key, payload) {\n\n Ok(ConsumerUpdate::OffsetCommit {\n\n group,\n\n topic,\n\n partition,\n", "file_path": "src/offsets.rs", "rank": 40, "score": 111982.42928423613 }, { "content": "// TODO: add doc\n\n// TODO: add limit\n\nfn build_group_list<F>(cache: &Cache, filter: F) -> HashMap<(ClusterId, String), GroupInfo>\n\nwhere\n\n F: Fn(&ClusterId, &String) -> bool,\n\n{\n\n let mut groups: HashMap<(ClusterId, String), GroupInfo> = cache.groups.lock_iter(|iter| {\n\n iter.filter(|&(&(ref c, ref g), _)| filter(c, g))\n\n .map(|(&(ref c, _), g)| {\n\n (\n\n (c.clone(), g.name.clone()),\n\n GroupInfo::new(g.state.clone(), g.members.len()),\n\n )\n\n })\n\n .collect()\n\n });\n\n\n\n let offsets = cache\n\n .offsets\n\n .filter_clone_k(|&(ref c, ref g, _)| filter(c, g));\n\n for (cluster_id, group, t) in offsets {\n\n groups\n\n .entry((cluster_id, group))\n\n .or_insert_with(GroupInfo::new_empty)\n\n .add_topic(t);\n\n }\n\n\n\n groups\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 41, "score": 109648.72222662391 }, { "content": "#[get(\"/topics?<search..>\")]\n\npub fn topic_search_p(search: OmnisearchFormParams) -> Markup {\n\n let search_form = layout::search_form(\"/topics\", \"Topic name\", &search.string, search.regex);\n\n let api_url = format!(\n\n \"/api/search/topic?string={}&regex={}\",\n\n &search.string, search.regex\n\n );\n\n let results = layout::datatable_ajax(\n\n \"topic-search-ajax\",\n\n &api_url,\n\n \"\",\n\n html! { tr { th { \"Cluster name\" } th { \"Topic name\" } th { \"#Partitions\" } th { \"Status\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\" title=\"Average over the last 15 minutes\" { \"Byte rate\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\" title=\"Average over the last 15 minutes\" { \"Msg rate\" }\n\n }},\n\n );\n\n\n\n layout::page(\n\n \"Topic search\",\n\n html! {\n\n (search_form)\n\n @if !search.string.is_empty() {\n\n h3 { \"Search results\" }\n\n (results)\n\n }\n\n },\n\n )\n\n}\n", "file_path": "src/web_server/pages/omnisearch.rs", "rank": 42, "score": 109357.68170056544 }, { "content": "#[get(\"/consumers?<search..>\")]\n\npub fn consumer_search_p(search: OmnisearchFormParams) -> Markup {\n\n let search_form =\n\n layout::search_form(\"/consumers\", \"Consumer name\", &search.string, search.regex);\n\n let api_url = format!(\n\n \"/api/search/consumer?string={}&regex={}\",\n\n &search.string, search.regex\n\n );\n\n let results = layout::datatable_ajax(\n\n \"group-search-ajax\",\n\n &api_url,\n\n \"\",\n\n html! { tr { th { \"Cluster\" } th { \"Group name\" } th { \"Status\" } th { \"Registered members\" } th { \"Stored topic offsets\" } } },\n\n );\n\n\n\n layout::page(\n\n \"Consumer search\",\n\n html! {\n\n (search_form)\n\n @if !search.string.is_empty() {\n\n h3 { \"Search results\" }\n\n (results)\n\n }\n\n },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/omnisearch.rs", "rank": 43, "score": 108990.91806145824 }, { "content": "pub fn warning_page(title: &str, message: &str) -> Markup {\n\n let content = layout::notification(\n\n \"warning\",\n\n html! {\n\n div class=\"flex-container\" {\n\n span class=\"flex-item\" style=\"padding: 0.3in; font-size: 16pt\" {\n\n i class=\"fa fa-frown-o fa-3x\" style=\"vertical-align: middle;\" { \"\" }\n\n \" \" (message)\n\n }\n\n }\n\n },\n\n );\n\n layout::page(title, content)\n\n}\n", "file_path": "src/web_server/pages/error_defaults.rs", "rank": 44, "score": 103952.54340080218 }, { "content": "fn empty() -> String {\n\n json!({\"data\": []}).to_string()\n\n}\n", "file_path": "src/web_server/api.rs", "rank": 45, "score": 103525.45441797872 }, { "content": "#[get(\"/api/clusters/<cluster_id>/reassignment\")]\n\npub fn cluster_reassignment(\n\n cluster_id: ClusterId,\n\n cache: State<Cache>,\n\n config: State<Config>,\n\n) -> String {\n\n if cache.brokers.get(&cluster_id).is_none() {\n\n return empty();\n\n }\n\n\n\n let zk_url = &config.clusters.get(&cluster_id).unwrap().zookeeper;\n\n\n\n let zk = match ZK::new(zk_url) {\n\n // TODO: cache ZK clients\n\n Ok(zk) => zk,\n\n Err(_) => {\n\n error!(\"Error connecting to {:?}\", zk_url);\n\n return empty();\n\n }\n\n };\n\n\n", "file_path": "src/web_server/api.rs", "rank": 46, "score": 101503.58905784429 }, { "content": "#[get(\"/clusters/<cluster_id>/brokers/<broker_id>\")]\n\npub fn broker_page(\n\n cluster_id: ClusterId,\n\n broker_id: BrokerId,\n\n cache: State<Cache>,\n\n config: State<Config>,\n\n) -> Markup {\n\n let broker = cache\n\n .brokers\n\n .get(&cluster_id)\n\n .and_then(|brokers| brokers.iter().find(|b| b.id == broker_id).cloned());\n\n let cluster_config = config.clusters.get(&cluster_id);\n\n\n\n if broker.is_none() || cluster_config.is_none() {\n\n return pages::warning_page(\n\n &format!(\"Broker: {}\", broker_id),\n\n \"The specified broker doesn't exist.\",\n\n );\n\n }\n\n\n\n let broker = broker.unwrap();\n", "file_path": "src/web_server/pages/cluster.rs", "rank": 47, "score": 99711.9458551661 }, { "content": "pub fn datatable_ajax(\n\n id: &str,\n\n url: &str,\n\n param: &str,\n\n table_header: PreEscaped<String>,\n\n) -> PreEscaped<String> {\n\n let table_id = format!(\"datatable-{}\", id);\n\n html! {\n\n table id=(table_id) data-url=(url) data-param=(param) width=\"100%\" class=\"table table-striped table-bordered table-hover\" {\n\n thead { (table_header) }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/view/layout.rs", "rank": 48, "score": 99708.18540103859 }, { "content": "pub fn search_form(\n\n action: &str,\n\n placeholder: &str,\n\n value: &str,\n\n regex: bool,\n\n) -> PreEscaped<String> {\n\n html! {\n\n form action=(action) {\n\n div class=\"row\" {\n\n div class=\"col-md-12\" style=\"margin-top: 20pt\" {}\n\n }\n\n div class=\"row\" {\n\n div class=\"col-md-2\" { \"\" }\n\n div class=\"col-md-8\" {\n\n div class=\"input-group custom-search-form\" {\n\n input class=\"form-control\" type=\"text\" name=\"string\" style=\"font-size: 18pt; height: 30pt\"\n\n placeholder=(placeholder) value=(value) {\n\n span class=\"input-group-btn\" {\n\n button class=\"btn btn-default\" style=\"height: 30pt\" type=\"submit\" {\n\n i class=\"fa fa-search fa-2x\" {}\n", "file_path": "src/web_server/view/layout.rs", "rank": 49, "score": 99708.18540103859 }, { "content": "fn main() -> Result<(), std::io::Error> {\n\n let outdir = var(\"OUT_DIR\").unwrap();\n\n let rust_version_file = Path::new(&outdir).join(\"rust_version.rs\");\n\n let output = Command::new(var(\"RUSTC\").unwrap())\n\n .arg(\"--version\")\n\n .output()?;\n\n let version = String::from_utf8_lossy(&output.stdout);\n\n\n\n let mut output_file = File::create(rust_version_file)?;\n\n output_file\n\n .write_all(format!(\"const RUST_VERSION: &str = \\\"{}\\\";\", version.trim()).as_bytes())?;\n\n\n\n Ok(())\n\n}\n", "file_path": "build.rs", "rank": 50, "score": 99261.29321253646 }, { "content": "#[get(\"/omnisearch\")]\n\npub fn omnisearch() -> Markup {\n\n omnisearch_p(OmnisearchFormParams {\n\n string: \"\".to_owned(),\n\n regex: false,\n\n })\n\n}\n\n\n", "file_path": "src/web_server/pages/omnisearch.rs", "rank": 51, "score": 96909.7659150624 }, { "content": "fn navbar_side() -> PreEscaped<String> {\n\n html! {\n\n div class=\"navbar-default sidebar\" role=\"navigation\" {\n\n div class=\"sidebar-nav navbar-collapse\" {\n\n ul class=\"nav\" id=\"side-menu\" {\n\n li class=\"sidebar-search\" {\n\n form action=\"/omnisearch\" {\n\n div class=\"input-group custom-search-form\" {\n\n input type=\"text\" name=\"string\" class=\"form-control\" placeholder=\"Omnisearch...\" {\n\n span class=\"input-group-btn\" {\n\n button class=\"btn btn-default\" type=\"submit\" {\n\n i class=\"fa fa-search\" {}\n\n }\n\n }\n\n }\n\n }\n\n }\n\n }\n\n // li a href=\"/\" { i class=\"fa fa-dashboard fa-fw\" {} \" Home\" }\n\n //li a href=\"/\" style=\"font-size: 12pt\" { i class=\"fa fa-info-circle fa-fw\" {} \" Home\" }\n", "file_path": "src/web_server/view/layout.rs", "rank": 53, "score": 93749.99372048579 }, { "content": "fn navbar_top() -> PreEscaped<String> {\n\n html! {\n\n ul class=\"nav navbar-top-links navbar-right\" {\n\n li class=\"dropdown\" {\n\n a class=\"dropdown-toggle\" style=\"font-size: 12pt\" data-toggle=\"dropdown\" href=\"#\" {\n\n i class=\"fa fa-question-circle-o fa-fw\" {}\n\n i class=\"fa fa-caret-down\" {}\n\n }\n\n ul class=\"dropdown-menu dropdown-user\" {\n\n li { a href=\"https://github.com/fede1024/kafka-view\" {\n\n i class=\"fa fa-github fa-fw\" {} \"GitHub\" }\n\n }\n\n // li class=\"divider\" {}\n\n // li { a href=\"#\" {i class=\"fa fa-sign-out fa-fw\" {} \"Logout\" } }\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/view/layout.rs", "rank": 54, "score": 93749.99372048579 }, { "content": "fn broker_table() -> PreEscaped<String> {\n\n layout::datatable_ajax(\n\n \"internals-cache-brokers-ajax\",\n\n \"/api/internals/cache/brokers\",\n\n \"\",\n\n html! { tr { th { \"Cluster id\" } th { \"Broker ids\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/internals.rs", "rank": 55, "score": 93749.99372048579 }, { "content": "fn offsets_table() -> PreEscaped<String> {\n\n layout::datatable_ajax(\n\n \"internals-cache-offsets-ajax\",\n\n \"/api/internals/cache/offsets\",\n\n \"\",\n\n html! { tr { th { \"Cluster id\" } th { \"Consumer group\" } th { \"Topic name\" } th { \"Offsets\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/internals.rs", "rank": 56, "score": 93749.99372048579 }, { "content": "fn navbar_header() -> PreEscaped<String> {\n\n html! {\n\n div class=\"navbar-header\" {\n\n button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\" {\n\n span class=\"sr-only\" { \"Toggle navigation\" }\n\n span class=\"icon-bar\" {}\n\n span class=\"icon-bar\" {}\n\n span class=\"icon-bar\" {}\n\n }\n\n a class=\"navbar-brand\" href=\"/\" {\n\n img src=\"/public/images/kafka_logo.png\"\n\n style=\"float:left;max-width:160%;max-height:160%; margin-top: -0.06in; margin-right: 0.07in\"\n\n align=\"bottom\"\n\n { \"Kafka-view\" }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/view/layout.rs", "rank": 57, "score": 93749.99372048579 }, { "content": "fn metrics_table() -> PreEscaped<String> {\n\n layout::datatable_ajax(\n\n \"internals-cache-metrics-ajax\",\n\n \"/api/internals/cache/metrics\",\n\n \"\",\n\n html! { tr { th { \"Cluster id\" } th { \"Topic name\" } th { \"Brokers\" } } },\n\n )\n\n}\n\n\n", "file_path": "src/web_server/pages/internals.rs", "rank": 58, "score": 93749.99372048579 }, { "content": "fn body(page_title: &str, content: PreEscaped<String>) -> PreEscaped<String> {\n\n html! {\n\n div id=\"wrapper\" {\n\n // Navigation\n\n nav class=\"navbar navbar-default navbar-static-top\" role=\"navigation\" style=\"margin-bottom: 0\" {\n\n (navbar_header())\n\n (navbar_top())\n\n (navbar_side())\n\n }\n\n\n\n div id=\"page-wrapper\" class=\"flex-container\" {\n\n div class=\"row\" {\n\n div class=\"col-md-12\" {\n\n h1 class=\"page-header\" { (page_title) }\n\n }\n\n }\n\n div class=\"row flex-body\" {\n\n div class=\"col-md-12\" {\n\n (content)\n\n }\n", "file_path": "src/web_server/view/layout.rs", "rank": 59, "score": 92428.64095218311 }, { "content": "#[derive(Serialize)]\n\nstruct TopicDetails {\n\n topic_name: String,\n\n partition_count: usize,\n\n errors: String,\n\n b_rate_15: f64,\n\n m_rate_15: f64,\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 60, "score": 92401.0719738063 }, { "content": "fn parse_message(key: &[u8], payload: &[u8]) -> Result<ConsumerUpdate, ParserError> {\n\n let mut key_rdr = Cursor::new(key);\n\n let mut payload_rdr = Cursor::new(payload);\n\n let key_version = key_rdr.read_i16::<BigEndian>()?;\n\n match key_version {\n\n 0 | 1 => Ok(parse_group_offset(&mut key_rdr, &mut payload_rdr)?),\n\n 2 => Ok(ConsumerUpdate::Metadata),\n\n _ => Err(ParserError::Format),\n\n }\n\n}\n\n\n", "file_path": "examples/consumer_offsets_reader.rs", "rank": 61, "score": 90836.98519289555 }, { "content": "fn html_head(title: &str) -> PreEscaped<String> {\n\n html! {\n\n head profile=\"http://www.w3.org/2005/10/profile\" {\n\n link rel=\"icon\" type=\"image/png\" href=\"/public/images/webkafka_favicon.png\" {}\n\n meta charset=\"utf-8\" {}\n\n meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" {}\n\n meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" {}\n\n title { (title) }\n\n link href=\"/public/sb-admin-2/vendor/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\" {}\n\n link href=\"/public/sb-admin-2/vendor/metisMenu/metisMenu.min.css\" rel=\"stylesheet\" {}\n\n link href=\"/public/sb-admin-2/vendor/datatables-plugins/dataTables.bootstrap.css\" rel=\"stylesheet\" {}\n\n // link href=\"/public/sb-admin-2/vendor/datatables/css/jquery.dataTables.min.css\" rel=\"stylesheet\" {}\n\n // link href=\"/public/sb-admin-2/vendor/datatables/css/dataTables.jqueryui.min.css\" rel=\"stylesheet\" {}\n\n link href=\"/public/sb-admin-2/dist/css/sb-admin-2.css\" rel=\"stylesheet\" {}\n\n link href=\"/public/css/font-awesome.min.css\" rel=\"stylesheet\" type=\"text/css\" {}\n\n link href=\"/public/my_css.css\" rel=\"stylesheet\" type=\"text/css\" {}\n\n script async=\"\" defer=\"\" src=\"https://buttons.github.io/buttons.js\" {}\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/view/layout.rs", "rank": 63, "score": 86173.50802764142 }, { "content": "#[get(\"/omnisearch?<search..>\")]\n\npub fn omnisearch_p(search: OmnisearchFormParams) -> Markup {\n\n let search_form =\n\n layout::search_form(\"/omnisearch\", \"Omnisearch\", &search.string, search.regex);\n\n let api_url = format!(\n\n \"/api/search/topic?string={}&regex={}\",\n\n &search.string, search.regex\n\n );\n\n let topics = layout::datatable_ajax(\n\n \"topic-search-ajax\",\n\n &api_url,\n\n \"\",\n\n html! { tr { th { \"Cluster name\" } th { \"Topic name\" } th { \"#Partitions\" } th { \"Status\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\" title=\"Average over the last 15 minutes\" { \"Byte rate\" }\n\n th data-toggle=\"tooltip\" data-container=\"body\" title=\"Average over the last 15 minutes\" { \"Msg rate\" }\n\n }},\n\n );\n\n let api_url = format!(\n\n \"/api/search/consumer?string={}&regex={}\",\n\n &search.string, search.regex\n\n );\n", "file_path": "src/web_server/pages/omnisearch.rs", "rank": 64, "score": 86081.08986281214 }, { "content": "#[get(\"/clusters\")]\n\npub fn clusters_page(cache: State<Cache>) -> Markup {\n\n let mut cluster_ids = cache.brokers.keys();\n\n cluster_ids.sort();\n\n\n\n let content = html! {\n\n @for cluster_id in &cluster_ids {\n\n (cluster_pane(cluster_id, &cache.brokers, &cache.topics))\n\n }\n\n };\n\n\n\n layout::page(\"Clusters\", content)\n\n}\n", "file_path": "src/web_server/pages/clusters.rs", "rank": 65, "score": 84110.01001370333 }, { "content": "#[get(\"/internals/caches\")]\n\npub fn caches_page(cache: State<Cache>) -> Markup {\n\n let content = html! {\n\n h3 style=\"margin-top: 0px\" { \"Information\" }\n\n h3 { \"Brokers\" }\n\n (cache_description_table(\"BrokerCache\", \"ClusterId\", \"Vec<Broker>\", cache.brokers.keys().len()))\n\n div { (broker_table()) }\n\n h3 { \"Metrics\" }\n\n (cache_description_table(\"MetricsCache\", \"(ClusterId, TopicName)\", \"TopicMetrics\", cache.metrics.keys().len()))\n\n div { (metrics_table()) }\n\n h3 { \"Offsets\" }\n\n (cache_description_table(\"OffsetsCache\", \"(ClusterId, GroupName, TopicName)\", \"Vec<i64>\", cache.offsets.keys().len()))\n\n div { (offsets_table()) }\n\n };\n\n layout::page(\"Caches\", content)\n\n}\n\n\n", "file_path": "src/web_server/pages/internals.rs", "rank": 66, "score": 84110.01001370333 }, { "content": "fn create_consumer(\n\n brokers: &str,\n\n group_id: &str,\n\n start_offsets: Option<Vec<i64>>,\n\n) -> Result<StreamConsumer<EmptyConsumerContext>> {\n\n let consumer = ClientConfig::new()\n\n .set(\"group.id\", group_id)\n\n .set(\"bootstrap.servers\", brokers)\n\n .set(\"enable.partition.eof\", \"false\")\n\n .set(\"enable.auto.commit\", \"false\")\n\n .set(\"session.timeout.ms\", \"30000\")\n\n .set(\"api.version.request\", \"true\")\n\n //.set(\"fetch.message.max.bytes\", \"1024000\") // Reduce memory usage\n\n .set(\"queued.min.messages\", \"10000\") // Reduce memory usage\n\n .set(\"message.max.bytes\", \"10485760\")\n\n .set_default_topic_config(\n\n TopicConfig::new()\n\n .set(\"auto.offset.reset\", \"smallest\")\n\n .finalize(),\n\n )\n", "file_path": "src/offsets.rs", "rank": 68, "score": 82649.54347420926 }, { "content": "fn read_str<'a>(rdr: &'a mut Cursor<&[u8]>) -> Result<&'a str, ParserError> {\n\n let strlen = rdr.read_i16::<BigEndian>()? as usize;\n\n let pos = rdr.position() as usize;\n\n let slice = str::from_utf8(&rdr.get_ref()[pos..(pos + strlen)])?;\n\n rdr.consume(strlen);\n\n Ok(slice)\n\n}\n\n\n", "file_path": "examples/consumer_offsets_reader.rs", "rank": 69, "score": 81799.11223177826 }, { "content": "fn consume_and_print(brokers: &str) {\n\n let consumer = ClientConfig::new()\n\n .set(\"group.id\", \"consumer_reader_group\")\n\n .set(\"bootstrap.servers\", brokers)\n\n .set(\"enable.partition.eof\", \"false\")\n\n .set(\"session.timeout.ms\", \"30000\")\n\n .set(\"enable.auto.commit\", \"false\")\n\n .set_default_topic_config(\n\n TopicConfig::new()\n\n .set(\"auto.offset.reset\", \"smallest\")\n\n .finalize(),\n\n )\n\n .create::<StreamConsumer<_>>()\n\n .expect(\"Consumer creation failed\");\n\n\n\n consumer\n\n .subscribe(&vec![\"__consumer_offsets\"])\n\n .expect(\"Can't subscribe to specified topics\");\n\n\n\n for message in consumer.start().wait() {\n", "file_path": "examples/consumer_offsets_reader.rs", "rank": 70, "score": 80964.15376735361 }, { "content": "fn format_jolokia_path(hostname: &str, port: i32, filter: &str) -> String {\n\n format!(\"http://{}:{}/jolokia/read/{}?ignoreErrors=true&includeStackTrace=false&maxCollectionSize=0\",\n\n hostname, port, filter)\n\n}\n\n\n", "file_path": "src/metrics.rs", "rank": 71, "score": 80808.76340715251 }, { "content": "fn main() {\n\n let matches = App::new(\"consumer example\")\n\n .version(option_env!(\"CARGO_PKG_VERSION\").unwrap_or(\"\"))\n\n .about(\"Simple command line consumer\")\n\n .arg(\n\n Arg::with_name(\"brokers\")\n\n .short(\"b\")\n\n .long(\"brokers\")\n\n .help(\"Broker list in kafka format\")\n\n .takes_value(true)\n\n .default_value(\"localhost:9092\"),\n\n )\n\n .get_matches();\n\n\n\n let (version_n, version_s) = get_rdkafka_version();\n\n println!(\"rd_kafka_version: 0x{:08x}, {}\", version_n, version_s);\n\n\n\n let brokers = matches.value_of(\"brokers\").unwrap();\n\n\n\n consume_and_print(brokers);\n\n}\n", "file_path": "examples/consumer_offsets_reader.rs", "rank": 72, "score": 80445.62725096918 }, { "content": "fn default_true() -> bool {\n\n true\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n\npub struct ClusterConfig {\n\n pub cluster_id: Option<ClusterId>, // This will always be available after load\n\n pub broker_list: Vec<String>,\n\n pub zookeeper: String,\n\n pub jolokia_port: Option<i32>,\n\n pub graph_url: Option<String>,\n\n #[serde(default = \"default_true\")]\n\n pub enable_tailing: bool,\n\n #[serde(default = \"default_true\")]\n\n pub show_zk_reassignments: bool,\n\n}\n\n\n\nimpl ClusterConfig {\n\n pub fn bootstrap_servers(&self) -> String {\n\n self.broker_list.join(\",\")\n", "file_path": "src/config.rs", "rank": 73, "score": 79932.4755389086 }, { "content": "pub fn read_str<'a>(rdr: &'a mut Cursor<&[u8]>) -> Result<&'a str> {\n\n let len = (rdr.read_i16::<BigEndian>()).chain_err(|| \"Failed to parse string len\")? as usize;\n\n let pos = rdr.position() as usize;\n\n let slice = str::from_utf8(&rdr.get_ref()[pos..(pos + len)])\n\n .chain_err(|| \"String is not valid UTF-8\")?;\n\n rdr.consume(len);\n\n Ok(slice)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 74, "score": 78104.87162527924 }, { "content": "fn jolokia_response_get_value(json_response: &Value) -> Result<&serde_json::Map<String, Value>> {\n\n let obj = match json_response.as_object() {\n\n Some(obj) => obj,\n\n None => bail!(\"The provided Value is not a JSON object\"),\n\n };\n\n if let Some(v) = obj.get(\"value\") {\n\n if let Some(value_obj) = v.as_object() {\n\n return Ok(value_obj);\n\n } else {\n\n bail!(\"'value' is not a JSON object\");\n\n }\n\n } else {\n\n bail!(\"Missing value\");\n\n }\n\n}\n\n\n", "file_path": "src/metrics.rs", "rank": 75, "score": 77032.5550766063 }, { "content": "fn parse_group_offset(\n\n key_rdr: &mut Cursor<&[u8]>,\n\n payload_rdr: &mut Cursor<&[u8]>,\n\n) -> Result<ConsumerUpdate, ParserError> {\n\n let group = read_str(key_rdr)?.to_owned();\n\n let topic = read_str(key_rdr)?.to_owned();\n\n let partition = key_rdr.read_i32::<BigEndian>()?;\n\n if !payload_rdr.get_ref().is_empty() {\n\n payload_rdr.read_i16::<BigEndian>()?;\n\n let offset = payload_rdr.read_i64::<BigEndian>()?;\n\n Ok(ConsumerUpdate::SetCommit {\n\n group: group,\n\n topic: topic,\n\n partition: partition,\n\n offset: offset,\n\n })\n\n } else {\n\n Ok(ConsumerUpdate::DeleteCommit {\n\n group: group,\n\n topic: topic,\n\n partition: partition,\n\n })\n\n }\n\n}\n\n\n", "file_path": "examples/consumer_offsets_reader.rs", "rank": 76, "score": 76473.16245332813 }, { "content": "pub fn setup_logger(log_thread: bool, rust_log: Option<&str>, date_format: &str) {\n\n let date_format = date_format.to_owned();\n\n let output_format = move |buffer: &mut Formatter, record: &Record| {\n\n let thread_name = if log_thread {\n\n format!(\"({}) \", thread::current().name().unwrap_or(\"unknown\"))\n\n } else {\n\n \"\".to_string()\n\n };\n\n let date = Local::now().format(&date_format).to_string();\n\n writeln!(\n\n buffer,\n\n \"{}: {}{} - {} - {}\",\n\n date,\n\n thread_name,\n\n record.level(),\n\n record.target(),\n\n record.args()\n\n )\n\n };\n\n\n", "file_path": "src/utils.rs", "rank": 77, "score": 75488.8029865208 }, { "content": "pub fn vec_merge_in_place<F, T: Copy>(vec1: &mut Vec<T>, vec2: &[T], default: T, merge_fn: F)\n\nwhere\n\n F: Fn(T, T) -> T,\n\n{\n\n let new_len = cmp::max(vec1.len(), vec2.len());\n\n vec1.resize(new_len, default);\n\n for i in 0..vec1.len() {\n\n vec1[i] = merge_fn(\n\n vec1.get(i).unwrap_or(&default).to_owned(),\n\n vec2.get(i).unwrap_or(&default).to_owned(),\n\n );\n\n }\n\n}\n\n\n\n//pub fn vec_merge<F, T: Clone>(vec1: Vec<T>, vec2: Vec<T>, default: T, merge: F) -> Vec<T>\n\n// where F: Fn(T, T) -> T\n\n//{\n\n// (0..cmp::max(vec1.len(), vec2.len()))\n\n// .map(|index|\n\n// merge(\n\n// vec1.get(index).unwrap_or(&default).to_owned(),\n\n// vec2.get(index).unwrap_or(&default).to_owned()))\n\n// .collect::<Vec<T>>()\n\n//}\n\n\n", "file_path": "src/offsets.rs", "rank": 78, "score": 72379.8940410074 }, { "content": "fn run_kafka_web(config_path: &str) -> Result<()> {\n\n let config = config::read_config(config_path)\n\n .chain_err(|| format!(\"Unable to load configuration from '{}'\", config_path))?;\n\n\n\n let replicator_bootstrap_servers = match config.cluster(&config.caching.cluster) {\n\n Some(cluster) => cluster.bootstrap_servers(),\n\n None => bail!(\"Can't find cache cluster {}\", config.caching.cluster),\n\n };\n\n let topic_name = &config.caching.topic;\n\n let replica_writer =\n\n ReplicaWriter::new(&replicator_bootstrap_servers, topic_name).chain_err(|| {\n\n format!(\n\n \"Replica writer creation failed (brokers: {}, topic: {})\",\n\n replicator_bootstrap_servers, topic_name\n\n )\n\n })?;\n\n let mut replica_reader = ReplicaReader::new(&replicator_bootstrap_servers, topic_name)\n\n .chain_err(|| {\n\n format!(\n\n \"Replica reader creation failed (brokers: {}, topic: {})\",\n", "file_path": "src/main.rs", "rank": 79, "score": 70190.11975734834 }, { "content": "fn fetch_groups(consumer: &MetadataConsumer, timeout_ms: i32) -> Result<Vec<Group>> {\n\n let group_list = consumer\n\n .fetch_group_list(None, timeout_ms)\n\n .chain_err(|| \"Failed to fetch consumer group list\")?;\n\n\n\n let mut groups = Vec::new();\n\n for rd_group in group_list.groups() {\n\n let members = rd_group\n\n .members()\n\n .iter()\n\n .map(|m| {\n\n let mut assigns = Vec::new();\n\n if rd_group.protocol_type() == \"consumer\" {\n\n if let Some(assignment) = m.assignment() {\n\n let mut payload_rdr = Cursor::new(assignment);\n\n assigns = parse_member_assignment(&mut payload_rdr)\n\n .expect(\"Parse member assignment failed\");\n\n }\n\n }\n\n GroupMember {\n", "file_path": "src/metadata.rs", "rank": 80, "score": 69673.39215603015 }, { "content": "fn cache_description_table(name: &str, key: &str, value: &str, count: usize) -> PreEscaped<String> {\n\n html! {\n\n table style=\"margin-top: 10px; margin-bottom: 10px\" {\n\n tr {\n\n td style=\"font-weight: bold\" { \"Name:\" }\n\n td style=\"font-family: monospace; padding-left: 20px\" { (name) }\n\n }\n\n tr {\n\n td style=\"font-weight: bold\" { \"Key:\" }\n\n td style=\"font-family: monospace; padding-left: 20px\" { (key) }\n\n }\n\n tr {\n\n td style=\"font-weight: bold\" { \"Value:\" }\n\n td style=\"font-family: monospace; padding-left: 20px\" { (value) }\n\n }\n\n tr {\n\n td style=\"font-weight: bold\" { \"Items count:\" }\n\n td style=\"font-family: monospace; padding-left: 20px\" { (count) }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/web_server/pages/internals.rs", "rank": 81, "score": 68795.93648829851 }, { "content": "/// Given a vector, will insert `value` at the desired position `pos`, filling the items\n\n/// with `default`s if needed.\n\npub fn insert_at<T: Copy>(vector: &mut Vec<T>, pos: usize, value: T, default: T) {\n\n for _ in vector.len()..=pos {\n\n vector.push(default);\n\n }\n\n vector[pos] = value;\n\n}\n\n\n\n/// Wraps a JSON value and implements a responder for it, with support for brotli compression.\n\n#[allow(dead_code)]\n\npub struct CompressedJSON(pub serde_json::Value);\n\n\n\nimpl Responder<'static> for CompressedJSON {\n\n fn respond_to(self, req: &Request) -> response::Result<'static> {\n\n let json = serde_json::to_vec(&self.0).unwrap();\n\n let reader = io::Cursor::new(json);\n\n let headers = req.headers();\n\n if headers.contains(\"Accept\") && headers.get(\"Accept-Encoding\").any(|e| e.contains(\"br\")) {\n\n Ok(Response::build()\n\n .status(Status::Ok)\n\n .header(ContentType::JSON)\n", "file_path": "src/utils.rs", "rank": 82, "score": 68658.32634583986 }, { "content": "type ReplicaConsumer = StreamConsumer<EmptyConsumerContext>;\n\n\n\npub struct ReplicaReader {\n\n consumer: ReplicaConsumer,\n\n brokers: String,\n\n topic_name: String,\n\n processed_messages: i64,\n\n}\n\n\n\nimpl ReplicaReader {\n\n pub fn new(brokers: &str, topic_name: &str) -> Result<ReplicaReader> {\n\n let consumer: ReplicaConsumer = ClientConfig::new()\n\n .set(\n\n \"group.id\",\n\n &format!(\"kafka_web_cache_reader_{}\", random::<i64>()),\n\n )\n\n .set(\"bootstrap.servers\", brokers)\n\n .set(\"session.timeout.ms\", \"6000\")\n\n .set(\"enable.auto.commit\", \"false\")\n\n .set(\"queued.min.messages\", \"10000\") // Reduce memory usage\n", "file_path": "src/cache.rs", "rank": 83, "score": 68065.40062174835 }, { "content": "struct NullWatcher;\n\nimpl Watcher for NullWatcher {\n\n fn handle(&self, _: WatchedEvent) {}\n\n}\n\n\n\nimpl ZK {\n\n pub fn new(url: &str) -> Result<ZK> {\n\n ZooKeeper::connect(url, Duration::from_secs(15), NullWatcher)\n\n .map(|client| ZK { client })\n\n .chain_err(|| \"Unable to connect to Zookeeper\") // TODO: show url?\n\n }\n\n\n\n pub fn pending_reassignment(&self) -> Option<Reassignment> {\n\n let data = match self.client.get_data(REASSIGN_PARTITIONS, false) {\n\n Ok((data, _)) => data,\n\n Err(ZkError::NoNode) => return None, // no pending reassignment node\n\n Err(error) => {\n\n println!(\"Error fetching reassignment: {:?}\", error);\n\n return None;\n\n }\n\n };\n\n\n\n let raw = str::from_utf8(&data).ok()?;\n\n serde_json::from_str(raw).ok()\n\n }\n\n}\n", "file_path": "src/zk.rs", "rank": 84, "score": 64189.51195024618 }, { "content": "fn parse_message(key: &[u8], payload: &[u8]) -> Result<ConsumerUpdate> {\n\n let mut key_rdr = Cursor::new(key);\n\n let key_version = key_rdr\n\n .read_i16::<BigEndian>()\n\n .chain_err(|| \"Failed to parse key version\")?;\n\n match key_version {\n\n 0 | 1 => parse_group_offset(&mut key_rdr, &mut Cursor::new(payload))\n\n .chain_err(|| \"Failed to parse group offset update\"),\n\n 2 => Ok(ConsumerUpdate::Metadata),\n\n _ => bail!(\"Key version not recognized\"),\n\n }\n\n}\n\n\n", "file_path": "src/offsets.rs", "rank": 85, "score": 63933.11180894145 }, { "content": "fn commit_offset_position_to_array(tp_list: TopicPartitionList) -> Vec<i64> {\n\n let tp_elements = tp_list.elements_for_topic(\"__consumer_offsets\");\n\n let mut offsets = vec![0; tp_elements.len()];\n\n for tp in &tp_elements {\n\n offsets[tp.partition() as usize] = tp.offset().to_raw();\n\n }\n\n offsets\n\n}\n\n\n", "file_path": "src/offsets.rs", "rank": 86, "score": 63117.0579751623 }, { "content": "#[derive(Debug)]\n\nstruct GroupInfo {\n\n state: String,\n\n members: usize,\n\n topics: HashSet<TopicName>,\n\n}\n\n\n\nimpl GroupInfo {\n\n fn new(state: String, members: usize) -> GroupInfo {\n\n GroupInfo {\n\n state,\n\n members,\n\n topics: HashSet::new(),\n\n }\n\n }\n\n\n\n fn new_empty() -> GroupInfo {\n\n GroupInfo {\n\n state: \"Offsets only\".to_owned(),\n\n members: 0,\n\n topics: HashSet::new(),\n\n }\n\n }\n\n\n\n fn add_topic(&mut self, topic_name: TopicName) {\n\n self.topics.insert(topic_name);\n\n }\n\n}\n\n\n", "file_path": "src/web_server/api.rs", "rank": 87, "score": 61937.92994284745 }, { "content": "#[derive(Clone)]\n\nstruct ValueContainer<V> {\n\n value: V,\n\n updated: u64, // millis since epoch\n\n}\n\n\n\nimpl<V> ValueContainer<V> {\n\n fn new(value: V) -> ValueContainer<V> {\n\n ValueContainer {\n\n value,\n\n updated: millis_to_epoch(SystemTime::now()) as u64,\n\n }\n\n }\n\n\n\n fn new_with_timestamp(value: V, timestamp: u64) -> ValueContainer<V> {\n\n ValueContainer {\n\n value,\n\n updated: timestamp,\n\n }\n\n }\n\n}\n", "file_path": "src/cache.rs", "rank": 88, "score": 60973.63267487487 }, { "content": "#[derive(Debug)]\n\nenum ParserError {\n\n Format,\n\n Io(io::Error),\n\n Utf8(str::Utf8Error),\n\n}\n\n\n\nimpl From<io::Error> for ParserError {\n\n fn from(err: io::Error) -> ParserError {\n\n ParserError::Io(err)\n\n }\n\n}\n\n\n\nimpl From<str::Utf8Error> for ParserError {\n\n fn from(err: str::Utf8Error) -> ParserError {\n\n ParserError::Utf8(err)\n\n }\n\n}\n\n\n", "file_path": "examples/consumer_offsets_reader.rs", "rank": 89, "score": 60802.27760545956 }, { "content": "fn parse_broker_rate_metrics(jolokia_json_response: &Value) -> Result<HashMap<TopicName, f64>> {\n\n let value_map = jolokia_response_get_value(jolokia_json_response)\n\n .chain_err(|| \"Failed to extract 'value' from jolokia response.\")?;\n\n let mut metrics = HashMap::new();\n\n let re = Regex::new(r\"topic=([^,]+),\").unwrap();\n\n\n\n for (mbean_name, value) in value_map.iter() {\n\n let topic = match re.captures(mbean_name) {\n\n Some(cap) => cap.get(1).unwrap().as_str(),\n\n None => \"__TOTAL__\",\n\n };\n\n if let Value::Object(ref obj) = *value {\n\n match obj.get(\"FifteenMinuteRate\") {\n\n Some(&Value::Number(ref rate)) => {\n\n metrics.insert(topic.to_owned(), rate.as_f64().unwrap_or(-1f64))\n\n }\n\n None => bail!(\"Can't find key in metric\"),\n\n _ => bail!(\"Unexpected metric type\"),\n\n };\n\n }\n\n }\n\n Ok(metrics)\n\n}\n\n\n", "file_path": "src/metrics.rs", "rank": 90, "score": 57948.23714807928 }, { "content": "pub trait OffsetStore {\n\n fn offsets_by_cluster(\n\n &self,\n\n cluster_id: &ClusterId,\n\n ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;\n\n fn offsets_by_cluster_topic(\n\n &self,\n\n cluster_id: &ClusterId,\n\n topic_name: &str,\n\n ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;\n\n fn offsets_by_cluster_group(\n\n &self,\n\n cluster_id: &ClusterId,\n\n group_name: &str,\n\n ) -> Vec<((ClusterId, String, TopicName), Vec<i64>)>;\n\n}\n\n\n\nimpl OffsetStore for Cache {\n\n fn offsets_by_cluster(\n\n &self,\n", "file_path": "src/offsets.rs", "rank": 91, "score": 57410.060366776066 }, { "content": "pub trait UpdateReceiver: Send + 'static {\n\n fn receive_update(&self, name: &str, update: ReplicaCacheUpdate) -> Result<()>;\n\n}\n\n\n", "file_path": "src/cache.rs", "rank": 92, "score": 52290.342933361724 }, { "content": "fn main() {\n\n let matches = setup_args();\n\n\n\n utils::setup_logger(true, matches.value_of(\"log-conf\"), \"%F %T%z\");\n\n\n\n let config_path = matches.value_of(\"conf\").unwrap();\n\n\n\n info!(\"Kafka-view is starting up!\");\n\n if let Err(e) = run_kafka_web(config_path) {\n\n format_error_chain!(e);\n\n std::process::exit(1);\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 93, "score": 51598.198642636286 }, { "content": "fn parse_group_offset(\n\n key_rdr: &mut Cursor<&[u8]>,\n\n payload_rdr: &mut Cursor<&[u8]>,\n\n) -> Result<ConsumerUpdate> {\n\n let group = read_string(key_rdr).chain_err(|| \"Failed to parse group name from key\")?;\n\n let topic = read_string(key_rdr).chain_err(|| \"Failed to parse topic name from key\")?;\n\n let partition = key_rdr\n\n .read_i32::<BigEndian>()\n\n .chain_err(|| \"Failed to parse partition from key\")?;\n\n if !payload_rdr.get_ref().is_empty() {\n\n // payload is not empty\n\n let _version = payload_rdr\n\n .read_i16::<BigEndian>()\n\n .chain_err(|| \"Failed to parse value version\")?;\n\n let offset = payload_rdr\n\n .read_i64::<BigEndian>()\n\n .chain_err(|| \"Failed to parse offset from value\")?;\n\n Ok(ConsumerUpdate::OffsetCommit {\n\n group,\n\n topic,\n", "file_path": "src/offsets.rs", "rank": 94, "score": 49379.14809722559 }, { "content": "// we should really have some tests here\n\nfn update_global_cache(\n\n cluster_id: &ClusterId,\n\n local_cache: &HashMap<(String, String), Vec<i64>>,\n\n cache: &OffsetsCache,\n\n) {\n\n for (&(ref group, ref topic), new_offsets) in local_cache {\n\n // Consider a consuming iterator\n\n // This logic is not needed if i store the consumer offset, right? wrong!\n\n if new_offsets.iter().any(|&offset| offset == -1) {\n\n if let Some(mut existing_offsets) =\n\n cache.get(&(cluster_id.to_owned(), group.to_owned(), topic.to_owned()))\n\n {\n\n // If the new offset is not complete and i have an old one, do the merge\n\n vec_merge_in_place(&mut existing_offsets, &new_offsets, -1, cmp::max);\n\n // for i in 0..(cmp::max(offsets.len(), existing_offsets.len())) {\n\n // let new_offset = cmp::max(\n\n // offsets.get(i).cloned().unwrap_or(-1),\n\n // existing_offsets.get(i).cloned().unwrap_or(-1));\n\n // insert_at(&mut existing_offsets, i, new_offset, -1);\n\n // }\n", "file_path": "src/offsets.rs", "rank": 95, "score": 49379.14809722559 }, { "content": "fn fetch_watermarks(\n\n cluster_id: &ClusterId,\n\n offsets: &[ClusterGroupOffsets],\n\n) -> Result<HashMap<TopicPartition, KafkaResult<(i64, i64)>>> {\n\n let consumer = CONSUMERS.get_err(cluster_id)?;\n\n\n\n let cpu_pool = Builder::new().pool_size(32).create();\n\n\n\n let mut futures = Vec::new();\n\n\n\n for &((_, _, ref topic), ref partitions) in offsets {\n\n for partition_id in 0..partitions.len() {\n\n let consumer_clone = consumer.clone();\n\n let topic_clone = topic.clone();\n\n let wm_future = cpu_pool.spawn_fn(move || {\n\n let wms = consumer_clone.fetch_watermarks(&topic_clone, partition_id as i32, 10000);\n\n Ok::<_, ()>(((topic_clone, partition_id as i32), wms)) // never fail\n\n });\n\n futures.push(wm_future);\n\n }\n", "file_path": "src/web_server/api.rs", "rank": 96, "score": 48382.94308815355 }, { "content": "fn parse_partition_size_metrics(\n\n jolokia_json_response: &Value,\n\n) -> Result<HashMap<TopicName, Vec<PartitionMetrics>>> {\n\n let value_map = jolokia_response_get_value(jolokia_json_response)\n\n .chain_err(|| \"Failed to extract 'value' from jolokia response.\")?;\n\n let topic_re = Regex::new(r\"topic=([^,]+),\").unwrap();\n\n let partition_re = Regex::new(r\"partition=([^,]+),\").unwrap();\n\n\n\n let mut metrics = HashMap::new();\n\n for (mbean_name, value) in value_map.iter() {\n\n let topic = topic_re\n\n .captures(mbean_name)\n\n .and_then(|cap| cap.get(1).map(|m| m.as_str()));\n\n let partition = partition_re\n\n .captures(mbean_name)\n\n .and_then(|cap| cap.get(1).map(|m| m.as_str()))\n\n .and_then(|p_str| p_str.parse::<u32>().ok());\n\n if topic.is_none() || partition.is_none() {\n\n bail!(\"Can't parse topic and partition metadata from metric name\");\n\n }\n", "file_path": "src/metrics.rs", "rank": 97, "score": 48382.94308815355 }, { "content": "fn cluster_pane(\n\n cluster_id: &ClusterId,\n\n broker_cache: &BrokerCache,\n\n topic_cache: &TopicCache,\n\n) -> PreEscaped<String> {\n\n let broker_count = broker_cache.get(cluster_id).unwrap_or_default().len();\n\n let topics_count = topic_cache.count(|&(ref c, _)| c == cluster_id);\n\n cluster_pane_layout(cluster_id, broker_count, topics_count)\n\n}\n\n\n", "file_path": "src/web_server/pages/clusters.rs", "rank": 98, "score": 47452.33576801783 }, { "content": "#[get(\"/\")]\n\nfn index() -> Redirect {\n\n Redirect::to(\"/clusters\")\n\n}\n\n\n\n// Make ClusterId a valid parameter\n\nimpl<'a> FromParam<'a> for ClusterId {\n\n type Error = ();\n\n\n\n fn from_param(param: &'a RawStr) -> std::result::Result<Self, Self::Error> {\n\n Ok(param.as_str().into())\n\n }\n\n}\n\n\n", "file_path": "src/web_server/server.rs", "rank": 99, "score": 47057.52262635785 } ]
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.10901526175 }, { "content": "CREATE UNIQUE INDEX transactions_t_hash_a_wi_hex_d_idx ON transactions (transaction_hash, account_workchain_id, account_hex, direction)\n\n WHERE transaction_hash IS NOT NULL;\n", "file_path": "migrations/20211007171042_transactions_hash_index.sql", "rank": 1, "score": 257492.49566000642 }, { "content": "CREATE UNIQUE INDEX token_transactions_t_hash_a_wi_hex_d_idx ON token_transactions (transaction_hash, account_workchain_id, account_hex, direction)\n\n WHERE transaction_hash IS NOT NULL;\n\n\n", "file_path": "migrations/20211007171529_token_transactions.sql", "rank": 2, "score": 247523.09660830634 }, { "content": "CREATE INDEX transactions_account_wc_hex_idx ON transactions (account_workchain_id, account_hex);\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 3, "score": 199175.30012252514 }, { "content": "CREATE INDEX transaction_events_account_wc_hex_idx ON transaction_events (account_workchain_id, account_hex);\n", "file_path": "migrations/20211007170926_transactions_events.sql", "rank": 4, "score": 190888.35566366883 }, { "content": "pub fn get_transactions_id(\n\n id: uuid::Uuid,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .get_transaction_by_id(&service_id, &id)\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 5, "score": 188784.81544737198 }, { "content": "pub fn get_tokens_transactions_id(\n\n id: uuid::Uuid,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .get_tokens_transaction_by_id(&service_id, &id)\n\n .await\n\n .map(From::from);\n\n let res = AccountTokenTransactionResponse::from(transaction);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 6, "score": 184433.58649666837 }, { "content": "CREATE INDEX token_transaction_events_account_wc_hex_idx ON token_transaction_events (account_workchain_id, account_hex);\n", "file_path": "migrations/20211007171551_token_transactions_events.sql", "rank": 7, "score": 183489.27126473212 }, { "content": "CREATE UNIQUE INDEX address_workchain_id_hex_idx ON address (workchain_id, hex);\n\n\n", "file_path": "migrations/20211007170839_initial_setup.sql", "rank": 8, "score": 180065.3902749388 }, { "content": "pub fn account_prefix(account: &UInt256, len: usize) -> u64 {\n\n debug_assert!(len <= 64);\n\n\n\n let account = account.as_slice();\n\n\n\n let mut value: u64 = 0;\n\n\n\n let bytes = len / 8;\n\n for (i, byte) in account.iter().enumerate().take(bytes) {\n\n value |= (*byte as u64) << (8 * (7 - i));\n\n }\n\n\n\n let remainder = len % 8;\n\n if remainder > 0 {\n\n let r = account[bytes] >> (8 - remainder);\n\n value |= (r as u64) << (8 * (7 - bytes) + 8 - remainder);\n\n }\n\n\n\n value\n\n}\n\n\n", "file_path": "src/utils/shard_utils.rs", "rank": 9, "score": 178729.20432782924 }, { "content": "pub fn contains_account(shard: &ton_block::ShardIdent, account: &UInt256) -> bool {\n\n let shard_prefix = shard.shard_prefix_with_tag();\n\n if shard_prefix == ton_block::SHARD_FULL {\n\n true\n\n } else {\n\n let len = shard.prefix_len();\n\n let account_prefix = account_prefix(account, len as usize) >> (64 - len);\n\n let shard_prefix = shard_prefix >> (64 - len);\n\n account_prefix == shard_prefix\n\n }\n\n}\n\n\n", "file_path": "src/utils/shard_utils.rs", "rank": 12, "score": 167125.619800864 }, { "content": "pub fn filter_transaction_query(\n\n args: &mut PgArguments,\n\n args_len: &mut i32,\n\n input: &TransactionsSearch,\n\n) -> Vec<String> {\n\n let TransactionsSearch {\n\n id,\n\n message_hash,\n\n transaction_hash,\n\n account,\n\n status,\n\n direction,\n\n created_at_min,\n\n created_at_max,\n\n ..\n\n } = input.clone();\n\n let mut updates = Vec::new();\n\n\n\n if let Some(id) = id {\n\n updates.push(format!(\" AND id = ${} \", *args_len + 1,));\n", "file_path": "src/sqlx_client/transactions.rs", "rank": 13, "score": 166020.55283177603 }, { "content": "pub fn filter_transaction_query(\n\n args: &mut PgArguments,\n\n args_len: &mut i32,\n\n input: &TransactionsEventsSearch,\n\n) -> Vec<String> {\n\n let TransactionsEventsSearch {\n\n created_at_ge,\n\n created_at_le,\n\n transaction_id,\n\n message_hash,\n\n account_workchain_id,\n\n account_hex,\n\n transaction_direction,\n\n transaction_status,\n\n event_status,\n\n ..\n\n } = input.clone();\n\n let mut updates = Vec::new();\n\n\n\n if let Some(transaction_id) = transaction_id {\n", "file_path": "src/sqlx_client/transactions_events.rs", "rank": 14, "score": 162884.54221814586 }, { "content": "pub fn get_transactions_h(\n\n transaction_hash: String,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .get_transaction_by_h(&service_id, &transaction_hash)\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 15, "score": 159093.7716651297 }, { "content": "pub fn post_transactions(\n\n service_id: ServiceId,\n\n input: PostTonTransactionsRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transactions = ctx\n\n .ton_service\n\n .search_transaction(&service_id, &input.into())\n\n .await\n\n .map(|transactions| {\n\n let transactions: Vec<_> = transactions\n\n .into_iter()\n\n .map(AccountTransactionDataResponse::from)\n\n .collect();\n\n TransactionsResponse {\n\n count: transactions.len() as i32,\n\n items: transactions,\n\n }\n\n });\n\n\n\n let res = TonTransactionsResponse::from(transactions);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 16, "score": 159093.7716651297 }, { "content": "pub fn get_events_id(\n\n id: uuid::Uuid,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let event = ctx\n\n .ton_service\n\n .get_event_by_id(&service_id, &id)\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionEventResponse::from(event);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 17, "score": 157180.05040381468 }, { "content": "pub fn post_address_create(\n\n service_id: ServiceId,\n\n input: CreateAddressRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let address = ctx\n\n .ton_service\n\n .create_address(&service_id, input.into())\n\n .await\n\n .map(From::from);\n\n let res = AccountAddressResponse::from(address);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 18, "score": 157165.9302240833 }, { "content": "pub fn post_address_check(\n\n _service_id: ServiceId,\n\n input: PostAddressBalanceRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let address = ctx\n\n .ton_service\n\n .check_address(input.address)\n\n .await\n\n .map(PostAddressValidResponse::new);\n\n let res = PostCheckedAddressResponse::from(address);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 19, "score": 157165.9302240833 }, { "content": "pub fn get_address_info(\n\n address: Address,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let address = ctx\n\n .ton_service\n\n .get_address_info(&service_id, address)\n\n .await\n\n .map(PostAddressInfoDataResponse::new);\n\n let res = AddressInfoResponse::from(address);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 20, "score": 157165.9302240833 }, { "content": "pub fn get_address_balance(\n\n address: Address,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let address = ctx\n\n .ton_service\n\n .get_address_balance(&service_id, address)\n\n .await\n\n .map(|(a, b)| PostAddressBalanceDataResponse::new(a, b));\n\n let res = AddressBalanceResponse::from(address);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 21, "score": 157165.9302240833 }, { "content": "pub fn filter_token_transaction_query(\n\n args: &mut PgArguments,\n\n args_len: &mut i32,\n\n input: &TokenTransactionsEventsSearch,\n\n) -> Vec<String> {\n\n let TokenTransactionsEventsSearch {\n\n created_at_ge,\n\n created_at_le,\n\n token_transaction_id,\n\n root_address,\n\n message_hash,\n\n account_workchain_id,\n\n account_hex,\n\n owner_message_hash,\n\n transaction_direction,\n\n transaction_status,\n\n event_status,\n\n ..\n\n } = input.clone();\n\n let mut updates = Vec::new();\n", "file_path": "src/sqlx_client/token_transactions_events.rs", "rank": 22, "score": 157144.14024146134 }, { "content": "CREATE INDEX tasks_account_wc_hex_idx ON tasks (account_workchain_id, account_hex);\n", "file_path": "migrations/20211007171015_tasks.sql", "rank": 23, "score": 156381.43615226969 }, { "content": "pub fn post_transactions_create(\n\n service_id: ServiceId,\n\n input: PostTonTransactionSendRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .create_send_transaction(&service_id, input.into())\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 24, "score": 155614.30216826402 }, { "content": "pub fn post_transactions_confirm(\n\n service_id: ServiceId,\n\n input: PostTonTransactionConfirmRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .create_confirm_transaction(&service_id, input.into())\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 25, "score": 155614.30216826402 }, { "content": "pub fn get_transactions_mh(\n\n message_hash: String,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .get_transaction_by_mh(&service_id, &message_hash)\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 26, "score": 155614.30216826402 }, { "content": "pub fn parse_last_transaction(\n\n last_transaction: &LastTransactionId,\n\n) -> (Option<String>, Option<String>) {\n\n let (last_transaction_hash, last_transaction_lt) = match last_transaction {\n\n LastTransactionId::Exact(transaction_id) => (\n\n Some(transaction_id.hash.to_hex_string()),\n\n Some(transaction_id.lt.to_string()),\n\n ),\n\n LastTransactionId::Inexact { .. } => (None, None),\n\n };\n\n\n\n (last_transaction_hash, last_transaction_lt)\n\n}\n", "file_path": "src/client/ton/utils.rs", "rank": 27, "score": 155614.30216826402 }, { "content": "pub fn get_token_wallet_account(\n\n root_contract: &ExistingContract,\n\n owner: &MsgAddressInt,\n\n) -> Result<UInt256> {\n\n let root_contract_state = RootTokenContractState(root_contract);\n\n let RootTokenContractDetails { version, .. } =\n\n root_contract_state.guess_details(&SimpleClock)?;\n\n\n\n let token_wallet_address =\n\n root_contract_state.get_wallet_address(&SimpleClock, version, owner)?;\n\n let token_wallet_account =\n\n UInt256::from_be_bytes(&token_wallet_address.address().get_bytestring(0));\n\n\n\n Ok(token_wallet_account)\n\n}\n\n\n", "file_path": "src/utils/token_wallet.rs", "rank": 28, "score": 153886.76196186815 }, { "content": "pub fn get_token_wallet_address(\n\n root_contract: &ExistingContract,\n\n owner: &MsgAddressInt,\n\n) -> Result<MsgAddressInt> {\n\n let root_contract_state = RootTokenContractState(root_contract);\n\n let RootTokenContractDetails { version, .. } =\n\n root_contract_state.guess_details(&SimpleClock)?;\n\n\n\n root_contract_state.get_wallet_address(&SimpleClock, version, owner)\n\n}\n\n\n", "file_path": "src/utils/token_wallet.rs", "rank": 29, "score": 153866.30015153624 }, { "content": "pub fn get_tokens_address_balance(\n\n address: Address,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let addresses = ctx\n\n .ton_service\n\n .get_token_address_balance(&service_id, &address)\n\n .await\n\n .map(|a| {\n\n a.into_iter()\n\n .map(|(a, b)| TokenBalanceResponse::new(a, b))\n\n .collect::<Vec<TokenBalanceResponse>>()\n\n });\n\n let res = AccountTokenBalanceResponse::from(addresses);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 30, "score": 153866.30015153624 }, { "content": "pub fn post_tokens_transactions_mint(\n\n service_id: ServiceId,\n\n input: PostTonTokenTransactionMintRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .create_mint_token_transaction(&service_id, &input.into())\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 31, "score": 152366.2770245844 }, { "content": "pub fn post_tokens_transactions_create(\n\n service_id: ServiceId,\n\n input: PostTonTokenTransactionSendRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .create_send_token_transaction(&service_id, &input.into())\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 32, "score": 152366.2770245844 }, { "content": "pub fn get_tokens_transactions_mh(\n\n message_hash: String,\n\n service_id: ServiceId,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .get_tokens_transaction_by_mh(&service_id, &message_hash)\n\n .await\n\n .map(From::from);\n\n let res = AccountTokenTransactionResponse::from(transaction);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 33, "score": 152366.2770245844 }, { "content": "pub fn post_tokens_transactions_burn(\n\n service_id: ServiceId,\n\n input: PostTonTokenTransactionBurnRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx\n\n .ton_service\n\n .create_burn_token_transaction(&service_id, &input.into())\n\n .await\n\n .map(From::from);\n\n let res = AccountTransactionResponse::from(transaction);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 34, "score": 152366.2770245844 }, { "content": "CREATE INDEX transactions_messages_hash_gin_idx ON transactions USING gin (messages_hash jsonb_path_ops);\n\n\n", "file_path": "migrations/20211007171337_fixes_old_scheme.sql", "rank": 35, "score": 150992.09355053242 }, { "content": "CREATE INDEX transactions_m_hash_idx ON transactions (message_hash);\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 36, "score": 145869.22767366222 }, { "content": "CREATE INDEX token_transactions_m_hash_idx ON token_transactions (message_hash);\n", "file_path": "migrations/20211007171529_token_transactions.sql", "rank": 37, "score": 138007.66423648005 }, { "content": "CREATE INDEX transaction_events_m_hash_idx ON transaction_events (message_hash);\n", "file_path": "migrations/20211007170926_transactions_events.sql", "rank": 38, "score": 138007.66423648005 }, { "content": "CREATE INDEX token_transaction_events_m_hash_idx ON token_transaction_events (message_hash);\n", "file_path": "migrations/20211007171551_token_transactions_events.sql", "rank": 40, "score": 131156.67351538118 }, { "content": "pub fn post_events(\n\n service_id: ServiceId,\n\n input: PostTonTransactionEventsRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transactions_events = ctx\n\n .ton_service\n\n .search_events(&service_id, &input.into())\n\n .await\n\n .map(|transactions_events| {\n\n let events: Vec<_> = transactions_events\n\n .into_iter()\n\n .map(AccountTransactionEvent::from)\n\n .collect();\n\n EventsResponse {\n\n count: events.len() as i32,\n\n items: events,\n\n }\n\n });\n\n\n\n let res = TonEventsResponse::from(transactions_events);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 41, "score": 126362.97709908904 }, { "content": "pub fn swagger() -> String {\n\n let api = describe_api! {\n\n info: {\n\n title: \"TON api\",\n\n version: \"4.0.0\",\n\n description: r##\"This API allows you to use TON api\"##,\n\n },\n\n servers: {\n\n \"https://ton-api.broxus.com/ton/v3\",\n\n \"https://ton-api-test.broxus.com/ton/v3\"\n\n },\n\n tags: {\n\n addresses,\n\n transactions,\n\n tokens,\n\n events,\n\n metrics,\n\n },\n\n paths: {\n\n (\"address\" / \"check\"): {\n", "file_path": "src/api/docs.rs", "rank": 43, "score": 124231.7198208154 }, { "content": "pub fn prepare_token_burn(\n\n owner: MsgAddressInt,\n\n token_wallet: MsgAddressInt,\n\n version: TokenWalletVersion,\n\n tokens: BigUint,\n\n send_gas_to: MsgAddressInt,\n\n callback_to: MsgAddressInt,\n\n attached_amount: u64,\n\n payload: ton_types::Cell,\n\n) -> Result<InternalMessage> {\n\n let (function, input) = match version {\n\n TokenWalletVersion::OldTip3v4 => {\n\n use old_tip3::token_wallet_contract;\n\n MessageBuilder::new(token_wallet_contract::burn_by_owner())\n\n .arg(BigUint128(tokens)) // amount\n\n .arg(0u128) // grams\n\n .arg(send_gas_to) // remainingGasTo\n\n .arg(callback_to) // callback_address\n\n .arg(payload) // payload\n\n .build()\n", "file_path": "src/utils/token_wallet.rs", "rank": 44, "score": 124009.5371247067 }, { "content": "pub fn prepare_token_transfer(\n\n owner: MsgAddressInt,\n\n token_wallet: MsgAddressInt,\n\n version: TokenWalletVersion,\n\n destination: TransferRecipient,\n\n tokens: BigUint,\n\n send_gas_to: MsgAddressInt,\n\n notify_receiver: bool,\n\n attached_amount: u64,\n\n payload: ton_types::Cell,\n\n) -> Result<InternalMessage> {\n\n let (function, input) = match version {\n\n TokenWalletVersion::OldTip3v4 => {\n\n use old_tip3::token_wallet_contract;\n\n match destination {\n\n TransferRecipient::TokenWallet(token_wallet) => {\n\n MessageBuilder::new(token_wallet_contract::transfer())\n\n .arg(token_wallet) // to\n\n .arg(BigUint128(tokens)) // tokens\n\n }\n", "file_path": "src/utils/token_wallet.rs", "rank": 45, "score": 124009.5371247067 }, { "content": "pub fn post_tokens_events(\n\n service_id: ServiceId,\n\n input: PostTonTokenTransactionEventsRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transactions_events = ctx\n\n .ton_service\n\n .search_token_events(&service_id, &input.into())\n\n .await?;\n\n let events: Vec<_> = transactions_events\n\n .into_iter()\n\n .map(AccountTransactionEvent::from)\n\n .collect();\n\n let res = TonTokenEventsResponse {\n\n status: TonStatus::Ok,\n\n data: Some(TokenEventsResponse {\n\n count: events.len() as i32,\n\n items: events,\n\n }),\n\n error_message: None,\n\n };\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 46, "score": 124009.5371247067 }, { "content": "pub fn prepare_token_mint(\n\n owner: MsgAddressInt,\n\n root_token: MsgAddressInt,\n\n version: TokenWalletVersion,\n\n tokens: BigUint,\n\n recipient: MsgAddressInt,\n\n deploy_wallet_value: BigUint,\n\n send_gas_to: MsgAddressInt,\n\n notify: bool,\n\n attached_amount: u64,\n\n payload: ton_types::Cell,\n\n) -> Result<InternalMessage> {\n\n let (function, input) = match version {\n\n TokenWalletVersion::OldTip3v4 => return Err(TokenWalletError::MintNotSupported.into()),\n\n TokenWalletVersion::Tip3 => {\n\n use tip3_1::root_token_contract;\n\n MessageBuilder::new(root_token_contract::mint())\n\n .arg(BigUint128(tokens)) // amount\n\n .arg(recipient) // recipient\n\n .arg(BigUint128(deploy_wallet_value)) // deployWalletValue\n", "file_path": "src/utils/token_wallet.rs", "rank": 47, "score": 124009.5371247067 }, { "content": "pub fn post_events_mark_all(\n\n service_id: ServiceId,\n\n input: MarkAllTransactionEventRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transactions = ctx\n\n .ton_service\n\n .mark_all_events(&service_id, input.event_status)\n\n .await;\n\n let res = MarkEventsResponse::from(transactions);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 48, "score": 124009.5371247067 }, { "content": "pub fn post_events_mark(\n\n service_id: ServiceId,\n\n input: PostTonMarkEventsRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let transaction = ctx.ton_service.mark_event(&service_id, &input.id).await;\n\n let res = MarkEventsResponse::from(transaction);\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 49, "score": 124009.5371247067 }, { "content": "pub fn encrypt_private_key(private_key: &[u8], key: [u8; 32], id: &uuid::Uuid) -> Result<String> {\n\n use chacha20poly1305::aead::NewAead;\n\n let nonce = Nonce::from_slice(&id.as_bytes()[0..12]);\n\n let key = chacha20poly1305::Key::from_slice(&key[..]);\n\n let mut encryptor = ChaCha20Poly1305::new(key);\n\n let res = encryptor.encrypt(nonce, private_key).map_err(Error::msg)?;\n\n Ok(base64::encode(&res))\n\n}\n\n\n", "file_path": "src/utils/encoding.rs", "rank": 51, "score": 122912.25301745857 }, { "content": "pub fn post_tokens_events_mark(\n\n service_id: ServiceId,\n\n input: PostTonTokenMarkEventsRequest,\n\n ctx: Context,\n\n) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n ctx.ton_service\n\n .mark_token_event(&service_id, &input.id)\n\n .await?;\n\n let res = MarkTokenEventsResponse {\n\n status: TonStatus::Ok,\n\n error_message: None,\n\n };\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n\n\n", "file_path": "src/api/controllers/ton.rs", "rank": 52, "score": 121812.64124221072 }, { "content": "pub fn get_token_wallet_details(\n\n token_contract: &ExistingContract,\n\n) -> Result<(TokenWalletDetails, TokenWalletVersion, [u8; 32])> {\n\n let contract_state = nekoton::core::token_wallet::TokenWalletContractState(token_contract);\n\n\n\n let hash = *contract_state.get_code_hash()?.as_slice();\n\n let version = contract_state.get_version(&SimpleClock)?;\n\n let details = contract_state.get_details(&SimpleClock, version)?;\n\n\n\n Ok((details, version, hash))\n\n}\n\n\n", "file_path": "src/utils/token_wallet.rs", "rank": 53, "score": 121812.64124221072 }, { "content": "pub fn get_token_wallet_basic_info(\n\n token_contract: &ExistingContract,\n\n) -> Result<(TokenWalletVersion, BigDecimal)> {\n\n let token_wallet_state = TokenWalletContractState(token_contract);\n\n\n\n let version = token_wallet_state.get_version(&SimpleClock)?;\n\n let balance = BigDecimal::new(\n\n token_wallet_state\n\n .get_balance(&SimpleClock, version)?\n\n .into(),\n\n 0,\n\n );\n\n\n\n Ok((version, balance))\n\n}\n\n\n", "file_path": "src/utils/token_wallet.rs", "rank": 54, "score": 119757.17290870889 }, { "content": "pub fn decrypt_private_key(private_key: &str, key: [u8; 32], id: &uuid::Uuid) -> Result<Vec<u8>> {\n\n use chacha20poly1305::aead::NewAead;\n\n let nonce = Nonce::from_slice(&id.as_bytes()[0..12]);\n\n let key = chacha20poly1305::Key::from_slice(&key[..]);\n\n let mut decrypter = ChaCha20Poly1305::new(key);\n\n decrypter\n\n .decrypt(nonce, base64::decode(private_key)?.as_slice())\n\n .map_err(Error::msg)\n\n}\n", "file_path": "src/utils/encoding.rs", "rank": 56, "score": 118871.93700561643 }, { "content": "CREATE INDEX token_owners_address_idx ON token_owners (owner_account_workchain_id, owner_account_hex, root_address);\n", "file_path": "migrations/20211007171539_token_owners.sql", "rank": 57, "score": 118693.56307496323 }, { "content": "CREATE INDEX token_transactions_owner_m_hash_idx ON token_transactions (owner_message_hash) WHERE owner_message_hash IS NOT NULL;\n", "file_path": "migrations/20211007171529_token_transactions.sql", "rank": 58, "score": 118657.06904140982 }, { "content": "CREATE INDEX transactions_t_hash_idx ON transactions (transaction_hash);\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 59, "score": 117018.47207275934 }, { "content": "CREATE INDEX token_transaction_events_owner_m_hash_idx ON token_transaction_events (owner_message_hash) WHERE owner_message_hash IS NOT NULL;\n", "file_path": "migrations/20211007171551_token_transactions_events.sql", "rank": 60, "score": 113281.56347590165 }, { "content": "CREATE INDEX token_transactions_t_hash_idx ON token_transactions (transaction_hash);\n", "file_path": "migrations/20211007171529_token_transactions.sql", "rank": 61, "score": 112367.3516933614 }, { "content": "ALTER TABLE transactions ADD COLUMN messages_hash JSONB;\n", "file_path": "migrations/20211007171337_fixes_old_scheme.sql", "rank": 62, "score": 111528.34946232065 }, { "content": "ALTER TABLE transactions ADD COLUMN multisig_transaction_id BIGINT;\n", "file_path": "migrations/20211130091836_transactions_events_add_multisig_transaction_id.sql", "rank": 63, "score": 106509.16370137228 }, { "content": "ALTER TABLE transaction_events ADD COLUMN multisig_transaction_id BIGINT;", "file_path": "migrations/20211130091836_transactions_events_add_multisig_transaction_id.sql", "rank": 64, "score": 105208.37147528667 }, { "content": "#[allow(dead_code)]\n\npub fn not_found_request() -> http::Response<hyper::Body> {\n\n let body = serde_json::json!({\n\n \"description\": \"Not found\",\n\n })\n\n .to_string();\n\n let response = Response::new(body);\n\n let (mut parts, body) = response.into_parts();\n\n parts.status = StatusCode::NOT_FOUND;\n\n parts\n\n .headers\n\n .insert(\"Content-Type\", HeaderValue::from_static(\"application/json\"));\n\n Response::from_parts(parts, body.into())\n\n}\n", "file_path": "src/api/utils.rs", "rank": 65, "score": 104743.39127854232 }, { "content": "fn build_token_transaction(\n\n ton_core: &Arc<TonCore>,\n\n id: Uuid,\n\n owner: MsgAddressInt,\n\n public_key: &[u8],\n\n private_key: &[u8],\n\n account_type: &AccountType,\n\n custodians: &Option<i32>,\n\n internal_message: InternalMessage,\n\n) -> Result<(SentTransaction, SignedMessage)> {\n\n let flags = TransactionSendOutputType::default();\n\n\n\n let bounce = internal_message.bounce;\n\n let destination = internal_message.destination;\n\n let amount = internal_message.amount;\n\n let body = Some(internal_message.body);\n\n\n\n let expiration = Expiration::Timeout(DEFAULT_EXPIRATION_TIMEOUT);\n\n\n\n let public_key = PublicKey::from_bytes(public_key).unwrap_or_default();\n", "file_path": "src/client/ton/mod.rs", "rank": 66, "score": 98642.58575027113 }, { "content": "pub fn bad_request(err: String) -> http::Response<hyper::Body> {\n\n let body = serde_json::json!({\n\n \"description\": \"Bad request\",\n\n \"error\": err\n\n })\n\n .to_string();\n\n let response = Response::new(body);\n\n let (mut parts, body) = response.into_parts();\n\n parts.status = StatusCode::BAD_REQUEST;\n\n parts\n\n .headers\n\n .insert(\"Content-Type\", HeaderValue::from_static(\"application/json\"));\n\n Response::from_parts(parts, body.into())\n\n}\n\n\n", "file_path": "src/api/utils.rs", "rank": 67, "score": 96081.11749079877 }, { "content": "pub fn get_root_token_version(root_contract: &ExistingContract) -> Result<TokenWalletVersion> {\n\n let root_contract_state = RootTokenContractState(root_contract);\n\n let RootTokenContractDetails { version, .. } =\n\n root_contract_state.guess_details(&SimpleClock)?;\n\n\n\n Ok(version)\n\n}\n\n\n", "file_path": "src/utils/token_wallet.rs", "rank": 69, "score": 93378.85789265204 }, { "content": "/// Helper trait to reduce boilerplate for getting accounts from shards state\n\npub trait ShardAccountsMapExt {\n\n /// Looks for a suitable shard and tries to extract information about the contract from it\n\n fn find_account(&self, account: &UInt256) -> Result<Option<ExistingContract>>;\n\n}\n\n\n\nimpl<T> ShardAccountsMapExt for &T\n\nwhere\n\n T: ShardAccountsMapExt,\n\n{\n\n fn find_account(&self, account: &UInt256) -> Result<Option<ExistingContract>> {\n\n T::find_account(self, account)\n\n }\n\n}\n\n\n\nimpl ShardAccountsMapExt for ShardAccountsMap {\n\n fn find_account(&self, account: &UInt256) -> Result<Option<ExistingContract>> {\n\n // Search suitable shard for account by prefix.\n\n // NOTE: In **most** cases suitable shard will be found\n\n let item = self\n\n .iter()\n", "file_path": "src/utils/shard_utils.rs", "rank": 70, "score": 93025.79718727975 }, { "content": "fn default_logger_settings() -> serde_yaml::Value {\n\n const DEFAULT_LOG4RS_SETTINGS: &str = r##\"\n\n appenders:\n\n stdout:\n\n kind: console\n\n encoder:\n\n pattern: \"{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - {h({l})} {M} = {m} {n}\"\n\n root:\n\n level: info\n\n appenders:\n\n - stdout\n\n loggers:\n\n ton_wallet_api:\n\n level: info\n\n appenders:\n\n - stdout\n\n additive: false\n\n \"##;\n\n serde_yaml::from_str(DEFAULT_LOG4RS_SETTINGS).trust_me()\n\n}\n", "file_path": "src/settings.rs", "rank": 71, "score": 93015.07451242069 }, { "content": "ALTER TABLE ONLY address ALTER COLUMN id SET DEFAULT uuid_generate_v4();\n", "file_path": "migrations/20211007171337_fixes_old_scheme.sql", "rank": 72, "score": 92632.96922724915 }, { "content": "pub trait ReadFromTransaction: Sized {\n\n fn read_from_transaction(ctx: &TxContext<'_>, state: HandleTransactionStatusTx)\n\n -> Option<Self>;\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\npub struct TxContext<'a> {\n\n pub shard_accounts: &'a ton_block::ShardAccounts,\n\n pub block_info: &'a ton_block::BlockInfo,\n\n pub block_hash: &'a UInt256,\n\n pub account: &'a UInt256,\n\n pub transaction_hash: &'a UInt256,\n\n pub transaction_info: &'a ton_block::TransactionDescrOrdinary,\n\n pub transaction: &'a ton_block::Transaction,\n\n pub in_msg: &'a ton_block::Message,\n\n pub token_transaction: &'a Option<nekoton::core::models::TokenWalletTransaction>,\n\n}\n\n\n\nimpl TxContext<'_> {\n\n pub fn in_msg_internal(&self) -> Option<&ton_block::Message> {\n", "file_path": "src/utils/tx_context.rs", "rank": 73, "score": 91319.12301896361 }, { "content": "CREATE OR REPLACE FUNCTION update_account_balance_on_update() RETURNS TRIGGER AS\n\n$$\n\nBEGIN\n\n LOCK TABLE address IN SHARE ROW EXCLUSIVE MODE;\n\n UPDATE address\n\n SET (balance, updated_at) = (balance + coalesce(NEW.balance_change, 0) - coalesce(OLD.balance_change, 0), current_timestamp)\n\n WHERE hex = NEW.account_hex AND workchain_id = NEW.account_workchain_id;\n\n RETURN NEW;\n\nEND;\n\n$$ LANGUAGE plpgsql;\n\n\n", "file_path": "migrations/20211007170940_address_balance.sql", "rank": 74, "score": 90365.2242516013 }, { "content": "CREATE OR REPLACE FUNCTION update_account_balance_on_insert() RETURNS TRIGGER AS\n\n$$\n\nBEGIN\n\n LOCK TABLE address IN SHARE ROW EXCLUSIVE MODE;\n\n UPDATE address\n\n SET (balance, updated_at) = (balance + coalesce(NEW.balance_change, 0), current_timestamp)\n\n WHERE hex = NEW.account_hex AND workchain_id = NEW.account_workchain_id;\n\n RETURN NEW;\n\nEND;\n\n$$ LANGUAGE plpgsql;\n\n\n", "file_path": "migrations/20211007170940_address_balance.sql", "rank": 75, "score": 90365.2242516013 }, { "content": "CREATE OR REPLACE FUNCTION update_account_balance_on_delete() RETURNS TRIGGER AS\n\n$$\n\nBEGIN\n\n LOCK TABLE address IN SHARE ROW EXCLUSIVE MODE;\n\n UPDATE address\n\n SET (balance, updated_at) = (balance - coalesce(OLD.balance_change, 0), current_timestamp)\n\n WHERE hex = OLD.account_hex AND workchain_id = OLD.account_workchain_id;\n\n RETURN NEW;\n\nEND;\n\n$$ LANGUAGE plpgsql;\n\n\n", "file_path": "migrations/20211007170940_address_balance.sql", "rank": 76, "score": 90365.2242516013 }, { "content": "CREATE INDEX transactions_service_id_idx ON transactions (service_id);\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 77, "score": 87791.93084567925 }, { "content": "CREATE UNIQUE INDEX transaction_events_transaction_id_status ON transaction_events (transaction_id, transaction_status);\n", "file_path": "migrations/20211007170926_transactions_events.sql", "rank": 78, "score": 87200.08972256904 }, { "content": "fn init_logger(config: &serde_yaml::Value) -> Result<()> {\n\n let config = serde_yaml::from_value(config.clone())?;\n\n log4rs::config::init_raw_config(config)?;\n\n Ok(())\n\n}\n", "file_path": "src/main.rs", "rank": 79, "score": 87120.3647255863 }, { "content": "fn calc_sign(body: String, url: String, timestamp_ms: i64, secret: String) -> String {\n\n let mut mac = Hmac::<sha2::Sha256>::new_from_slice(secret.as_bytes()).trust_me();\n\n let signing_phrase = format!(\"{}{}{}\", timestamp_ms, url, body);\n\n mac.update(signing_phrase.as_bytes());\n\n let hash_result = mac.finalize().into_bytes();\n\n base64::encode(&hash_result)\n\n}\n", "file_path": "src/client/callback/mod.rs", "rank": 80, "score": 87085.00923881275 }, { "content": "pub trait TransactionsSubscription: Send + Sync {\n\n fn handle_transaction(\n\n &self,\n\n ctx: TxContext<'_>,\n\n state: HandleTransactionStatusTx,\n\n ) -> Result<()>;\n\n}\n\n\n\n/// Generic listener for transactions\n\npub struct AccountObserver<T>(AccountEventsTx<T>);\n\n\n\nimpl<T> AccountObserver<T> {\n\n pub fn new(tx: AccountEventsTx<T>) -> Arc<Self> {\n\n Arc::new(Self(tx))\n\n }\n\n}\n\n\n\nimpl<T> TransactionsSubscription for AccountObserver<T>\n\nwhere\n\n T: ReadFromTransaction + std::fmt::Debug + Send + Sync,\n", "file_path": "src/ton_core/ton_subscriber/mod.rs", "rank": 81, "score": 83286.87401629784 }, { "content": "CREATE INDEX token_transactions_service_id_idx ON token_transactions (service_id);\n", "file_path": "migrations/20211007171529_token_transactions.sql", "rank": 82, "score": 83037.42314644963 }, { "content": "CREATE INDEX transaction_events_service_id_idx ON transaction_events (service_id);\n", "file_path": "migrations/20211007170926_transactions_events.sql", "rank": 83, "score": 83037.42314644963 }, { "content": "CREATE UNIQUE INDEX token_transaction_events_transaction_id_status ON token_transaction_events (token_transaction_id, transaction_status);\n", "file_path": "migrations/20211007171551_token_transactions_events.sql", "rank": 84, "score": 82779.37426668723 }, { "content": "pub fn get_metrics(ctx: Context) -> BoxFuture<'static, Result<impl warp::Reply, warp::Rejection>> {\n\n async move {\n\n let metrics = ctx.ton_service.get_metrics().await?;\n\n let res = MetricsResponse::from(metrics);\n\n\n\n Ok(warp::reply::json(&(res)))\n\n }\n\n .boxed()\n\n}\n", "file_path": "src/api/controllers/ton.rs", "rank": 85, "score": 80071.00682177088 }, { "content": "CREATE INDEX token_transaction_events_service_id_idx ON token_transaction_events (service_id);\n", "file_path": "migrations/20211007171551_token_transactions_events.sql", "rank": 86, "score": 78779.018049406 }, { "content": "ALTER TABLE transaction_events ADD COLUMN sender_hex VARCHAR(64);\n\n\n", "file_path": "migrations/20211007171337_fixes_old_scheme.sql", "rank": 87, "score": 78326.34653209611 }, { "content": "ALTER TABLE transaction_events ADD COLUMN sender_workchain_id INT;\n", "file_path": "migrations/20211007171337_fixes_old_scheme.sql", "rank": 88, "score": 77896.9650443636 }, { "content": "DROP TYPE IF EXISTS twa_transaction_direction;\n\n\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 89, "score": 77554.56206661882 }, { "content": "CREATE TYPE twa_transaction_direction as ENUM (\n\n 'Send',\n\n 'Receive'\n\n );\n\n\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 90, "score": 77554.56206661882 }, { "content": "#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]\n\nstruct PendingMessageId {\n\n account: UInt256,\n\n message_hash: UInt256,\n\n}\n\n\n", "file_path": "src/utils/pending_messages_queue.rs", "rank": 91, "score": 77295.00715184628 }, { "content": "ALTER TABLE address ADD COLUMN balance NUMERIC NOT NULL DEFAULT 0;\n", "file_path": "migrations/20211007170940_address_balance.sql", "rank": 92, "score": 77043.72618803839 }, { "content": "CREATE INDEX transactions_timestamp_idx ON transactions (transaction_timestamp) WHERE transaction_timestamp IS NOT NULL;\n", "file_path": "migrations/20211007171128_transaction_timestamp.sql", "rank": 93, "score": 76426.40639472374 }, { "content": "CREATE INDEX transactions_lt_idx ON transactions (transaction_lt) WHERE transaction_lt IS NOT NULL;\n", "file_path": "migrations/20211007171101_transaction_lt_index.sql", "rank": 94, "score": 75948.72063398163 }, { "content": "#[derive(thiserror::Error, Debug)]\n\nenum PendingMessagesQueueError {\n\n #[error(\"Already exists\")]\n\n AlreadyExists,\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n fn make_hash(id: u8) -> UInt256 {\n\n let mut hash = [0; 32];\n\n hash[0] = id;\n\n UInt256::from(hash)\n\n }\n\n\n\n fn make_queue() -> Arc<PendingMessagesQueue> {\n\n let queue = PendingMessagesQueue::new(10);\n\n assert_eq!(queue.min_expire_at.load(Ordering::Acquire), u32::MAX);\n\n queue\n\n }\n", "file_path": "src/utils/pending_messages_queue.rs", "rank": 95, "score": 75373.355599236 }, { "content": " transaction_id: t.token_transaction_id,\n\n message_hash: t.message_hash,\n\n owner_message_hash: t.owner_message_hash,\n\n account: AddressResponse {\n\n workchain_id: t.account_workchain_id,\n\n hex: Address(t.account_hex),\n\n base64url,\n\n },\n\n sender: None,\n\n balance_change: Some(t.value),\n\n root_address: Some(t.root_address),\n\n transaction_direction: t.transaction_direction,\n\n transaction_status: t.transaction_status.into(),\n\n event_status: t.event_status,\n\n multisig_transaction_id: None,\n\n created_at: t.created_at.timestamp_millis(),\n\n updated_at: t.updated_at.timestamp_millis(),\n\n }\n\n }\n\n}\n", "file_path": "src/models/account_transaction_event.rs", "rank": 96, "score": 72281.04785583695 }, { "content": " } else {\n\n None\n\n };\n\n\n\n Self {\n\n id: t.id,\n\n transaction_id: t.transaction_id,\n\n message_hash: t.message_hash,\n\n owner_message_hash: None,\n\n account: AddressResponse {\n\n workchain_id: t.account_workchain_id,\n\n hex: Address(t.account_hex),\n\n base64url,\n\n },\n\n sender,\n\n balance_change: t.balance_change,\n\n root_address: None,\n\n transaction_direction: t.transaction_direction,\n\n transaction_status: t.transaction_status,\n\n event_status: t.event_status,\n\n multisig_transaction_id: t.multisig_transaction_id,\n\n created_at: t.created_at.timestamp_millis(),\n\n updated_at: t.updated_at.timestamp_millis(),\n\n }\n\n }\n\n}\n", "file_path": "src/models/account_transaction_event.rs", "rank": 97, "score": 72278.08872613622 }, { "content": " #[opg(\"balanceChange\", string, optional)]\n\n pub balance_change: Option<BigDecimal>,\n\n pub root_address: Option<String>,\n\n pub transaction_direction: TonTransactionDirection,\n\n pub transaction_status: TonTransactionStatus,\n\n pub event_status: TonEventStatus,\n\n pub multisig_transaction_id: Option<i64>,\n\n pub created_at: i64,\n\n pub updated_at: i64,\n\n}\n\n\n\nimpl From<TokenTransactionEventDb> for AccountTransactionEvent {\n\n fn from(t: TokenTransactionEventDb) -> Self {\n\n let account =\n\n MsgAddressInt::from_str(&format!(\"{}:{}\", t.account_workchain_id, t.account_hex))\n\n .unwrap();\n\n let base64url = Address(pack_std_smc_addr(true, &account, true).unwrap());\n\n\n\n Self {\n\n id: t.id,\n", "file_path": "src/models/account_transaction_event.rs", "rank": 98, "score": 72274.9349810456 }, { "content": "use std::str::FromStr;\n\n\n\nuse bigdecimal::BigDecimal;\n\nuse nekoton_utils::pack_std_smc_addr;\n\nuse serde::{Deserialize, Serialize};\n\nuse ton_block::MsgAddressInt;\n\nuse uuid::Uuid;\n\n\n\nuse crate::models::*;\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone, derive_more::Constructor, opg::OpgModel)]\n\n#[serde(rename_all = \"camelCase\")]\n\n#[opg(\"AccountTokenTransactionEventResponse\")]\n\npub struct AccountTransactionEvent {\n\n pub id: Uuid,\n\n pub transaction_id: Uuid,\n\n pub message_hash: String,\n\n pub owner_message_hash: Option<String>,\n\n pub account: AddressResponse,\n\n pub sender: Option<AddressResponse>,\n", "file_path": "src/models/account_transaction_event.rs", "rank": 99, "score": 72271.95521147367 } ]
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_definition_items(\n\n exactly_one(GraphQLParser::parse(\n\n Rule::executable_document,\n\n input.as_ref(),\n\n )?),\n\n &mut pc,\n\n )?;\n\n\n\n let mut operations = None;\n\n let mut fragments: HashMap<_, Positioned<FragmentDefinition>> = HashMap::new();\n\n\n\n for item in items {\n\n match item {\n\n DefinitionItem::Operation(item) => {\n\n if let Some(name) = item.node.name {\n\n let operations = operations\n\n .get_or_insert_with(|| DocumentOperations::Multiple(HashMap::new()));\n", "file_path": "parser/src/parse/executable.rs", "rank": 0, "score": 245902.74007711856 }, { "content": "#[test]\n\n#[should_panic]\n\npub fn test_both_input_output_with_same_name() {\n\n #[derive(SimpleObject, InputObject)]\n\n #[allow(dead_code)]\n\n struct MyObject {\n\n #[graphql(default = 10)]\n\n a: i32,\n\n b: bool,\n\n #[graphql(skip)]\n\n c: String,\n\n }\n\n\n\n struct Query;\n\n\n\n #[Object]\n\n impl Query {\n\n async fn obj(&self, input: MyObject) -> MyObject {\n\n input\n\n }\n\n }\n\n\n", "file_path": "tests/input_object.rs", "rank": 1, "score": 242247.88813809142 }, { "content": "#[proc_macro_derive(InputObject, attributes(graphql))]\n\npub fn derive_input_object(input: TokenStream) -> TokenStream {\n\n let object_args =\n\n match args::InputObject::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match input_object::generate(&object_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 2, "score": 238783.5140678484 }, { "content": "#[proc_macro_attribute]\n\n#[allow(non_snake_case)]\n\npub fn Object(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let object_args = match args::Object::from_list(&parse_macro_input!(args as AttributeArgs)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n let mut item_impl = parse_macro_input!(input as ItemImpl);\n\n match object::generate(&object_args, &mut item_impl) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 3, "score": 236406.73219782705 }, { "content": "pub fn is_valid_input_value(\n\n registry: &registry::Registry,\n\n type_name: &str,\n\n value: &ConstValue,\n\n path_node: QueryPathNode,\n\n) -> Option<String> {\n\n match registry::MetaTypeName::create(type_name) {\n\n registry::MetaTypeName::NonNull(type_name) => match value {\n\n ConstValue::Null => Some(valid_error(\n\n &path_node,\n\n format!(\"expected type \\\"{}\\\"\", type_name),\n\n )),\n\n _ => is_valid_input_value(registry, type_name, value, path_node),\n\n },\n\n registry::MetaTypeName::List(type_name) => match value {\n\n ConstValue::List(elems) => elems.iter().enumerate().find_map(|(idx, elem)| {\n\n is_valid_input_value(\n\n registry,\n\n type_name,\n\n elem,\n", "file_path": "src/validation/utils.rs", "rank": 4, "score": 234961.28355276294 }, { "content": "#[proc_macro_derive(SimpleObject, attributes(graphql))]\n\npub fn derive_simple_object(input: TokenStream) -> TokenStream {\n\n let object_args =\n\n match args::SimpleObject::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match simple_object::generate(&object_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 5, "score": 225240.54765652097 }, { "content": "#[proc_macro_derive(OneofObject, attributes(graphql))]\n\npub fn derive_oneof_object(input: TokenStream) -> TokenStream {\n\n let object_args =\n\n match args::OneofObject::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match oneof_object::generate(&object_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n", "file_path": "derive/src/lib.rs", "rank": 6, "score": 225240.54765652097 }, { "content": "#[proc_macro_derive(MergedObject, attributes(graphql))]\n\npub fn derive_merged_object(input: TokenStream) -> TokenStream {\n\n let object_args =\n\n match args::MergedObject::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match merged_object::generate(&object_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 7, "score": 225240.54765652097 }, { "content": "/// Convert a GraphQL response to a Tide response.\n\npub fn respond(resp: impl Into<async_graphql::BatchResponse>) -> tide::Result {\n\n let resp = resp.into();\n\n\n\n let mut response = Response::new(StatusCode::Ok);\n\n if resp.is_ok() {\n\n if let Some(cache_control) = resp.cache_control().value() {\n\n response.insert_header(headers::CACHE_CONTROL, cache_control);\n\n }\n\n }\n\n\n\n for (name, value) in resp.http_headers_iter() {\n\n if let Ok(value) = value.to_str() {\n\n response.append_header(name.as_str(), value);\n\n }\n\n }\n\n\n\n response.set_body(Body::from_json(&resp)?);\n\n Ok(response)\n\n}\n", "file_path": "integrations/tide/src/lib.rs", "rank": 8, "score": 223305.20523892168 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct MyScalar2(::std::primitive::i32);\n\n::async_graphql::scalar!(MyScalar2);\n\n\n", "file_path": "tests/hygiene.rs", "rank": 9, "score": 221496.91981436155 }, { "content": "pub fn generate(object_args: &args::InputObject) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let (impl_generics, ty_generics, where_clause) = object_args.generics.split_for_impl();\n\n let ident = &object_args.ident;\n\n let s = match &object_args.data {\n\n Data::Struct(s) => s,\n\n _ => {\n\n return Err(\n\n Error::new_spanned(ident, \"InputObject can only be applied to an struct.\").into(),\n\n )\n\n }\n\n };\n\n\n\n let mut struct_fields = Vec::new();\n\n for field in &s.fields {\n\n let vis = &field.vis;\n\n let ty = &field.ty;\n\n let ident = match &field.ident {\n\n Some(ident) => ident,\n\n None => return Err(Error::new_spanned(&ident, \"All fields must be named.\").into()),\n", "file_path": "derive/src/input_object.rs", "rank": 10, "score": 215029.66041389186 }, { "content": "#[proc_macro_attribute]\n\n#[allow(non_snake_case)]\n\npub fn ComplexObject(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let object_args =\n\n match args::ComplexObject::from_list(&parse_macro_input!(args as AttributeArgs)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n let mut item_impl = parse_macro_input!(input as ItemImpl);\n\n match complex_object::generate(&object_args, &mut item_impl) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 11, "score": 208282.4771717338 }, { "content": "/// Parse a value as an enum value.\n\n///\n\n/// This can be used to implement `InputType::parse`.\n\npub fn parse_enum<T: EnumType + InputType>(value: Value) -> InputValueResult<T> {\n\n let value = match &value {\n\n Value::Enum(s) => s,\n\n Value::String(s) => s.as_str(),\n\n _ => return Err(InputValueError::expected_type(value)),\n\n };\n\n\n\n T::items()\n\n .iter()\n\n .find(|item| item.name == value)\n\n .map(|item| item.value)\n\n .ok_or_else(|| {\n\n InputValueError::custom(format_args!(\n\n r#\"Enumeration type does not contain value \"{}\".\"#,\n\n value,\n\n ))\n\n })\n\n}\n\n\n", "file_path": "src/resolver_utils/enum.rs", "rank": 12, "score": 201113.59210673213 }, { "content": "pub fn generate(\n\n object_args: &args::Object,\n\n item_impl: &mut ItemImpl,\n\n) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let (self_ty, self_name) = get_type_path_and_name(item_impl.self_ty.as_ref())?;\n\n let (impl_generics, _, where_clause) = item_impl.generics.split_for_impl();\n\n let extends = object_args.extends;\n\n let gql_typename = if !object_args.name_type {\n\n object_args\n\n .name\n\n .as_ref()\n\n .map(|name| quote!(::std::borrow::Cow::Borrowed(#name)))\n\n .unwrap_or_else(|| {\n\n let name = RenameTarget::Type.rename(self_name.clone());\n\n quote!(::std::borrow::Cow::Borrowed(#name))\n\n })\n\n } else {\n\n quote!(<Self as #crate_name::TypeName>::type_name())\n\n };\n", "file_path": "derive/src/object.rs", "rank": 13, "score": 200620.24331423338 }, { "content": "/// Parse a GraphQL schema document.\n\n///\n\n/// # Errors\n\n///\n\n/// Fails if the schema is not a valid GraphQL document.\n\npub fn parse_schema<T: AsRef<str>>(input: T) -> Result<ServiceDocument> {\n\n let mut pc = PositionCalculator::new(input.as_ref());\n\n Ok(parse_service_document(\n\n exactly_one(GraphQLParser::parse(\n\n Rule::service_document,\n\n input.as_ref(),\n\n )?),\n\n &mut pc,\n\n )?)\n\n}\n\n\n", "file_path": "parser/src/parse/service.rs", "rank": 14, "score": 197908.83662791637 }, { "content": "pub fn generate(\n\n object_args: &args::ComplexObject,\n\n item_impl: &mut ItemImpl,\n\n) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let (self_ty, _) = get_type_path_and_name(item_impl.self_ty.as_ref())?;\n\n let generics = &item_impl.generics;\n\n let where_clause = &item_impl.generics.where_clause;\n\n\n\n let mut resolvers = Vec::new();\n\n let mut schema_fields = Vec::new();\n\n\n\n // Computation of the derivated fields\n\n let mut derived_impls = vec![];\n\n for item in &mut item_impl.items {\n\n if let ImplItem::Method(method) = item {\n\n let method_args: args::ComplexObjectField =\n\n parse_graphql_attrs(&method.attrs)?.unwrap_or_default();\n\n\n\n for derived in method_args.derived {\n", "file_path": "derive/src/complex_object.rs", "rank": 15, "score": 195922.7337381948 }, { "content": "pub fn url<T: AsRef<str> + InputType>(value: &T) -> Result<(), InputValueError<T>> {\n\n if let Ok(true) = http::uri::Uri::from_str(value.as_ref())\n\n .map(|uri| uri.scheme().is_some() && uri.authority().is_some())\n\n {\n\n Ok(())\n\n } else {\n\n Err(\"invalid url\".into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_url() {\n\n assert!(url(&\"http\".to_string()).is_err());\n\n assert!(url(&\"https://google.com\".to_string()).is_ok());\n\n assert!(url(&\"http://localhost:80\".to_string()).is_ok());\n\n assert!(url(&\"ftp://localhost:80\".to_string()).is_ok());\n\n }\n\n}\n", "file_path": "src/validators/url.rs", "rank": 16, "score": 192911.83911869163 }, { "content": "pub fn ip<T: AsRef<str> + InputType>(value: &T) -> Result<(), InputValueError<T>> {\n\n if IpAddr::from_str(value.as_ref()).is_ok() {\n\n Ok(())\n\n } else {\n\n Err(\"invalid ip\".into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_ip() {\n\n assert!(ip(&\"1.1.1.1\".to_string()).is_ok());\n\n assert!(ip(&\"255.0.0.0\".to_string()).is_ok());\n\n assert!(ip(&\"256.1.1.1\".to_string()).is_err());\n\n assert!(ip(&\"fe80::223:6cff:fe8a:2e8a\".to_string()).is_ok());\n\n assert!(ip(&\"::ffff:254.42.16.14\".to_string()).is_ok());\n\n assert!(ip(&\"2a02::223:6cff :fe8a:2e8a\".to_string()).is_err());\n\n }\n\n}\n", "file_path": "src/validators/ip.rs", "rank": 17, "score": 192911.83911869163 }, { "content": "pub fn email<T: AsRef<str> + InputType>(value: &T) -> Result<(), InputValueError<T>> {\n\n if is_valid_email(value.as_ref()) {\n\n Ok(())\n\n } else {\n\n Err(\"invalid email\".into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_email() {\n\n assert!(email(&\"[email protected]\".to_string()).is_ok());\n\n assert!(email(&\"[email protected]\".to_string()).is_ok());\n\n assert!(email(&\"[email protected]\".to_string()).is_ok());\n\n assert!(email(&\"[email protected]\".to_string()).is_ok());\n\n\n\n assert!(email(&\"plainaddress\".to_string()).is_err());\n\n assert!(email(&\"@example.com\".to_string()).is_err());\n\n assert!(email(&\"email.example.com\".to_string()).is_err());\n\n }\n\n}\n", "file_path": "src/validators/email.rs", "rank": 18, "score": 192911.83911869163 }, { "content": "#[proc_macro_derive(Interface, attributes(graphql))]\n\npub fn derive_interface(input: TokenStream) -> TokenStream {\n\n let interface_args =\n\n match args::Interface::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(interface_args) => interface_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match interface::generate(&interface_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 19, "score": 191765.74866573184 }, { "content": "#[proc_macro_derive(NewType, attributes(graphql))]\n\npub fn derive_newtype(input: TokenStream) -> TokenStream {\n\n let newtype_args =\n\n match args::NewType::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(newtype_args) => newtype_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match newtype::generate(&newtype_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 20, "score": 191765.74866573184 }, { "content": "#[proc_macro_derive(Enum, attributes(graphql))]\n\npub fn derive_enum(input: TokenStream) -> TokenStream {\n\n let enum_args = match args::Enum::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(enum_args) => enum_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match r#enum::generate(&enum_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 21, "score": 191765.74866573184 }, { "content": "#[proc_macro_derive(Description, attributes(graphql))]\n\npub fn derive_description(input: TokenStream) -> TokenStream {\n\n let desc_args =\n\n match args::Description::from_derive_input(&parse_macro_input!(input as DeriveInput)) {\n\n Ok(desc_args) => desc_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match description::generate(&desc_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 22, "score": 191765.74866573184 }, { "content": "#[proc_macro_derive(Union, attributes(graphql))]\n\npub fn derive_union(input: TokenStream) -> TokenStream {\n\n let union_args = match args::Union::from_derive_input(&parse_macro_input!(input as DeriveInput))\n\n {\n\n Ok(union_args) => union_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match union::generate(&union_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 23, "score": 191765.74866573184 }, { "content": "#[proc_macro_derive(MergedSubscription, attributes(graphql))]\n\npub fn derive_merged_subscription(input: TokenStream) -> TokenStream {\n\n let object_args = match args::MergedSubscription::from_derive_input(&parse_macro_input!(\n\n input as DeriveInput\n\n )) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n match merged_subscription::generate(&object_args) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 24, "score": 188535.48213611724 }, { "content": "pub fn remove_graphql_attrs(attrs: &mut Vec<Attribute>) {\n\n if let Some((idx, _)) = attrs\n\n .iter()\n\n .enumerate()\n\n .find(|(_, a)| a.path.is_ident(\"graphql\"))\n\n {\n\n attrs.remove(idx);\n\n }\n\n}\n\n\n", "file_path": "derive/src/utils.rs", "rank": 25, "score": 187006.24602490797 }, { "content": "pub fn multiple_of<T, N>(value: &T, n: N) -> Result<(), InputValueError<T>>\n\nwhere\n\n T: AsPrimitive<N> + InputType,\n\n N: Rem<Output = N> + Zero + Display + Copy + PartialEq + 'static,\n\n{\n\n let value = value.as_();\n\n if !value.is_zero() && value % n == N::zero() {\n\n Ok(())\n\n } else {\n\n Err(format!(\"the value must be a multiple of {}.\", n).into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_multiple_of() {\n\n assert!(multiple_of(&5, 3).is_err());\n\n assert!(multiple_of(&6, 3).is_ok());\n\n assert!(multiple_of(&0, 3).is_err());\n\n }\n\n}\n", "file_path": "src/validators/multiple_of.rs", "rank": 26, "score": 185986.20703147195 }, { "content": "pub fn minimum<T, N>(value: &T, n: N) -> Result<(), InputValueError<T>>\n\nwhere\n\n T: AsPrimitive<N> + InputType,\n\n N: PartialOrd + Display + Copy + 'static,\n\n{\n\n if value.as_() >= n {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the value is {}, must be greater than or equal to {}\",\n\n value.as_(),\n\n n\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_minimum() {\n\n assert!(minimum(&99, 100).is_err());\n\n assert!(minimum(&100, 100).is_ok());\n\n assert!(minimum(&101, 100).is_ok());\n\n }\n\n}\n", "file_path": "src/validators/minimum.rs", "rank": 27, "score": 185986.20703147195 }, { "content": "pub fn maximum<T, N>(value: &T, n: N) -> Result<(), InputValueError<T>>\n\nwhere\n\n T: AsPrimitive<N> + InputType,\n\n N: PartialOrd + Display + Copy + 'static,\n\n{\n\n if value.as_() <= n {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the value is {}, must be less than or equal to {}\",\n\n value.as_(),\n\n n\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_maximum() {\n\n assert!(maximum(&99, 100).is_ok());\n\n assert!(maximum(&100, 100).is_ok());\n\n assert!(maximum(&101, 100).is_err());\n\n }\n\n}\n", "file_path": "src/validators/maximum.rs", "rank": 28, "score": 185986.20703147195 }, { "content": "struct ObjB<'a>(PhantomData<&'a i32>);\n\n\n\n#[Object]\n\n#[allow(unreachable_code)]\n\nimpl<'a> ObjB<'a> {\n\n async fn value(&self) -> &'a i32 {\n\n todo!()\n\n }\n\n}\n\n\n", "file_path": "tests/lifetime.rs", "rank": 29, "score": 183825.10228905018 }, { "content": "fn write_list<T: Display>(list: impl IntoIterator<Item = T>, f: &mut Formatter<'_>) -> fmt::Result {\n\n f.write_char('[')?;\n\n let mut iter = list.into_iter();\n\n if let Some(item) = iter.next() {\n\n item.fmt(f)?;\n\n }\n\n for item in iter {\n\n f.write_char(',')?;\n\n item.fmt(f)?;\n\n }\n\n f.write_char(']')\n\n}\n\n\n", "file_path": "value/src/lib.rs", "rank": 30, "score": 182769.70710262834 }, { "content": "fn build_schema() -> Schema<Query, EmptyMutation, EmptySubscription> {\n\n Schema::build(Query, EmptyMutation, EmptySubscription)\n\n .register_output_type::<ImplicitInterface>()\n\n .register_output_type::<InvisibleInterface>()\n\n .register_output_type::<UnreferencedInterface>()\n\n .finish()\n\n}\n\n\n\n#[tokio::test]\n\npub async fn test_interface_exports_interfaces_on_object_type() {\n\n #[derive(Deserialize)]\n\n struct QueryResponse {\n\n #[serde(rename = \"__type\")]\n\n ty: TypeResponse,\n\n }\n\n\n\n #[derive(Deserialize)]\n\n struct TypeResponse {\n\n name: String,\n\n kind: String,\n", "file_path": "tests/interface_exporting.rs", "rank": 31, "score": 179856.6655416591 }, { "content": "#[derive(async_graphql::InputObject)]\n\nstruct MyInputObject {\n\n /// Foo.\n\n foo: ::std::primitive::i32,\n\n #[graphql(default)]\n\n bar: ::std::string::String,\n\n}\n\n\n\n#[derive(async_graphql::Interface)]\n\n#[graphql(\n\n field(name = \"value\", type = \"::std::primitive::i32\"),\n\n field(name = \"other_value\", type = \"&::std::primitive::i16\")\n\n)]\n", "file_path": "tests/hygiene.rs", "rank": 32, "score": 179181.52274744658 }, { "content": "pub fn referenced_variables(value: &Value) -> Vec<&str> {\n\n let mut vars = Vec::new();\n\n referenced_variables_to_vec(value, &mut vars);\n\n vars\n\n}\n\n\n", "file_path": "src/validation/utils.rs", "rank": 33, "score": 177975.19760850666 }, { "content": "#[proc_macro_attribute]\n\n#[allow(non_snake_case)]\n\npub fn Directive(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let directive_args =\n\n match args::Directive::from_list(&parse_macro_input!(args as AttributeArgs)) {\n\n Ok(directive_args) => directive_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n let mut item_fn = parse_macro_input!(input as ItemFn);\n\n match directive::generate(&directive_args, &mut item_fn) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 34, "score": 176435.90443455498 }, { "content": "#[proc_macro_attribute]\n\n#[allow(non_snake_case)]\n\npub fn Subscription(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let object_args =\n\n match args::Subscription::from_list(&parse_macro_input!(args as AttributeArgs)) {\n\n Ok(object_args) => object_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n let mut item_impl = parse_macro_input!(input as ItemImpl);\n\n match subscription::generate(&object_args, &mut item_impl) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 35, "score": 176435.90443455498 }, { "content": "#[proc_macro_attribute]\n\n#[allow(non_snake_case)]\n\npub fn Scalar(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let scalar_args = match args::Scalar::from_list(&parse_macro_input!(args as AttributeArgs)) {\n\n Ok(scalar_args) => scalar_args,\n\n Err(err) => return TokenStream::from(err.write_errors()),\n\n };\n\n let mut item_impl = parse_macro_input!(input as ItemImpl);\n\n match scalar::generate(&scalar_args, &mut item_impl) {\n\n Ok(expanded) => expanded,\n\n Err(err) => err.write_errors().into(),\n\n }\n\n}\n\n\n", "file_path": "derive/src/lib.rs", "rank": 36, "score": 176435.90443455498 }, { "content": "fn export_input_value(input_value: &MetaInputValue) -> String {\n\n if let Some(default_value) = &input_value.default_value {\n\n format!(\n\n \"{}: {} = {}\",\n\n input_value.name, input_value.ty, default_value\n\n )\n\n } else {\n\n format!(\"{}: {}\", input_value.name, input_value.ty)\n\n }\n\n}\n\n\n", "file_path": "src/registry/export_sdl.rs", "rank": 37, "score": 175372.48389818775 }, { "content": "#[derive(SimpleObject)]\n\n#[graphql(internal, name = \"_Service\")]\n\nstruct Service {\n\n sdl: Option<String>,\n\n}\n\n\n\npub(crate) struct QueryRoot<T> {\n\n pub(crate) inner: T,\n\n}\n\n\n\n#[async_trait::async_trait]\n\nimpl<T: ObjectType> ContainerType for QueryRoot<T> {\n\n async fn resolve_field(&self, ctx: &Context<'_>) -> ServerResult<Option<Value>> {\n\n if matches!(\n\n ctx.schema_env.registry.introspection_mode,\n\n IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly\n\n ) && matches!(\n\n ctx.query_env.introspection_mode,\n\n IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly,\n\n ) {\n\n if ctx.item.node.name.node == \"__schema\" {\n\n let ctx_obj = ctx.with_selection_set(&ctx.item.node.selection_set);\n", "file_path": "src/types/query_root.rs", "rank": 38, "score": 174922.7090638031 }, { "content": "#[derive(SimpleObject)]\n\nstruct ObjectB {\n\n id: i32,\n\n title: String,\n\n}\n\n\n", "file_path": "tests/interface_exporting.rs", "rank": 39, "score": 174344.3068317661 }, { "content": "/// Convert the enum value into a GraphQL value.\n\n///\n\n/// This can be used to implement `InputType::to_value` or\n\n/// `OutputType::resolve`.\n\npub fn enum_value<T: EnumType>(value: T) -> Value {\n\n let item = T::items().iter().find(|item| item.value == value).unwrap();\n\n Value::Enum(Name::new(item.name))\n\n}\n", "file_path": "src/resolver_utils/enum.rs", "rank": 40, "score": 172914.49856770865 }, { "content": "/// GraphQL request filter\n\n///\n\n/// It outputs a tuple containing the `async_graphql::Schema` and\n\n/// `async_graphql::Request`.\n\n///\n\n/// # Examples\n\n///\n\n/// *[Full Example](<https://github.com/async-graphql/examples/blob/master/warp/starwars/src/main.rs>)*\n\n///\n\n/// ```no_run\n\n/// use std::convert::Infallible;\n\n///\n\n/// use async_graphql::*;\n\n/// use async_graphql_warp::*;\n\n/// use warp::Filter;\n\n///\n\n/// struct QueryRoot;\n\n///\n\n/// #[Object]\n\n/// impl QueryRoot {\n\n/// async fn value(&self, ctx: &Context<'_>) -> i32 {\n\n/// unimplemented!()\n\n/// }\n\n/// }\n\n///\n\n/// type MySchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;\n\n///\n\n/// # tokio::runtime::Runtime::new().unwrap().block_on(async {\n\n/// let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);\n\n/// let filter = async_graphql_warp::graphql(schema).and_then(\n\n/// |(schema, request): (MySchema, async_graphql::Request)| async move {\n\n/// Ok::<_, Infallible>(async_graphql_warp::GraphQLResponse::from(\n\n/// schema.execute(request).await,\n\n/// ))\n\n/// },\n\n/// );\n\n/// warp::serve(filter).run(([0, 0, 0, 0], 8000)).await;\n\n/// # });\n\n/// ```\n\npub fn graphql<Query, Mutation, Subscription>(\n\n schema: Schema<Query, Mutation, Subscription>,\n\n) -> impl Filter<\n\n Extract = ((\n\n Schema<Query, Mutation, Subscription>,\n\n async_graphql::Request,\n\n ),),\n\n Error = Rejection,\n\n> + Clone\n\nwhere\n\n Query: ObjectType + 'static,\n\n Mutation: ObjectType + 'static,\n\n Subscription: SubscriptionType + 'static,\n\n{\n\n graphql_opts(schema, Default::default())\n\n}\n\n\n", "file_path": "integrations/warp/src/request.rs", "rank": 41, "score": 171727.15087239313 }, { "content": "/// Create a new GraphQL endpoint with the schema.\n\n///\n\n/// Default multipart options are used and batch operations are supported.\n\npub fn graphql<Query, Mutation, Subscription>(\n\n schema: Schema<Query, Mutation, Subscription>,\n\n) -> GraphQLEndpoint<Query, Mutation, Subscription> {\n\n GraphQLEndpoint {\n\n schema,\n\n opts: MultipartOptions::default(),\n\n batch: true,\n\n }\n\n}\n\n\n\n/// A GraphQL endpoint.\n\n///\n\n/// This is created with the [`endpoint`](fn.endpoint.html) function.\n\n#[non_exhaustive]\n\npub struct GraphQLEndpoint<Query, Mutation, Subscription> {\n\n /// The schema of the endpoint.\n\n pub schema: Schema<Query, Mutation, Subscription>,\n\n /// The multipart options of the endpoint.\n\n pub opts: MultipartOptions,\n\n /// Whether to support batch requests in the endpoint.\n", "file_path": "integrations/tide/src/lib.rs", "rank": 42, "score": 171684.57224691054 }, { "content": "/// GraphQL subscription filter\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use std::time::Duration;\n\n///\n\n/// use async_graphql::*;\n\n/// use async_graphql_warp::*;\n\n/// use futures_util::stream::{Stream, StreamExt};\n\n/// use warp::Filter;\n\n///\n\n/// struct QueryRoot;\n\n///\n\n/// #[Object]\n\n/// impl QueryRoot {\n\n/// async fn value(&self) -> i32 {\n\n/// // A GraphQL Object type must define one or more fields.\n\n/// 100\n\n/// }\n\n/// }\n\n///\n\n/// struct SubscriptionRoot;\n\n///\n\n/// #[Subscription]\n\n/// impl SubscriptionRoot {\n\n/// async fn tick(&self) -> impl Stream<Item = String> {\n\n/// async_stream::stream! {\n\n/// let mut interval = tokio::time::interval(Duration::from_secs(1));\n\n/// loop {\n\n/// let n = interval.tick().await;\n\n/// yield format!(\"{}\", n.elapsed().as_secs_f32());\n\n/// }\n\n/// }\n\n/// }\n\n/// }\n\n///\n\n/// # tokio::runtime::Runtime::new().unwrap().block_on(async {\n\n/// let schema = Schema::new(QueryRoot, EmptyMutation, SubscriptionRoot);\n\n/// let filter =\n\n/// async_graphql_warp::graphql_subscription(schema).or(warp::any().map(|| \"Hello, World!\"));\n\n/// warp::serve(filter).run(([0, 0, 0, 0], 8000)).await;\n\n/// # });\n\n/// ```\n\npub fn graphql_subscription<Query, Mutation, Subscription>(\n\n schema: Schema<Query, Mutation, Subscription>,\n\n) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone\n\nwhere\n\n Query: ObjectType + Sync + Send + 'static,\n\n Mutation: ObjectType + Sync + Send + 'static,\n\n Subscription: SubscriptionType + Send + Sync + 'static,\n\n{\n\n warp::ws()\n\n .and(graphql_protocol())\n\n .map(move |ws: ws::Ws, protocol| {\n\n let schema = schema.clone();\n\n\n\n let reply = ws.on_upgrade(move |socket| {\n\n GraphQLWebSocket::new(socket, schema, protocol)\n\n .on_connection_init(default_on_connection_init)\n\n .serve()\n\n });\n\n\n\n warp::reply::with_header(\n\n reply,\n\n \"Sec-WebSocket-Protocol\",\n\n protocol.sec_websocket_protocol(),\n\n )\n\n })\n\n}\n\n\n", "file_path": "integrations/warp/src/subscription.rs", "rank": 43, "score": 168096.0743838109 }, { "content": "/// Similar to graphql, but you can set the options\n\n/// `async_graphql::MultipartOptions`.\n\npub fn graphql_opts<Query, Mutation, Subscription>(\n\n schema: Schema<Query, Mutation, Subscription>,\n\n opts: MultipartOptions,\n\n) -> impl Filter<Extract = ((Schema<Query, Mutation, Subscription>, Request),), Error = Rejection> + Clone\n\nwhere\n\n Query: ObjectType + 'static,\n\n Mutation: ObjectType + 'static,\n\n Subscription: SubscriptionType + 'static,\n\n{\n\n graphql_batch_opts(schema, opts).and_then(|(schema, batch): (_, BatchRequest)| async move {\n\n <Result<_, Rejection>>::Ok((\n\n schema,\n\n batch\n\n .into_single()\n\n .map_err(|e| warp::reject::custom(GraphQLBadRequest(e)))?,\n\n ))\n\n })\n\n}\n\n\n\n/// Reply for `async_graphql::Request`.\n", "file_path": "integrations/warp/src/request.rs", "rank": 44, "score": 168040.1903677762 }, { "content": "pub fn extract_input_args<T: FromMeta + Default>(\n\n crate_name: &proc_macro2::TokenStream,\n\n method: &mut ImplItemMethod,\n\n) -> GeneratorResult<Vec<(PatIdent, Type, T)>> {\n\n let mut args = Vec::new();\n\n let mut create_ctx = true;\n\n\n\n if method.sig.inputs.is_empty() {\n\n return Err(Error::new_spanned(\n\n &method.sig,\n\n \"The self receiver must be the first parameter.\",\n\n )\n\n .into());\n\n }\n\n\n\n for (idx, arg) in method.sig.inputs.iter_mut().enumerate() {\n\n if let FnArg::Receiver(receiver) = arg {\n\n if idx != 0 {\n\n return Err(Error::new_spanned(\n\n receiver,\n", "file_path": "derive/src/utils.rs", "rank": 45, "score": 167905.67188306115 }, { "content": "/// A GraphQL input object.\n\npub trait InputObjectType: InputType {}\n\n\n", "file_path": "src/base.rs", "rank": 46, "score": 167775.9450177314 }, { "content": "#[inline]\n\npub fn from_value<T: DeserializeOwned>(value: ConstValue) -> Result<T, DeserializerError> {\n\n T::deserialize(value)\n\n}\n", "file_path": "value/src/deserializer.rs", "rank": 47, "score": 167508.9077725109 }, { "content": "pub fn generate(object_args: &args::OneofObject) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let (impl_generics, ty_generics, where_clause) = object_args.generics.split_for_impl();\n\n let ident = &object_args.ident;\n\n let desc = get_rustdoc(&object_args.attrs)?\n\n .map(|s| quote! { ::std::option::Option::Some(#s) })\n\n .unwrap_or_else(|| quote! {::std::option::Option::None});\n\n let gql_typename = object_args\n\n .name\n\n .clone()\n\n .unwrap_or_else(|| RenameTarget::Type.rename(ident.to_string()));\n\n let s = match &object_args.data {\n\n Data::Enum(s) => s,\n\n _ => {\n\n return Err(\n\n Error::new_spanned(ident, \"InputObject can only be applied to an enum.\").into(),\n\n )\n\n }\n\n };\n\n\n", "file_path": "derive/src/oneof_object.rs", "rank": 48, "score": 167207.7941338936 }, { "content": "pub fn generate(object_args: &args::SimpleObject) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let ident = &object_args.ident;\n\n let (impl_generics, ty_generics, where_clause) = object_args.generics.split_for_impl();\n\n let extends = object_args.extends;\n\n let gql_typename = if !object_args.name_type {\n\n object_args\n\n .name\n\n .as_ref()\n\n .map(|name| quote!(::std::borrow::Cow::Borrowed(#name)))\n\n .unwrap_or_else(|| {\n\n let name = RenameTarget::Type.rename(ident.to_string());\n\n quote!(::std::borrow::Cow::Borrowed(#name))\n\n })\n\n } else {\n\n quote!(<Self as #crate_name::TypeName>::type_name())\n\n };\n\n\n\n let desc = get_rustdoc(&object_args.attrs)?\n\n .map(|s| quote! { ::std::option::Option::Some(#s) })\n", "file_path": "derive/src/simple_object.rs", "rank": 49, "score": 167207.7941338936 }, { "content": "pub fn generate(object_args: &args::MergedObject) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let ident = &object_args.ident;\n\n let (impl_generics, ty_generics, where_clause) = object_args.generics.split_for_impl();\n\n let extends = object_args.extends;\n\n let gql_typename = object_args\n\n .name\n\n .clone()\n\n .unwrap_or_else(|| RenameTarget::Type.rename(ident.to_string()));\n\n\n\n let desc = get_rustdoc(&object_args.attrs)?\n\n .map(|s| quote! { ::std::option::Option::Some(#s) })\n\n .unwrap_or_else(|| quote! {::std::option::Option::None});\n\n\n\n let s = match &object_args.data {\n\n Data::Struct(e) => e,\n\n _ => {\n\n return Err(\n\n Error::new_spanned(ident, \"MergedObject can only be applied to an struct.\").into(),\n\n )\n", "file_path": "derive/src/merged_object.rs", "rank": 50, "score": 167207.7941338936 }, { "content": "#[test]\n\n#[should_panic]\n\nfn object() {\n\n mod t {\n\n use async_graphql::*;\n\n\n\n pub struct MyObj;\n\n\n\n #[Object]\n\n impl MyObj {\n\n async fn a(&self) -> i32 {\n\n 1\n\n }\n\n }\n\n }\n\n\n\n struct MyObj;\n\n\n\n #[Object]\n\n impl MyObj {\n\n async fn b(&self) -> i32 {\n\n 1\n", "file_path": "tests/name_conflict.rs", "rank": 51, "score": 165634.94939135853 }, { "content": "#[inline]\n\npub fn to_value<T: ser::Serialize>(value: T) -> Result<ConstValue, SerializerError> {\n\n value.serialize(Serializer)\n\n}\n\n\n", "file_path": "value/src/serializer.rs", "rank": 52, "score": 165536.43207947447 }, { "content": "pub fn regex<T: AsRef<str> + InputType>(\n\n value: &T,\n\n regex: &'static str,\n\n) -> Result<(), InputValueError<T>> {\n\n if let Ok(true) = Regex::new(regex).map(|re| re.is_match(value.as_ref())) {\n\n Ok(())\n\n } else {\n\n Err(format_args!(\"value doesn't match expected format '{}'\", regex).into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_url() {\n\n assert!(regex(&\"123\".to_string(), \"^[0-9]+$\").is_ok());\n\n assert!(regex(&\"12a3\".to_string(), \"^[0-9]+$\").is_err());\n\n }\n\n}\n", "file_path": "src/validators/regex.rs", "rank": 53, "score": 164793.26983011022 }, { "content": "/// GraphQL batch request filter\n\n///\n\n/// It outputs a tuple containing the `async_graphql::Schema` and\n\n/// `async_graphql::BatchRequest`.\n\npub fn graphql_batch<Query, Mutation, Subscription>(\n\n schema: Schema<Query, Mutation, Subscription>,\n\n) -> impl Filter<Extract = ((Schema<Query, Mutation, Subscription>, BatchRequest),), Error = Rejection>\n\n + Clone\n\nwhere\n\n Query: ObjectType + 'static,\n\n Mutation: ObjectType + 'static,\n\n Subscription: SubscriptionType + 'static,\n\n{\n\n graphql_batch_opts(schema, Default::default())\n\n}\n\n\n", "file_path": "integrations/warp/src/batch_request.rs", "rank": 54, "score": 164618.38828620623 }, { "content": "fn insert_value(target: &mut IndexMap<Name, Value>, name: Name, value: Value) {\n\n if let Some(prev_value) = target.get_mut(&name) {\n\n if let Value::Object(target_map) = prev_value {\n\n if let Value::Object(obj) = value {\n\n for (key, value) in obj.into_iter() {\n\n insert_value(target_map, key, value);\n\n }\n\n }\n\n } else if let Value::List(target_list) = prev_value {\n\n if let Value::List(list) = value {\n\n for (idx, value) in list.into_iter().enumerate() {\n\n if let Some(Value::Object(target_map)) = target_list.get_mut(idx) {\n\n if let Value::Object(obj) = value {\n\n for (key, value) in obj.into_iter() {\n\n insert_value(target_map, key, value);\n\n }\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/resolver_utils/container.rs", "rank": 55, "score": 164255.02521227687 }, { "content": "/// A GraphQL oneof input object.\n\npub trait OneofObjectType: InputObjectType {}\n\n\n\n#[async_trait::async_trait]\n\nimpl<T: OutputType + ?Sized> OutputType for Box<T> {\n\n fn type_name() -> Cow<'static, str> {\n\n T::type_name()\n\n }\n\n\n\n fn create_type_info(registry: &mut Registry) -> String {\n\n T::create_type_info(registry)\n\n }\n\n\n\n #[allow(clippy::trivially_copy_pass_by_ref)]\n\n async fn resolve(\n\n &self,\n\n ctx: &ContextSelectionSet<'_>,\n\n field: &Positioned<Field>,\n\n ) -> ServerResult<Value> {\n\n T::resolve(&**self, ctx, field).await\n\n }\n", "file_path": "src/base.rs", "rank": 56, "score": 163958.5569731744 }, { "content": "fn referenced_variables_to_vec<'a>(value: &'a Value, vars: &mut Vec<&'a str>) {\n\n match value {\n\n Value::Variable(name) => {\n\n vars.push(name);\n\n }\n\n Value::List(values) => values\n\n .iter()\n\n .for_each(|value| referenced_variables_to_vec(value, vars)),\n\n Value::Object(obj) => obj\n\n .values()\n\n .for_each(|value| referenced_variables_to_vec(value, vars)),\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "src/validation/utils.rs", "rank": 57, "score": 163295.96370994044 }, { "content": "#[derive(InputObject)]\n\n#[graphql(internal)]\n\nstruct TestInput {\n\n id: i32,\n\n name: String,\n\n}\n\n\n\nimpl Default for TestInput {\n\n fn default() -> Self {\n\n Self {\n\n id: 423,\n\n name: \"foo\".to_string(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/validation/test_harness.rs", "rank": 58, "score": 162615.9813872973 }, { "content": "/// Similar to graphql_batch, but you can set the options with\n\n/// :`async_graphql::MultipartOptions`.\n\npub fn graphql_batch_opts<Query, Mutation, Subscription>(\n\n schema: Schema<Query, Mutation, Subscription>,\n\n opts: MultipartOptions,\n\n) -> impl Filter<Extract = ((Schema<Query, Mutation, Subscription>, BatchRequest),), Error = Rejection>\n\n + Clone\n\nwhere\n\n Query: ObjectType + 'static,\n\n Mutation: ObjectType + 'static,\n\n Subscription: SubscriptionType + 'static,\n\n{\n\n warp::any()\n\n .and(warp::get().and(warp::query()).map(BatchRequest::Single))\n\n .or(warp::post()\n\n .and(warp::header::optional::<String>(\"content-type\"))\n\n .and(warp::body::stream())\n\n .and_then(move |content_type, body| async move {\n\n async_graphql::http::receive_batch_body(\n\n content_type,\n\n TryStreamExt::map_err(body, |e| io::Error::new(ErrorKind::Other, e))\n\n .map_ok(|mut buf| {\n", "file_path": "integrations/warp/src/batch_request.rs", "rank": 59, "score": 161378.73805647297 }, { "content": "/// Create a `Filter` that parse [WebSocketProtocols] from\n\n/// `sec-websocket-protocol` header.\n\npub fn graphql_protocol() -> impl Filter<Extract = (WebSocketProtocols,), Error = Rejection> + Clone\n\n{\n\n warp::header::optional::<String>(\"sec-websocket-protocol\").map(|protocols: Option<String>| {\n\n protocols\n\n .and_then(|protocols| {\n\n protocols\n\n .split(',')\n\n .find_map(|p| WebSocketProtocols::from_str(p.trim()).ok())\n\n })\n\n .unwrap_or(WebSocketProtocols::SubscriptionsTransportWS)\n\n })\n\n}\n\n\n", "file_path": "integrations/warp/src/subscription.rs", "rank": 60, "score": 161359.5008802964 }, { "content": "pub fn make_suggestion<I, A>(prefix: &str, options: I, input: &str) -> Option<String>\n\nwhere\n\n I: IntoIterator<Item = A>,\n\n A: AsRef<str>,\n\n{\n\n let mut selected = Vec::new();\n\n let mut distances = HashMap::new();\n\n\n\n for opt in options {\n\n let opt = opt.as_ref().to_string();\n\n let distance = levenshtein_distance(input, &opt);\n\n let threshold = (input.len() / 2).max((opt.len() / 2).max(1));\n\n if distance < threshold {\n\n selected.push(opt.clone());\n\n distances.insert(opt, distance);\n\n }\n\n }\n\n\n\n if selected.is_empty() {\n\n return None;\n", "file_path": "src/validation/suggestion.rs", "rank": 61, "score": 160972.72269188293 }, { "content": "#[derive(Clone, Debug)]\n\nstruct TestScalar(i32);\n\n\n\n/// Test scalar\n\n#[Scalar]\n\nimpl ScalarType for TestScalar {\n\n fn parse(_value: Value) -> InputValueResult<Self> {\n\n Ok(TestScalar(42))\n\n }\n\n\n\n fn is_valid(_value: &Value) -> bool {\n\n true\n\n }\n\n\n\n fn to_value(&self) -> Value {\n\n Value::Number(self.0.into())\n\n }\n\n}\n\n\n\n/// Is SimpleObject\n\n/// and some more ```lorem ipsum```\n", "file_path": "tests/introspection.rs", "rank": 62, "score": 159895.75680089556 }, { "content": "fn remove_skipped_selection(selection_set: &mut SelectionSet, variables: &Variables) {\n\n fn is_skipped(directives: &[Positioned<Directive>], variables: &Variables) -> bool {\n\n for directive in directives {\n\n let include = match &*directive.node.name.node {\n\n \"skip\" => false,\n\n \"include\" => true,\n\n _ => continue,\n\n };\n\n\n\n if let Some(condition_input) = directive.node.get_argument(\"if\") {\n\n let value = condition_input\n\n .node\n\n .clone()\n\n .into_const_with(|name| variables.get(&name).cloned().ok_or(()))\n\n .unwrap_or_default();\n\n let value: bool = InputType::parse(Some(value)).unwrap_or_default();\n\n if include != value {\n\n return true;\n\n }\n\n }\n", "file_path": "src/schema.rs", "rank": 63, "score": 159625.25502676686 }, { "content": "fn write_quoted(s: &str, f: &mut Formatter<'_>) -> fmt::Result {\n\n f.write_char('\"')?;\n\n for c in s.chars() {\n\n match c {\n\n '\\r' => f.write_str(\"\\\\r\"),\n\n '\\n' => f.write_str(\"\\\\n\"),\n\n '\\t' => f.write_str(\"\\\\t\"),\n\n '\"' => f.write_str(\"\\\\\\\"\"),\n\n '\\\\' => f.write_str(\"\\\\\\\\\"),\n\n c if c.is_control() => write!(f, \"\\\\u{:04}\", c as u32),\n\n c => f.write_char(c),\n\n }?\n\n }\n\n f.write_char('\"')\n\n}\n\n\n", "file_path": "value/src/lib.rs", "rank": 64, "score": 158481.26346617177 }, { "content": "fn parse_input_value_definition(\n\n pair: Pair<Rule>,\n\n pc: &mut PositionCalculator,\n\n) -> Result<Positioned<InputValueDefinition>> {\n\n debug_assert_eq!(pair.as_rule(), Rule::input_value_definition);\n\n\n\n let pos = pc.step(&pair);\n\n let mut pairs = pair.into_inner();\n\n\n\n let description = parse_if_rule(&mut pairs, Rule::string, |pair| parse_string(pair, pc))?;\n\n let name = parse_name(pairs.next().unwrap(), pc)?;\n\n let ty = parse_type(pairs.next().unwrap(), pc)?;\n\n let default_value = parse_if_rule(&mut pairs, Rule::default_value, |pair| {\n\n parse_default_value(pair, pc)\n\n })?;\n\n let directives = parse_opt_const_directives(&mut pairs, pc)?;\n\n\n\n Ok(Positioned::new(\n\n InputValueDefinition {\n\n description,\n", "file_path": "parser/src/parse/service.rs", "rank": 65, "score": 158178.19544953405 }, { "content": "pub fn max_length<T: AsRef<str> + InputType>(\n\n value: &T,\n\n len: usize,\n\n) -> Result<(), InputValueError<T>> {\n\n if value.as_ref().len() <= len {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the string length is {}, must be less than or equal to {}\",\n\n value.as_ref().len(),\n\n len\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_max_length() {\n\n assert!(max_length(&\"ab\".to_string(), 3).is_ok());\n\n assert!(max_length(&\"abc\".to_string(), 3).is_ok());\n\n assert!(max_length(&\"abcd\".to_string(), 3).is_err());\n\n }\n\n}\n", "file_path": "src/validators/max_length.rs", "rank": 66, "score": 158139.17663076735 }, { "content": "pub fn min_length<T: AsRef<str> + InputType>(\n\n value: &T,\n\n len: usize,\n\n) -> Result<(), InputValueError<T>> {\n\n if value.as_ref().len() >= len {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the string length is {}, must be greater than or equal to {}\",\n\n value.as_ref().len(),\n\n len\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_min_length() {\n\n assert!(min_length(&\"ab\".to_string(), 3).is_err());\n\n assert!(min_length(&\"abc\".to_string(), 3).is_ok());\n\n assert!(min_length(&\"abcd\".to_string(), 3).is_ok());\n\n }\n\n}\n", "file_path": "src/validators/min_length.rs", "rank": 67, "score": 158139.17663076735 }, { "content": "fn visit_object<'de, V>(\n\n object: IndexMap<Name, ConstValue>,\n\n visitor: V,\n\n) -> Result<V::Value, DeserializerError>\n\nwhere\n\n V: Visitor<'de>,\n\n{\n\n let len = object.len();\n\n let mut deserializer = MapDeserializer::new(object);\n\n let map = visitor.visit_map(&mut deserializer)?;\n\n let remaining = deserializer.iter.len();\n\n if remaining == 0 {\n\n Ok(map)\n\n } else {\n\n Err(DeserializerError::invalid_length(\n\n len,\n\n &\"fewer elements in map\",\n\n ))\n\n }\n\n}\n", "file_path": "value/src/deserializer.rs", "rank": 68, "score": 156840.7548857094 }, { "content": "fn write_binary(bytes: &[u8], f: &mut Formatter<'_>) -> fmt::Result {\n\n f.write_char('[')?;\n\n let mut iter = bytes.iter().copied();\n\n if let Some(value) = iter.next() {\n\n value.fmt(f)?;\n\n }\n\n for value in iter {\n\n f.write_char(',')?;\n\n value.fmt(f)?;\n\n }\n\n f.write_char(']')\n\n}\n\n\n", "file_path": "value/src/lib.rs", "rank": 69, "score": 155056.8534311329 }, { "content": "pub fn generate(\n\n subscription_args: &args::Subscription,\n\n item_impl: &mut ItemImpl,\n\n) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(subscription_args.internal);\n\n let (self_ty, self_name) = get_type_path_and_name(item_impl.self_ty.as_ref())?;\n\n let generics = &item_impl.generics;\n\n let where_clause = &item_impl.generics.where_clause;\n\n let extends = subscription_args.extends;\n\n\n\n let gql_typename = subscription_args\n\n .name\n\n .clone()\n\n .unwrap_or_else(|| RenameTarget::Type.rename(self_name.clone()));\n\n\n\n let desc = if subscription_args.use_type_description {\n\n quote! { ::std::option::Option::Some(<Self as #crate_name::Description>::description()) }\n\n } else {\n\n get_rustdoc(&item_impl.attrs)?\n\n .map(|s| quote!(::std::option::Option::Some(#s)))\n", "file_path": "derive/src/subscription.rs", "rank": 70, "score": 154867.72027066906 }, { "content": "pub fn generate(\n\n directive_args: &args::Directive,\n\n item_fn: &mut ItemFn,\n\n) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(directive_args.internal);\n\n let ident = &item_fn.sig.ident;\n\n let vis = &item_fn.vis;\n\n let directive_name = directive_args\n\n .name\n\n .clone()\n\n .unwrap_or_else(|| item_fn.sig.ident.to_string());\n\n let desc = get_rustdoc(&item_fn.attrs)?\n\n .map(|s| quote!(::std::option::Option::Some(#s)))\n\n .unwrap_or_else(|| quote!(::std::option::Option::None));\n\n let visible = visible_fn(&directive_args.visible);\n\n let repeatable = directive_args.repeatable;\n\n\n\n let mut get_params = Vec::new();\n\n let mut use_params = Vec::new();\n\n let mut schema_args = Vec::new();\n", "file_path": "derive/src/directive.rs", "rank": 71, "score": 154867.72027066906 }, { "content": "pub fn generate(\n\n scalar_args: &args::Scalar,\n\n item_impl: &mut ItemImpl,\n\n) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(scalar_args.internal);\n\n let self_name = get_type_path_and_name(item_impl.self_ty.as_ref())?.1;\n\n let gql_typename = scalar_args\n\n .name\n\n .clone()\n\n .unwrap_or_else(|| RenameTarget::Type.rename(self_name.clone()));\n\n\n\n let desc = if scalar_args.use_type_description {\n\n quote! { ::std::option::Option::Some(<Self as #crate_name::Description>::description()) }\n\n } else {\n\n get_rustdoc(&item_impl.attrs)?\n\n .map(|s| quote!(::std::option::Option::Some(#s)))\n\n .unwrap_or_else(|| quote!(::std::option::Option::None))\n\n };\n\n\n\n let self_ty = &item_impl.self_ty;\n", "file_path": "derive/src/scalar.rs", "rank": 72, "score": 154867.72027066906 }, { "content": "pub fn min_password_strength<T: AsRef<str> + InputType>(\n\n value: &T,\n\n min_score: u8,\n\n) -> Result<(), InputValueError<T>> {\n\n match zxcvbn(value.as_ref(), &[]) {\n\n Ok(password_strength) => {\n\n if password_strength.score() < min_score {\n\n Err(\"password is too weak\".into())\n\n } else {\n\n Ok(())\n\n }\n\n }\n\n Err(ZxcvbnError::BlankPassword) => Err(\"password is too weak\".into()),\n\n _ => Err(\"error processing password strength\".into()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/validators/min_password_strength.rs", "rank": 73, "score": 152197.18157281788 }, { "content": "pub fn chars_min_length<T: AsRef<str> + InputType>(\n\n value: &T,\n\n len: usize,\n\n) -> Result<(), InputValueError<T>> {\n\n if value.as_ref().chars().count() >= len {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the chars length is {}, must be greater than or equal to {}\",\n\n value.as_ref().len(),\n\n len\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_chars_min_length() {\n\n assert!(chars_min_length(&\"你好\".to_string(), 3).is_err());\n\n assert!(chars_min_length(&\"你好啊\".to_string(), 3).is_ok());\n\n assert!(chars_min_length(&\"嗨你好啊\".to_string(), 3).is_ok());\n\n }\n\n}\n", "file_path": "src/validators/chars_min_length.rs", "rank": 74, "score": 152197.18157281785 }, { "content": "pub fn chars_max_length<T: AsRef<str> + InputType>(\n\n value: &T,\n\n len: usize,\n\n) -> Result<(), InputValueError<T>> {\n\n if value.as_ref().chars().count() <= len {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the chars length is {}, must be less than or equal to {}\",\n\n value.as_ref().len(),\n\n len\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_chars_max_length() {\n\n assert!(chars_max_length(&\"你好\".to_string(), 3).is_ok());\n\n assert!(chars_max_length(&\"你好啊\".to_string(), 3).is_ok());\n\n assert!(chars_max_length(&\"嗨你好啊\".to_string(), 3).is_err());\n\n }\n\n}\n", "file_path": "src/validators/chars_max_length.rs", "rank": 75, "score": 152197.18157281788 }, { "content": "fn parse_value(pair: Pair<Rule>, pc: &mut PositionCalculator) -> Result<Positioned<Value>> {\n\n debug_assert_eq!(pair.as_rule(), Rule::value);\n\n\n\n let pos = pc.step(&pair);\n\n let pair = exactly_one(pair.into_inner());\n\n\n\n Ok(Positioned::new(\n\n match pair.as_rule() {\n\n Rule::variable => Value::Variable(parse_variable(pair, pc)?.node),\n\n Rule::number => Value::Number(parse_number(pair, pc)?.node),\n\n Rule::string => Value::String(parse_string(pair, pc)?.node),\n\n Rule::boolean => Value::Boolean(parse_boolean(pair, pc)?.node),\n\n Rule::null => Value::Null,\n\n Rule::enum_value => Value::Enum(parse_enum_value(pair, pc)?.node),\n\n Rule::list => Value::List(\n\n pair.into_inner()\n\n .map(|pair| Ok(parse_value(pair, pc)?.node))\n\n .collect::<Result<_>>()?,\n\n ),\n\n Rule::object => Value::Object(\n", "file_path": "parser/src/parse/mod.rs", "rank": 76, "score": 152151.93445004764 }, { "content": "pub fn check_rules(\n\n registry: &Registry,\n\n doc: &ExecutableDocument,\n\n variables: Option<&Variables>,\n\n mode: ValidationMode,\n\n) -> Result<ValidationResult, Vec<ServerError>> {\n\n let mut ctx = VisitorContext::new(registry, doc, variables);\n\n let mut cache_control = CacheControl::default();\n\n let mut complexity = 0;\n\n let mut depth = 0;\n\n\n\n match mode {\n\n ValidationMode::Strict => {\n\n let mut visitor = VisitorNil\n\n .with(rules::ArgumentsOfCorrectType::default())\n\n .with(rules::DefaultValuesOfCorrectType)\n\n .with(rules::FieldsOnCorrectType)\n\n .with(rules::FragmentsOnCompositeTypes)\n\n .with(rules::KnownArgumentNames::default())\n\n .with(rules::NoFragmentCycles::default())\n", "file_path": "src/validation/mod.rs", "rank": 77, "score": 151727.61646874063 }, { "content": "pub fn generate_guards(\n\n crate_name: &TokenStream,\n\n code: &SpannedValue<String>,\n\n map_err: TokenStream,\n\n) -> GeneratorResult<TokenStream> {\n\n let expr: Expr =\n\n syn::parse_str(code).map_err(|err| Error::new(code.span(), err.to_string()))?;\n\n let code = quote! {{\n\n use #crate_name::GuardExt;\n\n #expr\n\n }};\n\n Ok(quote! {\n\n #crate_name::Guard::check(&#code, &ctx).await #map_err ?;\n\n })\n\n}\n\n\n", "file_path": "derive/src/utils.rs", "rank": 78, "score": 151727.61646874063 }, { "content": "pub fn generate_default(\n\n default: &Option<args::DefaultValue>,\n\n default_with: &Option<LitStr>,\n\n) -> GeneratorResult<Option<TokenStream>> {\n\n match (default, default_with) {\n\n (Some(args::DefaultValue::Default), _) => {\n\n Ok(Some(quote! { ::std::default::Default::default() }))\n\n }\n\n (Some(args::DefaultValue::Value(lit)), _) => Ok(Some(generate_default_value(lit)?)),\n\n (None, Some(lit)) => Ok(Some(generate_default_with(lit)?)),\n\n (None, None) => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "derive/src/utils.rs", "rank": 79, "score": 151727.61646874063 }, { "content": "fn visit_input_value<'a, V: Visitor<'a>>(\n\n v: &mut V,\n\n ctx: &mut VisitorContext<'a>,\n\n pos: Pos,\n\n expected_ty: Option<MetaTypeName<'a>>,\n\n value: &'a Value,\n\n) {\n\n v.enter_input_value(ctx, pos, &expected_ty, value);\n\n\n\n match value {\n\n Value::List(values) => {\n\n if let Some(expected_ty) = expected_ty {\n\n let elem_ty = expected_ty.unwrap_non_null();\n\n if let MetaTypeName::List(expected_ty) = elem_ty {\n\n values.iter().for_each(|value| {\n\n visit_input_value(\n\n v,\n\n ctx,\n\n pos,\n\n Some(MetaTypeName::create(expected_ty)),\n", "file_path": "src/validation/visitor.rs", "rank": 80, "score": 149425.03196453943 }, { "content": "#[test]\n\npub fn test_macro_generated_union() {\n\n #[derive(SimpleObject)]\n\n pub struct IntObj {\n\n pub val: i32,\n\n }\n\n\n\n generate_union!(MyEnum, IntObj);\n\n\n\n let _ = MyEnum::Val(IntObj { val: 1 });\n\n}\n", "file_path": "tests/union.rs", "rank": 81, "score": 148794.25217856566 }, { "content": "pub fn max_items<T: Deref<Target = [E]> + InputType, E>(\n\n value: &T,\n\n len: usize,\n\n) -> Result<(), InputValueError<T>> {\n\n if value.deref().len() <= len {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the value length is {}, must be less than or equal to {}\",\n\n value.deref().len(),\n\n len\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_max_items() {\n\n assert!(max_items(&vec![1, 2], 3).is_ok());\n\n assert!(max_items(&vec![1, 2, 3], 3).is_ok());\n\n assert!(max_items(&vec![1, 2, 3, 4], 3).is_err());\n\n }\n\n}\n", "file_path": "src/validators/max_items.rs", "rank": 82, "score": 147002.39863594886 }, { "content": "pub fn min_items<T: Deref<Target = [E]> + InputType, E>(\n\n value: &T,\n\n len: usize,\n\n) -> Result<(), InputValueError<T>> {\n\n if value.deref().len() >= len {\n\n Ok(())\n\n } else {\n\n Err(format!(\n\n \"the value length is {}, must be greater than or equal to {}\",\n\n value.deref().len(),\n\n len\n\n )\n\n .into())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_min_items() {\n\n assert!(min_items(&vec![1, 2], 3).is_err());\n\n assert!(min_items(&vec![1, 2, 3], 3).is_ok());\n\n assert!(min_items(&vec![1, 2, 3, 4], 3).is_ok());\n\n }\n\n}\n", "file_path": "src/validators/min_items.rs", "rank": 83, "score": 147002.39863594883 }, { "content": "pub fn generate(object_args: &args::MergedSubscription) -> GeneratorResult<TokenStream> {\n\n let crate_name = get_crate_name(object_args.internal);\n\n let ident = &object_args.ident;\n\n let extends = object_args.extends;\n\n let gql_typename = object_args\n\n .name\n\n .clone()\n\n .unwrap_or_else(|| RenameTarget::Type.rename(ident.to_string()));\n\n\n\n let desc = get_rustdoc(&object_args.attrs)?\n\n .map(|s| quote! { ::std::option::Option::Some(#s) })\n\n .unwrap_or_else(|| quote! {::std::option::Option::None});\n\n\n\n let s = match &object_args.data {\n\n Data::Struct(e) => e,\n\n _ => {\n\n return Err(Error::new_spanned(\n\n &ident,\n\n \"MergedSubscription can only be applied to an struct.\",\n\n )\n", "file_path": "derive/src/merged_subscription.rs", "rank": 84, "score": 146383.7800291475 }, { "content": "fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> {\n\n futures_util::future::ready(Ok(Data::default()))\n\n}\n\n\n\n/// A Websocket connection for GraphQL subscription.\n\npub struct GraphQLWebSocket<Sink, Stream, Query, Mutation, Subscription, OnConnInit> {\n\n sink: Sink,\n\n stream: Stream,\n\n schema: Schema<Query, Mutation, Subscription>,\n\n data: Data,\n\n on_connection_init: OnConnInit,\n\n protocol: GraphQLProtocol,\n\n}\n\n\n\nimpl<S, Query, Mutation, Subscription>\n\n GraphQLWebSocket<\n\n SplitSink<S, Message>,\n\n SplitStream<S>,\n\n Query,\n\n Mutation,\n", "file_path": "integrations/poem/src/subscription.rs", "rank": 85, "score": 145308.50328855458 }, { "content": "fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> {\n\n futures_util::future::ready(Ok(Data::default()))\n\n}\n\n\n\n/// A Websocket connection for GraphQL subscription.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use std::time::Duration;\n\n///\n\n/// use async_graphql::*;\n\n/// use async_graphql_warp::*;\n\n/// use futures_util::stream::{Stream, StreamExt};\n\n/// use warp::{ws, Filter};\n\n///\n\n/// struct QueryRoot;\n\n///\n\n/// #[Object]\n\n/// impl QueryRoot {\n", "file_path": "integrations/warp/src/subscription.rs", "rank": 86, "score": 145308.50328855458 }, { "content": "fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> {\n\n futures_util::future::ready(Ok(Data::default()))\n\n}\n\n\n\nimpl<Query, Mutation, Subscription>\n\n GraphQLSubscription<Query, Mutation, Subscription, DefaultOnConnInitType>\n\nwhere\n\n Query: ObjectType + 'static,\n\n Mutation: ObjectType + 'static,\n\n Subscription: SubscriptionType + 'static,\n\n{\n\n /// Create a [`GraphQLSubscription`] object.\n\n pub fn new(schema: Schema<Query, Mutation, Subscription>) -> Self {\n\n GraphQLSubscription {\n\n schema,\n\n on_connection_init: default_on_connection_init,\n\n }\n\n }\n\n}\n\n\n", "file_path": "integrations/tide/src/subscription.rs", "rank": 87, "score": 145308.50328855458 }, { "content": "fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> {\n\n futures_util::future::ready(Ok(Data::default()))\n\n}\n\n\n\n/// A Websocket connection for GraphQL subscription.\n\npub struct GraphQLWebSocket<Sink, Stream, Query, Mutation, Subscription, OnConnInit> {\n\n sink: Sink,\n\n stream: Stream,\n\n schema: Schema<Query, Mutation, Subscription>,\n\n data: Data,\n\n on_connection_init: OnConnInit,\n\n protocol: GraphQLProtocol,\n\n}\n\n\n\nimpl<S, Query, Mutation, Subscription>\n\n GraphQLWebSocket<\n\n SplitSink<S, Message>,\n\n SplitStream<S>,\n\n Query,\n\n Mutation,\n", "file_path": "integrations/axum/src/subscription.rs", "rank": 88, "score": 145308.50328855458 }, { "content": "fn write_object<K: Display, V: Display>(\n\n object: impl IntoIterator<Item = (K, V)>,\n\n f: &mut Formatter<'_>,\n\n) -> fmt::Result {\n\n f.write_char('{')?;\n\n let mut iter = object.into_iter();\n\n if let Some((name, value)) = iter.next() {\n\n write!(f, \"{}: {}\", name, value)?;\n\n }\n\n for (name, value) in iter {\n\n f.write_char(',')?;\n\n write!(f, \"{}: {}\", name, value)?;\n\n }\n\n f.write_char('}')\n\n}\n", "file_path": "value/src/lib.rs", "rank": 89, "score": 145176.20442018347 }, { "content": "fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> {\n\n futures_util::future::ready(Ok(Data::default()))\n\n}\n\n\n\n/// A builder for websocket subscription actor.\n\npub struct GraphQLSubscription<Query, Mutation, Subscription, OnInit> {\n\n schema: Schema<Query, Mutation, Subscription>,\n\n data: Data,\n\n on_connection_init: OnInit,\n\n}\n\n\n\nimpl<Query, Mutation, Subscription>\n\n GraphQLSubscription<Query, Mutation, Subscription, DefaultOnConnInitType>\n\nwhere\n\n Query: ObjectType + 'static,\n\n Mutation: ObjectType + 'static,\n\n Subscription: SubscriptionType + 'static,\n\n{\n\n /// Create a GraphQL subscription builder.\n\n pub fn new(schema: Schema<Query, Mutation, Subscription>) -> Self {\n", "file_path": "integrations/actix-web/src/subscription.rs", "rank": 90, "score": 142714.67676153025 }, { "content": "pub fn client() -> Client {\n\n Client::builder().no_proxy().build().unwrap()\n\n}\n\n\n\npub async fn wait_server_ready() {\n\n async_std::task::sleep(Duration::from_secs(1)).await;\n\n}\n", "file_path": "integrations/tide/tests/test_utils.rs", "rank": 91, "score": 141278.7019161816 }, { "content": "type DefaultOnConnInitType = fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>;\n\n\n", "file_path": "integrations/warp/src/subscription.rs", "rank": 92, "score": 140249.32937939768 }, { "content": "type DefaultOnConnInitType = fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>;\n\n\n", "file_path": "integrations/axum/src/subscription.rs", "rank": 93, "score": 140249.32937939768 }, { "content": "type DefaultOnConnInitType = fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>;\n\n\n", "file_path": "integrations/tide/src/subscription.rs", "rank": 94, "score": 140249.32937939768 }, { "content": "type DefaultOnConnInitType = fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>;\n\n\n", "file_path": "integrations/poem/src/subscription.rs", "rank": 95, "score": 140249.32937939768 }, { "content": "#[derive(Serialize, Deserialize)]\n\n#[repr(transparent)]\n\n#[serde(transparent)]\n\nstruct AssetId(pub uuid::Uuid);\n\n\n\nasync_graphql::scalar!(AssetId);\n\n\n\n#[tokio::test]\n\n/// Test case for\n\n/// https://github.com/async-graphql/async-graphql/issues/603\n\npub async fn test_serialize_uuid() {\n\n let generated_uuid = uuid::Uuid::new_v4();\n\n\n\n struct Query {\n\n data: AssetId,\n\n }\n\n\n\n #[Object]\n\n impl Query {\n\n async fn data(&self) -> &AssetId {\n\n &self.data\n\n }\n\n }\n", "file_path": "tests/serializer_uuid.rs", "rank": 96, "score": 139581.06341584053 }, { "content": "fn parse_field(pair: Pair<Rule>, pc: &mut PositionCalculator) -> Result<Positioned<Field>> {\n\n debug_assert_eq!(pair.as_rule(), Rule::field);\n\n\n\n let pos = pc.step(&pair);\n\n let mut pairs = pair.into_inner();\n\n\n\n let alias = parse_if_rule(&mut pairs, Rule::alias, |pair| parse_alias(pair, pc))?;\n\n let name = parse_name(pairs.next().unwrap(), pc)?;\n\n let arguments = parse_if_rule(&mut pairs, Rule::arguments, |pair| {\n\n parse_arguments(pair, pc)\n\n })?;\n\n let directives = parse_opt_directives(&mut pairs, pc)?;\n\n let selection_set = parse_if_rule(&mut pairs, Rule::selection_set, |pair| {\n\n parse_selection_set(pair, pc)\n\n })?;\n\n\n\n debug_assert_eq!(pairs.next(), None);\n\n\n\n Ok(Positioned::new(\n\n Field {\n\n alias,\n\n name,\n\n arguments: arguments.unwrap_or_default(),\n\n directives,\n\n selection_set: selection_set.unwrap_or_default(),\n\n },\n\n pos,\n\n ))\n\n}\n\n\n", "file_path": "parser/src/parse/executable.rs", "rank": 97, "score": 138730.7943816492 }, { "content": "fn parse_alias(pair: Pair<Rule>, pc: &mut PositionCalculator) -> Result<Positioned<Name>> {\n\n debug_assert_eq!(pair.as_rule(), Rule::alias);\n\n parse_name(exactly_one(pair.into_inner()), pc)\n\n}\n\n\n", "file_path": "parser/src/parse/executable.rs", "rank": 98, "score": 138730.7943816492 }, { "content": "fn parse_selection(pair: Pair<Rule>, pc: &mut PositionCalculator) -> Result<Positioned<Selection>> {\n\n debug_assert_eq!(pair.as_rule(), Rule::selection);\n\n\n\n let pos = pc.step(&pair);\n\n let pair = exactly_one(pair.into_inner());\n\n\n\n Ok(Positioned::new(\n\n match pair.as_rule() {\n\n Rule::field => Selection::Field(parse_field(pair, pc)?),\n\n Rule::fragment_spread => Selection::FragmentSpread(parse_fragment_spread(pair, pc)?),\n\n Rule::inline_fragment => Selection::InlineFragment(parse_inline_fragment(pair, pc)?),\n\n _ => unreachable!(),\n\n },\n\n pos,\n\n ))\n\n}\n\n\n", "file_path": "parser/src/parse/executable.rs", "rank": 99, "score": 138730.7943816492 } ]
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, "score": 149306.9401018221 }, { "content": "fn parse_page(doc: Document, result: &mut Vec<Offer>) -> Document {\n\n for entry in doc.find(Class(\"offer-card\")) {\n\n result.push(Offer {\n\n title: entry\n\n .find(And(Name(\"h3\"), Class(\"offer-card__title\")))\n\n .next()\n\n .unwrap()\n\n .text(),\n\n price: parse_price(&entry.find(Attr(\"itemprop\", \"price\")).next().unwrap().text())\n\n .unwrap(),\n\n url: format!(\n\n \"{}{}\",\n\n BASE_URL,\n\n entry\n\n .attr(\"href\")\n\n .expect(\"Cannot parse offer href\")\n\n .to_string(),\n\n ),\n\n })\n\n }\n\n\n\n doc\n\n}\n\n\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 4, "score": 100291.16317469825 }, { "content": "pub fn scrape(params: &HashMap<&str, &str>) -> Vec<Offer> {\n\n let mut collection = Vec::new();\n\n let url = build_url(params);\n\n let response = reqwest::get(&url).expect(\"Could not get url\");\n\n assert!(response.status().is_success());\n\n\n\n let mut first_page = Document::from_read(response).expect(\"Could not parse first page\");\n\n\n\n // scrape first page\n\n first_page = parse_page(first_page, &mut collection);\n\n\n\n if let Some(pager) = first_page.find(Class(\"pagination\")).next() {\n\n let with_pagination = || -> Result<u32, ParseIntError> {\n\n pager\n\n .find(Name(\"label\"))\n\n .next()\n\n .unwrap()\n\n .find(And(Name(\"span\"), Not(Class(\"sr-only\"))))\n\n .next()\n\n .unwrap()\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 6, "score": 92990.60418407043 }, { "content": "fn build_url(params: &HashMap<&str, &str>) -> String {\n\n let mut url = format!(\n\n \"{}/{}/q/{}\",\n\n BASE_URL,\n\n OFFERS_PATH,\n\n params.get(\"query\").unwrap()\n\n );\n\n\n\n if params.contains_key(\"min_price\") {\n\n add_filter(\n\n &format!(\"price_from={}\", params.get(\"min_price\").unwrap()),\n\n &mut url,\n\n );\n\n }\n\n\n\n if params.contains_key(\"max_price\") {\n\n add_filter(\n\n &format!(\"price_to={}\", params.get(\"max_price\").unwrap()),\n\n &mut url,\n\n );\n\n }\n\n\n\n url\n\n}\n\n\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 9, "score": 84052.92250615788 }, { "content": "fn parse_price(input: &str) -> Option<f32> {\n\n match {\n\n let t = input\n\n .trim_matches(char::is_alphabetic)\n\n .trim_matches(char::is_whitespace)\n\n .replace(\",\", \".\");\n\n\n\n t.parse::<f32>()\n\n } {\n\n Ok(v) => Some(v),\n\n Err(_) => Some(9999999f32),\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 10, "score": 58910.86130210089 }, { "content": "fn render_table(offers: &Vec<Offer>) {\n\n let mut table = Table::new();\n\n\n\n table\n\n .set_header(vec![\"Title\", \"Price\", \"URL\"])\n\n .set_content_arrangement(ContentArrangement::DynamicFullWidth);\n\n\n\n for offer in offers.iter() {\n\n table.add_row(vec![\n\n Cell::new(&offer.title),\n\n Cell::new(&offer.price.to_string()),\n\n Cell::new(&offer.url).add_attribute(Attribute::Italic),\n\n ]);\n\n }\n\n\n\n let url_column = table.get_column_mut(2).unwrap();\n\n url_column.set_padding((1, 1));\n\n url_column.set_cell_alignment(CellAlignment::Left);\n\n\n\n println!(\"{}\", table);\n", "file_path": "src/main.rs", "rank": 11, "score": 51039.647520207276 }, { "content": "fn export_csv(offers: &Vec<Offer>) {\n\n let mut wtr = csv::Writer::from_writer(io::stdout());\n\n\n\n for offer in offers.iter() {\n\n wtr.serialize(offer)\n\n .expect(\"Could not serialize offer into CSV\");\n\n }\n\n\n\n wtr.flush().unwrap();\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 12, "score": 51039.647520207276 }, { "content": "fn main() {\n\n let matches = App::new(\"alx\")\n\n .version(\"0.4.0\")\n\n .author(\"Valentin Michaluk <[email protected]>\")\n\n .about(\"Hey Alx'er! Let's find something!\")\n\n .arg(\n\n Arg::with_name(\"min_price\")\n\n .long(\"min\")\n\n .takes_value(true)\n\n .help(\"Minimum price\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"max_price\")\n\n .long(\"max\")\n\n .takes_value(true)\n\n .help(\"Maximum price\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"export_csv\")\n\n .long(\"export-csv\")\n", "file_path": "src/main.rs", "rank": 13, "score": 20351.82145084969 }, { "content": "}\n\n\n\n#[derive(Serialize)]\n\npub struct Offer {\n\n title: String,\n\n price: f32,\n\n url: String,\n\n}\n\n\n\nimpl fmt::Display for Offer {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(\n\n f,\n\n \"title: {}, price: {}\\n url: {}\",\n\n self.title, self.price, self.url\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 16, "score": 12.004338348767085 }, { "content": "use crate::parse_price;\n\nuse crate::Offer;\n\nuse select::document::Document;\n\nuse select::predicate::And;\n\nuse select::predicate::Not;\n\nuse select::predicate::{Attr, Class, Name};\n\n\n\nuse std::collections::HashMap;\n\nuse std::num::ParseIntError;\n\n\n\nstatic BASE_URL: &str = \"https://allegrolokalnie.pl\";\n\nstatic OFFERS_PATH: &str = \"oferty\";\n\n\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 17, "score": 11.519229043784652 }, { "content": " .text()\n\n .parse::<u32>()\n\n };\n\n\n\n // Parse rest of pages\n\n if let Ok(n) = with_pagination() {\n\n if n > 1 {\n\n for page_number in 2..=n {\n\n let u = format!(\"{}/?page={}\", &url, page_number);\n\n let resp = reqwest::get(&u).expect(\"Could not get url\");\n\n assert!(resp.status().is_success());\n\n\n\n let doc = Document::from_read(resp).unwrap();\n\n parse_page(doc, &mut collection);\n\n }\n\n }\n\n }\n\n };\n\n\n\n collection\n\n}\n\n\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 19, "score": 9.418905127499874 }, { "content": " .takes_value(false)\n\n .help(\"Exports search result into csv\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"query\")\n\n .help(\"Search query\")\n\n .index(1)\n\n .required(true)\n\n .multiple(true),\n\n )\n\n .get_matches();\n\n\n\n let mut params = HashMap::new();\n\n\n\n let q: &str = &matches\n\n .values_of(\"query\")\n\n .unwrap()\n\n .collect::<Vec<&str>>()\n\n .join(\" \");\n\n params.insert(\"query\", q);\n", "file_path": "src/main.rs", "rank": 20, "score": 7.456183011622307 }, { "content": "\n\n if matches.is_present(\"min_price\") {\n\n params.insert(\"min_price\", matches.value_of(\"min_price\").unwrap());\n\n }\n\n\n\n if matches.is_present(\"max_price\") {\n\n params.insert(\"max_price\", matches.value_of(\"max_price\").unwrap());\n\n }\n\n\n\n let mut offers = Vec::new();\n\n offers.append(&mut olx_client::scrape(&params));\n\n offers.append(&mut allegro_lokalnie_client::scrape(&params));\n\n offers.sort_unstable_by(|a, b| {\n\n a.price\n\n .partial_cmp(&b.price)\n\n .expect(\"Could not sort offers\")\n\n });\n\n\n\n if matches.is_present(\"export_csv\") {\n\n export_csv(&offers);\n", "file_path": "src/main.rs", "rank": 21, "score": 5.865694386265179 }, { "content": " } else {\n\n render_table(&offers);\n\n\n\n println!(\"Total items: {}\", offers.len());\n\n\n\n match { offers.iter().min_by_key(|o| o.price as u32) } {\n\n Some(lp) => {\n\n println!(\"Item with a lowest price: {}\", lp);\n\n }\n\n _ => (),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 22, "score": 3.995311243259084 }, { "content": "# alx\n\n\n\nHelps you with quick searches on olx.pl and allegrolokalnie.pl\n\n\n\n<img src=\"/docs/image.png?raw=true\" alt=\"alx\" title=\"alx\">\n\n \n\n# Install\n\n \n\n1. Install Rust - https://www.rust-lang.org/tools/install\n\n2. Install or upgrade the package:\n\n\n\n``` sh\n\ngit clone [email protected]:valpfft/alx.git\n\ncd alx\n\ncargo install --path . --force\n\n```\n\nIf it fails to compile and you installed Rust a long time ago, try `rustup update` to update Rust to the latest version.\n\n\n\n\n\n# Usage\n\n\n\n## Help\n\n\n\n```sh\n\n❯ alx --help\n\nalx 0.4.0\n\nHey Alx'er! Let's find something!\n\n\n\nUSAGE:\n\n alx [FLAGS] [OPTIONS] <query>...\n\n\n\nFLAGS:\n\n --export-csv Exports search result into csv\n\n -h, --help Prints help information\n\n -V, --version Prints version information\n\n\n\nOPTIONS:\n\n --max <max_price> Maximum price\n\n --min <min_price> Minimum price\n\n\n\nARGS:\n\n <query>... Search query\n\n```\n", "file_path": "README.md", "rank": 23, "score": 3.3336208739804754 }, { "content": "extern crate clap;\n\nextern crate csv;\n\nextern crate reqwest;\n\nextern crate select;\n\n\n\nuse std::collections::HashMap;\n\nuse std::{fmt, io};\n\n\n\nuse clap::{App, Arg};\n\nuse serde::Serialize;\n\n\n\nuse comfy_table::{Attribute, Cell, CellAlignment, ContentArrangement, Table};\n\nmod allegro_lokalnie_client;\n\nmod olx_client;\n\n\n", "file_path": "src/main.rs", "rank": 24, "score": 2.587019601697195 } ]