file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
install.rs
//! Implementation of the install aspects of the compiler. //! //! This module is responsible for installing the standard library, //! compiler, and documentation. use std::env; use std::fs; use std::path::{Component, PathBuf}; use std::process::Command; use build_helper::t; use crate::dist::{self, sanitize_sh}; use crate::tarball::GeneratedTarball; use crate::Compiler; use crate::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::config::{Config, TargetSelection}; #[cfg(target_os = "illumos")] const SHELL: &str = "bash"; #[cfg(not(target_os = "illumos"))] const SHELL: &str = "sh"; fn install_sh( builder: &Builder<'_>, package: &str, stage: u32, host: Option<TargetSelection>, tarball: &GeneratedTarball, ) { builder.info(&format!("Install {} stage{} ({:?})", package, stage, host)); let prefix = default_path(&builder.config.prefix, "/usr/local"); let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, "/etc")); let datadir = prefix.join(default_path(&builder.config.datadir, "share")); let docdir = prefix.join(default_path(&builder.config.docdir, "share/doc/rust")); let mandir = prefix.join(default_path(&builder.config.mandir, "share/man")); let libdir = prefix.join(default_path(&builder.config.libdir, "lib")); let bindir = prefix.join(&builder.config.bindir); // Default in config.rs let empty_dir = builder.out.join("tmp/empty_dir"); t!(fs::create_dir_all(&empty_dir)); let mut cmd = Command::new(SHELL); cmd.current_dir(&empty_dir) .arg(sanitize_sh(&tarball.decompressed_output().join("install.sh"))) .arg(format!("--prefix={}", prepare_dir(prefix))) .arg(format!("--sysconfdir={}", prepare_dir(sysconfdir))) .arg(format!("--datadir={}", prepare_dir(datadir))) .arg(format!("--docdir={}", prepare_dir(docdir))) .arg(format!("--bindir={}", prepare_dir(bindir))) .arg(format!("--libdir={}", prepare_dir(libdir))) .arg(format!("--mandir={}", prepare_dir(mandir))) .arg("--disable-ldconfig"); builder.run(&mut cmd); t!(fs::remove_dir_all(&empty_dir)); } fn default_path(config: &Option<PathBuf>, default: &str) -> PathBuf { config.as_ref().cloned().unwrap_or_else(|| PathBuf::from(default)) } fn prepare_dir(mut path: PathBuf) -> String { // The DESTDIR environment variable is a standard way to install software in a subdirectory // while keeping the original directory structure, even if the prefix or other directories // contain absolute paths. // // More information on the environment variable is available here: // https://www.gnu.org/prep/standards/html_node/DESTDIR.html if let Some(destdir) = env::var_os("DESTDIR").map(PathBuf::from)
// The installation command is not executed from the current directory, but from a temporary // directory. To prevent relative paths from breaking this converts relative paths to absolute // paths. std::fs::canonicalize is not used as that requires the path to actually be present. if path.is_relative() { path = std::env::current_dir().expect("failed to get the current directory").join(path); assert!(path.is_absolute(), "could not make the path relative"); } sanitize_sh(&path) } macro_rules! install { (($sel:ident, $builder:ident, $_config:ident), $($name:ident, $path:expr, $default_cond:expr, only_hosts: $only_hosts:expr, $run_item:block $(, $c:ident)*;)+) => { $( #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct $name { pub compiler: Compiler, pub target: TargetSelection, } impl $name { #[allow(dead_code)] fn should_build(config: &Config) -> bool { config.extended && config.tools.as_ref() .map_or(true, |t| t.contains($path)) } } impl Step for $name { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = $only_hosts; $(const $c: bool = true;)* fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let $_config = &run.builder.config; run.path($path).default_condition($default_cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure($name { compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build), target: run.target, }); } fn run($sel, $builder: &Builder<'_>) { $run_item } })+ } } install!((self, builder, _config), Docs, "src/doc", _config.docs, only_hosts: false, { let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs"); install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); }; Std, "library/std", true, only_hosts: false, { for target in &builder.targets { // `expect` should be safe, only None when host!= build, but this // only runs when host == build let tarball = builder.ensure(dist::Std { compiler: self.compiler, target: *target }).expect("missing std"); install_sh(builder, "std", self.compiler.stage, Some(*target), &tarball); } }; Cargo, "cargo", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Cargo { compiler: self.compiler, target: self.target }) .expect("missing cargo"); install_sh(builder, "cargo", self.compiler.stage, Some(self.target), &tarball); }; Rls, "rls", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rls { compiler: self.compiler, target: self.target }) { install_sh(builder, "rls", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RLS stage{} ({})", self.compiler.stage, self.target), ); } }; RustAnalyzer, "rust-analyzer", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::RustAnalyzer { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-analyzer", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install rust-analyzer stage{} ({})", self.compiler.stage, self.target), ); } }; Clippy, "clippy", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Clippy { compiler: self.compiler, target: self.target }) .expect("missing clippy"); install_sh(builder, "clippy", self.compiler.stage, Some(self.target), &tarball); }; Miri, "miri", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Miri { compiler: self.compiler, target: self.target }) { install_sh(builder, "miri", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install miri stage{} ({})", self.compiler.stage, self.target), ); } }; Rustfmt, "rustfmt", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rustfmt { compiler: self.compiler, target: self.target }) { install_sh(builder, "rustfmt", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install Rustfmt stage{} ({})", self.compiler.stage, self.target), ); } }; RustDemangler, "rust-demangler", Self::should_build(_config), only_hosts: true, { // Note: Even though `should_build` may return true for `extended` default tools, // dist::RustDemangler may still return None, unless the target-dependent `profiler` config // is also true, or the `tools` array explicitly includes "rust-demangler". if let Some(tarball) = builder.ensure(dist::RustDemangler { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-demangler", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RustDemangler stage{} ({})", self.compiler.stage, self.target), ); } }; Analysis, "analysis", Self::should_build(_config), only_hosts: false, { // `expect` should be safe, only None with host!= build, but this // only uses the `build` compiler let tarball = builder.ensure(dist::Analysis { // Find the actual compiler (handling the full bootstrap option) which // produced the save-analysis data because that data isn't copied // through the sysroot uplifting. compiler: builder.compiler_for(builder.top_stage, builder.config.build, self.target), target: self.target }).expect("missing analysis"); install_sh(builder, "analysis", self.compiler.stage, Some(self.target), &tarball); }; Rustc, "src/librustc", true, only_hosts: true, { let tarball = builder.ensure(dist::Rustc { compiler: builder.compiler(builder.top_stage, self.target), }); install_sh(builder, "rustc", self.compiler.stage, Some(self.target), &tarball); }; ); #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Src { pub stage: u32, } impl Step for Src { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let config = &run.builder.config; let cond = config.extended && config.tools.as_ref().map_or(true, |t| t.contains("src")); run.path("src").default_condition(cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure(Src { stage: run.builder.top_stage }); } fn run(self, builder: &Builder<'_>) { let tarball = builder.ensure(dist::Src); install_sh(builder, "src", self.stage, None, &tarball); } }
{ let without_destdir = path.clone(); path = destdir; // Custom .join() which ignores disk roots. for part in without_destdir.components() { if let Component::Normal(s) = part { path.push(s) } } }
conditional_block
install.rs
//! Implementation of the install aspects of the compiler. //! //! This module is responsible for installing the standard library, //! compiler, and documentation. use std::env; use std::fs; use std::path::{Component, PathBuf}; use std::process::Command; use build_helper::t; use crate::dist::{self, sanitize_sh}; use crate::tarball::GeneratedTarball; use crate::Compiler; use crate::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::config::{Config, TargetSelection}; #[cfg(target_os = "illumos")] const SHELL: &str = "bash"; #[cfg(not(target_os = "illumos"))] const SHELL: &str = "sh"; fn install_sh( builder: &Builder<'_>, package: &str, stage: u32, host: Option<TargetSelection>, tarball: &GeneratedTarball, ) { builder.info(&format!("Install {} stage{} ({:?})", package, stage, host)); let prefix = default_path(&builder.config.prefix, "/usr/local"); let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, "/etc")); let datadir = prefix.join(default_path(&builder.config.datadir, "share")); let docdir = prefix.join(default_path(&builder.config.docdir, "share/doc/rust")); let mandir = prefix.join(default_path(&builder.config.mandir, "share/man")); let libdir = prefix.join(default_path(&builder.config.libdir, "lib")); let bindir = prefix.join(&builder.config.bindir); // Default in config.rs let empty_dir = builder.out.join("tmp/empty_dir"); t!(fs::create_dir_all(&empty_dir)); let mut cmd = Command::new(SHELL); cmd.current_dir(&empty_dir) .arg(sanitize_sh(&tarball.decompressed_output().join("install.sh"))) .arg(format!("--prefix={}", prepare_dir(prefix))) .arg(format!("--sysconfdir={}", prepare_dir(sysconfdir))) .arg(format!("--datadir={}", prepare_dir(datadir))) .arg(format!("--docdir={}", prepare_dir(docdir))) .arg(format!("--bindir={}", prepare_dir(bindir))) .arg(format!("--libdir={}", prepare_dir(libdir))) .arg(format!("--mandir={}", prepare_dir(mandir))) .arg("--disable-ldconfig"); builder.run(&mut cmd); t!(fs::remove_dir_all(&empty_dir)); } fn default_path(config: &Option<PathBuf>, default: &str) -> PathBuf { config.as_ref().cloned().unwrap_or_else(|| PathBuf::from(default)) } fn prepare_dir(mut path: PathBuf) -> String { // The DESTDIR environment variable is a standard way to install software in a subdirectory // while keeping the original directory structure, even if the prefix or other directories // contain absolute paths. // // More information on the environment variable is available here: // https://www.gnu.org/prep/standards/html_node/DESTDIR.html if let Some(destdir) = env::var_os("DESTDIR").map(PathBuf::from) { let without_destdir = path.clone(); path = destdir; // Custom.join() which ignores disk roots. for part in without_destdir.components() { if let Component::Normal(s) = part { path.push(s) } } } // The installation command is not executed from the current directory, but from a temporary // directory. To prevent relative paths from breaking this converts relative paths to absolute // paths. std::fs::canonicalize is not used as that requires the path to actually be present. if path.is_relative() { path = std::env::current_dir().expect("failed to get the current directory").join(path); assert!(path.is_absolute(), "could not make the path relative"); } sanitize_sh(&path) } macro_rules! install { (($sel:ident, $builder:ident, $_config:ident), $($name:ident, $path:expr, $default_cond:expr, only_hosts: $only_hosts:expr, $run_item:block $(, $c:ident)*;)+) => { $( #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct $name { pub compiler: Compiler, pub target: TargetSelection, } impl $name { #[allow(dead_code)] fn should_build(config: &Config) -> bool { config.extended && config.tools.as_ref() .map_or(true, |t| t.contains($path)) } } impl Step for $name { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = $only_hosts; $(const $c: bool = true;)* fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let $_config = &run.builder.config; run.path($path).default_condition($default_cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure($name { compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build), target: run.target, }); } fn run($sel, $builder: &Builder<'_>) { $run_item } })+ } } install!((self, builder, _config), Docs, "src/doc", _config.docs, only_hosts: false, { let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs"); install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); }; Std, "library/std", true, only_hosts: false, { for target in &builder.targets { // `expect` should be safe, only None when host!= build, but this // only runs when host == build let tarball = builder.ensure(dist::Std { compiler: self.compiler, target: *target }).expect("missing std"); install_sh(builder, "std", self.compiler.stage, Some(*target), &tarball); } }; Cargo, "cargo", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Cargo { compiler: self.compiler, target: self.target }) .expect("missing cargo"); install_sh(builder, "cargo", self.compiler.stage, Some(self.target), &tarball); }; Rls, "rls", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rls { compiler: self.compiler, target: self.target }) { install_sh(builder, "rls", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RLS stage{} ({})", self.compiler.stage, self.target), ); } }; RustAnalyzer, "rust-analyzer", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::RustAnalyzer { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-analyzer", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install rust-analyzer stage{} ({})", self.compiler.stage, self.target), ); } }; Clippy, "clippy", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Clippy { compiler: self.compiler, target: self.target }) .expect("missing clippy"); install_sh(builder, "clippy", self.compiler.stage, Some(self.target), &tarball); }; Miri, "miri", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Miri { compiler: self.compiler, target: self.target }) { install_sh(builder, "miri", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install miri stage{} ({})", self.compiler.stage, self.target), ); } }; Rustfmt, "rustfmt", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rustfmt { compiler: self.compiler, target: self.target }) { install_sh(builder, "rustfmt", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install Rustfmt stage{} ({})", self.compiler.stage, self.target), ); } }; RustDemangler, "rust-demangler", Self::should_build(_config), only_hosts: true, { // Note: Even though `should_build` may return true for `extended` default tools, // dist::RustDemangler may still return None, unless the target-dependent `profiler` config // is also true, or the `tools` array explicitly includes "rust-demangler". if let Some(tarball) = builder.ensure(dist::RustDemangler { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-demangler", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RustDemangler stage{} ({})", self.compiler.stage, self.target), ); } }; Analysis, "analysis", Self::should_build(_config), only_hosts: false, { // `expect` should be safe, only None with host!= build, but this // only uses the `build` compiler let tarball = builder.ensure(dist::Analysis { // Find the actual compiler (handling the full bootstrap option) which // produced the save-analysis data because that data isn't copied // through the sysroot uplifting. compiler: builder.compiler_for(builder.top_stage, builder.config.build, self.target), target: self.target }).expect("missing analysis"); install_sh(builder, "analysis", self.compiler.stage, Some(self.target), &tarball); }; Rustc, "src/librustc", true, only_hosts: true, { let tarball = builder.ensure(dist::Rustc { compiler: builder.compiler(builder.top_stage, self.target), }); install_sh(builder, "rustc", self.compiler.stage, Some(self.target), &tarball); };
); #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Src { pub stage: u32, } impl Step for Src { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let config = &run.builder.config; let cond = config.extended && config.tools.as_ref().map_or(true, |t| t.contains("src")); run.path("src").default_condition(cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure(Src { stage: run.builder.top_stage }); } fn run(self, builder: &Builder<'_>) { let tarball = builder.ensure(dist::Src); install_sh(builder, "src", self.stage, None, &tarball); } }
random_line_split
install.rs
//! Implementation of the install aspects of the compiler. //! //! This module is responsible for installing the standard library, //! compiler, and documentation. use std::env; use std::fs; use std::path::{Component, PathBuf}; use std::process::Command; use build_helper::t; use crate::dist::{self, sanitize_sh}; use crate::tarball::GeneratedTarball; use crate::Compiler; use crate::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::config::{Config, TargetSelection}; #[cfg(target_os = "illumos")] const SHELL: &str = "bash"; #[cfg(not(target_os = "illumos"))] const SHELL: &str = "sh"; fn install_sh( builder: &Builder<'_>, package: &str, stage: u32, host: Option<TargetSelection>, tarball: &GeneratedTarball, ) { builder.info(&format!("Install {} stage{} ({:?})", package, stage, host)); let prefix = default_path(&builder.config.prefix, "/usr/local"); let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, "/etc")); let datadir = prefix.join(default_path(&builder.config.datadir, "share")); let docdir = prefix.join(default_path(&builder.config.docdir, "share/doc/rust")); let mandir = prefix.join(default_path(&builder.config.mandir, "share/man")); let libdir = prefix.join(default_path(&builder.config.libdir, "lib")); let bindir = prefix.join(&builder.config.bindir); // Default in config.rs let empty_dir = builder.out.join("tmp/empty_dir"); t!(fs::create_dir_all(&empty_dir)); let mut cmd = Command::new(SHELL); cmd.current_dir(&empty_dir) .arg(sanitize_sh(&tarball.decompressed_output().join("install.sh"))) .arg(format!("--prefix={}", prepare_dir(prefix))) .arg(format!("--sysconfdir={}", prepare_dir(sysconfdir))) .arg(format!("--datadir={}", prepare_dir(datadir))) .arg(format!("--docdir={}", prepare_dir(docdir))) .arg(format!("--bindir={}", prepare_dir(bindir))) .arg(format!("--libdir={}", prepare_dir(libdir))) .arg(format!("--mandir={}", prepare_dir(mandir))) .arg("--disable-ldconfig"); builder.run(&mut cmd); t!(fs::remove_dir_all(&empty_dir)); } fn default_path(config: &Option<PathBuf>, default: &str) -> PathBuf
fn prepare_dir(mut path: PathBuf) -> String { // The DESTDIR environment variable is a standard way to install software in a subdirectory // while keeping the original directory structure, even if the prefix or other directories // contain absolute paths. // // More information on the environment variable is available here: // https://www.gnu.org/prep/standards/html_node/DESTDIR.html if let Some(destdir) = env::var_os("DESTDIR").map(PathBuf::from) { let without_destdir = path.clone(); path = destdir; // Custom.join() which ignores disk roots. for part in without_destdir.components() { if let Component::Normal(s) = part { path.push(s) } } } // The installation command is not executed from the current directory, but from a temporary // directory. To prevent relative paths from breaking this converts relative paths to absolute // paths. std::fs::canonicalize is not used as that requires the path to actually be present. if path.is_relative() { path = std::env::current_dir().expect("failed to get the current directory").join(path); assert!(path.is_absolute(), "could not make the path relative"); } sanitize_sh(&path) } macro_rules! install { (($sel:ident, $builder:ident, $_config:ident), $($name:ident, $path:expr, $default_cond:expr, only_hosts: $only_hosts:expr, $run_item:block $(, $c:ident)*;)+) => { $( #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct $name { pub compiler: Compiler, pub target: TargetSelection, } impl $name { #[allow(dead_code)] fn should_build(config: &Config) -> bool { config.extended && config.tools.as_ref() .map_or(true, |t| t.contains($path)) } } impl Step for $name { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = $only_hosts; $(const $c: bool = true;)* fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let $_config = &run.builder.config; run.path($path).default_condition($default_cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure($name { compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build), target: run.target, }); } fn run($sel, $builder: &Builder<'_>) { $run_item } })+ } } install!((self, builder, _config), Docs, "src/doc", _config.docs, only_hosts: false, { let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs"); install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); }; Std, "library/std", true, only_hosts: false, { for target in &builder.targets { // `expect` should be safe, only None when host!= build, but this // only runs when host == build let tarball = builder.ensure(dist::Std { compiler: self.compiler, target: *target }).expect("missing std"); install_sh(builder, "std", self.compiler.stage, Some(*target), &tarball); } }; Cargo, "cargo", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Cargo { compiler: self.compiler, target: self.target }) .expect("missing cargo"); install_sh(builder, "cargo", self.compiler.stage, Some(self.target), &tarball); }; Rls, "rls", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rls { compiler: self.compiler, target: self.target }) { install_sh(builder, "rls", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RLS stage{} ({})", self.compiler.stage, self.target), ); } }; RustAnalyzer, "rust-analyzer", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::RustAnalyzer { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-analyzer", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install rust-analyzer stage{} ({})", self.compiler.stage, self.target), ); } }; Clippy, "clippy", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Clippy { compiler: self.compiler, target: self.target }) .expect("missing clippy"); install_sh(builder, "clippy", self.compiler.stage, Some(self.target), &tarball); }; Miri, "miri", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Miri { compiler: self.compiler, target: self.target }) { install_sh(builder, "miri", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install miri stage{} ({})", self.compiler.stage, self.target), ); } }; Rustfmt, "rustfmt", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rustfmt { compiler: self.compiler, target: self.target }) { install_sh(builder, "rustfmt", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install Rustfmt stage{} ({})", self.compiler.stage, self.target), ); } }; RustDemangler, "rust-demangler", Self::should_build(_config), only_hosts: true, { // Note: Even though `should_build` may return true for `extended` default tools, // dist::RustDemangler may still return None, unless the target-dependent `profiler` config // is also true, or the `tools` array explicitly includes "rust-demangler". if let Some(tarball) = builder.ensure(dist::RustDemangler { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-demangler", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RustDemangler stage{} ({})", self.compiler.stage, self.target), ); } }; Analysis, "analysis", Self::should_build(_config), only_hosts: false, { // `expect` should be safe, only None with host!= build, but this // only uses the `build` compiler let tarball = builder.ensure(dist::Analysis { // Find the actual compiler (handling the full bootstrap option) which // produced the save-analysis data because that data isn't copied // through the sysroot uplifting. compiler: builder.compiler_for(builder.top_stage, builder.config.build, self.target), target: self.target }).expect("missing analysis"); install_sh(builder, "analysis", self.compiler.stage, Some(self.target), &tarball); }; Rustc, "src/librustc", true, only_hosts: true, { let tarball = builder.ensure(dist::Rustc { compiler: builder.compiler(builder.top_stage, self.target), }); install_sh(builder, "rustc", self.compiler.stage, Some(self.target), &tarball); }; ); #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Src { pub stage: u32, } impl Step for Src { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let config = &run.builder.config; let cond = config.extended && config.tools.as_ref().map_or(true, |t| t.contains("src")); run.path("src").default_condition(cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure(Src { stage: run.builder.top_stage }); } fn run(self, builder: &Builder<'_>) { let tarball = builder.ensure(dist::Src); install_sh(builder, "src", self.stage, None, &tarball); } }
{ config.as_ref().cloned().unwrap_or_else(|| PathBuf::from(default)) }
identifier_body
install.rs
//! Implementation of the install aspects of the compiler. //! //! This module is responsible for installing the standard library, //! compiler, and documentation. use std::env; use std::fs; use std::path::{Component, PathBuf}; use std::process::Command; use build_helper::t; use crate::dist::{self, sanitize_sh}; use crate::tarball::GeneratedTarball; use crate::Compiler; use crate::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::config::{Config, TargetSelection}; #[cfg(target_os = "illumos")] const SHELL: &str = "bash"; #[cfg(not(target_os = "illumos"))] const SHELL: &str = "sh"; fn
( builder: &Builder<'_>, package: &str, stage: u32, host: Option<TargetSelection>, tarball: &GeneratedTarball, ) { builder.info(&format!("Install {} stage{} ({:?})", package, stage, host)); let prefix = default_path(&builder.config.prefix, "/usr/local"); let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, "/etc")); let datadir = prefix.join(default_path(&builder.config.datadir, "share")); let docdir = prefix.join(default_path(&builder.config.docdir, "share/doc/rust")); let mandir = prefix.join(default_path(&builder.config.mandir, "share/man")); let libdir = prefix.join(default_path(&builder.config.libdir, "lib")); let bindir = prefix.join(&builder.config.bindir); // Default in config.rs let empty_dir = builder.out.join("tmp/empty_dir"); t!(fs::create_dir_all(&empty_dir)); let mut cmd = Command::new(SHELL); cmd.current_dir(&empty_dir) .arg(sanitize_sh(&tarball.decompressed_output().join("install.sh"))) .arg(format!("--prefix={}", prepare_dir(prefix))) .arg(format!("--sysconfdir={}", prepare_dir(sysconfdir))) .arg(format!("--datadir={}", prepare_dir(datadir))) .arg(format!("--docdir={}", prepare_dir(docdir))) .arg(format!("--bindir={}", prepare_dir(bindir))) .arg(format!("--libdir={}", prepare_dir(libdir))) .arg(format!("--mandir={}", prepare_dir(mandir))) .arg("--disable-ldconfig"); builder.run(&mut cmd); t!(fs::remove_dir_all(&empty_dir)); } fn default_path(config: &Option<PathBuf>, default: &str) -> PathBuf { config.as_ref().cloned().unwrap_or_else(|| PathBuf::from(default)) } fn prepare_dir(mut path: PathBuf) -> String { // The DESTDIR environment variable is a standard way to install software in a subdirectory // while keeping the original directory structure, even if the prefix or other directories // contain absolute paths. // // More information on the environment variable is available here: // https://www.gnu.org/prep/standards/html_node/DESTDIR.html if let Some(destdir) = env::var_os("DESTDIR").map(PathBuf::from) { let without_destdir = path.clone(); path = destdir; // Custom.join() which ignores disk roots. for part in without_destdir.components() { if let Component::Normal(s) = part { path.push(s) } } } // The installation command is not executed from the current directory, but from a temporary // directory. To prevent relative paths from breaking this converts relative paths to absolute // paths. std::fs::canonicalize is not used as that requires the path to actually be present. if path.is_relative() { path = std::env::current_dir().expect("failed to get the current directory").join(path); assert!(path.is_absolute(), "could not make the path relative"); } sanitize_sh(&path) } macro_rules! install { (($sel:ident, $builder:ident, $_config:ident), $($name:ident, $path:expr, $default_cond:expr, only_hosts: $only_hosts:expr, $run_item:block $(, $c:ident)*;)+) => { $( #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct $name { pub compiler: Compiler, pub target: TargetSelection, } impl $name { #[allow(dead_code)] fn should_build(config: &Config) -> bool { config.extended && config.tools.as_ref() .map_or(true, |t| t.contains($path)) } } impl Step for $name { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = $only_hosts; $(const $c: bool = true;)* fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let $_config = &run.builder.config; run.path($path).default_condition($default_cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure($name { compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build), target: run.target, }); } fn run($sel, $builder: &Builder<'_>) { $run_item } })+ } } install!((self, builder, _config), Docs, "src/doc", _config.docs, only_hosts: false, { let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs"); install_sh(builder, "docs", self.compiler.stage, Some(self.target), &tarball); }; Std, "library/std", true, only_hosts: false, { for target in &builder.targets { // `expect` should be safe, only None when host!= build, but this // only runs when host == build let tarball = builder.ensure(dist::Std { compiler: self.compiler, target: *target }).expect("missing std"); install_sh(builder, "std", self.compiler.stage, Some(*target), &tarball); } }; Cargo, "cargo", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Cargo { compiler: self.compiler, target: self.target }) .expect("missing cargo"); install_sh(builder, "cargo", self.compiler.stage, Some(self.target), &tarball); }; Rls, "rls", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rls { compiler: self.compiler, target: self.target }) { install_sh(builder, "rls", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RLS stage{} ({})", self.compiler.stage, self.target), ); } }; RustAnalyzer, "rust-analyzer", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::RustAnalyzer { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-analyzer", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install rust-analyzer stage{} ({})", self.compiler.stage, self.target), ); } }; Clippy, "clippy", Self::should_build(_config), only_hosts: true, { let tarball = builder .ensure(dist::Clippy { compiler: self.compiler, target: self.target }) .expect("missing clippy"); install_sh(builder, "clippy", self.compiler.stage, Some(self.target), &tarball); }; Miri, "miri", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Miri { compiler: self.compiler, target: self.target }) { install_sh(builder, "miri", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install miri stage{} ({})", self.compiler.stage, self.target), ); } }; Rustfmt, "rustfmt", Self::should_build(_config), only_hosts: true, { if let Some(tarball) = builder.ensure(dist::Rustfmt { compiler: self.compiler, target: self.target }) { install_sh(builder, "rustfmt", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install Rustfmt stage{} ({})", self.compiler.stage, self.target), ); } }; RustDemangler, "rust-demangler", Self::should_build(_config), only_hosts: true, { // Note: Even though `should_build` may return true for `extended` default tools, // dist::RustDemangler may still return None, unless the target-dependent `profiler` config // is also true, or the `tools` array explicitly includes "rust-demangler". if let Some(tarball) = builder.ensure(dist::RustDemangler { compiler: self.compiler, target: self.target }) { install_sh(builder, "rust-demangler", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( &format!("skipping Install RustDemangler stage{} ({})", self.compiler.stage, self.target), ); } }; Analysis, "analysis", Self::should_build(_config), only_hosts: false, { // `expect` should be safe, only None with host!= build, but this // only uses the `build` compiler let tarball = builder.ensure(dist::Analysis { // Find the actual compiler (handling the full bootstrap option) which // produced the save-analysis data because that data isn't copied // through the sysroot uplifting. compiler: builder.compiler_for(builder.top_stage, builder.config.build, self.target), target: self.target }).expect("missing analysis"); install_sh(builder, "analysis", self.compiler.stage, Some(self.target), &tarball); }; Rustc, "src/librustc", true, only_hosts: true, { let tarball = builder.ensure(dist::Rustc { compiler: builder.compiler(builder.top_stage, self.target), }); install_sh(builder, "rustc", self.compiler.stage, Some(self.target), &tarball); }; ); #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct Src { pub stage: u32, } impl Step for Src { type Output = (); const DEFAULT: bool = true; const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let config = &run.builder.config; let cond = config.extended && config.tools.as_ref().map_or(true, |t| t.contains("src")); run.path("src").default_condition(cond) } fn make_run(run: RunConfig<'_>) { run.builder.ensure(Src { stage: run.builder.top_stage }); } fn run(self, builder: &Builder<'_>) { let tarball = builder.ensure(dist::Src); install_sh(builder, "src", self.stage, None, &tarball); } }
install_sh
identifier_name
base_hanlder.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #![allow(deprecated,unused_assignments, unused_must_use)] use jsonrpc_types::error::Error; use jsonrpc_types::request::RpcRequest; use serde_json; use std::result; pub type RpcResult<T> = result::Result<T, Error>; pub trait BaseHandler { fn select_topic(method: &String) -> String { let topic = if method.starts_with("cita_send") { "jsonrpc.new_tx" } else if method.starts_with("cita") || method.starts_with("eth") { "jsonrpc.request" } else if method.starts_with("net_") { "jsonrpc.net" } else { "jsonrpc" } .to_string(); topic } fn into_json(body: String) -> Result<RpcRequest, Error> { let rpc: Result<RpcRequest, serde_json::Error> = serde_json::from_str(&body); match rpc { Err(_err_msg) => Err(Error::parse_error()), Ok(rpc) => Ok(rpc), } } } #[derive(Debug, Clone, PartialEq)] pub enum TransferType { ALL, HTTP, WEBSOCKET, } impl Default for TransferType { fn default() -> TransferType { TransferType::ALL } } #[cfg(test)] mod test { use super::BaseHandler; struct
{} impl BaseHandler for Handler {} #[test] fn test_get_topic() { assert_eq!(Handler::select_topic(&"net_work".to_string()), "jsonrpc.net".to_string()); assert_eq!(Handler::select_topic(&"cita_send".to_string()), "jsonrpc.new_tx".to_string()); assert_eq!(Handler::select_topic(&"cita".to_string()), "jsonrpc.request".to_string()); assert_eq!(Handler::select_topic(&"eth".to_string()), "jsonrpc.request".to_string()); assert_eq!(Handler::select_topic(&"123".to_string()), "jsonrpc".to_string()); } }
Handler
identifier_name
base_hanlder.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #![allow(deprecated,unused_assignments, unused_must_use)] use jsonrpc_types::error::Error; use jsonrpc_types::request::RpcRequest; use serde_json; use std::result; pub type RpcResult<T> = result::Result<T, Error>; pub trait BaseHandler { fn select_topic(method: &String) -> String { let topic = if method.starts_with("cita_send") { "jsonrpc.new_tx" } else if method.starts_with("cita") || method.starts_with("eth") { "jsonrpc.request" } else if method.starts_with("net_") { "jsonrpc.net" } else
.to_string(); topic } fn into_json(body: String) -> Result<RpcRequest, Error> { let rpc: Result<RpcRequest, serde_json::Error> = serde_json::from_str(&body); match rpc { Err(_err_msg) => Err(Error::parse_error()), Ok(rpc) => Ok(rpc), } } } #[derive(Debug, Clone, PartialEq)] pub enum TransferType { ALL, HTTP, WEBSOCKET, } impl Default for TransferType { fn default() -> TransferType { TransferType::ALL } } #[cfg(test)] mod test { use super::BaseHandler; struct Handler {} impl BaseHandler for Handler {} #[test] fn test_get_topic() { assert_eq!(Handler::select_topic(&"net_work".to_string()), "jsonrpc.net".to_string()); assert_eq!(Handler::select_topic(&"cita_send".to_string()), "jsonrpc.new_tx".to_string()); assert_eq!(Handler::select_topic(&"cita".to_string()), "jsonrpc.request".to_string()); assert_eq!(Handler::select_topic(&"eth".to_string()), "jsonrpc.request".to_string()); assert_eq!(Handler::select_topic(&"123".to_string()), "jsonrpc".to_string()); } }
{ "jsonrpc" }
conditional_block
base_hanlder.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #![allow(deprecated,unused_assignments, unused_must_use)] use jsonrpc_types::error::Error; use jsonrpc_types::request::RpcRequest; use serde_json; use std::result;
let topic = if method.starts_with("cita_send") { "jsonrpc.new_tx" } else if method.starts_with("cita") || method.starts_with("eth") { "jsonrpc.request" } else if method.starts_with("net_") { "jsonrpc.net" } else { "jsonrpc" } .to_string(); topic } fn into_json(body: String) -> Result<RpcRequest, Error> { let rpc: Result<RpcRequest, serde_json::Error> = serde_json::from_str(&body); match rpc { Err(_err_msg) => Err(Error::parse_error()), Ok(rpc) => Ok(rpc), } } } #[derive(Debug, Clone, PartialEq)] pub enum TransferType { ALL, HTTP, WEBSOCKET, } impl Default for TransferType { fn default() -> TransferType { TransferType::ALL } } #[cfg(test)] mod test { use super::BaseHandler; struct Handler {} impl BaseHandler for Handler {} #[test] fn test_get_topic() { assert_eq!(Handler::select_topic(&"net_work".to_string()), "jsonrpc.net".to_string()); assert_eq!(Handler::select_topic(&"cita_send".to_string()), "jsonrpc.new_tx".to_string()); assert_eq!(Handler::select_topic(&"cita".to_string()), "jsonrpc.request".to_string()); assert_eq!(Handler::select_topic(&"eth".to_string()), "jsonrpc.request".to_string()); assert_eq!(Handler::select_topic(&"123".to_string()), "jsonrpc".to_string()); } }
pub type RpcResult<T> = result::Result<T, Error>; pub trait BaseHandler { fn select_topic(method: &String) -> String {
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive, plugin)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![crate_name = "gfx_traits"] #![crate_type = "rlib"] #![deny(unsafe_code)] extern crate azure; extern crate euclid; extern crate heapsize; extern crate layers; extern crate msg; extern crate serde; extern crate util; pub mod color; mod paint_listener; pub use paint_listener::PaintListener; use azure::azure_hl::Color; use euclid::matrix::Matrix4; use euclid::rect::Rect; use msg::constellation_msg::{Failure, PipelineId}; use std::fmt::{self, Debug, Formatter}; /// Messages from the paint task to the constellation. #[derive(Deserialize, Serialize)] pub enum PaintMsg { Failure(Failure), } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LayerKind { NoTransform, HasTransform, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub enum LayerType { /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. AfterPseudoContent, } /// The scrolling policy of a layer. #[derive(Clone, PartialEq, Eq, Copy, Deserialize, Serialize, Debug, HeapSizeOf)] pub enum ScrollPolicy { /// These layers scroll when the parent receives a scrolling message. Scrollable, /// These layers do not scroll when the parent receives a scrolling message. FixedPosition, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub struct LayerId( /// The type of the layer. This serves to differentiate layers that share fragments. LayerType, /// The identifier for this layer's fragment, derived from the fragment memory address. usize, /// An index for identifying companion layers, synthesized to ensure that /// content on top of this layer's fragment has the proper rendering order. usize ); impl Debug for LayerId { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let LayerId(layer_type, id, companion) = *self; let type_string = match layer_type { LayerType::FragmentBody => "-FragmentBody", LayerType::OverflowScroll => "-OverflowScroll", LayerType::BeforePseudoContent => "-BeforePseudoContent", LayerType::AfterPseudoContent => "-AfterPseudoContent", }; write!(f, "{}{}-{}", id, type_string, companion) } } impl LayerId {
pub fn null() -> LayerId { LayerId(LayerType::FragmentBody, 0, 0) } pub fn new_of_type(layer_type: LayerType, fragment_id: usize) -> LayerId { LayerId(layer_type, fragment_id, 0) } pub fn companion_layer_id(&self) -> LayerId { let LayerId(layer_type, id, companion) = *self; LayerId(layer_type, id, companion + 1) } pub fn original(&self) -> LayerId { let LayerId(layer_type, id, _) = *self; LayerId(layer_type, id, 0) } } /// All layer-specific information that the painting task sends to the compositor other than the /// buffer contents of the layer itself. #[derive(Copy, Clone, HeapSizeOf)] pub struct LayerProperties { /// An opaque ID. This is usually the address of the flow and index of the box within it. pub id: LayerId, /// The id of the parent layer. pub parent_id: Option<LayerId>, /// The position and size of the layer in pixels. pub rect: Rect<f32>, /// The background color of the layer. pub background_color: Color, /// The scrolling policy of this layer. pub scroll_policy: ScrollPolicy, /// The transform for this layer pub transform: Matrix4, /// The perspective transform for this layer pub perspective: Matrix4, /// The subpage that this layer represents. If this is `Some`, this layer represents an /// iframe. pub subpage_pipeline_id: Option<PipelineId>, /// Whether this layer establishes a new 3d rendering context. pub establishes_3d_context: bool, /// Whether this layer scrolls its overflow area. pub scrolls_overflow_area: bool, } /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(PartialEq, Eq, Debug, Copy, Clone, PartialOrd, Ord, Deserialize, Serialize)] pub struct Epoch(pub u32); impl Epoch { pub fn next(&mut self) { self.0 += 1; } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub struct FrameTreeId(pub u32); impl FrameTreeId { pub fn next(&mut self) { self.0 += 1; } }
/// FIXME(#2011, pcwalton): This is unfortunate. Maybe remove this in the future.
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive, plugin)] #![plugin(heapsize_plugin, plugins, serde_macros)] #![crate_name = "gfx_traits"] #![crate_type = "rlib"] #![deny(unsafe_code)] extern crate azure; extern crate euclid; extern crate heapsize; extern crate layers; extern crate msg; extern crate serde; extern crate util; pub mod color; mod paint_listener; pub use paint_listener::PaintListener; use azure::azure_hl::Color; use euclid::matrix::Matrix4; use euclid::rect::Rect; use msg::constellation_msg::{Failure, PipelineId}; use std::fmt::{self, Debug, Formatter}; /// Messages from the paint task to the constellation. #[derive(Deserialize, Serialize)] pub enum PaintMsg { Failure(Failure), } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LayerKind { NoTransform, HasTransform, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub enum LayerType { /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. AfterPseudoContent, } /// The scrolling policy of a layer. #[derive(Clone, PartialEq, Eq, Copy, Deserialize, Serialize, Debug, HeapSizeOf)] pub enum ScrollPolicy { /// These layers scroll when the parent receives a scrolling message. Scrollable, /// These layers do not scroll when the parent receives a scrolling message. FixedPosition, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub struct LayerId( /// The type of the layer. This serves to differentiate layers that share fragments. LayerType, /// The identifier for this layer's fragment, derived from the fragment memory address. usize, /// An index for identifying companion layers, synthesized to ensure that /// content on top of this layer's fragment has the proper rendering order. usize ); impl Debug for LayerId { fn
(&self, f: &mut Formatter) -> fmt::Result { let LayerId(layer_type, id, companion) = *self; let type_string = match layer_type { LayerType::FragmentBody => "-FragmentBody", LayerType::OverflowScroll => "-OverflowScroll", LayerType::BeforePseudoContent => "-BeforePseudoContent", LayerType::AfterPseudoContent => "-AfterPseudoContent", }; write!(f, "{}{}-{}", id, type_string, companion) } } impl LayerId { /// FIXME(#2011, pcwalton): This is unfortunate. Maybe remove this in the future. pub fn null() -> LayerId { LayerId(LayerType::FragmentBody, 0, 0) } pub fn new_of_type(layer_type: LayerType, fragment_id: usize) -> LayerId { LayerId(layer_type, fragment_id, 0) } pub fn companion_layer_id(&self) -> LayerId { let LayerId(layer_type, id, companion) = *self; LayerId(layer_type, id, companion + 1) } pub fn original(&self) -> LayerId { let LayerId(layer_type, id, _) = *self; LayerId(layer_type, id, 0) } } /// All layer-specific information that the painting task sends to the compositor other than the /// buffer contents of the layer itself. #[derive(Copy, Clone, HeapSizeOf)] pub struct LayerProperties { /// An opaque ID. This is usually the address of the flow and index of the box within it. pub id: LayerId, /// The id of the parent layer. pub parent_id: Option<LayerId>, /// The position and size of the layer in pixels. pub rect: Rect<f32>, /// The background color of the layer. pub background_color: Color, /// The scrolling policy of this layer. pub scroll_policy: ScrollPolicy, /// The transform for this layer pub transform: Matrix4, /// The perspective transform for this layer pub perspective: Matrix4, /// The subpage that this layer represents. If this is `Some`, this layer represents an /// iframe. pub subpage_pipeline_id: Option<PipelineId>, /// Whether this layer establishes a new 3d rendering context. pub establishes_3d_context: bool, /// Whether this layer scrolls its overflow area. pub scrolls_overflow_area: bool, } /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(PartialEq, Eq, Debug, Copy, Clone, PartialOrd, Ord, Deserialize, Serialize)] pub struct Epoch(pub u32); impl Epoch { pub fn next(&mut self) { self.0 += 1; } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub struct FrameTreeId(pub u32); impl FrameTreeId { pub fn next(&mut self) { self.0 += 1; } }
fmt
identifier_name
issue-21974.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that (for now) we report an ambiguity error here, because // specific trait relationships are ignored for the purposes of trait // matching. This behavior should likely be improved such that this // test passes. See #21974 for more details. trait Foo { fn foo(self); } fn foo<'a,'b,T>(x: &'a T, y: &'b T) where &'a T : Foo, &'b T : Foo { x.foo(); //~ ERROR type annotations required y.foo(); } fn
() { }
main
identifier_name
issue-21974.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that (for now) we report an ambiguity error here, because // specific trait relationships are ignored for the purposes of trait // matching. This behavior should likely be improved such that this // test passes. See #21974 for more details. trait Foo { fn foo(self); } fn foo<'a,'b,T>(x: &'a T, y: &'b T) where &'a T : Foo,
y.foo(); } fn main() { }
&'b T : Foo { x.foo(); //~ ERROR type annotations required
random_line_split
issue-21974.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that (for now) we report an ambiguity error here, because // specific trait relationships are ignored for the purposes of trait // matching. This behavior should likely be improved such that this // test passes. See #21974 for more details. trait Foo { fn foo(self); } fn foo<'a,'b,T>(x: &'a T, y: &'b T) where &'a T : Foo, &'b T : Foo { x.foo(); //~ ERROR type annotations required y.foo(); } fn main()
{ }
identifier_body
custom.rs
use graphics::character::CharacterCache; use super::Kind; use super::Update; use ui::{Ui, UiId}; /// A trait to be implemented for Custom widget types. /// /// If you think your widget might be useful enough for conrod's official widget library, Feel free /// to submit a PR at https://github.com/PistonDevelopers/conrod. pub trait Custom: Clone + ::std::fmt::Debug { /// State to be stored within the `Ui`s widget cache. type State: State; /// After building the widget, we use this method to set its current state into the given `Ui`. /// The `Ui` will cache this state and use it for rendering the next time `ui.draw(graphics)` /// is called. fn set<C>(self, ui_id: UiId, ui: &mut Ui<C, Self>) where C: CharacterCache { let state = match *ui.get_widget_mut(ui_id, Kind::Custom(Self::State::init())) { ::widget::Kind::Custom(ref state) => state.clone(), _ => panic!("The Kind variant returned by Ui is different to that which \ was requested (Check that there are no UiId conflicts)."), }; let Update { new_state, xy, depth, element } = self.update(state, ui_id, ui); ui.update_widget(ui_id, Kind::Custom(new_state), xy, depth, Some(element)); } /// This is the method you have to implement! Your widget's previous state is given to you as a /// parameter and it is your job to construct and return an Update that will be used to update /// the widget's cached state. fn update<C>(mut self, prev: Self::State, ui_id: UiId, ui: &mut Ui<C, Self>) -> Update<Self::State> where C: CharacterCache; } /// The state to be stored within the `Ui`s widget cache. pub trait State: Clone + ::std::fmt::Debug { /// Whether or not the state matches some other state. fn matches(&self, other: &Self) -> bool; /// The inital state. fn init() -> Self; } impl Custom for () { type State = (); fn set<C>(self, _: UiId, _ui: &mut Ui<C, ()>) {} fn update<C>(self, _: (), _: UiId, _: &mut Ui<C, ()>) -> Update<()> {
Update { new_state: (), xy: [0.0, 0.0], depth: 0.0, element: ::elmesque::element::empty(), } } } impl State for () { fn matches(&self, _other: &()) -> bool { true } fn init() -> Self { () } }
random_line_split
custom.rs
use graphics::character::CharacterCache; use super::Kind; use super::Update; use ui::{Ui, UiId}; /// A trait to be implemented for Custom widget types. /// /// If you think your widget might be useful enough for conrod's official widget library, Feel free /// to submit a PR at https://github.com/PistonDevelopers/conrod. pub trait Custom: Clone + ::std::fmt::Debug { /// State to be stored within the `Ui`s widget cache. type State: State; /// After building the widget, we use this method to set its current state into the given `Ui`. /// The `Ui` will cache this state and use it for rendering the next time `ui.draw(graphics)` /// is called. fn
<C>(self, ui_id: UiId, ui: &mut Ui<C, Self>) where C: CharacterCache { let state = match *ui.get_widget_mut(ui_id, Kind::Custom(Self::State::init())) { ::widget::Kind::Custom(ref state) => state.clone(), _ => panic!("The Kind variant returned by Ui is different to that which \ was requested (Check that there are no UiId conflicts)."), }; let Update { new_state, xy, depth, element } = self.update(state, ui_id, ui); ui.update_widget(ui_id, Kind::Custom(new_state), xy, depth, Some(element)); } /// This is the method you have to implement! Your widget's previous state is given to you as a /// parameter and it is your job to construct and return an Update that will be used to update /// the widget's cached state. fn update<C>(mut self, prev: Self::State, ui_id: UiId, ui: &mut Ui<C, Self>) -> Update<Self::State> where C: CharacterCache; } /// The state to be stored within the `Ui`s widget cache. pub trait State: Clone + ::std::fmt::Debug { /// Whether or not the state matches some other state. fn matches(&self, other: &Self) -> bool; /// The inital state. fn init() -> Self; } impl Custom for () { type State = (); fn set<C>(self, _: UiId, _ui: &mut Ui<C, ()>) {} fn update<C>(self, _: (), _: UiId, _: &mut Ui<C, ()>) -> Update<()> { Update { new_state: (), xy: [0.0, 0.0], depth: 0.0, element: ::elmesque::element::empty(), } } } impl State for () { fn matches(&self, _other: &()) -> bool { true } fn init() -> Self { () } }
set
identifier_name
custom.rs
use graphics::character::CharacterCache; use super::Kind; use super::Update; use ui::{Ui, UiId}; /// A trait to be implemented for Custom widget types. /// /// If you think your widget might be useful enough for conrod's official widget library, Feel free /// to submit a PR at https://github.com/PistonDevelopers/conrod. pub trait Custom: Clone + ::std::fmt::Debug { /// State to be stored within the `Ui`s widget cache. type State: State; /// After building the widget, we use this method to set its current state into the given `Ui`. /// The `Ui` will cache this state and use it for rendering the next time `ui.draw(graphics)` /// is called. fn set<C>(self, ui_id: UiId, ui: &mut Ui<C, Self>) where C: CharacterCache
/// This is the method you have to implement! Your widget's previous state is given to you as a /// parameter and it is your job to construct and return an Update that will be used to update /// the widget's cached state. fn update<C>(mut self, prev: Self::State, ui_id: UiId, ui: &mut Ui<C, Self>) -> Update<Self::State> where C: CharacterCache; } /// The state to be stored within the `Ui`s widget cache. pub trait State: Clone + ::std::fmt::Debug { /// Whether or not the state matches some other state. fn matches(&self, other: &Self) -> bool; /// The inital state. fn init() -> Self; } impl Custom for () { type State = (); fn set<C>(self, _: UiId, _ui: &mut Ui<C, ()>) {} fn update<C>(self, _: (), _: UiId, _: &mut Ui<C, ()>) -> Update<()> { Update { new_state: (), xy: [0.0, 0.0], depth: 0.0, element: ::elmesque::element::empty(), } } } impl State for () { fn matches(&self, _other: &()) -> bool { true } fn init() -> Self { () } }
{ let state = match *ui.get_widget_mut(ui_id, Kind::Custom(Self::State::init())) { ::widget::Kind::Custom(ref state) => state.clone(), _ => panic!("The Kind variant returned by Ui is different to that which \ was requested (Check that there are no UiId conflicts)."), }; let Update { new_state, xy, depth, element } = self.update(state, ui_id, ui); ui.update_widget(ui_id, Kind::Custom(new_state), xy, depth, Some(element)); }
identifier_body
main.rs
extern crate clap; extern crate octavo; use octavo::digest::prelude::*; use std::fmt::Write; fn md5(input: &str, mut output: &mut [u8])
#[inline(always)] fn to_char(x: u8) -> char { if x < 10 { (x + '0' as u8) as char } else if x < 16 { (x - 10 + 'a' as u8) as char } else { panic!("bad hex value: {}", x) } } fn crack_password_1(door_id: &str) -> String { let mut password = String::new(); let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.len() >= 8 { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0 { password.push(to_char(buf[2] & 0xF)); } } password } fn crack_password_2(door_id: &str) -> String { let mut password = vec![None; 8]; let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.iter().all(|opt| opt.is_some()) { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if!(buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0) { continue; } let password_index = (buf[2] & 0xF) as usize; if password_index >= 8 { continue; } if password[password_index].is_some() { continue; } password[password_index] = Some(to_char((buf[3] & 0xF0) >> 4)); } password.into_iter().map(|opt| opt.unwrap()).collect() } fn parse_args() -> String { clap::App::new("Day 05") .author("Devon Hollowood") .arg(clap::Arg::with_name("door-id") .help("file to read rooms from. Reads from stdin otherwise") .takes_value(true) .required(true) ) .get_matches() .value_of("door-id") .unwrap() .to_owned() } fn main() { let door_id = parse_args(); println!("first password: {}", crack_password_1(&door_id)); println!("second password: {}", crack_password_2(&door_id)); }
{ let mut digest = Md5::default(); digest.update(input); digest.result(&mut output); }
identifier_body
main.rs
extern crate clap; extern crate octavo; use octavo::digest::prelude::*; use std::fmt::Write; fn md5(input: &str, mut output: &mut [u8]) { let mut digest = Md5::default(); digest.update(input); digest.result(&mut output); } #[inline(always)] fn to_char(x: u8) -> char { if x < 10
else if x < 16 { (x - 10 + 'a' as u8) as char } else { panic!("bad hex value: {}", x) } } fn crack_password_1(door_id: &str) -> String { let mut password = String::new(); let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.len() >= 8 { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0 { password.push(to_char(buf[2] & 0xF)); } } password } fn crack_password_2(door_id: &str) -> String { let mut password = vec![None; 8]; let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.iter().all(|opt| opt.is_some()) { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if!(buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0) { continue; } let password_index = (buf[2] & 0xF) as usize; if password_index >= 8 { continue; } if password[password_index].is_some() { continue; } password[password_index] = Some(to_char((buf[3] & 0xF0) >> 4)); } password.into_iter().map(|opt| opt.unwrap()).collect() } fn parse_args() -> String { clap::App::new("Day 05") .author("Devon Hollowood") .arg(clap::Arg::with_name("door-id") .help("file to read rooms from. Reads from stdin otherwise") .takes_value(true) .required(true) ) .get_matches() .value_of("door-id") .unwrap() .to_owned() } fn main() { let door_id = parse_args(); println!("first password: {}", crack_password_1(&door_id)); println!("second password: {}", crack_password_2(&door_id)); }
{ (x + '0' as u8) as char }
conditional_block
main.rs
extern crate clap; extern crate octavo; use octavo::digest::prelude::*; use std::fmt::Write; fn md5(input: &str, mut output: &mut [u8]) { let mut digest = Md5::default(); digest.update(input); digest.result(&mut output); } #[inline(always)] fn to_char(x: u8) -> char { if x < 10 { (x + '0' as u8) as char } else if x < 16 { (x - 10 + 'a' as u8) as char } else { panic!("bad hex value: {}", x) } } fn crack_password_1(door_id: &str) -> String { let mut password = String::new(); let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.len() >= 8 { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0 { password.push(to_char(buf[2] & 0xF)); } } password } fn
(door_id: &str) -> String { let mut password = vec![None; 8]; let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.iter().all(|opt| opt.is_some()) { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if!(buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0) { continue; } let password_index = (buf[2] & 0xF) as usize; if password_index >= 8 { continue; } if password[password_index].is_some() { continue; } password[password_index] = Some(to_char((buf[3] & 0xF0) >> 4)); } password.into_iter().map(|opt| opt.unwrap()).collect() } fn parse_args() -> String { clap::App::new("Day 05") .author("Devon Hollowood") .arg(clap::Arg::with_name("door-id") .help("file to read rooms from. Reads from stdin otherwise") .takes_value(true) .required(true) ) .get_matches() .value_of("door-id") .unwrap() .to_owned() } fn main() { let door_id = parse_args(); println!("first password: {}", crack_password_1(&door_id)); println!("second password: {}", crack_password_2(&door_id)); }
crack_password_2
identifier_name
main.rs
extern crate clap; extern crate octavo; use octavo::digest::prelude::*; use std::fmt::Write; fn md5(input: &str, mut output: &mut [u8]) { let mut digest = Md5::default(); digest.update(input); digest.result(&mut output); } #[inline(always)] fn to_char(x: u8) -> char { if x < 10 { (x + '0' as u8) as char } else if x < 16 { (x - 10 + 'a' as u8) as char } else { panic!("bad hex value: {}", x) } } fn crack_password_1(door_id: &str) -> String { let mut password = String::new(); let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.len() >= 8 { break; } password_buffer.truncate(door_id.len());
.expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0 { password.push(to_char(buf[2] & 0xF)); } } password } fn crack_password_2(door_id: &str) -> String { let mut password = vec![None; 8]; let mut password_buffer = door_id.to_owned(); password.reserve(format!("{}", u64::max_value()).len()); let mut buf = vec![0u8; Md5::output_bytes()]; for index in 0u64.. { if password.iter().all(|opt| opt.is_some()) { break; } password_buffer.truncate(door_id.len()); write!(password_buffer, "{}", index) .expect("Could not write to buffer"); md5(&password_buffer, &mut buf); if!(buf[0] == 0 && buf[1] == 0 && (buf[2] & 0xF0) == 0) { continue; } let password_index = (buf[2] & 0xF) as usize; if password_index >= 8 { continue; } if password[password_index].is_some() { continue; } password[password_index] = Some(to_char((buf[3] & 0xF0) >> 4)); } password.into_iter().map(|opt| opt.unwrap()).collect() } fn parse_args() -> String { clap::App::new("Day 05") .author("Devon Hollowood") .arg(clap::Arg::with_name("door-id") .help("file to read rooms from. Reads from stdin otherwise") .takes_value(true) .required(true) ) .get_matches() .value_of("door-id") .unwrap() .to_owned() } fn main() { let door_id = parse_args(); println!("first password: {}", crack_password_1(&door_id)); println!("second password: {}", crack_password_2(&door_id)); }
write!(password_buffer, "{}", index)
random_line_split
borrowck-uninit-field-access.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // revisions: ast mir //[mir]compile-flags: -Z borrowck=mir // Check that do not allow access to fields of uninitialized or moved // structs. #[derive(Default)] struct Point { x: isize, y: isize, } #[derive(Default)] struct Line { origin: Point, middle: Point, target: Point, } impl Line { fn consume(self) { } } fn
() { let mut a: Point; let _ = a.x + 1; //[ast]~ ERROR use of possibly uninitialized variable: `a.x` //[mir]~^ ERROR [E0381] let mut line1 = Line::default(); let _moved = line1.origin; let _ = line1.origin.x + 1; //[ast]~ ERROR use of moved value: `line1.origin.x` //[mir]~^ [E0382] let mut line2 = Line::default(); let _moved = (line2.origin, line2.middle); line2.consume(); //[ast]~ ERROR use of partially moved value: `line2` [E0382] //[mir]~^ [E0382] }
main
identifier_name
borrowck-uninit-field-access.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // revisions: ast mir //[mir]compile-flags: -Z borrowck=mir // Check that do not allow access to fields of uninitialized or moved // structs. #[derive(Default)]
y: isize, } #[derive(Default)] struct Line { origin: Point, middle: Point, target: Point, } impl Line { fn consume(self) { } } fn main() { let mut a: Point; let _ = a.x + 1; //[ast]~ ERROR use of possibly uninitialized variable: `a.x` //[mir]~^ ERROR [E0381] let mut line1 = Line::default(); let _moved = line1.origin; let _ = line1.origin.x + 1; //[ast]~ ERROR use of moved value: `line1.origin.x` //[mir]~^ [E0382] let mut line2 = Line::default(); let _moved = (line2.origin, line2.middle); line2.consume(); //[ast]~ ERROR use of partially moved value: `line2` [E0382] //[mir]~^ [E0382] }
struct Point { x: isize,
random_line_split
front_test.rs
use std::env; use wtest_basic::dependencies::*; #[ test ] #[ rustversion::stable ] fn trybuild_tests() { println!( "current_dir : {:?}", env::current_dir().unwrap() ); } #[ test ] #[ rustversion::nightly ] fn trybuild_tests() { println!( "current_dir : {:?}", env::current_dir().unwrap() ); let t = trybuild::TestCases::new(); t.compile_fail( "../../../rust/test/former/all/bad_attr.rs" ); t.compile_fail( "../../../rust/test/former/all/vector_without_parameter.rs" ); t.compile_fail( "../../../rust/test/former/all/hashmap_without_parameter.rs" ); }
mod basic_runtime { include!( "./all/basic_runtime.rs" ); } mod basic { include!( "./all/basic.rs" ); } mod conflict { include!( "./all/conflict.rs" ); } mod string_slice_runtime { include!( "./all/string_slice_runtime.rs" ); } mod string_slice { include!( "./all/string_slice.rs" ); } mod default_primitive { include!( "./all/default_primitive.rs" ); } mod default_container { include!( "./all/default_container.rs" ); } mod after { include!( "./all/after.rs" ); }
/* xxx : use mod_at */
random_line_split
front_test.rs
use std::env; use wtest_basic::dependencies::*; #[ test ] #[ rustversion::stable ] fn trybuild_tests() { println!( "current_dir : {:?}", env::current_dir().unwrap() ); } #[ test ] #[ rustversion::nightly ] fn
() { println!( "current_dir : {:?}", env::current_dir().unwrap() ); let t = trybuild::TestCases::new(); t.compile_fail( "../../../rust/test/former/all/bad_attr.rs" ); t.compile_fail( "../../../rust/test/former/all/vector_without_parameter.rs" ); t.compile_fail( "../../../rust/test/former/all/hashmap_without_parameter.rs" ); } /* xxx : use mod_at */ mod basic_runtime { include!( "./all/basic_runtime.rs" ); } mod basic { include!( "./all/basic.rs" ); } mod conflict { include!( "./all/conflict.rs" ); } mod string_slice_runtime { include!( "./all/string_slice_runtime.rs" ); } mod string_slice { include!( "./all/string_slice.rs" ); } mod default_primitive { include!( "./all/default_primitive.rs" ); } mod default_container { include!( "./all/default_container.rs" ); } mod after { include!( "./all/after.rs" ); }
trybuild_tests
identifier_name
front_test.rs
use std::env; use wtest_basic::dependencies::*; #[ test ] #[ rustversion::stable ] fn trybuild_tests()
#[ test ] #[ rustversion::nightly ] fn trybuild_tests() { println!( "current_dir : {:?}", env::current_dir().unwrap() ); let t = trybuild::TestCases::new(); t.compile_fail( "../../../rust/test/former/all/bad_attr.rs" ); t.compile_fail( "../../../rust/test/former/all/vector_without_parameter.rs" ); t.compile_fail( "../../../rust/test/former/all/hashmap_without_parameter.rs" ); } /* xxx : use mod_at */ mod basic_runtime { include!( "./all/basic_runtime.rs" ); } mod basic { include!( "./all/basic.rs" ); } mod conflict { include!( "./all/conflict.rs" ); } mod string_slice_runtime { include!( "./all/string_slice_runtime.rs" ); } mod string_slice { include!( "./all/string_slice.rs" ); } mod default_primitive { include!( "./all/default_primitive.rs" ); } mod default_container { include!( "./all/default_container.rs" ); } mod after { include!( "./all/after.rs" ); }
{ println!( "current_dir : {:?}", env::current_dir().unwrap() ); }
identifier_body
skip_client_extensions.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::util::CustomMetadataDirectives; use graphql_ir::Selection; use graphql_ir::{ Directive, FragmentDefinition, FragmentSpread, InlineFragment, LinkedField, Program, ScalarField, Transformed, Transformer, }; use interner::StringKey; /// Transform to skip IR nodes if they are client-defined extensions /// to the schema pub fn skip_client_extensions<'s>(program: &Program<'s>) -> Program<'s> { let mut transform = SkipClientExtensionsTransform::new(program); transform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipClientExtensionsTransform<'s> { custom_metadata_directives: CustomMetadataDirectives, program: &'s Program<'s>, } impl<'s> SkipClientExtensionsTransform<'s> { fn new(program: &'s Program<'s>) -> Self { Self { custom_metadata_directives: Default::default(), program, } } } impl<'s> SkipClientExtensionsTransform<'s> { fn is_client_directive(&self, name: StringKey) -> bool { // Return true if: // - directive is a custom internal directive used to hold // metadata in the IR // - or, directive is a client-defined directive, not present // in the server schema self.custom_metadata_directives .is_custom_metadata_directive(name) || self.program.schema().is_extension_directive(name) } } impl<'s> Transformer for SkipClientExtensionsTransform<'s> { const NAME: &'static str = "SkipClientExtensionsTransform"; const VISIT_ARGUMENTS: bool = false; const VISIT_DIRECTIVES: bool = true; fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { self.default_transform_fragment(fragment) } } fn transform_fragment_spread(&mut self, spread: &FragmentSpread) -> Transformed<Selection> { let fragment = self.program.fragment(spread.fragment.item).unwrap(); if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { Transformed::Keep } } fn transform_inline_fragment(&mut self, fragment: &InlineFragment) -> Transformed<Selection>
fn transform_linked_field(&mut self, field: &LinkedField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_linked_field(field) } } fn transform_scalar_field(&mut self, field: &ScalarField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_scalar_field(field) } } fn transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { if self.is_client_directive(directive.name.item) { Transformed::Delete } else { self.default_transform_directive(directive) } } }
{ if let Some(type_condition) = fragment.type_condition { if self.program.schema().is_extension_type(type_condition) { return Transformed::Delete; } } self.default_transform_inline_fragment(fragment) }
identifier_body
skip_client_extensions.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::util::CustomMetadataDirectives; use graphql_ir::Selection; use graphql_ir::{ Directive, FragmentDefinition, FragmentSpread, InlineFragment, LinkedField, Program, ScalarField, Transformed, Transformer, }; use interner::StringKey; /// Transform to skip IR nodes if they are client-defined extensions /// to the schema pub fn skip_client_extensions<'s>(program: &Program<'s>) -> Program<'s> { let mut transform = SkipClientExtensionsTransform::new(program); transform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipClientExtensionsTransform<'s> { custom_metadata_directives: CustomMetadataDirectives, program: &'s Program<'s>, } impl<'s> SkipClientExtensionsTransform<'s> { fn new(program: &'s Program<'s>) -> Self { Self { custom_metadata_directives: Default::default(), program, } } } impl<'s> SkipClientExtensionsTransform<'s> { fn is_client_directive(&self, name: StringKey) -> bool { // Return true if: // - directive is a custom internal directive used to hold // metadata in the IR // - or, directive is a client-defined directive, not present // in the server schema self.custom_metadata_directives .is_custom_metadata_directive(name) || self.program.schema().is_extension_directive(name) } } impl<'s> Transformer for SkipClientExtensionsTransform<'s> { const NAME: &'static str = "SkipClientExtensionsTransform"; const VISIT_ARGUMENTS: bool = false; const VISIT_DIRECTIVES: bool = true; fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { self.default_transform_fragment(fragment) } } fn transform_fragment_spread(&mut self, spread: &FragmentSpread) -> Transformed<Selection> { let fragment = self.program.fragment(spread.fragment.item).unwrap(); if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { Transformed::Keep } } fn transform_inline_fragment(&mut self, fragment: &InlineFragment) -> Transformed<Selection> { if let Some(type_condition) = fragment.type_condition { if self.program.schema().is_extension_type(type_condition) { return Transformed::Delete; } } self.default_transform_inline_fragment(fragment) } fn transform_linked_field(&mut self, field: &LinkedField) -> Transformed<Selection> {
.schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_linked_field(field) } } fn transform_scalar_field(&mut self, field: &ScalarField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_scalar_field(field) } } fn transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { if self.is_client_directive(directive.name.item) { Transformed::Delete } else { self.default_transform_directive(directive) } } }
if self .program
random_line_split
skip_client_extensions.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::util::CustomMetadataDirectives; use graphql_ir::Selection; use graphql_ir::{ Directive, FragmentDefinition, FragmentSpread, InlineFragment, LinkedField, Program, ScalarField, Transformed, Transformer, }; use interner::StringKey; /// Transform to skip IR nodes if they are client-defined extensions /// to the schema pub fn skip_client_extensions<'s>(program: &Program<'s>) -> Program<'s> { let mut transform = SkipClientExtensionsTransform::new(program); transform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipClientExtensionsTransform<'s> { custom_metadata_directives: CustomMetadataDirectives, program: &'s Program<'s>, } impl<'s> SkipClientExtensionsTransform<'s> { fn new(program: &'s Program<'s>) -> Self { Self { custom_metadata_directives: Default::default(), program, } } } impl<'s> SkipClientExtensionsTransform<'s> { fn is_client_directive(&self, name: StringKey) -> bool { // Return true if: // - directive is a custom internal directive used to hold // metadata in the IR // - or, directive is a client-defined directive, not present // in the server schema self.custom_metadata_directives .is_custom_metadata_directive(name) || self.program.schema().is_extension_directive(name) } } impl<'s> Transformer for SkipClientExtensionsTransform<'s> { const NAME: &'static str = "SkipClientExtensionsTransform"; const VISIT_ARGUMENTS: bool = false; const VISIT_DIRECTIVES: bool = true; fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else
} fn transform_fragment_spread(&mut self, spread: &FragmentSpread) -> Transformed<Selection> { let fragment = self.program.fragment(spread.fragment.item).unwrap(); if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { Transformed::Keep } } fn transform_inline_fragment(&mut self, fragment: &InlineFragment) -> Transformed<Selection> { if let Some(type_condition) = fragment.type_condition { if self.program.schema().is_extension_type(type_condition) { return Transformed::Delete; } } self.default_transform_inline_fragment(fragment) } fn transform_linked_field(&mut self, field: &LinkedField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_linked_field(field) } } fn transform_scalar_field(&mut self, field: &ScalarField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_scalar_field(field) } } fn transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { if self.is_client_directive(directive.name.item) { Transformed::Delete } else { self.default_transform_directive(directive) } } }
{ self.default_transform_fragment(fragment) }
conditional_block
skip_client_extensions.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::util::CustomMetadataDirectives; use graphql_ir::Selection; use graphql_ir::{ Directive, FragmentDefinition, FragmentSpread, InlineFragment, LinkedField, Program, ScalarField, Transformed, Transformer, }; use interner::StringKey; /// Transform to skip IR nodes if they are client-defined extensions /// to the schema pub fn skip_client_extensions<'s>(program: &Program<'s>) -> Program<'s> { let mut transform = SkipClientExtensionsTransform::new(program); transform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipClientExtensionsTransform<'s> { custom_metadata_directives: CustomMetadataDirectives, program: &'s Program<'s>, } impl<'s> SkipClientExtensionsTransform<'s> { fn new(program: &'s Program<'s>) -> Self { Self { custom_metadata_directives: Default::default(), program, } } } impl<'s> SkipClientExtensionsTransform<'s> { fn is_client_directive(&self, name: StringKey) -> bool { // Return true if: // - directive is a custom internal directive used to hold // metadata in the IR // - or, directive is a client-defined directive, not present // in the server schema self.custom_metadata_directives .is_custom_metadata_directive(name) || self.program.schema().is_extension_directive(name) } } impl<'s> Transformer for SkipClientExtensionsTransform<'s> { const NAME: &'static str = "SkipClientExtensionsTransform"; const VISIT_ARGUMENTS: bool = false; const VISIT_DIRECTIVES: bool = true; fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { self.default_transform_fragment(fragment) } } fn
(&mut self, spread: &FragmentSpread) -> Transformed<Selection> { let fragment = self.program.fragment(spread.fragment.item).unwrap(); if self .program .schema() .is_extension_type(fragment.type_condition) { Transformed::Delete } else { Transformed::Keep } } fn transform_inline_fragment(&mut self, fragment: &InlineFragment) -> Transformed<Selection> { if let Some(type_condition) = fragment.type_condition { if self.program.schema().is_extension_type(type_condition) { return Transformed::Delete; } } self.default_transform_inline_fragment(fragment) } fn transform_linked_field(&mut self, field: &LinkedField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_linked_field(field) } } fn transform_scalar_field(&mut self, field: &ScalarField) -> Transformed<Selection> { if self .program .schema() .field(field.definition.item) .is_extension { Transformed::Delete } else { self.default_transform_scalar_field(field) } } fn transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { if self.is_client_directive(directive.name.item) { Transformed::Delete } else { self.default_transform_directive(directive) } } }
transform_fragment_spread
identifier_name
mod.rs
pub mod mocknet_controller; pub mod bitcoin_regtest_controller; pub use self::mocknet_controller::{MocknetController}; pub use self::bitcoin_regtest_controller::{BitcoinRegtestController}; use super::operations::BurnchainOpSigner; use std::time::Instant; use stacks::burnchains::BurnchainStateTransition; use stacks::chainstate::burn::db::burndb::{BurnDB}; use stacks::chainstate::burn::{BlockSnapshot}; use stacks::chainstate::burn::operations::BlockstackOperationType; pub trait BurnchainController { fn start(&mut self) -> BurnchainTip; fn submit_operation(&mut self, operation: BlockstackOperationType, op_signer: &mut BurnchainOpSigner) -> bool; fn sync(&mut self) -> BurnchainTip; fn burndb_ref(&self) -> &BurnDB; fn burndb_mut(&mut self) -> &mut BurnDB; fn get_chain_tip(&mut self) -> BurnchainTip; #[cfg(test)] fn bootstrap_chain(&mut self, blocks_count: u64); } #[derive(Debug, Clone)] pub struct BurnchainTip { pub block_snapshot: BlockSnapshot, pub state_transition: BurnchainStateTransition, pub received_at: Instant, } impl BurnchainTip { pub fn get_winning_tx_index(&self) -> Option<u32> { let winning_tx_id = self.block_snapshot.winning_block_txid; let mut winning_tx_vtindex = None; for op in self.state_transition.accepted_ops.iter() { if let BlockstackOperationType::LeaderBlockCommit(op) = op
} winning_tx_vtindex } }
{ if op.txid == winning_tx_id { winning_tx_vtindex = Some(op.vtxindex) } }
conditional_block
mod.rs
pub mod mocknet_controller; pub mod bitcoin_regtest_controller; pub use self::mocknet_controller::{MocknetController}; pub use self::bitcoin_regtest_controller::{BitcoinRegtestController}; use super::operations::BurnchainOpSigner; use std::time::Instant; use stacks::burnchains::BurnchainStateTransition; use stacks::chainstate::burn::db::burndb::{BurnDB}; use stacks::chainstate::burn::{BlockSnapshot}; use stacks::chainstate::burn::operations::BlockstackOperationType; pub trait BurnchainController { fn start(&mut self) -> BurnchainTip; fn submit_operation(&mut self, operation: BlockstackOperationType, op_signer: &mut BurnchainOpSigner) -> bool; fn sync(&mut self) -> BurnchainTip; fn burndb_ref(&self) -> &BurnDB; fn burndb_mut(&mut self) -> &mut BurnDB; fn get_chain_tip(&mut self) -> BurnchainTip; #[cfg(test)] fn bootstrap_chain(&mut self, blocks_count: u64); } #[derive(Debug, Clone)] pub struct BurnchainTip { pub block_snapshot: BlockSnapshot, pub state_transition: BurnchainStateTransition, pub received_at: Instant, } impl BurnchainTip { pub fn
(&self) -> Option<u32> { let winning_tx_id = self.block_snapshot.winning_block_txid; let mut winning_tx_vtindex = None; for op in self.state_transition.accepted_ops.iter() { if let BlockstackOperationType::LeaderBlockCommit(op) = op { if op.txid == winning_tx_id { winning_tx_vtindex = Some(op.vtxindex) } } } winning_tx_vtindex } }
get_winning_tx_index
identifier_name
mod.rs
pub mod mocknet_controller; pub mod bitcoin_regtest_controller; pub use self::mocknet_controller::{MocknetController}; pub use self::bitcoin_regtest_controller::{BitcoinRegtestController}; use super::operations::BurnchainOpSigner; use std::time::Instant; use stacks::burnchains::BurnchainStateTransition; use stacks::chainstate::burn::db::burndb::{BurnDB}; use stacks::chainstate::burn::{BlockSnapshot}; use stacks::chainstate::burn::operations::BlockstackOperationType; pub trait BurnchainController { fn start(&mut self) -> BurnchainTip; fn submit_operation(&mut self, operation: BlockstackOperationType, op_signer: &mut BurnchainOpSigner) -> bool; fn sync(&mut self) -> BurnchainTip; fn burndb_ref(&self) -> &BurnDB; fn burndb_mut(&mut self) -> &mut BurnDB;
#[cfg(test)] fn bootstrap_chain(&mut self, blocks_count: u64); } #[derive(Debug, Clone)] pub struct BurnchainTip { pub block_snapshot: BlockSnapshot, pub state_transition: BurnchainStateTransition, pub received_at: Instant, } impl BurnchainTip { pub fn get_winning_tx_index(&self) -> Option<u32> { let winning_tx_id = self.block_snapshot.winning_block_txid; let mut winning_tx_vtindex = None; for op in self.state_transition.accepted_ops.iter() { if let BlockstackOperationType::LeaderBlockCommit(op) = op { if op.txid == winning_tx_id { winning_tx_vtindex = Some(op.vtxindex) } } } winning_tx_vtindex } }
fn get_chain_tip(&mut self) -> BurnchainTip;
random_line_split
bwt.rs
#![feature(test)] extern crate nucleic_acid; #[macro_use] extern crate lazy_static; extern crate test; extern crate rand; use nucleic_acid::{suffix_array, FMIndex}; use rand::Rng; use test::Bencher;
(0..1000).map(|_| bases[rng.gen_range(0, bases.len())]).collect() }; static ref QUERY: String = { let mut rng = rand::thread_rng(); let idx = rng.gen_range(0, DATA.len() - 100); String::from_utf8_lossy(&DATA[idx..idx + 100]).into_owned() }; } #[bench] fn bench_sort_rotations_1000_random_values(b: &mut Bencher) { b.iter(|| { let mut rotations = (0..DATA.len()).map(|i| &DATA[i..]).collect::<Vec<_>>(); rotations.sort(); }) } #[bench] fn bench_suffix_array_1000_random_values(b: &mut Bencher) { b.iter(|| { suffix_array(&DATA); }) } #[bench] fn bench_fm_index_1000_random_values_constructor(b: &mut Bencher) { b.iter(|| { FMIndex::new(&DATA); }) } #[bench] fn bench_fm_index_1000_random_values_get_100_chars(b: &mut Bencher) { let index = FMIndex::new(&DATA); b.iter(|| { index.search(&QUERY); }) }
lazy_static! { static ref DATA: Vec<u8> = { let mut rng = rand::thread_rng(); let bases = vec![65, 67, 71, 84];
random_line_split
bwt.rs
#![feature(test)] extern crate nucleic_acid; #[macro_use] extern crate lazy_static; extern crate test; extern crate rand; use nucleic_acid::{suffix_array, FMIndex}; use rand::Rng; use test::Bencher; lazy_static! { static ref DATA: Vec<u8> = { let mut rng = rand::thread_rng(); let bases = vec![65, 67, 71, 84]; (0..1000).map(|_| bases[rng.gen_range(0, bases.len())]).collect() }; static ref QUERY: String = { let mut rng = rand::thread_rng(); let idx = rng.gen_range(0, DATA.len() - 100); String::from_utf8_lossy(&DATA[idx..idx + 100]).into_owned() }; } #[bench] fn bench_sort_rotations_1000_random_values(b: &mut Bencher) { b.iter(|| { let mut rotations = (0..DATA.len()).map(|i| &DATA[i..]).collect::<Vec<_>>(); rotations.sort(); }) } #[bench] fn bench_suffix_array_1000_random_values(b: &mut Bencher) { b.iter(|| { suffix_array(&DATA); }) } #[bench] fn bench_fm_index_1000_random_values_constructor(b: &mut Bencher) { b.iter(|| { FMIndex::new(&DATA); }) } #[bench] fn bench_fm_index_1000_random_values_get_100_chars(b: &mut Bencher)
{ let index = FMIndex::new(&DATA); b.iter(|| { index.search(&QUERY); }) }
identifier_body
bwt.rs
#![feature(test)] extern crate nucleic_acid; #[macro_use] extern crate lazy_static; extern crate test; extern crate rand; use nucleic_acid::{suffix_array, FMIndex}; use rand::Rng; use test::Bencher; lazy_static! { static ref DATA: Vec<u8> = { let mut rng = rand::thread_rng(); let bases = vec![65, 67, 71, 84]; (0..1000).map(|_| bases[rng.gen_range(0, bases.len())]).collect() }; static ref QUERY: String = { let mut rng = rand::thread_rng(); let idx = rng.gen_range(0, DATA.len() - 100); String::from_utf8_lossy(&DATA[idx..idx + 100]).into_owned() }; } #[bench] fn bench_sort_rotations_1000_random_values(b: &mut Bencher) { b.iter(|| { let mut rotations = (0..DATA.len()).map(|i| &DATA[i..]).collect::<Vec<_>>(); rotations.sort(); }) } #[bench] fn bench_suffix_array_1000_random_values(b: &mut Bencher) { b.iter(|| { suffix_array(&DATA); }) } #[bench] fn
(b: &mut Bencher) { b.iter(|| { FMIndex::new(&DATA); }) } #[bench] fn bench_fm_index_1000_random_values_get_100_chars(b: &mut Bencher) { let index = FMIndex::new(&DATA); b.iter(|| { index.search(&QUERY); }) }
bench_fm_index_1000_random_values_constructor
identifier_name
focus.rs
use dces::prelude::Entity; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, }; /// Used to request keyboard focus on the window. #[derive(Event, Clone)] pub enum FocusEvent { RequestFocus(Entity), RemoveFocus(Entity), } pub type FocusHandlerFn = dyn Fn(&mut StatesContext, FocusEvent) -> bool +'static; /// Structure for the focus handling of an event #[derive(IntoHandler)] pub struct FocusEventHandler { /// A reference counted handler pub handler: Rc<FocusHandlerFn>, } impl EventHandler for FocusEventHandler { fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool
fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<FocusEvent>() } }
{ if let Ok(event) = event.downcast_ref::<FocusEvent>() { return (self.handler)(states, event.clone()); } false }
identifier_body
focus.rs
use dces::prelude::Entity; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, }; /// Used to request keyboard focus on the window. #[derive(Event, Clone)] pub enum
{ RequestFocus(Entity), RemoveFocus(Entity), } pub type FocusHandlerFn = dyn Fn(&mut StatesContext, FocusEvent) -> bool +'static; /// Structure for the focus handling of an event #[derive(IntoHandler)] pub struct FocusEventHandler { /// A reference counted handler pub handler: Rc<FocusHandlerFn>, } impl EventHandler for FocusEventHandler { fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool { if let Ok(event) = event.downcast_ref::<FocusEvent>() { return (self.handler)(states, event.clone()); } false } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<FocusEvent>() } }
FocusEvent
identifier_name
focus.rs
use dces::prelude::Entity; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, }; /// Used to request keyboard focus on the window. #[derive(Event, Clone)] pub enum FocusEvent { RequestFocus(Entity), RemoveFocus(Entity), } pub type FocusHandlerFn = dyn Fn(&mut StatesContext, FocusEvent) -> bool +'static; /// Structure for the focus handling of an event #[derive(IntoHandler)] pub struct FocusEventHandler { /// A reference counted handler pub handler: Rc<FocusHandlerFn>, } impl EventHandler for FocusEventHandler { fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool { if let Ok(event) = event.downcast_ref::<FocusEvent>()
false } fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<FocusEvent>() } }
{ return (self.handler)(states, event.clone()); }
conditional_block
focus.rs
use dces::prelude::Entity; use crate::{ prelude::*, proc_macros::{Event, IntoHandler}, }; /// Used to request keyboard focus on the window. #[derive(Event, Clone)] pub enum FocusEvent { RequestFocus(Entity), RemoveFocus(Entity), } pub type FocusHandlerFn = dyn Fn(&mut StatesContext, FocusEvent) -> bool +'static; /// Structure for the focus handling of an event #[derive(IntoHandler)] pub struct FocusEventHandler { /// A reference counted handler pub handler: Rc<FocusHandlerFn>, } impl EventHandler for FocusEventHandler { fn handle_event(&self, states: &mut StatesContext, event: &EventBox) -> bool { if let Ok(event) = event.downcast_ref::<FocusEvent>() { return (self.handler)(states, event.clone()); }
fn handles_event(&self, event: &EventBox) -> bool { event.is_type::<FocusEvent>() } }
false }
random_line_split
init.rs
extern crate num_complex; use consts; use kiss_fft; use mode; use opus_decoder; use std; #[no_mangle] pub extern "C" fn opus_decoder_create<'a>() -> *mut opus_decoder::OpusDecoder<'a> { let mut mode = mode::CeltMode { window: vec![0.0; consts::WINDOW_SIZE], fft0: kiss_fft::KissFft::new(0, vec![5, 4, 4, 3, 2]), fft3: kiss_fft::KissFft::new(3, vec![5, 4, 3]), twiddles: vec![Default::default(); consts::FRAME_SIZE / 2], v: vec![vec![None; 176]; 176], }; for i in 0..mode.window.len() { let theta = 0.5 * std::f32::consts::PI * (i as f32 + 0.5) / mode.window.len() as f32; mode.window[i] = (0.5 * std::f32::consts::PI * theta.sin().powi(2)).sin(); } for i in 0..mode.twiddles.len() { let theta = 2.0 * std::f32::consts::PI * (i as f32) / mode.twiddles.len() as f32; mode.twiddles[i] = num_complex::Complex::new(theta.cos(), -theta.sin()); } // The number of n-dimensional unit pulse vectors with k pulses. // // The number of combinations, with replacement, of n items, taken k at a time, when a sign bit is added to each item taken at least once. A table of values for n < 10 and k < 10 looks like: // // v[10][10] = { // {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // {1, 2, 2, 2, 2, 2, 2, 2, 2, 2}, // {1, 4, 8, 12, 16, 20, 24, 28, 32, 36}, // {1, 6, 18, 38, 66, 102, 146, 198, 258, 326}, // {1, 8, 32, 88, 192, 360, 608, 952, 1408, 1992}, // {1, 10, 50, 170, 450, 1002, 1970, 3530, 5890, 9290}, // {1, 12, 72, 292, 912, 2364, 5336, 10836, 20256, 35436}, // {1, 14, 98, 462, 1666, 4942, 12642, 28814, 59906, 115598}, // {1, 16, 128, 688, 2816, 9424, 27008, 68464, 157184, 332688}, // {1, 18, 162, 978, 4482, 16722, 53154, 148626, 374274, 864146} // }; mode.v[0][0] = Some(1); for k in 1..mode.v[0].len() { mode.v[0][k] = Some(0); } for n in 1..mode.v.len() { mode.v[n][0] = Some(1); for k in 1..mode.v[n].len() { match (mode.v[n - 1][k], mode.v[n][k - 1], mode.v[n - 1][k - 1]) { (Some(a), Some(b), Some(c)) =>
, _ => {}, } } } let opus_decoder = opus_decoder::OpusDecoder { mode: mode, range: 0, pitch: 0, gain: 0.0, tapset: 0, preemph_mem: [0.0; 2], decode_mem: [ vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2], vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2] ], bands: [0.0; consts::NUM_BANDS * 6], ec: Default::default(), }; let b = Box::new(opus_decoder); return Box::into_raw(b); }
{ let (temp, overflow) = a.overflowing_add(b); if !overflow { let (temp, overflow) = temp.overflowing_add(c); if !overflow { mode.v[n][k] = Some(temp); } } }
conditional_block
init.rs
extern crate num_complex; use consts; use kiss_fft; use mode; use opus_decoder; use std; #[no_mangle] pub extern "C" fn
<'a>() -> *mut opus_decoder::OpusDecoder<'a> { let mut mode = mode::CeltMode { window: vec![0.0; consts::WINDOW_SIZE], fft0: kiss_fft::KissFft::new(0, vec![5, 4, 4, 3, 2]), fft3: kiss_fft::KissFft::new(3, vec![5, 4, 3]), twiddles: vec![Default::default(); consts::FRAME_SIZE / 2], v: vec![vec![None; 176]; 176], }; for i in 0..mode.window.len() { let theta = 0.5 * std::f32::consts::PI * (i as f32 + 0.5) / mode.window.len() as f32; mode.window[i] = (0.5 * std::f32::consts::PI * theta.sin().powi(2)).sin(); } for i in 0..mode.twiddles.len() { let theta = 2.0 * std::f32::consts::PI * (i as f32) / mode.twiddles.len() as f32; mode.twiddles[i] = num_complex::Complex::new(theta.cos(), -theta.sin()); } // The number of n-dimensional unit pulse vectors with k pulses. // // The number of combinations, with replacement, of n items, taken k at a time, when a sign bit is added to each item taken at least once. A table of values for n < 10 and k < 10 looks like: // // v[10][10] = { // {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // {1, 2, 2, 2, 2, 2, 2, 2, 2, 2}, // {1, 4, 8, 12, 16, 20, 24, 28, 32, 36}, // {1, 6, 18, 38, 66, 102, 146, 198, 258, 326}, // {1, 8, 32, 88, 192, 360, 608, 952, 1408, 1992}, // {1, 10, 50, 170, 450, 1002, 1970, 3530, 5890, 9290}, // {1, 12, 72, 292, 912, 2364, 5336, 10836, 20256, 35436}, // {1, 14, 98, 462, 1666, 4942, 12642, 28814, 59906, 115598}, // {1, 16, 128, 688, 2816, 9424, 27008, 68464, 157184, 332688}, // {1, 18, 162, 978, 4482, 16722, 53154, 148626, 374274, 864146} // }; mode.v[0][0] = Some(1); for k in 1..mode.v[0].len() { mode.v[0][k] = Some(0); } for n in 1..mode.v.len() { mode.v[n][0] = Some(1); for k in 1..mode.v[n].len() { match (mode.v[n - 1][k], mode.v[n][k - 1], mode.v[n - 1][k - 1]) { (Some(a), Some(b), Some(c)) => { let (temp, overflow) = a.overflowing_add(b); if!overflow { let (temp, overflow) = temp.overflowing_add(c); if!overflow { mode.v[n][k] = Some(temp); } } }, _ => {}, } } } let opus_decoder = opus_decoder::OpusDecoder { mode: mode, range: 0, pitch: 0, gain: 0.0, tapset: 0, preemph_mem: [0.0; 2], decode_mem: [ vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2], vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2] ], bands: [0.0; consts::NUM_BANDS * 6], ec: Default::default(), }; let b = Box::new(opus_decoder); return Box::into_raw(b); }
opus_decoder_create
identifier_name
init.rs
extern crate num_complex; use consts; use kiss_fft; use mode; use opus_decoder; use std; #[no_mangle] pub extern "C" fn opus_decoder_create<'a>() -> *mut opus_decoder::OpusDecoder<'a> { let mut mode = mode::CeltMode { window: vec![0.0; consts::WINDOW_SIZE], fft0: kiss_fft::KissFft::new(0, vec![5, 4, 4, 3, 2]), fft3: kiss_fft::KissFft::new(3, vec![5, 4, 3]), twiddles: vec![Default::default(); consts::FRAME_SIZE / 2], v: vec![vec![None; 176]; 176], }; for i in 0..mode.window.len() { let theta = 0.5 * std::f32::consts::PI * (i as f32 + 0.5) / mode.window.len() as f32; mode.window[i] = (0.5 * std::f32::consts::PI * theta.sin().powi(2)).sin(); } for i in 0..mode.twiddles.len() { let theta = 2.0 * std::f32::consts::PI * (i as f32) / mode.twiddles.len() as f32; mode.twiddles[i] = num_complex::Complex::new(theta.cos(), -theta.sin()); } // The number of n-dimensional unit pulse vectors with k pulses. // // The number of combinations, with replacement, of n items, taken k at a time, when a sign bit is added to each item taken at least once. A table of values for n < 10 and k < 10 looks like: // // v[10][10] = { // {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // {1, 2, 2, 2, 2, 2, 2, 2, 2, 2}, // {1, 4, 8, 12, 16, 20, 24, 28, 32, 36}, // {1, 6, 18, 38, 66, 102, 146, 198, 258, 326}, // {1, 8, 32, 88, 192, 360, 608, 952, 1408, 1992}, // {1, 10, 50, 170, 450, 1002, 1970, 3530, 5890, 9290}, // {1, 12, 72, 292, 912, 2364, 5336, 10836, 20256, 35436}, // {1, 14, 98, 462, 1666, 4942, 12642, 28814, 59906, 115598}, // {1, 16, 128, 688, 2816, 9424, 27008, 68464, 157184, 332688}, // {1, 18, 162, 978, 4482, 16722, 53154, 148626, 374274, 864146} // }; mode.v[0][0] = Some(1); for k in 1..mode.v[0].len() { mode.v[0][k] = Some(0); } for n in 1..mode.v.len() { mode.v[n][0] = Some(1); for k in 1..mode.v[n].len() { match (mode.v[n - 1][k], mode.v[n][k - 1], mode.v[n - 1][k - 1]) { (Some(a), Some(b), Some(c)) => { let (temp, overflow) = a.overflowing_add(b); if!overflow { let (temp, overflow) = temp.overflowing_add(c); if!overflow { mode.v[n][k] = Some(temp); }
} let opus_decoder = opus_decoder::OpusDecoder { mode: mode, range: 0, pitch: 0, gain: 0.0, tapset: 0, preemph_mem: [0.0; 2], decode_mem: [ vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2], vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2] ], bands: [0.0; consts::NUM_BANDS * 6], ec: Default::default(), }; let b = Box::new(opus_decoder); return Box::into_raw(b); }
} }, _ => {}, } }
random_line_split
init.rs
extern crate num_complex; use consts; use kiss_fft; use mode; use opus_decoder; use std; #[no_mangle] pub extern "C" fn opus_decoder_create<'a>() -> *mut opus_decoder::OpusDecoder<'a>
// // The number of combinations, with replacement, of n items, taken k at a time, when a sign bit is added to each item taken at least once. A table of values for n < 10 and k < 10 looks like: // // v[10][10] = { // {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // {1, 2, 2, 2, 2, 2, 2, 2, 2, 2}, // {1, 4, 8, 12, 16, 20, 24, 28, 32, 36}, // {1, 6, 18, 38, 66, 102, 146, 198, 258, 326}, // {1, 8, 32, 88, 192, 360, 608, 952, 1408, 1992}, // {1, 10, 50, 170, 450, 1002, 1970, 3530, 5890, 9290}, // {1, 12, 72, 292, 912, 2364, 5336, 10836, 20256, 35436}, // {1, 14, 98, 462, 1666, 4942, 12642, 28814, 59906, 115598}, // {1, 16, 128, 688, 2816, 9424, 27008, 68464, 157184, 332688}, // {1, 18, 162, 978, 4482, 16722, 53154, 148626, 374274, 864146} // }; mode.v[0][0] = Some(1); for k in 1..mode.v[0].len() { mode.v[0][k] = Some(0); } for n in 1..mode.v.len() { mode.v[n][0] = Some(1); for k in 1..mode.v[n].len() { match (mode.v[n - 1][k], mode.v[n][k - 1], mode.v[n - 1][k - 1]) { (Some(a), Some(b), Some(c)) => { let (temp, overflow) = a.overflowing_add(b); if!overflow { let (temp, overflow) = temp.overflowing_add(c); if!overflow { mode.v[n][k] = Some(temp); } } }, _ => {}, } } } let opus_decoder = opus_decoder::OpusDecoder { mode: mode, range: 0, pitch: 0, gain: 0.0, tapset: 0, preemph_mem: [0.0; 2], decode_mem: [ vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2], vec![0.0; opus_decoder::BUFFER_SIZE + 120 / 2] ], bands: [0.0; consts::NUM_BANDS * 6], ec: Default::default(), }; let b = Box::new(opus_decoder); return Box::into_raw(b); }
{ let mut mode = mode::CeltMode { window: vec![0.0; consts::WINDOW_SIZE], fft0: kiss_fft::KissFft::new(0, vec![5, 4, 4, 3, 2]), fft3: kiss_fft::KissFft::new(3, vec![5, 4, 3]), twiddles: vec![Default::default(); consts::FRAME_SIZE / 2], v: vec![vec![None; 176]; 176], }; for i in 0..mode.window.len() { let theta = 0.5 * std::f32::consts::PI * (i as f32 + 0.5) / mode.window.len() as f32; mode.window[i] = (0.5 * std::f32::consts::PI * theta.sin().powi(2)).sin(); } for i in 0..mode.twiddles.len() { let theta = 2.0 * std::f32::consts::PI * (i as f32) / mode.twiddles.len() as f32; mode.twiddles[i] = num_complex::Complex::new(theta.cos(), -theta.sin()); } // The number of n-dimensional unit pulse vectors with k pulses.
identifier_body
capsule_capsule_manifold_generator.rs
use crate::math::Isometry; use crate::pipeline::narrow_phase::{ ContactDispatcher, ContactManifoldGenerator, ConvexPolyhedronConvexPolyhedronManifoldGenerator, }; use crate::query::{ContactManifold, ContactPrediction, ContactPreprocessor}; use crate::shape::{Capsule, Shape}; use na::{self, RealField}; /// Collision detector between a concave shape and another shape. pub struct CapsuleCapsuleManifoldGenerator<N: RealField> { // FIXME: use a dedicated segment-segment algorithm instead. sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator<N>, } impl<N: RealField> CapsuleCapsuleManifoldGenerator<N> { /// Creates a new collision detector between a concave shape and another shape. pub fn new() -> CapsuleCapsuleManifoldGenerator<N> { CapsuleCapsuleManifoldGenerator { sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator::new(), } } fn do_update( &mut self, dispatcher: &dyn ContactDispatcher<N>, m1: &Isometry<N>, g1: &Capsule<N>, proc1: Option<&dyn ContactPreprocessor<N>>, m2: &Isometry<N>, g2: &Capsule<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { let segment1 = g1.segment(); let segment2 = g2.segment(); let mut prediction = prediction.clone(); let new_linear_prediction = prediction.linear() + g1.radius + g2.radius; prediction.set_linear(new_linear_prediction); // Update all collisions self.sub_detector.generate_contacts( dispatcher, m1, &segment1, Some(&(proc1, &g1.contact_preprocessor())), m2, &segment2, Some(&(proc2, &g2.contact_preprocessor())), &prediction, manifold, ) } } impl<N: RealField> ContactManifoldGenerator<N> for CapsuleCapsuleManifoldGenerator<N> { fn
( &mut self, d: &dyn ContactDispatcher<N>, ma: &Isometry<N>, a: &dyn Shape<N>, proc1: Option<&dyn ContactPreprocessor<N>>, mb: &Isometry<N>, b: &dyn Shape<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { if let (Some(cs1), Some(cs2)) = (a.as_shape::<Capsule<N>>(), b.as_shape::<Capsule<N>>()) { self.do_update(d, ma, cs1, proc1, mb, cs2, proc2, prediction, manifold) } else { false } } }
generate_contacts
identifier_name
capsule_capsule_manifold_generator.rs
use crate::math::Isometry; use crate::pipeline::narrow_phase::{ ContactDispatcher, ContactManifoldGenerator, ConvexPolyhedronConvexPolyhedronManifoldGenerator, }; use crate::query::{ContactManifold, ContactPrediction, ContactPreprocessor}; use crate::shape::{Capsule, Shape}; use na::{self, RealField}; /// Collision detector between a concave shape and another shape. pub struct CapsuleCapsuleManifoldGenerator<N: RealField> { // FIXME: use a dedicated segment-segment algorithm instead. sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator<N>, } impl<N: RealField> CapsuleCapsuleManifoldGenerator<N> { /// Creates a new collision detector between a concave shape and another shape. pub fn new() -> CapsuleCapsuleManifoldGenerator<N> { CapsuleCapsuleManifoldGenerator { sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator::new(), } } fn do_update( &mut self, dispatcher: &dyn ContactDispatcher<N>, m1: &Isometry<N>, g1: &Capsule<N>, proc1: Option<&dyn ContactPreprocessor<N>>, m2: &Isometry<N>, g2: &Capsule<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { let segment1 = g1.segment(); let segment2 = g2.segment(); let mut prediction = prediction.clone(); let new_linear_prediction = prediction.linear() + g1.radius + g2.radius; prediction.set_linear(new_linear_prediction); // Update all collisions self.sub_detector.generate_contacts( dispatcher, m1, &segment1, Some(&(proc1, &g1.contact_preprocessor())), m2, &segment2, Some(&(proc2, &g2.contact_preprocessor())), &prediction, manifold, ) } } impl<N: RealField> ContactManifoldGenerator<N> for CapsuleCapsuleManifoldGenerator<N> { fn generate_contacts( &mut self, d: &dyn ContactDispatcher<N>, ma: &Isometry<N>, a: &dyn Shape<N>, proc1: Option<&dyn ContactPreprocessor<N>>, mb: &Isometry<N>, b: &dyn Shape<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { if let (Some(cs1), Some(cs2)) = (a.as_shape::<Capsule<N>>(), b.as_shape::<Capsule<N>>())
else { false } } }
{ self.do_update(d, ma, cs1, proc1, mb, cs2, proc2, prediction, manifold) }
conditional_block
capsule_capsule_manifold_generator.rs
use crate::math::Isometry; use crate::pipeline::narrow_phase::{ ContactDispatcher, ContactManifoldGenerator, ConvexPolyhedronConvexPolyhedronManifoldGenerator, }; use crate::query::{ContactManifold, ContactPrediction, ContactPreprocessor}; use crate::shape::{Capsule, Shape}; use na::{self, RealField};
/// Collision detector between a concave shape and another shape. pub struct CapsuleCapsuleManifoldGenerator<N: RealField> { // FIXME: use a dedicated segment-segment algorithm instead. sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator<N>, } impl<N: RealField> CapsuleCapsuleManifoldGenerator<N> { /// Creates a new collision detector between a concave shape and another shape. pub fn new() -> CapsuleCapsuleManifoldGenerator<N> { CapsuleCapsuleManifoldGenerator { sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator::new(), } } fn do_update( &mut self, dispatcher: &dyn ContactDispatcher<N>, m1: &Isometry<N>, g1: &Capsule<N>, proc1: Option<&dyn ContactPreprocessor<N>>, m2: &Isometry<N>, g2: &Capsule<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { let segment1 = g1.segment(); let segment2 = g2.segment(); let mut prediction = prediction.clone(); let new_linear_prediction = prediction.linear() + g1.radius + g2.radius; prediction.set_linear(new_linear_prediction); // Update all collisions self.sub_detector.generate_contacts( dispatcher, m1, &segment1, Some(&(proc1, &g1.contact_preprocessor())), m2, &segment2, Some(&(proc2, &g2.contact_preprocessor())), &prediction, manifold, ) } } impl<N: RealField> ContactManifoldGenerator<N> for CapsuleCapsuleManifoldGenerator<N> { fn generate_contacts( &mut self, d: &dyn ContactDispatcher<N>, ma: &Isometry<N>, a: &dyn Shape<N>, proc1: Option<&dyn ContactPreprocessor<N>>, mb: &Isometry<N>, b: &dyn Shape<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { if let (Some(cs1), Some(cs2)) = (a.as_shape::<Capsule<N>>(), b.as_shape::<Capsule<N>>()) { self.do_update(d, ma, cs1, proc1, mb, cs2, proc2, prediction, manifold) } else { false } } }
random_line_split
capsule_capsule_manifold_generator.rs
use crate::math::Isometry; use crate::pipeline::narrow_phase::{ ContactDispatcher, ContactManifoldGenerator, ConvexPolyhedronConvexPolyhedronManifoldGenerator, }; use crate::query::{ContactManifold, ContactPrediction, ContactPreprocessor}; use crate::shape::{Capsule, Shape}; use na::{self, RealField}; /// Collision detector between a concave shape and another shape. pub struct CapsuleCapsuleManifoldGenerator<N: RealField> { // FIXME: use a dedicated segment-segment algorithm instead. sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator<N>, } impl<N: RealField> CapsuleCapsuleManifoldGenerator<N> { /// Creates a new collision detector between a concave shape and another shape. pub fn new() -> CapsuleCapsuleManifoldGenerator<N>
fn do_update( &mut self, dispatcher: &dyn ContactDispatcher<N>, m1: &Isometry<N>, g1: &Capsule<N>, proc1: Option<&dyn ContactPreprocessor<N>>, m2: &Isometry<N>, g2: &Capsule<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { let segment1 = g1.segment(); let segment2 = g2.segment(); let mut prediction = prediction.clone(); let new_linear_prediction = prediction.linear() + g1.radius + g2.radius; prediction.set_linear(new_linear_prediction); // Update all collisions self.sub_detector.generate_contacts( dispatcher, m1, &segment1, Some(&(proc1, &g1.contact_preprocessor())), m2, &segment2, Some(&(proc2, &g2.contact_preprocessor())), &prediction, manifold, ) } } impl<N: RealField> ContactManifoldGenerator<N> for CapsuleCapsuleManifoldGenerator<N> { fn generate_contacts( &mut self, d: &dyn ContactDispatcher<N>, ma: &Isometry<N>, a: &dyn Shape<N>, proc1: Option<&dyn ContactPreprocessor<N>>, mb: &Isometry<N>, b: &dyn Shape<N>, proc2: Option<&dyn ContactPreprocessor<N>>, prediction: &ContactPrediction<N>, manifold: &mut ContactManifold<N>, ) -> bool { if let (Some(cs1), Some(cs2)) = (a.as_shape::<Capsule<N>>(), b.as_shape::<Capsule<N>>()) { self.do_update(d, ma, cs1, proc1, mb, cs2, proc2, prediction, manifold) } else { false } } }
{ CapsuleCapsuleManifoldGenerator { sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator::new(), } }
identifier_body
error.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use boxed::Box; use convert::Into; use error; use fmt; use marker::{Send, Sync}; use option::Option::{self, Some, None}; use result; use sys; /// A type for results generated by I/O related functions where the `Err` type /// is hard-wired to `io::Error`. /// /// This typedef is generally used to avoid writing out `io::Error` directly and /// is otherwise a direct mapping to `std::result::Result`. #[stable(feature = "rust1", since = "1.0.0")] pub type Result<T> = result::Result<T, Error>; /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and /// associated traits. /// /// Errors mostly originate from the underlying OS, but custom instances of /// `Error` can be created with crafted error messages and a particular value of /// `ErrorKind`. #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Error { repr: Repr, } #[derive(Debug)] enum Repr { Os(i32), Custom(Box<Custom>), } #[derive(Debug)] struct Custom { kind: ErrorKind, error: Box<error::Error+Send+Sync>, } /// A list specifying general categories of I/O error. /// /// This list is intended to grow over time and it is not recommended to /// exhaustively match against it. #[derive(Copy, PartialEq, Eq, Clone, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum ErrorKind { /// An entity was not found, often a file. #[stable(feature = "rust1", since = "1.0.0")] NotFound, /// The operation lacked the necessary privileges to complete. #[stable(feature = "rust1", since = "1.0.0")] PermissionDenied, /// The connection was refused by the remote server. #[stable(feature = "rust1", since = "1.0.0")] ConnectionRefused, /// The connection was reset by the remote server. #[stable(feature = "rust1", since = "1.0.0")] ConnectionReset, /// The connection was aborted (terminated) by the remote server. #[stable(feature = "rust1", since = "1.0.0")] ConnectionAborted, /// The network operation failed because it was not connected yet. #[stable(feature = "rust1", since = "1.0.0")] NotConnected, /// A socket address could not be bound because the address is already in /// use elsewhere. #[stable(feature = "rust1", since = "1.0.0")] AddrInUse, /// A nonexistent interface was requested or the requested address was not /// local. #[stable(feature = "rust1", since = "1.0.0")] AddrNotAvailable, /// The operation failed because a pipe was closed. #[stable(feature = "rust1", since = "1.0.0")] BrokenPipe, /// An entity already exists, often a file. #[stable(feature = "rust1", since = "1.0.0")] AlreadyExists, /// The operation needs to block to complete, but the blocking operation was /// requested to not occur. #[stable(feature = "rust1", since = "1.0.0")] WouldBlock, /// A parameter was incorrect. #[stable(feature = "rust1", since = "1.0.0")] InvalidInput, /// Data not valid for the operation were encountered. /// /// Unlike `InvalidInput`, this typically means that the operation /// parameters were valid, however the error was caused by malformed /// input data. #[stable(feature = "io_invalid_data", since = "1.2.0")] InvalidData, /// The I/O operation's timeout expired, causing it to be canceled. #[stable(feature = "rust1", since = "1.0.0")] TimedOut, /// An error returned when an operation could not be completed because a /// call to `write` returned `Ok(0)`. /// /// This typically means that an operation could only succeed if it wrote a /// particular number of bytes but only a smaller number of bytes could be /// written. #[stable(feature = "rust1", since = "1.0.0")] WriteZero, /// This operation was interrupted. /// /// Interrupted operations can typically be retried. #[stable(feature = "rust1", since = "1.0.0")] Interrupted, /// Any I/O error not part of this list. #[stable(feature = "rust1", since = "1.0.0")] Other,
/// Any I/O error not part of this list. #[unstable(feature = "io_error_internals", reason = "better expressed through extensible enums that this \ enum cannot be exhaustively matched against")] #[doc(hidden)] __Nonexhaustive, } impl Error { /// Creates a new I/O error from a known kind of error as well as an /// arbitrary error payload. /// /// This function is used to generically create I/O errors which do not /// originate from the OS itself. The `error` argument is an arbitrary /// payload which will be contained in this `Error`. /// /// # Examples /// /// ``` /// use std::io::{Error, ErrorKind}; /// /// // errors can be created from strings /// let custom_error = Error::new(ErrorKind::Other, "oh no!"); /// /// // errors can also be created from other errors /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new<E>(kind: ErrorKind, error: E) -> Error where E: Into<Box<error::Error+Send+Sync>> { Error { repr: Repr::Custom(Box::new(Custom { kind: kind, error: error.into(), })) } } /// Returns an error representing the last OS error which occurred. /// /// This function reads the value of `errno` for the target platform (e.g. /// `GetLastError` on Windows) and will return a corresponding instance of /// `Error` for the error code. #[stable(feature = "rust1", since = "1.0.0")] pub fn last_os_error() -> Error { Error::from_raw_os_error(sys::os::errno() as i32) } /// Creates a new instance of an `Error` from a particular OS error code. #[stable(feature = "rust1", since = "1.0.0")] pub fn from_raw_os_error(code: i32) -> Error { Error { repr: Repr::Os(code) } } /// Returns the OS error that this error represents (if any). /// /// If this `Error` was constructed via `last_os_error` or /// `from_raw_os_error`, then this function will return `Some`, otherwise /// it will return `None`. #[stable(feature = "rust1", since = "1.0.0")] pub fn raw_os_error(&self) -> Option<i32> { match self.repr { Repr::Os(i) => Some(i), Repr::Custom(..) => None, } } /// Returns a reference to the inner error wrapped by this error (if any). /// /// If this `Error` was constructed via `new` then this function will /// return `Some`, otherwise it will return `None`. #[unstable(feature = "io_error_inner", reason = "recently added and requires UFCS to downcast")] pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> { match self.repr { Repr::Os(..) => None, Repr::Custom(ref c) => Some(&*c.error), } } /// Returns a mutable reference to the inner error wrapped by this error /// (if any). /// /// If this `Error` was constructed via `new` then this function will /// return `Some`, otherwise it will return `None`. #[unstable(feature = "io_error_inner", reason = "recently added and requires UFCS to downcast")] pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> { match self.repr { Repr::Os(..) => None, Repr::Custom(ref mut c) => Some(&mut *c.error), } } /// Consumes the `Error`, returning its inner error (if any). /// /// If this `Error` was constructed via `new` then this function will /// return `Some`, otherwise it will return `None`. #[unstable(feature = "io_error_inner", reason = "recently added and requires UFCS to downcast")] pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> { match self.repr { Repr::Os(..) => None, Repr::Custom(c) => Some(c.error) } } /// Returns the corresponding `ErrorKind` for this error. #[stable(feature = "rust1", since = "1.0.0")] pub fn kind(&self) -> ErrorKind { match self.repr { Repr::Os(code) => sys::decode_error_kind(code), Repr::Custom(ref c) => c.kind, } } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.repr { Repr::Os(code) => { let detail = sys::os::error_string(code); write!(fmt, "{} (os error {})", detail, code) } Repr::Custom(ref c) => c.error.fmt(fmt), } } } #[stable(feature = "rust1", since = "1.0.0")] impl error::Error for Error { fn description(&self) -> &str { match self.repr { Repr::Os(..) => "os error", Repr::Custom(ref c) => c.error.description(), } } fn cause(&self) -> Option<&error::Error> { match self.repr { Repr::Os(..) => None, Repr::Custom(ref c) => c.error.cause(), } } } fn _assert_error_is_sync_send() { fn _is_sync_send<T: Sync+Send>() {} _is_sync_send::<Error>(); } #[cfg(test)] mod test { use prelude::v1::*; use super::{Error, ErrorKind}; use error; use error::Error as error_Error; use fmt; #[test] fn test_downcasting() { #[derive(Debug)] struct TestError; impl fmt::Display for TestError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl error::Error for TestError { fn description(&self) -> &str { "asdf" } } // we have to call all of these UFCS style right now since method // resolution won't implicitly drop the Send+Sync bounds let mut err = Error::new(ErrorKind::Other, TestError); assert!(error::Error::is::<TestError>(err.get_ref().unwrap())); assert_eq!("asdf", err.get_ref().unwrap().description()); assert!(error::Error::is::<TestError>(err.get_mut().unwrap())); let extracted = err.into_inner().unwrap(); error::Error::downcast::<TestError>(extracted).unwrap(); } }
random_line_split
error.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use boxed::Box; use convert::Into; use error; use fmt; use marker::{Send, Sync}; use option::Option::{self, Some, None}; use result; use sys; /// A type for results generated by I/O related functions where the `Err` type /// is hard-wired to `io::Error`. /// /// This typedef is generally used to avoid writing out `io::Error` directly and /// is otherwise a direct mapping to `std::result::Result`. #[stable(feature = "rust1", since = "1.0.0")] pub type Result<T> = result::Result<T, Error>; /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and /// associated traits. /// /// Errors mostly originate from the underlying OS, but custom instances of /// `Error` can be created with crafted error messages and a particular value of /// `ErrorKind`. #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Error { repr: Repr, } #[derive(Debug)] enum Repr { Os(i32), Custom(Box<Custom>), } #[derive(Debug)] struct Custom { kind: ErrorKind, error: Box<error::Error+Send+Sync>, } /// A list specifying general categories of I/O error. /// /// This list is intended to grow over time and it is not recommended to /// exhaustively match against it. #[derive(Copy, PartialEq, Eq, Clone, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum ErrorKind { /// An entity was not found, often a file. #[stable(feature = "rust1", since = "1.0.0")] NotFound, /// The operation lacked the necessary privileges to complete. #[stable(feature = "rust1", since = "1.0.0")] PermissionDenied, /// The connection was refused by the remote server. #[stable(feature = "rust1", since = "1.0.0")] ConnectionRefused, /// The connection was reset by the remote server. #[stable(feature = "rust1", since = "1.0.0")] ConnectionReset, /// The connection was aborted (terminated) by the remote server. #[stable(feature = "rust1", since = "1.0.0")] ConnectionAborted, /// The network operation failed because it was not connected yet. #[stable(feature = "rust1", since = "1.0.0")] NotConnected, /// A socket address could not be bound because the address is already in /// use elsewhere. #[stable(feature = "rust1", since = "1.0.0")] AddrInUse, /// A nonexistent interface was requested or the requested address was not /// local. #[stable(feature = "rust1", since = "1.0.0")] AddrNotAvailable, /// The operation failed because a pipe was closed. #[stable(feature = "rust1", since = "1.0.0")] BrokenPipe, /// An entity already exists, often a file. #[stable(feature = "rust1", since = "1.0.0")] AlreadyExists, /// The operation needs to block to complete, but the blocking operation was /// requested to not occur. #[stable(feature = "rust1", since = "1.0.0")] WouldBlock, /// A parameter was incorrect. #[stable(feature = "rust1", since = "1.0.0")] InvalidInput, /// Data not valid for the operation were encountered. /// /// Unlike `InvalidInput`, this typically means that the operation /// parameters were valid, however the error was caused by malformed /// input data. #[stable(feature = "io_invalid_data", since = "1.2.0")] InvalidData, /// The I/O operation's timeout expired, causing it to be canceled. #[stable(feature = "rust1", since = "1.0.0")] TimedOut, /// An error returned when an operation could not be completed because a /// call to `write` returned `Ok(0)`. /// /// This typically means that an operation could only succeed if it wrote a /// particular number of bytes but only a smaller number of bytes could be /// written. #[stable(feature = "rust1", since = "1.0.0")] WriteZero, /// This operation was interrupted. /// /// Interrupted operations can typically be retried. #[stable(feature = "rust1", since = "1.0.0")] Interrupted, /// Any I/O error not part of this list. #[stable(feature = "rust1", since = "1.0.0")] Other, /// Any I/O error not part of this list. #[unstable(feature = "io_error_internals", reason = "better expressed through extensible enums that this \ enum cannot be exhaustively matched against")] #[doc(hidden)] __Nonexhaustive, } impl Error { /// Creates a new I/O error from a known kind of error as well as an /// arbitrary error payload. /// /// This function is used to generically create I/O errors which do not /// originate from the OS itself. The `error` argument is an arbitrary /// payload which will be contained in this `Error`. /// /// # Examples /// /// ``` /// use std::io::{Error, ErrorKind}; /// /// // errors can be created from strings /// let custom_error = Error::new(ErrorKind::Other, "oh no!"); /// /// // errors can also be created from other errors /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new<E>(kind: ErrorKind, error: E) -> Error where E: Into<Box<error::Error+Send+Sync>> { Error { repr: Repr::Custom(Box::new(Custom { kind: kind, error: error.into(), })) } } /// Returns an error representing the last OS error which occurred. /// /// This function reads the value of `errno` for the target platform (e.g. /// `GetLastError` on Windows) and will return a corresponding instance of /// `Error` for the error code. #[stable(feature = "rust1", since = "1.0.0")] pub fn last_os_error() -> Error { Error::from_raw_os_error(sys::os::errno() as i32) } /// Creates a new instance of an `Error` from a particular OS error code. #[stable(feature = "rust1", since = "1.0.0")] pub fn from_raw_os_error(code: i32) -> Error { Error { repr: Repr::Os(code) } } /// Returns the OS error that this error represents (if any). /// /// If this `Error` was constructed via `last_os_error` or /// `from_raw_os_error`, then this function will return `Some`, otherwise /// it will return `None`. #[stable(feature = "rust1", since = "1.0.0")] pub fn raw_os_error(&self) -> Option<i32> { match self.repr { Repr::Os(i) => Some(i), Repr::Custom(..) => None, } } /// Returns a reference to the inner error wrapped by this error (if any). /// /// If this `Error` was constructed via `new` then this function will /// return `Some`, otherwise it will return `None`. #[unstable(feature = "io_error_inner", reason = "recently added and requires UFCS to downcast")] pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> { match self.repr { Repr::Os(..) => None, Repr::Custom(ref c) => Some(&*c.error), } } /// Returns a mutable reference to the inner error wrapped by this error /// (if any). /// /// If this `Error` was constructed via `new` then this function will /// return `Some`, otherwise it will return `None`. #[unstable(feature = "io_error_inner", reason = "recently added and requires UFCS to downcast")] pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> { match self.repr { Repr::Os(..) => None, Repr::Custom(ref mut c) => Some(&mut *c.error), } } /// Consumes the `Error`, returning its inner error (if any). /// /// If this `Error` was constructed via `new` then this function will /// return `Some`, otherwise it will return `None`. #[unstable(feature = "io_error_inner", reason = "recently added and requires UFCS to downcast")] pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> { match self.repr { Repr::Os(..) => None, Repr::Custom(c) => Some(c.error) } } /// Returns the corresponding `ErrorKind` for this error. #[stable(feature = "rust1", since = "1.0.0")] pub fn kind(&self) -> ErrorKind { match self.repr { Repr::Os(code) => sys::decode_error_kind(code), Repr::Custom(ref c) => c.kind, } } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.repr { Repr::Os(code) => { let detail = sys::os::error_string(code); write!(fmt, "{} (os error {})", detail, code) } Repr::Custom(ref c) => c.error.fmt(fmt), } } } #[stable(feature = "rust1", since = "1.0.0")] impl error::Error for Error { fn description(&self) -> &str { match self.repr { Repr::Os(..) => "os error", Repr::Custom(ref c) => c.error.description(), } } fn
(&self) -> Option<&error::Error> { match self.repr { Repr::Os(..) => None, Repr::Custom(ref c) => c.error.cause(), } } } fn _assert_error_is_sync_send() { fn _is_sync_send<T: Sync+Send>() {} _is_sync_send::<Error>(); } #[cfg(test)] mod test { use prelude::v1::*; use super::{Error, ErrorKind}; use error; use error::Error as error_Error; use fmt; #[test] fn test_downcasting() { #[derive(Debug)] struct TestError; impl fmt::Display for TestError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl error::Error for TestError { fn description(&self) -> &str { "asdf" } } // we have to call all of these UFCS style right now since method // resolution won't implicitly drop the Send+Sync bounds let mut err = Error::new(ErrorKind::Other, TestError); assert!(error::Error::is::<TestError>(err.get_ref().unwrap())); assert_eq!("asdf", err.get_ref().unwrap().description()); assert!(error::Error::is::<TestError>(err.get_mut().unwrap())); let extracted = err.into_inner().unwrap(); error::Error::downcast::<TestError>(extracted).unwrap(); } }
cause
identifier_name
delete_permission_response.rs
use crate::from_headers::*; use azure_sdk_core::errors::AzureError; use azure_sdk_core::session_token_from_headers; use http::HeaderMap; #[derive(Debug, Clone, PartialEq)] pub struct DeletePermissionResponse {
pub content_path: String, pub alt_content_path: String, } impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DeletePermissionResponse { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let headers = value.0; let _body = value.1; debug!("headers == {:#?}", headers); debug!("_body == {:#?}", std::str::from_utf8(_body)?); Ok(Self { charge: request_charge_from_headers(headers)?, activity_id: activity_id_from_headers(headers)?, session_token: session_token_from_headers(headers)?, content_path: content_path_from_headers(headers)?.to_owned(), alt_content_path: alt_content_path_from_headers(headers)?.to_owned(), }) } }
pub charge: f64, pub activity_id: uuid::Uuid, pub session_token: String,
random_line_split
delete_permission_response.rs
use crate::from_headers::*; use azure_sdk_core::errors::AzureError; use azure_sdk_core::session_token_from_headers; use http::HeaderMap; #[derive(Debug, Clone, PartialEq)] pub struct
{ pub charge: f64, pub activity_id: uuid::Uuid, pub session_token: String, pub content_path: String, pub alt_content_path: String, } impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DeletePermissionResponse { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let headers = value.0; let _body = value.1; debug!("headers == {:#?}", headers); debug!("_body == {:#?}", std::str::from_utf8(_body)?); Ok(Self { charge: request_charge_from_headers(headers)?, activity_id: activity_id_from_headers(headers)?, session_token: session_token_from_headers(headers)?, content_path: content_path_from_headers(headers)?.to_owned(), alt_content_path: alt_content_path_from_headers(headers)?.to_owned(), }) } }
DeletePermissionResponse
identifier_name
main.rs
// Copyright 2014 The Gfx-rs Developers. // // 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. #[macro_use] extern crate gfx; extern crate gfx_app; extern crate image; use std::io::Cursor; use std::time::Instant; pub use gfx::format::{Rgba8, Depth}; pub use gfx_app::ColorFormat; use gfx::Bundle; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, F: gfx::Factory<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = factory.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<R: gfx::Resources>{ bundle: Bundle<R, pipe::Data<R>>, cycles: [f32; 2], time_start: Instant, } impl<R: gfx::Resources> gfx_app::Application<R> for App<R> { fn new<F: gfx::Factory<R>>(factory: &mut F, backend: gfx_app::shade::Backend, window_targets: gfx_app::WindowTargets<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_app::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(factory, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(factory, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(factory, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = factory.create_sampler_linear(); let pso = factory.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: factory.create_constant_buffer(1), out: window_targets.color, }; App { bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>)
let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(encoder); } fn on_resize(&mut self, window_targets: gfx_app::WindowTargets<R>) { self.bundle.data.out = window_targets.color; } } pub fn main() { use gfx_app::Application; App::launch_simple("Flowmap example"); }
{ let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 - .5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0 { self.cycles[0] -= 1.0; } self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1];
identifier_body
main.rs
// Copyright 2014 The Gfx-rs Developers. // // 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. #[macro_use] extern crate gfx; extern crate gfx_app; extern crate image; use std::io::Cursor; use std::time::Instant; pub use gfx::format::{Rgba8, Depth}; pub use gfx_app::ColorFormat; use gfx::Bundle; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } }
Vertex { pos: p, uv: u, } } } fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, F: gfx::Factory<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = factory.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<R: gfx::Resources>{ bundle: Bundle<R, pipe::Data<R>>, cycles: [f32; 2], time_start: Instant, } impl<R: gfx::Resources> gfx_app::Application<R> for App<R> { fn new<F: gfx::Factory<R>>(factory: &mut F, backend: gfx_app::shade::Backend, window_targets: gfx_app::WindowTargets<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_app::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(factory, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(factory, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(factory, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = factory.create_sampler_linear(); let pso = factory.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: factory.create_constant_buffer(1), out: window_targets.color, }; App { bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0 { self.cycles[0] -= 1.0; } self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(encoder); } fn on_resize(&mut self, window_targets: gfx_app::WindowTargets<R>) { self.bundle.data.out = window_targets.color; } } pub fn main() { use gfx_app::Application; App::launch_simple("Flowmap example"); }
impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
random_line_split
main.rs
// Copyright 2014 The Gfx-rs Developers. // // 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. #[macro_use] extern crate gfx; extern crate gfx_app; extern crate image; use std::io::Cursor; use std::time::Instant; pub use gfx::format::{Rgba8, Depth}; pub use gfx_app::ColorFormat; use gfx::Bundle; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, F: gfx::Factory<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = factory.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct App<R: gfx::Resources>{ bundle: Bundle<R, pipe::Data<R>>, cycles: [f32; 2], time_start: Instant, } impl<R: gfx::Resources> gfx_app::Application<R> for App<R> { fn new<F: gfx::Factory<R>>(factory: &mut F, backend: gfx_app::shade::Backend, window_targets: gfx_app::WindowTargets<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_app::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(factory, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(factory, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(factory, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = factory.create_sampler_linear(); let pso = factory.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: factory.create_constant_buffer(1), out: window_targets.color, }; App { bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0
self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(encoder); } fn on_resize(&mut self, window_targets: gfx_app::WindowTargets<R>) { self.bundle.data.out = window_targets.color; } } pub fn main() { use gfx_app::Application; App::launch_simple("Flowmap example"); }
{ self.cycles[0] -= 1.0; }
conditional_block
main.rs
// Copyright 2014 The Gfx-rs Developers. // // 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. #[macro_use] extern crate gfx; extern crate gfx_app; extern crate image; use std::io::Cursor; use std::time::Instant; pub use gfx::format::{Rgba8, Depth}; pub use gfx_app::ColorFormat; use gfx::Bundle; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", uv: [f32; 2] = "a_Uv", } constant Locals { offsets: [f32; 2] = "u_Offsets", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), color: gfx::TextureSampler<[f32; 4]> = "t_Color", flow: gfx::TextureSampler<[f32; 4]> = "t_Flow", noise: gfx::TextureSampler<[f32; 4]> = "t_Noise", offset0: gfx::Global<f32> = "f_Offset0", offset1: gfx::Global<f32> = "f_Offset1", locals: gfx::ConstantBuffer<Locals> = "Locals", out: gfx::RenderTarget<ColorFormat> = "Target0", } } impl Vertex { fn new(p: [f32; 2], u: [f32; 2]) -> Vertex { Vertex { pos: p, uv: u, } } } fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where R: gfx::Resources, F: gfx::Factory<R> { use gfx::texture as t; let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba(); let (width, height) = img.dimensions(); let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single); let (_, view) = factory.create_texture_immutable_u8::<Rgba8>(kind, &[&img]).unwrap(); Ok(view) } struct
<R: gfx::Resources>{ bundle: Bundle<R, pipe::Data<R>>, cycles: [f32; 2], time_start: Instant, } impl<R: gfx::Resources> gfx_app::Application<R> for App<R> { fn new<F: gfx::Factory<R>>(factory: &mut F, backend: gfx_app::shade::Backend, window_targets: gfx_app::WindowTargets<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslv"), glsl_150: include_bytes!("shader/flowmap_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), msl_11: include_bytes!("shader/flowmap_vertex.metal"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_120: include_bytes!("shader/flowmap_120.glslf"), glsl_150: include_bytes!("shader/flowmap_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), msl_11: include_bytes!("shader/flowmap_frag.metal"), .. gfx_app::shade::Source::empty() }; let vertex_data = [ Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, -1.0], [1.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, -1.0], [0.0, 0.0]), Vertex::new([ 1.0, 1.0], [1.0, 1.0]), Vertex::new([-1.0, 1.0], [0.0, 1.0]), ]; let (vbuf, slice) = factory.create_vertex_buffer_with_slice(&vertex_data, ()); let water_texture = load_texture(factory, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(factory, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(factory, &include_bytes!("image/noise.png")[..]).unwrap(); let sampler = factory.create_sampler_linear(); let pso = factory.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); let data = pipe::Data { vbuf: vbuf, color: (water_texture, sampler.clone()), flow: (flow_texture, sampler.clone()), noise: (noise_texture, sampler.clone()), offset0: 0.0, offset1: 0.0, locals: factory.create_constant_buffer(1), out: window_targets.color, }; App { bundle: Bundle::new(slice, pso, data), cycles: [0.0, 0.5], time_start: Instant::now(), } } fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) { let delta = self.time_start.elapsed(); self.time_start = Instant::now(); let delta = delta.as_secs() as f32 + delta.subsec_nanos() as f32 / 1000_000_000.0; // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticable). // They start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)` self.cycles[0] += 0.25 * delta; if self.cycles[0] > 1.0 { self.cycles[0] -= 1.0; } self.cycles[1] += 0.25 * delta; if self.cycles[1] > 1.0 { self.cycles[1] -= 1.0; } self.bundle.data.offset0 = self.cycles[0]; self.bundle.data.offset1 = self.cycles[1]; let locals = Locals { offsets: self.cycles }; encoder.update_constant_buffer(&self.bundle.data.locals, &locals); encoder.clear(&self.bundle.data.out, [0.3, 0.3, 0.3, 1.0]); self.bundle.encode(encoder); } fn on_resize(&mut self, window_targets: gfx_app::WindowTargets<R>) { self.bundle.data.out = window_targets.color; } } pub fn main() { use gfx_app::Application; App::launch_simple("Flowmap example"); }
App
identifier_name
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries use back::svh::Svh; use metadata::decoder; use metadata::loader; use std::cell::RefCell; use std::c_vec::CVec; use std::rc::Rc; use collections::HashMap; use syntax::ast; use syntax::crateid::CrateId; use syntax::codemap::Span; use syntax::parse::token::IdentInterner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = HashMap<ast::CrateNum, ast::CrateNum>; pub enum MetadataBlob { MetadataVec(CVec<u8>), MetadataArchive(loader::ArchiveMetadata), } pub struct crate_metadata { pub name: ~str, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub span: Span, } #[deriving(Show, Eq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[deriving(Eq, FromPrimitive)] pub enum NativeLibaryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library } // Where a crate came from on the local filesystem. One of these two options // must be non-None. #[deriving(Eq, Clone)] pub struct CrateSource { pub dylib: Option<Path>, pub rlib: Option<Path>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>, extern_mod_crate_map: RefCell<extern_mod_crate_map>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(~str, NativeLibaryKind)>>, used_link_args: RefCell<Vec<~str>>, pub intr: Rc<IdentInterner>, } // Map from NodeId's of local extern crate statements to crate numbers type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>; impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(HashMap::new()), extern_mod_crate_map: RefCell::new(HashMap::new()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data(&self, i: |ast::CrateNum, &crate_metadata|) { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum) .map(|source| source.clone()) } pub fn
(&self) { } pub fn reset(&self) { self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); } // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<Path>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.as_slice().contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); for (_, &dep) in meta.cnum_map.iter() { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.as_mut_slice().reverse(); let ordering = ordering.as_slice(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone(), RequireStatic => src.rlib.clone(), })) .collect::<Vec<(ast::CrateNum, Option<Path>)>>(); libs.sort_by(|&(a, _), &(b, _)| { ordering.position_elem(&a).cmp(&ordering.position_elem(&b)) }); libs } pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(~str, NativeLibaryKind)> > { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ') { self.used_link_args.borrow_mut().push(s.to_owned()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x) } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn crate_id(&self) -> CrateId { decoder::get_crate_id(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { match *self { MetadataVec(ref vec) => vec.as_slice(), MetadataArchive(ref ar) => ar.as_slice(), } } }
dump_phase_syntax_crates
identifier_name
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries use back::svh::Svh; use metadata::decoder; use metadata::loader; use std::cell::RefCell; use std::c_vec::CVec; use std::rc::Rc; use collections::HashMap; use syntax::ast; use syntax::crateid::CrateId; use syntax::codemap::Span; use syntax::parse::token::IdentInterner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = HashMap<ast::CrateNum, ast::CrateNum>; pub enum MetadataBlob { MetadataVec(CVec<u8>), MetadataArchive(loader::ArchiveMetadata), } pub struct crate_metadata { pub name: ~str, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub span: Span, } #[deriving(Show, Eq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[deriving(Eq, FromPrimitive)] pub enum NativeLibaryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library }
// Where a crate came from on the local filesystem. One of these two options // must be non-None. #[deriving(Eq, Clone)] pub struct CrateSource { pub dylib: Option<Path>, pub rlib: Option<Path>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>, extern_mod_crate_map: RefCell<extern_mod_crate_map>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(~str, NativeLibaryKind)>>, used_link_args: RefCell<Vec<~str>>, pub intr: Rc<IdentInterner>, } // Map from NodeId's of local extern crate statements to crate numbers type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>; impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(HashMap::new()), extern_mod_crate_map: RefCell::new(HashMap::new()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data(&self, i: |ast::CrateNum, &crate_metadata|) { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum) .map(|source| source.clone()) } pub fn dump_phase_syntax_crates(&self) { } pub fn reset(&self) { self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); } // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<Path>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.as_slice().contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); for (_, &dep) in meta.cnum_map.iter() { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.as_mut_slice().reverse(); let ordering = ordering.as_slice(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone(), RequireStatic => src.rlib.clone(), })) .collect::<Vec<(ast::CrateNum, Option<Path>)>>(); libs.sort_by(|&(a, _), &(b, _)| { ordering.position_elem(&a).cmp(&ordering.position_elem(&b)) }); libs } pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(~str, NativeLibaryKind)> > { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ') { self.used_link_args.borrow_mut().push(s.to_owned()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x) } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn crate_id(&self) -> CrateId { decoder::get_crate_id(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { match *self { MetadataVec(ref vec) => vec.as_slice(), MetadataArchive(ref ar) => ar.as_slice(), } } }
random_line_split
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries use back::svh::Svh; use metadata::decoder; use metadata::loader; use std::cell::RefCell; use std::c_vec::CVec; use std::rc::Rc; use collections::HashMap; use syntax::ast; use syntax::crateid::CrateId; use syntax::codemap::Span; use syntax::parse::token::IdentInterner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = HashMap<ast::CrateNum, ast::CrateNum>; pub enum MetadataBlob { MetadataVec(CVec<u8>), MetadataArchive(loader::ArchiveMetadata), } pub struct crate_metadata { pub name: ~str, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub span: Span, } #[deriving(Show, Eq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } #[deriving(Eq, FromPrimitive)] pub enum NativeLibaryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library } // Where a crate came from on the local filesystem. One of these two options // must be non-None. #[deriving(Eq, Clone)] pub struct CrateSource { pub dylib: Option<Path>, pub rlib: Option<Path>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>, extern_mod_crate_map: RefCell<extern_mod_crate_map>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(~str, NativeLibaryKind)>>, used_link_args: RefCell<Vec<~str>>, pub intr: Rc<IdentInterner>, } // Map from NodeId's of local extern crate statements to crate numbers type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>; impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(HashMap::new()), extern_mod_crate_map: RefCell::new(HashMap::new()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data(&self, i: |ast::CrateNum, &crate_metadata|) { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum) .map(|source| source.clone()) } pub fn dump_phase_syntax_crates(&self) { } pub fn reset(&self) { self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); } // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<Path>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.as_slice().contains(&cnum)
let meta = cstore.get_crate_data(cnum); for (_, &dep) in meta.cnum_map.iter() { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.as_mut_slice().reverse(); let ordering = ordering.as_slice(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone(), RequireStatic => src.rlib.clone(), })) .collect::<Vec<(ast::CrateNum, Option<Path>)>>(); libs.sort_by(|&(a, _), &(b, _)| { ordering.position_elem(&a).cmp(&ordering.position_elem(&b)) }); libs } pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(~str, NativeLibaryKind)> > { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ') { self.used_link_args.borrow_mut().push(s.to_owned()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<~str> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x) } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn crate_id(&self) -> CrateId { decoder::get_crate_id(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { match *self { MetadataVec(ref vec) => vec.as_slice(), MetadataArchive(ref ar) => ar.as_slice(), } } }
{ return }
conditional_block
issue_16723_multiple_items_syntax_ext.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-stage1 // ignore-android // aux-build:issue_16723_multiple_items_syntax_ext.rs #![feature(phase)] #[phase(plugin)] extern crate issue_16723_multiple_items_syntax_ext; multiple_items!() impl Struct1 { fn foo() {} } impl Struct2 { fn
() {} } fn main() { Struct1::foo(); Struct2::foo(); println!("hallo"); }
foo
identifier_name
issue_16723_multiple_items_syntax_ext.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// ignore-stage1 // ignore-android // aux-build:issue_16723_multiple_items_syntax_ext.rs #![feature(phase)] #[phase(plugin)] extern crate issue_16723_multiple_items_syntax_ext; multiple_items!() impl Struct1 { fn foo() {} } impl Struct2 { fn foo() {} } fn main() { Struct1::foo(); Struct2::foo(); println!("hallo"); }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
issue_16723_multiple_items_syntax_ext.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-stage1 // ignore-android // aux-build:issue_16723_multiple_items_syntax_ext.rs #![feature(phase)] #[phase(plugin)] extern crate issue_16723_multiple_items_syntax_ext; multiple_items!() impl Struct1 { fn foo() {} } impl Struct2 { fn foo() {} } fn main()
{ Struct1::foo(); Struct2::foo(); println!("hallo"); }
identifier_body
design_pattern-command.rs
//! Example of design pattern inspired from Head First Design Patterns //! //! Tested with rust-1.41.1-nightly //! //! @author Eliovir <http://github.com/~eliovir> //! //! @license MIT license <http://www.opensource.org/licenses/mit-license.php> //! //! @since 2014-04-20 //! Each action is encapsulated into a struct with the trait Command //! where only the method `execute()` is run. trait Command { fn execute(&self); } // Use a Null struct to initialize the remote control. struct NullCommand; impl NullCommand { fn new() -> NullCommand { NullCommand } } impl Command for NullCommand { fn execute(&self) { println!("Nothing to do!"); } } // The object to handle: a light #[derive(Copy, Clone)] struct Light; impl Light { fn new() -> Light { Light } fn on(&self) { println!("Light is on"); } fn off(&self) { println!("Light is off"); } } // The first command on the object: light on struct LightOnCommand { light: Light, } impl LightOnCommand { fn new(light: Light) -> LightOnCommand { LightOnCommand { light } } } impl Command for LightOnCommand { fn execute(&self) { self.light.on();
} } // The second command on the object: light off struct LightOffCommand { light: Light, } impl LightOffCommand { fn new(light: Light) -> LightOffCommand { LightOffCommand { light } } } impl Command for LightOffCommand { fn execute(&self) { self.light.off(); } } // The command will be launched by a remote control. struct SimpleRemoteControl<'a> { command: Box<dyn Command + 'a>, } impl<'a> SimpleRemoteControl<'a> { fn new() -> SimpleRemoteControl<'a> { SimpleRemoteControl { command: Box::new(NullCommand::new()) } } fn set_command(&mut self, cmd: Box<dyn Command + 'a>) { self.command = cmd; } fn button_was_pressed(&self) { self.command.execute(); } } fn main() { let mut remote = SimpleRemoteControl::new(); let light = Light::new(); let light_on = LightOnCommand::new(light); let light_off = LightOffCommand::new(light); remote.button_was_pressed(); remote.set_command(Box::new(light_on)); remote.button_was_pressed(); remote.set_command(Box::new(light_off)); remote.button_was_pressed(); }
random_line_split
design_pattern-command.rs
//! Example of design pattern inspired from Head First Design Patterns //! //! Tested with rust-1.41.1-nightly //! //! @author Eliovir <http://github.com/~eliovir> //! //! @license MIT license <http://www.opensource.org/licenses/mit-license.php> //! //! @since 2014-04-20 //! Each action is encapsulated into a struct with the trait Command //! where only the method `execute()` is run. trait Command { fn execute(&self); } // Use a Null struct to initialize the remote control. struct NullCommand; impl NullCommand { fn new() -> NullCommand { NullCommand } } impl Command for NullCommand { fn execute(&self) { println!("Nothing to do!"); } } // The object to handle: a light #[derive(Copy, Clone)] struct Light; impl Light { fn new() -> Light { Light } fn on(&self) { println!("Light is on"); } fn off(&self) { println!("Light is off"); } } // The first command on the object: light on struct LightOnCommand { light: Light, } impl LightOnCommand { fn new(light: Light) -> LightOnCommand { LightOnCommand { light } } } impl Command for LightOnCommand { fn execute(&self) { self.light.on(); } } // The second command on the object: light off struct LightOffCommand { light: Light, } impl LightOffCommand { fn new(light: Light) -> LightOffCommand { LightOffCommand { light } } } impl Command for LightOffCommand { fn
(&self) { self.light.off(); } } // The command will be launched by a remote control. struct SimpleRemoteControl<'a> { command: Box<dyn Command + 'a>, } impl<'a> SimpleRemoteControl<'a> { fn new() -> SimpleRemoteControl<'a> { SimpleRemoteControl { command: Box::new(NullCommand::new()) } } fn set_command(&mut self, cmd: Box<dyn Command + 'a>) { self.command = cmd; } fn button_was_pressed(&self) { self.command.execute(); } } fn main() { let mut remote = SimpleRemoteControl::new(); let light = Light::new(); let light_on = LightOnCommand::new(light); let light_off = LightOffCommand::new(light); remote.button_was_pressed(); remote.set_command(Box::new(light_on)); remote.button_was_pressed(); remote.set_command(Box::new(light_off)); remote.button_was_pressed(); }
execute
identifier_name
r3msg.rs
extern crate r3bar; extern crate i3ipc; use r3bar::r3ipc::{R3Msg}; use std::env; fn help() { println!("usage: msgtype <integer> msgtype number - see r3ipc documentation. payload [string] msg arguments if any."); } fn main() { let args: Vec<String> = env::args().collect(); let empty_payload = "".to_string(); match args.len() { // no arguments passed 1 => { help(); }, l @ 2...3 =>
, // all the other cases _ => { // show a help message help(); } } } fn send(msgtype: u32, payload: &str) { match R3Msg::new(None).unwrap().send_msg(msgtype, payload) { Ok(i3ipc::reply::Command{outcomes}) => println!("{:?}", outcomes), Err(e) => println!("{}", e) } }
{ let cmd = &args[1]; let payload; if l == 3 { payload = &args[2]; } else { payload = &empty_payload; } match cmd.parse::<u32>() { Ok(msgtype) => send(msgtype, payload), Err(_) => return help(), } }
conditional_block
r3msg.rs
extern crate r3bar; extern crate i3ipc; use r3bar::r3ipc::{R3Msg}; use std::env; fn help() { println!("usage: msgtype <integer> msgtype number - see r3ipc documentation. payload [string] msg arguments if any."); } fn main()
match cmd.parse::<u32>() { Ok(msgtype) => send(msgtype, payload), Err(_) => return help(), } }, // all the other cases _ => { // show a help message help(); } } } fn send(msgtype: u32, payload: &str) { match R3Msg::new(None).unwrap().send_msg(msgtype, payload) { Ok(i3ipc::reply::Command{outcomes}) => println!("{:?}", outcomes), Err(e) => println!("{}", e) } }
{ let args: Vec<String> = env::args().collect(); let empty_payload = "".to_string(); match args.len() { // no arguments passed 1 => { help(); }, l @ 2...3 => { let cmd = &args[1]; let payload; if l == 3 { payload = &args[2]; } else { payload = &empty_payload; }
identifier_body
r3msg.rs
extern crate r3bar; extern crate i3ipc; use r3bar::r3ipc::{R3Msg}; use std::env; fn
() { println!("usage: msgtype <integer> msgtype number - see r3ipc documentation. payload [string] msg arguments if any."); } fn main() { let args: Vec<String> = env::args().collect(); let empty_payload = "".to_string(); match args.len() { // no arguments passed 1 => { help(); }, l @ 2...3 => { let cmd = &args[1]; let payload; if l == 3 { payload = &args[2]; } else { payload = &empty_payload; } match cmd.parse::<u32>() { Ok(msgtype) => send(msgtype, payload), Err(_) => return help(), } }, // all the other cases _ => { // show a help message help(); } } } fn send(msgtype: u32, payload: &str) { match R3Msg::new(None).unwrap().send_msg(msgtype, payload) { Ok(i3ipc::reply::Command{outcomes}) => println!("{:?}", outcomes), Err(e) => println!("{}", e) } }
help
identifier_name
r3msg.rs
extern crate r3bar; extern crate i3ipc; use r3bar::r3ipc::{R3Msg}; use std::env; fn help() { println!("usage: msgtype <integer> msgtype number - see r3ipc documentation. payload [string] msg arguments if any."); }
let empty_payload = "".to_string(); match args.len() { // no arguments passed 1 => { help(); }, l @ 2...3 => { let cmd = &args[1]; let payload; if l == 3 { payload = &args[2]; } else { payload = &empty_payload; } match cmd.parse::<u32>() { Ok(msgtype) => send(msgtype, payload), Err(_) => return help(), } }, // all the other cases _ => { // show a help message help(); } } } fn send(msgtype: u32, payload: &str) { match R3Msg::new(None).unwrap().send_msg(msgtype, payload) { Ok(i3ipc::reply::Command{outcomes}) => println!("{:?}", outcomes), Err(e) => println!("{}", e) } }
fn main() { let args: Vec<String> = env::args().collect();
random_line_split
fmt.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Deprecated fmt! syntax extension use ast; use codemap::Span; use ext::base; use ext::build::AstBuilder; pub fn
(ecx: &mut base::ExtCtxt, sp: Span, _tts: &[ast::TokenTree]) -> ~base::MacResult { ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead"); ecx.parse_sess.span_diagnostic.span_note(sp, "see http://static.rust-lang.org/doc/master/std/fmt/index.html \ for documentation"); base::MacExpr::new(ecx.expr_uint(sp, 2)) }
expand_syntax_ext
identifier_name
fmt.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Deprecated fmt! syntax extension use ast; use codemap::Span; use ext::base; use ext::build::AstBuilder; pub fn expand_syntax_ext(ecx: &mut base::ExtCtxt, sp: Span, _tts: &[ast::TokenTree]) -> ~base::MacResult
{ ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead"); ecx.parse_sess.span_diagnostic.span_note(sp, "see http://static.rust-lang.org/doc/master/std/fmt/index.html \ for documentation"); base::MacExpr::new(ecx.expr_uint(sp, 2)) }
identifier_body
fmt.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// except according to those terms. /// Deprecated fmt! syntax extension use ast; use codemap::Span; use ext::base; use ext::build::AstBuilder; pub fn expand_syntax_ext(ecx: &mut base::ExtCtxt, sp: Span, _tts: &[ast::TokenTree]) -> ~base::MacResult { ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead"); ecx.parse_sess.span_diagnostic.span_note(sp, "see http://static.rust-lang.org/doc/master/std/fmt/index.html \ for documentation"); base::MacExpr::new(ecx.expr_uint(sp, 2)) }
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
gamepadlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::gamepad::Gamepad; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://www.w3.org/TR/gamepad/ #[dom_struct] pub struct GamepadList { reflector_: Reflector, list: DomRefCell<Vec<Dom<Gamepad>>>, } // TODO: support gamepad discovery #[allow(dead_code)] impl GamepadList { fn new_inherited(list: &[&Gamepad]) -> GamepadList { GamepadList { reflector_: Reflector::new(), list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()), } } pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> { reflect_dom_object(Box::new(GamepadList::new_inherited(list)), global) } pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>])
} impl GamepadListMethods for GamepadList { // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Length(&self) -> u32 { self.list.borrow().len() as u32 } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.list .borrow() .get(index as usize) .map(|gamepad| DomRoot::from_ref(&**gamepad)) } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.Item(index) } }
{ for gamepad in gamepads { if !self .list .borrow() .iter() .any(|g| g.gamepad_id() == gamepad.gamepad_id()) { self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1); } } }
identifier_body
gamepadlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::gamepad::Gamepad; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://www.w3.org/TR/gamepad/ #[dom_struct] pub struct GamepadList { reflector_: Reflector, list: DomRefCell<Vec<Dom<Gamepad>>>, } // TODO: support gamepad discovery #[allow(dead_code)] impl GamepadList { fn new_inherited(list: &[&Gamepad]) -> GamepadList { GamepadList { reflector_: Reflector::new(), list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()), } } pub fn
(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> { reflect_dom_object(Box::new(GamepadList::new_inherited(list)), global) } pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) { for gamepad in gamepads { if!self .list .borrow() .iter() .any(|g| g.gamepad_id() == gamepad.gamepad_id()) { self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1); } } } } impl GamepadListMethods for GamepadList { // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Length(&self) -> u32 { self.list.borrow().len() as u32 } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.list .borrow() .get(index as usize) .map(|gamepad| DomRoot::from_ref(&**gamepad)) } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.Item(index) } }
new
identifier_name
gamepadlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::gamepad::Gamepad; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://www.w3.org/TR/gamepad/ #[dom_struct] pub struct GamepadList { reflector_: Reflector, list: DomRefCell<Vec<Dom<Gamepad>>>, } // TODO: support gamepad discovery #[allow(dead_code)] impl GamepadList { fn new_inherited(list: &[&Gamepad]) -> GamepadList { GamepadList { reflector_: Reflector::new(), list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()), } } pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> { reflect_dom_object(Box::new(GamepadList::new_inherited(list)), global) } pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) { for gamepad in gamepads { if!self .list .borrow() .iter() .any(|g| g.gamepad_id() == gamepad.gamepad_id()) { self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1); } } } } impl GamepadListMethods for GamepadList {
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Length(&self) -> u32 { self.list.borrow().len() as u32 } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.list .borrow() .get(index as usize) .map(|gamepad| DomRoot::from_ref(&**gamepad)) } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.Item(index) } }
random_line_split
gamepadlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::gamepad::Gamepad; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://www.w3.org/TR/gamepad/ #[dom_struct] pub struct GamepadList { reflector_: Reflector, list: DomRefCell<Vec<Dom<Gamepad>>>, } // TODO: support gamepad discovery #[allow(dead_code)] impl GamepadList { fn new_inherited(list: &[&Gamepad]) -> GamepadList { GamepadList { reflector_: Reflector::new(), list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect()), } } pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> { reflect_dom_object(Box::new(GamepadList::new_inherited(list)), global) } pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) { for gamepad in gamepads { if!self .list .borrow() .iter() .any(|g| g.gamepad_id() == gamepad.gamepad_id())
} } } impl GamepadListMethods for GamepadList { // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Length(&self) -> u32 { self.list.borrow().len() as u32 } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.list .borrow() .get(index as usize) .map(|gamepad| DomRoot::from_ref(&**gamepad)) } // https://w3c.github.io/gamepad/#dom-navigator-getgamepads fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> { self.Item(index) } }
{ self.list.borrow_mut().push(Dom::from_ref(&*gamepad)); // Ensure that the gamepad has the correct index gamepad.update_index(self.list.borrow().len() as i32 - 1); }
conditional_block
bswap-const.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(core_intrinsics)] use std::intrinsics; const SWAPPED_U8: u8 = unsafe { intrinsics::bswap(0x12_u8) }; const SWAPPED_U16: u16 = unsafe { intrinsics::bswap(0x12_34_u16) }; const SWAPPED_I32: i32 = unsafe { intrinsics::bswap(0x12_34_56_78_i32) }; fn
() { assert_eq!(SWAPPED_U8, 0x12); assert_eq!(SWAPPED_U16, 0x34_12); assert_eq!(SWAPPED_I32, 0x78_56_34_12); }
main
identifier_name
bswap-const.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(core_intrinsics)] use std::intrinsics; const SWAPPED_U8: u8 = unsafe { intrinsics::bswap(0x12_u8) }; const SWAPPED_U16: u16 = unsafe { intrinsics::bswap(0x12_34_u16) }; const SWAPPED_I32: i32 = unsafe { intrinsics::bswap(0x12_34_56_78_i32) }; fn main()
{ assert_eq!(SWAPPED_U8, 0x12); assert_eq!(SWAPPED_U16, 0x34_12); assert_eq!(SWAPPED_I32, 0x78_56_34_12); }
identifier_body
bswap-const.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(core_intrinsics)] use std::intrinsics;
fn main() { assert_eq!(SWAPPED_U8, 0x12); assert_eq!(SWAPPED_U16, 0x34_12); assert_eq!(SWAPPED_I32, 0x78_56_34_12); }
const SWAPPED_U8: u8 = unsafe { intrinsics::bswap(0x12_u8) }; const SWAPPED_U16: u16 = unsafe { intrinsics::bswap(0x12_34_u16) }; const SWAPPED_I32: i32 = unsafe { intrinsics::bswap(0x12_34_56_78_i32) };
random_line_split
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; use core::default::Default; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold { self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; } } } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8])
} impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. /// /// # Examples /// /// ``` /// # #![feature(rand)] /// use std::rand::{Rng, SeedableRng, StdRng}; /// use std::rand::reseeding::{Reseeder, ReseedingRng}; /// /// struct TickTockReseeder { tick: bool } /// impl Reseeder<StdRng> for TickTockReseeder { /// fn reseed(&mut self, rng: &mut StdRng) { /// let val = if self.tick {0} else {1}; /// rng.reseed(&[val]); /// self.tick =!self.tick; /// } /// } /// fn main() { /// let rsdr = TickTockReseeder { tick: true }; /// /// let inner = StdRng::new().unwrap(); /// let mut rng = ReseedingRng::new(inner, 10, rsdr); /// /// // this will repeat, because it gets reseeded very regularly. /// let s: String = rng.gen_ascii_chars().take(100).collect(); /// println!("{}", s); /// } /// /// ``` pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use std::default::Default; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = repeat(0).take(FILL_BYTES_V_LEN).collect::<Vec<_>>(); ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64!= 0.0); } }
{ self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) }
identifier_body
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; use core::default::Default; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold { self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; } } } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. /// /// # Examples /// /// ``` /// # #![feature(rand)] /// use std::rand::{Rng, SeedableRng, StdRng}; /// use std::rand::reseeding::{Reseeder, ReseedingRng}; /// /// struct TickTockReseeder { tick: bool } /// impl Reseeder<StdRng> for TickTockReseeder { /// fn reseed(&mut self, rng: &mut StdRng) { /// let val = if self.tick {0} else {1}; /// rng.reseed(&[val]); /// self.tick =!self.tick; /// } /// } /// fn main() { /// let rsdr = TickTockReseeder { tick: true }; /// /// let inner = StdRng::new().unwrap(); /// let mut rng = ReseedingRng::new(inner, 10, rsdr); /// /// // this will repeat, because it gets reseeded very regularly. /// let s: String = rng.gen_ascii_chars().take(100).collect(); /// println!("{}", s); /// }
pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use std::default::Default; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = repeat(0).take(FILL_BYTES_V_LEN).collect::<Vec<_>>(); ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64!= 0.0); } }
/// /// ```
random_line_split
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; use core::default::Default; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold
} } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. /// /// # Examples /// /// ``` /// # #![feature(rand)] /// use std::rand::{Rng, SeedableRng, StdRng}; /// use std::rand::reseeding::{Reseeder, ReseedingRng}; /// /// struct TickTockReseeder { tick: bool } /// impl Reseeder<StdRng> for TickTockReseeder { /// fn reseed(&mut self, rng: &mut StdRng) { /// let val = if self.tick {0} else {1}; /// rng.reseed(&[val]); /// self.tick =!self.tick; /// } /// } /// fn main() { /// let rsdr = TickTockReseeder { tick: true }; /// /// let inner = StdRng::new().unwrap(); /// let mut rng = ReseedingRng::new(inner, 10, rsdr); /// /// // this will repeat, because it gets reseeded very regularly. /// let s: String = rng.gen_ascii_chars().take(100).collect(); /// println!("{}", s); /// } /// /// ``` pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use std::default::Default; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = repeat(0).take(FILL_BYTES_V_LEN).collect::<Vec<_>>(); ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64!= 0.0); } }
{ self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; }
conditional_block
reseeding.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around another RNG that reseeds it after it //! generates a certain number of random bytes. use core::prelude::*; use {Rng, SeedableRng}; use core::default::Default; /// How many bytes of entropy the underling RNG is allowed to generate /// before it is reseeded. const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct
<R, Rsdr> { rng: R, generation_threshold: usize, bytes_generated: usize, /// Controls the behaviour when reseeding the RNG. pub reseeder: Rsdr, } impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> { /// Create a new `ReseedingRng` with the given parameters. /// /// # Arguments /// /// * `rng`: the random number generator to use. /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG. /// * `reseeder`: the reseeding object to use. pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> { ReseedingRng { rng: rng, generation_threshold: generation_threshold, bytes_generated: 0, reseeder: reseeder } } /// Reseed the internal RNG if the number of bytes that have been /// generated exceed the threshold. pub fn reseed_if_necessary(&mut self) { if self.bytes_generated >= self.generation_threshold { self.reseeder.reseed(&mut self.rng); self.bytes_generated = 0; } } } impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> { fn next_u32(&mut self) -> u32 { self.reseed_if_necessary(); self.bytes_generated += 4; self.rng.next_u32() } fn next_u64(&mut self) -> u64 { self.reseed_if_necessary(); self.bytes_generated += 8; self.rng.next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.reseed_if_necessary(); self.bytes_generated += dest.len(); self.rng.fill_bytes(dest) } } impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default> SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> { fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) { self.rng.reseed(seed); self.reseeder = rsdr; self.bytes_generated = 0; } /// Create a new `ReseedingRng` from the given reseeder and /// seed. This uses a default value for `generation_threshold`. fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> { ReseedingRng { rng: SeedableRng::from_seed(seed), generation_threshold: DEFAULT_GENERATION_THRESHOLD, bytes_generated: 0, reseeder: rsdr } } } /// Something that can be used to reseed an RNG via `ReseedingRng`. /// /// # Examples /// /// ``` /// # #![feature(rand)] /// use std::rand::{Rng, SeedableRng, StdRng}; /// use std::rand::reseeding::{Reseeder, ReseedingRng}; /// /// struct TickTockReseeder { tick: bool } /// impl Reseeder<StdRng> for TickTockReseeder { /// fn reseed(&mut self, rng: &mut StdRng) { /// let val = if self.tick {0} else {1}; /// rng.reseed(&[val]); /// self.tick =!self.tick; /// } /// } /// fn main() { /// let rsdr = TickTockReseeder { tick: true }; /// /// let inner = StdRng::new().unwrap(); /// let mut rng = ReseedingRng::new(inner, 10, rsdr); /// /// // this will repeat, because it gets reseeded very regularly. /// let s: String = rng.gen_ascii_chars().take(100).collect(); /// println!("{}", s); /// } /// /// ``` pub trait Reseeder<R> { /// Reseed the given RNG. fn reseed(&mut self, rng: &mut R); } /// Reseed an RNG using a `Default` instance. This reseeds by /// replacing the RNG with the result of a `Default::default` call. #[derive(Copy, Clone)] pub struct ReseedWithDefault; impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault { fn reseed(&mut self, rng: &mut R) { *rng = Default::default(); } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for ReseedWithDefault { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> ReseedWithDefault { ReseedWithDefault } } #[cfg(test)] mod test { use std::prelude::v1::*; use core::iter::{order, repeat}; use super::{ReseedingRng, ReseedWithDefault}; use std::default::Default; use {SeedableRng, Rng}; struct Counter { i: u32 } impl Rng for Counter { fn next_u32(&mut self) -> u32 { self.i += 1; // very random self.i - 1 } } impl Default for Counter { fn default() -> Counter { Counter { i: 0 } } } impl SeedableRng<u32> for Counter { fn reseed(&mut self, seed: u32) { self.i = seed; } fn from_seed(seed: u32) -> Counter { Counter { i: seed } } } type MyRng = ReseedingRng<Counter, ReseedWithDefault>; #[test] fn test_reseeding() { let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault); let mut i = 0; for _ in 0..1000 { assert_eq!(rs.next_u32(), i % 100); i += 1; } } #[test] fn test_rng_seeded() { let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2)); assert!(order::equals(ra.gen_ascii_chars().take(100), rb.gen_ascii_chars().take(100))); } #[test] fn test_rng_reseed() { let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3)); let string1: String = r.gen_ascii_chars().take(100).collect(); r.reseed((ReseedWithDefault, 3)); let string2: String = r.gen_ascii_chars().take(100).collect(); assert_eq!(string1, string2); } const FILL_BYTES_V_LEN: usize = 13579; #[test] fn test_rng_fill_bytes() { let mut v = repeat(0).take(FILL_BYTES_V_LEN).collect::<Vec<_>>(); ::test::rng().fill_bytes(&mut v); // Sanity test: if we've gotten here, `fill_bytes` has not infinitely // recursed. assert_eq!(v.len(), FILL_BYTES_V_LEN); // To test that `fill_bytes` actually did something, check that the // average of `v` is not 0. let mut sum = 0.0; for &x in &v { sum += x as f64; } assert!(sum / v.len() as f64!= 0.0); } }
ReseedingRng
identifier_name
first.rs
pub fn
(x: &mut [u32], up: bool) { if x.len() > 1 { let mid_point = x.len() / 2; sort(&mut x[..mid_point], true); sort(&mut x[mid_point..], false); sub_sort(x, up); } } fn sub_sort(x: &mut [u32], up: bool) { if x.len() > 1 { compare_and_swap(x, up); let mid_point = x.len() / 2; sub_sort(&mut x[..mid_point], up); sub_sort(&mut x[mid_point..], up); } } fn compare_and_swap(x: &mut [u32], up: bool) { let mid_point = x.len() / 2; for i in 0..mid_point { if (x[i] > x[mid_point + i]) == up { x.swap(i, mid_point + i); } } } #[cfg(test)] mod tests { use super::sort; #[test] fn sort_u32_ascending() { let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, true); assert_eq!(x, vec![4, 10, 11, 20, 21, 30, 110, 330]); } #[test] fn sort_u32_descending() { let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, false); assert_eq!(x, vec![330, 110, 30, 21, 20, 11, 10, 4]); } }
sort
identifier_name
first.rs
pub fn sort(x: &mut [u32], up: bool) { if x.len() > 1 { let mid_point = x.len() / 2; sort(&mut x[..mid_point], true); sort(&mut x[mid_point..], false); sub_sort(x, up); } } fn sub_sort(x: &mut [u32], up: bool) { if x.len() > 1 { compare_and_swap(x, up); let mid_point = x.len() / 2; sub_sort(&mut x[..mid_point], up); sub_sort(&mut x[mid_point..], up); } } fn compare_and_swap(x: &mut [u32], up: bool) { let mid_point = x.len() / 2; for i in 0..mid_point { if (x[i] > x[mid_point + i]) == up { x.swap(i, mid_point + i); } } } #[cfg(test)] mod tests { use super::sort; #[test] fn sort_u32_ascending()
#[test] fn sort_u32_descending() { let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, false); assert_eq!(x, vec![330, 110, 30, 21, 20, 11, 10, 4]); } }
{ let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, true); assert_eq!(x, vec![4, 10, 11, 20, 21, 30, 110, 330]); }
identifier_body
first.rs
pub fn sort(x: &mut [u32], up: bool) { if x.len() > 1 { let mid_point = x.len() / 2; sort(&mut x[..mid_point], true); sort(&mut x[mid_point..], false); sub_sort(x, up); } } fn sub_sort(x: &mut [u32], up: bool) { if x.len() > 1 { compare_and_swap(x, up); let mid_point = x.len() / 2; sub_sort(&mut x[..mid_point], up); sub_sort(&mut x[mid_point..], up); } } fn compare_and_swap(x: &mut [u32], up: bool) { let mid_point = x.len() / 2; for i in 0..mid_point { if (x[i] > x[mid_point + i]) == up { x.swap(i, mid_point + i); } } } #[cfg(test)] mod tests { use super::sort; #[test] fn sort_u32_ascending() {
} #[test] fn sort_u32_descending() { let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, false); assert_eq!(x, vec![330, 110, 30, 21, 20, 11, 10, 4]); } }
let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, true); assert_eq!(x, vec![4, 10, 11, 20, 21, 30, 110, 330]);
random_line_split
first.rs
pub fn sort(x: &mut [u32], up: bool) { if x.len() > 1 { let mid_point = x.len() / 2; sort(&mut x[..mid_point], true); sort(&mut x[mid_point..], false); sub_sort(x, up); } } fn sub_sort(x: &mut [u32], up: bool) { if x.len() > 1 { compare_and_swap(x, up); let mid_point = x.len() / 2; sub_sort(&mut x[..mid_point], up); sub_sort(&mut x[mid_point..], up); } } fn compare_and_swap(x: &mut [u32], up: bool) { let mid_point = x.len() / 2; for i in 0..mid_point { if (x[i] > x[mid_point + i]) == up
} } #[cfg(test)] mod tests { use super::sort; #[test] fn sort_u32_ascending() { let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, true); assert_eq!(x, vec![4, 10, 11, 20, 21, 30, 110, 330]); } #[test] fn sort_u32_descending() { let mut x = vec![10, 30, 11, 20, 4, 330, 21, 110]; sort(&mut x, false); assert_eq!(x, vec![330, 110, 30, 21, 20, 11, 10, 4]); } }
{ x.swap(i, mid_point + i); }
conditional_block
connected_pov.rs
use serde_derive::Serialize; use std::sync::{Arc, Mutex}; use std::sync::mpsc; use std::thread; use serde_json; use uuid::Uuid; use crate::lila; use crate::lila::Session; use super::LatencyRecorder; use super::Pov; use super::Color; use crate::game::socket; use crate::game::lila_message::LilaMessage; pub struct ConnectedPov { pub pov: Arc<Mutex<Pov>>, pub latency: Arc<Mutex<LatencyRecorder>>, send_tx: mpsc::Sender<String>, } impl ConnectedPov { pub fn new(session: &lila::Session, path: &str) -> ConnectedPov { let body = session.get(path); log::debug!("GET response: {}", body); let pov: Pov = serde_json::from_str(&body).unwrap(); let version = match pov.player.version { Some(v) => v as u64, None => 0 }; let socket_path = pov.url.socket.clone(); let pov_1 = Arc::new(Mutex::new(pov)); let (game_tx, game_rx) = mpsc::channel(); let (send_tx, send_rx) = mpsc::channel(); let send_rx = Arc::new(Mutex::new(send_rx)); let pov_2 = pov_1.clone(); let c = session.cookie.clone(); let sri = Uuid::new_v4(); log::debug!("SRI set to {}", sri); //let new_path = str::replace(path, "/v1", "/v2"); let url = Session::socket_url(&format!("{}?sri={}&version={}", socket_path, sri, version)); thread::spawn(move || { socket::Client::connect(&c, url.clone(), version, game_tx.clone(), send_rx); }); let latency_1 = Arc::new(Mutex::new(LatencyRecorder::new())); let latency_2 = latency_1.clone(); thread::spawn(move || loop { let obj = game_rx.recv().unwrap(); let mut pov = pov_2.lock().unwrap(); match LilaMessage::decode(&obj) { Some(LilaMessage::Pong(p)) => { latency_2.lock().unwrap().add(p.latency); }, Some(LilaMessage::Move(m)) => { pov.game.fen = m.fen; pov.game.turns = m.ply; pov.game.player = if m.ply % 2 == 0 { Color::white } else { Color::black }; if let Some(c) = m.clock { pov.clock = Some(c); }; }, Some(LilaMessage::Clock(c)) => { pov.clock = Some(c); }, //LilaMessage::End => tx_1.send(Message::close()).unwrap(), _ => () }; }); ConnectedPov { pov: pov_1, latency: latency_1, send_tx: send_tx, } } pub fn send_move(&mut self, from: String, to: String) { let move_packet = MovePacket { t: "move".into(), l: None, // TODO d: Dest { from: from, to: to, promotion: None, }, }; let message = serde_json::to_string(&move_packet).unwrap(); self.send_tx.send(message).unwrap(); } } #[derive(Serialize, Debug)] pub struct MovePacket { t: String, d: Dest, l: Option<i64>, } #[derive(Serialize, Debug)] pub struct
{ pub from: String, pub to: String, pub promotion: Option<String>, }
Dest
identifier_name
connected_pov.rs
use serde_derive::Serialize; use std::sync::{Arc, Mutex}; use std::sync::mpsc; use std::thread; use serde_json; use uuid::Uuid; use crate::lila; use crate::lila::Session; use super::LatencyRecorder; use super::Pov; use super::Color; use crate::game::socket; use crate::game::lila_message::LilaMessage; pub struct ConnectedPov { pub pov: Arc<Mutex<Pov>>, pub latency: Arc<Mutex<LatencyRecorder>>, send_tx: mpsc::Sender<String>, } impl ConnectedPov { pub fn new(session: &lila::Session, path: &str) -> ConnectedPov { let body = session.get(path); log::debug!("GET response: {}", body); let pov: Pov = serde_json::from_str(&body).unwrap(); let version = match pov.player.version { Some(v) => v as u64, None => 0 }; let socket_path = pov.url.socket.clone(); let pov_1 = Arc::new(Mutex::new(pov)); let (game_tx, game_rx) = mpsc::channel(); let (send_tx, send_rx) = mpsc::channel(); let send_rx = Arc::new(Mutex::new(send_rx)); let pov_2 = pov_1.clone(); let c = session.cookie.clone(); let sri = Uuid::new_v4(); log::debug!("SRI set to {}", sri); //let new_path = str::replace(path, "/v1", "/v2"); let url = Session::socket_url(&format!("{}?sri={}&version={}", socket_path, sri, version)); thread::spawn(move || { socket::Client::connect(&c, url.clone(), version, game_tx.clone(), send_rx); }); let latency_1 = Arc::new(Mutex::new(LatencyRecorder::new())); let latency_2 = latency_1.clone(); thread::spawn(move || loop { let obj = game_rx.recv().unwrap(); let mut pov = pov_2.lock().unwrap(); match LilaMessage::decode(&obj) { Some(LilaMessage::Pong(p)) => { latency_2.lock().unwrap().add(p.latency); }, Some(LilaMessage::Move(m)) => { pov.game.fen = m.fen; pov.game.turns = m.ply; pov.game.player = if m.ply % 2 == 0 { Color::white } else { Color::black }; if let Some(c) = m.clock { pov.clock = Some(c); }; }, Some(LilaMessage::Clock(c)) => { pov.clock = Some(c); }, //LilaMessage::End => tx_1.send(Message::close()).unwrap(), _ => () }; }); ConnectedPov { pov: pov_1, latency: latency_1, send_tx: send_tx, } } pub fn send_move(&mut self, from: String, to: String) { let move_packet = MovePacket { t: "move".into(), l: None, // TODO d: Dest { from: from, to: to, promotion: None, }, }; let message = serde_json::to_string(&move_packet).unwrap();
pub struct MovePacket { t: String, d: Dest, l: Option<i64>, } #[derive(Serialize, Debug)] pub struct Dest { pub from: String, pub to: String, pub promotion: Option<String>, }
self.send_tx.send(message).unwrap(); } } #[derive(Serialize, Debug)]
random_line_split
connected_pov.rs
use serde_derive::Serialize; use std::sync::{Arc, Mutex}; use std::sync::mpsc; use std::thread; use serde_json; use uuid::Uuid; use crate::lila; use crate::lila::Session; use super::LatencyRecorder; use super::Pov; use super::Color; use crate::game::socket; use crate::game::lila_message::LilaMessage; pub struct ConnectedPov { pub pov: Arc<Mutex<Pov>>, pub latency: Arc<Mutex<LatencyRecorder>>, send_tx: mpsc::Sender<String>, } impl ConnectedPov { pub fn new(session: &lila::Session, path: &str) -> ConnectedPov { let body = session.get(path); log::debug!("GET response: {}", body); let pov: Pov = serde_json::from_str(&body).unwrap(); let version = match pov.player.version { Some(v) => v as u64, None => 0 }; let socket_path = pov.url.socket.clone(); let pov_1 = Arc::new(Mutex::new(pov)); let (game_tx, game_rx) = mpsc::channel(); let (send_tx, send_rx) = mpsc::channel(); let send_rx = Arc::new(Mutex::new(send_rx)); let pov_2 = pov_1.clone(); let c = session.cookie.clone(); let sri = Uuid::new_v4(); log::debug!("SRI set to {}", sri); //let new_path = str::replace(path, "/v1", "/v2"); let url = Session::socket_url(&format!("{}?sri={}&version={}", socket_path, sri, version)); thread::spawn(move || { socket::Client::connect(&c, url.clone(), version, game_tx.clone(), send_rx); }); let latency_1 = Arc::new(Mutex::new(LatencyRecorder::new())); let latency_2 = latency_1.clone(); thread::spawn(move || loop { let obj = game_rx.recv().unwrap(); let mut pov = pov_2.lock().unwrap(); match LilaMessage::decode(&obj) { Some(LilaMessage::Pong(p)) => { latency_2.lock().unwrap().add(p.latency); }, Some(LilaMessage::Move(m)) => { pov.game.fen = m.fen; pov.game.turns = m.ply; pov.game.player = if m.ply % 2 == 0 { Color::white } else
; if let Some(c) = m.clock { pov.clock = Some(c); }; }, Some(LilaMessage::Clock(c)) => { pov.clock = Some(c); }, //LilaMessage::End => tx_1.send(Message::close()).unwrap(), _ => () }; }); ConnectedPov { pov: pov_1, latency: latency_1, send_tx: send_tx, } } pub fn send_move(&mut self, from: String, to: String) { let move_packet = MovePacket { t: "move".into(), l: None, // TODO d: Dest { from: from, to: to, promotion: None, }, }; let message = serde_json::to_string(&move_packet).unwrap(); self.send_tx.send(message).unwrap(); } } #[derive(Serialize, Debug)] pub struct MovePacket { t: String, d: Dest, l: Option<i64>, } #[derive(Serialize, Debug)] pub struct Dest { pub from: String, pub to: String, pub promotion: Option<String>, }
{ Color::black }
conditional_block
md5.rs
use std::io::{MemWriter, BufWriter}; use super::Hasher; static R: [u32,..64]= [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ]; static K: [u32,..64] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, ]; pub struct MD5 { h: [u32,..4], data: Vec<u8>, length: u64, } impl MD5 { pub fn new() -> MD5 { MD5 { h: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476], data: Vec::new(), length: 0, } } fn process_block(&mut self, block: &[u8]) { assert_eq!(block.len(), 64); let mut words = [0u32,..16]; for (i, chunk) in block.chunks(4).enumerate() { words[i] = (chunk[0] as u32) | (chunk[1] as u32 << 8) | (chunk[2] as u32 << 16) | (chunk[3] as u32 << 24) ; } let ff = |b: u32, c: u32, d: u32| d ^ (b & (c ^ d)); let gg = |b: u32, c: u32, d: u32| c ^ (d & (b ^ c)); let hh = |b: u32, c: u32, d: u32| (b ^ c ^ d); let ii = |b: u32, c: u32, d: u32| (c ^ (b |!d)); let left_rotate = |x: u32, n: u32| (x << n as uint) | (x >> (32 - n) as uint); let h = self.h; let (mut a, mut b, mut c, mut d) = (h[0], h[1], h[2], h[3]); for i in range(0u, 64u) { let (f, g) = match i { 0...15 => (ff(b, c, d), i), 16...31 => (gg(b, c, d), (5 * i + 1) % 16), 32...47 => (hh(b, c, d), (3 * i + 5) % 16), 48...63 => (ii(b, c, d), (7 * i) % 16), _ => (0, 0), }; let tmp = d; d = c; c = b; b = left_rotate(a + f + K[i] + words[g], R[i]) + b; a = tmp; } self.h[0] += a; self.h[1] += b; self.h[2] += c; self.h[3] += d; } } impl Hasher for MD5 { fn reset(&mut self) { self.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; self.data.clear(); self.length = 0; } fn update(&mut self, data: &[u8]) { let mut d = self.data.clone(); self.data.clear(); d.push_all(data); for chunk in d.as_slice().chunks(64) { self.length += chunk.len() as u64; if chunk.len() == 64 { self.process_block(chunk); } else { self.data.push_all(chunk); } } } #[allow(unused_must_use)] fn output(&self, out: &mut [u8]) { let mut m = MD5 { h: self.h, data: Vec::new(), length: 0, }; let mut w = MemWriter::new(); w.write(self.data.as_slice()); w.write_u8(0x80); w.write(Vec::from_elem(56 - self.data.len() - 1, 0x00 as u8).as_slice()); w.write_le_u64(self.length * 8); m.process_block(w.get_ref()); let mut w = BufWriter::new(out); for n in m.h.iter() { w.write_le_u32(*n); } } fn
(&self) -> uint { 128 } fn block_size_bits(&self) -> uint { 512 } } #[cfg(test)] mod test { use hash::Hasher; use hash::md5::MD5; use serialize::hex::ToHex; #[test] fn test_simple() { let tests = [ ("The quick brown fox jumps over the lazy dog", "9e107d9d372bb6826bd81d3542a419d6"), ("The quick brown fox jumps over the lazy dog.", "e4d909c290d0fb1ca068ffaddf22cbd0"), ("", "d41d8cd98f00b204e9800998ecf8427e"), ]; let mut m = MD5::new(); for &(s, ref h) in tests.iter() { let data = s.as_bytes(); m.reset(); m.update(data); let hh = m.digest().as_slice().to_hex(); assert_eq!(hh.len(), h.len()); assert_eq!(hh.as_slice(), *h); } } } #[cfg(test)] mod bench { use hash::Hasher; use hash::md5::MD5; use test::test::Bencher; #[bench] fn bench_10(bh: &mut Bencher) { let bytes = [1u8,..10]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64(bh: &mut Bencher) { let bytes = [1u8,..64]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_1k(bh: &mut Bencher) { let bytes = [1u8,..1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64(bh: &mut Bencher) { let bytes = [1u8,..64]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_128k(bh: &mut Bencher) { let bytes = [1u8,..2 * 64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } }
output_size_bits
identifier_name
md5.rs
use std::io::{MemWriter, BufWriter}; use super::Hasher; static R: [u32,..64]= [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ]; static K: [u32,..64] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, ]; pub struct MD5 { h: [u32,..4], data: Vec<u8>, length: u64, } impl MD5 { pub fn new() -> MD5 { MD5 { h: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476], data: Vec::new(), length: 0, } } fn process_block(&mut self, block: &[u8]) { assert_eq!(block.len(), 64); let mut words = [0u32,..16]; for (i, chunk) in block.chunks(4).enumerate() { words[i] = (chunk[0] as u32) | (chunk[1] as u32 << 8) | (chunk[2] as u32 << 16) | (chunk[3] as u32 << 24) ; } let ff = |b: u32, c: u32, d: u32| d ^ (b & (c ^ d)); let gg = |b: u32, c: u32, d: u32| c ^ (d & (b ^ c)); let hh = |b: u32, c: u32, d: u32| (b ^ c ^ d); let ii = |b: u32, c: u32, d: u32| (c ^ (b |!d)); let left_rotate = |x: u32, n: u32| (x << n as uint) | (x >> (32 - n) as uint); let h = self.h; let (mut a, mut b, mut c, mut d) = (h[0], h[1], h[2], h[3]); for i in range(0u, 64u) { let (f, g) = match i { 0...15 => (ff(b, c, d), i), 16...31 => (gg(b, c, d), (5 * i + 1) % 16), 32...47 => (hh(b, c, d), (3 * i + 5) % 16), 48...63 => (ii(b, c, d), (7 * i) % 16), _ => (0, 0), }; let tmp = d; d = c; c = b; b = left_rotate(a + f + K[i] + words[g], R[i]) + b; a = tmp; } self.h[0] += a; self.h[1] += b; self.h[2] += c; self.h[3] += d; } } impl Hasher for MD5 { fn reset(&mut self) { self.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; self.data.clear(); self.length = 0; } fn update(&mut self, data: &[u8]) { let mut d = self.data.clone(); self.data.clear(); d.push_all(data); for chunk in d.as_slice().chunks(64) { self.length += chunk.len() as u64; if chunk.len() == 64 { self.process_block(chunk); } else
} } #[allow(unused_must_use)] fn output(&self, out: &mut [u8]) { let mut m = MD5 { h: self.h, data: Vec::new(), length: 0, }; let mut w = MemWriter::new(); w.write(self.data.as_slice()); w.write_u8(0x80); w.write(Vec::from_elem(56 - self.data.len() - 1, 0x00 as u8).as_slice()); w.write_le_u64(self.length * 8); m.process_block(w.get_ref()); let mut w = BufWriter::new(out); for n in m.h.iter() { w.write_le_u32(*n); } } fn output_size_bits(&self) -> uint { 128 } fn block_size_bits(&self) -> uint { 512 } } #[cfg(test)] mod test { use hash::Hasher; use hash::md5::MD5; use serialize::hex::ToHex; #[test] fn test_simple() { let tests = [ ("The quick brown fox jumps over the lazy dog", "9e107d9d372bb6826bd81d3542a419d6"), ("The quick brown fox jumps over the lazy dog.", "e4d909c290d0fb1ca068ffaddf22cbd0"), ("", "d41d8cd98f00b204e9800998ecf8427e"), ]; let mut m = MD5::new(); for &(s, ref h) in tests.iter() { let data = s.as_bytes(); m.reset(); m.update(data); let hh = m.digest().as_slice().to_hex(); assert_eq!(hh.len(), h.len()); assert_eq!(hh.as_slice(), *h); } } } #[cfg(test)] mod bench { use hash::Hasher; use hash::md5::MD5; use test::test::Bencher; #[bench] fn bench_10(bh: &mut Bencher) { let bytes = [1u8,..10]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64(bh: &mut Bencher) { let bytes = [1u8,..64]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_1k(bh: &mut Bencher) { let bytes = [1u8,..1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64(bh: &mut Bencher) { let bytes = [1u8,..64]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_128k(bh: &mut Bencher) { let bytes = [1u8,..2 * 64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } }
{ self.data.push_all(chunk); }
conditional_block
md5.rs
use std::io::{MemWriter, BufWriter}; use super::Hasher; static R: [u32,..64]= [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ]; static K: [u32,..64] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, ]; pub struct MD5 { h: [u32,..4], data: Vec<u8>, length: u64, } impl MD5 { pub fn new() -> MD5 { MD5 { h: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476], data: Vec::new(), length: 0, } } fn process_block(&mut self, block: &[u8]) { assert_eq!(block.len(), 64); let mut words = [0u32,..16]; for (i, chunk) in block.chunks(4).enumerate() { words[i] = (chunk[0] as u32) | (chunk[1] as u32 << 8) | (chunk[2] as u32 << 16) | (chunk[3] as u32 << 24) ; } let ff = |b: u32, c: u32, d: u32| d ^ (b & (c ^ d)); let gg = |b: u32, c: u32, d: u32| c ^ (d & (b ^ c)); let hh = |b: u32, c: u32, d: u32| (b ^ c ^ d); let ii = |b: u32, c: u32, d: u32| (c ^ (b |!d)); let left_rotate = |x: u32, n: u32| (x << n as uint) | (x >> (32 - n) as uint); let h = self.h; let (mut a, mut b, mut c, mut d) = (h[0], h[1], h[2], h[3]); for i in range(0u, 64u) { let (f, g) = match i { 0...15 => (ff(b, c, d), i), 16...31 => (gg(b, c, d), (5 * i + 1) % 16), 32...47 => (hh(b, c, d), (3 * i + 5) % 16), 48...63 => (ii(b, c, d), (7 * i) % 16),
let tmp = d; d = c; c = b; b = left_rotate(a + f + K[i] + words[g], R[i]) + b; a = tmp; } self.h[0] += a; self.h[1] += b; self.h[2] += c; self.h[3] += d; } } impl Hasher for MD5 { fn reset(&mut self) { self.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; self.data.clear(); self.length = 0; } fn update(&mut self, data: &[u8]) { let mut d = self.data.clone(); self.data.clear(); d.push_all(data); for chunk in d.as_slice().chunks(64) { self.length += chunk.len() as u64; if chunk.len() == 64 { self.process_block(chunk); } else { self.data.push_all(chunk); } } } #[allow(unused_must_use)] fn output(&self, out: &mut [u8]) { let mut m = MD5 { h: self.h, data: Vec::new(), length: 0, }; let mut w = MemWriter::new(); w.write(self.data.as_slice()); w.write_u8(0x80); w.write(Vec::from_elem(56 - self.data.len() - 1, 0x00 as u8).as_slice()); w.write_le_u64(self.length * 8); m.process_block(w.get_ref()); let mut w = BufWriter::new(out); for n in m.h.iter() { w.write_le_u32(*n); } } fn output_size_bits(&self) -> uint { 128 } fn block_size_bits(&self) -> uint { 512 } } #[cfg(test)] mod test { use hash::Hasher; use hash::md5::MD5; use serialize::hex::ToHex; #[test] fn test_simple() { let tests = [ ("The quick brown fox jumps over the lazy dog", "9e107d9d372bb6826bd81d3542a419d6"), ("The quick brown fox jumps over the lazy dog.", "e4d909c290d0fb1ca068ffaddf22cbd0"), ("", "d41d8cd98f00b204e9800998ecf8427e"), ]; let mut m = MD5::new(); for &(s, ref h) in tests.iter() { let data = s.as_bytes(); m.reset(); m.update(data); let hh = m.digest().as_slice().to_hex(); assert_eq!(hh.len(), h.len()); assert_eq!(hh.as_slice(), *h); } } } #[cfg(test)] mod bench { use hash::Hasher; use hash::md5::MD5; use test::test::Bencher; #[bench] fn bench_10(bh: &mut Bencher) { let bytes = [1u8,..10]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64(bh: &mut Bencher) { let bytes = [1u8,..64]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_1k(bh: &mut Bencher) { let bytes = [1u8,..1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64(bh: &mut Bencher) { let bytes = [1u8,..64]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_128k(bh: &mut Bencher) { let bytes = [1u8,..2 * 64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } }
_ => (0, 0), };
random_line_split
md5.rs
use std::io::{MemWriter, BufWriter}; use super::Hasher; static R: [u32,..64]= [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ]; static K: [u32,..64] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, ]; pub struct MD5 { h: [u32,..4], data: Vec<u8>, length: u64, } impl MD5 { pub fn new() -> MD5 { MD5 { h: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476], data: Vec::new(), length: 0, } } fn process_block(&mut self, block: &[u8]) { assert_eq!(block.len(), 64); let mut words = [0u32,..16]; for (i, chunk) in block.chunks(4).enumerate() { words[i] = (chunk[0] as u32) | (chunk[1] as u32 << 8) | (chunk[2] as u32 << 16) | (chunk[3] as u32 << 24) ; } let ff = |b: u32, c: u32, d: u32| d ^ (b & (c ^ d)); let gg = |b: u32, c: u32, d: u32| c ^ (d & (b ^ c)); let hh = |b: u32, c: u32, d: u32| (b ^ c ^ d); let ii = |b: u32, c: u32, d: u32| (c ^ (b |!d)); let left_rotate = |x: u32, n: u32| (x << n as uint) | (x >> (32 - n) as uint); let h = self.h; let (mut a, mut b, mut c, mut d) = (h[0], h[1], h[2], h[3]); for i in range(0u, 64u) { let (f, g) = match i { 0...15 => (ff(b, c, d), i), 16...31 => (gg(b, c, d), (5 * i + 1) % 16), 32...47 => (hh(b, c, d), (3 * i + 5) % 16), 48...63 => (ii(b, c, d), (7 * i) % 16), _ => (0, 0), }; let tmp = d; d = c; c = b; b = left_rotate(a + f + K[i] + words[g], R[i]) + b; a = tmp; } self.h[0] += a; self.h[1] += b; self.h[2] += c; self.h[3] += d; } } impl Hasher for MD5 { fn reset(&mut self)
fn update(&mut self, data: &[u8]) { let mut d = self.data.clone(); self.data.clear(); d.push_all(data); for chunk in d.as_slice().chunks(64) { self.length += chunk.len() as u64; if chunk.len() == 64 { self.process_block(chunk); } else { self.data.push_all(chunk); } } } #[allow(unused_must_use)] fn output(&self, out: &mut [u8]) { let mut m = MD5 { h: self.h, data: Vec::new(), length: 0, }; let mut w = MemWriter::new(); w.write(self.data.as_slice()); w.write_u8(0x80); w.write(Vec::from_elem(56 - self.data.len() - 1, 0x00 as u8).as_slice()); w.write_le_u64(self.length * 8); m.process_block(w.get_ref()); let mut w = BufWriter::new(out); for n in m.h.iter() { w.write_le_u32(*n); } } fn output_size_bits(&self) -> uint { 128 } fn block_size_bits(&self) -> uint { 512 } } #[cfg(test)] mod test { use hash::Hasher; use hash::md5::MD5; use serialize::hex::ToHex; #[test] fn test_simple() { let tests = [ ("The quick brown fox jumps over the lazy dog", "9e107d9d372bb6826bd81d3542a419d6"), ("The quick brown fox jumps over the lazy dog.", "e4d909c290d0fb1ca068ffaddf22cbd0"), ("", "d41d8cd98f00b204e9800998ecf8427e"), ]; let mut m = MD5::new(); for &(s, ref h) in tests.iter() { let data = s.as_bytes(); m.reset(); m.update(data); let hh = m.digest().as_slice().to_hex(); assert_eq!(hh.len(), h.len()); assert_eq!(hh.as_slice(), *h); } } } #[cfg(test)] mod bench { use hash::Hasher; use hash::md5::MD5; use test::test::Bencher; #[bench] fn bench_10(bh: &mut Bencher) { let bytes = [1u8,..10]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64(bh: &mut Bencher) { let bytes = [1u8,..64]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_1k(bh: &mut Bencher) { let bytes = [1u8,..1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; bh.iter(|| { let mut m = MD5::new(); m.reset(); m.update(bytes); m.digest(); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64(bh: &mut Bencher) { let bytes = [1u8,..64]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_64k(bh: &mut Bencher) { let bytes = [1u8,..64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] fn bench_update_128k(bh: &mut Bencher) { let bytes = [1u8,..2 * 64 * 1024]; let mut m = MD5::new(); m.reset(); bh.iter(|| { m.update(bytes); }); bh.bytes = bytes.len() as u64; } }
{ self.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; self.data.clear(); self.length = 0; }
identifier_body
alg.rs
use super::{Graph, NodeId, Length}; use std::time::Instant; use std::cmp::Ordering; use std::usize; use std::collections::VecDeque; impl Graph { pub fn count_components(&self) -> usize { let start = Instant::now(); let mut union = UnionFind::new(self.node_info.len()); for id in 0..self.node_info.len() { if id == union.find(id) { self.dfs(id, &mut union); } } let count = union.count(); let end = Instant::now(); println!("Counting Components took {:?}", end.duration_since(start)); count } fn dfs(&self, start: NodeId, union: &mut UnionFind) { let mut queue = Vec::<NodeId>::new(); queue.push(start); while let Some(n) = queue.pop() { if union.find(n) == n { union.union(start, n); queue.extend(self.outgoing_edges_for(n).iter().map(|e| e.endpoint)); } } } pub fn dijkstra(&self) -> Dijkstra { Dijkstra { dist: vec![usize::MAX; self.node_count()], touched: Default::default(), graph: self, } } } #[derive(Debug)] struct UnionFind { parent: Vec<NodeId>, } impl UnionFind { pub fn new(size: usize) -> UnionFind { let parent = (0..size).collect(); UnionFind { parent: parent } } pub fn find(&mut self, id: NodeId) -> NodeId { let mut visited_ids = vec![id]; let mut cur_id = id; let mut par_id = self.parent[id]; while cur_id!= par_id { cur_id = par_id; visited_ids.push(cur_id); par_id = self.parent[cur_id]; } for id in visited_ids { self.parent[id] = par_id; } par_id } pub fn union(&mut self, r: NodeId, s: NodeId) { let r_par = self.find(r); let s_par = self.find(s); if r_par!= s_par { self.parent[s_par] = r_par; } } fn
(&self) -> usize { let mut result = 0; for (index, &par) in self.parent.iter().enumerate() { if index == par { result += 1; } } result } } #[derive(PartialEq, Eq, Debug)] struct NodeCost { node: NodeId, cost: usize, } impl Ord for NodeCost { fn cmp(&self, other: &Self) -> Ordering { other.cost.cmp(&self.cost) } } impl PartialOrd for NodeCost { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } #[test] fn count() { use super::{EdgeInfo, NodeInfo}; let g = Graph::new( vec![ NodeInfo::new(1, 2.3, 3.4, 0), NodeInfo::new(2, 2.3, 3.4, 0), NodeInfo::new(3, 2.3, 3.4, 0), NodeInfo::new(4, 2.3, 3.4, 0), NodeInfo::new(5, 2.3, 3.4, 0), ], vec![ EdgeInfo::new(0, 1, 3, 3), EdgeInfo::new(0, 2, 3, 3), EdgeInfo::new(2, 3, 3, 3), EdgeInfo::new(4, 0, 3, 3), ], ); assert_eq!(g.count_components(), 1) } pub struct Dijkstra<'a> { dist: Vec<Length>, touched: Vec<NodeId>, graph: &'a Graph, } impl<'a> Dijkstra<'a> { pub fn distance(&mut self, source: NodeId, dest: NodeId) -> Option<(Length, VecDeque<NodeId>)> { use std::collections::BinaryHeap; for node in self.touched.drain(..) { self.dist[node] = usize::MAX; } let mut heap = BinaryHeap::new(); heap.push(NodeCost { node: source, cost: 0, }); let mut prev: Vec<NodeId> = (0..self.graph.node_count()).collect(); self.dist[source] = 0; self.touched.push(source); while let Some(NodeCost { node, cost }) = heap.pop() { if node == dest { let mut path = VecDeque::new(); let mut cur = node; while cur!= source { path.push_front(cur); cur = prev[cur]; } path.push_front(source); return Some((cost, path)); } if cost > self.dist[node] { continue; } for edge in self.graph.outgoing_edges_for(node) { let next = NodeCost { node: edge.endpoint, cost: cost + edge.weight, }; if next.cost < self.dist[next.node] { prev[next.node] = node; self.dist[next.node] = next.cost; self.touched.push(next.node); heap.push(next); } } } None } }
count
identifier_name
alg.rs
use super::{Graph, NodeId, Length}; use std::time::Instant; use std::cmp::Ordering; use std::usize; use std::collections::VecDeque; impl Graph { pub fn count_components(&self) -> usize { let start = Instant::now(); let mut union = UnionFind::new(self.node_info.len()); for id in 0..self.node_info.len() { if id == union.find(id) { self.dfs(id, &mut union); } } let count = union.count(); let end = Instant::now(); println!("Counting Components took {:?}", end.duration_since(start)); count } fn dfs(&self, start: NodeId, union: &mut UnionFind) { let mut queue = Vec::<NodeId>::new(); queue.push(start); while let Some(n) = queue.pop() {
union.union(start, n); queue.extend(self.outgoing_edges_for(n).iter().map(|e| e.endpoint)); } } } pub fn dijkstra(&self) -> Dijkstra { Dijkstra { dist: vec![usize::MAX; self.node_count()], touched: Default::default(), graph: self, } } } #[derive(Debug)] struct UnionFind { parent: Vec<NodeId>, } impl UnionFind { pub fn new(size: usize) -> UnionFind { let parent = (0..size).collect(); UnionFind { parent: parent } } pub fn find(&mut self, id: NodeId) -> NodeId { let mut visited_ids = vec![id]; let mut cur_id = id; let mut par_id = self.parent[id]; while cur_id!= par_id { cur_id = par_id; visited_ids.push(cur_id); par_id = self.parent[cur_id]; } for id in visited_ids { self.parent[id] = par_id; } par_id } pub fn union(&mut self, r: NodeId, s: NodeId) { let r_par = self.find(r); let s_par = self.find(s); if r_par!= s_par { self.parent[s_par] = r_par; } } fn count(&self) -> usize { let mut result = 0; for (index, &par) in self.parent.iter().enumerate() { if index == par { result += 1; } } result } } #[derive(PartialEq, Eq, Debug)] struct NodeCost { node: NodeId, cost: usize, } impl Ord for NodeCost { fn cmp(&self, other: &Self) -> Ordering { other.cost.cmp(&self.cost) } } impl PartialOrd for NodeCost { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } #[test] fn count() { use super::{EdgeInfo, NodeInfo}; let g = Graph::new( vec![ NodeInfo::new(1, 2.3, 3.4, 0), NodeInfo::new(2, 2.3, 3.4, 0), NodeInfo::new(3, 2.3, 3.4, 0), NodeInfo::new(4, 2.3, 3.4, 0), NodeInfo::new(5, 2.3, 3.4, 0), ], vec![ EdgeInfo::new(0, 1, 3, 3), EdgeInfo::new(0, 2, 3, 3), EdgeInfo::new(2, 3, 3, 3), EdgeInfo::new(4, 0, 3, 3), ], ); assert_eq!(g.count_components(), 1) } pub struct Dijkstra<'a> { dist: Vec<Length>, touched: Vec<NodeId>, graph: &'a Graph, } impl<'a> Dijkstra<'a> { pub fn distance(&mut self, source: NodeId, dest: NodeId) -> Option<(Length, VecDeque<NodeId>)> { use std::collections::BinaryHeap; for node in self.touched.drain(..) { self.dist[node] = usize::MAX; } let mut heap = BinaryHeap::new(); heap.push(NodeCost { node: source, cost: 0, }); let mut prev: Vec<NodeId> = (0..self.graph.node_count()).collect(); self.dist[source] = 0; self.touched.push(source); while let Some(NodeCost { node, cost }) = heap.pop() { if node == dest { let mut path = VecDeque::new(); let mut cur = node; while cur!= source { path.push_front(cur); cur = prev[cur]; } path.push_front(source); return Some((cost, path)); } if cost > self.dist[node] { continue; } for edge in self.graph.outgoing_edges_for(node) { let next = NodeCost { node: edge.endpoint, cost: cost + edge.weight, }; if next.cost < self.dist[next.node] { prev[next.node] = node; self.dist[next.node] = next.cost; self.touched.push(next.node); heap.push(next); } } } None } }
if union.find(n) == n {
random_line_split
alg.rs
use super::{Graph, NodeId, Length}; use std::time::Instant; use std::cmp::Ordering; use std::usize; use std::collections::VecDeque; impl Graph { pub fn count_components(&self) -> usize { let start = Instant::now(); let mut union = UnionFind::new(self.node_info.len()); for id in 0..self.node_info.len() { if id == union.find(id) { self.dfs(id, &mut union); } } let count = union.count(); let end = Instant::now(); println!("Counting Components took {:?}", end.duration_since(start)); count } fn dfs(&self, start: NodeId, union: &mut UnionFind) { let mut queue = Vec::<NodeId>::new(); queue.push(start); while let Some(n) = queue.pop() { if union.find(n) == n { union.union(start, n); queue.extend(self.outgoing_edges_for(n).iter().map(|e| e.endpoint)); } } } pub fn dijkstra(&self) -> Dijkstra { Dijkstra { dist: vec![usize::MAX; self.node_count()], touched: Default::default(), graph: self, } } } #[derive(Debug)] struct UnionFind { parent: Vec<NodeId>, } impl UnionFind { pub fn new(size: usize) -> UnionFind { let parent = (0..size).collect(); UnionFind { parent: parent } } pub fn find(&mut self, id: NodeId) -> NodeId { let mut visited_ids = vec![id]; let mut cur_id = id; let mut par_id = self.parent[id]; while cur_id!= par_id { cur_id = par_id; visited_ids.push(cur_id); par_id = self.parent[cur_id]; } for id in visited_ids { self.parent[id] = par_id; } par_id } pub fn union(&mut self, r: NodeId, s: NodeId) { let r_par = self.find(r); let s_par = self.find(s); if r_par!= s_par { self.parent[s_par] = r_par; } } fn count(&self) -> usize { let mut result = 0; for (index, &par) in self.parent.iter().enumerate() { if index == par { result += 1; } } result } } #[derive(PartialEq, Eq, Debug)] struct NodeCost { node: NodeId, cost: usize, } impl Ord for NodeCost { fn cmp(&self, other: &Self) -> Ordering { other.cost.cmp(&self.cost) } } impl PartialOrd for NodeCost { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } #[test] fn count() { use super::{EdgeInfo, NodeInfo}; let g = Graph::new( vec![ NodeInfo::new(1, 2.3, 3.4, 0), NodeInfo::new(2, 2.3, 3.4, 0), NodeInfo::new(3, 2.3, 3.4, 0), NodeInfo::new(4, 2.3, 3.4, 0), NodeInfo::new(5, 2.3, 3.4, 0), ], vec![ EdgeInfo::new(0, 1, 3, 3), EdgeInfo::new(0, 2, 3, 3), EdgeInfo::new(2, 3, 3, 3), EdgeInfo::new(4, 0, 3, 3), ], ); assert_eq!(g.count_components(), 1) } pub struct Dijkstra<'a> { dist: Vec<Length>, touched: Vec<NodeId>, graph: &'a Graph, } impl<'a> Dijkstra<'a> { pub fn distance(&mut self, source: NodeId, dest: NodeId) -> Option<(Length, VecDeque<NodeId>)> { use std::collections::BinaryHeap; for node in self.touched.drain(..) { self.dist[node] = usize::MAX; } let mut heap = BinaryHeap::new(); heap.push(NodeCost { node: source, cost: 0, }); let mut prev: Vec<NodeId> = (0..self.graph.node_count()).collect(); self.dist[source] = 0; self.touched.push(source); while let Some(NodeCost { node, cost }) = heap.pop() { if node == dest
if cost > self.dist[node] { continue; } for edge in self.graph.outgoing_edges_for(node) { let next = NodeCost { node: edge.endpoint, cost: cost + edge.weight, }; if next.cost < self.dist[next.node] { prev[next.node] = node; self.dist[next.node] = next.cost; self.touched.push(next.node); heap.push(next); } } } None } }
{ let mut path = VecDeque::new(); let mut cur = node; while cur != source { path.push_front(cur); cur = prev[cur]; } path.push_front(source); return Some((cost, path)); }
conditional_block
gamepadbuttonlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::GamepadButtonListBinding; use dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot, RootedReference}; use dom::gamepadbutton::GamepadButton; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRGamepadButton; // https://w3c.github.io/gamepad/#gamepadbutton-interface #[dom_struct] pub struct GamepadButtonList { reflector_: Reflector, list: Vec<Dom<GamepadButton>> } impl GamepadButtonList { #[allow(unrooted_must_root)] fn
(list: &[&GamepadButton]) -> GamepadButtonList { GamepadButtonList { reflector_: Reflector::new(), list: list.iter().map(|button| Dom::from_ref(*button)).collect(), } } pub fn new_from_vr(global: &GlobalScope, buttons: &[WebVRGamepadButton]) -> DomRoot<GamepadButtonList> { rooted_vec!(let list <- buttons.iter() .map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched))); reflect_dom_object(Box::new(GamepadButtonList::new_inherited(list.r())), global, GamepadButtonListBinding::Wrap) } pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) { for (gp_btn, btn) in self.list.iter().zip(vr_buttons.iter()) { gp_btn.update(btn.pressed, btn.touched); } } } impl GamepadButtonListMethods for GamepadButtonList { // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Length(&self) -> u32 { self.list.len() as u32 } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.list.get(index as usize).map(|button| DomRoot::from_ref(&**button)) } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn IndexedGetter(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.Item(index) } }
new_inherited
identifier_name
gamepadbuttonlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::GamepadButtonListBinding; use dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot, RootedReference}; use dom::gamepadbutton::GamepadButton; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRGamepadButton; // https://w3c.github.io/gamepad/#gamepadbutton-interface #[dom_struct] pub struct GamepadButtonList { reflector_: Reflector, list: Vec<Dom<GamepadButton>> } impl GamepadButtonList { #[allow(unrooted_must_root)] fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList { GamepadButtonList { reflector_: Reflector::new(), list: list.iter().map(|button| Dom::from_ref(*button)).collect(), } } pub fn new_from_vr(global: &GlobalScope, buttons: &[WebVRGamepadButton]) -> DomRoot<GamepadButtonList>
pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) { for (gp_btn, btn) in self.list.iter().zip(vr_buttons.iter()) { gp_btn.update(btn.pressed, btn.touched); } } } impl GamepadButtonListMethods for GamepadButtonList { // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Length(&self) -> u32 { self.list.len() as u32 } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.list.get(index as usize).map(|button| DomRoot::from_ref(&**button)) } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn IndexedGetter(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.Item(index) } }
{ rooted_vec!(let list <- buttons.iter() .map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched))); reflect_dom_object(Box::new(GamepadButtonList::new_inherited(list.r())), global, GamepadButtonListBinding::Wrap) }
identifier_body
gamepadbuttonlist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::root::{Dom, DomRoot, RootedReference}; use dom::gamepadbutton::GamepadButton; use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRGamepadButton; // https://w3c.github.io/gamepad/#gamepadbutton-interface #[dom_struct] pub struct GamepadButtonList { reflector_: Reflector, list: Vec<Dom<GamepadButton>> } impl GamepadButtonList { #[allow(unrooted_must_root)] fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList { GamepadButtonList { reflector_: Reflector::new(), list: list.iter().map(|button| Dom::from_ref(*button)).collect(), } } pub fn new_from_vr(global: &GlobalScope, buttons: &[WebVRGamepadButton]) -> DomRoot<GamepadButtonList> { rooted_vec!(let list <- buttons.iter() .map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched))); reflect_dom_object(Box::new(GamepadButtonList::new_inherited(list.r())), global, GamepadButtonListBinding::Wrap) } pub fn sync_from_vr(&self, vr_buttons: &[WebVRGamepadButton]) { for (gp_btn, btn) in self.list.iter().zip(vr_buttons.iter()) { gp_btn.update(btn.pressed, btn.touched); } } } impl GamepadButtonListMethods for GamepadButtonList { // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Length(&self) -> u32 { self.list.len() as u32 } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.list.get(index as usize).map(|button| DomRoot::from_ref(&**button)) } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn IndexedGetter(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.Item(index) } }
use dom::bindings::codegen::Bindings::GamepadButtonListBinding; use dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object};
random_line_split
free.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; #[cfg(target_os = "redox")] extern crate syscall; #[cfg(target_os = "redox")] fn free(parser: &coreutils::ArgParser) -> ::std::io::Result<()> { use coreutils::to_human_readable_string; use std::io::Error; use syscall::data::StatVfs; let mut stat = StatVfs::default(); { let fd = syscall::open("memory:", syscall::O_STAT).map_err(|err| Error::from_raw_os_error(err.errno))?; syscall::fstatvfs(fd, &mut stat).map_err(|err| Error::from_raw_os_error(err.errno))?; let _ = syscall::close(fd); } let size = stat.f_blocks * stat.f_bsize as u64; let used = (stat.f_blocks - stat.f_bfree) * stat.f_bsize as u64; let free = stat.f_bavail * stat.f_bsize as u64; if parser.found("human-readable") { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", to_human_readable_string(size), to_human_readable_string(used), to_human_readable_string(free)); } else { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", (size + 1023)/1024, (used + 1023)/1024, (free + 1023)/1024); } Ok(()) } #[cfg(target_os = "redox")] fn main() { use std::env; use std::io::{stdout, stderr, Write}; use std::process::exit; use coreutils::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{free} */ r#" NAME free - view memory usage SYNOPSIS free [ -h | --help ] DESCRIPTION free displays the current memory usage of the system OPTIONS -h --human-readable human readable output --help display this help and exit "#; /* @MANEND */ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "human-readable"]) .add_flag(&["help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } println!("{:<8}{:>10}{:>10}{:>10}", "", "total", "used", "free"); free(&parser).try(&mut stderr); } #[cfg(not(target_os = "redox"))] fn
() { use std::io::{stderr, Write}; use std::process::exit; let mut stderr = stderr(); stderr.write(b"error: unimplemented outside redox").unwrap(); exit(1); }
main
identifier_name
free.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; #[cfg(target_os = "redox")] extern crate syscall; #[cfg(target_os = "redox")] fn free(parser: &coreutils::ArgParser) -> ::std::io::Result<()> { use coreutils::to_human_readable_string; use std::io::Error; use syscall::data::StatVfs; let mut stat = StatVfs::default(); { let fd = syscall::open("memory:", syscall::O_STAT).map_err(|err| Error::from_raw_os_error(err.errno))?; syscall::fstatvfs(fd, &mut stat).map_err(|err| Error::from_raw_os_error(err.errno))?; let _ = syscall::close(fd); } let size = stat.f_blocks * stat.f_bsize as u64; let used = (stat.f_blocks - stat.f_bfree) * stat.f_bsize as u64;
if parser.found("human-readable") { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", to_human_readable_string(size), to_human_readable_string(used), to_human_readable_string(free)); } else { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", (size + 1023)/1024, (used + 1023)/1024, (free + 1023)/1024); } Ok(()) } #[cfg(target_os = "redox")] fn main() { use std::env; use std::io::{stdout, stderr, Write}; use std::process::exit; use coreutils::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{free} */ r#" NAME free - view memory usage SYNOPSIS free [ -h | --help ] DESCRIPTION free displays the current memory usage of the system OPTIONS -h --human-readable human readable output --help display this help and exit "#; /* @MANEND */ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "human-readable"]) .add_flag(&["help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } println!("{:<8}{:>10}{:>10}{:>10}", "", "total", "used", "free"); free(&parser).try(&mut stderr); } #[cfg(not(target_os = "redox"))] fn main() { use std::io::{stderr, Write}; use std::process::exit; let mut stderr = stderr(); stderr.write(b"error: unimplemented outside redox").unwrap(); exit(1); }
let free = stat.f_bavail * stat.f_bsize as u64;
random_line_split
free.rs
#![deny(warnings)] extern crate coreutils; extern crate extra; #[cfg(target_os = "redox")] extern crate syscall; #[cfg(target_os = "redox")] fn free(parser: &coreutils::ArgParser) -> ::std::io::Result<()> { use coreutils::to_human_readable_string; use std::io::Error; use syscall::data::StatVfs; let mut stat = StatVfs::default(); { let fd = syscall::open("memory:", syscall::O_STAT).map_err(|err| Error::from_raw_os_error(err.errno))?; syscall::fstatvfs(fd, &mut stat).map_err(|err| Error::from_raw_os_error(err.errno))?; let _ = syscall::close(fd); } let size = stat.f_blocks * stat.f_bsize as u64; let used = (stat.f_blocks - stat.f_bfree) * stat.f_bsize as u64; let free = stat.f_bavail * stat.f_bsize as u64; if parser.found("human-readable") { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", to_human_readable_string(size), to_human_readable_string(used), to_human_readable_string(free)); } else { println!("{:<8}{:>10}{:>10}{:>10}", "Mem:", (size + 1023)/1024, (used + 1023)/1024, (free + 1023)/1024); } Ok(()) } #[cfg(target_os = "redox")] fn main() { use std::env; use std::io::{stdout, stderr, Write}; use std::process::exit; use coreutils::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{free} */ r#" NAME free - view memory usage SYNOPSIS free [ -h | --help ] DESCRIPTION free displays the current memory usage of the system OPTIONS -h --human-readable human readable output --help display this help and exit "#; /* @MANEND */ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "human-readable"]) .add_flag(&["help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } println!("{:<8}{:>10}{:>10}{:>10}", "", "total", "used", "free"); free(&parser).try(&mut stderr); } #[cfg(not(target_os = "redox"))] fn main()
{ use std::io::{stderr, Write}; use std::process::exit; let mut stderr = stderr(); stderr.write(b"error: unimplemented outside redox").unwrap(); exit(1); }
identifier_body