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 |
---|---|---|---|---|
fun-call-variants.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.
fn ho<F>(f: F) -> isize where F: FnOnce(isize) -> isize { let n: isize = f(3); return n; }
fn direct(x: isize) -> isize |
pub fn main() {
let a: isize = direct(3); // direct
let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
}
| { return x + 1; } | identifier_body |
fun-call-variants.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.
fn | <F>(f: F) -> isize where F: FnOnce(isize) -> isize { let n: isize = f(3); return n; }
fn direct(x: isize) -> isize { return x + 1; }
pub fn main() {
let a: isize = direct(3); // direct
let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
}
| ho | identifier_name |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? */
use itertools::Itertools;
use shared::Permutations;
fn main() | {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join(""));
} | identifier_body |
|
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? */
use itertools::Itertools;
use shared::Permutations;
fn main() {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join("")); | } | random_line_split |
|
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? */
use itertools::Itertools;
use shared::Permutations;
fn | () {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join(""));
}
| main | identifier_name |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds;
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[cfg(target_os = "windows")]
#[lang = "eh_unwind_resume"]
extern fn | () {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..)
take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..=42)
}
| eh_unwind_resume | identifier_name |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds;
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[cfg(target_os = "windows")]
#[lang = "eh_unwind_resume"]
extern fn eh_unwind_resume() {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here | take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..=42)
} | //~| SUGGESTION &(..)
| random_line_split |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds;
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[cfg(target_os = "windows")]
#[lang = "eh_unwind_resume"]
extern fn eh_unwind_resume() {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) |
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..)
take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..=42)
}
| {} | identifier_body |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Repository::discover(current_dir).chain_err(|| ""))?;
Ok(Repo { repo })
}
pub fn config(&self) -> Result<Config> {
self.repo
.config()
.map(|config| Config { config })
.chain_err(|| "")
}
pub fn auto_include(&self, filename: &str) -> Result<()> {
let include_path = format!("../{}", filename);
let workdir = match self.repo.workdir() {
Some(dir) => dir,
_ => {
return Ok(());
}
};
let mut path_buf = workdir.to_path_buf();
path_buf.push(filename);
if!path_buf.exists() {
return Ok(());
}
let include_paths = self.include_paths()?;
if include_paths.contains(&include_path) {
return Ok(());
}
let mut config = self.local_config()?;
config
.set_multivar("include.path", "^$", &include_path) | fn include_paths(&self) -> Result<Vec<String>> {
let config = self.local_config()?;
let include_paths: Vec<String> = config
.entries(Some("include.path"))
.chain_err(|| "")?
.into_iter()
.map(|entry| {
entry
.chain_err(|| "")
.and_then(|entry| entry.value().map(String::from).ok_or_else(|| "".into()))
})
.collect::<Result<_>>()?;
Ok(include_paths)
}
fn local_config(&self) -> Result<git2::Config> {
let config = self.repo.config().chain_err(|| "")?;
config.open_level(git2::ConfigLevel::Local).chain_err(|| "")
}
}
pub struct Config {
config: git2::Config,
}
impl Config {
pub fn new(scope: ConfigScope) -> Result<Self> {
let config = match scope {
ConfigScope::Local => git2::Config::open_default(),
ConfigScope::Global => git2::Config::open_default().and_then(|mut r| r.open_global()),
};
config.map(|config| Config { config }).chain_err(|| "")
}
}
impl config::Config for Config {
fn get(&self, name: &str) -> Result<String> {
self.config
.get_string(name)
.chain_err(|| format!("error getting git config for '{}'", name))
}
fn get_all(&self, glob: &str) -> Result<HashMap<String, String>> {
let mut result = HashMap::new();
let entries = self
.config
.entries(Some(glob))
.chain_err(|| "error getting git config entries")?;
for entry in &entries {
let entry = entry.chain_err(|| "error getting git config entry")?;
if let (Some(name), Some(value)) = (entry.name(), entry.value()) {
result.insert(name.into(), value.into());
}
}
Ok(result)
}
fn add(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_multivar(name, "^$", value)
.chain_err(|| format!("error adding git config '{}': '{}'", name, value))
}
fn set(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_str(name, value)
.chain_err(|| format!("error setting git config '{}': '{}'", name, value))
}
fn clear(&mut self, name: &str) -> Result<()> {
self.config
.remove(name)
.chain_err(|| format!("error removing git config '{}'", name))
}
} | .and(Ok(()))
.chain_err(|| "")
}
| random_line_split |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Repository::discover(current_dir).chain_err(|| ""))?;
Ok(Repo { repo })
}
pub fn config(&self) -> Result<Config> {
self.repo
.config()
.map(|config| Config { config })
.chain_err(|| "")
}
pub fn auto_include(&self, filename: &str) -> Result<()> {
let include_path = format!("../{}", filename);
let workdir = match self.repo.workdir() {
Some(dir) => dir,
_ => {
return Ok(());
}
};
let mut path_buf = workdir.to_path_buf();
path_buf.push(filename);
if!path_buf.exists() {
return Ok(());
}
let include_paths = self.include_paths()?;
if include_paths.contains(&include_path) {
return Ok(());
}
let mut config = self.local_config()?;
config
.set_multivar("include.path", "^$", &include_path)
.and(Ok(()))
.chain_err(|| "")
}
fn include_paths(&self) -> Result<Vec<String>> {
let config = self.local_config()?;
let include_paths: Vec<String> = config
.entries(Some("include.path"))
.chain_err(|| "")?
.into_iter()
.map(|entry| {
entry
.chain_err(|| "")
.and_then(|entry| entry.value().map(String::from).ok_or_else(|| "".into()))
})
.collect::<Result<_>>()?;
Ok(include_paths)
}
fn local_config(&self) -> Result<git2::Config> {
let config = self.repo.config().chain_err(|| "")?;
config.open_level(git2::ConfigLevel::Local).chain_err(|| "")
}
}
pub struct Config {
config: git2::Config,
}
impl Config {
pub fn new(scope: ConfigScope) -> Result<Self> {
let config = match scope {
ConfigScope::Local => git2::Config::open_default(),
ConfigScope::Global => git2::Config::open_default().and_then(|mut r| r.open_global()),
};
config.map(|config| Config { config }).chain_err(|| "")
}
}
impl config::Config for Config {
fn get(&self, name: &str) -> Result<String> {
self.config
.get_string(name)
.chain_err(|| format!("error getting git config for '{}'", name))
}
fn get_all(&self, glob: &str) -> Result<HashMap<String, String>> {
let mut result = HashMap::new();
let entries = self
.config
.entries(Some(glob))
.chain_err(|| "error getting git config entries")?;
for entry in &entries {
let entry = entry.chain_err(|| "error getting git config entry")?;
if let (Some(name), Some(value)) = (entry.name(), entry.value()) {
result.insert(name.into(), value.into());
}
}
Ok(result)
}
fn | (&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_multivar(name, "^$", value)
.chain_err(|| format!("error adding git config '{}': '{}'", name, value))
}
fn set(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_str(name, value)
.chain_err(|| format!("error setting git config '{}': '{}'", name, value))
}
fn clear(&mut self, name: &str) -> Result<()> {
self.config
.remove(name)
.chain_err(|| format!("error removing git config '{}'", name))
}
}
| add | identifier_name |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Repository::discover(current_dir).chain_err(|| ""))?;
Ok(Repo { repo })
}
pub fn config(&self) -> Result<Config> {
self.repo
.config()
.map(|config| Config { config })
.chain_err(|| "")
}
pub fn auto_include(&self, filename: &str) -> Result<()> {
let include_path = format!("../{}", filename);
let workdir = match self.repo.workdir() {
Some(dir) => dir,
_ => {
return Ok(());
}
};
let mut path_buf = workdir.to_path_buf();
path_buf.push(filename);
if!path_buf.exists() |
let include_paths = self.include_paths()?;
if include_paths.contains(&include_path) {
return Ok(());
}
let mut config = self.local_config()?;
config
.set_multivar("include.path", "^$", &include_path)
.and(Ok(()))
.chain_err(|| "")
}
fn include_paths(&self) -> Result<Vec<String>> {
let config = self.local_config()?;
let include_paths: Vec<String> = config
.entries(Some("include.path"))
.chain_err(|| "")?
.into_iter()
.map(|entry| {
entry
.chain_err(|| "")
.and_then(|entry| entry.value().map(String::from).ok_or_else(|| "".into()))
})
.collect::<Result<_>>()?;
Ok(include_paths)
}
fn local_config(&self) -> Result<git2::Config> {
let config = self.repo.config().chain_err(|| "")?;
config.open_level(git2::ConfigLevel::Local).chain_err(|| "")
}
}
pub struct Config {
config: git2::Config,
}
impl Config {
pub fn new(scope: ConfigScope) -> Result<Self> {
let config = match scope {
ConfigScope::Local => git2::Config::open_default(),
ConfigScope::Global => git2::Config::open_default().and_then(|mut r| r.open_global()),
};
config.map(|config| Config { config }).chain_err(|| "")
}
}
impl config::Config for Config {
fn get(&self, name: &str) -> Result<String> {
self.config
.get_string(name)
.chain_err(|| format!("error getting git config for '{}'", name))
}
fn get_all(&self, glob: &str) -> Result<HashMap<String, String>> {
let mut result = HashMap::new();
let entries = self
.config
.entries(Some(glob))
.chain_err(|| "error getting git config entries")?;
for entry in &entries {
let entry = entry.chain_err(|| "error getting git config entry")?;
if let (Some(name), Some(value)) = (entry.name(), entry.value()) {
result.insert(name.into(), value.into());
}
}
Ok(result)
}
fn add(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_multivar(name, "^$", value)
.chain_err(|| format!("error adding git config '{}': '{}'", name, value))
}
fn set(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_str(name, value)
.chain_err(|| format!("error setting git config '{}': '{}'", name, value))
}
fn clear(&mut self, name: &str) -> Result<()> {
self.config
.remove(name)
.chain_err(|| format!("error removing git config '{}'", name))
}
}
| {
return Ok(());
} | conditional_block |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Repository::discover(current_dir).chain_err(|| ""))?;
Ok(Repo { repo })
}
pub fn config(&self) -> Result<Config> {
self.repo
.config()
.map(|config| Config { config })
.chain_err(|| "")
}
pub fn auto_include(&self, filename: &str) -> Result<()> {
let include_path = format!("../{}", filename);
let workdir = match self.repo.workdir() {
Some(dir) => dir,
_ => {
return Ok(());
}
};
let mut path_buf = workdir.to_path_buf();
path_buf.push(filename);
if!path_buf.exists() {
return Ok(());
}
let include_paths = self.include_paths()?;
if include_paths.contains(&include_path) {
return Ok(());
}
let mut config = self.local_config()?;
config
.set_multivar("include.path", "^$", &include_path)
.and(Ok(()))
.chain_err(|| "")
}
fn include_paths(&self) -> Result<Vec<String>> {
let config = self.local_config()?;
let include_paths: Vec<String> = config
.entries(Some("include.path"))
.chain_err(|| "")?
.into_iter()
.map(|entry| {
entry
.chain_err(|| "")
.and_then(|entry| entry.value().map(String::from).ok_or_else(|| "".into()))
})
.collect::<Result<_>>()?;
Ok(include_paths)
}
fn local_config(&self) -> Result<git2::Config> {
let config = self.repo.config().chain_err(|| "")?;
config.open_level(git2::ConfigLevel::Local).chain_err(|| "")
}
}
pub struct Config {
config: git2::Config,
}
impl Config {
pub fn new(scope: ConfigScope) -> Result<Self> {
let config = match scope {
ConfigScope::Local => git2::Config::open_default(),
ConfigScope::Global => git2::Config::open_default().and_then(|mut r| r.open_global()),
};
config.map(|config| Config { config }).chain_err(|| "")
}
}
impl config::Config for Config {
fn get(&self, name: &str) -> Result<String> {
self.config
.get_string(name)
.chain_err(|| format!("error getting git config for '{}'", name))
}
fn get_all(&self, glob: &str) -> Result<HashMap<String, String>> |
fn add(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_multivar(name, "^$", value)
.chain_err(|| format!("error adding git config '{}': '{}'", name, value))
}
fn set(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_str(name, value)
.chain_err(|| format!("error setting git config '{}': '{}'", name, value))
}
fn clear(&mut self, name: &str) -> Result<()> {
self.config
.remove(name)
.chain_err(|| format!("error removing git config '{}'", name))
}
}
| {
let mut result = HashMap::new();
let entries = self
.config
.entries(Some(glob))
.chain_err(|| "error getting git config entries")?;
for entry in &entries {
let entry = entry.chain_err(|| "error getting git config entry")?;
if let (Some(name), Some(value)) = (entry.name(), entry.value()) {
result.insert(name.into(), value.into());
}
}
Ok(result)
} | identifier_body |
partialeq_ne_impl.rs | use clippy_utils::diagnostics::span_lint_hir;
use clippy_utils::is_automatically_derived;
use if_chain::if_chain;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for manual re-implementations of `PartialEq::ne`.
///
/// ### Why is this bad?
/// `PartialEq::ne` is required to always return the
/// negated result of `PartialEq::eq`, which is exactly what the default
/// implementation does. Therefore, there should never be any need to
/// re-implement it.
///
/// ### Example
/// ```rust
/// struct Foo;
///
/// impl PartialEq for Foo {
/// fn eq(&self, other: &Foo) -> bool { true }
/// fn ne(&self, other: &Foo) -> bool {!(self == other) }
/// } |
declare_lint_pass!(PartialEqNeImpl => [PARTIALEQ_NE_IMPL]);
impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if_chain! {
if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items,.. }) = item.kind;
let attrs = cx.tcx.hir().attrs(item.hir_id());
if!is_automatically_derived(attrs);
if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
if trait_ref.path.res.def_id() == eq_trait;
then {
for impl_item in impl_items {
if impl_item.ident.name == sym::ne {
span_lint_hir(
cx,
PARTIALEQ_NE_IMPL,
impl_item.id.hir_id(),
impl_item.span,
"re-implementing `PartialEq::ne` is unnecessary",
);
}
}
}
};
}
} | /// ```
pub PARTIALEQ_NE_IMPL,
complexity,
"re-implementing `PartialEq::ne`"
} | random_line_split |
partialeq_ne_impl.rs | use clippy_utils::diagnostics::span_lint_hir;
use clippy_utils::is_automatically_derived;
use if_chain::if_chain;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for manual re-implementations of `PartialEq::ne`.
///
/// ### Why is this bad?
/// `PartialEq::ne` is required to always return the
/// negated result of `PartialEq::eq`, which is exactly what the default
/// implementation does. Therefore, there should never be any need to
/// re-implement it.
///
/// ### Example
/// ```rust
/// struct Foo;
///
/// impl PartialEq for Foo {
/// fn eq(&self, other: &Foo) -> bool { true }
/// fn ne(&self, other: &Foo) -> bool {!(self == other) }
/// }
/// ```
pub PARTIALEQ_NE_IMPL,
complexity,
"re-implementing `PartialEq::ne`"
}
declare_lint_pass!(PartialEqNeImpl => [PARTIALEQ_NE_IMPL]);
impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) | };
}
}
| {
if_chain! {
if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items, .. }) = item.kind;
let attrs = cx.tcx.hir().attrs(item.hir_id());
if !is_automatically_derived(attrs);
if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
if trait_ref.path.res.def_id() == eq_trait;
then {
for impl_item in impl_items {
if impl_item.ident.name == sym::ne {
span_lint_hir(
cx,
PARTIALEQ_NE_IMPL,
impl_item.id.hir_id(),
impl_item.span,
"re-implementing `PartialEq::ne` is unnecessary",
);
}
}
} | identifier_body |
partialeq_ne_impl.rs | use clippy_utils::diagnostics::span_lint_hir;
use clippy_utils::is_automatically_derived;
use if_chain::if_chain;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for manual re-implementations of `PartialEq::ne`.
///
/// ### Why is this bad?
/// `PartialEq::ne` is required to always return the
/// negated result of `PartialEq::eq`, which is exactly what the default
/// implementation does. Therefore, there should never be any need to
/// re-implement it.
///
/// ### Example
/// ```rust
/// struct Foo;
///
/// impl PartialEq for Foo {
/// fn eq(&self, other: &Foo) -> bool { true }
/// fn ne(&self, other: &Foo) -> bool {!(self == other) }
/// }
/// ```
pub PARTIALEQ_NE_IMPL,
complexity,
"re-implementing `PartialEq::ne`"
}
declare_lint_pass!(PartialEqNeImpl => [PARTIALEQ_NE_IMPL]);
impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl {
fn | (&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if_chain! {
if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items,.. }) = item.kind;
let attrs = cx.tcx.hir().attrs(item.hir_id());
if!is_automatically_derived(attrs);
if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
if trait_ref.path.res.def_id() == eq_trait;
then {
for impl_item in impl_items {
if impl_item.ident.name == sym::ne {
span_lint_hir(
cx,
PARTIALEQ_NE_IMPL,
impl_item.id.hir_id(),
impl_item.span,
"re-implementing `PartialEq::ne` is unnecessary",
);
}
}
}
};
}
}
| check_item | identifier_name |
lib.rs | // Copyright 2014 The Rust Project Developers. See the 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.
//! This crate provides a native implementation of regular expressions that is
//! heavily based on RE2 both in syntax and in implementation. Notably,
//! backreferences and arbitrary lookahead/lookbehind assertions are not
//! provided. In return, regular expression searching provided by this package
//! has excellent worst case performance. The specific syntax supported is
//! documented further down.
//!
//! This crate's documentation provides some simple examples, describes Unicode
//! support and exhaustively lists the supported syntax. For more specific
//! details on the API, please see the documentation for the `Regex` type.
//!
//! # First example: find a date
//!
//! General use of regular expressions in this package involves compiling an
//! expression and then using it to search, split or replace text. For example,
//! to confirm that some text resembles a date:
//!
//! ```rust
//! use regex::Regex;
//! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") {
//! Ok(re) => re,
//! Err(err) => fail!("{}", err),
//! };
//! assert_eq!(re.is_match("2014-01-01"), true);
//! ```
//!
//! Notice the use of the `^` and `$` anchors. In this crate, every expression
//! is executed with an implicit `.*?` at the beginning and end, which allows
//! it to match anywhere in the text. Anchors can be used to ensure that the
//! full text matches an expression.
//!
//! This example also demonstrates the utility of raw strings in Rust, which
//! are just like regular strings except they are prefixed with an `r` and do
//! not process any escape sequences. For example, `"\\d"` is the same
//! expression as `r"\d"`.
//!
//! # The `regex!` macro
//!
//! Rust's compile time meta-programming facilities provide a way to write a
//! `regex!` macro which compiles regular expressions *when your program
//! compiles*. Said differently, if you only use `regex!` to build regular
//! expressions in your program, then your program cannot compile with an
//! invalid regular expression. Moreover, the `regex!` macro compiles the
//! given expression to native Rust code, which makes it much faster for
//! searching text.
//!
//! Since `regex!` provides compiled regular expressions that are both safer
//! and faster to use, you should use them whenever possible. The only
//! requirement for using them is that you have a string literal corresponding
//! to your expression. Otherwise, it is indistinguishable from an expression
//! compiled at runtime with `Regex::new`.
//!
//! To use the `regex!` macro, you must enable the `phase` feature and import
//! the `regex_macros` crate as a syntax extension:
//!
//! ```rust
//! #![feature(phase)]
//! #[phase(syntax)]
//! extern crate regex_macros;
//! extern crate regex;
//!
//! fn main() {
//! let re = regex!(r"^\d{4}-\d{2}-\d{2}$");
//! assert_eq!(re.is_match("2014-01-01"), true);
//! }
//! ```
//!
//! There are a few things worth mentioning about using the `regex!` macro.
//! Firstly, the `regex!` macro *only* accepts string *literals*.
//! Secondly, the `regex` crate *must* be linked with the name `regex` since
//! the generated code depends on finding symbols in the `regex` crate.
//!
//! The only downside of using the `regex!` macro is that it can increase the
//! size of your program's binary since it generates specialized Rust code.
//! The extra size probably won't be significant for a small number of
//! expressions, but 100+ calls to `regex!` will probably result in a
//! noticeably bigger binary.
//!
//! # Example: iterating over capture groups
//!
//! This crate provides convenient iterators for matching an expression
//! repeatedly against a search string to find successive non-overlapping
//! matches. For example, to find all dates in a string and be able to access
//! them by their component pieces:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(syntax)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(\d{4})-(\d{2})-(\d{2})");
//! let text = "2012-03-14, 2013-01-01 and 2014-07-05";
//! for cap in re.captures_iter(text) {
//! println!("Month: {} Day: {} Year: {}", cap.at(2), cap.at(3), cap.at(1));
//! }
//! // Output:
//! // Month: 03 Day: 14 Year: 2012
//! // Month: 01 Day: 01 Year: 2013
//! // Month: 07 Day: 05 Year: 2014
//! # }
//! ```
//!
//! Notice that the year is in the capture group indexed at `1`. This is
//! because the *entire match* is stored in the capture group at index `0`.
//!
//! # Example: replacement with named capture groups
//!
//! Building on the previous example, perhaps we'd like to rearrange the date
//! formats. This can be done with text replacement. But to make the code
//! clearer, we can *name* our capture groups and use those names as variables
//! in our replacement text:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(syntax)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})");
//! let before = "2012-03-14, 2013-01-01 and 2014-07-05";
//! let after = re.replace_all(before, "$m/$d/$y");
//! assert_eq!(after.as_slice(), "03/14/2012, 01/01/2013 and 07/05/2014");
//! # }
//! ```
//!
//! The `replace` methods are actually polymorphic in the replacement, which
//! provides more flexibility than is seen here. (See the documentation for
//! `Regex::replace` for more details.)
//!
//! # Pay for what you use
//!
//! With respect to searching text with a regular expression, there are three
//! questions that can be asked:
//!
//! 1. Does the text match this expression?
//! 2. If so, where does it match?
//! 3. Where are the submatches?
//!
//! Generally speaking, this crate could provide a function to answer only #3,
//! which would subsume #1 and #2 automatically. However, it can be
//! significantly more expensive to compute the location of submatches, so it's
//! best not to do it if you don't need to.
//!
//! Therefore, only use what you need. For example, don't use `find` if you
//! only need to test if an expression matches a string. (Use `is_match`
//! instead.)
//!
//! # Unicode
//!
//! This implementation executes regular expressions **only** on sequences of
//! UTF8 codepoints while exposing match locations as byte indices.
//!
//! Currently, only naive case folding is supported. Namely, when matching
//! case insensitively, the characters are first converted to their uppercase
//! forms and then compared.
//!
//! Regular expressions themselves are also **only** interpreted as a sequence
//! of UTF8 codepoints. This means you can embed Unicode characters directly
//! into your expression:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(syntax)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(?i)Δ+");
//! assert_eq!(re.find("ΔδΔ"), Some((0, 6)));
//! # }
//! ```
//!
//! Finally, Unicode general categories and scripts are available as character
//! classes. For example, you can match a sequence of numerals, Greek or
//! Cherokee letters:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(syntax)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"[\pN\p{Greek}\p{Cherokee}]+");
//! assert_eq!(re.find("abcΔᎠβⅠᏴγδⅡxyz"), Some((3, 23)));
//! # }
//! ```
//!
//! # Syntax
//!
//! The syntax supported in this crate is almost in an exact correspondence
//! with the syntax supported by RE2.
//!
//! ## Matching one character
//!
//! <pre class="rust">
//!. any character except new line (includes new line with s flag)
//! [xyz] A character class matching either x, y or z.
//! [^xyz] A character class matching any character except x, y and z.
//! [a-z] A character class matching any character in range a-z.
//! \d Perl character class ([0-9])
//! \D Negated Perl character class ([^0-9])
//! [:alpha:] ASCII character class ([A-Za-z])
//! [:^alpha:] Negated ASCII character class ([^A-Za-z])
//! \pN One letter name Unicode character class
//! \p{Greek} Unicode character class (general category or script)
//! \PN Negated one letter name Unicode character class
//! \P{Greek} negated Unicode character class (general category or script)
//! </pre>
//!
//! Any named character class may appear inside a bracketed `[...]` character
//! class. For example, `[\p{Greek}\pN]` matches any Greek or numeral
//! character.
//!
//! ## Composites
//!
//! <pre class="rust">
//! xy concatenation (x followed by y)
//! x|y alternation (x or y, prefer x)
//! </pre>
//!
//! ## Repetitions
//!
//! <pre class="rust">
//! x* zero or more of x (greedy)
//! x+ one or more of x (greedy)
//! x? zero or one of x (greedy)
//! x*? zero or more of x (ungreedy)
//! x+? one or more of x (ungreedy)
//! x?? zero or one of x (ungreedy)
//! x{n,m} at least n and at most x (greedy)
//! x{n,} at least n x (greedy)
//! x{n} exactly n x
//! x{n,m}? at least n and at most x (ungreedy)
//! x{n,}? at least n x (ungreedy)
//! x{n}? exactly n x
//! </pre>
//!
//! ## Empty matches
//!
//! <pre class="rust">
//! ^ the beginning of text (or start-of-line with multi-line mode)
//! $ the end of text (or end-of-line with multi-line mode)
//! \A only the beginning of text (even with multi-line mode enabled)
//! \z only the end of text (even with multi-line mode enabled)
//! \b a Unicode word boundary (\w on one side and \W, \A, or \z on other)
//! \B not a Unicode word boundary
//! </pre>
//!
//! ## Grouping and flags
//!
//! <pre class="rust">
//! (exp) numbered capture group (indexed by opening parenthesis)
//! (?P<name>exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
//! (?:exp) non-capturing group
//! (?flags) set flags within current group
//! (?flags:exp) set flags for exp (non-capturing)
//! </pre>
//!
//! Flags are each a single character. For example, `(?x)` sets the flag `x`
//! and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
//! the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
//! the `x` flag and clears the `y` flag.
//!
//! All flags are by default disabled. They are:
//!
//! <pre class="rust">
//! i case insensitive
//! m multi-line mode: ^ and $ match begin/end of line
//! s allow. to match \n
//! U swap the meaning of x* and x*?
//! </pre>
//!
//! Here's an example that matches case insensitively for only part of the
//! expression:
//!
//! ```rust
//! # #![feature(phase)]
//! # extern crate regex; #[phase(syntax)] extern crate regex_macros;
//! # fn main() {
//! let re = regex!(r"(?i)a+(?-i)b+");
//! let cap = re.captures("AaAaAbbBBBb").unwrap();
//! assert_eq!(cap.at(0), "AaAaAbb");
//! # }
//! ```
//!
//! Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
//! `b`.
//!
//! ## Escape sequences
//!
//! <pre class="rust">
//! \* literal *, works for any punctuation character: \.+*?()|[]{}^$
//! \a bell (\x07)
//! \f form feed (\x0C)
//! \t horizontal tab
//! \n new line
//! \r carriage return
//! \v vertical tab (\x0B)
//! \123 octal character code (up to three digits)
//! \x7F hex character code (exactly two digits)
//! \x{10FFFF} any hex character code corresponding to a valid UTF8 codepoint
//! </pre>
//!
//! ## Perl character classes (Unicode friendly)
//!
//! <pre class="rust">
//! \d digit ([0-9] + \p{Nd})
//! \D not digit
//! \s whitespace ([\t\n\f\r ] + \p{Z})
//! \S not whitespace
//! \w word character ([0-9A-Za-z_] + \p{L})
//! \W not word character
//! </pre>
//!
//! ## ASCII character classes
//!
//! <pre class="rust">
//! [:alnum:] alphanumeric ([0-9A-Za-z])
//! [:alpha:] alphabetic ([A-Za-z])
//! [:ascii:] ASCII ([\x00-\x7F])
//! [:blank:] blank ([\t ])
//! [:cntrl:] control ([\x00-\x1F\x7F])
//! [:digit:] digits ([0-9])
//! [:graph:] graphical ([!-~])
//! [:lower:] lower case ([a-z])
//! [:print:] printable ([ -~])
//! [:punct:] punctuation ([!-/:-@[-`{-~])
//! [:space:] whitespace ([\t\n\v\f\r ])
//! [:upper:] upper case ([A-Z])
//! [:word:] word characters ([0-9A-Za-z_])
//! [:xdigit:] hex digit ([0-9A-Fa-f])
//! </pre>
//!
//! # Untrusted input
//!
//! There are two factors to consider here: untrusted regular expressions and
//! untrusted search text.
//!
//! Currently, there are no counter-measures in place to prevent a malicious
//! user from writing an expression that may use a lot of resources. One such
//! example is to repeat counted repetitions: `((a{100}){100}){100}` will try
//! to repeat the `a` instruction `100^3` times. Essentially, this means it's
//! very easy for an attacker to exhaust your system's memory if they are
//! allowed to execute arbitrary regular expressions. A possible solution to
//! this is to impose a hard limit on the size of a compiled expression, but it
//! does not yet exist.
//!
//! The story is a bit better with untrusted search text, since this crate's
//! implementation provides `O(nm)` search where `n` is the number of
//! characters in the search text and `m` is the number of instructions in a
//! compiled expression.
#![crate_id = "regex#0.11-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![experimental]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate collections;
#[cfg(test)]
extern crate stdtest = "test";
#[cfg(test)]
extern crate rand;
// During tests, this links with the `regex` crate so that the `regex!` macro
// can be tested.
#[cfg(test)]
extern crate regex;
pub use parse::Error;
pub use re::{Regex, Captures, SubCaptures, SubCapturesPos};
pub use re::{FindCaptures, FindMatches};
pub use re::{Replacer, NoExpand, RegexSplits, RegexSplitsN};
pub use re::{quote, is_match};
mod compile;
mod parse;
mod re;
mod vm;
// FIXME(#13725) windows needs fixing.
#[cfg(test, not(windows))]
mod test;
/// The `program` module exists to support the `regex!` macro. Do not use.
#[doc(hidden)]
pub mod native {
// Exporting this stuff is bad form, but it's necessary for two reasons.
// Firstly, the `regex!` syntax extension is in a different crate and
// requires access to the representation of a regex (particularly the
// instruction set) in order to compile to native Rust. This could be
// mitigated if `regex!` was defined in the same crate, but this has
// undesirable consequences (such as requiring a dependency on
// `libsyntax`).
//
// Secondly, the code generated generated by `regex!` must *also* be able
// to access various functions in this crate to reduce code duplication
// and to provide a value with precisely the same `Regex` type in this
// crate. This, AFAIK, is impossible to mitigate.
//
// On the bright side, `rustdoc` lets us hide this from the public API
// documentation.
pub use compile::{
Program,
OneChar, CharClass, Any, Save, Jump, Split,
Match, EmptyBegin, EmptyEnd, EmptyWordBoundary,
};
pub use parse::{
FLAG_EMPTY, FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL,
FLAG_SWAP_GREED, FLAG_NEGATED,
};
pub use re::{Dynamic, Native};
pub use vm::{
MatchKind, Exists, Location, Submatches,
StepState, StepMatchEarlyReturn, StepMatch, StepContinue,
CharReader, find_prefix,
};
} | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
installed_packages.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.
// Listing installed packages
use rustc::metadata::filesearch::rust_path;
use path_util::*;
use std::os;
use std::io;
use std::io::fs;
pub fn list_installed_packages(f: |&CrateId| -> bool) -> bool {
let workspaces = rust_path();
for p in workspaces.iter() {
let binfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("bin"))
};
for exec in binfiles.iter() {
// FIXME (#9639): This needs to handle non-utf8 paths
match exec.filestem_str() {
None => (),
Some(exec_path) => {
if!f(&CrateId::new(exec_path)) {
return false;
}
}
}
}
let libfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("lib"))
};
for lib in libfiles.iter() {
debug!("Full name: {}", lib.display());
match has_library(lib) {
Some(basename) => {
let parent = p.join("lib");
debug!("parent = {}, child = {}",
parent.display(), lib.display());
let rel_p = lib.path_relative_from(&parent).unwrap();
debug!("Rel: {}", rel_p.display());
let rel_path = rel_p.join(basename);
rel_path.display().with_str(|s| {
debug!("Rel name: {}", s);
f(&CrateId::new(s));
});
}
None => ()
}
};
}
true
}
pub fn | (p: &Path) -> Option<~str> {
let files = {
let _guard = io::ignore_io_error();
fs::readdir(p)
};
for path in files.iter() {
if path.extension_str() == Some(os::consts::DLL_EXTENSION) {
let stuff : &str = path.filestem_str().expect("has_library: weird path");
let mut stuff2 = stuff.split_str("-");
let stuff3: ~[&str] = stuff2.collect();
// argh
let chars_to_drop = os::consts::DLL_PREFIX.len();
return Some(stuff3[0].slice(chars_to_drop, stuff3[0].len()).to_owned());
}
}
None
}
pub fn package_is_installed(p: &CrateId) -> bool {
let mut is_installed = false;
list_installed_packages(|installed| {
if installed == p {
is_installed = true;
false
} else {
true
}
});
is_installed
}
| has_library | identifier_name |
installed_packages.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.
// Listing installed packages
use rustc::metadata::filesearch::rust_path;
use path_util::*;
use std::os;
use std::io;
use std::io::fs; | let workspaces = rust_path();
for p in workspaces.iter() {
let binfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("bin"))
};
for exec in binfiles.iter() {
// FIXME (#9639): This needs to handle non-utf8 paths
match exec.filestem_str() {
None => (),
Some(exec_path) => {
if!f(&CrateId::new(exec_path)) {
return false;
}
}
}
}
let libfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("lib"))
};
for lib in libfiles.iter() {
debug!("Full name: {}", lib.display());
match has_library(lib) {
Some(basename) => {
let parent = p.join("lib");
debug!("parent = {}, child = {}",
parent.display(), lib.display());
let rel_p = lib.path_relative_from(&parent).unwrap();
debug!("Rel: {}", rel_p.display());
let rel_path = rel_p.join(basename);
rel_path.display().with_str(|s| {
debug!("Rel name: {}", s);
f(&CrateId::new(s));
});
}
None => ()
}
};
}
true
}
pub fn has_library(p: &Path) -> Option<~str> {
let files = {
let _guard = io::ignore_io_error();
fs::readdir(p)
};
for path in files.iter() {
if path.extension_str() == Some(os::consts::DLL_EXTENSION) {
let stuff : &str = path.filestem_str().expect("has_library: weird path");
let mut stuff2 = stuff.split_str("-");
let stuff3: ~[&str] = stuff2.collect();
// argh
let chars_to_drop = os::consts::DLL_PREFIX.len();
return Some(stuff3[0].slice(chars_to_drop, stuff3[0].len()).to_owned());
}
}
None
}
pub fn package_is_installed(p: &CrateId) -> bool {
let mut is_installed = false;
list_installed_packages(|installed| {
if installed == p {
is_installed = true;
false
} else {
true
}
});
is_installed
} |
pub fn list_installed_packages(f: |&CrateId| -> bool) -> bool { | random_line_split |
installed_packages.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.
// Listing installed packages
use rustc::metadata::filesearch::rust_path;
use path_util::*;
use std::os;
use std::io;
use std::io::fs;
pub fn list_installed_packages(f: |&CrateId| -> bool) -> bool {
let workspaces = rust_path();
for p in workspaces.iter() {
let binfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("bin"))
};
for exec in binfiles.iter() {
// FIXME (#9639): This needs to handle non-utf8 paths
match exec.filestem_str() {
None => (),
Some(exec_path) => |
}
}
let libfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("lib"))
};
for lib in libfiles.iter() {
debug!("Full name: {}", lib.display());
match has_library(lib) {
Some(basename) => {
let parent = p.join("lib");
debug!("parent = {}, child = {}",
parent.display(), lib.display());
let rel_p = lib.path_relative_from(&parent).unwrap();
debug!("Rel: {}", rel_p.display());
let rel_path = rel_p.join(basename);
rel_path.display().with_str(|s| {
debug!("Rel name: {}", s);
f(&CrateId::new(s));
});
}
None => ()
}
};
}
true
}
pub fn has_library(p: &Path) -> Option<~str> {
let files = {
let _guard = io::ignore_io_error();
fs::readdir(p)
};
for path in files.iter() {
if path.extension_str() == Some(os::consts::DLL_EXTENSION) {
let stuff : &str = path.filestem_str().expect("has_library: weird path");
let mut stuff2 = stuff.split_str("-");
let stuff3: ~[&str] = stuff2.collect();
// argh
let chars_to_drop = os::consts::DLL_PREFIX.len();
return Some(stuff3[0].slice(chars_to_drop, stuff3[0].len()).to_owned());
}
}
None
}
pub fn package_is_installed(p: &CrateId) -> bool {
let mut is_installed = false;
list_installed_packages(|installed| {
if installed == p {
is_installed = true;
false
} else {
true
}
});
is_installed
}
| {
if !f(&CrateId::new(exec_path)) {
return false;
}
} | conditional_block |
installed_packages.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.
// Listing installed packages
use rustc::metadata::filesearch::rust_path;
use path_util::*;
use std::os;
use std::io;
use std::io::fs;
pub fn list_installed_packages(f: |&CrateId| -> bool) -> bool {
let workspaces = rust_path();
for p in workspaces.iter() {
let binfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("bin"))
};
for exec in binfiles.iter() {
// FIXME (#9639): This needs to handle non-utf8 paths
match exec.filestem_str() {
None => (),
Some(exec_path) => {
if!f(&CrateId::new(exec_path)) {
return false;
}
}
}
}
let libfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("lib"))
};
for lib in libfiles.iter() {
debug!("Full name: {}", lib.display());
match has_library(lib) {
Some(basename) => {
let parent = p.join("lib");
debug!("parent = {}, child = {}",
parent.display(), lib.display());
let rel_p = lib.path_relative_from(&parent).unwrap();
debug!("Rel: {}", rel_p.display());
let rel_path = rel_p.join(basename);
rel_path.display().with_str(|s| {
debug!("Rel name: {}", s);
f(&CrateId::new(s));
});
}
None => ()
}
};
}
true
}
pub fn has_library(p: &Path) -> Option<~str> {
let files = {
let _guard = io::ignore_io_error();
fs::readdir(p)
};
for path in files.iter() {
if path.extension_str() == Some(os::consts::DLL_EXTENSION) {
let stuff : &str = path.filestem_str().expect("has_library: weird path");
let mut stuff2 = stuff.split_str("-");
let stuff3: ~[&str] = stuff2.collect();
// argh
let chars_to_drop = os::consts::DLL_PREFIX.len();
return Some(stuff3[0].slice(chars_to_drop, stuff3[0].len()).to_owned());
}
}
None
}
pub fn package_is_installed(p: &CrateId) -> bool | {
let mut is_installed = false;
list_installed_packages(|installed| {
if installed == p {
is_installed = true;
false
} else {
true
}
});
is_installed
} | identifier_body |
|
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player {
Player::new(weapon, armor, rings)
}
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_points, damage, armor)
}
pub trait Character {
fn hit_points(&self) -> u32;
fn damage(&self) -> u32;
fn armor(&self) -> u32;
fn beats(&self, other: &Character) -> bool {
let win_after = turns_to_beat(self.damage(), other.hit_points(), other.armor());
let lose_after = turns_to_beat(other.damage(), self.hit_points(), self.armor());
win_after <= lose_after
}
}
fn turns_to_beat(damage: u32, hit_points: u32, armor: u32) -> u32 {
let effective_damage = if damage > armor { damage - armor } else | ;
let (div, rem) = hit_points.div_rem(&effective_damage);
if rem == 0 { div } else { div + 1 }
}
| { 1 } | conditional_block |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player {
Player::new(weapon, armor, rings)
}
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_points, damage, armor)
}
pub trait Character {
fn hit_points(&self) -> u32;
fn damage(&self) -> u32;
fn armor(&self) -> u32;
fn beats(&self, other: &Character) -> bool {
let win_after = turns_to_beat(self.damage(), other.hit_points(), other.armor());
let lose_after = turns_to_beat(other.damage(), self.hit_points(), self.armor());
win_after <= lose_after
}
}
fn | (damage: u32, hit_points: u32, armor: u32) -> u32 {
let effective_damage = if damage > armor { damage - armor } else { 1 };
let (div, rem) = hit_points.div_rem(&effective_damage);
if rem == 0 { div } else { div + 1 }
}
| turns_to_beat | identifier_name |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player |
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_points, damage, armor)
}
pub trait Character {
fn hit_points(&self) -> u32;
fn damage(&self) -> u32;
fn armor(&self) -> u32;
fn beats(&self, other: &Character) -> bool {
let win_after = turns_to_beat(self.damage(), other.hit_points(), other.armor());
let lose_after = turns_to_beat(other.damage(), self.hit_points(), self.armor());
win_after <= lose_after
}
}
fn turns_to_beat(damage: u32, hit_points: u32, armor: u32) -> u32 {
let effective_damage = if damage > armor { damage - armor } else { 1 };
let (div, rem) = hit_points.div_rem(&effective_damage);
if rem == 0 { div } else { div + 1 }
}
| {
Player::new(weapon, armor, rings)
} | identifier_body |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player {
Player::new(weapon, armor, rings)
}
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_points, damage, armor)
}
pub trait Character { | fn damage(&self) -> u32;
fn armor(&self) -> u32;
fn beats(&self, other: &Character) -> bool {
let win_after = turns_to_beat(self.damage(), other.hit_points(), other.armor());
let lose_after = turns_to_beat(other.damage(), self.hit_points(), self.armor());
win_after <= lose_after
}
}
fn turns_to_beat(damage: u32, hit_points: u32, armor: u32) -> u32 {
let effective_damage = if damage > armor { damage - armor } else { 1 };
let (div, rem) = hit_points.div_rem(&effective_damage);
if rem == 0 { div } else { div + 1 }
} | fn hit_points(&self) -> u32; | random_line_split |
parallel.rs | // Benchmark from https://github.com/lschmierer/ecs_bench
#![feature(test)]
extern crate test;
use calx_ecs::{build_ecs, Entity};
use serde::{Deserialize, Serialize};
use test::Bencher;
pub const N: usize = 10000;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct R {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W1 {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W2 {
pub x: f32,
}
build_ecs! {
r: R,
w1: W1,
w2: W2,
}
fn build() -> Ecs {
let mut ecs = Ecs::new();
for _ in 0..N {
let e = ecs.make();
ecs.r.insert(e, R { x: 0.0 });
ecs.w1.insert(e, W1 { x: 0.0 });
ecs.w2.insert(e, W2 { x: 0.0 });
}
ecs
}
#[bench]
fn bench_build(b: &mut Bencher) |
#[bench]
fn bench_update(b: &mut Bencher) {
let mut ecs = build();
b.iter(|| {
let es: Vec<Entity> = ecs.r.ent_iter().cloned().collect();
for &e in &es {
let rx = ecs.r[e].x;
ecs.w1.get_mut(e).map(|w1| w1.x = rx);
}
for &e in &es {
let rx = ecs.r[e].x;
ecs.w2.get_mut(e).map(|w2| w2.x = rx);
}
});
}
| { b.iter(build); } | identifier_body |
parallel.rs | // Benchmark from https://github.com/lschmierer/ecs_bench
#![feature(test)]
extern crate test;
use calx_ecs::{build_ecs, Entity};
use serde::{Deserialize, Serialize};
use test::Bencher;
| pub const N: usize = 10000;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct R {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W1 {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W2 {
pub x: f32,
}
build_ecs! {
r: R,
w1: W1,
w2: W2,
}
fn build() -> Ecs {
let mut ecs = Ecs::new();
for _ in 0..N {
let e = ecs.make();
ecs.r.insert(e, R { x: 0.0 });
ecs.w1.insert(e, W1 { x: 0.0 });
ecs.w2.insert(e, W2 { x: 0.0 });
}
ecs
}
#[bench]
fn bench_build(b: &mut Bencher) { b.iter(build); }
#[bench]
fn bench_update(b: &mut Bencher) {
let mut ecs = build();
b.iter(|| {
let es: Vec<Entity> = ecs.r.ent_iter().cloned().collect();
for &e in &es {
let rx = ecs.r[e].x;
ecs.w1.get_mut(e).map(|w1| w1.x = rx);
}
for &e in &es {
let rx = ecs.r[e].x;
ecs.w2.get_mut(e).map(|w2| w2.x = rx);
}
});
} | random_line_split |
|
parallel.rs | // Benchmark from https://github.com/lschmierer/ecs_bench
#![feature(test)]
extern crate test;
use calx_ecs::{build_ecs, Entity};
use serde::{Deserialize, Serialize};
use test::Bencher;
pub const N: usize = 10000;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct R {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W1 {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W2 {
pub x: f32,
}
build_ecs! {
r: R,
w1: W1,
w2: W2,
}
fn build() -> Ecs {
let mut ecs = Ecs::new();
for _ in 0..N {
let e = ecs.make();
ecs.r.insert(e, R { x: 0.0 });
ecs.w1.insert(e, W1 { x: 0.0 });
ecs.w2.insert(e, W2 { x: 0.0 });
}
ecs
}
#[bench]
fn bench_build(b: &mut Bencher) { b.iter(build); }
#[bench]
fn | (b: &mut Bencher) {
let mut ecs = build();
b.iter(|| {
let es: Vec<Entity> = ecs.r.ent_iter().cloned().collect();
for &e in &es {
let rx = ecs.r[e].x;
ecs.w1.get_mut(e).map(|w1| w1.x = rx);
}
for &e in &es {
let rx = ecs.r[e].x;
ecs.w2.get_mut(e).map(|w2| w2.x = rx);
}
});
}
| bench_update | identifier_name |
mod.rs | #[macro_use]
pub mod macros;
/// Constants like memory locations
pub mod consts;
/// Debugging support
pub mod debug;
/// Devices
pub mod device;
/// Global descriptor table
pub mod gdt;
/// Graphical debug
#[cfg(feature = "graphical_debug")]
mod graphical_debug;
/// Interrupt instructions
#[macro_use]
pub mod interrupt;
/// Interrupt descriptor table
pub mod idt;
| pub mod ipi;
/// Paging
pub mod paging;
/// Page table isolation
pub mod pti;
pub mod rmm;
/// Initialization and start function
pub mod start;
/// Stop function
pub mod stop;
pub use ::rmm::X8664Arch as CurrentRmmArch;
// Flags
pub mod flags {
pub const SHIFT_SINGLESTEP: usize = 8;
pub const FLAG_SINGLESTEP: usize = 1 << SHIFT_SINGLESTEP;
pub const FLAG_INTERRUPTS: usize = 1 << 9;
} | /// Inter-processor interrupts | random_line_split |
moves-based-on-type-no-recursive-stack-closure.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.
// Tests correct kind-checking of the reason stack closures without the :Copy
// bound must be noncopyable. For details see
// http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
extern crate debug;
struct R<'a> {
// This struct is needed to create the
// otherwise infinite type of a fn that
// accepts itself as argument:
c: |&mut R, bool|: 'a | let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
println!("{:?}", msg);
},
None => fail!("oops"),
}
}
})
}
fn conspirator(f: |&mut R, bool|) {
let mut r = R {c: f};
f(&mut r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() } | }
fn innocent_looking_victim() { | random_line_split |
moves-based-on-type-no-recursive-stack-closure.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.
// Tests correct kind-checking of the reason stack closures without the :Copy
// bound must be noncopyable. For details see
// http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
extern crate debug;
struct R<'a> {
// This struct is needed to create the
// otherwise infinite type of a fn that
// accepts itself as argument:
c: |&mut R, bool|: 'a
}
fn innocent_looking_victim() |
fn conspirator(f: |&mut R, bool|) {
let mut r = R {c: f};
f(&mut r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() }
| {
let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
println!("{:?}", msg);
},
None => fail!("oops"),
}
}
})
} | identifier_body |
moves-based-on-type-no-recursive-stack-closure.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.
// Tests correct kind-checking of the reason stack closures without the :Copy
// bound must be noncopyable. For details see
// http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
extern crate debug;
struct R<'a> {
// This struct is needed to create the
// otherwise infinite type of a fn that
// accepts itself as argument:
c: |&mut R, bool|: 'a
}
fn innocent_looking_victim() {
let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else |
})
}
fn conspirator(f: |&mut R, bool|) {
let mut r = R {c: f};
f(&mut r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() }
| {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
println!("{:?}", msg);
},
None => fail!("oops"),
}
} | conditional_block |
moves-based-on-type-no-recursive-stack-closure.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.
// Tests correct kind-checking of the reason stack closures without the :Copy
// bound must be noncopyable. For details see
// http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
extern crate debug;
struct R<'a> {
// This struct is needed to create the
// otherwise infinite type of a fn that
// accepts itself as argument:
c: |&mut R, bool|: 'a
}
fn | () {
let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
println!("{:?}", msg);
},
None => fail!("oops"),
}
}
})
}
fn conspirator(f: |&mut R, bool|) {
let mut r = R {c: f};
f(&mut r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() }
| innocent_looking_victim | identifier_name |
bouncy_circles.rs | #![feature (test)]
#![feature (macro_vis_matcher)]
extern crate test;
#[macro_use]
extern crate time_steward;
#[macro_use]
extern crate glium;
extern crate nalgebra;
extern crate rand;
extern crate boolinator;
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use test::Bencher;
use time_steward::{DeterministicRandomId};
use time_steward::{PersistentTypeId, ListedType, PersistentlyIdentifiedType, DataTimelineCellTrait, Basics as BasicsTrait};
//use time_steward::stewards::{simple_full as steward_module};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Event, DataTimelineCell, EventAccessor, FutureCleanupAccessor, SnapshotAccessor, simple_timeline};
use simple_timeline::{SimpleTimeline, GetVarying};
#[path = "../dev-shared/bouncy_circles.rs"] mod bouncy_circles;
use bouncy_circles::*;
#[bench]
fn bouncy_circles_straightforward(bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 0..1000 {
let time = 10*SECOND*index/1000;
steward.snapshot_before(& time).expect("steward failed to provide snapshot");
steward.forget_before(& time);
}
})
}
#[bench]
fn | (bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb{ coordinates: [ARENA_SIZE/3,ARENA_SIZE/3]}).unwrap();
}
for index in 0..1000 {
let time = 10*SECOND*index/1000;
steward.snapshot_before(& time).expect("steward failed to provide snapshot");
steward.forget_before(& time);
}
})
}
/*
#[bench]
fn bouncy_circles_disturbed_retroactive (bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: amortized::Steward<Basics> = amortized::Steward::from_constants(());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize::new()).unwrap();
steward.snapshot_before(& (10*SECOND)).expect("steward failed to provide snapshot");
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb::new ([ARENA_SIZE/3,ARENA_SIZE/3])).unwrap();
steward.snapshot_before(& (10*SECOND)).expect("steward failed to provide snapshot");
}
})
}
*/
| bouncy_circles_disturbed | identifier_name |
bouncy_circles.rs | #![feature (test)]
#![feature (macro_vis_matcher)]
extern crate test;
#[macro_use]
extern crate time_steward;
#[macro_use]
extern crate glium;
extern crate nalgebra;
extern crate rand;
extern crate boolinator;
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use test::Bencher;
use time_steward::{DeterministicRandomId};
use time_steward::{PersistentTypeId, ListedType, PersistentlyIdentifiedType, DataTimelineCellTrait, Basics as BasicsTrait};
//use time_steward::stewards::{simple_full as steward_module};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Event, DataTimelineCell, EventAccessor, FutureCleanupAccessor, SnapshotAccessor, simple_timeline};
use simple_timeline::{SimpleTimeline, GetVarying};
#[path = "../dev-shared/bouncy_circles.rs"] mod bouncy_circles;
use bouncy_circles::*;
#[bench]
fn bouncy_circles_straightforward(bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 0..1000 {
let time = 10*SECOND*index/1000;
steward.snapshot_before(& time).expect("steward failed to provide snapshot");
steward.forget_before(& time);
}
})
}
#[bench]
fn bouncy_circles_disturbed (bencher: &mut Bencher) |
/*
#[bench]
fn bouncy_circles_disturbed_retroactive (bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: amortized::Steward<Basics> = amortized::Steward::from_constants(());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize::new()).unwrap();
steward.snapshot_before(& (10*SECOND)).expect("steward failed to provide snapshot");
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb::new ([ARENA_SIZE/3,ARENA_SIZE/3])).unwrap();
steward.snapshot_before(& (10*SECOND)).expect("steward failed to provide snapshot");
}
})
}
*/
| {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb{ coordinates: [ARENA_SIZE/3,ARENA_SIZE/3]}).unwrap();
}
for index in 0..1000 {
let time = 10*SECOND*index/1000;
steward.snapshot_before(& time).expect("steward failed to provide snapshot");
steward.forget_before(& time);
}
})
} | identifier_body |
bouncy_circles.rs | #![feature (test)]
#![feature (macro_vis_matcher)]
extern crate test;
#[macro_use]
extern crate time_steward;
#[macro_use]
extern crate glium;
extern crate nalgebra;
extern crate rand;
extern crate boolinator;
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use test::Bencher;
use time_steward::{DeterministicRandomId};
use time_steward::{PersistentTypeId, ListedType, PersistentlyIdentifiedType, DataTimelineCellTrait, Basics as BasicsTrait};
//use time_steward::stewards::{simple_full as steward_module};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Event, DataTimelineCell, EventAccessor, FutureCleanupAccessor, SnapshotAccessor, simple_timeline};
use simple_timeline::{SimpleTimeline, GetVarying};
#[path = "../dev-shared/bouncy_circles.rs"] mod bouncy_circles;
use bouncy_circles::*;
#[bench]
fn bouncy_circles_straightforward(bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 0..1000 {
let time = 10*SECOND*index/1000;
steward.snapshot_before(& time).expect("steward failed to provide snapshot");
steward.forget_before(& time);
}
})
}
#[bench]
fn bouncy_circles_disturbed (bencher: &mut Bencher) {
bencher.iter(|| { | steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb{ coordinates: [ARENA_SIZE/3,ARENA_SIZE/3]}).unwrap();
}
for index in 0..1000 {
let time = 10*SECOND*index/1000;
steward.snapshot_before(& time).expect("steward failed to provide snapshot");
steward.forget_before(& time);
}
})
}
/*
#[bench]
fn bouncy_circles_disturbed_retroactive (bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: amortized::Steward<Basics> = amortized::Steward::from_constants(());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize::new()).unwrap();
steward.snapshot_before(& (10*SECOND)).expect("steward failed to provide snapshot");
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb::new ([ARENA_SIZE/3,ARENA_SIZE/3])).unwrap();
steward.snapshot_before(& (10*SECOND)).expect("steward failed to provide snapshot");
}
})
}
*/ | let mut steward: Steward = Steward::from_globals (make_globals()); | random_line_split |
logging-separate-lines.rs | // Copyright 2013-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.
// ignore-android
// ignore-windows
// exec-env:RUST_LOG=debug
#[macro_use]
extern crate log;
use std::io::Command;
use std::os;
use std::str;
fn main() | {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
return
}
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(lines.next().unwrap().contains("bar"));
} | identifier_body |
|
logging-separate-lines.rs | // Copyright 2013-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.
// ignore-android
// ignore-windows
// exec-env:RUST_LOG=debug
#[macro_use]
extern crate log;
use std::io::Command;
use std::os;
use std::str;
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" |
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(lines.next().unwrap().contains("bar"));
}
| {
debug!("foo");
debug!("bar");
return
} | conditional_block |
logging-separate-lines.rs | // Copyright 2013-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.
| extern crate log;
use std::io::Command;
use std::os;
use std::str;
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
return
}
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(lines.next().unwrap().contains("bar"));
} | // ignore-android
// ignore-windows
// exec-env:RUST_LOG=debug
#[macro_use] | random_line_split |
logging-separate-lines.rs | // Copyright 2013-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.
// ignore-android
// ignore-windows
// exec-env:RUST_LOG=debug
#[macro_use]
extern crate log;
use std::io::Command;
use std::os;
use std::str;
fn | () {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
return
}
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(lines.next().unwrap().contains("bar"));
}
| main | identifier_name |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use nonzero::NonZero;
use std::cell::Cell;
use std::fmt;
use webrender_api;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left, | Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
pub struct KeyModifiers: u8 {
const NONE = 0x00;
const SHIFT = 0x01;
const CONTROL = 0x02;
const ALT = 0x04;
const SUPER = 0x08;
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum TraversalDirection {
Forward(usize),
Back(usize),
}
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
index: u32,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
index: 0,
}));
});
}
fn next_index(&mut self) -> NonZero<u32> {
self.index += 1;
NonZero::new(self.index).expect("pipeline id index wrapped!")
}
fn next_pipeline_id(&mut self) -> PipelineId {
PipelineId {
namespace_id: self.id,
index: PipelineIndex(self.next_index()),
}
}
fn next_browsing_context_id(&mut self) -> BrowsingContextId {
BrowsingContextId {
namespace_id: self.id,
index: BrowsingContextIndex(self.next_index()),
}
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineIndex(pub NonZero<u32>);
malloc_size_of_is_0!(PipelineIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next_pipeline_id();
tls.set(Some(namespace));
new_pipeline_id
})
}
pub fn to_webrender(&self) -> webrender_api::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_api::PipelineId(namespace_id, index.get())
}
#[allow(unsafe_code)]
pub fn from_webrender(pipeline: webrender_api::PipelineId) -> PipelineId {
let webrender_api::PipelineId(namespace_id, index) = pipeline;
unsafe {
PipelineId {
namespace_id: PipelineNamespaceId(namespace_id),
index: PipelineIndex(NonZero::new_unchecked(index)),
}
}
}
pub fn root_scroll_node(&self) -> webrender_api::ClipId {
webrender_api::ClipId::root_scroll_node(self.to_webrender())
}
pub fn root_scroll_id(&self) -> webrender_api::ExternalScrollId {
webrender_api::ExternalScrollId(0, self.to_webrender())
}
pub fn root_clip_and_scroll_info(&self) -> webrender_api::ClipAndScrollInfo {
webrender_api::ClipAndScrollInfo::simple(self.root_scroll_node())
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextIndex(pub NonZero<u32>);
malloc_size_of_is_0!(BrowsingContextIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextId {
pub namespace_id: PipelineNamespaceId,
pub index: BrowsingContextIndex,
}
impl BrowsingContextId {
pub fn new() -> BrowsingContextId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_browsing_context_id = namespace.next_browsing_context_id();
tls.set(Some(namespace));
new_browsing_context_id
})
}
}
impl fmt::Display for BrowsingContextId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let BrowsingContextIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
thread_local!(pub static TOP_LEVEL_BROWSING_CONTEXT_ID: Cell<Option<TopLevelBrowsingContextId>> = Cell::new(None));
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct TopLevelBrowsingContextId(BrowsingContextId);
impl TopLevelBrowsingContextId {
pub fn new() -> TopLevelBrowsingContextId {
TopLevelBrowsingContextId(BrowsingContextId::new())
}
/// Each script and layout thread should have the top-level browsing context id installed,
/// since it is used by crash reporting.
pub fn install(id: TopLevelBrowsingContextId) {
TOP_LEVEL_BROWSING_CONTEXT_ID.with(|tls| tls.set(Some(id)))
}
pub fn installed() -> Option<TopLevelBrowsingContextId> {
TOP_LEVEL_BROWSING_CONTEXT_ID.with(|tls| tls.get())
}
}
impl fmt::Display for TopLevelBrowsingContextId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(fmt)
}
}
impl From<TopLevelBrowsingContextId> for BrowsingContextId {
fn from(id: TopLevelBrowsingContextId) -> BrowsingContextId {
id.0
}
}
impl PartialEq<TopLevelBrowsingContextId> for BrowsingContextId {
fn eq(&self, rhs: &TopLevelBrowsingContextId) -> bool {
self.eq(&rhs.0)
}
}
impl PartialEq<BrowsingContextId> for TopLevelBrowsingContextId {
fn eq(&self, rhs: &BrowsingContextId) -> bool {
self.0.eq(rhs)
}
}
// We provide ids just for unit testing.
pub const TEST_NAMESPACE: PipelineNamespaceId = PipelineNamespaceId(1234);
#[allow(unsafe_code)]
#[cfg(feature = "unstable")]
pub const TEST_PIPELINE_INDEX: PipelineIndex = unsafe { PipelineIndex(NonZero::new_unchecked(5678)) };
#[cfg(feature = "unstable")]
pub const TEST_PIPELINE_ID: PipelineId = PipelineId { namespace_id: TEST_NAMESPACE, index: TEST_PIPELINE_INDEX };
#[allow(unsafe_code)]
#[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_INDEX: BrowsingContextIndex =
unsafe { BrowsingContextIndex(NonZero::new_unchecked(8765)) };
#[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId =
BrowsingContextId { namespace_id: TEST_NAMESPACE, index: TEST_BROWSING_CONTEXT_INDEX };
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum FrameType {
IFrame,
MozBrowserIFrame,
} | Down, | random_line_split |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use nonzero::NonZero;
use std::cell::Cell;
use std::fmt;
use webrender_api;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
pub struct KeyModifiers: u8 {
const NONE = 0x00;
const SHIFT = 0x01;
const CONTROL = 0x02;
const ALT = 0x04;
const SUPER = 0x08;
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum TraversalDirection {
Forward(usize),
Back(usize),
}
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
index: u32,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
index: 0,
}));
});
}
fn next_index(&mut self) -> NonZero<u32> {
self.index += 1;
NonZero::new(self.index).expect("pipeline id index wrapped!")
}
fn next_pipeline_id(&mut self) -> PipelineId {
PipelineId {
namespace_id: self.id,
index: PipelineIndex(self.next_index()),
}
}
fn next_browsing_context_id(&mut self) -> BrowsingContextId {
BrowsingContextId {
namespace_id: self.id,
index: BrowsingContextIndex(self.next_index()),
}
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineIndex(pub NonZero<u32>);
malloc_size_of_is_0!(PipelineIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next_pipeline_id();
tls.set(Some(namespace));
new_pipeline_id
})
}
pub fn to_webrender(&self) -> webrender_api::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_api::PipelineId(namespace_id, index.get())
}
#[allow(unsafe_code)]
pub fn from_webrender(pipeline: webrender_api::PipelineId) -> PipelineId {
let webrender_api::PipelineId(namespace_id, index) = pipeline;
unsafe {
PipelineId {
namespace_id: PipelineNamespaceId(namespace_id),
index: PipelineIndex(NonZero::new_unchecked(index)),
}
}
}
pub fn root_scroll_node(&self) -> webrender_api::ClipId {
webrender_api::ClipId::root_scroll_node(self.to_webrender())
}
pub fn root_scroll_id(&self) -> webrender_api::ExternalScrollId {
webrender_api::ExternalScrollId(0, self.to_webrender())
}
pub fn root_clip_and_scroll_info(&self) -> webrender_api::ClipAndScrollInfo |
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextIndex(pub NonZero<u32>);
malloc_size_of_is_0!(BrowsingContextIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextId {
pub namespace_id: PipelineNamespaceId,
pub index: BrowsingContextIndex,
}
impl BrowsingContextId {
pub fn new() -> BrowsingContextId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_browsing_context_id = namespace.next_browsing_context_id();
tls.set(Some(namespace));
new_browsing_context_id
})
}
}
impl fmt::Display for BrowsingContextId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let BrowsingContextIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
thread_local!(pub static TOP_LEVEL_BROWSING_CONTEXT_ID: Cell<Option<TopLevelBrowsingContextId>> = Cell::new(None));
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct TopLevelBrowsingContextId(BrowsingContextId);
impl TopLevelBrowsingContextId {
pub fn new() -> TopLevelBrowsingContextId {
TopLevelBrowsingContextId(BrowsingContextId::new())
}
/// Each script and layout thread should have the top-level browsing context id installed,
/// since it is used by crash reporting.
pub fn install(id: TopLevelBrowsingContextId) {
TOP_LEVEL_BROWSING_CONTEXT_ID.with(|tls| tls.set(Some(id)))
}
pub fn installed() -> Option<TopLevelBrowsingContextId> {
TOP_LEVEL_BROWSING_CONTEXT_ID.with(|tls| tls.get())
}
}
impl fmt::Display for TopLevelBrowsingContextId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(fmt)
}
}
impl From<TopLevelBrowsingContextId> for BrowsingContextId {
fn from(id: TopLevelBrowsingContextId) -> BrowsingContextId {
id.0
}
}
impl PartialEq<TopLevelBrowsingContextId> for BrowsingContextId {
fn eq(&self, rhs: &TopLevelBrowsingContextId) -> bool {
self.eq(&rhs.0)
}
}
impl PartialEq<BrowsingContextId> for TopLevelBrowsingContextId {
fn eq(&self, rhs: &BrowsingContextId) -> bool {
self.0.eq(rhs)
}
}
// We provide ids just for unit testing.
pub const TEST_NAMESPACE: PipelineNamespaceId = PipelineNamespaceId(1234);
#[allow(unsafe_code)]
#[cfg(feature = "unstable")]
pub const TEST_PIPELINE_INDEX: PipelineIndex = unsafe { PipelineIndex(NonZero::new_unchecked(5678)) };
#[cfg(feature = "unstable")]
pub const TEST_PIPELINE_ID: PipelineId = PipelineId { namespace_id: TEST_NAMESPACE, index: TEST_PIPELINE_INDEX };
#[allow(unsafe_code)]
#[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_INDEX: BrowsingContextIndex =
unsafe { BrowsingContextIndex(NonZero::new_unchecked(8765)) };
#[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId =
BrowsingContextId { namespace_id: TEST_NAMESPACE, index: TEST_BROWSING_CONTEXT_INDEX };
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum FrameType {
IFrame,
MozBrowserIFrame,
}
| {
webrender_api::ClipAndScrollInfo::simple(self.root_scroll_node())
} | identifier_body |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use nonzero::NonZero;
use std::cell::Cell;
use std::fmt;
use webrender_api;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
pub struct KeyModifiers: u8 {
const NONE = 0x00;
const SHIFT = 0x01;
const CONTROL = 0x02;
const ALT = 0x04;
const SUPER = 0x08;
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum TraversalDirection {
Forward(usize),
Back(usize),
}
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
index: u32,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
index: 0,
}));
});
}
fn next_index(&mut self) -> NonZero<u32> {
self.index += 1;
NonZero::new(self.index).expect("pipeline id index wrapped!")
}
fn next_pipeline_id(&mut self) -> PipelineId {
PipelineId {
namespace_id: self.id,
index: PipelineIndex(self.next_index()),
}
}
fn next_browsing_context_id(&mut self) -> BrowsingContextId {
BrowsingContextId {
namespace_id: self.id,
index: BrowsingContextIndex(self.next_index()),
}
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineIndex(pub NonZero<u32>);
malloc_size_of_is_0!(PipelineIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next_pipeline_id();
tls.set(Some(namespace));
new_pipeline_id
})
}
pub fn to_webrender(&self) -> webrender_api::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_api::PipelineId(namespace_id, index.get())
}
#[allow(unsafe_code)]
pub fn | (pipeline: webrender_api::PipelineId) -> PipelineId {
let webrender_api::PipelineId(namespace_id, index) = pipeline;
unsafe {
PipelineId {
namespace_id: PipelineNamespaceId(namespace_id),
index: PipelineIndex(NonZero::new_unchecked(index)),
}
}
}
pub fn root_scroll_node(&self) -> webrender_api::ClipId {
webrender_api::ClipId::root_scroll_node(self.to_webrender())
}
pub fn root_scroll_id(&self) -> webrender_api::ExternalScrollId {
webrender_api::ExternalScrollId(0, self.to_webrender())
}
pub fn root_clip_and_scroll_info(&self) -> webrender_api::ClipAndScrollInfo {
webrender_api::ClipAndScrollInfo::simple(self.root_scroll_node())
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextIndex(pub NonZero<u32>);
malloc_size_of_is_0!(BrowsingContextIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextId {
pub namespace_id: PipelineNamespaceId,
pub index: BrowsingContextIndex,
}
impl BrowsingContextId {
pub fn new() -> BrowsingContextId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_browsing_context_id = namespace.next_browsing_context_id();
tls.set(Some(namespace));
new_browsing_context_id
})
}
}
impl fmt::Display for BrowsingContextId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let BrowsingContextIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
thread_local!(pub static TOP_LEVEL_BROWSING_CONTEXT_ID: Cell<Option<TopLevelBrowsingContextId>> = Cell::new(None));
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
pub struct TopLevelBrowsingContextId(BrowsingContextId);
impl TopLevelBrowsingContextId {
pub fn new() -> TopLevelBrowsingContextId {
TopLevelBrowsingContextId(BrowsingContextId::new())
}
/// Each script and layout thread should have the top-level browsing context id installed,
/// since it is used by crash reporting.
pub fn install(id: TopLevelBrowsingContextId) {
TOP_LEVEL_BROWSING_CONTEXT_ID.with(|tls| tls.set(Some(id)))
}
pub fn installed() -> Option<TopLevelBrowsingContextId> {
TOP_LEVEL_BROWSING_CONTEXT_ID.with(|tls| tls.get())
}
}
impl fmt::Display for TopLevelBrowsingContextId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(fmt)
}
}
impl From<TopLevelBrowsingContextId> for BrowsingContextId {
fn from(id: TopLevelBrowsingContextId) -> BrowsingContextId {
id.0
}
}
impl PartialEq<TopLevelBrowsingContextId> for BrowsingContextId {
fn eq(&self, rhs: &TopLevelBrowsingContextId) -> bool {
self.eq(&rhs.0)
}
}
impl PartialEq<BrowsingContextId> for TopLevelBrowsingContextId {
fn eq(&self, rhs: &BrowsingContextId) -> bool {
self.0.eq(rhs)
}
}
// We provide ids just for unit testing.
pub const TEST_NAMESPACE: PipelineNamespaceId = PipelineNamespaceId(1234);
#[allow(unsafe_code)]
#[cfg(feature = "unstable")]
pub const TEST_PIPELINE_INDEX: PipelineIndex = unsafe { PipelineIndex(NonZero::new_unchecked(5678)) };
#[cfg(feature = "unstable")]
pub const TEST_PIPELINE_ID: PipelineId = PipelineId { namespace_id: TEST_NAMESPACE, index: TEST_PIPELINE_INDEX };
#[allow(unsafe_code)]
#[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_INDEX: BrowsingContextIndex =
unsafe { BrowsingContextIndex(NonZero::new_unchecked(8765)) };
#[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId =
BrowsingContextId { namespace_id: TEST_NAMESPACE, index: TEST_BROWSING_CONTEXT_INDEX };
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum FrameType {
IFrame,
MozBrowserIFrame,
}
| from_webrender | identifier_name |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mutex<Queue>>) {
for stream in listener.incoming() {
match stream {
Ok(mut stream) => {
let mut buf = [0; 256];
let data = stream.read(&mut buf);
if data.is_ok() {
let command = Command::from(&buf);
if command.is_ok() |
}
},
Err(_) => println!("Error"),
}
}
}
/// Creates a library from /home/$USER/Music, creates a tray icon if the feature is enabled, and
/// starts the server and the event loop.
fn main() {
// Initialize library
let library_path = env::home_dir();
if library_path.is_none() {
let _ = writeln!(&mut std::io::stderr(), "Error: cannot read home dir");
process::exit(1);
}
let library_path = library_path.unwrap().join("Music");
let library = Library::new_rc(&library_path);
let queue_for_server = {
let library = library.borrow();
Arc::clone(library.queue())
};
use tray;
let queue_for_tray = Arc::clone(&queue_for_server);
// Initialize tray icon
thread::spawn(move || {
tray::start_tray(&queue_for_tray);
});
// Initialize server
let listener = TcpListener::bind("127.0.0.1:5000");
if let Ok(listener) = listener {
thread::spawn(move || {
start_server(&listener, &queue_for_server);
});
library.borrow_mut().event_loop();
} else {
let _ = writeln!(&mut std::io::stderr(), "Error: could not start server");
process::exit(1);
}
}
| {
let mut queue = queue.lock().unwrap();
queue.push(command.unwrap(), Some(stream));
} | conditional_block |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mutex<Queue>>) {
for stream in listener.incoming() {
match stream {
Ok(mut stream) => {
let mut buf = [0; 256];
let data = stream.read(&mut buf);
if data.is_ok() {
let command = Command::from(&buf);
if command.is_ok() {
let mut queue = queue.lock().unwrap();
queue.push(command.unwrap(), Some(stream));
}
}
},
Err(_) => println!("Error"),
}
}
}
/// Creates a library from /home/$USER/Music, creates a tray icon if the feature is enabled, and
/// starts the server and the event loop.
fn main() {
// Initialize library
let library_path = env::home_dir();
if library_path.is_none() {
let _ = writeln!(&mut std::io::stderr(), "Error: cannot read home dir");
process::exit(1);
}
let library_path = library_path.unwrap().join("Music");
let library = Library::new_rc(&library_path);
let queue_for_server = {
let library = library.borrow();
Arc::clone(library.queue())
};
use tray;
let queue_for_tray = Arc::clone(&queue_for_server);
// Initialize tray icon
thread::spawn(move || {
tray::start_tray(&queue_for_tray);
});
|
if let Ok(listener) = listener {
thread::spawn(move || {
start_server(&listener, &queue_for_server);
});
library.borrow_mut().event_loop();
} else {
let _ = writeln!(&mut std::io::stderr(), "Error: could not start server");
process::exit(1);
}
} | // Initialize server
let listener = TcpListener::bind("127.0.0.1:5000"); | random_line_split |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mutex<Queue>>) {
for stream in listener.incoming() {
match stream {
Ok(mut stream) => {
let mut buf = [0; 256];
let data = stream.read(&mut buf);
if data.is_ok() {
let command = Command::from(&buf);
if command.is_ok() {
let mut queue = queue.lock().unwrap();
queue.push(command.unwrap(), Some(stream));
}
}
},
Err(_) => println!("Error"),
}
}
}
/// Creates a library from /home/$USER/Music, creates a tray icon if the feature is enabled, and
/// starts the server and the event loop.
fn main() | let queue_for_tray = Arc::clone(&queue_for_server);
// Initialize tray icon
thread::spawn(move || {
tray::start_tray(&queue_for_tray);
});
// Initialize server
let listener = TcpListener::bind("127.0.0.1:5000");
if let Ok(listener) = listener {
thread::spawn(move || {
start_server(&listener, &queue_for_server);
});
library.borrow_mut().event_loop();
} else {
let _ = writeln!(&mut std::io::stderr(), "Error: could not start server");
process::exit(1);
}
}
| {
// Initialize library
let library_path = env::home_dir();
if library_path.is_none() {
let _ = writeln!(&mut std::io::stderr(), "Error: cannot read home dir");
process::exit(1);
}
let library_path = library_path.unwrap().join("Music");
let library = Library::new_rc(&library_path);
let queue_for_server = {
let library = library.borrow();
Arc::clone(library.queue())
};
use tray; | identifier_body |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mutex<Queue>>) {
for stream in listener.incoming() {
match stream {
Ok(mut stream) => {
let mut buf = [0; 256];
let data = stream.read(&mut buf);
if data.is_ok() {
let command = Command::from(&buf);
if command.is_ok() {
let mut queue = queue.lock().unwrap();
queue.push(command.unwrap(), Some(stream));
}
}
},
Err(_) => println!("Error"),
}
}
}
/// Creates a library from /home/$USER/Music, creates a tray icon if the feature is enabled, and
/// starts the server and the event loop.
fn | () {
// Initialize library
let library_path = env::home_dir();
if library_path.is_none() {
let _ = writeln!(&mut std::io::stderr(), "Error: cannot read home dir");
process::exit(1);
}
let library_path = library_path.unwrap().join("Music");
let library = Library::new_rc(&library_path);
let queue_for_server = {
let library = library.borrow();
Arc::clone(library.queue())
};
use tray;
let queue_for_tray = Arc::clone(&queue_for_server);
// Initialize tray icon
thread::spawn(move || {
tray::start_tray(&queue_for_tray);
});
// Initialize server
let listener = TcpListener::bind("127.0.0.1:5000");
if let Ok(listener) = listener {
thread::spawn(move || {
start_server(&listener, &queue_for_server);
});
library.borrow_mut().event_loop();
} else {
let _ = writeln!(&mut std::io::stderr(), "Error: could not start server");
process::exit(1);
}
}
| main | identifier_name |
sokoban.rs | #![crate_type = "bin"]
#![allow(unused_must_use)]
//extern crate native;
extern crate libc;
use std::from_str::{FromStr};
use std::io::{File};
use std::io::stdio::{stdin};
use std::path::{Path};
use std::os;
use sokoboard::{SokoBoard};
use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan};
mod raw;
mod bdd;
mod sokoboard;
mod sokoannotatedboard;
fn main() | {
let args = os::args();
let contents;
if args.len() > 1 {
contents = File::open(&Path::new(args[1].as_slice())).read_to_str();
println!("Reading from file.");
} else {
contents = stdin().read_to_str();
println!("Reading from stdin.");
}
let board: SokoBoard = FromStr::from_str( contents.unwrap() )
.expect("Invalid sokoban board");
let annotated = SokoAnnotatedBoard::fromSokoBoard(board);
do_sylvan(&annotated);
} | identifier_body |
|
sokoban.rs | #![crate_type = "bin"]
| //extern crate native;
extern crate libc;
use std::from_str::{FromStr};
use std::io::{File};
use std::io::stdio::{stdin};
use std::path::{Path};
use std::os;
use sokoboard::{SokoBoard};
use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan};
mod raw;
mod bdd;
mod sokoboard;
mod sokoannotatedboard;
fn main() {
let args = os::args();
let contents;
if args.len() > 1 {
contents = File::open(&Path::new(args[1].as_slice())).read_to_str();
println!("Reading from file.");
} else {
contents = stdin().read_to_str();
println!("Reading from stdin.");
}
let board: SokoBoard = FromStr::from_str( contents.unwrap() )
.expect("Invalid sokoban board");
let annotated = SokoAnnotatedBoard::fromSokoBoard(board);
do_sylvan(&annotated);
} | #![allow(unused_must_use)]
| random_line_split |
sokoban.rs | #![crate_type = "bin"]
#![allow(unused_must_use)]
//extern crate native;
extern crate libc;
use std::from_str::{FromStr};
use std::io::{File};
use std::io::stdio::{stdin};
use std::path::{Path};
use std::os;
use sokoboard::{SokoBoard};
use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan};
mod raw;
mod bdd;
mod sokoboard;
mod sokoannotatedboard;
fn | () {
let args = os::args();
let contents;
if args.len() > 1 {
contents = File::open(&Path::new(args[1].as_slice())).read_to_str();
println!("Reading from file.");
} else {
contents = stdin().read_to_str();
println!("Reading from stdin.");
}
let board: SokoBoard = FromStr::from_str( contents.unwrap() )
.expect("Invalid sokoban board");
let annotated = SokoAnnotatedBoard::fromSokoBoard(board);
do_sylvan(&annotated);
}
| main | identifier_name |
sokoban.rs | #![crate_type = "bin"]
#![allow(unused_must_use)]
//extern crate native;
extern crate libc;
use std::from_str::{FromStr};
use std::io::{File};
use std::io::stdio::{stdin};
use std::path::{Path};
use std::os;
use sokoboard::{SokoBoard};
use sokoannotatedboard::{SokoAnnotatedBoard, do_sylvan};
mod raw;
mod bdd;
mod sokoboard;
mod sokoannotatedboard;
fn main() {
let args = os::args();
let contents;
if args.len() > 1 {
contents = File::open(&Path::new(args[1].as_slice())).read_to_str();
println!("Reading from file.");
} else |
let board: SokoBoard = FromStr::from_str( contents.unwrap() )
.expect("Invalid sokoban board");
let annotated = SokoAnnotatedBoard::fromSokoBoard(board);
do_sylvan(&annotated);
}
| {
contents = stdin().read_to_str();
println!("Reading from stdin.");
} | conditional_block |
config.rs | use errors::*;
use modules::{centerdevice, pocket, slack};
use std::fs::File;
use std::io::Read;
use std::path::Path;
use toml;
#[derive(Debug, Deserialize)]
#[serde(tag = "format")]
#[derive(PartialOrd, PartialEq, Eq)]
#[derive(Clone, Copy)]
pub enum OutputFormat {
JSON,
HUMAN,
}
impl<'a> From<&'a str> for OutputFormat {
fn | (format: &'a str) -> Self {
let format_sane: &str = &format.to_string().to_uppercase();
match format_sane {
"JSON" => OutputFormat::JSON,
_ => OutputFormat::HUMAN
}
}
}
#[derive(Debug, Deserialize)]
#[serde(tag = "verbosity")]
#[derive(PartialOrd, PartialEq, Eq)]
#[derive(Clone, Copy)]
pub enum Verbosity {
VERBOSE = 1,
NORMAL = 2,
QUIET = 3,
}
#[derive(Debug, Deserialize)]
pub struct GeneralConfig {
pub cache_dir: String,
pub output_format: OutputFormat,
pub verbosity: Verbosity,
}
#[derive(Debug, Deserialize)]
pub struct Config {
pub general: GeneralConfig,
pub centerdevice: centerdevice::CenterDeviceConfig,
pub pocket: pocket::PocketConfig,
pub slack: slack::SlackConfig,
}
impl Config {
pub fn from_file(file_path: &Path) -> Result<Config> {
let mut config_file = File::open(file_path).chain_err(|| "Could not open config file.")?;
let mut config_content = String::new();
config_file.read_to_string(&mut config_content).chain_err(|| "Could not read config file.")?;
let config: Config = toml::from_str(&config_content).chain_err(|| "Could not parse config file.")?;
Ok(config)
}
}
| from | identifier_name |
config.rs | use errors::*;
use modules::{centerdevice, pocket, slack};
use std::fs::File;
use std::io::Read;
use std::path::Path; | #[derive(PartialOrd, PartialEq, Eq)]
#[derive(Clone, Copy)]
pub enum OutputFormat {
JSON,
HUMAN,
}
impl<'a> From<&'a str> for OutputFormat {
fn from(format: &'a str) -> Self {
let format_sane: &str = &format.to_string().to_uppercase();
match format_sane {
"JSON" => OutputFormat::JSON,
_ => OutputFormat::HUMAN
}
}
}
#[derive(Debug, Deserialize)]
#[serde(tag = "verbosity")]
#[derive(PartialOrd, PartialEq, Eq)]
#[derive(Clone, Copy)]
pub enum Verbosity {
VERBOSE = 1,
NORMAL = 2,
QUIET = 3,
}
#[derive(Debug, Deserialize)]
pub struct GeneralConfig {
pub cache_dir: String,
pub output_format: OutputFormat,
pub verbosity: Verbosity,
}
#[derive(Debug, Deserialize)]
pub struct Config {
pub general: GeneralConfig,
pub centerdevice: centerdevice::CenterDeviceConfig,
pub pocket: pocket::PocketConfig,
pub slack: slack::SlackConfig,
}
impl Config {
pub fn from_file(file_path: &Path) -> Result<Config> {
let mut config_file = File::open(file_path).chain_err(|| "Could not open config file.")?;
let mut config_content = String::new();
config_file.read_to_string(&mut config_content).chain_err(|| "Could not read config file.")?;
let config: Config = toml::from_str(&config_content).chain_err(|| "Could not parse config file.")?;
Ok(config)
}
} | use toml;
#[derive(Debug, Deserialize)]
#[serde(tag = "format")] | random_line_split |
method-two-trait-defer-resolution-2.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.
// Test that we pick which version of `Foo` to run based on whether
// the type we (ultimately) inferred for `x` is copyable or not.
//
// In this case, the two versions are both impls of same trait, and
// hence we we can resolve method even without knowing yet which
// version will run (note that the `push` occurs after the call to
// `foo()`).
trait Foo {
fn foo(&self) -> int;
}
impl<T:Copy> Foo for Vec<T> {
fn foo(&self) -> int {1}
}
impl<T> Foo for Vec<Box<T>> {
fn foo(&self) -> int {2}
}
fn call_foo_copy() -> int {
let mut x = Vec::new();
let y = x.foo();
x.push(0u);
y
}
fn call_foo_other() -> int |
fn main() {
assert_eq!(call_foo_copy(), 1);
assert_eq!(call_foo_other(), 2);
}
| {
let mut x = Vec::new();
let y = x.foo();
x.push(box 0i);
y
} | identifier_body |
method-two-trait-defer-resolution-2.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.
// Test that we pick which version of `Foo` to run based on whether
// the type we (ultimately) inferred for `x` is copyable or not.
//
// In this case, the two versions are both impls of same trait, and
// hence we we can resolve method even without knowing yet which
// version will run (note that the `push` occurs after the call to
// `foo()`).
trait Foo {
fn foo(&self) -> int;
}
impl<T:Copy> Foo for Vec<T> {
fn foo(&self) -> int {1}
}
impl<T> Foo for Vec<Box<T>> {
fn | (&self) -> int {2}
}
fn call_foo_copy() -> int {
let mut x = Vec::new();
let y = x.foo();
x.push(0u);
y
}
fn call_foo_other() -> int {
let mut x = Vec::new();
let y = x.foo();
x.push(box 0i);
y
}
fn main() {
assert_eq!(call_foo_copy(), 1);
assert_eq!(call_foo_other(), 2);
}
| foo | identifier_name |
instr_pminsb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pminsb_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword)
}
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 144, 209, 9, 14, 106], OperandSize::Dword)
}
#[test]
fn pminsb_3() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 201], OperandSize::Qword)
}
#[test]
fn pminsb_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Eight, 1699663306, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 188, 223, 202, 205, 78, 101], OperandSize::Qword)
}
| pminsb_2 | identifier_name |
instr_pminsb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*; | use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pminsb_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword)
}
#[test]
fn pminsb_2() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 144, 209, 9, 14, 106], OperandSize::Dword)
}
#[test]
fn pminsb_3() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 201], OperandSize::Qword)
}
#[test]
fn pminsb_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Eight, 1699663306, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 188, 223, 202, 205, 78, 101], OperandSize::Qword)
} | random_line_split |
|
instr_pminsb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pminsb_1() |
#[test]
fn pminsb_2() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM2)), operand2: Some(IndirectDisplaced(EAX, 1779304913, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 144, 209, 9, 14, 106], OperandSize::Dword)
}
#[test]
fn pminsb_3() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 201], OperandSize::Qword)
}
#[test]
fn pminsb_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM7)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Eight, 1699663306, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 188, 223, 202, 205, 78, 101], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::PMINSB, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 56, 223], OperandSize::Dword)
} | identifier_body |
day_4.rs | use std::str::Chars;
use self::DisplayResult::{Output, NotANumber};
use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero};
#[derive(PartialEq, Debug)]
pub enum | {
Output(Vec<Number>),
NotANumber
}
impl From<Chars<'static>> for DisplayResult {
fn from(chars: Chars) -> DisplayResult {
let len = chars.as_str().len();
let mut vec = Vec::with_capacity(len);
for c in chars {
if c < '0' || c > '9' {
return NotANumber;
}
let n = Number::from(c);
vec.push(n);
}
Output(vec)
}
}
#[derive(PartialEq, Debug)]
pub enum Number {
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Zero
}
impl From<char> for Number {
fn from(c: char) -> Number {
match c {
'1' => One,
'2' => Two,
'3' => Three,
'4' => Four,
'5' => Five,
'6' => Six,
'7' => Seven,
'8' => Eight,
'9' => Nine,
'0' => Zero,
_ => unreachable!("Impossible!"),
}
}
}
#[derive(Default)]
pub struct Display {
input: Option<&'static str>
}
impl Display {
pub fn new() -> Display {
Display {
input: None
}
}
pub fn output(&self) -> DisplayResult {
match self.input {
Some(data) => DisplayResult::from(data.chars()),
None => Output(vec![]),
}
}
pub fn input(&mut self, data: &'static str) {
self.input = Some(data);
}
}
| DisplayResult | identifier_name |
day_4.rs | use std::str::Chars;
use self::DisplayResult::{Output, NotANumber};
use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero};
#[derive(PartialEq, Debug)]
pub enum DisplayResult {
Output(Vec<Number>),
NotANumber
}
impl From<Chars<'static>> for DisplayResult {
fn from(chars: Chars) -> DisplayResult {
let len = chars.as_str().len();
let mut vec = Vec::with_capacity(len);
for c in chars {
if c < '0' || c > '9' {
return NotANumber;
}
let n = Number::from(c);
vec.push(n);
}
Output(vec)
}
}
#[derive(PartialEq, Debug)]
pub enum Number {
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Zero
}
impl From<char> for Number {
fn from(c: char) -> Number {
match c {
'1' => One,
'2' => Two,
'3' => Three,
'4' => Four,
'5' => Five,
'6' => Six,
'7' => Seven,
'8' => Eight,
'9' => Nine,
'0' => Zero,
_ => unreachable!("Impossible!"),
}
}
}
#[derive(Default)]
pub struct Display {
input: Option<&'static str>
}
impl Display {
| input: None
}
}
pub fn output(&self) -> DisplayResult {
match self.input {
Some(data) => DisplayResult::from(data.chars()),
None => Output(vec![]),
}
}
pub fn input(&mut self, data: &'static str) {
self.input = Some(data);
}
} | pub fn new() -> Display {
Display { | random_line_split |
day_4.rs | use std::str::Chars;
use self::DisplayResult::{Output, NotANumber};
use self::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero};
#[derive(PartialEq, Debug)]
pub enum DisplayResult {
Output(Vec<Number>),
NotANumber
}
impl From<Chars<'static>> for DisplayResult {
fn from(chars: Chars) -> DisplayResult {
let len = chars.as_str().len();
let mut vec = Vec::with_capacity(len);
for c in chars {
if c < '0' || c > '9' {
return NotANumber;
}
let n = Number::from(c);
vec.push(n);
}
Output(vec)
}
}
#[derive(PartialEq, Debug)]
pub enum Number {
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Zero
}
impl From<char> for Number {
fn from(c: char) -> Number {
match c {
'1' => One,
'2' => Two,
'3' => Three,
'4' => Four,
'5' => Five,
'6' => Six,
'7' => Seven,
'8' => Eight,
'9' => Nine,
'0' => Zero,
_ => unreachable!("Impossible!"),
}
}
}
#[derive(Default)]
pub struct Display {
input: Option<&'static str>
}
impl Display {
pub fn new() -> Display {
Display {
input: None
}
}
pub fn output(&self) -> DisplayResult {
match self.input {
Some(data) => DisplayResult::from(data.chars()),
None => Output(vec![]),
}
}
pub fn input(&mut self, data: &'static str) |
}
| {
self.input = Some(data);
} | identifier_body |
init.rs | use std::fs::{canonicalize, create_dir};
use std::path::Path;
use std::path::PathBuf;
use errors::{bail, Result};
use utils::fs::create_file;
use crate::console;
use crate::prompt::{ask_bool, ask_url};
const CONFIG: &str = r#"
# The URL the site will be built for
base_url = "%BASE_URL%"
# Whether to automatically compile all Sass files in the sass directory
compile_sass = %COMPILE_SASS%
# Whether to build a search index to be used later on by a JavaScript library
build_search_index = %SEARCH%
[markdown]
# Whether to do syntax highlighting
# Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
highlight_code = %HIGHLIGHT%
[extra]
# Put all your custom variables here
"#;
// canonicalize(path) function on windows system returns a path with UNC.
// Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project
// More details on Universal Naming Convention (UNC):
// https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention
// So the following const will be used to remove the network part of the UNC to display users a more common
// path on windows systems.
// This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed.
const LOCAL_UNC: &str = "\\\\?\\";
// Given a path, return true if it is a directory and it doesn't have any
// non-hidden files, otherwise return false (path is assumed to exist)
pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> {
if path.is_dir() {
let mut entries = match path.read_dir() {
Ok(entries) => entries,
Err(e) => {
bail!(
"Could not read `{}` because of error: {}",
path.to_string_lossy().to_string(),
e
);
}
};
// If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error
if entries.any(|x| match x {
Ok(file) =>!file
.file_name()
.to_str()
.expect("Could not convert filename to &str")
.starts_with('.'),
Err(_) => true,
}) {
return Ok(false);
}
return Ok(true);
}
Ok(false)
}
// Remove the unc part of a windows path
fn strip_unc(path: &PathBuf) -> String {
let path_to_refine = path.to_str().unwrap();
path_to_refine.trim_start_matches(LOCAL_UNC).to_string()
}
pub fn create_new_project(name: &str, force: bool) -> Result<()> {
let path = Path::new(name);
// Better error message than the rust default
if path.exists() &&!is_directory_quasi_empty(&path)? &&!force {
if name == "." {
bail!("The current directory is not an empty folder (hidden files are ignored).");
} else {
bail!(
"`{}` is not an empty folder (hidden files are ignored).",
path.to_string_lossy().to_string()
)
}
}
console::info("Welcome to Zola!");
console::info("Please answer a few questions to get started quickly.");
console::info("Any choices made can be changed by modifying the `config.toml` file later.");
let base_url = ask_url("> What is the URL of your site?", "https://example.com")?;
let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?;
let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?;
let search = ask_bool("> Do you want to build a search index of the content?", false)?;
let config = CONFIG
.trim_start()
.replace("%BASE_URL%", &base_url)
.replace("%COMPILE_SASS%", &format!("{}", compile_sass))
.replace("%SEARCH%", &format!("{}", search))
.replace("%HIGHLIGHT%", &format!("{}", highlight));
populate(&path, compile_sass, &config)?;
println!();
console::success(&format!(
"Done! Your site was created in {}",
strip_unc(&canonicalize(path).unwrap())
));
println!();
console::info(
"Get started by moving into the directory and using the built-in server: `zola serve`",
);
println!("Visit https://www.getzola.org for the full documentation.");
Ok(())
}
fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> {
if!path.exists() {
create_dir(path)?;
}
create_file(&path.join("config.toml"), &config)?;
create_dir(path.join("content"))?;
create_dir(path.join("templates"))?;
create_dir(path.join("static"))?;
create_dir(path.join("themes"))?;
if compile_sass {
create_dir(path.join("sass"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::env::temp_dir;
use std::fs::{create_dir, remove_dir, remove_dir_all};
use std::path::Path;
#[test]
fn init_empty_directory() {
let mut dir = temp_dir();
dir.push("test_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn init_non_empty_directory() {
let mut dir = temp_dir();
dir.push("test_non_empty_dir");
if dir.exists() |
create_dir(&dir).expect("Could not create test directory");
let mut content = dir.clone();
content.push("content");
create_dir(&content).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&content).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(false, allowed);
}
#[test]
fn init_quasi_empty_directory() {
let mut dir = temp_dir();
dir.push("test_quasi_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut git = dir.clone();
git.push(".git");
create_dir(&git).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&git).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn populate_existing_directory() {
let mut dir = temp_dir();
dir.push("test_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_non_existing_directory() {
let mut dir = temp_dir();
dir.push("test_non_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.exists());
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_without_sass() {
let mut dir = temp_dir();
dir.push("test_wihout_sass_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, false, "").expect("Could not populate zola directories");
assert_eq!(false, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn strip_unc_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
if cfg!(target_os = "windows") {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
"C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
)
} else {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string()
);
}
remove_dir_all(&dir).unwrap();
}
// If the following test fails it means that the canonicalize function is fixed and strip_unc
// function/workaround is not anymore required.
// See issue https://github.com/rust-lang/rust/issues/42869 as a reference.
#[test]
#[cfg(target_os = "windows")]
fn strip_unc_required_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
assert_eq!(
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(),
"\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
);
remove_dir_all(&dir).unwrap();
}
}
| {
remove_dir_all(&dir).expect("Could not free test directory");
} | conditional_block |
init.rs | use std::fs::{canonicalize, create_dir};
use std::path::Path;
use std::path::PathBuf;
use errors::{bail, Result};
use utils::fs::create_file;
use crate::console;
use crate::prompt::{ask_bool, ask_url};
const CONFIG: &str = r#"
# The URL the site will be built for
base_url = "%BASE_URL%"
# Whether to automatically compile all Sass files in the sass directory
compile_sass = %COMPILE_SASS%
# Whether to build a search index to be used later on by a JavaScript library
build_search_index = %SEARCH%
[markdown]
# Whether to do syntax highlighting
# Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
highlight_code = %HIGHLIGHT%
[extra]
# Put all your custom variables here
"#;
// canonicalize(path) function on windows system returns a path with UNC.
// Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project
// More details on Universal Naming Convention (UNC):
// https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention
// So the following const will be used to remove the network part of the UNC to display users a more common
// path on windows systems.
// This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed.
const LOCAL_UNC: &str = "\\\\?\\";
// Given a path, return true if it is a directory and it doesn't have any
// non-hidden files, otherwise return false (path is assumed to exist)
pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> {
if path.is_dir() {
let mut entries = match path.read_dir() {
Ok(entries) => entries,
Err(e) => {
bail!(
"Could not read `{}` because of error: {}",
path.to_string_lossy().to_string(),
e
);
}
};
// If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error
if entries.any(|x| match x {
Ok(file) =>!file
.file_name()
.to_str()
.expect("Could not convert filename to &str")
.starts_with('.'),
Err(_) => true,
}) {
return Ok(false);
}
return Ok(true);
}
Ok(false)
}
// Remove the unc part of a windows path
fn strip_unc(path: &PathBuf) -> String {
let path_to_refine = path.to_str().unwrap();
path_to_refine.trim_start_matches(LOCAL_UNC).to_string()
}
pub fn create_new_project(name: &str, force: bool) -> Result<()> {
let path = Path::new(name);
// Better error message than the rust default
if path.exists() &&!is_directory_quasi_empty(&path)? &&!force {
if name == "." {
bail!("The current directory is not an empty folder (hidden files are ignored).");
} else {
bail!(
"`{}` is not an empty folder (hidden files are ignored).",
path.to_string_lossy().to_string()
)
}
}
console::info("Welcome to Zola!");
console::info("Please answer a few questions to get started quickly.");
console::info("Any choices made can be changed by modifying the `config.toml` file later.");
let base_url = ask_url("> What is the URL of your site?", "https://example.com")?;
let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?;
let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?;
let search = ask_bool("> Do you want to build a search index of the content?", false)?;
let config = CONFIG
.trim_start()
.replace("%BASE_URL%", &base_url)
.replace("%COMPILE_SASS%", &format!("{}", compile_sass))
.replace("%SEARCH%", &format!("{}", search))
.replace("%HIGHLIGHT%", &format!("{}", highlight));
populate(&path, compile_sass, &config)?;
println!();
console::success(&format!(
"Done! Your site was created in {}",
strip_unc(&canonicalize(path).unwrap())
));
println!();
console::info(
"Get started by moving into the directory and using the built-in server: `zola serve`",
);
println!("Visit https://www.getzola.org for the full documentation.");
Ok(())
}
fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> {
if!path.exists() {
create_dir(path)?;
}
create_file(&path.join("config.toml"), &config)?;
create_dir(path.join("content"))?;
create_dir(path.join("templates"))?;
create_dir(path.join("static"))?;
create_dir(path.join("themes"))?;
if compile_sass {
create_dir(path.join("sass"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::env::temp_dir;
use std::fs::{create_dir, remove_dir, remove_dir_all};
use std::path::Path;
#[test]
fn init_empty_directory() {
let mut dir = temp_dir();
dir.push("test_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn init_non_empty_directory() |
#[test]
fn init_quasi_empty_directory() {
let mut dir = temp_dir();
dir.push("test_quasi_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut git = dir.clone();
git.push(".git");
create_dir(&git).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&git).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn populate_existing_directory() {
let mut dir = temp_dir();
dir.push("test_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_non_existing_directory() {
let mut dir = temp_dir();
dir.push("test_non_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.exists());
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_without_sass() {
let mut dir = temp_dir();
dir.push("test_wihout_sass_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, false, "").expect("Could not populate zola directories");
assert_eq!(false, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn strip_unc_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
if cfg!(target_os = "windows") {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
"C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
)
} else {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string()
);
}
remove_dir_all(&dir).unwrap();
}
// If the following test fails it means that the canonicalize function is fixed and strip_unc
// function/workaround is not anymore required.
// See issue https://github.com/rust-lang/rust/issues/42869 as a reference.
#[test]
#[cfg(target_os = "windows")]
fn strip_unc_required_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
assert_eq!(
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(),
"\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
);
remove_dir_all(&dir).unwrap();
}
}
| {
let mut dir = temp_dir();
dir.push("test_non_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut content = dir.clone();
content.push("content");
create_dir(&content).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&content).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(false, allowed);
} | identifier_body |
init.rs | use std::fs::{canonicalize, create_dir};
use std::path::Path;
use std::path::PathBuf;
use errors::{bail, Result};
use utils::fs::create_file;
use crate::console;
use crate::prompt::{ask_bool, ask_url};
const CONFIG: &str = r#"
# The URL the site will be built for
base_url = "%BASE_URL%"
# Whether to automatically compile all Sass files in the sass directory
compile_sass = %COMPILE_SASS%
# Whether to build a search index to be used later on by a JavaScript library
build_search_index = %SEARCH%
[markdown]
# Whether to do syntax highlighting
# Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
highlight_code = %HIGHLIGHT%
[extra]
# Put all your custom variables here
"#;
// canonicalize(path) function on windows system returns a path with UNC.
// Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project
// More details on Universal Naming Convention (UNC):
// https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention
// So the following const will be used to remove the network part of the UNC to display users a more common
// path on windows systems.
// This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed.
const LOCAL_UNC: &str = "\\\\?\\";
// Given a path, return true if it is a directory and it doesn't have any
// non-hidden files, otherwise return false (path is assumed to exist)
pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> {
if path.is_dir() {
let mut entries = match path.read_dir() {
Ok(entries) => entries,
Err(e) => {
bail!(
"Could not read `{}` because of error: {}",
path.to_string_lossy().to_string(),
e
);
}
};
// If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error
if entries.any(|x| match x {
Ok(file) =>!file
.file_name()
.to_str()
.expect("Could not convert filename to &str")
.starts_with('.'),
Err(_) => true,
}) {
return Ok(false);
}
return Ok(true);
}
Ok(false)
}
// Remove the unc part of a windows path
fn strip_unc(path: &PathBuf) -> String {
let path_to_refine = path.to_str().unwrap();
path_to_refine.trim_start_matches(LOCAL_UNC).to_string()
}
pub fn create_new_project(name: &str, force: bool) -> Result<()> {
let path = Path::new(name);
// Better error message than the rust default
if path.exists() &&!is_directory_quasi_empty(&path)? &&!force {
if name == "." {
bail!("The current directory is not an empty folder (hidden files are ignored).");
} else {
bail!(
"`{}` is not an empty folder (hidden files are ignored).",
path.to_string_lossy().to_string()
)
}
}
console::info("Welcome to Zola!");
console::info("Please answer a few questions to get started quickly.");
console::info("Any choices made can be changed by modifying the `config.toml` file later.");
let base_url = ask_url("> What is the URL of your site?", "https://example.com")?;
let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?;
let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?;
let search = ask_bool("> Do you want to build a search index of the content?", false)?;
let config = CONFIG
.trim_start()
.replace("%BASE_URL%", &base_url)
.replace("%COMPILE_SASS%", &format!("{}", compile_sass))
.replace("%SEARCH%", &format!("{}", search))
.replace("%HIGHLIGHT%", &format!("{}", highlight));
populate(&path, compile_sass, &config)?;
println!();
console::success(&format!(
"Done! Your site was created in {}",
strip_unc(&canonicalize(path).unwrap())
));
println!();
console::info(
"Get started by moving into the directory and using the built-in server: `zola serve`",
);
println!("Visit https://www.getzola.org for the full documentation.");
Ok(())
}
fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> {
if!path.exists() {
create_dir(path)?;
}
create_file(&path.join("config.toml"), &config)?;
create_dir(path.join("content"))?;
create_dir(path.join("templates"))?;
create_dir(path.join("static"))?;
create_dir(path.join("themes"))?;
if compile_sass {
create_dir(path.join("sass"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::env::temp_dir;
use std::fs::{create_dir, remove_dir, remove_dir_all};
use std::path::Path;
#[test]
fn init_empty_directory() {
let mut dir = temp_dir();
dir.push("test_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn | () {
let mut dir = temp_dir();
dir.push("test_non_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut content = dir.clone();
content.push("content");
create_dir(&content).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&content).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(false, allowed);
}
#[test]
fn init_quasi_empty_directory() {
let mut dir = temp_dir();
dir.push("test_quasi_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut git = dir.clone();
git.push(".git");
create_dir(&git).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&git).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn populate_existing_directory() {
let mut dir = temp_dir();
dir.push("test_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_non_existing_directory() {
let mut dir = temp_dir();
dir.push("test_non_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.exists());
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_without_sass() {
let mut dir = temp_dir();
dir.push("test_wihout_sass_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, false, "").expect("Could not populate zola directories");
assert_eq!(false, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn strip_unc_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
if cfg!(target_os = "windows") {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
"C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
)
} else {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string()
);
}
remove_dir_all(&dir).unwrap();
}
// If the following test fails it means that the canonicalize function is fixed and strip_unc
// function/workaround is not anymore required.
// See issue https://github.com/rust-lang/rust/issues/42869 as a reference.
#[test]
#[cfg(target_os = "windows")]
fn strip_unc_required_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
assert_eq!(
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(),
"\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
);
remove_dir_all(&dir).unwrap();
}
}
| init_non_empty_directory | identifier_name |
init.rs | use std::fs::{canonicalize, create_dir};
use std::path::Path;
use std::path::PathBuf;
use errors::{bail, Result};
use utils::fs::create_file;
use crate::console;
use crate::prompt::{ask_bool, ask_url};
const CONFIG: &str = r#"
# The URL the site will be built for
base_url = "%BASE_URL%"
# Whether to automatically compile all Sass files in the sass directory
compile_sass = %COMPILE_SASS%
# Whether to build a search index to be used later on by a JavaScript library
build_search_index = %SEARCH%
[markdown]
# Whether to do syntax highlighting
# Theme can be customised by setting the `highlight_theme` variable to a theme supported by Zola
highlight_code = %HIGHLIGHT%
[extra]
# Put all your custom variables here
"#;
// canonicalize(path) function on windows system returns a path with UNC.
// Example: \\?\C:\Users\VssAdministrator\AppData\Local\Temp\new_project
// More details on Universal Naming Convention (UNC):
// https://en.wikipedia.org/wiki/Path_(computing)#Uniform_Naming_Convention
// So the following const will be used to remove the network part of the UNC to display users a more common
// path on windows systems.
// This is a workaround until this issue https://github.com/rust-lang/rust/issues/42869 was fixed.
const LOCAL_UNC: &str = "\\\\?\\";
// Given a path, return true if it is a directory and it doesn't have any
// non-hidden files, otherwise return false (path is assumed to exist)
pub fn is_directory_quasi_empty(path: &Path) -> Result<bool> {
if path.is_dir() {
let mut entries = match path.read_dir() {
Ok(entries) => entries, | );
}
};
// If any entry raises an error or isn't hidden (i.e. starts with `.`), we raise an error
if entries.any(|x| match x {
Ok(file) =>!file
.file_name()
.to_str()
.expect("Could not convert filename to &str")
.starts_with('.'),
Err(_) => true,
}) {
return Ok(false);
}
return Ok(true);
}
Ok(false)
}
// Remove the unc part of a windows path
fn strip_unc(path: &PathBuf) -> String {
let path_to_refine = path.to_str().unwrap();
path_to_refine.trim_start_matches(LOCAL_UNC).to_string()
}
pub fn create_new_project(name: &str, force: bool) -> Result<()> {
let path = Path::new(name);
// Better error message than the rust default
if path.exists() &&!is_directory_quasi_empty(&path)? &&!force {
if name == "." {
bail!("The current directory is not an empty folder (hidden files are ignored).");
} else {
bail!(
"`{}` is not an empty folder (hidden files are ignored).",
path.to_string_lossy().to_string()
)
}
}
console::info("Welcome to Zola!");
console::info("Please answer a few questions to get started quickly.");
console::info("Any choices made can be changed by modifying the `config.toml` file later.");
let base_url = ask_url("> What is the URL of your site?", "https://example.com")?;
let compile_sass = ask_bool("> Do you want to enable Sass compilation?", true)?;
let highlight = ask_bool("> Do you want to enable syntax highlighting?", false)?;
let search = ask_bool("> Do you want to build a search index of the content?", false)?;
let config = CONFIG
.trim_start()
.replace("%BASE_URL%", &base_url)
.replace("%COMPILE_SASS%", &format!("{}", compile_sass))
.replace("%SEARCH%", &format!("{}", search))
.replace("%HIGHLIGHT%", &format!("{}", highlight));
populate(&path, compile_sass, &config)?;
println!();
console::success(&format!(
"Done! Your site was created in {}",
strip_unc(&canonicalize(path).unwrap())
));
println!();
console::info(
"Get started by moving into the directory and using the built-in server: `zola serve`",
);
println!("Visit https://www.getzola.org for the full documentation.");
Ok(())
}
fn populate(path: &Path, compile_sass: bool, config: &str) -> Result<()> {
if!path.exists() {
create_dir(path)?;
}
create_file(&path.join("config.toml"), &config)?;
create_dir(path.join("content"))?;
create_dir(path.join("templates"))?;
create_dir(path.join("static"))?;
create_dir(path.join("themes"))?;
if compile_sass {
create_dir(path.join("sass"))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::env::temp_dir;
use std::fs::{create_dir, remove_dir, remove_dir_all};
use std::path::Path;
#[test]
fn init_empty_directory() {
let mut dir = temp_dir();
dir.push("test_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn init_non_empty_directory() {
let mut dir = temp_dir();
dir.push("test_non_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut content = dir.clone();
content.push("content");
create_dir(&content).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&content).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(false, allowed);
}
#[test]
fn init_quasi_empty_directory() {
let mut dir = temp_dir();
dir.push("test_quasi_empty_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
let mut git = dir.clone();
git.push(".git");
create_dir(&git).unwrap();
let allowed = is_directory_quasi_empty(&dir)
.expect("An error happened reading the directory's contents");
remove_dir(&git).unwrap();
remove_dir(&dir).unwrap();
assert_eq!(true, allowed);
}
#[test]
fn populate_existing_directory() {
let mut dir = temp_dir();
dir.push("test_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_non_existing_directory() {
let mut dir = temp_dir();
dir.push("test_non_existing_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
populate(&dir, true, "").expect("Could not populate zola directories");
assert_eq!(true, dir.exists());
assert_eq!(true, dir.join("config.toml").exists());
assert_eq!(true, dir.join("content").exists());
assert_eq!(true, dir.join("templates").exists());
assert_eq!(true, dir.join("static").exists());
assert_eq!(true, dir.join("themes").exists());
assert_eq!(true, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn populate_without_sass() {
let mut dir = temp_dir();
dir.push("test_wihout_sass_dir");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
populate(&dir, false, "").expect("Could not populate zola directories");
assert_eq!(false, dir.join("sass").exists());
remove_dir_all(&dir).unwrap();
}
#[test]
fn strip_unc_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
if cfg!(target_os = "windows") {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
"C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
)
} else {
assert_eq!(
strip_unc(&canonicalize(Path::new(&dir)).unwrap()),
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap().to_string()
);
}
remove_dir_all(&dir).unwrap();
}
// If the following test fails it means that the canonicalize function is fixed and strip_unc
// function/workaround is not anymore required.
// See issue https://github.com/rust-lang/rust/issues/42869 as a reference.
#[test]
#[cfg(target_os = "windows")]
fn strip_unc_required_test() {
let mut dir = temp_dir();
dir.push("new_project");
if dir.exists() {
remove_dir_all(&dir).expect("Could not free test directory");
}
create_dir(&dir).expect("Could not create test directory");
assert_eq!(
canonicalize(Path::new(&dir)).unwrap().to_str().unwrap(),
"\\\\?\\C:\\Users\\VssAdministrator\\AppData\\Local\\Temp\\new_project"
);
remove_dir_all(&dir).unwrap();
}
} | Err(e) => {
bail!(
"Could not read `{}` because of error: {}",
path.to_string_lossy().to_string(),
e | random_line_split |
assignment_tracker.rs | use common::*;
use disassembler::*;
use instruction_graph::*;
pub struct AssignmentTracker;
impl AssignmentTracker {
// NOTE: expects reversed graph
pub fn find(
graph: &InstructionGraph,
address: u64,
register: Reg,
try_match: &mut FnMut(&Insn, Reg) -> bool,
) -> Option<u64> {
let mut skipped_initial_instruction = false;
let mut stack = vec![address];
while!stack.is_empty() {
let address = stack.pop().unwrap();
for pair in graph.get_adjacent(&address).into_iter().rev() {
if let Ok((addr, link)) = pair {
match link.type_ {
LinkType::Next | LinkType::Branch | LinkType::SwitchCaseJump => {
stack.push(*addr);
}
_ => (),
}
}
}
if!skipped_initial_instruction {
skipped_initial_instruction = true;
}
let insn = graph.get_vertex(&address);
if try_match(insn, register) {
match insn.operands[1] {
Operand::Register(_, r) => {
return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| {
if let Operand::Register(_, r) = i.operands[0] {
if r == reg && i.code == Mnemonic::Imov {
return true;
}
}
return false;
});
}
Operand::ImmediateSigned(_, v) => return Some(v as u64),
Operand::ImmediateUnsigned(_, v) => return Some(v),
_ => {
// TODO: logger.Warn("Cannot track assignments from 0x{0:x8} operand type {1}", instr.Offset, instr.Operands.[1].Type)
return None;
}
}
}
if graph.get_in_value(insn.address) > 1 {
// TODO: logger.Warn("Cannot track assignments from 0x{0:x8}, the number of incoming links > 1", instr.Offset)
return None;
}
if let Mnemonic::Imov = insn.code {
match (insn.operands[0], insn.operands[1]) {
(Operand::Register(_, r0), Operand::Register(_, r1)) if r0 == register => {
return AssignmentTracker::find(graph, insn.address, r1, try_match);
}
_ => {} | }
None
}
} | }
} | random_line_split |
assignment_tracker.rs | use common::*;
use disassembler::*;
use instruction_graph::*;
pub struct | ;
impl AssignmentTracker {
// NOTE: expects reversed graph
pub fn find(
graph: &InstructionGraph,
address: u64,
register: Reg,
try_match: &mut FnMut(&Insn, Reg) -> bool,
) -> Option<u64> {
let mut skipped_initial_instruction = false;
let mut stack = vec![address];
while!stack.is_empty() {
let address = stack.pop().unwrap();
for pair in graph.get_adjacent(&address).into_iter().rev() {
if let Ok((addr, link)) = pair {
match link.type_ {
LinkType::Next | LinkType::Branch | LinkType::SwitchCaseJump => {
stack.push(*addr);
}
_ => (),
}
}
}
if!skipped_initial_instruction {
skipped_initial_instruction = true;
}
let insn = graph.get_vertex(&address);
if try_match(insn, register) {
match insn.operands[1] {
Operand::Register(_, r) => {
return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| {
if let Operand::Register(_, r) = i.operands[0] {
if r == reg && i.code == Mnemonic::Imov {
return true;
}
}
return false;
});
}
Operand::ImmediateSigned(_, v) => return Some(v as u64),
Operand::ImmediateUnsigned(_, v) => return Some(v),
_ => {
// TODO: logger.Warn("Cannot track assignments from 0x{0:x8} operand type {1}", instr.Offset, instr.Operands.[1].Type)
return None;
}
}
}
if graph.get_in_value(insn.address) > 1 {
// TODO: logger.Warn("Cannot track assignments from 0x{0:x8}, the number of incoming links > 1", instr.Offset)
return None;
}
if let Mnemonic::Imov = insn.code {
match (insn.operands[0], insn.operands[1]) {
(Operand::Register(_, r0), Operand::Register(_, r1)) if r0 == register => {
return AssignmentTracker::find(graph, insn.address, r1, try_match);
}
_ => {}
}
}
}
None
}
}
| AssignmentTracker | identifier_name |
assignment_tracker.rs | use common::*;
use disassembler::*;
use instruction_graph::*;
pub struct AssignmentTracker;
impl AssignmentTracker {
// NOTE: expects reversed graph
pub fn find(
graph: &InstructionGraph,
address: u64,
register: Reg,
try_match: &mut FnMut(&Insn, Reg) -> bool,
) -> Option<u64> |
let insn = graph.get_vertex(&address);
if try_match(insn, register) {
match insn.operands[1] {
Operand::Register(_, r) => {
return AssignmentTracker::find(graph, insn.address, r, &mut |i, reg| {
if let Operand::Register(_, r) = i.operands[0] {
if r == reg && i.code == Mnemonic::Imov {
return true;
}
}
return false;
});
}
Operand::ImmediateSigned(_, v) => return Some(v as u64),
Operand::ImmediateUnsigned(_, v) => return Some(v),
_ => {
// TODO: logger.Warn("Cannot track assignments from 0x{0:x8} operand type {1}", instr.Offset, instr.Operands.[1].Type)
return None;
}
}
}
if graph.get_in_value(insn.address) > 1 {
// TODO: logger.Warn("Cannot track assignments from 0x{0:x8}, the number of incoming links > 1", instr.Offset)
return None;
}
if let Mnemonic::Imov = insn.code {
match (insn.operands[0], insn.operands[1]) {
(Operand::Register(_, r0), Operand::Register(_, r1)) if r0 == register => {
return AssignmentTracker::find(graph, insn.address, r1, try_match);
}
_ => {}
}
}
}
None
}
}
| {
let mut skipped_initial_instruction = false;
let mut stack = vec![address];
while !stack.is_empty() {
let address = stack.pop().unwrap();
for pair in graph.get_adjacent(&address).into_iter().rev() {
if let Ok((addr, link)) = pair {
match link.type_ {
LinkType::Next | LinkType::Branch | LinkType::SwitchCaseJump => {
stack.push(*addr);
}
_ => (),
}
}
}
if !skipped_initial_instruction {
skipped_initial_instruction = true;
} | identifier_body |
unwind.rs | // taken from https://github.com/thepowersgang/rust-barebones-kernel
#[lang="panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) ->! {
// 'args' will print to the formatted string passed to panic!
log!("file='{}', line={} :: {}", file, line, args);
loop {}
}
#[lang="stack_exhausted"]
#[no_mangle]
pub extern "C" fn | () ->! {
loop {}
}
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
}
#[allow(non_camel_case_types)]
#[derive(Clone,Copy)]
pub struct _Unwind_Context;
#[allow(non_camel_case_types)]
pub type _Unwind_Action = u32;
static _UA_SEARCH_PHASE: _Unwind_Action = 1;
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
#[allow(raw_pointer_derive)]
pub struct _Unwind_Exception {
exception_class: u64,
exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception),
private: [u64; 2],
}
#[lang="eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality(_version: isize,
_actions: _Unwind_Action,
_exception_class: u64,
_exception_object: &_Unwind_Exception,
_context: &_Unwind_Context)
-> _Unwind_Reason_Code {
loop {}
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn _Unwind_Resume() {
loop {}
}
| __morestack | identifier_name |
unwind.rs | // taken from https://github.com/thepowersgang/rust-barebones-kernel
#[lang="panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) ->! {
// 'args' will print to the formatted string passed to panic!
log!("file='{}', line={} :: {}", file, line, args);
loop {}
} | loop {}
}
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
}
#[allow(non_camel_case_types)]
#[derive(Clone,Copy)]
pub struct _Unwind_Context;
#[allow(non_camel_case_types)]
pub type _Unwind_Action = u32;
static _UA_SEARCH_PHASE: _Unwind_Action = 1;
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
#[allow(raw_pointer_derive)]
pub struct _Unwind_Exception {
exception_class: u64,
exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception),
private: [u64; 2],
}
#[lang="eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality(_version: isize,
_actions: _Unwind_Action,
_exception_class: u64,
_exception_object: &_Unwind_Exception,
_context: &_Unwind_Context)
-> _Unwind_Reason_Code {
loop {}
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn _Unwind_Resume() {
loop {}
} |
#[lang="stack_exhausted"]
#[no_mangle]
pub extern "C" fn __morestack() -> ! { | random_line_split |
unwind.rs | // taken from https://github.com/thepowersgang/rust-barebones-kernel
#[lang="panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) ->! {
// 'args' will print to the formatted string passed to panic!
log!("file='{}', line={} :: {}", file, line, args);
loop {}
}
#[lang="stack_exhausted"]
#[no_mangle]
pub extern "C" fn __morestack() ->! {
loop {}
}
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
}
#[allow(non_camel_case_types)]
#[derive(Clone,Copy)]
pub struct _Unwind_Context;
#[allow(non_camel_case_types)]
pub type _Unwind_Action = u32;
static _UA_SEARCH_PHASE: _Unwind_Action = 1;
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
#[allow(raw_pointer_derive)]
pub struct _Unwind_Exception {
exception_class: u64,
exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception),
private: [u64; 2],
}
#[lang="eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality(_version: isize,
_actions: _Unwind_Action,
_exception_class: u64,
_exception_object: &_Unwind_Exception,
_context: &_Unwind_Context)
-> _Unwind_Reason_Code |
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn _Unwind_Resume() {
loop {}
}
| {
loop {}
} | identifier_body |
cond-macro.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.
fn clamp<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T |
fn main() {
assert_eq!(clamp(1, 2, 4), 2);
assert_eq!(clamp(8, 2, 4), 4);
assert_eq!(clamp(3, 2, 4), 3);
}
| {
cond!(
(x > mx) { mx }
(x < mn) { mn }
_ { x }
)
} | identifier_body |
cond-macro.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.
fn clamp<T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T {
cond!(
(x > mx) { mx }
(x < mn) { mn }
_ { x }
)
}
fn main() {
assert_eq!(clamp(1, 2, 4), 2);
assert_eq!(clamp(8, 2, 4), 4);
assert_eq!(clamp(3, 2, 4), 3);
} | random_line_split |
|
cond-macro.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.
fn | <T:Copy + Ord + Signed>(x: T, mn: T, mx: T) -> T {
cond!(
(x > mx) { mx }
(x < mn) { mn }
_ { x }
)
}
fn main() {
assert_eq!(clamp(1, 2, 4), 2);
assert_eq!(clamp(8, 2, 4), 4);
assert_eq!(clamp(3, 2, 4), 3);
}
| clamp | identifier_name |
result.rs | //! A module describing Lox-specific Result and Error types
use object::Object;
use std::result;
use std::error;
use std::fmt;
use std::io;
/// A Lox-Specific Result Type
pub type Result<T> = result::Result<T, Error>;
/// A Lox-Specific Error
#[derive(Debug)]
pub enum | {
/// Returned if the CLI command is used incorrectly
Usage,
/// Returned if there is an error reading from a file or stdin
IO(io::Error),
/// Returned if the scanner encounters an error
Lexical(u64, String, String),
/// Returned if the parser encounters an error
Parse(u64, String, String),
/// Returned if there is an error at runtime
Runtime(u64, String, String),
/// Sentinel error for break statements
Break(u64),
/// Sentinel error for return statements
Return(u64, Object),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::IO(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Usage => write!(f, "Usage: rlox [script]"),
Error::IO(ref e) => e.fmt(f),
Error::Lexical(ref line, ref msg, ref whence) =>
write!(f, "Lexical Error [line {}] {}: {:?}", line, msg, whence),
Error::Parse(ref line, ref msg, ref near) =>
write!(f, "Parse Error [line {}] {}: near {}", line, msg, &near),
Error::Runtime(ref line, ref msg, ref near) =>
write!(f, "Runtime Error [line {}] {}: near {}", line, msg, &near),
Error::Break(ref line) =>
write!(f, "Runtime Error [line {}] unexpected break statement", line),
Error::Return(ref line, _) =>
write!(f, "Runtime Error [line {}] unexpected return statement", line),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Usage => "usage error",
Error::IO(ref e) => e.description(),
Error::Lexical(_, _, _) => "lexical error",
Error::Parse(_, _, _) => "parse error",
Error::Runtime(_, _, _) => "runtime error",
Error::Break(_) => "break error",
Error::Return(_, _) => "return error",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::IO(ref e) => e.cause(),
_ => None,
}
}
}
| Error | identifier_name |
result.rs | //! A module describing Lox-specific Result and Error types
| use std::fmt;
use std::io;
/// A Lox-Specific Result Type
pub type Result<T> = result::Result<T, Error>;
/// A Lox-Specific Error
#[derive(Debug)]
pub enum Error {
/// Returned if the CLI command is used incorrectly
Usage,
/// Returned if there is an error reading from a file or stdin
IO(io::Error),
/// Returned if the scanner encounters an error
Lexical(u64, String, String),
/// Returned if the parser encounters an error
Parse(u64, String, String),
/// Returned if there is an error at runtime
Runtime(u64, String, String),
/// Sentinel error for break statements
Break(u64),
/// Sentinel error for return statements
Return(u64, Object),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::IO(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Usage => write!(f, "Usage: rlox [script]"),
Error::IO(ref e) => e.fmt(f),
Error::Lexical(ref line, ref msg, ref whence) =>
write!(f, "Lexical Error [line {}] {}: {:?}", line, msg, whence),
Error::Parse(ref line, ref msg, ref near) =>
write!(f, "Parse Error [line {}] {}: near {}", line, msg, &near),
Error::Runtime(ref line, ref msg, ref near) =>
write!(f, "Runtime Error [line {}] {}: near {}", line, msg, &near),
Error::Break(ref line) =>
write!(f, "Runtime Error [line {}] unexpected break statement", line),
Error::Return(ref line, _) =>
write!(f, "Runtime Error [line {}] unexpected return statement", line),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Usage => "usage error",
Error::IO(ref e) => e.description(),
Error::Lexical(_, _, _) => "lexical error",
Error::Parse(_, _, _) => "parse error",
Error::Runtime(_, _, _) => "runtime error",
Error::Break(_) => "break error",
Error::Return(_, _) => "return error",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::IO(ref e) => e.cause(),
_ => None,
}
}
} | use object::Object;
use std::result;
use std::error; | random_line_split |
input.rs | //! Provides utilities for tracking the state of various input devices
use cable_math::Vec2;
const MOUSE_KEYS: usize = 5;
const KEYBOARD_KEYS: usize = 256; // This MUST be `u8::max_value() + 1`
/// Passed to `Window::poll_events` each frame to get updated.
#[derive(Clone)]
pub struct Input {
/// The position of the mouse, in window space
pub mouse_pos: Vec2<f32>,
/// The amount `mouse_pos` has changed since last frame
/// TODO document whether this stays constant if the mouse is grabbed
pub mouse_delta: Vec2<f32>,
/// The amount of movement directly reported by the mouse sensor. Should be used for e.g. first
/// person cameras in games.
pub raw_mouse_delta: Vec2<f32>,
/// Units scrolled in the last frame. 1.0 corresponds to one tick of the wheel
pub mouse_scroll: f32,
/// The state of mouse keys. 0 is left, 1 is right, 2 is middle. 3 and 4 are usually the keys
/// for clicking the mousewheel laterally, for mice that have such keys. Sometimes they are
/// also placed on the side of the mouse.
///
/// On linux, 3 and 4 are always `Up`, because these codes are used for the scroll wheel
/// internally.
pub mouse_keys: [KeyState; MOUSE_KEYS],
/// The state of keyboard keys. Can also be accessed more ergonomically throug the
/// `Input::key()` method
pub keys: [KeyState; KEYBOARD_KEYS],
/// Cleared each frame. Contains typed characters in the order they where typed
pub type_buffer: String,
pub window_has_keyboard_focus: bool,
pub received_events_this_frame: bool,
#[cfg(feature = "gamepad")]
pub gamepads: [Gamepad; 4],
}
impl Input {
pub fn new() -> Input {
Input {
mouse_pos: Vec2::ZERO,
mouse_delta: Vec2::ZERO,
raw_mouse_delta: Vec2::ZERO,
mouse_scroll: 0.0,
mouse_keys: [KeyState::Up; MOUSE_KEYS],
keys: [KeyState::Up; KEYBOARD_KEYS],
type_buffer: String::with_capacity(10),
window_has_keyboard_focus: false,
received_events_this_frame: false,
#[cfg(feature = "gamepad")]
gamepads: [Default::default(), Default::default(), Default::default(), Default::default()],
}
}
// Called by `Window::poll_events` in the platform layer
pub(crate) fn refresh(&mut self) {
self.mouse_delta = Vec2::ZERO;
self.raw_mouse_delta = Vec2::ZERO;
self.mouse_scroll = 0.0;
self.type_buffer.clear();
for state in self.mouse_keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state!= KeyState::PressedRepeat);
}
for state in self.keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
if *state == KeyState::PressedRepeat { *state = KeyState::Down; }
}
#[cfg(feature = "gamepad")]
for gamepad in self.gamepads.iter_mut() {
if gamepad.connected {
for state in gamepad.buttons.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state!= KeyState::PressedRepeat);
}
} else {
gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT];
gamepad.left = Vec2::ZERO;
gamepad.right = Vec2::ZERO;
gamepad.left_trigger = 0.0;
gamepad.right_trigger = 0.0;
}
}
self.received_events_this_frame = false;
}
/// The state of the given keyboard key. Note that `Key` represent scancodes.
/// See [`Key`](enum.Key.html) for more info
pub fn key(&self, key: Key) -> KeyState {
self.keys[key as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyState {
/// The button is not held down.
Up,
/// The button is being held down. In the previous frame it was not held down.
Pressed,
/// The button is being held down, and its repeat action triggered
PressedRepeat,
/// The button is being held down.
Down,
/// The button is not being held down. In the previous frame it was held down.
Released,
}
impl Default for KeyState {
fn default() -> KeyState { KeyState::Up }
}
impl KeyState {
/// Returns true if the button is being held down (`Down` or `Pressed`) and
/// false otherwise (`Up`, `Released` or `PressedRepeat`).
pub fn down(self) -> bool {
match self {
KeyState::Up | KeyState::Released => false,
KeyState::Down | KeyState::Pressed | KeyState::PressedRepeat => true,
}
}
/// Returns true if the button is not being held down (`Up` or `Released`) and
/// false otherwise (`Down` or `Pressed`).
pub fn up(self) -> bool {
!self.down()
}
/// Returns true if the button is being held down, but was not held down in the last
/// frame (`Pressed`)
pub fn pressed(self) -> bool { self == KeyState::Pressed }
/// Returns true either if this button is being held down and was not held down in the
/// last frame (`Pressed`), or if the repeat action has been triggered by the key being
/// held down for an extended amount of time (`PressedRepeat`).
pub fn pressed_repeat(self) -> bool {
self == KeyState::Pressed || self == KeyState::PressedRepeat
}
/// Returns true if the button is being not held down, but was held down in the last
/// frame (`Released`)
pub fn released(self) -> bool { self == KeyState::Released }
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position
/// on the keyboard, rather than a specific symbol. These can be used as parameters
/// to [`InputManager::key`](struct.InputManager.html#method.key). The names are
/// based on the american keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "linux")]
#[repr(u8)]
pub enum Key {
Key1 = 0xa, Key2 = 0xb, Key3 = 0xc, Key4 = 0xd, Key5 = 0xe,
Key6 = 0xf, Key7 = 0x10, Key8 = 0x11, Key9 = 0x12, Key0 = 0x13,
Q = 0x18, W = 0x19, E = 0x1a, R = 0x1b, T = 0x1c, Y = 0x1d, U = 0x1e, I = 0x1f, O = 0x20, P = 0x21,
A = 0x26, S = 0x27, D = 0x28, F = 0x29, G = 0x2a, H = 0x2b, J = 0x2c, K = 0x2d, L = 0x2e,
Z = 0x34, X = 0x35, C = 0x36, V = 0x37, B = 0x38, N = 0x39, M = 0x3a,
Space = 0x41,
Escape = 0x9, Grave = 0x31, Tab = 0x17, CapsLock = 0x42,
LShift = 0x32, LCtrl = 0x25, LAlt = 0x40,
RAlt = 0x6c, RMeta = 0x86, RCtrl = 0x69, RShift = 0x3e, Return = 0x24, Back = 0x16,
Right = 0x72, Left = 0x71, Down = 0x74, Up = 0x6f,
Insert = 0x76, Delete = 0x77, Home = 0x6e, End = 0x73, PageUp = 0x70, PageDown = 0x75,
F1 = 0x43, F2 = 0x44, F3 = 0x45, F4 = 0x46, F5 = 0x47, F6 = 0x48,
F7 = 0x49, F8 = 0x4a, F9 = 0x4b, F10 = 0x4c, F11 = 0x5f, F12 = 0x60,
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position on the
/// keyboard, rather than a specific symbol. These can be used as parameters to
/// [`InputManager::key`](struct.InputManager.html#method.key). The names are based on the american
/// keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "windows")]
#[repr(u8)]
pub enum Key {
Key1 = 0x2, Key2 = 0x3, Key3 = 0x4, Key4 = 0x5, Key5 = 0x6,
Key6 = 0x7, Key7 = 0x8, Key8 = 0x9, Key9 = 0xa, Key0 = 0xb,
Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19,
A = 0x1e, S = 0x1f, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26,
Z = 0x2c, X = 0x2d, C = 0x2e, V = 0x2f, B = 0x30, N = 0x31, M = 0x32,
Space = 0x39, | Tab = 0xf,
// CapsLock = 0x42,
LShift = 0x2a,
LCtrl = 0x1d,
// LAlt = 0x40,
// RAlt = 0x6c,
// RMeta = 0x86,
// RCtrl = 0x1d, // Same scancode as LCtrl :/
RShift = 0x36,
Return = 0x1c,
Back = 0xe,
Right = 0x4d, Left = 0x4b, Down = 0x50, Up = 0x48,
Insert = 0x52, Delete = 0x53, Home = 0x47, End = 0x4f, PageUp = 0x49, PageDown = 0x51,
F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40,
F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58,
}
#[cfg(feature = "gamepad")]
#[derive(Clone, Default)]
pub struct Gamepad {
pub connected: bool,
pub buttons: [KeyState; GAMEPAD_BUTTON_COUNT],
pub left: Vec2<f32>,
pub right: Vec2<f32>,
pub left_trigger: f32,
pub right_trigger: f32,
}
#[cfg(feature = "gamepad")]
const GAMEPAD_BUTTON_COUNT: usize = 24;
#[cfg(feature = "gamepad")]
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum GamepadButton {
DpadUp = 0,
DpadDown,
DpadLeft,
DpadRight,
LeftUp,
LeftDown,
LeftRight,
LeftLeft,
RightUp,
RightDown,
RightRight,
RightLeft,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
A, B, X, Y,
}
#[cfg(feature = "gamepad")]
impl Gamepad {
pub fn button(&self, button: GamepadButton) -> KeyState {
self.buttons[button as usize]
}
} |
Escape = 0x1,
// Grave = 0x31, | random_line_split |
input.rs |
//! Provides utilities for tracking the state of various input devices
use cable_math::Vec2;
const MOUSE_KEYS: usize = 5;
const KEYBOARD_KEYS: usize = 256; // This MUST be `u8::max_value() + 1`
/// Passed to `Window::poll_events` each frame to get updated.
#[derive(Clone)]
pub struct Input {
/// The position of the mouse, in window space
pub mouse_pos: Vec2<f32>,
/// The amount `mouse_pos` has changed since last frame
/// TODO document whether this stays constant if the mouse is grabbed
pub mouse_delta: Vec2<f32>,
/// The amount of movement directly reported by the mouse sensor. Should be used for e.g. first
/// person cameras in games.
pub raw_mouse_delta: Vec2<f32>,
/// Units scrolled in the last frame. 1.0 corresponds to one tick of the wheel
pub mouse_scroll: f32,
/// The state of mouse keys. 0 is left, 1 is right, 2 is middle. 3 and 4 are usually the keys
/// for clicking the mousewheel laterally, for mice that have such keys. Sometimes they are
/// also placed on the side of the mouse.
///
/// On linux, 3 and 4 are always `Up`, because these codes are used for the scroll wheel
/// internally.
pub mouse_keys: [KeyState; MOUSE_KEYS],
/// The state of keyboard keys. Can also be accessed more ergonomically throug the
/// `Input::key()` method
pub keys: [KeyState; KEYBOARD_KEYS],
/// Cleared each frame. Contains typed characters in the order they where typed
pub type_buffer: String,
pub window_has_keyboard_focus: bool,
pub received_events_this_frame: bool,
#[cfg(feature = "gamepad")]
pub gamepads: [Gamepad; 4],
}
impl Input {
pub fn new() -> Input {
Input {
mouse_pos: Vec2::ZERO,
mouse_delta: Vec2::ZERO,
raw_mouse_delta: Vec2::ZERO,
mouse_scroll: 0.0,
mouse_keys: [KeyState::Up; MOUSE_KEYS],
keys: [KeyState::Up; KEYBOARD_KEYS],
type_buffer: String::with_capacity(10),
window_has_keyboard_focus: false,
received_events_this_frame: false,
#[cfg(feature = "gamepad")]
gamepads: [Default::default(), Default::default(), Default::default(), Default::default()],
}
}
// Called by `Window::poll_events` in the platform layer
pub(crate) fn refresh(&mut self) {
self.mouse_delta = Vec2::ZERO;
self.raw_mouse_delta = Vec2::ZERO;
self.mouse_scroll = 0.0;
self.type_buffer.clear();
for state in self.mouse_keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state!= KeyState::PressedRepeat);
}
for state in self.keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
if *state == KeyState::PressedRepeat { *state = KeyState::Down; }
}
#[cfg(feature = "gamepad")]
for gamepad in self.gamepads.iter_mut() {
if gamepad.connected | else {
gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT];
gamepad.left = Vec2::ZERO;
gamepad.right = Vec2::ZERO;
gamepad.left_trigger = 0.0;
gamepad.right_trigger = 0.0;
}
}
self.received_events_this_frame = false;
}
/// The state of the given keyboard key. Note that `Key` represent scancodes.
/// See [`Key`](enum.Key.html) for more info
pub fn key(&self, key: Key) -> KeyState {
self.keys[key as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyState {
/// The button is not held down.
Up,
/// The button is being held down. In the previous frame it was not held down.
Pressed,
/// The button is being held down, and its repeat action triggered
PressedRepeat,
/// The button is being held down.
Down,
/// The button is not being held down. In the previous frame it was held down.
Released,
}
impl Default for KeyState {
fn default() -> KeyState { KeyState::Up }
}
impl KeyState {
/// Returns true if the button is being held down (`Down` or `Pressed`) and
/// false otherwise (`Up`, `Released` or `PressedRepeat`).
pub fn down(self) -> bool {
match self {
KeyState::Up | KeyState::Released => false,
KeyState::Down | KeyState::Pressed | KeyState::PressedRepeat => true,
}
}
/// Returns true if the button is not being held down (`Up` or `Released`) and
/// false otherwise (`Down` or `Pressed`).
pub fn up(self) -> bool {
!self.down()
}
/// Returns true if the button is being held down, but was not held down in the last
/// frame (`Pressed`)
pub fn pressed(self) -> bool { self == KeyState::Pressed }
/// Returns true either if this button is being held down and was not held down in the
/// last frame (`Pressed`), or if the repeat action has been triggered by the key being
/// held down for an extended amount of time (`PressedRepeat`).
pub fn pressed_repeat(self) -> bool {
self == KeyState::Pressed || self == KeyState::PressedRepeat
}
/// Returns true if the button is being not held down, but was held down in the last
/// frame (`Released`)
pub fn released(self) -> bool { self == KeyState::Released }
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position
/// on the keyboard, rather than a specific symbol. These can be used as parameters
/// to [`InputManager::key`](struct.InputManager.html#method.key). The names are
/// based on the american keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "linux")]
#[repr(u8)]
pub enum Key {
Key1 = 0xa, Key2 = 0xb, Key3 = 0xc, Key4 = 0xd, Key5 = 0xe,
Key6 = 0xf, Key7 = 0x10, Key8 = 0x11, Key9 = 0x12, Key0 = 0x13,
Q = 0x18, W = 0x19, E = 0x1a, R = 0x1b, T = 0x1c, Y = 0x1d, U = 0x1e, I = 0x1f, O = 0x20, P = 0x21,
A = 0x26, S = 0x27, D = 0x28, F = 0x29, G = 0x2a, H = 0x2b, J = 0x2c, K = 0x2d, L = 0x2e,
Z = 0x34, X = 0x35, C = 0x36, V = 0x37, B = 0x38, N = 0x39, M = 0x3a,
Space = 0x41,
Escape = 0x9, Grave = 0x31, Tab = 0x17, CapsLock = 0x42,
LShift = 0x32, LCtrl = 0x25, LAlt = 0x40,
RAlt = 0x6c, RMeta = 0x86, RCtrl = 0x69, RShift = 0x3e, Return = 0x24, Back = 0x16,
Right = 0x72, Left = 0x71, Down = 0x74, Up = 0x6f,
Insert = 0x76, Delete = 0x77, Home = 0x6e, End = 0x73, PageUp = 0x70, PageDown = 0x75,
F1 = 0x43, F2 = 0x44, F3 = 0x45, F4 = 0x46, F5 = 0x47, F6 = 0x48,
F7 = 0x49, F8 = 0x4a, F9 = 0x4b, F10 = 0x4c, F11 = 0x5f, F12 = 0x60,
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position on the
/// keyboard, rather than a specific symbol. These can be used as parameters to
/// [`InputManager::key`](struct.InputManager.html#method.key). The names are based on the american
/// keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "windows")]
#[repr(u8)]
pub enum Key {
Key1 = 0x2, Key2 = 0x3, Key3 = 0x4, Key4 = 0x5, Key5 = 0x6,
Key6 = 0x7, Key7 = 0x8, Key8 = 0x9, Key9 = 0xa, Key0 = 0xb,
Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19,
A = 0x1e, S = 0x1f, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26,
Z = 0x2c, X = 0x2d, C = 0x2e, V = 0x2f, B = 0x30, N = 0x31, M = 0x32,
Space = 0x39,
Escape = 0x1,
// Grave = 0x31,
Tab = 0xf,
// CapsLock = 0x42,
LShift = 0x2a,
LCtrl = 0x1d,
// LAlt = 0x40,
// RAlt = 0x6c,
// RMeta = 0x86,
// RCtrl = 0x1d, // Same scancode as LCtrl :/
RShift = 0x36,
Return = 0x1c,
Back = 0xe,
Right = 0x4d, Left = 0x4b, Down = 0x50, Up = 0x48,
Insert = 0x52, Delete = 0x53, Home = 0x47, End = 0x4f, PageUp = 0x49, PageDown = 0x51,
F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40,
F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58,
}
#[cfg(feature = "gamepad")]
#[derive(Clone, Default)]
pub struct Gamepad {
pub connected: bool,
pub buttons: [KeyState; GAMEPAD_BUTTON_COUNT],
pub left: Vec2<f32>,
pub right: Vec2<f32>,
pub left_trigger: f32,
pub right_trigger: f32,
}
#[cfg(feature = "gamepad")]
const GAMEPAD_BUTTON_COUNT: usize = 24;
#[cfg(feature = "gamepad")]
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum GamepadButton {
DpadUp = 0,
DpadDown,
DpadLeft,
DpadRight,
LeftUp,
LeftDown,
LeftRight,
LeftLeft,
RightUp,
RightDown,
RightRight,
RightLeft,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
A, B, X, Y,
}
#[cfg(feature = "gamepad")]
impl Gamepad {
pub fn button(&self, button: GamepadButton) -> KeyState {
self.buttons[button as usize]
}
}
| {
for state in gamepad.buttons.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
} | conditional_block |
input.rs |
//! Provides utilities for tracking the state of various input devices
use cable_math::Vec2;
const MOUSE_KEYS: usize = 5;
const KEYBOARD_KEYS: usize = 256; // This MUST be `u8::max_value() + 1`
/// Passed to `Window::poll_events` each frame to get updated.
#[derive(Clone)]
pub struct Input {
/// The position of the mouse, in window space
pub mouse_pos: Vec2<f32>,
/// The amount `mouse_pos` has changed since last frame
/// TODO document whether this stays constant if the mouse is grabbed
pub mouse_delta: Vec2<f32>,
/// The amount of movement directly reported by the mouse sensor. Should be used for e.g. first
/// person cameras in games.
pub raw_mouse_delta: Vec2<f32>,
/// Units scrolled in the last frame. 1.0 corresponds to one tick of the wheel
pub mouse_scroll: f32,
/// The state of mouse keys. 0 is left, 1 is right, 2 is middle. 3 and 4 are usually the keys
/// for clicking the mousewheel laterally, for mice that have such keys. Sometimes they are
/// also placed on the side of the mouse.
///
/// On linux, 3 and 4 are always `Up`, because these codes are used for the scroll wheel
/// internally.
pub mouse_keys: [KeyState; MOUSE_KEYS],
/// The state of keyboard keys. Can also be accessed more ergonomically throug the
/// `Input::key()` method
pub keys: [KeyState; KEYBOARD_KEYS],
/// Cleared each frame. Contains typed characters in the order they where typed
pub type_buffer: String,
pub window_has_keyboard_focus: bool,
pub received_events_this_frame: bool,
#[cfg(feature = "gamepad")]
pub gamepads: [Gamepad; 4],
}
impl Input {
pub fn new() -> Input {
Input {
mouse_pos: Vec2::ZERO,
mouse_delta: Vec2::ZERO,
raw_mouse_delta: Vec2::ZERO,
mouse_scroll: 0.0,
mouse_keys: [KeyState::Up; MOUSE_KEYS],
keys: [KeyState::Up; KEYBOARD_KEYS],
type_buffer: String::with_capacity(10),
window_has_keyboard_focus: false,
received_events_this_frame: false,
#[cfg(feature = "gamepad")]
gamepads: [Default::default(), Default::default(), Default::default(), Default::default()],
}
}
// Called by `Window::poll_events` in the platform layer
pub(crate) fn refresh(&mut self) {
self.mouse_delta = Vec2::ZERO;
self.raw_mouse_delta = Vec2::ZERO;
self.mouse_scroll = 0.0;
self.type_buffer.clear();
for state in self.mouse_keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state!= KeyState::PressedRepeat);
}
for state in self.keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
if *state == KeyState::PressedRepeat { *state = KeyState::Down; }
}
#[cfg(feature = "gamepad")]
for gamepad in self.gamepads.iter_mut() {
if gamepad.connected {
for state in gamepad.buttons.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state!= KeyState::PressedRepeat);
}
} else {
gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT];
gamepad.left = Vec2::ZERO;
gamepad.right = Vec2::ZERO;
gamepad.left_trigger = 0.0;
gamepad.right_trigger = 0.0;
}
}
self.received_events_this_frame = false;
}
/// The state of the given keyboard key. Note that `Key` represent scancodes.
/// See [`Key`](enum.Key.html) for more info
pub fn key(&self, key: Key) -> KeyState {
self.keys[key as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyState {
/// The button is not held down.
Up,
/// The button is being held down. In the previous frame it was not held down.
Pressed,
/// The button is being held down, and its repeat action triggered
PressedRepeat,
/// The button is being held down.
Down,
/// The button is not being held down. In the previous frame it was held down.
Released,
}
impl Default for KeyState {
fn default() -> KeyState { KeyState::Up }
}
impl KeyState {
/// Returns true if the button is being held down (`Down` or `Pressed`) and
/// false otherwise (`Up`, `Released` or `PressedRepeat`).
pub fn down(self) -> bool {
match self {
KeyState::Up | KeyState::Released => false,
KeyState::Down | KeyState::Pressed | KeyState::PressedRepeat => true,
}
}
/// Returns true if the button is not being held down (`Up` or `Released`) and
/// false otherwise (`Down` or `Pressed`).
pub fn | (self) -> bool {
!self.down()
}
/// Returns true if the button is being held down, but was not held down in the last
/// frame (`Pressed`)
pub fn pressed(self) -> bool { self == KeyState::Pressed }
/// Returns true either if this button is being held down and was not held down in the
/// last frame (`Pressed`), or if the repeat action has been triggered by the key being
/// held down for an extended amount of time (`PressedRepeat`).
pub fn pressed_repeat(self) -> bool {
self == KeyState::Pressed || self == KeyState::PressedRepeat
}
/// Returns true if the button is being not held down, but was held down in the last
/// frame (`Released`)
pub fn released(self) -> bool { self == KeyState::Released }
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position
/// on the keyboard, rather than a specific symbol. These can be used as parameters
/// to [`InputManager::key`](struct.InputManager.html#method.key). The names are
/// based on the american keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "linux")]
#[repr(u8)]
pub enum Key {
Key1 = 0xa, Key2 = 0xb, Key3 = 0xc, Key4 = 0xd, Key5 = 0xe,
Key6 = 0xf, Key7 = 0x10, Key8 = 0x11, Key9 = 0x12, Key0 = 0x13,
Q = 0x18, W = 0x19, E = 0x1a, R = 0x1b, T = 0x1c, Y = 0x1d, U = 0x1e, I = 0x1f, O = 0x20, P = 0x21,
A = 0x26, S = 0x27, D = 0x28, F = 0x29, G = 0x2a, H = 0x2b, J = 0x2c, K = 0x2d, L = 0x2e,
Z = 0x34, X = 0x35, C = 0x36, V = 0x37, B = 0x38, N = 0x39, M = 0x3a,
Space = 0x41,
Escape = 0x9, Grave = 0x31, Tab = 0x17, CapsLock = 0x42,
LShift = 0x32, LCtrl = 0x25, LAlt = 0x40,
RAlt = 0x6c, RMeta = 0x86, RCtrl = 0x69, RShift = 0x3e, Return = 0x24, Back = 0x16,
Right = 0x72, Left = 0x71, Down = 0x74, Up = 0x6f,
Insert = 0x76, Delete = 0x77, Home = 0x6e, End = 0x73, PageUp = 0x70, PageDown = 0x75,
F1 = 0x43, F2 = 0x44, F3 = 0x45, F4 = 0x46, F5 = 0x47, F6 = 0x48,
F7 = 0x49, F8 = 0x4a, F9 = 0x4b, F10 = 0x4c, F11 = 0x5f, F12 = 0x60,
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position on the
/// keyboard, rather than a specific symbol. These can be used as parameters to
/// [`InputManager::key`](struct.InputManager.html#method.key). The names are based on the american
/// keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "windows")]
#[repr(u8)]
pub enum Key {
Key1 = 0x2, Key2 = 0x3, Key3 = 0x4, Key4 = 0x5, Key5 = 0x6,
Key6 = 0x7, Key7 = 0x8, Key8 = 0x9, Key9 = 0xa, Key0 = 0xb,
Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19,
A = 0x1e, S = 0x1f, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26,
Z = 0x2c, X = 0x2d, C = 0x2e, V = 0x2f, B = 0x30, N = 0x31, M = 0x32,
Space = 0x39,
Escape = 0x1,
// Grave = 0x31,
Tab = 0xf,
// CapsLock = 0x42,
LShift = 0x2a,
LCtrl = 0x1d,
// LAlt = 0x40,
// RAlt = 0x6c,
// RMeta = 0x86,
// RCtrl = 0x1d, // Same scancode as LCtrl :/
RShift = 0x36,
Return = 0x1c,
Back = 0xe,
Right = 0x4d, Left = 0x4b, Down = 0x50, Up = 0x48,
Insert = 0x52, Delete = 0x53, Home = 0x47, End = 0x4f, PageUp = 0x49, PageDown = 0x51,
F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40,
F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58,
}
#[cfg(feature = "gamepad")]
#[derive(Clone, Default)]
pub struct Gamepad {
pub connected: bool,
pub buttons: [KeyState; GAMEPAD_BUTTON_COUNT],
pub left: Vec2<f32>,
pub right: Vec2<f32>,
pub left_trigger: f32,
pub right_trigger: f32,
}
#[cfg(feature = "gamepad")]
const GAMEPAD_BUTTON_COUNT: usize = 24;
#[cfg(feature = "gamepad")]
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum GamepadButton {
DpadUp = 0,
DpadDown,
DpadLeft,
DpadRight,
LeftUp,
LeftDown,
LeftRight,
LeftLeft,
RightUp,
RightDown,
RightRight,
RightLeft,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
A, B, X, Y,
}
#[cfg(feature = "gamepad")]
impl Gamepad {
pub fn button(&self, button: GamepadButton) -> KeyState {
self.buttons[button as usize]
}
}
| up | identifier_name |
insert.rs | use redox::*;
use super::*; | pub enum InsertMode {
Append,
Insert,
Replace,
}
#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct InsertOptions {
/// The mode type
pub mode: InsertMode,
}
impl Editor {
/// Insert text
pub fn insert(&mut self, c: Key) {
let x = self.x();
let y = self.y();
match c {
Key::Char('\n') => {
let ln = self.text[y].clone();
let (slice, _) = ln.as_slices();
let first_part = (&slice[..x]).clone();
let second_part = (&slice[x..]).clone();
self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));
self.text.insert(y + 1, VecDeque::from_iter(second_part.iter().map(|x| *x)));
self.next();
},
Key::Escape => { // Escape key
self.cursor_mut().mode = Mode::Command(CommandMode::Normal);
},
Key::Backspace => { // Backspace
if self.x()!= 0 || self.y()!= 0 {
self.previous();
self.delete();
}
},
Key::Char(ch) => {
self.text[y].insert(x, ch);
self.next();
}
_ => {},
}
}
} | use core::iter::FromIterator;
#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode | random_line_split |
insert.rs | use redox::*;
use super::*;
use core::iter::FromIterator;
#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode
pub enum InsertMode {
Append,
Insert,
Replace,
}
#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct | {
/// The mode type
pub mode: InsertMode,
}
impl Editor {
/// Insert text
pub fn insert(&mut self, c: Key) {
let x = self.x();
let y = self.y();
match c {
Key::Char('\n') => {
let ln = self.text[y].clone();
let (slice, _) = ln.as_slices();
let first_part = (&slice[..x]).clone();
let second_part = (&slice[x..]).clone();
self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));
self.text.insert(y + 1, VecDeque::from_iter(second_part.iter().map(|x| *x)));
self.next();
},
Key::Escape => { // Escape key
self.cursor_mut().mode = Mode::Command(CommandMode::Normal);
},
Key::Backspace => { // Backspace
if self.x()!= 0 || self.y()!= 0 {
self.previous();
self.delete();
}
},
Key::Char(ch) => {
self.text[y].insert(x, ch);
self.next();
}
_ => {},
}
}
}
| InsertOptions | identifier_name |
insert.rs | use redox::*;
use super::*;
use core::iter::FromIterator;
#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode
pub enum InsertMode {
Append,
Insert,
Replace,
}
#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct InsertOptions {
/// The mode type
pub mode: InsertMode,
}
impl Editor {
/// Insert text
pub fn insert(&mut self, c: Key) {
let x = self.x();
let y = self.y();
match c {
Key::Char('\n') => {
let ln = self.text[y].clone();
let (slice, _) = ln.as_slices();
let first_part = (&slice[..x]).clone();
let second_part = (&slice[x..]).clone();
self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));
self.text.insert(y + 1, VecDeque::from_iter(second_part.iter().map(|x| *x)));
self.next();
},
Key::Escape => { // Escape key
self.cursor_mut().mode = Mode::Command(CommandMode::Normal);
},
Key::Backspace => { // Backspace
if self.x()!= 0 || self.y()!= 0 {
self.previous();
self.delete();
}
},
Key::Char(ch) => |
_ => {},
}
}
}
| {
self.text[y].insert(x, ch);
self.next();
} | conditional_block |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len()!= 4 {
println!("usage : {} start numline width", args[0]);
return;
}
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 { | let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
} | buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
}
fn gen_line(linewidth: u64) -> String { | random_line_split |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len()!= 4 |
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 {
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
}
fn gen_line(linewidth: u64) -> String {
let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
}
| {
println!("usage : {} start numline width", args[0]);
return;
} | conditional_block |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len()!= 4 {
println!("usage : {} start numline width", args[0]);
return;
}
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () |
fn gen_line(linewidth: u64) -> String {
let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
}
| {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 {
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
} | identifier_body |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len()!= 4 {
println!("usage : {} start numline width", args[0]);
return;
}
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 {
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
}
fn | (linewidth: u64) -> String {
let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
}
| gen_line | identifier_name |
message.rs | use std::net::SocketAddr;
use std::sync::mpsc::Sender;
#[derive(Debug, Clone)]
pub struct Member {
pub name: String,
pub addr: SocketAddr
}
pub struct Request {
pub addr: SocketAddr,
pub body: RequestBody
}
pub enum RequestBody {
Join { tx: Sender<Notify> },
Leave,
List,
Rename { name: String },
Submit { message: String },
UnicastMessage { message: String }
}
#[derive(Debug, Clone)]
pub enum Notify {
Unicast(UnicastNotify),
Broadcast(BroadcastNotify)
}
#[derive(Debug, Clone)]
pub enum | {
Join { name: String },
Leave,
List(Vec<(Member)>),
Rename(bool),
Submit(bool),
Message(String)
}
#[derive(Debug, Clone)]
pub enum BroadcastNotify {
Join { name: String, addr: SocketAddr },
Leave { name: String, addr: SocketAddr },
Rename { old_name: String, new_name: String, addr: SocketAddr },
Submit { name: String, addr: SocketAddr, message: String },
}
| UnicastNotify | identifier_name |
message.rs | use std::net::SocketAddr;
use std::sync::mpsc::Sender;
#[derive(Debug, Clone)]
pub struct Member {
pub name: String,
pub addr: SocketAddr
}
pub struct Request {
pub addr: SocketAddr,
pub body: RequestBody
}
pub enum RequestBody {
Join { tx: Sender<Notify> },
Leave,
List,
Rename { name: String },
Submit { message: String },
UnicastMessage { message: String }
}
#[derive(Debug, Clone)]
pub enum Notify {
Unicast(UnicastNotify),
Broadcast(BroadcastNotify)
}
#[derive(Debug, Clone)]
pub enum UnicastNotify {
Join { name: String },
Leave,
List(Vec<(Member)>),
Rename(bool),
Submit(bool),
Message(String)
}
| pub enum BroadcastNotify {
Join { name: String, addr: SocketAddr },
Leave { name: String, addr: SocketAddr },
Rename { old_name: String, new_name: String, addr: SocketAddr },
Submit { name: String, addr: SocketAddr, message: String },
} | #[derive(Debug, Clone)] | random_line_split |
rcvr-borrowed-to-region.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.
#![feature(managed_boxes)]
use std::gc::GC;
trait get {
fn get(self) -> int;
}
// Note: impl on a slice; we're checking that the pointers below
// correctly get borrowed to `&`. (similar to impling for `int`, with
// `&self` instead of `self`.)
impl<'a> get for &'a int {
fn get(self) -> int {
return *self;
}
}
pub fn main() | {
let x = box(GC) 6;
let y = x.get();
assert_eq!(y, 6);
let x = box(GC) 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = &6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
} | identifier_body |
|
rcvr-borrowed-to-region.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.
#![feature(managed_boxes)]
use std::gc::GC;
trait get {
fn get(self) -> int;
}
// Note: impl on a slice; we're checking that the pointers below
// correctly get borrowed to `&`. (similar to impling for `int`, with
// `&self` instead of `self`.)
impl<'a> get for &'a int {
fn get(self) -> int {
return *self;
}
}
pub fn | () {
let x = box(GC) 6;
let y = x.get();
assert_eq!(y, 6);
let x = box(GC) 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = &6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
}
| main | identifier_name |
rcvr-borrowed-to-region.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.
#![feature(managed_boxes)]
use std::gc::GC;
trait get {
fn get(self) -> int;
}
// Note: impl on a slice; we're checking that the pointers below
// correctly get borrowed to `&`. (similar to impling for `int`, with
// `&self` instead of `self`.)
impl<'a> get for &'a int {
fn get(self) -> int {
return *self;
}
}
pub fn main() {
let x = box(GC) 6;
let y = x.get();
assert_eq!(y, 6);
let x = box(GC) 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = &6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
} | random_line_split |
|
diepempmsk.rs | #[doc = "Register `DIEPEMPMSK` reader"]
pub struct R(crate::R<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPEMPMSK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPEMPMSK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPEMPMSK` writer"]
pub struct W(crate::W<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPEMPMSK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self {
W(writer) | pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>);
impl INEPTXFEMPMSK_R {
pub(crate) fn new(bits: u16) -> Self {
INEPTXFEMPMSK_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPTXFEMPMSK_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_W<'a> {
w: &'a mut W,
}
impl<'a> INEPTXFEMPMSK_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits &!0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&self) -> INEPTXFEMPMSK_R {
INEPTXFEMPMSK_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&mut self) -> INEPTXFEMPMSK_W {
INEPTXFEMPMSK_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device IN Endpoint FIFO Empty Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepempmsk](index.html) module"]
pub struct DIEPEMPMSK_SPEC;
impl crate::RegisterSpec for DIEPEMPMSK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepempmsk::R](R) reader structure"]
impl crate::Readable for DIEPEMPMSK_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [diepempmsk::W](W) writer structure"]
impl crate::Writable for DIEPEMPMSK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPEMPMSK to value 0"]
impl crate::Resettable for DIEPEMPMSK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | }
}
#[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"] | random_line_split |
diepempmsk.rs | #[doc = "Register `DIEPEMPMSK` reader"]
pub struct R(crate::R<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPEMPMSK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPEMPMSK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPEMPMSK` writer"]
pub struct W(crate::W<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn | (&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPEMPMSK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>);
impl INEPTXFEMPMSK_R {
pub(crate) fn new(bits: u16) -> Self {
INEPTXFEMPMSK_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPTXFEMPMSK_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_W<'a> {
w: &'a mut W,
}
impl<'a> INEPTXFEMPMSK_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits &!0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&self) -> INEPTXFEMPMSK_R {
INEPTXFEMPMSK_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&mut self) -> INEPTXFEMPMSK_W {
INEPTXFEMPMSK_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device IN Endpoint FIFO Empty Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepempmsk](index.html) module"]
pub struct DIEPEMPMSK_SPEC;
impl crate::RegisterSpec for DIEPEMPMSK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepempmsk::R](R) reader structure"]
impl crate::Readable for DIEPEMPMSK_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [diepempmsk::W](W) writer structure"]
impl crate::Writable for DIEPEMPMSK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPEMPMSK to value 0"]
impl crate::Resettable for DIEPEMPMSK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| deref_mut | identifier_name |
diepempmsk.rs | #[doc = "Register `DIEPEMPMSK` reader"]
pub struct R(crate::R<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPEMPMSK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPEMPMSK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPEMPMSK` writer"]
pub struct W(crate::W<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPEMPMSK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>);
impl INEPTXFEMPMSK_R {
pub(crate) fn new(bits: u16) -> Self {
INEPTXFEMPMSK_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPTXFEMPMSK_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target |
}
#[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_W<'a> {
w: &'a mut W,
}
impl<'a> INEPTXFEMPMSK_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits &!0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&self) -> INEPTXFEMPMSK_R {
INEPTXFEMPMSK_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&mut self) -> INEPTXFEMPMSK_W {
INEPTXFEMPMSK_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device IN Endpoint FIFO Empty Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepempmsk](index.html) module"]
pub struct DIEPEMPMSK_SPEC;
impl crate::RegisterSpec for DIEPEMPMSK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepempmsk::R](R) reader structure"]
impl crate::Readable for DIEPEMPMSK_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [diepempmsk::W](W) writer structure"]
impl crate::Writable for DIEPEMPMSK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPEMPMSK to value 0"]
impl crate::Resettable for DIEPEMPMSK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
&self.0
} | identifier_body |
path.rs | recursive: true,
.. PathSource::new(root, id, config)
}
}
pub fn root_package(&mut self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
self.update()?;
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
pub fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.recursive {
ops::read_packages(&self.path, &self.source_id, self.config)
} else {
let path = self.path.join("Cargo.toml");
let (pkg, _) = ops::read_package(&path, &self.source_id, self.config)?;
Ok(vec![pkg])
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine the
/// set of files underneath this source's directory which are relevant for
/// building `pkg`.
///
/// The basic assumption of this method is that all files in the directory
/// are relevant for building this package, but it also contains logic to
/// use other methods like.gitignore to filter the list of files.
///
/// ## Pattern matching strategy
///
/// Migrating from a glob-like pattern matching (using `glob` crate) to a
/// gitignore-like pattern matching (using `ignore` crate). The migration
/// stages are:
///
/// 1) Only warn users about the future change iff their matching rules are
/// affected. (CURRENT STAGE)
///
/// 2) Switch to the new strategy and upate documents. Still keep warning
/// affected users.
///
/// 3) Drop the old strategy and no mor warnings.
///
/// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let no_include_option = pkg.manifest().include().is_empty();
// glob-like matching rules
let glob_parse = |p: &String| {
let pattern: &str = if p.starts_with('/') {
&p[1..p.len()]
} else {
p
};
Pattern::new(pattern).map_err(|e| {
CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e))
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package!= ignore_should_package {
if glob_should_package {
if no_include_option | else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and.git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
//.gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and.git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
//.gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if!file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path!= pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p|!p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::Dir | {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} | conditional_block |
path.rs |
///
/// 2) Switch to the new strategy and upate documents. Still keep warning
/// affected users.
///
/// 3) Drop the old strategy and no mor warnings.
///
/// See <https://github.com/rust-lang/cargo/issues/4268> for more info.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let no_include_option = pkg.manifest().include().is_empty();
// glob-like matching rules
let glob_parse = |p: &String| {
let pattern: &str = if p.starts_with('/') {
&p[1..p.len()]
} else {
p
};
Pattern::new(pattern).map_err(|e| {
CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e))
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package!= ignore_should_package {
if glob_should_package {
if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and.git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
//.gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and.git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
//.gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if!file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path!= pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p|!p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn | supports_checksums | identifier_name |
|
path.rs |
})
};
let glob_exclude = pkg.manifest()
.exclude()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_include = pkg.manifest()
.include()
.iter()
.map(|p| glob_parse(p))
.collect::<Result<Vec<_>, _>>()?;
let glob_should_package = |relative_path: &Path| -> bool {
fn glob_match(patterns: &Vec<Pattern>, relative_path: &Path) -> bool {
patterns.iter().any(|pattern| pattern.matches_path(relative_path))
}
// include and exclude options are mutually exclusive.
if no_include_option {
!glob_match(&glob_exclude, relative_path)
} else {
glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package!= ignore_should_package {
if glob_should_package {
if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and.git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
//.gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and.git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
//.gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if!file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path!= pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p|!p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn supports_checksums(&self) -> bool {
false
}
fn requires_precise(&self) -> bool {
false
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn source_id(&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
if!self.updated {
let packages = self.read_packages()?;
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package> | {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
} | identifier_body |
|
path.rs | glob_match(&glob_include, relative_path)
}
};
// ignore-like matching rules
let mut exclude_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().exclude() {
exclude_builder.add_line(None, rule)?;
}
let ignore_exclude = exclude_builder.build()?;
let mut include_builder = GitignoreBuilder::new(root);
for rule in pkg.manifest().include() {
include_builder.add_line(None, rule)?;
}
let ignore_include = include_builder.build()?;
let ignore_should_package = |relative_path: &Path| -> CargoResult<bool> {
// include and exclude options are mutually exclusive.
if no_include_option {
match ignore_exclude.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(true),
Match::Ignore(_) => Ok(false),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"exclude rules cannot start with `!`: {}",
pattern.original()
))),
}
} else {
match ignore_include.matched_path_or_any_parents(
relative_path,
/* is_dir */ false,
) {
Match::None => Ok(false),
Match::Ignore(_) => Ok(true),
Match::Whitelist(pattern) => Err(CargoError::from(format!(
"include rules cannot start with `!`: {}",
pattern.original()
))),
}
}
};
// matching to paths
let mut filter = |path: &Path| -> CargoResult<bool> {
let relative_path = util::without_prefix(path, root).unwrap();
let glob_should_package = glob_should_package(relative_path);
let ignore_should_package = ignore_should_package(relative_path)?;
if glob_should_package!= ignore_should_package {
if glob_should_package {
if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
} else if no_include_option {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be excluded in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
} else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be included in a future Cargo version.\n\
See https://github.com/rust-lang/cargo/issues/4268 for more info",
relative_path.display()
))?;
}
}
// Update to ignore_should_package for Stage 2
Ok(glob_should_package)
};
// attempt git-prepopulate only if no `include` (rust-lang/cargo#4135)
if no_include_option {
if let Some(result) = self.discover_git_and_list_files(pkg, root, &mut filter) {
return result;
}
}
self.list_files_walk(pkg, &mut filter)
}
// Returns Some(_) if found sibling Cargo.toml and.git folder;
// otherwise caller should fall back on full file list.
fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this package is in a git repository, then we really do want to
// query the git repository as it takes into account items such as
//.gitignore. We're not quite sure where the git repository is,
// however, so we do a bit of a probe.
//
// We walk this package's path upwards and look for a sibling
// Cargo.toml and.git folder. If we find one then we assume that we're
// part of that repository.
let mut cur = root;
loop {
if cur.join("Cargo.toml").is_file() {
// If we find a git repository next to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
Ok(index) => index,
Err(err) => return Some(Err(err.into())),
};
let path = util::without_prefix(root, cur)
.unwrap().join("Cargo.toml");
if index.get_path(&path, 0).is_some() {
return Some(self.list_files_git(pkg, repo, filter));
}
}
}
// don't cross submodule boundaries
if cur.join(".git").is_dir() {
break
}
match cur.parent() {
Some(parent) => cur = parent,
None => break,
}
}
None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
internal("Can't list files on a bare repository.")
})?;
let pkg_path = pkg.root();
let mut ret = Vec::<PathBuf>::new();
// We use information from the git repository to guide us in traversing
// its tree. The primary purpose of this is to take advantage of the
//.gitignore and auto-ignore files that don't matter.
//
// Here we're also careful to look at both tracked and untracked files as
// the untracked files are often part of a build and may become relevant
// as part of a future commit.
let index_files = index.iter().map(|entry| {
use libgit2_sys::GIT_FILEMODE_COMMIT;
let is_dir = entry.mode == GIT_FILEMODE_COMMIT as u32;
(join(root, &entry.path), Some(is_dir))
});
let mut opts = git2::StatusOptions::new();
opts.include_untracked(true);
if let Some(suffix) = util::without_prefix(pkg_path, root) {
opts.pathspec(suffix);
}
let statuses = repo.statuses(Some(&mut opts))?;
let untracked = statuses.iter().filter_map(|entry| {
match entry.status() {
git2::STATUS_WT_NEW => Some((join(root, entry.path_bytes()), None)),
_ => None,
}
});
let mut subpackages_found = Vec::new();
for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = file_path?;
// Filter out files blatantly outside this package. This is helped a
// bit obove via the `pathspec` function call, but we need to filter
// the entries in the index as well.
if!file_path.starts_with(pkg_path) {
continue
}
match file_path.file_name().and_then(|s| s.to_str()) {
// Filter out Cargo.lock and target always, we don't want to
// package a lock file no one will ever read and we also avoid
// build artifacts
Some("Cargo.lock") |
Some("target") => continue,
// Keep track of all sub-packages found and also strip out all
// matches we've found so far. Note, though, that if we find
// our own `Cargo.toml` we keep going.
Some("Cargo.toml") => {
let path = file_path.parent().unwrap();
if path!= pkg_path {
warn!("subpackage found: {}", path.display());
ret.retain(|p|!p.starts_with(path));
subpackages_found.push(path.to_path_buf());
continue
}
}
_ => {}
}
// If this file is part of any other sub-package we've found so far,
// skip it.
if subpackages_found.iter().any(|p| file_path.starts_with(p)) {
continue
}
if is_dir.unwrap_or_else(|| file_path.is_dir()) {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, root).unwrap();
let rel = rel.to_str().ok_or_else(|| {
CargoError::from(format!("invalid utf-8 filename: {}", rel.display()))
})?;
// Git submodules are currently only named through `/` path
// separators, explicitly not `\` which windows uses. Who knew?
let rel = rel.replace(r"\", "/");
match repo.find_submodule(&rel).and_then(|s| s.open()) {
Ok(repo) => {
let files = self.list_files_git(pkg, repo, filter)?;
ret.extend(files.into_iter());
}
Err(..) => {
PathSource::walk(&file_path, &mut ret, false, filter)?;
}
}
} else if (*filter)(&file_path)? {
// We found a file!
warn!(" found {}", file_path.display());
ret.push(file_path);
}
}
return Ok(ret);
#[cfg(unix)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
use std::ffi::OsStr;
Ok(path.join(<OsStr as OsStrExt>::from_bytes(data)))
}
#[cfg(windows)]
fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(data) {
Ok(s) => Ok(path.join(s)),
Err(..) => Err(internal("cannot process path in git with a non \
unicode filename")),
}
}
}
fn list_files_walk(&self, pkg: &Package, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
PathSource::walk(pkg.root(), &mut ret, true, filter)?;
Ok(ret)
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<()>
{
if!fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
if (*filter)(path)? {
ret.push(path.to_path_buf());
}
return Ok(())
}
// Don't recurse into any sub-packages that we have
if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
return Ok(())
}
// For package integration tests, we need to sort the paths in a deterministic order to
// be able to match stdout warnings in the same order.
//
// TODO: Drop collect and sort after transition period and dropping wraning tests.
// See <https://github.com/rust-lang/cargo/issues/4268>
// and <https://github.com/rust-lang/cargo/pull/4270>
let mut entries: Vec<fs::DirEntry> = fs::read_dir(path)?.map(|e| e.unwrap()).collect();
entries.sort_by(|a, b| a.path().as_os_str().cmp(b.path().as_os_str()));
for entry in entries {
let path = entry.path();
let name = path.file_name().and_then(|s| s.to_str());
// Skip dotfile directories
if name.map(|s| s.starts_with('.')) == Some(true) {
continue
} else if is_root {
// Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue,
_ => {}
}
}
PathSource::walk(&path, ret, false, filter)?;
}
Ok(())
}
}
impl<'cfg> Debug for PathSource<'cfg> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "the paths source")
}
}
impl<'cfg> Registry for PathSource<'cfg> {
fn query(&mut self,
dep: &Dependency,
f: &mut FnMut(Summary)) -> CargoResult<()> {
for s in self.packages.iter().map(|p| p.summary()) {
if dep.matches(s) {
f(s.clone())
}
}
Ok(())
}
fn supports_checksums(&self) -> bool {
false
}
fn requires_precise(&self) -> bool {
false
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn source_id(&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
if!self.updated {
let packages = self.read_packages()?;
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package> {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if!self.updated {
return Err(internal("BUG: source was not updated"));
}
let mut max = FileTime::zero();
let mut max_path = PathBuf::from("");
for file in self.list_files(pkg)? {
// An fs::stat error here is either because path is a
// broken symlink, a permissions error, or a race
// condition where this path was rm'ed - either way,
// we can ignore the error and treat the path's mtime
// as 0.
let mtime = fs::metadata(&file).map(|meta| {
FileTime::from_last_modification_time(&meta)
}).unwrap_or(FileTime::zero());
warn!("{} {}", mtime, file.display());
if mtime > max {
max = mtime;
max_path = file;
}
} | random_line_split |
||
typeid-intrinsic2.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.
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn | () -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId { TypeId::of::<C>() }
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T:'static>() -> TypeId { TypeId::of::<T>() }
| id_B | identifier_name |
typeid-intrinsic2.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 |
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn id_B() -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId { TypeId::of::<C>() }
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T:'static>() -> TypeId { TypeId::of::<T>() } | // option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
typeid-intrinsic2.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.
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn id_B() -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId |
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T:'static>() -> TypeId { TypeId::of::<T>() }
| { TypeId::of::<C>() } | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.