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 |
---|---|---|---|---|
unix.rs
|
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std::io::{Result, Error};
use ::libc;
use self::c_types::{c_passwd, getpwuid};
#[path = "../../common/c_types.rs"] mod c_types;
extern {
pub fn geteuid() -> libc::uid_t;
}
pub unsafe fn getusername() -> Result<String>
|
{
// Get effective user id
let uid = geteuid();
// Try to find username for uid
let passwd: *const c_passwd = getpwuid(uid);
if passwd.is_null() {
return Err(Error::last_os_error())
}
// Extract username from passwd struct
let pw_name: *const libc::c_char = (*passwd).pw_name;
let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string();
Ok(username)
}
|
identifier_body
|
|
p035.rs
|
//! [Problem 35](https://projecteuler.net/problem=35) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
extern crate prime;
use integer::Integer;
use prime::PrimeSet;
fn is_circular_prime(ps: &PrimeSet, n: u64) -> bool {
let radix = 10;
let ds = n.into_digits(radix).collect::<Vec<_>>();
let mut buf = ds.clone();
for i in (1.. ds.len()) {
for j in (0.. buf.len()) {
buf[j] = ds[(i + j) % ds.len()];
}
let circ = Integer::from_digits(buf.iter().map(|&x| x), radix);
if!ps.contains(circ) {
return false;
}
}
true
}
fn compute(limit: u64) -> usize {
let ps = PrimeSet::new();
ps.iter()
.take_while(|&p| p < limit)
.filter(|&n| is_circular_prime(&ps, n))
.count()
}
fn solve() -> String {
compute(1000000).to_string()
}
problem!("55", solve);
#[cfg(test)]
mod tests {
use prime::PrimeSet;
#[test]
fn is_circular_prime() {
let ps = PrimeSet::new();
assert_eq!(true, super::is_circular_prime(&ps, 197));
assert_eq!(false, super::is_circular_prime(&ps, 21));
assert_eq!(true, super::is_circular_prime(&ps, 2));
|
}
}
|
}
#[test]
fn below100() {
assert_eq!(13, super::compute(100));
|
random_line_split
|
p035.rs
|
//! [Problem 35](https://projecteuler.net/problem=35) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
extern crate prime;
use integer::Integer;
use prime::PrimeSet;
fn is_circular_prime(ps: &PrimeSet, n: u64) -> bool {
let radix = 10;
let ds = n.into_digits(radix).collect::<Vec<_>>();
let mut buf = ds.clone();
for i in (1.. ds.len()) {
for j in (0.. buf.len()) {
buf[j] = ds[(i + j) % ds.len()];
}
let circ = Integer::from_digits(buf.iter().map(|&x| x), radix);
if!ps.contains(circ) {
return false;
}
}
true
}
fn compute(limit: u64) -> usize {
let ps = PrimeSet::new();
ps.iter()
.take_while(|&p| p < limit)
.filter(|&n| is_circular_prime(&ps, n))
.count()
}
fn solve() -> String {
compute(1000000).to_string()
}
problem!("55", solve);
#[cfg(test)]
mod tests {
use prime::PrimeSet;
#[test]
fn is_circular_prime() {
let ps = PrimeSet::new();
assert_eq!(true, super::is_circular_prime(&ps, 197));
assert_eq!(false, super::is_circular_prime(&ps, 21));
assert_eq!(true, super::is_circular_prime(&ps, 2));
}
#[test]
fn
|
() {
assert_eq!(13, super::compute(100));
}
}
|
below100
|
identifier_name
|
p035.rs
|
//! [Problem 35](https://projecteuler.net/problem=35) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
extern crate prime;
use integer::Integer;
use prime::PrimeSet;
fn is_circular_prime(ps: &PrimeSet, n: u64) -> bool {
let radix = 10;
let ds = n.into_digits(radix).collect::<Vec<_>>();
let mut buf = ds.clone();
for i in (1.. ds.len()) {
for j in (0.. buf.len()) {
buf[j] = ds[(i + j) % ds.len()];
}
let circ = Integer::from_digits(buf.iter().map(|&x| x), radix);
if!ps.contains(circ)
|
}
true
}
fn compute(limit: u64) -> usize {
let ps = PrimeSet::new();
ps.iter()
.take_while(|&p| p < limit)
.filter(|&n| is_circular_prime(&ps, n))
.count()
}
fn solve() -> String {
compute(1000000).to_string()
}
problem!("55", solve);
#[cfg(test)]
mod tests {
use prime::PrimeSet;
#[test]
fn is_circular_prime() {
let ps = PrimeSet::new();
assert_eq!(true, super::is_circular_prime(&ps, 197));
assert_eq!(false, super::is_circular_prime(&ps, 21));
assert_eq!(true, super::is_circular_prime(&ps, 2));
}
#[test]
fn below100() {
assert_eq!(13, super::compute(100));
}
}
|
{
return false;
}
|
conditional_block
|
p035.rs
|
//! [Problem 35](https://projecteuler.net/problem=35) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
extern crate prime;
use integer::Integer;
use prime::PrimeSet;
fn is_circular_prime(ps: &PrimeSet, n: u64) -> bool {
let radix = 10;
let ds = n.into_digits(radix).collect::<Vec<_>>();
let mut buf = ds.clone();
for i in (1.. ds.len()) {
for j in (0.. buf.len()) {
buf[j] = ds[(i + j) % ds.len()];
}
let circ = Integer::from_digits(buf.iter().map(|&x| x), radix);
if!ps.contains(circ) {
return false;
}
}
true
}
fn compute(limit: u64) -> usize
|
fn solve() -> String {
compute(1000000).to_string()
}
problem!("55", solve);
#[cfg(test)]
mod tests {
use prime::PrimeSet;
#[test]
fn is_circular_prime() {
let ps = PrimeSet::new();
assert_eq!(true, super::is_circular_prime(&ps, 197));
assert_eq!(false, super::is_circular_prime(&ps, 21));
assert_eq!(true, super::is_circular_prime(&ps, 2));
}
#[test]
fn below100() {
assert_eq!(13, super::compute(100));
}
}
|
{
let ps = PrimeSet::new();
ps.iter()
.take_while(|&p| p < limit)
.filter(|&n| is_circular_prime(&ps, n))
.count()
}
|
identifier_body
|
lib.rs
|
// Copyright (C) 2019 Sajeer Ahamed <[email protected]>
// Copyright (C) 2019 Sebastian Dröge <[email protected]>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Extracts release for [GStreamer](https://gstreamer.freedesktop.org) plugin metadata
//!
//! See [`get_info`](fn.get_info.html) for details.
//!
//! This function is supposed to be used as follows in the `build.rs` of a crate that implements a
//! plugin:
//!
//! ```rust,ignore
//! gst_plugin_version_helper::get_info();
//! ```
//!
//! Inside `lib.rs` of the plugin, the information provided by `get_info` are usable as follows:
//!
//! ```rust,ignore
//! gst_plugin_define!(
//! the_plugin_name,
//! env!("CARGO_PKG_DESCRIPTION"),
//! plugin_init,
//! concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
//! "The Plugin's License",
//! env!("CARGO_PKG_NAME"),
//! env!("CARGO_PKG_NAME"),
//! env!("CARGO_PKG_REPOSITORY"),
//! env!("BUILD_REL_DATE")
//! );
//! ```
mod git;
use chrono::TimeZone;
use std::convert::TryInto;
use std::time::SystemTime;
use std::{env, fs, path};
/// Extracts release for GStreamer plugin metadata
///
/// Release information is first tried to be extracted from a git repository at the same
/// place as the `Cargo.toml`, or one directory up to allow for Cargo workspaces. If no
/// git repository is found, we assume this is a release.
///
/// - If extracted from a git repository, sets the `COMMIT_ID` environment variable to the short
/// commit id of the latest commit and the `BUILD_REL_DATE` environment variable to the date of the
/// commit.
///
/// - If not, `COMMIT_ID` will be set to the string `RELEASE` and the
/// `BUILD_REL_DATE` variable will be set to the mtime of `Cargo.toml`.
///
/// - If neither is possible, `COMMIT_ID` is set to the string `UNKNOWN` and `BUILD_REL_DATE` to the
/// current date.
///
pub fn get_info() {
let crate_dir =
path::PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
let mut repo_dir = crate_dir.clone();
// First check for a git repository in the manifest directory and if there
// is none try one directory up in case we're in a Cargo workspace
let git_info = git::repo_hash(&repo_dir).or_else(move || {
repo_dir.pop();
git::repo_hash(&repo_dir)
});
// If there is a git repository, extract the version information from there.
// Otherwise assume this is a release and use Cargo.toml mtime as date.
let (commit_id, commit_date) = git_info.unwrap_or_else(|| {
let date = cargo_mtime_date(crate_dir).expect("Failed to get Cargo.toml mtime");
("RELEASE".into(), date)
});
println!("cargo:rustc-env=COMMIT_ID={}", commit_id);
println!("cargo:rustc-env=BUILD_REL_DATE={}", commit_date);
}
fn c
|
crate_dir: path::PathBuf) -> Option<String> {
let mut cargo_toml = crate_dir;
cargo_toml.push("Cargo.toml");
let metadata = fs::metadata(&cargo_toml).ok()?;
let mtime = metadata.modified().ok()?;
let unix_time = mtime.duration_since(SystemTime::UNIX_EPOCH).ok()?;
let dt = chrono::Utc.timestamp(unix_time.as_secs().try_into().ok()?, 0);
Some(dt.format("%Y-%m-%d").to_string())
}
|
argo_mtime_date(
|
identifier_name
|
lib.rs
|
// Copyright (C) 2019 Sajeer Ahamed <[email protected]>
// Copyright (C) 2019 Sebastian Dröge <[email protected]>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Extracts release for [GStreamer](https://gstreamer.freedesktop.org) plugin metadata
//!
//! See [`get_info`](fn.get_info.html) for details.
//!
//! This function is supposed to be used as follows in the `build.rs` of a crate that implements a
//! plugin:
//!
//! ```rust,ignore
//! gst_plugin_version_helper::get_info();
//! ```
//!
//! Inside `lib.rs` of the plugin, the information provided by `get_info` are usable as follows:
//!
//! ```rust,ignore
//! gst_plugin_define!(
//! the_plugin_name,
//! env!("CARGO_PKG_DESCRIPTION"),
//! plugin_init,
//! concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
//! "The Plugin's License",
//! env!("CARGO_PKG_NAME"),
//! env!("CARGO_PKG_NAME"),
//! env!("CARGO_PKG_REPOSITORY"),
//! env!("BUILD_REL_DATE")
//! );
//! ```
mod git;
use chrono::TimeZone;
use std::convert::TryInto;
use std::time::SystemTime;
use std::{env, fs, path};
/// Extracts release for GStreamer plugin metadata
///
/// Release information is first tried to be extracted from a git repository at the same
|
///
/// - If extracted from a git repository, sets the `COMMIT_ID` environment variable to the short
/// commit id of the latest commit and the `BUILD_REL_DATE` environment variable to the date of the
/// commit.
///
/// - If not, `COMMIT_ID` will be set to the string `RELEASE` and the
/// `BUILD_REL_DATE` variable will be set to the mtime of `Cargo.toml`.
///
/// - If neither is possible, `COMMIT_ID` is set to the string `UNKNOWN` and `BUILD_REL_DATE` to the
/// current date.
///
pub fn get_info() {
let crate_dir =
path::PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
let mut repo_dir = crate_dir.clone();
// First check for a git repository in the manifest directory and if there
// is none try one directory up in case we're in a Cargo workspace
let git_info = git::repo_hash(&repo_dir).or_else(move || {
repo_dir.pop();
git::repo_hash(&repo_dir)
});
// If there is a git repository, extract the version information from there.
// Otherwise assume this is a release and use Cargo.toml mtime as date.
let (commit_id, commit_date) = git_info.unwrap_or_else(|| {
let date = cargo_mtime_date(crate_dir).expect("Failed to get Cargo.toml mtime");
("RELEASE".into(), date)
});
println!("cargo:rustc-env=COMMIT_ID={}", commit_id);
println!("cargo:rustc-env=BUILD_REL_DATE={}", commit_date);
}
fn cargo_mtime_date(crate_dir: path::PathBuf) -> Option<String> {
let mut cargo_toml = crate_dir;
cargo_toml.push("Cargo.toml");
let metadata = fs::metadata(&cargo_toml).ok()?;
let mtime = metadata.modified().ok()?;
let unix_time = mtime.duration_since(SystemTime::UNIX_EPOCH).ok()?;
let dt = chrono::Utc.timestamp(unix_time.as_secs().try_into().ok()?, 0);
Some(dt.format("%Y-%m-%d").to_string())
}
|
/// place as the `Cargo.toml`, or one directory up to allow for Cargo workspaces. If no
/// git repository is found, we assume this is a release.
|
random_line_split
|
lib.rs
|
// Copyright (C) 2019 Sajeer Ahamed <[email protected]>
// Copyright (C) 2019 Sebastian Dröge <[email protected]>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Extracts release for [GStreamer](https://gstreamer.freedesktop.org) plugin metadata
//!
//! See [`get_info`](fn.get_info.html) for details.
//!
//! This function is supposed to be used as follows in the `build.rs` of a crate that implements a
//! plugin:
//!
//! ```rust,ignore
//! gst_plugin_version_helper::get_info();
//! ```
//!
//! Inside `lib.rs` of the plugin, the information provided by `get_info` are usable as follows:
//!
//! ```rust,ignore
//! gst_plugin_define!(
//! the_plugin_name,
//! env!("CARGO_PKG_DESCRIPTION"),
//! plugin_init,
//! concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
//! "The Plugin's License",
//! env!("CARGO_PKG_NAME"),
//! env!("CARGO_PKG_NAME"),
//! env!("CARGO_PKG_REPOSITORY"),
//! env!("BUILD_REL_DATE")
//! );
//! ```
mod git;
use chrono::TimeZone;
use std::convert::TryInto;
use std::time::SystemTime;
use std::{env, fs, path};
/// Extracts release for GStreamer plugin metadata
///
/// Release information is first tried to be extracted from a git repository at the same
/// place as the `Cargo.toml`, or one directory up to allow for Cargo workspaces. If no
/// git repository is found, we assume this is a release.
///
/// - If extracted from a git repository, sets the `COMMIT_ID` environment variable to the short
/// commit id of the latest commit and the `BUILD_REL_DATE` environment variable to the date of the
/// commit.
///
/// - If not, `COMMIT_ID` will be set to the string `RELEASE` and the
/// `BUILD_REL_DATE` variable will be set to the mtime of `Cargo.toml`.
///
/// - If neither is possible, `COMMIT_ID` is set to the string `UNKNOWN` and `BUILD_REL_DATE` to the
/// current date.
///
pub fn get_info() {
|
println!("cargo:rustc-env=BUILD_REL_DATE={}", commit_date);
}
fn cargo_mtime_date(crate_dir: path::PathBuf) -> Option<String> {
let mut cargo_toml = crate_dir;
cargo_toml.push("Cargo.toml");
let metadata = fs::metadata(&cargo_toml).ok()?;
let mtime = metadata.modified().ok()?;
let unix_time = mtime.duration_since(SystemTime::UNIX_EPOCH).ok()?;
let dt = chrono::Utc.timestamp(unix_time.as_secs().try_into().ok()?, 0);
Some(dt.format("%Y-%m-%d").to_string())
}
|
let crate_dir =
path::PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
let mut repo_dir = crate_dir.clone();
// First check for a git repository in the manifest directory and if there
// is none try one directory up in case we're in a Cargo workspace
let git_info = git::repo_hash(&repo_dir).or_else(move || {
repo_dir.pop();
git::repo_hash(&repo_dir)
});
// If there is a git repository, extract the version information from there.
// Otherwise assume this is a release and use Cargo.toml mtime as date.
let (commit_id, commit_date) = git_info.unwrap_or_else(|| {
let date = cargo_mtime_date(crate_dir).expect("Failed to get Cargo.toml mtime");
("RELEASE".into(), date)
});
println!("cargo:rustc-env=COMMIT_ID={}", commit_id);
|
identifier_body
|
timer.rs
|
use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn add_timer<'b, 'c>(&'b self, delay: u32, callback: TimerCallback<'c>) -> Timer<'b, 'c> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
raw: timer_id,
_marker: PhantomData
}
}
}
/// Gets the number of milliseconds elapsed since the timer subsystem was initialized.
///
/// It's recommended that you use another library for timekeeping, such as `time`.
pub fn ticks(&mut self) -> u32 {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_GetTicks() }
}
/// Sleeps the current thread for the specified amount of milliseconds.
///
/// It's recommended that you use `std::thread::sleep_ms()` instead.
pub fn
|
(&mut self, ms: u32) {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_Delay(ms) }
}
pub fn performance_counter(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn performance_frequency(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
pub struct Timer<'b, 'a> {
callback: Option<Box<TimerCallback<'a>>>,
raw: ll::SDL_TimerID,
_marker: PhantomData<&'b ()>
}
impl<'b, 'a> Timer<'b, 'a> {
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
impl<'b, 'a> Drop for Timer<'b, 'a> {
#[inline]
fn drop(&mut self) {
// SDL_RemoveTimer returns SDL_FALSE if the timer wasn't found (impossible),
// or the timer has been cancelled via the callback (possible).
// The timer being cancelled isn't an issue, so we ignore the result.
unsafe { ll::SDL_RemoveTimer(self.raw) };
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *mut c_void) -> uint32_t {
unsafe {
let f: *mut Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
::std::thread::sleep_ms(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[cfg(test)]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
::std::thread::sleep_ms(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[cfg(test)]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = timer_subsystem.add_timer(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
::std::thread::sleep_ms(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = timer_subsystem.add_timer(20, closure);
::std::thread::sleep_ms(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
#[test]
fn test_timer() {
test_timer_runs_multiple_times();
test_timer_runs_at_least_once();
test_timer_can_be_recreated();
}
|
delay
|
identifier_name
|
timer.rs
|
use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn add_timer<'b, 'c>(&'b self, delay: u32, callback: TimerCallback<'c>) -> Timer<'b, 'c> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
raw: timer_id,
_marker: PhantomData
}
}
}
/// Gets the number of milliseconds elapsed since the timer subsystem was initialized.
///
/// It's recommended that you use another library for timekeeping, such as `time`.
pub fn ticks(&mut self) -> u32 {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_GetTicks() }
}
/// Sleeps the current thread for the specified amount of milliseconds.
///
/// It's recommended that you use `std::thread::sleep_ms()` instead.
pub fn delay(&mut self, ms: u32) {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_Delay(ms) }
}
pub fn performance_counter(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn performance_frequency(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
pub struct Timer<'b, 'a> {
callback: Option<Box<TimerCallback<'a>>>,
raw: ll::SDL_TimerID,
_marker: PhantomData<&'b ()>
}
impl<'b, 'a> Timer<'b, 'a> {
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
impl<'b, 'a> Drop for Timer<'b, 'a> {
#[inline]
fn drop(&mut self) {
// SDL_RemoveTimer returns SDL_FALSE if the timer wasn't found (impossible),
// or the timer has been cancelled via the callback (possible).
// The timer being cancelled isn't an issue, so we ignore the result.
unsafe { ll::SDL_RemoveTimer(self.raw) };
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *mut c_void) -> uint32_t {
unsafe {
let f: *mut Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
::std::thread::sleep_ms(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[cfg(test)]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
::std::thread::sleep_ms(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
|
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = timer_subsystem.add_timer(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
::std::thread::sleep_ms(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = timer_subsystem.add_timer(20, closure);
::std::thread::sleep_ms(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
#[test]
fn test_timer() {
test_timer_runs_multiple_times();
test_timer_runs_at_least_once();
test_timer_can_be_recreated();
}
|
#[cfg(test)]
|
random_line_split
|
timer.rs
|
use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn add_timer<'b, 'c>(&'b self, delay: u32, callback: TimerCallback<'c>) -> Timer<'b, 'c> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
raw: timer_id,
_marker: PhantomData
}
}
}
/// Gets the number of milliseconds elapsed since the timer subsystem was initialized.
///
/// It's recommended that you use another library for timekeeping, such as `time`.
pub fn ticks(&mut self) -> u32 {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_GetTicks() }
}
/// Sleeps the current thread for the specified amount of milliseconds.
///
/// It's recommended that you use `std::thread::sleep_ms()` instead.
pub fn delay(&mut self, ms: u32) {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_Delay(ms) }
}
pub fn performance_counter(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn performance_frequency(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
pub struct Timer<'b, 'a> {
callback: Option<Box<TimerCallback<'a>>>,
raw: ll::SDL_TimerID,
_marker: PhantomData<&'b ()>
}
impl<'b, 'a> Timer<'b, 'a> {
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
impl<'b, 'a> Drop for Timer<'b, 'a> {
#[inline]
fn drop(&mut self) {
// SDL_RemoveTimer returns SDL_FALSE if the timer wasn't found (impossible),
// or the timer has been cancelled via the callback (possible).
// The timer being cancelled isn't an issue, so we ignore the result.
unsafe { ll::SDL_RemoveTimer(self.raw) };
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *mut c_void) -> uint32_t {
unsafe {
let f: *mut Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
#[cfg(test)]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9
|
else { 0 }
}));
::std::thread::sleep_ms(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[cfg(test)]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
::std::thread::sleep_ms(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[cfg(test)]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = timer_subsystem.add_timer(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
::std::thread::sleep_ms(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = timer_subsystem.add_timer(20, closure);
::std::thread::sleep_ms(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
#[test]
fn test_timer() {
test_timer_runs_multiple_times();
test_timer_runs_at_least_once();
test_timer_can_be_recreated();
}
|
{
*num += 1;
20
}
|
conditional_block
|
timer.rs
|
use libc::{uint32_t, c_void};
use std::marker::PhantomData;
use std::mem;
use sys::timer as ll;
use TimerSubsystem;
impl TimerSubsystem {
/// Constructs a new timer using the boxed closure `callback`.
///
/// The timer is started immediately, it will be cancelled either:
///
/// * when the timer is dropped
/// * or when the callback returns a non-positive continuation interval
pub fn add_timer<'b, 'c>(&'b self, delay: u32, callback: TimerCallback<'c>) -> Timer<'b, 'c> {
unsafe {
let callback = Box::new(callback);
let timer_id = ll::SDL_AddTimer(delay,
Some(c_timer_callback),
mem::transmute_copy(&callback));
Timer {
callback: Some(callback),
raw: timer_id,
_marker: PhantomData
}
}
}
/// Gets the number of milliseconds elapsed since the timer subsystem was initialized.
///
/// It's recommended that you use another library for timekeeping, such as `time`.
pub fn ticks(&mut self) -> u32 {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_GetTicks() }
}
/// Sleeps the current thread for the specified amount of milliseconds.
///
/// It's recommended that you use `std::thread::sleep_ms()` instead.
pub fn delay(&mut self, ms: u32) {
// Google says this is probably not thread-safe (TODO: prove/disprove this).
unsafe { ll::SDL_Delay(ms) }
}
pub fn performance_counter(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceCounter() }
}
pub fn performance_frequency(&self) -> u64 {
unsafe { ll::SDL_GetPerformanceFrequency() }
}
}
pub type TimerCallback<'a> = Box<FnMut() -> u32+'a+Sync>;
pub struct Timer<'b, 'a> {
callback: Option<Box<TimerCallback<'a>>>,
raw: ll::SDL_TimerID,
_marker: PhantomData<&'b ()>
}
impl<'b, 'a> Timer<'b, 'a> {
/// Returns the closure as a trait-object and cancels the timer
/// by consuming it...
pub fn into_inner(mut self) -> TimerCallback<'a> {
*self.callback.take().unwrap()
}
}
impl<'b, 'a> Drop for Timer<'b, 'a> {
#[inline]
fn drop(&mut self) {
// SDL_RemoveTimer returns SDL_FALSE if the timer wasn't found (impossible),
// or the timer has been cancelled via the callback (possible).
// The timer being cancelled isn't an issue, so we ignore the result.
unsafe { ll::SDL_RemoveTimer(self.raw) };
}
}
extern "C" fn c_timer_callback(_interval: u32, param: *mut c_void) -> uint32_t
|
#[cfg(test)]
fn test_timer_runs_multiple_times() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
// increment up to 10 times (0 -> 9)
// tick again in 100ms after each increment
//
let mut num = timer_num.lock().unwrap();
if *num < 9 {
*num += 1;
20
} else { 0 }
}));
::std::thread::sleep_ms(250); // tick the timer at least 10 times w/ 200ms of "buffer"
let num = local_num.lock().unwrap(); // read the number back
assert_eq!(*num, 9); // it should have incremented at least 10 times...
}
#[cfg(test)]
fn test_timer_runs_at_least_once() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_flag = Arc::new(Mutex::new(false));
let timer_flag = local_flag.clone();
let _timer = timer_subsystem.add_timer(20, Box::new(|| {
let mut flag = timer_flag.lock().unwrap();
*flag = true; 0
}));
::std::thread::sleep_ms(50);
let flag = local_flag.lock().unwrap();
assert_eq!(*flag, true);
}
#[cfg(test)]
fn test_timer_can_be_recreated() {
use std::sync::{Arc, Mutex};
let sdl_context = ::sdl::init().unwrap();
let timer_subsystem = sdl_context.timer().unwrap();
let local_num = Arc::new(Mutex::new(0));
let timer_num = local_num.clone();
// run the timer once and reclaim its closure
let timer_1 = timer_subsystem.add_timer(20, Box::new(move|| {
let mut num = timer_num.lock().unwrap();
*num += 1; // increment the number
0 // do not run timer again
}));
// reclaim closure after timer runs
::std::thread::sleep_ms(50);
let closure = timer_1.into_inner();
// create a second timer and increment again
let _timer_2 = timer_subsystem.add_timer(20, closure);
::std::thread::sleep_ms(50);
// check that timer was incremented twice
let num = local_num.lock().unwrap();
assert_eq!(*num, 2);
}
#[test]
fn test_timer() {
test_timer_runs_multiple_times();
test_timer_runs_at_least_once();
test_timer_can_be_recreated();
}
|
{
unsafe {
let f: *mut Box<Fn() -> u32> = mem::transmute(param);
(*f)() as uint32_t
}
}
|
identifier_body
|
automata.rs
|
// Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
|
const S0:&'static str = "S0";
const S1:&'static str = "S1";
const S2:&'static str = "S2";
fn assert_state(state:&'static str,desired:&'static str) -> bool {
state == desired
}
#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
let mut state = S0;
// initializing the dfa to the start state with any symbol
if s.len() > 0 {state=S1;} else {return false;}
for i in s.chars() {
if i=='1' && assert_state(&state,S1)
{state = S1;}
else if i=='0' && assert_state(&state,S1)
{state = S2;}
else if i=='0' && assert_state(&state,S2)
{state = S1;}
else if i=='1' && assert_state(&state,S2)
{state = S2;}
}
// automatic boolean return from match arm
assert_state(&state,S1)
}
pub fn init_fsm(st:&String) {
if dfa(st) {println!("Language accepted by the dfa");}
else {println!("Language not recognized");}
}
#[test]
fn test_dfa() {
let string = "100".to_string();
if dfa(&string) {
println!("Language accepted by the dfa");
}else {
println!("Language not recognized");
}
}
}
|
pub mod even_zeros_dfa {
|
random_line_split
|
automata.rs
|
// Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
pub mod even_zeros_dfa {
const S0:&'static str = "S0";
const S1:&'static str = "S1";
const S2:&'static str = "S2";
fn assert_state(state:&'static str,desired:&'static str) -> bool {
state == desired
}
#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
let mut state = S0;
// initializing the dfa to the start state with any symbol
if s.len() > 0 {state=S1;} else {return false;}
for i in s.chars() {
if i=='1' && assert_state(&state,S1)
{state = S1;}
else if i=='0' && assert_state(&state,S1)
{state = S2;}
else if i=='0' && assert_state(&state,S2)
{state = S1;}
else if i=='1' && assert_state(&state,S2)
{state = S2;}
}
// automatic boolean return from match arm
assert_state(&state,S1)
}
pub fn init_fsm(st:&String) {
if dfa(st) {println!("Language accepted by the dfa");}
else
|
}
#[test]
fn test_dfa() {
let string = "100".to_string();
if dfa(&string) {
println!("Language accepted by the dfa");
}else {
println!("Language not recognized");
}
}
}
|
{println!("Language not recognized");}
|
conditional_block
|
automata.rs
|
// Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
pub mod even_zeros_dfa {
const S0:&'static str = "S0";
const S1:&'static str = "S1";
const S2:&'static str = "S2";
fn assert_state(state:&'static str,desired:&'static str) -> bool
|
#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
let mut state = S0;
// initializing the dfa to the start state with any symbol
if s.len() > 0 {state=S1;} else {return false;}
for i in s.chars() {
if i=='1' && assert_state(&state,S1)
{state = S1;}
else if i=='0' && assert_state(&state,S1)
{state = S2;}
else if i=='0' && assert_state(&state,S2)
{state = S1;}
else if i=='1' && assert_state(&state,S2)
{state = S2;}
}
// automatic boolean return from match arm
assert_state(&state,S1)
}
pub fn init_fsm(st:&String) {
if dfa(st) {println!("Language accepted by the dfa");}
else {println!("Language not recognized");}
}
#[test]
fn test_dfa() {
let string = "100".to_string();
if dfa(&string) {
println!("Language accepted by the dfa");
}else {
println!("Language not recognized");
}
}
}
|
{
state == desired
}
|
identifier_body
|
automata.rs
|
// Transition table for a language consisting of strings having even number of zeroes ( that includes having no zeroes as well )
//____________
//S1 | 1 -> S1
//S1 | 0 -> S2
//S2 | 0 -> S1
//S2 | 1 -> S2
//------------
/*#[derive(Debug)]
enum STATE {
S0,
S1,
S2,
}*/
pub mod even_zeros_dfa {
const S0:&'static str = "S0";
const S1:&'static str = "S1";
const S2:&'static str = "S2";
fn assert_state(state:&'static str,desired:&'static str) -> bool {
state == desired
}
#[allow(unused_assignments)]
fn dfa(s:&String) -> bool {
let mut state = S0;
// initializing the dfa to the start state with any symbol
if s.len() > 0 {state=S1;} else {return false;}
for i in s.chars() {
if i=='1' && assert_state(&state,S1)
{state = S1;}
else if i=='0' && assert_state(&state,S1)
{state = S2;}
else if i=='0' && assert_state(&state,S2)
{state = S1;}
else if i=='1' && assert_state(&state,S2)
{state = S2;}
}
// automatic boolean return from match arm
assert_state(&state,S1)
}
pub fn init_fsm(st:&String) {
if dfa(st) {println!("Language accepted by the dfa");}
else {println!("Language not recognized");}
}
#[test]
fn
|
() {
let string = "100".to_string();
if dfa(&string) {
println!("Language accepted by the dfa");
}else {
println!("Language not recognized");
}
}
}
|
test_dfa
|
identifier_name
|
util.rs
|
#![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflect w around wh
pub fn reflect(w: Vector3<Float>, wh: Vector3<Float>) -> Vector3<Float> {
-w + 2.0 * wh.dot(w) * wh
}
/// Reflect w around n
pub fn reflect_n(w: Vector3<Float>) -> Vector3<Float> {
Vector3::new(-w.x, -w.y, w.z)
}
/// Refract w around wh, which is assumed to be in the same hemisphere as w.
/// eta_mat defines the index of refraction inside the material (outside is assumed to be air).
pub fn refract(w: Vector3<Float>, wh: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Determine if w is entering or exiting the material
let eta = eta(w, eta_mat);
let cos_ti = w.dot(wh).abs();
let sin2_ti = (1.0 - cos_ti.powi(2)).max(0.0);
let sin2_tt = eta.powi(2) * sin2_ti;
// Total internal reflection
if sin2_tt >= 1.0 {
return None;
}
let cos_tt = (1.0 - sin2_tt).sqrt();
Some(-w * eta + (eta * cos_ti - cos_tt) * wh)
}
/// Refract w around the shading normal (0, 0, 1)
pub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Make sure normal is in the same hemisphere as w
let n = w.z.signum() * Vector3::unit_z();
refract(w, n, eta_mat)
}
/// Compute the total index of refraction for incident direction w.
pub fn eta(w: Vector3<Float>, eta_mat: Float) -> Float {
if w.z > 0.0 {
1.0 / eta_mat
} else {
eta_mat
}
}
// Trigonometric functions
pub fn cos_t(vec: Vector3<Float>) -> Float {
vec.z
}
pub fn cos2_t(vec: Vector3<Float>) -> Float {
vec.z * vec.z
}
pub fn sin2_t(vec: Vector3<Float>) -> Float {
1.0 - cos2_t(vec)
}
pub fn sin_t(vec: Vector3<Float>) -> Float {
sin2_t(vec).sqrt()
}
pub fn
|
(vec: Vector3<Float>) -> Float {
sin2_t(vec) / cos2_t(vec)
}
|
tan2_t
|
identifier_name
|
util.rs
|
#![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflect w around wh
pub fn reflect(w: Vector3<Float>, wh: Vector3<Float>) -> Vector3<Float> {
-w + 2.0 * wh.dot(w) * wh
}
/// Reflect w around n
pub fn reflect_n(w: Vector3<Float>) -> Vector3<Float> {
Vector3::new(-w.x, -w.y, w.z)
}
/// Refract w around wh, which is assumed to be in the same hemisphere as w.
/// eta_mat defines the index of refraction inside the material (outside is assumed to be air).
pub fn refract(w: Vector3<Float>, wh: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Determine if w is entering or exiting the material
let eta = eta(w, eta_mat);
let cos_ti = w.dot(wh).abs();
let sin2_ti = (1.0 - cos_ti.powi(2)).max(0.0);
let sin2_tt = eta.powi(2) * sin2_ti;
// Total internal reflection
if sin2_tt >= 1.0 {
return None;
}
let cos_tt = (1.0 - sin2_tt).sqrt();
Some(-w * eta + (eta * cos_ti - cos_tt) * wh)
}
/// Refract w around the shading normal (0, 0, 1)
pub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Make sure normal is in the same hemisphere as w
let n = w.z.signum() * Vector3::unit_z();
refract(w, n, eta_mat)
}
/// Compute the total index of refraction for incident direction w.
pub fn eta(w: Vector3<Float>, eta_mat: Float) -> Float {
if w.z > 0.0 {
1.0 / eta_mat
} else {
eta_mat
}
}
// Trigonometric functions
pub fn cos_t(vec: Vector3<Float>) -> Float {
vec.z
}
pub fn cos2_t(vec: Vector3<Float>) -> Float {
vec.z * vec.z
}
pub fn sin2_t(vec: Vector3<Float>) -> Float
|
pub fn sin_t(vec: Vector3<Float>) -> Float {
sin2_t(vec).sqrt()
}
pub fn tan2_t(vec: Vector3<Float>) -> Float {
sin2_t(vec) / cos2_t(vec)
}
|
{
1.0 - cos2_t(vec)
}
|
identifier_body
|
util.rs
|
#![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflect w around wh
pub fn reflect(w: Vector3<Float>, wh: Vector3<Float>) -> Vector3<Float> {
-w + 2.0 * wh.dot(w) * wh
}
/// Reflect w around n
pub fn reflect_n(w: Vector3<Float>) -> Vector3<Float> {
Vector3::new(-w.x, -w.y, w.z)
}
/// Refract w around wh, which is assumed to be in the same hemisphere as w.
/// eta_mat defines the index of refraction inside the material (outside is assumed to be air).
pub fn refract(w: Vector3<Float>, wh: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Determine if w is entering or exiting the material
let eta = eta(w, eta_mat);
let cos_ti = w.dot(wh).abs();
let sin2_ti = (1.0 - cos_ti.powi(2)).max(0.0);
let sin2_tt = eta.powi(2) * sin2_ti;
// Total internal reflection
if sin2_tt >= 1.0
|
let cos_tt = (1.0 - sin2_tt).sqrt();
Some(-w * eta + (eta * cos_ti - cos_tt) * wh)
}
/// Refract w around the shading normal (0, 0, 1)
pub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Make sure normal is in the same hemisphere as w
let n = w.z.signum() * Vector3::unit_z();
refract(w, n, eta_mat)
}
/// Compute the total index of refraction for incident direction w.
pub fn eta(w: Vector3<Float>, eta_mat: Float) -> Float {
if w.z > 0.0 {
1.0 / eta_mat
} else {
eta_mat
}
}
// Trigonometric functions
pub fn cos_t(vec: Vector3<Float>) -> Float {
vec.z
}
pub fn cos2_t(vec: Vector3<Float>) -> Float {
vec.z * vec.z
}
pub fn sin2_t(vec: Vector3<Float>) -> Float {
1.0 - cos2_t(vec)
}
pub fn sin_t(vec: Vector3<Float>) -> Float {
sin2_t(vec).sqrt()
}
pub fn tan2_t(vec: Vector3<Float>) -> Float {
sin2_t(vec) / cos2_t(vec)
}
|
{
return None;
}
|
conditional_block
|
util.rs
|
#![allow(dead_code)]
//! Utility functions for operating on vectors in shading coordinates
use cgmath::prelude::*;
use cgmath::Vector3;
use crate::float::*;
/// Check if the vectors are in the same hemisphere
pub fn same_hemisphere(w1: Vector3<Float>, w2: Vector3<Float>) -> bool {
w1.z * w2.z > 0.0
}
/// Reflect w around wh
pub fn reflect(w: Vector3<Float>, wh: Vector3<Float>) -> Vector3<Float> {
-w + 2.0 * wh.dot(w) * wh
}
/// Reflect w around n
pub fn reflect_n(w: Vector3<Float>) -> Vector3<Float> {
Vector3::new(-w.x, -w.y, w.z)
}
/// Refract w around wh, which is assumed to be in the same hemisphere as w.
/// eta_mat defines the index of refraction inside the material (outside is assumed to be air).
pub fn refract(w: Vector3<Float>, wh: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Determine if w is entering or exiting the material
let eta = eta(w, eta_mat);
let cos_ti = w.dot(wh).abs();
let sin2_ti = (1.0 - cos_ti.powi(2)).max(0.0);
let sin2_tt = eta.powi(2) * sin2_ti;
|
if sin2_tt >= 1.0 {
return None;
}
let cos_tt = (1.0 - sin2_tt).sqrt();
Some(-w * eta + (eta * cos_ti - cos_tt) * wh)
}
/// Refract w around the shading normal (0, 0, 1)
pub fn refract_n(w: Vector3<Float>, eta_mat: Float) -> Option<Vector3<Float>> {
// Make sure normal is in the same hemisphere as w
let n = w.z.signum() * Vector3::unit_z();
refract(w, n, eta_mat)
}
/// Compute the total index of refraction for incident direction w.
pub fn eta(w: Vector3<Float>, eta_mat: Float) -> Float {
if w.z > 0.0 {
1.0 / eta_mat
} else {
eta_mat
}
}
// Trigonometric functions
pub fn cos_t(vec: Vector3<Float>) -> Float {
vec.z
}
pub fn cos2_t(vec: Vector3<Float>) -> Float {
vec.z * vec.z
}
pub fn sin2_t(vec: Vector3<Float>) -> Float {
1.0 - cos2_t(vec)
}
pub fn sin_t(vec: Vector3<Float>) -> Float {
sin2_t(vec).sqrt()
}
pub fn tan2_t(vec: Vector3<Float>) -> Float {
sin2_t(vec) / cos2_t(vec)
}
|
// Total internal reflection
|
random_line_split
|
camera.rs
|
//! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two rotations.
pub struct T {
#[allow(missing_docs)]
pub position: Point3<f32>,
#[allow(missing_docs)]
lateral_rotation: f32,
#[allow(missing_docs)]
vertical_rotation: f32,
// Projection matrix components
#[allow(missing_docs)]
pub translation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub rotation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub fov: Matrix4<GLfloat>,
}
/// This T sits at (0, 0, 0),
/// maps [-1, 1] in x horizontally,
/// maps [-1, 1] in y vertically,
/// and [0, -1] in z in depth.
pub fn unit() -> T
|
impl T {
#[allow(missing_docs)]
pub fn projection_matrix(&self) -> Matrix4<GLfloat> {
self.fov * self.rotation * self.translation
}
#[allow(missing_docs)]
pub fn translate_to(&mut self, p: Point3<f32>) {
self.position = p;
self.translation = Matrix4::from_translation(-p.to_vec());
}
/// Rotate about a given vector, by `r` radians.
fn rotate(&mut self, v: &Vector3<f32>, r: f32) {
let mat = Matrix3::from_axis_angle(*v, -cgmath::Rad(r));
let mat =
Matrix4::new(
mat.x.x, mat.x.y, mat.x.z, 0.0,
mat.y.x, mat.y.y, mat.y.z, 0.0,
mat.z.x, mat.z.y, mat.z.z, 0.0,
0.0, 0.0, 0.0, 1.0,
);
self.rotation = self.rotation * mat;
}
/// Rotate the camera around the y axis, by `r` radians. Positive is counterclockwise.
pub fn rotate_lateral(&mut self, r: GLfloat) {
self.lateral_rotation = self.lateral_rotation + r;
self.rotate(&Vector3::new(0.0, 1.0, 0.0), r);
}
/// Changes the camera pitch by `r` radians. Positive is up.
/// Angles that "flip around" (i.e. looking too far up or down)
/// are sliently rejected.
pub fn rotate_vertical(&mut self, r: GLfloat) {
let new_rotation = self.vertical_rotation + r;
if new_rotation < -PI / 2.0
|| new_rotation > PI / 2.0 {
return
}
self.vertical_rotation = new_rotation;
let axis =
Matrix3::from_axis_angle(
Vector3::new(0.0, 1.0, 0.0),
cgmath::Rad(self.lateral_rotation),
);
let axis = axis * (&Vector3::new(1.0, 0.0, 0.0));
self.rotate(&axis, r);
}
}
/// Set a shader's projection matrix to match that of a camera.
pub fn set_camera(shader: &mut Shader, gl: &mut GLContext, c: &T) {
let projection_matrix = shader.get_uniform_location("projection_matrix");
shader.use_shader(gl);
unsafe {
let val = c.projection_matrix();
let ptr = &val as *const _ as *const _;
gl::UniformMatrix4fv(projection_matrix, 1, 0, ptr);
}
}
|
{
T {
position : Point3::new(0.0, 0.0, 0.0),
lateral_rotation : 0.0,
vertical_rotation : 0.0,
translation : Matrix4::one(),
rotation : Matrix4::one(),
fov : Matrix4::one(),
}
}
|
identifier_body
|
camera.rs
|
//! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two rotations.
pub struct T {
#[allow(missing_docs)]
pub position: Point3<f32>,
#[allow(missing_docs)]
lateral_rotation: f32,
#[allow(missing_docs)]
vertical_rotation: f32,
// Projection matrix components
#[allow(missing_docs)]
pub translation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub rotation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub fov: Matrix4<GLfloat>,
}
/// This T sits at (0, 0, 0),
/// maps [-1, 1] in x horizontally,
/// maps [-1, 1] in y vertically,
/// and [0, -1] in z in depth.
pub fn unit() -> T {
T {
position : Point3::new(0.0, 0.0, 0.0),
lateral_rotation : 0.0,
vertical_rotation : 0.0,
translation : Matrix4::one(),
rotation : Matrix4::one(),
fov : Matrix4::one(),
}
}
impl T {
#[allow(missing_docs)]
pub fn projection_matrix(&self) -> Matrix4<GLfloat> {
self.fov * self.rotation * self.translation
}
#[allow(missing_docs)]
pub fn translate_to(&mut self, p: Point3<f32>) {
self.position = p;
self.translation = Matrix4::from_translation(-p.to_vec());
}
/// Rotate about a given vector, by `r` radians.
fn rotate(&mut self, v: &Vector3<f32>, r: f32) {
let mat = Matrix3::from_axis_angle(*v, -cgmath::Rad(r));
let mat =
Matrix4::new(
mat.x.x, mat.x.y, mat.x.z, 0.0,
mat.y.x, mat.y.y, mat.y.z, 0.0,
mat.z.x, mat.z.y, mat.z.z, 0.0,
0.0, 0.0, 0.0, 1.0,
);
self.rotation = self.rotation * mat;
}
/// Rotate the camera around the y axis, by `r` radians. Positive is counterclockwise.
pub fn rotate_lateral(&mut self, r: GLfloat) {
|
/// Changes the camera pitch by `r` radians. Positive is up.
/// Angles that "flip around" (i.e. looking too far up or down)
/// are sliently rejected.
pub fn rotate_vertical(&mut self, r: GLfloat) {
let new_rotation = self.vertical_rotation + r;
if new_rotation < -PI / 2.0
|| new_rotation > PI / 2.0 {
return
}
self.vertical_rotation = new_rotation;
let axis =
Matrix3::from_axis_angle(
Vector3::new(0.0, 1.0, 0.0),
cgmath::Rad(self.lateral_rotation),
);
let axis = axis * (&Vector3::new(1.0, 0.0, 0.0));
self.rotate(&axis, r);
}
}
/// Set a shader's projection matrix to match that of a camera.
pub fn set_camera(shader: &mut Shader, gl: &mut GLContext, c: &T) {
let projection_matrix = shader.get_uniform_location("projection_matrix");
shader.use_shader(gl);
unsafe {
let val = c.projection_matrix();
let ptr = &val as *const _ as *const _;
gl::UniformMatrix4fv(projection_matrix, 1, 0, ptr);
}
}
|
self.lateral_rotation = self.lateral_rotation + r;
self.rotate(&Vector3::new(0.0, 1.0, 0.0), r);
}
|
random_line_split
|
camera.rs
|
//! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two rotations.
pub struct T {
#[allow(missing_docs)]
pub position: Point3<f32>,
#[allow(missing_docs)]
lateral_rotation: f32,
#[allow(missing_docs)]
vertical_rotation: f32,
// Projection matrix components
#[allow(missing_docs)]
pub translation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub rotation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub fov: Matrix4<GLfloat>,
}
/// This T sits at (0, 0, 0),
/// maps [-1, 1] in x horizontally,
/// maps [-1, 1] in y vertically,
/// and [0, -1] in z in depth.
pub fn unit() -> T {
T {
position : Point3::new(0.0, 0.0, 0.0),
lateral_rotation : 0.0,
vertical_rotation : 0.0,
translation : Matrix4::one(),
rotation : Matrix4::one(),
fov : Matrix4::one(),
}
}
impl T {
#[allow(missing_docs)]
pub fn projection_matrix(&self) -> Matrix4<GLfloat> {
self.fov * self.rotation * self.translation
}
#[allow(missing_docs)]
pub fn translate_to(&mut self, p: Point3<f32>) {
self.position = p;
self.translation = Matrix4::from_translation(-p.to_vec());
}
/// Rotate about a given vector, by `r` radians.
fn rotate(&mut self, v: &Vector3<f32>, r: f32) {
let mat = Matrix3::from_axis_angle(*v, -cgmath::Rad(r));
let mat =
Matrix4::new(
mat.x.x, mat.x.y, mat.x.z, 0.0,
mat.y.x, mat.y.y, mat.y.z, 0.0,
mat.z.x, mat.z.y, mat.z.z, 0.0,
0.0, 0.0, 0.0, 1.0,
);
self.rotation = self.rotation * mat;
}
/// Rotate the camera around the y axis, by `r` radians. Positive is counterclockwise.
pub fn rotate_lateral(&mut self, r: GLfloat) {
self.lateral_rotation = self.lateral_rotation + r;
self.rotate(&Vector3::new(0.0, 1.0, 0.0), r);
}
/// Changes the camera pitch by `r` radians. Positive is up.
/// Angles that "flip around" (i.e. looking too far up or down)
/// are sliently rejected.
pub fn rotate_vertical(&mut self, r: GLfloat) {
let new_rotation = self.vertical_rotation + r;
if new_rotation < -PI / 2.0
|| new_rotation > PI / 2.0
|
self.vertical_rotation = new_rotation;
let axis =
Matrix3::from_axis_angle(
Vector3::new(0.0, 1.0, 0.0),
cgmath::Rad(self.lateral_rotation),
);
let axis = axis * (&Vector3::new(1.0, 0.0, 0.0));
self.rotate(&axis, r);
}
}
/// Set a shader's projection matrix to match that of a camera.
pub fn set_camera(shader: &mut Shader, gl: &mut GLContext, c: &T) {
let projection_matrix = shader.get_uniform_location("projection_matrix");
shader.use_shader(gl);
unsafe {
let val = c.projection_matrix();
let ptr = &val as *const _ as *const _;
gl::UniformMatrix4fv(projection_matrix, 1, 0, ptr);
}
}
|
{
return
}
|
conditional_block
|
camera.rs
|
//! Camera structure and manipulation functions.
use gl;
use gl::types::*;
use cgmath;
use cgmath::{Matrix3, Matrix4, One, Vector3, Point3, EuclideanSpace};
use std::f32::consts::PI;
use yaglw::gl_context::GLContext;
use yaglw::shader::Shader;
/// T representation as 3 distinct matrices, as well as a position + two rotations.
pub struct T {
#[allow(missing_docs)]
pub position: Point3<f32>,
#[allow(missing_docs)]
lateral_rotation: f32,
#[allow(missing_docs)]
vertical_rotation: f32,
// Projection matrix components
#[allow(missing_docs)]
pub translation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub rotation: Matrix4<GLfloat>,
#[allow(missing_docs)]
pub fov: Matrix4<GLfloat>,
}
/// This T sits at (0, 0, 0),
/// maps [-1, 1] in x horizontally,
/// maps [-1, 1] in y vertically,
/// and [0, -1] in z in depth.
pub fn unit() -> T {
T {
position : Point3::new(0.0, 0.0, 0.0),
lateral_rotation : 0.0,
vertical_rotation : 0.0,
translation : Matrix4::one(),
rotation : Matrix4::one(),
fov : Matrix4::one(),
}
}
impl T {
#[allow(missing_docs)]
pub fn projection_matrix(&self) -> Matrix4<GLfloat> {
self.fov * self.rotation * self.translation
}
#[allow(missing_docs)]
pub fn
|
(&mut self, p: Point3<f32>) {
self.position = p;
self.translation = Matrix4::from_translation(-p.to_vec());
}
/// Rotate about a given vector, by `r` radians.
fn rotate(&mut self, v: &Vector3<f32>, r: f32) {
let mat = Matrix3::from_axis_angle(*v, -cgmath::Rad(r));
let mat =
Matrix4::new(
mat.x.x, mat.x.y, mat.x.z, 0.0,
mat.y.x, mat.y.y, mat.y.z, 0.0,
mat.z.x, mat.z.y, mat.z.z, 0.0,
0.0, 0.0, 0.0, 1.0,
);
self.rotation = self.rotation * mat;
}
/// Rotate the camera around the y axis, by `r` radians. Positive is counterclockwise.
pub fn rotate_lateral(&mut self, r: GLfloat) {
self.lateral_rotation = self.lateral_rotation + r;
self.rotate(&Vector3::new(0.0, 1.0, 0.0), r);
}
/// Changes the camera pitch by `r` radians. Positive is up.
/// Angles that "flip around" (i.e. looking too far up or down)
/// are sliently rejected.
pub fn rotate_vertical(&mut self, r: GLfloat) {
let new_rotation = self.vertical_rotation + r;
if new_rotation < -PI / 2.0
|| new_rotation > PI / 2.0 {
return
}
self.vertical_rotation = new_rotation;
let axis =
Matrix3::from_axis_angle(
Vector3::new(0.0, 1.0, 0.0),
cgmath::Rad(self.lateral_rotation),
);
let axis = axis * (&Vector3::new(1.0, 0.0, 0.0));
self.rotate(&axis, r);
}
}
/// Set a shader's projection matrix to match that of a camera.
pub fn set_camera(shader: &mut Shader, gl: &mut GLContext, c: &T) {
let projection_matrix = shader.get_uniform_location("projection_matrix");
shader.use_shader(gl);
unsafe {
let val = c.projection_matrix();
let ptr = &val as *const _ as *const _;
gl::UniformMatrix4fv(projection_matrix, 1, 0, ptr);
}
}
|
translate_to
|
identifier_name
|
modulo_one.rs
|
#![warn(clippy::modulo_one)]
#![allow(clippy::no_effect, clippy::unnecessary_operation)]
static STATIC_ONE: usize = 2 - 1;
static STATIC_NEG_ONE: i64 = 1 - 2;
fn main()
|
{
10 % 1;
10 % -1;
10 % 2;
i32::MIN % (-1); // also caught by rustc
const ONE: u32 = 1 * 1;
const NEG_ONE: i64 = 1 - 2;
const INT_MIN: i64 = i64::MIN;
2 % ONE;
5 % STATIC_ONE; // NOT caught by lint
2 % NEG_ONE;
5 % STATIC_NEG_ONE; // NOT caught by lint
INT_MIN % NEG_ONE; // also caught by rustc
INT_MIN % STATIC_NEG_ONE; // ONLY caught by rustc
}
|
identifier_body
|
|
modulo_one.rs
|
#![warn(clippy::modulo_one)]
#![allow(clippy::no_effect, clippy::unnecessary_operation)]
static STATIC_ONE: usize = 2 - 1;
static STATIC_NEG_ONE: i64 = 1 - 2;
fn
|
() {
10 % 1;
10 % -1;
10 % 2;
i32::MIN % (-1); // also caught by rustc
const ONE: u32 = 1 * 1;
const NEG_ONE: i64 = 1 - 2;
const INT_MIN: i64 = i64::MIN;
2 % ONE;
5 % STATIC_ONE; // NOT caught by lint
2 % NEG_ONE;
5 % STATIC_NEG_ONE; // NOT caught by lint
INT_MIN % NEG_ONE; // also caught by rustc
INT_MIN % STATIC_NEG_ONE; // ONLY caught by rustc
}
|
main
|
identifier_name
|
modulo_one.rs
|
#![warn(clippy::modulo_one)]
#![allow(clippy::no_effect, clippy::unnecessary_operation)]
static STATIC_ONE: usize = 2 - 1;
static STATIC_NEG_ONE: i64 = 1 - 2;
fn main() {
|
i32::MIN % (-1); // also caught by rustc
const ONE: u32 = 1 * 1;
const NEG_ONE: i64 = 1 - 2;
const INT_MIN: i64 = i64::MIN;
2 % ONE;
5 % STATIC_ONE; // NOT caught by lint
2 % NEG_ONE;
5 % STATIC_NEG_ONE; // NOT caught by lint
INT_MIN % NEG_ONE; // also caught by rustc
INT_MIN % STATIC_NEG_ONE; // ONLY caught by rustc
}
|
10 % 1;
10 % -1;
10 % 2;
|
random_line_split
|
range_expansion.rs
|
// http://rosettacode.org/wiki/Range_expansion
extern crate regex;
#[cfg(not(test))]
fn main() {
let range = "-6,-3-1,3-5,7-11,14,15,17-20";
println!("Expanded range: {:?}", expand_range(range));
}
// Expand a string containing numbers and ranges, into a vector of numbers
fn expand_range(range: &str) -> Vec<isize> {
let mut result = vec![];
for item in range.split(',') {
result.extend(expand_item(item).into_iter());
}
result
}
// Expand a single element, which can be a number or a range.
fn expand_item(item: &str) -> Vec<isize> {
use regex::Regex;
// Handle the case of a single number
for cap in Regex::new(r"^(-?\d+)$").unwrap().captures_iter(item) {
return vec![cap.at(0).and_then(|s| s.parse().ok()).unwrap()]
}
// Handle the case of a range
for cap in Regex::new(r"^(-?\d+)-(-?\d+)$").unwrap().captures_iter(item) {
let left: isize = cap.at(1).and_then(|s| s.parse().ok()).unwrap();
let right: isize = cap.at(2).and_then(|s| s.parse().ok()).unwrap();
// Generate and collect a range between them
return (left..right+1).collect()
}
panic!("The item `{}` is not a number or a range!", item);
}
#[test]
fn test_basic() {
let range = "1-5,6";
assert!(expand_range(range) == vec![1, 2, 3, 4, 5, 6]);
let range = "-6,-3-1,3-5,7-11,14,15,17-20";
assert!(expand_range(range) ==
vec![-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}
#[test]
#[should_panic]
fn test_wrong() {
|
assert!(expand_range(range) == vec![1, 2, 3, 4, 5, 6]);
}
|
let range = "one-five,six";
|
random_line_split
|
range_expansion.rs
|
// http://rosettacode.org/wiki/Range_expansion
extern crate regex;
#[cfg(not(test))]
fn main() {
let range = "-6,-3-1,3-5,7-11,14,15,17-20";
println!("Expanded range: {:?}", expand_range(range));
}
// Expand a string containing numbers and ranges, into a vector of numbers
fn expand_range(range: &str) -> Vec<isize> {
let mut result = vec![];
for item in range.split(',') {
result.extend(expand_item(item).into_iter());
}
result
}
// Expand a single element, which can be a number or a range.
fn
|
(item: &str) -> Vec<isize> {
use regex::Regex;
// Handle the case of a single number
for cap in Regex::new(r"^(-?\d+)$").unwrap().captures_iter(item) {
return vec![cap.at(0).and_then(|s| s.parse().ok()).unwrap()]
}
// Handle the case of a range
for cap in Regex::new(r"^(-?\d+)-(-?\d+)$").unwrap().captures_iter(item) {
let left: isize = cap.at(1).and_then(|s| s.parse().ok()).unwrap();
let right: isize = cap.at(2).and_then(|s| s.parse().ok()).unwrap();
// Generate and collect a range between them
return (left..right+1).collect()
}
panic!("The item `{}` is not a number or a range!", item);
}
#[test]
fn test_basic() {
let range = "1-5,6";
assert!(expand_range(range) == vec![1, 2, 3, 4, 5, 6]);
let range = "-6,-3-1,3-5,7-11,14,15,17-20";
assert!(expand_range(range) ==
vec![-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}
#[test]
#[should_panic]
fn test_wrong() {
let range = "one-five,six";
assert!(expand_range(range) == vec![1, 2, 3, 4, 5, 6]);
}
|
expand_item
|
identifier_name
|
range_expansion.rs
|
// http://rosettacode.org/wiki/Range_expansion
extern crate regex;
#[cfg(not(test))]
fn main() {
let range = "-6,-3-1,3-5,7-11,14,15,17-20";
println!("Expanded range: {:?}", expand_range(range));
}
// Expand a string containing numbers and ranges, into a vector of numbers
fn expand_range(range: &str) -> Vec<isize>
|
// Expand a single element, which can be a number or a range.
fn expand_item(item: &str) -> Vec<isize> {
use regex::Regex;
// Handle the case of a single number
for cap in Regex::new(r"^(-?\d+)$").unwrap().captures_iter(item) {
return vec![cap.at(0).and_then(|s| s.parse().ok()).unwrap()]
}
// Handle the case of a range
for cap in Regex::new(r"^(-?\d+)-(-?\d+)$").unwrap().captures_iter(item) {
let left: isize = cap.at(1).and_then(|s| s.parse().ok()).unwrap();
let right: isize = cap.at(2).and_then(|s| s.parse().ok()).unwrap();
// Generate and collect a range between them
return (left..right+1).collect()
}
panic!("The item `{}` is not a number or a range!", item);
}
#[test]
fn test_basic() {
let range = "1-5,6";
assert!(expand_range(range) == vec![1, 2, 3, 4, 5, 6]);
let range = "-6,-3-1,3-5,7-11,14,15,17-20";
assert!(expand_range(range) ==
vec![-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}
#[test]
#[should_panic]
fn test_wrong() {
let range = "one-five,six";
assert!(expand_range(range) == vec![1, 2, 3, 4, 5, 6]);
}
|
{
let mut result = vec![];
for item in range.split(',') {
result.extend(expand_item(item).into_iter());
}
result
}
|
identifier_body
|
ioreg.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[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.
/*!
## I/O register interface
On most embedded platforms interaction with hardware peripherals
occurs through memory-mapped registers. This crate provides a syntax
extension for `rustc` to generate convenient, type-safe register
interfaces from a minimal definition.
### Concepts
A *register* is group of bits (typically a word, although on some
platforms smaller). By manipulating the bits of a register one can
affect the state of the associated peripheral.
### Example register definition
Let's consider a register block for a simple UART-like peripheral. The
documentation for the peripheral will likely have a table defining the
interface resembling the following,
```notrust
offset name description
─────── ──────── ──────────────────────────
0x0 CR Configuration register
bit 0 RXE Receive enable
bit 1 TXE Transmit enable
bit 2 RXIE Recieve interrupt enable
bit 3 TXIE Transmit interrupt enable
bit 12:4 BR Baudrate
bit 16:14 PARITY Parity
0x0 No parity
0x1 Reserved
0x2 Even parity
0x3 Odd parity
0x4 SR Status register
bit 0 RXNE Receive data register not empty flag (read-only)
bit 1 TXE Transmit data register not empty flag (read-only)
bit 2 FE Framing error flag (set to clear)
0x8 DR Data register
bits 7:0 D Read returns received data
Write transmits data
```
The syntax extension is invoked through through the `ioregs!` macro. A
register definition for the above peripheral might look like this,
```
ioregs!(UART = {
0x0 => reg32 cr {
0 => rxe,
1 => txe,
2 => rxie,
3 => txie,
4..12 => br,
14..16 => parity {
0x0 => NoParity,
0x2 => EvenParity,
0x3 => OddParity,
}
}
0x4 => reg32 sr {
0 => rxne: ro,
1 => txe: ro,
2 => fe: set_to_clear,
}
0x8 => reg32 dr {
0..7 => d
}
})
```
Here we've defined a register block called `UART` consisting of a
three registers: `cr`, `sr`, and `dr`. Each register definition
consists of an offset from the beginning of the register block width,
a register type giving the width of the register (`reg32` in this
case), a name, and a list of fields.
The `cr` register has four boolean flags, an integer
field `br`, and a field `parity` with four possible values
(`NoParity`, `EvenParity`, and `OddParity`). Each field is defined by
a bit or bit range, a name, some optional modifiers (e.g. `ro` in the
case of `rxne`), and an optional list of values.
This register definition will produce a variety of types, along with
associated accessor methods for convenient, safe manipulation of the
described registers. In the process of generating these, `ioregs!`
will perform a variety of sanity checks (e.g. ensuring that registers
and bitfields are free of overlap).
#### Documenting register definitions
It is highly recommended that register definitions include
docstrings. Registers, fields, and `enum` values can all be annotated
with docstrings with the typical Rust doc comment syntax. Both outer
(`/// comment`) and inner (`//! comment`) comments are accepted. Inner
comments apply to the item to which the current block belongs whereas
outer comments apply to the item that follows. In addition,
trailing comments are supported with the `//=` syntax. These apply
to the preceding item, allowing definitions and associated comments
to inhabit the same line. Multiple successive comments of the same
type will be concatenated together into a single doc comment.
For instance, we might document the above example as follows,
```
ioregs!(UART = {
/// Control register
/// Here is some discussion of the function of the `cr` register.
0x0 => reg32 cr {
0 => rxe, //= Receive enable
1 => txe, //= Transmit enable
2 => rxie, //= Receive interrupt enable
3 => txie, //= Transmit interrupt enable
4..12 => br, //= Baud rate
14..16 => parity { //! Parity selection
0x0 => NoParity, //= No parity
0x2 => EvenParity, //= Even parity
0x3 => OddParity, //= Odd parity
}
}
...
})
```
#### Nesting register blocks
In addition to primitive register types (e.g. `reg32`), one can also
nest groups of logically related registers. For instance, in the case
of a DMA peripheral it is common that the same block of registers will
be replicated, one for each DMA channel. This can be accomplished with
`ioregs!` as follows,
```
ioregs!(DMA = {
0x0 => reg32 cr {... }
0x10 => group channel[4] {
0x0 => reg32 cr {... }
0x4 => reg32 sr {... }
}
0x30 => reg32 sr {... }
})
```
This will produce the following layout in memory,
```notrust
address register
──────── ──────────────
0x0 cr
0x10 channel[0].cr
0x14 channel[0].sr
0x18 channel[1].cr
0x1c channel[1].sr
0x20 channel[2].cr
0x24 channel[2].sr
0x28 channel[3].cr
0x2c channel[3].sr
0x30 sr
```
### What is produced
The `ioregs!` extension produces a variety of types and methods for
each register and field. Let's start by examining the top-level types
representing the structure of the interface.
```
pub enum UART_cr_parity {
NoParity = 0, EvenParity = 2, OddParity = 3,
}
pub struct UART_cr {... }
pub struct UART_sr {... }
pub struct UART_dr {... }
pub struct UART {
pub cr: UART_cr,
pub sr: UART_sr,
pub dr: UART_dr,
}
```
The `UART` struct is the the "entry-point" into the interface and is
ultimately what will be instantiated to represent the peripheral's
register window, typically as a `static extern` item,
```
extern { pub static UART: UART; }
```
The register structs (`UART_cr`, `UART_sr`, and `UART_dr`)
have no user visible members but expose a variety of methods. Let's
look at `cr` in particular,
```
impl UART_cr {
pub fn get(&self) -> UART_cr_Get {... }
pub fn set_rxe(&self, new_value: bool) -> UART_cr_Update {... }
pub fn rxe(&self) -> bool {... }
// similar methods for `txe`, `rxie`, `txie`
pub fn set_br(&self, new_value: u32) -> UART_cr_Update {... }
pub fn br(&self) -> u32 {... }
pub fn set_parity(&self, new_value: UART_cr_parity) -> UART_cr_Update {... }
pub fn parity(&self) -> UART_cr_parity {... }
}
```
Here we see each field has a corresponding "get" function (e.g. `rxe`,
`br`, and `parity`) as well as a "set" function. Note that the set
function returns a `UART_cr_Update` object. This object mirrors the
setter methods of `UART_cr`, collecting multiple field updates within
a register, performing them on destruction with the `Drop` trait,
```
pub struct UART_cr_Update {... }
impl Drop for UART_cr_Update {... }
impl UART_cr_Update {
pub fn set_rxe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
pub fn set_txe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
...
}
```
As the set methods return references to `self` they can be easily
chained together. For instance, we can update the `rxe` and `txe`
fields of the `cr` register atomically,
```
UART.cr.set_rxe(true).set_txe(false);
```
In addition to get and set methods, `UART_cr` also implements a `get`
method which returns a `UART_cr_Get` object mirroring the get methods
of `UART_cr`. This object captures the state of the register allowing
field values to be later atomically queried,
```
let cr: UART_cr_Get = UART.cr.get();
format!("txe={}, rxe={}, br={}", cr.txe(), cr.rxe(), cr.br())
```
In the case of read-only (resp. write-only) fields the set (resp. get)
method is omitted. In the case of `set_to_clear` fields a `clear`
method is instead produced in place of `set`. For instance, in the
case of the `sr` register's `fe` flag,
```
pub fn fe(self: &UART_sr_Getter) -> bool {... }
pub fn clear_fe(self: &UART_sr_Update) -> UART_sr_Update {... }
```
### Informal grammar
In the below discussion `THING,...` will denote a list of one or more
`THING`s. The `THING`s must be comma separated except when ending
with a brace-enclosed block. Optional elements are enclosed in `⟦...⟧`
brackets.
The `ioregs!` macro expects a definition of the form,
```
ioregs!(IDENT = { REG,... })
```
Where a `REG` is either a register group,
```notrust
OFFSET => group IDENT⟦[COUNT]⟧ { REG,... }
```
or a primitive register,
```notrust
OFFSET => TYPE IDENT⟦[COUNT]⟧ { FIELD,... }
```
`COUNT` is an integer count and a register `TYPE` is one of `reg8` (a
one byte wide register), `reg16` (two bytes wide), or `reg32` (four
bytes wide).
A field is given by
```notrust
BITS => IDENT⟦[COUNT]⟧ ⟦: MODIFIER⟧ ⟦{ VALUE,... }⟧
```
where `BITS` is either an inclusive range of integers (`N..M`) or a
single integer (shorthand for `N..N`). If a list of values is given
the field is of an enumerated type. Otherwise single bit fields are
of type `bool` and wider fields unsigned integers (in particular, of
the same width as the containing register).
A `MODIFIER` is one of `rw` (read/write), `ro` (read-only), `wo`
(write-only), or `set_to_clear` (a flag which can be cleared by
setting to one).
A `VALUE` is given by,
```notrust
N => NAME
```
*/
#![feature(quote, plugin_registrar)]
#![crate_name="ioreg"]
#![crate_type="dylib"]
#![allow(unstable)]
extern crate rustc;
extern crate syntax;
extern crate serialize;
use rustc::plugin::Registry;
use syntax::ast;
use syntax::ptr::P;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::util::small_vector::SmallVector;
pub mod node;
pub mod parser;
pub mod builder;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("ioregs", macro_ioregs);
}
pub fn macro_ioregs(cx: &mut ExtCtxt, _: Span, tts: &[ast::TokenTree])
-> Box<MacResult+'static> {
match parser::Parser::new(cx, tts).parse_ioregs() {
Some(group) => {
let mut builder = builder::Builder::new();
let items = builder.emit_items(cx, group);
MacItems::new(items)
},
None => {
panic!();
}
}
}
pub struct MacItems {
items: Vec<P<ast::Item>>
}
impl MacItems {
pub fn new(items: Vec<P<ast::Item>>) -> Box<MacRe
|
::new(MacItems { items: items })
}
}
impl MacResult for MacItems {
fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> {
Some(SmallVector::many(self.items.clone()))
}
}
|
sult+'static> {
Box
|
conditional_block
|
ioreg.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[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.
/*!
## I/O register interface
On most embedded platforms interaction with hardware peripherals
occurs through memory-mapped registers. This crate provides a syntax
extension for `rustc` to generate convenient, type-safe register
interfaces from a minimal definition.
### Concepts
A *register* is group of bits (typically a word, although on some
platforms smaller). By manipulating the bits of a register one can
affect the state of the associated peripheral.
### Example register definition
Let's consider a register block for a simple UART-like peripheral. The
documentation for the peripheral will likely have a table defining the
interface resembling the following,
```notrust
offset name description
─────── ──────── ──────────────────────────
0x0 CR Configuration register
bit 0 RXE Receive enable
bit 1 TXE Transmit enable
bit 2 RXIE Recieve interrupt enable
bit 3 TXIE Transmit interrupt enable
bit 12:4 BR Baudrate
bit 16:14 PARITY Parity
0x0 No parity
0x1 Reserved
0x2 Even parity
0x3 Odd parity
0x4 SR Status register
bit 0 RXNE Receive data register not empty flag (read-only)
bit 1 TXE Transmit data register not empty flag (read-only)
bit 2 FE Framing error flag (set to clear)
0x8 DR Data register
bits 7:0 D Read returns received data
Write transmits data
```
The syntax extension is invoked through through the `ioregs!` macro. A
register definition for the above peripheral might look like this,
```
ioregs!(UART = {
0x0 => reg32 cr {
0 => rxe,
1 => txe,
2 => rxie,
3 => txie,
4..12 => br,
14..16 => parity {
0x0 => NoParity,
0x2 => EvenParity,
0x3 => OddParity,
}
}
0x4 => reg32 sr {
0 => rxne: ro,
1 => txe: ro,
2 => fe: set_to_clear,
}
0x8 => reg32 dr {
0..7 => d
}
})
```
Here we've defined a register block called `UART` consisting of a
three registers: `cr`, `sr`, and `dr`. Each register definition
consists of an offset from the beginning of the register block width,
a register type giving the width of the register (`reg32` in this
case), a name, and a list of fields.
The `cr` register has four boolean flags, an integer
field `br`, and a field `parity` with four possible values
(`NoParity`, `EvenParity`, and `OddParity`). Each field is defined by
a bit or bit range, a name, some optional modifiers (e.g. `ro` in the
case of `rxne`), and an optional list of values.
This register definition will produce a variety of types, along with
associated accessor methods for convenient, safe manipulation of the
described registers. In the process of generating these, `ioregs!`
will perform a variety of sanity checks (e.g. ensuring that registers
and bitfields are free of overlap).
#### Documenting register definitions
It is highly recommended that register definitions include
docstrings. Registers, fields, and `enum` values can all be annotated
with docstrings with the typical Rust doc comment syntax. Both outer
(`/// comment`) and inner (`//! comment`) comments are accepted. Inner
comments apply to the item to which the current block belongs whereas
outer comments apply to the item that follows. In addition,
trailing comments are supported with the `//=` syntax. These apply
to the preceding item, allowing definitions and associated comments
to inhabit the same line. Multiple successive comments of the same
type will be concatenated together into a single doc comment.
For instance, we might document the above example as follows,
```
ioregs!(UART = {
/// Control register
/// Here is some discussion of the function of the `cr` register.
0x0 => reg32 cr {
0 => rxe, //= Receive enable
1 => txe, //= Transmit enable
2 => rxie, //= Receive interrupt enable
3 => txie, //= Transmit interrupt enable
4..12 => br, //= Baud rate
14..16 => parity { //! Parity selection
0x0 => NoParity, //= No parity
0x2 => EvenParity, //= Even parity
0x3 => OddParity, //= Odd parity
}
}
...
})
```
#### Nesting register blocks
In addition to primitive register types (e.g. `reg32`), one can also
nest groups of logically related registers. For instance, in the case
of a DMA peripheral it is common that the same block of registers will
be replicated, one for each DMA channel. This can be accomplished with
`ioregs!` as follows,
```
ioregs!(DMA = {
0x0 => reg32 cr {... }
0x10 => group channel[4] {
0x0 => reg32 cr {... }
0x4 => reg32 sr {... }
}
0x30 => reg32 sr {... }
})
```
This will produce the following layout in memory,
```notrust
address register
──────── ──────────────
0x0 cr
0x10 channel[0].cr
0x14 channel[0].sr
0x18 channel[1].cr
0x1c channel[1].sr
0x20 channel[2].cr
0x24 channel[2].sr
0x28 channel[3].cr
0x2c channel[3].sr
0x30 sr
```
### What is produced
The `ioregs!` extension produces a variety of types and methods for
each register and field. Let's start by examining the top-level types
representing the structure of the interface.
```
pub enum UART_cr_parity {
NoParity = 0, EvenParity = 2, OddParity = 3,
}
pub struct UART_cr {... }
pub struct UART_sr {... }
pub struct UART_dr {... }
pub struct UART {
pub cr: UART_cr,
pub sr: UART_sr,
pub dr: UART_dr,
}
```
The `UART` struct is the the "entry-point" into the interface and is
ultimately what will be instantiated to represent the peripheral's
register window, typically as a `static extern` item,
```
extern { pub static UART: UART; }
```
The register structs (`UART_cr`, `UART_sr`, and `UART_dr`)
have no user visible members but expose a variety of methods. Let's
look at `cr` in particular,
```
impl UART_cr {
pub fn get(&self) -> UART_cr_Get {... }
pub fn set_rxe(&self, new_value: bool) -> UART_cr_Update {... }
pub fn rxe(&self) -> bool {... }
// similar methods for `txe`, `rxie`, `txie`
pub fn set_br(&self, new_value: u32) -> UART_cr_Update {... }
pub fn br(&self) -> u32 {... }
pub fn set_parity(&self, new_value: UART_cr_parity) -> UART_cr_Update {... }
pub fn parity(&self) -> UART_cr_parity {... }
}
```
Here we see each field has a corresponding "get" function (e.g. `rxe`,
`br`, and `parity`) as well as a "set" function. Note that the set
function returns a `UART_cr_Update` object. This object mirrors the
setter methods of `UART_cr`, collecting multiple field updates within
a register, performing them on destruction with the `Drop` trait,
```
pub struct UART_cr_Update {... }
impl Drop for UART_cr_Update {... }
impl UART_cr_Update {
pub fn set_rxe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
pub fn set_txe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
...
}
```
As the set methods return references to `self` they can be easily
chained together. For instance, we can update the `rxe` and `txe`
fields of the `cr` register atomically,
```
UART.cr.set_rxe(true).set_txe(false);
```
In addition to get and set methods, `UART_cr` also implements a `get`
method which returns a `UART_cr_Get` object mirroring the get methods
of `UART_cr`. This object captures the state of the register allowing
field values to be later atomically queried,
```
let cr: UART_cr_Get = UART.cr.get();
format!("txe={}, rxe={}, br={}", cr.txe(), cr.rxe(), cr.br())
```
In the case of read-only (resp. write-only) fields the set (resp. get)
method is omitted. In the case of `set_to_clear` fields a `clear`
method is instead produced in place of `set`. For instance, in the
case of the `sr` register's `fe` flag,
```
pub fn fe(self: &UART_sr_Getter) -> bool {... }
pub fn clear_fe(self: &UART_sr_Update) -> UART_sr_Update {... }
```
### Informal grammar
In the below discussion `THING,...` will denote a list of one or more
`THING`s. The `THING`s must be comma separated except when ending
with a brace-enclosed block. Optional elements are enclosed in `⟦...⟧`
brackets.
The `ioregs!` macro expects a definition of the form,
```
ioregs!(IDENT = { REG,... })
```
Where a `REG` is either a register group,
```notrust
OFFSET => group IDENT⟦[COUNT]⟧ { REG,... }
```
or a primitive register,
```notrust
OFFSET => TYPE IDENT⟦[COUNT]⟧ { FIELD,... }
```
`COUNT` is an integer count and a register `TYPE` is one of `reg8` (a
one byte wide register), `reg16` (two bytes wide), or `reg32` (four
bytes wide).
A field is given by
```notrust
BITS => IDENT⟦[COUNT]⟧ ⟦: MODIFIER⟧ ⟦{ VALUE,... }⟧
```
where `BITS` is either an inclusive range of integers (`N..M`) or a
single integer (shorthand for `N..N`). If a list of values is given
the field is of an enumerated type. Otherwise single bit fields are
of type `bool` and wider fields unsigned integers (in particular, of
the same width as the containing register).
A `MODIFIER` is one of `rw` (read/write), `ro` (read-only), `wo`
(write-only), or `set_to_clear` (a flag which can be cleared by
setting to one).
A `VALUE` is given by,
```notrust
N => NAME
```
*/
#![feature(quote, plugin_registrar)]
#![crate_name="ioreg"]
#![crate_type="dylib"]
#![allow(unstable)]
extern crate rustc;
extern crate syntax;
extern crate serialize;
use rustc::plugin::Registry;
use syntax::ast;
use syntax::ptr::P;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::util::small_vector::SmallVector;
pub mod node;
pub mod parser;
pub mod builder;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("ioregs", macro_ioregs);
}
pub fn macro_ioregs(cx: &mut ExtCtxt, _: Span, tts: &[ast::TokenTree])
-> Box<MacResult+'static> {
match parser::Parser::new(cx, tts).parse_ioregs() {
Some(group) => {
let mut builder = builder::Builder::new();
let items = builder.emit_items(cx, group);
MacItems::new(items)
},
None => {
panic!();
}
}
}
pub struct MacItems {
items: Vec<P<ast::Item>>
}
impl MacItems {
pub fn new(items: Vec<P<ast::Item>>) -> Box<MacResult+'static> {
Box::new(MacItems { items: items })
}
}
impl MacResult for MacItems {
fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>
|
one()))
}
}
|
>> {
Some(SmallVector::many(self.items.cl
|
identifier_body
|
ioreg.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[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.
/*!
## I/O register interface
On most embedded platforms interaction with hardware peripherals
occurs through memory-mapped registers. This crate provides a syntax
extension for `rustc` to generate convenient, type-safe register
interfaces from a minimal definition.
### Concepts
A *register* is group of bits (typically a word, although on some
platforms smaller). By manipulating the bits of a register one can
affect the state of the associated peripheral.
### Example register definition
Let's consider a register block for a simple UART-like peripheral. The
documentation for the peripheral will likely have a table defining the
interface resembling the following,
```notrust
offset name description
─────── ──────── ──────────────────────────
0x0 CR Configuration register
bit 0 RXE Receive enable
bit 1 TXE Transmit enable
bit 2 RXIE Recieve interrupt enable
bit 3 TXIE Transmit interrupt enable
bit 12:4 BR Baudrate
bit 16:14 PARITY Parity
0x0 No parity
0x1 Reserved
0x2 Even parity
0x3 Odd parity
0x4 SR Status register
bit 0 RXNE Receive data register not empty flag (read-only)
bit 1 TXE Transmit data register not empty flag (read-only)
bit 2 FE Framing error flag (set to clear)
0x8 DR Data register
bits 7:0 D Read returns received data
Write transmits data
```
The syntax extension is invoked through through the `ioregs!` macro. A
register definition for the above peripheral might look like this,
```
ioregs!(UART = {
0x0 => reg32 cr {
0 => rxe,
1 => txe,
2 => rxie,
3 => txie,
4..12 => br,
14..16 => parity {
0x0 => NoParity,
0x2 => EvenParity,
0x3 => OddParity,
}
}
0x4 => reg32 sr {
0 => rxne: ro,
1 => txe: ro,
2 => fe: set_to_clear,
}
0x8 => reg32 dr {
0..7 => d
}
})
```
Here we've defined a register block called `UART` consisting of a
three registers: `cr`, `sr`, and `dr`. Each register definition
consists of an offset from the beginning of the register block width,
a register type giving the width of the register (`reg32` in this
case), a name, and a list of fields.
The `cr` register has four boolean flags, an integer
field `br`, and a field `parity` with four possible values
(`NoParity`, `EvenParity`, and `OddParity`). Each field is defined by
a bit or bit range, a name, some optional modifiers (e.g. `ro` in the
case of `rxne`), and an optional list of values.
This register definition will produce a variety of types, along with
associated accessor methods for convenient, safe manipulation of the
described registers. In the process of generating these, `ioregs!`
will perform a variety of sanity checks (e.g. ensuring that registers
and bitfields are free of overlap).
#### Documenting register definitions
It is highly recommended that register definitions include
docstrings. Registers, fields, and `enum` values can all be annotated
with docstrings with the typical Rust doc comment syntax. Both outer
(`/// comment`) and inner (`//! comment`) comments are accepted. Inner
comments apply to the item to which the current block belongs whereas
outer comments apply to the item that follows. In addition,
trailing comments are supported with the `//=` syntax. These apply
to the preceding item, allowing definitions and associated comments
to inhabit the same line. Multiple successive comments of the same
type will be concatenated together into a single doc comment.
For instance, we might document the above example as follows,
```
ioregs!(UART = {
/// Control register
/// Here is some discussion of the function of the `cr` register.
0x0 => reg32 cr {
0 => rxe, //= Receive enable
1 => txe, //= Transmit enable
2 => rxie, //= Receive interrupt enable
3 => txie, //= Transmit interrupt enable
4..12 => br, //= Baud rate
14..16 => parity { //! Parity selection
0x0 => NoParity, //= No parity
0x2 => EvenParity, //= Even parity
0x3 => OddParity, //= Odd parity
}
}
...
})
```
#### Nesting register blocks
In addition to primitive register types (e.g. `reg32`), one can also
nest groups of logically related registers. For instance, in the case
of a DMA peripheral it is common that the same block of registers will
be replicated, one for each DMA channel. This can be accomplished with
`ioregs!` as follows,
```
ioregs!(DMA = {
0x0 => reg32 cr {... }
0x10 => group channel[4] {
0x0 => reg32 cr {... }
0x4 => reg32 sr {... }
}
0x30 => reg32 sr {... }
})
```
This will produce the following layout in memory,
```notrust
address register
──────── ──────────────
0x0 cr
0x10 channel[0].cr
0x14 channel[0].sr
0x18 channel[1].cr
0x1c channel[1].sr
0x20 channel[2].cr
0x24 channel[2].sr
0x28 channel[3].cr
0x2c channel[3].sr
0x30 sr
```
### What is produced
The `ioregs!` extension produces a variety of types and methods for
each register and field. Let's start by examining the top-level types
representing the structure of the interface.
```
pub enum UART_cr_parity {
NoParity = 0, EvenParity = 2, OddParity = 3,
}
pub struct UART_cr {... }
pub struct UART_sr {... }
pub struct UART_dr {... }
pub struct UART {
pub cr: UART_cr,
pub sr: UART_sr,
pub dr: UART_dr,
}
```
The `UART` struct is the the "entry-point" into the interface and is
ultimately what will be instantiated to represent the peripheral's
register window, typically as a `static extern` item,
```
extern { pub static UART: UART; }
```
The register structs (`UART_cr`, `UART_sr`, and `UART_dr`)
have no user visible members but expose a variety of methods. Let's
look at `cr` in particular,
```
impl UART_cr {
pub fn get(&self) -> UART_cr_Get {... }
pub fn set_rxe(&self, new_value: bool) -> UART_cr_Update {... }
pub fn rxe(&self) -> bool {... }
// similar methods for `txe`, `rxie`, `txie`
pub fn set_br(&self, new_value: u32) -> UART_cr_Update {... }
pub fn br(&self) -> u32 {... }
pub fn set_parity(&self, new_value: UART_cr_parity) -> UART_cr_Update {... }
pub fn parity(&self) -> UART_cr_parity {... }
}
```
Here we see each field has a corresponding "get" function (e.g. `rxe`,
`br`, and `parity`) as well as a "set" function. Note that the set
function returns a `UART_cr_Update` object. This object mirrors the
setter methods of `UART_cr`, collecting multiple field updates within
a register, performing them on destruction with the `Drop` trait,
```
pub struct UART_cr_Update {... }
impl Drop for UART_cr_Update {... }
impl UART_cr_Update {
pub fn set_rxe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
pub fn set_txe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
...
}
```
As the set methods return references to `self` they can be easily
chained together. For instance, we can update the `rxe` and `txe`
fields of the `cr` register atomically,
```
UART.cr.set_rxe(true).set_txe(false);
```
In addition to get and set methods, `UART_cr` also implements a `get`
method which returns a `UART_cr_Get` object mirroring the get methods
of `UART_cr`. This object captures the state of the register allowing
field values to be later atomically queried,
```
let cr: UART_cr_Get = UART.cr.get();
format!("txe={}, rxe={}, br={}", cr.txe(), cr.rxe(), cr.br())
```
In the case of read-only (resp. write-only) fields the set (resp. get)
method is omitted. In the case of `set_to_clear` fields a `clear`
method is instead produced in place of `set`. For instance, in the
case of the `sr` register's `fe` flag,
```
pub fn fe(self: &UART_sr_Getter) -> bool {... }
pub fn clear_fe(self: &UART_sr_Update) -> UART_sr_Update {... }
```
### Informal grammar
In the below discussion `THING,...` will denote a list of one or more
`THING`s. The `THING`s must be comma separated except when ending
with a brace-enclosed block. Optional elements are enclosed in `⟦...⟧`
brackets.
The `ioregs!` macro expects a definition of the form,
```
ioregs!(IDENT = { REG,... })
```
Where a `REG` is either a register group,
```notrust
OFFSET => group IDENT⟦[COUNT]⟧ { REG,... }
```
or a primitive register,
```notrust
OFFSET => TYPE IDENT⟦[COUNT]⟧ { FIELD,... }
```
`COUNT` is an integer count and a register `TYPE` is one of `reg8` (a
one byte wide register), `reg16` (two bytes wide), or `reg32` (four
bytes wide).
A field is given by
```notrust
BITS => IDENT⟦[COUNT]⟧ ⟦: MODIFIER⟧ ⟦{ VALUE,... }⟧
```
where `BITS` is either an inclusive range of integers (`N..M`) or a
single integer (shorthand for `N..N`). If a list of values is given
the field is of an enumerated type. Otherwise single bit fields are
of type `bool` and wider fields unsigned integers (in particular, of
the same width as the containing register).
A `MODIFIER` is one of `rw` (read/write), `ro` (read-only), `wo`
(write-only), or `set_to_clear` (a flag which can be cleared by
setting to one).
A `VALUE` is given by,
```notrust
N => NAME
```
*/
#![feature(quote, plugin_registrar)]
#![crate_name="ioreg"]
#![crate_type="dylib"]
#![allow(unstable)]
extern crate rustc;
extern crate syntax;
extern crate serialize;
use rustc::plugin::Registry;
use syntax::ast;
use syntax::ptr::P;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::util::small_vector::SmallVector;
pub mod node;
pub mod parser;
pub mod builder;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("ioregs", macro_ioregs);
}
pub fn macro_ioregs(cx: &mut ExtCtxt, _: Span, tts: &[ast::Tok
|
-> Box<MacResult+'static> {
match parser::Parser::new(cx, tts).parse_ioregs() {
Some(group) => {
let mut builder = builder::Builder::new();
let items = builder.emit_items(cx, group);
MacItems::new(items)
},
None => {
panic!();
}
}
}
pub struct MacItems {
items: Vec<P<ast::Item>>
}
impl MacItems {
pub fn new(items: Vec<P<ast::Item>>) -> Box<MacResult+'static> {
Box::new(MacItems { items: items })
}
}
impl MacResult for MacItems {
fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> {
Some(SmallVector::many(self.items.clone()))
}
}
|
enTree])
|
identifier_name
|
ioreg.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[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.
/*!
## I/O register interface
On most embedded platforms interaction with hardware peripherals
occurs through memory-mapped registers. This crate provides a syntax
extension for `rustc` to generate convenient, type-safe register
interfaces from a minimal definition.
### Concepts
A *register* is group of bits (typically a word, although on some
platforms smaller). By manipulating the bits of a register one can
affect the state of the associated peripheral.
### Example register definition
Let's consider a register block for a simple UART-like peripheral. The
documentation for the peripheral will likely have a table defining the
interface resembling the following,
```notrust
offset name description
─────── ──────── ──────────────────────────
0x0 CR Configuration register
bit 0 RXE Receive enable
bit 1 TXE Transmit enable
bit 2 RXIE Recieve interrupt enable
bit 3 TXIE Transmit interrupt enable
bit 12:4 BR Baudrate
bit 16:14 PARITY Parity
0x0 No parity
0x1 Reserved
0x2 Even parity
0x3 Odd parity
0x4 SR Status register
bit 0 RXNE Receive data register not empty flag (read-only)
bit 1 TXE Transmit data register not empty flag (read-only)
bit 2 FE Framing error flag (set to clear)
0x8 DR Data register
bits 7:0 D Read returns received data
Write transmits data
```
The syntax extension is invoked through through the `ioregs!` macro. A
register definition for the above peripheral might look like this,
```
ioregs!(UART = {
0x0 => reg32 cr {
0 => rxe,
1 => txe,
2 => rxie,
3 => txie,
4..12 => br,
14..16 => parity {
0x0 => NoParity,
0x2 => EvenParity,
0x3 => OddParity,
}
}
0x4 => reg32 sr {
0 => rxne: ro,
1 => txe: ro,
2 => fe: set_to_clear,
}
0x8 => reg32 dr {
0..7 => d
}
})
```
Here we've defined a register block called `UART` consisting of a
three registers: `cr`, `sr`, and `dr`. Each register definition
consists of an offset from the beginning of the register block width,
a register type giving the width of the register (`reg32` in this
case), a name, and a list of fields.
The `cr` register has four boolean flags, an integer
field `br`, and a field `parity` with four possible values
(`NoParity`, `EvenParity`, and `OddParity`). Each field is defined by
a bit or bit range, a name, some optional modifiers (e.g. `ro` in the
case of `rxne`), and an optional list of values.
This register definition will produce a variety of types, along with
associated accessor methods for convenient, safe manipulation of the
described registers. In the process of generating these, `ioregs!`
will perform a variety of sanity checks (e.g. ensuring that registers
and bitfields are free of overlap).
#### Documenting register definitions
It is highly recommended that register definitions include
docstrings. Registers, fields, and `enum` values can all be annotated
with docstrings with the typical Rust doc comment syntax. Both outer
(`/// comment`) and inner (`//! comment`) comments are accepted. Inner
comments apply to the item to which the current block belongs whereas
outer comments apply to the item that follows. In addition,
trailing comments are supported with the `//=` syntax. These apply
to the preceding item, allowing definitions and associated comments
to inhabit the same line. Multiple successive comments of the same
type will be concatenated together into a single doc comment.
For instance, we might document the above example as follows,
```
ioregs!(UART = {
/// Control register
/// Here is some discussion of the function of the `cr` register.
0x0 => reg32 cr {
0 => rxe, //= Receive enable
1 => txe, //= Transmit enable
2 => rxie, //= Receive interrupt enable
3 => txie, //= Transmit interrupt enable
4..12 => br, //= Baud rate
14..16 => parity { //! Parity selection
0x0 => NoParity, //= No parity
0x2 => EvenParity, //= Even parity
0x3 => OddParity, //= Odd parity
}
}
...
})
```
#### Nesting register blocks
In addition to primitive register types (e.g. `reg32`), one can also
nest groups of logically related registers. For instance, in the case
of a DMA peripheral it is common that the same block of registers will
be replicated, one for each DMA channel. This can be accomplished with
`ioregs!` as follows,
```
ioregs!(DMA = {
0x0 => reg32 cr {... }
0x10 => group channel[4] {
0x0 => reg32 cr {... }
0x4 => reg32 sr {... }
}
0x30 => reg32 sr {... }
})
```
This will produce the following layout in memory,
```notrust
address register
──────── ──────────────
0x0 cr
0x10 channel[0].cr
0x14 channel[0].sr
0x18 channel[1].cr
0x1c channel[1].sr
0x20 channel[2].cr
0x24 channel[2].sr
0x28 channel[3].cr
0x2c channel[3].sr
0x30 sr
```
### What is produced
The `ioregs!` extension produces a variety of types and methods for
each register and field. Let's start by examining the top-level types
representing the structure of the interface.
```
pub enum UART_cr_parity {
NoParity = 0, EvenParity = 2, OddParity = 3,
}
pub struct UART_cr {... }
pub struct UART_sr {... }
pub struct UART_dr {... }
pub struct UART {
pub cr: UART_cr,
pub sr: UART_sr,
pub dr: UART_dr,
}
```
The `UART` struct is the the "entry-point" into the interface and is
ultimately what will be instantiated to represent the peripheral's
register window, typically as a `static extern` item,
```
extern { pub static UART: UART; }
```
The register structs (`UART_cr`, `UART_sr`, and `UART_dr`)
have no user visible members but expose a variety of methods. Let's
look at `cr` in particular,
```
impl UART_cr {
pub fn get(&self) -> UART_cr_Get {... }
pub fn set_rxe(&self, new_value: bool) -> UART_cr_Update {... }
pub fn rxe(&self) -> bool {... }
// similar methods for `txe`, `rxie`, `txie`
pub fn set_br(&self, new_value: u32) -> UART_cr_Update {... }
pub fn br(&self) -> u32 {... }
pub fn set_parity(&self, new_value: UART_cr_parity) -> UART_cr_Update {... }
pub fn parity(&self) -> UART_cr_parity {... }
}
```
Here we see each field has a corresponding "get" function (e.g. `rxe`,
`br`, and `parity`) as well as a "set" function. Note that the set
function returns a `UART_cr_Update` object. This object mirrors the
setter methods of `UART_cr`, collecting multiple field updates within
a register, performing them on destruction with the `Drop` trait,
```
pub struct UART_cr_Update {... }
impl Drop for UART_cr_Update {... }
impl UART_cr_Update {
pub fn set_rxe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
pub fn set_txe<'a>(&'a mut self, new_value: bool) -> &'a mut UART_cr_Update {... }
...
}
```
As the set methods return references to `self` they can be easily
chained together. For instance, we can update the `rxe` and `txe`
fields of the `cr` register atomically,
```
UART.cr.set_rxe(true).set_txe(false);
```
In addition to get and set methods, `UART_cr` also implements a `get`
method which returns a `UART_cr_Get` object mirroring the get methods
of `UART_cr`. This object captures the state of the register allowing
field values to be later atomically queried,
```
let cr: UART_cr_Get = UART.cr.get();
format!("txe={}, rxe={}, br={}", cr.txe(), cr.rxe(), cr.br())
```
In the case of read-only (resp. write-only) fields the set (resp. get)
method is omitted. In the case of `set_to_clear` fields a `clear`
method is instead produced in place of `set`. For instance, in the
case of the `sr` register's `fe` flag,
```
pub fn fe(self: &UART_sr_Getter) -> bool {... }
pub fn clear_fe(self: &UART_sr_Update) -> UART_sr_Update {... }
```
### Informal grammar
In the below discussion `THING,...` will denote a list of one or more
`THING`s. The `THING`s must be comma separated except when ending
with a brace-enclosed block. Optional elements are enclosed in `⟦...⟧`
brackets.
The `ioregs!` macro expects a definition of the form,
```
ioregs!(IDENT = { REG,... })
```
Where a `REG` is either a register group,
```notrust
OFFSET => group IDENT⟦[COUNT]⟧ { REG,... }
```
or a primitive register,
```notrust
OFFSET => TYPE IDENT⟦[COUNT]⟧ { FIELD,... }
```
`COUNT` is an integer count and a register `TYPE` is one of `reg8` (a
one byte wide register), `reg16` (two bytes wide), or `reg32` (four
bytes wide).
A field is given by
```notrust
BITS => IDENT⟦[COUNT]⟧ ⟦: MODIFIER⟧ ⟦{ VALUE,... }⟧
```
where `BITS` is either an inclusive range of integers (`N..M`) or a
single integer (shorthand for `N..N`). If a list of values is given
the field is of an enumerated type. Otherwise single bit fields are
of type `bool` and wider fields unsigned integers (in particular, of
the same width as the containing register).
A `MODIFIER` is one of `rw` (read/write), `ro` (read-only), `wo`
(write-only), or `set_to_clear` (a flag which can be cleared by
setting to one).
A `VALUE` is given by,
```notrust
N => NAME
```
*/
#![feature(quote, plugin_registrar)]
#![crate_name="ioreg"]
#![crate_type="dylib"]
#![allow(unstable)]
extern crate rustc;
extern crate syntax;
extern crate serialize;
use rustc::plugin::Registry;
use syntax::ast;
use syntax::ptr::P;
use syntax::codemap::Span;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::util::small_vector::SmallVector;
pub mod node;
pub mod parser;
pub mod builder;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("ioregs", macro_ioregs);
}
pub fn macro_ioregs(cx: &mut ExtCtxt, _: Span, tts: &[ast::TokenTree])
-> Box<MacResult+'static> {
match parser::Parser::new(cx, tts).parse_ioregs() {
Some(group) => {
let mut builder = builder::Builder::new();
let items = builder.emit_items(cx, group);
MacItems::new(items)
},
None => {
panic!();
}
}
}
pub struct MacItems {
items: Vec<P<ast::Item>>
}
impl MacItems {
|
}
impl MacResult for MacItems {
fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> {
Some(SmallVector::many(self.items.clone()))
}
}
|
pub fn new(items: Vec<P<ast::Item>>) -> Box<MacResult+'static> {
Box::new(MacItems { items: items })
}
|
random_line_split
|
math.rs
|
//! Various methods for computing with vectors.
use std::ops::{Add, Rem};
use vecmath::{self, traits::Float};
pub use vecmath::{
mat2x3_inv as invert, row_mat2x3_mul as multiply, row_mat2x3_transform_pos2 as transform_pos,
row_mat2x3_transform_vec2 as transform_vec, vec2_add as add, vec2_cast as cast,
vec2_cross as cross, vec2_dot as dot, vec2_mul as mul, vec2_scale as mul_scalar,
vec2_square_len as square_len, vec2_sub as sub,
};
use crate::{
modular_index::previous,
types::{Area, Color, Line, Polygon, Ray, Rectangle, SourceRectangle, Triangle},
};
/// The type used for scalars.
pub type Scalar = f64;
/// The type used for matrices.
pub type Matrix2d<T = Scalar> = vecmath::Matrix2x3<T>;
/// The type used for 2D vectors.
pub type Vec2d<T = Scalar> = vecmath::Vector2<T>;
/// The type used for 3D vectors.
pub type Vec3d<T = Scalar> = vecmath::Vector3<T>;
/// Creates a perpendicular vector.
#[inline(always)]
pub fn perp<T>(v: [T; 2]) -> [T; 2]
where
T: Float,
{
[-v[1], v[0]]
}
/// Transforms from normalized to absolute coordinates.
///
/// Computes absolute transform from width and height of viewport.
/// In absolute coordinates, the x axis points to the right,
/// and the y axis points down on the screen.
#[inline(always)]
pub fn abs_transform<T>(w: T, h: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
let _2: T = FromPrimitive::from_f64(2.0);
let sx = _2 / w;
let sy = -_2 / h;
[[sx, _0, -_1], [_0, sy, _1]]
}
/// Creates a translation matrix.
#[inline(always)]
pub fn translate<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, v[0]], [_0, _1, v[1]]]
}
/// Creates a rotation matrix.
#[inline(always)]
pub fn rotate_radians<T>(angle: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let c = angle.cos();
let s = angle.sin();
[[c, -s, _0], [s, c, _0]]
}
/// Orients x axis to look at point.
///
/// Leaves x axis unchanged if the
/// point to look at is the origin.
#[inline(always)]
pub fn orient<T>(x: T, y: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let len = x * x + y * y;
if len == _0 {
return identity();
}
let len = len.sqrt();
let c = x / len;
let s = y / len;
[[c, -s, _0], [s, c, _0]]
}
/// Create a scale matrix.
#[inline(always)]
pub fn scale<T>(sx: T, sy: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
[[sx, _0, _0], [_0, sy, _0]]
}
/// Create a shear matrix.
#[inline(always)]
pub fn shear<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0 = Zero::zero();
let _1 = One::one();
[[_1, v[0], _0], [v[1], _1, _0]]
}
/// Create an identity matrix.
#[inline(always)]
pub fn identity<T>() -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, _0], [_0, _1, _0]]
}
/// Extract scale information from matrix.
#[inline(always)]
pub fn get_scale<T>(m: Matrix2d<T>) -> Vec2d<T>
where
T: Float,
{
[
(m[0][0] * m[0][0] + m[1][0] * m[1][0]).sqrt(),
(m[0][1] * m[0][1] + m[1][1] * m[1][1]).sqrt(),
]
}
/// Compute the shortest vector from point to ray.
/// A ray stores starting point and directional vector.
#[inline(always)]
pub fn separation<T>(ray: Ray<T>, v: Vec2d<T>) -> Vec2d<T>
where
T: Float,
{
// Get the directional vector.
let (dir_x, dir_y) = (ray[2], ray[3]);
// Get displacement vector from point.
let (dx, dy) = (ray[0] - v[0], ray[1] - v[1]);
// Compute the component of position in ray direction.
let dot = dir_x * v[0] + dir_y * v[1];
// The directional vector multiplied with
// the dot gives us a parallel vector.
// When we subtract this from the displacement
// we get a vector normal to the ray.
// This is the shortest vector from the point to the ray.
[dx - dot * dir_x, dy - dot * dir_y]
}
/// Returns the least separation out of four.
/// Each seperation can be computed using `separation` function.
/// The separation returned can be used
/// to solve collision of rectangles.
#[inline(always)]
pub fn least_separation_4<T>(
sep1: Vec2d<T>,
sep2: Vec2d<T>,
sep3: Vec2d<T>,
sep4: Vec2d<T>,
) -> Vec2d<T>
where
T: Float,
{
let dot1 = sep1[0] * sep1[0] + sep1[1] * sep1[1];
let dot2 = sep2[0] * sep2[0] + sep2[1] * sep2[1];
let dot3 = sep3[0] * sep3[0] + sep3[1] * sep3[1];
let dot4 = sep4[0] * sep4[0] + sep4[1] * sep4[1];
// Search for the smallest dot product.
if dot1 < dot2 {
if dot3 < dot4 {
if dot1 < dot3 {
sep1
} else {
sep3
}
} else {
if dot1 < dot4 {
sep1
} else {
sep4
}
}
} else {
if dot3 < dot4 {
if dot2 < dot3 {
sep2
} else {
sep3
}
} else {
if dot2 < dot4 {
sep2
} else {
sep4
}
}
}
}
/// Shrinks a rectangle by a factor on all sides.
#[inline(always)]
pub fn margin_rectangle<T>(rect: Rectangle<T>, m: T) -> Rectangle<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _2: T = FromPrimitive::from_f64(2.0);
let w = rect[2] - _2 * m;
let h = rect[3] - _2 * m;
let (x, w) = if w < _0 {
(rect[0] + _05 * rect[2], _0)
} else {
(rect[0] + m, w)
};
let (y, h) = if h < _0 {
(rect[1] + _05 * rect[3], _0)
} else {
(rect[1] + m, h)
};
[x, y, w, h]
}
/// Computes a relative rectangle using the rectangle as a tile.
#[inline(always)]
pub fn relative_rectangle<T>(rect: Rectangle<T>, v: Vec2d<T>) -> Rectangle<T>
where
T: Float,
{
[
rect[0] + v[0] * rect[2],
rect[1] + v[1] * rect[3],
rect[2],
rect[3],
]
}
/// Computes overlap between two rectangles.
/// The area of the overlapping rectangle is positive.
/// A shared edge or corner is not considered overlap.
#[inline(always)]
pub fn overlap_rectangle<T>(a: Rectangle<T>, b: Rectangle<T>) -> Option<Rectangle<T>>
where
T: Float,
{
#[inline(always)]
fn min<T: Float>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
#[inline(always)]
fn max<T: Float>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
if a[0] < b[0] + b[2] && a[1] < b[1] + b[3] && b[0] < a[0] + a[2] && b[1] < a[1] + a[3] {
let x = max(a[0], b[0]);
let y = max(a[1], b[1]);
let w = min(a[0] + a[2], b[0] + b[2]) - x;
let h = min(a[1] + a[3], b[1] + b[3]) - y;
Some([x, y, w, h])
} else {
None
}
}
#[cfg(test)]
mod test_overlap {
use super::overlap_rectangle;
#[test]
fn overlap() {
let a = [0.0, 1.0, 100.0, 101.0];
let b = [51.0, 52.0, 102.0, 103.0];
let c = overlap_rectangle(a, b).unwrap();
assert_eq!(c, [51.0, 52.0, 49.0, 50.0]);
let d = overlap_rectangle(a, c).unwrap();
assert_eq!(d, c);
let e = overlap_rectangle(b, c).unwrap();
assert_eq!(e, c);
}
#[test]
fn edge() {
let a = [0.0, 0.0, 100.0, 100.0];
let b = [100.0, 0.0, 100.0, 100.0];
let c = overlap_rectangle(a, b);
assert_eq!(c, None);
}
}
/// Computes a relative source rectangle using
/// the source rectangle as a tile.
#[inline(always)]
pub fn relative_source_rectangle<T>(rect: SourceRectangle<T>, x: T, y: T) -> SourceRectangle<T>
where
T: Float,
{
let (rx, ry, rw, rh) = (rect[0], rect[1], rect[2], rect[3]);
let (x, y) = (rx + x * rw, ry + y * rh);
[x, y, rw, rh]
}
/// Computes modular offset safely for numbers.
#[inline(always)]
pub fn modular_offset<T: Add<Output = T> + Rem<Output = T> + Copy>(n: &T, i: &T, off: &T) -> T {
(*i + (*off % *n + *n)) % *n
}
#[cfg(test)]
mod test_modular_offset {
use super::*;
#[test]
fn test_modular_offset() {
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &-1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &-1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &1.0_f64), 1.0_f64);
}
}
/// Computes the area and centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
/// Source: http://en.wikipedia.org/wiki/Polygon_area#Simple_polygons
pub fn area_centroid<T>(polygon: Polygon<'_, T>) -> (Area<T>, Vec2d<T>)
where
T: Float,
|
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _3: T = FromPrimitive::from_f64(3.0);
let n = polygon.len();
let mut sum = _0;
let (mut cx, mut cy) = (_0, _0);
for i in 0..n {
let qx = polygon[i][0];
let qy = polygon[i][1];
let p_i = previous(n, i);
let px = polygon[p_i][0];
let py = polygon[p_i][1];
let cross = px * qy - qx * py;
cx += (px + qx) * cross;
cy += (py + qy) * cross;
sum += cross;
}
let area = _05 * sum;
// 'cx / (6.0 * area)' = 'cx / (3.0 * sum)'
let centroid = [cx / (_3 * sum), cy / (_3 * sum)];
(area, centroid)
}
/// Computes area of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn area<T>(polygon: Polygon<'_, T>) -> T
where
T: Float,
{
let (res, _) = area_centroid(polygon);
res
}
/// Computes centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn centroid<T>(polygon: Polygon<'_, T>) -> Vec2d<T>
where
T: Float,
{
let (_, res) = area_centroid(polygon);
res
}
/// Returns a number that tells which side it is relative to a line.
///
/// Computes the cross product of the vector that gives the line
/// with the vector between point and starting point of line.
/// One side of the line has opposite sign of the other.
#[inline(always)]
pub fn line_side<T>(line: Line<T>, v: Vec2d<T>) -> T
where
T: Float,
{
let (ax, ay) = (line[0], line[1]);
let (bx, by) = (line[2], line[3]);
(bx - ax) * (v[1] - ay) - (by - ay) * (v[0] - ax)
}
/// Returns true if point is inside triangle.
///
/// This is done by computing a `side` number for each edge.
/// If the number is inside if it is on the same side for all edges.
/// Might break for very small triangles.
pub fn inside_triangle<T>(triangle: Triangle<T>, v: Vec2d<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], v);
let bc_side = line_side([bx, by, cx, cy], v);
let ca_side = line_side([cx, cy, ax, ay], v);
let ab_positive = ab_side >= _0;
let bc_positive = bc_side >= _0;
let ca_positive = ca_side >= _0;
ab_positive == bc_positive && bc_positive == ca_positive
}
/// Returns true if triangle is clockwise.
///
/// This is done by computing which side the third vertex is relative to
/// the line starting from the first vertex to second vertex.
///
/// The triangle is considered clockwise if the third vertex is on the line
/// between the two first vertices.
#[inline(always)]
pub fn triangle_face<T>(triangle: Triangle<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], [cx, cy]);
ab_side <= _0
}
#[cfg(test)]
mod test_triangle {
use super::*;
#[test]
fn test_triangle() {
// Triangle counter clock-wise.
let tri_1 = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]];
// Triangle clock-wise.
let tri_2 = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0]];
let (x, y) = (0.5, 0.25);
assert!(inside_triangle(tri_1, [x, y]));
assert!(inside_triangle(tri_2, [x, y]));
assert_eq!(triangle_face(tri_1), false);
assert!(triangle_face(tri_2));
}
}
/// Transforms from cartesian coordinates to barycentric.
#[inline(always)]
pub fn to_barycentric<T>(triangle: Triangle<T>, pos: Vec2d<T>) -> Vec3d<T>
where
T: Float,
{
use vecmath::traits::One;
let _1: T = One::one();
let x = pos[0];
let y = pos[1];
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
let lambda1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda3 = _1 - lambda1 - lambda2;
[lambda1, lambda2, lambda3]
}
/// Transforms from barycentric coordinates to cartesian.
#[inline(always)]
pub fn from_barycentric<T>(triangle: Triangle<T>, lambda: Vec3d<T>) -> Vec2d<T>
where
T: Float,
{
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
[
lambda[0] * x1 + lambda[1] * x2 + lambda[2] * x3,
lambda[0] * y1 + lambda[1] * y2 + lambda[2] * y3,
]
}
#[cfg(test)]
mod test_barycentric {
use super::*;
#[test]
fn test_barycentric() {
let triangle = [[0.0, 0.0], [100.0, 0.0], [0.0, 50.0]];
let old_pos = [10.0, 20.0];
let b = to_barycentric(triangle, old_pos);
let new_pos: Vec2d = from_barycentric(triangle, b);
let eps = 0.00001;
assert!((new_pos[0] - old_pos[0]).abs() < eps);
assert!((new_pos[1] - old_pos[1]).abs() < eps);
}
}
/// Transform color with hue, saturation and value.
///
/// Source: http://beesbuzz.biz/code/hsv_color_transforms.php
#[inline(always)]
pub fn hsv(color: Color, h_rad: f32, s: f32, v: f32) -> Color {
let vsu = v * s * h_rad.cos();
let vsw = v * s * h_rad.sin();
[
(0.299 * v + 0.701 * vsu + 0.168 * vsw) * color[0]
+ (0.587 * v - 0.587 * vsu + 0.330 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu - 0.497 * vsw) * color[2],
(0.299 * v - 0.299 * vsu - 0.328 * vsw) * color[0]
+ (0.587 * v + 0.413 * vsu + 0.035 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu + 0.292 * vsw) * color[2],
(0.299 * v - 0.3 * vsu + 1.25 * vsw) * color[0]
+ (0.587 * v - 0.588 * vsu - 1.05 * vsw) * color[1]
+ (0.114 * v + 0.886 * vsu - 0.203 * vsw) * color[2],
color[3],
]
}
|
{
|
random_line_split
|
math.rs
|
//! Various methods for computing with vectors.
use std::ops::{Add, Rem};
use vecmath::{self, traits::Float};
pub use vecmath::{
mat2x3_inv as invert, row_mat2x3_mul as multiply, row_mat2x3_transform_pos2 as transform_pos,
row_mat2x3_transform_vec2 as transform_vec, vec2_add as add, vec2_cast as cast,
vec2_cross as cross, vec2_dot as dot, vec2_mul as mul, vec2_scale as mul_scalar,
vec2_square_len as square_len, vec2_sub as sub,
};
use crate::{
modular_index::previous,
types::{Area, Color, Line, Polygon, Ray, Rectangle, SourceRectangle, Triangle},
};
/// The type used for scalars.
pub type Scalar = f64;
/// The type used for matrices.
pub type Matrix2d<T = Scalar> = vecmath::Matrix2x3<T>;
/// The type used for 2D vectors.
pub type Vec2d<T = Scalar> = vecmath::Vector2<T>;
/// The type used for 3D vectors.
pub type Vec3d<T = Scalar> = vecmath::Vector3<T>;
/// Creates a perpendicular vector.
#[inline(always)]
pub fn perp<T>(v: [T; 2]) -> [T; 2]
where
T: Float,
{
[-v[1], v[0]]
}
/// Transforms from normalized to absolute coordinates.
///
/// Computes absolute transform from width and height of viewport.
/// In absolute coordinates, the x axis points to the right,
/// and the y axis points down on the screen.
#[inline(always)]
pub fn abs_transform<T>(w: T, h: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
let _2: T = FromPrimitive::from_f64(2.0);
let sx = _2 / w;
let sy = -_2 / h;
[[sx, _0, -_1], [_0, sy, _1]]
}
/// Creates a translation matrix.
#[inline(always)]
pub fn translate<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, v[0]], [_0, _1, v[1]]]
}
/// Creates a rotation matrix.
#[inline(always)]
pub fn rotate_radians<T>(angle: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let c = angle.cos();
let s = angle.sin();
[[c, -s, _0], [s, c, _0]]
}
/// Orients x axis to look at point.
///
/// Leaves x axis unchanged if the
/// point to look at is the origin.
#[inline(always)]
pub fn orient<T>(x: T, y: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let len = x * x + y * y;
if len == _0
|
let len = len.sqrt();
let c = x / len;
let s = y / len;
[[c, -s, _0], [s, c, _0]]
}
/// Create a scale matrix.
#[inline(always)]
pub fn scale<T>(sx: T, sy: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
[[sx, _0, _0], [_0, sy, _0]]
}
/// Create a shear matrix.
#[inline(always)]
pub fn shear<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0 = Zero::zero();
let _1 = One::one();
[[_1, v[0], _0], [v[1], _1, _0]]
}
/// Create an identity matrix.
#[inline(always)]
pub fn identity<T>() -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, _0], [_0, _1, _0]]
}
/// Extract scale information from matrix.
#[inline(always)]
pub fn get_scale<T>(m: Matrix2d<T>) -> Vec2d<T>
where
T: Float,
{
[
(m[0][0] * m[0][0] + m[1][0] * m[1][0]).sqrt(),
(m[0][1] * m[0][1] + m[1][1] * m[1][1]).sqrt(),
]
}
/// Compute the shortest vector from point to ray.
/// A ray stores starting point and directional vector.
#[inline(always)]
pub fn separation<T>(ray: Ray<T>, v: Vec2d<T>) -> Vec2d<T>
where
T: Float,
{
// Get the directional vector.
let (dir_x, dir_y) = (ray[2], ray[3]);
// Get displacement vector from point.
let (dx, dy) = (ray[0] - v[0], ray[1] - v[1]);
// Compute the component of position in ray direction.
let dot = dir_x * v[0] + dir_y * v[1];
// The directional vector multiplied with
// the dot gives us a parallel vector.
// When we subtract this from the displacement
// we get a vector normal to the ray.
// This is the shortest vector from the point to the ray.
[dx - dot * dir_x, dy - dot * dir_y]
}
/// Returns the least separation out of four.
/// Each seperation can be computed using `separation` function.
/// The separation returned can be used
/// to solve collision of rectangles.
#[inline(always)]
pub fn least_separation_4<T>(
sep1: Vec2d<T>,
sep2: Vec2d<T>,
sep3: Vec2d<T>,
sep4: Vec2d<T>,
) -> Vec2d<T>
where
T: Float,
{
let dot1 = sep1[0] * sep1[0] + sep1[1] * sep1[1];
let dot2 = sep2[0] * sep2[0] + sep2[1] * sep2[1];
let dot3 = sep3[0] * sep3[0] + sep3[1] * sep3[1];
let dot4 = sep4[0] * sep4[0] + sep4[1] * sep4[1];
// Search for the smallest dot product.
if dot1 < dot2 {
if dot3 < dot4 {
if dot1 < dot3 {
sep1
} else {
sep3
}
} else {
if dot1 < dot4 {
sep1
} else {
sep4
}
}
} else {
if dot3 < dot4 {
if dot2 < dot3 {
sep2
} else {
sep3
}
} else {
if dot2 < dot4 {
sep2
} else {
sep4
}
}
}
}
/// Shrinks a rectangle by a factor on all sides.
#[inline(always)]
pub fn margin_rectangle<T>(rect: Rectangle<T>, m: T) -> Rectangle<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _2: T = FromPrimitive::from_f64(2.0);
let w = rect[2] - _2 * m;
let h = rect[3] - _2 * m;
let (x, w) = if w < _0 {
(rect[0] + _05 * rect[2], _0)
} else {
(rect[0] + m, w)
};
let (y, h) = if h < _0 {
(rect[1] + _05 * rect[3], _0)
} else {
(rect[1] + m, h)
};
[x, y, w, h]
}
/// Computes a relative rectangle using the rectangle as a tile.
#[inline(always)]
pub fn relative_rectangle<T>(rect: Rectangle<T>, v: Vec2d<T>) -> Rectangle<T>
where
T: Float,
{
[
rect[0] + v[0] * rect[2],
rect[1] + v[1] * rect[3],
rect[2],
rect[3],
]
}
/// Computes overlap between two rectangles.
/// The area of the overlapping rectangle is positive.
/// A shared edge or corner is not considered overlap.
#[inline(always)]
pub fn overlap_rectangle<T>(a: Rectangle<T>, b: Rectangle<T>) -> Option<Rectangle<T>>
where
T: Float,
{
#[inline(always)]
fn min<T: Float>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
#[inline(always)]
fn max<T: Float>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
if a[0] < b[0] + b[2] && a[1] < b[1] + b[3] && b[0] < a[0] + a[2] && b[1] < a[1] + a[3] {
let x = max(a[0], b[0]);
let y = max(a[1], b[1]);
let w = min(a[0] + a[2], b[0] + b[2]) - x;
let h = min(a[1] + a[3], b[1] + b[3]) - y;
Some([x, y, w, h])
} else {
None
}
}
#[cfg(test)]
mod test_overlap {
use super::overlap_rectangle;
#[test]
fn overlap() {
let a = [0.0, 1.0, 100.0, 101.0];
let b = [51.0, 52.0, 102.0, 103.0];
let c = overlap_rectangle(a, b).unwrap();
assert_eq!(c, [51.0, 52.0, 49.0, 50.0]);
let d = overlap_rectangle(a, c).unwrap();
assert_eq!(d, c);
let e = overlap_rectangle(b, c).unwrap();
assert_eq!(e, c);
}
#[test]
fn edge() {
let a = [0.0, 0.0, 100.0, 100.0];
let b = [100.0, 0.0, 100.0, 100.0];
let c = overlap_rectangle(a, b);
assert_eq!(c, None);
}
}
/// Computes a relative source rectangle using
/// the source rectangle as a tile.
#[inline(always)]
pub fn relative_source_rectangle<T>(rect: SourceRectangle<T>, x: T, y: T) -> SourceRectangle<T>
where
T: Float,
{
let (rx, ry, rw, rh) = (rect[0], rect[1], rect[2], rect[3]);
let (x, y) = (rx + x * rw, ry + y * rh);
[x, y, rw, rh]
}
/// Computes modular offset safely for numbers.
#[inline(always)]
pub fn modular_offset<T: Add<Output = T> + Rem<Output = T> + Copy>(n: &T, i: &T, off: &T) -> T {
(*i + (*off % *n + *n)) % *n
}
#[cfg(test)]
mod test_modular_offset {
use super::*;
#[test]
fn test_modular_offset() {
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &-1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &-1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &1.0_f64), 1.0_f64);
}
}
/// Computes the area and centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
/// Source: http://en.wikipedia.org/wiki/Polygon_area#Simple_polygons
pub fn area_centroid<T>(polygon: Polygon<'_, T>) -> (Area<T>, Vec2d<T>)
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _3: T = FromPrimitive::from_f64(3.0);
let n = polygon.len();
let mut sum = _0;
let (mut cx, mut cy) = (_0, _0);
for i in 0..n {
let qx = polygon[i][0];
let qy = polygon[i][1];
let p_i = previous(n, i);
let px = polygon[p_i][0];
let py = polygon[p_i][1];
let cross = px * qy - qx * py;
cx += (px + qx) * cross;
cy += (py + qy) * cross;
sum += cross;
}
let area = _05 * sum;
// 'cx / (6.0 * area)' = 'cx / (3.0 * sum)'
let centroid = [cx / (_3 * sum), cy / (_3 * sum)];
(area, centroid)
}
/// Computes area of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn area<T>(polygon: Polygon<'_, T>) -> T
where
T: Float,
{
let (res, _) = area_centroid(polygon);
res
}
/// Computes centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn centroid<T>(polygon: Polygon<'_, T>) -> Vec2d<T>
where
T: Float,
{
let (_, res) = area_centroid(polygon);
res
}
/// Returns a number that tells which side it is relative to a line.
///
/// Computes the cross product of the vector that gives the line
/// with the vector between point and starting point of line.
/// One side of the line has opposite sign of the other.
#[inline(always)]
pub fn line_side<T>(line: Line<T>, v: Vec2d<T>) -> T
where
T: Float,
{
let (ax, ay) = (line[0], line[1]);
let (bx, by) = (line[2], line[3]);
(bx - ax) * (v[1] - ay) - (by - ay) * (v[0] - ax)
}
/// Returns true if point is inside triangle.
///
/// This is done by computing a `side` number for each edge.
/// If the number is inside if it is on the same side for all edges.
/// Might break for very small triangles.
pub fn inside_triangle<T>(triangle: Triangle<T>, v: Vec2d<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], v);
let bc_side = line_side([bx, by, cx, cy], v);
let ca_side = line_side([cx, cy, ax, ay], v);
let ab_positive = ab_side >= _0;
let bc_positive = bc_side >= _0;
let ca_positive = ca_side >= _0;
ab_positive == bc_positive && bc_positive == ca_positive
}
/// Returns true if triangle is clockwise.
///
/// This is done by computing which side the third vertex is relative to
/// the line starting from the first vertex to second vertex.
///
/// The triangle is considered clockwise if the third vertex is on the line
/// between the two first vertices.
#[inline(always)]
pub fn triangle_face<T>(triangle: Triangle<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], [cx, cy]);
ab_side <= _0
}
#[cfg(test)]
mod test_triangle {
use super::*;
#[test]
fn test_triangle() {
// Triangle counter clock-wise.
let tri_1 = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]];
// Triangle clock-wise.
let tri_2 = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0]];
let (x, y) = (0.5, 0.25);
assert!(inside_triangle(tri_1, [x, y]));
assert!(inside_triangle(tri_2, [x, y]));
assert_eq!(triangle_face(tri_1), false);
assert!(triangle_face(tri_2));
}
}
/// Transforms from cartesian coordinates to barycentric.
#[inline(always)]
pub fn to_barycentric<T>(triangle: Triangle<T>, pos: Vec2d<T>) -> Vec3d<T>
where
T: Float,
{
use vecmath::traits::One;
let _1: T = One::one();
let x = pos[0];
let y = pos[1];
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
let lambda1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda3 = _1 - lambda1 - lambda2;
[lambda1, lambda2, lambda3]
}
/// Transforms from barycentric coordinates to cartesian.
#[inline(always)]
pub fn from_barycentric<T>(triangle: Triangle<T>, lambda: Vec3d<T>) -> Vec2d<T>
where
T: Float,
{
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
[
lambda[0] * x1 + lambda[1] * x2 + lambda[2] * x3,
lambda[0] * y1 + lambda[1] * y2 + lambda[2] * y3,
]
}
#[cfg(test)]
mod test_barycentric {
use super::*;
#[test]
fn test_barycentric() {
let triangle = [[0.0, 0.0], [100.0, 0.0], [0.0, 50.0]];
let old_pos = [10.0, 20.0];
let b = to_barycentric(triangle, old_pos);
let new_pos: Vec2d = from_barycentric(triangle, b);
let eps = 0.00001;
assert!((new_pos[0] - old_pos[0]).abs() < eps);
assert!((new_pos[1] - old_pos[1]).abs() < eps);
}
}
/// Transform color with hue, saturation and value.
///
/// Source: http://beesbuzz.biz/code/hsv_color_transforms.php
#[inline(always)]
pub fn hsv(color: Color, h_rad: f32, s: f32, v: f32) -> Color {
let vsu = v * s * h_rad.cos();
let vsw = v * s * h_rad.sin();
[
(0.299 * v + 0.701 * vsu + 0.168 * vsw) * color[0]
+ (0.587 * v - 0.587 * vsu + 0.330 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu - 0.497 * vsw) * color[2],
(0.299 * v - 0.299 * vsu - 0.328 * vsw) * color[0]
+ (0.587 * v + 0.413 * vsu + 0.035 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu + 0.292 * vsw) * color[2],
(0.299 * v - 0.3 * vsu + 1.25 * vsw) * color[0]
+ (0.587 * v - 0.588 * vsu - 1.05 * vsw) * color[1]
+ (0.114 * v + 0.886 * vsu - 0.203 * vsw) * color[2],
color[3],
]
}
|
{
return identity();
}
|
conditional_block
|
math.rs
|
//! Various methods for computing with vectors.
use std::ops::{Add, Rem};
use vecmath::{self, traits::Float};
pub use vecmath::{
mat2x3_inv as invert, row_mat2x3_mul as multiply, row_mat2x3_transform_pos2 as transform_pos,
row_mat2x3_transform_vec2 as transform_vec, vec2_add as add, vec2_cast as cast,
vec2_cross as cross, vec2_dot as dot, vec2_mul as mul, vec2_scale as mul_scalar,
vec2_square_len as square_len, vec2_sub as sub,
};
use crate::{
modular_index::previous,
types::{Area, Color, Line, Polygon, Ray, Rectangle, SourceRectangle, Triangle},
};
/// The type used for scalars.
pub type Scalar = f64;
/// The type used for matrices.
pub type Matrix2d<T = Scalar> = vecmath::Matrix2x3<T>;
/// The type used for 2D vectors.
pub type Vec2d<T = Scalar> = vecmath::Vector2<T>;
/// The type used for 3D vectors.
pub type Vec3d<T = Scalar> = vecmath::Vector3<T>;
/// Creates a perpendicular vector.
#[inline(always)]
pub fn perp<T>(v: [T; 2]) -> [T; 2]
where
T: Float,
{
[-v[1], v[0]]
}
/// Transforms from normalized to absolute coordinates.
///
/// Computes absolute transform from width and height of viewport.
/// In absolute coordinates, the x axis points to the right,
/// and the y axis points down on the screen.
#[inline(always)]
pub fn abs_transform<T>(w: T, h: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
let _2: T = FromPrimitive::from_f64(2.0);
let sx = _2 / w;
let sy = -_2 / h;
[[sx, _0, -_1], [_0, sy, _1]]
}
/// Creates a translation matrix.
#[inline(always)]
pub fn translate<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, v[0]], [_0, _1, v[1]]]
}
/// Creates a rotation matrix.
#[inline(always)]
pub fn rotate_radians<T>(angle: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let c = angle.cos();
let s = angle.sin();
[[c, -s, _0], [s, c, _0]]
}
/// Orients x axis to look at point.
///
/// Leaves x axis unchanged if the
/// point to look at is the origin.
#[inline(always)]
pub fn orient<T>(x: T, y: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let len = x * x + y * y;
if len == _0 {
return identity();
}
let len = len.sqrt();
let c = x / len;
let s = y / len;
[[c, -s, _0], [s, c, _0]]
}
/// Create a scale matrix.
#[inline(always)]
pub fn scale<T>(sx: T, sy: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
[[sx, _0, _0], [_0, sy, _0]]
}
/// Create a shear matrix.
#[inline(always)]
pub fn shear<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0 = Zero::zero();
let _1 = One::one();
[[_1, v[0], _0], [v[1], _1, _0]]
}
/// Create an identity matrix.
#[inline(always)]
pub fn identity<T>() -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, _0], [_0, _1, _0]]
}
/// Extract scale information from matrix.
#[inline(always)]
pub fn get_scale<T>(m: Matrix2d<T>) -> Vec2d<T>
where
T: Float,
{
[
(m[0][0] * m[0][0] + m[1][0] * m[1][0]).sqrt(),
(m[0][1] * m[0][1] + m[1][1] * m[1][1]).sqrt(),
]
}
/// Compute the shortest vector from point to ray.
/// A ray stores starting point and directional vector.
#[inline(always)]
pub fn separation<T>(ray: Ray<T>, v: Vec2d<T>) -> Vec2d<T>
where
T: Float,
{
// Get the directional vector.
let (dir_x, dir_y) = (ray[2], ray[3]);
// Get displacement vector from point.
let (dx, dy) = (ray[0] - v[0], ray[1] - v[1]);
// Compute the component of position in ray direction.
let dot = dir_x * v[0] + dir_y * v[1];
// The directional vector multiplied with
// the dot gives us a parallel vector.
// When we subtract this from the displacement
// we get a vector normal to the ray.
// This is the shortest vector from the point to the ray.
[dx - dot * dir_x, dy - dot * dir_y]
}
/// Returns the least separation out of four.
/// Each seperation can be computed using `separation` function.
/// The separation returned can be used
/// to solve collision of rectangles.
#[inline(always)]
pub fn least_separation_4<T>(
sep1: Vec2d<T>,
sep2: Vec2d<T>,
sep3: Vec2d<T>,
sep4: Vec2d<T>,
) -> Vec2d<T>
where
T: Float,
{
let dot1 = sep1[0] * sep1[0] + sep1[1] * sep1[1];
let dot2 = sep2[0] * sep2[0] + sep2[1] * sep2[1];
let dot3 = sep3[0] * sep3[0] + sep3[1] * sep3[1];
let dot4 = sep4[0] * sep4[0] + sep4[1] * sep4[1];
// Search for the smallest dot product.
if dot1 < dot2 {
if dot3 < dot4 {
if dot1 < dot3 {
sep1
} else {
sep3
}
} else {
if dot1 < dot4 {
sep1
} else {
sep4
}
}
} else {
if dot3 < dot4 {
if dot2 < dot3 {
sep2
} else {
sep3
}
} else {
if dot2 < dot4 {
sep2
} else {
sep4
}
}
}
}
/// Shrinks a rectangle by a factor on all sides.
#[inline(always)]
pub fn margin_rectangle<T>(rect: Rectangle<T>, m: T) -> Rectangle<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _2: T = FromPrimitive::from_f64(2.0);
let w = rect[2] - _2 * m;
let h = rect[3] - _2 * m;
let (x, w) = if w < _0 {
(rect[0] + _05 * rect[2], _0)
} else {
(rect[0] + m, w)
};
let (y, h) = if h < _0 {
(rect[1] + _05 * rect[3], _0)
} else {
(rect[1] + m, h)
};
[x, y, w, h]
}
/// Computes a relative rectangle using the rectangle as a tile.
#[inline(always)]
pub fn relative_rectangle<T>(rect: Rectangle<T>, v: Vec2d<T>) -> Rectangle<T>
where
T: Float,
{
[
rect[0] + v[0] * rect[2],
rect[1] + v[1] * rect[3],
rect[2],
rect[3],
]
}
/// Computes overlap between two rectangles.
/// The area of the overlapping rectangle is positive.
/// A shared edge or corner is not considered overlap.
#[inline(always)]
pub fn overlap_rectangle<T>(a: Rectangle<T>, b: Rectangle<T>) -> Option<Rectangle<T>>
where
T: Float,
{
#[inline(always)]
fn min<T: Float>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
#[inline(always)]
fn max<T: Float>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
if a[0] < b[0] + b[2] && a[1] < b[1] + b[3] && b[0] < a[0] + a[2] && b[1] < a[1] + a[3] {
let x = max(a[0], b[0]);
let y = max(a[1], b[1]);
let w = min(a[0] + a[2], b[0] + b[2]) - x;
let h = min(a[1] + a[3], b[1] + b[3]) - y;
Some([x, y, w, h])
} else {
None
}
}
#[cfg(test)]
mod test_overlap {
use super::overlap_rectangle;
#[test]
fn overlap() {
let a = [0.0, 1.0, 100.0, 101.0];
let b = [51.0, 52.0, 102.0, 103.0];
let c = overlap_rectangle(a, b).unwrap();
assert_eq!(c, [51.0, 52.0, 49.0, 50.0]);
let d = overlap_rectangle(a, c).unwrap();
assert_eq!(d, c);
let e = overlap_rectangle(b, c).unwrap();
assert_eq!(e, c);
}
#[test]
fn edge() {
let a = [0.0, 0.0, 100.0, 100.0];
let b = [100.0, 0.0, 100.0, 100.0];
let c = overlap_rectangle(a, b);
assert_eq!(c, None);
}
}
/// Computes a relative source rectangle using
/// the source rectangle as a tile.
#[inline(always)]
pub fn relative_source_rectangle<T>(rect: SourceRectangle<T>, x: T, y: T) -> SourceRectangle<T>
where
T: Float,
{
let (rx, ry, rw, rh) = (rect[0], rect[1], rect[2], rect[3]);
let (x, y) = (rx + x * rw, ry + y * rh);
[x, y, rw, rh]
}
/// Computes modular offset safely for numbers.
#[inline(always)]
pub fn modular_offset<T: Add<Output = T> + Rem<Output = T> + Copy>(n: &T, i: &T, off: &T) -> T {
(*i + (*off % *n + *n)) % *n
}
#[cfg(test)]
mod test_modular_offset {
use super::*;
#[test]
fn test_modular_offset() {
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &-1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &-1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &1.0_f64), 1.0_f64);
}
}
/// Computes the area and centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
/// Source: http://en.wikipedia.org/wiki/Polygon_area#Simple_polygons
pub fn area_centroid<T>(polygon: Polygon<'_, T>) -> (Area<T>, Vec2d<T>)
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _3: T = FromPrimitive::from_f64(3.0);
let n = polygon.len();
let mut sum = _0;
let (mut cx, mut cy) = (_0, _0);
for i in 0..n {
let qx = polygon[i][0];
let qy = polygon[i][1];
let p_i = previous(n, i);
let px = polygon[p_i][0];
let py = polygon[p_i][1];
let cross = px * qy - qx * py;
cx += (px + qx) * cross;
cy += (py + qy) * cross;
sum += cross;
}
let area = _05 * sum;
// 'cx / (6.0 * area)' = 'cx / (3.0 * sum)'
let centroid = [cx / (_3 * sum), cy / (_3 * sum)];
(area, centroid)
}
/// Computes area of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn area<T>(polygon: Polygon<'_, T>) -> T
where
T: Float,
{
let (res, _) = area_centroid(polygon);
res
}
/// Computes centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn centroid<T>(polygon: Polygon<'_, T>) -> Vec2d<T>
where
T: Float,
{
let (_, res) = area_centroid(polygon);
res
}
/// Returns a number that tells which side it is relative to a line.
///
/// Computes the cross product of the vector that gives the line
/// with the vector between point and starting point of line.
/// One side of the line has opposite sign of the other.
#[inline(always)]
pub fn line_side<T>(line: Line<T>, v: Vec2d<T>) -> T
where
T: Float,
{
let (ax, ay) = (line[0], line[1]);
let (bx, by) = (line[2], line[3]);
(bx - ax) * (v[1] - ay) - (by - ay) * (v[0] - ax)
}
/// Returns true if point is inside triangle.
///
/// This is done by computing a `side` number for each edge.
/// If the number is inside if it is on the same side for all edges.
/// Might break for very small triangles.
pub fn inside_triangle<T>(triangle: Triangle<T>, v: Vec2d<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], v);
let bc_side = line_side([bx, by, cx, cy], v);
let ca_side = line_side([cx, cy, ax, ay], v);
let ab_positive = ab_side >= _0;
let bc_positive = bc_side >= _0;
let ca_positive = ca_side >= _0;
ab_positive == bc_positive && bc_positive == ca_positive
}
/// Returns true if triangle is clockwise.
///
/// This is done by computing which side the third vertex is relative to
/// the line starting from the first vertex to second vertex.
///
/// The triangle is considered clockwise if the third vertex is on the line
/// between the two first vertices.
#[inline(always)]
pub fn triangle_face<T>(triangle: Triangle<T>) -> bool
where
T: Float,
|
#[cfg(test)]
mod test_triangle {
use super::*;
#[test]
fn test_triangle() {
// Triangle counter clock-wise.
let tri_1 = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]];
// Triangle clock-wise.
let tri_2 = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0]];
let (x, y) = (0.5, 0.25);
assert!(inside_triangle(tri_1, [x, y]));
assert!(inside_triangle(tri_2, [x, y]));
assert_eq!(triangle_face(tri_1), false);
assert!(triangle_face(tri_2));
}
}
/// Transforms from cartesian coordinates to barycentric.
#[inline(always)]
pub fn to_barycentric<T>(triangle: Triangle<T>, pos: Vec2d<T>) -> Vec3d<T>
where
T: Float,
{
use vecmath::traits::One;
let _1: T = One::one();
let x = pos[0];
let y = pos[1];
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
let lambda1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda3 = _1 - lambda1 - lambda2;
[lambda1, lambda2, lambda3]
}
/// Transforms from barycentric coordinates to cartesian.
#[inline(always)]
pub fn from_barycentric<T>(triangle: Triangle<T>, lambda: Vec3d<T>) -> Vec2d<T>
where
T: Float,
{
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
[
lambda[0] * x1 + lambda[1] * x2 + lambda[2] * x3,
lambda[0] * y1 + lambda[1] * y2 + lambda[2] * y3,
]
}
#[cfg(test)]
mod test_barycentric {
use super::*;
#[test]
fn test_barycentric() {
let triangle = [[0.0, 0.0], [100.0, 0.0], [0.0, 50.0]];
let old_pos = [10.0, 20.0];
let b = to_barycentric(triangle, old_pos);
let new_pos: Vec2d = from_barycentric(triangle, b);
let eps = 0.00001;
assert!((new_pos[0] - old_pos[0]).abs() < eps);
assert!((new_pos[1] - old_pos[1]).abs() < eps);
}
}
/// Transform color with hue, saturation and value.
///
/// Source: http://beesbuzz.biz/code/hsv_color_transforms.php
#[inline(always)]
pub fn hsv(color: Color, h_rad: f32, s: f32, v: f32) -> Color {
let vsu = v * s * h_rad.cos();
let vsw = v * s * h_rad.sin();
[
(0.299 * v + 0.701 * vsu + 0.168 * vsw) * color[0]
+ (0.587 * v - 0.587 * vsu + 0.330 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu - 0.497 * vsw) * color[2],
(0.299 * v - 0.299 * vsu - 0.328 * vsw) * color[0]
+ (0.587 * v + 0.413 * vsu + 0.035 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu + 0.292 * vsw) * color[2],
(0.299 * v - 0.3 * vsu + 1.25 * vsw) * color[0]
+ (0.587 * v - 0.588 * vsu - 1.05 * vsw) * color[1]
+ (0.114 * v + 0.886 * vsu - 0.203 * vsw) * color[2],
color[3],
]
}
|
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], [cx, cy]);
ab_side <= _0
}
|
identifier_body
|
math.rs
|
//! Various methods for computing with vectors.
use std::ops::{Add, Rem};
use vecmath::{self, traits::Float};
pub use vecmath::{
mat2x3_inv as invert, row_mat2x3_mul as multiply, row_mat2x3_transform_pos2 as transform_pos,
row_mat2x3_transform_vec2 as transform_vec, vec2_add as add, vec2_cast as cast,
vec2_cross as cross, vec2_dot as dot, vec2_mul as mul, vec2_scale as mul_scalar,
vec2_square_len as square_len, vec2_sub as sub,
};
use crate::{
modular_index::previous,
types::{Area, Color, Line, Polygon, Ray, Rectangle, SourceRectangle, Triangle},
};
/// The type used for scalars.
pub type Scalar = f64;
/// The type used for matrices.
pub type Matrix2d<T = Scalar> = vecmath::Matrix2x3<T>;
/// The type used for 2D vectors.
pub type Vec2d<T = Scalar> = vecmath::Vector2<T>;
/// The type used for 3D vectors.
pub type Vec3d<T = Scalar> = vecmath::Vector3<T>;
/// Creates a perpendicular vector.
#[inline(always)]
pub fn perp<T>(v: [T; 2]) -> [T; 2]
where
T: Float,
{
[-v[1], v[0]]
}
/// Transforms from normalized to absolute coordinates.
///
/// Computes absolute transform from width and height of viewport.
/// In absolute coordinates, the x axis points to the right,
/// and the y axis points down on the screen.
#[inline(always)]
pub fn abs_transform<T>(w: T, h: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
let _2: T = FromPrimitive::from_f64(2.0);
let sx = _2 / w;
let sy = -_2 / h;
[[sx, _0, -_1], [_0, sy, _1]]
}
/// Creates a translation matrix.
#[inline(always)]
pub fn translate<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, v[0]], [_0, _1, v[1]]]
}
/// Creates a rotation matrix.
#[inline(always)]
pub fn rotate_radians<T>(angle: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let c = angle.cos();
let s = angle.sin();
[[c, -s, _0], [s, c, _0]]
}
/// Orients x axis to look at point.
///
/// Leaves x axis unchanged if the
/// point to look at is the origin.
#[inline(always)]
pub fn orient<T>(x: T, y: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let len = x * x + y * y;
if len == _0 {
return identity();
}
let len = len.sqrt();
let c = x / len;
let s = y / len;
[[c, -s, _0], [s, c, _0]]
}
/// Create a scale matrix.
#[inline(always)]
pub fn scale<T>(sx: T, sy: T) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
[[sx, _0, _0], [_0, sy, _0]]
}
/// Create a shear matrix.
#[inline(always)]
pub fn shear<T>(v: Vec2d<T>) -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0 = Zero::zero();
let _1 = One::one();
[[_1, v[0], _0], [v[1], _1, _0]]
}
/// Create an identity matrix.
#[inline(always)]
pub fn identity<T>() -> Matrix2d<T>
where
T: Float,
{
use vecmath::traits::{One, Zero};
let _0: T = Zero::zero();
let _1: T = One::one();
[[_1, _0, _0], [_0, _1, _0]]
}
/// Extract scale information from matrix.
#[inline(always)]
pub fn get_scale<T>(m: Matrix2d<T>) -> Vec2d<T>
where
T: Float,
{
[
(m[0][0] * m[0][0] + m[1][0] * m[1][0]).sqrt(),
(m[0][1] * m[0][1] + m[1][1] * m[1][1]).sqrt(),
]
}
/// Compute the shortest vector from point to ray.
/// A ray stores starting point and directional vector.
#[inline(always)]
pub fn separation<T>(ray: Ray<T>, v: Vec2d<T>) -> Vec2d<T>
where
T: Float,
{
// Get the directional vector.
let (dir_x, dir_y) = (ray[2], ray[3]);
// Get displacement vector from point.
let (dx, dy) = (ray[0] - v[0], ray[1] - v[1]);
// Compute the component of position in ray direction.
let dot = dir_x * v[0] + dir_y * v[1];
// The directional vector multiplied with
// the dot gives us a parallel vector.
// When we subtract this from the displacement
// we get a vector normal to the ray.
// This is the shortest vector from the point to the ray.
[dx - dot * dir_x, dy - dot * dir_y]
}
/// Returns the least separation out of four.
/// Each seperation can be computed using `separation` function.
/// The separation returned can be used
/// to solve collision of rectangles.
#[inline(always)]
pub fn least_separation_4<T>(
sep1: Vec2d<T>,
sep2: Vec2d<T>,
sep3: Vec2d<T>,
sep4: Vec2d<T>,
) -> Vec2d<T>
where
T: Float,
{
let dot1 = sep1[0] * sep1[0] + sep1[1] * sep1[1];
let dot2 = sep2[0] * sep2[0] + sep2[1] * sep2[1];
let dot3 = sep3[0] * sep3[0] + sep3[1] * sep3[1];
let dot4 = sep4[0] * sep4[0] + sep4[1] * sep4[1];
// Search for the smallest dot product.
if dot1 < dot2 {
if dot3 < dot4 {
if dot1 < dot3 {
sep1
} else {
sep3
}
} else {
if dot1 < dot4 {
sep1
} else {
sep4
}
}
} else {
if dot3 < dot4 {
if dot2 < dot3 {
sep2
} else {
sep3
}
} else {
if dot2 < dot4 {
sep2
} else {
sep4
}
}
}
}
/// Shrinks a rectangle by a factor on all sides.
#[inline(always)]
pub fn margin_rectangle<T>(rect: Rectangle<T>, m: T) -> Rectangle<T>
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _2: T = FromPrimitive::from_f64(2.0);
let w = rect[2] - _2 * m;
let h = rect[3] - _2 * m;
let (x, w) = if w < _0 {
(rect[0] + _05 * rect[2], _0)
} else {
(rect[0] + m, w)
};
let (y, h) = if h < _0 {
(rect[1] + _05 * rect[3], _0)
} else {
(rect[1] + m, h)
};
[x, y, w, h]
}
/// Computes a relative rectangle using the rectangle as a tile.
#[inline(always)]
pub fn relative_rectangle<T>(rect: Rectangle<T>, v: Vec2d<T>) -> Rectangle<T>
where
T: Float,
{
[
rect[0] + v[0] * rect[2],
rect[1] + v[1] * rect[3],
rect[2],
rect[3],
]
}
/// Computes overlap between two rectangles.
/// The area of the overlapping rectangle is positive.
/// A shared edge or corner is not considered overlap.
#[inline(always)]
pub fn overlap_rectangle<T>(a: Rectangle<T>, b: Rectangle<T>) -> Option<Rectangle<T>>
where
T: Float,
{
#[inline(always)]
fn min<T: Float>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
#[inline(always)]
fn max<T: Float>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
if a[0] < b[0] + b[2] && a[1] < b[1] + b[3] && b[0] < a[0] + a[2] && b[1] < a[1] + a[3] {
let x = max(a[0], b[0]);
let y = max(a[1], b[1]);
let w = min(a[0] + a[2], b[0] + b[2]) - x;
let h = min(a[1] + a[3], b[1] + b[3]) - y;
Some([x, y, w, h])
} else {
None
}
}
#[cfg(test)]
mod test_overlap {
use super::overlap_rectangle;
#[test]
fn overlap() {
let a = [0.0, 1.0, 100.0, 101.0];
let b = [51.0, 52.0, 102.0, 103.0];
let c = overlap_rectangle(a, b).unwrap();
assert_eq!(c, [51.0, 52.0, 49.0, 50.0]);
let d = overlap_rectangle(a, c).unwrap();
assert_eq!(d, c);
let e = overlap_rectangle(b, c).unwrap();
assert_eq!(e, c);
}
#[test]
fn edge() {
let a = [0.0, 0.0, 100.0, 100.0];
let b = [100.0, 0.0, 100.0, 100.0];
let c = overlap_rectangle(a, b);
assert_eq!(c, None);
}
}
/// Computes a relative source rectangle using
/// the source rectangle as a tile.
#[inline(always)]
pub fn relative_source_rectangle<T>(rect: SourceRectangle<T>, x: T, y: T) -> SourceRectangle<T>
where
T: Float,
{
let (rx, ry, rw, rh) = (rect[0], rect[1], rect[2], rect[3]);
let (x, y) = (rx + x * rw, ry + y * rh);
[x, y, rw, rh]
}
/// Computes modular offset safely for numbers.
#[inline(always)]
pub fn modular_offset<T: Add<Output = T> + Rem<Output = T> + Copy>(n: &T, i: &T, off: &T) -> T {
(*i + (*off % *n + *n)) % *n
}
#[cfg(test)]
mod test_modular_offset {
use super::*;
#[test]
fn test_modular_offset() {
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &-1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &-1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &-1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &0.0_f64, &1.0_f64), 1.0_f64);
assert_eq!(modular_offset(&3.0_f64, &1.0_f64, &1.0_f64), 2.0_f64);
assert_eq!(modular_offset(&3.0_f64, &2.0_f64, &1.0_f64), 0.0_f64);
assert_eq!(modular_offset(&3.0_f64, &3.0_f64, &1.0_f64), 1.0_f64);
}
}
/// Computes the area and centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
/// Source: http://en.wikipedia.org/wiki/Polygon_area#Simple_polygons
pub fn area_centroid<T>(polygon: Polygon<'_, T>) -> (Area<T>, Vec2d<T>)
where
T: Float,
{
use vecmath::traits::{FromPrimitive, Zero};
let _0: T = Zero::zero();
let _05: T = FromPrimitive::from_f64(0.5);
let _3: T = FromPrimitive::from_f64(3.0);
let n = polygon.len();
let mut sum = _0;
let (mut cx, mut cy) = (_0, _0);
for i in 0..n {
let qx = polygon[i][0];
let qy = polygon[i][1];
let p_i = previous(n, i);
let px = polygon[p_i][0];
let py = polygon[p_i][1];
let cross = px * qy - qx * py;
cx += (px + qx) * cross;
cy += (py + qy) * cross;
sum += cross;
}
let area = _05 * sum;
// 'cx / (6.0 * area)' = 'cx / (3.0 * sum)'
let centroid = [cx / (_3 * sum), cy / (_3 * sum)];
(area, centroid)
}
/// Computes area of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn area<T>(polygon: Polygon<'_, T>) -> T
where
T: Float,
{
let (res, _) = area_centroid(polygon);
res
}
/// Computes centroid of a simple polygon.
///
/// A simple polygon is one that does not intersect itself.
#[inline(always)]
pub fn
|
<T>(polygon: Polygon<'_, T>) -> Vec2d<T>
where
T: Float,
{
let (_, res) = area_centroid(polygon);
res
}
/// Returns a number that tells which side it is relative to a line.
///
/// Computes the cross product of the vector that gives the line
/// with the vector between point and starting point of line.
/// One side of the line has opposite sign of the other.
#[inline(always)]
pub fn line_side<T>(line: Line<T>, v: Vec2d<T>) -> T
where
T: Float,
{
let (ax, ay) = (line[0], line[1]);
let (bx, by) = (line[2], line[3]);
(bx - ax) * (v[1] - ay) - (by - ay) * (v[0] - ax)
}
/// Returns true if point is inside triangle.
///
/// This is done by computing a `side` number for each edge.
/// If the number is inside if it is on the same side for all edges.
/// Might break for very small triangles.
pub fn inside_triangle<T>(triangle: Triangle<T>, v: Vec2d<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0: T = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], v);
let bc_side = line_side([bx, by, cx, cy], v);
let ca_side = line_side([cx, cy, ax, ay], v);
let ab_positive = ab_side >= _0;
let bc_positive = bc_side >= _0;
let ca_positive = ca_side >= _0;
ab_positive == bc_positive && bc_positive == ca_positive
}
/// Returns true if triangle is clockwise.
///
/// This is done by computing which side the third vertex is relative to
/// the line starting from the first vertex to second vertex.
///
/// The triangle is considered clockwise if the third vertex is on the line
/// between the two first vertices.
#[inline(always)]
pub fn triangle_face<T>(triangle: Triangle<T>) -> bool
where
T: Float,
{
use vecmath::traits::Zero;
let _0 = Zero::zero();
let ax = triangle[0][0];
let ay = triangle[0][1];
let bx = triangle[1][0];
let by = triangle[1][1];
let cx = triangle[2][0];
let cy = triangle[2][1];
let ab_side = line_side([ax, ay, bx, by], [cx, cy]);
ab_side <= _0
}
#[cfg(test)]
mod test_triangle {
use super::*;
#[test]
fn test_triangle() {
// Triangle counter clock-wise.
let tri_1 = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]];
// Triangle clock-wise.
let tri_2 = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0]];
let (x, y) = (0.5, 0.25);
assert!(inside_triangle(tri_1, [x, y]));
assert!(inside_triangle(tri_2, [x, y]));
assert_eq!(triangle_face(tri_1), false);
assert!(triangle_face(tri_2));
}
}
/// Transforms from cartesian coordinates to barycentric.
#[inline(always)]
pub fn to_barycentric<T>(triangle: Triangle<T>, pos: Vec2d<T>) -> Vec3d<T>
where
T: Float,
{
use vecmath::traits::One;
let _1: T = One::one();
let x = pos[0];
let y = pos[1];
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
let lambda1 = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda2 = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3))
/ ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
let lambda3 = _1 - lambda1 - lambda2;
[lambda1, lambda2, lambda3]
}
/// Transforms from barycentric coordinates to cartesian.
#[inline(always)]
pub fn from_barycentric<T>(triangle: Triangle<T>, lambda: Vec3d<T>) -> Vec2d<T>
where
T: Float,
{
let x1 = triangle[0][0];
let y1 = triangle[0][1];
let x2 = triangle[1][0];
let y2 = triangle[1][1];
let x3 = triangle[2][0];
let y3 = triangle[2][1];
[
lambda[0] * x1 + lambda[1] * x2 + lambda[2] * x3,
lambda[0] * y1 + lambda[1] * y2 + lambda[2] * y3,
]
}
#[cfg(test)]
mod test_barycentric {
use super::*;
#[test]
fn test_barycentric() {
let triangle = [[0.0, 0.0], [100.0, 0.0], [0.0, 50.0]];
let old_pos = [10.0, 20.0];
let b = to_barycentric(triangle, old_pos);
let new_pos: Vec2d = from_barycentric(triangle, b);
let eps = 0.00001;
assert!((new_pos[0] - old_pos[0]).abs() < eps);
assert!((new_pos[1] - old_pos[1]).abs() < eps);
}
}
/// Transform color with hue, saturation and value.
///
/// Source: http://beesbuzz.biz/code/hsv_color_transforms.php
#[inline(always)]
pub fn hsv(color: Color, h_rad: f32, s: f32, v: f32) -> Color {
let vsu = v * s * h_rad.cos();
let vsw = v * s * h_rad.sin();
[
(0.299 * v + 0.701 * vsu + 0.168 * vsw) * color[0]
+ (0.587 * v - 0.587 * vsu + 0.330 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu - 0.497 * vsw) * color[2],
(0.299 * v - 0.299 * vsu - 0.328 * vsw) * color[0]
+ (0.587 * v + 0.413 * vsu + 0.035 * vsw) * color[1]
+ (0.114 * v - 0.114 * vsu + 0.292 * vsw) * color[2],
(0.299 * v - 0.3 * vsu + 1.25 * vsw) * color[0]
+ (0.587 * v - 0.588 * vsu - 1.05 * vsw) * color[1]
+ (0.114 * v + 0.886 * vsu - 0.203 * vsw) * color[2],
color[3],
]
}
|
centroid
|
identifier_name
|
scoping_rules_lifetimes_structs.rs
|
// A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// Similarly, both references here must outlive this structure.
#[derive(Debug)]
struct NamedBorrowed<'a> {
x: &'a i32,
y: &'a i32,
}
// An enum which is either an `i32` or a reference to one.
#[derive(Debug)]
enum Either<'a> {
Num(i32),
Ref(&'a i32),
}
pub fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
|
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);
println!("x is borrowed in {:?}", reference);
println!("y is *not* borrowed in {:?}", number);
}
|
let reference = Either::Ref(&x);
let number = Either::Num(y);
|
random_line_split
|
scoping_rules_lifetimes_structs.rs
|
// A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// Similarly, both references here must outlive this structure.
#[derive(Debug)]
struct NamedBorrowed<'a> {
x: &'a i32,
y: &'a i32,
}
// An enum which is either an `i32` or a reference to one.
#[derive(Debug)]
enum
|
<'a> {
Num(i32),
Ref(&'a i32),
}
pub fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
let reference = Either::Ref(&x);
let number = Either::Num(y);
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);
println!("x is borrowed in {:?}", reference);
println!("y is *not* borrowed in {:?}", number);
}
|
Either
|
identifier_name
|
report.rs
|
use rustc_serialize::json;
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ReportContent {
pub domains: Option<Vec<String>>,
pub definitions: Option<Vec<String>>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct
|
{
pub report: super::MetadataObjectBody<ReportContent>,
}
impl Report {
pub fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.report
}
}
impl super::MetadataObjectGetter<ReportContent> for Report {
fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.object()
}
}
impl Into<String> for Report {
fn into(self) -> String {
format!("{}\n", json::as_pretty_json(&self).to_string())
}
}
pub const NAME: &'static str = "report";
impl super::MetadataObjectRootKey for Report {
fn root_key() -> String {
NAME.to_string()
}
}
impl super::MetadataQuery<super::MetadataQueryBody<Report>> {
pub fn find_by_identifier(&self, identifier: &String) -> (u32, Option<Report>) {
let mut i: u32 = 0;
for item in self.objects().items().into_iter() {
if item.object().meta().identifier().as_ref().unwrap() == identifier {
return (i, Some(item.clone()));
}
i += 1;
}
(0, None)
}
}
|
Report
|
identifier_name
|
report.rs
|
use rustc_serialize::json;
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ReportContent {
pub domains: Option<Vec<String>>,
pub definitions: Option<Vec<String>>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct Report {
pub report: super::MetadataObjectBody<ReportContent>,
}
impl Report {
pub fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.report
}
}
impl super::MetadataObjectGetter<ReportContent> for Report {
fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.object()
}
}
impl Into<String> for Report {
fn into(self) -> String {
format!("{}\n", json::as_pretty_json(&self).to_string())
}
}
pub const NAME: &'static str = "report";
impl super::MetadataObjectRootKey for Report {
fn root_key() -> String {
NAME.to_string()
}
}
impl super::MetadataQuery<super::MetadataQueryBody<Report>> {
pub fn find_by_identifier(&self, identifier: &String) -> (u32, Option<Report>) {
let mut i: u32 = 0;
for item in self.objects().items().into_iter() {
if item.object().meta().identifier().as_ref().unwrap() == identifier
|
i += 1;
}
(0, None)
}
}
|
{
return (i, Some(item.clone()));
}
|
conditional_block
|
report.rs
|
use rustc_serialize::json;
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ReportContent {
pub domains: Option<Vec<String>>,
pub definitions: Option<Vec<String>>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct Report {
pub report: super::MetadataObjectBody<ReportContent>,
}
impl Report {
pub fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.report
}
}
impl super::MetadataObjectGetter<ReportContent> for Report {
fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.object()
}
}
impl Into<String> for Report {
fn into(self) -> String {
format!("{}\n", json::as_pretty_json(&self).to_string())
}
}
pub const NAME: &'static str = "report";
impl super::MetadataObjectRootKey for Report {
fn root_key() -> String {
NAME.to_string()
}
}
|
impl super::MetadataQuery<super::MetadataQueryBody<Report>> {
pub fn find_by_identifier(&self, identifier: &String) -> (u32, Option<Report>) {
let mut i: u32 = 0;
for item in self.objects().items().into_iter() {
if item.object().meta().identifier().as_ref().unwrap() == identifier {
return (i, Some(item.clone()));
}
i += 1;
}
(0, None)
}
}
|
random_line_split
|
|
report.rs
|
use rustc_serialize::json;
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ReportContent {
pub domains: Option<Vec<String>>,
pub definitions: Option<Vec<String>>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct Report {
pub report: super::MetadataObjectBody<ReportContent>,
}
impl Report {
pub fn object(&self) -> &super::MetadataObjectBody<ReportContent>
|
}
impl super::MetadataObjectGetter<ReportContent> for Report {
fn object(&self) -> &super::MetadataObjectBody<ReportContent> {
&self.object()
}
}
impl Into<String> for Report {
fn into(self) -> String {
format!("{}\n", json::as_pretty_json(&self).to_string())
}
}
pub const NAME: &'static str = "report";
impl super::MetadataObjectRootKey for Report {
fn root_key() -> String {
NAME.to_string()
}
}
impl super::MetadataQuery<super::MetadataQueryBody<Report>> {
pub fn find_by_identifier(&self, identifier: &String) -> (u32, Option<Report>) {
let mut i: u32 = 0;
for item in self.objects().items().into_iter() {
if item.object().meta().identifier().as_ref().unwrap() == identifier {
return (i, Some(item.clone()));
}
i += 1;
}
(0, None)
}
}
|
{
&self.report
}
|
identifier_body
|
version.rs
|
/* automatically generated by rust-bindgen */
pub const R_VERSION: u32 = 197635;
|
pub const R_MINOR: &'static [u8; 4usize] = b"4.3\0";
pub const R_STATUS: &'static [u8; 1usize] = b"\0";
pub const R_YEAR: &'static [u8; 5usize] = b"2017\0";
pub const R_MONTH: &'static [u8; 3usize] = b"11\0";
pub const R_DAY: &'static [u8; 3usize] = b"30\0";
pub const R_SVN_REVISION: u32 = 73796;
|
pub const R_NICK: &'static [u8; 17usize] = b"Kite-Eating Tree\0";
pub const R_MAJOR: &'static [u8; 2usize] = b"3\0";
|
random_line_split
|
context.rs
|
use ::handle::{Handle,HandleMut};
/// A `libgphoto2` library context.
pub struct Context {
context: *mut ::gphoto2::GPContext,
}
impl Context {
/// Creates a new context.
pub fn new() -> ::Result<Context> {
let ptr = unsafe { ::gphoto2::gp_context_new() };
if!ptr.is_null() {
Ok(Context { context: ptr })
}
else
|
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
::gphoto2::gp_context_unref(self.context);
}
}
}
#[doc(hidden)]
impl Handle<::gphoto2::GPContext> for Context {
unsafe fn as_ptr(&self) -> *const ::gphoto2::GPContext {
self.context
}
}
#[doc(hidden)]
impl HandleMut<::gphoto2::GPContext> for Context {
unsafe fn as_mut_ptr(&mut self) -> *mut ::gphoto2::GPContext {
self.context
}
}
|
{
Err(::error::from_libgphoto2(::gphoto2::GP_ERROR_NO_MEMORY))
}
|
conditional_block
|
context.rs
|
use ::handle::{Handle,HandleMut};
/// A `libgphoto2` library context.
pub struct Context {
context: *mut ::gphoto2::GPContext,
}
impl Context {
/// Creates a new context.
pub fn new() -> ::Result<Context> {
let ptr = unsafe { ::gphoto2::gp_context_new() };
if!ptr.is_null() {
Ok(Context { context: ptr })
}
else {
Err(::error::from_libgphoto2(::gphoto2::GP_ERROR_NO_MEMORY))
}
}
}
impl Drop for Context {
fn drop(&mut self)
|
}
#[doc(hidden)]
impl Handle<::gphoto2::GPContext> for Context {
unsafe fn as_ptr(&self) -> *const ::gphoto2::GPContext {
self.context
}
}
#[doc(hidden)]
impl HandleMut<::gphoto2::GPContext> for Context {
unsafe fn as_mut_ptr(&mut self) -> *mut ::gphoto2::GPContext {
self.context
}
}
|
{
unsafe {
::gphoto2::gp_context_unref(self.context);
}
}
|
identifier_body
|
context.rs
|
use ::handle::{Handle,HandleMut};
/// A `libgphoto2` library context.
pub struct Context {
context: *mut ::gphoto2::GPContext,
}
impl Context {
/// Creates a new context.
pub fn new() -> ::Result<Context> {
let ptr = unsafe { ::gphoto2::gp_context_new() };
if!ptr.is_null() {
Ok(Context { context: ptr })
}
else {
Err(::error::from_libgphoto2(::gphoto2::GP_ERROR_NO_MEMORY))
}
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
::gphoto2::gp_context_unref(self.context);
}
}
}
#[doc(hidden)]
impl Handle<::gphoto2::GPContext> for Context {
unsafe fn
|
(&self) -> *const ::gphoto2::GPContext {
self.context
}
}
#[doc(hidden)]
impl HandleMut<::gphoto2::GPContext> for Context {
unsafe fn as_mut_ptr(&mut self) -> *mut ::gphoto2::GPContext {
self.context
}
}
|
as_ptr
|
identifier_name
|
context.rs
|
use ::handle::{Handle,HandleMut};
/// A `libgphoto2` library context.
pub struct Context {
context: *mut ::gphoto2::GPContext,
}
impl Context {
/// Creates a new context.
pub fn new() -> ::Result<Context> {
let ptr = unsafe { ::gphoto2::gp_context_new() };
if!ptr.is_null() {
Ok(Context { context: ptr })
}
else {
Err(::error::from_libgphoto2(::gphoto2::GP_ERROR_NO_MEMORY))
}
}
}
impl Drop for Context {
|
unsafe {
::gphoto2::gp_context_unref(self.context);
}
}
}
#[doc(hidden)]
impl Handle<::gphoto2::GPContext> for Context {
unsafe fn as_ptr(&self) -> *const ::gphoto2::GPContext {
self.context
}
}
#[doc(hidden)]
impl HandleMut<::gphoto2::GPContext> for Context {
unsafe fn as_mut_ptr(&mut self) -> *mut ::gphoto2::GPContext {
self.context
}
}
|
fn drop(&mut self) {
|
random_line_split
|
resource.rs
|
//! Configure the process resource limits.
use cfg_if::cfg_if;
use crate::errno::Errno;
use crate::Result;
pub use libc::rlim_t;
use std::mem;
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
use libc::{__rlimit_resource_t, rlimit, RLIM_INFINITY};
} else if #[cfg(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "dragonfly",
all(target_os = "linux", not(target_env = "gnu"))
))]{
use libc::{c_int, rlimit, RLIM_INFINITY};
}
}
libc_enum! {
/// Types of process resources.
///
/// The Resource enum is platform dependent. Check different platform
/// manuals for more details. Some platform links have been provided for
/// easier reference (non-exhaustive).
///
/// * [Linux](https://man7.org/linux/man-pages/man2/getrlimit.2.html)
/// * [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=setrlimit)
/// * [NetBSD](https://man.netbsd.org/setrlimit.2)
// linux-gnu uses u_int as resource enum, which is implemented in libc as
// well.
//
// https://gcc.gnu.org/legacy-ml/gcc/2015-08/msg00441.html
// https://github.com/rust-lang/libc/blob/master/src/unix/linux_like/linux/gnu/mod.rs
#[cfg_attr(all(target_os = "linux", target_env = "gnu"), repr(u32))]
#[cfg_attr(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "dragonfly",
all(target_os = "linux", not(target_env = "gnu"))
), repr(i32))]
#[non_exhaustive]
pub enum Resource {
#[cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum amount (in bytes) of virtual memory the process is
/// allowed to map.
RLIMIT_AS,
/// The largest size (in bytes) core(5) file that may be created.
RLIMIT_CORE,
/// The maximum amount of cpu time (in seconds) to be used by each
/// process.
RLIMIT_CPU,
/// The maximum size (in bytes) of the data segment for a process
RLIMIT_DATA,
/// The largest size (in bytes) file that may be created.
RLIMIT_FSIZE,
/// The maximum number of open files for this process.
RLIMIT_NOFILE,
/// The maximum size (in bytes) of the stack segment for a process.
RLIMIT_STACK,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of kqueues this user id is allowed to create.
RLIMIT_KQUEUES,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the combined number of flock locks and fcntl leases that
/// this process may establish.
RLIMIT_LOCKS,
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "openbsd",
target_os = "linux",
target_os = "netbsd"
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) which a process may lock into memory
/// using the mlock(2) system call.
RLIMIT_MEMLOCK,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the number of bytes that can be allocated for POSIX
/// message queues for the real user ID of the calling process.
RLIMIT_MSGQUEUE,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A ceiling to which the process's nice value can be raised using
/// setpriority or nice.
RLIMIT_NICE,
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux",
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of simultaneous processes for this user id.
RLIMIT_NPROC,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of pseudo-terminals this user id is allowed to
/// create.
RLIMIT_NPTS,
#[cfg(any(target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux",
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// When there is memory pressure and swap is available, prioritize
/// eviction of a process' resident pages beyond this amount (in bytes).
RLIMIT_RSS,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A ceiling on the real-time priority that may be set for this process
/// using sched_setscheduler and sched_set‐ param.
RLIMIT_RTPRIO,
#[cfg(any(target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit (in microseconds) on the amount of CPU time that a process
/// scheduled under a real-time scheduling policy may con‐ sume without
/// making a blocking system call.
RLIMIT_RTTIME,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the number of signals that may be queued for the real
/// user ID of the calling process.
RLIMIT_SIGPENDING,
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
|
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) of the swap space that may be reserved
/// or used by all of this user id's processes.
RLIMIT_SWAP,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// An alias for RLIMIT_AS.
RLIMIT_VMEM,
}
}
/// Get the current processes resource limits
///
/// A value of `None` indicates the value equals to `RLIM_INFINITY` which means
/// there is no limit.
///
/// # Parameters
///
/// * `resource`: The [`Resource`] that we want to get the limits of.
///
/// # Examples
///
/// ```
/// # use nix::sys::resource::{getrlimit, Resource};
///
/// let (soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap();
/// println!("current soft_limit: {:?}", soft_limit);
/// println!("current hard_limit: {:?}", hard_limit);
/// ```
///
/// # References
///
/// [getrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
///
/// [`Resource`]: enum.Resource.html
pub fn getrlimit(resource: Resource) -> Result<(Option<rlim_t>, Option<rlim_t>)> {
let mut old_rlim = mem::MaybeUninit::<rlimit>::uninit();
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
let res = unsafe { libc::getrlimit(resource as __rlimit_resource_t, old_rlim.as_mut_ptr()) };
} else {
let res = unsafe { libc::getrlimit(resource as c_int, old_rlim.as_mut_ptr()) };
}
}
Errno::result(res).map(|_| {
let rlimit { rlim_cur, rlim_max } = unsafe { old_rlim.assume_init() };
(Some(rlim_cur), Some(rlim_max))
})
}
/// Set the current processes resource limits
///
/// # Parameters
///
/// * `resource`: The [`Resource`] that we want to set the limits of.
/// * `soft_limit`: The value that the kernel enforces for the corresponding
/// resource. Note: `None` input will be replaced by constant `RLIM_INFINITY`.
/// * `hard_limit`: The ceiling for the soft limit. Must be lower or equal to
/// the current hard limit for non-root users. Note: `None` input will be
/// replaced by constant `RLIM_INFINITY`.
///
/// > Note: for some os (linux_gnu), setting hard_limit to `RLIM_INFINITY` can
/// > results `EPERM` Error. So you will need to set the number explicitly.
///
/// # Examples
///
/// ```
/// # use nix::sys::resource::{setrlimit, Resource};
///
/// let soft_limit = Some(512);
/// let hard_limit = Some(1024);
/// setrlimit(Resource::RLIMIT_NOFILE, soft_limit, hard_limit).unwrap();
/// ```
///
/// # References
///
/// [setrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
///
/// [`Resource`]: enum.Resource.html
///
/// Note: `setrlimit` provides a safe wrapper to libc's `setrlimit`.
pub fn setrlimit(
resource: Resource,
soft_limit: Option<rlim_t>,
hard_limit: Option<rlim_t>,
) -> Result<()> {
let new_rlim = rlimit {
rlim_cur: soft_limit.unwrap_or(RLIM_INFINITY),
rlim_max: hard_limit.unwrap_or(RLIM_INFINITY),
};
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
let res = unsafe { libc::setrlimit(resource as __rlimit_resource_t, &new_rlim as *const rlimit) };
}else{
let res = unsafe { libc::setrlimit(resource as c_int, &new_rlim as *const rlimit) };
}
}
Errno::result(res).map(drop)
}
|
/// The maximum size (in bytes) of socket buffer usage for this user.
RLIMIT_SBSIZE,
#[cfg(target_os = "freebsd")]
|
random_line_split
|
resource.rs
|
//! Configure the process resource limits.
use cfg_if::cfg_if;
use crate::errno::Errno;
use crate::Result;
pub use libc::rlim_t;
use std::mem;
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
use libc::{__rlimit_resource_t, rlimit, RLIM_INFINITY};
} else if #[cfg(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "dragonfly",
all(target_os = "linux", not(target_env = "gnu"))
))]{
use libc::{c_int, rlimit, RLIM_INFINITY};
}
}
libc_enum! {
/// Types of process resources.
///
/// The Resource enum is platform dependent. Check different platform
/// manuals for more details. Some platform links have been provided for
/// easier reference (non-exhaustive).
///
/// * [Linux](https://man7.org/linux/man-pages/man2/getrlimit.2.html)
/// * [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=setrlimit)
/// * [NetBSD](https://man.netbsd.org/setrlimit.2)
// linux-gnu uses u_int as resource enum, which is implemented in libc as
// well.
//
// https://gcc.gnu.org/legacy-ml/gcc/2015-08/msg00441.html
// https://github.com/rust-lang/libc/blob/master/src/unix/linux_like/linux/gnu/mod.rs
#[cfg_attr(all(target_os = "linux", target_env = "gnu"), repr(u32))]
#[cfg_attr(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "dragonfly",
all(target_os = "linux", not(target_env = "gnu"))
), repr(i32))]
#[non_exhaustive]
pub enum Resource {
#[cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum amount (in bytes) of virtual memory the process is
/// allowed to map.
RLIMIT_AS,
/// The largest size (in bytes) core(5) file that may be created.
RLIMIT_CORE,
/// The maximum amount of cpu time (in seconds) to be used by each
/// process.
RLIMIT_CPU,
/// The maximum size (in bytes) of the data segment for a process
RLIMIT_DATA,
/// The largest size (in bytes) file that may be created.
RLIMIT_FSIZE,
/// The maximum number of open files for this process.
RLIMIT_NOFILE,
/// The maximum size (in bytes) of the stack segment for a process.
RLIMIT_STACK,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of kqueues this user id is allowed to create.
RLIMIT_KQUEUES,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the combined number of flock locks and fcntl leases that
/// this process may establish.
RLIMIT_LOCKS,
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "openbsd",
target_os = "linux",
target_os = "netbsd"
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) which a process may lock into memory
/// using the mlock(2) system call.
RLIMIT_MEMLOCK,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the number of bytes that can be allocated for POSIX
/// message queues for the real user ID of the calling process.
RLIMIT_MSGQUEUE,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A ceiling to which the process's nice value can be raised using
/// setpriority or nice.
RLIMIT_NICE,
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux",
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of simultaneous processes for this user id.
RLIMIT_NPROC,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of pseudo-terminals this user id is allowed to
/// create.
RLIMIT_NPTS,
#[cfg(any(target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux",
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// When there is memory pressure and swap is available, prioritize
/// eviction of a process' resident pages beyond this amount (in bytes).
RLIMIT_RSS,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A ceiling on the real-time priority that may be set for this process
/// using sched_setscheduler and sched_set‐ param.
RLIMIT_RTPRIO,
#[cfg(any(target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit (in microseconds) on the amount of CPU time that a process
/// scheduled under a real-time scheduling policy may con‐ sume without
/// making a blocking system call.
RLIMIT_RTTIME,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the number of signals that may be queued for the real
/// user ID of the calling process.
RLIMIT_SIGPENDING,
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) of socket buffer usage for this user.
RLIMIT_SBSIZE,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) of the swap space that may be reserved
/// or used by all of this user id's processes.
RLIMIT_SWAP,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// An alias for RLIMIT_AS.
RLIMIT_VMEM,
}
}
/// Get the current processes resource limits
///
/// A value of `None` indicates the value equals to `RLIM_INFINITY` which means
/// there is no limit.
///
/// # Parameters
///
/// * `resource`: The [`Resource`] that we want to get the limits of.
///
/// # Examples
///
/// ```
/// # use nix::sys::resource::{getrlimit, Resource};
///
/// let (soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap();
/// println!("current soft_limit: {:?}", soft_limit);
/// println!("current hard_limit: {:?}", hard_limit);
/// ```
///
/// # References
///
/// [getrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
///
/// [`Resource`]: enum.Resource.html
pub fn getrlimit(resource: Resource) -> Result<(Option<rlim_t>, Option<rlim_t>)> {
let mut old_rlim = mem::MaybeUninit::<rlimit>::uninit();
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
let res = unsafe { libc::getrlimit(resource as __rlimit_resource_t, old_rlim.as_mut_ptr()) };
} else {
let res = unsafe { libc::getrlimit(resource as c_int, old_rlim.as_mut_ptr()) };
}
}
Errno::result(res).map(|_| {
let rlimit { rlim_cur, rlim_max } = unsafe { old_rlim.assume_init() };
(Some(rlim_cur), Some(rlim_max))
})
}
/// Set the current processes resource limits
///
/// # Parameters
///
/// * `resource`: The [`Resource`] that we want to set the limits of.
/// * `soft_limit`: The value that the kernel enforces for the corresponding
/// resource. Note: `None` input will be replaced by constant `RLIM_INFINITY`.
/// * `hard_limit`: The ceiling for the soft limit. Must be lower or equal to
/// the current hard limit for non-root users. Note: `None` input will be
/// replaced by constant `RLIM_INFINITY`.
///
/// > Note: for some os (linux_gnu), setting hard_limit to `RLIM_INFINITY` can
/// > results `EPERM` Error. So you will need to set the number explicitly.
///
/// # Examples
///
/// ```
/// # use nix::sys::resource::{setrlimit, Resource};
///
/// let soft_limit = Some(512);
/// let hard_limit = Some(1024);
/// setrlimit(Resource::RLIMIT_NOFILE, soft_limit, hard_limit).unwrap();
/// ```
///
/// # References
///
/// [setrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
///
/// [`Resource`]: enum.Resource.html
///
/// Note: `setrlimit` provides a safe wrapper to libc's `setrlimit`.
pub fn setr
|
resource: Resource,
soft_limit: Option<rlim_t>,
hard_limit: Option<rlim_t>,
) -> Result<()> {
let new_rlim = rlimit {
rlim_cur: soft_limit.unwrap_or(RLIM_INFINITY),
rlim_max: hard_limit.unwrap_or(RLIM_INFINITY),
};
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
let res = unsafe { libc::setrlimit(resource as __rlimit_resource_t, &new_rlim as *const rlimit) };
}else{
let res = unsafe { libc::setrlimit(resource as c_int, &new_rlim as *const rlimit) };
}
}
Errno::result(res).map(drop)
}
|
limit(
|
identifier_name
|
resource.rs
|
//! Configure the process resource limits.
use cfg_if::cfg_if;
use crate::errno::Errno;
use crate::Result;
pub use libc::rlim_t;
use std::mem;
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
use libc::{__rlimit_resource_t, rlimit, RLIM_INFINITY};
} else if #[cfg(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "dragonfly",
all(target_os = "linux", not(target_env = "gnu"))
))]{
use libc::{c_int, rlimit, RLIM_INFINITY};
}
}
libc_enum! {
/// Types of process resources.
///
/// The Resource enum is platform dependent. Check different platform
/// manuals for more details. Some platform links have been provided for
/// easier reference (non-exhaustive).
///
/// * [Linux](https://man7.org/linux/man-pages/man2/getrlimit.2.html)
/// * [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=setrlimit)
/// * [NetBSD](https://man.netbsd.org/setrlimit.2)
// linux-gnu uses u_int as resource enum, which is implemented in libc as
// well.
//
// https://gcc.gnu.org/legacy-ml/gcc/2015-08/msg00441.html
// https://github.com/rust-lang/libc/blob/master/src/unix/linux_like/linux/gnu/mod.rs
#[cfg_attr(all(target_os = "linux", target_env = "gnu"), repr(u32))]
#[cfg_attr(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "dragonfly",
all(target_os = "linux", not(target_env = "gnu"))
), repr(i32))]
#[non_exhaustive]
pub enum Resource {
#[cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum amount (in bytes) of virtual memory the process is
/// allowed to map.
RLIMIT_AS,
/// The largest size (in bytes) core(5) file that may be created.
RLIMIT_CORE,
/// The maximum amount of cpu time (in seconds) to be used by each
/// process.
RLIMIT_CPU,
/// The maximum size (in bytes) of the data segment for a process
RLIMIT_DATA,
/// The largest size (in bytes) file that may be created.
RLIMIT_FSIZE,
/// The maximum number of open files for this process.
RLIMIT_NOFILE,
/// The maximum size (in bytes) of the stack segment for a process.
RLIMIT_STACK,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of kqueues this user id is allowed to create.
RLIMIT_KQUEUES,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the combined number of flock locks and fcntl leases that
/// this process may establish.
RLIMIT_LOCKS,
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "openbsd",
target_os = "linux",
target_os = "netbsd"
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) which a process may lock into memory
/// using the mlock(2) system call.
RLIMIT_MEMLOCK,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the number of bytes that can be allocated for POSIX
/// message queues for the real user ID of the calling process.
RLIMIT_MSGQUEUE,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A ceiling to which the process's nice value can be raised using
/// setpriority or nice.
RLIMIT_NICE,
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux",
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of simultaneous processes for this user id.
RLIMIT_NPROC,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum number of pseudo-terminals this user id is allowed to
/// create.
RLIMIT_NPTS,
#[cfg(any(target_os = "android",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux",
))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// When there is memory pressure and swap is available, prioritize
/// eviction of a process' resident pages beyond this amount (in bytes).
RLIMIT_RSS,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A ceiling on the real-time priority that may be set for this process
/// using sched_setscheduler and sched_set‐ param.
RLIMIT_RTPRIO,
#[cfg(any(target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit (in microseconds) on the amount of CPU time that a process
/// scheduled under a real-time scheduling policy may con‐ sume without
/// making a blocking system call.
RLIMIT_RTTIME,
#[cfg(any(target_os = "android", target_os = "linux"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// A limit on the number of signals that may be queued for the real
/// user ID of the calling process.
RLIMIT_SIGPENDING,
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) of socket buffer usage for this user.
RLIMIT_SBSIZE,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// The maximum size (in bytes) of the swap space that may be reserved
/// or used by all of this user id's processes.
RLIMIT_SWAP,
#[cfg(target_os = "freebsd")]
#[cfg_attr(docsrs, doc(cfg(all())))]
/// An alias for RLIMIT_AS.
RLIMIT_VMEM,
}
}
/// Get the current processes resource limits
///
/// A value of `None` indicates the value equals to `RLIM_INFINITY` which means
/// there is no limit.
///
/// # Parameters
///
/// * `resource`: The [`Resource`] that we want to get the limits of.
///
/// # Examples
///
/// ```
/// # use nix::sys::resource::{getrlimit, Resource};
///
/// let (soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap();
/// println!("current soft_limit: {:?}", soft_limit);
/// println!("current hard_limit: {:?}", hard_limit);
/// ```
///
/// # References
///
/// [getrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
///
/// [`Resource`]: enum.Resource.html
pub fn getrlimit(resource: Resource) -> Result<(Option<rlim_t>, Option<rlim_t>)> {
|
/ Set the current processes resource limits
///
/// # Parameters
///
/// * `resource`: The [`Resource`] that we want to set the limits of.
/// * `soft_limit`: The value that the kernel enforces for the corresponding
/// resource. Note: `None` input will be replaced by constant `RLIM_INFINITY`.
/// * `hard_limit`: The ceiling for the soft limit. Must be lower or equal to
/// the current hard limit for non-root users. Note: `None` input will be
/// replaced by constant `RLIM_INFINITY`.
///
/// > Note: for some os (linux_gnu), setting hard_limit to `RLIM_INFINITY` can
/// > results `EPERM` Error. So you will need to set the number explicitly.
///
/// # Examples
///
/// ```
/// # use nix::sys::resource::{setrlimit, Resource};
///
/// let soft_limit = Some(512);
/// let hard_limit = Some(1024);
/// setrlimit(Resource::RLIMIT_NOFILE, soft_limit, hard_limit).unwrap();
/// ```
///
/// # References
///
/// [setrlimit(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html#tag_16_215)
///
/// [`Resource`]: enum.Resource.html
///
/// Note: `setrlimit` provides a safe wrapper to libc's `setrlimit`.
pub fn setrlimit(
resource: Resource,
soft_limit: Option<rlim_t>,
hard_limit: Option<rlim_t>,
) -> Result<()> {
let new_rlim = rlimit {
rlim_cur: soft_limit.unwrap_or(RLIM_INFINITY),
rlim_max: hard_limit.unwrap_or(RLIM_INFINITY),
};
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
let res = unsafe { libc::setrlimit(resource as __rlimit_resource_t, &new_rlim as *const rlimit) };
}else{
let res = unsafe { libc::setrlimit(resource as c_int, &new_rlim as *const rlimit) };
}
}
Errno::result(res).map(drop)
}
|
let mut old_rlim = mem::MaybeUninit::<rlimit>::uninit();
cfg_if! {
if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{
let res = unsafe { libc::getrlimit(resource as __rlimit_resource_t, old_rlim.as_mut_ptr()) };
} else {
let res = unsafe { libc::getrlimit(resource as c_int, old_rlim.as_mut_ptr()) };
}
}
Errno::result(res).map(|_| {
let rlimit { rlim_cur, rlim_max } = unsafe { old_rlim.assume_init() };
(Some(rlim_cur), Some(rlim_max))
})
}
//
|
identifier_body
|
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::{BlockFlow, MarginsMayNotCollapse, WidthAndMarginsComputer};
use context::LayoutContext;
use flow::{TableCellFlowClass, FlowClass, Flow};
use fragment::Fragment;
use model::{MaybeAuto};
use table::InternalTable;
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCellFlow {
/// Data common to all flows.
pub block_flow: BlockFlow,
}
impl TableCellFlow {
pub fn from_node_and_fragment(node: &ThreadSafeLayoutNode, fragment: Fragment) -> TableCellFlow {
TableCellFlow {
block_flow: BlockFlow::from_node_and_fragment(node, fragment)
}
}
pub fn fragment<'a>(&'a mut self) -> &'a Fragment {
&self.block_flow.fragment
}
pub fn mut_fragment<'a>(&'a mut self) -> &'a mut Fragment {
&mut self.block_flow.fragment
}
/// Assign height for table-cell flow.
///
/// TODO(#2015, pcwalton): This doesn't handle floats right.
///
/// inline(always) because this is only ever called by in-order or non-in-order top-level
/// methods
#[inline(always)]
fn assign_height_table_cell_base(&mut self, layout_context: &mut LayoutContext) {
self.block_flow.assign_height_block_base(layout_context, MarginsMayNotCollapse)
}
pub fn build_display_list_table_cell(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table: same process as block flow");
self.block_flow.build_display_list_block(layout_context)
}
}
impl Flow for TableCellFlow {
fn class(&self) -> FlowClass {
TableCellFlowClass
}
fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow
|
/// Minimum/preferred widths set by this function are used in automatic table layout calculation.
fn bubble_widths(&mut self, ctx: &mut LayoutContext) {
self.block_flow.bubble_widths(ctx);
let specified_width = MaybeAuto::from_style(self.block_flow.fragment.style().get_box().width,
Au::new(0)).specified_or_zero();
if self.block_flow.base.intrinsic_widths.minimum_width < specified_width {
self.block_flow.base.intrinsic_widths.minimum_width = specified_width;
}
if self.block_flow.base.intrinsic_widths.preferred_width <
self.block_flow.base.intrinsic_widths.minimum_width {
self.block_flow.base.intrinsic_widths.preferred_width =
self.block_flow.base.intrinsic_widths.minimum_width;
}
}
/// Recursively (top-down) determines the actual width of child contexts and fragments. When
/// called on this context, the context has had its width set by the parent table row.
fn assign_widths(&mut self, ctx: &mut LayoutContext) {
debug!("assign_widths({}): assigning width for flow", "table_cell");
// The position was set to the column width by the parent flow, table row flow.
let containing_block_width = self.block_flow.base.position.size.width;
let width_computer = InternalTable;
width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width);
let left_content_edge = self.block_flow.fragment.border_box.origin.x +
self.block_flow.fragment.border_padding.left;
let padding_and_borders = self.block_flow.fragment.border_padding.horizontal();
let content_width = self.block_flow.fragment.border_box.size.width - padding_and_borders;
self.block_flow.propagate_assigned_width_to_children(left_content_edge,
content_width,
None);
}
fn assign_height(&mut self, ctx: &mut LayoutContext) {
debug!("assign_height: assigning height for table_cell");
self.assign_height_table_cell_base(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
}
impl fmt::Show for TableCellFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCellFlow: {}", self.block_flow)
}
}
|
{
&mut self.block_flow
}
|
identifier_body
|
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::{BlockFlow, MarginsMayNotCollapse, WidthAndMarginsComputer};
use context::LayoutContext;
use flow::{TableCellFlowClass, FlowClass, Flow};
use fragment::Fragment;
use model::{MaybeAuto};
use table::InternalTable;
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCellFlow {
/// Data common to all flows.
pub block_flow: BlockFlow,
}
impl TableCellFlow {
pub fn from_node_and_fragment(node: &ThreadSafeLayoutNode, fragment: Fragment) -> TableCellFlow {
TableCellFlow {
block_flow: BlockFlow::from_node_and_fragment(node, fragment)
}
}
pub fn
|
<'a>(&'a mut self) -> &'a Fragment {
&self.block_flow.fragment
}
pub fn mut_fragment<'a>(&'a mut self) -> &'a mut Fragment {
&mut self.block_flow.fragment
}
/// Assign height for table-cell flow.
///
/// TODO(#2015, pcwalton): This doesn't handle floats right.
///
/// inline(always) because this is only ever called by in-order or non-in-order top-level
/// methods
#[inline(always)]
fn assign_height_table_cell_base(&mut self, layout_context: &mut LayoutContext) {
self.block_flow.assign_height_block_base(layout_context, MarginsMayNotCollapse)
}
pub fn build_display_list_table_cell(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table: same process as block flow");
self.block_flow.build_display_list_block(layout_context)
}
}
impl Flow for TableCellFlow {
fn class(&self) -> FlowClass {
TableCellFlowClass
}
fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
/// Minimum/preferred widths set by this function are used in automatic table layout calculation.
fn bubble_widths(&mut self, ctx: &mut LayoutContext) {
self.block_flow.bubble_widths(ctx);
let specified_width = MaybeAuto::from_style(self.block_flow.fragment.style().get_box().width,
Au::new(0)).specified_or_zero();
if self.block_flow.base.intrinsic_widths.minimum_width < specified_width {
self.block_flow.base.intrinsic_widths.minimum_width = specified_width;
}
if self.block_flow.base.intrinsic_widths.preferred_width <
self.block_flow.base.intrinsic_widths.minimum_width {
self.block_flow.base.intrinsic_widths.preferred_width =
self.block_flow.base.intrinsic_widths.minimum_width;
}
}
/// Recursively (top-down) determines the actual width of child contexts and fragments. When
/// called on this context, the context has had its width set by the parent table row.
fn assign_widths(&mut self, ctx: &mut LayoutContext) {
debug!("assign_widths({}): assigning width for flow", "table_cell");
// The position was set to the column width by the parent flow, table row flow.
let containing_block_width = self.block_flow.base.position.size.width;
let width_computer = InternalTable;
width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width);
let left_content_edge = self.block_flow.fragment.border_box.origin.x +
self.block_flow.fragment.border_padding.left;
let padding_and_borders = self.block_flow.fragment.border_padding.horizontal();
let content_width = self.block_flow.fragment.border_box.size.width - padding_and_borders;
self.block_flow.propagate_assigned_width_to_children(left_content_edge,
content_width,
None);
}
fn assign_height(&mut self, ctx: &mut LayoutContext) {
debug!("assign_height: assigning height for table_cell");
self.assign_height_table_cell_base(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
}
impl fmt::Show for TableCellFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCellFlow: {}", self.block_flow)
}
}
|
fragment
|
identifier_name
|
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::{BlockFlow, MarginsMayNotCollapse, WidthAndMarginsComputer};
use context::LayoutContext;
use flow::{TableCellFlowClass, FlowClass, Flow};
use fragment::Fragment;
use model::{MaybeAuto};
use table::InternalTable;
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCellFlow {
/// Data common to all flows.
pub block_flow: BlockFlow,
}
impl TableCellFlow {
pub fn from_node_and_fragment(node: &ThreadSafeLayoutNode, fragment: Fragment) -> TableCellFlow {
TableCellFlow {
block_flow: BlockFlow::from_node_and_fragment(node, fragment)
}
}
pub fn fragment<'a>(&'a mut self) -> &'a Fragment {
&self.block_flow.fragment
}
pub fn mut_fragment<'a>(&'a mut self) -> &'a mut Fragment {
&mut self.block_flow.fragment
}
/// Assign height for table-cell flow.
///
/// TODO(#2015, pcwalton): This doesn't handle floats right.
///
/// inline(always) because this is only ever called by in-order or non-in-order top-level
/// methods
#[inline(always)]
fn assign_height_table_cell_base(&mut self, layout_context: &mut LayoutContext) {
self.block_flow.assign_height_block_base(layout_context, MarginsMayNotCollapse)
}
pub fn build_display_list_table_cell(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table: same process as block flow");
self.block_flow.build_display_list_block(layout_context)
}
}
impl Flow for TableCellFlow {
fn class(&self) -> FlowClass {
TableCellFlowClass
}
fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
/// Minimum/preferred widths set by this function are used in automatic table layout calculation.
fn bubble_widths(&mut self, ctx: &mut LayoutContext) {
self.block_flow.bubble_widths(ctx);
let specified_width = MaybeAuto::from_style(self.block_flow.fragment.style().get_box().width,
Au::new(0)).specified_or_zero();
if self.block_flow.base.intrinsic_widths.minimum_width < specified_width {
self.block_flow.base.intrinsic_widths.minimum_width = specified_width;
}
if self.block_flow.base.intrinsic_widths.preferred_width <
self.block_flow.base.intrinsic_widths.minimum_width
|
}
/// Recursively (top-down) determines the actual width of child contexts and fragments. When
/// called on this context, the context has had its width set by the parent table row.
fn assign_widths(&mut self, ctx: &mut LayoutContext) {
debug!("assign_widths({}): assigning width for flow", "table_cell");
// The position was set to the column width by the parent flow, table row flow.
let containing_block_width = self.block_flow.base.position.size.width;
let width_computer = InternalTable;
width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width);
let left_content_edge = self.block_flow.fragment.border_box.origin.x +
self.block_flow.fragment.border_padding.left;
let padding_and_borders = self.block_flow.fragment.border_padding.horizontal();
let content_width = self.block_flow.fragment.border_box.size.width - padding_and_borders;
self.block_flow.propagate_assigned_width_to_children(left_content_edge,
content_width,
None);
}
fn assign_height(&mut self, ctx: &mut LayoutContext) {
debug!("assign_height: assigning height for table_cell");
self.assign_height_table_cell_base(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
}
impl fmt::Show for TableCellFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCellFlow: {}", self.block_flow)
}
}
|
{
self.block_flow.base.intrinsic_widths.preferred_width =
self.block_flow.base.intrinsic_widths.minimum_width;
}
|
conditional_block
|
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::{BlockFlow, MarginsMayNotCollapse, WidthAndMarginsComputer};
use context::LayoutContext;
use flow::{TableCellFlowClass, FlowClass, Flow};
use fragment::Fragment;
use model::{MaybeAuto};
use table::InternalTable;
use wrapper::ThreadSafeLayoutNode;
use servo_util::geometry::Au;
use std::fmt;
/// A table formatting context.
pub struct TableCellFlow {
/// Data common to all flows.
pub block_flow: BlockFlow,
}
impl TableCellFlow {
pub fn from_node_and_fragment(node: &ThreadSafeLayoutNode, fragment: Fragment) -> TableCellFlow {
TableCellFlow {
block_flow: BlockFlow::from_node_and_fragment(node, fragment)
}
}
pub fn fragment<'a>(&'a mut self) -> &'a Fragment {
&self.block_flow.fragment
}
pub fn mut_fragment<'a>(&'a mut self) -> &'a mut Fragment {
&mut self.block_flow.fragment
}
/// Assign height for table-cell flow.
///
/// TODO(#2015, pcwalton): This doesn't handle floats right.
///
/// inline(always) because this is only ever called by in-order or non-in-order top-level
/// methods
#[inline(always)]
fn assign_height_table_cell_base(&mut self, layout_context: &mut LayoutContext) {
self.block_flow.assign_height_block_base(layout_context, MarginsMayNotCollapse)
}
pub fn build_display_list_table_cell(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table: same process as block flow");
self.block_flow.build_display_list_block(layout_context)
}
}
impl Flow for TableCellFlow {
fn class(&self) -> FlowClass {
TableCellFlowClass
}
fn as_table_cell<'a>(&'a mut self) -> &'a mut TableCellFlow {
self
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
&mut self.block_flow
}
/// Minimum/preferred widths set by this function are used in automatic table layout calculation.
fn bubble_widths(&mut self, ctx: &mut LayoutContext) {
self.block_flow.bubble_widths(ctx);
let specified_width = MaybeAuto::from_style(self.block_flow.fragment.style().get_box().width,
Au::new(0)).specified_or_zero();
if self.block_flow.base.intrinsic_widths.minimum_width < specified_width {
self.block_flow.base.intrinsic_widths.minimum_width = specified_width;
}
if self.block_flow.base.intrinsic_widths.preferred_width <
self.block_flow.base.intrinsic_widths.minimum_width {
self.block_flow.base.intrinsic_widths.preferred_width =
self.block_flow.base.intrinsic_widths.minimum_width;
}
}
/// Recursively (top-down) determines the actual width of child contexts and fragments. When
/// called on this context, the context has had its width set by the parent table row.
fn assign_widths(&mut self, ctx: &mut LayoutContext) {
debug!("assign_widths({}): assigning width for flow", "table_cell");
// The position was set to the column width by the parent flow, table row flow.
let containing_block_width = self.block_flow.base.position.size.width;
let width_computer = InternalTable;
width_computer.compute_used_width(&mut self.block_flow, ctx, containing_block_width);
let left_content_edge = self.block_flow.fragment.border_box.origin.x +
self.block_flow.fragment.border_padding.left;
let padding_and_borders = self.block_flow.fragment.border_padding.horizontal();
let content_width = self.block_flow.fragment.border_box.size.width - padding_and_borders;
self.block_flow.propagate_assigned_width_to_children(left_content_edge,
content_width,
None);
}
fn assign_height(&mut self, ctx: &mut LayoutContext) {
debug!("assign_height: assigning height for table_cell");
self.assign_height_table_cell_base(ctx);
}
fn compute_absolute_position(&mut self) {
self.block_flow.compute_absolute_position()
}
}
impl fmt::Show for TableCellFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCellFlow: {}", self.block_flow)
|
}
|
}
|
random_line_split
|
lib.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]
#![allow(clippy::large_enum_variant)]
mod char_constants;
mod lexer;
mod lexer_position;
mod parser;
mod source;
mod syntax_error;
mod syntax_node;
mod token_kind;
pub use source::GraphQLSource;
pub use syntax_error::{SyntaxError, SyntaxErrorKind, SyntaxErrorWithSource};
pub use syntax_node::*;
use crate::parser::Parser;
use common::FileKey;
pub fn parse(source: &str, file: FileKey) -> SyntaxResult<Document> {
let parser = Parser::new(source, file);
parser.parse_document()
}
pub fn
|
(source: &str, file: FileKey) -> SyntaxResult<TypeAnnotation> {
let parser = Parser::new(source, file);
parser.parse_type()
}
|
parse_type
|
identifier_name
|
lib.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]
#![allow(clippy::large_enum_variant)]
mod char_constants;
mod lexer;
mod lexer_position;
|
mod token_kind;
pub use source::GraphQLSource;
pub use syntax_error::{SyntaxError, SyntaxErrorKind, SyntaxErrorWithSource};
pub use syntax_node::*;
use crate::parser::Parser;
use common::FileKey;
pub fn parse(source: &str, file: FileKey) -> SyntaxResult<Document> {
let parser = Parser::new(source, file);
parser.parse_document()
}
pub fn parse_type(source: &str, file: FileKey) -> SyntaxResult<TypeAnnotation> {
let parser = Parser::new(source, file);
parser.parse_type()
}
|
mod parser;
mod source;
mod syntax_error;
mod syntax_node;
|
random_line_split
|
lib.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]
#![allow(clippy::large_enum_variant)]
mod char_constants;
mod lexer;
mod lexer_position;
mod parser;
mod source;
mod syntax_error;
mod syntax_node;
mod token_kind;
pub use source::GraphQLSource;
pub use syntax_error::{SyntaxError, SyntaxErrorKind, SyntaxErrorWithSource};
pub use syntax_node::*;
use crate::parser::Parser;
use common::FileKey;
pub fn parse(source: &str, file: FileKey) -> SyntaxResult<Document>
|
pub fn parse_type(source: &str, file: FileKey) -> SyntaxResult<TypeAnnotation> {
let parser = Parser::new(source, file);
parser.parse_type()
}
|
{
let parser = Parser::new(source, file);
parser.parse_document()
}
|
identifier_body
|
color_matrix.rs
|
use cssparser::Parser;
use markup5ever::{expanded_name, local_name, namespace_url, ns};
use nalgebra::{Matrix3, Matrix4x5, Matrix5, Vector5};
use crate::document::AcquiredNodes;
use crate::drawing_ctx::DrawingCtx;
use crate::element::{ElementResult, SetAttributes};
use crate::error::*;
use crate::node::{CascadedValues, Node};
use crate::parsers::{NumberList, Parse, ParseValue};
use crate::properties::ColorInterpolationFilters;
use crate::rect::IRect;
use crate::surface_utils::{
iterators::Pixels, shared_surface::ExclusiveImageSurface, ImageSurfaceDataExt, Pixel,
};
use crate::util::clamp;
use crate::xml::Attributes;
use super::bounds::BoundsBuilder;
use super::context::{FilterContext, FilterOutput};
use super::{
FilterEffect, FilterError, FilterResolveError, Input, Primitive, PrimitiveParams,
ResolvedPrimitive,
};
/// Color matrix operation types.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum OperationType {
Matrix,
Saturate,
HueRotate,
LuminanceToAlpha,
}
enum_default!(OperationType, OperationType::Matrix);
/// The `feColorMatrix` filter primitive.
#[derive(Default)]
pub struct FeColorMatrix {
base: Primitive,
params: ColorMatrix,
}
/// Resolved `feColorMatrix` primitive for rendering.
#[derive(Clone)]
pub struct ColorMatrix {
pub in1: Input,
pub matrix: Matrix5<f64>,
pub color_interpolation_filters: ColorInterpolationFilters,
}
impl Default for ColorMatrix {
fn default() -> ColorMatrix {
ColorMatrix {
in1: Default::default(),
color_interpolation_filters: Default::default(),
// nalgebra's Default for Matrix5 is all zeroes, so we actually need this :(
matrix: Matrix5::identity(),
}
}
}
#[rustfmt::skip]
impl SetAttributes for FeColorMatrix {
fn set_attributes(&mut self, attrs: &Attributes) -> ElementResult {
self.params.in1 = self.base.parse_one_input(attrs)?;
// First, determine the operation type.
let mut operation_type = Default::default();
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "type"))
{
operation_type = attr.parse(value)?;
}
// Now read the matrix correspondingly.
// LuminanceToAlpha doesn't accept any matrix.
if operation_type == OperationType::LuminanceToAlpha {
self.params.matrix = {
Matrix5::new(
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.2125, 0.7154, 0.0721, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
};
} else {
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "values"))
{
let new_matrix = match operation_type {
OperationType::LuminanceToAlpha => unreachable!(),
OperationType::Matrix => {
let NumberList::<20, 20>(v) = attr.parse(value)?;
let matrix = Matrix4x5::from_row_slice(&v);
let mut matrix = matrix.fixed_resize(0.0);
matrix[(4, 4)] = 1.0;
matrix
}
OperationType::Saturate => {
let s: f64 = attr.parse(value)?;
Matrix5::new(
0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
}
OperationType::HueRotate =>
|
};
self.params.matrix = new_matrix;
}
}
Ok(())
}
}
impl ColorMatrix {
pub fn render(
&self,
bounds_builder: BoundsBuilder,
ctx: &FilterContext,
acquired_nodes: &mut AcquiredNodes<'_>,
draw_ctx: &mut DrawingCtx,
) -> Result<FilterOutput, FilterError> {
let input_1 = ctx.get_input(
acquired_nodes,
draw_ctx,
&self.in1,
self.color_interpolation_filters,
)?;
let bounds: IRect = bounds_builder
.add_input(&input_1)
.compute(ctx)
.clipped
.into();
let mut surface = ExclusiveImageSurface::new(
ctx.source_graphic().width(),
ctx.source_graphic().height(),
input_1.surface().surface_type(),
)?;
surface.modify(&mut |data, stride| {
for (x, y, pixel) in Pixels::within(input_1.surface(), bounds) {
let alpha = f64::from(pixel.a) / 255f64;
let pixel_vec = if alpha == 0.0 {
Vector5::new(0.0, 0.0, 0.0, 0.0, 1.0)
} else {
Vector5::new(
f64::from(pixel.r) / 255f64 / alpha,
f64::from(pixel.g) / 255f64 / alpha,
f64::from(pixel.b) / 255f64 / alpha,
alpha,
1.0,
)
};
let mut new_pixel_vec = Vector5::zeros();
self.matrix.mul_to(&pixel_vec, &mut new_pixel_vec);
let new_alpha = clamp(new_pixel_vec[3], 0.0, 1.0);
let premultiply = |x: f64| ((clamp(x, 0.0, 1.0) * new_alpha * 255f64) + 0.5) as u8;
let output_pixel = Pixel {
r: premultiply(new_pixel_vec[0]),
g: premultiply(new_pixel_vec[1]),
b: premultiply(new_pixel_vec[2]),
a: ((new_alpha * 255f64) + 0.5) as u8,
};
data.set_pixel(stride, output_pixel, x, y);
}
});
Ok(FilterOutput {
surface: surface.share()?,
bounds,
})
}
pub fn hue_rotate_matrix(radians: f64) -> Matrix5<f64> {
let (sin, cos) = radians.sin_cos();
let a = Matrix3::new(
0.213, 0.715, 0.072, 0.213, 0.715, 0.072, 0.213, 0.715, 0.072,
);
let b = Matrix3::new(
0.787, -0.715, -0.072, -0.213, 0.285, -0.072, -0.213, -0.715, 0.928,
);
let c = Matrix3::new(
-0.213, -0.715, 0.928, 0.143, 0.140, -0.283, -0.787, 0.715, 0.072,
);
let top_left = a + b * cos + c * sin;
let mut matrix = top_left.fixed_resize(0.0);
matrix[(3, 3)] = 1.0;
matrix[(4, 4)] = 1.0;
matrix
}
}
impl FilterEffect for FeColorMatrix {
fn resolve(
&self,
_acquired_nodes: &mut AcquiredNodes<'_>,
node: &Node,
) -> Result<ResolvedPrimitive, FilterResolveError> {
let cascaded = CascadedValues::new_from_node(node);
let values = cascaded.get();
let mut params = self.params.clone();
params.color_interpolation_filters = values.color_interpolation_filters();
Ok(ResolvedPrimitive {
primitive: self.base.clone(),
params: PrimitiveParams::ColorMatrix(params),
})
}
}
impl Parse for OperationType {
fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> {
Ok(parse_identifiers!(
parser,
"matrix" => OperationType::Matrix,
"saturate" => OperationType::Saturate,
"hueRotate" => OperationType::HueRotate,
"luminanceToAlpha" => OperationType::LuminanceToAlpha,
)?)
}
}
|
{
let degrees: f64 = attr.parse(value)?;
ColorMatrix::hue_rotate_matrix(degrees.to_radians())
}
|
conditional_block
|
color_matrix.rs
|
use cssparser::Parser;
use markup5ever::{expanded_name, local_name, namespace_url, ns};
use nalgebra::{Matrix3, Matrix4x5, Matrix5, Vector5};
use crate::document::AcquiredNodes;
use crate::drawing_ctx::DrawingCtx;
use crate::element::{ElementResult, SetAttributes};
use crate::error::*;
use crate::node::{CascadedValues, Node};
use crate::parsers::{NumberList, Parse, ParseValue};
use crate::properties::ColorInterpolationFilters;
use crate::rect::IRect;
use crate::surface_utils::{
iterators::Pixels, shared_surface::ExclusiveImageSurface, ImageSurfaceDataExt, Pixel,
};
use crate::util::clamp;
use crate::xml::Attributes;
use super::bounds::BoundsBuilder;
use super::context::{FilterContext, FilterOutput};
use super::{
FilterEffect, FilterError, FilterResolveError, Input, Primitive, PrimitiveParams,
ResolvedPrimitive,
};
/// Color matrix operation types.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum OperationType {
Matrix,
Saturate,
HueRotate,
LuminanceToAlpha,
}
enum_default!(OperationType, OperationType::Matrix);
/// The `feColorMatrix` filter primitive.
#[derive(Default)]
pub struct FeColorMatrix {
base: Primitive,
params: ColorMatrix,
}
/// Resolved `feColorMatrix` primitive for rendering.
#[derive(Clone)]
pub struct ColorMatrix {
pub in1: Input,
pub matrix: Matrix5<f64>,
pub color_interpolation_filters: ColorInterpolationFilters,
}
impl Default for ColorMatrix {
fn default() -> ColorMatrix {
ColorMatrix {
in1: Default::default(),
color_interpolation_filters: Default::default(),
// nalgebra's Default for Matrix5 is all zeroes, so we actually need this :(
matrix: Matrix5::identity(),
}
}
}
#[rustfmt::skip]
impl SetAttributes for FeColorMatrix {
fn set_attributes(&mut self, attrs: &Attributes) -> ElementResult {
self.params.in1 = self.base.parse_one_input(attrs)?;
// First, determine the operation type.
let mut operation_type = Default::default();
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "type"))
{
operation_type = attr.parse(value)?;
}
// Now read the matrix correspondingly.
// LuminanceToAlpha doesn't accept any matrix.
if operation_type == OperationType::LuminanceToAlpha {
self.params.matrix = {
Matrix5::new(
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.2125, 0.7154, 0.0721, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
};
} else {
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "values"))
{
let new_matrix = match operation_type {
OperationType::LuminanceToAlpha => unreachable!(),
OperationType::Matrix => {
let NumberList::<20, 20>(v) = attr.parse(value)?;
let matrix = Matrix4x5::from_row_slice(&v);
let mut matrix = matrix.fixed_resize(0.0);
matrix[(4, 4)] = 1.0;
matrix
}
OperationType::Saturate => {
let s: f64 = attr.parse(value)?;
Matrix5::new(
0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
}
OperationType::HueRotate => {
let degrees: f64 = attr.parse(value)?;
ColorMatrix::hue_rotate_matrix(degrees.to_radians())
}
};
self.params.matrix = new_matrix;
}
}
Ok(())
}
}
impl ColorMatrix {
pub fn render(
&self,
bounds_builder: BoundsBuilder,
ctx: &FilterContext,
acquired_nodes: &mut AcquiredNodes<'_>,
draw_ctx: &mut DrawingCtx,
) -> Result<FilterOutput, FilterError> {
let input_1 = ctx.get_input(
acquired_nodes,
draw_ctx,
&self.in1,
self.color_interpolation_filters,
)?;
let bounds: IRect = bounds_builder
.add_input(&input_1)
.compute(ctx)
.clipped
.into();
let mut surface = ExclusiveImageSurface::new(
ctx.source_graphic().width(),
ctx.source_graphic().height(),
input_1.surface().surface_type(),
)?;
surface.modify(&mut |data, stride| {
for (x, y, pixel) in Pixels::within(input_1.surface(), bounds) {
let alpha = f64::from(pixel.a) / 255f64;
let pixel_vec = if alpha == 0.0 {
Vector5::new(0.0, 0.0, 0.0, 0.0, 1.0)
} else {
Vector5::new(
f64::from(pixel.r) / 255f64 / alpha,
f64::from(pixel.g) / 255f64 / alpha,
f64::from(pixel.b) / 255f64 / alpha,
alpha,
1.0,
)
};
let mut new_pixel_vec = Vector5::zeros();
self.matrix.mul_to(&pixel_vec, &mut new_pixel_vec);
let new_alpha = clamp(new_pixel_vec[3], 0.0, 1.0);
let premultiply = |x: f64| ((clamp(x, 0.0, 1.0) * new_alpha * 255f64) + 0.5) as u8;
let output_pixel = Pixel {
r: premultiply(new_pixel_vec[0]),
g: premultiply(new_pixel_vec[1]),
b: premultiply(new_pixel_vec[2]),
a: ((new_alpha * 255f64) + 0.5) as u8,
};
data.set_pixel(stride, output_pixel, x, y);
}
});
Ok(FilterOutput {
surface: surface.share()?,
bounds,
})
}
pub fn hue_rotate_matrix(radians: f64) -> Matrix5<f64> {
let (sin, cos) = radians.sin_cos();
let a = Matrix3::new(
0.213, 0.715, 0.072, 0.213, 0.715, 0.072, 0.213, 0.715, 0.072,
);
let b = Matrix3::new(
0.787, -0.715, -0.072, -0.213, 0.285, -0.072, -0.213, -0.715, 0.928,
);
let c = Matrix3::new(
-0.213, -0.715, 0.928, 0.143, 0.140, -0.283, -0.787, 0.715, 0.072,
);
let top_left = a + b * cos + c * sin;
let mut matrix = top_left.fixed_resize(0.0);
matrix[(3, 3)] = 1.0;
matrix[(4, 4)] = 1.0;
matrix
}
}
impl FilterEffect for FeColorMatrix {
fn resolve(
&self,
_acquired_nodes: &mut AcquiredNodes<'_>,
node: &Node,
) -> Result<ResolvedPrimitive, FilterResolveError> {
let cascaded = CascadedValues::new_from_node(node);
let values = cascaded.get();
let mut params = self.params.clone();
params.color_interpolation_filters = values.color_interpolation_filters();
Ok(ResolvedPrimitive {
primitive: self.base.clone(),
params: PrimitiveParams::ColorMatrix(params),
})
}
}
impl Parse for OperationType {
fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> {
Ok(parse_identifiers!(
|
"matrix" => OperationType::Matrix,
"saturate" => OperationType::Saturate,
"hueRotate" => OperationType::HueRotate,
"luminanceToAlpha" => OperationType::LuminanceToAlpha,
)?)
}
}
|
parser,
|
random_line_split
|
color_matrix.rs
|
use cssparser::Parser;
use markup5ever::{expanded_name, local_name, namespace_url, ns};
use nalgebra::{Matrix3, Matrix4x5, Matrix5, Vector5};
use crate::document::AcquiredNodes;
use crate::drawing_ctx::DrawingCtx;
use crate::element::{ElementResult, SetAttributes};
use crate::error::*;
use crate::node::{CascadedValues, Node};
use crate::parsers::{NumberList, Parse, ParseValue};
use crate::properties::ColorInterpolationFilters;
use crate::rect::IRect;
use crate::surface_utils::{
iterators::Pixels, shared_surface::ExclusiveImageSurface, ImageSurfaceDataExt, Pixel,
};
use crate::util::clamp;
use crate::xml::Attributes;
use super::bounds::BoundsBuilder;
use super::context::{FilterContext, FilterOutput};
use super::{
FilterEffect, FilterError, FilterResolveError, Input, Primitive, PrimitiveParams,
ResolvedPrimitive,
};
/// Color matrix operation types.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum OperationType {
Matrix,
Saturate,
HueRotate,
LuminanceToAlpha,
}
enum_default!(OperationType, OperationType::Matrix);
/// The `feColorMatrix` filter primitive.
#[derive(Default)]
pub struct FeColorMatrix {
base: Primitive,
params: ColorMatrix,
}
/// Resolved `feColorMatrix` primitive for rendering.
#[derive(Clone)]
pub struct ColorMatrix {
pub in1: Input,
pub matrix: Matrix5<f64>,
pub color_interpolation_filters: ColorInterpolationFilters,
}
impl Default for ColorMatrix {
fn default() -> ColorMatrix {
ColorMatrix {
in1: Default::default(),
color_interpolation_filters: Default::default(),
// nalgebra's Default for Matrix5 is all zeroes, so we actually need this :(
matrix: Matrix5::identity(),
}
}
}
#[rustfmt::skip]
impl SetAttributes for FeColorMatrix {
fn
|
(&mut self, attrs: &Attributes) -> ElementResult {
self.params.in1 = self.base.parse_one_input(attrs)?;
// First, determine the operation type.
let mut operation_type = Default::default();
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "type"))
{
operation_type = attr.parse(value)?;
}
// Now read the matrix correspondingly.
// LuminanceToAlpha doesn't accept any matrix.
if operation_type == OperationType::LuminanceToAlpha {
self.params.matrix = {
Matrix5::new(
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.2125, 0.7154, 0.0721, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
};
} else {
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "values"))
{
let new_matrix = match operation_type {
OperationType::LuminanceToAlpha => unreachable!(),
OperationType::Matrix => {
let NumberList::<20, 20>(v) = attr.parse(value)?;
let matrix = Matrix4x5::from_row_slice(&v);
let mut matrix = matrix.fixed_resize(0.0);
matrix[(4, 4)] = 1.0;
matrix
}
OperationType::Saturate => {
let s: f64 = attr.parse(value)?;
Matrix5::new(
0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
}
OperationType::HueRotate => {
let degrees: f64 = attr.parse(value)?;
ColorMatrix::hue_rotate_matrix(degrees.to_radians())
}
};
self.params.matrix = new_matrix;
}
}
Ok(())
}
}
impl ColorMatrix {
pub fn render(
&self,
bounds_builder: BoundsBuilder,
ctx: &FilterContext,
acquired_nodes: &mut AcquiredNodes<'_>,
draw_ctx: &mut DrawingCtx,
) -> Result<FilterOutput, FilterError> {
let input_1 = ctx.get_input(
acquired_nodes,
draw_ctx,
&self.in1,
self.color_interpolation_filters,
)?;
let bounds: IRect = bounds_builder
.add_input(&input_1)
.compute(ctx)
.clipped
.into();
let mut surface = ExclusiveImageSurface::new(
ctx.source_graphic().width(),
ctx.source_graphic().height(),
input_1.surface().surface_type(),
)?;
surface.modify(&mut |data, stride| {
for (x, y, pixel) in Pixels::within(input_1.surface(), bounds) {
let alpha = f64::from(pixel.a) / 255f64;
let pixel_vec = if alpha == 0.0 {
Vector5::new(0.0, 0.0, 0.0, 0.0, 1.0)
} else {
Vector5::new(
f64::from(pixel.r) / 255f64 / alpha,
f64::from(pixel.g) / 255f64 / alpha,
f64::from(pixel.b) / 255f64 / alpha,
alpha,
1.0,
)
};
let mut new_pixel_vec = Vector5::zeros();
self.matrix.mul_to(&pixel_vec, &mut new_pixel_vec);
let new_alpha = clamp(new_pixel_vec[3], 0.0, 1.0);
let premultiply = |x: f64| ((clamp(x, 0.0, 1.0) * new_alpha * 255f64) + 0.5) as u8;
let output_pixel = Pixel {
r: premultiply(new_pixel_vec[0]),
g: premultiply(new_pixel_vec[1]),
b: premultiply(new_pixel_vec[2]),
a: ((new_alpha * 255f64) + 0.5) as u8,
};
data.set_pixel(stride, output_pixel, x, y);
}
});
Ok(FilterOutput {
surface: surface.share()?,
bounds,
})
}
pub fn hue_rotate_matrix(radians: f64) -> Matrix5<f64> {
let (sin, cos) = radians.sin_cos();
let a = Matrix3::new(
0.213, 0.715, 0.072, 0.213, 0.715, 0.072, 0.213, 0.715, 0.072,
);
let b = Matrix3::new(
0.787, -0.715, -0.072, -0.213, 0.285, -0.072, -0.213, -0.715, 0.928,
);
let c = Matrix3::new(
-0.213, -0.715, 0.928, 0.143, 0.140, -0.283, -0.787, 0.715, 0.072,
);
let top_left = a + b * cos + c * sin;
let mut matrix = top_left.fixed_resize(0.0);
matrix[(3, 3)] = 1.0;
matrix[(4, 4)] = 1.0;
matrix
}
}
impl FilterEffect for FeColorMatrix {
fn resolve(
&self,
_acquired_nodes: &mut AcquiredNodes<'_>,
node: &Node,
) -> Result<ResolvedPrimitive, FilterResolveError> {
let cascaded = CascadedValues::new_from_node(node);
let values = cascaded.get();
let mut params = self.params.clone();
params.color_interpolation_filters = values.color_interpolation_filters();
Ok(ResolvedPrimitive {
primitive: self.base.clone(),
params: PrimitiveParams::ColorMatrix(params),
})
}
}
impl Parse for OperationType {
fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> {
Ok(parse_identifiers!(
parser,
"matrix" => OperationType::Matrix,
"saturate" => OperationType::Saturate,
"hueRotate" => OperationType::HueRotate,
"luminanceToAlpha" => OperationType::LuminanceToAlpha,
)?)
}
}
|
set_attributes
|
identifier_name
|
color_matrix.rs
|
use cssparser::Parser;
use markup5ever::{expanded_name, local_name, namespace_url, ns};
use nalgebra::{Matrix3, Matrix4x5, Matrix5, Vector5};
use crate::document::AcquiredNodes;
use crate::drawing_ctx::DrawingCtx;
use crate::element::{ElementResult, SetAttributes};
use crate::error::*;
use crate::node::{CascadedValues, Node};
use crate::parsers::{NumberList, Parse, ParseValue};
use crate::properties::ColorInterpolationFilters;
use crate::rect::IRect;
use crate::surface_utils::{
iterators::Pixels, shared_surface::ExclusiveImageSurface, ImageSurfaceDataExt, Pixel,
};
use crate::util::clamp;
use crate::xml::Attributes;
use super::bounds::BoundsBuilder;
use super::context::{FilterContext, FilterOutput};
use super::{
FilterEffect, FilterError, FilterResolveError, Input, Primitive, PrimitiveParams,
ResolvedPrimitive,
};
/// Color matrix operation types.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum OperationType {
Matrix,
Saturate,
HueRotate,
LuminanceToAlpha,
}
enum_default!(OperationType, OperationType::Matrix);
/// The `feColorMatrix` filter primitive.
#[derive(Default)]
pub struct FeColorMatrix {
base: Primitive,
params: ColorMatrix,
}
/// Resolved `feColorMatrix` primitive for rendering.
#[derive(Clone)]
pub struct ColorMatrix {
pub in1: Input,
pub matrix: Matrix5<f64>,
pub color_interpolation_filters: ColorInterpolationFilters,
}
impl Default for ColorMatrix {
fn default() -> ColorMatrix
|
}
#[rustfmt::skip]
impl SetAttributes for FeColorMatrix {
fn set_attributes(&mut self, attrs: &Attributes) -> ElementResult {
self.params.in1 = self.base.parse_one_input(attrs)?;
// First, determine the operation type.
let mut operation_type = Default::default();
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "type"))
{
operation_type = attr.parse(value)?;
}
// Now read the matrix correspondingly.
// LuminanceToAlpha doesn't accept any matrix.
if operation_type == OperationType::LuminanceToAlpha {
self.params.matrix = {
Matrix5::new(
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.2125, 0.7154, 0.0721, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
};
} else {
for (attr, value) in attrs
.iter()
.filter(|(attr, _)| attr.expanded() == expanded_name!("", "values"))
{
let new_matrix = match operation_type {
OperationType::LuminanceToAlpha => unreachable!(),
OperationType::Matrix => {
let NumberList::<20, 20>(v) = attr.parse(value)?;
let matrix = Matrix4x5::from_row_slice(&v);
let mut matrix = matrix.fixed_resize(0.0);
matrix[(4, 4)] = 1.0;
matrix
}
OperationType::Saturate => {
let s: f64 = attr.parse(value)?;
Matrix5::new(
0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0.0, 0.0,
0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
}
OperationType::HueRotate => {
let degrees: f64 = attr.parse(value)?;
ColorMatrix::hue_rotate_matrix(degrees.to_radians())
}
};
self.params.matrix = new_matrix;
}
}
Ok(())
}
}
impl ColorMatrix {
pub fn render(
&self,
bounds_builder: BoundsBuilder,
ctx: &FilterContext,
acquired_nodes: &mut AcquiredNodes<'_>,
draw_ctx: &mut DrawingCtx,
) -> Result<FilterOutput, FilterError> {
let input_1 = ctx.get_input(
acquired_nodes,
draw_ctx,
&self.in1,
self.color_interpolation_filters,
)?;
let bounds: IRect = bounds_builder
.add_input(&input_1)
.compute(ctx)
.clipped
.into();
let mut surface = ExclusiveImageSurface::new(
ctx.source_graphic().width(),
ctx.source_graphic().height(),
input_1.surface().surface_type(),
)?;
surface.modify(&mut |data, stride| {
for (x, y, pixel) in Pixels::within(input_1.surface(), bounds) {
let alpha = f64::from(pixel.a) / 255f64;
let pixel_vec = if alpha == 0.0 {
Vector5::new(0.0, 0.0, 0.0, 0.0, 1.0)
} else {
Vector5::new(
f64::from(pixel.r) / 255f64 / alpha,
f64::from(pixel.g) / 255f64 / alpha,
f64::from(pixel.b) / 255f64 / alpha,
alpha,
1.0,
)
};
let mut new_pixel_vec = Vector5::zeros();
self.matrix.mul_to(&pixel_vec, &mut new_pixel_vec);
let new_alpha = clamp(new_pixel_vec[3], 0.0, 1.0);
let premultiply = |x: f64| ((clamp(x, 0.0, 1.0) * new_alpha * 255f64) + 0.5) as u8;
let output_pixel = Pixel {
r: premultiply(new_pixel_vec[0]),
g: premultiply(new_pixel_vec[1]),
b: premultiply(new_pixel_vec[2]),
a: ((new_alpha * 255f64) + 0.5) as u8,
};
data.set_pixel(stride, output_pixel, x, y);
}
});
Ok(FilterOutput {
surface: surface.share()?,
bounds,
})
}
pub fn hue_rotate_matrix(radians: f64) -> Matrix5<f64> {
let (sin, cos) = radians.sin_cos();
let a = Matrix3::new(
0.213, 0.715, 0.072, 0.213, 0.715, 0.072, 0.213, 0.715, 0.072,
);
let b = Matrix3::new(
0.787, -0.715, -0.072, -0.213, 0.285, -0.072, -0.213, -0.715, 0.928,
);
let c = Matrix3::new(
-0.213, -0.715, 0.928, 0.143, 0.140, -0.283, -0.787, 0.715, 0.072,
);
let top_left = a + b * cos + c * sin;
let mut matrix = top_left.fixed_resize(0.0);
matrix[(3, 3)] = 1.0;
matrix[(4, 4)] = 1.0;
matrix
}
}
impl FilterEffect for FeColorMatrix {
fn resolve(
&self,
_acquired_nodes: &mut AcquiredNodes<'_>,
node: &Node,
) -> Result<ResolvedPrimitive, FilterResolveError> {
let cascaded = CascadedValues::new_from_node(node);
let values = cascaded.get();
let mut params = self.params.clone();
params.color_interpolation_filters = values.color_interpolation_filters();
Ok(ResolvedPrimitive {
primitive: self.base.clone(),
params: PrimitiveParams::ColorMatrix(params),
})
}
}
impl Parse for OperationType {
fn parse<'i>(parser: &mut Parser<'i, '_>) -> Result<Self, ParseError<'i>> {
Ok(parse_identifiers!(
parser,
"matrix" => OperationType::Matrix,
"saturate" => OperationType::Saturate,
"hueRotate" => OperationType::HueRotate,
"luminanceToAlpha" => OperationType::LuminanceToAlpha,
)?)
}
}
|
{
ColorMatrix {
in1: Default::default(),
color_interpolation_filters: Default::default(),
// nalgebra's Default for Matrix5 is all zeroes, so we actually need this :(
matrix: Matrix5::identity(),
}
}
|
identifier_body
|
diagnostic.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.
use codemap::{Pos, Span};
use codemap;
use std::io;
use std::io::stdio::StdWriter;
use std::local_data;
use extra::term;
static BUG_REPORT_URL: &'static str =
"https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report";
pub trait Emitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub trait handler {
fn fatal(@mut self, msg: &str) ->!;
fn err(@mut self, msg: &str);
fn bump_err_count(@mut self);
fn err_count(@mut self) -> uint;
fn has_errors(@mut self) -> bool;
fn abort_if_errors(@mut self);
fn warn(@mut self, msg: &str);
fn note(@mut self, msg: &str);
// used to indicate a bug in the compiler:
fn bug(@mut self, msg: &str) ->!;
fn unimpl(@mut self, msg: &str) ->!;
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub trait span_handler {
fn span_fatal(@mut self, sp: Span, msg: &str) ->!;
fn span_err(@mut self, sp: Span, msg: &str);
fn span_warn(@mut self, sp: Span, msg: &str);
fn span_note(@mut self, sp: Span, msg: &str);
fn span_bug(@mut self, sp: Span, msg: &str) ->!;
fn span_unimpl(@mut self, sp: Span, msg: &str) ->!;
fn handler(@mut self) -> @mut handler;
}
struct HandlerT {
err_count: uint,
emit: @Emitter,
}
struct CodemapT {
handler: @mut handler,
cm: @codemap::CodeMap,
}
impl span_handler for CodemapT {
fn span_fatal(@mut self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail!();
}
fn span_err(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(@mut self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
fn span_unimpl(@mut self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
fn handler(@mut self) -> @mut handler {
self.handler
}
}
impl handler for HandlerT {
fn fatal(@mut self, msg: &str) ->! {
self.emit.emit(None, msg, fatal);
fail!();
}
fn err(@mut self, msg: &str) {
self.emit.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count(@mut self) {
self.err_count += 1u;
}
fn err_count(@mut self) -> uint {
self.err_count
}
fn has_errors(@mut self) -> bool {
self.err_count > 0u
}
fn abort_if_errors(@mut self) {
let s;
match self.err_count {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = format!("aborting due to {} previous errors",
self.err_count);
}
}
self.fatal(s);
}
fn warn(@mut self, msg: &str) {
self.emit.emit(None, msg, warning);
}
fn note(@mut self, msg: &str) {
self.emit.emit(None, msg, note);
}
fn bug(@mut self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
fn unimpl(@mut self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
self.emit.emit(cmsp, msg, lvl);
|
pub fn ice_msg(msg: &str) -> ~str {
format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \
\nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL)
}
pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap)
-> @mut span_handler {
@mut CodemapT {
handler: handler,
cm: cm,
} as @mut span_handler
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @mut handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@mut HandlerT {
err_count: 0,
emit: emit,
} as @mut handler
}
#[deriving(Eq)]
pub enum level {
fatal,
error,
warning,
note,
}
fn diagnosticstr(lvl: level) -> ~str {
match lvl {
fatal => ~"error",
error => ~"error",
warning => ~"warning",
note => ~"note"
}
}
fn diagnosticcolor(lvl: level) -> term::color::Color {
match lvl {
fatal => term::color::BRIGHT_RED,
error => term::color::BRIGHT_RED,
warning => term::color::BRIGHT_YELLOW,
note => term::color::BRIGHT_GREEN
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>)
fn is_stderr_screen() -> bool {
use std::libc;
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) {
term.attr(c);
term.write(s.as_bytes());
term.reset();
}
if is_stderr_screen() {
local_data::get_mut(tls_terminal, |term| {
match term {
Some(term) => {
match **term {
Some(ref mut term) => write_pretty(term, msg, color),
None => io::stderr().write(msg.as_bytes())
}
}
None => {
let t = ~match term::Terminal::new(io::stderr()) {
Ok(mut term) => {
write_pretty(&mut term, msg, color);
Some(term)
}
Err(_) => {
io::stderr().write(msg.as_bytes());
None
}
};
local_data::set(tls_terminal, t);
}
}
});
} else {
io::stderr().write(msg.as_bytes());
}
}
fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let mut stderr = io::stderr();
if!topic.is_empty() {
write!(&mut stderr as &mut io::Writer, "{} ", topic);
}
print_maybe_styled(format!("{}: ", diagnosticstr(lvl)),
term::attr::ForegroundColor(diagnosticcolor(lvl)));
print_maybe_styled(format!("{}\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: @codemap::CodeMap,
sp: Span,
lvl: level,
lines: @codemap::FileLines) {
let fm = lines.file;
let mut err = io::stderr();
let err = &mut err as &mut io::Writer;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = /* FIXME (#2543) */ lines.lines.clone();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines).to_owned();
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int));
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = format!("{}:{} ", fm.name, last_line + 1u);
write!(err, "{0:1$}...\n", "", s.len());
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
skip.times(|| s.push_char(' '));
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
write!(err, "{}", s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
num_squigglies.times(|| s.push_char('~'));
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(diagnosticcolor(lvl)));
}
}
fn print_macro_backtrace(cm: @codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.as_ref().map_default(~"", |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
};
print_diagnostic(ss, note,
format!("in expansion of {}{}{}", pre, ei.callee.name, post));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(
diag: @mut span_handler,
opt: Option<T>,
msg: || -> ~str)
-> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
|
}
}
|
random_line_split
|
diagnostic.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.
use codemap::{Pos, Span};
use codemap;
use std::io;
use std::io::stdio::StdWriter;
use std::local_data;
use extra::term;
static BUG_REPORT_URL: &'static str =
"https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report";
pub trait Emitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub trait handler {
fn fatal(@mut self, msg: &str) ->!;
fn err(@mut self, msg: &str);
fn bump_err_count(@mut self);
fn err_count(@mut self) -> uint;
fn has_errors(@mut self) -> bool;
fn abort_if_errors(@mut self);
fn warn(@mut self, msg: &str);
fn note(@mut self, msg: &str);
// used to indicate a bug in the compiler:
fn bug(@mut self, msg: &str) ->!;
fn unimpl(@mut self, msg: &str) ->!;
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub trait span_handler {
fn span_fatal(@mut self, sp: Span, msg: &str) ->!;
fn span_err(@mut self, sp: Span, msg: &str);
fn span_warn(@mut self, sp: Span, msg: &str);
fn span_note(@mut self, sp: Span, msg: &str);
fn span_bug(@mut self, sp: Span, msg: &str) ->!;
fn span_unimpl(@mut self, sp: Span, msg: &str) ->!;
fn handler(@mut self) -> @mut handler;
}
struct
|
{
err_count: uint,
emit: @Emitter,
}
struct CodemapT {
handler: @mut handler,
cm: @codemap::CodeMap,
}
impl span_handler for CodemapT {
fn span_fatal(@mut self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail!();
}
fn span_err(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(@mut self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
fn span_unimpl(@mut self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
fn handler(@mut self) -> @mut handler {
self.handler
}
}
impl handler for HandlerT {
fn fatal(@mut self, msg: &str) ->! {
self.emit.emit(None, msg, fatal);
fail!();
}
fn err(@mut self, msg: &str) {
self.emit.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count(@mut self) {
self.err_count += 1u;
}
fn err_count(@mut self) -> uint {
self.err_count
}
fn has_errors(@mut self) -> bool {
self.err_count > 0u
}
fn abort_if_errors(@mut self) {
let s;
match self.err_count {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = format!("aborting due to {} previous errors",
self.err_count);
}
}
self.fatal(s);
}
fn warn(@mut self, msg: &str) {
self.emit.emit(None, msg, warning);
}
fn note(@mut self, msg: &str) {
self.emit.emit(None, msg, note);
}
fn bug(@mut self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
fn unimpl(@mut self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \
\nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL)
}
pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap)
-> @mut span_handler {
@mut CodemapT {
handler: handler,
cm: cm,
} as @mut span_handler
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @mut handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@mut HandlerT {
err_count: 0,
emit: emit,
} as @mut handler
}
#[deriving(Eq)]
pub enum level {
fatal,
error,
warning,
note,
}
fn diagnosticstr(lvl: level) -> ~str {
match lvl {
fatal => ~"error",
error => ~"error",
warning => ~"warning",
note => ~"note"
}
}
fn diagnosticcolor(lvl: level) -> term::color::Color {
match lvl {
fatal => term::color::BRIGHT_RED,
error => term::color::BRIGHT_RED,
warning => term::color::BRIGHT_YELLOW,
note => term::color::BRIGHT_GREEN
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>)
fn is_stderr_screen() -> bool {
use std::libc;
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) {
term.attr(c);
term.write(s.as_bytes());
term.reset();
}
if is_stderr_screen() {
local_data::get_mut(tls_terminal, |term| {
match term {
Some(term) => {
match **term {
Some(ref mut term) => write_pretty(term, msg, color),
None => io::stderr().write(msg.as_bytes())
}
}
None => {
let t = ~match term::Terminal::new(io::stderr()) {
Ok(mut term) => {
write_pretty(&mut term, msg, color);
Some(term)
}
Err(_) => {
io::stderr().write(msg.as_bytes());
None
}
};
local_data::set(tls_terminal, t);
}
}
});
} else {
io::stderr().write(msg.as_bytes());
}
}
fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let mut stderr = io::stderr();
if!topic.is_empty() {
write!(&mut stderr as &mut io::Writer, "{} ", topic);
}
print_maybe_styled(format!("{}: ", diagnosticstr(lvl)),
term::attr::ForegroundColor(diagnosticcolor(lvl)));
print_maybe_styled(format!("{}\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: @codemap::CodeMap,
sp: Span,
lvl: level,
lines: @codemap::FileLines) {
let fm = lines.file;
let mut err = io::stderr();
let err = &mut err as &mut io::Writer;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = /* FIXME (#2543) */ lines.lines.clone();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines).to_owned();
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int));
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = format!("{}:{} ", fm.name, last_line + 1u);
write!(err, "{0:1$}...\n", "", s.len());
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
skip.times(|| s.push_char(' '));
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
write!(err, "{}", s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
num_squigglies.times(|| s.push_char('~'));
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(diagnosticcolor(lvl)));
}
}
fn print_macro_backtrace(cm: @codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.as_ref().map_default(~"", |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
};
print_diagnostic(ss, note,
format!("in expansion of {}{}{}", pre, ei.callee.name, post));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(
diag: @mut span_handler,
opt: Option<T>,
msg: || -> ~str)
-> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
|
HandlerT
|
identifier_name
|
diagnostic.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.
use codemap::{Pos, Span};
use codemap;
use std::io;
use std::io::stdio::StdWriter;
use std::local_data;
use extra::term;
static BUG_REPORT_URL: &'static str =
"https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report";
pub trait Emitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub trait handler {
fn fatal(@mut self, msg: &str) ->!;
fn err(@mut self, msg: &str);
fn bump_err_count(@mut self);
fn err_count(@mut self) -> uint;
fn has_errors(@mut self) -> bool;
fn abort_if_errors(@mut self);
fn warn(@mut self, msg: &str);
fn note(@mut self, msg: &str);
// used to indicate a bug in the compiler:
fn bug(@mut self, msg: &str) ->!;
fn unimpl(@mut self, msg: &str) ->!;
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub trait span_handler {
fn span_fatal(@mut self, sp: Span, msg: &str) ->!;
fn span_err(@mut self, sp: Span, msg: &str);
fn span_warn(@mut self, sp: Span, msg: &str);
fn span_note(@mut self, sp: Span, msg: &str);
fn span_bug(@mut self, sp: Span, msg: &str) ->!;
fn span_unimpl(@mut self, sp: Span, msg: &str) ->!;
fn handler(@mut self) -> @mut handler;
}
struct HandlerT {
err_count: uint,
emit: @Emitter,
}
struct CodemapT {
handler: @mut handler,
cm: @codemap::CodeMap,
}
impl span_handler for CodemapT {
fn span_fatal(@mut self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((self.cm, sp)), msg, fatal);
fail!();
}
fn span_err(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, error);
self.handler.bump_err_count();
}
fn span_warn(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, warning);
}
fn span_note(@mut self, sp: Span, msg: &str) {
self.handler.emit(Some((self.cm, sp)), msg, note);
}
fn span_bug(@mut self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
fn span_unimpl(@mut self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
fn handler(@mut self) -> @mut handler {
self.handler
}
}
impl handler for HandlerT {
fn fatal(@mut self, msg: &str) ->! {
self.emit.emit(None, msg, fatal);
fail!();
}
fn err(@mut self, msg: &str) {
self.emit.emit(None, msg, error);
self.bump_err_count();
}
fn bump_err_count(@mut self) {
self.err_count += 1u;
}
fn err_count(@mut self) -> uint {
self.err_count
}
fn has_errors(@mut self) -> bool {
self.err_count > 0u
}
fn abort_if_errors(@mut self) {
let s;
match self.err_count {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = format!("aborting due to {} previous errors",
self.err_count);
}
}
self.fatal(s);
}
fn warn(@mut self, msg: &str) {
self.emit.emit(None, msg, warning);
}
fn note(@mut self, msg: &str) {
self.emit.emit(None, msg, note);
}
fn bug(@mut self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
fn unimpl(@mut self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
fn emit(@mut self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \
\nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL)
}
pub fn mk_span_handler(handler: @mut handler, cm: @codemap::CodeMap)
-> @mut span_handler {
@mut CodemapT {
handler: handler,
cm: cm,
} as @mut span_handler
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @mut handler
|
#[deriving(Eq)]
pub enum level {
fatal,
error,
warning,
note,
}
fn diagnosticstr(lvl: level) -> ~str {
match lvl {
fatal => ~"error",
error => ~"error",
warning => ~"warning",
note => ~"note"
}
}
fn diagnosticcolor(lvl: level) -> term::color::Color {
match lvl {
fatal => term::color::BRIGHT_RED,
error => term::color::BRIGHT_RED,
warning => term::color::BRIGHT_YELLOW,
note => term::color::BRIGHT_GREEN
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>)
fn is_stderr_screen() -> bool {
use std::libc;
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) {
term.attr(c);
term.write(s.as_bytes());
term.reset();
}
if is_stderr_screen() {
local_data::get_mut(tls_terminal, |term| {
match term {
Some(term) => {
match **term {
Some(ref mut term) => write_pretty(term, msg, color),
None => io::stderr().write(msg.as_bytes())
}
}
None => {
let t = ~match term::Terminal::new(io::stderr()) {
Ok(mut term) => {
write_pretty(&mut term, msg, color);
Some(term)
}
Err(_) => {
io::stderr().write(msg.as_bytes());
None
}
};
local_data::set(tls_terminal, t);
}
}
});
} else {
io::stderr().write(msg.as_bytes());
}
}
fn print_diagnostic(topic: &str, lvl: level, msg: &str) {
let mut stderr = io::stderr();
if!topic.is_empty() {
write!(&mut stderr as &mut io::Writer, "{} ", topic);
}
print_maybe_styled(format!("{}: ", diagnosticstr(lvl)),
term::attr::ForegroundColor(diagnosticcolor(lvl)));
print_maybe_styled(format!("{}\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(@codemap::CodeMap, Span)>,
msg: &str,
lvl: level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: @codemap::CodeMap,
sp: Span,
lvl: level,
lines: @codemap::FileLines) {
let fm = lines.file;
let mut err = io::stderr();
let err = &mut err as &mut io::Writer;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = /* FIXME (#2543) */ lines.lines.clone();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines).to_owned();
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int));
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = format!("{}:{} ", fm.name, last_line + 1u);
write!(err, "{0:1$}...\n", "", s.len());
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
skip.times(|| s.push_char(' '));
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
write!(err, "{}", s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
num_squigglies.times(|| s.push_char('~'));
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(diagnosticcolor(lvl)));
}
}
fn print_macro_backtrace(cm: @codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.as_ref().map_default(~"", |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
};
print_diagnostic(ss, note,
format!("in expansion of {}{}{}", pre, ei.callee.name, post));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(
diag: @mut span_handler,
opt: Option<T>,
msg: || -> ~str)
-> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
|
{
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@mut HandlerT {
err_count: 0,
emit: emit,
} as @mut handler
}
|
identifier_body
|
edition-keywords-2015-2015.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unused_mut)]
#![allow(unused_assignments)]
#![allow(unused_variables)]
// edition:2015
// aux-build:edition-kw-macro-2015.rs
#[macro_use]
extern crate edition_kw_macro_2015;
pub fn check_async() {
let mut async = 1; // OK
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
if passes_ident!(async) == 1 {} // OK
if passes_ident!(r#async) == 1 {} // OK
one_async::async(); // OK
one_async::r#async(); // OK
two_async::async(); // OK
two_async::r#async(); // OK
}
mod one_async {
produces_async! {} // OK
}
mod two_async {
produces_async_raw! {} // OK
}
fn
|
() {}
|
main
|
identifier_name
|
edition-keywords-2015-2015.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unused_mut)]
#![allow(unused_assignments)]
#![allow(unused_variables)]
// edition:2015
// aux-build:edition-kw-macro-2015.rs
#[macro_use]
extern crate edition_kw_macro_2015;
pub fn check_async()
|
mod one_async {
produces_async! {} // OK
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
|
{
let mut async = 1; // OK
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
if passes_ident!(async) == 1 {} // OK
if passes_ident!(r#async) == 1 {} // OK
one_async::async(); // OK
one_async::r#async(); // OK
two_async::async(); // OK
two_async::r#async(); // OK
}
|
identifier_body
|
edition-keywords-2015-2015.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unused_mut)]
#![allow(unused_assignments)]
#![allow(unused_variables)]
// edition:2015
// aux-build:edition-kw-macro-2015.rs
#[macro_use]
extern crate edition_kw_macro_2015;
pub fn check_async() {
let mut async = 1; // OK
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
if passes_ident!(async) == 1 {} // OK
if passes_ident!(r#async) == 1
|
// OK
one_async::async(); // OK
one_async::r#async(); // OK
two_async::async(); // OK
two_async::r#async(); // OK
}
mod one_async {
produces_async! {} // OK
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
|
{}
|
conditional_block
|
edition-keywords-2015-2015.rs
|
// Copyright 2018 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
|
#![allow(unused_mut)]
#![allow(unused_assignments)]
#![allow(unused_variables)]
// edition:2015
// aux-build:edition-kw-macro-2015.rs
#[macro_use]
extern crate edition_kw_macro_2015;
pub fn check_async() {
let mut async = 1; // OK
let mut r#async = 1; // OK
r#async = consumes_async!(async); // OK
// r#async = consumes_async!(r#async); // ERROR, not a match
// r#async = consumes_async_raw!(async); // ERROR, not a match
r#async = consumes_async_raw!(r#async); // OK
if passes_ident!(async) == 1 {} // OK
if passes_ident!(r#async) == 1 {} // OK
one_async::async(); // OK
one_async::r#async(); // OK
two_async::async(); // OK
two_async::r#async(); // OK
}
mod one_async {
produces_async! {} // OK
}
mod two_async {
produces_async_raw! {} // OK
}
fn main() {}
|
// 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.
|
random_line_split
|
font_metrics.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/. */
//! Access to font metrics from the style system.
#![deny(missing_docs)]
use Atom;
use app_units::Au;
use euclid::Size2D;
use std::fmt;
/// Represents the font metrics that style needs from a font to compute the
/// value of certain CSS units like `ex`.
#[derive(Debug, PartialEq, Clone)]
pub struct
|
{
/// The x-height of the font.
pub x_height: Au,
/// The zero advance.
pub zero_advance_measure: Size2D<Au>,
}
/// The result for querying font metrics for a given font family.
#[derive(Debug, PartialEq, Clone)]
pub enum FontMetricsQueryResult {
/// The font is available, but we may or may not have found any font metrics
/// for it.
Available(Option<FontMetrics>),
/// The font is not available.
NotAvailable,
}
/// A trait used to represent something capable of providing us font metrics.
pub trait FontMetricsProvider: Send + Sync + fmt::Debug {
/// Obtain the metrics for given font family.
///
/// TODO: We could make this take the full list, I guess, and save a few
/// virtual calls in the case we are repeatedly unable to find font metrics?
/// That is not too common in practice though.
fn query(&self, _font_name: &Atom) -> FontMetricsQueryResult {
FontMetricsQueryResult::NotAvailable
}
}
|
FontMetrics
|
identifier_name
|
font_metrics.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/. */
//! Access to font metrics from the style system.
#![deny(missing_docs)]
use Atom;
use app_units::Au;
use euclid::Size2D;
use std::fmt;
/// Represents the font metrics that style needs from a font to compute the
/// value of certain CSS units like `ex`.
#[derive(Debug, PartialEq, Clone)]
pub struct FontMetrics {
/// The x-height of the font.
pub x_height: Au,
/// The zero advance.
pub zero_advance_measure: Size2D<Au>,
}
/// The result for querying font metrics for a given font family.
#[derive(Debug, PartialEq, Clone)]
pub enum FontMetricsQueryResult {
/// The font is available, but we may or may not have found any font metrics
/// for it.
Available(Option<FontMetrics>),
/// The font is not available.
NotAvailable,
|
/// A trait used to represent something capable of providing us font metrics.
pub trait FontMetricsProvider: Send + Sync + fmt::Debug {
/// Obtain the metrics for given font family.
///
/// TODO: We could make this take the full list, I guess, and save a few
/// virtual calls in the case we are repeatedly unable to find font metrics?
/// That is not too common in practice though.
fn query(&self, _font_name: &Atom) -> FontMetricsQueryResult {
FontMetricsQueryResult::NotAvailable
}
}
|
}
|
random_line_split
|
workqueue.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/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
#[cfg(windows)]
extern crate kernel32;
use deque::{self, Abort, Data, Empty, Stealer, Worker};
#[cfg(not(windows))]
use libc::usleep;
use rand::{Rng, XorShiftRng, weak_rng};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use thread::spawn_named;
use thread_state;
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData: Send> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum
|
<QueueData:'static, WorkData:'static + Send> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker to measure the heap size of its TLS using the supplied function.
HeapSizeOfTLS(fn() -> usize),
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static + Send> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static + Send> {
Finished,
HeapSizeOfTLS(usize),
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static + Send> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static + Send> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static + Send> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static + Send> Send for WorkerThread<QueueData, WorkData> {}
const SPINS_UNTIL_BACKOFF: u32 = 128;
const BACKOFF_INCREMENT_IN_US: u32 = 5;
const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6;
#[cfg(not(windows))]
fn sleep_microseconds(usec: u32) {
unsafe {
usleep(usec);
}
}
#[cfg(windows)]
fn sleep_microseconds(_: u32) {
unsafe {
kernel32::Sleep(0);
}
}
impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
let deque_index_mask = (self.other_deques.len() as u32).next_power_of_two() - 1;
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
WorkerMsg::HeapSizeOfTLS(f) => {
self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap();
continue;
}
};
let mut back_off_sleep = 0 as u32;
// We're off!
'outer: loop {
let work_unit;
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
loop {
// Don't just use `rand % len` because that's slow on ARM.
let mut victim;
loop {
victim = self.rng.next_u32() & deque_index_mask;
if (victim as usize) < self.other_deques.len() {
break
}
}
match self.other_deques[victim as usize].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
if back_off_sleep >= BACKOFF_INCREMENT_IN_US *
BACKOFFS_UNTIL_CONTROL_CHECK {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => break 'outer,
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
}
}
sleep_microseconds(back_off_sleep);
back_off_sleep += BACKOFF_INCREMENT_IN_US;
i = 0
} else {
i += 1
}
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
// queue_data is kept alive in the stack frame of
// WorkQueue::run until we send the
// SupervisorMsg::ReturnDeque message below.
queue_data: unsafe { &*queue_data },
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::Release) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a + Send> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: &'a QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::Relaxed));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data(&self) -> &'a QueueData {
self.queue_data
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static + Send> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
}
impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(thread_name: &'static str,
state: thread_state::ThreadState,
thread_count: usize) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let (worker, thief) = deque::new();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for (i, mut thread) in threads.iter_mut().enumerate() {
for (j, info) in infos.iter().enumerate() {
if i!= j {
thread.other_deques.push(info.thief.clone())
}
}
assert!(thread.other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", thread_name, i + 1, thread_count),
move || {
thread_state::initialize(state | thread_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self, data: &QueueData) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in &mut self.workers {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in &self.workers {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
/// Synchronously measure memory usage of any thread-local storage.
pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> {
// Tell the workers to measure themselves.
for worker in &self.workers {
worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap()
}
// Wait for the workers to finish measuring themselves.
let mut sizes = vec![];
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::HeapSizeOfTLS(size) => {
sizes.push(size);
}
_ => panic!("unexpected message!"),
}
}
sizes
}
pub fn shutdown(&mut self) {
for worker in &self.workers {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
|
WorkerMsg
|
identifier_name
|
workqueue.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/. */
//! A work queue for scheduling units of work across threads in a fork-join fashion.
//!
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism.
#[cfg(windows)]
extern crate kernel32;
use deque::{self, Abort, Data, Empty, Stealer, Worker};
#[cfg(not(windows))]
use libc::usleep;
use rand::{Rng, XorShiftRng, weak_rng};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use thread::spawn_named;
use thread_state;
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData: Send> {
/// The function to execute.
pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>),
/// Arbitrary data.
pub data: WorkData,
}
/// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData:'static, WorkData:'static + Send> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker to measure the heap size of its TLS using the supplied function.
HeapSizeOfTLS(fn() -> usize),
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData:'static, WorkData:'static + Send> Send for WorkerMsg<QueueData, WorkData> {}
/// Messages to the supervisor.
enum SupervisorMsg<QueueData:'static, WorkData:'static + Send> {
Finished,
HeapSizeOfTLS(usize),
ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData:'static, WorkData:'static + Send> Send for SupervisorMsg<QueueData, WorkData> {}
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData:'static, WorkData:'static + Send> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit<QueueData, WorkData>>>,
/// The thief end of the work-stealing deque.
thief: Stealer<WorkUnit<QueueData, WorkData>>,
}
/// Information specific to each worker thread that the thread keeps.
struct WorkerThread<QueueData:'static, WorkData:'static + Send> {
/// The index of this worker.
index: usize,
/// The communication port from the supervisor.
port: Receiver<WorkerMsg<QueueData, WorkData>>,
/// The communication channel on which messages are sent to the supervisor.
chan: Sender<SupervisorMsg<QueueData, WorkData>>,
/// The thief end of the work-stealing deque for all other workers.
other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>,
/// The random number generator for this worker.
rng: XorShiftRng,
}
unsafe impl<QueueData:'static, WorkData:'static + Send> Send for WorkerThread<QueueData, WorkData> {}
const SPINS_UNTIL_BACKOFF: u32 = 128;
const BACKOFF_INCREMENT_IN_US: u32 = 5;
const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6;
#[cfg(not(windows))]
fn sleep_microseconds(usec: u32) {
unsafe {
usleep(usec);
}
}
#[cfg(windows)]
fn sleep_microseconds(_: u32) {
unsafe {
kernel32::Sleep(0);
}
}
impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> {
/// The main logic. This function starts up the worker and listens for
/// messages.
fn start(&mut self) {
let deque_index_mask = (self.other_deques.len() as u32).next_power_of_two() - 1;
loop {
// Wait for a start message.
let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() {
WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data),
WorkerMsg::Stop => panic!("unexpected stop message"),
WorkerMsg::Exit => return,
WorkerMsg::HeapSizeOfTLS(f) => {
self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap();
continue;
}
};
let mut back_off_sleep = 0 as u32;
// We're off!
'outer: loop {
let work_unit;
match deque.pop() {
Some(work) => work_unit = work,
None => {
// Become a thief.
let mut i = 0;
loop {
// Don't just use `rand % len` because that's slow on ARM.
let mut victim;
loop {
victim = self.rng.next_u32() & deque_index_mask;
if (victim as usize) < self.other_deques.len() {
break
}
}
match self.other_deques[victim as usize].steal() {
Empty | Abort => {
// Continue.
}
Data(work) => {
work_unit = work;
back_off_sleep = 0 as u32;
break
}
}
if i > SPINS_UNTIL_BACKOFF {
if back_off_sleep >= BACKOFF_INCREMENT_IN_US *
BACKOFFS_UNTIL_CONTROL_CHECK {
match self.port.try_recv() {
Ok(WorkerMsg::Stop) => break 'outer,
|
}
}
sleep_microseconds(back_off_sleep);
back_off_sleep += BACKOFF_INCREMENT_IN_US;
i = 0
} else {
i += 1
}
}
}
}
// At this point, we have some work. Perform it.
let mut proxy = WorkerProxy {
worker: &mut deque,
ref_count: ref_count,
// queue_data is kept alive in the stack frame of
// WorkQueue::run until we send the
// SupervisorMsg::ReturnDeque message below.
queue_data: unsafe { &*queue_data },
worker_index: self.index as u8,
};
(work_unit.fun)(work_unit.data, &mut proxy);
// The work is done. Now decrement the count of outstanding work items. If this was
// the last work unit in the queue, then send a message on the channel.
unsafe {
if (*ref_count).fetch_sub(1, Ordering::Release) == 1 {
self.chan.send(SupervisorMsg::Finished).unwrap()
}
}
}
// Give the deque back to the supervisor.
self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap()
}
}
}
/// A handle to the work queue that individual work units have.
pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a + Send> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUsize,
queue_data: &'a QueueData,
worker_index: u8,
}
impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> {
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
unsafe {
drop((*self.ref_count).fetch_add(1, Ordering::Relaxed));
}
self.worker.push(work_unit);
}
/// Retrieves the queue user data.
#[inline]
pub fn user_data(&self) -> &'a QueueData {
self.queue_data
}
/// Retrieves the index of the worker.
#[inline]
pub fn worker_index(&self) -> u8 {
self.worker_index
}
}
/// A work queue on which units of work can be submitted.
pub struct WorkQueue<QueueData:'static, WorkData:'static + Send> {
/// Information about each of the workers.
workers: Vec<WorkerInfo<QueueData, WorkData>>,
/// A port on which deques can be received from the workers.
port: Receiver<SupervisorMsg<QueueData, WorkData>>,
/// The amount of work that has been enqueued.
work_count: usize,
}
impl<QueueData: Sync, WorkData: Send> WorkQueue<QueueData, WorkData> {
/// Creates a new work queue and spawns all the threads associated with
/// it.
pub fn new(thread_name: &'static str,
state: thread_state::ThreadState,
thread_count: usize) -> WorkQueue<QueueData, WorkData> {
// Set up data structures.
let (supervisor_chan, supervisor_port) = channel();
let (mut infos, mut threads) = (vec!(), vec!());
for i in 0..thread_count {
let (worker_chan, worker_port) = channel();
let (worker, thief) = deque::new();
infos.push(WorkerInfo {
chan: worker_chan,
deque: Some(worker),
thief: thief,
});
threads.push(WorkerThread {
index: i,
port: worker_port,
chan: supervisor_chan.clone(),
other_deques: vec!(),
rng: weak_rng(),
});
}
// Connect workers to one another.
for (i, mut thread) in threads.iter_mut().enumerate() {
for (j, info) in infos.iter().enumerate() {
if i!= j {
thread.other_deques.push(info.thief.clone())
}
}
assert!(thread.other_deques.len() == thread_count - 1)
}
// Spawn threads.
for (i, thread) in threads.into_iter().enumerate() {
spawn_named(
format!("{} worker {}/{}", thread_name, i + 1, thread_count),
move || {
thread_state::initialize(state | thread_state::IN_WORKER);
let mut thread = thread;
thread.start()
})
}
WorkQueue {
workers: infos,
port: supervisor_port,
work_count: 0,
}
}
/// Enqueues a block into the work queue.
#[inline]
pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
}
/// Synchronously runs all the enqueued tasks and waits for them to complete.
pub fn run(&mut self, data: &QueueData) {
// Tell the workers to start.
let mut work_count = AtomicUsize::new(self.work_count);
for worker in &mut self.workers {
worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(),
&mut work_count,
data)).unwrap()
}
// Wait for the work to finish.
drop(self.port.recv());
self.work_count = 0;
// Tell everyone to stop.
for worker in &self.workers {
worker.chan.send(WorkerMsg::Stop).unwrap()
}
// Get our deques back.
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque),
SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"),
SupervisorMsg::Finished => panic!("unexpected finished message!"),
}
}
}
/// Synchronously measure memory usage of any thread-local storage.
pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> {
// Tell the workers to measure themselves.
for worker in &self.workers {
worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap()
}
// Wait for the workers to finish measuring themselves.
let mut sizes = vec![];
for _ in 0..self.workers.len() {
match self.port.recv().unwrap() {
SupervisorMsg::HeapSizeOfTLS(size) => {
sizes.push(size);
}
_ => panic!("unexpected message!"),
}
}
sizes
}
pub fn shutdown(&mut self) {
for worker in &self.workers {
worker.chan.send(WorkerMsg::Exit).unwrap()
}
}
}
|
Ok(WorkerMsg::Exit) => return,
Ok(_) => panic!("unexpected message"),
_ => {}
|
random_line_split
|
poll.rs
|
use std::fmt;
use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
})
}
pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.register(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn reregister<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.reregister(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn deregister<H: IoHandle>(&mut self, io: &H) -> MioResult<()> {
debug!("deregistering IO with poller");
// Deregister interests for this socket
try!(self.selector.deregister(io.desc()));
Ok(())
}
pub fn poll(&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
EventsIterator { events: &self.events, index: 0 }
}
}
impl fmt::Debug for Poll {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result
|
}
pub struct EventsIterator<'a> {
events: &'a os::Events,
index: usize
}
impl<'a> Iterator for EventsIterator<'a> {
type Item = event::IoEvent;
fn next(&mut self) -> Option<event::IoEvent> {
if self.index == self.events.len() {
None
} else {
self.index += 1;
Some(self.events.get(self.index - 1))
}
}
}
|
{
write!(fmt, "Poll")
}
|
identifier_body
|
poll.rs
|
use std::fmt;
use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn
|
() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
})
}
pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.register(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn reregister<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.reregister(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn deregister<H: IoHandle>(&mut self, io: &H) -> MioResult<()> {
debug!("deregistering IO with poller");
// Deregister interests for this socket
try!(self.selector.deregister(io.desc()));
Ok(())
}
pub fn poll(&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
EventsIterator { events: &self.events, index: 0 }
}
}
impl fmt::Debug for Poll {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Poll")
}
}
pub struct EventsIterator<'a> {
events: &'a os::Events,
index: usize
}
impl<'a> Iterator for EventsIterator<'a> {
type Item = event::IoEvent;
fn next(&mut self) -> Option<event::IoEvent> {
if self.index == self.events.len() {
None
} else {
self.index += 1;
Some(self.events.get(self.index - 1))
}
}
}
|
new
|
identifier_name
|
poll.rs
|
use std::fmt;
use error::MioResult;
|
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
})
}
pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.register(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn reregister<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.reregister(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn deregister<H: IoHandle>(&mut self, io: &H) -> MioResult<()> {
debug!("deregistering IO with poller");
// Deregister interests for this socket
try!(self.selector.deregister(io.desc()));
Ok(())
}
pub fn poll(&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
EventsIterator { events: &self.events, index: 0 }
}
}
impl fmt::Debug for Poll {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Poll")
}
}
pub struct EventsIterator<'a> {
events: &'a os::Events,
index: usize
}
impl<'a> Iterator for EventsIterator<'a> {
type Item = event::IoEvent;
fn next(&mut self) -> Option<event::IoEvent> {
if self.index == self.events.len() {
None
} else {
self.index += 1;
Some(self.events.get(self.index - 1))
}
}
}
|
use io::IoHandle;
use os;
use os::token::Token;
|
random_line_split
|
poll.rs
|
use std::fmt;
use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
})
}
pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.register(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn reregister<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
debug!("registering with poller");
// Register interests for this socket
try!(self.selector.reregister(io.desc(), token.as_usize(), interest, opts));
Ok(())
}
pub fn deregister<H: IoHandle>(&mut self, io: &H) -> MioResult<()> {
debug!("deregistering IO with poller");
// Deregister interests for this socket
try!(self.selector.deregister(io.desc()));
Ok(())
}
pub fn poll(&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
EventsIterator { events: &self.events, index: 0 }
}
}
impl fmt::Debug for Poll {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Poll")
}
}
pub struct EventsIterator<'a> {
events: &'a os::Events,
index: usize
}
impl<'a> Iterator for EventsIterator<'a> {
type Item = event::IoEvent;
fn next(&mut self) -> Option<event::IoEvent> {
if self.index == self.events.len()
|
else {
self.index += 1;
Some(self.events.get(self.index - 1))
}
}
}
|
{
None
}
|
conditional_block
|
mod.rs
|
//! Contains all of the currently completed standard bots/searchers/AIs.
//!
//! These are mostly for example purposes, to see how one can create a chess AI.
extern crate rand;
pub mod minimax;
pub mod parallel_minimax;
pub mod alphabeta;
pub mod jamboree;
pub mod iterative_parallel_mvv_lva;
use core::piece_move::*;
use tools::Searcher;
use board::Board;
use tools::eval::*;
use core::score::*;
const MAX_PLY: u16 = 4;
const MATE_V: i16 = MATE as i16;
const DRAW_V: i16 = DRAW as i16;
const NEG_INF_V: i16 = NEG_INFINITE as i16;
const INF_V: i16 = INFINITE as i16;
struct BoardWrapper<'a> {
b: &'a mut Board
}
/// Searcher that randomly chooses a move. The fastest, yet dumbest, searcher we have to offer.
pub struct RandomBot {}
/// Searcher that uses a MiniMax algorithm to search for a best move.
pub struct MiniMaxSearcher {}
/// Searcher that uses a MiniMax algorithm to search for a best move, but does so in parallel.
pub struct ParallelMiniMaxSearcher {}
/// Searcher that uses an alpha-beta algorithm to search for a best move.
pub struct AlphaBetaSearcher {}
/// Searcher that uses a modified alpha-beta algorithm to search for a best move, but does so in parallel.
/// The specific name of this algorithm is called "jamboree".
pub struct JamboreeSearcher {}
/// Modified `JamboreeSearcher` that uses the parallel alpha-beta algorithm. Improves upon `JamboreeSearcher` by
/// adding iterative deepening with an aspiration window, MVV-LVA move ordering, as well as a qscience search.
pub struct IterativeSearcher {}
impl Searcher for RandomBot {
fn name() -> &'static str {
"Random Searcher"
}
fn
|
(board: Board, _depth: u16) -> BitMove {
let moves = board.generate_moves();
moves[rand::random::<usize>() % moves.len()]
}
}
impl Searcher for AlphaBetaSearcher {
fn name() -> &'static str {
"AlphaBeta Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
let alpha = NEG_INF_V;
let beta = INF_V;
alphabeta::alpha_beta_search(&mut board.shallow_clone(), alpha, beta, depth)
.bit_move
}
}
impl Searcher for IterativeSearcher {
fn name() -> &'static str {
"Advanced Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
iterative_parallel_mvv_lva::iterative_deepening(&mut board.shallow_clone(), depth)
}
}
impl Searcher for JamboreeSearcher {
fn name() -> &'static str {
"Jamboree Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
let alpha = NEG_INF_V;
let beta = INF_V;
jamboree::jamboree(&mut board.shallow_clone(), alpha, beta, depth, 2)
.bit_move
}
}
impl Searcher for MiniMaxSearcher {
fn name() -> &'static str {
"Simple Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
minimax::minimax( &mut board.shallow_clone(), depth).bit_move
}
}
impl Searcher for ParallelMiniMaxSearcher {
fn name() -> &'static str {
"Parallel Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
parallel_minimax::parallel_minimax(&mut board.shallow_clone(), depth)
.bit_move
}
}
#[doc(hidden)]
pub fn eval_board(board: &Board) -> ScoringMove {
ScoringMove::blank(Eval::eval_low(board) as i16)
}
#[cfg(test)]
mod tests {
use super::*;
// We test these, as both algorithms should give the same result no matter if paralleized
// or not.
#[test]
fn minimax_equality() {
let b = Board::start_pos();
let b2 = b.shallow_clone();
assert_eq!(MiniMaxSearcher::best_move(b, 5), ParallelMiniMaxSearcher::best_move(b2, 5));
}
#[test]
fn alpha_equality() {
let b = Board::start_pos();
let b2 = b.shallow_clone();
assert_eq!(AlphaBetaSearcher::best_move(b, 5), JamboreeSearcher::best_move(b2, 5));
}
}
|
best_move
|
identifier_name
|
mod.rs
|
//! Contains all of the currently completed standard bots/searchers/AIs.
//!
//! These are mostly for example purposes, to see how one can create a chess AI.
extern crate rand;
pub mod minimax;
pub mod parallel_minimax;
pub mod alphabeta;
pub mod jamboree;
pub mod iterative_parallel_mvv_lva;
use core::piece_move::*;
use tools::Searcher;
use board::Board;
use tools::eval::*;
use core::score::*;
const MAX_PLY: u16 = 4;
const MATE_V: i16 = MATE as i16;
const DRAW_V: i16 = DRAW as i16;
const NEG_INF_V: i16 = NEG_INFINITE as i16;
const INF_V: i16 = INFINITE as i16;
|
/// Searcher that randomly chooses a move. The fastest, yet dumbest, searcher we have to offer.
pub struct RandomBot {}
/// Searcher that uses a MiniMax algorithm to search for a best move.
pub struct MiniMaxSearcher {}
/// Searcher that uses a MiniMax algorithm to search for a best move, but does so in parallel.
pub struct ParallelMiniMaxSearcher {}
/// Searcher that uses an alpha-beta algorithm to search for a best move.
pub struct AlphaBetaSearcher {}
/// Searcher that uses a modified alpha-beta algorithm to search for a best move, but does so in parallel.
/// The specific name of this algorithm is called "jamboree".
pub struct JamboreeSearcher {}
/// Modified `JamboreeSearcher` that uses the parallel alpha-beta algorithm. Improves upon `JamboreeSearcher` by
/// adding iterative deepening with an aspiration window, MVV-LVA move ordering, as well as a qscience search.
pub struct IterativeSearcher {}
impl Searcher for RandomBot {
fn name() -> &'static str {
"Random Searcher"
}
fn best_move(board: Board, _depth: u16) -> BitMove {
let moves = board.generate_moves();
moves[rand::random::<usize>() % moves.len()]
}
}
impl Searcher for AlphaBetaSearcher {
fn name() -> &'static str {
"AlphaBeta Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
let alpha = NEG_INF_V;
let beta = INF_V;
alphabeta::alpha_beta_search(&mut board.shallow_clone(), alpha, beta, depth)
.bit_move
}
}
impl Searcher for IterativeSearcher {
fn name() -> &'static str {
"Advanced Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
iterative_parallel_mvv_lva::iterative_deepening(&mut board.shallow_clone(), depth)
}
}
impl Searcher for JamboreeSearcher {
fn name() -> &'static str {
"Jamboree Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
let alpha = NEG_INF_V;
let beta = INF_V;
jamboree::jamboree(&mut board.shallow_clone(), alpha, beta, depth, 2)
.bit_move
}
}
impl Searcher for MiniMaxSearcher {
fn name() -> &'static str {
"Simple Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
minimax::minimax( &mut board.shallow_clone(), depth).bit_move
}
}
impl Searcher for ParallelMiniMaxSearcher {
fn name() -> &'static str {
"Parallel Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
parallel_minimax::parallel_minimax(&mut board.shallow_clone(), depth)
.bit_move
}
}
#[doc(hidden)]
pub fn eval_board(board: &Board) -> ScoringMove {
ScoringMove::blank(Eval::eval_low(board) as i16)
}
#[cfg(test)]
mod tests {
use super::*;
// We test these, as both algorithms should give the same result no matter if paralleized
// or not.
#[test]
fn minimax_equality() {
let b = Board::start_pos();
let b2 = b.shallow_clone();
assert_eq!(MiniMaxSearcher::best_move(b, 5), ParallelMiniMaxSearcher::best_move(b2, 5));
}
#[test]
fn alpha_equality() {
let b = Board::start_pos();
let b2 = b.shallow_clone();
assert_eq!(AlphaBetaSearcher::best_move(b, 5), JamboreeSearcher::best_move(b2, 5));
}
}
|
struct BoardWrapper<'a> {
b: &'a mut Board
}
|
random_line_split
|
mod.rs
|
//! Contains all of the currently completed standard bots/searchers/AIs.
//!
//! These are mostly for example purposes, to see how one can create a chess AI.
extern crate rand;
pub mod minimax;
pub mod parallel_minimax;
pub mod alphabeta;
pub mod jamboree;
pub mod iterative_parallel_mvv_lva;
use core::piece_move::*;
use tools::Searcher;
use board::Board;
use tools::eval::*;
use core::score::*;
const MAX_PLY: u16 = 4;
const MATE_V: i16 = MATE as i16;
const DRAW_V: i16 = DRAW as i16;
const NEG_INF_V: i16 = NEG_INFINITE as i16;
const INF_V: i16 = INFINITE as i16;
struct BoardWrapper<'a> {
b: &'a mut Board
}
/// Searcher that randomly chooses a move. The fastest, yet dumbest, searcher we have to offer.
pub struct RandomBot {}
/// Searcher that uses a MiniMax algorithm to search for a best move.
pub struct MiniMaxSearcher {}
/// Searcher that uses a MiniMax algorithm to search for a best move, but does so in parallel.
pub struct ParallelMiniMaxSearcher {}
/// Searcher that uses an alpha-beta algorithm to search for a best move.
pub struct AlphaBetaSearcher {}
/// Searcher that uses a modified alpha-beta algorithm to search for a best move, but does so in parallel.
/// The specific name of this algorithm is called "jamboree".
pub struct JamboreeSearcher {}
/// Modified `JamboreeSearcher` that uses the parallel alpha-beta algorithm. Improves upon `JamboreeSearcher` by
/// adding iterative deepening with an aspiration window, MVV-LVA move ordering, as well as a qscience search.
pub struct IterativeSearcher {}
impl Searcher for RandomBot {
fn name() -> &'static str {
"Random Searcher"
}
fn best_move(board: Board, _depth: u16) -> BitMove {
let moves = board.generate_moves();
moves[rand::random::<usize>() % moves.len()]
}
}
impl Searcher for AlphaBetaSearcher {
fn name() -> &'static str {
"AlphaBeta Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
let alpha = NEG_INF_V;
let beta = INF_V;
alphabeta::alpha_beta_search(&mut board.shallow_clone(), alpha, beta, depth)
.bit_move
}
}
impl Searcher for IterativeSearcher {
fn name() -> &'static str {
"Advanced Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
iterative_parallel_mvv_lva::iterative_deepening(&mut board.shallow_clone(), depth)
}
}
impl Searcher for JamboreeSearcher {
fn name() -> &'static str {
"Jamboree Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
let alpha = NEG_INF_V;
let beta = INF_V;
jamboree::jamboree(&mut board.shallow_clone(), alpha, beta, depth, 2)
.bit_move
}
}
impl Searcher for MiniMaxSearcher {
fn name() -> &'static str
|
fn best_move(board: Board, depth: u16) -> BitMove {
minimax::minimax( &mut board.shallow_clone(), depth).bit_move
}
}
impl Searcher for ParallelMiniMaxSearcher {
fn name() -> &'static str {
"Parallel Searcher"
}
fn best_move(board: Board, depth: u16) -> BitMove {
parallel_minimax::parallel_minimax(&mut board.shallow_clone(), depth)
.bit_move
}
}
#[doc(hidden)]
pub fn eval_board(board: &Board) -> ScoringMove {
ScoringMove::blank(Eval::eval_low(board) as i16)
}
#[cfg(test)]
mod tests {
use super::*;
// We test these, as both algorithms should give the same result no matter if paralleized
// or not.
#[test]
fn minimax_equality() {
let b = Board::start_pos();
let b2 = b.shallow_clone();
assert_eq!(MiniMaxSearcher::best_move(b, 5), ParallelMiniMaxSearcher::best_move(b2, 5));
}
#[test]
fn alpha_equality() {
let b = Board::start_pos();
let b2 = b.shallow_clone();
assert_eq!(AlphaBetaSearcher::best_move(b, 5), JamboreeSearcher::best_move(b2, 5));
}
}
|
{
"Simple Searcher"
}
|
identifier_body
|
camera.rs
|
use cgmath::Ortho;
use glium::uniforms::{AsUniformValue, UniformValue};
use transform::Transform;
use types::{Scalar, Mat4};
/// Orthogonal 2D Camera.
pub struct Camera2D {
pub transform: Transform,
matrix: Mat4,
}
impl Camera2D {
pub fn new(width: u32, height: u32) -> Camera2D
|
fn build_matrix(width: u32, height: u32, transform: &Mat4) -> Mat4 {
let (w, h) = (width as Scalar, height as Scalar);
let ortho = Ortho {
left: 0.0,
right: w,
bottom: 0.0,
top: h,
near: -1.0,
far: 1.0,
};
Mat4::from(ortho) * transform
}
}
impl<'a> AsUniformValue for &'a Camera2D {
fn as_uniform_value(&self) -> UniformValue {
let matrix: &[[Scalar; 4]; 4] = self.matrix.as_ref();
matrix.as_uniform_value()
}
}
|
{
let transform = Transform::new();
Camera2D {
matrix: Camera2D::build_matrix(width, height, &transform.matrix),
transform: transform,
}
}
|
identifier_body
|
camera.rs
|
use cgmath::Ortho;
use glium::uniforms::{AsUniformValue, UniformValue};
use transform::Transform;
use types::{Scalar, Mat4};
/// Orthogonal 2D Camera.
pub struct Camera2D {
pub transform: Transform,
matrix: Mat4,
}
impl Camera2D {
pub fn new(width: u32, height: u32) -> Camera2D {
let transform = Transform::new();
Camera2D {
matrix: Camera2D::build_matrix(width, height, &transform.matrix),
transform: transform,
}
}
fn build_matrix(width: u32, height: u32, transform: &Mat4) -> Mat4 {
let (w, h) = (width as Scalar, height as Scalar);
let ortho = Ortho {
left: 0.0,
right: w,
bottom: 0.0,
top: h,
near: -1.0,
far: 1.0,
};
Mat4::from(ortho) * transform
}
}
impl<'a> AsUniformValue for &'a Camera2D {
fn as_uniform_value(&self) -> UniformValue {
let matrix: &[[Scalar; 4]; 4] = self.matrix.as_ref();
matrix.as_uniform_value()
}
|
}
|
random_line_split
|
|
camera.rs
|
use cgmath::Ortho;
use glium::uniforms::{AsUniformValue, UniformValue};
use transform::Transform;
use types::{Scalar, Mat4};
/// Orthogonal 2D Camera.
pub struct Camera2D {
pub transform: Transform,
matrix: Mat4,
}
impl Camera2D {
pub fn
|
(width: u32, height: u32) -> Camera2D {
let transform = Transform::new();
Camera2D {
matrix: Camera2D::build_matrix(width, height, &transform.matrix),
transform: transform,
}
}
fn build_matrix(width: u32, height: u32, transform: &Mat4) -> Mat4 {
let (w, h) = (width as Scalar, height as Scalar);
let ortho = Ortho {
left: 0.0,
right: w,
bottom: 0.0,
top: h,
near: -1.0,
far: 1.0,
};
Mat4::from(ortho) * transform
}
}
impl<'a> AsUniformValue for &'a Camera2D {
fn as_uniform_value(&self) -> UniformValue {
let matrix: &[[Scalar; 4]; 4] = self.matrix.as_ref();
matrix.as_uniform_value()
}
}
|
new
|
identifier_name
|
touch.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 euclid::point::TypedPoint2D;
use euclid::scale_factor::ScaleFactor;
use gfx_traits::DevicePixel;
use script_traits::{EventResult, TouchId};
use self::TouchState::*;
/// Minimum number of ScreenPx to begin touch scrolling.
const TOUCH_PAN_MIN_SCREEN_PX: f32 = 20.0;
pub struct TouchHandler {
pub state: TouchState,
pub active_touch_points: Vec<TouchPoint>,
}
#[derive(Clone, Copy, Debug)]
pub struct TouchPoint {
pub id: TouchId,
pub point: TypedPoint2D<f32, DevicePixel>
}
impl TouchPoint {
pub fn new(id: TouchId, point: TypedPoint2D<f32, DevicePixel>) -> Self {
TouchPoint { id: id, point: point }
}
}
/// The states of the touch input state machine.
///
/// TODO: Add support for "flinging" (scrolling inertia)
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TouchState {
/// Not tracking any touch point
Nothing,
/// A touchstart event was dispatched to the page, but the response wasn't received yet.
/// Contains the initial touch point.
WaitingForScript,
/// Script is consuming the current touch sequence; don't perform default actions.
DefaultPrevented,
/// A single touch point is active and may perform click or pan default actions.
/// Contains the initial touch location.
Touching,
/// A single touch point is active and has started panning.
Panning,
/// A two-finger pinch zoom gesture is active.
Pinching,
/// A multi-touch gesture is in progress. Contains the number of active touch points.
MultiTouch,
}
/// The action to take in response to a touch event
#[derive(Clone, Copy, Debug)]
pub enum TouchAction {
/// Simulate a mouse click.
Click,
/// Scroll by the provided offset.
Scroll(TypedPoint2D<f32, DevicePixel>),
/// Zoom by a magnification factor and scroll by the provided offset.
Zoom(f32, TypedPoint2D<f32, DevicePixel>),
/// Send a JavaScript event to content.
DispatchEvent,
/// Don't do anything.
NoAction,
}
impl TouchHandler {
pub fn new() -> Self
|
pub fn on_touch_down(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>) {
let point = TouchPoint::new(id, point);
self.active_touch_points.push(point);
self.state = match self.state {
Nothing => WaitingForScript,
Touching | Panning => Pinching,
WaitingForScript => WaitingForScript,
DefaultPrevented => DefaultPrevented,
Pinching | MultiTouch => MultiTouch,
};
}
pub fn on_touch_move(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>)
-> TouchAction {
let idx = match self.active_touch_points.iter_mut().position(|t| t.id == id) {
Some(i) => i,
None => {
warn!("Got a touchmove event for a non-active touch point");
return TouchAction::NoAction;
}
};
let old_point = self.active_touch_points[idx].point;
let action = match self.state {
Touching => {
let delta = point - old_point;
// TODO let delta: TypedPoint2D<_, ScreenPx> = delta / self.device_pixels_per_screen_px();
if delta.x.abs() > TOUCH_PAN_MIN_SCREEN_PX ||
delta.y.abs() > TOUCH_PAN_MIN_SCREEN_PX
{
self.state = Panning;
TouchAction::Scroll(delta)
} else {
TouchAction::NoAction
}
}
Panning => {
let delta = point - old_point;
TouchAction::Scroll(delta)
}
DefaultPrevented => {
TouchAction::DispatchEvent
}
Pinching => {
let (d0, c0) = self.pinch_distance_and_center();
self.active_touch_points[idx].point = point;
let (d1, c1) = self.pinch_distance_and_center();
let magnification = d1 / d0;
let scroll_delta = c1 - c0 * ScaleFactor::new(magnification);
TouchAction::Zoom(magnification, scroll_delta)
}
WaitingForScript => TouchAction::NoAction,
MultiTouch => TouchAction::NoAction,
Nothing => unreachable!(),
};
// If we're still waiting to see whether this is a click or pan, remember the original
// location. Otherwise, update the touch point with the latest location.
if self.state!= Touching && self.state!= WaitingForScript {
self.active_touch_points[idx].point = point;
}
action
}
pub fn on_touch_up(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>)
-> TouchAction {
match self.active_touch_points.iter().position(|t| t.id == id) {
Some(i) => {
self.active_touch_points.swap_remove(i);
}
None => {
warn!("Got a touch up event for a non-active touch point");
}
}
match self.state {
Touching => {
// FIXME: If the duration exceeds some threshold, send a contextmenu event instead.
// FIXME: Don't send a click if preventDefault is called on the touchend event.
self.state = Nothing;
TouchAction::Click
}
Nothing | Panning => {
self.state = Nothing;
TouchAction::NoAction
}
Pinching => {
self.state = Panning;
TouchAction::NoAction
}
WaitingForScript | DefaultPrevented | MultiTouch => {
if self.active_touch_points.is_empty() {
self.state = Nothing;
}
TouchAction::NoAction
}
}
}
pub fn on_touch_cancel(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>) {
match self.active_touch_points.iter().position(|t| t.id == id) {
Some(i) => {
self.active_touch_points.swap_remove(i);
}
None => {
warn!("Got a touchcancel event for a non-active touch point");
return;
}
}
match self.state {
Nothing => {}
Touching | Panning => {
self.state = Nothing;
}
Pinching => {
self.state = Panning;
}
WaitingForScript | DefaultPrevented | MultiTouch => {
if self.active_touch_points.is_empty() {
self.state = Nothing;
}
}
}
}
pub fn on_event_processed(&mut self, result: EventResult) {
if let WaitingForScript = self.state {
self.state = match result {
EventResult::DefaultPrevented => DefaultPrevented,
EventResult::DefaultAllowed => match self.touch_count() {
1 => Touching,
2 => Pinching,
_ => MultiTouch,
}
}
}
}
fn touch_count(&self) -> usize {
self.active_touch_points.len()
}
fn pinch_distance_and_center(&self) -> (f32, TypedPoint2D<f32, DevicePixel>) {
debug_assert!(self.touch_count() == 2);
let p0 = self.active_touch_points[0].point;
let p1 = self.active_touch_points[1].point;
let center = (p0 + p1) / ScaleFactor::new(2.0);
let d = p0 - p1;
let distance = f32::sqrt(d.x * d.x + d.y * d.y);
(distance, center)
}
}
|
{
TouchHandler {
state: Nothing,
active_touch_points: Vec::new(),
}
}
|
identifier_body
|
touch.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 euclid::point::TypedPoint2D;
use euclid::scale_factor::ScaleFactor;
use gfx_traits::DevicePixel;
use script_traits::{EventResult, TouchId};
use self::TouchState::*;
/// Minimum number of ScreenPx to begin touch scrolling.
const TOUCH_PAN_MIN_SCREEN_PX: f32 = 20.0;
pub struct TouchHandler {
pub state: TouchState,
pub active_touch_points: Vec<TouchPoint>,
}
#[derive(Clone, Copy, Debug)]
pub struct TouchPoint {
pub id: TouchId,
pub point: TypedPoint2D<f32, DevicePixel>
}
impl TouchPoint {
pub fn new(id: TouchId, point: TypedPoint2D<f32, DevicePixel>) -> Self {
TouchPoint { id: id, point: point }
}
}
/// The states of the touch input state machine.
///
/// TODO: Add support for "flinging" (scrolling inertia)
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TouchState {
/// Not tracking any touch point
Nothing,
/// A touchstart event was dispatched to the page, but the response wasn't received yet.
/// Contains the initial touch point.
WaitingForScript,
/// Script is consuming the current touch sequence; don't perform default actions.
DefaultPrevented,
/// A single touch point is active and may perform click or pan default actions.
/// Contains the initial touch location.
Touching,
/// A single touch point is active and has started panning.
Panning,
/// A two-finger pinch zoom gesture is active.
Pinching,
/// A multi-touch gesture is in progress. Contains the number of active touch points.
MultiTouch,
}
/// The action to take in response to a touch event
#[derive(Clone, Copy, Debug)]
pub enum TouchAction {
/// Simulate a mouse click.
Click,
/// Scroll by the provided offset.
Scroll(TypedPoint2D<f32, DevicePixel>),
/// Zoom by a magnification factor and scroll by the provided offset.
Zoom(f32, TypedPoint2D<f32, DevicePixel>),
/// Send a JavaScript event to content.
DispatchEvent,
/// Don't do anything.
NoAction,
}
impl TouchHandler {
pub fn new() -> Self {
TouchHandler {
state: Nothing,
active_touch_points: Vec::new(),
}
}
pub fn on_touch_down(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>) {
let point = TouchPoint::new(id, point);
self.active_touch_points.push(point);
self.state = match self.state {
Nothing => WaitingForScript,
Touching | Panning => Pinching,
WaitingForScript => WaitingForScript,
DefaultPrevented => DefaultPrevented,
Pinching | MultiTouch => MultiTouch,
};
}
pub fn on_touch_move(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>)
-> TouchAction {
let idx = match self.active_touch_points.iter_mut().position(|t| t.id == id) {
Some(i) => i,
None => {
warn!("Got a touchmove event for a non-active touch point");
return TouchAction::NoAction;
}
};
let old_point = self.active_touch_points[idx].point;
let action = match self.state {
Touching => {
let delta = point - old_point;
// TODO let delta: TypedPoint2D<_, ScreenPx> = delta / self.device_pixels_per_screen_px();
if delta.x.abs() > TOUCH_PAN_MIN_SCREEN_PX ||
delta.y.abs() > TOUCH_PAN_MIN_SCREEN_PX
{
self.state = Panning;
TouchAction::Scroll(delta)
} else {
TouchAction::NoAction
}
}
Panning => {
let delta = point - old_point;
TouchAction::Scroll(delta)
}
DefaultPrevented => {
TouchAction::DispatchEvent
}
Pinching => {
let (d0, c0) = self.pinch_distance_and_center();
self.active_touch_points[idx].point = point;
let (d1, c1) = self.pinch_distance_and_center();
let magnification = d1 / d0;
let scroll_delta = c1 - c0 * ScaleFactor::new(magnification);
TouchAction::Zoom(magnification, scroll_delta)
}
WaitingForScript => TouchAction::NoAction,
MultiTouch => TouchAction::NoAction,
Nothing => unreachable!(),
};
// If we're still waiting to see whether this is a click or pan, remember the original
// location. Otherwise, update the touch point with the latest location.
if self.state!= Touching && self.state!= WaitingForScript {
self.active_touch_points[idx].point = point;
}
action
}
|
pub fn on_touch_up(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>)
-> TouchAction {
match self.active_touch_points.iter().position(|t| t.id == id) {
Some(i) => {
self.active_touch_points.swap_remove(i);
}
None => {
warn!("Got a touch up event for a non-active touch point");
}
}
match self.state {
Touching => {
// FIXME: If the duration exceeds some threshold, send a contextmenu event instead.
// FIXME: Don't send a click if preventDefault is called on the touchend event.
self.state = Nothing;
TouchAction::Click
}
Nothing | Panning => {
self.state = Nothing;
TouchAction::NoAction
}
Pinching => {
self.state = Panning;
TouchAction::NoAction
}
WaitingForScript | DefaultPrevented | MultiTouch => {
if self.active_touch_points.is_empty() {
self.state = Nothing;
}
TouchAction::NoAction
}
}
}
pub fn on_touch_cancel(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>) {
match self.active_touch_points.iter().position(|t| t.id == id) {
Some(i) => {
self.active_touch_points.swap_remove(i);
}
None => {
warn!("Got a touchcancel event for a non-active touch point");
return;
}
}
match self.state {
Nothing => {}
Touching | Panning => {
self.state = Nothing;
}
Pinching => {
self.state = Panning;
}
WaitingForScript | DefaultPrevented | MultiTouch => {
if self.active_touch_points.is_empty() {
self.state = Nothing;
}
}
}
}
pub fn on_event_processed(&mut self, result: EventResult) {
if let WaitingForScript = self.state {
self.state = match result {
EventResult::DefaultPrevented => DefaultPrevented,
EventResult::DefaultAllowed => match self.touch_count() {
1 => Touching,
2 => Pinching,
_ => MultiTouch,
}
}
}
}
fn touch_count(&self) -> usize {
self.active_touch_points.len()
}
fn pinch_distance_and_center(&self) -> (f32, TypedPoint2D<f32, DevicePixel>) {
debug_assert!(self.touch_count() == 2);
let p0 = self.active_touch_points[0].point;
let p1 = self.active_touch_points[1].point;
let center = (p0 + p1) / ScaleFactor::new(2.0);
let d = p0 - p1;
let distance = f32::sqrt(d.x * d.x + d.y * d.y);
(distance, center)
}
}
|
random_line_split
|
|
touch.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 euclid::point::TypedPoint2D;
use euclid::scale_factor::ScaleFactor;
use gfx_traits::DevicePixel;
use script_traits::{EventResult, TouchId};
use self::TouchState::*;
/// Minimum number of ScreenPx to begin touch scrolling.
const TOUCH_PAN_MIN_SCREEN_PX: f32 = 20.0;
pub struct TouchHandler {
pub state: TouchState,
pub active_touch_points: Vec<TouchPoint>,
}
#[derive(Clone, Copy, Debug)]
pub struct TouchPoint {
pub id: TouchId,
pub point: TypedPoint2D<f32, DevicePixel>
}
impl TouchPoint {
pub fn new(id: TouchId, point: TypedPoint2D<f32, DevicePixel>) -> Self {
TouchPoint { id: id, point: point }
}
}
/// The states of the touch input state machine.
///
/// TODO: Add support for "flinging" (scrolling inertia)
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TouchState {
/// Not tracking any touch point
Nothing,
/// A touchstart event was dispatched to the page, but the response wasn't received yet.
/// Contains the initial touch point.
WaitingForScript,
/// Script is consuming the current touch sequence; don't perform default actions.
DefaultPrevented,
/// A single touch point is active and may perform click or pan default actions.
/// Contains the initial touch location.
Touching,
/// A single touch point is active and has started panning.
Panning,
/// A two-finger pinch zoom gesture is active.
Pinching,
/// A multi-touch gesture is in progress. Contains the number of active touch points.
MultiTouch,
}
/// The action to take in response to a touch event
#[derive(Clone, Copy, Debug)]
pub enum TouchAction {
/// Simulate a mouse click.
Click,
/// Scroll by the provided offset.
Scroll(TypedPoint2D<f32, DevicePixel>),
/// Zoom by a magnification factor and scroll by the provided offset.
Zoom(f32, TypedPoint2D<f32, DevicePixel>),
/// Send a JavaScript event to content.
DispatchEvent,
/// Don't do anything.
NoAction,
}
impl TouchHandler {
pub fn new() -> Self {
TouchHandler {
state: Nothing,
active_touch_points: Vec::new(),
}
}
pub fn
|
(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>) {
let point = TouchPoint::new(id, point);
self.active_touch_points.push(point);
self.state = match self.state {
Nothing => WaitingForScript,
Touching | Panning => Pinching,
WaitingForScript => WaitingForScript,
DefaultPrevented => DefaultPrevented,
Pinching | MultiTouch => MultiTouch,
};
}
pub fn on_touch_move(&mut self, id: TouchId, point: TypedPoint2D<f32, DevicePixel>)
-> TouchAction {
let idx = match self.active_touch_points.iter_mut().position(|t| t.id == id) {
Some(i) => i,
None => {
warn!("Got a touchmove event for a non-active touch point");
return TouchAction::NoAction;
}
};
let old_point = self.active_touch_points[idx].point;
let action = match self.state {
Touching => {
let delta = point - old_point;
// TODO let delta: TypedPoint2D<_, ScreenPx> = delta / self.device_pixels_per_screen_px();
if delta.x.abs() > TOUCH_PAN_MIN_SCREEN_PX ||
delta.y.abs() > TOUCH_PAN_MIN_SCREEN_PX
{
self.state = Panning;
TouchAction::Scroll(delta)
} else {
TouchAction::NoAction
}
}
Panning => {
let delta = point - old_point;
TouchAction::Scroll(delta)
}
DefaultPrevented => {
TouchAction::DispatchEvent
}
Pinching => {
let (d0, c0) = self.pinch_distance_and_center();
self.active_touch_points[idx].point = point;
let (d1, c1) = self.pinch_distance_and_center();
let magnification = d1 / d0;
let scroll_delta = c1 - c0 * ScaleFactor::new(magnification);
TouchAction::Zoom(magnification, scroll_delta)
}
WaitingForScript => TouchAction::NoAction,
MultiTouch => TouchAction::NoAction,
Nothing => unreachable!(),
};
// If we're still waiting to see whether this is a click or pan, remember the original
// location. Otherwise, update the touch point with the latest location.
if self.state!= Touching && self.state!= WaitingForScript {
self.active_touch_points[idx].point = point;
}
action
}
pub fn on_touch_up(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>)
-> TouchAction {
match self.active_touch_points.iter().position(|t| t.id == id) {
Some(i) => {
self.active_touch_points.swap_remove(i);
}
None => {
warn!("Got a touch up event for a non-active touch point");
}
}
match self.state {
Touching => {
// FIXME: If the duration exceeds some threshold, send a contextmenu event instead.
// FIXME: Don't send a click if preventDefault is called on the touchend event.
self.state = Nothing;
TouchAction::Click
}
Nothing | Panning => {
self.state = Nothing;
TouchAction::NoAction
}
Pinching => {
self.state = Panning;
TouchAction::NoAction
}
WaitingForScript | DefaultPrevented | MultiTouch => {
if self.active_touch_points.is_empty() {
self.state = Nothing;
}
TouchAction::NoAction
}
}
}
pub fn on_touch_cancel(&mut self, id: TouchId, _point: TypedPoint2D<f32, DevicePixel>) {
match self.active_touch_points.iter().position(|t| t.id == id) {
Some(i) => {
self.active_touch_points.swap_remove(i);
}
None => {
warn!("Got a touchcancel event for a non-active touch point");
return;
}
}
match self.state {
Nothing => {}
Touching | Panning => {
self.state = Nothing;
}
Pinching => {
self.state = Panning;
}
WaitingForScript | DefaultPrevented | MultiTouch => {
if self.active_touch_points.is_empty() {
self.state = Nothing;
}
}
}
}
pub fn on_event_processed(&mut self, result: EventResult) {
if let WaitingForScript = self.state {
self.state = match result {
EventResult::DefaultPrevented => DefaultPrevented,
EventResult::DefaultAllowed => match self.touch_count() {
1 => Touching,
2 => Pinching,
_ => MultiTouch,
}
}
}
}
fn touch_count(&self) -> usize {
self.active_touch_points.len()
}
fn pinch_distance_and_center(&self) -> (f32, TypedPoint2D<f32, DevicePixel>) {
debug_assert!(self.touch_count() == 2);
let p0 = self.active_touch_points[0].point;
let p1 = self.active_touch_points[1].point;
let center = (p0 + p1) / ScaleFactor::new(2.0);
let d = p0 - p1;
let distance = f32::sqrt(d.x * d.x + d.y * d.y);
(distance, center)
}
}
|
on_touch_down
|
identifier_name
|
ez_rpc.rs
|
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use rpc_capnp::{message, return_};
use capnp::private::capability::{ClientHook};
use capnp::capability::{FromClientHook, Server};
use rpc::{RpcConnectionState, RpcEvent};
use capability::{LocalClient};
pub struct EzRpcClient {
rpc_chan : ::std::sync::mpsc::Sender<RpcEvent>,
tcp : ::std::net::TcpStream,
}
impl Drop for EzRpcClient {
fn drop(&mut self) {
self.rpc_chan.send(RpcEvent::Shutdown).is_ok();
//self.tcp.close_read().is_ok();
}
}
struct EmptyCap;
impl Server for EmptyCap {
fn dispatch_call(&mut self, _interface_id : u64, _method_id : u16,
context : ::capnp::capability::CallContext<::capnp::any_pointer::Reader,
::capnp::any_pointer::Builder>) {
context.fail("Attempted to call a method on an empty capability.".to_string());
}
}
impl EzRpcClient {
pub fn new<A: ::std::net::ToSocketAddrs>(server_address : A) -> ::std::io::Result<EzRpcClient> {
let tcp = try!(::std::net::TcpStream::connect(server_address));
let connection_state = RpcConnectionState::new();
let empty_cap = Box::new(EmptyCap);
let bootstrap = Box::new(LocalClient::new(empty_cap));
let chan = connection_state.run(try!(tcp.try_clone()),
try!(tcp.try_clone()),
bootstrap,
::capnp::message::ReaderOptions::new());
return Ok(EzRpcClient { rpc_chan : chan, tcp : tcp });
}
pub fn get_main<T : FromClientHook>(&mut self) -> T {
let mut message = Box::new(::capnp::message::Builder::new_default());
{
message.init_root::<message::Builder>().init_bootstrap();
}
let (outgoing, answer_port, _question_port) = RpcEvent::new_outgoing(message);
self.rpc_chan.send(RpcEvent::Outgoing(outgoing)).unwrap();
let mut response_hook = answer_port.recv().unwrap();
let message : message::Reader = response_hook.get().get_as().unwrap();
let client = match message.which() {
Ok(message::Return(Ok(ret))) => {
match ret.which() {
Ok(return_::Results(Ok(payload))) => {
payload.get_content().get_as_capability::<T>().unwrap()
}
_ =>
|
}
}
_ => {panic!()}
};
return client;
}
}
pub struct EzRpcServer {
tcp_listener : ::std::net::TcpListener,
}
impl EzRpcServer {
pub fn new<A: ::std::net::ToSocketAddrs>(bind_address : A) -> ::std::io::Result<EzRpcServer> {
let tcp_listener = try!(::std::net::TcpListener::bind(bind_address));
Ok(EzRpcServer { tcp_listener : tcp_listener })
}
pub fn serve<'a>(self, bootstrap_interface : Box<Server + Send>) {
let server = self;
let bootstrap_interface = Box::new(LocalClient::new(bootstrap_interface));
for stream_result in server.tcp_listener.incoming() {
let bootstrap_interface = bootstrap_interface.copy();
let tcp = stream_result.unwrap();
::std::thread::spawn(move || {
let connection_state = RpcConnectionState::new();
let _rpc_chan = connection_state.run(
tcp.try_clone().unwrap(),
tcp,
bootstrap_interface,
::capnp::message::ReaderOptions::new());
});
}
}
}
|
{ panic!() }
|
conditional_block
|
ez_rpc.rs
|
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use rpc_capnp::{message, return_};
use capnp::private::capability::{ClientHook};
use capnp::capability::{FromClientHook, Server};
use rpc::{RpcConnectionState, RpcEvent};
use capability::{LocalClient};
pub struct EzRpcClient {
rpc_chan : ::std::sync::mpsc::Sender<RpcEvent>,
tcp : ::std::net::TcpStream,
}
impl Drop for EzRpcClient {
fn drop(&mut self) {
self.rpc_chan.send(RpcEvent::Shutdown).is_ok();
//self.tcp.close_read().is_ok();
}
}
struct
|
;
impl Server for EmptyCap {
fn dispatch_call(&mut self, _interface_id : u64, _method_id : u16,
context : ::capnp::capability::CallContext<::capnp::any_pointer::Reader,
::capnp::any_pointer::Builder>) {
context.fail("Attempted to call a method on an empty capability.".to_string());
}
}
impl EzRpcClient {
pub fn new<A: ::std::net::ToSocketAddrs>(server_address : A) -> ::std::io::Result<EzRpcClient> {
let tcp = try!(::std::net::TcpStream::connect(server_address));
let connection_state = RpcConnectionState::new();
let empty_cap = Box::new(EmptyCap);
let bootstrap = Box::new(LocalClient::new(empty_cap));
let chan = connection_state.run(try!(tcp.try_clone()),
try!(tcp.try_clone()),
bootstrap,
::capnp::message::ReaderOptions::new());
return Ok(EzRpcClient { rpc_chan : chan, tcp : tcp });
}
pub fn get_main<T : FromClientHook>(&mut self) -> T {
let mut message = Box::new(::capnp::message::Builder::new_default());
{
message.init_root::<message::Builder>().init_bootstrap();
}
let (outgoing, answer_port, _question_port) = RpcEvent::new_outgoing(message);
self.rpc_chan.send(RpcEvent::Outgoing(outgoing)).unwrap();
let mut response_hook = answer_port.recv().unwrap();
let message : message::Reader = response_hook.get().get_as().unwrap();
let client = match message.which() {
Ok(message::Return(Ok(ret))) => {
match ret.which() {
Ok(return_::Results(Ok(payload))) => {
payload.get_content().get_as_capability::<T>().unwrap()
}
_ => { panic!() }
}
}
_ => {panic!()}
};
return client;
}
}
pub struct EzRpcServer {
tcp_listener : ::std::net::TcpListener,
}
impl EzRpcServer {
pub fn new<A: ::std::net::ToSocketAddrs>(bind_address : A) -> ::std::io::Result<EzRpcServer> {
let tcp_listener = try!(::std::net::TcpListener::bind(bind_address));
Ok(EzRpcServer { tcp_listener : tcp_listener })
}
pub fn serve<'a>(self, bootstrap_interface : Box<Server + Send>) {
let server = self;
let bootstrap_interface = Box::new(LocalClient::new(bootstrap_interface));
for stream_result in server.tcp_listener.incoming() {
let bootstrap_interface = bootstrap_interface.copy();
let tcp = stream_result.unwrap();
::std::thread::spawn(move || {
let connection_state = RpcConnectionState::new();
let _rpc_chan = connection_state.run(
tcp.try_clone().unwrap(),
tcp,
bootstrap_interface,
::capnp::message::ReaderOptions::new());
});
}
}
}
|
EmptyCap
|
identifier_name
|
ez_rpc.rs
|
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use rpc_capnp::{message, return_};
use capnp::private::capability::{ClientHook};
use capnp::capability::{FromClientHook, Server};
use rpc::{RpcConnectionState, RpcEvent};
use capability::{LocalClient};
pub struct EzRpcClient {
rpc_chan : ::std::sync::mpsc::Sender<RpcEvent>,
tcp : ::std::net::TcpStream,
}
impl Drop for EzRpcClient {
fn drop(&mut self) {
self.rpc_chan.send(RpcEvent::Shutdown).is_ok();
//self.tcp.close_read().is_ok();
}
}
struct EmptyCap;
impl Server for EmptyCap {
fn dispatch_call(&mut self, _interface_id : u64, _method_id : u16,
context : ::capnp::capability::CallContext<::capnp::any_pointer::Reader,
::capnp::any_pointer::Builder>) {
context.fail("Attempted to call a method on an empty capability.".to_string());
}
}
impl EzRpcClient {
pub fn new<A: ::std::net::ToSocketAddrs>(server_address : A) -> ::std::io::Result<EzRpcClient> {
let tcp = try!(::std::net::TcpStream::connect(server_address));
let connection_state = RpcConnectionState::new();
let empty_cap = Box::new(EmptyCap);
let bootstrap = Box::new(LocalClient::new(empty_cap));
let chan = connection_state.run(try!(tcp.try_clone()),
try!(tcp.try_clone()),
bootstrap,
::capnp::message::ReaderOptions::new());
return Ok(EzRpcClient { rpc_chan : chan, tcp : tcp });
}
pub fn get_main<T : FromClientHook>(&mut self) -> T {
let mut message = Box::new(::capnp::message::Builder::new_default());
{
message.init_root::<message::Builder>().init_bootstrap();
}
let (outgoing, answer_port, _question_port) = RpcEvent::new_outgoing(message);
self.rpc_chan.send(RpcEvent::Outgoing(outgoing)).unwrap();
let mut response_hook = answer_port.recv().unwrap();
let message : message::Reader = response_hook.get().get_as().unwrap();
let client = match message.which() {
Ok(message::Return(Ok(ret))) => {
match ret.which() {
Ok(return_::Results(Ok(payload))) => {
|
}
_ => {panic!()}
};
return client;
}
}
pub struct EzRpcServer {
tcp_listener : ::std::net::TcpListener,
}
impl EzRpcServer {
pub fn new<A: ::std::net::ToSocketAddrs>(bind_address : A) -> ::std::io::Result<EzRpcServer> {
let tcp_listener = try!(::std::net::TcpListener::bind(bind_address));
Ok(EzRpcServer { tcp_listener : tcp_listener })
}
pub fn serve<'a>(self, bootstrap_interface : Box<Server + Send>) {
let server = self;
let bootstrap_interface = Box::new(LocalClient::new(bootstrap_interface));
for stream_result in server.tcp_listener.incoming() {
let bootstrap_interface = bootstrap_interface.copy();
let tcp = stream_result.unwrap();
::std::thread::spawn(move || {
let connection_state = RpcConnectionState::new();
let _rpc_chan = connection_state.run(
tcp.try_clone().unwrap(),
tcp,
bootstrap_interface,
::capnp::message::ReaderOptions::new());
});
}
}
}
|
payload.get_content().get_as_capability::<T>().unwrap()
}
_ => { panic!() }
}
|
random_line_split
|
lib.rs
|
//! Functionality for working with SIMD registers and instructions.
//!
//! [Source](https://github.com/huonw/simd), [crates.io](https://crates.io/crates/simd)
#![feature(trace_macros, link_llvm_intrinsics, simd_ffi,
core)]
extern crate simdty;
extern crate llvmint;
use std::mem;
pub use convert::bitcast::Bitcast;
pub use convert::semantic::{Convert, Tails, TailsMut};
mod convert;
mod generated;
pub mod maths;
/// A SIMD vector, storing precisely `count()` elements of (primitive)
/// type `Item` sequentially in memory.
///
/// This trait is `unsafe` because it is used inside `unsafe` code
/// relying on the correctness of `Item` and `count()`.
pub unsafe trait Vector: Sized + Copy {
/// The type that this vector contains.
type Item;
/// Return the number of items in `self`.
#[inline(always)]
fn count(_: Option<Self>) -> usize {
let vsize = mem::size_of::<Self>();
let esize = mem::size_of::<Self::Item>();
assert!(vsize % esize == 0);
vsize / esize
}
}
/// SIMD vectors which can be separated into two SIMD vectors of half
/// the size with the same elements.
pub unsafe trait HalfVector: Vector {
type Half /*: Vector<Item = Self::Item>*/;
/// Retrieve the upper and lower halves of the `self` vector.
fn split(self) -> (Self::Half, Self::Half);
/// Retrieve the lower half of the `self` vector.
#[inline]
fn lower(self) -> Self::Half { self.split().0 }
/// Retrieve the upper half of the `self` vector.
#[inline]
fn upper(self) -> Self::Half { self.split().1 }
}
/// SIMD vectors which can be merged with another of the same type to
/// create one of double the length with the same elements.
pub unsafe trait DoubleVector: Vector {
type Double /*: Vector<Item = Self::Item>*/;
/// Concatenate the elements of `self` and `other` into a single
/// SIMD vector.
fn merge(self, other: Self) -> Self::Double;
}
/// Return a platform-specific approximation to the square root of
/// `x`.
#[inline]
pub fn
|
<T: maths::sqrt::Sqrt>(x: T) -> T {
x.sqrt()
}
/// Return a platform-specific approximation to the reciprocal-square
/// root of `x`.
#[inline]
pub fn rsqrt<T: maths::sqrt::RSqrt>(x: T) -> T {
x.rsqrt()
}
|
sqrt
|
identifier_name
|
lib.rs
|
//! Functionality for working with SIMD registers and instructions.
//!
//! [Source](https://github.com/huonw/simd), [crates.io](https://crates.io/crates/simd)
#![feature(trace_macros, link_llvm_intrinsics, simd_ffi,
core)]
extern crate simdty;
extern crate llvmint;
use std::mem;
pub use convert::bitcast::Bitcast;
pub use convert::semantic::{Convert, Tails, TailsMut};
mod convert;
mod generated;
pub mod maths;
/// A SIMD vector, storing precisely `count()` elements of (primitive)
/// type `Item` sequentially in memory.
///
/// This trait is `unsafe` because it is used inside `unsafe` code
/// relying on the correctness of `Item` and `count()`.
pub unsafe trait Vector: Sized + Copy {
/// The type that this vector contains.
type Item;
|
let vsize = mem::size_of::<Self>();
let esize = mem::size_of::<Self::Item>();
assert!(vsize % esize == 0);
vsize / esize
}
}
/// SIMD vectors which can be separated into two SIMD vectors of half
/// the size with the same elements.
pub unsafe trait HalfVector: Vector {
type Half /*: Vector<Item = Self::Item>*/;
/// Retrieve the upper and lower halves of the `self` vector.
fn split(self) -> (Self::Half, Self::Half);
/// Retrieve the lower half of the `self` vector.
#[inline]
fn lower(self) -> Self::Half { self.split().0 }
/// Retrieve the upper half of the `self` vector.
#[inline]
fn upper(self) -> Self::Half { self.split().1 }
}
/// SIMD vectors which can be merged with another of the same type to
/// create one of double the length with the same elements.
pub unsafe trait DoubleVector: Vector {
type Double /*: Vector<Item = Self::Item>*/;
/// Concatenate the elements of `self` and `other` into a single
/// SIMD vector.
fn merge(self, other: Self) -> Self::Double;
}
/// Return a platform-specific approximation to the square root of
/// `x`.
#[inline]
pub fn sqrt<T: maths::sqrt::Sqrt>(x: T) -> T {
x.sqrt()
}
/// Return a platform-specific approximation to the reciprocal-square
/// root of `x`.
#[inline]
pub fn rsqrt<T: maths::sqrt::RSqrt>(x: T) -> T {
x.rsqrt()
}
|
/// Return the number of items in `self`.
#[inline(always)]
fn count(_: Option<Self>) -> usize {
|
random_line_split
|
lib.rs
|
//! Functionality for working with SIMD registers and instructions.
//!
//! [Source](https://github.com/huonw/simd), [crates.io](https://crates.io/crates/simd)
#![feature(trace_macros, link_llvm_intrinsics, simd_ffi,
core)]
extern crate simdty;
extern crate llvmint;
use std::mem;
pub use convert::bitcast::Bitcast;
pub use convert::semantic::{Convert, Tails, TailsMut};
mod convert;
mod generated;
pub mod maths;
/// A SIMD vector, storing precisely `count()` elements of (primitive)
/// type `Item` sequentially in memory.
///
/// This trait is `unsafe` because it is used inside `unsafe` code
/// relying on the correctness of `Item` and `count()`.
pub unsafe trait Vector: Sized + Copy {
/// The type that this vector contains.
type Item;
/// Return the number of items in `self`.
#[inline(always)]
fn count(_: Option<Self>) -> usize {
let vsize = mem::size_of::<Self>();
let esize = mem::size_of::<Self::Item>();
assert!(vsize % esize == 0);
vsize / esize
}
}
/// SIMD vectors which can be separated into two SIMD vectors of half
/// the size with the same elements.
pub unsafe trait HalfVector: Vector {
type Half /*: Vector<Item = Self::Item>*/;
/// Retrieve the upper and lower halves of the `self` vector.
fn split(self) -> (Self::Half, Self::Half);
/// Retrieve the lower half of the `self` vector.
#[inline]
fn lower(self) -> Self::Half { self.split().0 }
/// Retrieve the upper half of the `self` vector.
#[inline]
fn upper(self) -> Self::Half
|
}
/// SIMD vectors which can be merged with another of the same type to
/// create one of double the length with the same elements.
pub unsafe trait DoubleVector: Vector {
type Double /*: Vector<Item = Self::Item>*/;
/// Concatenate the elements of `self` and `other` into a single
/// SIMD vector.
fn merge(self, other: Self) -> Self::Double;
}
/// Return a platform-specific approximation to the square root of
/// `x`.
#[inline]
pub fn sqrt<T: maths::sqrt::Sqrt>(x: T) -> T {
x.sqrt()
}
/// Return a platform-specific approximation to the reciprocal-square
/// root of `x`.
#[inline]
pub fn rsqrt<T: maths::sqrt::RSqrt>(x: T) -> T {
x.rsqrt()
}
|
{ self.split().1 }
|
identifier_body
|
to_bits.rs
|
use malachite_base::num::logic::traits::{BitAccess, SignificantBits};
use malachite_nz::integer::Integer;
pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
for i in 0..n.significant_bits() {
bits.push(n.get_bit(i));
}
let last_bit = *bits.last().unwrap();
if last_bit!= (*n < 0) {
bits.push(!last_bit);
}
bits
}
pub fn to_bits_desc_naive(n: &Integer) -> Vec<bool>
|
{
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
let significant_bits = n.significant_bits();
let last_bit = n.get_bit(significant_bits - 1);
if last_bit != (*n < 0) {
bits.push(!last_bit);
}
for i in (0..significant_bits).rev() {
bits.push(n.get_bit(i));
}
bits
}
|
identifier_body
|
|
to_bits.rs
|
use malachite_base::num::logic::traits::{BitAccess, SignificantBits};
use malachite_nz::integer::Integer;
pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
for i in 0..n.significant_bits() {
bits.push(n.get_bit(i));
}
let last_bit = *bits.last().unwrap();
if last_bit!= (*n < 0)
|
bits
}
pub fn to_bits_desc_naive(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
let significant_bits = n.significant_bits();
let last_bit = n.get_bit(significant_bits - 1);
if last_bit!= (*n < 0) {
bits.push(!last_bit);
}
for i in (0..significant_bits).rev() {
bits.push(n.get_bit(i));
}
bits
}
|
{
bits.push(!last_bit);
}
|
conditional_block
|
to_bits.rs
|
use malachite_base::num::logic::traits::{BitAccess, SignificantBits};
use malachite_nz::integer::Integer;
pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
for i in 0..n.significant_bits() {
bits.push(n.get_bit(i));
}
let last_bit = *bits.last().unwrap();
if last_bit!= (*n < 0) {
bits.push(!last_bit);
}
bits
}
pub fn
|
(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
let significant_bits = n.significant_bits();
let last_bit = n.get_bit(significant_bits - 1);
if last_bit!= (*n < 0) {
bits.push(!last_bit);
}
for i in (0..significant_bits).rev() {
bits.push(n.get_bit(i));
}
bits
}
|
to_bits_desc_naive
|
identifier_name
|
to_bits.rs
|
use malachite_base::num::logic::traits::{BitAccess, SignificantBits};
use malachite_nz::integer::Integer;
pub fn to_bits_asc_naive(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
for i in 0..n.significant_bits() {
bits.push(n.get_bit(i));
}
let last_bit = *bits.last().unwrap();
if last_bit!= (*n < 0) {
bits.push(!last_bit);
}
bits
}
|
pub fn to_bits_desc_naive(n: &Integer) -> Vec<bool> {
let mut bits = Vec::new();
if *n == 0 {
return bits;
}
let significant_bits = n.significant_bits();
let last_bit = n.get_bit(significant_bits - 1);
if last_bit!= (*n < 0) {
bits.push(!last_bit);
}
for i in (0..significant_bits).rev() {
bits.push(n.get_bit(i));
}
bits
}
|
random_line_split
|
|
main.rs
|
//! Requires the 'framework' feature flag be enabled in your project's
//! `Cargo.toml`.
//!
//! This can be enabled by specifying the feature in the dependency section:
//!
//! ```toml
//! [dependencies.serenity]
//! git = "https://github.com/serenity-rs/serenity.git"
//! features = ["framework", "standard_framework"]
//! ```
mod commands;
use std::{collections::HashSet, env, sync::Arc};
use commands::{math::*, meta::*, owner::*};
use serenity::{
async_trait,
client::bridge::gateway::ShardManager,
framework::{standard::macros::group, StandardFramework},
http::Http,
model::{event::ResumedEvent, gateway::Ready},
prelude::*,
};
use tracing::{error, info};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
pub struct ShardManagerContainer;
impl TypeMapKey for ShardManagerContainer {
type Value = Arc<Mutex<ShardManager>>;
}
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, _: Context, ready: Ready) {
info!("Connected as {}", ready.user.name);
}
async fn resume(&self, _: Context, _: ResumedEvent)
|
}
#[group]
#[commands(multiply, ping, quit)]
struct General;
#[tokio::main]
async fn main() {
// This will load the environment variables located at `./.env`, relative to
// the CWD. See `./.env.example` for an example on how to structure this.
dotenv::dotenv().expect("Failed to load.env file");
// Initialize the logger to use environment variables.
//
// In this case, a good default is setting the environment variable
// `RUST_LOG` to debug`.
let subscriber =
FmtSubscriber::builder().with_env_filter(EnvFilter::from_default_env()).finish();
tracing::subscriber::set_global_default(subscriber).expect("Failed to start the logger");
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let http = Http::new_with_token(&token);
// We will fetch your bot's owners and id
let (owners, _bot_id) = match http.get_current_application_info().await {
Ok(info) => {
let mut owners = HashSet::new();
owners.insert(info.owner.id);
(owners, info.id)
},
Err(why) => panic!("Could not access application info: {:?}", why),
};
// Create the framework
let framework =
StandardFramework::new().configure(|c| c.owners(owners).prefix("~")).group(&GENERAL_GROUP);
let mut client = Client::builder(&token)
.framework(framework)
.event_handler(Handler)
.await
.expect("Err creating client");
{
let mut data = client.data.write().await;
data.insert::<ShardManagerContainer>(client.shard_manager.clone());
}
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Could not register ctrl+c handler");
shard_manager.lock().await.shutdown_all().await;
});
if let Err(why) = client.start().await {
error!("Client error: {:?}", why);
}
}
|
{
info!("Resumed");
}
|
identifier_body
|
main.rs
|
//! Requires the 'framework' feature flag be enabled in your project's
//! `Cargo.toml`.
//!
//! This can be enabled by specifying the feature in the dependency section:
//!
//! ```toml
//! [dependencies.serenity]
//! git = "https://github.com/serenity-rs/serenity.git"
//! features = ["framework", "standard_framework"]
//! ```
mod commands;
use std::{collections::HashSet, env, sync::Arc};
use commands::{math::*, meta::*, owner::*};
use serenity::{
async_trait,
client::bridge::gateway::ShardManager,
framework::{standard::macros::group, StandardFramework},
http::Http,
model::{event::ResumedEvent, gateway::Ready},
prelude::*,
};
use tracing::{error, info};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
pub struct ShardManagerContainer;
impl TypeMapKey for ShardManagerContainer {
type Value = Arc<Mutex<ShardManager>>;
}
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn
|
(&self, _: Context, ready: Ready) {
info!("Connected as {}", ready.user.name);
}
async fn resume(&self, _: Context, _: ResumedEvent) {
info!("Resumed");
}
}
#[group]
#[commands(multiply, ping, quit)]
struct General;
#[tokio::main]
async fn main() {
// This will load the environment variables located at `./.env`, relative to
// the CWD. See `./.env.example` for an example on how to structure this.
dotenv::dotenv().expect("Failed to load.env file");
// Initialize the logger to use environment variables.
//
// In this case, a good default is setting the environment variable
// `RUST_LOG` to debug`.
let subscriber =
FmtSubscriber::builder().with_env_filter(EnvFilter::from_default_env()).finish();
tracing::subscriber::set_global_default(subscriber).expect("Failed to start the logger");
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let http = Http::new_with_token(&token);
// We will fetch your bot's owners and id
let (owners, _bot_id) = match http.get_current_application_info().await {
Ok(info) => {
let mut owners = HashSet::new();
owners.insert(info.owner.id);
(owners, info.id)
},
Err(why) => panic!("Could not access application info: {:?}", why),
};
// Create the framework
let framework =
StandardFramework::new().configure(|c| c.owners(owners).prefix("~")).group(&GENERAL_GROUP);
let mut client = Client::builder(&token)
.framework(framework)
.event_handler(Handler)
.await
.expect("Err creating client");
{
let mut data = client.data.write().await;
data.insert::<ShardManagerContainer>(client.shard_manager.clone());
}
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Could not register ctrl+c handler");
shard_manager.lock().await.shutdown_all().await;
});
if let Err(why) = client.start().await {
error!("Client error: {:?}", why);
}
}
|
ready
|
identifier_name
|
main.rs
|
//! Requires the 'framework' feature flag be enabled in your project's
//! `Cargo.toml`.
//!
//! This can be enabled by specifying the feature in the dependency section:
//!
//! ```toml
//! [dependencies.serenity]
//! git = "https://github.com/serenity-rs/serenity.git"
|
use commands::{math::*, meta::*, owner::*};
use serenity::{
async_trait,
client::bridge::gateway::ShardManager,
framework::{standard::macros::group, StandardFramework},
http::Http,
model::{event::ResumedEvent, gateway::Ready},
prelude::*,
};
use tracing::{error, info};
use tracing_subscriber::{EnvFilter, FmtSubscriber};
pub struct ShardManagerContainer;
impl TypeMapKey for ShardManagerContainer {
type Value = Arc<Mutex<ShardManager>>;
}
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, _: Context, ready: Ready) {
info!("Connected as {}", ready.user.name);
}
async fn resume(&self, _: Context, _: ResumedEvent) {
info!("Resumed");
}
}
#[group]
#[commands(multiply, ping, quit)]
struct General;
#[tokio::main]
async fn main() {
// This will load the environment variables located at `./.env`, relative to
// the CWD. See `./.env.example` for an example on how to structure this.
dotenv::dotenv().expect("Failed to load.env file");
// Initialize the logger to use environment variables.
//
// In this case, a good default is setting the environment variable
// `RUST_LOG` to debug`.
let subscriber =
FmtSubscriber::builder().with_env_filter(EnvFilter::from_default_env()).finish();
tracing::subscriber::set_global_default(subscriber).expect("Failed to start the logger");
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let http = Http::new_with_token(&token);
// We will fetch your bot's owners and id
let (owners, _bot_id) = match http.get_current_application_info().await {
Ok(info) => {
let mut owners = HashSet::new();
owners.insert(info.owner.id);
(owners, info.id)
},
Err(why) => panic!("Could not access application info: {:?}", why),
};
// Create the framework
let framework =
StandardFramework::new().configure(|c| c.owners(owners).prefix("~")).group(&GENERAL_GROUP);
let mut client = Client::builder(&token)
.framework(framework)
.event_handler(Handler)
.await
.expect("Err creating client");
{
let mut data = client.data.write().await;
data.insert::<ShardManagerContainer>(client.shard_manager.clone());
}
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Could not register ctrl+c handler");
shard_manager.lock().await.shutdown_all().await;
});
if let Err(why) = client.start().await {
error!("Client error: {:?}", why);
}
}
|
//! features = ["framework", "standard_framework"]
//! ```
mod commands;
use std::{collections::HashSet, env, sync::Arc};
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.