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 |
---|---|---|---|---|
publisher_to_multiple_subscribers.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String, rosgraph_msgs / Log); | #[test]
fn publisher_to_multiple_subscribers() {
let _roscore = util::run_roscore_for(util::Language::Multi, util::Feature::Publisher);
let _subscriber_cpp = util::ChildProcessTerminator::spawn(
Command::new("rosrun")
.arg("roscpp_tutorials")
.arg("listener")
.arg("__name:=listener_cpp"),
);
let _subscriber_py = util::ChildProcessTerminator::spawn(
Command::new("rosrun")
.arg("rospy_tutorials")
.arg("listener"),
);
let _subscriber_rust = util::ChildProcessTerminator::spawn_example(
Command::new("cargo")
.arg("run")
.arg("--example")
.arg("subscriber"),
);
rosrust::init("hello_world_talker");
let (tx, rx) = unbounded();
let _log_subscriber =
rosrust::subscribe::<msg::rosgraph_msgs::Log, _>("/rosout_agg", 100, move |data| {
tx.send((data.level, data.msg)).unwrap();
})
.unwrap();
let publisher = rosrust::publish::<msg::std_msgs::String>("chatter", 100).unwrap();
let message = msg::std_msgs::String {
data: "hello world".into(),
};
println!("Checking roscpp subscriber");
util::test_publisher(&publisher, &message, &rx, r"^I heard: \[hello world\]$", 50);
println!("Checking rospy subscriber");
util::test_publisher(&publisher, &message, &rx, r"I heard hello world$", 50);
println!("Checking rosrust subscriber");
util::test_publisher(&publisher, &message, &rx, r"^Received: hello world$", 50);
assert_eq!(publisher.subscriber_count(), 3);
} | }
| random_line_split |
path.rs | use std::cmp;
use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, ChainError};
use util::Config;
pub struct PathSource<'cfg> {
id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
}
// TODO: Figure out if packages should be discovered in new or self should be
// mut and packages are discovered in update
impl<'cfg> PathSource<'cfg> {
pub fn for_path(path: &Path, config: &'cfg Config)
-> CargoResult<PathSource<'cfg>> {
trace!("PathSource::for_path; path={}", path.display());
Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config))
}
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
/// The source will read the manifest and find any other packages contained
/// in the directory structure reachable by the root manifest.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
trace!("new; id={}", id);
PathSource {
id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
}
}
pub fn root_package(&self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
if!self.updated {
return Err(internal("source has not been updated"))
}
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.id.is_path() && self.id.precise().is_some() {
// If our source id is a path and it's listed with a precise
// version, then it means that we're not allowed to have nested
// dependencies (they've been rewritten to crates.io dependencies)
// In this case we specifically read just one package, not a list of
// packages.
let path = self.path.join("Cargo.toml");
let (pkg, _) = try!(ops::read_package(&path, &self.id,
self.config));
Ok(vec![pkg])
} else {
ops::read_packages(&self.path, &self.id, self.config)
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine what is 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.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let parse = |p: &String| {
Pattern::new(p).map_err(|e| {
human(format!("could not parse pattern `{}`: {}", p, e))
})
};
let exclude = try!(pkg.manifest().exclude().iter()
.map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
let include = try!(pkg.manifest().include().iter()
.map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
let mut filter = |p: &Path| {
let relative_path = util::without_prefix(p, &root).unwrap();
include.iter().any(|p| p.matches_path(&relative_path)) || {
include.len() == 0 &&
!exclude.iter().any(|p| p.matches_path(&relative_path))
}
};
// If this package is 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 check all packages in this source that are ancestors of the
// specified package (including the same package) to see if they're at
// the root of the git repository. This isn't always true, but it'll get
// us there most of the time!.
let repo = self.packages.iter()
.map(|pkg| pkg.root())
.filter(|path| root.starts_with(path))
.filter_map(|path| git2::Repository::open(&path).ok())
.next();
match repo {
Some(repo) => self.list_files_git(pkg, repo, &mut filter),
None => self.list_files_walk(pkg, &mut filter),
}
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> bool)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = try!(repo.index());
let root = try!(repo.workdir().chain_error(|| {
internal_error("Can't list files on a bare repository.", "")
}));
let pkg_path = pkg.root();
let mut ret = Vec::new();
// We use information from the git repository to guide use 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 an 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_t::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 = try!(repo.statuses(Some(&mut opts)));
let untracked = statuses.iter().map(|entry| {
(join(&root, entry.path_bytes()), None)
});
'outer: for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = try!(file_path);
// Filter out files outside this package.
if!file_path.starts_with(pkg_path) { continue }
// Filter out Cargo.lock and target always
{
let fname = file_path.file_name().and_then(|s| s.to_str());
if fname == Some("Cargo.lock") { continue }
if fname == Some("target") { continue }
}
// Filter out sub-packages of this package
for other_pkg in self.packages.iter().filter(|p| *p!= pkg) {
let other_path = other_pkg.root();
if other_path.starts_with(pkg_path) &&
file_path.starts_with(other_path) {
continue 'outer;
}
}
let is_dir = is_dir.or_else(|| {
fs::metadata(&file_path).ok().map(|m| m.is_dir())
}).unwrap_or(false);
if is_dir {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, &root).unwrap();
let rel = try!(rel.to_str().chain_error(|| {
human(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 = try!(self.list_files_git(pkg, repo, filter));
ret.extend(files.into_iter());
}
Err(..) => {
try!(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) -> bool)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
for pkg in self.packages.iter().filter(|p| *p == pkg) {
let loc = pkg.root();
try!(PathSource::walk(loc, &mut ret, true, filter));
}
return Ok(ret);
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> 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 dir in try!(fs::read_dir(path)) {
let dir = try!(dir).path();
let name = dir.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 { | _ => {}
}
}
try!(PathSource::walk(&dir, ret, false, filter));
}
return 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) -> CargoResult<Vec<Summary>> {
self.packages.query(dep)
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn update(&mut self) -> CargoResult<()> {
if!self.updated {
let packages = try!(self.read_packages());
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, _: &[PackageId]) -> CargoResult<()>{
// TODO: assert! that the PackageId is contained by the source
Ok(())
}
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
trace!("getting packages; ids={:?}", ids);
Ok(self.packages.iter()
.filter(|pkg| ids.iter().any(|id| pkg.package_id() == id))
.map(|pkg| pkg.clone())
.collect())
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if!self.updated {
return Err(internal_error("BUG: source was not updated", ""));
}
let mut max = FileTime::zero();
for file in try!(self.list_files(pkg)).iter() {
// 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());
max = cmp::max(max, mtime);
}
trace!("fingerprint {}: {}", self.path.display(), max);
Ok(max.to_string())
}
} | // Skip cargo artifacts
match name {
Some("target") | Some("Cargo.lock") => continue, | random_line_split |
path.rs | use std::cmp;
use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, ChainError};
use util::Config;
pub struct PathSource<'cfg> {
id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
}
// TODO: Figure out if packages should be discovered in new or self should be
// mut and packages are discovered in update
impl<'cfg> PathSource<'cfg> {
pub fn for_path(path: &Path, config: &'cfg Config)
-> CargoResult<PathSource<'cfg>> {
trace!("PathSource::for_path; path={}", path.display());
Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config))
}
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
/// The source will read the manifest and find any other packages contained
/// in the directory structure reachable by the root manifest.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
trace!("new; id={}", id);
PathSource {
id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
}
}
pub fn root_package(&self) -> CargoResult<Package> {
trace!("root_package; source={:?}", self);
if!self.updated {
return Err(internal("source has not been updated"))
}
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
}
fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.id.is_path() && self.id.precise().is_some() {
// If our source id is a path and it's listed with a precise
// version, then it means that we're not allowed to have nested
// dependencies (they've been rewritten to crates.io dependencies)
// In this case we specifically read just one package, not a list of
// packages.
let path = self.path.join("Cargo.toml");
let (pkg, _) = try!(ops::read_package(&path, &self.id,
self.config));
Ok(vec![pkg])
} else {
ops::read_packages(&self.path, &self.id, self.config)
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine what is 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.
pub fn | (&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let parse = |p: &String| {
Pattern::new(p).map_err(|e| {
human(format!("could not parse pattern `{}`: {}", p, e))
})
};
let exclude = try!(pkg.manifest().exclude().iter()
.map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
let include = try!(pkg.manifest().include().iter()
.map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
let mut filter = |p: &Path| {
let relative_path = util::without_prefix(p, &root).unwrap();
include.iter().any(|p| p.matches_path(&relative_path)) || {
include.len() == 0 &&
!exclude.iter().any(|p| p.matches_path(&relative_path))
}
};
// If this package is 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 check all packages in this source that are ancestors of the
// specified package (including the same package) to see if they're at
// the root of the git repository. This isn't always true, but it'll get
// us there most of the time!.
let repo = self.packages.iter()
.map(|pkg| pkg.root())
.filter(|path| root.starts_with(path))
.filter_map(|path| git2::Repository::open(&path).ok())
.next();
match repo {
Some(repo) => self.list_files_git(pkg, repo, &mut filter),
None => self.list_files_walk(pkg, &mut filter),
}
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> bool)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = try!(repo.index());
let root = try!(repo.workdir().chain_error(|| {
internal_error("Can't list files on a bare repository.", "")
}));
let pkg_path = pkg.root();
let mut ret = Vec::new();
// We use information from the git repository to guide use 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 an 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_t::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 = try!(repo.statuses(Some(&mut opts)));
let untracked = statuses.iter().map(|entry| {
(join(&root, entry.path_bytes()), None)
});
'outer: for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = try!(file_path);
// Filter out files outside this package.
if!file_path.starts_with(pkg_path) { continue }
// Filter out Cargo.lock and target always
{
let fname = file_path.file_name().and_then(|s| s.to_str());
if fname == Some("Cargo.lock") { continue }
if fname == Some("target") { continue }
}
// Filter out sub-packages of this package
for other_pkg in self.packages.iter().filter(|p| *p!= pkg) {
let other_path = other_pkg.root();
if other_path.starts_with(pkg_path) &&
file_path.starts_with(other_path) {
continue 'outer;
}
}
let is_dir = is_dir.or_else(|| {
fs::metadata(&file_path).ok().map(|m| m.is_dir())
}).unwrap_or(false);
if is_dir {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, &root).unwrap();
let rel = try!(rel.to_str().chain_error(|| {
human(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 = try!(self.list_files_git(pkg, repo, filter));
ret.extend(files.into_iter());
}
Err(..) => {
try!(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) -> bool)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
for pkg in self.packages.iter().filter(|p| *p == pkg) {
let loc = pkg.root();
try!(PathSource::walk(loc, &mut ret, true, filter));
}
return Ok(ret);
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> 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 dir in try!(fs::read_dir(path)) {
let dir = try!(dir).path();
let name = dir.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,
_ => {}
}
}
try!(PathSource::walk(&dir, ret, false, filter));
}
return 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) -> CargoResult<Vec<Summary>> {
self.packages.query(dep)
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn update(&mut self) -> CargoResult<()> {
if!self.updated {
let packages = try!(self.read_packages());
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, _: &[PackageId]) -> CargoResult<()>{
// TODO: assert! that the PackageId is contained by the source
Ok(())
}
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
trace!("getting packages; ids={:?}", ids);
Ok(self.packages.iter()
.filter(|pkg| ids.iter().any(|id| pkg.package_id() == id))
.map(|pkg| pkg.clone())
.collect())
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if!self.updated {
return Err(internal_error("BUG: source was not updated", ""));
}
let mut max = FileTime::zero();
for file in try!(self.list_files(pkg)).iter() {
// 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());
max = cmp::max(max, mtime);
}
trace!("fingerprint {}: {}", self.path.display(), max);
Ok(max.to_string())
}
}
| list_files | identifier_name |
path.rs | use std::cmp;
use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use filetime::FileTime;
use git2;
use glob::Pattern;
use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry};
use ops;
use util::{self, CargoResult, internal, internal_error, human, ChainError};
use util::Config;
pub struct PathSource<'cfg> {
id: SourceId,
path: PathBuf,
updated: bool,
packages: Vec<Package>,
config: &'cfg Config,
}
// TODO: Figure out if packages should be discovered in new or self should be
// mut and packages are discovered in update
impl<'cfg> PathSource<'cfg> {
pub fn for_path(path: &Path, config: &'cfg Config)
-> CargoResult<PathSource<'cfg>> {
trace!("PathSource::for_path; path={}", path.display());
Ok(PathSource::new(path, &try!(SourceId::for_path(path)), config))
}
/// Invoked with an absolute path to a directory that contains a Cargo.toml.
/// The source will read the manifest and find any other packages contained
/// in the directory structure reachable by the root manifest.
pub fn new(path: &Path, id: &SourceId, config: &'cfg Config)
-> PathSource<'cfg> {
trace!("new; id={}", id);
PathSource {
id: id.clone(),
path: path.to_path_buf(),
updated: false,
packages: Vec::new(),
config: config,
}
}
pub fn root_package(&self) -> CargoResult<Package> |
fn read_packages(&self) -> CargoResult<Vec<Package>> {
if self.updated {
Ok(self.packages.clone())
} else if self.id.is_path() && self.id.precise().is_some() {
// If our source id is a path and it's listed with a precise
// version, then it means that we're not allowed to have nested
// dependencies (they've been rewritten to crates.io dependencies)
// In this case we specifically read just one package, not a list of
// packages.
let path = self.path.join("Cargo.toml");
let (pkg, _) = try!(ops::read_package(&path, &self.id,
self.config));
Ok(vec![pkg])
} else {
ops::read_packages(&self.path, &self.id, self.config)
}
}
/// List all files relevant to building this package inside this source.
///
/// This function will use the appropriate methods to determine what is 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.
pub fn list_files(&self, pkg: &Package) -> CargoResult<Vec<PathBuf>> {
let root = pkg.root();
let parse = |p: &String| {
Pattern::new(p).map_err(|e| {
human(format!("could not parse pattern `{}`: {}", p, e))
})
};
let exclude = try!(pkg.manifest().exclude().iter()
.map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
let include = try!(pkg.manifest().include().iter()
.map(|p| parse(p)).collect::<Result<Vec<_>, _>>());
let mut filter = |p: &Path| {
let relative_path = util::without_prefix(p, &root).unwrap();
include.iter().any(|p| p.matches_path(&relative_path)) || {
include.len() == 0 &&
!exclude.iter().any(|p| p.matches_path(&relative_path))
}
};
// If this package is 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 check all packages in this source that are ancestors of the
// specified package (including the same package) to see if they're at
// the root of the git repository. This isn't always true, but it'll get
// us there most of the time!.
let repo = self.packages.iter()
.map(|pkg| pkg.root())
.filter(|path| root.starts_with(path))
.filter_map(|path| git2::Repository::open(&path).ok())
.next();
match repo {
Some(repo) => self.list_files_git(pkg, repo, &mut filter),
None => self.list_files_walk(pkg, &mut filter),
}
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> bool)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = try!(repo.index());
let root = try!(repo.workdir().chain_error(|| {
internal_error("Can't list files on a bare repository.", "")
}));
let pkg_path = pkg.root();
let mut ret = Vec::new();
// We use information from the git repository to guide use 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 an 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_t::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 = try!(repo.statuses(Some(&mut opts)));
let untracked = statuses.iter().map(|entry| {
(join(&root, entry.path_bytes()), None)
});
'outer: for (file_path, is_dir) in index_files.chain(untracked) {
let file_path = try!(file_path);
// Filter out files outside this package.
if!file_path.starts_with(pkg_path) { continue }
// Filter out Cargo.lock and target always
{
let fname = file_path.file_name().and_then(|s| s.to_str());
if fname == Some("Cargo.lock") { continue }
if fname == Some("target") { continue }
}
// Filter out sub-packages of this package
for other_pkg in self.packages.iter().filter(|p| *p!= pkg) {
let other_path = other_pkg.root();
if other_path.starts_with(pkg_path) &&
file_path.starts_with(other_path) {
continue 'outer;
}
}
let is_dir = is_dir.or_else(|| {
fs::metadata(&file_path).ok().map(|m| m.is_dir())
}).unwrap_or(false);
if is_dir {
warn!(" found submodule {}", file_path.display());
let rel = util::without_prefix(&file_path, &root).unwrap();
let rel = try!(rel.to_str().chain_error(|| {
human(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 = try!(self.list_files_git(pkg, repo, filter));
ret.extend(files.into_iter());
}
Err(..) => {
try!(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) -> bool)
-> CargoResult<Vec<PathBuf>> {
let mut ret = Vec::new();
for pkg in self.packages.iter().filter(|p| *p == pkg) {
let loc = pkg.root();
try!(PathSource::walk(loc, &mut ret, true, filter));
}
return Ok(ret);
}
fn walk(path: &Path, ret: &mut Vec<PathBuf>,
is_root: bool, filter: &mut FnMut(&Path) -> 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 dir in try!(fs::read_dir(path)) {
let dir = try!(dir).path();
let name = dir.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,
_ => {}
}
}
try!(PathSource::walk(&dir, ret, false, filter));
}
return 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) -> CargoResult<Vec<Summary>> {
self.packages.query(dep)
}
}
impl<'cfg> Source for PathSource<'cfg> {
fn update(&mut self) -> CargoResult<()> {
if!self.updated {
let packages = try!(self.read_packages());
self.packages.extend(packages.into_iter());
self.updated = true;
}
Ok(())
}
fn download(&mut self, _: &[PackageId]) -> CargoResult<()>{
// TODO: assert! that the PackageId is contained by the source
Ok(())
}
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
trace!("getting packages; ids={:?}", ids);
Ok(self.packages.iter()
.filter(|pkg| ids.iter().any(|id| pkg.package_id() == id))
.map(|pkg| pkg.clone())
.collect())
}
fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
if!self.updated {
return Err(internal_error("BUG: source was not updated", ""));
}
let mut max = FileTime::zero();
for file in try!(self.list_files(pkg)).iter() {
// 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());
max = cmp::max(max, mtime);
}
trace!("fingerprint {}: {}", self.path.display(), max);
Ok(max.to_string())
}
}
| {
trace!("root_package; source={:?}", self);
if !self.updated {
return Err(internal("source has not been updated"))
}
match self.packages.iter().find(|p| p.root() == &*self.path) {
Some(pkg) => Ok(pkg.clone()),
None => Err(internal("no package found in source"))
}
} | identifier_body |
selector_parser.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/. */
//! Gecko-specific bits for selector-parsing.
use cssparser::ToCss;
use element_state::ElementState;
use gecko_bindings::structs::CSSPseudoClassType;
use selector_parser::{SelectorParser, PseudoElementCascadeType};
use selector_parser::{attr_equals_selector_is_shareable, attr_exists_selector_is_shareable};
use selectors::parser::AttrSelector;
use std::borrow::Cow;
use std::fmt;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
/// A representation of a CSS pseudo-element.
///
/// In Gecko, we represent pseudo-elements as plain `Atom`s.
///
/// The boolean field represents whether this element is an anonymous box. This
/// is just for convenience, instead of recomputing it.
///
/// Also, note that the `Atom` member is always a static atom, so if space is a
/// concern, we can use the raw pointer and use the lower bit to represent it
/// without space overhead.
///
/// FIXME(emilio): we know all these atoms are static. Patches are starting to
/// pile up, but a further potential optimisation is generating bindings without
/// `-no-gen-bitfield-methods` (that was removed to compile on stable, but it no
/// longer depends on it), and using the raw *mut nsIAtom (properly asserting
/// we're a static atom).
///
/// This should allow us to avoid random FFI overhead when cloning/dropping
/// pseudos.
///
/// Also, we can further optimize PartialEq and hash comparing/hashing only the
/// atoms.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PseudoElement(Atom, bool);
impl PseudoElement {
/// Get the pseudo-element as an atom.
#[inline]
pub fn as_atom(&self) -> &Atom {
&self.0
}
/// Whether this pseudo-element is an anonymous box.
#[inline]
fn is_anon_box(&self) -> bool {
self.1
}
/// Construct a pseudo-element from an `Atom`, receiving whether it is also
/// an anonymous box, and don't check it on release builds.
///
/// On debug builds we assert it's the result we expect.
#[inline]
pub fn from_atom_unchecked(atom: Atom, is_anon_box: bool) -> Self {
if cfg!(debug_assertions) {
// Do the check on debug regardless.
match Self::from_atom(&*atom, true) {
Some(pseudo) => {
assert_eq!(pseudo.is_anon_box(), is_anon_box);
return pseudo;
}
None => panic!("Unknown pseudo: {:?}", atom),
}
}
PseudoElement(atom, is_anon_box)
}
#[inline]
fn from_atom(atom: &WeakAtom, _in_ua: bool) -> Option<Self> {
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if atom == &*$atom {
return Some(PseudoElement($atom, $is_anon_box));
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
/// Constructs an atom from a string of text, and whether we're in a
/// user-agent stylesheet.
///
/// If we're not in a user-agent stylesheet, we will never parse anonymous
/// box pseudo-elements.
///
/// Returns `None` if the pseudo-element is not recognised.
#[inline]
fn from_slice(s: &str, in_ua_stylesheet: bool) -> Option<Self> {
use std::ascii::AsciiExt;
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if!$is_anon_box || in_ua_stylesheet {
if s.eq_ignore_ascii_case(&$pseudo_str_with_colon[1..]) {
return Some(PseudoElement($atom, $is_anon_box))
}
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
}
impl ToCss for PseudoElement {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
// FIXME: why does the atom contain one colon? Pseudo-element has two
debug_assert!(self.0.as_slice().starts_with(&[b':' as u16]) &&
!self.0.as_slice().starts_with(&[b':' as u16, b':' as u16]));
try!(dest.write_char(':'));
write!(dest, "{}", self.0)
}
}
bitflags! {
flags NonTSPseudoClassFlag: u8 {
// See NonTSPseudoClass::is_internal()
const PSEUDO_CLASS_INTERNAL = 0x01,
}
}
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
#[doc = "Our representation of a non tree-structural pseudo-class."]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum NonTSPseudoClass {
$(
#[doc = $css]
$name,
)*
}
}
}
include!("non_ts_pseudo_class_list.rs");
impl ToCss for NonTSPseudoClass {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => concat!(":", $css),)*
}
}
}
dest.write_str(include!("non_ts_pseudo_class_list.rs"))
}
}
impl NonTSPseudoClass {
/// A pseudo-class is internal if it can only be used inside
/// user agent style sheets.
pub fn is_internal(&self) -> bool {
macro_rules! check_flag {
(_) => (false);
($flags:expr) => ($flags.contains(PSEUDO_CLASS_INTERNAL));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => check_flag!($flags),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Get the state flag associated with a pseudo-class, if any.
pub fn state_flag(&self) -> ElementState {
macro_rules! flag {
(_) => (ElementState::empty());
($state:ident) => (::element_state::$state);
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => flag!($state),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Convert NonTSPseudoClass to Gecko's CSSPseudoClassType.
pub fn to_gecko_pseudoclasstype(&self) -> Option<CSSPseudoClassType> {
macro_rules! gecko_type {
(_) => (None);
($gecko_type:ident) =>
(Some(::gecko_bindings::structs::CSSPseudoClassType::$gecko_type));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => gecko_type!($gecko_type),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
}
/// The dummy struct we use to implement our selector parsing.
#[derive(Clone, Debug, PartialEq)]
pub struct | ;
impl ::selectors::SelectorImpl for SelectorImpl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespacePrefix = Atom;
type NamespaceUrl = Namespace;
type BorrowedNamespaceUrl = WeakNamespace;
type BorrowedLocalName = WeakAtom;
type PseudoElement = PseudoElement;
type NonTSPseudoClass = NonTSPseudoClass;
fn attr_exists_selector_is_shareable(attr_selector: &AttrSelector<Self>) -> bool {
attr_exists_selector_is_shareable(attr_selector)
}
fn attr_equals_selector_is_shareable(attr_selector: &AttrSelector<Self>,
value: &Self::AttrValue) -> bool {
attr_equals_selector_is_shareable(attr_selector, value)
}
}
impl<'a> ::selectors::Parser for SelectorParser<'a> {
type Impl = SelectorImpl;
fn parse_non_ts_pseudo_class(&self, name: Cow<str>) -> Result<NonTSPseudoClass, ()> {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match_ignore_ascii_case! { &name,
$($css => NonTSPseudoClass::$name,)*
_ => return Err(())
}
}
}
let pseudo_class = include!("non_ts_pseudo_class_list.rs");
if!pseudo_class.is_internal() || self.in_user_agent_stylesheet() {
Ok(pseudo_class)
} else {
Err(())
}
}
fn parse_pseudo_element(&self, name: Cow<str>) -> Result<PseudoElement, ()> {
match PseudoElement::from_slice(&name, self.in_user_agent_stylesheet()) {
Some(pseudo) => Ok(pseudo),
None => Err(()),
}
}
fn default_namespace(&self) -> Option<Namespace> {
self.namespaces.default.clone()
}
fn namespace_for_prefix(&self, prefix: &Atom) -> Option<Namespace> {
self.namespaces.prefixes.get(prefix).cloned()
}
}
impl SelectorImpl {
#[inline]
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn pseudo_element_cascade_type(pseudo: &PseudoElement) -> PseudoElementCascadeType {
if Self::pseudo_is_before_or_after(pseudo) {
return PseudoElementCascadeType::Eager
}
if pseudo.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
#[inline]
/// Executes a function for each pseudo-element.
pub fn each_pseudo_element<F>(mut fun: F)
where F: FnMut(PseudoElement),
{
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
fun(PseudoElement($atom, $is_anon_box));
}}
}
include!("generated/gecko_pseudo_element_helper.rs")
}
#[inline]
/// Returns whether the given pseudo-element is `::before` or `::after`.
pub fn pseudo_is_before_or_after(pseudo: &PseudoElement) -> bool {
*pseudo.as_atom() == atom!(":before") ||
*pseudo.as_atom() == atom!(":after")
}
#[inline]
/// Returns the relevant state flag for a given non-tree-structural
/// pseudo-class.
pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState {
pc.state_flag()
}
}
| SelectorImpl | identifier_name |
selector_parser.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/. */
//! Gecko-specific bits for selector-parsing.
use cssparser::ToCss;
use element_state::ElementState;
use gecko_bindings::structs::CSSPseudoClassType;
use selector_parser::{SelectorParser, PseudoElementCascadeType};
use selector_parser::{attr_equals_selector_is_shareable, attr_exists_selector_is_shareable};
use selectors::parser::AttrSelector;
use std::borrow::Cow;
use std::fmt;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
/// A representation of a CSS pseudo-element.
///
/// In Gecko, we represent pseudo-elements as plain `Atom`s.
///
/// The boolean field represents whether this element is an anonymous box. This
/// is just for convenience, instead of recomputing it.
///
/// Also, note that the `Atom` member is always a static atom, so if space is a
/// concern, we can use the raw pointer and use the lower bit to represent it
/// without space overhead.
///
/// FIXME(emilio): we know all these atoms are static. Patches are starting to
/// pile up, but a further potential optimisation is generating bindings without
/// `-no-gen-bitfield-methods` (that was removed to compile on stable, but it no
/// longer depends on it), and using the raw *mut nsIAtom (properly asserting
/// we're a static atom).
///
/// This should allow us to avoid random FFI overhead when cloning/dropping
/// pseudos.
///
/// Also, we can further optimize PartialEq and hash comparing/hashing only the
/// atoms.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PseudoElement(Atom, bool);
impl PseudoElement {
/// Get the pseudo-element as an atom.
#[inline]
pub fn as_atom(&self) -> &Atom {
&self.0
}
/// Whether this pseudo-element is an anonymous box.
#[inline]
fn is_anon_box(&self) -> bool {
self.1
}
/// Construct a pseudo-element from an `Atom`, receiving whether it is also
/// an anonymous box, and don't check it on release builds.
///
/// On debug builds we assert it's the result we expect.
#[inline]
pub fn from_atom_unchecked(atom: Atom, is_anon_box: bool) -> Self {
if cfg!(debug_assertions) |
PseudoElement(atom, is_anon_box)
}
#[inline]
fn from_atom(atom: &WeakAtom, _in_ua: bool) -> Option<Self> {
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if atom == &*$atom {
return Some(PseudoElement($atom, $is_anon_box));
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
/// Constructs an atom from a string of text, and whether we're in a
/// user-agent stylesheet.
///
/// If we're not in a user-agent stylesheet, we will never parse anonymous
/// box pseudo-elements.
///
/// Returns `None` if the pseudo-element is not recognised.
#[inline]
fn from_slice(s: &str, in_ua_stylesheet: bool) -> Option<Self> {
use std::ascii::AsciiExt;
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if!$is_anon_box || in_ua_stylesheet {
if s.eq_ignore_ascii_case(&$pseudo_str_with_colon[1..]) {
return Some(PseudoElement($atom, $is_anon_box))
}
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
}
impl ToCss for PseudoElement {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
// FIXME: why does the atom contain one colon? Pseudo-element has two
debug_assert!(self.0.as_slice().starts_with(&[b':' as u16]) &&
!self.0.as_slice().starts_with(&[b':' as u16, b':' as u16]));
try!(dest.write_char(':'));
write!(dest, "{}", self.0)
}
}
bitflags! {
flags NonTSPseudoClassFlag: u8 {
// See NonTSPseudoClass::is_internal()
const PSEUDO_CLASS_INTERNAL = 0x01,
}
}
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
#[doc = "Our representation of a non tree-structural pseudo-class."]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum NonTSPseudoClass {
$(
#[doc = $css]
$name,
)*
}
}
}
include!("non_ts_pseudo_class_list.rs");
impl ToCss for NonTSPseudoClass {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => concat!(":", $css),)*
}
}
}
dest.write_str(include!("non_ts_pseudo_class_list.rs"))
}
}
impl NonTSPseudoClass {
/// A pseudo-class is internal if it can only be used inside
/// user agent style sheets.
pub fn is_internal(&self) -> bool {
macro_rules! check_flag {
(_) => (false);
($flags:expr) => ($flags.contains(PSEUDO_CLASS_INTERNAL));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => check_flag!($flags),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Get the state flag associated with a pseudo-class, if any.
pub fn state_flag(&self) -> ElementState {
macro_rules! flag {
(_) => (ElementState::empty());
($state:ident) => (::element_state::$state);
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => flag!($state),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Convert NonTSPseudoClass to Gecko's CSSPseudoClassType.
pub fn to_gecko_pseudoclasstype(&self) -> Option<CSSPseudoClassType> {
macro_rules! gecko_type {
(_) => (None);
($gecko_type:ident) =>
(Some(::gecko_bindings::structs::CSSPseudoClassType::$gecko_type));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => gecko_type!($gecko_type),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
}
/// The dummy struct we use to implement our selector parsing.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectorImpl;
impl ::selectors::SelectorImpl for SelectorImpl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespacePrefix = Atom;
type NamespaceUrl = Namespace;
type BorrowedNamespaceUrl = WeakNamespace;
type BorrowedLocalName = WeakAtom;
type PseudoElement = PseudoElement;
type NonTSPseudoClass = NonTSPseudoClass;
fn attr_exists_selector_is_shareable(attr_selector: &AttrSelector<Self>) -> bool {
attr_exists_selector_is_shareable(attr_selector)
}
fn attr_equals_selector_is_shareable(attr_selector: &AttrSelector<Self>,
value: &Self::AttrValue) -> bool {
attr_equals_selector_is_shareable(attr_selector, value)
}
}
impl<'a> ::selectors::Parser for SelectorParser<'a> {
type Impl = SelectorImpl;
fn parse_non_ts_pseudo_class(&self, name: Cow<str>) -> Result<NonTSPseudoClass, ()> {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match_ignore_ascii_case! { &name,
$($css => NonTSPseudoClass::$name,)*
_ => return Err(())
}
}
}
let pseudo_class = include!("non_ts_pseudo_class_list.rs");
if!pseudo_class.is_internal() || self.in_user_agent_stylesheet() {
Ok(pseudo_class)
} else {
Err(())
}
}
fn parse_pseudo_element(&self, name: Cow<str>) -> Result<PseudoElement, ()> {
match PseudoElement::from_slice(&name, self.in_user_agent_stylesheet()) {
Some(pseudo) => Ok(pseudo),
None => Err(()),
}
}
fn default_namespace(&self) -> Option<Namespace> {
self.namespaces.default.clone()
}
fn namespace_for_prefix(&self, prefix: &Atom) -> Option<Namespace> {
self.namespaces.prefixes.get(prefix).cloned()
}
}
impl SelectorImpl {
#[inline]
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn pseudo_element_cascade_type(pseudo: &PseudoElement) -> PseudoElementCascadeType {
if Self::pseudo_is_before_or_after(pseudo) {
return PseudoElementCascadeType::Eager
}
if pseudo.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
#[inline]
/// Executes a function for each pseudo-element.
pub fn each_pseudo_element<F>(mut fun: F)
where F: FnMut(PseudoElement),
{
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
fun(PseudoElement($atom, $is_anon_box));
}}
}
include!("generated/gecko_pseudo_element_helper.rs")
}
#[inline]
/// Returns whether the given pseudo-element is `::before` or `::after`.
pub fn pseudo_is_before_or_after(pseudo: &PseudoElement) -> bool {
*pseudo.as_atom() == atom!(":before") ||
*pseudo.as_atom() == atom!(":after")
}
#[inline]
/// Returns the relevant state flag for a given non-tree-structural
/// pseudo-class.
pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState {
pc.state_flag()
}
}
| {
// Do the check on debug regardless.
match Self::from_atom(&*atom, true) {
Some(pseudo) => {
assert_eq!(pseudo.is_anon_box(), is_anon_box);
return pseudo;
}
None => panic!("Unknown pseudo: {:?}", atom),
}
} | conditional_block |
selector_parser.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/. */
//! Gecko-specific bits for selector-parsing.
use cssparser::ToCss;
use element_state::ElementState;
use gecko_bindings::structs::CSSPseudoClassType;
use selector_parser::{SelectorParser, PseudoElementCascadeType};
use selector_parser::{attr_equals_selector_is_shareable, attr_exists_selector_is_shareable};
use selectors::parser::AttrSelector;
use std::borrow::Cow;
use std::fmt;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
/// A representation of a CSS pseudo-element.
///
/// In Gecko, we represent pseudo-elements as plain `Atom`s.
///
/// The boolean field represents whether this element is an anonymous box. This
/// is just for convenience, instead of recomputing it.
///
/// Also, note that the `Atom` member is always a static atom, so if space is a
/// concern, we can use the raw pointer and use the lower bit to represent it
/// without space overhead.
///
/// FIXME(emilio): we know all these atoms are static. Patches are starting to
/// pile up, but a further potential optimisation is generating bindings without
/// `-no-gen-bitfield-methods` (that was removed to compile on stable, but it no
/// longer depends on it), and using the raw *mut nsIAtom (properly asserting
/// we're a static atom).
///
/// This should allow us to avoid random FFI overhead when cloning/dropping
/// pseudos.
///
/// Also, we can further optimize PartialEq and hash comparing/hashing only the
/// atoms.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PseudoElement(Atom, bool);
impl PseudoElement {
/// Get the pseudo-element as an atom.
#[inline]
pub fn as_atom(&self) -> &Atom {
&self.0
}
/// Whether this pseudo-element is an anonymous box.
#[inline]
fn is_anon_box(&self) -> bool {
self.1
}
/// Construct a pseudo-element from an `Atom`, receiving whether it is also
/// an anonymous box, and don't check it on release builds.
///
/// On debug builds we assert it's the result we expect.
#[inline]
pub fn from_atom_unchecked(atom: Atom, is_anon_box: bool) -> Self {
if cfg!(debug_assertions) {
// Do the check on debug regardless.
match Self::from_atom(&*atom, true) {
Some(pseudo) => {
assert_eq!(pseudo.is_anon_box(), is_anon_box);
return pseudo;
}
None => panic!("Unknown pseudo: {:?}", atom),
}
}
PseudoElement(atom, is_anon_box)
}
#[inline]
fn from_atom(atom: &WeakAtom, _in_ua: bool) -> Option<Self> {
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if atom == &*$atom {
return Some(PseudoElement($atom, $is_anon_box));
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
/// Constructs an atom from a string of text, and whether we're in a
/// user-agent stylesheet.
///
/// If we're not in a user-agent stylesheet, we will never parse anonymous
/// box pseudo-elements.
///
/// Returns `None` if the pseudo-element is not recognised.
#[inline]
fn from_slice(s: &str, in_ua_stylesheet: bool) -> Option<Self> {
use std::ascii::AsciiExt;
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if!$is_anon_box || in_ua_stylesheet {
if s.eq_ignore_ascii_case(&$pseudo_str_with_colon[1..]) {
return Some(PseudoElement($atom, $is_anon_box))
}
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
}
impl ToCss for PseudoElement {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
// FIXME: why does the atom contain one colon? Pseudo-element has two
debug_assert!(self.0.as_slice().starts_with(&[b':' as u16]) &&
!self.0.as_slice().starts_with(&[b':' as u16, b':' as u16]));
try!(dest.write_char(':'));
write!(dest, "{}", self.0)
}
}
bitflags! {
flags NonTSPseudoClassFlag: u8 {
// See NonTSPseudoClass::is_internal()
const PSEUDO_CLASS_INTERNAL = 0x01,
}
}
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
#[doc = "Our representation of a non tree-structural pseudo-class."]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum NonTSPseudoClass {
$(
#[doc = $css]
$name,
)*
}
}
}
include!("non_ts_pseudo_class_list.rs");
impl ToCss for NonTSPseudoClass {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => concat!(":", $css),)*
}
}
}
dest.write_str(include!("non_ts_pseudo_class_list.rs"))
}
}
impl NonTSPseudoClass {
/// A pseudo-class is internal if it can only be used inside
/// user agent style sheets.
pub fn is_internal(&self) -> bool {
macro_rules! check_flag {
(_) => (false);
($flags:expr) => ($flags.contains(PSEUDO_CLASS_INTERNAL));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => check_flag!($flags),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Get the state flag associated with a pseudo-class, if any.
pub fn state_flag(&self) -> ElementState {
macro_rules! flag {
(_) => (ElementState::empty());
($state:ident) => (::element_state::$state);
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => flag!($state),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Convert NonTSPseudoClass to Gecko's CSSPseudoClassType.
pub fn to_gecko_pseudoclasstype(&self) -> Option<CSSPseudoClassType> {
macro_rules! gecko_type {
(_) => (None);
($gecko_type:ident) =>
(Some(::gecko_bindings::structs::CSSPseudoClassType::$gecko_type));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => gecko_type!($gecko_type),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
}
/// The dummy struct we use to implement our selector parsing.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectorImpl;
impl ::selectors::SelectorImpl for SelectorImpl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespacePrefix = Atom;
type NamespaceUrl = Namespace;
type BorrowedNamespaceUrl = WeakNamespace;
type BorrowedLocalName = WeakAtom;
type PseudoElement = PseudoElement;
type NonTSPseudoClass = NonTSPseudoClass;
fn attr_exists_selector_is_shareable(attr_selector: &AttrSelector<Self>) -> bool {
attr_exists_selector_is_shareable(attr_selector)
}
fn attr_equals_selector_is_shareable(attr_selector: &AttrSelector<Self>,
value: &Self::AttrValue) -> bool {
attr_equals_selector_is_shareable(attr_selector, value)
} | type Impl = SelectorImpl;
fn parse_non_ts_pseudo_class(&self, name: Cow<str>) -> Result<NonTSPseudoClass, ()> {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match_ignore_ascii_case! { &name,
$($css => NonTSPseudoClass::$name,)*
_ => return Err(())
}
}
}
let pseudo_class = include!("non_ts_pseudo_class_list.rs");
if!pseudo_class.is_internal() || self.in_user_agent_stylesheet() {
Ok(pseudo_class)
} else {
Err(())
}
}
fn parse_pseudo_element(&self, name: Cow<str>) -> Result<PseudoElement, ()> {
match PseudoElement::from_slice(&name, self.in_user_agent_stylesheet()) {
Some(pseudo) => Ok(pseudo),
None => Err(()),
}
}
fn default_namespace(&self) -> Option<Namespace> {
self.namespaces.default.clone()
}
fn namespace_for_prefix(&self, prefix: &Atom) -> Option<Namespace> {
self.namespaces.prefixes.get(prefix).cloned()
}
}
impl SelectorImpl {
#[inline]
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn pseudo_element_cascade_type(pseudo: &PseudoElement) -> PseudoElementCascadeType {
if Self::pseudo_is_before_or_after(pseudo) {
return PseudoElementCascadeType::Eager
}
if pseudo.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
#[inline]
/// Executes a function for each pseudo-element.
pub fn each_pseudo_element<F>(mut fun: F)
where F: FnMut(PseudoElement),
{
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
fun(PseudoElement($atom, $is_anon_box));
}}
}
include!("generated/gecko_pseudo_element_helper.rs")
}
#[inline]
/// Returns whether the given pseudo-element is `::before` or `::after`.
pub fn pseudo_is_before_or_after(pseudo: &PseudoElement) -> bool {
*pseudo.as_atom() == atom!(":before") ||
*pseudo.as_atom() == atom!(":after")
}
#[inline]
/// Returns the relevant state flag for a given non-tree-structural
/// pseudo-class.
pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState {
pc.state_flag()
}
} | }
impl<'a> ::selectors::Parser for SelectorParser<'a> { | random_line_split |
selector_parser.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/. */
//! Gecko-specific bits for selector-parsing.
use cssparser::ToCss;
use element_state::ElementState;
use gecko_bindings::structs::CSSPseudoClassType;
use selector_parser::{SelectorParser, PseudoElementCascadeType};
use selector_parser::{attr_equals_selector_is_shareable, attr_exists_selector_is_shareable};
use selectors::parser::AttrSelector;
use std::borrow::Cow;
use std::fmt;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
/// A representation of a CSS pseudo-element.
///
/// In Gecko, we represent pseudo-elements as plain `Atom`s.
///
/// The boolean field represents whether this element is an anonymous box. This
/// is just for convenience, instead of recomputing it.
///
/// Also, note that the `Atom` member is always a static atom, so if space is a
/// concern, we can use the raw pointer and use the lower bit to represent it
/// without space overhead.
///
/// FIXME(emilio): we know all these atoms are static. Patches are starting to
/// pile up, but a further potential optimisation is generating bindings without
/// `-no-gen-bitfield-methods` (that was removed to compile on stable, but it no
/// longer depends on it), and using the raw *mut nsIAtom (properly asserting
/// we're a static atom).
///
/// This should allow us to avoid random FFI overhead when cloning/dropping
/// pseudos.
///
/// Also, we can further optimize PartialEq and hash comparing/hashing only the
/// atoms.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PseudoElement(Atom, bool);
impl PseudoElement {
/// Get the pseudo-element as an atom.
#[inline]
pub fn as_atom(&self) -> &Atom {
&self.0
}
/// Whether this pseudo-element is an anonymous box.
#[inline]
fn is_anon_box(&self) -> bool {
self.1
}
/// Construct a pseudo-element from an `Atom`, receiving whether it is also
/// an anonymous box, and don't check it on release builds.
///
/// On debug builds we assert it's the result we expect.
#[inline]
pub fn from_atom_unchecked(atom: Atom, is_anon_box: bool) -> Self {
if cfg!(debug_assertions) {
// Do the check on debug regardless.
match Self::from_atom(&*atom, true) {
Some(pseudo) => {
assert_eq!(pseudo.is_anon_box(), is_anon_box);
return pseudo;
}
None => panic!("Unknown pseudo: {:?}", atom),
}
}
PseudoElement(atom, is_anon_box)
}
#[inline]
fn from_atom(atom: &WeakAtom, _in_ua: bool) -> Option<Self> {
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if atom == &*$atom {
return Some(PseudoElement($atom, $is_anon_box));
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
/// Constructs an atom from a string of text, and whether we're in a
/// user-agent stylesheet.
///
/// If we're not in a user-agent stylesheet, we will never parse anonymous
/// box pseudo-elements.
///
/// Returns `None` if the pseudo-element is not recognised.
#[inline]
fn from_slice(s: &str, in_ua_stylesheet: bool) -> Option<Self> {
use std::ascii::AsciiExt;
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
if!$is_anon_box || in_ua_stylesheet {
if s.eq_ignore_ascii_case(&$pseudo_str_with_colon[1..]) {
return Some(PseudoElement($atom, $is_anon_box))
}
}
}}
}
include!("generated/gecko_pseudo_element_helper.rs");
None
}
}
impl ToCss for PseudoElement {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
// FIXME: why does the atom contain one colon? Pseudo-element has two
debug_assert!(self.0.as_slice().starts_with(&[b':' as u16]) &&
!self.0.as_slice().starts_with(&[b':' as u16, b':' as u16]));
try!(dest.write_char(':'));
write!(dest, "{}", self.0)
}
}
bitflags! {
flags NonTSPseudoClassFlag: u8 {
// See NonTSPseudoClass::is_internal()
const PSEUDO_CLASS_INTERNAL = 0x01,
}
}
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
#[doc = "Our representation of a non tree-structural pseudo-class."]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum NonTSPseudoClass {
$(
#[doc = $css]
$name,
)*
}
}
}
include!("non_ts_pseudo_class_list.rs");
impl ToCss for NonTSPseudoClass {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => concat!(":", $css),)*
}
}
}
dest.write_str(include!("non_ts_pseudo_class_list.rs"))
}
}
impl NonTSPseudoClass {
/// A pseudo-class is internal if it can only be used inside
/// user agent style sheets.
pub fn is_internal(&self) -> bool {
macro_rules! check_flag {
(_) => (false);
($flags:expr) => ($flags.contains(PSEUDO_CLASS_INTERNAL));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => check_flag!($flags),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Get the state flag associated with a pseudo-class, if any.
pub fn state_flag(&self) -> ElementState {
macro_rules! flag {
(_) => (ElementState::empty());
($state:ident) => (::element_state::$state);
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $_gecko_type:tt, $state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => flag!($state),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
/// Convert NonTSPseudoClass to Gecko's CSSPseudoClassType.
pub fn to_gecko_pseudoclasstype(&self) -> Option<CSSPseudoClassType> {
macro_rules! gecko_type {
(_) => (None);
($gecko_type:ident) =>
(Some(::gecko_bindings::structs::CSSPseudoClassType::$gecko_type));
}
macro_rules! pseudo_class_list {
($(($_css:expr, $name:ident, $gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match *self {
$(NonTSPseudoClass::$name => gecko_type!($gecko_type),)*
}
}
}
include!("non_ts_pseudo_class_list.rs")
}
}
/// The dummy struct we use to implement our selector parsing.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectorImpl;
impl ::selectors::SelectorImpl for SelectorImpl {
type AttrValue = Atom;
type Identifier = Atom;
type ClassName = Atom;
type LocalName = Atom;
type NamespacePrefix = Atom;
type NamespaceUrl = Namespace;
type BorrowedNamespaceUrl = WeakNamespace;
type BorrowedLocalName = WeakAtom;
type PseudoElement = PseudoElement;
type NonTSPseudoClass = NonTSPseudoClass;
fn attr_exists_selector_is_shareable(attr_selector: &AttrSelector<Self>) -> bool {
attr_exists_selector_is_shareable(attr_selector)
}
fn attr_equals_selector_is_shareable(attr_selector: &AttrSelector<Self>,
value: &Self::AttrValue) -> bool {
attr_equals_selector_is_shareable(attr_selector, value)
}
}
impl<'a> ::selectors::Parser for SelectorParser<'a> {
type Impl = SelectorImpl;
fn parse_non_ts_pseudo_class(&self, name: Cow<str>) -> Result<NonTSPseudoClass, ()> {
macro_rules! pseudo_class_list {
($(($css:expr, $name:ident, $_gecko_type:tt, $_state:tt, $_flags:tt),)*) => {
match_ignore_ascii_case! { &name,
$($css => NonTSPseudoClass::$name,)*
_ => return Err(())
}
}
}
let pseudo_class = include!("non_ts_pseudo_class_list.rs");
if!pseudo_class.is_internal() || self.in_user_agent_stylesheet() {
Ok(pseudo_class)
} else {
Err(())
}
}
fn parse_pseudo_element(&self, name: Cow<str>) -> Result<PseudoElement, ()> {
match PseudoElement::from_slice(&name, self.in_user_agent_stylesheet()) {
Some(pseudo) => Ok(pseudo),
None => Err(()),
}
}
fn default_namespace(&self) -> Option<Namespace> {
self.namespaces.default.clone()
}
fn namespace_for_prefix(&self, prefix: &Atom) -> Option<Namespace> {
self.namespaces.prefixes.get(prefix).cloned()
}
}
impl SelectorImpl {
#[inline]
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn pseudo_element_cascade_type(pseudo: &PseudoElement) -> PseudoElementCascadeType {
if Self::pseudo_is_before_or_after(pseudo) {
return PseudoElementCascadeType::Eager
}
if pseudo.is_anon_box() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
#[inline]
/// Executes a function for each pseudo-element.
pub fn each_pseudo_element<F>(mut fun: F)
where F: FnMut(PseudoElement),
{
macro_rules! pseudo_element {
($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{
fun(PseudoElement($atom, $is_anon_box));
}}
}
include!("generated/gecko_pseudo_element_helper.rs")
}
#[inline]
/// Returns whether the given pseudo-element is `::before` or `::after`.
pub fn pseudo_is_before_or_after(pseudo: &PseudoElement) -> bool {
*pseudo.as_atom() == atom!(":before") ||
*pseudo.as_atom() == atom!(":after")
}
#[inline]
/// Returns the relevant state flag for a given non-tree-structural
/// pseudo-class.
pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState |
}
| {
pc.state_flag()
} | identifier_body |
error.rs | use std::fmt;
use std::error::Error;
/// Error when spawning a new state machine
pub enum SpawnError<S: Sized> {
/// The State Machine Slab capacity is reached
///
/// The capacity is configured in the `rotor::Config` and is used
/// for creating `rotor::Loop`.
///
/// The item in this struct is the Seed that send to create a machine
NoSlabSpace(S),
/// Error returned from `Machine::create` handler
UserError(Box<Error>),
}
impl<S> fmt::Display for SpawnError<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::SpawnError::*;
match *self {
NoSlabSpace(_) => {
write!(fmt, "state machine slab capacity limit is reached")
}
UserError(ref err) => {
write!(fmt, "{}", err)
}
}
}
}
impl<S> SpawnError<S> {
pub fn | (&self) -> &str {
use self::SpawnError::*;
match self {
&NoSlabSpace(_) => "state machine slab capacity limit is reached",
&UserError(ref err) => err.description(),
}
}
pub fn cause(&self) -> Option<&Error> {
use self::SpawnError::*;
match self {
&NoSlabSpace(_) => None,
&UserError(ref err) => Some(&**err),
}
}
pub fn map<T:Sized, F: FnOnce(S) -> T>(self, fun:F) -> SpawnError<T> {
use self::SpawnError::*;
match self {
NoSlabSpace(x) => NoSlabSpace(fun(x)),
UserError(e) => UserError(e),
}
}
}
impl<S: Error> Error for SpawnError<S> {
fn description(&self) -> &str {
self.description()
}
fn cause(&self) -> Option<&Error> {
self.cause()
}
}
impl<S> From<Box<Error>> for SpawnError<S> {
fn from(x: Box<Error>) -> SpawnError<S> {
SpawnError::UserError(x)
}
}
impl<S> fmt::Debug for SpawnError<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::SpawnError::*;
match *self {
NoSlabSpace(..) => {
write!(fmt, "NoSlabSpace(<hidden seed>)")
}
UserError(ref err) => {
write!(fmt, "UserError({:?})", err)
}
}
}
}
| description | identifier_name |
error.rs | use std::fmt;
use std::error::Error;
/// Error when spawning a new state machine
pub enum SpawnError<S: Sized> {
/// The State Machine Slab capacity is reached
///
/// The capacity is configured in the `rotor::Config` and is used
/// for creating `rotor::Loop`.
///
/// The item in this struct is the Seed that send to create a machine
NoSlabSpace(S),
/// Error returned from `Machine::create` handler
UserError(Box<Error>),
}
impl<S> fmt::Display for SpawnError<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::SpawnError::*;
match *self {
NoSlabSpace(_) => {
write!(fmt, "state machine slab capacity limit is reached")
}
UserError(ref err) => {
write!(fmt, "{}", err)
}
}
}
}
impl<S> SpawnError<S> {
pub fn description(&self) -> &str {
use self::SpawnError::*;
match self {
&NoSlabSpace(_) => "state machine slab capacity limit is reached",
&UserError(ref err) => err.description(),
}
}
pub fn cause(&self) -> Option<&Error> {
use self::SpawnError::*;
match self {
&NoSlabSpace(_) => None,
&UserError(ref err) => Some(&**err),
}
}
pub fn map<T:Sized, F: FnOnce(S) -> T>(self, fun:F) -> SpawnError<T> {
use self::SpawnError::*;
match self {
NoSlabSpace(x) => NoSlabSpace(fun(x)),
UserError(e) => UserError(e),
}
}
}
impl<S: Error> Error for SpawnError<S> {
fn description(&self) -> &str {
self.description()
}
fn cause(&self) -> Option<&Error> {
self.cause()
}
}
impl<S> From<Box<Error>> for SpawnError<S> {
fn from(x: Box<Error>) -> SpawnError<S> {
SpawnError::UserError(x)
}
}
| NoSlabSpace(..) => {
write!(fmt, "NoSlabSpace(<hidden seed>)")
}
UserError(ref err) => {
write!(fmt, "UserError({:?})", err)
}
}
}
} | impl<S> fmt::Debug for SpawnError<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::SpawnError::*;
match *self { | random_line_split |
error.rs | use std::fmt;
use std::error::Error;
/// Error when spawning a new state machine
pub enum SpawnError<S: Sized> {
/// The State Machine Slab capacity is reached
///
/// The capacity is configured in the `rotor::Config` and is used
/// for creating `rotor::Loop`.
///
/// The item in this struct is the Seed that send to create a machine
NoSlabSpace(S),
/// Error returned from `Machine::create` handler
UserError(Box<Error>),
}
impl<S> fmt::Display for SpawnError<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result |
}
impl<S> SpawnError<S> {
pub fn description(&self) -> &str {
use self::SpawnError::*;
match self {
&NoSlabSpace(_) => "state machine slab capacity limit is reached",
&UserError(ref err) => err.description(),
}
}
pub fn cause(&self) -> Option<&Error> {
use self::SpawnError::*;
match self {
&NoSlabSpace(_) => None,
&UserError(ref err) => Some(&**err),
}
}
pub fn map<T:Sized, F: FnOnce(S) -> T>(self, fun:F) -> SpawnError<T> {
use self::SpawnError::*;
match self {
NoSlabSpace(x) => NoSlabSpace(fun(x)),
UserError(e) => UserError(e),
}
}
}
impl<S: Error> Error for SpawnError<S> {
fn description(&self) -> &str {
self.description()
}
fn cause(&self) -> Option<&Error> {
self.cause()
}
}
impl<S> From<Box<Error>> for SpawnError<S> {
fn from(x: Box<Error>) -> SpawnError<S> {
SpawnError::UserError(x)
}
}
impl<S> fmt::Debug for SpawnError<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::SpawnError::*;
match *self {
NoSlabSpace(..) => {
write!(fmt, "NoSlabSpace(<hidden seed>)")
}
UserError(ref err) => {
write!(fmt, "UserError({:?})", err)
}
}
}
}
| {
use self::SpawnError::*;
match *self {
NoSlabSpace(_) => {
write!(fmt, "state machine slab capacity limit is reached")
}
UserError(ref err) => {
write!(fmt, "{}", err)
}
}
} | identifier_body |
webglrenderbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::webgl::{WebGLCommand, WebGLError, WebGLRenderbufferId, WebGLResult, is_gles, webgl_channel};
use dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as WebGl2Constants;
use dom::bindings::codegen::Bindings::WebGLRenderbufferBinding;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::webglobject::WebGLObject;
use dom::webglrenderingcontext::WebGLRenderingContext;
use dom_struct::dom_struct;
use std::cell::Cell;
#[dom_struct]
pub struct WebGLRenderbuffer {
webgl_object: WebGLObject,
id: WebGLRenderbufferId,
ever_bound: Cell<bool>,
is_deleted: Cell<bool>,
size: Cell<Option<(i32, i32)>>,
internal_format: Cell<Option<u32>>,
is_initialized: Cell<bool>,
}
impl WebGLRenderbuffer {
fn new_inherited(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> Self {
Self {
webgl_object: WebGLObject::new_inherited(context),
id: id,
ever_bound: Cell::new(false),
is_deleted: Cell::new(false),
internal_format: Cell::new(None),
size: Cell::new(None),
is_initialized: Cell::new(false),
}
}
pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> {
let (sender, receiver) = webgl_channel().unwrap();
context.send_command(WebGLCommand::CreateRenderbuffer(sender));
receiver
.recv()
.unwrap()
.map(|id| WebGLRenderbuffer::new(context, id))
}
pub fn new(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> DomRoot<Self> {
reflect_dom_object(
Box::new(WebGLRenderbuffer::new_inherited(context, id)),
&*context.global(),
WebGLRenderbufferBinding::Wrap,
)
}
}
impl WebGLRenderbuffer {
pub fn id(&self) -> WebGLRenderbufferId {
self.id
}
pub fn size(&self) -> Option<(i32, i32)> {
self.size.get()
}
pub fn internal_format(&self) -> u32 {
self.internal_format.get().unwrap_or(constants::RGBA4)
}
pub fn mark_initialized(&self) {
self.is_initialized.set(true);
}
pub fn is_initialized(&self) -> bool {
self.is_initialized.get()
}
pub fn bind(&self, target: u32) {
self.ever_bound.set(true);
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::BindRenderbuffer(target, Some(self.id)));
}
pub fn delete(&self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
/*
If a renderbuffer object is deleted while its image is attached to the currently
bound framebuffer, then it is as if FramebufferRenderbuffer had been called, with
a renderbuffer of 0, for each attachment point to which this image was attached
in the currently bound framebuffer.
- GLES 2.0, 4.4.3, "Attaching Renderbuffer Images to a Framebuffer"
*/
let currently_bound_framebuffer =
self.upcast::<WebGLObject>().context().bound_framebuffer();
if let Some(fb) = currently_bound_framebuffer {
fb.detach_renderbuffer(self);
}
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::DeleteRenderbuffer(self.id));
}
}
pub fn is_deleted(&self) -> bool {
self.is_deleted.get()
}
pub fn ever_bound(&self) -> bool {
self.ever_bound.get()
}
pub fn storage(&self, internal_format: u32, width: i32, height: i32) -> WebGLResult<()> {
// Validate the internal_format, and save it for completeness
// validation.
let actual_format = match internal_format {
constants::RGBA4 |
constants::DEPTH_COMPONENT16 |
constants::STENCIL_INDEX8 => internal_format,
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.8
constants::DEPTH_STENCIL => WebGl2Constants::DEPTH24_STENCIL8,
constants::RGB5_A1 => |
constants::RGB565 => {
// RGB565 is not supported on desktop GL.
if is_gles() {
constants::RGB565
} else {
WebGl2Constants::RGB8
}
}
_ => return Err(WebGLError::InvalidEnum),
};
self.internal_format.set(Some(internal_format));
self.is_initialized.set(false);
// FIXME: Invalidate completeness after the call
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::RenderbufferStorage(
constants::RENDERBUFFER,
actual_format,
width,
height,
));
self.size.set(Some((width, height)));
Ok(())
}
}
impl Drop for WebGLRenderbuffer {
fn drop(&mut self) {
self.delete();
}
}
| {
// 16-bit RGBA formats are not supported on desktop GL.
if is_gles() {
constants::RGB5_A1
} else {
WebGl2Constants::RGBA8
}
} | conditional_block |
webglrenderbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::webgl::{WebGLCommand, WebGLError, WebGLRenderbufferId, WebGLResult, is_gles, webgl_channel};
use dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as WebGl2Constants;
use dom::bindings::codegen::Bindings::WebGLRenderbufferBinding;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::webglobject::WebGLObject;
use dom::webglrenderingcontext::WebGLRenderingContext;
use dom_struct::dom_struct;
use std::cell::Cell;
#[dom_struct]
pub struct WebGLRenderbuffer {
webgl_object: WebGLObject,
id: WebGLRenderbufferId,
ever_bound: Cell<bool>,
is_deleted: Cell<bool>,
size: Cell<Option<(i32, i32)>>,
internal_format: Cell<Option<u32>>,
is_initialized: Cell<bool>,
}
impl WebGLRenderbuffer {
fn new_inherited(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> Self {
Self {
webgl_object: WebGLObject::new_inherited(context),
id: id,
ever_bound: Cell::new(false),
is_deleted: Cell::new(false),
internal_format: Cell::new(None),
size: Cell::new(None),
is_initialized: Cell::new(false),
}
}
pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> {
let (sender, receiver) = webgl_channel().unwrap();
context.send_command(WebGLCommand::CreateRenderbuffer(sender));
receiver
.recv()
.unwrap()
.map(|id| WebGLRenderbuffer::new(context, id))
}
pub fn new(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> DomRoot<Self> {
reflect_dom_object(
Box::new(WebGLRenderbuffer::new_inherited(context, id)),
&*context.global(),
WebGLRenderbufferBinding::Wrap,
)
}
}
impl WebGLRenderbuffer {
pub fn id(&self) -> WebGLRenderbufferId {
self.id
}
pub fn size(&self) -> Option<(i32, i32)> {
self.size.get()
}
pub fn internal_format(&self) -> u32 {
self.internal_format.get().unwrap_or(constants::RGBA4)
}
pub fn mark_initialized(&self) {
self.is_initialized.set(true);
}
pub fn is_initialized(&self) -> bool {
self.is_initialized.get()
}
pub fn bind(&self, target: u32) {
self.ever_bound.set(true);
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::BindRenderbuffer(target, Some(self.id)));
}
pub fn delete(&self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
/*
If a renderbuffer object is deleted while its image is attached to the currently
bound framebuffer, then it is as if FramebufferRenderbuffer had been called, with
a renderbuffer of 0, for each attachment point to which this image was attached
in the currently bound framebuffer.
- GLES 2.0, 4.4.3, "Attaching Renderbuffer Images to a Framebuffer"
*/
let currently_bound_framebuffer =
self.upcast::<WebGLObject>().context().bound_framebuffer();
if let Some(fb) = currently_bound_framebuffer {
fb.detach_renderbuffer(self);
}
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::DeleteRenderbuffer(self.id));
}
}
pub fn is_deleted(&self) -> bool |
pub fn ever_bound(&self) -> bool {
self.ever_bound.get()
}
pub fn storage(&self, internal_format: u32, width: i32, height: i32) -> WebGLResult<()> {
// Validate the internal_format, and save it for completeness
// validation.
let actual_format = match internal_format {
constants::RGBA4 |
constants::DEPTH_COMPONENT16 |
constants::STENCIL_INDEX8 => internal_format,
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.8
constants::DEPTH_STENCIL => WebGl2Constants::DEPTH24_STENCIL8,
constants::RGB5_A1 => {
// 16-bit RGBA formats are not supported on desktop GL.
if is_gles() {
constants::RGB5_A1
} else {
WebGl2Constants::RGBA8
}
}
constants::RGB565 => {
// RGB565 is not supported on desktop GL.
if is_gles() {
constants::RGB565
} else {
WebGl2Constants::RGB8
}
}
_ => return Err(WebGLError::InvalidEnum),
};
self.internal_format.set(Some(internal_format));
self.is_initialized.set(false);
// FIXME: Invalidate completeness after the call
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::RenderbufferStorage(
constants::RENDERBUFFER,
actual_format,
width,
height,
));
self.size.set(Some((width, height)));
Ok(())
}
}
impl Drop for WebGLRenderbuffer {
fn drop(&mut self) {
self.delete();
}
}
| {
self.is_deleted.get()
} | identifier_body |
webglrenderbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::webgl::{WebGLCommand, WebGLError, WebGLRenderbufferId, WebGLResult, is_gles, webgl_channel};
use dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as WebGl2Constants;
use dom::bindings::codegen::Bindings::WebGLRenderbufferBinding;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::webglobject::WebGLObject;
use dom::webglrenderingcontext::WebGLRenderingContext;
use dom_struct::dom_struct;
use std::cell::Cell;
#[dom_struct]
pub struct WebGLRenderbuffer {
webgl_object: WebGLObject,
id: WebGLRenderbufferId,
ever_bound: Cell<bool>,
is_deleted: Cell<bool>,
size: Cell<Option<(i32, i32)>>,
internal_format: Cell<Option<u32>>,
is_initialized: Cell<bool>,
}
impl WebGLRenderbuffer {
fn new_inherited(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> Self {
Self {
webgl_object: WebGLObject::new_inherited(context),
id: id,
ever_bound: Cell::new(false),
is_deleted: Cell::new(false),
internal_format: Cell::new(None),
size: Cell::new(None),
is_initialized: Cell::new(false),
}
}
pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> {
let (sender, receiver) = webgl_channel().unwrap();
context.send_command(WebGLCommand::CreateRenderbuffer(sender));
receiver
.recv()
.unwrap()
.map(|id| WebGLRenderbuffer::new(context, id))
}
pub fn new(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> DomRoot<Self> {
reflect_dom_object(
Box::new(WebGLRenderbuffer::new_inherited(context, id)),
&*context.global(),
WebGLRenderbufferBinding::Wrap,
)
}
}
impl WebGLRenderbuffer {
pub fn id(&self) -> WebGLRenderbufferId {
self.id
}
pub fn size(&self) -> Option<(i32, i32)> {
self.size.get()
}
pub fn internal_format(&self) -> u32 {
self.internal_format.get().unwrap_or(constants::RGBA4)
}
pub fn mark_initialized(&self) {
self.is_initialized.set(true);
}
pub fn is_initialized(&self) -> bool {
self.is_initialized.get()
}
pub fn bind(&self, target: u32) {
self.ever_bound.set(true);
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::BindRenderbuffer(target, Some(self.id)));
}
pub fn delete(&self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
/*
If a renderbuffer object is deleted while its image is attached to the currently
bound framebuffer, then it is as if FramebufferRenderbuffer had been called, with
a renderbuffer of 0, for each attachment point to which this image was attached
in the currently bound framebuffer.
- GLES 2.0, 4.4.3, "Attaching Renderbuffer Images to a Framebuffer"
*/
let currently_bound_framebuffer =
self.upcast::<WebGLObject>().context().bound_framebuffer();
if let Some(fb) = currently_bound_framebuffer {
fb.detach_renderbuffer(self);
}
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::DeleteRenderbuffer(self.id));
}
}
pub fn is_deleted(&self) -> bool {
self.is_deleted.get()
}
pub fn ever_bound(&self) -> bool {
self.ever_bound.get()
}
pub fn storage(&self, internal_format: u32, width: i32, height: i32) -> WebGLResult<()> {
// Validate the internal_format, and save it for completeness
// validation.
let actual_format = match internal_format {
constants::RGBA4 |
constants::DEPTH_COMPONENT16 |
constants::STENCIL_INDEX8 => internal_format,
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.8
constants::DEPTH_STENCIL => WebGl2Constants::DEPTH24_STENCIL8,
constants::RGB5_A1 => {
// 16-bit RGBA formats are not supported on desktop GL.
if is_gles() {
constants::RGB5_A1
} else {
WebGl2Constants::RGBA8
}
}
constants::RGB565 => {
// RGB565 is not supported on desktop GL.
if is_gles() {
constants::RGB565
} else {
WebGl2Constants::RGB8
}
}
_ => return Err(WebGLError::InvalidEnum),
};
self.internal_format.set(Some(internal_format));
self.is_initialized.set(false);
// FIXME: Invalidate completeness after the call
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::RenderbufferStorage(
constants::RENDERBUFFER,
actual_format,
width,
height,
));
self.size.set(Some((width, height)));
Ok(())
}
}
impl Drop for WebGLRenderbuffer {
fn drop(&mut self) {
self.delete();
}
} | random_line_split |
|
webglrenderbuffer.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::webgl::{WebGLCommand, WebGLError, WebGLRenderbufferId, WebGLResult, is_gles, webgl_channel};
use dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as WebGl2Constants;
use dom::bindings::codegen::Bindings::WebGLRenderbufferBinding;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::webglobject::WebGLObject;
use dom::webglrenderingcontext::WebGLRenderingContext;
use dom_struct::dom_struct;
use std::cell::Cell;
#[dom_struct]
pub struct WebGLRenderbuffer {
webgl_object: WebGLObject,
id: WebGLRenderbufferId,
ever_bound: Cell<bool>,
is_deleted: Cell<bool>,
size: Cell<Option<(i32, i32)>>,
internal_format: Cell<Option<u32>>,
is_initialized: Cell<bool>,
}
impl WebGLRenderbuffer {
fn new_inherited(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> Self {
Self {
webgl_object: WebGLObject::new_inherited(context),
id: id,
ever_bound: Cell::new(false),
is_deleted: Cell::new(false),
internal_format: Cell::new(None),
size: Cell::new(None),
is_initialized: Cell::new(false),
}
}
pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> {
let (sender, receiver) = webgl_channel().unwrap();
context.send_command(WebGLCommand::CreateRenderbuffer(sender));
receiver
.recv()
.unwrap()
.map(|id| WebGLRenderbuffer::new(context, id))
}
pub fn new(context: &WebGLRenderingContext, id: WebGLRenderbufferId) -> DomRoot<Self> {
reflect_dom_object(
Box::new(WebGLRenderbuffer::new_inherited(context, id)),
&*context.global(),
WebGLRenderbufferBinding::Wrap,
)
}
}
impl WebGLRenderbuffer {
pub fn id(&self) -> WebGLRenderbufferId {
self.id
}
pub fn size(&self) -> Option<(i32, i32)> {
self.size.get()
}
pub fn | (&self) -> u32 {
self.internal_format.get().unwrap_or(constants::RGBA4)
}
pub fn mark_initialized(&self) {
self.is_initialized.set(true);
}
pub fn is_initialized(&self) -> bool {
self.is_initialized.get()
}
pub fn bind(&self, target: u32) {
self.ever_bound.set(true);
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::BindRenderbuffer(target, Some(self.id)));
}
pub fn delete(&self) {
if!self.is_deleted.get() {
self.is_deleted.set(true);
/*
If a renderbuffer object is deleted while its image is attached to the currently
bound framebuffer, then it is as if FramebufferRenderbuffer had been called, with
a renderbuffer of 0, for each attachment point to which this image was attached
in the currently bound framebuffer.
- GLES 2.0, 4.4.3, "Attaching Renderbuffer Images to a Framebuffer"
*/
let currently_bound_framebuffer =
self.upcast::<WebGLObject>().context().bound_framebuffer();
if let Some(fb) = currently_bound_framebuffer {
fb.detach_renderbuffer(self);
}
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::DeleteRenderbuffer(self.id));
}
}
pub fn is_deleted(&self) -> bool {
self.is_deleted.get()
}
pub fn ever_bound(&self) -> bool {
self.ever_bound.get()
}
pub fn storage(&self, internal_format: u32, width: i32, height: i32) -> WebGLResult<()> {
// Validate the internal_format, and save it for completeness
// validation.
let actual_format = match internal_format {
constants::RGBA4 |
constants::DEPTH_COMPONENT16 |
constants::STENCIL_INDEX8 => internal_format,
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#6.8
constants::DEPTH_STENCIL => WebGl2Constants::DEPTH24_STENCIL8,
constants::RGB5_A1 => {
// 16-bit RGBA formats are not supported on desktop GL.
if is_gles() {
constants::RGB5_A1
} else {
WebGl2Constants::RGBA8
}
}
constants::RGB565 => {
// RGB565 is not supported on desktop GL.
if is_gles() {
constants::RGB565
} else {
WebGl2Constants::RGB8
}
}
_ => return Err(WebGLError::InvalidEnum),
};
self.internal_format.set(Some(internal_format));
self.is_initialized.set(false);
// FIXME: Invalidate completeness after the call
self.upcast::<WebGLObject>()
.context()
.send_command(WebGLCommand::RenderbufferStorage(
constants::RENDERBUFFER,
actual_format,
width,
height,
));
self.size.set(Some((width, height)));
Ok(())
}
}
impl Drop for WebGLRenderbuffer {
fn drop(&mut self) {
self.delete();
}
}
| internal_format | identifier_name |
build.rs | #![allow(unused)]
use std::env;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
fn wasi_sdk() -> PathBuf {
Path::new(&env::var("WASI_SDK").unwrap_or("/opt/wasi-sdk".to_owned())).to_path_buf()
}
fn wasi_sysroot() -> PathBuf {
match env::var("WASI_SYSROOT") {
Ok(wasi_sysroot) => Path::new(&wasi_sysroot).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("share");
path.push("wasi-sysroot");
path
}
}
}
fn wasm_clang_root() -> PathBuf {
match env::var("CLANG_ROOT") {
Ok(clang) => Path::new(&clang).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("lib");
path.push("clang");
path.push("8.0.1");
path
}
}
}
// `src/wasi_host.rs` is automatically generated using clang and
// wasi-libc headers. This requires these to be present, and installed
// at specific paths, which is not something we can rely on outside
// of our environment.
// So, we follow what most other tools using `bindgen` do, and provide
// a pre-generated version of the file, along with a way to update it.
// This is what the `update-bindings` feature do. It requires the WASI SDK
// to be either installed in `/opt/wasi-sdk`, or at a location defined by
// a `WASI_SDK` environment variable, as well as `clang` headers either
// being part of `WASI_SDK`, or found in a path defined by a
// `CLANG_ROOT` environment variable.
#[cfg(not(feature = "update-bindings"))]
fn | () {}
#[cfg(feature = "update-bindings")]
fn main() {
let wasi_sysroot = wasi_sysroot();
let wasm_clang_root = wasm_clang_root();
assert!(
wasi_sysroot.exists(),
"wasi-sysroot not present at {:?}",
wasi_sysroot
);
assert!(
wasm_clang_root.exists(),
"clang-root not present at {:?}",
wasm_clang_root
);
let wasi_sysroot_core_h = wasi_sysroot.join("include/wasi/core.h");
assert!(
wasi_sysroot_core_h.exists(),
"wasi-sysroot core.h not present at {:?}",
wasi_sysroot_core_h
);
println!("cargo:rerun-if-changed={}", wasi_sysroot_core_h.display());
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let core_h_path = out_path.join("core.h");
let core_h = File::create(&core_h_path).unwrap();
// `bindgen` doesn't understand typed constant macros like `UINT8_C(123)`, so this fun regex
// strips them off to yield a copy of `wasi/core.h` with bare constants.
let sed_result = Command::new("sed")
.arg("-E")
.arg(r#"s/U?INT[0-9]+_C\(((0x)?[0-9]+)\)/\1/g"#)
.arg(wasi_sysroot_core_h)
.stdout(Stdio::from(core_h))
.status()
.expect("can execute sed");
if!sed_result.success() {
// something failed, but how?
match sed_result.code() {
Some(code) => panic!("sed failed with code {}", code),
None => panic!("sed exited abnormally"),
}
}
let host_builder = bindgen::Builder::default()
.clang_arg("-nostdinc")
.clang_arg("-D__wasi__")
.clang_arg(format!("-isystem={}/include/", wasi_sysroot.display()))
.clang_arg(format!("-I{}/include/", wasm_clang_root.display()))
.header(core_h_path.to_str().unwrap())
.whitelist_type("__wasi_.*")
.whitelist_var("__WASI_.*");
let src_path = Path::new("src");
host_builder
.generate()
.expect("can generate host bindings")
.write_to_file(src_path.join("wasi_host.rs"))
.expect("can write host bindings");
}
| main | identifier_name |
build.rs | #![allow(unused)]
use std::env;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
fn wasi_sdk() -> PathBuf {
Path::new(&env::var("WASI_SDK").unwrap_or("/opt/wasi-sdk".to_owned())).to_path_buf()
}
fn wasi_sysroot() -> PathBuf {
match env::var("WASI_SYSROOT") {
Ok(wasi_sysroot) => Path::new(&wasi_sysroot).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("share");
path.push("wasi-sysroot");
path
}
}
}
fn wasm_clang_root() -> PathBuf {
match env::var("CLANG_ROOT") {
Ok(clang) => Path::new(&clang).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("lib");
path.push("clang");
path.push("8.0.1");
path
}
}
}
// `src/wasi_host.rs` is automatically generated using clang and
// wasi-libc headers. This requires these to be present, and installed
// at specific paths, which is not something we can rely on outside
// of our environment.
// So, we follow what most other tools using `bindgen` do, and provide
// a pre-generated version of the file, along with a way to update it.
// This is what the `update-bindings` feature do. It requires the WASI SDK
// to be either installed in `/opt/wasi-sdk`, or at a location defined by
// a `WASI_SDK` environment variable, as well as `clang` headers either
// being part of `WASI_SDK`, or found in a path defined by a
// `CLANG_ROOT` environment variable.
#[cfg(not(feature = "update-bindings"))]
fn main() {}
#[cfg(feature = "update-bindings")]
fn main() {
let wasi_sysroot = wasi_sysroot();
let wasm_clang_root = wasm_clang_root();
assert!(
wasi_sysroot.exists(),
"wasi-sysroot not present at {:?}",
wasi_sysroot
);
assert!(
wasm_clang_root.exists(),
"clang-root not present at {:?}",
wasm_clang_root
);
let wasi_sysroot_core_h = wasi_sysroot.join("include/wasi/core.h");
assert!(
wasi_sysroot_core_h.exists(),
"wasi-sysroot core.h not present at {:?}",
wasi_sysroot_core_h
);
println!("cargo:rerun-if-changed={}", wasi_sysroot_core_h.display());
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let core_h_path = out_path.join("core.h");
let core_h = File::create(&core_h_path).unwrap();
// `bindgen` doesn't understand typed constant macros like `UINT8_C(123)`, so this fun regex
// strips them off to yield a copy of `wasi/core.h` with bare constants.
let sed_result = Command::new("sed")
.arg("-E")
.arg(r#"s/U?INT[0-9]+_C\(((0x)?[0-9]+)\)/\1/g"#)
.arg(wasi_sysroot_core_h)
.stdout(Stdio::from(core_h))
.status()
.expect("can execute sed");
if!sed_result.success() {
// something failed, but how?
match sed_result.code() {
Some(code) => panic!("sed failed with code {}", code),
None => panic!("sed exited abnormally"),
}
} |
let host_builder = bindgen::Builder::default()
.clang_arg("-nostdinc")
.clang_arg("-D__wasi__")
.clang_arg(format!("-isystem={}/include/", wasi_sysroot.display()))
.clang_arg(format!("-I{}/include/", wasm_clang_root.display()))
.header(core_h_path.to_str().unwrap())
.whitelist_type("__wasi_.*")
.whitelist_var("__WASI_.*");
let src_path = Path::new("src");
host_builder
.generate()
.expect("can generate host bindings")
.write_to_file(src_path.join("wasi_host.rs"))
.expect("can write host bindings");
} | random_line_split |
|
build.rs | #![allow(unused)]
use std::env;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
fn wasi_sdk() -> PathBuf {
Path::new(&env::var("WASI_SDK").unwrap_or("/opt/wasi-sdk".to_owned())).to_path_buf()
}
fn wasi_sysroot() -> PathBuf |
fn wasm_clang_root() -> PathBuf {
match env::var("CLANG_ROOT") {
Ok(clang) => Path::new(&clang).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("lib");
path.push("clang");
path.push("8.0.1");
path
}
}
}
// `src/wasi_host.rs` is automatically generated using clang and
// wasi-libc headers. This requires these to be present, and installed
// at specific paths, which is not something we can rely on outside
// of our environment.
// So, we follow what most other tools using `bindgen` do, and provide
// a pre-generated version of the file, along with a way to update it.
// This is what the `update-bindings` feature do. It requires the WASI SDK
// to be either installed in `/opt/wasi-sdk`, or at a location defined by
// a `WASI_SDK` environment variable, as well as `clang` headers either
// being part of `WASI_SDK`, or found in a path defined by a
// `CLANG_ROOT` environment variable.
#[cfg(not(feature = "update-bindings"))]
fn main() {}
#[cfg(feature = "update-bindings")]
fn main() {
let wasi_sysroot = wasi_sysroot();
let wasm_clang_root = wasm_clang_root();
assert!(
wasi_sysroot.exists(),
"wasi-sysroot not present at {:?}",
wasi_sysroot
);
assert!(
wasm_clang_root.exists(),
"clang-root not present at {:?}",
wasm_clang_root
);
let wasi_sysroot_core_h = wasi_sysroot.join("include/wasi/core.h");
assert!(
wasi_sysroot_core_h.exists(),
"wasi-sysroot core.h not present at {:?}",
wasi_sysroot_core_h
);
println!("cargo:rerun-if-changed={}", wasi_sysroot_core_h.display());
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let core_h_path = out_path.join("core.h");
let core_h = File::create(&core_h_path).unwrap();
// `bindgen` doesn't understand typed constant macros like `UINT8_C(123)`, so this fun regex
// strips them off to yield a copy of `wasi/core.h` with bare constants.
let sed_result = Command::new("sed")
.arg("-E")
.arg(r#"s/U?INT[0-9]+_C\(((0x)?[0-9]+)\)/\1/g"#)
.arg(wasi_sysroot_core_h)
.stdout(Stdio::from(core_h))
.status()
.expect("can execute sed");
if!sed_result.success() {
// something failed, but how?
match sed_result.code() {
Some(code) => panic!("sed failed with code {}", code),
None => panic!("sed exited abnormally"),
}
}
let host_builder = bindgen::Builder::default()
.clang_arg("-nostdinc")
.clang_arg("-D__wasi__")
.clang_arg(format!("-isystem={}/include/", wasi_sysroot.display()))
.clang_arg(format!("-I{}/include/", wasm_clang_root.display()))
.header(core_h_path.to_str().unwrap())
.whitelist_type("__wasi_.*")
.whitelist_var("__WASI_.*");
let src_path = Path::new("src");
host_builder
.generate()
.expect("can generate host bindings")
.write_to_file(src_path.join("wasi_host.rs"))
.expect("can write host bindings");
}
| {
match env::var("WASI_SYSROOT") {
Ok(wasi_sysroot) => Path::new(&wasi_sysroot).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("share");
path.push("wasi-sysroot");
path
}
}
} | identifier_body |
performancetiming.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::PerformanceTimingBinding;
use crate::dom::bindings::codegen::Bindings::PerformanceTimingBinding::PerformanceTimingMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::document::Document;
use crate::dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct PerformanceTiming {
reflector_: Reflector,
navigation_start: u64,
navigation_start_precise: u64,
document: Dom<Document>,
}
impl PerformanceTiming {
fn new_inherited(
nav_start: u64,
nav_start_precise: u64,
document: &Document,
) -> PerformanceTiming {
PerformanceTiming {
reflector_: Reflector::new(),
navigation_start: nav_start,
navigation_start_precise: nav_start_precise,
document: Dom::from_ref(document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
navigation_start: u64,
navigation_start_precise: u64,
) -> DomRoot<PerformanceTiming> {
let timing = PerformanceTiming::new_inherited(
navigation_start,
navigation_start_precise,
&window.Document(),
);
reflect_dom_object(Box::new(timing), window, PerformanceTimingBinding::Wrap)
}
}
impl PerformanceTimingMethods for PerformanceTiming {
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-navigationStart
fn NavigationStart(&self) -> u64 {
self.navigation_start
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domLoading
fn DomLoading(&self) -> u64 {
self.document.get_dom_loading()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domInteractive
fn DomInteractive(&self) -> u64 {
self.document.get_dom_interactive()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domContentLoadedEventStart
fn DomContentLoadedEventStart(&self) -> u64 {
self.document.get_dom_content_loaded_event_start()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domContentLoadedEventEnd
fn DomContentLoadedEventEnd(&self) -> u64 {
self.document.get_dom_content_loaded_event_end()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domComplete
fn DomComplete(&self) -> u64 {
self.document.get_dom_complete()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-loadEventStart
fn LoadEventStart(&self) -> u64 {
self.document.get_load_event_start()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-loadEventEnd
fn | (&self) -> u64 {
self.document.get_load_event_end()
}
// check-tidy: no specs after this line
// Servo-only timing for when top-level content (not iframes) is complete
fn TopLevelDomComplete(&self) -> u64 {
self.document.get_top_level_dom_complete()
}
}
impl PerformanceTiming {
pub fn navigation_start_precise(&self) -> u64 {
self.navigation_start_precise
}
}
| LoadEventEnd | identifier_name |
performancetiming.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::PerformanceTimingBinding;
use crate::dom::bindings::codegen::Bindings::PerformanceTimingBinding::PerformanceTimingMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::document::Document;
use crate::dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct PerformanceTiming {
reflector_: Reflector,
navigation_start: u64,
navigation_start_precise: u64,
document: Dom<Document>,
}
impl PerformanceTiming {
fn new_inherited(
nav_start: u64,
nav_start_precise: u64,
document: &Document,
) -> PerformanceTiming {
PerformanceTiming {
reflector_: Reflector::new(),
navigation_start: nav_start,
navigation_start_precise: nav_start_precise,
document: Dom::from_ref(document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
navigation_start: u64,
navigation_start_precise: u64,
) -> DomRoot<PerformanceTiming> {
let timing = PerformanceTiming::new_inherited(
navigation_start,
navigation_start_precise,
&window.Document(),
);
reflect_dom_object(Box::new(timing), window, PerformanceTimingBinding::Wrap)
}
}
impl PerformanceTimingMethods for PerformanceTiming {
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-navigationStart
fn NavigationStart(&self) -> u64 {
self.navigation_start
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domLoading
fn DomLoading(&self) -> u64 {
self.document.get_dom_loading()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domInteractive
fn DomInteractive(&self) -> u64 {
self.document.get_dom_interactive()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domContentLoadedEventStart
fn DomContentLoadedEventStart(&self) -> u64 {
self.document.get_dom_content_loaded_event_start()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domContentLoadedEventEnd
fn DomContentLoadedEventEnd(&self) -> u64 {
self.document.get_dom_content_loaded_event_end()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domComplete
fn DomComplete(&self) -> u64 {
self.document.get_dom_complete()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-loadEventStart
fn LoadEventStart(&self) -> u64 {
self.document.get_load_event_start() | // https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-loadEventEnd
fn LoadEventEnd(&self) -> u64 {
self.document.get_load_event_end()
}
// check-tidy: no specs after this line
// Servo-only timing for when top-level content (not iframes) is complete
fn TopLevelDomComplete(&self) -> u64 {
self.document.get_top_level_dom_complete()
}
}
impl PerformanceTiming {
pub fn navigation_start_precise(&self) -> u64 {
self.navigation_start_precise
}
} | }
| random_line_split |
performancetiming.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::PerformanceTimingBinding;
use crate::dom::bindings::codegen::Bindings::PerformanceTimingBinding::PerformanceTimingMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::document::Document;
use crate::dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct PerformanceTiming {
reflector_: Reflector,
navigation_start: u64,
navigation_start_precise: u64,
document: Dom<Document>,
}
impl PerformanceTiming {
fn new_inherited(
nav_start: u64,
nav_start_precise: u64,
document: &Document,
) -> PerformanceTiming {
PerformanceTiming {
reflector_: Reflector::new(),
navigation_start: nav_start,
navigation_start_precise: nav_start_precise,
document: Dom::from_ref(document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
navigation_start: u64,
navigation_start_precise: u64,
) -> DomRoot<PerformanceTiming> {
let timing = PerformanceTiming::new_inherited(
navigation_start,
navigation_start_precise,
&window.Document(),
);
reflect_dom_object(Box::new(timing), window, PerformanceTimingBinding::Wrap)
}
}
impl PerformanceTimingMethods for PerformanceTiming {
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-navigationStart
fn NavigationStart(&self) -> u64 {
self.navigation_start
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domLoading
fn DomLoading(&self) -> u64 {
self.document.get_dom_loading()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domInteractive
fn DomInteractive(&self) -> u64 |
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domContentLoadedEventStart
fn DomContentLoadedEventStart(&self) -> u64 {
self.document.get_dom_content_loaded_event_start()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domContentLoadedEventEnd
fn DomContentLoadedEventEnd(&self) -> u64 {
self.document.get_dom_content_loaded_event_end()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-domComplete
fn DomComplete(&self) -> u64 {
self.document.get_dom_complete()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-loadEventStart
fn LoadEventStart(&self) -> u64 {
self.document.get_load_event_start()
}
// https://w3c.github.io/navigation-timing/#widl-PerformanceTiming-loadEventEnd
fn LoadEventEnd(&self) -> u64 {
self.document.get_load_event_end()
}
// check-tidy: no specs after this line
// Servo-only timing for when top-level content (not iframes) is complete
fn TopLevelDomComplete(&self) -> u64 {
self.document.get_top_level_dom_complete()
}
}
impl PerformanceTiming {
pub fn navigation_start_precise(&self) -> u64 {
self.navigation_start_precise
}
}
| {
self.document.get_dom_interactive()
} | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread;
fn | () {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::env::var_os("RUST_BENCH").is_some() {
200000
} else {
std::env::args()
.nth(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| print_complements | identifier_name |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => |
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::env::var_os("RUST_BENCH").is_some() {
200000
} else {
std::env::args()
.nth(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| {" zero"} | conditional_block |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() | {
let nn = if std::env::var_os("RUST_BENCH").is_some() {
200000
} else {
std::env::args()
.nth(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
} | identifier_body |
|
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => { | if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::env::var_os("RUST_BENCH").is_some() {
200000
} else {
std::env::args()
.nth(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
} | color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1; | random_line_split |
imprint_bool.rs | use core::ops::Deref;
use super::{Grid as GridTrait,SizeAxis,Pos,RectangularBound};
use ::data::Cell;
///Imprints `b` on `a`
#[derive(Copy,Clone,Eq,PartialEq)]
pub struct Grid<GA,GB>{
pub a: GA,
pub b: GB,
}
impl<DA,DB,GA,GB> GridTrait for Grid<DA,DB>
where DA: Deref<Target = GA>,
DB: Deref<Target = GB>,
GA: GridTrait,
GB: GridTrait,
<GA as GridTrait>::Cell: Cell + Copy,
<GB as GridTrait>::Cell: Cell + Copy,
{
type Cell = bool;
#[inline]fn is_out_of_bounds(&self,pos: Pos) -> bool{
self.a.is_out_of_bounds(pos)
}
unsafe fn pos(&self,pos: Pos) -> Self::Cell{
if self.a.pos(pos).is_occupied(){
true
}else{
if self.b.is_out_of_bounds(pos){
false
}else{
self.b.pos(pos).is_occupied()
}
}
}
}
impl<DA,DB,GA> RectangularBound for Grid<DA,DB>
where DA: Deref<Target = GA>,
GA: RectangularBound,
{
#[inline]fn bound_start(&self) -> Pos{self.a.bound_start()}
#[inline]fn width(&self) -> SizeAxis{self.a.width()}
#[inline]fn | (&self) -> SizeAxis{self.a.height()}
}
| height | identifier_name |
imprint_bool.rs | use core::ops::Deref;
use super::{Grid as GridTrait,SizeAxis,Pos,RectangularBound};
use ::data::Cell;
///Imprints `b` on `a`
#[derive(Copy,Clone,Eq,PartialEq)]
pub struct Grid<GA,GB>{ | }
impl<DA,DB,GA,GB> GridTrait for Grid<DA,DB>
where DA: Deref<Target = GA>,
DB: Deref<Target = GB>,
GA: GridTrait,
GB: GridTrait,
<GA as GridTrait>::Cell: Cell + Copy,
<GB as GridTrait>::Cell: Cell + Copy,
{
type Cell = bool;
#[inline]fn is_out_of_bounds(&self,pos: Pos) -> bool{
self.a.is_out_of_bounds(pos)
}
unsafe fn pos(&self,pos: Pos) -> Self::Cell{
if self.a.pos(pos).is_occupied(){
true
}else{
if self.b.is_out_of_bounds(pos){
false
}else{
self.b.pos(pos).is_occupied()
}
}
}
}
impl<DA,DB,GA> RectangularBound for Grid<DA,DB>
where DA: Deref<Target = GA>,
GA: RectangularBound,
{
#[inline]fn bound_start(&self) -> Pos{self.a.bound_start()}
#[inline]fn width(&self) -> SizeAxis{self.a.width()}
#[inline]fn height(&self) -> SizeAxis{self.a.height()}
} | pub a: GA,
pub b: GB, | random_line_split |
imprint_bool.rs | use core::ops::Deref;
use super::{Grid as GridTrait,SizeAxis,Pos,RectangularBound};
use ::data::Cell;
///Imprints `b` on `a`
#[derive(Copy,Clone,Eq,PartialEq)]
pub struct Grid<GA,GB>{
pub a: GA,
pub b: GB,
}
impl<DA,DB,GA,GB> GridTrait for Grid<DA,DB>
where DA: Deref<Target = GA>,
DB: Deref<Target = GB>,
GA: GridTrait,
GB: GridTrait,
<GA as GridTrait>::Cell: Cell + Copy,
<GB as GridTrait>::Cell: Cell + Copy,
{
type Cell = bool;
#[inline]fn is_out_of_bounds(&self,pos: Pos) -> bool{
self.a.is_out_of_bounds(pos)
}
unsafe fn pos(&self,pos: Pos) -> Self::Cell{
if self.a.pos(pos).is_occupied(){
true
}else{
if self.b.is_out_of_bounds(pos){
false
}else |
}
}
}
impl<DA,DB,GA> RectangularBound for Grid<DA,DB>
where DA: Deref<Target = GA>,
GA: RectangularBound,
{
#[inline]fn bound_start(&self) -> Pos{self.a.bound_start()}
#[inline]fn width(&self) -> SizeAxis{self.a.width()}
#[inline]fn height(&self) -> SizeAxis{self.a.height()}
}
| {
self.b.pos(pos).is_occupied()
} | conditional_block |
rs_receiver.rs | // Copyright (c) 2014, 2015 Robert Clipsham <[email protected]>
//
// 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.
// FIXME Remove after 1.0
#![feature(slice_extras)]
extern crate pnet;
extern crate time;
use pnet::datalink::{datalink_channel};
use pnet::datalink::DataLinkChannelType::Layer2;
use pnet::util::{NetworkInterface, get_network_interfaces};
use std::env;
fn main() {
let iface_name = env::args().nth(1).unwrap();
let interface_names_match = |iface: &NetworkInterface| iface.name == iface_name;
// Find the network interface with the provided name
let interfaces = get_network_interfaces();
let interface = interfaces.into_iter()
.filter(interface_names_match)
.next()
.unwrap();
// Create a channel to receive on
let (_, mut rx) = match datalink_channel(&interface, 0, 4096, Layer2) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("rs_benchmark: unable to create channel: {}", e)
};
let mut i = 0usize;
let mut timestamps = Vec::with_capacity(201);
timestamps.push(time::precise_time_ns() / 1_000);
let mut iter = rx.iter();
loop {
match iter.next() {
Ok(_) => {
i += 1;
if i == 1_000_000 |
},
Err(e) => {
println!("rs_benchmark: unable to receive packet: {}", e);
}
}
}
// We received 1_000_000 packets in ((b - a) * 1_000_000) seconds.
for (a, b) in timestamps.iter().zip(timestamps.tail().iter()) {
println!("{}", *b - *a);
}
}
| {
timestamps.push(time::precise_time_ns() / 1_000);
if timestamps.len() == 201 {
break;
}
i = 0;
} | conditional_block |
rs_receiver.rs | // Copyright (c) 2014, 2015 Robert Clipsham <[email protected]>
//
// 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.
// FIXME Remove after 1.0
#![feature(slice_extras)]
extern crate pnet;
extern crate time;
use pnet::datalink::{datalink_channel};
use pnet::datalink::DataLinkChannelType::Layer2;
use pnet::util::{NetworkInterface, get_network_interfaces};
use std::env;
fn | () {
let iface_name = env::args().nth(1).unwrap();
let interface_names_match = |iface: &NetworkInterface| iface.name == iface_name;
// Find the network interface with the provided name
let interfaces = get_network_interfaces();
let interface = interfaces.into_iter()
.filter(interface_names_match)
.next()
.unwrap();
// Create a channel to receive on
let (_, mut rx) = match datalink_channel(&interface, 0, 4096, Layer2) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("rs_benchmark: unable to create channel: {}", e)
};
let mut i = 0usize;
let mut timestamps = Vec::with_capacity(201);
timestamps.push(time::precise_time_ns() / 1_000);
let mut iter = rx.iter();
loop {
match iter.next() {
Ok(_) => {
i += 1;
if i == 1_000_000 {
timestamps.push(time::precise_time_ns() / 1_000);
if timestamps.len() == 201 {
break;
}
i = 0;
}
},
Err(e) => {
println!("rs_benchmark: unable to receive packet: {}", e);
}
}
}
// We received 1_000_000 packets in ((b - a) * 1_000_000) seconds.
for (a, b) in timestamps.iter().zip(timestamps.tail().iter()) {
println!("{}", *b - *a);
}
}
| main | identifier_name |
rs_receiver.rs | // Copyright (c) 2014, 2015 Robert Clipsham <[email protected]>
//
// 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.
// FIXME Remove after 1.0
#![feature(slice_extras)]
extern crate pnet;
extern crate time;
use pnet::datalink::{datalink_channel};
use pnet::datalink::DataLinkChannelType::Layer2;
use pnet::util::{NetworkInterface, get_network_interfaces};
use std::env;
fn main() |
let mut iter = rx.iter();
loop {
match iter.next() {
Ok(_) => {
i += 1;
if i == 1_000_000 {
timestamps.push(time::precise_time_ns() / 1_000);
if timestamps.len() == 201 {
break;
}
i = 0;
}
},
Err(e) => {
println!("rs_benchmark: unable to receive packet: {}", e);
}
}
}
// We received 1_000_000 packets in ((b - a) * 1_000_000) seconds.
for (a, b) in timestamps.iter().zip(timestamps.tail().iter()) {
println!("{}", *b - *a);
}
}
| {
let iface_name = env::args().nth(1).unwrap();
let interface_names_match = |iface: &NetworkInterface| iface.name == iface_name;
// Find the network interface with the provided name
let interfaces = get_network_interfaces();
let interface = interfaces.into_iter()
.filter(interface_names_match)
.next()
.unwrap();
// Create a channel to receive on
let (_, mut rx) = match datalink_channel(&interface, 0, 4096, Layer2) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("rs_benchmark: unable to create channel: {}", e)
};
let mut i = 0usize;
let mut timestamps = Vec::with_capacity(201);
timestamps.push(time::precise_time_ns() / 1_000); | identifier_body |
rs_receiver.rs | // Copyright (c) 2014, 2015 Robert Clipsham <[email protected]>
//
// 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.
// FIXME Remove after 1.0
#![feature(slice_extras)]
extern crate pnet;
extern crate time;
use pnet::datalink::{datalink_channel};
use pnet::datalink::DataLinkChannelType::Layer2;
use pnet::util::{NetworkInterface, get_network_interfaces};
use std::env;
fn main() {
let iface_name = env::args().nth(1).unwrap();
let interface_names_match = |iface: &NetworkInterface| iface.name == iface_name;
// Find the network interface with the provided name
let interfaces = get_network_interfaces();
let interface = interfaces.into_iter()
.filter(interface_names_match)
.next()
.unwrap();
// Create a channel to receive on
let (_, mut rx) = match datalink_channel(&interface, 0, 4096, Layer2) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("rs_benchmark: unable to create channel: {}", e)
};
let mut i = 0usize;
let mut timestamps = Vec::with_capacity(201);
timestamps.push(time::precise_time_ns() / 1_000);
let mut iter = rx.iter();
loop {
match iter.next() {
Ok(_) => {
i += 1;
if i == 1_000_000 {
timestamps.push(time::precise_time_ns() / 1_000);
if timestamps.len() == 201 {
break;
}
i = 0;
}
},
Err(e) => {
println!("rs_benchmark: unable to receive packet: {}", e); | }
}
}
// We received 1_000_000 packets in ((b - a) * 1_000_000) seconds.
for (a, b) in timestamps.iter().zip(timestamps.tail().iter()) {
println!("{}", *b - *a);
}
} | random_line_split |
|
core-map.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.
extern mod extra;
use extra::time;
use extra::treemap::TreeMap;
use std::hashmap::{HashMap, HashSet};
use std::os;
use std::rand::{Rng, IsaacRng, SeedableRng};
use std::trie::TrieMap;
use std::uint;
use std::vec;
fn timed(label: &str, f: ||) {
let start = time::precise_time_s();
f();
let end = time::precise_time_s();
println!(" {}: {}", label, end - start);
}
fn ascending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Ascending integers:");
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn descending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Descending integers:");
timed("insert", || {
for i in range(0, n_keys).invert() {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0, n_keys).invert() {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn vector<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint, dist: &[uint]) |
fn main() {
let args = os::args();
let n_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
1000000
}
};
let mut rand = vec::with_capacity(n_keys);
{
let mut rng: IsaacRng = SeedableRng::from_seed(&[1, 1, 1, 1, 1, 1, 1]);
let mut set = HashSet::new();
while set.len()!= n_keys {
let next = rng.gen();
if set.insert(next) {
rand.push(next);
}
}
}
println!("{} keys", n_keys);
// FIXME: #9970
println!("{}", "\nTreeMap:");
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TreeMap<uint,uint> = TreeMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nHashMap:");
{
let mut map: HashMap<uint,uint> = HashMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: HashMap<uint,uint> = HashMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nTrieMap:");
{
let mut map: TrieMap<uint> = TrieMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TrieMap<uint> = TrieMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TrieMap<uint> = TrieMap::new();
vector(&mut map, n_keys, rand);
}
}
| {
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(dist[i], i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&dist[i]).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0u, n_keys) {
assert!(map.remove(&dist[i]));
}
});
} | identifier_body |
core-map.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.
extern mod extra;
use extra::time;
use extra::treemap::TreeMap;
use std::hashmap::{HashMap, HashSet};
use std::os;
use std::rand::{Rng, IsaacRng, SeedableRng};
use std::trie::TrieMap;
use std::uint;
use std::vec;
fn timed(label: &str, f: ||) {
let start = time::precise_time_s();
f();
let end = time::precise_time_s();
println!(" {}: {}", label, end - start);
}
fn ascending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Ascending integers:");
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn descending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Descending integers:");
timed("insert", || {
for i in range(0, n_keys).invert() {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0, n_keys).invert() {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn vector<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint, dist: &[uint]) {
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(dist[i], i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&dist[i]).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0u, n_keys) {
assert!(map.remove(&dist[i]));
}
});
}
fn main() {
let args = os::args();
let n_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else |
};
let mut rand = vec::with_capacity(n_keys);
{
let mut rng: IsaacRng = SeedableRng::from_seed(&[1, 1, 1, 1, 1, 1, 1]);
let mut set = HashSet::new();
while set.len()!= n_keys {
let next = rng.gen();
if set.insert(next) {
rand.push(next);
}
}
}
println!("{} keys", n_keys);
// FIXME: #9970
println!("{}", "\nTreeMap:");
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TreeMap<uint,uint> = TreeMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nHashMap:");
{
let mut map: HashMap<uint,uint> = HashMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: HashMap<uint,uint> = HashMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nTrieMap:");
{
let mut map: TrieMap<uint> = TrieMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TrieMap<uint> = TrieMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TrieMap<uint> = TrieMap::new();
vector(&mut map, n_keys, rand);
}
}
| {
1000000
} | conditional_block |
core-map.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.
extern mod extra;
use extra::time;
use extra::treemap::TreeMap;
use std::hashmap::{HashMap, HashSet};
use std::os;
use std::rand::{Rng, IsaacRng, SeedableRng};
use std::trie::TrieMap;
use std::uint;
use std::vec;
fn | (label: &str, f: ||) {
let start = time::precise_time_s();
f();
let end = time::precise_time_s();
println!(" {}: {}", label, end - start);
}
fn ascending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Ascending integers:");
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn descending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Descending integers:");
timed("insert", || {
for i in range(0, n_keys).invert() {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0, n_keys).invert() {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn vector<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint, dist: &[uint]) {
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(dist[i], i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&dist[i]).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0u, n_keys) {
assert!(map.remove(&dist[i]));
}
});
}
fn main() {
let args = os::args();
let n_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
1000000
}
};
let mut rand = vec::with_capacity(n_keys);
{
let mut rng: IsaacRng = SeedableRng::from_seed(&[1, 1, 1, 1, 1, 1, 1]);
let mut set = HashSet::new();
while set.len()!= n_keys {
let next = rng.gen();
if set.insert(next) {
rand.push(next);
}
}
}
println!("{} keys", n_keys);
// FIXME: #9970
println!("{}", "\nTreeMap:");
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TreeMap<uint,uint> = TreeMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nHashMap:");
{
let mut map: HashMap<uint,uint> = HashMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: HashMap<uint,uint> = HashMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nTrieMap:");
{
let mut map: TrieMap<uint> = TrieMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TrieMap<uint> = TrieMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TrieMap<uint> = TrieMap::new();
vector(&mut map, n_keys, rand);
}
}
| timed | identifier_name |
core-map.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.
extern mod extra;
use extra::time;
use extra::treemap::TreeMap;
use std::hashmap::{HashMap, HashSet};
use std::os;
use std::rand::{Rng, IsaacRng, SeedableRng};
use std::trie::TrieMap;
use std::uint;
use std::vec;
fn timed(label: &str, f: ||) {
let start = time::precise_time_s();
f();
let end = time::precise_time_s();
println!(" {}: {}", label, end - start);
}
fn ascending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Ascending integers:");
timed("insert", || {
for i in range(0u, n_keys) {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
});
}
fn descending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
println!(" Descending integers:");
timed("insert", || {
for i in range(0, n_keys).invert() {
map.insert(i, i + 1);
}
});
timed("search", || {
for i in range(0, n_keys).invert() {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0, n_keys) {
assert!(map.remove(&i));
}
}); | timed("insert", || {
for i in range(0u, n_keys) {
map.insert(dist[i], i + 1);
}
});
timed("search", || {
for i in range(0u, n_keys) {
assert_eq!(map.find(&dist[i]).unwrap(), &(i + 1));
}
});
timed("remove", || {
for i in range(0u, n_keys) {
assert!(map.remove(&dist[i]));
}
});
}
fn main() {
let args = os::args();
let n_keys = {
if args.len() == 2 {
from_str::<uint>(args[1]).unwrap()
} else {
1000000
}
};
let mut rand = vec::with_capacity(n_keys);
{
let mut rng: IsaacRng = SeedableRng::from_seed(&[1, 1, 1, 1, 1, 1, 1]);
let mut set = HashSet::new();
while set.len()!= n_keys {
let next = rng.gen();
if set.insert(next) {
rand.push(next);
}
}
}
println!("{} keys", n_keys);
// FIXME: #9970
println!("{}", "\nTreeMap:");
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TreeMap<uint,uint> = TreeMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TreeMap<uint,uint> = TreeMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nHashMap:");
{
let mut map: HashMap<uint,uint> = HashMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: HashMap<uint,uint> = HashMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: HashMap<uint,uint> = HashMap::new();
vector(&mut map, n_keys, rand);
}
// FIXME: #9970
println!("{}", "\nTrieMap:");
{
let mut map: TrieMap<uint> = TrieMap::new();
ascending(&mut map, n_keys);
}
{
let mut map: TrieMap<uint> = TrieMap::new();
descending(&mut map, n_keys);
}
{
println!(" Random integers:");
let mut map: TrieMap<uint> = TrieMap::new();
vector(&mut map, n_keys, rand);
}
} | }
fn vector<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint, dist: &[uint]) { | random_line_split |
fix_ssa_opcalls.rs | //! Fixes the call target for all call sites in the SSA
//! For every [`OpCall`] SSA node in every function, try to find that call
//! site's corresponding edge in [the callgraph] and replace the "target"
//! operand of the SSA node with a constant value for the address of the actual
//! call target.
//!
//! [`OpCall`]: ir::MOpcode::OpCall
//! [the callgraph]: RadecoModule::callgraph
use analysis::analyzer::{
Action, Analyzer, AnalyzerInfo, AnalyzerKind, AnalyzerResult, Change, ModuleAnalyzer,
};
use frontend::radeco_containers::*;
use middle::ir;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use std::any::Any;
use std::collections::HashMap;
const NAME: &str = "call_size_fixer";
const REQUIRES: &[AnalyzerKind] = &[];
pub const INFO: AnalyzerInfo = AnalyzerInfo {
name: NAME,
kind: AnalyzerKind::CallSiteFixer,
requires: REQUIRES,
uses_policy: false,
};
#[derive(Debug)]
pub struct CallSiteFixer;
impl CallSiteFixer {
pub fn new() -> Self {
CallSiteFixer
}
}
impl Analyzer for CallSiteFixer {
fn info(&self) -> &'static AnalyzerInfo {
&INFO
}
fn | (&self) -> &dyn Any {
self
}
}
impl ModuleAnalyzer for CallSiteFixer {
fn analyze<T: FnMut(Box<Change>) -> Action>(
&mut self,
rmod: &mut RadecoModule,
_policy: Option<T>,
) -> Option<Box<AnalyzerResult>> {
for rfun in rmod.functions.values_mut() {
go_fn(rfun, &rmod.callgraph);
}
None
}
}
fn go_fn(rfun: &mut RadecoFunction, callgraph: &CallGraph) -> () {
let _fn_addr = rfun.offset;
let call_site_addr_to_target_addr: HashMap<u64, u64> = callgraph
.callees(rfun.cgid())
.map(|(cs_a, tgt_idx)| (cs_a, callgraph[tgt_idx]))
.collect();
let ssa = rfun.ssa_mut();
for node in ssa.inorder_walk() {
if let Ok(NodeType::Op(ir::MOpcode::OpCall)) = ssa.node_data(node).map(|x| x.nt) {
fix_call_site(ssa, node, &call_site_addr_to_target_addr).unwrap_or_else(|| {
radeco_err!(
"failed to fix call site {:?} in function at {:#X}",
node,
_fn_addr
)
});
}
}
}
fn fix_call_site(
ssa: &mut SSAStorage,
call_node: <SSAStorage as SSA>::ValueRef,
fn_call_map: &HashMap<u64, u64>,
) -> Option<()> {
let call_site_addr = ssa.address(call_node)?.address;
if let Some(&call_target_addr) = fn_call_map.get(&call_site_addr) {
let old_opcall_tgt_node = ssa
.sparse_operands_of(call_node)
.iter()
.find(|x| x.0 == 0)?
.1;
let new_opcall_tgt_node = ssa.insert_const(call_target_addr, None)?;
ssa.op_unuse(call_node, old_opcall_tgt_node);
ssa.op_use(call_node, 0, new_opcall_tgt_node);
} else {
radeco_trace!(
"call site at {:#X} isn't in call graph; perhaps the call is indirect?",
call_site_addr
);
}
Some(())
}
| as_any | identifier_name |
fix_ssa_opcalls.rs | //! Fixes the call target for all call sites in the SSA
//! For every [`OpCall`] SSA node in every function, try to find that call
//! site's corresponding edge in [the callgraph] and replace the "target"
//! operand of the SSA node with a constant value for the address of the actual
//! call target.
//!
//! [`OpCall`]: ir::MOpcode::OpCall
//! [the callgraph]: RadecoModule::callgraph
use analysis::analyzer::{
Action, Analyzer, AnalyzerInfo, AnalyzerKind, AnalyzerResult, Change, ModuleAnalyzer,
};
use frontend::radeco_containers::*;
use middle::ir;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use std::any::Any;
use std::collections::HashMap;
const NAME: &str = "call_size_fixer";
const REQUIRES: &[AnalyzerKind] = &[];
pub const INFO: AnalyzerInfo = AnalyzerInfo {
name: NAME,
kind: AnalyzerKind::CallSiteFixer,
requires: REQUIRES,
uses_policy: false,
};
#[derive(Debug)]
pub struct CallSiteFixer;
impl CallSiteFixer {
pub fn new() -> Self |
}
impl Analyzer for CallSiteFixer {
fn info(&self) -> &'static AnalyzerInfo {
&INFO
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl ModuleAnalyzer for CallSiteFixer {
fn analyze<T: FnMut(Box<Change>) -> Action>(
&mut self,
rmod: &mut RadecoModule,
_policy: Option<T>,
) -> Option<Box<AnalyzerResult>> {
for rfun in rmod.functions.values_mut() {
go_fn(rfun, &rmod.callgraph);
}
None
}
}
fn go_fn(rfun: &mut RadecoFunction, callgraph: &CallGraph) -> () {
let _fn_addr = rfun.offset;
let call_site_addr_to_target_addr: HashMap<u64, u64> = callgraph
.callees(rfun.cgid())
.map(|(cs_a, tgt_idx)| (cs_a, callgraph[tgt_idx]))
.collect();
let ssa = rfun.ssa_mut();
for node in ssa.inorder_walk() {
if let Ok(NodeType::Op(ir::MOpcode::OpCall)) = ssa.node_data(node).map(|x| x.nt) {
fix_call_site(ssa, node, &call_site_addr_to_target_addr).unwrap_or_else(|| {
radeco_err!(
"failed to fix call site {:?} in function at {:#X}",
node,
_fn_addr
)
});
}
}
}
fn fix_call_site(
ssa: &mut SSAStorage,
call_node: <SSAStorage as SSA>::ValueRef,
fn_call_map: &HashMap<u64, u64>,
) -> Option<()> {
let call_site_addr = ssa.address(call_node)?.address;
if let Some(&call_target_addr) = fn_call_map.get(&call_site_addr) {
let old_opcall_tgt_node = ssa
.sparse_operands_of(call_node)
.iter()
.find(|x| x.0 == 0)?
.1;
let new_opcall_tgt_node = ssa.insert_const(call_target_addr, None)?;
ssa.op_unuse(call_node, old_opcall_tgt_node);
ssa.op_use(call_node, 0, new_opcall_tgt_node);
} else {
radeco_trace!(
"call site at {:#X} isn't in call graph; perhaps the call is indirect?",
call_site_addr
);
}
Some(())
}
| {
CallSiteFixer
} | identifier_body |
fix_ssa_opcalls.rs | //! Fixes the call target for all call sites in the SSA
//! For every [`OpCall`] SSA node in every function, try to find that call
//! site's corresponding edge in [the callgraph] and replace the "target"
//! operand of the SSA node with a constant value for the address of the actual
//! call target.
//!
//! [`OpCall`]: ir::MOpcode::OpCall
//! [the callgraph]: RadecoModule::callgraph
use analysis::analyzer::{
Action, Analyzer, AnalyzerInfo, AnalyzerKind, AnalyzerResult, Change, ModuleAnalyzer,
};
use frontend::radeco_containers::*;
use middle::ir;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use std::any::Any;
use std::collections::HashMap;
const NAME: &str = "call_size_fixer";
const REQUIRES: &[AnalyzerKind] = &[];
pub const INFO: AnalyzerInfo = AnalyzerInfo {
name: NAME,
kind: AnalyzerKind::CallSiteFixer,
requires: REQUIRES,
uses_policy: false,
};
#[derive(Debug)]
pub struct CallSiteFixer;
impl CallSiteFixer {
pub fn new() -> Self {
CallSiteFixer
}
}
impl Analyzer for CallSiteFixer {
fn info(&self) -> &'static AnalyzerInfo {
&INFO
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl ModuleAnalyzer for CallSiteFixer {
fn analyze<T: FnMut(Box<Change>) -> Action>(
&mut self,
rmod: &mut RadecoModule,
_policy: Option<T>,
) -> Option<Box<AnalyzerResult>> {
for rfun in rmod.functions.values_mut() {
go_fn(rfun, &rmod.callgraph);
}
None
}
}
fn go_fn(rfun: &mut RadecoFunction, callgraph: &CallGraph) -> () {
let _fn_addr = rfun.offset;
let call_site_addr_to_target_addr: HashMap<u64, u64> = callgraph
.callees(rfun.cgid())
.map(|(cs_a, tgt_idx)| (cs_a, callgraph[tgt_idx]))
.collect();
let ssa = rfun.ssa_mut();
for node in ssa.inorder_walk() {
if let Ok(NodeType::Op(ir::MOpcode::OpCall)) = ssa.node_data(node).map(|x| x.nt) |
}
}
fn fix_call_site(
ssa: &mut SSAStorage,
call_node: <SSAStorage as SSA>::ValueRef,
fn_call_map: &HashMap<u64, u64>,
) -> Option<()> {
let call_site_addr = ssa.address(call_node)?.address;
if let Some(&call_target_addr) = fn_call_map.get(&call_site_addr) {
let old_opcall_tgt_node = ssa
.sparse_operands_of(call_node)
.iter()
.find(|x| x.0 == 0)?
.1;
let new_opcall_tgt_node = ssa.insert_const(call_target_addr, None)?;
ssa.op_unuse(call_node, old_opcall_tgt_node);
ssa.op_use(call_node, 0, new_opcall_tgt_node);
} else {
radeco_trace!(
"call site at {:#X} isn't in call graph; perhaps the call is indirect?",
call_site_addr
);
}
Some(())
}
| {
fix_call_site(ssa, node, &call_site_addr_to_target_addr).unwrap_or_else(|| {
radeco_err!(
"failed to fix call site {:?} in function at {:#X}",
node,
_fn_addr
)
});
} | conditional_block |
fix_ssa_opcalls.rs | //! Fixes the call target for all call sites in the SSA
//! For every [`OpCall`] SSA node in every function, try to find that call
//! site's corresponding edge in [the callgraph] and replace the "target"
//! operand of the SSA node with a constant value for the address of the actual
//! call target.
//!
//! [`OpCall`]: ir::MOpcode::OpCall
//! [the callgraph]: RadecoModule::callgraph
use analysis::analyzer::{
Action, Analyzer, AnalyzerInfo, AnalyzerKind, AnalyzerResult, Change, ModuleAnalyzer,
};
use frontend::radeco_containers::*;
use middle::ir;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use std::any::Any;
use std::collections::HashMap;
const NAME: &str = "call_size_fixer";
const REQUIRES: &[AnalyzerKind] = &[];
pub const INFO: AnalyzerInfo = AnalyzerInfo {
name: NAME,
kind: AnalyzerKind::CallSiteFixer,
requires: REQUIRES,
uses_policy: false,
};
#[derive(Debug)]
pub struct CallSiteFixer;
impl CallSiteFixer {
pub fn new() -> Self {
CallSiteFixer
}
}
impl Analyzer for CallSiteFixer {
fn info(&self) -> &'static AnalyzerInfo {
&INFO
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl ModuleAnalyzer for CallSiteFixer {
fn analyze<T: FnMut(Box<Change>) -> Action>(
&mut self,
rmod: &mut RadecoModule,
_policy: Option<T>,
) -> Option<Box<AnalyzerResult>> {
for rfun in rmod.functions.values_mut() {
go_fn(rfun, &rmod.callgraph);
}
None | let call_site_addr_to_target_addr: HashMap<u64, u64> = callgraph
.callees(rfun.cgid())
.map(|(cs_a, tgt_idx)| (cs_a, callgraph[tgt_idx]))
.collect();
let ssa = rfun.ssa_mut();
for node in ssa.inorder_walk() {
if let Ok(NodeType::Op(ir::MOpcode::OpCall)) = ssa.node_data(node).map(|x| x.nt) {
fix_call_site(ssa, node, &call_site_addr_to_target_addr).unwrap_or_else(|| {
radeco_err!(
"failed to fix call site {:?} in function at {:#X}",
node,
_fn_addr
)
});
}
}
}
fn fix_call_site(
ssa: &mut SSAStorage,
call_node: <SSAStorage as SSA>::ValueRef,
fn_call_map: &HashMap<u64, u64>,
) -> Option<()> {
let call_site_addr = ssa.address(call_node)?.address;
if let Some(&call_target_addr) = fn_call_map.get(&call_site_addr) {
let old_opcall_tgt_node = ssa
.sparse_operands_of(call_node)
.iter()
.find(|x| x.0 == 0)?
.1;
let new_opcall_tgt_node = ssa.insert_const(call_target_addr, None)?;
ssa.op_unuse(call_node, old_opcall_tgt_node);
ssa.op_use(call_node, 0, new_opcall_tgt_node);
} else {
radeco_trace!(
"call site at {:#X} isn't in call graph; perhaps the call is indirect?",
call_site_addr
);
}
Some(())
} | }
}
fn go_fn(rfun: &mut RadecoFunction, callgraph: &CallGraph) -> () {
let _fn_addr = rfun.offset; | random_line_split |
vector.rs | use crate::{CodePair, DxfError, DxfResult};
/// Represents a simple vector in Cartesian space.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Vector {
/// The X component of the vector.
pub x: f64,
/// The Y component of the vector.
pub y: f64,
/// The Z component of the vector.
pub z: f64,
}
impl Vector {
/// Creates a new `Vector` with the specified values.
pub fn new(x: f64, y: f64, z: f64) -> Vector {
Vector { x, y, z }
}
/// Returns a new zero vector representing (0, 0, 0).
pub fn zero() -> Vector {
Vector::new(0.0, 0.0, 0.0)
}
/// Returns a new vector representing the X axis.
pub fn x_axis() -> Vector {
Vector::new(1.0, 0.0, 0.0)
}
/// Returns a new vector representing the Y axis.
pub fn y_axis() -> Vector {
Vector::new(0.0, 1.0, 0.0)
}
/// Returns a new vector representing the Z axis.
pub fn z_axis() -> Vector { | pub(crate) fn set(&mut self, pair: &CodePair) -> DxfResult<()> {
match pair.code {
10 => self.x = pair.assert_f64()?,
20 => self.y = pair.assert_f64()?,
30 => self.z = pair.assert_f64()?,
_ => {
return Err(DxfError::UnexpectedCodePair(
pair.clone(),
String::from("expected code [10, 20, 30] for vector"),
))
}
}
Ok(())
}
} | Vector::new(0.0, 0.0, 1.0)
} | random_line_split |
vector.rs | use crate::{CodePair, DxfError, DxfResult};
/// Represents a simple vector in Cartesian space.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Vector {
/// The X component of the vector.
pub x: f64,
/// The Y component of the vector.
pub y: f64,
/// The Z component of the vector.
pub z: f64,
}
impl Vector {
/// Creates a new `Vector` with the specified values.
pub fn new(x: f64, y: f64, z: f64) -> Vector {
Vector { x, y, z }
}
/// Returns a new zero vector representing (0, 0, 0).
pub fn zero() -> Vector {
Vector::new(0.0, 0.0, 0.0)
}
/// Returns a new vector representing the X axis.
pub fn x_axis() -> Vector {
Vector::new(1.0, 0.0, 0.0)
}
/// Returns a new vector representing the Y axis.
pub fn y_axis() -> Vector {
Vector::new(0.0, 1.0, 0.0)
}
/// Returns a new vector representing the Z axis.
pub fn z_axis() -> Vector {
Vector::new(0.0, 0.0, 1.0)
}
pub(crate) fn set(&mut self, pair: &CodePair) -> DxfResult<()> |
}
| {
match pair.code {
10 => self.x = pair.assert_f64()?,
20 => self.y = pair.assert_f64()?,
30 => self.z = pair.assert_f64()?,
_ => {
return Err(DxfError::UnexpectedCodePair(
pair.clone(),
String::from("expected code [10, 20, 30] for vector"),
))
}
}
Ok(())
} | identifier_body |
vector.rs | use crate::{CodePair, DxfError, DxfResult};
/// Represents a simple vector in Cartesian space.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct | {
/// The X component of the vector.
pub x: f64,
/// The Y component of the vector.
pub y: f64,
/// The Z component of the vector.
pub z: f64,
}
impl Vector {
/// Creates a new `Vector` with the specified values.
pub fn new(x: f64, y: f64, z: f64) -> Vector {
Vector { x, y, z }
}
/// Returns a new zero vector representing (0, 0, 0).
pub fn zero() -> Vector {
Vector::new(0.0, 0.0, 0.0)
}
/// Returns a new vector representing the X axis.
pub fn x_axis() -> Vector {
Vector::new(1.0, 0.0, 0.0)
}
/// Returns a new vector representing the Y axis.
pub fn y_axis() -> Vector {
Vector::new(0.0, 1.0, 0.0)
}
/// Returns a new vector representing the Z axis.
pub fn z_axis() -> Vector {
Vector::new(0.0, 0.0, 1.0)
}
pub(crate) fn set(&mut self, pair: &CodePair) -> DxfResult<()> {
match pair.code {
10 => self.x = pair.assert_f64()?,
20 => self.y = pair.assert_f64()?,
30 => self.z = pair.assert_f64()?,
_ => {
return Err(DxfError::UnexpectedCodePair(
pair.clone(),
String::from("expected code [10, 20, 30] for vector"),
))
}
}
Ok(())
}
}
| Vector | identifier_name |
svh-a-no-change.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `svh-a-*.rs` files are all deviations from the base file
//! svh-a-base.rs with some difference (usually in `fn foo`) that
//! should not affect the strict version hash (SVH) computation
//! (#14132).
#![crate_name = "a"]
#![feature(core)]
use std::marker::MarkerTrait;
macro_rules! three {
() => { 3 }
}
pub trait U : MarkerTrait {}
pub trait V : MarkerTrait {}
impl U for () {}
impl V for () {}
static A_CONSTANT : isize = 2;
pub fn foo<T:U>(_: isize) -> isize {
3
}
pub fn | () -> isize {
4
}
| an_unused_name | identifier_name |
svh-a-no-change.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `svh-a-*.rs` files are all deviations from the base file
//! svh-a-base.rs with some difference (usually in `fn foo`) that
//! should not affect the strict version hash (SVH) computation
//! (#14132).
#![crate_name = "a"]
#![feature(core)]
use std::marker::MarkerTrait;
macro_rules! three {
() => { 3 }
}
pub trait U : MarkerTrait {}
pub trait V : MarkerTrait {}
impl U for () {}
impl V for () {}
static A_CONSTANT : isize = 2;
pub fn foo<T:U>(_: isize) -> isize |
pub fn an_unused_name() -> isize {
4
}
| {
3
} | identifier_body |
svh-a-no-change.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `svh-a-*.rs` files are all deviations from the base file
//! svh-a-base.rs with some difference (usually in `fn foo`) that
//! should not affect the strict version hash (SVH) computation
//! (#14132).
#![crate_name = "a"]
#![feature(core)]
use std::marker::MarkerTrait; | pub trait U : MarkerTrait {}
pub trait V : MarkerTrait {}
impl U for () {}
impl V for () {}
static A_CONSTANT : isize = 2;
pub fn foo<T:U>(_: isize) -> isize {
3
}
pub fn an_unused_name() -> isize {
4
} |
macro_rules! three {
() => { 3 }
}
| random_line_split |
3_09_wave_c.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 3-9: Wave_C
use nannou::prelude::*;
fn | () {
nannou::app(model).update(update).run();
}
struct Model {
start_angle: f32,
angle_vel: f32,
}
fn model(app: &App) -> Model {
app.new_window().size(200, 200).view(view).build().unwrap();
let start_angle = 0.0;
let angle_vel = 0.4;
Model {
start_angle,
angle_vel,
}
}
fn update(_app: &App, model: &mut Model, _update: Update) {
model.start_angle += 0.015;
}
fn view(app: &App, model: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
let mut angle = model.start_angle;
let rect = app.window_rect();
let mut x = rect.left();
while x <= rect.right() {
let y = map_range(angle.sin(), -1.0, 1.0, rect.top(), rect.bottom());
draw.ellipse()
.x_y(x as f32, y)
.w_h(48.0, 48.0)
.rgba(0.0, 0.0, 0.0, 0.5)
.stroke(BLACK)
.stroke_weight(2.0);
angle += model.angle_vel;
x += 24.0;
}
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
| main | identifier_name |
3_09_wave_c.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 3-9: Wave_C
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
start_angle: f32,
angle_vel: f32,
}
fn model(app: &App) -> Model {
app.new_window().size(200, 200).view(view).build().unwrap();
let start_angle = 0.0;
let angle_vel = 0.4;
Model {
start_angle,
angle_vel,
}
}
fn update(_app: &App, model: &mut Model, _update: Update) |
fn view(app: &App, model: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
let mut angle = model.start_angle;
let rect = app.window_rect();
let mut x = rect.left();
while x <= rect.right() {
let y = map_range(angle.sin(), -1.0, 1.0, rect.top(), rect.bottom());
draw.ellipse()
.x_y(x as f32, y)
.w_h(48.0, 48.0)
.rgba(0.0, 0.0, 0.0, 0.5)
.stroke(BLACK)
.stroke_weight(2.0);
angle += model.angle_vel;
x += 24.0;
}
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
| {
model.start_angle += 0.015;
} | identifier_body |
3_09_wave_c.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 3-9: Wave_C
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
start_angle: f32,
angle_vel: f32,
}
fn model(app: &App) -> Model {
app.new_window().size(200, 200).view(view).build().unwrap();
let start_angle = 0.0;
let angle_vel = 0.4;
Model {
start_angle,
angle_vel,
}
}
fn update(_app: &App, model: &mut Model, _update: Update) {
model.start_angle += 0.015;
}
fn view(app: &App, model: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
let mut angle = model.start_angle;
let rect = app.window_rect();
let mut x = rect.left();
while x <= rect.right() {
let y = map_range(angle.sin(), -1.0, 1.0, rect.top(), rect.bottom());
draw.ellipse()
.x_y(x as f32, y)
.w_h(48.0, 48.0)
.rgba(0.0, 0.0, 0.0, 0.5)
.stroke(BLACK)
.stroke_weight(2.0);
angle += model.angle_vel;
x += 24.0;
}
// Write the result of our drawing to the window's frame. | } | draw.to_frame(app, &frame).unwrap(); | random_line_split |
numops.rs | /*
* PCG Random Number Generation for Rust
*
* Copyright 2015 John Brooks <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/// The types of numaric options that PCG needs to operate.
/// Some day this will be replaced with Num-traits when they support
/// wrapping opts for everything, and when extprim supports those traits as
/// well.
pub trait PcgOps {
fn wrap_mul(&self, rhs: Self) -> Self;
fn wrap_add(&self, rhs: Self) -> Self;
}
/// Convert a value to a usize don't care about overflow etc
pub trait AsUsize {
fn as_usize(&self) -> usize;
}
/// A trait that determines how many bits are in a type.
pub trait BitSize {
const BITS: usize;
}
/// Allows a type to become a type of a smaller value.
pub trait AsSmaller<T> {
fn shrink(self) -> T;
}
//Implementations of the traits for basic types
macro_rules! basic_ops {
( $( $t:ty, $bits:expr);*) => {
$(impl BitSize for $t {
const BITS: usize = $bits;
}
impl AsUsize for $t {
#[inline]
fn as_usize(&self) -> usize {
*self as usize
}
}
impl PcgOps for $t {
#[inline]
fn wrap_mul(&self, rhs : $t) -> $t {
self.wrapping_mul(rhs)
}
#[inline]
fn wrap_add(&self, rhs : $t) -> $t {
self.wrapping_add(rhs)
}
}
)*
}
}
basic_ops!(
u8, 8;
u16, 16; | u128, 128
);
macro_rules! smaller {
( $( $t:ty, $other:ty);*) => {
$(
impl AsSmaller<$other> for $t {
#[inline]
fn shrink(self) -> $other {
self as $other
}
}
)*
}
}
smaller!(
u128, u128;
u128, u64;
u128, u32;
u128, u16;
u128, u8;
u64, u64;
u64, u32;
u64, u16;
u64, u8;
u32, u32;
u32, u16;
u32, u8;
u16, u16;
u16, u8
); | u32, 32;
u64, 64; | random_line_split |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated! | //
// =================================================================
#![doc(
html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png"
)]
//! <p><fullname>AWS Shield Advanced</fullname> <p>This is the <i>AWS Shield Advanced API Reference</i>. This guide is for developers who need detailed information about the AWS Shield Advanced API actions, data types, and errors. For detailed information about AWS WAF and AWS Shield Advanced features and an overview of how to use the AWS WAF and AWS Shield Advanced APIs, see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/">AWS WAF and AWS Shield Developer Guide</a>.</p></p>
//!
//! If you're using the service, you're probably looking for [ShieldClient](struct.ShieldClient.html) and [Shield](trait.Shield.html).
mod custom;
mod generated;
pub use custom::*;
pub use generated::*; | //
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to generate the changes. | random_line_split |
callbacks.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod native;
extern mod glfw;
use std::libc;
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while!window.should_close() { | glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct FramebufferSizeContext;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
} | random_line_split |
|
callbacks.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern mod native;
extern mod glfw;
use std::libc;
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, main)
}
fn main() {
glfw::set_error_callback(~ErrorContext);
do glfw::start {
glfw::window_hint::resizable(true);
let window = glfw::Window::create(800, 600, "Hello, I am a window.", glfw::Windowed)
.expect("Failed to create GLFW window.");
window.set_sticky_keys(true);
// Register event callbacks
window.set_pos_callback(~WindowPosContext);
window.set_size_callback(~WindowSizeContext);
window.set_close_callback(~WindowCloseContext);
window.set_refresh_callback(~WindowRefreshContext);
window.set_focus_callback(~WindowFocusContext);
window.set_iconify_callback(~WindowIconifyContext);
window.set_framebuffer_size_callback(~FramebufferSizeContext);
window.set_key_callback(~KeyContext);
window.set_char_callback(~CharContext);
window.set_mouse_button_callback(~MouseButtonContext);
window.set_cursor_pos_callback(~CursorPosContext);
window.set_cursor_enter_callback(~CursorEnterContext);
window.set_scroll_callback(~ScrollContext);
window.make_context_current();
while!window.should_close() {
glfw::poll_events();
}
}
}
struct ErrorContext;
impl glfw::ErrorCallback for ErrorContext {
fn call(&self, _: glfw::Error, description: ~str) {
println!("GLFW Error: {:s}", description);
}
}
struct WindowPosContext;
impl glfw::WindowPosCallback for WindowPosContext {
fn call(&self, window: &glfw::Window, x: i32, y: i32) {
window.set_title(format!("Window pos: ({}, {})", x, y));
}
}
struct WindowSizeContext;
impl glfw::WindowSizeCallback for WindowSizeContext {
fn call(&self, window: &glfw::Window, width: i32, height: i32) {
window.set_title(format!("Window size: ({}, {})", width, height));
}
}
struct WindowCloseContext;
impl glfw::WindowCloseCallback for WindowCloseContext {
fn call(&self, _: &glfw::Window) {
println("Window close requested.");
}
}
struct WindowRefreshContext;
impl glfw::WindowRefreshCallback for WindowRefreshContext {
fn call(&self, _: &glfw::Window) {
println("Window refresh callback triggered.");
}
}
struct WindowFocusContext;
impl glfw::WindowFocusCallback for WindowFocusContext {
fn call(&self, _: &glfw::Window, activated: bool) {
if activated { println("Window focus gained."); }
else { println("Window focus lost."); }
}
}
struct WindowIconifyContext;
impl glfw::WindowIconifyCallback for WindowIconifyContext {
fn call(&self, _: &glfw::Window, iconified: bool) {
if iconified { println("Window was minimised"); }
else { println("Window was maximised."); }
}
}
struct | ;
impl glfw::FramebufferSizeCallback for FramebufferSizeContext {
fn call(&self, _: &glfw::Window, width: i32, height: i32) {
println!("Framebuffer size: {} {}", width, height);
}
}
struct KeyContext;
impl glfw::KeyCallback for KeyContext {
fn call(&self, window: &glfw::Window, key: glfw::Key, scancode: libc::c_int, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s} (scan code : {})",
key.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
},
scancode);
match (key, action) {
(glfw::KeyEscape, glfw::Press) => {
window.set_should_close(true);
}
(glfw::KeyR, glfw::Press) => {
// Resize should cause the window to "refresh"
let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => ()
}
}
}
struct CharContext;
impl glfw::CharCallback for CharContext {
fn call(&self, _: &glfw::Window, character: char) {
println!("Character: {}", character);
}
}
struct MouseButtonContext;
impl glfw::MouseButtonCallback for MouseButtonContext {
fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) {
println!("{} {:s}{:s}",
button.to_str(),
action.to_str(),
match mods.to_str() {
~"" => ~"",
s => format!(" with: {:s}", s),
});
}
}
struct CursorPosContext;
impl glfw::CursorPosCallback for CursorPosContext {
fn call(&self, window: &glfw::Window, xpos: f64, ypos: f64) {
window.set_title(format!("Cursor position: ({}, {})", xpos, ypos));
}
}
struct CursorEnterContext;
impl glfw::CursorEnterCallback for CursorEnterContext {
fn call(&self, _: &glfw::Window, entered: bool) {
if entered { println("Cursor entered window."); }
else { println("Cursor left window."); }
}
}
struct ScrollContext;
impl glfw::ScrollCallback for ScrollContext {
fn call(&self, window: &glfw::Window, x: f64, y: f64) {
window.set_title(format!("Scroll offset: ({}, {})", x, y));
}
}
| FramebufferSizeContext | identifier_name |
impl_core.rs | #![allow(unused_unsafe)]
//! Contains implementations for rust core that have not been stabilized
//!
//! Functions in this are expected to be properly peer reviewed by the community
//!
//! Any modifications done are purely to make the code compatible with bincode
use core::mem::{self, MaybeUninit};
/// Pulls `N` items from `iter` and returns them as an array. If the iterator
/// yields fewer than `N` items, `None` is returned and all already yielded
/// items are dropped.
///
/// Since the iterator is passed as a mutable reference and this function calls
/// `next` at most `N` times, the iterator can still be used afterwards to
/// retrieve the remaining items.
///
/// If `iter.next()` panicks, all items already yielded by the iterator are
/// dropped.
#[allow(clippy::while_let_on_iterator)]
pub fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
where
I: Iterator<Item = Result<T, E>>,
{
if N == 0 {
// SAFETY: An empty array is always inhabited and has no validity invariants.
return unsafe { Some(Ok(mem::zeroed())) };
}
struct Guard<'a, T, const N: usize> {
array_mut: &'a mut [MaybeUninit<T>; N],
initialized: usize,
}
impl<T, const N: usize> Drop for Guard<'_, T, N> {
fn drop(&mut self) {
debug_assert!(self.initialized <= N);
// SAFETY: this slice will contain only initialized objects.
unsafe {
core::ptr::drop_in_place(slice_assume_init_mut(
self.array_mut.get_unchecked_mut(..self.initialized), |
let mut array = uninit_array::<T, N>();
let mut guard = Guard {
array_mut: &mut array,
initialized: 0,
};
while let Some(item_rslt) = iter.next() {
let item = match item_rslt {
Err(err) => {
return Some(Err(err));
}
Ok(elem) => elem,
};
// SAFETY: `guard.initialized` starts at 0, is increased by one in the
// loop and the loop is aborted once it reaches N (which is
// `array.len()`).
unsafe {
guard
.array_mut
.get_unchecked_mut(guard.initialized)
.write(item);
}
guard.initialized += 1;
// Check if the whole array was initialized.
if guard.initialized == N {
mem::forget(guard);
// SAFETY: the condition above asserts that all elements are
// initialized.
let out = unsafe { array_assume_init(array) };
return Some(Ok(out));
}
}
// This is only reached if the iterator is exhausted before
// `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
// dropping all already initialized elements.
None
}
/// Assuming all the elements are initialized, get a mutable slice to them.
///
/// # Safety
///
/// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
/// really are in an initialized state.
/// Calling this when the content is not yet fully initialized causes undefined behavior.
///
/// See [`assume_init_mut`] for more details and examples.
///
/// [`assume_init_mut`]: MaybeUninit::assume_init_mut
// #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
// #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a
// mutable reference which is also guaranteed to be valid for writes.
unsafe { &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) }
}
/// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
///
/// Note: in a future Rust version this method may become unnecessary
/// when Rust allows
/// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
/// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
///
/// use std::mem::MaybeUninit;
///
/// extern "C" {
/// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
/// }
///
/// /// Returns a (possibly smaller) slice of data that was actually read
/// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
/// unsafe {
/// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
/// MaybeUninit::slice_assume_init_ref(&buf[..len])
/// }
/// }
///
/// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
/// let data = read(&mut buf);
/// ```
// #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
// #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
#[inline(always)]
fn uninit_array<T, const LEN: usize>() -> [MaybeUninit<T>; LEN] {
// SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
}
/// Extracts the values from an array of `MaybeUninit` containers.
///
/// # Safety
///
/// It is up to the caller to guarantee that all elements of the array are
/// in an initialized state.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array)]
/// #![feature(maybe_uninit_array_assume_init)]
/// use std::mem::MaybeUninit;
///
/// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
/// array[0].write(0);
/// array[1].write(1);
/// array[2].write(2);
///
/// // SAFETY: Now safe as we initialised all elements
/// let array = unsafe {
/// MaybeUninit::array_assume_init(array)
/// };
///
/// assert_eq!(array, [0, 1, 2]);
/// ```
// #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
#[inline(always)]
pub unsafe fn array_assume_init<T, const N: usize>(array: [MaybeUninit<T>; N]) -> [T; N] {
// SAFETY:
// * The caller guarantees that all elements of the array are initialized
// * `MaybeUninit<T>` and T are guaranteed to have the same layout
// * `MaybeUninit` does not drop, so there are no double-frees
// And thus the conversion is safe
unsafe {
// intrinsics::assert_inhabited::<[T; N]>();
(&array as *const _ as *const [T; N]).read()
}
} | ));
}
}
} | random_line_split |
impl_core.rs | #![allow(unused_unsafe)]
//! Contains implementations for rust core that have not been stabilized
//!
//! Functions in this are expected to be properly peer reviewed by the community
//!
//! Any modifications done are purely to make the code compatible with bincode
use core::mem::{self, MaybeUninit};
/// Pulls `N` items from `iter` and returns them as an array. If the iterator
/// yields fewer than `N` items, `None` is returned and all already yielded
/// items are dropped.
///
/// Since the iterator is passed as a mutable reference and this function calls
/// `next` at most `N` times, the iterator can still be used afterwards to
/// retrieve the remaining items.
///
/// If `iter.next()` panicks, all items already yielded by the iterator are
/// dropped.
#[allow(clippy::while_let_on_iterator)]
pub fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
where
I: Iterator<Item = Result<T, E>>,
{
if N == 0 {
// SAFETY: An empty array is always inhabited and has no validity invariants.
return unsafe { Some(Ok(mem::zeroed())) };
}
struct Guard<'a, T, const N: usize> {
array_mut: &'a mut [MaybeUninit<T>; N],
initialized: usize,
}
impl<T, const N: usize> Drop for Guard<'_, T, N> {
fn drop(&mut self) |
}
let mut array = uninit_array::<T, N>();
let mut guard = Guard {
array_mut: &mut array,
initialized: 0,
};
while let Some(item_rslt) = iter.next() {
let item = match item_rslt {
Err(err) => {
return Some(Err(err));
}
Ok(elem) => elem,
};
// SAFETY: `guard.initialized` starts at 0, is increased by one in the
// loop and the loop is aborted once it reaches N (which is
// `array.len()`).
unsafe {
guard
.array_mut
.get_unchecked_mut(guard.initialized)
.write(item);
}
guard.initialized += 1;
// Check if the whole array was initialized.
if guard.initialized == N {
mem::forget(guard);
// SAFETY: the condition above asserts that all elements are
// initialized.
let out = unsafe { array_assume_init(array) };
return Some(Ok(out));
}
}
// This is only reached if the iterator is exhausted before
// `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
// dropping all already initialized elements.
None
}
/// Assuming all the elements are initialized, get a mutable slice to them.
///
/// # Safety
///
/// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
/// really are in an initialized state.
/// Calling this when the content is not yet fully initialized causes undefined behavior.
///
/// See [`assume_init_mut`] for more details and examples.
///
/// [`assume_init_mut`]: MaybeUninit::assume_init_mut
// #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
// #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a
// mutable reference which is also guaranteed to be valid for writes.
unsafe { &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) }
}
/// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
///
/// Note: in a future Rust version this method may become unnecessary
/// when Rust allows
/// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
/// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
///
/// use std::mem::MaybeUninit;
///
/// extern "C" {
/// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
/// }
///
/// /// Returns a (possibly smaller) slice of data that was actually read
/// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
/// unsafe {
/// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
/// MaybeUninit::slice_assume_init_ref(&buf[..len])
/// }
/// }
///
/// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
/// let data = read(&mut buf);
/// ```
// #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
// #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
#[inline(always)]
fn uninit_array<T, const LEN: usize>() -> [MaybeUninit<T>; LEN] {
// SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
}
/// Extracts the values from an array of `MaybeUninit` containers.
///
/// # Safety
///
/// It is up to the caller to guarantee that all elements of the array are
/// in an initialized state.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array)]
/// #![feature(maybe_uninit_array_assume_init)]
/// use std::mem::MaybeUninit;
///
/// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
/// array[0].write(0);
/// array[1].write(1);
/// array[2].write(2);
///
/// // SAFETY: Now safe as we initialised all elements
/// let array = unsafe {
/// MaybeUninit::array_assume_init(array)
/// };
///
/// assert_eq!(array, [0, 1, 2]);
/// ```
// #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
#[inline(always)]
pub unsafe fn array_assume_init<T, const N: usize>(array: [MaybeUninit<T>; N]) -> [T; N] {
// SAFETY:
// * The caller guarantees that all elements of the array are initialized
// * `MaybeUninit<T>` and T are guaranteed to have the same layout
// * `MaybeUninit` does not drop, so there are no double-frees
// And thus the conversion is safe
unsafe {
// intrinsics::assert_inhabited::<[T; N]>();
(&array as *const _ as *const [T; N]).read()
}
}
| {
debug_assert!(self.initialized <= N);
// SAFETY: this slice will contain only initialized objects.
unsafe {
core::ptr::drop_in_place(slice_assume_init_mut(
self.array_mut.get_unchecked_mut(..self.initialized),
));
}
} | identifier_body |
impl_core.rs | #![allow(unused_unsafe)]
//! Contains implementations for rust core that have not been stabilized
//!
//! Functions in this are expected to be properly peer reviewed by the community
//!
//! Any modifications done are purely to make the code compatible with bincode
use core::mem::{self, MaybeUninit};
/// Pulls `N` items from `iter` and returns them as an array. If the iterator
/// yields fewer than `N` items, `None` is returned and all already yielded
/// items are dropped.
///
/// Since the iterator is passed as a mutable reference and this function calls
/// `next` at most `N` times, the iterator can still be used afterwards to
/// retrieve the remaining items.
///
/// If `iter.next()` panicks, all items already yielded by the iterator are
/// dropped.
#[allow(clippy::while_let_on_iterator)]
pub fn | <E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
where
I: Iterator<Item = Result<T, E>>,
{
if N == 0 {
// SAFETY: An empty array is always inhabited and has no validity invariants.
return unsafe { Some(Ok(mem::zeroed())) };
}
struct Guard<'a, T, const N: usize> {
array_mut: &'a mut [MaybeUninit<T>; N],
initialized: usize,
}
impl<T, const N: usize> Drop for Guard<'_, T, N> {
fn drop(&mut self) {
debug_assert!(self.initialized <= N);
// SAFETY: this slice will contain only initialized objects.
unsafe {
core::ptr::drop_in_place(slice_assume_init_mut(
self.array_mut.get_unchecked_mut(..self.initialized),
));
}
}
}
let mut array = uninit_array::<T, N>();
let mut guard = Guard {
array_mut: &mut array,
initialized: 0,
};
while let Some(item_rslt) = iter.next() {
let item = match item_rslt {
Err(err) => {
return Some(Err(err));
}
Ok(elem) => elem,
};
// SAFETY: `guard.initialized` starts at 0, is increased by one in the
// loop and the loop is aborted once it reaches N (which is
// `array.len()`).
unsafe {
guard
.array_mut
.get_unchecked_mut(guard.initialized)
.write(item);
}
guard.initialized += 1;
// Check if the whole array was initialized.
if guard.initialized == N {
mem::forget(guard);
// SAFETY: the condition above asserts that all elements are
// initialized.
let out = unsafe { array_assume_init(array) };
return Some(Ok(out));
}
}
// This is only reached if the iterator is exhausted before
// `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
// dropping all already initialized elements.
None
}
/// Assuming all the elements are initialized, get a mutable slice to them.
///
/// # Safety
///
/// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
/// really are in an initialized state.
/// Calling this when the content is not yet fully initialized causes undefined behavior.
///
/// See [`assume_init_mut`] for more details and examples.
///
/// [`assume_init_mut`]: MaybeUninit::assume_init_mut
// #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
// #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a
// mutable reference which is also guaranteed to be valid for writes.
unsafe { &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) }
}
/// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
///
/// Note: in a future Rust version this method may become unnecessary
/// when Rust allows
/// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
/// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
///
/// use std::mem::MaybeUninit;
///
/// extern "C" {
/// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
/// }
///
/// /// Returns a (possibly smaller) slice of data that was actually read
/// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
/// unsafe {
/// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
/// MaybeUninit::slice_assume_init_ref(&buf[..len])
/// }
/// }
///
/// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
/// let data = read(&mut buf);
/// ```
// #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
// #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
#[inline(always)]
fn uninit_array<T, const LEN: usize>() -> [MaybeUninit<T>; LEN] {
// SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
}
/// Extracts the values from an array of `MaybeUninit` containers.
///
/// # Safety
///
/// It is up to the caller to guarantee that all elements of the array are
/// in an initialized state.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array)]
/// #![feature(maybe_uninit_array_assume_init)]
/// use std::mem::MaybeUninit;
///
/// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
/// array[0].write(0);
/// array[1].write(1);
/// array[2].write(2);
///
/// // SAFETY: Now safe as we initialised all elements
/// let array = unsafe {
/// MaybeUninit::array_assume_init(array)
/// };
///
/// assert_eq!(array, [0, 1, 2]);
/// ```
// #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
#[inline(always)]
pub unsafe fn array_assume_init<T, const N: usize>(array: [MaybeUninit<T>; N]) -> [T; N] {
// SAFETY:
// * The caller guarantees that all elements of the array are initialized
// * `MaybeUninit<T>` and T are guaranteed to have the same layout
// * `MaybeUninit` does not drop, so there are no double-frees
// And thus the conversion is safe
unsafe {
// intrinsics::assert_inhabited::<[T; N]>();
(&array as *const _ as *const [T; N]).read()
}
}
| collect_into_array | identifier_name |
impl_core.rs | #![allow(unused_unsafe)]
//! Contains implementations for rust core that have not been stabilized
//!
//! Functions in this are expected to be properly peer reviewed by the community
//!
//! Any modifications done are purely to make the code compatible with bincode
use core::mem::{self, MaybeUninit};
/// Pulls `N` items from `iter` and returns them as an array. If the iterator
/// yields fewer than `N` items, `None` is returned and all already yielded
/// items are dropped.
///
/// Since the iterator is passed as a mutable reference and this function calls
/// `next` at most `N` times, the iterator can still be used afterwards to
/// retrieve the remaining items.
///
/// If `iter.next()` panicks, all items already yielded by the iterator are
/// dropped.
#[allow(clippy::while_let_on_iterator)]
pub fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
where
I: Iterator<Item = Result<T, E>>,
{
if N == 0 {
// SAFETY: An empty array is always inhabited and has no validity invariants.
return unsafe { Some(Ok(mem::zeroed())) };
}
struct Guard<'a, T, const N: usize> {
array_mut: &'a mut [MaybeUninit<T>; N],
initialized: usize,
}
impl<T, const N: usize> Drop for Guard<'_, T, N> {
fn drop(&mut self) {
debug_assert!(self.initialized <= N);
// SAFETY: this slice will contain only initialized objects.
unsafe {
core::ptr::drop_in_place(slice_assume_init_mut(
self.array_mut.get_unchecked_mut(..self.initialized),
));
}
}
}
let mut array = uninit_array::<T, N>();
let mut guard = Guard {
array_mut: &mut array,
initialized: 0,
};
while let Some(item_rslt) = iter.next() {
let item = match item_rslt {
Err(err) => {
return Some(Err(err));
}
Ok(elem) => elem,
};
// SAFETY: `guard.initialized` starts at 0, is increased by one in the
// loop and the loop is aborted once it reaches N (which is
// `array.len()`).
unsafe {
guard
.array_mut
.get_unchecked_mut(guard.initialized)
.write(item);
}
guard.initialized += 1;
// Check if the whole array was initialized.
if guard.initialized == N |
}
// This is only reached if the iterator is exhausted before
// `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
// dropping all already initialized elements.
None
}
/// Assuming all the elements are initialized, get a mutable slice to them.
///
/// # Safety
///
/// It is up to the caller to guarantee that the `MaybeUninit<T>` elements
/// really are in an initialized state.
/// Calling this when the content is not yet fully initialized causes undefined behavior.
///
/// See [`assume_init_mut`] for more details and examples.
///
/// [`assume_init_mut`]: MaybeUninit::assume_init_mut
// #[unstable(feature = "maybe_uninit_slice", issue = "63569")]
// #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")]
#[inline(always)]
pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a
// mutable reference which is also guaranteed to be valid for writes.
unsafe { &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) }
}
/// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
///
/// Note: in a future Rust version this method may become unnecessary
/// when Rust allows
/// [inline const expressions](https://github.com/rust-lang/rust/issues/76001).
/// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]
///
/// use std::mem::MaybeUninit;
///
/// extern "C" {
/// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
/// }
///
/// /// Returns a (possibly smaller) slice of data that was actually read
/// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
/// unsafe {
/// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
/// MaybeUninit::slice_assume_init_ref(&buf[..len])
/// }
/// }
///
/// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
/// let data = read(&mut buf);
/// ```
// #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
// #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")]
#[inline(always)]
fn uninit_array<T, const LEN: usize>() -> [MaybeUninit<T>; LEN] {
// SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
}
/// Extracts the values from an array of `MaybeUninit` containers.
///
/// # Safety
///
/// It is up to the caller to guarantee that all elements of the array are
/// in an initialized state.
///
/// # Examples
///
/// ```ignore
/// #![feature(maybe_uninit_uninit_array)]
/// #![feature(maybe_uninit_array_assume_init)]
/// use std::mem::MaybeUninit;
///
/// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
/// array[0].write(0);
/// array[1].write(1);
/// array[2].write(2);
///
/// // SAFETY: Now safe as we initialised all elements
/// let array = unsafe {
/// MaybeUninit::array_assume_init(array)
/// };
///
/// assert_eq!(array, [0, 1, 2]);
/// ```
// #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")]
#[inline(always)]
pub unsafe fn array_assume_init<T, const N: usize>(array: [MaybeUninit<T>; N]) -> [T; N] {
// SAFETY:
// * The caller guarantees that all elements of the array are initialized
// * `MaybeUninit<T>` and T are guaranteed to have the same layout
// * `MaybeUninit` does not drop, so there are no double-frees
// And thus the conversion is safe
unsafe {
// intrinsics::assert_inhabited::<[T; N]>();
(&array as *const _ as *const [T; N]).read()
}
}
| {
mem::forget(guard);
// SAFETY: the condition above asserts that all elements are
// initialized.
let out = unsafe { array_assume_init(array) };
return Some(Ok(out));
} | conditional_block |
chain.rs | //! A container for a series of audio devices.
//!
//! A chain can be used when a single series of audio devices passes its output
//! to the input of the next device. It is initialized from a single starting
//! device that will receive no input, and ends in a device who's output is
//! ignored.
//!
//!
//! # Example
//! The following will pass microphone input through a low pass filter, then out
//! to the speaker:
//!
//! ```no_run
//! use oxcable::chain::{DeviceChain, Tick};
//! use oxcable::filters::first_order::{Filter, LowPass};
//! use oxcable::io::audio::AudioEngine;
//!
//! let engine = AudioEngine::with_buffer_size(256).unwrap();
//! let mut chain = DeviceChain::from(
//! engine.default_input(1).unwrap()
//! ).into(
//! Filter::new(LowPass(8000f32), 1)
//! ).into(
//! engine.default_output(1).unwrap()
//! );
//! chain.tick_forever();
//! ```
use types::{AudioDevice, Sample, Time};
pub use tick::Tick;
/// A container for a series of audio devices.
pub struct DeviceChain {
bus: Vec<Sample>,
devices: Vec<AudioNode>,
time: Time
}
impl DeviceChain {
/// Creates a new chain that starts from the provided device. This device
/// will receive no inputs unless they are manually supplied using
/// DeviceChain::get_input.
pub fn from<D>(device: D) -> Self where D:'static+AudioDevice {
let mut chain = DeviceChain {
bus: Vec::new(),
devices: Vec::new(),
time: 0
};
for _ in 0..device.num_inputs() {
chain.bus.push(0.0);
}
chain.devices.push(AudioNode::new(device, &mut chain.bus));
chain
}
/// Appends the provided device to the end of the chain. This device will be
/// passed the output of the last device as input. This method returns the
/// same chain it was passed.
///
/// # Panics
///
/// Panics if the provided device does not have as many inputs as the
/// previous device has outputs.
pub fn into<D>(mut self, device: D) -> Self where D:'static+AudioDevice {
if self.devices[self.devices.len()-1].device.num_outputs()!=
device.num_inputs() {
panic!("DeviceChain: number of outputs must match number of inputs");
}
self.devices.push(AudioNode::new(device, &mut self.bus));
self
}
/// Return a mutable slice to the input of the first device in the chain.
///
/// These inputs never get overwritten, so if you are supplying input you
/// must manually zero the buffer again.
pub fn get_input(&mut self) -> &mut[Sample] {
&mut self.bus[..self.devices[0].device.num_inputs()] | let outputs = self.devices[self.devices.len()-1].device.num_outputs();
&self.bus[self.bus.len()-outputs..]
}
}
impl Tick for DeviceChain {
fn tick(&mut self) {
for device in self.devices.iter_mut() {
device.tick(self.time, &mut self.bus);
}
self.time += 1;
}
}
/// Wrap an audio device behind a pointer, and stores an index into the bus.
struct AudioNode {
device: Box<AudioDevice>,
bus_start: usize,
bus_end: usize,
split_point: usize
}
impl AudioNode {
/// Wraps the provided audio device in a new node and allocate space for it
/// in the bus.
fn new<D>(device: D, bus: &mut Vec<Sample>) -> AudioNode
where D:'static+AudioDevice {
let inputs = device.num_inputs();
let outputs = device.num_outputs();
let bus_start = bus.len() - inputs;
for _ in 0..outputs {
bus.push(0.0);
}
AudioNode {
device: Box::new(device),
bus_start: bus_start,
bus_end: bus_start + inputs + outputs,
split_point: inputs,
}
}
/// Ticks the device one time step.
fn tick(&mut self, t: Time, bus: &mut [Sample]) {
let bus_slice = &mut bus[self.bus_start.. self.bus_end];
let (inputs, outputs) = bus_slice.split_at_mut(self.split_point);
self.device.tick(t, inputs, outputs);
}
}
#[cfg(test)]
mod test {
use testing::MockAudioDevice;
use super::{DeviceChain, Tick};
#[test]
fn test_success() {
let mut mock1 = MockAudioDevice::new("mock1", 0, 1);
let mut mock2 = MockAudioDevice::new("mock2", 1, 2);
let mut mock3 = MockAudioDevice::new("mock3", 2, 0);
mock1.will_tick(&[], &[1.0]);
mock2.will_tick(&[1.0], &[2.0, 3.0]);
mock3.will_tick(&[2.0, 3.0], &[]);
DeviceChain::from(mock1).into(mock2).into(mock3).tick();
}
#[test]
fn test_input() {
let mut mock = MockAudioDevice::new("mock1", 1, 0);
mock.will_tick(&[1.0], &[]);
let mut chain = DeviceChain::from(mock);
chain.get_input()[0] = 1.0;
chain.tick();
}
#[test]
fn test_output() {
let mut mock = MockAudioDevice::new("mock1", 0, 1);
mock.will_tick(&[], &[1.0]);
let mut chain = DeviceChain::from(mock);
chain.tick();
assert_eq!(chain.get_output(), [1.0]);
}
#[test]
#[should_panic]
fn test_wrong_number_inputs() {
let mock1 = MockAudioDevice::new("mock1", 0, 1);
let mock2 = MockAudioDevice::new("mock2", 2, 1);
DeviceChain::from(mock1).into(mock2);
}
} | }
/// Returns a slice to the output of the last device in the chain.
pub fn get_output(&self) -> &[Sample] { | random_line_split |
chain.rs | //! A container for a series of audio devices.
//!
//! A chain can be used when a single series of audio devices passes its output
//! to the input of the next device. It is initialized from a single starting
//! device that will receive no input, and ends in a device who's output is
//! ignored.
//!
//!
//! # Example
//! The following will pass microphone input through a low pass filter, then out
//! to the speaker:
//!
//! ```no_run
//! use oxcable::chain::{DeviceChain, Tick};
//! use oxcable::filters::first_order::{Filter, LowPass};
//! use oxcable::io::audio::AudioEngine;
//!
//! let engine = AudioEngine::with_buffer_size(256).unwrap();
//! let mut chain = DeviceChain::from(
//! engine.default_input(1).unwrap()
//! ).into(
//! Filter::new(LowPass(8000f32), 1)
//! ).into(
//! engine.default_output(1).unwrap()
//! );
//! chain.tick_forever();
//! ```
use types::{AudioDevice, Sample, Time};
pub use tick::Tick;
/// A container for a series of audio devices.
pub struct DeviceChain {
bus: Vec<Sample>,
devices: Vec<AudioNode>,
time: Time
}
impl DeviceChain {
/// Creates a new chain that starts from the provided device. This device
/// will receive no inputs unless they are manually supplied using
/// DeviceChain::get_input.
pub fn from<D>(device: D) -> Self where D:'static+AudioDevice {
let mut chain = DeviceChain {
bus: Vec::new(),
devices: Vec::new(),
time: 0
};
for _ in 0..device.num_inputs() {
chain.bus.push(0.0);
}
chain.devices.push(AudioNode::new(device, &mut chain.bus));
chain
}
/// Appends the provided device to the end of the chain. This device will be
/// passed the output of the last device as input. This method returns the
/// same chain it was passed.
///
/// # Panics
///
/// Panics if the provided device does not have as many inputs as the
/// previous device has outputs.
pub fn into<D>(mut self, device: D) -> Self where D:'static+AudioDevice {
if self.devices[self.devices.len()-1].device.num_outputs()!=
device.num_inputs() {
panic!("DeviceChain: number of outputs must match number of inputs");
}
self.devices.push(AudioNode::new(device, &mut self.bus));
self
}
/// Return a mutable slice to the input of the first device in the chain.
///
/// These inputs never get overwritten, so if you are supplying input you
/// must manually zero the buffer again.
pub fn get_input(&mut self) -> &mut[Sample] {
&mut self.bus[..self.devices[0].device.num_inputs()]
}
/// Returns a slice to the output of the last device in the chain.
pub fn | (&self) -> &[Sample] {
let outputs = self.devices[self.devices.len()-1].device.num_outputs();
&self.bus[self.bus.len()-outputs..]
}
}
impl Tick for DeviceChain {
fn tick(&mut self) {
for device in self.devices.iter_mut() {
device.tick(self.time, &mut self.bus);
}
self.time += 1;
}
}
/// Wrap an audio device behind a pointer, and stores an index into the bus.
struct AudioNode {
device: Box<AudioDevice>,
bus_start: usize,
bus_end: usize,
split_point: usize
}
impl AudioNode {
/// Wraps the provided audio device in a new node and allocate space for it
/// in the bus.
fn new<D>(device: D, bus: &mut Vec<Sample>) -> AudioNode
where D:'static+AudioDevice {
let inputs = device.num_inputs();
let outputs = device.num_outputs();
let bus_start = bus.len() - inputs;
for _ in 0..outputs {
bus.push(0.0);
}
AudioNode {
device: Box::new(device),
bus_start: bus_start,
bus_end: bus_start + inputs + outputs,
split_point: inputs,
}
}
/// Ticks the device one time step.
fn tick(&mut self, t: Time, bus: &mut [Sample]) {
let bus_slice = &mut bus[self.bus_start.. self.bus_end];
let (inputs, outputs) = bus_slice.split_at_mut(self.split_point);
self.device.tick(t, inputs, outputs);
}
}
#[cfg(test)]
mod test {
use testing::MockAudioDevice;
use super::{DeviceChain, Tick};
#[test]
fn test_success() {
let mut mock1 = MockAudioDevice::new("mock1", 0, 1);
let mut mock2 = MockAudioDevice::new("mock2", 1, 2);
let mut mock3 = MockAudioDevice::new("mock3", 2, 0);
mock1.will_tick(&[], &[1.0]);
mock2.will_tick(&[1.0], &[2.0, 3.0]);
mock3.will_tick(&[2.0, 3.0], &[]);
DeviceChain::from(mock1).into(mock2).into(mock3).tick();
}
#[test]
fn test_input() {
let mut mock = MockAudioDevice::new("mock1", 1, 0);
mock.will_tick(&[1.0], &[]);
let mut chain = DeviceChain::from(mock);
chain.get_input()[0] = 1.0;
chain.tick();
}
#[test]
fn test_output() {
let mut mock = MockAudioDevice::new("mock1", 0, 1);
mock.will_tick(&[], &[1.0]);
let mut chain = DeviceChain::from(mock);
chain.tick();
assert_eq!(chain.get_output(), [1.0]);
}
#[test]
#[should_panic]
fn test_wrong_number_inputs() {
let mock1 = MockAudioDevice::new("mock1", 0, 1);
let mock2 = MockAudioDevice::new("mock2", 2, 1);
DeviceChain::from(mock1).into(mock2);
}
}
| get_output | identifier_name |
chain.rs | //! A container for a series of audio devices.
//!
//! A chain can be used when a single series of audio devices passes its output
//! to the input of the next device. It is initialized from a single starting
//! device that will receive no input, and ends in a device who's output is
//! ignored.
//!
//!
//! # Example
//! The following will pass microphone input through a low pass filter, then out
//! to the speaker:
//!
//! ```no_run
//! use oxcable::chain::{DeviceChain, Tick};
//! use oxcable::filters::first_order::{Filter, LowPass};
//! use oxcable::io::audio::AudioEngine;
//!
//! let engine = AudioEngine::with_buffer_size(256).unwrap();
//! let mut chain = DeviceChain::from(
//! engine.default_input(1).unwrap()
//! ).into(
//! Filter::new(LowPass(8000f32), 1)
//! ).into(
//! engine.default_output(1).unwrap()
//! );
//! chain.tick_forever();
//! ```
use types::{AudioDevice, Sample, Time};
pub use tick::Tick;
/// A container for a series of audio devices.
pub struct DeviceChain {
bus: Vec<Sample>,
devices: Vec<AudioNode>,
time: Time
}
impl DeviceChain {
/// Creates a new chain that starts from the provided device. This device
/// will receive no inputs unless they are manually supplied using
/// DeviceChain::get_input.
pub fn from<D>(device: D) -> Self where D:'static+AudioDevice {
let mut chain = DeviceChain {
bus: Vec::new(),
devices: Vec::new(),
time: 0
};
for _ in 0..device.num_inputs() {
chain.bus.push(0.0);
}
chain.devices.push(AudioNode::new(device, &mut chain.bus));
chain
}
/// Appends the provided device to the end of the chain. This device will be
/// passed the output of the last device as input. This method returns the
/// same chain it was passed.
///
/// # Panics
///
/// Panics if the provided device does not have as many inputs as the
/// previous device has outputs.
pub fn into<D>(mut self, device: D) -> Self where D:'static+AudioDevice {
if self.devices[self.devices.len()-1].device.num_outputs()!=
device.num_inputs() {
panic!("DeviceChain: number of outputs must match number of inputs");
}
self.devices.push(AudioNode::new(device, &mut self.bus));
self
}
/// Return a mutable slice to the input of the first device in the chain.
///
/// These inputs never get overwritten, so if you are supplying input you
/// must manually zero the buffer again.
pub fn get_input(&mut self) -> &mut[Sample] {
&mut self.bus[..self.devices[0].device.num_inputs()]
}
/// Returns a slice to the output of the last device in the chain.
pub fn get_output(&self) -> &[Sample] {
let outputs = self.devices[self.devices.len()-1].device.num_outputs();
&self.bus[self.bus.len()-outputs..]
}
}
impl Tick for DeviceChain {
fn tick(&mut self) {
for device in self.devices.iter_mut() {
device.tick(self.time, &mut self.bus);
}
self.time += 1;
}
}
/// Wrap an audio device behind a pointer, and stores an index into the bus.
struct AudioNode {
device: Box<AudioDevice>,
bus_start: usize,
bus_end: usize,
split_point: usize
}
impl AudioNode {
/// Wraps the provided audio device in a new node and allocate space for it
/// in the bus.
fn new<D>(device: D, bus: &mut Vec<Sample>) -> AudioNode
where D:'static+AudioDevice {
let inputs = device.num_inputs();
let outputs = device.num_outputs();
let bus_start = bus.len() - inputs;
for _ in 0..outputs {
bus.push(0.0);
}
AudioNode {
device: Box::new(device),
bus_start: bus_start,
bus_end: bus_start + inputs + outputs,
split_point: inputs,
}
}
/// Ticks the device one time step.
fn tick(&mut self, t: Time, bus: &mut [Sample]) {
let bus_slice = &mut bus[self.bus_start.. self.bus_end];
let (inputs, outputs) = bus_slice.split_at_mut(self.split_point);
self.device.tick(t, inputs, outputs);
}
}
#[cfg(test)]
mod test {
use testing::MockAudioDevice;
use super::{DeviceChain, Tick};
#[test]
fn test_success() {
let mut mock1 = MockAudioDevice::new("mock1", 0, 1);
let mut mock2 = MockAudioDevice::new("mock2", 1, 2);
let mut mock3 = MockAudioDevice::new("mock3", 2, 0);
mock1.will_tick(&[], &[1.0]);
mock2.will_tick(&[1.0], &[2.0, 3.0]);
mock3.will_tick(&[2.0, 3.0], &[]);
DeviceChain::from(mock1).into(mock2).into(mock3).tick();
}
#[test]
fn test_input() {
let mut mock = MockAudioDevice::new("mock1", 1, 0);
mock.will_tick(&[1.0], &[]);
let mut chain = DeviceChain::from(mock);
chain.get_input()[0] = 1.0;
chain.tick();
}
#[test]
fn test_output() {
let mut mock = MockAudioDevice::new("mock1", 0, 1);
mock.will_tick(&[], &[1.0]);
let mut chain = DeviceChain::from(mock);
chain.tick();
assert_eq!(chain.get_output(), [1.0]);
}
#[test]
#[should_panic]
fn test_wrong_number_inputs() |
}
| {
let mock1 = MockAudioDevice::new("mock1", 0, 1);
let mock2 = MockAudioDevice::new("mock2", 2, 1);
DeviceChain::from(mock1).into(mock2);
} | identifier_body |
chain.rs | //! A container for a series of audio devices.
//!
//! A chain can be used when a single series of audio devices passes its output
//! to the input of the next device. It is initialized from a single starting
//! device that will receive no input, and ends in a device who's output is
//! ignored.
//!
//!
//! # Example
//! The following will pass microphone input through a low pass filter, then out
//! to the speaker:
//!
//! ```no_run
//! use oxcable::chain::{DeviceChain, Tick};
//! use oxcable::filters::first_order::{Filter, LowPass};
//! use oxcable::io::audio::AudioEngine;
//!
//! let engine = AudioEngine::with_buffer_size(256).unwrap();
//! let mut chain = DeviceChain::from(
//! engine.default_input(1).unwrap()
//! ).into(
//! Filter::new(LowPass(8000f32), 1)
//! ).into(
//! engine.default_output(1).unwrap()
//! );
//! chain.tick_forever();
//! ```
use types::{AudioDevice, Sample, Time};
pub use tick::Tick;
/// A container for a series of audio devices.
pub struct DeviceChain {
bus: Vec<Sample>,
devices: Vec<AudioNode>,
time: Time
}
impl DeviceChain {
/// Creates a new chain that starts from the provided device. This device
/// will receive no inputs unless they are manually supplied using
/// DeviceChain::get_input.
pub fn from<D>(device: D) -> Self where D:'static+AudioDevice {
let mut chain = DeviceChain {
bus: Vec::new(),
devices: Vec::new(),
time: 0
};
for _ in 0..device.num_inputs() {
chain.bus.push(0.0);
}
chain.devices.push(AudioNode::new(device, &mut chain.bus));
chain
}
/// Appends the provided device to the end of the chain. This device will be
/// passed the output of the last device as input. This method returns the
/// same chain it was passed.
///
/// # Panics
///
/// Panics if the provided device does not have as many inputs as the
/// previous device has outputs.
pub fn into<D>(mut self, device: D) -> Self where D:'static+AudioDevice {
if self.devices[self.devices.len()-1].device.num_outputs()!=
device.num_inputs() |
self.devices.push(AudioNode::new(device, &mut self.bus));
self
}
/// Return a mutable slice to the input of the first device in the chain.
///
/// These inputs never get overwritten, so if you are supplying input you
/// must manually zero the buffer again.
pub fn get_input(&mut self) -> &mut[Sample] {
&mut self.bus[..self.devices[0].device.num_inputs()]
}
/// Returns a slice to the output of the last device in the chain.
pub fn get_output(&self) -> &[Sample] {
let outputs = self.devices[self.devices.len()-1].device.num_outputs();
&self.bus[self.bus.len()-outputs..]
}
}
impl Tick for DeviceChain {
fn tick(&mut self) {
for device in self.devices.iter_mut() {
device.tick(self.time, &mut self.bus);
}
self.time += 1;
}
}
/// Wrap an audio device behind a pointer, and stores an index into the bus.
struct AudioNode {
device: Box<AudioDevice>,
bus_start: usize,
bus_end: usize,
split_point: usize
}
impl AudioNode {
/// Wraps the provided audio device in a new node and allocate space for it
/// in the bus.
fn new<D>(device: D, bus: &mut Vec<Sample>) -> AudioNode
where D:'static+AudioDevice {
let inputs = device.num_inputs();
let outputs = device.num_outputs();
let bus_start = bus.len() - inputs;
for _ in 0..outputs {
bus.push(0.0);
}
AudioNode {
device: Box::new(device),
bus_start: bus_start,
bus_end: bus_start + inputs + outputs,
split_point: inputs,
}
}
/// Ticks the device one time step.
fn tick(&mut self, t: Time, bus: &mut [Sample]) {
let bus_slice = &mut bus[self.bus_start.. self.bus_end];
let (inputs, outputs) = bus_slice.split_at_mut(self.split_point);
self.device.tick(t, inputs, outputs);
}
}
#[cfg(test)]
mod test {
use testing::MockAudioDevice;
use super::{DeviceChain, Tick};
#[test]
fn test_success() {
let mut mock1 = MockAudioDevice::new("mock1", 0, 1);
let mut mock2 = MockAudioDevice::new("mock2", 1, 2);
let mut mock3 = MockAudioDevice::new("mock3", 2, 0);
mock1.will_tick(&[], &[1.0]);
mock2.will_tick(&[1.0], &[2.0, 3.0]);
mock3.will_tick(&[2.0, 3.0], &[]);
DeviceChain::from(mock1).into(mock2).into(mock3).tick();
}
#[test]
fn test_input() {
let mut mock = MockAudioDevice::new("mock1", 1, 0);
mock.will_tick(&[1.0], &[]);
let mut chain = DeviceChain::from(mock);
chain.get_input()[0] = 1.0;
chain.tick();
}
#[test]
fn test_output() {
let mut mock = MockAudioDevice::new("mock1", 0, 1);
mock.will_tick(&[], &[1.0]);
let mut chain = DeviceChain::from(mock);
chain.tick();
assert_eq!(chain.get_output(), [1.0]);
}
#[test]
#[should_panic]
fn test_wrong_number_inputs() {
let mock1 = MockAudioDevice::new("mock1", 0, 1);
let mock2 = MockAudioDevice::new("mock2", 2, 1);
DeviceChain::from(mock1).into(mock2);
}
}
| {
panic!("DeviceChain: number of outputs must match number of inputs");
} | conditional_block |
x11_sockets.rs | use std::{
io::{Read, Write},
os::unix::{io::FromRawFd, net::UnixStream},
};
use slog::{debug, info, warn};
use nix::{errno::Errno, sys::socket, Result as NixResult};
/// Find a free X11 display slot and setup
pub(crate) fn prepare_x11_sockets(log: ::slog::Logger) -> Result<(X11Lock, [UnixStream; 2]), std::io::Error> {
for d in 0..33 {
// if fails, try the next one
if let Ok(lock) = X11Lock::grab(d, log.clone()) {
// we got a lockfile, try and create the socket
if let Ok(sockets) = open_x11_sockets_for_display(d) {
return Ok((lock, sockets));
}
}
}
// If we reach here, all values from 0 to 32 failed
// we need to stop trying at some point
Err(std::io::Error::new(
std::io::ErrorKind::AddrInUse,
"Could not find a free socket for the XServer.",
))
}
#[derive(Debug)]
pub(crate) struct X11Lock {
display: u32,
log: ::slog::Logger,
}
impl X11Lock {
/// Try to grab a lockfile for given X display number
fn grab(display: u32, log: ::slog::Logger) -> Result<X11Lock, ()> {
debug!(log, "Attempting to aquire an X11 display lock"; "D" => display);
let filename = format!("/tmp/.X{}-lock", display);
let lockfile = ::std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&filename);
match lockfile {
Ok(mut file) => |
Err(_) => {
debug!(log, "Failed to acquire lock"; "D" => display);
// we could not open the file, now we try to read it
// and if it contains the pid of a process that no longer
// exist (so if a previous x server claimed it and did not
// exit gracefully and remove it), we claim it
// if we can't open it, give up
let mut file = ::std::fs::File::open(&filename).map_err(|_| ())?;
let mut spid = [0u8; 11];
file.read_exact(&mut spid).map_err(|_| ())?;
::std::mem::drop(file);
let pid = ::nix::unistd::Pid::from_raw(
::std::str::from_utf8(&spid)
.map_err(|_| ())?
.trim()
.parse::<i32>()
.map_err(|_| ())?,
);
if let Err(Errno::ESRCH) = ::nix::sys::signal::kill(pid, None) {
// no process whose pid equals the contents of the lockfile exists
// remove the lockfile and try grabbing it again
if let Ok(()) = ::std::fs::remove_file(filename) {
debug!(log, "Lock was blocked by a defunct X11 server, trying again"; "D" => display);
return X11Lock::grab(display, log);
} else {
// we could not remove the lockfile, abort
return Err(());
}
}
// if we reach here, this lockfile exists and is probably in use, give up
Err(())
}
}
}
pub(crate) fn display(&self) -> u32 {
self.display
}
}
impl Drop for X11Lock {
fn drop(&mut self) {
info!(self.log, "Cleaning up X11 lock.");
// Cleanup all the X11 files
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X11-unix/X{}", self.display)) {
warn!(self.log, "Failed to remove X11 socket"; "error" => format!("{:?}", e));
}
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X{}-lock", self.display)) {
warn!(self.log, "Failed to remove X11 lockfile"; "error" => format!("{:?}", e));
}
}
}
/// Open the two unix sockets an X server listens on
///
/// Should only be done after the associated lockfile is acquired!
fn open_x11_sockets_for_display(display: u32) -> NixResult<[UnixStream; 2]> {
let path = format!("/tmp/.X11-unix/X{}", display);
let _ = ::std::fs::remove_file(&path);
// We know this path is not to long, these unwrap cannot fail
let fs_addr = socket::UnixAddr::new(path.as_bytes()).unwrap();
let abs_addr = socket::UnixAddr::new_abstract(path.as_bytes()).unwrap();
let fs_socket = open_socket(fs_addr)?;
let abstract_socket = open_socket(abs_addr)?;
Ok([fs_socket, abstract_socket])
}
/// Open an unix socket for listening and bind it to given path
fn open_socket(addr: socket::UnixAddr) -> NixResult<UnixStream> {
// create an unix stream socket
let fd = socket::socket(
socket::AddressFamily::Unix,
socket::SockType::Stream,
socket::SockFlag::SOCK_CLOEXEC,
None,
)?;
// bind it to requested address
if let Err(e) = socket::bind(fd, &socket::SockAddr::Unix(addr)) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
if let Err(e) = socket::listen(fd, 1) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
Ok(unsafe { FromRawFd::from_raw_fd(fd) })
}
| {
// we got it, write our PID in it and we're good
let ret = file.write_fmt(format_args!("{:>10}\n", ::nix::unistd::Pid::this()));
if ret.is_err() {
// write to the file failed ? we abandon
::std::mem::drop(file);
let _ = ::std::fs::remove_file(&filename);
Err(())
} else {
debug!(log, "X11 lock acquired"; "D" => display);
// we got the lockfile and wrote our pid to it, all is good
Ok(X11Lock { display, log })
}
} | conditional_block |
x11_sockets.rs | use std::{
io::{Read, Write},
os::unix::{io::FromRawFd, net::UnixStream},
};
use slog::{debug, info, warn};
use nix::{errno::Errno, sys::socket, Result as NixResult};
/// Find a free X11 display slot and setup
pub(crate) fn prepare_x11_sockets(log: ::slog::Logger) -> Result<(X11Lock, [UnixStream; 2]), std::io::Error> {
for d in 0..33 {
// if fails, try the next one
if let Ok(lock) = X11Lock::grab(d, log.clone()) {
// we got a lockfile, try and create the socket
if let Ok(sockets) = open_x11_sockets_for_display(d) {
return Ok((lock, sockets));
}
}
}
// If we reach here, all values from 0 to 32 failed
// we need to stop trying at some point
Err(std::io::Error::new(
std::io::ErrorKind::AddrInUse,
"Could not find a free socket for the XServer.",
))
}
#[derive(Debug)]
pub(crate) struct X11Lock {
display: u32,
log: ::slog::Logger,
}
impl X11Lock {
/// Try to grab a lockfile for given X display number
fn grab(display: u32, log: ::slog::Logger) -> Result<X11Lock, ()> {
debug!(log, "Attempting to aquire an X11 display lock"; "D" => display);
let filename = format!("/tmp/.X{}-lock", display);
let lockfile = ::std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&filename);
match lockfile {
Ok(mut file) => {
// we got it, write our PID in it and we're good
let ret = file.write_fmt(format_args!("{:>10}\n", ::nix::unistd::Pid::this()));
if ret.is_err() {
// write to the file failed? we abandon
::std::mem::drop(file);
let _ = ::std::fs::remove_file(&filename);
Err(())
} else {
debug!(log, "X11 lock acquired"; "D" => display);
// we got the lockfile and wrote our pid to it, all is good
Ok(X11Lock { display, log })
}
}
Err(_) => {
debug!(log, "Failed to acquire lock"; "D" => display);
// we could not open the file, now we try to read it
// and if it contains the pid of a process that no longer
// exist (so if a previous x server claimed it and did not
// exit gracefully and remove it), we claim it
// if we can't open it, give up
let mut file = ::std::fs::File::open(&filename).map_err(|_| ())?;
let mut spid = [0u8; 11];
file.read_exact(&mut spid).map_err(|_| ())?;
::std::mem::drop(file);
let pid = ::nix::unistd::Pid::from_raw(
::std::str::from_utf8(&spid)
.map_err(|_| ())?
.trim()
.parse::<i32>()
.map_err(|_| ())?,
);
if let Err(Errno::ESRCH) = ::nix::sys::signal::kill(pid, None) {
// no process whose pid equals the contents of the lockfile exists
// remove the lockfile and try grabbing it again
if let Ok(()) = ::std::fs::remove_file(filename) {
debug!(log, "Lock was blocked by a defunct X11 server, trying again"; "D" => display);
return X11Lock::grab(display, log);
} else {
// we could not remove the lockfile, abort
return Err(());
}
}
// if we reach here, this lockfile exists and is probably in use, give up
Err(())
}
}
}
pub(crate) fn display(&self) -> u32 {
self.display
}
}
impl Drop for X11Lock {
fn drop(&mut self) {
info!(self.log, "Cleaning up X11 lock.");
// Cleanup all the X11 files
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X11-unix/X{}", self.display)) {
warn!(self.log, "Failed to remove X11 socket"; "error" => format!("{:?}", e));
}
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X{}-lock", self.display)) {
warn!(self.log, "Failed to remove X11 lockfile"; "error" => format!("{:?}", e));
}
}
}
/// Open the two unix sockets an X server listens on
///
/// Should only be done after the associated lockfile is acquired!
fn open_x11_sockets_for_display(display: u32) -> NixResult<[UnixStream; 2]> {
let path = format!("/tmp/.X11-unix/X{}", display);
let _ = ::std::fs::remove_file(&path);
// We know this path is not to long, these unwrap cannot fail
let fs_addr = socket::UnixAddr::new(path.as_bytes()).unwrap();
let abs_addr = socket::UnixAddr::new_abstract(path.as_bytes()).unwrap();
let fs_socket = open_socket(fs_addr)?;
let abstract_socket = open_socket(abs_addr)?;
Ok([fs_socket, abstract_socket])
}
/// Open an unix socket for listening and bind it to given path
fn open_socket(addr: socket::UnixAddr) -> NixResult<UnixStream> {
// create an unix stream socket
let fd = socket::socket(
socket::AddressFamily::Unix,
socket::SockType::Stream,
socket::SockFlag::SOCK_CLOEXEC,
None,
)?;
// bind it to requested address
if let Err(e) = socket::bind(fd, &socket::SockAddr::Unix(addr)) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
if let Err(e) = socket::listen(fd, 1) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
Ok(unsafe { FromRawFd::from_raw_fd(fd) }) | } | random_line_split |
|
x11_sockets.rs | use std::{
io::{Read, Write},
os::unix::{io::FromRawFd, net::UnixStream},
};
use slog::{debug, info, warn};
use nix::{errno::Errno, sys::socket, Result as NixResult};
/// Find a free X11 display slot and setup
pub(crate) fn prepare_x11_sockets(log: ::slog::Logger) -> Result<(X11Lock, [UnixStream; 2]), std::io::Error> {
for d in 0..33 {
// if fails, try the next one
if let Ok(lock) = X11Lock::grab(d, log.clone()) {
// we got a lockfile, try and create the socket
if let Ok(sockets) = open_x11_sockets_for_display(d) {
return Ok((lock, sockets));
}
}
}
// If we reach here, all values from 0 to 32 failed
// we need to stop trying at some point
Err(std::io::Error::new(
std::io::ErrorKind::AddrInUse,
"Could not find a free socket for the XServer.",
))
}
#[derive(Debug)]
pub(crate) struct X11Lock {
display: u32,
log: ::slog::Logger,
}
impl X11Lock {
/// Try to grab a lockfile for given X display number
fn grab(display: u32, log: ::slog::Logger) -> Result<X11Lock, ()> {
debug!(log, "Attempting to aquire an X11 display lock"; "D" => display);
let filename = format!("/tmp/.X{}-lock", display);
let lockfile = ::std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&filename);
match lockfile {
Ok(mut file) => {
// we got it, write our PID in it and we're good
let ret = file.write_fmt(format_args!("{:>10}\n", ::nix::unistd::Pid::this()));
if ret.is_err() {
// write to the file failed? we abandon
::std::mem::drop(file);
let _ = ::std::fs::remove_file(&filename);
Err(())
} else {
debug!(log, "X11 lock acquired"; "D" => display);
// we got the lockfile and wrote our pid to it, all is good
Ok(X11Lock { display, log })
}
}
Err(_) => {
debug!(log, "Failed to acquire lock"; "D" => display);
// we could not open the file, now we try to read it
// and if it contains the pid of a process that no longer
// exist (so if a previous x server claimed it and did not
// exit gracefully and remove it), we claim it
// if we can't open it, give up
let mut file = ::std::fs::File::open(&filename).map_err(|_| ())?;
let mut spid = [0u8; 11];
file.read_exact(&mut spid).map_err(|_| ())?;
::std::mem::drop(file);
let pid = ::nix::unistd::Pid::from_raw(
::std::str::from_utf8(&spid)
.map_err(|_| ())?
.trim()
.parse::<i32>()
.map_err(|_| ())?,
);
if let Err(Errno::ESRCH) = ::nix::sys::signal::kill(pid, None) {
// no process whose pid equals the contents of the lockfile exists
// remove the lockfile and try grabbing it again
if let Ok(()) = ::std::fs::remove_file(filename) {
debug!(log, "Lock was blocked by a defunct X11 server, trying again"; "D" => display);
return X11Lock::grab(display, log);
} else {
// we could not remove the lockfile, abort
return Err(());
}
}
// if we reach here, this lockfile exists and is probably in use, give up
Err(())
}
}
}
pub(crate) fn display(&self) -> u32 {
self.display
}
}
impl Drop for X11Lock {
fn drop(&mut self) {
info!(self.log, "Cleaning up X11 lock.");
// Cleanup all the X11 files
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X11-unix/X{}", self.display)) {
warn!(self.log, "Failed to remove X11 socket"; "error" => format!("{:?}", e));
}
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X{}-lock", self.display)) {
warn!(self.log, "Failed to remove X11 lockfile"; "error" => format!("{:?}", e));
}
}
}
/// Open the two unix sockets an X server listens on
///
/// Should only be done after the associated lockfile is acquired!
fn | (display: u32) -> NixResult<[UnixStream; 2]> {
let path = format!("/tmp/.X11-unix/X{}", display);
let _ = ::std::fs::remove_file(&path);
// We know this path is not to long, these unwrap cannot fail
let fs_addr = socket::UnixAddr::new(path.as_bytes()).unwrap();
let abs_addr = socket::UnixAddr::new_abstract(path.as_bytes()).unwrap();
let fs_socket = open_socket(fs_addr)?;
let abstract_socket = open_socket(abs_addr)?;
Ok([fs_socket, abstract_socket])
}
/// Open an unix socket for listening and bind it to given path
fn open_socket(addr: socket::UnixAddr) -> NixResult<UnixStream> {
// create an unix stream socket
let fd = socket::socket(
socket::AddressFamily::Unix,
socket::SockType::Stream,
socket::SockFlag::SOCK_CLOEXEC,
None,
)?;
// bind it to requested address
if let Err(e) = socket::bind(fd, &socket::SockAddr::Unix(addr)) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
if let Err(e) = socket::listen(fd, 1) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
Ok(unsafe { FromRawFd::from_raw_fd(fd) })
}
| open_x11_sockets_for_display | identifier_name |
x11_sockets.rs | use std::{
io::{Read, Write},
os::unix::{io::FromRawFd, net::UnixStream},
};
use slog::{debug, info, warn};
use nix::{errno::Errno, sys::socket, Result as NixResult};
/// Find a free X11 display slot and setup
pub(crate) fn prepare_x11_sockets(log: ::slog::Logger) -> Result<(X11Lock, [UnixStream; 2]), std::io::Error> {
for d in 0..33 {
// if fails, try the next one
if let Ok(lock) = X11Lock::grab(d, log.clone()) {
// we got a lockfile, try and create the socket
if let Ok(sockets) = open_x11_sockets_for_display(d) {
return Ok((lock, sockets));
}
}
}
// If we reach here, all values from 0 to 32 failed
// we need to stop trying at some point
Err(std::io::Error::new(
std::io::ErrorKind::AddrInUse,
"Could not find a free socket for the XServer.",
))
}
#[derive(Debug)]
pub(crate) struct X11Lock {
display: u32,
log: ::slog::Logger,
}
impl X11Lock {
/// Try to grab a lockfile for given X display number
fn grab(display: u32, log: ::slog::Logger) -> Result<X11Lock, ()> | }
}
Err(_) => {
debug!(log, "Failed to acquire lock"; "D" => display);
// we could not open the file, now we try to read it
// and if it contains the pid of a process that no longer
// exist (so if a previous x server claimed it and did not
// exit gracefully and remove it), we claim it
// if we can't open it, give up
let mut file = ::std::fs::File::open(&filename).map_err(|_| ())?;
let mut spid = [0u8; 11];
file.read_exact(&mut spid).map_err(|_| ())?;
::std::mem::drop(file);
let pid = ::nix::unistd::Pid::from_raw(
::std::str::from_utf8(&spid)
.map_err(|_| ())?
.trim()
.parse::<i32>()
.map_err(|_| ())?,
);
if let Err(Errno::ESRCH) = ::nix::sys::signal::kill(pid, None) {
// no process whose pid equals the contents of the lockfile exists
// remove the lockfile and try grabbing it again
if let Ok(()) = ::std::fs::remove_file(filename) {
debug!(log, "Lock was blocked by a defunct X11 server, trying again"; "D" => display);
return X11Lock::grab(display, log);
} else {
// we could not remove the lockfile, abort
return Err(());
}
}
// if we reach here, this lockfile exists and is probably in use, give up
Err(())
}
}
}
pub(crate) fn display(&self) -> u32 {
self.display
}
}
impl Drop for X11Lock {
fn drop(&mut self) {
info!(self.log, "Cleaning up X11 lock.");
// Cleanup all the X11 files
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X11-unix/X{}", self.display)) {
warn!(self.log, "Failed to remove X11 socket"; "error" => format!("{:?}", e));
}
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X{}-lock", self.display)) {
warn!(self.log, "Failed to remove X11 lockfile"; "error" => format!("{:?}", e));
}
}
}
/// Open the two unix sockets an X server listens on
///
/// Should only be done after the associated lockfile is acquired!
fn open_x11_sockets_for_display(display: u32) -> NixResult<[UnixStream; 2]> {
let path = format!("/tmp/.X11-unix/X{}", display);
let _ = ::std::fs::remove_file(&path);
// We know this path is not to long, these unwrap cannot fail
let fs_addr = socket::UnixAddr::new(path.as_bytes()).unwrap();
let abs_addr = socket::UnixAddr::new_abstract(path.as_bytes()).unwrap();
let fs_socket = open_socket(fs_addr)?;
let abstract_socket = open_socket(abs_addr)?;
Ok([fs_socket, abstract_socket])
}
/// Open an unix socket for listening and bind it to given path
fn open_socket(addr: socket::UnixAddr) -> NixResult<UnixStream> {
// create an unix stream socket
let fd = socket::socket(
socket::AddressFamily::Unix,
socket::SockType::Stream,
socket::SockFlag::SOCK_CLOEXEC,
None,
)?;
// bind it to requested address
if let Err(e) = socket::bind(fd, &socket::SockAddr::Unix(addr)) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
if let Err(e) = socket::listen(fd, 1) {
let _ = ::nix::unistd::close(fd);
return Err(e);
}
Ok(unsafe { FromRawFd::from_raw_fd(fd) })
}
| {
debug!(log, "Attempting to aquire an X11 display lock"; "D" => display);
let filename = format!("/tmp/.X{}-lock", display);
let lockfile = ::std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&filename);
match lockfile {
Ok(mut file) => {
// we got it, write our PID in it and we're good
let ret = file.write_fmt(format_args!("{:>10}\n", ::nix::unistd::Pid::this()));
if ret.is_err() {
// write to the file failed ? we abandon
::std::mem::drop(file);
let _ = ::std::fs::remove_file(&filename);
Err(())
} else {
debug!(log, "X11 lock acquired"; "D" => display);
// we got the lockfile and wrote our pid to it, all is good
Ok(X11Lock { display, log }) | identifier_body |
addrinfo.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.
/*!
Synchronous DNS Resolution
Contains the functionality to perform DNS resolution in a style related to
getaddrinfo()
*/
#![allow(missing_docs)]
use iter::Iterator;
use io::{IoResult};
use io::net::ip::{SocketAddr, IpAddr};
use option::{Option, Some, None};
use sys;
use vec::Vec;
/// Hints to the types of sockets that are desired when looking up hosts
pub enum SocketType {
Stream, Datagram, Raw
}
/// Flags which can be or'd into the `flags` field of a `Hint`. These are used
/// to manipulate how a query is performed.
///
/// The meaning of each of these flags can be found with `man -s 3 getaddrinfo`
pub enum | {
AddrConfig,
All,
CanonName,
NumericHost,
NumericServ,
Passive,
V4Mapped,
}
/// A transport protocol associated with either a hint or a return value of
/// `lookup`
pub enum Protocol {
TCP, UDP
}
/// This structure is used to provide hints when fetching addresses for a
/// remote host to control how the lookup is performed.
///
/// For details on these fields, see their corresponding definitions via
/// `man -s 3 getaddrinfo`
pub struct Hint {
pub family: uint,
pub socktype: Option<SocketType>,
pub protocol: Option<Protocol>,
pub flags: uint,
}
pub struct Info {
pub address: SocketAddr,
pub family: uint,
pub socktype: Option<SocketType>,
pub protocol: Option<Protocol>,
pub flags: uint,
}
/// Easy name resolution. Given a hostname, returns the list of IP addresses for
/// that hostname.
pub fn get_host_addresses(host: &str) -> IoResult<Vec<IpAddr>> {
lookup(Some(host), None, None).map(|a| a.into_iter().map(|i| i.address.ip).collect())
}
/// Full-fledged resolution. This function will perform a synchronous call to
/// getaddrinfo, controlled by the parameters
///
/// # Arguments
///
/// * hostname - an optional hostname to lookup against
/// * servname - an optional service name, listed in the system services
/// * hint - see the hint structure, and "man -s 3 getaddrinfo", for how this
/// controls lookup
///
/// FIXME: this is not public because the `Hint` structure is not ready for public
/// consumption just yet.
#[allow(unused_variables)]
fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option<Hint>)
-> IoResult<Vec<Info>> {
sys::addrinfo::get_host_addresses(hostname, servname, hint)
}
// Ignored on android since we cannot give tcp/ip
// permission without help of apk
#[cfg(all(test, not(target_os = "android")))]
mod test {
use prelude::*;
use super::*;
use io::net::ip::*;
#[test]
fn dns_smoke_test() {
let ipaddrs = get_host_addresses("localhost").unwrap();
let mut found_local = false;
let local_addr = &Ipv4Addr(127, 0, 0, 1);
for addr in ipaddrs.iter() {
found_local = found_local || addr == local_addr;
}
assert!(found_local);
}
#[ignore]
#[test]
fn issue_10663() {
// Something should happen here, but this certainly shouldn't cause
// everything to die. The actual outcome we don't care too much about.
get_host_addresses("example.com").unwrap();
}
}
| Flag | identifier_name |
addrinfo.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.
/*!
Synchronous DNS Resolution
Contains the functionality to perform DNS resolution in a style related to
getaddrinfo()
*/
#![allow(missing_docs)]
use iter::Iterator;
use io::{IoResult};
use io::net::ip::{SocketAddr, IpAddr};
use option::{Option, Some, None};
use sys;
use vec::Vec;
/// Hints to the types of sockets that are desired when looking up hosts
pub enum SocketType {
Stream, Datagram, Raw
}
/// Flags which can be or'd into the `flags` field of a `Hint`. These are used
/// to manipulate how a query is performed.
///
/// The meaning of each of these flags can be found with `man -s 3 getaddrinfo`
pub enum Flag {
AddrConfig,
All,
CanonName,
NumericHost,
NumericServ,
Passive,
V4Mapped,
}
/// A transport protocol associated with either a hint or a return value of
/// `lookup`
pub enum Protocol {
TCP, UDP
}
/// This structure is used to provide hints when fetching addresses for a
/// remote host to control how the lookup is performed.
///
/// For details on these fields, see their corresponding definitions via
/// `man -s 3 getaddrinfo`
pub struct Hint {
pub family: uint,
pub socktype: Option<SocketType>,
pub protocol: Option<Protocol>,
pub flags: uint,
}
pub struct Info {
pub address: SocketAddr,
pub family: uint,
pub socktype: Option<SocketType>,
pub protocol: Option<Protocol>,
pub flags: uint,
}
/// Easy name resolution. Given a hostname, returns the list of IP addresses for
/// that hostname.
pub fn get_host_addresses(host: &str) -> IoResult<Vec<IpAddr>> {
lookup(Some(host), None, None).map(|a| a.into_iter().map(|i| i.address.ip).collect())
}
/// Full-fledged resolution. This function will perform a synchronous call to
/// getaddrinfo, controlled by the parameters
///
/// # Arguments
///
/// * hostname - an optional hostname to lookup against
/// * servname - an optional service name, listed in the system services
/// * hint - see the hint structure, and "man -s 3 getaddrinfo", for how this
/// controls lookup
///
/// FIXME: this is not public because the `Hint` structure is not ready for public
/// consumption just yet.
#[allow(unused_variables)]
fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option<Hint>)
-> IoResult<Vec<Info>> |
// Ignored on android since we cannot give tcp/ip
// permission without help of apk
#[cfg(all(test, not(target_os = "android")))]
mod test {
use prelude::*;
use super::*;
use io::net::ip::*;
#[test]
fn dns_smoke_test() {
let ipaddrs = get_host_addresses("localhost").unwrap();
let mut found_local = false;
let local_addr = &Ipv4Addr(127, 0, 0, 1);
for addr in ipaddrs.iter() {
found_local = found_local || addr == local_addr;
}
assert!(found_local);
}
#[ignore]
#[test]
fn issue_10663() {
// Something should happen here, but this certainly shouldn't cause
// everything to die. The actual outcome we don't care too much about.
get_host_addresses("example.com").unwrap();
}
}
| {
sys::addrinfo::get_host_addresses(hostname, servname, hint)
} | identifier_body |
addrinfo.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 |
Synchronous DNS Resolution
Contains the functionality to perform DNS resolution in a style related to
getaddrinfo()
*/
#![allow(missing_docs)]
use iter::Iterator;
use io::{IoResult};
use io::net::ip::{SocketAddr, IpAddr};
use option::{Option, Some, None};
use sys;
use vec::Vec;
/// Hints to the types of sockets that are desired when looking up hosts
pub enum SocketType {
Stream, Datagram, Raw
}
/// Flags which can be or'd into the `flags` field of a `Hint`. These are used
/// to manipulate how a query is performed.
///
/// The meaning of each of these flags can be found with `man -s 3 getaddrinfo`
pub enum Flag {
AddrConfig,
All,
CanonName,
NumericHost,
NumericServ,
Passive,
V4Mapped,
}
/// A transport protocol associated with either a hint or a return value of
/// `lookup`
pub enum Protocol {
TCP, UDP
}
/// This structure is used to provide hints when fetching addresses for a
/// remote host to control how the lookup is performed.
///
/// For details on these fields, see their corresponding definitions via
/// `man -s 3 getaddrinfo`
pub struct Hint {
pub family: uint,
pub socktype: Option<SocketType>,
pub protocol: Option<Protocol>,
pub flags: uint,
}
pub struct Info {
pub address: SocketAddr,
pub family: uint,
pub socktype: Option<SocketType>,
pub protocol: Option<Protocol>,
pub flags: uint,
}
/// Easy name resolution. Given a hostname, returns the list of IP addresses for
/// that hostname.
pub fn get_host_addresses(host: &str) -> IoResult<Vec<IpAddr>> {
lookup(Some(host), None, None).map(|a| a.into_iter().map(|i| i.address.ip).collect())
}
/// Full-fledged resolution. This function will perform a synchronous call to
/// getaddrinfo, controlled by the parameters
///
/// # Arguments
///
/// * hostname - an optional hostname to lookup against
/// * servname - an optional service name, listed in the system services
/// * hint - see the hint structure, and "man -s 3 getaddrinfo", for how this
/// controls lookup
///
/// FIXME: this is not public because the `Hint` structure is not ready for public
/// consumption just yet.
#[allow(unused_variables)]
fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option<Hint>)
-> IoResult<Vec<Info>> {
sys::addrinfo::get_host_addresses(hostname, servname, hint)
}
// Ignored on android since we cannot give tcp/ip
// permission without help of apk
#[cfg(all(test, not(target_os = "android")))]
mod test {
use prelude::*;
use super::*;
use io::net::ip::*;
#[test]
fn dns_smoke_test() {
let ipaddrs = get_host_addresses("localhost").unwrap();
let mut found_local = false;
let local_addr = &Ipv4Addr(127, 0, 0, 1);
for addr in ipaddrs.iter() {
found_local = found_local || addr == local_addr;
}
assert!(found_local);
}
#[ignore]
#[test]
fn issue_10663() {
// Something should happen here, but this certainly shouldn't cause
// everything to die. The actual outcome we don't care too much about.
get_host_addresses("example.com").unwrap();
}
} | // except according to those terms.
/*! | random_line_split |
const-err3.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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(rustc_attrs)]
#![deny(const_err)]
fn black_box<T>(_: T) {
unimplemented!()
}
fn main() {
let b = 200u8 + 200u8 + 200u8;
//~^ ERROR const_err
let c = 200u8 * 4;
//~^ ERROR const_err
let d = 42u8 - (42u8 + 1);
//~^ ERROR const_err
let _e = [5u8][1];
//~^ ERROR const_err
black_box(b);
black_box(c);
black_box(d);
} | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
const-err3.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(rustc_attrs)]
#![deny(const_err)]
fn black_box<T>(_: T) |
fn main() {
let b = 200u8 + 200u8 + 200u8;
//~^ ERROR const_err
let c = 200u8 * 4;
//~^ ERROR const_err
let d = 42u8 - (42u8 + 1);
//~^ ERROR const_err
let _e = [5u8][1];
//~^ ERROR const_err
black_box(b);
black_box(c);
black_box(d);
}
| {
unimplemented!()
} | identifier_body |
const-err3.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(rustc_attrs)]
#![deny(const_err)]
fn | <T>(_: T) {
unimplemented!()
}
fn main() {
let b = 200u8 + 200u8 + 200u8;
//~^ ERROR const_err
let c = 200u8 * 4;
//~^ ERROR const_err
let d = 42u8 - (42u8 + 1);
//~^ ERROR const_err
let _e = [5u8][1];
//~^ ERROR const_err
black_box(b);
black_box(c);
black_box(d);
}
| black_box | identifier_name |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)
#![allow(non_snake_case)]
#![doc(primitive = "char")]
use mem::transmute;
use option::{None, Option, Some};
use iter::range_step;
use collections::Collection;
// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8 = 0b1000_0000u8;
static TAG_TWO_B: u8 = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8 = 0b1111_0000u8;
static MAX_ONE_B: u32 = 0x80u32;
static MAX_TWO_B: u32 = 0x800u32;
static MAX_THREE_B: u32 = 0x10000u32;
/*
Lu Uppercase_Letter an uppercase letter
Ll Lowercase_Letter a lowercase letter
Lt Titlecase_Letter a digraphic character, with first part uppercase
Lm Modifier_Letter a modifier letter
Lo Other_Letter other letters, including syllables and ideographs
Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
Mc Spacing_Mark a spacing combining mark (positive advance width)
Me Enclosing_Mark an enclosing combining mark
Nd Decimal_Number a decimal digit
Nl Letter_Number a letterlike numeric character
No Other_Number a numeric character of other type
Pc Connector_Punctuation a connecting punctuation mark, like a tie
Pd Dash_Punctuation a dash or hyphen punctuation mark
Ps Open_Punctuation an opening punctuation mark (of a pair)
Pe Close_Punctuation a closing punctuation mark (of a pair)
Pi Initial_Punctuation an initial quotation mark
Pf Final_Punctuation a final quotation mark
Po Other_Punctuation a punctuation mark of other type
Sm Math_Symbol a symbol of primarily mathematical use
Sc Currency_Symbol a currency sign
Sk Modifier_Symbol a non-letterlike modifier symbol
So Other_Symbol a symbol of other type
Zs Space_Separator a space character (of various non-zero widths)
Zl Line_Separator U+2028 LINE SEPARATOR only
Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
Cc Control a C0 or C1 control code
Cf Format a format control character
Cs Surrogate a surrogate code point
Co Private_Use a private-use character
Cn Unassigned a reserved unassigned code point or a noncharacter
*/
/// The highest valid code point
pub const MAX: char = '\U0010ffff';
/// Converts from `u32` to a `char`
#[inline]
pub fn from_u32(i: u32) -> Option<char> {
// catch out-of-bounds and surrogates
if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
None
} else {
Some(unsafe { transmute(i) })
}
}
///
/// Checks if a `char` parses as a numeric digit in the given radix
///
/// Compared to `is_digit()`, this function only recognizes the
/// characters `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a `radix` > 36.
///
/// # Note
///
/// This just wraps `to_digit()`.
///
#[inline]
pub fn is_digit_radix(c: char, radix: uint) -> bool {
match to_digit(c, radix) {
Some(_) => true,
None => false,
}
}
///
/// Converts a `char` to the corresponding digit
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value
/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
/// 'b' or 'B', 11, etc. Returns none if the `char` does not
/// refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a `radix` outside the range `[0..36]`.
///
#[inline]
pub fn to_digit(c: char, radix: uint) -> Option<uint> {
if radix > 36 {
fail!("to_digit: radix is too high (maximum 36)");
}
let val = match c {
'0'... '9' => c as uint - ('0' as uint),
'a'... 'z' => c as uint + 10u - ('a' as uint),
'A'... 'Z' => c as uint + 10u - ('A' as uint),
_ => return None,
};
if val < radix { Some(val) }
else { None }
}
///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given an `radix` > 36.
///
#[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 {
fail!("from_digit: radix is to high (maximum 36)");
}
if num < radix {
unsafe {
if num < 10 {
Some(transmute(('0' as uint + num) as u32))
} else {
Some(transmute(('a' as uint + num - 10u) as u32))
}
}
} else {
None
}
}
///
/// Returns the hexadecimal Unicode escape of a `char`
///
/// The rules are as follows:
///
/// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
/// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
/// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
///
pub fn escape_unicode(c: char, f: |char|) {
// avoid calling str::to_str_radix because we don't really need to allocate
// here.
f('\\');
let pad = match () {
_ if c <= '\xff' => { f('x'); 2 }
_ if c <= '\uffff' => { f('u'); 4 }
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0... 9 => { f(transmute('0' as i32 + i)); }
i => { f(transmute('a' as i32 + (i - 10))); }
}
}
}
}
///
/// Returns a 'default' ASCII and C++11-like literal escape of a `char`
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// - Single-quote, double-quote and backslash chars are backslash-escaped.
/// - Any other chars in the range [0x20,0x7e] are not escaped.
/// - Any other chars are given hex Unicode escapes; see `escape_unicode`.
///
pub fn escape_default(c: char, f: |char|) {
match c {
'\t' => { f('\\'); f('t'); }
'\r' => { f('\\'); f('r'); }
'\n' => { f('\\'); f('n'); }
'\\' => { f('\\'); f('\\'); }
'\'' => { f('\\'); f('\''); }
'"' => { f('\\'); f('"'); }
'\x20'... '\x7e' => { f(c); }
_ => c.escape_unicode(f),
}
}
/// Returns the amount of bytes this `char` would need if encoded in UTF-8
#[inline]
pub fn len_utf8_bytes(c: char) -> uint {
let code = c as u32;
match () {
_ if code < MAX_ONE_B => 1u,
_ if code < MAX_TWO_B => 2u,
_ if code < MAX_THREE_B => 3u,
_ => 4u,
}
}
/// Basic `char` manipulations.
pub trait Char {
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_digit()`, this function only recognizes the characters
/// `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn is_digit_radix(&self, radix: uint) -> bool;
/// Converts a character to the corresponding digit.
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value between 0 and
/// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
/// none if the character does not refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a radix outside the range [0..36].
fn to_digit(&self, radix: uint) -> Option<uint>;
/// Converts a number to the character representing it.
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn from_digit(num: uint, radix: uint) -> Option<Self>;
/// Returns the hexadecimal Unicode escape of a character.
///
/// The rules are as follows:
///
/// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
/// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
/// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
fn escape_unicode(&self, f: |char|);
/// Returns a 'default' ASCII and C++11-like literal escape of a
/// character.
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// * Single-quote, double-quote and backslash chars are backslash-
/// escaped.
/// * Any other chars in the range [0x20,0x7e] are not escaped.
/// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
fn escape_default(&self, f: |char|);
/// Returns the amount of bytes this character would need if encoded in
/// UTF-8.
fn len_utf8_bytes(&self) -> uint;
/// Encodes this character as UTF-8 into the provided byte buffer,
/// and then returns the number of bytes written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
/// Encodes this character as UTF-16 into the provided `u16` buffer,
/// and then returns the number of `u16`s written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
}
impl Char for char {
fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
fn escape_default(&self, f: |char|) { escape_default(*self, f) }
#[inline]
fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
#[inline]
fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let code = *self as u32;
if code < MAX_ONE_B && dst.len() >= 1 {
dst[0] = code as u8; | } else if code < MAX_THREE_B && dst.len() >= 3 {
dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(3)
} else if dst.len() >= 4 {
dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(4)
} else {
None
}
}
#[inline]
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let mut ch = *self as u32;
if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 {
// The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16;
Some(1)
} else if dst.len() >= 2 {
// Supplementary planes break into surrogates.
ch -= 0x1_0000_u32;
dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
Some(2)
} else {
None
}
}
} | Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 {
dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(2) | random_line_split |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)
#![allow(non_snake_case)]
#![doc(primitive = "char")]
use mem::transmute;
use option::{None, Option, Some};
use iter::range_step;
use collections::Collection;
// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8 = 0b1000_0000u8;
static TAG_TWO_B: u8 = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8 = 0b1111_0000u8;
static MAX_ONE_B: u32 = 0x80u32;
static MAX_TWO_B: u32 = 0x800u32;
static MAX_THREE_B: u32 = 0x10000u32;
/*
Lu Uppercase_Letter an uppercase letter
Ll Lowercase_Letter a lowercase letter
Lt Titlecase_Letter a digraphic character, with first part uppercase
Lm Modifier_Letter a modifier letter
Lo Other_Letter other letters, including syllables and ideographs
Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
Mc Spacing_Mark a spacing combining mark (positive advance width)
Me Enclosing_Mark an enclosing combining mark
Nd Decimal_Number a decimal digit
Nl Letter_Number a letterlike numeric character
No Other_Number a numeric character of other type
Pc Connector_Punctuation a connecting punctuation mark, like a tie
Pd Dash_Punctuation a dash or hyphen punctuation mark
Ps Open_Punctuation an opening punctuation mark (of a pair)
Pe Close_Punctuation a closing punctuation mark (of a pair)
Pi Initial_Punctuation an initial quotation mark
Pf Final_Punctuation a final quotation mark
Po Other_Punctuation a punctuation mark of other type
Sm Math_Symbol a symbol of primarily mathematical use
Sc Currency_Symbol a currency sign
Sk Modifier_Symbol a non-letterlike modifier symbol
So Other_Symbol a symbol of other type
Zs Space_Separator a space character (of various non-zero widths)
Zl Line_Separator U+2028 LINE SEPARATOR only
Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
Cc Control a C0 or C1 control code
Cf Format a format control character
Cs Surrogate a surrogate code point
Co Private_Use a private-use character
Cn Unassigned a reserved unassigned code point or a noncharacter
*/
/// The highest valid code point
pub const MAX: char = '\U0010ffff';
/// Converts from `u32` to a `char`
#[inline]
pub fn from_u32(i: u32) -> Option<char> {
// catch out-of-bounds and surrogates
if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
None
} else {
Some(unsafe { transmute(i) })
}
}
///
/// Checks if a `char` parses as a numeric digit in the given radix
///
/// Compared to `is_digit()`, this function only recognizes the
/// characters `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a `radix` > 36.
///
/// # Note
///
/// This just wraps `to_digit()`.
///
#[inline]
pub fn is_digit_radix(c: char, radix: uint) -> bool {
match to_digit(c, radix) {
Some(_) => true,
None => false,
}
}
///
/// Converts a `char` to the corresponding digit
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value
/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
/// 'b' or 'B', 11, etc. Returns none if the `char` does not
/// refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a `radix` outside the range `[0..36]`.
///
#[inline]
pub fn to_digit(c: char, radix: uint) -> Option<uint> {
if radix > 36 {
fail!("to_digit: radix is too high (maximum 36)");
}
let val = match c {
'0'... '9' => c as uint - ('0' as uint),
'a'... 'z' => c as uint + 10u - ('a' as uint),
'A'... 'Z' => c as uint + 10u - ('A' as uint),
_ => return None,
};
if val < radix { Some(val) }
else { None }
}
///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given an `radix` > 36.
///
#[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 {
fail!("from_digit: radix is to high (maximum 36)");
}
if num < radix {
unsafe {
if num < 10 {
Some(transmute(('0' as uint + num) as u32))
} else {
Some(transmute(('a' as uint + num - 10u) as u32))
}
}
} else {
None
}
}
///
/// Returns the hexadecimal Unicode escape of a `char`
///
/// The rules are as follows:
///
/// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
/// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
/// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
///
pub fn escape_unicode(c: char, f: |char|) {
// avoid calling str::to_str_radix because we don't really need to allocate
// here.
f('\\');
let pad = match () {
_ if c <= '\xff' => { f('x'); 2 }
_ if c <= '\uffff' => { f('u'); 4 }
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0... 9 => { f(transmute('0' as i32 + i)); }
i => { f(transmute('a' as i32 + (i - 10))); }
}
}
}
}
///
/// Returns a 'default' ASCII and C++11-like literal escape of a `char`
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// - Single-quote, double-quote and backslash chars are backslash-escaped.
/// - Any other chars in the range [0x20,0x7e] are not escaped.
/// - Any other chars are given hex Unicode escapes; see `escape_unicode`.
///
pub fn escape_default(c: char, f: |char|) {
match c {
'\t' => { f('\\'); f('t'); }
'\r' => { f('\\'); f('r'); }
'\n' => { f('\\'); f('n'); }
'\\' => { f('\\'); f('\\'); }
'\'' => { f('\\'); f('\''); }
'"' => { f('\\'); f('"'); }
'\x20'... '\x7e' => { f(c); }
_ => c.escape_unicode(f),
}
}
/// Returns the amount of bytes this `char` would need if encoded in UTF-8
#[inline]
pub fn len_utf8_bytes(c: char) -> uint {
let code = c as u32;
match () {
_ if code < MAX_ONE_B => 1u,
_ if code < MAX_TWO_B => 2u,
_ if code < MAX_THREE_B => 3u,
_ => 4u,
}
}
/// Basic `char` manipulations.
pub trait Char {
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_digit()`, this function only recognizes the characters
/// `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn is_digit_radix(&self, radix: uint) -> bool;
/// Converts a character to the corresponding digit.
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value between 0 and
/// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
/// none if the character does not refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a radix outside the range [0..36].
fn to_digit(&self, radix: uint) -> Option<uint>;
/// Converts a number to the character representing it.
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn from_digit(num: uint, radix: uint) -> Option<Self>;
/// Returns the hexadecimal Unicode escape of a character.
///
/// The rules are as follows:
///
/// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
/// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
/// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
fn escape_unicode(&self, f: |char|);
/// Returns a 'default' ASCII and C++11-like literal escape of a
/// character.
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// * Single-quote, double-quote and backslash chars are backslash-
/// escaped.
/// * Any other chars in the range [0x20,0x7e] are not escaped.
/// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
fn escape_default(&self, f: |char|);
/// Returns the amount of bytes this character would need if encoded in
/// UTF-8.
fn len_utf8_bytes(&self) -> uint;
/// Encodes this character as UTF-8 into the provided byte buffer,
/// and then returns the number of bytes written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
/// Encodes this character as UTF-16 into the provided `u16` buffer,
/// and then returns the number of `u16`s written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
}
impl Char for char {
fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
fn escape_default(&self, f: |char|) { escape_default(*self, f) }
#[inline]
fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
#[inline]
fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let code = *self as u32;
if code < MAX_ONE_B && dst.len() >= 1 {
dst[0] = code as u8;
Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 {
dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(2)
} else if code < MAX_THREE_B && dst.len() >= 3 {
dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(3)
} else if dst.len() >= 4 {
dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(4)
} else {
None
}
}
#[inline]
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let mut ch = *self as u32;
if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 | else if dst.len() >= 2 {
// Supplementary planes break into surrogates.
ch -= 0x1_0000_u32;
dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
Some(2)
} else {
None
}
}
}
| {
// The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16;
Some(1)
} | conditional_block |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)
#![allow(non_snake_case)]
#![doc(primitive = "char")]
use mem::transmute;
use option::{None, Option, Some};
use iter::range_step;
use collections::Collection;
// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8 = 0b1000_0000u8;
static TAG_TWO_B: u8 = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8 = 0b1111_0000u8;
static MAX_ONE_B: u32 = 0x80u32;
static MAX_TWO_B: u32 = 0x800u32;
static MAX_THREE_B: u32 = 0x10000u32;
/*
Lu Uppercase_Letter an uppercase letter
Ll Lowercase_Letter a lowercase letter
Lt Titlecase_Letter a digraphic character, with first part uppercase
Lm Modifier_Letter a modifier letter
Lo Other_Letter other letters, including syllables and ideographs
Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
Mc Spacing_Mark a spacing combining mark (positive advance width)
Me Enclosing_Mark an enclosing combining mark
Nd Decimal_Number a decimal digit
Nl Letter_Number a letterlike numeric character
No Other_Number a numeric character of other type
Pc Connector_Punctuation a connecting punctuation mark, like a tie
Pd Dash_Punctuation a dash or hyphen punctuation mark
Ps Open_Punctuation an opening punctuation mark (of a pair)
Pe Close_Punctuation a closing punctuation mark (of a pair)
Pi Initial_Punctuation an initial quotation mark
Pf Final_Punctuation a final quotation mark
Po Other_Punctuation a punctuation mark of other type
Sm Math_Symbol a symbol of primarily mathematical use
Sc Currency_Symbol a currency sign
Sk Modifier_Symbol a non-letterlike modifier symbol
So Other_Symbol a symbol of other type
Zs Space_Separator a space character (of various non-zero widths)
Zl Line_Separator U+2028 LINE SEPARATOR only
Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
Cc Control a C0 or C1 control code
Cf Format a format control character
Cs Surrogate a surrogate code point
Co Private_Use a private-use character
Cn Unassigned a reserved unassigned code point or a noncharacter
*/
/// The highest valid code point
pub const MAX: char = '\U0010ffff';
/// Converts from `u32` to a `char`
#[inline]
pub fn from_u32(i: u32) -> Option<char> {
// catch out-of-bounds and surrogates
if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
None
} else {
Some(unsafe { transmute(i) })
}
}
///
/// Checks if a `char` parses as a numeric digit in the given radix
///
/// Compared to `is_digit()`, this function only recognizes the
/// characters `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a `radix` > 36.
///
/// # Note
///
/// This just wraps `to_digit()`.
///
#[inline]
pub fn is_digit_radix(c: char, radix: uint) -> bool {
match to_digit(c, radix) {
Some(_) => true,
None => false,
}
}
///
/// Converts a `char` to the corresponding digit
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value
/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
/// 'b' or 'B', 11, etc. Returns none if the `char` does not
/// refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a `radix` outside the range `[0..36]`.
///
#[inline]
pub fn to_digit(c: char, radix: uint) -> Option<uint> {
if radix > 36 {
fail!("to_digit: radix is too high (maximum 36)");
}
let val = match c {
'0'... '9' => c as uint - ('0' as uint),
'a'... 'z' => c as uint + 10u - ('a' as uint),
'A'... 'Z' => c as uint + 10u - ('A' as uint),
_ => return None,
};
if val < radix { Some(val) }
else { None }
}
///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given an `radix` > 36.
///
#[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 {
fail!("from_digit: radix is to high (maximum 36)");
}
if num < radix {
unsafe {
if num < 10 {
Some(transmute(('0' as uint + num) as u32))
} else {
Some(transmute(('a' as uint + num - 10u) as u32))
}
}
} else {
None
}
}
///
/// Returns the hexadecimal Unicode escape of a `char`
///
/// The rules are as follows:
///
/// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
/// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
/// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
///
pub fn escape_unicode(c: char, f: |char|) {
// avoid calling str::to_str_radix because we don't really need to allocate
// here.
f('\\');
let pad = match () {
_ if c <= '\xff' => { f('x'); 2 }
_ if c <= '\uffff' => { f('u'); 4 }
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0... 9 => { f(transmute('0' as i32 + i)); }
i => { f(transmute('a' as i32 + (i - 10))); }
}
}
}
}
///
/// Returns a 'default' ASCII and C++11-like literal escape of a `char`
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// - Single-quote, double-quote and backslash chars are backslash-escaped.
/// - Any other chars in the range [0x20,0x7e] are not escaped.
/// - Any other chars are given hex Unicode escapes; see `escape_unicode`.
///
pub fn escape_default(c: char, f: |char|) {
match c {
'\t' => { f('\\'); f('t'); }
'\r' => { f('\\'); f('r'); }
'\n' => { f('\\'); f('n'); }
'\\' => { f('\\'); f('\\'); }
'\'' => { f('\\'); f('\''); }
'"' => { f('\\'); f('"'); }
'\x20'... '\x7e' => { f(c); }
_ => c.escape_unicode(f),
}
}
/// Returns the amount of bytes this `char` would need if encoded in UTF-8
#[inline]
pub fn len_utf8_bytes(c: char) -> uint {
let code = c as u32;
match () {
_ if code < MAX_ONE_B => 1u,
_ if code < MAX_TWO_B => 2u,
_ if code < MAX_THREE_B => 3u,
_ => 4u,
}
}
/// Basic `char` manipulations.
pub trait Char {
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_digit()`, this function only recognizes the characters
/// `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn is_digit_radix(&self, radix: uint) -> bool;
/// Converts a character to the corresponding digit.
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value between 0 and
/// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
/// none if the character does not refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a radix outside the range [0..36].
fn to_digit(&self, radix: uint) -> Option<uint>;
/// Converts a number to the character representing it.
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn from_digit(num: uint, radix: uint) -> Option<Self>;
/// Returns the hexadecimal Unicode escape of a character.
///
/// The rules are as follows:
///
/// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
/// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
/// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
fn escape_unicode(&self, f: |char|);
/// Returns a 'default' ASCII and C++11-like literal escape of a
/// character.
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// * Single-quote, double-quote and backslash chars are backslash-
/// escaped.
/// * Any other chars in the range [0x20,0x7e] are not escaped.
/// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
fn escape_default(&self, f: |char|);
/// Returns the amount of bytes this character would need if encoded in
/// UTF-8.
fn len_utf8_bytes(&self) -> uint;
/// Encodes this character as UTF-8 into the provided byte buffer,
/// and then returns the number of bytes written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
/// Encodes this character as UTF-16 into the provided `u16` buffer,
/// and then returns the number of `u16`s written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
}
impl Char for char {
fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
fn escape_default(&self, f: |char|) { escape_default(*self, f) }
#[inline]
fn | (&self) -> uint { len_utf8_bytes(*self) }
#[inline]
fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let code = *self as u32;
if code < MAX_ONE_B && dst.len() >= 1 {
dst[0] = code as u8;
Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 {
dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(2)
} else if code < MAX_THREE_B && dst.len() >= 3 {
dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(3)
} else if dst.len() >= 4 {
dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(4)
} else {
None
}
}
#[inline]
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let mut ch = *self as u32;
if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 {
// The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16;
Some(1)
} else if dst.len() >= 2 {
// Supplementary planes break into surrogates.
ch -= 0x1_0000_u32;
dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
Some(2)
} else {
None
}
}
}
| len_utf8_bytes | identifier_name |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)
#![allow(non_snake_case)]
#![doc(primitive = "char")]
use mem::transmute;
use option::{None, Option, Some};
use iter::range_step;
use collections::Collection;
// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8 = 0b1000_0000u8;
static TAG_TWO_B: u8 = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8 = 0b1111_0000u8;
static MAX_ONE_B: u32 = 0x80u32;
static MAX_TWO_B: u32 = 0x800u32;
static MAX_THREE_B: u32 = 0x10000u32;
/*
Lu Uppercase_Letter an uppercase letter
Ll Lowercase_Letter a lowercase letter
Lt Titlecase_Letter a digraphic character, with first part uppercase
Lm Modifier_Letter a modifier letter
Lo Other_Letter other letters, including syllables and ideographs
Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
Mc Spacing_Mark a spacing combining mark (positive advance width)
Me Enclosing_Mark an enclosing combining mark
Nd Decimal_Number a decimal digit
Nl Letter_Number a letterlike numeric character
No Other_Number a numeric character of other type
Pc Connector_Punctuation a connecting punctuation mark, like a tie
Pd Dash_Punctuation a dash or hyphen punctuation mark
Ps Open_Punctuation an opening punctuation mark (of a pair)
Pe Close_Punctuation a closing punctuation mark (of a pair)
Pi Initial_Punctuation an initial quotation mark
Pf Final_Punctuation a final quotation mark
Po Other_Punctuation a punctuation mark of other type
Sm Math_Symbol a symbol of primarily mathematical use
Sc Currency_Symbol a currency sign
Sk Modifier_Symbol a non-letterlike modifier symbol
So Other_Symbol a symbol of other type
Zs Space_Separator a space character (of various non-zero widths)
Zl Line_Separator U+2028 LINE SEPARATOR only
Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
Cc Control a C0 or C1 control code
Cf Format a format control character
Cs Surrogate a surrogate code point
Co Private_Use a private-use character
Cn Unassigned a reserved unassigned code point or a noncharacter
*/
/// The highest valid code point
pub const MAX: char = '\U0010ffff';
/// Converts from `u32` to a `char`
#[inline]
pub fn from_u32(i: u32) -> Option<char> {
// catch out-of-bounds and surrogates
if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
None
} else {
Some(unsafe { transmute(i) })
}
}
///
/// Checks if a `char` parses as a numeric digit in the given radix
///
/// Compared to `is_digit()`, this function only recognizes the
/// characters `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a `radix` > 36.
///
/// # Note
///
/// This just wraps `to_digit()`.
///
#[inline]
pub fn is_digit_radix(c: char, radix: uint) -> bool {
match to_digit(c, radix) {
Some(_) => true,
None => false,
}
}
///
/// Converts a `char` to the corresponding digit
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value
/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
/// 'b' or 'B', 11, etc. Returns none if the `char` does not
/// refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a `radix` outside the range `[0..36]`.
///
#[inline]
pub fn to_digit(c: char, radix: uint) -> Option<uint> {
if radix > 36 {
fail!("to_digit: radix is too high (maximum 36)");
}
let val = match c {
'0'... '9' => c as uint - ('0' as uint),
'a'... 'z' => c as uint + 10u - ('a' as uint),
'A'... 'Z' => c as uint + 10u - ('A' as uint),
_ => return None,
};
if val < radix { Some(val) }
else { None }
}
///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given an `radix` > 36.
///
#[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 {
fail!("from_digit: radix is to high (maximum 36)");
}
if num < radix {
unsafe {
if num < 10 {
Some(transmute(('0' as uint + num) as u32))
} else {
Some(transmute(('a' as uint + num - 10u) as u32))
}
}
} else {
None
}
}
///
/// Returns the hexadecimal Unicode escape of a `char`
///
/// The rules are as follows:
///
/// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
/// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
/// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
///
pub fn escape_unicode(c: char, f: |char|) |
///
/// Returns a 'default' ASCII and C++11-like literal escape of a `char`
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// - Single-quote, double-quote and backslash chars are backslash-escaped.
/// - Any other chars in the range [0x20,0x7e] are not escaped.
/// - Any other chars are given hex Unicode escapes; see `escape_unicode`.
///
pub fn escape_default(c: char, f: |char|) {
match c {
'\t' => { f('\\'); f('t'); }
'\r' => { f('\\'); f('r'); }
'\n' => { f('\\'); f('n'); }
'\\' => { f('\\'); f('\\'); }
'\'' => { f('\\'); f('\''); }
'"' => { f('\\'); f('"'); }
'\x20'... '\x7e' => { f(c); }
_ => c.escape_unicode(f),
}
}
/// Returns the amount of bytes this `char` would need if encoded in UTF-8
#[inline]
pub fn len_utf8_bytes(c: char) -> uint {
let code = c as u32;
match () {
_ if code < MAX_ONE_B => 1u,
_ if code < MAX_TWO_B => 2u,
_ if code < MAX_THREE_B => 3u,
_ => 4u,
}
}
/// Basic `char` manipulations.
pub trait Char {
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_digit()`, this function only recognizes the characters
/// `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn is_digit_radix(&self, radix: uint) -> bool;
/// Converts a character to the corresponding digit.
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value between 0 and
/// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
/// none if the character does not refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a radix outside the range [0..36].
fn to_digit(&self, radix: uint) -> Option<uint>;
/// Converts a number to the character representing it.
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn from_digit(num: uint, radix: uint) -> Option<Self>;
/// Returns the hexadecimal Unicode escape of a character.
///
/// The rules are as follows:
///
/// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
/// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
/// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
fn escape_unicode(&self, f: |char|);
/// Returns a 'default' ASCII and C++11-like literal escape of a
/// character.
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// * Single-quote, double-quote and backslash chars are backslash-
/// escaped.
/// * Any other chars in the range [0x20,0x7e] are not escaped.
/// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
fn escape_default(&self, f: |char|);
/// Returns the amount of bytes this character would need if encoded in
/// UTF-8.
fn len_utf8_bytes(&self) -> uint;
/// Encodes this character as UTF-8 into the provided byte buffer,
/// and then returns the number of bytes written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
/// Encodes this character as UTF-16 into the provided `u16` buffer,
/// and then returns the number of `u16`s written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
}
impl Char for char {
fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
fn escape_default(&self, f: |char|) { escape_default(*self, f) }
#[inline]
fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
#[inline]
fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let code = *self as u32;
if code < MAX_ONE_B && dst.len() >= 1 {
dst[0] = code as u8;
Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 {
dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(2)
} else if code < MAX_THREE_B && dst.len() >= 3 {
dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(3)
} else if dst.len() >= 4 {
dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(4)
} else {
None
}
}
#[inline]
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let mut ch = *self as u32;
if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 {
// The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16;
Some(1)
} else if dst.len() >= 2 {
// Supplementary planes break into surrogates.
ch -= 0x1_0000_u32;
dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
Some(2)
} else {
None
}
}
}
| {
// avoid calling str::to_str_radix because we don't really need to allocate
// here.
f('\\');
let pad = match () {
_ if c <= '\xff' => { f('x'); 2 }
_ if c <= '\uffff' => { f('u'); 4 }
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0 ... 9 => { f(transmute('0' as i32 + i)); }
i => { f(transmute('a' as i32 + (i - 10))); }
}
}
}
} | identifier_body |
cninetyninehexfloatf.rs | //! formatter for %a %F C99 Hex-floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, primitive_to_str_common};
use super::base_conv;
use super::base_conv::RadixDef;
pub struct CninetyNineHexFloatf {
as_num: f64,
}
impl CninetyNineHexFloatf {
pub fn new() -> CninetyNineHexFloatf {
CninetyNineHexFloatf { as_num: 0.0 }
}
}
impl Formatter for CninetyNineHexFloatf {
fn get_primitive(&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str)
-> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(&str_in,
inprefix,
Some(second_field as usize),
None,
true);
let f = get_primitive_hex(inprefix,
&str_in[inprefix.offset..],
&analysis,
second_field as usize,
*field.field_char == 'A');
Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
// c99 hex has unique requirements of all floating point subs in pretty much every part of building a primitive, from prefix and suffix to need for base conversion (in all other cases if you don't have decimal you must have decimal, here it's the other way around)
// on the todo list is to have a trait for get_primitive that is implemented by each float formatter and can override a default. when that happens we can take the parts of get_primitive_dec specific to dec and spin them out to their own functions that can be overriden.
#[allow(unused_variables)]
#[allow(unused_assignments)]
fn get_primitive_hex(inprefix: &InPrefix,
str_in: &str,
analysis: &FloatAnalysis,
last_dec_place: usize,
capitalized: bool)
-> FormatPrimitive {
let mut f: FormatPrimitive = Default::default();
f.prefix = Some(String::from(if inprefix.sign == -1 {
"-0x"
} else {
"0x"
}));
// assign the digits before and after the decimal points
// to separate slices. If no digits after decimal point,
// assign 0
let (mut first_segment_raw, second_segment_raw) = match analysis.decimal_pos {
Some(pos) => (&str_in[..pos], &str_in[pos + 1..]),
None => (&str_in[..], "0"),
};
if first_segment_raw.len() == 0 {
first_segment_raw = "0";
}
// convert to string, hexifying if input is in dec.
// let (first_segment, second_segment) =
// match inprefix.radix_in {
// Base::Ten => {
// (to_hex(first_segment_raw, true),
// to_hex(second_segment_raw, false))
// }
// _ => {
// (String::from(first_segment_raw),
// String::from(second_segment_raw))
// }
// };
//
//
// f.pre_decimal = Some(first_segment);
// f.post_decimal = Some(second_segment);
//
// TODO actual conversion, make sure to get back mantissa.
// for hex to hex, it's really just a matter of moving the
// decimal point and calculating the mantissa by its initial
// position and its moves, with every position counting for
// the addition or subtraction of 4 (2**4, because 4 bits in a hex digit)
// to the exponent.
// decimal's going to be a little more complicated. correct simulation
// of glibc will require after-decimal division to a specified precisino.
// the difficult part of this (arrnum_int_div_step) is already implemented.
// the hex float name may be a bit misleading in terms of how to go about the
// conversion. The best way to do it is to just convert the floatnum
// directly to base 2 and then at the end translate back to hex.
let mantissa = 0;
f.suffix = Some({
let ind = if capitalized {
"P"
} else {
"p"
};
if mantissa >= 0 {
format!("{}+{}", ind, mantissa)
} else {
format!("{}{}", ind, mantissa)
}
});
f
}
fn | (src: &str, before_decimal: bool) -> String {
let rten = base_conv::RadixTen;
let rhex = base_conv::RadixHex;
if before_decimal {
base_conv::base_conv_str(src, &rten, &rhex)
} else {
let as_arrnum_ten = base_conv::str_to_arrnum(src, &rten);
let s = format!("{}",
base_conv::base_conv_float(&as_arrnum_ten, rten.get_max(), rhex.get_max()));
if s.len() > 2 {
String::from(&s[2..])
} else {
// zero
s
}
}
}
| to_hex | identifier_name |
cninetyninehexfloatf.rs | //! formatter for %a %F C99 Hex-floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, primitive_to_str_common};
use super::base_conv;
use super::base_conv::RadixDef;
pub struct CninetyNineHexFloatf {
as_num: f64,
}
impl CninetyNineHexFloatf {
pub fn new() -> CninetyNineHexFloatf {
CninetyNineHexFloatf { as_num: 0.0 }
}
}
impl Formatter for CninetyNineHexFloatf {
fn get_primitive(&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str)
-> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(&str_in,
inprefix,
Some(second_field as usize),
None,
true);
let f = get_primitive_hex(inprefix,
&str_in[inprefix.offset..],
&analysis,
second_field as usize,
*field.field_char == 'A');
Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
// c99 hex has unique requirements of all floating point subs in pretty much every part of building a primitive, from prefix and suffix to need for base conversion (in all other cases if you don't have decimal you must have decimal, here it's the other way around)
// on the todo list is to have a trait for get_primitive that is implemented by each float formatter and can override a default. when that happens we can take the parts of get_primitive_dec specific to dec and spin them out to their own functions that can be overriden.
#[allow(unused_variables)]
#[allow(unused_assignments)]
fn get_primitive_hex(inprefix: &InPrefix,
str_in: &str,
analysis: &FloatAnalysis,
last_dec_place: usize,
capitalized: bool)
-> FormatPrimitive {
let mut f: FormatPrimitive = Default::default();
f.prefix = Some(String::from(if inprefix.sign == -1 {
"-0x"
} else {
"0x" | // assign 0
let (mut first_segment_raw, second_segment_raw) = match analysis.decimal_pos {
Some(pos) => (&str_in[..pos], &str_in[pos + 1..]),
None => (&str_in[..], "0"),
};
if first_segment_raw.len() == 0 {
first_segment_raw = "0";
}
// convert to string, hexifying if input is in dec.
// let (first_segment, second_segment) =
// match inprefix.radix_in {
// Base::Ten => {
// (to_hex(first_segment_raw, true),
// to_hex(second_segment_raw, false))
// }
// _ => {
// (String::from(first_segment_raw),
// String::from(second_segment_raw))
// }
// };
//
//
// f.pre_decimal = Some(first_segment);
// f.post_decimal = Some(second_segment);
//
// TODO actual conversion, make sure to get back mantissa.
// for hex to hex, it's really just a matter of moving the
// decimal point and calculating the mantissa by its initial
// position and its moves, with every position counting for
// the addition or subtraction of 4 (2**4, because 4 bits in a hex digit)
// to the exponent.
// decimal's going to be a little more complicated. correct simulation
// of glibc will require after-decimal division to a specified precisino.
// the difficult part of this (arrnum_int_div_step) is already implemented.
// the hex float name may be a bit misleading in terms of how to go about the
// conversion. The best way to do it is to just convert the floatnum
// directly to base 2 and then at the end translate back to hex.
let mantissa = 0;
f.suffix = Some({
let ind = if capitalized {
"P"
} else {
"p"
};
if mantissa >= 0 {
format!("{}+{}", ind, mantissa)
} else {
format!("{}{}", ind, mantissa)
}
});
f
}
fn to_hex(src: &str, before_decimal: bool) -> String {
let rten = base_conv::RadixTen;
let rhex = base_conv::RadixHex;
if before_decimal {
base_conv::base_conv_str(src, &rten, &rhex)
} else {
let as_arrnum_ten = base_conv::str_to_arrnum(src, &rten);
let s = format!("{}",
base_conv::base_conv_float(&as_arrnum_ten, rten.get_max(), rhex.get_max()));
if s.len() > 2 {
String::from(&s[2..])
} else {
// zero
s
}
}
} | }));
// assign the digits before and after the decimal points
// to separate slices. If no digits after decimal point, | random_line_split |
cninetyninehexfloatf.rs | //! formatter for %a %F C99 Hex-floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, primitive_to_str_common};
use super::base_conv;
use super::base_conv::RadixDef;
pub struct CninetyNineHexFloatf {
as_num: f64,
}
impl CninetyNineHexFloatf {
pub fn new() -> CninetyNineHexFloatf {
CninetyNineHexFloatf { as_num: 0.0 }
}
}
impl Formatter for CninetyNineHexFloatf {
fn get_primitive(&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str)
-> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(&str_in,
inprefix,
Some(second_field as usize),
None,
true);
let f = get_primitive_hex(inprefix,
&str_in[inprefix.offset..],
&analysis,
second_field as usize,
*field.field_char == 'A');
Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
// c99 hex has unique requirements of all floating point subs in pretty much every part of building a primitive, from prefix and suffix to need for base conversion (in all other cases if you don't have decimal you must have decimal, here it's the other way around)
// on the todo list is to have a trait for get_primitive that is implemented by each float formatter and can override a default. when that happens we can take the parts of get_primitive_dec specific to dec and spin them out to their own functions that can be overriden.
#[allow(unused_variables)]
#[allow(unused_assignments)]
fn get_primitive_hex(inprefix: &InPrefix,
str_in: &str,
analysis: &FloatAnalysis,
last_dec_place: usize,
capitalized: bool)
-> FormatPrimitive {
let mut f: FormatPrimitive = Default::default();
f.prefix = Some(String::from(if inprefix.sign == -1 {
"-0x"
} else {
"0x"
}));
// assign the digits before and after the decimal points
// to separate slices. If no digits after decimal point,
// assign 0
let (mut first_segment_raw, second_segment_raw) = match analysis.decimal_pos {
Some(pos) => (&str_in[..pos], &str_in[pos + 1..]),
None => (&str_in[..], "0"),
};
if first_segment_raw.len() == 0 {
first_segment_raw = "0";
}
// convert to string, hexifying if input is in dec.
// let (first_segment, second_segment) =
// match inprefix.radix_in {
// Base::Ten => {
// (to_hex(first_segment_raw, true),
// to_hex(second_segment_raw, false))
// }
// _ => {
// (String::from(first_segment_raw),
// String::from(second_segment_raw))
// }
// };
//
//
// f.pre_decimal = Some(first_segment);
// f.post_decimal = Some(second_segment);
//
// TODO actual conversion, make sure to get back mantissa.
// for hex to hex, it's really just a matter of moving the
// decimal point and calculating the mantissa by its initial
// position and its moves, with every position counting for
// the addition or subtraction of 4 (2**4, because 4 bits in a hex digit)
// to the exponent.
// decimal's going to be a little more complicated. correct simulation
// of glibc will require after-decimal division to a specified precisino.
// the difficult part of this (arrnum_int_div_step) is already implemented.
// the hex float name may be a bit misleading in terms of how to go about the
// conversion. The best way to do it is to just convert the floatnum
// directly to base 2 and then at the end translate back to hex.
let mantissa = 0;
f.suffix = Some({
let ind = if capitalized {
"P"
} else {
"p"
};
if mantissa >= 0 {
format!("{}+{}", ind, mantissa)
} else {
format!("{}{}", ind, mantissa)
}
});
f
}
fn to_hex(src: &str, before_decimal: bool) -> String | {
let rten = base_conv::RadixTen;
let rhex = base_conv::RadixHex;
if before_decimal {
base_conv::base_conv_str(src, &rten, &rhex)
} else {
let as_arrnum_ten = base_conv::str_to_arrnum(src, &rten);
let s = format!("{}",
base_conv::base_conv_float(&as_arrnum_ten, rten.get_max(), rhex.get_max()));
if s.len() > 2 {
String::from(&s[2..])
} else {
// zero
s
}
}
} | identifier_body |
|
cninetyninehexfloatf.rs | //! formatter for %a %F C99 Hex-floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, primitive_to_str_common};
use super::base_conv;
use super::base_conv::RadixDef;
pub struct CninetyNineHexFloatf {
as_num: f64,
}
impl CninetyNineHexFloatf {
pub fn new() -> CninetyNineHexFloatf {
CninetyNineHexFloatf { as_num: 0.0 }
}
}
impl Formatter for CninetyNineHexFloatf {
fn get_primitive(&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str)
-> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
let analysis = FloatAnalysis::analyze(&str_in,
inprefix,
Some(second_field as usize),
None,
true);
let f = get_primitive_hex(inprefix,
&str_in[inprefix.offset..],
&analysis,
second_field as usize,
*field.field_char == 'A');
Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
// c99 hex has unique requirements of all floating point subs in pretty much every part of building a primitive, from prefix and suffix to need for base conversion (in all other cases if you don't have decimal you must have decimal, here it's the other way around)
// on the todo list is to have a trait for get_primitive that is implemented by each float formatter and can override a default. when that happens we can take the parts of get_primitive_dec specific to dec and spin them out to their own functions that can be overriden.
#[allow(unused_variables)]
#[allow(unused_assignments)]
fn get_primitive_hex(inprefix: &InPrefix,
str_in: &str,
analysis: &FloatAnalysis,
last_dec_place: usize,
capitalized: bool)
-> FormatPrimitive {
let mut f: FormatPrimitive = Default::default();
f.prefix = Some(String::from(if inprefix.sign == -1 {
"-0x"
} else {
"0x"
}));
// assign the digits before and after the decimal points
// to separate slices. If no digits after decimal point,
// assign 0
let (mut first_segment_raw, second_segment_raw) = match analysis.decimal_pos {
Some(pos) => (&str_in[..pos], &str_in[pos + 1..]),
None => (&str_in[..], "0"),
};
if first_segment_raw.len() == 0 {
first_segment_raw = "0";
}
// convert to string, hexifying if input is in dec.
// let (first_segment, second_segment) =
// match inprefix.radix_in {
// Base::Ten => {
// (to_hex(first_segment_raw, true),
// to_hex(second_segment_raw, false))
// }
// _ => {
// (String::from(first_segment_raw),
// String::from(second_segment_raw))
// }
// };
//
//
// f.pre_decimal = Some(first_segment);
// f.post_decimal = Some(second_segment);
//
// TODO actual conversion, make sure to get back mantissa.
// for hex to hex, it's really just a matter of moving the
// decimal point and calculating the mantissa by its initial
// position and its moves, with every position counting for
// the addition or subtraction of 4 (2**4, because 4 bits in a hex digit)
// to the exponent.
// decimal's going to be a little more complicated. correct simulation
// of glibc will require after-decimal division to a specified precisino.
// the difficult part of this (arrnum_int_div_step) is already implemented.
// the hex float name may be a bit misleading in terms of how to go about the
// conversion. The best way to do it is to just convert the floatnum
// directly to base 2 and then at the end translate back to hex.
let mantissa = 0;
f.suffix = Some({
let ind = if capitalized | else {
"p"
};
if mantissa >= 0 {
format!("{}+{}", ind, mantissa)
} else {
format!("{}{}", ind, mantissa)
}
});
f
}
fn to_hex(src: &str, before_decimal: bool) -> String {
let rten = base_conv::RadixTen;
let rhex = base_conv::RadixHex;
if before_decimal {
base_conv::base_conv_str(src, &rten, &rhex)
} else {
let as_arrnum_ten = base_conv::str_to_arrnum(src, &rten);
let s = format!("{}",
base_conv::base_conv_float(&as_arrnum_ten, rten.get_max(), rhex.get_max()));
if s.len() > 2 {
String::from(&s[2..])
} else {
// zero
s
}
}
}
| {
"P"
} | conditional_block |
synonyms.rs | use fnv::FnvHashMap;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error;
use std::path::Path;
#[inline]
pub fn parse_line(line: &str) -> Result<(String, String), Error> |
pub fn load(path: &Path) -> Option<FnvHashMap<String, String>> {
if path.is_file() {
Some(parse_file(&path).unwrap())
} else {
None
}
}
fn parse_file(path: &Path) -> Result<FnvHashMap<String, String>, Error> {
let mut synonyms = FnvHashMap::default();
let f = File::open(path)?;
let file = BufReader::new(&f);
for line in file.lines() {
let line = line.unwrap();
let (word, synonym) = parse_line(&line).unwrap();
synonyms.insert(word, synonym);
}
Ok(synonyms)
}
| {
let v: Vec<&str> = line.split(" ").map(|t| t.trim()).collect();
let (word, synonym) = match v.len() {
2 => (v[0].to_string(), v[1].to_string()),
_ => panic!("Unknown format: {:?}!", &line),
};
Ok((word, synonym))
} | identifier_body |
synonyms.rs | use fnv::FnvHashMap;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error;
use std::path::Path;
#[inline]
pub fn parse_line(line: &str) -> Result<(String, String), Error> {
let v: Vec<&str> = line.split(" ").map(|t| t.trim()).collect();
let (word, synonym) = match v.len() {
2 => (v[0].to_string(), v[1].to_string()),
_ => panic!("Unknown format: {:?}!", &line),
};
Ok((word, synonym))
}
pub fn load(path: &Path) -> Option<FnvHashMap<String, String>> {
if path.is_file() {
Some(parse_file(&path).unwrap())
} else {
None
}
}
fn parse_file(path: &Path) -> Result<FnvHashMap<String, String>, Error> {
let mut synonyms = FnvHashMap::default();
let f = File::open(path)?;
let file = BufReader::new(&f);
for line in file.lines() {
let line = line.unwrap(); |
Ok(synonyms)
} | let (word, synonym) = parse_line(&line).unwrap();
synonyms.insert(word, synonym);
} | random_line_split |
synonyms.rs | use fnv::FnvHashMap;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error;
use std::path::Path;
#[inline]
pub fn parse_line(line: &str) -> Result<(String, String), Error> {
let v: Vec<&str> = line.split(" ").map(|t| t.trim()).collect();
let (word, synonym) = match v.len() {
2 => (v[0].to_string(), v[1].to_string()),
_ => panic!("Unknown format: {:?}!", &line),
};
Ok((word, synonym))
}
pub fn load(path: &Path) -> Option<FnvHashMap<String, String>> {
if path.is_file() {
Some(parse_file(&path).unwrap())
} else {
None
}
}
fn | (path: &Path) -> Result<FnvHashMap<String, String>, Error> {
let mut synonyms = FnvHashMap::default();
let f = File::open(path)?;
let file = BufReader::new(&f);
for line in file.lines() {
let line = line.unwrap();
let (word, synonym) = parse_line(&line).unwrap();
synonyms.insert(word, synonym);
}
Ok(synonyms)
}
| parse_file | identifier_name |
guard.rs | /*!
This module defines request guards for accessing the current game state.
You can use these types in the parameters of the request handler, like so:
```rust,ignore
#[route("/whatever/<foo>")]
fn (foo: usize, game: Game) -> &'static str {
let j = game.jamnum();
...
}
```
These request guards guarantee the existence of a current game: if there
is no current game, the request will fail.
Both of the guard types `Game` and `MutGame` implement `Deref` and the latter
implements `DerefMut` to `GameState`, so you can use them just like you would
a regular `GameState`.
*/
use std::ops::{Deref, DerefMut};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread;
use std::time::Duration;
use rocket;
use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{Request,FromRequest};
use gamestate;
use roster;
/// A request guard for using the current game state, for read-only access.
pub struct Game<'a> { game: RwLockReadGuard<'a, Option<gamestate::GameState>> }
impl<'a> Deref for Game<'a> {
type Target = gamestate::GameState;
fn | (&self) -> &gamestate::GameState { self.game.as_ref().unwrap() }
}
impl<'a, 'r> FromRequest<'a, 'r> for Game<'r> {
type Error = ();
fn from_request(_: &'a Request<'r>) -> rocket::request::Outcome<Game<'r>, ()> {
// TODO: authentication goes here
let game = get_game();
if game.is_none() {
Outcome::Failure((Status::BadRequest, ()))
} else {
Outcome::Success(Game { game: game })
}
}
}
/// A request guard for using the current game state, for read-only access.
pub struct MutGame<'a> { game: RwLockWriteGuard<'a, Option<gamestate::GameState>> }
impl<'a> Deref for MutGame<'a> {
type Target = gamestate::GameState;
fn deref(&self) -> &gamestate::GameState { &self.game.as_ref().unwrap() }
}
impl<'a> DerefMut for MutGame<'a> {
fn deref_mut(&mut self) -> &mut gamestate::GameState { self.game.as_mut().unwrap() }
}
impl<'a, 'r> FromRequest<'a, 'r> for MutGame<'r> {
type Error = ();
fn from_request(_: &'a Request<'r>) -> rocket::request::Outcome<MutGame<'r>, ()> {
// TODO: authentication goes here
let game = get_game_mut();
if game.is_none() {
return rocket::Outcome::Failure((Status::BadRequest, ()))
}
rocket::Outcome::Success(MutGame { game: game })
}
}
/// Start a new game, with the given rosters and time to derby
pub fn start_game(team1: roster::Team, team2: roster::Team, time_to_derby: Duration) -> () {
*CUR_GAME.write().unwrap() = Some(gamestate::GameState::new(team1, team2, time_to_derby));
thread::spawn(move || {
loop {
thread::park_timeout(Duration::new(0, 100_000_000));
let mut guard = get_game_mut();
guard.as_mut().unwrap().tick();
}
});
}
/// Get the current game state for read-only access, in the form of an `RwLockReadGuard`.
/// You probably want to use the Game struct via rocket's FromRequest mechanism.
pub fn get_game<'a>() -> RwLockReadGuard<'a, Option<gamestate::GameState>> {
CUR_GAME.read().unwrap()
}
/// Get the current game state for read-write access, in the form of an `RwLockWriteGuard`.
/// You probably want to use the MutGame struct via rocket's FromRequest mechanism.
pub fn get_game_mut<'a>() -> RwLockWriteGuard<'a, Option<gamestate::GameState>> {
CUR_GAME.write().unwrap()
}
lazy_static! {
static ref CUR_GAME : RwLock<Option<gamestate::GameState>> = RwLock::new(None);
}
| deref | identifier_name |
guard.rs | /*!
This module defines request guards for accessing the current game state.
You can use these types in the parameters of the request handler, like so:
```rust,ignore
#[route("/whatever/<foo>")]
fn (foo: usize, game: Game) -> &'static str {
let j = game.jamnum();
... | is no current game, the request will fail.
Both of the guard types `Game` and `MutGame` implement `Deref` and the latter
implements `DerefMut` to `GameState`, so you can use them just like you would
a regular `GameState`.
*/
use std::ops::{Deref, DerefMut};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread;
use std::time::Duration;
use rocket;
use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{Request,FromRequest};
use gamestate;
use roster;
/// A request guard for using the current game state, for read-only access.
pub struct Game<'a> { game: RwLockReadGuard<'a, Option<gamestate::GameState>> }
impl<'a> Deref for Game<'a> {
type Target = gamestate::GameState;
fn deref(&self) -> &gamestate::GameState { self.game.as_ref().unwrap() }
}
impl<'a, 'r> FromRequest<'a, 'r> for Game<'r> {
type Error = ();
fn from_request(_: &'a Request<'r>) -> rocket::request::Outcome<Game<'r>, ()> {
// TODO: authentication goes here
let game = get_game();
if game.is_none() {
Outcome::Failure((Status::BadRequest, ()))
} else {
Outcome::Success(Game { game: game })
}
}
}
/// A request guard for using the current game state, for read-only access.
pub struct MutGame<'a> { game: RwLockWriteGuard<'a, Option<gamestate::GameState>> }
impl<'a> Deref for MutGame<'a> {
type Target = gamestate::GameState;
fn deref(&self) -> &gamestate::GameState { &self.game.as_ref().unwrap() }
}
impl<'a> DerefMut for MutGame<'a> {
fn deref_mut(&mut self) -> &mut gamestate::GameState { self.game.as_mut().unwrap() }
}
impl<'a, 'r> FromRequest<'a, 'r> for MutGame<'r> {
type Error = ();
fn from_request(_: &'a Request<'r>) -> rocket::request::Outcome<MutGame<'r>, ()> {
// TODO: authentication goes here
let game = get_game_mut();
if game.is_none() {
return rocket::Outcome::Failure((Status::BadRequest, ()))
}
rocket::Outcome::Success(MutGame { game: game })
}
}
/// Start a new game, with the given rosters and time to derby
pub fn start_game(team1: roster::Team, team2: roster::Team, time_to_derby: Duration) -> () {
*CUR_GAME.write().unwrap() = Some(gamestate::GameState::new(team1, team2, time_to_derby));
thread::spawn(move || {
loop {
thread::park_timeout(Duration::new(0, 100_000_000));
let mut guard = get_game_mut();
guard.as_mut().unwrap().tick();
}
});
}
/// Get the current game state for read-only access, in the form of an `RwLockReadGuard`.
/// You probably want to use the Game struct via rocket's FromRequest mechanism.
pub fn get_game<'a>() -> RwLockReadGuard<'a, Option<gamestate::GameState>> {
CUR_GAME.read().unwrap()
}
/// Get the current game state for read-write access, in the form of an `RwLockWriteGuard`.
/// You probably want to use the MutGame struct via rocket's FromRequest mechanism.
pub fn get_game_mut<'a>() -> RwLockWriteGuard<'a, Option<gamestate::GameState>> {
CUR_GAME.write().unwrap()
}
lazy_static! {
static ref CUR_GAME : RwLock<Option<gamestate::GameState>> = RwLock::new(None);
} | }
```
These request guards guarantee the existence of a current game: if there | random_line_split |
guard.rs | /*!
This module defines request guards for accessing the current game state.
You can use these types in the parameters of the request handler, like so:
```rust,ignore
#[route("/whatever/<foo>")]
fn (foo: usize, game: Game) -> &'static str {
let j = game.jamnum();
...
}
```
These request guards guarantee the existence of a current game: if there
is no current game, the request will fail.
Both of the guard types `Game` and `MutGame` implement `Deref` and the latter
implements `DerefMut` to `GameState`, so you can use them just like you would
a regular `GameState`.
*/
use std::ops::{Deref, DerefMut};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread;
use std::time::Duration;
use rocket;
use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{Request,FromRequest};
use gamestate;
use roster;
/// A request guard for using the current game state, for read-only access.
pub struct Game<'a> { game: RwLockReadGuard<'a, Option<gamestate::GameState>> }
impl<'a> Deref for Game<'a> {
type Target = gamestate::GameState;
fn deref(&self) -> &gamestate::GameState { self.game.as_ref().unwrap() }
}
impl<'a, 'r> FromRequest<'a, 'r> for Game<'r> {
type Error = ();
fn from_request(_: &'a Request<'r>) -> rocket::request::Outcome<Game<'r>, ()> {
// TODO: authentication goes here
let game = get_game();
if game.is_none() {
Outcome::Failure((Status::BadRequest, ()))
} else {
Outcome::Success(Game { game: game })
}
}
}
/// A request guard for using the current game state, for read-only access.
pub struct MutGame<'a> { game: RwLockWriteGuard<'a, Option<gamestate::GameState>> }
impl<'a> Deref for MutGame<'a> {
type Target = gamestate::GameState;
fn deref(&self) -> &gamestate::GameState { &self.game.as_ref().unwrap() }
}
impl<'a> DerefMut for MutGame<'a> {
fn deref_mut(&mut self) -> &mut gamestate::GameState { self.game.as_mut().unwrap() }
}
impl<'a, 'r> FromRequest<'a, 'r> for MutGame<'r> {
type Error = ();
fn from_request(_: &'a Request<'r>) -> rocket::request::Outcome<MutGame<'r>, ()> {
// TODO: authentication goes here
let game = get_game_mut();
if game.is_none() |
rocket::Outcome::Success(MutGame { game: game })
}
}
/// Start a new game, with the given rosters and time to derby
pub fn start_game(team1: roster::Team, team2: roster::Team, time_to_derby: Duration) -> () {
*CUR_GAME.write().unwrap() = Some(gamestate::GameState::new(team1, team2, time_to_derby));
thread::spawn(move || {
loop {
thread::park_timeout(Duration::new(0, 100_000_000));
let mut guard = get_game_mut();
guard.as_mut().unwrap().tick();
}
});
}
/// Get the current game state for read-only access, in the form of an `RwLockReadGuard`.
/// You probably want to use the Game struct via rocket's FromRequest mechanism.
pub fn get_game<'a>() -> RwLockReadGuard<'a, Option<gamestate::GameState>> {
CUR_GAME.read().unwrap()
}
/// Get the current game state for read-write access, in the form of an `RwLockWriteGuard`.
/// You probably want to use the MutGame struct via rocket's FromRequest mechanism.
pub fn get_game_mut<'a>() -> RwLockWriteGuard<'a, Option<gamestate::GameState>> {
CUR_GAME.write().unwrap()
}
lazy_static! {
static ref CUR_GAME : RwLock<Option<gamestate::GameState>> = RwLock::new(None);
}
| {
return rocket::Outcome::Failure((Status::BadRequest, ()))
} | conditional_block |
svggraphicselement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::SVGGraphicsElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::node::Node;
use dom::svgelement::SVGElement;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::element_state::ElementState;
#[dom_struct]
pub struct SVGGraphicsElement {
svgelement: SVGElement,
}
impl SVGGraphicsElement {
pub fn new_inherited(tag_name: Atom, prefix: Option<DOMString>,
document: &Document) -> SVGGraphicsElement {
SVGGraphicsElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document)
}
pub fn new_inherited_with_state(state: ElementState, tag_name: Atom,
prefix: Option<DOMString>, document: &Document)
-> SVGGraphicsElement {
SVGGraphicsElement {
svgelement:
SVGElement::new_inherited_with_state(state, tag_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<SVGGraphicsElement> {
Node::reflect_node(box SVGGraphicsElement::new_inherited(local_name, prefix, document),
document,
SVGGraphicsElementBinding::Wrap)
}
}
impl VirtualMethods for SVGGraphicsElement {
fn super_type(&self) -> Option<&VirtualMethods> { | } | Some(self.upcast::<SVGElement>() as &VirtualMethods)
} | random_line_split |
svggraphicselement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::SVGGraphicsElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::node::Node;
use dom::svgelement::SVGElement;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::element_state::ElementState;
#[dom_struct]
pub struct | {
svgelement: SVGElement,
}
impl SVGGraphicsElement {
pub fn new_inherited(tag_name: Atom, prefix: Option<DOMString>,
document: &Document) -> SVGGraphicsElement {
SVGGraphicsElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document)
}
pub fn new_inherited_with_state(state: ElementState, tag_name: Atom,
prefix: Option<DOMString>, document: &Document)
-> SVGGraphicsElement {
SVGGraphicsElement {
svgelement:
SVGElement::new_inherited_with_state(state, tag_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<SVGGraphicsElement> {
Node::reflect_node(box SVGGraphicsElement::new_inherited(local_name, prefix, document),
document,
SVGGraphicsElementBinding::Wrap)
}
}
impl VirtualMethods for SVGGraphicsElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<SVGElement>() as &VirtualMethods)
}
}
| SVGGraphicsElement | identifier_name |
svggraphicselement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::SVGGraphicsElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::node::Node;
use dom::svgelement::SVGElement;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::element_state::ElementState;
#[dom_struct]
pub struct SVGGraphicsElement {
svgelement: SVGElement,
}
impl SVGGraphicsElement {
pub fn new_inherited(tag_name: Atom, prefix: Option<DOMString>,
document: &Document) -> SVGGraphicsElement |
pub fn new_inherited_with_state(state: ElementState, tag_name: Atom,
prefix: Option<DOMString>, document: &Document)
-> SVGGraphicsElement {
SVGGraphicsElement {
svgelement:
SVGElement::new_inherited_with_state(state, tag_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<SVGGraphicsElement> {
Node::reflect_node(box SVGGraphicsElement::new_inherited(local_name, prefix, document),
document,
SVGGraphicsElementBinding::Wrap)
}
}
impl VirtualMethods for SVGGraphicsElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<SVGElement>() as &VirtualMethods)
}
}
| {
SVGGraphicsElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document)
} | identifier_body |
lib.rs | // Copyright (c) 2017 FaultyRAM
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT
// or http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! A helper library for Google Code Jam solutions.
//!
//! In the Google Code Jam, solving a problem typically requires the following steps:
//!
//! 1. Open an input file containing a series of test cases.
//! 2. Open an output file where solutions will be written.
//! 2. Read the first line from the input file, which consists solely of an unsigned integer
//! specifying the number of test cases in the input file.
//! 3. For each test case, perform the following steps:
//! 1. Obtain the corresponding test data by reading one or more lines from the input file (it
//! may be a fixed number, or specified within the test data itself).
//! 2. Perform some logic using the test data, in order to obtain a set of results.
//! 3. Write the string `"Case #N:"` (where `N` is the number of completed test cases) followed
//! by the results obtained in the previous step, formatted as the problem requires.
//!
//! Writing code to handle all of the above is tedious and time-consuming, in a situation where
//! every microsecond counts. `gcj-helper` is designed to handle the boilerplate, so you can focus
//! on writing solutions instead.
//!
//! # The `TestEngine` type
//!
//! To execute test cases, you need to create a `TestEngine` and call `TestEngine::run()`.
//! `TestEngine::run()` accepts two closures:
//!
//! 1. A *parser* that reads from an input file and returns the data for one test case.
//! 2. A *solver* that performs logic on the data for one test case and returns a result, encoded
//! as a `Display` type.
//!
//! This two-step process to writing solutions is useful for two reasons:
//!
//! * It separates parsing from the solution itself, making your code easier to read;
//! * It enables test case parallelisation if the `parallel` feature is enabled, improving
//! run-time performance at the cost of increased build times.
//!
//! # The `InputReader` type
//!
//! `gcj-helper` provides parsers with access to an `InputReader`, which obtains data from the
//! input file in a `io::Read`-like fashion. The `InputReader::read_next_line()` method reads a
//! line of text from the input file, consuming the end-of-line marker, and returns a `&str`
//! containing the result.
//!
//! # Formatting test results
//!
//! Before each test case, the `TestEngine` writes the string `"Case #N:"`, where `N` is the
//! current test case. This does not prepend or append any whitespace. This means that if the
//! colon must be followed by a space, your result should begin with one, and that the result must
//! end with a newline.
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", forbid(clippy))]
#![cfg_attr(feature = "clippy", forbid(clippy_internal))]
#![cfg_attr(feature = "clippy", forbid(clippy_pedantic))]
#![forbid(warnings)]
#![forbid(box_pointers)]
#![forbid(fat_ptr_transmutes)]
#![forbid(missing_copy_implementations)]
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![forbid(trivial_casts)]
#![forbid(trivial_numeric_casts)]
#![forbid(unsafe_code)]
#![forbid(unused_extern_crates)]
#![forbid(unused_import_braces)]
#![deny(unused_qualifications)]
#![forbid(unused_results)]
#![forbid(variant_size_differences)]
#[cfg(feature = "parallel")]
extern crate rayon;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use std::{env, io};
use std::ffi::OsString;
use std::fmt::{Arguments, Display};
use std::fs::{File, OpenOptions};
use std::io::{LineWriter, Read, Write};
use std::path::Path;
/// Facilitates the execution of problem solving code.
#[derive(Debug)]
pub struct TestEngine<I: AsRef<Path>, O: AsRef<Path>> {
/// A path to an input file.
input_file_path: I,
/// A path to an output file.
output_file_path: O,
}
/// Supports reading from an input file.
#[derive(Debug)]
pub struct InputReader {
/// A string representing the input file.
input: String,
/// The current position within the input file.
offset: usize,
}
/// Supports writing to an output file.
struct OutputWriter(LineWriter<File>);
impl<I: AsRef<Path>, O: AsRef<Path>> TestEngine<I, O> {
/// Creates a new test engine using the specified input and output file paths.
///
/// Calling this method is cheap; no files are opened until `TestEngine::run()` is called.
pub fn new(input_file_path: I, output_file_path: O) -> TestEngine<I, O> {
TestEngine {
input_file_path: input_file_path,
output_file_path: output_file_path,
}
}
#[cfg(not(feature = "parallel"))]
/// Consumes the test engine, executing a parser and solver once per test case.
///
/// # Panics
///
/// This method panics in the event of an I/O error.
pub fn run<
D: Sized + Send + Sync,
R: Display + Sized + Send,
P: Fn(&mut InputReader) -> D,
S: Fn(&D) -> R + Sync
>
(
self,
p: P,
s: S,
) {
let mut reader = InputReader::new(self.input_file_path);
let mut writer = OutputWriter::new(self.output_file_path);
let mut current_case: usize = 1;
let case_count = reader.get_case_count();
while current_case <= case_count {
writer.write_test_result(current_case, (s)(&(p)(&mut reader)));
current_case += 1;
}
}
/// Consumes the test engine, executing a parser and solver once per test case.
///
/// # Panics
///
/// This method panics in the event of an I/O error.
#[cfg(feature = "parallel")]
pub fn run<
D: Sized + Send + Sync,
R: Display + Sized + Send,
P: Fn(&mut InputReader) -> D,
S: Fn(&D) -> R + Sync
>
(
self,
p: P,
s: S,
) {
let mut reader = InputReader::new(self.input_file_path);
let mut writer = OutputWriter::new(self.output_file_path);
let case_count = reader.get_case_count();
let mut data = Vec::with_capacity(0);
data.reserve_exact(case_count);
for _ in 0..case_count {
data.push((p(&mut reader), None));
}
data.par_iter_mut().for_each(|d| d.1 = Some(s(&d.0)));
for (i, &(_, ref r)) in data.iter().enumerate() {
writer.write_test_result(
i + 1,
match *r {
Some(ref x) => x,
None => unreachable!(),
},
);
}
}
}
impl TestEngine<OsString, OsString> {
/// Creates a new test engine using input and output file paths obtained from command line
/// arguments.
///
/// Calling this method is cheap; no files are opened until `TestEngine::run()` is called.
///
/// # Panics
///
/// This method panics if either the input file path or output file path is missing.
pub fn from_args() -> TestEngine<OsString, OsString> |
}
impl Default for TestEngine<OsString, OsString> {
fn default() -> TestEngine<OsString, OsString> {
Self::from_args()
}
}
impl InputReader {
/// Reads a line of text from the input file, consuming the end-of-line marker if one is
/// present.
pub fn read_next_line(&mut self) -> &str {
if self.offset >= self.input.len() {
panic!("could not read line from input file: reached end of file");
}
let start = self.offset;
let end = self.input
.char_indices()
.skip(start)
.take_while(|&(_, c)| c!= '\n')
.last()
.map_or(start, |(i, _)| i + 1);
let s = &self.input[start..end];
if s.is_empty() {
self.offset = end + 2;
} else {
self.offset = end + 1;
}
s
}
/// Creates a new input reader over the given input file.
fn new<P: AsRef<Path>>(path: P) -> InputReader {
let mut file = OpenOptions::new()
.read(true)
.open(path)
.expect("could not open input file for reading");
let mut s = String::with_capacity(0);
let _ = file.read_to_string(&mut s)
.expect("could not read input file into string");
InputReader {
input: s,
offset: 0,
}
}
/// Reads the number of test cases from the input file.
fn get_case_count(&mut self) -> usize {
usize::from_str_radix(self.read_next_line(), 10).expect("could not parse test case count")
}
}
impl OutputWriter {
/// Creates a new output writer over the given output file.
fn new<P: AsRef<Path>>(path: P) -> OutputWriter {
OutputWriter(
LineWriter::new(
OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(path)
.expect("could not open output file for writing"),
),
)
}
/// Writes a test result to the output file.
fn write_test_result<R: Display>(&mut self, case: usize, result: R) {
let case_prefix = "Case #";
let case_number = case.to_string();
let case_colon = ":";
let r = result.to_string();
let mut output = String::with_capacity(0);
output.reserve_exact(case_prefix.len() + case_number.len() + case_colon.len() + r.len(),);
output.push_str(case_prefix);
output.push_str(&case_number);
output.push_str(case_colon);
output.push_str(&r);
self.write_all(output.as_bytes())
.expect("could not write test result to output file");
}
}
impl Write for OutputWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.0.write_all(buf)
}
fn write_fmt(&mut self, fmt: Arguments) -> io::Result<()> {
self.0.write_fmt(fmt)
}
}
| {
let mut args = env::args_os();
let input_file_path = args.nth(1).expect("input file path not specified");
let output_file_path = args.next().expect("output file path not specified");
Self::new(input_file_path, output_file_path)
} | identifier_body |
lib.rs | // Copyright (c) 2017 FaultyRAM
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT
// or http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! A helper library for Google Code Jam solutions.
//!
//! In the Google Code Jam, solving a problem typically requires the following steps:
//!
//! 1. Open an input file containing a series of test cases.
//! 2. Open an output file where solutions will be written.
//! 2. Read the first line from the input file, which consists solely of an unsigned integer
//! specifying the number of test cases in the input file.
//! 3. For each test case, perform the following steps:
//! 1. Obtain the corresponding test data by reading one or more lines from the input file (it
//! may be a fixed number, or specified within the test data itself).
//! 2. Perform some logic using the test data, in order to obtain a set of results.
//! 3. Write the string `"Case #N:"` (where `N` is the number of completed test cases) followed
//! by the results obtained in the previous step, formatted as the problem requires.
//!
//! Writing code to handle all of the above is tedious and time-consuming, in a situation where
//! every microsecond counts. `gcj-helper` is designed to handle the boilerplate, so you can focus
//! on writing solutions instead.
//!
//! # The `TestEngine` type
//!
//! To execute test cases, you need to create a `TestEngine` and call `TestEngine::run()`.
//! `TestEngine::run()` accepts two closures:
//!
//! 1. A *parser* that reads from an input file and returns the data for one test case.
//! 2. A *solver* that performs logic on the data for one test case and returns a result, encoded
//! as a `Display` type.
//!
//! This two-step process to writing solutions is useful for two reasons:
//!
//! * It separates parsing from the solution itself, making your code easier to read;
//! * It enables test case parallelisation if the `parallel` feature is enabled, improving
//! run-time performance at the cost of increased build times.
//!
//! # The `InputReader` type
//!
//! `gcj-helper` provides parsers with access to an `InputReader`, which obtains data from the
//! input file in a `io::Read`-like fashion. The `InputReader::read_next_line()` method reads a
//! line of text from the input file, consuming the end-of-line marker, and returns a `&str`
//! containing the result.
//!
//! # Formatting test results
//!
//! Before each test case, the `TestEngine` writes the string `"Case #N:"`, where `N` is the
//! current test case. This does not prepend or append any whitespace. This means that if the
//! colon must be followed by a space, your result should begin with one, and that the result must
//! end with a newline.
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", forbid(clippy))]
#![cfg_attr(feature = "clippy", forbid(clippy_internal))]
#![cfg_attr(feature = "clippy", forbid(clippy_pedantic))]
#![forbid(warnings)]
#![forbid(box_pointers)]
#![forbid(fat_ptr_transmutes)]
#![forbid(missing_copy_implementations)]
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![forbid(trivial_casts)]
#![forbid(trivial_numeric_casts)]
#![forbid(unsafe_code)]
#![forbid(unused_extern_crates)]
#![forbid(unused_import_braces)]
#![deny(unused_qualifications)]
#![forbid(unused_results)]
#![forbid(variant_size_differences)]
#[cfg(feature = "parallel")]
extern crate rayon;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use std::{env, io};
use std::ffi::OsString;
use std::fmt::{Arguments, Display};
use std::fs::{File, OpenOptions};
use std::io::{LineWriter, Read, Write};
use std::path::Path;
/// Facilitates the execution of problem solving code.
#[derive(Debug)]
pub struct TestEngine<I: AsRef<Path>, O: AsRef<Path>> {
/// A path to an input file.
input_file_path: I,
/// A path to an output file.
output_file_path: O,
}
/// Supports reading from an input file.
#[derive(Debug)]
pub struct InputReader {
/// A string representing the input file.
input: String,
/// The current position within the input file.
offset: usize,
}
/// Supports writing to an output file.
struct OutputWriter(LineWriter<File>);
impl<I: AsRef<Path>, O: AsRef<Path>> TestEngine<I, O> {
/// Creates a new test engine using the specified input and output file paths.
///
/// Calling this method is cheap; no files are opened until `TestEngine::run()` is called.
pub fn new(input_file_path: I, output_file_path: O) -> TestEngine<I, O> {
TestEngine {
input_file_path: input_file_path,
output_file_path: output_file_path,
}
}
#[cfg(not(feature = "parallel"))]
/// Consumes the test engine, executing a parser and solver once per test case.
///
/// # Panics
///
/// This method panics in the event of an I/O error.
pub fn run<
D: Sized + Send + Sync,
R: Display + Sized + Send,
P: Fn(&mut InputReader) -> D,
S: Fn(&D) -> R + Sync
>
(
self,
p: P,
s: S,
) {
let mut reader = InputReader::new(self.input_file_path);
let mut writer = OutputWriter::new(self.output_file_path);
let mut current_case: usize = 1;
let case_count = reader.get_case_count();
while current_case <= case_count {
writer.write_test_result(current_case, (s)(&(p)(&mut reader)));
current_case += 1;
}
}
/// Consumes the test engine, executing a parser and solver once per test case.
///
/// # Panics
///
/// This method panics in the event of an I/O error.
#[cfg(feature = "parallel")]
pub fn run<
D: Sized + Send + Sync,
R: Display + Sized + Send,
P: Fn(&mut InputReader) -> D,
S: Fn(&D) -> R + Sync
>
(
self,
p: P,
s: S,
) {
let mut reader = InputReader::new(self.input_file_path);
let mut writer = OutputWriter::new(self.output_file_path);
let case_count = reader.get_case_count();
let mut data = Vec::with_capacity(0);
data.reserve_exact(case_count);
for _ in 0..case_count {
data.push((p(&mut reader), None));
}
data.par_iter_mut().for_each(|d| d.1 = Some(s(&d.0)));
for (i, &(_, ref r)) in data.iter().enumerate() {
writer.write_test_result(
i + 1,
match *r {
Some(ref x) => x,
None => unreachable!(),
},
);
}
}
}
impl TestEngine<OsString, OsString> {
/// Creates a new test engine using input and output file paths obtained from command line
/// arguments.
///
/// Calling this method is cheap; no files are opened until `TestEngine::run()` is called.
///
/// # Panics
///
/// This method panics if either the input file path or output file path is missing.
pub fn from_args() -> TestEngine<OsString, OsString> {
let mut args = env::args_os();
let input_file_path = args.nth(1).expect("input file path not specified");
let output_file_path = args.next().expect("output file path not specified");
Self::new(input_file_path, output_file_path)
}
}
| fn default() -> TestEngine<OsString, OsString> {
Self::from_args()
}
}
impl InputReader {
/// Reads a line of text from the input file, consuming the end-of-line marker if one is
/// present.
pub fn read_next_line(&mut self) -> &str {
if self.offset >= self.input.len() {
panic!("could not read line from input file: reached end of file");
}
let start = self.offset;
let end = self.input
.char_indices()
.skip(start)
.take_while(|&(_, c)| c!= '\n')
.last()
.map_or(start, |(i, _)| i + 1);
let s = &self.input[start..end];
if s.is_empty() {
self.offset = end + 2;
} else {
self.offset = end + 1;
}
s
}
/// Creates a new input reader over the given input file.
fn new<P: AsRef<Path>>(path: P) -> InputReader {
let mut file = OpenOptions::new()
.read(true)
.open(path)
.expect("could not open input file for reading");
let mut s = String::with_capacity(0);
let _ = file.read_to_string(&mut s)
.expect("could not read input file into string");
InputReader {
input: s,
offset: 0,
}
}
/// Reads the number of test cases from the input file.
fn get_case_count(&mut self) -> usize {
usize::from_str_radix(self.read_next_line(), 10).expect("could not parse test case count")
}
}
impl OutputWriter {
/// Creates a new output writer over the given output file.
fn new<P: AsRef<Path>>(path: P) -> OutputWriter {
OutputWriter(
LineWriter::new(
OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(path)
.expect("could not open output file for writing"),
),
)
}
/// Writes a test result to the output file.
fn write_test_result<R: Display>(&mut self, case: usize, result: R) {
let case_prefix = "Case #";
let case_number = case.to_string();
let case_colon = ":";
let r = result.to_string();
let mut output = String::with_capacity(0);
output.reserve_exact(case_prefix.len() + case_number.len() + case_colon.len() + r.len(),);
output.push_str(case_prefix);
output.push_str(&case_number);
output.push_str(case_colon);
output.push_str(&r);
self.write_all(output.as_bytes())
.expect("could not write test result to output file");
}
}
impl Write for OutputWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.0.write_all(buf)
}
fn write_fmt(&mut self, fmt: Arguments) -> io::Result<()> {
self.0.write_fmt(fmt)
}
} | impl Default for TestEngine<OsString, OsString> { | random_line_split |
lib.rs | // Copyright (c) 2017 FaultyRAM
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT
// or http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! A helper library for Google Code Jam solutions.
//!
//! In the Google Code Jam, solving a problem typically requires the following steps:
//!
//! 1. Open an input file containing a series of test cases.
//! 2. Open an output file where solutions will be written.
//! 2. Read the first line from the input file, which consists solely of an unsigned integer
//! specifying the number of test cases in the input file.
//! 3. For each test case, perform the following steps:
//! 1. Obtain the corresponding test data by reading one or more lines from the input file (it
//! may be a fixed number, or specified within the test data itself).
//! 2. Perform some logic using the test data, in order to obtain a set of results.
//! 3. Write the string `"Case #N:"` (where `N` is the number of completed test cases) followed
//! by the results obtained in the previous step, formatted as the problem requires.
//!
//! Writing code to handle all of the above is tedious and time-consuming, in a situation where
//! every microsecond counts. `gcj-helper` is designed to handle the boilerplate, so you can focus
//! on writing solutions instead.
//!
//! # The `TestEngine` type
//!
//! To execute test cases, you need to create a `TestEngine` and call `TestEngine::run()`.
//! `TestEngine::run()` accepts two closures:
//!
//! 1. A *parser* that reads from an input file and returns the data for one test case.
//! 2. A *solver* that performs logic on the data for one test case and returns a result, encoded
//! as a `Display` type.
//!
//! This two-step process to writing solutions is useful for two reasons:
//!
//! * It separates parsing from the solution itself, making your code easier to read;
//! * It enables test case parallelisation if the `parallel` feature is enabled, improving
//! run-time performance at the cost of increased build times.
//!
//! # The `InputReader` type
//!
//! `gcj-helper` provides parsers with access to an `InputReader`, which obtains data from the
//! input file in a `io::Read`-like fashion. The `InputReader::read_next_line()` method reads a
//! line of text from the input file, consuming the end-of-line marker, and returns a `&str`
//! containing the result.
//!
//! # Formatting test results
//!
//! Before each test case, the `TestEngine` writes the string `"Case #N:"`, where `N` is the
//! current test case. This does not prepend or append any whitespace. This means that if the
//! colon must be followed by a space, your result should begin with one, and that the result must
//! end with a newline.
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", forbid(clippy))]
#![cfg_attr(feature = "clippy", forbid(clippy_internal))]
#![cfg_attr(feature = "clippy", forbid(clippy_pedantic))]
#![forbid(warnings)]
#![forbid(box_pointers)]
#![forbid(fat_ptr_transmutes)]
#![forbid(missing_copy_implementations)]
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![forbid(trivial_casts)]
#![forbid(trivial_numeric_casts)]
#![forbid(unsafe_code)]
#![forbid(unused_extern_crates)]
#![forbid(unused_import_braces)]
#![deny(unused_qualifications)]
#![forbid(unused_results)]
#![forbid(variant_size_differences)]
#[cfg(feature = "parallel")]
extern crate rayon;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use std::{env, io};
use std::ffi::OsString;
use std::fmt::{Arguments, Display};
use std::fs::{File, OpenOptions};
use std::io::{LineWriter, Read, Write};
use std::path::Path;
/// Facilitates the execution of problem solving code.
#[derive(Debug)]
pub struct TestEngine<I: AsRef<Path>, O: AsRef<Path>> {
/// A path to an input file.
input_file_path: I,
/// A path to an output file.
output_file_path: O,
}
/// Supports reading from an input file.
#[derive(Debug)]
pub struct InputReader {
/// A string representing the input file.
input: String,
/// The current position within the input file.
offset: usize,
}
/// Supports writing to an output file.
struct OutputWriter(LineWriter<File>);
impl<I: AsRef<Path>, O: AsRef<Path>> TestEngine<I, O> {
/// Creates a new test engine using the specified input and output file paths.
///
/// Calling this method is cheap; no files are opened until `TestEngine::run()` is called.
pub fn new(input_file_path: I, output_file_path: O) -> TestEngine<I, O> {
TestEngine {
input_file_path: input_file_path,
output_file_path: output_file_path,
}
}
#[cfg(not(feature = "parallel"))]
/// Consumes the test engine, executing a parser and solver once per test case.
///
/// # Panics
///
/// This method panics in the event of an I/O error.
pub fn run<
D: Sized + Send + Sync,
R: Display + Sized + Send,
P: Fn(&mut InputReader) -> D,
S: Fn(&D) -> R + Sync
>
(
self,
p: P,
s: S,
) {
let mut reader = InputReader::new(self.input_file_path);
let mut writer = OutputWriter::new(self.output_file_path);
let mut current_case: usize = 1;
let case_count = reader.get_case_count();
while current_case <= case_count {
writer.write_test_result(current_case, (s)(&(p)(&mut reader)));
current_case += 1;
}
}
/// Consumes the test engine, executing a parser and solver once per test case.
///
/// # Panics
///
/// This method panics in the event of an I/O error.
#[cfg(feature = "parallel")]
pub fn run<
D: Sized + Send + Sync,
R: Display + Sized + Send,
P: Fn(&mut InputReader) -> D,
S: Fn(&D) -> R + Sync
>
(
self,
p: P,
s: S,
) {
let mut reader = InputReader::new(self.input_file_path);
let mut writer = OutputWriter::new(self.output_file_path);
let case_count = reader.get_case_count();
let mut data = Vec::with_capacity(0);
data.reserve_exact(case_count);
for _ in 0..case_count {
data.push((p(&mut reader), None));
}
data.par_iter_mut().for_each(|d| d.1 = Some(s(&d.0)));
for (i, &(_, ref r)) in data.iter().enumerate() {
writer.write_test_result(
i + 1,
match *r {
Some(ref x) => x,
None => unreachable!(),
},
);
}
}
}
impl TestEngine<OsString, OsString> {
/// Creates a new test engine using input and output file paths obtained from command line
/// arguments.
///
/// Calling this method is cheap; no files are opened until `TestEngine::run()` is called.
///
/// # Panics
///
/// This method panics if either the input file path or output file path is missing.
pub fn from_args() -> TestEngine<OsString, OsString> {
let mut args = env::args_os();
let input_file_path = args.nth(1).expect("input file path not specified");
let output_file_path = args.next().expect("output file path not specified");
Self::new(input_file_path, output_file_path)
}
}
impl Default for TestEngine<OsString, OsString> {
fn default() -> TestEngine<OsString, OsString> {
Self::from_args()
}
}
impl InputReader {
/// Reads a line of text from the input file, consuming the end-of-line marker if one is
/// present.
pub fn read_next_line(&mut self) -> &str {
if self.offset >= self.input.len() {
panic!("could not read line from input file: reached end of file");
}
let start = self.offset;
let end = self.input
.char_indices()
.skip(start)
.take_while(|&(_, c)| c!= '\n')
.last()
.map_or(start, |(i, _)| i + 1);
let s = &self.input[start..end];
if s.is_empty() {
self.offset = end + 2;
} else {
self.offset = end + 1;
}
s
}
/// Creates a new input reader over the given input file.
fn new<P: AsRef<Path>>(path: P) -> InputReader {
let mut file = OpenOptions::new()
.read(true)
.open(path)
.expect("could not open input file for reading");
let mut s = String::with_capacity(0);
let _ = file.read_to_string(&mut s)
.expect("could not read input file into string");
InputReader {
input: s,
offset: 0,
}
}
/// Reads the number of test cases from the input file.
fn get_case_count(&mut self) -> usize {
usize::from_str_radix(self.read_next_line(), 10).expect("could not parse test case count")
}
}
impl OutputWriter {
/// Creates a new output writer over the given output file.
fn new<P: AsRef<Path>>(path: P) -> OutputWriter {
OutputWriter(
LineWriter::new(
OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(path)
.expect("could not open output file for writing"),
),
)
}
/// Writes a test result to the output file.
fn write_test_result<R: Display>(&mut self, case: usize, result: R) {
let case_prefix = "Case #";
let case_number = case.to_string();
let case_colon = ":";
let r = result.to_string();
let mut output = String::with_capacity(0);
output.reserve_exact(case_prefix.len() + case_number.len() + case_colon.len() + r.len(),);
output.push_str(case_prefix);
output.push_str(&case_number);
output.push_str(case_colon);
output.push_str(&r);
self.write_all(output.as_bytes())
.expect("could not write test result to output file");
}
}
impl Write for OutputWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
fn | (&mut self, buf: &[u8]) -> io::Result<()> {
self.0.write_all(buf)
}
fn write_fmt(&mut self, fmt: Arguments) -> io::Result<()> {
self.0.write_fmt(fmt)
}
}
| write_all | identifier_name |
spawn.rs | use engine::components::Spawned;
use engine::resources::{SpawnBuffer, UnitTypeMap};
use specs::prelude::*;
#[derive(Default)]
pub struct SpawnSystem {
spawn_buf_bak: SpawnBuffer,
spawn_buf_tmp: SpawnBuffer,
}
impl SpawnSystem {
pub fn | (&mut self, world: &mut World) {
use std::mem;
self.spawn_buf_tmp.0.clear();
// Need this for borrow checking or we're just borrowing world while we try to pass it
// mutably
mem::swap(
&mut self.spawn_buf_tmp,
&mut *world.write_resource::<SpawnBuffer>(),
);
// We're basically just "pouring" one bucket into another through a mesh
//
// If the delay suggests we should spawn the entity now, we don't put it in
// the backup buffer, and instead spawn it. Otherwise we just decrease the time
// and let it naturally filter into the backup buffer
self.spawn_buf_bak
.0
.extend(self.spawn_buf_tmp.0.drain(..).filter_map(|mut spawn| {
if spawn.delay <= 1 {
// really unfortunate but we need to clone for borrow checker
let u_type = world
.read_resource::<UnitTypeMap>()
.tag_map
.get(&spawn.u_type)
.expect(&format!(
"Unknown unit type {} at spawn of {:?}",
spawn.u_type, spawn,
))
.clone();
let entity =
u_type.build_entity(world, spawn.pos, spawn.curr_hp, spawn.faction);
world.write::<Spawned>().insert(entity, Spawned);
None
} else {
spawn.delay -= 1;
Some(spawn)
}
}));
mem::swap(
&mut *world.write_resource::<SpawnBuffer>(),
&mut self.spawn_buf_bak,
);
}
}
| update | identifier_name |
spawn.rs | use engine::components::Spawned;
use engine::resources::{SpawnBuffer, UnitTypeMap};
use specs::prelude::*;
#[derive(Default)]
pub struct SpawnSystem {
spawn_buf_bak: SpawnBuffer,
spawn_buf_tmp: SpawnBuffer,
}
impl SpawnSystem {
pub fn update(&mut self, world: &mut World) {
use std::mem;
self.spawn_buf_tmp.0.clear();
// Need this for borrow checking or we're just borrowing world while we try to pass it
// mutably
mem::swap(
&mut self.spawn_buf_tmp,
&mut *world.write_resource::<SpawnBuffer>(),
);
// We're basically just "pouring" one bucket into another through a mesh
//
// If the delay suggests we should spawn the entity now, we don't put it in
// the backup buffer, and instead spawn it. Otherwise we just decrease the time
// and let it naturally filter into the backup buffer
self.spawn_buf_bak
.0
.extend(self.spawn_buf_tmp.0.drain(..).filter_map(|mut spawn| {
if spawn.delay <= 1 {
// really unfortunate but we need to clone for borrow checker
let u_type = world
.read_resource::<UnitTypeMap>()
.tag_map
.get(&spawn.u_type)
.expect(&format!(
"Unknown unit type {} at spawn of {:?}",
spawn.u_type, spawn,
))
.clone();
let entity =
u_type.build_entity(world, spawn.pos, spawn.curr_hp, spawn.faction);
world.write::<Spawned>().insert(entity, Spawned);
None
} else |
}));
mem::swap(
&mut *world.write_resource::<SpawnBuffer>(),
&mut self.spawn_buf_bak,
);
}
}
| {
spawn.delay -= 1;
Some(spawn)
} | conditional_block |
spawn.rs | use engine::components::Spawned;
use engine::resources::{SpawnBuffer, UnitTypeMap};
use specs::prelude::*;
#[derive(Default)]
pub struct SpawnSystem {
spawn_buf_bak: SpawnBuffer,
spawn_buf_tmp: SpawnBuffer,
}
| use std::mem;
self.spawn_buf_tmp.0.clear();
// Need this for borrow checking or we're just borrowing world while we try to pass it
// mutably
mem::swap(
&mut self.spawn_buf_tmp,
&mut *world.write_resource::<SpawnBuffer>(),
);
// We're basically just "pouring" one bucket into another through a mesh
//
// If the delay suggests we should spawn the entity now, we don't put it in
// the backup buffer, and instead spawn it. Otherwise we just decrease the time
// and let it naturally filter into the backup buffer
self.spawn_buf_bak
.0
.extend(self.spawn_buf_tmp.0.drain(..).filter_map(|mut spawn| {
if spawn.delay <= 1 {
// really unfortunate but we need to clone for borrow checker
let u_type = world
.read_resource::<UnitTypeMap>()
.tag_map
.get(&spawn.u_type)
.expect(&format!(
"Unknown unit type {} at spawn of {:?}",
spawn.u_type, spawn,
))
.clone();
let entity =
u_type.build_entity(world, spawn.pos, spawn.curr_hp, spawn.faction);
world.write::<Spawned>().insert(entity, Spawned);
None
} else {
spawn.delay -= 1;
Some(spawn)
}
}));
mem::swap(
&mut *world.write_resource::<SpawnBuffer>(),
&mut self.spawn_buf_bak,
);
}
} | impl SpawnSystem {
pub fn update(&mut self, world: &mut World) { | random_line_split |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::rt::io;
use std::rt::io::Writer;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn | (buf: &[u8]) {
let mut stderr = io::stderr();
stderr.write(bytes!(" "));
for (i, &v) in buf.iter().enumerate() {
let output = format!("{:02X} ", v as uint);
stderr.write(output.as_bytes());
match i % 16 {
15 => stderr.write(bytes!("\n ")),
7 => stderr.write(bytes!(" ")),
_ => ()
}
stderr.flush();
}
stderr.write(bytes!("\n"));
}
pub fn hexdump<T>(obj: &T) {
unsafe {
let buf: *u8 = transmute(obj);
debug!("dumping at {:p}", buf);
buf_as_slice(buf, size_of::<T>(), hexdump_slice);
}
}
| hexdump_slice | identifier_name |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::rt::io;
use std::rt::io::Writer;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn hexdump_slice(buf: &[u8]) |
pub fn hexdump<T>(obj: &T) {
unsafe {
let buf: *u8 = transmute(obj);
debug!("dumping at {:p}", buf);
buf_as_slice(buf, size_of::<T>(), hexdump_slice);
}
}
| {
let mut stderr = io::stderr();
stderr.write(bytes!(" "));
for (i, &v) in buf.iter().enumerate() {
let output = format!("{:02X} ", v as uint);
stderr.write(output.as_bytes());
match i % 16 {
15 => stderr.write(bytes!("\n ")),
7 => stderr.write(bytes!(" ")),
_ => ()
}
stderr.flush();
}
stderr.write(bytes!("\n"));
} | identifier_body |
debug.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::rt::io; | use std::rt::io::Writer;
use std::vec::raw::buf_as_slice;
use std::cast::transmute;
use std::mem::size_of;
fn hexdump_slice(buf: &[u8]) {
let mut stderr = io::stderr();
stderr.write(bytes!(" "));
for (i, &v) in buf.iter().enumerate() {
let output = format!("{:02X} ", v as uint);
stderr.write(output.as_bytes());
match i % 16 {
15 => stderr.write(bytes!("\n ")),
7 => stderr.write(bytes!(" ")),
_ => ()
}
stderr.flush();
}
stderr.write(bytes!("\n"));
}
pub fn hexdump<T>(obj: &T) {
unsafe {
let buf: *u8 = transmute(obj);
debug!("dumping at {:p}", buf);
buf_as_slice(buf, size_of::<T>(), hexdump_slice);
}
} | random_line_split |
|
lib.rs | extern crate banko_lib;
use banko_lib::Bankoplade;
use std::u64;
#[no_mangle]
pub extern "C" fn rust_encoder_init() -> *mut banko_lib::Encoder {
let result: Box<banko_lib::Encoder> = Default::default();
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn rust_encoder_free(ptr: *mut banko_lib::Encoder) {
Box::from_raw(ptr);
}
#[no_mangle]
pub extern "C" fn rust_encoder_run(
encoder: *const banko_lib::Encoder,
in_plade: *const Bankoplade,
out_u64: *mut u64,
) -> bool {
match unsafe { (encoder.as_ref(), in_plade.as_ref(), out_u64.as_mut()) } {
(Some(encoder), Some(in_plade), Some(out_u64)) => {
if let Some(out) = encoder.encode(in_plade) {
*out_u64 = out;
true
} else {
*out_u64 = u64::MAX;
false
}
}
_ => false,
}
}
#[no_mangle]
pub extern "C" fn rust_decoder_init() -> *mut banko_lib::Decoder {
let result: Box<banko_lib::Decoder> = Default::default();
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn rust_decoder_free(ptr: *mut banko_lib::Decoder) |
#[no_mangle]
pub extern "C" fn rust_decoder_run(
decoder: *mut banko_lib::Decoder,
in_u64: u64,
out_plade: *mut Bankoplade,
) -> bool {
match unsafe { (decoder.as_ref(), out_plade.as_mut()) } {
(Some(decoder), Some(out_plade)) => {
let plade = decoder.decode(in_u64);
let result = plade.is_some();
*out_plade = plade.unwrap_or_else(Bankoplade::zero_plade);
result
}
_ => false,
}
}
| {
Box::from_raw(ptr);
} | identifier_body |
lib.rs | extern crate banko_lib;
use banko_lib::Bankoplade;
use std::u64;
#[no_mangle]
pub extern "C" fn rust_encoder_init() -> *mut banko_lib::Encoder {
let result: Box<banko_lib::Encoder> = Default::default();
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn rust_encoder_free(ptr: *mut banko_lib::Encoder) {
Box::from_raw(ptr);
}
#[no_mangle]
pub extern "C" fn | (
encoder: *const banko_lib::Encoder,
in_plade: *const Bankoplade,
out_u64: *mut u64,
) -> bool {
match unsafe { (encoder.as_ref(), in_plade.as_ref(), out_u64.as_mut()) } {
(Some(encoder), Some(in_plade), Some(out_u64)) => {
if let Some(out) = encoder.encode(in_plade) {
*out_u64 = out;
true
} else {
*out_u64 = u64::MAX;
false
}
}
_ => false,
}
}
#[no_mangle]
pub extern "C" fn rust_decoder_init() -> *mut banko_lib::Decoder {
let result: Box<banko_lib::Decoder> = Default::default();
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn rust_decoder_free(ptr: *mut banko_lib::Decoder) {
Box::from_raw(ptr);
}
#[no_mangle]
pub extern "C" fn rust_decoder_run(
decoder: *mut banko_lib::Decoder,
in_u64: u64,
out_plade: *mut Bankoplade,
) -> bool {
match unsafe { (decoder.as_ref(), out_plade.as_mut()) } {
(Some(decoder), Some(out_plade)) => {
let plade = decoder.decode(in_u64);
let result = plade.is_some();
*out_plade = plade.unwrap_or_else(Bankoplade::zero_plade);
result
}
_ => false,
}
}
| rust_encoder_run | identifier_name |
lib.rs | extern crate banko_lib;
use banko_lib::Bankoplade;
use std::u64;
#[no_mangle]
pub extern "C" fn rust_encoder_init() -> *mut banko_lib::Encoder {
let result: Box<banko_lib::Encoder> = Default::default();
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn rust_encoder_free(ptr: *mut banko_lib::Encoder) {
Box::from_raw(ptr);
}
#[no_mangle]
pub extern "C" fn rust_encoder_run(
encoder: *const banko_lib::Encoder,
in_plade: *const Bankoplade,
out_u64: *mut u64,
) -> bool {
match unsafe { (encoder.as_ref(), in_plade.as_ref(), out_u64.as_mut()) } {
(Some(encoder), Some(in_plade), Some(out_u64)) => {
if let Some(out) = encoder.encode(in_plade) {
*out_u64 = out;
true
} else {
*out_u64 = u64::MAX;
false
}
}
_ => false,
}
}
#[no_mangle]
pub extern "C" fn rust_decoder_init() -> *mut banko_lib::Decoder { | pub unsafe extern "C" fn rust_decoder_free(ptr: *mut banko_lib::Decoder) {
Box::from_raw(ptr);
}
#[no_mangle]
pub extern "C" fn rust_decoder_run(
decoder: *mut banko_lib::Decoder,
in_u64: u64,
out_plade: *mut Bankoplade,
) -> bool {
match unsafe { (decoder.as_ref(), out_plade.as_mut()) } {
(Some(decoder), Some(out_plade)) => {
let plade = decoder.decode(in_u64);
let result = plade.is_some();
*out_plade = plade.unwrap_or_else(Bankoplade::zero_plade);
result
}
_ => false,
}
} | let result: Box<banko_lib::Decoder> = Default::default();
Box::into_raw(result)
}
#[no_mangle] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.