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 |
---|---|---|---|---|
app_chooser.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use glib::translate::{FromGlibPtr};
use gtk::{self, ffi};
use gtk::cast::GTK_APP_CHOOSER;
pub trait AppChooserTrait: gtk::WidgetTrait {
fn get_app_info(&self) -> Option<gtk::AppInfo> {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else
|
}
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}
|
{
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
|
conditional_block
|
app_chooser.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use glib::translate::{FromGlibPtr};
use gtk::{self, ffi};
use gtk::cast::GTK_APP_CHOOSER;
pub trait AppChooserTrait: gtk::WidgetTrait {
fn get_app_info(&self) -> Option<gtk::AppInfo> {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
fn
|
(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
}
|
get_content_info
|
identifier_name
|
macros.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/. */
//! Various macro helpers.
macro_rules! trivial_to_computed_value {
($name:ty) => {
impl $crate::values::computed::ToComputedValue for $name {
type ComputedValue = $name;
fn to_computed_value(&self, _: &$crate::values::computed::Context) -> Self {
self.clone()
}
fn from_computed_value(other: &Self) -> Self {
other.clone()
}
}
}
}
/// A macro to parse an identifier, or return an `UnexpectedIndent` error
/// otherwise.
///
/// FIXME(emilio): The fact that `UnexpectedIdent` is a `SelectorParseError`
/// doesn't make a lot of sense to me.
macro_rules! try_match_ident_ignore_ascii_case {
($input:expr, $( $match_body:tt )*) => {
let location = $input.current_source_location();
let ident = $input.expect_ident_cloned()?;
(match_ignore_ascii_case! { &ident,
$( $match_body )*
_ => Err(()),
})
.map_err(|()| {
location.new_custom_error(
::selectors::parser::SelectorParseErrorKind::UnexpectedIdent(ident.clone())
)
})
}
}
macro_rules! define_numbered_css_keyword_enum {
($name: ident: $( $css: expr => $variant: ident = $value: expr ),+,) => {
define_numbered_css_keyword_enum!($name: $( $css => $variant = $value ),+);
};
($name: ident: $( $css: expr => $variant: ident = $value: expr ),+) => {
#[allow(non_camel_case_types, missing_docs)]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))]
pub enum $name {
$( $variant = $value ),+
}
|
) -> Result<$name, ::style_traits::ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input,
$( $css => Ok($name::$variant), )+
}
}
}
impl ::style_traits::values::ToCss for $name {
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result
where
W: ::std::fmt::Write,
{
match *self {
$( $name::$variant => dest.write_str($css) ),+
}
}
}
}
}
/// A macro for implementing `ToComputedValue`, and `Parse` traits for
/// the enums defined using `define_css_keyword_enum` macro.
///
/// NOTE: We should either move `Parse` trait to `style_traits`
/// or `define_css_keyword_enum` macro to this crate, but that
/// may involve significant cleanup in both the crates.
macro_rules! add_impls_for_keyword_enum {
($name:ident) => {
impl $crate::parser::Parse for $name {
#[inline]
fn parse<'i, 't>(
_context: &$crate::parser::ParserContext,
input: &mut ::cssparser::Parser<'i, 't>,
) -> Result<Self, ::style_traits::ParseError<'i>> {
$name::parse(input)
}
}
trivial_to_computed_value!($name);
};
}
macro_rules! define_keyword_type {
($name: ident, $css: expr) => {
#[allow(missing_docs)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, PartialEq)]
#[derive(ToAnimatedZero, ToComputedValue, ToCss)]
pub struct $name;
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str($css)
}
}
impl $crate::parser::Parse for $name {
fn parse<'i, 't>(
_context: &$crate::parser::ParserContext,
input: &mut ::cssparser::Parser<'i, 't>
) -> Result<$name, ::style_traits::ParseError<'i>> {
input.expect_ident_matching($css).map(|_| $name).map_err(|e| e.into())
}
}
impl $crate::values::animated::AnimatedValueAsComputed for $name {}
};
}
|
impl $crate::parser::Parse for $name {
fn parse<'i, 't>(
_context: &$crate::parser::ParserContext,
input: &mut ::cssparser::Parser<'i, 't>,
|
random_line_split
|
auto-dedup.rs
|
// run-pass
#![allow(unused_assignments)]
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {}
// A dummy struct to implement `Trait` and `Send`.
struct Struct;
impl Trait for Struct {}
// These three functions should be equivalent.
fn takes_dyn_trait_send(_: Box<dyn Trait + Send>) {}
fn takes_dyn_trait_send_send(_: Box<dyn Trait + Send + Send>) {}
fn
|
(_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&self) {}
}
fn main() {
// 1. Moving into a variable with more `Send`s and back.
let mut dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
let dyn_trait_send_send: Box<dyn Trait + Send + Send> = dyn_trait_send;
dyn_trait_send = dyn_trait_send_send;
// 2. Calling methods with different number of `Send`s.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_send(dyn_trait_send);
let dyn_trait_send_send = Box::new(Struct) as Box<dyn Trait + Send + Send>;
takes_dyn_trait_send(dyn_trait_send_send);
// 3. Aliases to the trait are transparent.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_sendalias(dyn_trait_send);
// 4. Calling an impl that duplicates an auto trait.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
dyn_trait_send.do_nothing();
}
|
takes_dyn_trait_send_sendalias
|
identifier_name
|
auto-dedup.rs
|
// run-pass
#![allow(unused_assignments)]
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {}
// A dummy struct to implement `Trait` and `Send`.
struct Struct;
impl Trait for Struct {}
// These three functions should be equivalent.
fn takes_dyn_trait_send(_: Box<dyn Trait + Send>)
|
fn takes_dyn_trait_send_send(_: Box<dyn Trait + Send + Send>) {}
fn takes_dyn_trait_send_sendalias(_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&self) {}
}
fn main() {
// 1. Moving into a variable with more `Send`s and back.
let mut dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
let dyn_trait_send_send: Box<dyn Trait + Send + Send> = dyn_trait_send;
dyn_trait_send = dyn_trait_send_send;
// 2. Calling methods with different number of `Send`s.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_send(dyn_trait_send);
let dyn_trait_send_send = Box::new(Struct) as Box<dyn Trait + Send + Send>;
takes_dyn_trait_send(dyn_trait_send_send);
// 3. Aliases to the trait are transparent.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_sendalias(dyn_trait_send);
// 4. Calling an impl that duplicates an auto trait.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
dyn_trait_send.do_nothing();
}
|
{}
|
identifier_body
|
auto-dedup.rs
|
// run-pass
#![allow(unused_assignments)]
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {}
|
impl Trait for Struct {}
// These three functions should be equivalent.
fn takes_dyn_trait_send(_: Box<dyn Trait + Send>) {}
fn takes_dyn_trait_send_send(_: Box<dyn Trait + Send + Send>) {}
fn takes_dyn_trait_send_sendalias(_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&self) {}
}
fn main() {
// 1. Moving into a variable with more `Send`s and back.
let mut dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
let dyn_trait_send_send: Box<dyn Trait + Send + Send> = dyn_trait_send;
dyn_trait_send = dyn_trait_send_send;
// 2. Calling methods with different number of `Send`s.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_send(dyn_trait_send);
let dyn_trait_send_send = Box::new(Struct) as Box<dyn Trait + Send + Send>;
takes_dyn_trait_send(dyn_trait_send_send);
// 3. Aliases to the trait are transparent.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
takes_dyn_trait_send_sendalias(dyn_trait_send);
// 4. Calling an impl that duplicates an auto trait.
let dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
dyn_trait_send.do_nothing();
}
|
// A dummy struct to implement `Trait` and `Send`.
struct Struct;
|
random_line_split
|
endpoint.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! URL Endpoint traits
use hyper::{self, server, net};
|
pub host: String,
pub port: u16,
pub using_dapps_domains: bool,
}
#[derive(Debug, PartialEq, Clone)]
pub struct EndpointInfo {
pub name: String,
pub description: String,
pub version: String,
pub author: String,
pub icon_url: String,
}
pub type Endpoints = BTreeMap<String, Box<Endpoint>>;
pub type Handler = server::Handler<net::HttpStream> + Send;
pub trait Endpoint : Send + Sync {
fn info(&self) -> Option<&EndpointInfo> { None }
fn to_handler(&self, _path: EndpointPath) -> Box<Handler> {
panic!("This Endpoint is asynchronous and requires Control object.");
}
fn to_async_handler(&self, path: EndpointPath, _control: hyper::Control) -> Box<Handler> {
self.to_handler(path)
}
}
|
use std::collections::BTreeMap;
#[derive(Debug, PartialEq, Default, Clone)]
pub struct EndpointPath {
pub app_id: String,
|
random_line_split
|
endpoint.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! URL Endpoint traits
use hyper::{self, server, net};
use std::collections::BTreeMap;
#[derive(Debug, PartialEq, Default, Clone)]
pub struct EndpointPath {
pub app_id: String,
pub host: String,
pub port: u16,
pub using_dapps_domains: bool,
}
#[derive(Debug, PartialEq, Clone)]
pub struct EndpointInfo {
pub name: String,
pub description: String,
pub version: String,
pub author: String,
pub icon_url: String,
}
pub type Endpoints = BTreeMap<String, Box<Endpoint>>;
pub type Handler = server::Handler<net::HttpStream> + Send;
pub trait Endpoint : Send + Sync {
fn info(&self) -> Option<&EndpointInfo> { None }
fn to_handler(&self, _path: EndpointPath) -> Box<Handler> {
panic!("This Endpoint is asynchronous and requires Control object.");
}
fn
|
(&self, path: EndpointPath, _control: hyper::Control) -> Box<Handler> {
self.to_handler(path)
}
}
|
to_async_handler
|
identifier_name
|
main.rs
|
#[macro_use] extern crate libeuler;
use libeuler::prime::SieveOfAtkin;
/// The first two consecutive numbers to have two distinct prime factors are:
///
/// 14 = 2 × 7
/// 15 = 3 × 5
///
/// The first three consecutive numbers to have three distinct prime factors are:
///
/// 644 = 2² × 7 × 23
/// 645 = 3 × 5 × 43
/// 646 = 2 × 17 × 19.
///
/// Find the first four consecutive integers to have four distinct prime factors. What is the first
/// of these numbers?
fn main() {
sol
|
return first;
}
}
None
}
}
}
|
utions! {
inputs: (num: usize = 4)
sol naive {
let sieve = SieveOfAtkin::new(1_000_000);
let mut first = None;
let mut count = 0;
for i in 0..1_000_000 {
if sieve.factors(i).len() == num {
first = match first {
Some(v) => Some(v),
None => Some(i)
};
count += 1;
} else {
first = None;
count = 0;
}
if count == num {
|
identifier_body
|
main.rs
|
#[macro_use] extern crate libeuler;
use libeuler::prime::SieveOfAtkin;
/// The first two consecutive numbers to have two distinct prime factors are:
///
/// 14 = 2 × 7
/// 15 = 3 × 5
///
/// The first three consecutive numbers to have three distinct prime factors are:
///
/// 644 = 2² × 7 × 23
/// 645 = 3 × 5 × 43
/// 646 = 2 × 17 × 19.
///
/// Find the first four consecutive integers to have four distinct prime factors. What is the first
/// of these numbers?
fn main() {
solutions! {
inputs: (num: usize = 4)
sol naive {
let sieve = SieveOfAtkin::new(1_000_000);
let mut first = None;
let mut count = 0;
for i in 0..1_000_000 {
if sieve.factors(i).len() == num {
first = match first {
Some(v) => Some(v),
None => Some(i)
};
count += 1;
} else {
first = None;
count = 0;
}
|
if count == num {
return first;
}
}
None
}
}
}
|
random_line_split
|
|
main.rs
|
#[macro_use] extern crate libeuler;
use libeuler::prime::SieveOfAtkin;
/// The first two consecutive numbers to have two distinct prime factors are:
///
/// 14 = 2 × 7
/// 15 = 3 × 5
///
/// The first three consecutive numbers to have three distinct prime factors are:
///
/// 644 = 2² × 7 × 23
/// 645 = 3 × 5 × 43
/// 646 = 2 × 17 × 19.
///
/// Find the first four consecutive integers to have four distinct prime factors. What is the first
/// of these numbers?
fn main() {
|
solutions! {
inputs: (num: usize = 4)
sol naive {
let sieve = SieveOfAtkin::new(1_000_000);
let mut first = None;
let mut count = 0;
for i in 0..1_000_000 {
if sieve.factors(i).len() == num {
first = match first {
Some(v) => Some(v),
None => Some(i)
};
count += 1;
} else {
first = None;
count = 0;
}
if count == num {
return first;
}
}
None
}
}
}
|
identifier_name
|
|
image_texture.rs
|
use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimensions().1
}
fn get(&self, x: u32, y: u32) -> Option<I::Pixel> {
if self.in_bounds(x, y)
|
else {
None
}
}
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn outline() -> Rgba<u8> {
Rgba([255, 0, 0, 255])
}
}
impl Pixel for Rgb<u8> {
fn is_transparent(&self) -> bool {
false
}
fn transparency() -> Option<Rgb<u8>> {
None
}
fn outline() -> Rgb<u8> {
Rgb([255, 0, 0])
}
}
|
{
Some(self.get_pixel(x, y))
}
|
conditional_block
|
image_texture.rs
|
use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimensions().1
}
fn get(&self, x: u32, y: u32) -> Option<I::Pixel> {
if self.in_bounds(x, y) {
Some(self.get_pixel(x, y))
} else {
None
}
}
|
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn outline() -> Rgba<u8> {
Rgba([255, 0, 0, 255])
}
}
impl Pixel for Rgb<u8> {
fn is_transparent(&self) -> bool {
false
}
fn transparency() -> Option<Rgb<u8>> {
None
}
fn outline() -> Rgb<u8> {
Rgb([255, 0, 0])
}
}
|
random_line_split
|
|
image_texture.rs
|
use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32
|
fn get(&self, x: u32, y: u32) -> Option<I::Pixel> {
if self.in_bounds(x, y) {
Some(self.get_pixel(x, y))
} else {
None
}
}
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn outline() -> Rgba<u8> {
Rgba([255, 0, 0, 255])
}
}
impl Pixel for Rgb<u8> {
fn is_transparent(&self) -> bool {
false
}
fn transparency() -> Option<Rgb<u8>> {
None
}
fn outline() -> Rgb<u8> {
Rgb([255, 0, 0])
}
}
|
{
self.dimensions().1
}
|
identifier_body
|
image_texture.rs
|
use image;
use image::{
GenericImage,
Rgba,
Rgb,
};
use texture::{
Pixel,
Texture,
};
impl<P: Pixel + image::Pixel, I: GenericImage<Pixel=P>> Texture for I {
type Pixel = I::Pixel;
fn width(&self) -> u32 {
self.dimensions().0
}
fn height(&self) -> u32 {
self.dimensions().1
}
fn get(&self, x: u32, y: u32) -> Option<I::Pixel> {
if self.in_bounds(x, y) {
Some(self.get_pixel(x, y))
} else {
None
}
}
fn set(&mut self, x: u32, y: u32, val: I::Pixel) {
self.put_pixel(x, y, val);
}
}
impl Pixel for Rgba<u8> {
fn is_transparent(&self) -> bool {
self[3] == 0
}
fn transparency() -> Option<Rgba<u8>> {
Some(Rgba([0; 4]))
}
fn outline() -> Rgba<u8> {
Rgba([255, 0, 0, 255])
}
}
impl Pixel for Rgb<u8> {
fn is_transparent(&self) -> bool {
false
}
fn transparency() -> Option<Rgb<u8>> {
None
}
fn
|
() -> Rgb<u8> {
Rgb([255, 0, 0])
}
}
|
outline
|
identifier_name
|
backup.rs
|
// id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing the duration of
// how long the image is stored. This is one of "snapshot", "temporary" or
// "backup".
// distribution string The base distribution used for this image.
// slug nullable string A uniquely identifying string that is
// associated with each of the DigitalOcean-provided public images. These can
// be used to reference a public image as an alternative to the numeric id.
// public boolean A boolean value that indicates whether the
// image in question is public. An image that is public is available to all
// accounts. A non-public image is only accessible from your account.
// regions array An array of the regions that the image is
// available in. The regions are represented by their identifying slug values.
// min_disk_size number The minimum 'disk' required for a size to use
// this image.
use std::fmt;
use std::borrow::Cow;
use response::NamedResponse;
use response;
#[derive(Deserialize, Debug)]
pub struct Backup {
pub id: f64,
pub name: String,
#[serde(rename = "type")]
pub b_type: String,
pub distribution: String,
pub slug: Option<String>,
pub public: bool,
pub regions: Vec<String>,
pub min_disk_size: f64,
}
impl response::NotArray for Backup {}
impl fmt::Display for Backup {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"ID: {:.0}\n\
Name: {}\n\
Type:{}\n\
Distribution:{}\n\
Slug:{}\n\
Public:{}\n\
Regions:{}\n\
Minimum Disk Size: {:.0} MB\n",
self.id,
self.name,
self.b_type,
self.distribution,
if let Some(ref s) = self.slug {
s.clone()
} else {
"None".to_owned()
},
self.public,
self.regions.iter().fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.min_disk_size)
}
}
pub type Backups = Vec<Backup>;
impl NamedResponse for Backup {
fn name<'a>() -> Cow<'a, str>
|
}
|
{ "backup".into() }
|
identifier_body
|
backup.rs
|
// id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing the duration of
// how long the image is stored. This is one of "snapshot", "temporary" or
// "backup".
// distribution string The base distribution used for this image.
// slug nullable string A uniquely identifying string that is
// associated with each of the DigitalOcean-provided public images. These can
// be used to reference a public image as an alternative to the numeric id.
// public boolean A boolean value that indicates whether the
// image in question is public. An image that is public is available to all
// accounts. A non-public image is only accessible from your account.
// regions array An array of the regions that the image is
// available in. The regions are represented by their identifying slug values.
// min_disk_size number The minimum 'disk' required for a size to use
// this image.
use std::fmt;
use std::borrow::Cow;
use response::NamedResponse;
use response;
#[derive(Deserialize, Debug)]
pub struct
|
{
pub id: f64,
pub name: String,
#[serde(rename = "type")]
pub b_type: String,
pub distribution: String,
pub slug: Option<String>,
pub public: bool,
pub regions: Vec<String>,
pub min_disk_size: f64,
}
impl response::NotArray for Backup {}
impl fmt::Display for Backup {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"ID: {:.0}\n\
Name: {}\n\
Type:{}\n\
Distribution:{}\n\
Slug:{}\n\
Public:{}\n\
Regions:{}\n\
Minimum Disk Size: {:.0} MB\n",
self.id,
self.name,
self.b_type,
self.distribution,
if let Some(ref s) = self.slug {
s.clone()
} else {
"None".to_owned()
},
self.public,
self.regions.iter().fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.min_disk_size)
}
}
pub type Backups = Vec<Backup>;
impl NamedResponse for Backup {
fn name<'a>() -> Cow<'a, str> { "backup".into() }
}
|
Backup
|
identifier_name
|
backup.rs
|
// id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing the duration of
|
// how long the image is stored. This is one of "snapshot", "temporary" or
// "backup".
// distribution string The base distribution used for this image.
// slug nullable string A uniquely identifying string that is
// associated with each of the DigitalOcean-provided public images. These can
// be used to reference a public image as an alternative to the numeric id.
// public boolean A boolean value that indicates whether the
// image in question is public. An image that is public is available to all
// accounts. A non-public image is only accessible from your account.
// regions array An array of the regions that the image is
// available in. The regions are represented by their identifying slug values.
// min_disk_size number The minimum 'disk' required for a size to use
// this image.
use std::fmt;
use std::borrow::Cow;
use response::NamedResponse;
use response;
#[derive(Deserialize, Debug)]
pub struct Backup {
pub id: f64,
pub name: String,
#[serde(rename = "type")]
pub b_type: String,
pub distribution: String,
pub slug: Option<String>,
pub public: bool,
pub regions: Vec<String>,
pub min_disk_size: f64,
}
impl response::NotArray for Backup {}
impl fmt::Display for Backup {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"ID: {:.0}\n\
Name: {}\n\
Type:{}\n\
Distribution:{}\n\
Slug:{}\n\
Public:{}\n\
Regions:{}\n\
Minimum Disk Size: {:.0} MB\n",
self.id,
self.name,
self.b_type,
self.distribution,
if let Some(ref s) = self.slug {
s.clone()
} else {
"None".to_owned()
},
self.public,
self.regions.iter().fold(String::new(), |acc, s| acc + &format!(" {},", s)[..]),
self.min_disk_size)
}
}
pub type Backups = Vec<Backup>;
impl NamedResponse for Backup {
fn name<'a>() -> Cow<'a, str> { "backup".into() }
}
|
random_line_split
|
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
extern mod extra;
use std::comm::{SharedChan, Chan, stream};
use std::io;
use std::os;
use std::task;
use std::uint;
fn move_out<T>(_x: T)
|
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Port<request>, responses: &Chan<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.try_recv() {
Some(get_count) => { responses.send(count.clone()); }
Some(bytes(b)) => {
//error!("server: received %? bytes", b);
count += b;
}
None => { done = true; }
_ => { }
}
}
responses.send(count);
//error!("server exiting");
}
fn run(args: &[~str]) {
let (from_child, to_parent) = stream();
let (from_parent, to_child) = stream();
let to_child = SharedChan::new(to_child);
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = extra::time::precise_time_s();
let mut worker_results = ~[];
for _ in range(0u, workers) {
let to_child = to_child.clone();
let mut builder = task::task();
builder.future_result(|r| worker_results.push(r));
do builder.spawn {
for _ in range(0u, size / workers) {
//error!("worker %?: sending %? bytes", i, num_bytes);
to_child.send(bytes(num_bytes));
}
//error!("worker %? exiting", i);
};
}
do task::spawn || {
server(&from_parent, &to_parent);
}
for r in worker_results.iter() {
r.recv();
}
//error!("sending stop message");
to_child.send(stop);
move_out(to_child);
let result = from_child.recv();
let end = extra::time::precise_time_s();
let elapsed = end - start;
io::stdout().write_str(fmt!("Count is %?\n", result));
io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed));
let thruput = ((size / workers * workers) as float) / (elapsed as float);
io::stdout().write_str(fmt!("Throughput=%f per sec\n", thruput));
assert_eq!(result, num_bytes * size);
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"1000000", ~"8"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"4"]
} else {
args.clone()
};
info!("%?", args);
run(args);
}
|
{}
|
identifier_body
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
extern mod extra;
use std::comm::{SharedChan, Chan, stream};
use std::io;
use std::os;
use std::task;
use std::uint;
fn move_out<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Port<request>, responses: &Chan<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.try_recv() {
Some(get_count) => { responses.send(count.clone()); }
Some(bytes(b)) => {
//error!("server: received %? bytes", b);
count += b;
}
None => { done = true; }
_ => { }
}
}
responses.send(count);
//error!("server exiting");
}
fn run(args: &[~str]) {
let (from_child, to_parent) = stream();
let (from_parent, to_child) = stream();
let to_child = SharedChan::new(to_child);
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = extra::time::precise_time_s();
let mut worker_results = ~[];
for _ in range(0u, workers) {
let to_child = to_child.clone();
let mut builder = task::task();
builder.future_result(|r| worker_results.push(r));
do builder.spawn {
for _ in range(0u, size / workers) {
//error!("worker %?: sending %? bytes", i, num_bytes);
to_child.send(bytes(num_bytes));
}
//error!("worker %? exiting", i);
};
}
do task::spawn || {
server(&from_parent, &to_parent);
}
for r in worker_results.iter() {
r.recv();
}
//error!("sending stop message");
to_child.send(stop);
move_out(to_child);
let result = from_child.recv();
let end = extra::time::precise_time_s();
let elapsed = end - start;
io::stdout().write_str(fmt!("Count is %?\n", result));
io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed));
let thruput = ((size / workers * workers) as float) / (elapsed as float);
io::stdout().write_str(fmt!("Throughput=%f per sec\n", thruput));
assert_eq!(result, num_bytes * size);
}
fn
|
() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"1000000", ~"8"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"4"]
} else {
args.clone()
};
info!("%?", args);
run(args);
}
|
main
|
identifier_name
|
msgsend-pipes.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.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
extern mod extra;
use std::comm::{SharedChan, Chan, stream};
use std::io;
use std::os;
use std::task;
use std::uint;
fn move_out<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Port<request>, responses: &Chan<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.try_recv() {
Some(get_count) => { responses.send(count.clone()); }
Some(bytes(b)) => {
//error!("server: received %? bytes", b);
count += b;
}
None => { done = true; }
_ =>
|
}
}
responses.send(count);
//error!("server exiting");
}
fn run(args: &[~str]) {
let (from_child, to_parent) = stream();
let (from_parent, to_child) = stream();
let to_child = SharedChan::new(to_child);
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = extra::time::precise_time_s();
let mut worker_results = ~[];
for _ in range(0u, workers) {
let to_child = to_child.clone();
let mut builder = task::task();
builder.future_result(|r| worker_results.push(r));
do builder.spawn {
for _ in range(0u, size / workers) {
//error!("worker %?: sending %? bytes", i, num_bytes);
to_child.send(bytes(num_bytes));
}
//error!("worker %? exiting", i);
};
}
do task::spawn || {
server(&from_parent, &to_parent);
}
for r in worker_results.iter() {
r.recv();
}
//error!("sending stop message");
to_child.send(stop);
move_out(to_child);
let result = from_child.recv();
let end = extra::time::precise_time_s();
let elapsed = end - start;
io::stdout().write_str(fmt!("Count is %?\n", result));
io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed));
let thruput = ((size / workers * workers) as float) / (elapsed as float);
io::stdout().write_str(fmt!("Throughput=%f per sec\n", thruput));
assert_eq!(result, num_bytes * size);
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"1000000", ~"8"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"4"]
} else {
args.clone()
};
info!("%?", args);
run(args);
}
|
{ }
|
conditional_block
|
msgsend-pipes.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.
//
|
// except according to those terms.
// A port of the simplistic benchmark from
//
// http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.
extern mod extra;
use std::comm::{SharedChan, Chan, stream};
use std::io;
use std::os;
use std::task;
use std::uint;
fn move_out<T>(_x: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Port<request>, responses: &Chan<uint>) {
let mut count: uint = 0;
let mut done = false;
while!done {
match requests.try_recv() {
Some(get_count) => { responses.send(count.clone()); }
Some(bytes(b)) => {
//error!("server: received %? bytes", b);
count += b;
}
None => { done = true; }
_ => { }
}
}
responses.send(count);
//error!("server exiting");
}
fn run(args: &[~str]) {
let (from_child, to_parent) = stream();
let (from_parent, to_child) = stream();
let to_child = SharedChan::new(to_child);
let size = from_str::<uint>(args[1]).unwrap();
let workers = from_str::<uint>(args[2]).unwrap();
let num_bytes = 100;
let start = extra::time::precise_time_s();
let mut worker_results = ~[];
for _ in range(0u, workers) {
let to_child = to_child.clone();
let mut builder = task::task();
builder.future_result(|r| worker_results.push(r));
do builder.spawn {
for _ in range(0u, size / workers) {
//error!("worker %?: sending %? bytes", i, num_bytes);
to_child.send(bytes(num_bytes));
}
//error!("worker %? exiting", i);
};
}
do task::spawn || {
server(&from_parent, &to_parent);
}
for r in worker_results.iter() {
r.recv();
}
//error!("sending stop message");
to_child.send(stop);
move_out(to_child);
let result = from_child.recv();
let end = extra::time::precise_time_s();
let elapsed = end - start;
io::stdout().write_str(fmt!("Count is %?\n", result));
io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed));
let thruput = ((size / workers * workers) as float) / (elapsed as float);
io::stdout().write_str(fmt!("Throughput=%f per sec\n", thruput));
assert_eq!(result, num_bytes * size);
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"1000000", ~"8"]
} else if args.len() <= 1u {
~[~"", ~"10000", ~"4"]
} else {
args.clone()
};
info!("%?", args);
run(args);
}
|
// 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
|
random_line_split
|
exchanger.rs
|
use std::collections::VecDeque;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::atomic::Ordering::{Acquire, Release};
use std::thread;
use std::time::Instant;
|
use select::handle::{self, Handle};
use util::Backoff;
/// Waiting strategy in an exchange operation.
enum Wait {
/// Yield once and then time out.
YieldOnce,
/// Wait until an optional deadline.
Until(Option<Instant>),
}
/// Enumeration of possible exchange errors.
pub enum ExchangeError<T> {
/// The exchange operation timed out.
Timeout(T),
/// The exchanger was disconnected.
Disconnected(T),
}
/// Inner representation of an exchanger.
///
/// This data structure is wrapped in a mutex.
struct Inner<T> {
/// There are two wait queues, one per side.
wait_queues: [WaitQueue<T>; 2],
/// `true` if the exchanger is closed.
closed: bool,
}
/// A two-sided exchanger.
///
/// This is a concurrent data structure with two sides: left and right. A thread can offer a
/// message on one side, and if there is another thread waiting on the opposite side at the same
/// time, they exchange messages.
///
/// Instead of *offering* a concrete message for excahnge, a thread can also *promise* a message.
/// If another thread pairs up with the promise on the opposite end, then it will wait until the
/// promise is fulfilled. The thread that promised the message must in the end either revoke the
/// promise or fulfill it.
pub struct Exchanger<T> {
inner: Mutex<Inner<T>>,
}
impl<T> Exchanger<T> {
/// Returns a new exchanger.
pub fn new() -> Self {
Exchanger {
inner: Mutex::new(Inner {
wait_queues: [WaitQueue::new(), WaitQueue::new()],
closed: false,
}),
}
}
/// Returns the left side of the exchanger.
pub fn left(&self) -> Side<T> {
Side {
index: 0,
exchanger: self,
}
}
/// Returns the right side of the exchanger.
pub fn right(&self) -> Side<T> {
Side {
index: 1,
exchanger: self,
}
}
/// Closes the exchanger.
pub fn close(&self) -> bool {
let mut inner = self.inner.lock();
if inner.closed {
false
} else {
inner.closed = true;
inner.wait_queues[0].abort_all();
inner.wait_queues[1].abort_all();
true
}
}
/// Returns `true` if the exchanger is closed.
pub fn is_closed(&self) -> bool {
self.inner.lock().closed
}
}
/// One side of an exchanger.
pub struct Side<'a, T: 'a> {
/// The index is 0 or 1.
index: usize,
/// A reference to the parent exchanger.
exchanger: &'a Exchanger<T>,
}
impl<'a, T> Side<'a, T> {
/// Promises a message for exchange.
pub fn promise(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].promise(case_id);
}
/// Revokes the previously made promise.
///
/// TODO: what if somebody paired up with it?
pub fn revoke(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].revoke(case_id);
}
/// Fulfills the previously made promise.
pub fn fulfill(&self, msg: T) -> T {
finish_exchange(msg, self.exchanger)
}
/// Exchanges `msg` if there is an offer or promise on the opposite side.
pub fn try_exchange(
&self,
msg: T,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::YieldOnce, case_id)
}
/// Exchanges `msg`, waiting until the specified `deadline`.
pub fn exchange_until(
&self,
msg: T,
deadline: Option<Instant>,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::Until(deadline), case_id)
}
/// Returns `true` if there is an offer or promise on the opposite side.
pub fn can_notify(&self) -> bool {
self.exchanger.inner.lock().wait_queues[self.index].can_notify()
}
/// Exchanges `msg` with the specified `wait` strategy.
fn exchange(
&self,
mut msg: T,
wait: Wait,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
loop {
// Allocate a packet on the stack.
let packet;
{
let mut inner = self.exchanger.inner.lock();
if inner.closed {
return Err(ExchangeError::Disconnected(msg));
}
// If there's someone on the other side, exchange messages with it.
if let Some(case) = inner.wait_queues[self.index ^ 1].pop() {
drop(inner);
return Ok(case.exchange(msg, self.exchanger));
}
// Promise a packet with the message.
handle::current_reset();
packet = Packet::new(msg);
inner.wait_queues[self.index].offer(&packet, case_id);
}
let timed_out = match wait {
Wait::YieldOnce => {
thread::yield_now();
handle::current_try_select(CaseId::abort())
},
Wait::Until(deadline) => {
!handle::current_wait_until(deadline)
},
};
// If someone requested the promised message...
if handle::current_selected()!= CaseId::abort() {
// Wait until the message is taken and return.
packet.wait();
return Ok(packet.into_inner());
}
// Revoke the promise.
let mut inner = self.exchanger.inner.lock();
inner.wait_queues[self.index].revoke(case_id);
msg = packet.into_inner();
// If we timed out, return.
if timed_out {
return Err(ExchangeError::Timeout(msg));
}
// Otherwise, another thread must have woken us up. Let's try again.
}
}
}
enum Case<T> {
Offer {
handle: Handle,
packet: *const Packet<T>,
case_id: CaseId,
},
Promise { local: Arc<Local>, case_id: CaseId },
}
impl<T> Case<T> {
fn exchange(&self, msg: T, exchanger: &Exchanger<T>) -> T {
match *self {
Case::Offer {
ref handle, packet,..
} => {
let m = unsafe { (*packet).exchange(msg) };
handle.unpark();
m
}
Case::Promise { ref local,.. } => {
handle::current_reset();
let req = Request::new(msg, exchanger);
local.request_ptr.store(&req as *const _ as usize, Release);
local.handle.unpark();
handle::current_wait_until(None);
req.packet.into_inner()
}
}
}
fn handle(&self) -> &Handle {
match *self {
Case::Offer { ref handle,.. } => handle,
Case::Promise { ref local,.. } => &local.handle,
}
}
fn case_id(&self) -> CaseId {
match *self {
Case::Offer { case_id,.. } => case_id,
Case::Promise { case_id,.. } => case_id,
}
}
}
fn finish_exchange<T>(msg: T, exchanger: &Exchanger<T>) -> T {
let req = loop {
let ptr = LOCAL.with(|l| l.request_ptr.swap(0, Acquire) as *const Request<T>);
if!ptr.is_null() {
break ptr;
}
thread::yield_now();
};
unsafe {
assert!((*req).exchanger == exchanger);
let handle = (*req).handle.clone();
let m = (*req).packet.exchange(msg);
(*req).handle.try_select(CaseId::abort());
handle.unpark();
m
}
}
struct WaitQueue<T> {
cases: VecDeque<Case<T>>,
}
impl<T> WaitQueue<T> {
fn new() -> Self {
WaitQueue {
cases: VecDeque::new(),
}
}
fn pop(&mut self) -> Option<Case<T>> {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
if self.cases[i].handle().try_select(self.cases[i].case_id()) {
return Some(self.cases.remove(i).unwrap());
}
}
}
None
}
fn offer(&mut self, packet: *const Packet<T>, case_id: CaseId) {
self.cases.push_back(Case::Offer {
handle: handle::current(),
packet,
case_id,
});
}
fn promise(&mut self, case_id: CaseId) {
self.cases.push_back(Case::Promise {
local: LOCAL.with(|l| l.clone()),
case_id,
});
}
fn revoke(&mut self, case_id: CaseId) {
let thread_id = current_thread_id();
if let Some((i, _)) = self.cases.iter().enumerate().find(|&(_, case)| {
case.case_id() == case_id && case.handle().thread_id() == thread_id
}) {
self.cases.remove(i);
self.maybe_shrink();
}
}
fn can_notify(&self) -> bool {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
return true;
}
}
false
}
fn abort_all(&mut self) {
for case in self.cases.drain(..) {
case.handle().try_select(CaseId::abort());
case.handle().unpark();
}
self.maybe_shrink();
}
fn maybe_shrink(&mut self) {
if self.cases.capacity() > 32 && self.cases.capacity() / 2 > self.cases.len() {
self.cases.shrink_to_fit();
}
}
}
impl<T> Drop for WaitQueue<T> {
fn drop(&mut self) {
debug_assert!(self.cases.is_empty());
}
}
thread_local! {
static THREAD_ID: thread::ThreadId = thread::current().id();
}
fn current_thread_id() -> thread::ThreadId {
THREAD_ID.with(|id| *id)
}
thread_local! {
static LOCAL: Arc<Local> = Arc::new(Local {
handle: handle::current(),
request_ptr: AtomicUsize::new(0),
});
}
struct Local {
handle: Handle,
request_ptr: AtomicUsize,
}
struct Request<T> {
handle: Handle,
packet: Packet<T>,
exchanger: *const Exchanger<T>,
}
impl<T> Request<T> {
fn new(msg: T, exchanger: &Exchanger<T>) -> Self {
Request {
handle: handle::current(),
packet: Packet::new(msg),
exchanger,
}
}
}
struct Packet<T> {
msg: Mutex<Option<T>>,
ready: AtomicBool,
}
impl<T> Packet<T> {
fn new(msg: T) -> Self {
Packet {
msg: Mutex::new(Some(msg)),
ready: AtomicBool::new(false),
}
}
fn exchange(&self, msg: T) -> T {
let r = mem::replace(&mut *self.msg.try_lock().unwrap(), Some(msg));
self.ready.store(true, Release);
r.unwrap()
}
fn into_inner(self) -> T {
self.msg.try_lock().unwrap().take().unwrap()
}
/// Spin-waits until the packet becomes ready.
fn wait(&self) {
let mut backoff = Backoff::new();
while!self.ready.load(Acquire) {
backoff.step();
}
}
}
|
use parking_lot::Mutex;
use select::CaseId;
|
random_line_split
|
exchanger.rs
|
use std::collections::VecDeque;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::atomic::Ordering::{Acquire, Release};
use std::thread;
use std::time::Instant;
use parking_lot::Mutex;
use select::CaseId;
use select::handle::{self, Handle};
use util::Backoff;
/// Waiting strategy in an exchange operation.
enum Wait {
/// Yield once and then time out.
YieldOnce,
/// Wait until an optional deadline.
Until(Option<Instant>),
}
/// Enumeration of possible exchange errors.
pub enum ExchangeError<T> {
/// The exchange operation timed out.
Timeout(T),
/// The exchanger was disconnected.
Disconnected(T),
}
/// Inner representation of an exchanger.
///
/// This data structure is wrapped in a mutex.
struct Inner<T> {
/// There are two wait queues, one per side.
wait_queues: [WaitQueue<T>; 2],
/// `true` if the exchanger is closed.
closed: bool,
}
/// A two-sided exchanger.
///
/// This is a concurrent data structure with two sides: left and right. A thread can offer a
/// message on one side, and if there is another thread waiting on the opposite side at the same
/// time, they exchange messages.
///
/// Instead of *offering* a concrete message for excahnge, a thread can also *promise* a message.
/// If another thread pairs up with the promise on the opposite end, then it will wait until the
/// promise is fulfilled. The thread that promised the message must in the end either revoke the
/// promise or fulfill it.
pub struct Exchanger<T> {
inner: Mutex<Inner<T>>,
}
impl<T> Exchanger<T> {
/// Returns a new exchanger.
pub fn new() -> Self {
Exchanger {
inner: Mutex::new(Inner {
wait_queues: [WaitQueue::new(), WaitQueue::new()],
closed: false,
}),
}
}
/// Returns the left side of the exchanger.
pub fn left(&self) -> Side<T> {
Side {
index: 0,
exchanger: self,
}
}
/// Returns the right side of the exchanger.
pub fn right(&self) -> Side<T> {
Side {
index: 1,
exchanger: self,
}
}
/// Closes the exchanger.
pub fn close(&self) -> bool {
let mut inner = self.inner.lock();
if inner.closed {
false
} else
|
}
/// Returns `true` if the exchanger is closed.
pub fn is_closed(&self) -> bool {
self.inner.lock().closed
}
}
/// One side of an exchanger.
pub struct Side<'a, T: 'a> {
/// The index is 0 or 1.
index: usize,
/// A reference to the parent exchanger.
exchanger: &'a Exchanger<T>,
}
impl<'a, T> Side<'a, T> {
/// Promises a message for exchange.
pub fn promise(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].promise(case_id);
}
/// Revokes the previously made promise.
///
/// TODO: what if somebody paired up with it?
pub fn revoke(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].revoke(case_id);
}
/// Fulfills the previously made promise.
pub fn fulfill(&self, msg: T) -> T {
finish_exchange(msg, self.exchanger)
}
/// Exchanges `msg` if there is an offer or promise on the opposite side.
pub fn try_exchange(
&self,
msg: T,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::YieldOnce, case_id)
}
/// Exchanges `msg`, waiting until the specified `deadline`.
pub fn exchange_until(
&self,
msg: T,
deadline: Option<Instant>,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::Until(deadline), case_id)
}
/// Returns `true` if there is an offer or promise on the opposite side.
pub fn can_notify(&self) -> bool {
self.exchanger.inner.lock().wait_queues[self.index].can_notify()
}
/// Exchanges `msg` with the specified `wait` strategy.
fn exchange(
&self,
mut msg: T,
wait: Wait,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
loop {
// Allocate a packet on the stack.
let packet;
{
let mut inner = self.exchanger.inner.lock();
if inner.closed {
return Err(ExchangeError::Disconnected(msg));
}
// If there's someone on the other side, exchange messages with it.
if let Some(case) = inner.wait_queues[self.index ^ 1].pop() {
drop(inner);
return Ok(case.exchange(msg, self.exchanger));
}
// Promise a packet with the message.
handle::current_reset();
packet = Packet::new(msg);
inner.wait_queues[self.index].offer(&packet, case_id);
}
let timed_out = match wait {
Wait::YieldOnce => {
thread::yield_now();
handle::current_try_select(CaseId::abort())
},
Wait::Until(deadline) => {
!handle::current_wait_until(deadline)
},
};
// If someone requested the promised message...
if handle::current_selected()!= CaseId::abort() {
// Wait until the message is taken and return.
packet.wait();
return Ok(packet.into_inner());
}
// Revoke the promise.
let mut inner = self.exchanger.inner.lock();
inner.wait_queues[self.index].revoke(case_id);
msg = packet.into_inner();
// If we timed out, return.
if timed_out {
return Err(ExchangeError::Timeout(msg));
}
// Otherwise, another thread must have woken us up. Let's try again.
}
}
}
enum Case<T> {
Offer {
handle: Handle,
packet: *const Packet<T>,
case_id: CaseId,
},
Promise { local: Arc<Local>, case_id: CaseId },
}
impl<T> Case<T> {
fn exchange(&self, msg: T, exchanger: &Exchanger<T>) -> T {
match *self {
Case::Offer {
ref handle, packet,..
} => {
let m = unsafe { (*packet).exchange(msg) };
handle.unpark();
m
}
Case::Promise { ref local,.. } => {
handle::current_reset();
let req = Request::new(msg, exchanger);
local.request_ptr.store(&req as *const _ as usize, Release);
local.handle.unpark();
handle::current_wait_until(None);
req.packet.into_inner()
}
}
}
fn handle(&self) -> &Handle {
match *self {
Case::Offer { ref handle,.. } => handle,
Case::Promise { ref local,.. } => &local.handle,
}
}
fn case_id(&self) -> CaseId {
match *self {
Case::Offer { case_id,.. } => case_id,
Case::Promise { case_id,.. } => case_id,
}
}
}
fn finish_exchange<T>(msg: T, exchanger: &Exchanger<T>) -> T {
let req = loop {
let ptr = LOCAL.with(|l| l.request_ptr.swap(0, Acquire) as *const Request<T>);
if!ptr.is_null() {
break ptr;
}
thread::yield_now();
};
unsafe {
assert!((*req).exchanger == exchanger);
let handle = (*req).handle.clone();
let m = (*req).packet.exchange(msg);
(*req).handle.try_select(CaseId::abort());
handle.unpark();
m
}
}
struct WaitQueue<T> {
cases: VecDeque<Case<T>>,
}
impl<T> WaitQueue<T> {
fn new() -> Self {
WaitQueue {
cases: VecDeque::new(),
}
}
fn pop(&mut self) -> Option<Case<T>> {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
if self.cases[i].handle().try_select(self.cases[i].case_id()) {
return Some(self.cases.remove(i).unwrap());
}
}
}
None
}
fn offer(&mut self, packet: *const Packet<T>, case_id: CaseId) {
self.cases.push_back(Case::Offer {
handle: handle::current(),
packet,
case_id,
});
}
fn promise(&mut self, case_id: CaseId) {
self.cases.push_back(Case::Promise {
local: LOCAL.with(|l| l.clone()),
case_id,
});
}
fn revoke(&mut self, case_id: CaseId) {
let thread_id = current_thread_id();
if let Some((i, _)) = self.cases.iter().enumerate().find(|&(_, case)| {
case.case_id() == case_id && case.handle().thread_id() == thread_id
}) {
self.cases.remove(i);
self.maybe_shrink();
}
}
fn can_notify(&self) -> bool {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
return true;
}
}
false
}
fn abort_all(&mut self) {
for case in self.cases.drain(..) {
case.handle().try_select(CaseId::abort());
case.handle().unpark();
}
self.maybe_shrink();
}
fn maybe_shrink(&mut self) {
if self.cases.capacity() > 32 && self.cases.capacity() / 2 > self.cases.len() {
self.cases.shrink_to_fit();
}
}
}
impl<T> Drop for WaitQueue<T> {
fn drop(&mut self) {
debug_assert!(self.cases.is_empty());
}
}
thread_local! {
static THREAD_ID: thread::ThreadId = thread::current().id();
}
fn current_thread_id() -> thread::ThreadId {
THREAD_ID.with(|id| *id)
}
thread_local! {
static LOCAL: Arc<Local> = Arc::new(Local {
handle: handle::current(),
request_ptr: AtomicUsize::new(0),
});
}
struct Local {
handle: Handle,
request_ptr: AtomicUsize,
}
struct Request<T> {
handle: Handle,
packet: Packet<T>,
exchanger: *const Exchanger<T>,
}
impl<T> Request<T> {
fn new(msg: T, exchanger: &Exchanger<T>) -> Self {
Request {
handle: handle::current(),
packet: Packet::new(msg),
exchanger,
}
}
}
struct Packet<T> {
msg: Mutex<Option<T>>,
ready: AtomicBool,
}
impl<T> Packet<T> {
fn new(msg: T) -> Self {
Packet {
msg: Mutex::new(Some(msg)),
ready: AtomicBool::new(false),
}
}
fn exchange(&self, msg: T) -> T {
let r = mem::replace(&mut *self.msg.try_lock().unwrap(), Some(msg));
self.ready.store(true, Release);
r.unwrap()
}
fn into_inner(self) -> T {
self.msg.try_lock().unwrap().take().unwrap()
}
/// Spin-waits until the packet becomes ready.
fn wait(&self) {
let mut backoff = Backoff::new();
while!self.ready.load(Acquire) {
backoff.step();
}
}
}
|
{
inner.closed = true;
inner.wait_queues[0].abort_all();
inner.wait_queues[1].abort_all();
true
}
|
conditional_block
|
exchanger.rs
|
use std::collections::VecDeque;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::atomic::Ordering::{Acquire, Release};
use std::thread;
use std::time::Instant;
use parking_lot::Mutex;
use select::CaseId;
use select::handle::{self, Handle};
use util::Backoff;
/// Waiting strategy in an exchange operation.
enum Wait {
/// Yield once and then time out.
YieldOnce,
/// Wait until an optional deadline.
Until(Option<Instant>),
}
/// Enumeration of possible exchange errors.
pub enum ExchangeError<T> {
/// The exchange operation timed out.
Timeout(T),
/// The exchanger was disconnected.
Disconnected(T),
}
/// Inner representation of an exchanger.
///
/// This data structure is wrapped in a mutex.
struct Inner<T> {
/// There are two wait queues, one per side.
wait_queues: [WaitQueue<T>; 2],
/// `true` if the exchanger is closed.
closed: bool,
}
/// A two-sided exchanger.
///
/// This is a concurrent data structure with two sides: left and right. A thread can offer a
/// message on one side, and if there is another thread waiting on the opposite side at the same
/// time, they exchange messages.
///
/// Instead of *offering* a concrete message for excahnge, a thread can also *promise* a message.
/// If another thread pairs up with the promise on the opposite end, then it will wait until the
/// promise is fulfilled. The thread that promised the message must in the end either revoke the
/// promise or fulfill it.
pub struct Exchanger<T> {
inner: Mutex<Inner<T>>,
}
impl<T> Exchanger<T> {
/// Returns a new exchanger.
pub fn new() -> Self {
Exchanger {
inner: Mutex::new(Inner {
wait_queues: [WaitQueue::new(), WaitQueue::new()],
closed: false,
}),
}
}
/// Returns the left side of the exchanger.
pub fn left(&self) -> Side<T> {
Side {
index: 0,
exchanger: self,
}
}
/// Returns the right side of the exchanger.
pub fn right(&self) -> Side<T> {
Side {
index: 1,
exchanger: self,
}
}
/// Closes the exchanger.
pub fn close(&self) -> bool {
let mut inner = self.inner.lock();
if inner.closed {
false
} else {
inner.closed = true;
inner.wait_queues[0].abort_all();
inner.wait_queues[1].abort_all();
true
}
}
/// Returns `true` if the exchanger is closed.
pub fn is_closed(&self) -> bool {
self.inner.lock().closed
}
}
/// One side of an exchanger.
pub struct Side<'a, T: 'a> {
/// The index is 0 or 1.
index: usize,
/// A reference to the parent exchanger.
exchanger: &'a Exchanger<T>,
}
impl<'a, T> Side<'a, T> {
/// Promises a message for exchange.
pub fn promise(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].promise(case_id);
}
/// Revokes the previously made promise.
///
/// TODO: what if somebody paired up with it?
pub fn revoke(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].revoke(case_id);
}
/// Fulfills the previously made promise.
pub fn fulfill(&self, msg: T) -> T {
finish_exchange(msg, self.exchanger)
}
/// Exchanges `msg` if there is an offer or promise on the opposite side.
pub fn try_exchange(
&self,
msg: T,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::YieldOnce, case_id)
}
/// Exchanges `msg`, waiting until the specified `deadline`.
pub fn exchange_until(
&self,
msg: T,
deadline: Option<Instant>,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::Until(deadline), case_id)
}
/// Returns `true` if there is an offer or promise on the opposite side.
pub fn can_notify(&self) -> bool {
self.exchanger.inner.lock().wait_queues[self.index].can_notify()
}
/// Exchanges `msg` with the specified `wait` strategy.
fn exchange(
&self,
mut msg: T,
wait: Wait,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
loop {
// Allocate a packet on the stack.
let packet;
{
let mut inner = self.exchanger.inner.lock();
if inner.closed {
return Err(ExchangeError::Disconnected(msg));
}
// If there's someone on the other side, exchange messages with it.
if let Some(case) = inner.wait_queues[self.index ^ 1].pop() {
drop(inner);
return Ok(case.exchange(msg, self.exchanger));
}
// Promise a packet with the message.
handle::current_reset();
packet = Packet::new(msg);
inner.wait_queues[self.index].offer(&packet, case_id);
}
let timed_out = match wait {
Wait::YieldOnce => {
thread::yield_now();
handle::current_try_select(CaseId::abort())
},
Wait::Until(deadline) => {
!handle::current_wait_until(deadline)
},
};
// If someone requested the promised message...
if handle::current_selected()!= CaseId::abort() {
// Wait until the message is taken and return.
packet.wait();
return Ok(packet.into_inner());
}
// Revoke the promise.
let mut inner = self.exchanger.inner.lock();
inner.wait_queues[self.index].revoke(case_id);
msg = packet.into_inner();
// If we timed out, return.
if timed_out {
return Err(ExchangeError::Timeout(msg));
}
// Otherwise, another thread must have woken us up. Let's try again.
}
}
}
enum Case<T> {
Offer {
handle: Handle,
packet: *const Packet<T>,
case_id: CaseId,
},
Promise { local: Arc<Local>, case_id: CaseId },
}
impl<T> Case<T> {
fn exchange(&self, msg: T, exchanger: &Exchanger<T>) -> T {
match *self {
Case::Offer {
ref handle, packet,..
} => {
let m = unsafe { (*packet).exchange(msg) };
handle.unpark();
m
}
Case::Promise { ref local,.. } => {
handle::current_reset();
let req = Request::new(msg, exchanger);
local.request_ptr.store(&req as *const _ as usize, Release);
local.handle.unpark();
handle::current_wait_until(None);
req.packet.into_inner()
}
}
}
fn handle(&self) -> &Handle {
match *self {
Case::Offer { ref handle,.. } => handle,
Case::Promise { ref local,.. } => &local.handle,
}
}
fn case_id(&self) -> CaseId {
match *self {
Case::Offer { case_id,.. } => case_id,
Case::Promise { case_id,.. } => case_id,
}
}
}
fn finish_exchange<T>(msg: T, exchanger: &Exchanger<T>) -> T {
let req = loop {
let ptr = LOCAL.with(|l| l.request_ptr.swap(0, Acquire) as *const Request<T>);
if!ptr.is_null() {
break ptr;
}
thread::yield_now();
};
unsafe {
assert!((*req).exchanger == exchanger);
let handle = (*req).handle.clone();
let m = (*req).packet.exchange(msg);
(*req).handle.try_select(CaseId::abort());
handle.unpark();
m
}
}
struct WaitQueue<T> {
cases: VecDeque<Case<T>>,
}
impl<T> WaitQueue<T> {
fn new() -> Self {
WaitQueue {
cases: VecDeque::new(),
}
}
fn pop(&mut self) -> Option<Case<T>> {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
if self.cases[i].handle().try_select(self.cases[i].case_id()) {
return Some(self.cases.remove(i).unwrap());
}
}
}
None
}
fn offer(&mut self, packet: *const Packet<T>, case_id: CaseId) {
self.cases.push_back(Case::Offer {
handle: handle::current(),
packet,
case_id,
});
}
fn promise(&mut self, case_id: CaseId) {
self.cases.push_back(Case::Promise {
local: LOCAL.with(|l| l.clone()),
case_id,
});
}
fn revoke(&mut self, case_id: CaseId) {
let thread_id = current_thread_id();
if let Some((i, _)) = self.cases.iter().enumerate().find(|&(_, case)| {
case.case_id() == case_id && case.handle().thread_id() == thread_id
}) {
self.cases.remove(i);
self.maybe_shrink();
}
}
fn can_notify(&self) -> bool {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
return true;
}
}
false
}
fn abort_all(&mut self) {
for case in self.cases.drain(..) {
case.handle().try_select(CaseId::abort());
case.handle().unpark();
}
self.maybe_shrink();
}
fn maybe_shrink(&mut self) {
if self.cases.capacity() > 32 && self.cases.capacity() / 2 > self.cases.len() {
self.cases.shrink_to_fit();
}
}
}
impl<T> Drop for WaitQueue<T> {
fn drop(&mut self) {
debug_assert!(self.cases.is_empty());
}
}
thread_local! {
static THREAD_ID: thread::ThreadId = thread::current().id();
}
fn current_thread_id() -> thread::ThreadId {
THREAD_ID.with(|id| *id)
}
thread_local! {
static LOCAL: Arc<Local> = Arc::new(Local {
handle: handle::current(),
request_ptr: AtomicUsize::new(0),
});
}
struct Local {
handle: Handle,
request_ptr: AtomicUsize,
}
struct Request<T> {
handle: Handle,
packet: Packet<T>,
exchanger: *const Exchanger<T>,
}
impl<T> Request<T> {
fn new(msg: T, exchanger: &Exchanger<T>) -> Self {
Request {
handle: handle::current(),
packet: Packet::new(msg),
exchanger,
}
}
}
struct Packet<T> {
msg: Mutex<Option<T>>,
ready: AtomicBool,
}
impl<T> Packet<T> {
fn new(msg: T) -> Self {
Packet {
msg: Mutex::new(Some(msg)),
ready: AtomicBool::new(false),
}
}
fn exchange(&self, msg: T) -> T {
let r = mem::replace(&mut *self.msg.try_lock().unwrap(), Some(msg));
self.ready.store(true, Release);
r.unwrap()
}
fn
|
(self) -> T {
self.msg.try_lock().unwrap().take().unwrap()
}
/// Spin-waits until the packet becomes ready.
fn wait(&self) {
let mut backoff = Backoff::new();
while!self.ready.load(Acquire) {
backoff.step();
}
}
}
|
into_inner
|
identifier_name
|
exchanger.rs
|
use std::collections::VecDeque;
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::atomic::Ordering::{Acquire, Release};
use std::thread;
use std::time::Instant;
use parking_lot::Mutex;
use select::CaseId;
use select::handle::{self, Handle};
use util::Backoff;
/// Waiting strategy in an exchange operation.
enum Wait {
/// Yield once and then time out.
YieldOnce,
/// Wait until an optional deadline.
Until(Option<Instant>),
}
/// Enumeration of possible exchange errors.
pub enum ExchangeError<T> {
/// The exchange operation timed out.
Timeout(T),
/// The exchanger was disconnected.
Disconnected(T),
}
/// Inner representation of an exchanger.
///
/// This data structure is wrapped in a mutex.
struct Inner<T> {
/// There are two wait queues, one per side.
wait_queues: [WaitQueue<T>; 2],
/// `true` if the exchanger is closed.
closed: bool,
}
/// A two-sided exchanger.
///
/// This is a concurrent data structure with two sides: left and right. A thread can offer a
/// message on one side, and if there is another thread waiting on the opposite side at the same
/// time, they exchange messages.
///
/// Instead of *offering* a concrete message for excahnge, a thread can also *promise* a message.
/// If another thread pairs up with the promise on the opposite end, then it will wait until the
/// promise is fulfilled. The thread that promised the message must in the end either revoke the
/// promise or fulfill it.
pub struct Exchanger<T> {
inner: Mutex<Inner<T>>,
}
impl<T> Exchanger<T> {
/// Returns a new exchanger.
pub fn new() -> Self {
Exchanger {
inner: Mutex::new(Inner {
wait_queues: [WaitQueue::new(), WaitQueue::new()],
closed: false,
}),
}
}
/// Returns the left side of the exchanger.
pub fn left(&self) -> Side<T> {
Side {
index: 0,
exchanger: self,
}
}
/// Returns the right side of the exchanger.
pub fn right(&self) -> Side<T> {
Side {
index: 1,
exchanger: self,
}
}
/// Closes the exchanger.
pub fn close(&self) -> bool {
let mut inner = self.inner.lock();
if inner.closed {
false
} else {
inner.closed = true;
inner.wait_queues[0].abort_all();
inner.wait_queues[1].abort_all();
true
}
}
/// Returns `true` if the exchanger is closed.
pub fn is_closed(&self) -> bool {
self.inner.lock().closed
}
}
/// One side of an exchanger.
pub struct Side<'a, T: 'a> {
/// The index is 0 or 1.
index: usize,
/// A reference to the parent exchanger.
exchanger: &'a Exchanger<T>,
}
impl<'a, T> Side<'a, T> {
/// Promises a message for exchange.
pub fn promise(&self, case_id: CaseId) {
self.exchanger.inner.lock().wait_queues[self.index].promise(case_id);
}
/// Revokes the previously made promise.
///
/// TODO: what if somebody paired up with it?
pub fn revoke(&self, case_id: CaseId)
|
/// Fulfills the previously made promise.
pub fn fulfill(&self, msg: T) -> T {
finish_exchange(msg, self.exchanger)
}
/// Exchanges `msg` if there is an offer or promise on the opposite side.
pub fn try_exchange(
&self,
msg: T,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::YieldOnce, case_id)
}
/// Exchanges `msg`, waiting until the specified `deadline`.
pub fn exchange_until(
&self,
msg: T,
deadline: Option<Instant>,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
self.exchange(msg, Wait::Until(deadline), case_id)
}
/// Returns `true` if there is an offer or promise on the opposite side.
pub fn can_notify(&self) -> bool {
self.exchanger.inner.lock().wait_queues[self.index].can_notify()
}
/// Exchanges `msg` with the specified `wait` strategy.
fn exchange(
&self,
mut msg: T,
wait: Wait,
case_id: CaseId,
) -> Result<T, ExchangeError<T>> {
loop {
// Allocate a packet on the stack.
let packet;
{
let mut inner = self.exchanger.inner.lock();
if inner.closed {
return Err(ExchangeError::Disconnected(msg));
}
// If there's someone on the other side, exchange messages with it.
if let Some(case) = inner.wait_queues[self.index ^ 1].pop() {
drop(inner);
return Ok(case.exchange(msg, self.exchanger));
}
// Promise a packet with the message.
handle::current_reset();
packet = Packet::new(msg);
inner.wait_queues[self.index].offer(&packet, case_id);
}
let timed_out = match wait {
Wait::YieldOnce => {
thread::yield_now();
handle::current_try_select(CaseId::abort())
},
Wait::Until(deadline) => {
!handle::current_wait_until(deadline)
},
};
// If someone requested the promised message...
if handle::current_selected()!= CaseId::abort() {
// Wait until the message is taken and return.
packet.wait();
return Ok(packet.into_inner());
}
// Revoke the promise.
let mut inner = self.exchanger.inner.lock();
inner.wait_queues[self.index].revoke(case_id);
msg = packet.into_inner();
// If we timed out, return.
if timed_out {
return Err(ExchangeError::Timeout(msg));
}
// Otherwise, another thread must have woken us up. Let's try again.
}
}
}
enum Case<T> {
Offer {
handle: Handle,
packet: *const Packet<T>,
case_id: CaseId,
},
Promise { local: Arc<Local>, case_id: CaseId },
}
impl<T> Case<T> {
fn exchange(&self, msg: T, exchanger: &Exchanger<T>) -> T {
match *self {
Case::Offer {
ref handle, packet,..
} => {
let m = unsafe { (*packet).exchange(msg) };
handle.unpark();
m
}
Case::Promise { ref local,.. } => {
handle::current_reset();
let req = Request::new(msg, exchanger);
local.request_ptr.store(&req as *const _ as usize, Release);
local.handle.unpark();
handle::current_wait_until(None);
req.packet.into_inner()
}
}
}
fn handle(&self) -> &Handle {
match *self {
Case::Offer { ref handle,.. } => handle,
Case::Promise { ref local,.. } => &local.handle,
}
}
fn case_id(&self) -> CaseId {
match *self {
Case::Offer { case_id,.. } => case_id,
Case::Promise { case_id,.. } => case_id,
}
}
}
fn finish_exchange<T>(msg: T, exchanger: &Exchanger<T>) -> T {
let req = loop {
let ptr = LOCAL.with(|l| l.request_ptr.swap(0, Acquire) as *const Request<T>);
if!ptr.is_null() {
break ptr;
}
thread::yield_now();
};
unsafe {
assert!((*req).exchanger == exchanger);
let handle = (*req).handle.clone();
let m = (*req).packet.exchange(msg);
(*req).handle.try_select(CaseId::abort());
handle.unpark();
m
}
}
struct WaitQueue<T> {
cases: VecDeque<Case<T>>,
}
impl<T> WaitQueue<T> {
fn new() -> Self {
WaitQueue {
cases: VecDeque::new(),
}
}
fn pop(&mut self) -> Option<Case<T>> {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
if self.cases[i].handle().try_select(self.cases[i].case_id()) {
return Some(self.cases.remove(i).unwrap());
}
}
}
None
}
fn offer(&mut self, packet: *const Packet<T>, case_id: CaseId) {
self.cases.push_back(Case::Offer {
handle: handle::current(),
packet,
case_id,
});
}
fn promise(&mut self, case_id: CaseId) {
self.cases.push_back(Case::Promise {
local: LOCAL.with(|l| l.clone()),
case_id,
});
}
fn revoke(&mut self, case_id: CaseId) {
let thread_id = current_thread_id();
if let Some((i, _)) = self.cases.iter().enumerate().find(|&(_, case)| {
case.case_id() == case_id && case.handle().thread_id() == thread_id
}) {
self.cases.remove(i);
self.maybe_shrink();
}
}
fn can_notify(&self) -> bool {
let thread_id = current_thread_id();
for i in 0..self.cases.len() {
if self.cases[i].handle().thread_id()!= thread_id {
return true;
}
}
false
}
fn abort_all(&mut self) {
for case in self.cases.drain(..) {
case.handle().try_select(CaseId::abort());
case.handle().unpark();
}
self.maybe_shrink();
}
fn maybe_shrink(&mut self) {
if self.cases.capacity() > 32 && self.cases.capacity() / 2 > self.cases.len() {
self.cases.shrink_to_fit();
}
}
}
impl<T> Drop for WaitQueue<T> {
fn drop(&mut self) {
debug_assert!(self.cases.is_empty());
}
}
thread_local! {
static THREAD_ID: thread::ThreadId = thread::current().id();
}
fn current_thread_id() -> thread::ThreadId {
THREAD_ID.with(|id| *id)
}
thread_local! {
static LOCAL: Arc<Local> = Arc::new(Local {
handle: handle::current(),
request_ptr: AtomicUsize::new(0),
});
}
struct Local {
handle: Handle,
request_ptr: AtomicUsize,
}
struct Request<T> {
handle: Handle,
packet: Packet<T>,
exchanger: *const Exchanger<T>,
}
impl<T> Request<T> {
fn new(msg: T, exchanger: &Exchanger<T>) -> Self {
Request {
handle: handle::current(),
packet: Packet::new(msg),
exchanger,
}
}
}
struct Packet<T> {
msg: Mutex<Option<T>>,
ready: AtomicBool,
}
impl<T> Packet<T> {
fn new(msg: T) -> Self {
Packet {
msg: Mutex::new(Some(msg)),
ready: AtomicBool::new(false),
}
}
fn exchange(&self, msg: T) -> T {
let r = mem::replace(&mut *self.msg.try_lock().unwrap(), Some(msg));
self.ready.store(true, Release);
r.unwrap()
}
fn into_inner(self) -> T {
self.msg.try_lock().unwrap().take().unwrap()
}
/// Spin-waits until the packet becomes ready.
fn wait(&self) {
let mut backoff = Backoff::new();
while!self.ready.load(Acquire) {
backoff.step();
}
}
}
|
{
self.exchanger.inner.lock().wait_queues[self.index].revoke(case_id);
}
|
identifier_body
|
filters.rs
|
use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64) -> f64 + Send + Sync>
}
impl Filter {
pub fn new(resolution: Pixel, config: FilterConfig) -> Filter {
match config.function {
FilterFunctionConfig::Box => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(|_, _| 1.0)
},
FilterFunctionConfig::Gauss(alpha) => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(move |x, y| {
let gauss = |x: f64| -> f64 {
(-alpha * (x * x)).exp()
};
gauss(x) * gauss(y)
})
}
}
}
pub fn apply(&self, samples: &Vec<(Sample, Color)>) -> Image
|
fn neighbours(&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
let ok_pixel = |x, y| {
0 <= x && x < self.resolution[0] as i32 &&
0 <= y && y < self.resolution[1] as i32
};
let point = from_uniform(self.resolution, point);
let lower = point - self.extent;
let upper = point + self.extent;
let mut result = Vec::new();
for x in discretize_range(lower.x, upper.x) {
for y in discretize_range(lower.y, upper.y) {
if ok_pixel(x, y) {
result.push([x as u32, y as u32]);
}
}
}
result
}
}
|
{
let mut image = Image::fill(self.resolution, Color::new(0.0, 0.0, 0.0));
let mut weights = Matrix::<f64>::fill(self.resolution, 0.0);
for &(sample, radiance) in samples.iter() {
for pixel in self.neighbours(sample.pixel) {
let diff = ScreenPoint::from(pixel) - from_uniform(self.resolution, sample.pixel);
let weight = (self.weight)(diff.x.abs(), diff.y.abs());
image[pixel] = image[pixel] + radiance * weight;
weights[pixel] += weight;
}
}
for (i, weight) in weights.iter() {
if weight != 0.0 {
image[i] = image[i] / weight;
}
}
image
}
|
identifier_body
|
filters.rs
|
use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64) -> f64 + Send + Sync>
}
impl Filter {
pub fn new(resolution: Pixel, config: FilterConfig) -> Filter {
match config.function {
FilterFunctionConfig::Box => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(|_, _| 1.0)
},
FilterFunctionConfig::Gauss(alpha) => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(move |x, y| {
let gauss = |x: f64| -> f64 {
(-alpha * (x * x)).exp()
};
gauss(x) * gauss(y)
})
}
}
}
pub fn apply(&self, samples: &Vec<(Sample, Color)>) -> Image {
let mut image = Image::fill(self.resolution, Color::new(0.0, 0.0, 0.0));
let mut weights = Matrix::<f64>::fill(self.resolution, 0.0);
for &(sample, radiance) in samples.iter() {
for pixel in self.neighbours(sample.pixel) {
let diff = ScreenPoint::from(pixel) - from_uniform(self.resolution, sample.pixel);
let weight = (self.weight)(diff.x.abs(), diff.y.abs());
image[pixel] = image[pixel] + radiance * weight;
weights[pixel] += weight;
}
}
for (i, weight) in weights.iter() {
if weight!= 0.0 {
image[i] = image[i] / weight;
}
}
image
}
fn neighbours(&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
let ok_pixel = |x, y| {
0 <= x && x < self.resolution[0] as i32 &&
0 <= y && y < self.resolution[1] as i32
};
let point = from_uniform(self.resolution, point);
let lower = point - self.extent;
let upper = point + self.extent;
let mut result = Vec::new();
for x in discretize_range(lower.x, upper.x) {
for y in discretize_range(lower.y, upper.y) {
if ok_pixel(x, y)
|
}
}
result
}
}
|
{
result.push([x as u32, y as u32]);
}
|
conditional_block
|
filters.rs
|
use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64) -> f64 + Send + Sync>
}
impl Filter {
pub fn new(resolution: Pixel, config: FilterConfig) -> Filter {
match config.function {
FilterFunctionConfig::Box => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(|_, _| 1.0)
},
FilterFunctionConfig::Gauss(alpha) => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(move |x, y| {
let gauss = |x: f64| -> f64 {
(-alpha * (x * x)).exp()
};
gauss(x) * gauss(y)
})
}
}
}
pub fn apply(&self, samples: &Vec<(Sample, Color)>) -> Image {
let mut image = Image::fill(self.resolution, Color::new(0.0, 0.0, 0.0));
let mut weights = Matrix::<f64>::fill(self.resolution, 0.0);
for &(sample, radiance) in samples.iter() {
for pixel in self.neighbours(sample.pixel) {
let diff = ScreenPoint::from(pixel) - from_uniform(self.resolution, sample.pixel);
let weight = (self.weight)(diff.x.abs(), diff.y.abs());
image[pixel] = image[pixel] + radiance * weight;
weights[pixel] += weight;
}
}
for (i, weight) in weights.iter() {
if weight!= 0.0 {
image[i] = image[i] / weight;
}
}
image
}
fn
|
(&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
let ok_pixel = |x, y| {
0 <= x && x < self.resolution[0] as i32 &&
0 <= y && y < self.resolution[1] as i32
};
let point = from_uniform(self.resolution, point);
let lower = point - self.extent;
let upper = point + self.extent;
let mut result = Vec::new();
for x in discretize_range(lower.x, upper.x) {
for y in discretize_range(lower.y, upper.y) {
if ok_pixel(x, y) {
result.push([x as u32, y as u32]);
}
}
}
result
}
}
|
neighbours
|
identifier_name
|
filters.rs
|
use color::Color;
use utils::datastructures::Matrix;
use scene::ScreenPoint;
use super::{Image, Pixel};
use super::samplers::Sample;
use super::utils::from_uniform;
use super::config::{FilterConfig, FilterFunctionConfig};
pub struct Filter {
extent: ScreenPoint,
resolution: Pixel,
weight: Box<Fn(f64, f64) -> f64 + Send + Sync>
}
impl Filter {
pub fn new(resolution: Pixel, config: FilterConfig) -> Filter {
match config.function {
FilterFunctionConfig::Box => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(|_, _| 1.0)
},
FilterFunctionConfig::Gauss(alpha) => Filter {
extent: ScreenPoint::from(config.extent),
resolution: resolution,
weight: Box::new(move |x, y| {
let gauss = |x: f64| -> f64 {
(-alpha * (x * x)).exp()
};
gauss(x) * gauss(y)
})
}
}
}
pub fn apply(&self, samples: &Vec<(Sample, Color)>) -> Image {
let mut image = Image::fill(self.resolution, Color::new(0.0, 0.0, 0.0));
let mut weights = Matrix::<f64>::fill(self.resolution, 0.0);
for &(sample, radiance) in samples.iter() {
for pixel in self.neighbours(sample.pixel) {
let diff = ScreenPoint::from(pixel) - from_uniform(self.resolution, sample.pixel);
let weight = (self.weight)(diff.x.abs(), diff.y.abs());
image[pixel] = image[pixel] + radiance * weight;
weights[pixel] += weight;
}
}
for (i, weight) in weights.iter() {
|
image[i] = image[i] / weight;
}
}
image
}
fn neighbours(&self, point: ScreenPoint) -> Vec<Pixel> {
let discretize_range = |lower: f64, upper: f64| {
assert!(lower <= upper);
lower.ceil() as i32..upper.floor() as i32 + 1
};
let ok_pixel = |x, y| {
0 <= x && x < self.resolution[0] as i32 &&
0 <= y && y < self.resolution[1] as i32
};
let point = from_uniform(self.resolution, point);
let lower = point - self.extent;
let upper = point + self.extent;
let mut result = Vec::new();
for x in discretize_range(lower.x, upper.x) {
for y in discretize_range(lower.y, upper.y) {
if ok_pixel(x, y) {
result.push([x as u32, y as u32]);
}
}
}
result
}
}
|
if weight != 0.0 {
|
random_line_split
|
main.rs
|
extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response>
|
static HTTP_ADDR: &'static str = "localhost:4242";
fn main() {
let mut size: usize = 20;
let mut reverse: bool = false;
let mut server_mode: bool = false;
let mut skin = "███".to_string();
let padding = vec![" ", " ", "", " ", " ", " ", " ", " "];
{
// this block limits scope of borrows by ap.refer() method
let mut ap = ArgumentParser::new();
ap.set_description("Print a beautiful millipede (written in rust)");
ap.refer(&mut size)
.add_option(&["-w", "--width"], Store, "millipede width");
ap.refer(&mut skin)
.add_option(&["-s", "--skin"], Store, "millipede skin");
ap.refer(&mut reverse)
.add_option(&["-r", "--reverse"], StoreTrue, "reverse the millipede");
ap.refer(&mut server_mode)
.add_option(&["--server"], StoreTrue, "Spawn http server");
ap.parse_args_or_exit();
}
if server_mode == true {
let chain = Chain::new(http_server);
println!("Listening on {}", HTTP_ADDR);
Iron::new(chain).http(HTTP_ADDR).unwrap();
}
if reverse == false {
let mut i: usize = 0;
println!(" ╚⊙ ⊙╝");
while i < size {
println!("{}╚═({})═╝", padding[i % 8], skin);
i = i + 1;
}
} else {
let mut i: usize = size;
while i > 0 {
println!("{}╔═({})═╗", padding[i % 8], skin);
i = i - 1;
}
println!(" ╔⊙ ⊙╗");
}
}
|
{
Ok(Response::with((iron::status::Ok, "Rust server")))
}
|
identifier_body
|
main.rs
|
extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Rust server")))
}
static HTTP_ADDR: &'static str = "localhost:4242";
fn main() {
let mut size: usize = 20;
let mut reverse: bool = false;
let mut server_mode: bool = false;
let mut skin = "███".to_string();
let padding = vec![" ", " ", "", " ", " ", " ", " ", " "];
|
// this block limits scope of borrows by ap.refer() method
let mut ap = ArgumentParser::new();
ap.set_description("Print a beautiful millipede (written in rust)");
ap.refer(&mut size)
.add_option(&["-w", "--width"], Store, "millipede width");
ap.refer(&mut skin)
.add_option(&["-s", "--skin"], Store, "millipede skin");
ap.refer(&mut reverse)
.add_option(&["-r", "--reverse"], StoreTrue, "reverse the millipede");
ap.refer(&mut server_mode)
.add_option(&["--server"], StoreTrue, "Spawn http server");
ap.parse_args_or_exit();
}
if server_mode == true {
let chain = Chain::new(http_server);
println!("Listening on {}", HTTP_ADDR);
Iron::new(chain).http(HTTP_ADDR).unwrap();
}
if reverse == false {
let mut i: usize = 0;
println!(" ╚⊙ ⊙╝");
while i < size {
println!("{}╚═({})═╝", padding[i % 8], skin);
i = i + 1;
}
} else {
let mut i: usize = size;
while i > 0 {
println!("{}╔═({})═╗", padding[i % 8], skin);
i = i - 1;
}
println!(" ╔⊙ ⊙╗");
}
}
|
{
|
random_line_split
|
main.rs
|
extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Rust server")))
}
static HTTP_ADDR: &'static str = "localhost:4242";
fn
|
() {
let mut size: usize = 20;
let mut reverse: bool = false;
let mut server_mode: bool = false;
let mut skin = "███".to_string();
let padding = vec![" ", " ", "", " ", " ", " ", " ", " "];
{
// this block limits scope of borrows by ap.refer() method
let mut ap = ArgumentParser::new();
ap.set_description("Print a beautiful millipede (written in rust)");
ap.refer(&mut size)
.add_option(&["-w", "--width"], Store, "millipede width");
ap.refer(&mut skin)
.add_option(&["-s", "--skin"], Store, "millipede skin");
ap.refer(&mut reverse)
.add_option(&["-r", "--reverse"], StoreTrue, "reverse the millipede");
ap.refer(&mut server_mode)
.add_option(&["--server"], StoreTrue, "Spawn http server");
ap.parse_args_or_exit();
}
if server_mode == true {
let chain = Chain::new(http_server);
println!("Listening on {}", HTTP_ADDR);
Iron::new(chain).http(HTTP_ADDR).unwrap();
}
if reverse == false {
let mut i: usize = 0;
println!(" ╚⊙ ⊙╝");
while i < size {
println!("{}╚═({})═╝", padding[i % 8], skin);
i = i + 1;
}
} else {
let mut i: usize = size;
while i > 0 {
println!("{}╔═({})═╗", padding[i % 8], skin);
i = i - 1;
}
println!(" ╔⊙ ⊙╗");
}
}
|
main
|
identifier_name
|
main.rs
|
extern crate argparse;
extern crate iron;
use argparse::{ArgumentParser, StoreTrue, Store};
use iron::prelude::*;
fn http_server(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Rust server")))
}
static HTTP_ADDR: &'static str = "localhost:4242";
fn main() {
let mut size: usize = 20;
let mut reverse: bool = false;
let mut server_mode: bool = false;
let mut skin = "███".to_string();
let padding = vec![" ", " ", "", " ", " ", " ", " ", " "];
{
// this block limits scope of borrows by ap.refer() method
let mut ap = ArgumentParser::new();
ap.set_description("Print a beautiful millipede (written in rust)");
ap.refer(&mut size)
.add_option(&["-w", "--width"], Store, "millipede width");
ap.refer(&mut skin)
.add_option(&["-s", "--skin"], Store, "millipede skin");
ap.refer(&mut reverse)
.add_option(&["-r", "--reverse"], StoreTrue, "reverse the millipede");
ap.refer(&mut server_mode)
.add_option(&["--server"], StoreTrue, "Spawn http server");
ap.parse_args_or_exit();
}
if server_mode == true {
let chain = Chain::new(http_server);
println!("Listening on {}", HTTP_ADDR);
Iron::new(chain).http(HTTP_ADDR).unwrap();
}
if reverse == false {
|
t i: usize = size;
while i > 0 {
println!("{}╔═({})═╗", padding[i % 8], skin);
i = i - 1;
}
println!(" ╔⊙ ⊙╗");
}
}
|
let mut i: usize = 0;
println!(" ╚⊙ ⊙╝");
while i < size {
println!("{}╚═({})═╝", padding[i % 8], skin);
i = i + 1;
}
} else {
let mu
|
conditional_block
|
pipe.rs
|
use gfx;
use gfx_phase;
use gfx_scene;
use std::cmp::Ordering;
/// Custom ordering function to draw opaque objects first in a
/// front-to-back order, and transparent objects on top in a
/// back-to-front order.
pub fn
|
<S: PartialOrd, R: gfx::Resources>(
a: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>,
b: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>)
-> Ordering {
use ::Transparency::*;
match (a.kernel.transparency, b.kernel.transparency) {
(Blend(_), Blend(_)) => b.cmp_depth(a),
(Blend(_), _) => Ordering::Greater,
(_, Blend(_)) => Ordering::Less,
(_, _) => a.cmp_depth(b),
}
}
/// The foreard rendering pipeline.
pub struct Pipeline<R: gfx::Resources> {
/// The only rendering phase.
pub phase: super::Phase<R>,
/// Background color. Set to none if you don't want the screen to be cleared.
pub background: Option<gfx::ColorValue>,
}
impl<R: gfx::Resources> Pipeline<R> {
/// Create a new pipeline.
pub fn new<F: gfx::Factory<R>>(factory: &mut F)
-> Result<Pipeline<R>, super::Error> {
super::Technique::new(factory).map(|tech| Pipeline {
phase: gfx_phase::Phase::new("Main", tech)
.with_sort(order)
.with_cache(),
background: Some([0.0; 4]),
})
}
}
impl<R: gfx::Resources> ::Pipeline<f32, R> for Pipeline<R> {
fn render<A, T>(&mut self, scene: &A, camera: &A::Camera, stream: &mut T)
-> Result<A::Status, gfx_scene::Error> where
A: gfx_scene::AbstractScene<R, ViewInfo = ::view::Info<f32>, Material = ::Material<R>>,
T: gfx::Stream<R>,
{
// prepare
self.phase.technique.update(stream);
// clear
if let Some(color) = self.background {
stream.clear(gfx::ClearData {
color: color,
depth: 1.0,
stencil: 0,
});
}
// draw
scene.draw(&mut self.phase, camera, stream)
}
}
|
order
|
identifier_name
|
pipe.rs
|
use gfx;
use gfx_phase;
|
use gfx_scene;
use std::cmp::Ordering;
/// Custom ordering function to draw opaque objects first in a
/// front-to-back order, and transparent objects on top in a
/// back-to-front order.
pub fn order<S: PartialOrd, R: gfx::Resources>(
a: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>,
b: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>)
-> Ordering {
use ::Transparency::*;
match (a.kernel.transparency, b.kernel.transparency) {
(Blend(_), Blend(_)) => b.cmp_depth(a),
(Blend(_), _) => Ordering::Greater,
(_, Blend(_)) => Ordering::Less,
(_, _) => a.cmp_depth(b),
}
}
/// The foreard rendering pipeline.
pub struct Pipeline<R: gfx::Resources> {
/// The only rendering phase.
pub phase: super::Phase<R>,
/// Background color. Set to none if you don't want the screen to be cleared.
pub background: Option<gfx::ColorValue>,
}
impl<R: gfx::Resources> Pipeline<R> {
/// Create a new pipeline.
pub fn new<F: gfx::Factory<R>>(factory: &mut F)
-> Result<Pipeline<R>, super::Error> {
super::Technique::new(factory).map(|tech| Pipeline {
phase: gfx_phase::Phase::new("Main", tech)
.with_sort(order)
.with_cache(),
background: Some([0.0; 4]),
})
}
}
impl<R: gfx::Resources> ::Pipeline<f32, R> for Pipeline<R> {
fn render<A, T>(&mut self, scene: &A, camera: &A::Camera, stream: &mut T)
-> Result<A::Status, gfx_scene::Error> where
A: gfx_scene::AbstractScene<R, ViewInfo = ::view::Info<f32>, Material = ::Material<R>>,
T: gfx::Stream<R>,
{
// prepare
self.phase.technique.update(stream);
// clear
if let Some(color) = self.background {
stream.clear(gfx::ClearData {
color: color,
depth: 1.0,
stencil: 0,
});
}
// draw
scene.draw(&mut self.phase, camera, stream)
}
}
|
random_line_split
|
|
pipe.rs
|
use gfx;
use gfx_phase;
use gfx_scene;
use std::cmp::Ordering;
/// Custom ordering function to draw opaque objects first in a
/// front-to-back order, and transparent objects on top in a
/// back-to-front order.
pub fn order<S: PartialOrd, R: gfx::Resources>(
a: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>,
b: &gfx_phase::Object<S, super::Kernel, super::param::Struct<R>>)
-> Ordering {
use ::Transparency::*;
match (a.kernel.transparency, b.kernel.transparency) {
(Blend(_), Blend(_)) => b.cmp_depth(a),
(Blend(_), _) => Ordering::Greater,
(_, Blend(_)) => Ordering::Less,
(_, _) => a.cmp_depth(b),
}
}
/// The foreard rendering pipeline.
pub struct Pipeline<R: gfx::Resources> {
/// The only rendering phase.
pub phase: super::Phase<R>,
/// Background color. Set to none if you don't want the screen to be cleared.
pub background: Option<gfx::ColorValue>,
}
impl<R: gfx::Resources> Pipeline<R> {
/// Create a new pipeline.
pub fn new<F: gfx::Factory<R>>(factory: &mut F)
-> Result<Pipeline<R>, super::Error> {
super::Technique::new(factory).map(|tech| Pipeline {
phase: gfx_phase::Phase::new("Main", tech)
.with_sort(order)
.with_cache(),
background: Some([0.0; 4]),
})
}
}
impl<R: gfx::Resources> ::Pipeline<f32, R> for Pipeline<R> {
fn render<A, T>(&mut self, scene: &A, camera: &A::Camera, stream: &mut T)
-> Result<A::Status, gfx_scene::Error> where
A: gfx_scene::AbstractScene<R, ViewInfo = ::view::Info<f32>, Material = ::Material<R>>,
T: gfx::Stream<R>,
|
}
|
{
// prepare
self.phase.technique.update(stream);
// clear
if let Some(color) = self.background {
stream.clear(gfx::ClearData {
color: color,
depth: 1.0,
stencil: 0,
});
}
// draw
scene.draw(&mut self.phase, camera, stream)
}
|
identifier_body
|
lib.rs
|
use net_traits::image_cache::ImageCache;
use net_traits::storage_thread::StorageType;
use profile_traits::mem;
use profile_traits::time as profile_time;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use servo_atoms::Atom;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, RecvTimeoutError};
use style_traits::CSSPixel;
use style_traits::SpeculativePainter;
use style_traits::cursor::CursorKind;
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_api::{ExternalScrollId, DevicePixel, DeviceUintSize, DocumentId, ImageKey};
use webvr_traits::{WebVREvent, WebVRMsg};
pub use script_msg::{LayoutMsg, ScriptMsg, EventResult, LogEntry};
pub use script_msg::{ServiceWorkerMsg, ScopeThings, SWManagerMsg, SWManagerSenders, DOMMessage};
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct UntrustedNodeAddress(pub *const c_void);
malloc_size_of_is_0!(UntrustedNodeAddress);
#[allow(unsafe_code)]
unsafe impl Send for UntrustedNodeAddress {}
impl Serialize for UntrustedNodeAddress {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(self.0 as usize).serialize(s)
}
}
impl<'de> Deserialize<'de> for UntrustedNodeAddress {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
let value: usize = Deserialize::deserialize(d)?;
Ok(UntrustedNodeAddress::from_id(value))
}
}
impl UntrustedNodeAddress {
/// Creates an `UntrustedNodeAddress` from the given pointer address value.
#[inline]
pub fn from_id(id: usize) -> UntrustedNodeAddress {
UntrustedNodeAddress(id as *const c_void)
}
}
/// Messages sent to the layout thread from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout thread exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
/// Send the paint time for a specific epoch to the layout thread.
PaintMetric(Epoch, u64),
}
/// can be passed to `LoadUrl` to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoadData {
/// The URL.
pub url: ServoUrl,
/// The creator pipeline id if this is an about:blank load.
pub creator_pipeline_id: Option<PipelineId>,
/// The method.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub method: Method,
/// The headers.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub headers: Headers,
/// The data.
pub data: Option<Vec<u8>>,
/// The result of evaluating a javascript scheme url.
pub js_eval_result: Option<JsEvalResult>,
/// The referrer policy.
pub referrer_policy: Option<ReferrerPolicy>,
/// The referrer URL.
pub referrer_url: Option<ServoUrl>,
}
/// The result of evaluating a javascript scheme url.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum JsEvalResult {
/// The js evaluation had a non-string result, 204 status code.
/// <https://html.spec.whatwg.org/multipage/#navigate> 12.11
NoContent,
/// The js evaluation had a string result.
Ok(Vec<u8>)
}
impl LoadData {
/// Create a new `LoadData` object.
pub fn
|
(url: ServoUrl,
creator_pipeline_id: Option<PipelineId>,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<ServoUrl>)
-> LoadData {
LoadData {
url: url,
creator_pipeline_id: creator_pipeline_id,
method: Method::Get,
headers: Headers::new(),
data: None,
js_eval_result: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
/// The initial data required to create a new layout attached to an existing script thread.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// The ID of the parent pipeline and frame type, if any.
/// If `None`, this is a root pipeline.
pub parent_info: Option<PipelineId>,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the browsing context associated with this pipeline.
pub browsing_context_id: BrowsingContextId,
/// Id of the top-level browsing context associated with this pipeline.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// Network request data which will be initiated by the script thread.
pub load_data: LoadData,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: Option<IpcSender<()>>,
/// Number of threads to use for layout.
pub layout_threads: usize,
}
/// When a pipeline is closed, should its browsing context be discarded too?
#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum DiscardBrowsingContext {
/// Discard the browsing context
Yes,
/// Don't discard the browsing context
No,
}
/// Is a document fully active, active or inactive?
/// A document is active if it is the current active document in its session history,
/// it is fuly active if it is active and all of its ancestors are active,
/// and it is inactive otherwise.
///
/// * <https://html.spec.whatwg.org/multipage/#active-document>
/// * <https://html.spec.whatwg.org/multipage/#fully-active>
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum DocumentActivity {
/// An inactive document
Inactive,
/// An active but not fully active document
Active,
/// A fully active document
FullyActive,
}
/// Type of recorded progressive web metric
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum ProgressiveWebMetricType {
/// Time to first Paint
FirstPaint,
/// Time to first contentful paint
FirstContentfulPaint,
/// Time to interactive
TimeToInteractive,
}
/// The reason why the pipeline id of an iframe is being updated.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum UpdatePipelineIdReason {
/// The pipeline id is being updated due to a navigation.
Navigation,
/// The pipeline id is being updated due to a history traversal.
Traversal,
}
/// Messages sent from the constellation or layout to the script thread.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Sends the final response to script thread for fetching after all redirections
/// have been resolved
NavigationResponse(PipelineId, FetchResponseMsg),
/// Gives a channel and ID to a layout thread, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData, WindowSizeType),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, DiscardBrowsingContext),
/// Notifies the script that the whole thread should be closed.
ExitScriptThread,
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Notifies script of a new set of scroll offsets.
SetScrollState(PipelineId, Vec<(UntrustedNodeAddress, Vector2D<f32>)>),
/// Requests that the script thread immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script thread of a change to one of its document's activity
SetDocumentActivity(PipelineId, DocumentActivity),
/// Notifies script thread whether frame is visible
ChangeFrameVisibilityStatus(PipelineId, bool),
/// Notifies script thread that frame visibility change is complete
/// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
NotifyVisibilityChange(PipelineId, BrowsingContextId, bool),
/// Notifies script thread that a url should be loaded in this iframe.
/// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
Navigate(PipelineId, BrowsingContextId, LoadData, bool),
/// Post a message to a given window.
PostMessage(PipelineId, Option<ImmutableOrigin>, Vec<u8>),
/// Updates the current pipeline ID of a given iframe.
/// First PipelineId is for the parent, second is the new PipelineId for the frame.
UpdatePipelineId(PipelineId, BrowsingContextId, PipelineId, UpdatePipelineIdReason),
/// Updates the history state of a given pipeline.
UpdateHistoryStateId(PipelineId, Option<HistoryStateId>),
/// Removes inaccesible history states.
RemoveHistoryStates(PipelineId, Vec<HistoryStateId>),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
/// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
FocusIFrame(PipelineId, BrowsingContextId),
/// Passes a webdriver command to the script thread for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script thread that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script thread of a transition end
TransitionEnd(UntrustedNodeAddress, String, f64),
/// Notifies the script thread that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
/// Cause a `load` event to be dispatched at the appropriate iframe element.
DispatchIFrameLoadEvent {
/// The frame that has been marked as loaded.
target: BrowsingContextId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId,
/// The pipeline that has completed loading.
child: PipelineId,
},
/// Cause a `storage` event to be dispatched at the appropriate window.
/// The strings are key, old value and new value.
DispatchStorageEvent(PipelineId, StorageType, ServoUrl, Option<String>, Option<String>, Option<String>),
/// Report an error from a CSS parser for the given pipeline
ReportCSSError(PipelineId, String, u32, u32, String),
/// Reload the given page.
Reload(PipelineId),
/// Notifies the script thread of WebVR events.
WebVREvents(PipelineId, Vec<WebVREvent>),
/// Notifies the script thread about a new recorded paint metric.
PaintMetric(PipelineId, ProgressiveWebMetricType, u64),
}
impl fmt::Debug for ConstellationControlMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationControlMsg::*;
let variant = match *self {
NavigationResponse(..) => "NavigationResponse",
AttachLayout(..) => "AttachLayout",
Resize(..) => "Resize",
ResizeInactive(..) => "ResizeInactive",
ExitPipeline(..) => "ExitPipeline",
ExitScriptThread => "ExitScriptThread",
SendEvent(..) => "SendEvent",
Viewport(..) => "Viewport",
SetScrollState(..) => "SetScrollState",
GetTitle(..) => "GetTitle",
SetDocumentActivity(..) => "SetDocumentActivity",
ChangeFrameVisibilityStatus(..) => "ChangeFrameVisibilityStatus",
NotifyVisibilityChange(..) => "NotifyVisibilityChange",
Navigate(..) => "Navigate",
PostMessage(..) => "PostMessage",
UpdatePipelineId(..) => "UpdatePipelineId",
UpdateHistoryStateId(..) => "UpdateHistoryStateId",
RemoveHistoryStates(..) => "RemoveHistoryStates",
FocusIFrame(..) => "FocusIFrame",
WebDriverScriptCommand(..) => "WebDriverScriptCommand",
TickAllAnimations(..) => "TickAllAnimations",
TransitionEnd(..) => "TransitionEnd",
WebFontLoaded(..) => "WebFontLoaded",
DispatchIFrameLoadEvent {.. } => "DispatchIFrameLoadEvent",
DispatchStorageEvent(..) => "DispatchStorageEvent",
ReportCSSError(..) => "ReportCSSError",
Reload(..) => "Reload",
WebVREvents(..) => "WebVREvents",
PaintMetric(..) => "PaintMetric",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
/// For a given pipeline, whether any animations are currently running
/// and any animation callbacks are queued
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AnimationState {
/// Animations are active but no callbacks are queued
AnimationsPresent,
/// Animations are active and callbacks are queued
AnimationCallbacksPresent,
/// No animations are active and no callbacks are queued
NoAnimationsPresent,
/// No animations are active but callbacks are queued
NoAnimationCallbacksPresent,
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// <http://w3c.github.io/touch-events/#widl-Touch-identifier>
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TouchId(pub i32);
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// The types of mouse events
#[derive(Deserialize, MallocSizeOf, Serialize)]
pub enum MouseEventType {
/// Mouse button clicked
Click,
/// Mouse button down
MouseDown,
/// Mouse button up
MouseUp,
}
/// Events from the compositor that the script thread needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData, WindowSizeType),
/// A mouse button state changed.
MouseButtonEvent(
MouseEventType,
MouseButton,
Point2D<f32>,
Option<UntrustedNodeAddress>,
Option<Point2D<f32>>
),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>, Option<UntrustedNodeAddress>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>, Option<UntrustedNodeAddress>),
/// A key was pressed.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
}
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>, pub TimerSource, pub TimerEventId, pub MsDuration);
/// Type of messages that can be sent to the timer scheduler.
#[derive(Deserialize, Serialize)]
pub enum TimerSchedulerMsg {
/// Message to schedule a new timer event.
Request(TimerEventRequest),
/// Message to exit the timer scheduler.
Exit,
}
/// Notifies the script thread to fire due timers.
/// `TimerSource` must be `FromWindow` when dispatched to `ScriptThread` and
/// must be `FromWorker` when dispatched to a `DedicatedGlobalWorkerScope`
#[derive(Debug, Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
/// Describes the thread that requested the TimerEvent.
#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
pub enum TimerSource {
/// The event was requested from a window (ScriptThread).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker,
}
/// The id to be used for a `TimerEvent` is defined by the corresponding `TimerEventRequest`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, MallocSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, MallocSizeOf)]
pub enum Nanoseconds {}
/// Amount of milliseconds.
pub type MsDuration = Length<u64, Milliseconds>;
/// Amount of nanoseconds.
pub type NsDuration = Length<u64, Nanoseconds>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<PipelineId>,
/// The ID of the browsing context this script is part of.
pub browsing_context_id: BrowsingContextId,
/// The ID of the top-level browsing context this script is part of.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// A channel with which messages can be sent to us (the script thread).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub script_to_constellation_chan: ScriptToConstellationChan,
/// A sender for the layout thread to communicate to the constellation.
pub layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerSchedulerMsg>,
/// A channel to the resource manager thread.
pub resource_threads: ResourceThreads,
/// A channel to the bluetooth thread.
pub bluetooth_thread: IpcSender<BluetoothRequest>,
/// The image cache for this script thread.
pub image_cache: Arc<ImageCache>,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
/// A channel to the WebGL thread used in this pipeline.
pub webgl_chan: Option<WebGLPipeline>,
/// A channel to the webvr thread, if available.
pub webvr_chan: Option<IpcSender<WebVRMsg>>,
/// The Webrender document ID associated with this thread.
pub webrender_document: DocumentId,
}
/// This trait allows creating a `ScriptThread` without depending on the `script`
/// crate.
pub trait ScriptThreadFactory {
/// Type of message sent from script to layout.
type Message;
/// Create a `ScriptThread`.
fn create(state: InitialScriptState, load_data: LoadData)
-> (Sender<Self::Message>, Receiver<Self::Message>);
}
/// Whether the sandbox attribute is present for an iframe element
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum IFrameSandboxState {
/// Sandbox attribute is present
IFrameSandboxed,
/// Sandbox attribute is not present
IFrameUnsandboxed,
}
/// Specifies the information required to load an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfo {
/// Pipeline ID of the parent of this iframe
pub parent_pipeline_id: PipelineId,
/// The ID for this iframe's nested browsing context.
pub browsing_context_id: BrowsingContextId,
/// The ID for the top-level ancestor browsing context of this iframe's nested browsing context.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Whether this iframe should be considered private
pub is_private: bool,
/// Wether this load should replace the current entry (reload). If true, the current
/// entry will be replaced instead of a new entry being added.
pub replace: bool,
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfoWithData {
/// The information required to load an iframe.
pub info: IFrameLoadInfo,
/// Load data containing the url to load
pub load_data: Option<LoadData>,
/// The old pipeline ID for this iframe, if a page was previously loaded.
pub old_pipeline_id: Option<PipelineId>,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
/// The script thread.
Script,
/// The layout thread.
Layout,
}
/// The scroll state of a stacking context.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct ScrollState {
/// The ID of the scroll root.
pub scroll_id: ExternalScrollId,
/// The scrolling offset of this stacking context.
pub scroll_offset: Vector2D<f32>,
}
/// Data about the window size.
#[derive(Clone, Copy, Deserialize, MallocSizeOf, Serialize)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// <http://www.w3.org/TR/css-device-adapt/#initial-viewport>
pub initial_viewport: TypedSize2D<f32, CSSPixel>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>,
}
/// The type of window size change.
#[derive(Clone, Copy, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum WindowSizeType {
/// Initial load.
Initial,
/// Window resize.
Resize,
}
/// Messages to the constellation originating from the WebDriver server.
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
/// Get the window size.
GetWindowSize(TopLevelBrowsingContextId, IpcSender<WindowSizeData>),
/// Load a URL in the top-level browsing context with the given ID.
LoadUrl(TopLevelBrowsingContextId, LoadData, IpcSender<LoadStatus>),
/// Refresh the top-level browsing context with the given ID.
Refresh(TopLevelBrowsingContextId, IpcSender<LoadStatus>),
/// Pass a webdriver command to the script thread of the current pipeline
/// of a browsing context.
ScriptCommand(BrowsingContextId, WebDriverScriptCommand),
/// Act as if keys were pressed in the browsing context with the given ID.
SendKeys(BrowsingContextId, Vec<(Key, KeyModifiers, KeyState)>),
/// Set the window size.
SetWindowSize(TopLevelBrowsingContextId, DeviceUintSize, IpcSender<WindowSizeData>),
/// Take a screenshot of the window.
TakeScreenshot(TopLevelBrowsingContextId, IpcSender<Option<Image>>),
}
/// Messages to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ConstellationMsg {
/// Exit the constellation.
Exit,
/// Request that the constellation send the BrowsingContextId corresponding to the document
/// with the provided pipeline id
GetBrowsingContext(PipelineId, IpcSender<Option<BrowsingContextId>>),
/// Request that the constellation send the current pipeline id for the provided
/// browsing context id, over a provided channel.
GetPipeline(BrowsingContextId, IpcSender<Option<PipelineId>>),
/// Request that the constellation send the current focused top-level browsing context id,
/// over a provided channel.
GetFocusTopLevelBrowsingContext(IpcSender<Option<TopLevelBrowsingContextId>>),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Inform the constellation of a key event.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Request to load a page.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Request to traverse the joint session history of the provided browsing context.
TraverseHistory(TopLevelBrowsingContextId, TraversalDirection),
/// Inform the constellation of a window being resized.
WindowSize(Option<TopLevelBrowsingContextId>, WindowSizeData, WindowSizeType),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
/// Reload a top-level browsing context.
Reload(TopLevelBrowsingContextId),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<TopLevelBrowsingContextId>, Option<String>, LogEntry),
/// Dispatch WebVR events to the subscribed script threads.
WebVREvents(Vec<PipelineId>, Vec<WebVREvent>),
/// Create a new top level browsing context.
NewBrowser(ServoUrl, IpcSender<TopLevelBrowsingContextId>),
/// Close a top level browsing context.
CloseBrowser(TopLevelBrowsingContextId),
/// Make browser visible.
SelectBrowser(TopLevelBrowsingContextId),
/// Forward
|
new
|
identifier_name
|
lib.rs
|
;
use net_traits::image_cache::ImageCache;
use net_traits::storage_thread::StorageType;
use profile_traits::mem;
use profile_traits::time as profile_time;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use servo_atoms::Atom;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, RecvTimeoutError};
use style_traits::CSSPixel;
use style_traits::SpeculativePainter;
use style_traits::cursor::CursorKind;
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_api::{ExternalScrollId, DevicePixel, DeviceUintSize, DocumentId, ImageKey};
use webvr_traits::{WebVREvent, WebVRMsg};
pub use script_msg::{LayoutMsg, ScriptMsg, EventResult, LogEntry};
pub use script_msg::{ServiceWorkerMsg, ScopeThings, SWManagerMsg, SWManagerSenders, DOMMessage};
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct UntrustedNodeAddress(pub *const c_void);
malloc_size_of_is_0!(UntrustedNodeAddress);
#[allow(unsafe_code)]
unsafe impl Send for UntrustedNodeAddress {}
impl Serialize for UntrustedNodeAddress {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(self.0 as usize).serialize(s)
}
}
impl<'de> Deserialize<'de> for UntrustedNodeAddress {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
let value: usize = Deserialize::deserialize(d)?;
Ok(UntrustedNodeAddress::from_id(value))
}
}
impl UntrustedNodeAddress {
/// Creates an `UntrustedNodeAddress` from the given pointer address value.
#[inline]
pub fn from_id(id: usize) -> UntrustedNodeAddress {
UntrustedNodeAddress(id as *const c_void)
}
}
/// Messages sent to the layout thread from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout thread exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
/// Send the paint time for a specific epoch to the layout thread.
PaintMetric(Epoch, u64),
}
/// can be passed to `LoadUrl` to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoadData {
/// The URL.
pub url: ServoUrl,
/// The creator pipeline id if this is an about:blank load.
pub creator_pipeline_id: Option<PipelineId>,
/// The method.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub method: Method,
/// The headers.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub headers: Headers,
/// The data.
pub data: Option<Vec<u8>>,
/// The result of evaluating a javascript scheme url.
pub js_eval_result: Option<JsEvalResult>,
/// The referrer policy.
pub referrer_policy: Option<ReferrerPolicy>,
/// The referrer URL.
pub referrer_url: Option<ServoUrl>,
}
/// The result of evaluating a javascript scheme url.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum JsEvalResult {
/// The js evaluation had a non-string result, 204 status code.
/// <https://html.spec.whatwg.org/multipage/#navigate> 12.11
NoContent,
/// The js evaluation had a string result.
Ok(Vec<u8>)
}
impl LoadData {
/// Create a new `LoadData` object.
pub fn new(url: ServoUrl,
creator_pipeline_id: Option<PipelineId>,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<ServoUrl>)
-> LoadData {
LoadData {
url: url,
creator_pipeline_id: creator_pipeline_id,
method: Method::Get,
headers: Headers::new(),
data: None,
js_eval_result: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
/// The initial data required to create a new layout attached to an existing script thread.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// The ID of the parent pipeline and frame type, if any.
/// If `None`, this is a root pipeline.
pub parent_info: Option<PipelineId>,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the browsing context associated with this pipeline.
pub browsing_context_id: BrowsingContextId,
/// Id of the top-level browsing context associated with this pipeline.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// Network request data which will be initiated by the script thread.
pub load_data: LoadData,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: Option<IpcSender<()>>,
/// Number of threads to use for layout.
pub layout_threads: usize,
}
/// When a pipeline is closed, should its browsing context be discarded too?
#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum DiscardBrowsingContext {
/// Discard the browsing context
Yes,
/// Don't discard the browsing context
No,
}
/// Is a document fully active, active or inactive?
/// A document is active if it is the current active document in its session history,
/// it is fuly active if it is active and all of its ancestors are active,
/// and it is inactive otherwise.
///
/// * <https://html.spec.whatwg.org/multipage/#active-document>
/// * <https://html.spec.whatwg.org/multipage/#fully-active>
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum DocumentActivity {
/// An inactive document
Inactive,
/// An active but not fully active document
Active,
/// A fully active document
FullyActive,
}
/// Type of recorded progressive web metric
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum ProgressiveWebMetricType {
/// Time to first Paint
FirstPaint,
/// Time to first contentful paint
FirstContentfulPaint,
/// Time to interactive
TimeToInteractive,
}
/// The reason why the pipeline id of an iframe is being updated.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
pub enum UpdatePipelineIdReason {
/// The pipeline id is being updated due to a navigation.
Navigation,
/// The pipeline id is being updated due to a history traversal.
Traversal,
}
/// Messages sent from the constellation or layout to the script thread.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Sends the final response to script thread for fetching after all redirections
/// have been resolved
NavigationResponse(PipelineId, FetchResponseMsg),
/// Gives a channel and ID to a layout thread, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData, WindowSizeType),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, DiscardBrowsingContext),
/// Notifies the script that the whole thread should be closed.
ExitScriptThread,
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Notifies script of a new set of scroll offsets.
SetScrollState(PipelineId, Vec<(UntrustedNodeAddress, Vector2D<f32>)>),
/// Requests that the script thread immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script thread of a change to one of its document's activity
SetDocumentActivity(PipelineId, DocumentActivity),
/// Notifies script thread whether frame is visible
ChangeFrameVisibilityStatus(PipelineId, bool),
/// Notifies script thread that frame visibility change is complete
/// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
NotifyVisibilityChange(PipelineId, BrowsingContextId, bool),
/// Notifies script thread that a url should be loaded in this iframe.
/// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
Navigate(PipelineId, BrowsingContextId, LoadData, bool),
/// Post a message to a given window.
PostMessage(PipelineId, Option<ImmutableOrigin>, Vec<u8>),
/// Updates the current pipeline ID of a given iframe.
/// First PipelineId is for the parent, second is the new PipelineId for the frame.
UpdatePipelineId(PipelineId, BrowsingContextId, PipelineId, UpdatePipelineIdReason),
/// Updates the history state of a given pipeline.
UpdateHistoryStateId(PipelineId, Option<HistoryStateId>),
/// Removes inaccesible history states.
RemoveHistoryStates(PipelineId, Vec<HistoryStateId>),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
/// PipelineId is for the parent, BrowsingContextId is for the nested browsing context
FocusIFrame(PipelineId, BrowsingContextId),
/// Passes a webdriver command to the script thread for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script thread that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script thread of a transition end
TransitionEnd(UntrustedNodeAddress, String, f64),
/// Notifies the script thread that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
|
DispatchIFrameLoadEvent {
/// The frame that has been marked as loaded.
target: BrowsingContextId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId,
/// The pipeline that has completed loading.
child: PipelineId,
},
/// Cause a `storage` event to be dispatched at the appropriate window.
/// The strings are key, old value and new value.
DispatchStorageEvent(PipelineId, StorageType, ServoUrl, Option<String>, Option<String>, Option<String>),
/// Report an error from a CSS parser for the given pipeline
ReportCSSError(PipelineId, String, u32, u32, String),
/// Reload the given page.
Reload(PipelineId),
/// Notifies the script thread of WebVR events.
WebVREvents(PipelineId, Vec<WebVREvent>),
/// Notifies the script thread about a new recorded paint metric.
PaintMetric(PipelineId, ProgressiveWebMetricType, u64),
}
impl fmt::Debug for ConstellationControlMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationControlMsg::*;
let variant = match *self {
NavigationResponse(..) => "NavigationResponse",
AttachLayout(..) => "AttachLayout",
Resize(..) => "Resize",
ResizeInactive(..) => "ResizeInactive",
ExitPipeline(..) => "ExitPipeline",
ExitScriptThread => "ExitScriptThread",
SendEvent(..) => "SendEvent",
Viewport(..) => "Viewport",
SetScrollState(..) => "SetScrollState",
GetTitle(..) => "GetTitle",
SetDocumentActivity(..) => "SetDocumentActivity",
ChangeFrameVisibilityStatus(..) => "ChangeFrameVisibilityStatus",
NotifyVisibilityChange(..) => "NotifyVisibilityChange",
Navigate(..) => "Navigate",
PostMessage(..) => "PostMessage",
UpdatePipelineId(..) => "UpdatePipelineId",
UpdateHistoryStateId(..) => "UpdateHistoryStateId",
RemoveHistoryStates(..) => "RemoveHistoryStates",
FocusIFrame(..) => "FocusIFrame",
WebDriverScriptCommand(..) => "WebDriverScriptCommand",
TickAllAnimations(..) => "TickAllAnimations",
TransitionEnd(..) => "TransitionEnd",
WebFontLoaded(..) => "WebFontLoaded",
DispatchIFrameLoadEvent {.. } => "DispatchIFrameLoadEvent",
DispatchStorageEvent(..) => "DispatchStorageEvent",
ReportCSSError(..) => "ReportCSSError",
Reload(..) => "Reload",
WebVREvents(..) => "WebVREvents",
PaintMetric(..) => "PaintMetric",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
/// For a given pipeline, whether any animations are currently running
/// and any animation callbacks are queued
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AnimationState {
/// Animations are active but no callbacks are queued
AnimationsPresent,
/// Animations are active and callbacks are queued
AnimationCallbacksPresent,
/// No animations are active and no callbacks are queued
NoAnimationsPresent,
/// No animations are active but callbacks are queued
NoAnimationCallbacksPresent,
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// <http://w3c.github.io/touch-events/#widl-Touch-identifier>
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TouchId(pub i32);
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// The types of mouse events
#[derive(Deserialize, MallocSizeOf, Serialize)]
pub enum MouseEventType {
/// Mouse button clicked
Click,
/// Mouse button down
MouseDown,
/// Mouse button up
MouseUp,
}
/// Events from the compositor that the script thread needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData, WindowSizeType),
/// A mouse button state changed.
MouseButtonEvent(
MouseEventType,
MouseButton,
Point2D<f32>,
Option<UntrustedNodeAddress>,
Option<Point2D<f32>>
),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>, Option<UntrustedNodeAddress>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>, Option<UntrustedNodeAddress>),
/// A key was pressed.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
}
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>, pub TimerSource, pub TimerEventId, pub MsDuration);
/// Type of messages that can be sent to the timer scheduler.
#[derive(Deserialize, Serialize)]
pub enum TimerSchedulerMsg {
/// Message to schedule a new timer event.
Request(TimerEventRequest),
/// Message to exit the timer scheduler.
Exit,
}
/// Notifies the script thread to fire due timers.
/// `TimerSource` must be `FromWindow` when dispatched to `ScriptThread` and
/// must be `FromWorker` when dispatched to a `DedicatedGlobalWorkerScope`
#[derive(Debug, Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
/// Describes the thread that requested the TimerEvent.
#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
pub enum TimerSource {
/// The event was requested from a window (ScriptThread).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker,
}
/// The id to be used for a `TimerEvent` is defined by the corresponding `TimerEventRequest`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, MallocSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, MallocSizeOf)]
pub enum Nanoseconds {}
/// Amount of milliseconds.
pub type MsDuration = Length<u64, Milliseconds>;
/// Amount of nanoseconds.
pub type NsDuration = Length<u64, Nanoseconds>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<PipelineId>,
/// The ID of the browsing context this script is part of.
pub browsing_context_id: BrowsingContextId,
/// The ID of the top-level browsing context this script is part of.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// A channel with which messages can be sent to us (the script thread).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub script_to_constellation_chan: ScriptToConstellationChan,
/// A sender for the layout thread to communicate to the constellation.
pub layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerSchedulerMsg>,
/// A channel to the resource manager thread.
pub resource_threads: ResourceThreads,
/// A channel to the bluetooth thread.
pub bluetooth_thread: IpcSender<BluetoothRequest>,
/// The image cache for this script thread.
pub image_cache: Arc<ImageCache>,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
/// A channel to the WebGL thread used in this pipeline.
pub webgl_chan: Option<WebGLPipeline>,
/// A channel to the webvr thread, if available.
pub webvr_chan: Option<IpcSender<WebVRMsg>>,
/// The Webrender document ID associated with this thread.
pub webrender_document: DocumentId,
}
/// This trait allows creating a `ScriptThread` without depending on the `script`
/// crate.
pub trait ScriptThreadFactory {
/// Type of message sent from script to layout.
type Message;
/// Create a `ScriptThread`.
fn create(state: InitialScriptState, load_data: LoadData)
-> (Sender<Self::Message>, Receiver<Self::Message>);
}
/// Whether the sandbox attribute is present for an iframe element
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum IFrameSandboxState {
/// Sandbox attribute is present
IFrameSandboxed,
/// Sandbox attribute is not present
IFrameUnsandboxed,
}
/// Specifies the information required to load an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfo {
/// Pipeline ID of the parent of this iframe
pub parent_pipeline_id: PipelineId,
/// The ID for this iframe's nested browsing context.
pub browsing_context_id: BrowsingContextId,
/// The ID for the top-level ancestor browsing context of this iframe's nested browsing context.
pub top_level_browsing_context_id: TopLevelBrowsingContextId,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Whether this iframe should be considered private
pub is_private: bool,
/// Wether this load should replace the current entry (reload). If true, the current
/// entry will be replaced instead of a new entry being added.
pub replace: bool,
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfoWithData {
/// The information required to load an iframe.
pub info: IFrameLoadInfo,
/// Load data containing the url to load
pub load_data: Option<LoadData>,
/// The old pipeline ID for this iframe, if a page was previously loaded.
pub old_pipeline_id: Option<PipelineId>,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
/// The script thread.
Script,
/// The layout thread.
Layout,
}
/// The scroll state of a stacking context.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct ScrollState {
/// The ID of the scroll root.
pub scroll_id: ExternalScrollId,
/// The scrolling offset of this stacking context.
pub scroll_offset: Vector2D<f32>,
}
/// Data about the window size.
#[derive(Clone, Copy, Deserialize, MallocSizeOf, Serialize)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// <http://www.w3.org/TR/css-device-adapt/#initial-viewport>
pub initial_viewport: TypedSize2D<f32, CSSPixel>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>,
}
/// The type of window size change.
#[derive(Clone, Copy, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum WindowSizeType {
/// Initial load.
Initial,
/// Window resize.
Resize,
}
/// Messages to the constellation originating from the WebDriver server.
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
/// Get the window size.
GetWindowSize(TopLevelBrowsingContextId, IpcSender<WindowSizeData>),
/// Load a URL in the top-level browsing context with the given ID.
LoadUrl(TopLevelBrowsingContextId, LoadData, IpcSender<LoadStatus>),
/// Refresh the top-level browsing context with the given ID.
Refresh(TopLevelBrowsingContextId, IpcSender<LoadStatus>),
/// Pass a webdriver command to the script thread of the current pipeline
/// of a browsing context.
ScriptCommand(BrowsingContextId, WebDriverScriptCommand),
/// Act as if keys were pressed in the browsing context with the given ID.
SendKeys(BrowsingContextId, Vec<(Key, KeyModifiers, KeyState)>),
/// Set the window size.
SetWindowSize(TopLevelBrowsingContextId, DeviceUintSize, IpcSender<WindowSizeData>),
/// Take a screenshot of the window.
TakeScreenshot(TopLevelBrowsingContextId, IpcSender<Option<Image>>),
}
/// Messages to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ConstellationMsg {
/// Exit the constellation.
Exit,
/// Request that the constellation send the BrowsingContextId corresponding to the document
/// with the provided pipeline id
GetBrowsingContext(PipelineId, IpcSender<Option<BrowsingContextId>>),
/// Request that the constellation send the current pipeline id for the provided
/// browsing context id, over a provided channel.
GetPipeline(BrowsingContextId, IpcSender<Option<PipelineId>>),
/// Request that the constellation send the current focused top-level browsing context id,
/// over a provided channel.
GetFocusTopLevelBrowsingContext(IpcSender<Option<TopLevelBrowsingContextId>>),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
/// Inform the constellation of a key event.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Request to load a page.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Request to traverse the joint session history of the provided browsing context.
TraverseHistory(TopLevelBrowsingContextId, TraversalDirection),
/// Inform the constellation of a window being resized.
WindowSize(Option<TopLevelBrowsingContextId>, WindowSizeData, WindowSizeType),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
/// Reload a top-level browsing context.
Reload(TopLevelBrowsingContextId),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<TopLevelBrowsingContextId>, Option<String>, LogEntry),
/// Dispatch WebVR events to the subscribed script threads.
WebVREvents(Vec<PipelineId>, Vec<WebVREvent>),
/// Create a new top level browsing context.
NewBrowser(ServoUrl, IpcSender<TopLevelBrowsingContextId>),
/// Close a top level browsing context.
CloseBrowser(TopLevelBrowsingContextId),
/// Make browser visible.
SelectBrowser(TopLevelBrowsingContextId),
/// Forward an event
|
/// Cause a `load` event to be dispatched at the appropriate iframe element.
|
random_line_split
|
doco.rs
|
use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct Item<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}
}
pub struct Module<T>(pub T);
impl<T: AsRef<str>> Display for Module<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "//!", fmt)
}
}
fn preprocess(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult
|
fn prefix(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
for (i, line) in input.lines().enumerate() {
if i > 0 {
fmt.write_char('\n')?;
}
if line.len() == 0 {
write!(fmt, "{}", pre)?;
} else {
write!(fmt, "{} {}", pre, line.trim())?;
}
}
Ok(())
}
|
{
// fix up problems in AWS docs
let escaped_1 = input.replace("<code>\\</code>", "<code>\</code>");
let escaped_2 = escaped_1.replace("\"</p>\"", "</p>");
// parse and render markdown
let markdown = Markdown::new(&escaped_2);
let mut html_renderer = Html::new(Flags::empty(), 0);
let buffer = html_renderer.render(&markdown);
let rendered = buffer.to_str().unwrap();
// prefix and write to formatter
prefix(&rendered, pre, fmt)
}
|
identifier_body
|
doco.rs
|
use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct Item<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}
}
pub struct Module<T>(pub T);
impl<T: AsRef<str>> Display for Module<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "//!", fmt)
}
}
fn preprocess(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
// fix up problems in AWS docs
let escaped_1 = input.replace("<code>\\</code>", "<code>\</code>");
let escaped_2 = escaped_1.replace("\"</p>\"", "</p>");
// parse and render markdown
let markdown = Markdown::new(&escaped_2);
let mut html_renderer = Html::new(Flags::empty(), 0);
let buffer = html_renderer.render(&markdown);
let rendered = buffer.to_str().unwrap();
// prefix and write to formatter
prefix(&rendered, pre, fmt)
}
fn prefix(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
for (i, line) in input.lines().enumerate() {
if i > 0 {
fmt.write_char('\n')?;
}
if line.len() == 0 {
write!(fmt, "{}", pre)?;
} else
|
}
Ok(())
}
|
{
write!(fmt, "{} {}", pre, line.trim())?;
}
|
conditional_block
|
doco.rs
|
use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct Item<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}
}
pub struct Module<T>(pub T);
impl<T: AsRef<str>> Display for Module<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "//!", fmt)
}
}
fn preprocess(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
// fix up problems in AWS docs
let escaped_1 = input.replace("<code>\\</code>", "<code>\</code>");
let escaped_2 = escaped_1.replace("\"</p>\"", "</p>");
// parse and render markdown
let markdown = Markdown::new(&escaped_2);
let mut html_renderer = Html::new(Flags::empty(), 0);
let buffer = html_renderer.render(&markdown);
let rendered = buffer.to_str().unwrap();
// prefix and write to formatter
prefix(&rendered, pre, fmt)
}
fn prefix(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
for (i, line) in input.lines().enumerate() {
|
if i > 0 {
fmt.write_char('\n')?;
}
if line.len() == 0 {
write!(fmt, "{}", pre)?;
} else {
write!(fmt, "{} {}", pre, line.trim())?;
}
}
Ok(())
}
|
random_line_split
|
|
doco.rs
|
use std::fmt::{Display, Formatter, Result as FmtResult, Write};
use hoedown::{Markdown, Render};
use hoedown::renderer::html::{Html, Flags};
pub struct
|
<T>(pub T);
impl<T: AsRef<str>> Display for Item<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "///", fmt)
}
}
pub struct Module<T>(pub T);
impl<T: AsRef<str>> Display for Module<T> {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
preprocess(self.0.as_ref(), "//!", fmt)
}
}
fn preprocess(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
// fix up problems in AWS docs
let escaped_1 = input.replace("<code>\\</code>", "<code>\</code>");
let escaped_2 = escaped_1.replace("\"</p>\"", "</p>");
// parse and render markdown
let markdown = Markdown::new(&escaped_2);
let mut html_renderer = Html::new(Flags::empty(), 0);
let buffer = html_renderer.render(&markdown);
let rendered = buffer.to_str().unwrap();
// prefix and write to formatter
prefix(&rendered, pre, fmt)
}
fn prefix(input: &str, pre: &str, fmt: &mut Formatter) -> FmtResult {
for (i, line) in input.lines().enumerate() {
if i > 0 {
fmt.write_char('\n')?;
}
if line.len() == 0 {
write!(fmt, "{}", pre)?;
} else {
write!(fmt, "{} {}", pre, line.trim())?;
}
}
Ok(())
}
|
Item
|
identifier_name
|
main.rs
|
extern crate rand;
extern crate walkdir;
use walkdir::WalkDir;
use rand::{Rng, thread_rng};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{Error, SeekFrom};
use std::cmp;
use std::path::Path;
fn
|
() {
let mut recursive: bool = false;
let mut file: String = String::from("");
for argument in env::args().skip(1) {
if argument.to_lowercase() == "--help" || argument.to_lowercase() == "-help" {
help();
return;
} else if argument.to_lowercase() == "--v" || argument.to_lowercase() == "-v" ||
argument.to_lowercase() == "-version" ||
argument.to_lowercase() == "--version" {
version();
return;
} else if argument.to_lowercase() == "-r" {
recursive = true;
} else {
file = argument;
break;
}
}
if file == "" {
help();
return;
}
file = get_path(&file);
if recursive {
for entry in WalkDir::new(file) {
let entry = entry.unwrap();
trumpify_file(entry.path());
}
} else {
trumpify_file(file)
}
}
fn get_path2(file: &str) -> Result<String, Error> {
let path = try!(fs::canonicalize(file));
Ok(path.display().to_string())
}
fn get_path(file: &str) -> String {
get_path2(file).unwrap_or(file.to_owned())
}
fn version() {
println!("\x1b[32mVersion:");
println!("\x1b[0m trump-0.1.0");
println!("\x1b[32mWebsite:");
println!("\x1b[0m https://github.com/x13machine/trump/");
println!("\x1b[32mCreator:");
println!("\x1b[0m <Googolplexking/x13machine> https://googolplex.ninja/");
}
fn help() {
println!("\x1b[32mHelp:");
println!("\x1b[0m trump --help");
println!("\x1b[32mVersion:");
println!("\x1b[0m trump -v");
println!("\x1b[32mFiles:");
println!("\x1b[0m trump <File>");
println!("\x1b[32mDirectories:");
println!("\x1b[0m trump -r <Directory>");
}
fn trumpify_file<P: AsRef<Path>>(path: P) {
let path = path.as_ref();
let name = match path.file_name() {
Some(name) => name.to_string_lossy(),
None => return,
};
let capitalized_name = format!("{}{}",
&name[0..1].to_uppercase(),
&name[1..name.len()].to_lowercase());
// Ansi Color Codes!!!
println!("\x1b[32mMaking Great Again:\x1b[0m {:?}", path);
let text = format!("Make {} Great Again!", capitalized_name);
let mut file = match OpenOptions::new().read(true).write(true).open(path) {
Ok(file) => file,
Err(_) => return,
};
let mut data = Vec::new();
if let Err(_) = file.read_to_end(&mut data) {
return;
}
if data.is_empty() {
return;
}
trumpify_bytes(&mut data, text.as_bytes());
if let Err(_) = file.seek(SeekFrom::Start(0)) {
return;
}
let _ = file.write_all(&data);
}
fn trumpify_bytes(data: &mut [u8], replace_with: &[u8]) {
let replace_len = replace_with.len();
let loops = cmp::max(data.len() / replace_len / 2, 1);
let mut rng = thread_rng();
for _ in 0..loops {
let offset = rng.gen_range(0, data.len());
let to = cmp::min(offset + replace_len, data.len());
let mut slice = &mut data[offset..to];
let len = slice.len();
slice.clone_from_slice(&replace_with[..len]);
}
}
|
main
|
identifier_name
|
main.rs
|
extern crate rand;
extern crate walkdir;
use walkdir::WalkDir;
use rand::{Rng, thread_rng};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{Error, SeekFrom};
use std::cmp;
use std::path::Path;
fn main() {
let mut recursive: bool = false;
let mut file: String = String::from("");
for argument in env::args().skip(1) {
if argument.to_lowercase() == "--help" || argument.to_lowercase() == "-help" {
help();
return;
} else if argument.to_lowercase() == "--v" || argument.to_lowercase() == "-v" ||
argument.to_lowercase() == "-version" ||
argument.to_lowercase() == "--version" {
version();
return;
} else if argument.to_lowercase() == "-r" {
recursive = true;
} else {
file = argument;
break;
}
}
if file == "" {
help();
return;
}
|
file = get_path(&file);
if recursive {
for entry in WalkDir::new(file) {
let entry = entry.unwrap();
trumpify_file(entry.path());
}
} else {
trumpify_file(file)
}
}
fn get_path2(file: &str) -> Result<String, Error> {
let path = try!(fs::canonicalize(file));
Ok(path.display().to_string())
}
fn get_path(file: &str) -> String {
get_path2(file).unwrap_or(file.to_owned())
}
fn version() {
println!("\x1b[32mVersion:");
println!("\x1b[0m trump-0.1.0");
println!("\x1b[32mWebsite:");
println!("\x1b[0m https://github.com/x13machine/trump/");
println!("\x1b[32mCreator:");
println!("\x1b[0m <Googolplexking/x13machine> https://googolplex.ninja/");
}
fn help() {
println!("\x1b[32mHelp:");
println!("\x1b[0m trump --help");
println!("\x1b[32mVersion:");
println!("\x1b[0m trump -v");
println!("\x1b[32mFiles:");
println!("\x1b[0m trump <File>");
println!("\x1b[32mDirectories:");
println!("\x1b[0m trump -r <Directory>");
}
fn trumpify_file<P: AsRef<Path>>(path: P) {
let path = path.as_ref();
let name = match path.file_name() {
Some(name) => name.to_string_lossy(),
None => return,
};
let capitalized_name = format!("{}{}",
&name[0..1].to_uppercase(),
&name[1..name.len()].to_lowercase());
// Ansi Color Codes!!!
println!("\x1b[32mMaking Great Again:\x1b[0m {:?}", path);
let text = format!("Make {} Great Again!", capitalized_name);
let mut file = match OpenOptions::new().read(true).write(true).open(path) {
Ok(file) => file,
Err(_) => return,
};
let mut data = Vec::new();
if let Err(_) = file.read_to_end(&mut data) {
return;
}
if data.is_empty() {
return;
}
trumpify_bytes(&mut data, text.as_bytes());
if let Err(_) = file.seek(SeekFrom::Start(0)) {
return;
}
let _ = file.write_all(&data);
}
fn trumpify_bytes(data: &mut [u8], replace_with: &[u8]) {
let replace_len = replace_with.len();
let loops = cmp::max(data.len() / replace_len / 2, 1);
let mut rng = thread_rng();
for _ in 0..loops {
let offset = rng.gen_range(0, data.len());
let to = cmp::min(offset + replace_len, data.len());
let mut slice = &mut data[offset..to];
let len = slice.len();
slice.clone_from_slice(&replace_with[..len]);
}
}
|
random_line_split
|
|
main.rs
|
extern crate rand;
extern crate walkdir;
use walkdir::WalkDir;
use rand::{Rng, thread_rng};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::prelude::*;
use std::io::{Error, SeekFrom};
use std::cmp;
use std::path::Path;
fn main() {
let mut recursive: bool = false;
let mut file: String = String::from("");
for argument in env::args().skip(1) {
if argument.to_lowercase() == "--help" || argument.to_lowercase() == "-help" {
help();
return;
} else if argument.to_lowercase() == "--v" || argument.to_lowercase() == "-v" ||
argument.to_lowercase() == "-version" ||
argument.to_lowercase() == "--version" {
version();
return;
} else if argument.to_lowercase() == "-r" {
recursive = true;
} else {
file = argument;
break;
}
}
if file == "" {
help();
return;
}
file = get_path(&file);
if recursive {
for entry in WalkDir::new(file) {
let entry = entry.unwrap();
trumpify_file(entry.path());
}
} else {
trumpify_file(file)
}
}
fn get_path2(file: &str) -> Result<String, Error>
|
fn get_path(file: &str) -> String {
get_path2(file).unwrap_or(file.to_owned())
}
fn version() {
println!("\x1b[32mVersion:");
println!("\x1b[0m trump-0.1.0");
println!("\x1b[32mWebsite:");
println!("\x1b[0m https://github.com/x13machine/trump/");
println!("\x1b[32mCreator:");
println!("\x1b[0m <Googolplexking/x13machine> https://googolplex.ninja/");
}
fn help() {
println!("\x1b[32mHelp:");
println!("\x1b[0m trump --help");
println!("\x1b[32mVersion:");
println!("\x1b[0m trump -v");
println!("\x1b[32mFiles:");
println!("\x1b[0m trump <File>");
println!("\x1b[32mDirectories:");
println!("\x1b[0m trump -r <Directory>");
}
fn trumpify_file<P: AsRef<Path>>(path: P) {
let path = path.as_ref();
let name = match path.file_name() {
Some(name) => name.to_string_lossy(),
None => return,
};
let capitalized_name = format!("{}{}",
&name[0..1].to_uppercase(),
&name[1..name.len()].to_lowercase());
// Ansi Color Codes!!!
println!("\x1b[32mMaking Great Again:\x1b[0m {:?}", path);
let text = format!("Make {} Great Again!", capitalized_name);
let mut file = match OpenOptions::new().read(true).write(true).open(path) {
Ok(file) => file,
Err(_) => return,
};
let mut data = Vec::new();
if let Err(_) = file.read_to_end(&mut data) {
return;
}
if data.is_empty() {
return;
}
trumpify_bytes(&mut data, text.as_bytes());
if let Err(_) = file.seek(SeekFrom::Start(0)) {
return;
}
let _ = file.write_all(&data);
}
fn trumpify_bytes(data: &mut [u8], replace_with: &[u8]) {
let replace_len = replace_with.len();
let loops = cmp::max(data.len() / replace_len / 2, 1);
let mut rng = thread_rng();
for _ in 0..loops {
let offset = rng.gen_range(0, data.len());
let to = cmp::min(offset + replace_len, data.len());
let mut slice = &mut data[offset..to];
let len = slice.len();
slice.clone_from_slice(&replace_with[..len]);
}
}
|
{
let path = try!(fs::canonicalize(file));
Ok(path.display().to_string())
}
|
identifier_body
|
args.rs
|
use ::structopt::StructOpt;
///
/// The structure of the commands for the app.
///
/// A large amount of this is generated by StructOpt.
/// See that project for how to write large amounts of this.
///
/// The gist however is that we make a struct that will hold
/// all of our arguments. Commands are then parsed, and then
/// turned into this struct.
///
#[derive(StructOpt, Debug)]
#[structopt(name = "ls-pretty", about = "Like ls, but pretty.")]
pub struct Args {
/// Enable logging, use multiple `v`s to increase verbosity.
#[structopt(short = "a", long = "all", help = "Set to show all hidden files and directories.")]
pub all: bool,
/// Set the minimum width of the directory column.
#[structopt(default_value = "0", short = "d", long = "directory-width", help = "Minimum width of the directory column.")]
pub dirs_width: usize,
/// Optional path to the folder we are going to perform the list on.
#[structopt(default_value = ".", help = "Set to show all hidden files and directories.")]
|
///
/// Builds a new args from the main arguments given.
///
pub fn new_from_args() -> Args {
return Args::from_args();
}
}
|
pub path: String,
}
impl Args {
|
random_line_split
|
args.rs
|
use ::structopt::StructOpt;
///
/// The structure of the commands for the app.
///
/// A large amount of this is generated by StructOpt.
/// See that project for how to write large amounts of this.
///
/// The gist however is that we make a struct that will hold
/// all of our arguments. Commands are then parsed, and then
/// turned into this struct.
///
#[derive(StructOpt, Debug)]
#[structopt(name = "ls-pretty", about = "Like ls, but pretty.")]
pub struct
|
{
/// Enable logging, use multiple `v`s to increase verbosity.
#[structopt(short = "a", long = "all", help = "Set to show all hidden files and directories.")]
pub all: bool,
/// Set the minimum width of the directory column.
#[structopt(default_value = "0", short = "d", long = "directory-width", help = "Minimum width of the directory column.")]
pub dirs_width: usize,
/// Optional path to the folder we are going to perform the list on.
#[structopt(default_value = ".", help = "Set to show all hidden files and directories.")]
pub path: String,
}
impl Args {
///
/// Builds a new args from the main arguments given.
///
pub fn new_from_args() -> Args {
return Args::from_args();
}
}
|
Args
|
identifier_name
|
abstractworker.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::script_runtime::CommonScriptMsg;
use script_traits::StructuredSerializedData;
use servo_url::ImmutableOrigin;
/// Messages used to control the worker event loops
pub enum WorkerScriptMsg {
/// Common variants associated with the script messages
Common(CommonScriptMsg),
/// Message sent through Worker.postMessage
DOMMessage {
origin: ImmutableOrigin,
data: StructuredSerializedData,
},
}
pub struct SimpleWorkerErrorHandler<T: DomObject> {
pub addr: Trusted<T>,
}
impl<T: DomObject> SimpleWorkerErrorHandler<T> {
pub fn new(addr: Trusted<T>) -> SimpleWorkerErrorHandler<T>
|
}
|
{
SimpleWorkerErrorHandler { addr: addr }
}
|
identifier_body
|
abstractworker.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::script_runtime::CommonScriptMsg;
use script_traits::StructuredSerializedData;
use servo_url::ImmutableOrigin;
/// Messages used to control the worker event loops
pub enum WorkerScriptMsg {
/// Common variants associated with the script messages
Common(CommonScriptMsg),
/// Message sent through Worker.postMessage
DOMMessage {
origin: ImmutableOrigin,
data: StructuredSerializedData,
},
}
pub struct SimpleWorkerErrorHandler<T: DomObject> {
pub addr: Trusted<T>,
}
impl<T: DomObject> SimpleWorkerErrorHandler<T> {
pub fn
|
(addr: Trusted<T>) -> SimpleWorkerErrorHandler<T> {
SimpleWorkerErrorHandler { addr: addr }
}
}
|
new
|
identifier_name
|
abstractworker.rs
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::script_runtime::CommonScriptMsg;
use script_traits::StructuredSerializedData;
use servo_url::ImmutableOrigin;
/// Messages used to control the worker event loops
pub enum WorkerScriptMsg {
/// Common variants associated with the script messages
Common(CommonScriptMsg),
/// Message sent through Worker.postMessage
DOMMessage {
origin: ImmutableOrigin,
data: StructuredSerializedData,
},
}
pub struct SimpleWorkerErrorHandler<T: DomObject> {
pub addr: Trusted<T>,
}
impl<T: DomObject> SimpleWorkerErrorHandler<T> {
pub fn new(addr: Trusted<T>) -> SimpleWorkerErrorHandler<T> {
SimpleWorkerErrorHandler { addr: addr }
}
}
|
/* 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
|
random_line_split
|
|
dice.rs
|
use error::DiceParseError;
use generator::Generator;
use regex::Regex;
lazy_static! {
static ref DICE_CMD_PATTERN: Regex = Regex::new(r"^\d+(d\d+)?$").unwrap();
}
/// `Dice` describes a set of dice of the same type that can be "rolled" all at once, i.e. "2d6"
#[derive(Debug, Eq, PartialEq)]
pub struct Dice {
pub count: u32,
pub range: u32,
}
impl Dice {
/// Creates a new `Dice` struct with the provided dice count and range values
pub fn new(count: u32, range: u32) -> Dice {
Dice {
count: count,
range: range,
}
}
/// Generates the result of a dice roll for a given `Dice` value
pub fn gen_result<T: Generator>(&self, generator: &mut T) -> <T as Generator>::Output {
generator.generate(&self)
}
}
impl str::FromStr for Dice {
type Err = DiceParseError;
fn from_str(s: &str) -> Result<Dice, Self::Err> {
if!DICE_CMD_PATTERN.is_match(s) {
return Err(DiceParseError::InvalidExpression)
}
let mut parts = s.split('d').filter_map(|n| n.parse().ok());
match (parts.next(), parts.next()) {
(Some(count), Some(range)) => Ok(Dice::new(count, range)),
(Some(range), None) => Ok(Dice::new(1, range)),
_ => Err(DiceParseError::InvalidExpression),
}
}
}
|
use std::str;
|
random_line_split
|
|
dice.rs
|
use std::str;
use error::DiceParseError;
use generator::Generator;
use regex::Regex;
lazy_static! {
static ref DICE_CMD_PATTERN: Regex = Regex::new(r"^\d+(d\d+)?$").unwrap();
}
/// `Dice` describes a set of dice of the same type that can be "rolled" all at once, i.e. "2d6"
#[derive(Debug, Eq, PartialEq)]
pub struct Dice {
pub count: u32,
pub range: u32,
}
impl Dice {
/// Creates a new `Dice` struct with the provided dice count and range values
pub fn new(count: u32, range: u32) -> Dice {
Dice {
count: count,
range: range,
}
}
/// Generates the result of a dice roll for a given `Dice` value
pub fn
|
<T: Generator>(&self, generator: &mut T) -> <T as Generator>::Output {
generator.generate(&self)
}
}
impl str::FromStr for Dice {
type Err = DiceParseError;
fn from_str(s: &str) -> Result<Dice, Self::Err> {
if!DICE_CMD_PATTERN.is_match(s) {
return Err(DiceParseError::InvalidExpression)
}
let mut parts = s.split('d').filter_map(|n| n.parse().ok());
match (parts.next(), parts.next()) {
(Some(count), Some(range)) => Ok(Dice::new(count, range)),
(Some(range), None) => Ok(Dice::new(1, range)),
_ => Err(DiceParseError::InvalidExpression),
}
}
}
|
gen_result
|
identifier_name
|
dice.rs
|
use std::str;
use error::DiceParseError;
use generator::Generator;
use regex::Regex;
lazy_static! {
static ref DICE_CMD_PATTERN: Regex = Regex::new(r"^\d+(d\d+)?$").unwrap();
}
/// `Dice` describes a set of dice of the same type that can be "rolled" all at once, i.e. "2d6"
#[derive(Debug, Eq, PartialEq)]
pub struct Dice {
pub count: u32,
pub range: u32,
}
impl Dice {
/// Creates a new `Dice` struct with the provided dice count and range values
pub fn new(count: u32, range: u32) -> Dice
|
/// Generates the result of a dice roll for a given `Dice` value
pub fn gen_result<T: Generator>(&self, generator: &mut T) -> <T as Generator>::Output {
generator.generate(&self)
}
}
impl str::FromStr for Dice {
type Err = DiceParseError;
fn from_str(s: &str) -> Result<Dice, Self::Err> {
if!DICE_CMD_PATTERN.is_match(s) {
return Err(DiceParseError::InvalidExpression)
}
let mut parts = s.split('d').filter_map(|n| n.parse().ok());
match (parts.next(), parts.next()) {
(Some(count), Some(range)) => Ok(Dice::new(count, range)),
(Some(range), None) => Ok(Dice::new(1, range)),
_ => Err(DiceParseError::InvalidExpression),
}
}
}
|
{
Dice {
count: count,
range: range,
}
}
|
identifier_body
|
weird-exprs.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.
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(unused_parens)]
// compile-flags: -Z borrowck=compare
#![recursion_limit = "128"]
use std::cell::Cell;
use std::mem::swap;
// Just a grab bag of stuff that you wouldn't want to actually write.
fn strange() -> bool { let _x: bool = return true; }
fn funny() {
fn f(_x: ()) { }
f(return);
}
fn what() {
fn the(x: &Cell<bool>) {
return while!x.get() { x.set(true); };
}
let i = &Cell::new(false);
let dont = {||the(i)};
dont();
assert!((i.get()));
}
fn zombiejesus() {
loop {
while (return) {
if (return) {
match (return) {
1 => {
if (return) {
return
} else {
return
}
}
_ => { return }
};
} else if (return) {
return;
}
}
if (return) { break; }
}
}
fn notsure() {
let mut _x: isize;
let mut _y = (_x = 0) == (_x = 0);
let mut _z = (_x = 0) < (_x = 0);
let _a = (_x += 0) == (_x = 0);
let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}
fn canttouchthis() -> usize {
fn p() -> bool { true }
let _a = (assert!((true)) == (assert!(p())));
let _c = (assert!((p())) == ());
let _b: bool = (println!("{}", 0) == (return 0));
}
fn angrydome() {
loop { if break { } }
let mut i = 0;
loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
break; }
}
fn evil_lincoln() { let _evil = println!("lincoln"); }
fn dots() {
assert_eq!(String::from(".................................................."),
format!("{:?}",..........................
........................));
}
fn u8(u8: u8) {
if u8!= 0u8 {
assert_eq!(8u8, {
macro_rules! u8 {
(u8) => {
mod u8 {
pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 {
"u8";
u8
}
}
};
}
u8!(u8);
let &u8: &u8 = u8::u8(&8u8);
::u8(0u8);
u8
});
}
}
fn fishy() {
assert_eq!(String::from("><>"),
String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}
fn union() {
union union<'union> { union: &'union union<'union>, }
}
fn special_characters() {
let val =!((|(..):(_,_),__@_|__)((&*"\\",'🤔')/**/,{})=={&[..=..][..];})//
;
assert!(!val);
}
fn punch_card() -> impl std::fmt::Debug {
..=..=.... ........ ........ ....=....
..=....=.. ........ ........ ..=..=..=..
..=....=.. ..=....=.. ....=..=.. ....=....
..=..=.... ..=....=.. ..=...... ....=....
..=....=.. ..=....=.. ....=.... ....=....
..=....=.. ..=....=.. ......=.. ....=....
..=....=.. ....=..=.. ..=..=.... ....=....
}
pub fn main() {
strange();
funny();
what();
zombiejesus();
notsure();
canttouchthis();
angrydome();
evil_lincoln();
dots();
u8(8u8);
fishy();
|
punch_card();
}
|
union();
special_characters();
|
random_line_split
|
weird-exprs.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.
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(unused_parens)]
// compile-flags: -Z borrowck=compare
#![recursion_limit = "128"]
use std::cell::Cell;
use std::mem::swap;
// Just a grab bag of stuff that you wouldn't want to actually write.
fn strange() -> bool { let _x: bool = return true; }
fn funny() {
fn f(_x: ()) { }
f(return);
}
fn what() {
fn the(x: &Cell<bool>) {
return while!x.get() { x.set(true); };
}
let i = &Cell::new(false);
let dont = {||the(i)};
dont();
assert!((i.get()));
}
fn zombiejesus() {
loop {
while (return) {
if (return) {
match (return) {
1 => {
if (return) {
return
} else {
return
}
}
_ => { return }
};
} else if (return) {
return;
}
}
if (return) { break; }
}
}
fn notsure() {
let mut _x: isize;
let mut _y = (_x = 0) == (_x = 0);
let mut _z = (_x = 0) < (_x = 0);
let _a = (_x += 0) == (_x = 0);
let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}
fn canttouchthis() -> usize {
fn p() -> bool { true }
let _a = (assert!((true)) == (assert!(p())));
let _c = (assert!((p())) == ());
let _b: bool = (println!("{}", 0) == (return 0));
}
fn
|
() {
loop { if break { } }
let mut i = 0;
loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
break; }
}
fn evil_lincoln() { let _evil = println!("lincoln"); }
fn dots() {
assert_eq!(String::from(".................................................."),
format!("{:?}",..........................
........................));
}
fn u8(u8: u8) {
if u8!= 0u8 {
assert_eq!(8u8, {
macro_rules! u8 {
(u8) => {
mod u8 {
pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 {
"u8";
u8
}
}
};
}
u8!(u8);
let &u8: &u8 = u8::u8(&8u8);
::u8(0u8);
u8
});
}
}
fn fishy() {
assert_eq!(String::from("><>"),
String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}
fn union() {
union union<'union> { union: &'union union<'union>, }
}
fn special_characters() {
let val =!((|(..):(_,_),__@_|__)((&*"\\",'🤔')/**/,{})=={&[..=..][..];})//
;
assert!(!val);
}
fn punch_card() -> impl std::fmt::Debug {
..=..=.... ........ ........ ....=....
..=....=.. ........ ........ ..=..=..=..
..=....=.. ..=....=.. ....=..=.. ....=....
..=..=.... ..=....=.. ..=...... ....=....
..=....=.. ..=....=.. ....=.... ....=....
..=....=.. ..=....=.. ......=.. ....=....
..=....=.. ....=..=.. ..=..=.... ....=....
}
pub fn main() {
strange();
funny();
what();
zombiejesus();
notsure();
canttouchthis();
angrydome();
evil_lincoln();
dots();
u8(8u8);
fishy();
union();
special_characters();
punch_card();
}
|
angrydome
|
identifier_name
|
weird-exprs.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.
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(unused_parens)]
// compile-flags: -Z borrowck=compare
#![recursion_limit = "128"]
use std::cell::Cell;
use std::mem::swap;
// Just a grab bag of stuff that you wouldn't want to actually write.
fn strange() -> bool { let _x: bool = return true; }
fn funny() {
fn f(_x: ()) { }
f(return);
}
fn what() {
fn the(x: &Cell<bool>) {
return while!x.get() { x.set(true); };
}
let i = &Cell::new(false);
let dont = {||the(i)};
dont();
assert!((i.get()));
}
fn zombiejesus() {
loop {
while (return) {
if (return) {
match (return) {
1 => {
if (return) {
return
} else {
return
}
}
_ => { return }
};
} else if (return) {
return;
}
}
if (return) { break; }
}
}
fn notsure() {
let mut _x: isize;
let mut _y = (_x = 0) == (_x = 0);
let mut _z = (_x = 0) < (_x = 0);
let _a = (_x += 0) == (_x = 0);
let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}
fn canttouchthis() -> usize {
fn p() -> bool { true }
let _a = (assert!((true)) == (assert!(p())));
let _c = (assert!((p())) == ());
let _b: bool = (println!("{}", 0) == (return 0));
}
fn angrydome() {
loop { if break { } }
let mut i = 0;
loop { i += 1; if i == 1
|
break; }
}
fn evil_lincoln() { let _evil = println!("lincoln"); }
fn dots() {
assert_eq!(String::from(".................................................."),
format!("{:?}",..........................
........................));
}
fn u8(u8: u8) {
if u8!= 0u8 {
assert_eq!(8u8, {
macro_rules! u8 {
(u8) => {
mod u8 {
pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 {
"u8";
u8
}
}
};
}
u8!(u8);
let &u8: &u8 = u8::u8(&8u8);
::u8(0u8);
u8
});
}
}
fn fishy() {
assert_eq!(String::from("><>"),
String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}
fn union() {
union union<'union> { union: &'union union<'union>, }
}
fn special_characters() {
let val =!((|(..):(_,_),__@_|__)((&*"\\",'🤔')/**/,{})=={&[..=..][..];})//
;
assert!(!val);
}
fn punch_card() -> impl std::fmt::Debug {
..=..=.... ........ ........ ....=....
..=....=.. ........ ........ ..=..=..=..
..=....=.. ..=....=.. ....=..=.. ....=....
..=..=.... ..=....=.. ..=...... ....=....
..=....=.. ..=....=.. ....=.... ....=....
..=....=.. ..=....=.. ......=.. ....=....
..=....=.. ....=..=.. ..=..=.... ....=....
}
pub fn main() {
strange();
funny();
what();
zombiejesus();
notsure();
canttouchthis();
angrydome();
evil_lincoln();
dots();
u8(8u8);
fishy();
union();
special_characters();
punch_card();
}
|
{ match (continue) { 1 => { }, _ => panic!("wat") } }
|
conditional_block
|
weird-exprs.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.
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(unused_parens)]
// compile-flags: -Z borrowck=compare
#![recursion_limit = "128"]
use std::cell::Cell;
use std::mem::swap;
// Just a grab bag of stuff that you wouldn't want to actually write.
fn strange() -> bool { let _x: bool = return true; }
fn funny()
|
fn what() {
fn the(x: &Cell<bool>) {
return while!x.get() { x.set(true); };
}
let i = &Cell::new(false);
let dont = {||the(i)};
dont();
assert!((i.get()));
}
fn zombiejesus() {
loop {
while (return) {
if (return) {
match (return) {
1 => {
if (return) {
return
} else {
return
}
}
_ => { return }
};
} else if (return) {
return;
}
}
if (return) { break; }
}
}
fn notsure() {
let mut _x: isize;
let mut _y = (_x = 0) == (_x = 0);
let mut _z = (_x = 0) < (_x = 0);
let _a = (_x += 0) == (_x = 0);
let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}
fn canttouchthis() -> usize {
fn p() -> bool { true }
let _a = (assert!((true)) == (assert!(p())));
let _c = (assert!((p())) == ());
let _b: bool = (println!("{}", 0) == (return 0));
}
fn angrydome() {
loop { if break { } }
let mut i = 0;
loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
break; }
}
fn evil_lincoln() { let _evil = println!("lincoln"); }
fn dots() {
assert_eq!(String::from(".................................................."),
format!("{:?}",..........................
........................));
}
fn u8(u8: u8) {
if u8!= 0u8 {
assert_eq!(8u8, {
macro_rules! u8 {
(u8) => {
mod u8 {
pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 {
"u8";
u8
}
}
};
}
u8!(u8);
let &u8: &u8 = u8::u8(&8u8);
::u8(0u8);
u8
});
}
}
fn fishy() {
assert_eq!(String::from("><>"),
String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}
fn union() {
union union<'union> { union: &'union union<'union>, }
}
fn special_characters() {
let val =!((|(..):(_,_),__@_|__)((&*"\\",'🤔')/**/,{})=={&[..=..][..];})//
;
assert!(!val);
}
fn punch_card() -> impl std::fmt::Debug {
..=..=.... ........ ........ ....=....
..=....=.. ........ ........ ..=..=..=..
..=....=.. ..=....=.. ....=..=.. ....=....
..=..=.... ..=....=.. ..=...... ....=....
..=....=.. ..=....=.. ....=.... ....=....
..=....=.. ..=....=.. ......=.. ....=....
..=....=.. ....=..=.. ..=..=.... ....=....
}
pub fn main() {
strange();
funny();
what();
zombiejesus();
notsure();
canttouchthis();
angrydome();
evil_lincoln();
dots();
u8(8u8);
fishy();
union();
special_characters();
punch_card();
}
|
{
fn f(_x: ()) { }
f(return);
}
|
identifier_body
|
type-referenced-by-whitelisted-function.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct dl_phdr_info {
pub x: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_dl_phdr_info()
|
stringify!(x)
)
);
}
extern "C" {
pub fn dl_iterate_phdr(arg1: *mut dl_phdr_info) -> ::std::os::raw::c_int;
}
|
{
assert_eq!(
::std::mem::size_of::<dl_phdr_info>(),
4usize,
concat!("Size of: ", stringify!(dl_phdr_info))
);
assert_eq!(
::std::mem::align_of::<dl_phdr_info>(),
4usize,
concat!("Alignment of ", stringify!(dl_phdr_info))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<dl_phdr_info>())).x as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(dl_phdr_info),
"::",
|
identifier_body
|
type-referenced-by-whitelisted-function.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct
|
{
pub x: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_dl_phdr_info() {
assert_eq!(
::std::mem::size_of::<dl_phdr_info>(),
4usize,
concat!("Size of: ", stringify!(dl_phdr_info))
);
assert_eq!(
::std::mem::align_of::<dl_phdr_info>(),
4usize,
concat!("Alignment of ", stringify!(dl_phdr_info))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<dl_phdr_info>())).x as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(dl_phdr_info),
"::",
stringify!(x)
)
);
}
extern "C" {
pub fn dl_iterate_phdr(arg1: *mut dl_phdr_info) -> ::std::os::raw::c_int;
}
|
dl_phdr_info
|
identifier_name
|
type-referenced-by-whitelisted-function.rs
|
/* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct dl_phdr_info {
pub x: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_dl_phdr_info() {
assert_eq!(
::std::mem::size_of::<dl_phdr_info>(),
4usize,
|
4usize,
concat!("Alignment of ", stringify!(dl_phdr_info))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<dl_phdr_info>())).x as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(dl_phdr_info),
"::",
stringify!(x)
)
);
}
extern "C" {
pub fn dl_iterate_phdr(arg1: *mut dl_phdr_info) -> ::std::os::raw::c_int;
}
|
concat!("Size of: ", stringify!(dl_phdr_info))
);
assert_eq!(
::std::mem::align_of::<dl_phdr_info>(),
|
random_line_split
|
point.rs
|
//! A 2d point type.
use num::{Num, NumCast};
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A 2d point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T> {
/// x-coordinate.
pub x: T,
/// y-coordinate.
pub y: T,
}
impl<T> Point<T> {
/// Construct a point at (x, y).
pub fn new(x: T, y: T) -> Point<T> {
Point::<T> { x, y }
}
}
impl<T: Num> Add for Point<T> {
type Output = Self;
fn add(self, other: Point<T>) -> Point<T> {
Point::new(self.x + other.x, self.y + other.y)
}
}
impl<T: Num + Copy> AddAssign for Point<T> {
fn add_assign(&mut self, rhs: Self) {
self.x = self.x + rhs.x;
self.y = self.y + rhs.y;
}
}
impl<T: Num> Sub for Point<T> {
type Output = Self;
fn sub(self, other: Point<T>) -> Point<T> {
Point::new(self.x - other.x, self.y - other.y)
}
}
impl<T: Num + Copy> SubAssign for Point<T> {
fn sub_assign(&mut self, rhs: Self) {
self.x = self.x - rhs.x;
self.y = self.y - rhs.y;
}
}
impl<T: NumCast> Point<T> {
/// Converts to a Point<f64>. Panics if the cast fails.
pub(crate) fn to_f64(&self) -> Point<f64> {
Point::new(self.x.to_f64().unwrap(), self.y.to_f64().unwrap())
}
/// Converts to a Point<i32>. Panics if the cast fails.
pub(crate) fn to_i32(&self) -> Point<i32> {
Point::new(self.x.to_i32().unwrap(), self.y.to_i32().unwrap())
}
}
/// Returns the Euclidean distance between two points.
pub(crate) fn distance<T: NumCast>(p: Point<T>, q: Point<T>) -> f64 {
distance_sq(p, q).sqrt()
}
/// Returns the square of the Euclidean distance between two points.
pub(crate) fn distance_sq<T: NumCast>(p: Point<T>, q: Point<T>) -> f64 {
let p = p.to_f64();
let q = q.to_f64();
(p.x - q.x).powf(2.0) + (p.y - q.y).powf(2.0)
}
/// A fixed rotation. This struct exists solely to cache the values of `sin(theta)` and `cos(theta)` when
/// applying a fixed rotation to multiple points.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Rotation {
sin_theta: f64,
cos_theta: f64,
}
impl Rotation {
/// A rotation of `theta` radians.
pub(crate) fn new(theta: f64) -> Rotation {
let (sin_theta, cos_theta) = theta.sin_cos();
Rotation {
sin_theta,
cos_theta,
}
}
}
impl Point<f64> {
/// Rotates a point.
pub(crate) fn rotate(&self, rotation: Rotation) -> Point<f64> {
let x = self.x * rotation.cos_theta + self.y * rotation.sin_theta;
let y = self.y * rotation.cos_theta - self.x * rotation.sin_theta;
Point::new(x, y)
}
/// Inverts a rotation.
pub(crate) fn invert_rotation(&self, rotation: Rotation) -> Point<f64> {
let x = self.x * rotation.cos_theta - self.y * rotation.sin_theta;
let y = self.y * rotation.cos_theta + self.x * rotation.sin_theta;
Point::new(x, y)
}
}
/// A line of the form Ax + By + C = 0.
|
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Line {
a: f64,
b: f64,
c: f64,
}
impl Line {
/// Returns the `Line` that passes through p and q.
pub fn from_points(p: Point<f64>, q: Point<f64>) -> Line {
let a = p.y - q.y;
let b = q.x - p.x;
let c = p.x * q.y - q.x * p.y;
Line { a, b, c }
}
/// Computes the shortest distance from this line to the given point.
pub fn distance_from_point(&self, point: Point<f64>) -> f64 {
let Line { a, b, c } = self;
(a * point.x + b * point.y + c).abs() / (a.powf(2.0) + b.powf(2.)).sqrt()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_from_points() {
let p = Point::new(5.0, 7.0);
let q = Point::new(10.0, 3.0);
assert_eq!(
Line::from_points(p, q),
Line {
a: 4.0,
b: 5.0,
c: -55.0
}
);
}
#[test]
fn distance_between_line_and_point() {
assert_approx_eq!(
Line {
a: 8.0,
b: 7.0,
c: 5.0
}
.distance_from_point(Point::new(2.0, 3.0)),
3.9510276472,
1e-10
);
}
}
|
random_line_split
|
|
point.rs
|
//! A 2d point type.
use num::{Num, NumCast};
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A 2d point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T> {
/// x-coordinate.
pub x: T,
/// y-coordinate.
pub y: T,
}
impl<T> Point<T> {
/// Construct a point at (x, y).
pub fn new(x: T, y: T) -> Point<T> {
Point::<T> { x, y }
}
}
impl<T: Num> Add for Point<T> {
type Output = Self;
fn add(self, other: Point<T>) -> Point<T> {
Point::new(self.x + other.x, self.y + other.y)
}
}
impl<T: Num + Copy> AddAssign for Point<T> {
fn add_assign(&mut self, rhs: Self) {
self.x = self.x + rhs.x;
self.y = self.y + rhs.y;
}
}
impl<T: Num> Sub for Point<T> {
type Output = Self;
fn sub(self, other: Point<T>) -> Point<T> {
Point::new(self.x - other.x, self.y - other.y)
}
}
impl<T: Num + Copy> SubAssign for Point<T> {
fn sub_assign(&mut self, rhs: Self) {
self.x = self.x - rhs.x;
self.y = self.y - rhs.y;
}
}
impl<T: NumCast> Point<T> {
/// Converts to a Point<f64>. Panics if the cast fails.
pub(crate) fn to_f64(&self) -> Point<f64> {
Point::new(self.x.to_f64().unwrap(), self.y.to_f64().unwrap())
}
/// Converts to a Point<i32>. Panics if the cast fails.
pub(crate) fn to_i32(&self) -> Point<i32> {
Point::new(self.x.to_i32().unwrap(), self.y.to_i32().unwrap())
}
}
/// Returns the Euclidean distance between two points.
pub(crate) fn distance<T: NumCast>(p: Point<T>, q: Point<T>) -> f64 {
distance_sq(p, q).sqrt()
}
/// Returns the square of the Euclidean distance between two points.
pub(crate) fn distance_sq<T: NumCast>(p: Point<T>, q: Point<T>) -> f64 {
let p = p.to_f64();
let q = q.to_f64();
(p.x - q.x).powf(2.0) + (p.y - q.y).powf(2.0)
}
/// A fixed rotation. This struct exists solely to cache the values of `sin(theta)` and `cos(theta)` when
/// applying a fixed rotation to multiple points.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct
|
{
sin_theta: f64,
cos_theta: f64,
}
impl Rotation {
/// A rotation of `theta` radians.
pub(crate) fn new(theta: f64) -> Rotation {
let (sin_theta, cos_theta) = theta.sin_cos();
Rotation {
sin_theta,
cos_theta,
}
}
}
impl Point<f64> {
/// Rotates a point.
pub(crate) fn rotate(&self, rotation: Rotation) -> Point<f64> {
let x = self.x * rotation.cos_theta + self.y * rotation.sin_theta;
let y = self.y * rotation.cos_theta - self.x * rotation.sin_theta;
Point::new(x, y)
}
/// Inverts a rotation.
pub(crate) fn invert_rotation(&self, rotation: Rotation) -> Point<f64> {
let x = self.x * rotation.cos_theta - self.y * rotation.sin_theta;
let y = self.y * rotation.cos_theta + self.x * rotation.sin_theta;
Point::new(x, y)
}
}
/// A line of the form Ax + By + C = 0.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Line {
a: f64,
b: f64,
c: f64,
}
impl Line {
/// Returns the `Line` that passes through p and q.
pub fn from_points(p: Point<f64>, q: Point<f64>) -> Line {
let a = p.y - q.y;
let b = q.x - p.x;
let c = p.x * q.y - q.x * p.y;
Line { a, b, c }
}
/// Computes the shortest distance from this line to the given point.
pub fn distance_from_point(&self, point: Point<f64>) -> f64 {
let Line { a, b, c } = self;
(a * point.x + b * point.y + c).abs() / (a.powf(2.0) + b.powf(2.)).sqrt()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_from_points() {
let p = Point::new(5.0, 7.0);
let q = Point::new(10.0, 3.0);
assert_eq!(
Line::from_points(p, q),
Line {
a: 4.0,
b: 5.0,
c: -55.0
}
);
}
#[test]
fn distance_between_line_and_point() {
assert_approx_eq!(
Line {
a: 8.0,
b: 7.0,
c: 5.0
}
.distance_from_point(Point::new(2.0, 3.0)),
3.9510276472,
1e-10
);
}
}
|
Rotation
|
identifier_name
|
point.rs
|
//! A 2d point type.
use num::{Num, NumCast};
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A 2d point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T> {
/// x-coordinate.
pub x: T,
/// y-coordinate.
pub y: T,
}
impl<T> Point<T> {
/// Construct a point at (x, y).
pub fn new(x: T, y: T) -> Point<T> {
Point::<T> { x, y }
}
}
impl<T: Num> Add for Point<T> {
type Output = Self;
fn add(self, other: Point<T>) -> Point<T> {
Point::new(self.x + other.x, self.y + other.y)
}
}
impl<T: Num + Copy> AddAssign for Point<T> {
fn add_assign(&mut self, rhs: Self) {
self.x = self.x + rhs.x;
self.y = self.y + rhs.y;
}
}
impl<T: Num> Sub for Point<T> {
type Output = Self;
fn sub(self, other: Point<T>) -> Point<T> {
Point::new(self.x - other.x, self.y - other.y)
}
}
impl<T: Num + Copy> SubAssign for Point<T> {
fn sub_assign(&mut self, rhs: Self) {
self.x = self.x - rhs.x;
self.y = self.y - rhs.y;
}
}
impl<T: NumCast> Point<T> {
/// Converts to a Point<f64>. Panics if the cast fails.
pub(crate) fn to_f64(&self) -> Point<f64> {
Point::new(self.x.to_f64().unwrap(), self.y.to_f64().unwrap())
}
/// Converts to a Point<i32>. Panics if the cast fails.
pub(crate) fn to_i32(&self) -> Point<i32> {
Point::new(self.x.to_i32().unwrap(), self.y.to_i32().unwrap())
}
}
/// Returns the Euclidean distance between two points.
pub(crate) fn distance<T: NumCast>(p: Point<T>, q: Point<T>) -> f64
|
/// Returns the square of the Euclidean distance between two points.
pub(crate) fn distance_sq<T: NumCast>(p: Point<T>, q: Point<T>) -> f64 {
let p = p.to_f64();
let q = q.to_f64();
(p.x - q.x).powf(2.0) + (p.y - q.y).powf(2.0)
}
/// A fixed rotation. This struct exists solely to cache the values of `sin(theta)` and `cos(theta)` when
/// applying a fixed rotation to multiple points.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Rotation {
sin_theta: f64,
cos_theta: f64,
}
impl Rotation {
/// A rotation of `theta` radians.
pub(crate) fn new(theta: f64) -> Rotation {
let (sin_theta, cos_theta) = theta.sin_cos();
Rotation {
sin_theta,
cos_theta,
}
}
}
impl Point<f64> {
/// Rotates a point.
pub(crate) fn rotate(&self, rotation: Rotation) -> Point<f64> {
let x = self.x * rotation.cos_theta + self.y * rotation.sin_theta;
let y = self.y * rotation.cos_theta - self.x * rotation.sin_theta;
Point::new(x, y)
}
/// Inverts a rotation.
pub(crate) fn invert_rotation(&self, rotation: Rotation) -> Point<f64> {
let x = self.x * rotation.cos_theta - self.y * rotation.sin_theta;
let y = self.y * rotation.cos_theta + self.x * rotation.sin_theta;
Point::new(x, y)
}
}
/// A line of the form Ax + By + C = 0.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Line {
a: f64,
b: f64,
c: f64,
}
impl Line {
/// Returns the `Line` that passes through p and q.
pub fn from_points(p: Point<f64>, q: Point<f64>) -> Line {
let a = p.y - q.y;
let b = q.x - p.x;
let c = p.x * q.y - q.x * p.y;
Line { a, b, c }
}
/// Computes the shortest distance from this line to the given point.
pub fn distance_from_point(&self, point: Point<f64>) -> f64 {
let Line { a, b, c } = self;
(a * point.x + b * point.y + c).abs() / (a.powf(2.0) + b.powf(2.)).sqrt()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_from_points() {
let p = Point::new(5.0, 7.0);
let q = Point::new(10.0, 3.0);
assert_eq!(
Line::from_points(p, q),
Line {
a: 4.0,
b: 5.0,
c: -55.0
}
);
}
#[test]
fn distance_between_line_and_point() {
assert_approx_eq!(
Line {
a: 8.0,
b: 7.0,
c: 5.0
}
.distance_from_point(Point::new(2.0, 3.0)),
3.9510276472,
1e-10
);
}
}
|
{
distance_sq(p, q).sqrt()
}
|
identifier_body
|
printer.rs
|
use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.insert('"', "\\\"");
m.insert('\n', "\\n");
m.insert('\\', "\\\\");
m
};
}
impl super::types::MalType {
pub fn pr_str(&self, print_readably: bool) -> String {
match *self {
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Integer(integer) => integer.to_string(),
Str(ref string) => {
if print_readably {
let escaped = string
.chars()
.map(|c| match STR_ESCAPED_CHARS_MAP.get(&c) {
Some(escaped_char) => escaped_char.to_string(),
None => c.to_string(),
})
.collect::<Vec<String>>()
.join("");
format!("\"{}\"", escaped)
} else {
string.clone()
}
}
Symbol(ref string) => string.clone(),
List(ref seq) => pr_seq(seq, print_readably, "(", ")", " "),
Vector(ref seq) => pr_seq(seq, print_readably, "[", "]", " "),
Hash(ref hash) => pr_hash(hash, print_readably, "{", "}", " "),
Function(ref data) => format!("{:?}", data),
MalFunction(ref data) => format!("{:?}", data),
}
}
}
impl fmt::Debug for super::types::MalType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.pr_str(true))
}
}
fn pr_seq(seq: &[MalValue], print_readably: bool, start: &str, end: &str, sep: &str) -> String
|
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash
.iter()
.flat_map(|(k, v)| vec![new_str(k.clone()), v.clone()])
.collect();
pr_seq(&list, print_readably, start, end, sep)
}
|
{
let mut string = String::new();
string.push_str(start);
let mut first = true;
for value in seq {
if first {
first = false;
} else {
string.push_str(sep);
}
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
string
}
|
identifier_body
|
printer.rs
|
use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.insert('"', "\\\"");
m.insert('\n', "\\n");
m.insert('\\', "\\\\");
m
};
}
impl super::types::MalType {
pub fn pr_str(&self, print_readably: bool) -> String {
match *self {
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Integer(integer) => integer.to_string(),
Str(ref string) => {
if print_readably {
let escaped = string
.chars()
.map(|c| match STR_ESCAPED_CHARS_MAP.get(&c) {
Some(escaped_char) => escaped_char.to_string(),
None => c.to_string(),
})
.collect::<Vec<String>>()
.join("");
format!("\"{}\"", escaped)
} else {
string.clone()
}
}
Symbol(ref string) => string.clone(),
List(ref seq) => pr_seq(seq, print_readably, "(", ")", " "),
Vector(ref seq) => pr_seq(seq, print_readably, "[", "]", " "),
Hash(ref hash) => pr_hash(hash, print_readably, "{", "}", " "),
Function(ref data) => format!("{:?}", data),
MalFunction(ref data) => format!("{:?}", data),
}
}
}
impl fmt::Debug for super::types::MalType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.pr_str(true))
}
}
fn pr_seq(seq: &[MalValue], print_readably: bool, start: &str, end: &str, sep: &str) -> String {
let mut string = String::new();
string.push_str(start);
let mut first = true;
for value in seq {
if first {
first = false;
} else {
|
}
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
string
}
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash
.iter()
.flat_map(|(k, v)| vec![new_str(k.clone()), v.clone()])
.collect();
pr_seq(&list, print_readably, start, end, sep)
}
|
string.push_str(sep);
|
random_line_split
|
printer.rs
|
use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.insert('"', "\\\"");
m.insert('\n', "\\n");
m.insert('\\', "\\\\");
m
};
}
impl super::types::MalType {
pub fn pr_str(&self, print_readably: bool) -> String {
match *self {
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Integer(integer) => integer.to_string(),
Str(ref string) => {
if print_readably {
let escaped = string
.chars()
.map(|c| match STR_ESCAPED_CHARS_MAP.get(&c) {
Some(escaped_char) => escaped_char.to_string(),
None => c.to_string(),
})
.collect::<Vec<String>>()
.join("");
format!("\"{}\"", escaped)
} else {
string.clone()
}
}
Symbol(ref string) => string.clone(),
List(ref seq) => pr_seq(seq, print_readably, "(", ")", " "),
Vector(ref seq) => pr_seq(seq, print_readably, "[", "]", " "),
Hash(ref hash) => pr_hash(hash, print_readably, "{", "}", " "),
Function(ref data) => format!("{:?}", data),
MalFunction(ref data) => format!("{:?}", data),
}
}
}
impl fmt::Debug for super::types::MalType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.pr_str(true))
}
}
fn pr_seq(seq: &[MalValue], print_readably: bool, start: &str, end: &str, sep: &str) -> String {
let mut string = String::new();
string.push_str(start);
let mut first = true;
for value in seq {
if first
|
else {
string.push_str(sep);
}
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
string
}
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash
.iter()
.flat_map(|(k, v)| vec![new_str(k.clone()), v.clone()])
.collect();
pr_seq(&list, print_readably, start, end, sep)
}
|
{
first = false;
}
|
conditional_block
|
printer.rs
|
use std::collections::HashMap;
/// Module allowing to display an AST of 'MalValue'.
use std::fmt;
use super::types::MalType::*;
use super::types::{new_str, MalHashContainer, MalValue};
lazy_static! {
static ref STR_ESCAPED_CHARS_MAP: HashMap<char, &'static str> = {
let mut m = HashMap::new();
m.insert('"', "\\\"");
m.insert('\n', "\\n");
m.insert('\\', "\\\\");
m
};
}
impl super::types::MalType {
pub fn
|
(&self, print_readably: bool) -> String {
match *self {
Nil => "nil".to_string(),
True => "true".to_string(),
False => "false".to_string(),
Integer(integer) => integer.to_string(),
Str(ref string) => {
if print_readably {
let escaped = string
.chars()
.map(|c| match STR_ESCAPED_CHARS_MAP.get(&c) {
Some(escaped_char) => escaped_char.to_string(),
None => c.to_string(),
})
.collect::<Vec<String>>()
.join("");
format!("\"{}\"", escaped)
} else {
string.clone()
}
}
Symbol(ref string) => string.clone(),
List(ref seq) => pr_seq(seq, print_readably, "(", ")", " "),
Vector(ref seq) => pr_seq(seq, print_readably, "[", "]", " "),
Hash(ref hash) => pr_hash(hash, print_readably, "{", "}", " "),
Function(ref data) => format!("{:?}", data),
MalFunction(ref data) => format!("{:?}", data),
}
}
}
impl fmt::Debug for super::types::MalType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.pr_str(true))
}
}
fn pr_seq(seq: &[MalValue], print_readably: bool, start: &str, end: &str, sep: &str) -> String {
let mut string = String::new();
string.push_str(start);
let mut first = true;
for value in seq {
if first {
first = false;
} else {
string.push_str(sep);
}
string.push_str(&value.pr_str(print_readably)[..])
}
string.push_str(end);
string
}
fn pr_hash(
hash: &MalHashContainer,
print_readably: bool,
start: &str,
end: &str,
sep: &str,
) -> String {
let list: Vec<MalValue> = hash
.iter()
.flat_map(|(k, v)| vec![new_str(k.clone()), v.clone()])
.collect();
pr_seq(&list, print_readably, start, end, sep)
}
|
pr_str
|
identifier_name
|
dependency_queue.rs
|
//! A graph-like structure used to represent a set of dependencies and in what
//! order they should be built.
//!
//! This structure is used to store the dependency graph and dynamically update
//! it to figure out when a dependency should be built.
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
pub use self::Freshness::{Fresh, Dirty};
#[derive(Debug)]
pub struct DependencyQueue<K: Eq + Hash, V> {
/// A list of all known keys to build.
///
/// The value of the hash map is list of dependencies which still need to be
/// built before the package can be built. Note that the set is dynamically
/// updated as more dependencies are built.
dep_map: HashMap<K, (HashSet<K>, V)>,
/// A reverse mapping of a package to all packages that depend on that
/// package.
///
/// This map is statically known and does not get updated throughout the
/// lifecycle of the DependencyQueue.
reverse_dep_map: HashMap<K, HashSet<K>>,
/// A set of dirty packages.
///
/// Packages may become dirty over time if their dependencies are rebuilt.
dirty: HashSet<K>,
/// The packages which are currently being built, waiting for a call to
/// `finish`.
pending: HashSet<K>,
}
/// Indication of the freshness of a package.
///
/// A fresh package does not necessarily need to be rebuilt (unless a dependency
/// was also rebuilt), and a dirty package must always be rebuilt.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Freshness {
Fresh,
Dirty,
}
/// A trait for discovering the dependencies of a piece of data.
pub trait Dependency: Hash + Eq + Clone {
type Context;
fn dependencies(&self, cx: &Self::Context) -> Vec<Self>;
}
impl Freshness {
pub fn combine(&self, other: Freshness) -> Freshness {
match *self { Fresh => other, Dirty => Dirty }
}
}
impl<K: Dependency, V> DependencyQueue<K, V> {
/// Creates a new dependency queue with 0 packages.
pub fn new() -> DependencyQueue<K, V> {
DependencyQueue {
dep_map: HashMap::new(),
reverse_dep_map: HashMap::new(),
dirty: HashSet::new(),
pending: HashSet::new(),
}
}
/// Adds a new package to this dependency queue.
///
/// It is assumed that any dependencies of this package will eventually also
/// be added to the dependency queue.
pub fn queue(&mut self, cx: &K::Context, fresh: Freshness,
key: K, value: V) -> &mut V {
let slot = match self.dep_map.entry(key.clone()) {
Occupied(v) => return &mut v.into_mut().1,
Vacant(v) => v,
};
if fresh == Dirty {
self.dirty.insert(key.clone());
}
let mut my_dependencies = HashSet::new();
for dep in key.dependencies(cx).into_iter() {
assert!(my_dependencies.insert(dep.clone()));
let rev = self.reverse_dep_map.entry(dep).or_insert(HashSet::new());
assert!(rev.insert(key.clone()));
}
&mut slot.insert((my_dependencies, value)).1
}
/// Dequeues a package that is ready to be built.
///
/// A package is ready to be built when it has 0 un-built dependencies. If
/// `None` is returned then no packages are ready to be built.
pub fn dequeue(&mut self) -> Option<(Freshness, K, V)> {
let key = match self.dep_map.iter()
.find(|&(_, &(ref deps, _))| deps.is_empty())
.map(|(key, _)| key.clone()) {
Some(key) => key,
None => return None
};
let (_, data) = self.dep_map.remove(&key).unwrap();
let fresh = if self.dirty.contains(&key) {Dirty} else {Fresh};
self.pending.insert(key.clone());
Some((fresh, key, data))
}
/// Returns whether there are remaining packages to be built.
pub fn is_empty(&self) -> bool {
self.dep_map.is_empty() && self.pending.is_empty()
}
/// Returns the number of remaining packages to be built.
pub fn
|
(&self) -> usize {
self.dep_map.len() + self.pending.len()
}
/// Indicate that a package has been built.
///
/// This function will update the dependency queue with this information,
/// possibly allowing the next invocation of `dequeue` to return a package.
pub fn finish(&mut self, key: &K, fresh: Freshness) {
assert!(self.pending.remove(key));
let reverse_deps = match self.reverse_dep_map.get(key) {
Some(deps) => deps,
None => return,
};
for dep in reverse_deps.iter() {
if fresh == Dirty {
self.dirty.insert(dep.clone());
}
assert!(self.dep_map.get_mut(dep).unwrap().0.remove(key));
}
}
}
|
len
|
identifier_name
|
dependency_queue.rs
|
//! A graph-like structure used to represent a set of dependencies and in what
//! order they should be built.
//!
//! This structure is used to store the dependency graph and dynamically update
//! it to figure out when a dependency should be built.
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
pub use self::Freshness::{Fresh, Dirty};
#[derive(Debug)]
pub struct DependencyQueue<K: Eq + Hash, V> {
/// A list of all known keys to build.
///
/// The value of the hash map is list of dependencies which still need to be
/// built before the package can be built. Note that the set is dynamically
/// updated as more dependencies are built.
dep_map: HashMap<K, (HashSet<K>, V)>,
/// A reverse mapping of a package to all packages that depend on that
/// package.
///
/// This map is statically known and does not get updated throughout the
/// lifecycle of the DependencyQueue.
reverse_dep_map: HashMap<K, HashSet<K>>,
/// A set of dirty packages.
///
/// Packages may become dirty over time if their dependencies are rebuilt.
dirty: HashSet<K>,
/// The packages which are currently being built, waiting for a call to
/// `finish`.
pending: HashSet<K>,
}
/// Indication of the freshness of a package.
///
/// A fresh package does not necessarily need to be rebuilt (unless a dependency
/// was also rebuilt), and a dirty package must always be rebuilt.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Freshness {
Fresh,
Dirty,
}
/// A trait for discovering the dependencies of a piece of data.
pub trait Dependency: Hash + Eq + Clone {
type Context;
fn dependencies(&self, cx: &Self::Context) -> Vec<Self>;
}
|
match *self { Fresh => other, Dirty => Dirty }
}
}
impl<K: Dependency, V> DependencyQueue<K, V> {
/// Creates a new dependency queue with 0 packages.
pub fn new() -> DependencyQueue<K, V> {
DependencyQueue {
dep_map: HashMap::new(),
reverse_dep_map: HashMap::new(),
dirty: HashSet::new(),
pending: HashSet::new(),
}
}
/// Adds a new package to this dependency queue.
///
/// It is assumed that any dependencies of this package will eventually also
/// be added to the dependency queue.
pub fn queue(&mut self, cx: &K::Context, fresh: Freshness,
key: K, value: V) -> &mut V {
let slot = match self.dep_map.entry(key.clone()) {
Occupied(v) => return &mut v.into_mut().1,
Vacant(v) => v,
};
if fresh == Dirty {
self.dirty.insert(key.clone());
}
let mut my_dependencies = HashSet::new();
for dep in key.dependencies(cx).into_iter() {
assert!(my_dependencies.insert(dep.clone()));
let rev = self.reverse_dep_map.entry(dep).or_insert(HashSet::new());
assert!(rev.insert(key.clone()));
}
&mut slot.insert((my_dependencies, value)).1
}
/// Dequeues a package that is ready to be built.
///
/// A package is ready to be built when it has 0 un-built dependencies. If
/// `None` is returned then no packages are ready to be built.
pub fn dequeue(&mut self) -> Option<(Freshness, K, V)> {
let key = match self.dep_map.iter()
.find(|&(_, &(ref deps, _))| deps.is_empty())
.map(|(key, _)| key.clone()) {
Some(key) => key,
None => return None
};
let (_, data) = self.dep_map.remove(&key).unwrap();
let fresh = if self.dirty.contains(&key) {Dirty} else {Fresh};
self.pending.insert(key.clone());
Some((fresh, key, data))
}
/// Returns whether there are remaining packages to be built.
pub fn is_empty(&self) -> bool {
self.dep_map.is_empty() && self.pending.is_empty()
}
/// Returns the number of remaining packages to be built.
pub fn len(&self) -> usize {
self.dep_map.len() + self.pending.len()
}
/// Indicate that a package has been built.
///
/// This function will update the dependency queue with this information,
/// possibly allowing the next invocation of `dequeue` to return a package.
pub fn finish(&mut self, key: &K, fresh: Freshness) {
assert!(self.pending.remove(key));
let reverse_deps = match self.reverse_dep_map.get(key) {
Some(deps) => deps,
None => return,
};
for dep in reverse_deps.iter() {
if fresh == Dirty {
self.dirty.insert(dep.clone());
}
assert!(self.dep_map.get_mut(dep).unwrap().0.remove(key));
}
}
}
|
impl Freshness {
pub fn combine(&self, other: Freshness) -> Freshness {
|
random_line_split
|
mod.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.
/*
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in two major
phases: collect and check. The collect phase passes over all items and
determines their type, without examining their "innards". The check phase
then checks function bodies and so forth.
Within the check phase, we check each function body one at a time (bodies of
function expressions are checked as part of the containing function).
Inference is used to supply types wherever they are unknown. The actual
checking of a function itself has several phases (check, regionck, writeback),
as discussed in the documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
*/
use driver::session;
use middle::resolve;
use middle::ty;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use std::hashmap::HashMap;
use std::result;
use extra::list::List;
use extra::list;
use syntax::codemap::span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::opt_vec;
#[path = "check/mod.rs"]
pub mod check;
pub mod rscope;
pub mod astconv;
#[path = "infer/mod.rs"]
pub mod infer;
pub mod collect;
pub mod coherence;
#[deriving(Encodable, Decodable)]
pub enum method_origin {
// supertrait method invoked on "self" inside a default method
// first field is supertrait ID;
// second field is method index (relative to the *supertrait*
// method list)
method_super(ast::def_id, uint),
// fully statically resolved method
method_static(ast::def_id),
// method invoked on a type parameter with a bounded trait
method_param(method_param),
// method invoked on a trait instance
method_trait(ast::def_id, uint, ty::TraitStore),
// method invoked on "self" inside a default method
method_self(ast::def_id, uint)
}
// details for a method invoked with a receiver whose type is a type parameter
// with a bounded trait.
#[deriving(Encodable, Decodable)]
pub struct method_param {
// the trait containing the method to be invoked
trait_id: ast::def_id,
// index of the method to be invoked amongst the trait's methods
method_num: uint,
// index of the type parameter (from those that are in scope) that is
// the type of the receiver
param_num: uint,
// index of the bound for this type parameter which specifies the trait
bound_num: uint,
}
pub struct method_map_entry {
// the type of the self parameter, which is not reflected in the fn type
// (FIXME #3446)
self_ty: ty::t,
// the mode of `self`
self_mode: ty::SelfMode,
// the type of explicit self on the method
explicit_self: ast::explicit_self_,
// method details being invoked
origin: method_origin,
}
// maps from an expression id that corresponds to a method call to the details
// of the method to be invoked
pub type method_map = @mut HashMap<ast::node_id, method_map_entry>;
pub type vtable_param_res = @~[vtable_origin];
// Resolutions for bounds of all parameters, left to right, for a given path.
pub type vtable_res = @~[vtable_param_res];
pub enum vtable_origin {
/*
Statically known vtable. def_id gives the class or impl item
from whence comes the vtable, and tys are the type substs.
vtable_res is the vtable itself
*/
vtable_static(ast::def_id, ~[ty::t], vtable_res),
/*
Dynamic vtable, comes from a parameter that has a bound on it:
fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
vtable_param origin
The first uint is the param number (identifying T in the example),
and the second is the bound number (identifying baz)
*/
vtable_param(uint, uint),
/*
Dynamic vtable, comes from self.
*/
vtable_self(ast::def_id)
}
impl Repr for vtable_origin {
fn repr(&self, tcx: ty::ctxt) -> ~str {
match *self {
vtable_static(def_id, ref tys, ref vtable_res) => {
fmt!("vtable_static(%?:%s, %s, %s)",
def_id,
ty::item_path_str(tcx, def_id),
tys.repr(tcx),
vtable_res.repr(tcx))
}
vtable_param(x, y) => {
fmt!("vtable_param(%?, %?)", x, y)
}
vtable_self(def_id) => {
fmt!("vtable_self(%?)", def_id)
}
}
}
}
pub type vtable_map = @mut HashMap<ast::node_id, vtable_res>;
pub struct CrateCtxt {
// A mapping from method call sites to traits that have that method.
trait_map: resolve::TraitMap,
method_map: method_map,
vtable_map: vtable_map,
coherence_info: coherence::CoherenceInfo,
tcx: ty::ctxt
}
// Functions that write types into the node type table
pub fn write_ty_to_tcx(tcx: ty::ctxt, node_id: ast::node_id, ty: ty::t) {
debug!("write_ty_to_tcx(%d, %s)", node_id, ppaux::ty_to_str(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_types.insert(node_id as uint, ty);
}
pub fn write_substs_to_tcx(tcx: ty::ctxt,
node_id: ast::node_id,
substs: ~[ty::t]) {
if substs.len() > 0u {
debug!("write_substs_to_tcx(%d, %?)", node_id,
substs.map(|t| ppaux::ty_to_str(tcx, *t)));
assert!(substs.iter().all(|t|!ty::type_needs_infer(*t)));
tcx.node_type_substs.insert(node_id, substs);
}
}
pub fn write_tpt_to_tcx(tcx: ty::ctxt,
node_id: ast::node_id,
tpt: &ty::ty_param_substs_and_ty) {
write_ty_to_tcx(tcx, node_id, tpt.ty);
if!tpt.substs.tps.is_empty() {
write_substs_to_tcx(tcx, node_id, copy tpt.substs.tps);
}
}
pub fn lookup_def_tcx(tcx: ty::ctxt, sp: span, id: ast::node_id) -> ast::def {
match tcx.def_map.find(&id) {
Some(&x) => x,
_ => {
tcx.sess.span_fatal(sp, "internal error looking up a definition")
}
}
}
pub fn lookup_def_ccx(ccx: &CrateCtxt, sp: span, id: ast::node_id)
-> ast::def {
lookup_def_tcx(ccx.tcx, sp, id)
}
pub fn no_params(t: ty::t) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: ty::Generics {type_param_defs: @~[],
region_param: None},
ty: t
}
}
pub fn require_same_types(
tcx: ty::ctxt,
maybe_infcx: Option<@mut infer::InferCtxt>,
t1_is_expected: bool,
span: span,
t1: ty::t,
t2: ty::t,
msg: &fn() -> ~str) -> bool {
let l_tcx;
let l_infcx;
match maybe_infcx {
None => {
l_tcx = tcx;
l_infcx = infer::new_infer_ctxt(tcx);
}
Some(i) => {
l_tcx = i.tcx;
l_infcx = i;
}
}
match infer::mk_eqty(l_infcx, t1_is_expected, infer::Misc(span), t1, t2) {
result::Ok(()) => true,
result::Err(ref terr) => {
l_tcx.sess.span_err(span, msg() + ": " +
ty::type_err_to_str(l_tcx, terr));
ty::note_and_explain_type_err(l_tcx, terr);
false
}
}
}
// a list of mapping from in-scope-region-names ("isr") to the
// corresponding ty::Region
pub type isr_alist = @List<(ty::bound_region, ty::Region)>;
trait get_and_find_region {
fn get(&self, br: ty::bound_region) -> ty::Region;
fn find(&self, br: ty::bound_region) -> Option<ty::Region>;
}
impl get_and_find_region for isr_alist {
pub fn get(&self, br: ty::bound_region) -> ty::Region {
self.find(br).get()
}
pub fn find(&self, br: ty::bound_region) -> Option<ty::Region> {
for list::each(*self) |isr| {
let (isr_br, isr_r) = *isr;
if isr_br == br { return Some(isr_r); }
}
return None;
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::node_id,
main_span: span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match ty::get(main_t).sty {
ty::ty_bare_fn(ref fn_ty) => {
match tcx.items.find(&main_id) {
Some(&ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_, _, _, ref ps, _)
if ps.is_parameterized() => {
tcx.sess.span_err(
main_span,
"main function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::impure_fn,
abis: abi::AbiSet::Rust(),
|
output: ty::mk_nil()
}
});
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| fmt!("main function expects type: `%s`",
ppaux::ty_to_str(ccx.tcx, se_ty)));
}
_ => {
tcx.sess.span_bug(main_span,
fmt!("main has a non-function type: found `%s`",
ppaux::ty_to_str(tcx, main_t)));
}
}
}
fn check_start_fn_ty(ccx: &CrateCtxt,
start_id: ast::node_id,
start_span: span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match ty::get(start_t).sty {
ty::ty_bare_fn(_) => {
match tcx.items.find(&start_id) {
Some(&ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_,_,_,ref ps,_)
if ps.is_parameterized() => {
tcx.sess.span_err(
start_span,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::impure_fn,
abis: abi::AbiSet::Rust(),
sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[
ty::mk_int(),
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, ty::mk_u8())),
ty::mk_imm_ptr(tcx, ty::mk_u8())
],
output: ty::mk_int()
}
});
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| fmt!("start function expects type: `%s`", ppaux::ty_to_str(ccx.tcx, se_ty)));
}
_ => {
tcx.sess.span_bug(start_span,
fmt!("start has a non-function type: found `%s`",
ppaux::ty_to_str(tcx, start_t)));
}
}
}
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
if!*tcx.sess.building_library {
match *tcx.sess.entry_fn {
Some((id, sp)) => match *tcx.sess.entry_type {
Some(session::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(session::EntryStart) => check_start_fn_ty(ccx, id, sp),
None => tcx.sess.bug("entry function without a type")
},
None => tcx.sess.bug("type checking without entry function")
}
}
}
pub fn check_crate(tcx: ty::ctxt,
trait_map: resolve::TraitMap,
crate: &ast::crate)
-> (method_map, vtable_map) {
let time_passes = tcx.sess.time_passes();
let ccx = @mut CrateCtxt {
trait_map: trait_map,
method_map: @mut HashMap::new(),
vtable_map: @mut HashMap::new(),
coherence_info: coherence::CoherenceInfo(),
tcx: tcx
};
time(time_passes, ~"type collecting", ||
collect::collect_item_types(ccx, crate));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, ~"coherence checking", ||
coherence::check_coherence(ccx, crate));
time(time_passes, ~"type checking", ||
check::check_item_types(ccx, crate));
check_for_entry_fn(ccx);
tcx.sess.abort_if_errors();
(ccx.method_map, ccx.vtable_map)
}
|
sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[],
|
random_line_split
|
mod.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.
/*
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in two major
phases: collect and check. The collect phase passes over all items and
determines their type, without examining their "innards". The check phase
then checks function bodies and so forth.
Within the check phase, we check each function body one at a time (bodies of
function expressions are checked as part of the containing function).
Inference is used to supply types wherever they are unknown. The actual
checking of a function itself has several phases (check, regionck, writeback),
as discussed in the documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
*/
use driver::session;
use middle::resolve;
use middle::ty;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use std::hashmap::HashMap;
use std::result;
use extra::list::List;
use extra::list;
use syntax::codemap::span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::opt_vec;
#[path = "check/mod.rs"]
pub mod check;
pub mod rscope;
pub mod astconv;
#[path = "infer/mod.rs"]
pub mod infer;
pub mod collect;
pub mod coherence;
#[deriving(Encodable, Decodable)]
pub enum method_origin {
// supertrait method invoked on "self" inside a default method
// first field is supertrait ID;
// second field is method index (relative to the *supertrait*
// method list)
method_super(ast::def_id, uint),
// fully statically resolved method
method_static(ast::def_id),
// method invoked on a type parameter with a bounded trait
method_param(method_param),
// method invoked on a trait instance
method_trait(ast::def_id, uint, ty::TraitStore),
// method invoked on "self" inside a default method
method_self(ast::def_id, uint)
}
// details for a method invoked with a receiver whose type is a type parameter
// with a bounded trait.
#[deriving(Encodable, Decodable)]
pub struct method_param {
// the trait containing the method to be invoked
trait_id: ast::def_id,
// index of the method to be invoked amongst the trait's methods
method_num: uint,
// index of the type parameter (from those that are in scope) that is
// the type of the receiver
param_num: uint,
// index of the bound for this type parameter which specifies the trait
bound_num: uint,
}
pub struct method_map_entry {
// the type of the self parameter, which is not reflected in the fn type
// (FIXME #3446)
self_ty: ty::t,
// the mode of `self`
self_mode: ty::SelfMode,
// the type of explicit self on the method
explicit_self: ast::explicit_self_,
// method details being invoked
origin: method_origin,
}
// maps from an expression id that corresponds to a method call to the details
// of the method to be invoked
pub type method_map = @mut HashMap<ast::node_id, method_map_entry>;
pub type vtable_param_res = @~[vtable_origin];
// Resolutions for bounds of all parameters, left to right, for a given path.
pub type vtable_res = @~[vtable_param_res];
pub enum vtable_origin {
/*
Statically known vtable. def_id gives the class or impl item
from whence comes the vtable, and tys are the type substs.
vtable_res is the vtable itself
*/
vtable_static(ast::def_id, ~[ty::t], vtable_res),
/*
Dynamic vtable, comes from a parameter that has a bound on it:
fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
vtable_param origin
The first uint is the param number (identifying T in the example),
and the second is the bound number (identifying baz)
*/
vtable_param(uint, uint),
/*
Dynamic vtable, comes from self.
*/
vtable_self(ast::def_id)
}
impl Repr for vtable_origin {
fn repr(&self, tcx: ty::ctxt) -> ~str
|
}
pub type vtable_map = @mut HashMap<ast::node_id, vtable_res>;
pub struct CrateCtxt {
// A mapping from method call sites to traits that have that method.
trait_map: resolve::TraitMap,
method_map: method_map,
vtable_map: vtable_map,
coherence_info: coherence::CoherenceInfo,
tcx: ty::ctxt
}
// Functions that write types into the node type table
pub fn write_ty_to_tcx(tcx: ty::ctxt, node_id: ast::node_id, ty: ty::t) {
debug!("write_ty_to_tcx(%d, %s)", node_id, ppaux::ty_to_str(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_types.insert(node_id as uint, ty);
}
pub fn write_substs_to_tcx(tcx: ty::ctxt,
node_id: ast::node_id,
substs: ~[ty::t]) {
if substs.len() > 0u {
debug!("write_substs_to_tcx(%d, %?)", node_id,
substs.map(|t| ppaux::ty_to_str(tcx, *t)));
assert!(substs.iter().all(|t|!ty::type_needs_infer(*t)));
tcx.node_type_substs.insert(node_id, substs);
}
}
pub fn write_tpt_to_tcx(tcx: ty::ctxt,
node_id: ast::node_id,
tpt: &ty::ty_param_substs_and_ty) {
write_ty_to_tcx(tcx, node_id, tpt.ty);
if!tpt.substs.tps.is_empty() {
write_substs_to_tcx(tcx, node_id, copy tpt.substs.tps);
}
}
pub fn lookup_def_tcx(tcx: ty::ctxt, sp: span, id: ast::node_id) -> ast::def {
match tcx.def_map.find(&id) {
Some(&x) => x,
_ => {
tcx.sess.span_fatal(sp, "internal error looking up a definition")
}
}
}
pub fn lookup_def_ccx(ccx: &CrateCtxt, sp: span, id: ast::node_id)
-> ast::def {
lookup_def_tcx(ccx.tcx, sp, id)
}
pub fn no_params(t: ty::t) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: ty::Generics {type_param_defs: @~[],
region_param: None},
ty: t
}
}
pub fn require_same_types(
tcx: ty::ctxt,
maybe_infcx: Option<@mut infer::InferCtxt>,
t1_is_expected: bool,
span: span,
t1: ty::t,
t2: ty::t,
msg: &fn() -> ~str) -> bool {
let l_tcx;
let l_infcx;
match maybe_infcx {
None => {
l_tcx = tcx;
l_infcx = infer::new_infer_ctxt(tcx);
}
Some(i) => {
l_tcx = i.tcx;
l_infcx = i;
}
}
match infer::mk_eqty(l_infcx, t1_is_expected, infer::Misc(span), t1, t2) {
result::Ok(()) => true,
result::Err(ref terr) => {
l_tcx.sess.span_err(span, msg() + ": " +
ty::type_err_to_str(l_tcx, terr));
ty::note_and_explain_type_err(l_tcx, terr);
false
}
}
}
// a list of mapping from in-scope-region-names ("isr") to the
// corresponding ty::Region
pub type isr_alist = @List<(ty::bound_region, ty::Region)>;
trait get_and_find_region {
fn get(&self, br: ty::bound_region) -> ty::Region;
fn find(&self, br: ty::bound_region) -> Option<ty::Region>;
}
impl get_and_find_region for isr_alist {
pub fn get(&self, br: ty::bound_region) -> ty::Region {
self.find(br).get()
}
pub fn find(&self, br: ty::bound_region) -> Option<ty::Region> {
for list::each(*self) |isr| {
let (isr_br, isr_r) = *isr;
if isr_br == br { return Some(isr_r); }
}
return None;
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::node_id,
main_span: span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match ty::get(main_t).sty {
ty::ty_bare_fn(ref fn_ty) => {
match tcx.items.find(&main_id) {
Some(&ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_, _, _, ref ps, _)
if ps.is_parameterized() => {
tcx.sess.span_err(
main_span,
"main function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::impure_fn,
abis: abi::AbiSet::Rust(),
sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[],
output: ty::mk_nil()
}
});
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| fmt!("main function expects type: `%s`",
ppaux::ty_to_str(ccx.tcx, se_ty)));
}
_ => {
tcx.sess.span_bug(main_span,
fmt!("main has a non-function type: found `%s`",
ppaux::ty_to_str(tcx, main_t)));
}
}
}
fn check_start_fn_ty(ccx: &CrateCtxt,
start_id: ast::node_id,
start_span: span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match ty::get(start_t).sty {
ty::ty_bare_fn(_) => {
match tcx.items.find(&start_id) {
Some(&ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_,_,_,ref ps,_)
if ps.is_parameterized() => {
tcx.sess.span_err(
start_span,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::impure_fn,
abis: abi::AbiSet::Rust(),
sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[
ty::mk_int(),
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, ty::mk_u8())),
ty::mk_imm_ptr(tcx, ty::mk_u8())
],
output: ty::mk_int()
}
});
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| fmt!("start function expects type: `%s`", ppaux::ty_to_str(ccx.tcx, se_ty)));
}
_ => {
tcx.sess.span_bug(start_span,
fmt!("start has a non-function type: found `%s`",
ppaux::ty_to_str(tcx, start_t)));
}
}
}
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
if!*tcx.sess.building_library {
match *tcx.sess.entry_fn {
Some((id, sp)) => match *tcx.sess.entry_type {
Some(session::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(session::EntryStart) => check_start_fn_ty(ccx, id, sp),
None => tcx.sess.bug("entry function without a type")
},
None => tcx.sess.bug("type checking without entry function")
}
}
}
pub fn check_crate(tcx: ty::ctxt,
trait_map: resolve::TraitMap,
crate: &ast::crate)
-> (method_map, vtable_map) {
let time_passes = tcx.sess.time_passes();
let ccx = @mut CrateCtxt {
trait_map: trait_map,
method_map: @mut HashMap::new(),
vtable_map: @mut HashMap::new(),
coherence_info: coherence::CoherenceInfo(),
tcx: tcx
};
time(time_passes, ~"type collecting", ||
collect::collect_item_types(ccx, crate));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, ~"coherence checking", ||
coherence::check_coherence(ccx, crate));
time(time_passes, ~"type checking", ||
check::check_item_types(ccx, crate));
check_for_entry_fn(ccx);
tcx.sess.abort_if_errors();
(ccx.method_map, ccx.vtable_map)
}
|
{
match *self {
vtable_static(def_id, ref tys, ref vtable_res) => {
fmt!("vtable_static(%?:%s, %s, %s)",
def_id,
ty::item_path_str(tcx, def_id),
tys.repr(tcx),
vtable_res.repr(tcx))
}
vtable_param(x, y) => {
fmt!("vtable_param(%?, %?)", x, y)
}
vtable_self(def_id) => {
fmt!("vtable_self(%?)", def_id)
}
}
}
|
identifier_body
|
mod.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.
/*
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in two major
phases: collect and check. The collect phase passes over all items and
determines their type, without examining their "innards". The check phase
then checks function bodies and so forth.
Within the check phase, we check each function body one at a time (bodies of
function expressions are checked as part of the containing function).
Inference is used to supply types wherever they are unknown. The actual
checking of a function itself has several phases (check, regionck, writeback),
as discussed in the documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
*/
use driver::session;
use middle::resolve;
use middle::ty;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use std::hashmap::HashMap;
use std::result;
use extra::list::List;
use extra::list;
use syntax::codemap::span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::opt_vec;
#[path = "check/mod.rs"]
pub mod check;
pub mod rscope;
pub mod astconv;
#[path = "infer/mod.rs"]
pub mod infer;
pub mod collect;
pub mod coherence;
#[deriving(Encodable, Decodable)]
pub enum method_origin {
// supertrait method invoked on "self" inside a default method
// first field is supertrait ID;
// second field is method index (relative to the *supertrait*
// method list)
method_super(ast::def_id, uint),
// fully statically resolved method
method_static(ast::def_id),
// method invoked on a type parameter with a bounded trait
method_param(method_param),
// method invoked on a trait instance
method_trait(ast::def_id, uint, ty::TraitStore),
// method invoked on "self" inside a default method
method_self(ast::def_id, uint)
}
// details for a method invoked with a receiver whose type is a type parameter
// with a bounded trait.
#[deriving(Encodable, Decodable)]
pub struct method_param {
// the trait containing the method to be invoked
trait_id: ast::def_id,
// index of the method to be invoked amongst the trait's methods
method_num: uint,
// index of the type parameter (from those that are in scope) that is
// the type of the receiver
param_num: uint,
// index of the bound for this type parameter which specifies the trait
bound_num: uint,
}
pub struct method_map_entry {
// the type of the self parameter, which is not reflected in the fn type
// (FIXME #3446)
self_ty: ty::t,
// the mode of `self`
self_mode: ty::SelfMode,
// the type of explicit self on the method
explicit_self: ast::explicit_self_,
// method details being invoked
origin: method_origin,
}
// maps from an expression id that corresponds to a method call to the details
// of the method to be invoked
pub type method_map = @mut HashMap<ast::node_id, method_map_entry>;
pub type vtable_param_res = @~[vtable_origin];
// Resolutions for bounds of all parameters, left to right, for a given path.
pub type vtable_res = @~[vtable_param_res];
pub enum vtable_origin {
/*
Statically known vtable. def_id gives the class or impl item
from whence comes the vtable, and tys are the type substs.
vtable_res is the vtable itself
*/
vtable_static(ast::def_id, ~[ty::t], vtable_res),
/*
Dynamic vtable, comes from a parameter that has a bound on it:
fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
vtable_param origin
The first uint is the param number (identifying T in the example),
and the second is the bound number (identifying baz)
*/
vtable_param(uint, uint),
/*
Dynamic vtable, comes from self.
*/
vtable_self(ast::def_id)
}
impl Repr for vtable_origin {
fn repr(&self, tcx: ty::ctxt) -> ~str {
match *self {
vtable_static(def_id, ref tys, ref vtable_res) => {
fmt!("vtable_static(%?:%s, %s, %s)",
def_id,
ty::item_path_str(tcx, def_id),
tys.repr(tcx),
vtable_res.repr(tcx))
}
vtable_param(x, y) => {
fmt!("vtable_param(%?, %?)", x, y)
}
vtable_self(def_id) => {
fmt!("vtable_self(%?)", def_id)
}
}
}
}
pub type vtable_map = @mut HashMap<ast::node_id, vtable_res>;
pub struct CrateCtxt {
// A mapping from method call sites to traits that have that method.
trait_map: resolve::TraitMap,
method_map: method_map,
vtable_map: vtable_map,
coherence_info: coherence::CoherenceInfo,
tcx: ty::ctxt
}
// Functions that write types into the node type table
pub fn write_ty_to_tcx(tcx: ty::ctxt, node_id: ast::node_id, ty: ty::t) {
debug!("write_ty_to_tcx(%d, %s)", node_id, ppaux::ty_to_str(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_types.insert(node_id as uint, ty);
}
pub fn write_substs_to_tcx(tcx: ty::ctxt,
node_id: ast::node_id,
substs: ~[ty::t]) {
if substs.len() > 0u {
debug!("write_substs_to_tcx(%d, %?)", node_id,
substs.map(|t| ppaux::ty_to_str(tcx, *t)));
assert!(substs.iter().all(|t|!ty::type_needs_infer(*t)));
tcx.node_type_substs.insert(node_id, substs);
}
}
pub fn write_tpt_to_tcx(tcx: ty::ctxt,
node_id: ast::node_id,
tpt: &ty::ty_param_substs_and_ty) {
write_ty_to_tcx(tcx, node_id, tpt.ty);
if!tpt.substs.tps.is_empty() {
write_substs_to_tcx(tcx, node_id, copy tpt.substs.tps);
}
}
pub fn lookup_def_tcx(tcx: ty::ctxt, sp: span, id: ast::node_id) -> ast::def {
match tcx.def_map.find(&id) {
Some(&x) => x,
_ => {
tcx.sess.span_fatal(sp, "internal error looking up a definition")
}
}
}
pub fn lookup_def_ccx(ccx: &CrateCtxt, sp: span, id: ast::node_id)
-> ast::def {
lookup_def_tcx(ccx.tcx, sp, id)
}
pub fn no_params(t: ty::t) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: ty::Generics {type_param_defs: @~[],
region_param: None},
ty: t
}
}
pub fn require_same_types(
tcx: ty::ctxt,
maybe_infcx: Option<@mut infer::InferCtxt>,
t1_is_expected: bool,
span: span,
t1: ty::t,
t2: ty::t,
msg: &fn() -> ~str) -> bool {
let l_tcx;
let l_infcx;
match maybe_infcx {
None => {
l_tcx = tcx;
l_infcx = infer::new_infer_ctxt(tcx);
}
Some(i) => {
l_tcx = i.tcx;
l_infcx = i;
}
}
match infer::mk_eqty(l_infcx, t1_is_expected, infer::Misc(span), t1, t2) {
result::Ok(()) => true,
result::Err(ref terr) => {
l_tcx.sess.span_err(span, msg() + ": " +
ty::type_err_to_str(l_tcx, terr));
ty::note_and_explain_type_err(l_tcx, terr);
false
}
}
}
// a list of mapping from in-scope-region-names ("isr") to the
// corresponding ty::Region
pub type isr_alist = @List<(ty::bound_region, ty::Region)>;
trait get_and_find_region {
fn get(&self, br: ty::bound_region) -> ty::Region;
fn find(&self, br: ty::bound_region) -> Option<ty::Region>;
}
impl get_and_find_region for isr_alist {
pub fn get(&self, br: ty::bound_region) -> ty::Region {
self.find(br).get()
}
pub fn find(&self, br: ty::bound_region) -> Option<ty::Region> {
for list::each(*self) |isr| {
let (isr_br, isr_r) = *isr;
if isr_br == br { return Some(isr_r); }
}
return None;
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::node_id,
main_span: span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match ty::get(main_t).sty {
ty::ty_bare_fn(ref fn_ty) => {
match tcx.items.find(&main_id) {
Some(&ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_, _, _, ref ps, _)
if ps.is_parameterized() => {
tcx.sess.span_err(
main_span,
"main function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::impure_fn,
abis: abi::AbiSet::Rust(),
sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[],
output: ty::mk_nil()
}
});
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| fmt!("main function expects type: `%s`",
ppaux::ty_to_str(ccx.tcx, se_ty)));
}
_ => {
tcx.sess.span_bug(main_span,
fmt!("main has a non-function type: found `%s`",
ppaux::ty_to_str(tcx, main_t)));
}
}
}
fn check_start_fn_ty(ccx: &CrateCtxt,
start_id: ast::node_id,
start_span: span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match ty::get(start_t).sty {
ty::ty_bare_fn(_) => {
match tcx.items.find(&start_id) {
Some(&ast_map::node_item(it,_)) => {
match it.node {
ast::item_fn(_,_,_,ref ps,_)
if ps.is_parameterized() => {
tcx.sess.span_err(
start_span,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy {
purity: ast::impure_fn,
abis: abi::AbiSet::Rust(),
sig: ty::FnSig {
bound_lifetime_names: opt_vec::Empty,
inputs: ~[
ty::mk_int(),
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, ty::mk_u8())),
ty::mk_imm_ptr(tcx, ty::mk_u8())
],
output: ty::mk_int()
}
});
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| fmt!("start function expects type: `%s`", ppaux::ty_to_str(ccx.tcx, se_ty)));
}
_ => {
tcx.sess.span_bug(start_span,
fmt!("start has a non-function type: found `%s`",
ppaux::ty_to_str(tcx, start_t)));
}
}
}
fn
|
(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
if!*tcx.sess.building_library {
match *tcx.sess.entry_fn {
Some((id, sp)) => match *tcx.sess.entry_type {
Some(session::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(session::EntryStart) => check_start_fn_ty(ccx, id, sp),
None => tcx.sess.bug("entry function without a type")
},
None => tcx.sess.bug("type checking without entry function")
}
}
}
pub fn check_crate(tcx: ty::ctxt,
trait_map: resolve::TraitMap,
crate: &ast::crate)
-> (method_map, vtable_map) {
let time_passes = tcx.sess.time_passes();
let ccx = @mut CrateCtxt {
trait_map: trait_map,
method_map: @mut HashMap::new(),
vtable_map: @mut HashMap::new(),
coherence_info: coherence::CoherenceInfo(),
tcx: tcx
};
time(time_passes, ~"type collecting", ||
collect::collect_item_types(ccx, crate));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, ~"coherence checking", ||
coherence::check_coherence(ccx, crate));
time(time_passes, ~"type checking", ||
check::check_item_types(ccx, crate));
check_for_entry_fn(ccx);
tcx.sess.abort_if_errors();
(ccx.method_map, ccx.vtable_map)
}
|
check_for_entry_fn
|
identifier_name
|
unquote.rs
|
/* Copyright (C) 2015-2016 Yutaka Kamei */
use std::string::FromUtf8Error;
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%20DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let mut result : Vec<u8> = Vec::new();
let mut items = s.as_ref().as_bytes().split(|&b| b == b'%');
match items.next() {
Some(item) => result.append(&mut item.to_vec()),
None => return String::from_utf8(result),
}
for item in items {
match item.len() {
0 => result.push(b'%'),
1 => {
result.push(b'%');
result.append(&mut item.to_vec());
},
_ => {
let fs = &item[..2];
let ls = &item[2..];
if let Some(digit) = to_digit(*fs.get(0).unwrap(), *fs.get(1).unwrap()) {
result.push(digit);
result.append(&mut ls.to_vec());
} else {
result.push(b'%');
result.append(&mut item.to_vec());
}
},
}
}
return String::from_utf8(result);
}
/// Like unquote(), but also replaces plus signs by spaces, as required for
/// unquoting HTML form values.
///
/// # Examples
///
/// ```
/// use urlparse::unquote_plus;
///
/// let s = unquote_plus("ABC%3D123%21+DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote_plus<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error>
|
fn to_digit(n1: u8, n2: u8) -> Option<u8> {
let mut byte : u8 = 0;
match DIGIT.binary_search(&n1) {
Ok(_n1) => byte += if _n1 < 16 {_n1 as u8 * 16} else {(_n1 - OFFSET) as u8 * 16},
Err(_) => return None,
}
match DIGIT.binary_search(&n2) {
Ok(_n2) => byte += if _n2 < 16 {_n2 as u8} else {(_n2 - OFFSET) as u8},
Err(_) => return None,
}
return Some(byte);
}
#[test]
fn test_to_digit() {
assert_eq!(to_digit(b'1', b'2'), Some(0x12));
assert_eq!(to_digit(b'e', b'a'), Some(0xEA));
assert_eq!(to_digit(b'E', b'A'), Some(0xEA));
assert_eq!(to_digit(b'F', b'F'), Some(0xFF));
assert_eq!(to_digit(b'X', b'1'), None);
assert_eq!(to_digit(b'A', b'x'), None);
}
|
{
let _s = s.as_ref().replace("+", " ");
return unquote(_s);
}
|
identifier_body
|
unquote.rs
|
/* Copyright (C) 2015-2016 Yutaka Kamei */
|
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%20DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let mut result : Vec<u8> = Vec::new();
let mut items = s.as_ref().as_bytes().split(|&b| b == b'%');
match items.next() {
Some(item) => result.append(&mut item.to_vec()),
None => return String::from_utf8(result),
}
for item in items {
match item.len() {
0 => result.push(b'%'),
1 => {
result.push(b'%');
result.append(&mut item.to_vec());
},
_ => {
let fs = &item[..2];
let ls = &item[2..];
if let Some(digit) = to_digit(*fs.get(0).unwrap(), *fs.get(1).unwrap()) {
result.push(digit);
result.append(&mut ls.to_vec());
} else {
result.push(b'%');
result.append(&mut item.to_vec());
}
},
}
}
return String::from_utf8(result);
}
/// Like unquote(), but also replaces plus signs by spaces, as required for
/// unquoting HTML form values.
///
/// # Examples
///
/// ```
/// use urlparse::unquote_plus;
///
/// let s = unquote_plus("ABC%3D123%21+DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote_plus<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let _s = s.as_ref().replace("+", " ");
return unquote(_s);
}
fn to_digit(n1: u8, n2: u8) -> Option<u8> {
let mut byte : u8 = 0;
match DIGIT.binary_search(&n1) {
Ok(_n1) => byte += if _n1 < 16 {_n1 as u8 * 16} else {(_n1 - OFFSET) as u8 * 16},
Err(_) => return None,
}
match DIGIT.binary_search(&n2) {
Ok(_n2) => byte += if _n2 < 16 {_n2 as u8} else {(_n2 - OFFSET) as u8},
Err(_) => return None,
}
return Some(byte);
}
#[test]
fn test_to_digit() {
assert_eq!(to_digit(b'1', b'2'), Some(0x12));
assert_eq!(to_digit(b'e', b'a'), Some(0xEA));
assert_eq!(to_digit(b'E', b'A'), Some(0xEA));
assert_eq!(to_digit(b'F', b'F'), Some(0xFF));
assert_eq!(to_digit(b'X', b'1'), None);
assert_eq!(to_digit(b'A', b'x'), None);
}
|
use std::string::FromUtf8Error;
|
random_line_split
|
unquote.rs
|
/* Copyright (C) 2015-2016 Yutaka Kamei */
use std::string::FromUtf8Error;
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%20DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let mut result : Vec<u8> = Vec::new();
let mut items = s.as_ref().as_bytes().split(|&b| b == b'%');
match items.next() {
Some(item) => result.append(&mut item.to_vec()),
None => return String::from_utf8(result),
}
for item in items {
match item.len() {
0 => result.push(b'%'),
1 => {
result.push(b'%');
result.append(&mut item.to_vec());
},
_ => {
let fs = &item[..2];
let ls = &item[2..];
if let Some(digit) = to_digit(*fs.get(0).unwrap(), *fs.get(1).unwrap()) {
result.push(digit);
result.append(&mut ls.to_vec());
} else {
result.push(b'%');
result.append(&mut item.to_vec());
}
},
}
}
return String::from_utf8(result);
}
/// Like unquote(), but also replaces plus signs by spaces, as required for
/// unquoting HTML form values.
///
/// # Examples
///
/// ```
/// use urlparse::unquote_plus;
///
/// let s = unquote_plus("ABC%3D123%21+DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote_plus<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let _s = s.as_ref().replace("+", " ");
return unquote(_s);
}
fn to_digit(n1: u8, n2: u8) -> Option<u8> {
let mut byte : u8 = 0;
match DIGIT.binary_search(&n1) {
Ok(_n1) => byte += if _n1 < 16 {_n1 as u8 * 16} else {(_n1 - OFFSET) as u8 * 16},
Err(_) => return None,
}
match DIGIT.binary_search(&n2) {
Ok(_n2) => byte += if _n2 < 16 {_n2 as u8} else
|
,
Err(_) => return None,
}
return Some(byte);
}
#[test]
fn test_to_digit() {
assert_eq!(to_digit(b'1', b'2'), Some(0x12));
assert_eq!(to_digit(b'e', b'a'), Some(0xEA));
assert_eq!(to_digit(b'E', b'A'), Some(0xEA));
assert_eq!(to_digit(b'F', b'F'), Some(0xFF));
assert_eq!(to_digit(b'X', b'1'), None);
assert_eq!(to_digit(b'A', b'x'), None);
}
|
{(_n2 - OFFSET) as u8}
|
conditional_block
|
unquote.rs
|
/* Copyright (C) 2015-2016 Yutaka Kamei */
use std::string::FromUtf8Error;
const OFFSET : usize = 6;
const DIGIT : &'static [u8] = b"0123456789ABCDEFabcdef";
/// Replaces %xx escapes by their single-character equivalent.
///
/// # Examples
///
/// ```
/// use urlparse::unquote;
///
/// let s = unquote("ABC%3D123%21%20DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn unquote<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let mut result : Vec<u8> = Vec::new();
let mut items = s.as_ref().as_bytes().split(|&b| b == b'%');
match items.next() {
Some(item) => result.append(&mut item.to_vec()),
None => return String::from_utf8(result),
}
for item in items {
match item.len() {
0 => result.push(b'%'),
1 => {
result.push(b'%');
result.append(&mut item.to_vec());
},
_ => {
let fs = &item[..2];
let ls = &item[2..];
if let Some(digit) = to_digit(*fs.get(0).unwrap(), *fs.get(1).unwrap()) {
result.push(digit);
result.append(&mut ls.to_vec());
} else {
result.push(b'%');
result.append(&mut item.to_vec());
}
},
}
}
return String::from_utf8(result);
}
/// Like unquote(), but also replaces plus signs by spaces, as required for
/// unquoting HTML form values.
///
/// # Examples
///
/// ```
/// use urlparse::unquote_plus;
///
/// let s = unquote_plus("ABC%3D123%21+DEF%3D%23%23");
/// assert_eq!(s.ok().unwrap(), "ABC=123! DEF=##");
/// ```
///
pub fn
|
<S: AsRef<str>>(s: S) -> Result<String, FromUtf8Error> {
let _s = s.as_ref().replace("+", " ");
return unquote(_s);
}
fn to_digit(n1: u8, n2: u8) -> Option<u8> {
let mut byte : u8 = 0;
match DIGIT.binary_search(&n1) {
Ok(_n1) => byte += if _n1 < 16 {_n1 as u8 * 16} else {(_n1 - OFFSET) as u8 * 16},
Err(_) => return None,
}
match DIGIT.binary_search(&n2) {
Ok(_n2) => byte += if _n2 < 16 {_n2 as u8} else {(_n2 - OFFSET) as u8},
Err(_) => return None,
}
return Some(byte);
}
#[test]
fn test_to_digit() {
assert_eq!(to_digit(b'1', b'2'), Some(0x12));
assert_eq!(to_digit(b'e', b'a'), Some(0xEA));
assert_eq!(to_digit(b'E', b'A'), Some(0xEA));
assert_eq!(to_digit(b'F', b'F'), Some(0xFF));
assert_eq!(to_digit(b'X', b'1'), None);
assert_eq!(to_digit(b'A', b'x'), None);
}
|
unquote_plus
|
identifier_name
|
mean.rs
|
//! Functions for calculating mean
use std::f64::NAN;
/// Calculates arithmetic mean (AM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [8., 16.];
/// assert_eq!(mean::arithmetic(&slice), 12.);
/// ```
pub fn
|
(slice: &[f64]) -> f64 {
slice.iter().fold(0., |a, b| a + b) / slice.len() as f64
}
/// Calculate geometric mean (GM) of data set `slice`.
///
/// If the result would be imaginary, function returns `NAN`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [9., 16.];
/// assert_eq!(mean::geometric(&slice), 12.);
/// ```
pub fn geometric(slice: &[f64]) -> f64 {
let product = slice.iter().fold(1., |a, b| a * b);
match product < 0. {
true => NAN,
false => product.powf(1. / slice.len() as f64),
}
}
/// Calculate harmonic mean (HM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [1., 7.];
/// assert_eq!(mean::harmonic(&slice), 1.75);
/// ```
pub fn harmonic(slice: &[f64]) -> f64 {
slice.len() as f64 / slice.iter().fold(0., |a, b| a + 1. / b)
}
#[cfg(test)]
mod tests {
use std::f64::{ NAN, INFINITY, NEG_INFINITY };
use round;
macro_rules! test_mean {
($func:path [ $($name:ident: $params:expr,)* ]) => {
$(
#[test]
fn $name() {
let (slice, expected): (&[f64], f64) = $params;
let result = $func(slice);
match result.is_nan() {
true => assert_eq!(expected.is_nan(), true),
false => assert_eq!(round::half_up(result, 6), expected),
}
}
)*
}
}
test_mean! { super::arithmetic [
arithmetic_1: (&[-7., -4., 1., 3., 8.], 0.2),
arithmetic_2: (&[-4., 1., 3., 8., 12.], 4.),
arithmetic_3: (&[0., 0., 0., 0., 0.], 0.),
arithmetic_4: (&[0., 4., 7., 9., 17.], 7.4),
arithmetic_5: (&[1., 2., 6., 4., 13.], 5.2),
arithmetic_6: (&[1., 5., 10., 20., 25.], 12.2),
arithmetic_7: (&[2., 3., 5., 7., 11.], 5.6),
arithmetic_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NEG_INFINITY),
arithmetic_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::geometric [
geometric_1: (&[-7., -4., 1., 3., 8.], 3.676833),
geometric_2: (&[-4., 1., 3., 8., 12.], NAN),
geometric_3: (&[0., 0., 0., 0., 0.], 0.),
geometric_4: (&[0., 4., 7., 9., 17.], 0.),
geometric_5: (&[1., 2., 6., 4., 13.], 3.622738),
geometric_6: (&[1., 5., 10., 20., 25.], 7.578583),
geometric_7: (&[2., 3., 5., 7., 11.], 4.706764),
geometric_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NAN),
geometric_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::harmonic [
harmonic_1: (&[-7., -4., 1., 3., 8.], 4.692737),
harmonic_2: (&[-4., 1., 3., 8., 12.], 3.870968),
harmonic_3: (&[0., 0., 0., 0., 0.], 0.),
harmonic_4: (&[0., 4., 7., 9., 17.], 0.),
harmonic_5: (&[1., 2., 6., 4., 13.], 2.508039),
harmonic_6: (&[1., 5., 10., 20., 25.], 3.597122),
harmonic_7: (&[2., 3., 5., 7., 11.], 3.94602),
harmonic_8: (&[NEG_INFINITY, 1., 2., 3., 4.], 2.4),
harmonic_9: (&[1., 2., 3., 4., INFINITY], 2.4),
]}
}
|
arithmetic
|
identifier_name
|
mean.rs
|
//! Functions for calculating mean
use std::f64::NAN;
/// Calculates arithmetic mean (AM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [8., 16.];
/// assert_eq!(mean::arithmetic(&slice), 12.);
/// ```
pub fn arithmetic(slice: &[f64]) -> f64 {
slice.iter().fold(0., |a, b| a + b) / slice.len() as f64
}
/// Calculate geometric mean (GM) of data set `slice`.
///
/// If the result would be imaginary, function returns `NAN`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [9., 16.];
/// assert_eq!(mean::geometric(&slice), 12.);
/// ```
pub fn geometric(slice: &[f64]) -> f64 {
let product = slice.iter().fold(1., |a, b| a * b);
match product < 0. {
true => NAN,
false => product.powf(1. / slice.len() as f64),
}
}
/// Calculate harmonic mean (HM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [1., 7.];
/// assert_eq!(mean::harmonic(&slice), 1.75);
/// ```
pub fn harmonic(slice: &[f64]) -> f64 {
slice.len() as f64 / slice.iter().fold(0., |a, b| a + 1. / b)
}
#[cfg(test)]
mod tests {
use std::f64::{ NAN, INFINITY, NEG_INFINITY };
use round;
macro_rules! test_mean {
($func:path [ $($name:ident: $params:expr,)* ]) => {
$(
#[test]
fn $name() {
let (slice, expected): (&[f64], f64) = $params;
let result = $func(slice);
match result.is_nan() {
true => assert_eq!(expected.is_nan(), true),
false => assert_eq!(round::half_up(result, 6), expected),
}
}
)*
}
}
test_mean! { super::arithmetic [
arithmetic_1: (&[-7., -4., 1., 3., 8.], 0.2),
arithmetic_2: (&[-4., 1., 3., 8., 12.], 4.),
arithmetic_3: (&[0., 0., 0., 0., 0.], 0.),
arithmetic_4: (&[0., 4., 7., 9., 17.], 7.4),
arithmetic_5: (&[1., 2., 6., 4., 13.], 5.2),
arithmetic_6: (&[1., 5., 10., 20., 25.], 12.2),
arithmetic_7: (&[2., 3., 5., 7., 11.], 5.6),
arithmetic_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NEG_INFINITY),
arithmetic_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::geometric [
geometric_1: (&[-7., -4., 1., 3., 8.], 3.676833),
geometric_2: (&[-4., 1., 3., 8., 12.], NAN),
geometric_3: (&[0., 0., 0., 0., 0.], 0.),
|
geometric_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NAN),
geometric_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::harmonic [
harmonic_1: (&[-7., -4., 1., 3., 8.], 4.692737),
harmonic_2: (&[-4., 1., 3., 8., 12.], 3.870968),
harmonic_3: (&[0., 0., 0., 0., 0.], 0.),
harmonic_4: (&[0., 4., 7., 9., 17.], 0.),
harmonic_5: (&[1., 2., 6., 4., 13.], 2.508039),
harmonic_6: (&[1., 5., 10., 20., 25.], 3.597122),
harmonic_7: (&[2., 3., 5., 7., 11.], 3.94602),
harmonic_8: (&[NEG_INFINITY, 1., 2., 3., 4.], 2.4),
harmonic_9: (&[1., 2., 3., 4., INFINITY], 2.4),
]}
}
|
geometric_4: (&[0., 4., 7., 9., 17.], 0.),
geometric_5: (&[1., 2., 6., 4., 13.], 3.622738),
geometric_6: (&[1., 5., 10., 20., 25.], 7.578583),
geometric_7: (&[2., 3., 5., 7., 11.], 4.706764),
|
random_line_split
|
mean.rs
|
//! Functions for calculating mean
use std::f64::NAN;
/// Calculates arithmetic mean (AM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [8., 16.];
/// assert_eq!(mean::arithmetic(&slice), 12.);
/// ```
pub fn arithmetic(slice: &[f64]) -> f64
|
/// Calculate geometric mean (GM) of data set `slice`.
///
/// If the result would be imaginary, function returns `NAN`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [9., 16.];
/// assert_eq!(mean::geometric(&slice), 12.);
/// ```
pub fn geometric(slice: &[f64]) -> f64 {
let product = slice.iter().fold(1., |a, b| a * b);
match product < 0. {
true => NAN,
false => product.powf(1. / slice.len() as f64),
}
}
/// Calculate harmonic mean (HM) of data set `slice`.
///
/// # Arguments
///
/// * `slice` - collection of values
///
/// # Example
///
/// ```
/// use math::mean;
///
/// let slice = [1., 7.];
/// assert_eq!(mean::harmonic(&slice), 1.75);
/// ```
pub fn harmonic(slice: &[f64]) -> f64 {
slice.len() as f64 / slice.iter().fold(0., |a, b| a + 1. / b)
}
#[cfg(test)]
mod tests {
use std::f64::{ NAN, INFINITY, NEG_INFINITY };
use round;
macro_rules! test_mean {
($func:path [ $($name:ident: $params:expr,)* ]) => {
$(
#[test]
fn $name() {
let (slice, expected): (&[f64], f64) = $params;
let result = $func(slice);
match result.is_nan() {
true => assert_eq!(expected.is_nan(), true),
false => assert_eq!(round::half_up(result, 6), expected),
}
}
)*
}
}
test_mean! { super::arithmetic [
arithmetic_1: (&[-7., -4., 1., 3., 8.], 0.2),
arithmetic_2: (&[-4., 1., 3., 8., 12.], 4.),
arithmetic_3: (&[0., 0., 0., 0., 0.], 0.),
arithmetic_4: (&[0., 4., 7., 9., 17.], 7.4),
arithmetic_5: (&[1., 2., 6., 4., 13.], 5.2),
arithmetic_6: (&[1., 5., 10., 20., 25.], 12.2),
arithmetic_7: (&[2., 3., 5., 7., 11.], 5.6),
arithmetic_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NEG_INFINITY),
arithmetic_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::geometric [
geometric_1: (&[-7., -4., 1., 3., 8.], 3.676833),
geometric_2: (&[-4., 1., 3., 8., 12.], NAN),
geometric_3: (&[0., 0., 0., 0., 0.], 0.),
geometric_4: (&[0., 4., 7., 9., 17.], 0.),
geometric_5: (&[1., 2., 6., 4., 13.], 3.622738),
geometric_6: (&[1., 5., 10., 20., 25.], 7.578583),
geometric_7: (&[2., 3., 5., 7., 11.], 4.706764),
geometric_8: (&[NEG_INFINITY, 1., 2., 3., 4.], NAN),
geometric_9: (&[1., 2., 3., 4., INFINITY], INFINITY),
]}
test_mean! { super::harmonic [
harmonic_1: (&[-7., -4., 1., 3., 8.], 4.692737),
harmonic_2: (&[-4., 1., 3., 8., 12.], 3.870968),
harmonic_3: (&[0., 0., 0., 0., 0.], 0.),
harmonic_4: (&[0., 4., 7., 9., 17.], 0.),
harmonic_5: (&[1., 2., 6., 4., 13.], 2.508039),
harmonic_6: (&[1., 5., 10., 20., 25.], 3.597122),
harmonic_7: (&[2., 3., 5., 7., 11.], 3.94602),
harmonic_8: (&[NEG_INFINITY, 1., 2., 3., 4.], 2.4),
harmonic_9: (&[1., 2., 3., 4., INFINITY], 2.4),
]}
}
|
{
slice.iter().fold(0., |a, b| a + b) / slice.len() as f64
}
|
identifier_body
|
window.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 windowing implementation using GLUT.
use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver};
use compositing::windowing::{WindowEvent, WindowMethods};
use compositing::windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use compositing::windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use compositing::windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use compositing::windowing::{Forward, Back};
use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use geom::point::{Point2D, TypedPoint2D};
use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::platform::surface::NativeGraphicsMetadata;
use msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use msg::compositor_msg::{FinishedLoading, Blank, ReadyState};
use util::geometry::ScreenPx;
use glut::glut::{ACTIVE_SHIFT, WindowHeight};
use glut::glut::WindowWidth;
use glut::glut;
// static THROBBER: [char,..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];
/// The type of a window.
pub struct Window {
pub glut_window: glut::Window,
pub event_queue: RefCell<Vec<WindowEvent>>,
pub drag_origin: Point2D<c_int>,
pub mouse_down_button: Cell<c_int>,
pub mouse_down_point: Cell<Point2D<c_int>>,
pub ready_state: Cell<ReadyState>,
pub render_state: Cell<RenderState>,
pub throbber_frame: Cell<u8>,
}
impl Window {
/// Creates a new window.
pub fn new(size: TypedSize2D<DevicePixel, uint>) -> Rc<Window> {
// Create the GLUT window.
let window_size = size.to_untyped();
glut::init_window_size(window_size.width, window_size.height);
let glut_window = glut::create_window("Servo".to_string());
// Create our window object.
let window = Window {
glut_window: glut_window,
event_queue: RefCell::new(vec!()),
drag_origin: Point2D(0 as c_int, 0),
mouse_down_button: Cell::new(0),
mouse_down_point: Cell::new(Point2D(0 as c_int, 0)),
ready_state: Cell::new(Blank),
render_state: Cell::new(IdleRenderState),
throbber_frame: Cell::new(0),
};
// Register event handlers.
//Added dummy display callback to freeglut. According to freeglut ref, we should register some kind of display callback after freeglut 3.0.
struct DisplayCallbackState;
impl glut::DisplayCallback for DisplayCallbackState {
fn call(&self) {
debug!("GLUT display func registgered");
}
}
glut::display_func(box DisplayCallbackState);
struct ReshapeCallbackState;
impl glut::ReshapeCallback for ReshapeCallbackState {
fn call(&self, width: c_int, height: c_int) {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ResizeWindowEvent(TypedSize2D(width as uint, height as uint)))
}
}
glut::reshape_func(glut_window, box ReshapeCallbackState);
struct KeyboardCallbackState;
impl glut::KeyboardCallback for KeyboardCallbackState {
fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
let tmp = local_window();
tmp.handle_key(key)
}
}
glut::keyboard_func(box KeyboardCallbackState);
struct MouseCallbackState;
impl glut::MouseCallback for MouseCallbackState {
fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
if button < 3 {
let tmp = local_window();
tmp.handle_mouse(button, state, x, y);
} else {
match button {
3 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32)));
},
4 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32)));
},
_ => {}
}
}
}
}
glut::mouse_func(box MouseCallbackState);
let wrapped_window = Rc::new(window);
install_local_window(wrapped_window.clone());
wrapped_window
}
pub fn wait_events(&self) -> WindowEvent {
if!self.event_queue.borrow_mut().is_empty() {
return self.event_queue.borrow_mut().remove(0).unwrap();
}
// XXX: Need a function that blocks waiting for events, like glfwWaitEvents.
glut::check_loop();
self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent)
}
}
impl Drop for Window {
fn drop(&mut self) {
drop_local_window();
}
}
impl WindowMethods for Window {
/// Returns the size of the window in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint> {
TypedSize2D(glut::get(WindowWidth) as uint, glut::get(WindowHeight) as uint)
}
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<ScreenPx, f32> {
self.framebuffer_size().as_f32() / self.hidpi_factor()
}
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self) {
glut::swap_buffers();
}
fn create_compositor_channel(_: &Option<Rc<Window>>)
-> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) {
let (sender, receiver) = channel();
(box GlutCompositorProxy {
sender: sender,
} as Box<CompositorProxy+Send>,
box receiver as Box<CompositorReceiver>)
}
/// Sets the ready state.
fn set_ready_state(&self, ready_state: ReadyState) {
self.ready_state.set(ready_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
/// Sets the render state.
fn set_render_state(&self, render_state: RenderState) {
if self.ready_state.get() == FinishedLoading &&
self.render_state.get() == RenderingRenderState &&
render_state == IdleRenderState {
// page loaded
self.event_queue.borrow_mut().push(FinishedWindowEvent);
}
self.render_state.set(render_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
//FIXME: Do nothing in GLUT now.
ScaleFactor(1.0)
}
fn native_metadata(&self) -> NativeGraphicsMetadata {
use egl::egl::GetCurrentDisplay;
NativeGraphicsMetadata {
display: GetCurrentDisplay(),
}
}
}
impl Window {
/// Helper function to set the window title in accordance with the ready state.
// fn update_window_title(&self) {
// let throbber = THROBBER[self.throbber_frame];
// match self.ready_state {
// Blank => {
// glut::set_window_title(self.glut_window, "Blank")
// }
// Loading => {
// glut::set_window_title(self.glut_window, format!("{:c} Loading. Servo", throbber))
// }
// PerformingLayout => {
// glut::set_window_title(self.glut_window, format!("{:c} Performing Layout. Servo", throbber))
// }
// FinishedLoading => {
// match self.render_state {
// RenderingRenderState => {
// glut::set_window_title(self.glut_window, format!("{:c} Rendering. Servo", throbber))
// }
// IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
// }
// }
// }
// }
/// Helper function to handle keyboard events.
fn handle_key(&self, key: u8) {
debug!("got key: {}", key);
let modifiers = glut::get_modifiers();
match key {
42 => self.load_url(),
43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32))),
50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32))),
127 => {
if (modifiers & ACTIVE_SHIFT)!= 0 {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));
}
else {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Back));
}
}
_ => {}
}
}
/// Helper function to handle a click
fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
// FIXME(tkuehn): max pixel dist should be based on pixel density
let max_pixel_dist = 10f32;
let event = match state {
glut::MOUSE_DOWN => {
self.mouse_down_point.set(Point2D(x, y));
self.mouse_down_button.set(button);
MouseWindowMouseDownEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
glut::MOUSE_UP => {
if self.mouse_down_button.get() == button {
let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
let pixel_dist = ((pixel_dist.x * pixel_dist.x +
pixel_dist.y * pixel_dist.y) as f32).sqrt();
if pixel_dist < max_pixel_dist {
let click_event = MouseWindowClickEvent(button as uint,
TypedPoint2D(x as f32, y as f32));
self.event_queue.borrow_mut().push(MouseWindowEventClass(click_event));
}
}
MouseWindowMouseUpEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
_ => panic!("I cannot recognize the type of mouse action that occured. :-(")
};
self.event_queue.borrow_mut().push(MouseWindowEventClass(event));
}
/// Helper function to pop up an alert box prompting the user to load a URL.
fn load_url(&self) {
let mut alert: Alert = AlertMethods::new("Navigate to:");
alert.add_prompt();
alert.run();
let value = alert.prompt_value();
if "" == value.as_slice() { // To avoid crashing on Linux.
self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_string()))
} else {
self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
}
}
}
struct GlutCompositorProxy {
sender: Sender<compositor_task::Msg>,
}
impl CompositorProxy for GlutCompositorProxy {
fn send(&mut self, msg: compositor_task::Msg) {
// Send a message and kick the OS event loop awake.
self.sender.send(msg);
// XXX: Need a way to unblock wait_events, like glfwPostEmptyEvent
}
fn clone_compositor_proxy(&self) -> Box<CompositorProxy+Send> {
box Gl
|
key!(TLS_KEY: Rc<Window>)
fn install_local_window(window: Rc<Window>) {
TLS_KEY.replace(Some(window));
}
fn drop_local_window() {
TLS_KEY.replace(None);
}
fn local_window() -> Rc<Window> {
TLS_KEY.get().unwrap().clone()
}
|
utCompositorProxy {
sender: self.sender.clone(),
} as Box<CompositorProxy+Send>
}
}
local_data_
|
identifier_body
|
window.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 windowing implementation using GLUT.
use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver};
use compositing::windowing::{WindowEvent, WindowMethods};
use compositing::windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use compositing::windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use compositing::windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use compositing::windowing::{Forward, Back};
use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use geom::point::{Point2D, TypedPoint2D};
use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::platform::surface::NativeGraphicsMetadata;
use msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use msg::compositor_msg::{FinishedLoading, Blank, ReadyState};
use util::geometry::ScreenPx;
use glut::glut::{ACTIVE_SHIFT, WindowHeight};
use glut::glut::WindowWidth;
use glut::glut;
// static THROBBER: [char,..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];
/// The type of a window.
pub struct Window {
pub glut_window: glut::Window,
pub event_queue: RefCell<Vec<WindowEvent>>,
pub drag_origin: Point2D<c_int>,
pub mouse_down_button: Cell<c_int>,
pub mouse_down_point: Cell<Point2D<c_int>>,
pub ready_state: Cell<ReadyState>,
pub render_state: Cell<RenderState>,
pub throbber_frame: Cell<u8>,
}
impl Window {
/// Creates a new window.
pub fn new(size: TypedSize2D<DevicePixel, uint>) -> Rc<Window> {
// Create the GLUT window.
let window_size = size.to_untyped();
glut::init_window_size(window_size.width, window_size.height);
let glut_window = glut::create_window("Servo".to_string());
// Create our window object.
let window = Window {
glut_window: glut_window,
event_queue: RefCell::new(vec!()),
drag_origin: Point2D(0 as c_int, 0),
mouse_down_button: Cell::new(0),
mouse_down_point: Cell::new(Point2D(0 as c_int, 0)),
ready_state: Cell::new(Blank),
render_state: Cell::new(IdleRenderState),
throbber_frame: Cell::new(0),
};
// Register event handlers.
//Added dummy display callback to freeglut. According to freeglut ref, we should register some kind of display callback after freeglut 3.0.
struct DisplayCallbackState;
impl glut::DisplayCallback for DisplayCallbackState {
fn call(&self) {
debug!("GLUT display func registgered");
}
}
glut::display_func(box DisplayCallbackState);
struct ReshapeCallbackState;
impl glut::ReshapeCallback for ReshapeCallbackState {
fn call(&self, width: c_int, height: c_int) {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ResizeWindowEvent(TypedSize2D(width as uint, height as uint)))
}
}
glut::reshape_func(glut_window, box ReshapeCallbackState);
struct KeyboardCallbackState;
impl glut::KeyboardCallback for KeyboardCallbackState {
fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
let tmp = local_window();
tmp.handle_key(key)
}
}
glut::keyboard_func(box KeyboardCallbackState);
struct MouseCallbackState;
impl glut::MouseCallback for MouseCallbackState {
fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
if button < 3 {
let tmp = local_window();
tmp.handle_mouse(button, state, x, y);
} else {
match button {
3 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32)));
},
4 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32)));
},
_ => {}
}
}
}
}
glut::mouse_func(box MouseCallbackState);
let wrapped_window = Rc::new(window);
install_local_window(wrapped_window.clone());
wrapped_window
}
pub fn wait_events(&self) -> WindowEvent {
if!self.event_queue.borrow_mut().is_empty() {
return self.event_queue.borrow_mut().remove(0).unwrap();
}
// XXX: Need a function that blocks waiting for events, like glfwWaitEvents.
glut::check_loop();
self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent)
}
}
impl Drop for Window {
fn drop(&mut self) {
drop_local_window();
}
}
impl WindowMethods for Window {
/// Returns the size of the window in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint> {
TypedSize2D(glut::get(WindowWidth) as uint, glut::get(WindowHeight) as uint)
}
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<ScreenPx, f32> {
self.framebuffer_size().as_f32() / self.hidpi_factor()
}
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self) {
glut::swap_buffers();
}
fn create_compositor_channel(_: &Option<Rc<Window>>)
-> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) {
let (sender, receiver) = channel();
(box GlutCompositorProxy {
sender: sender,
} as Box<CompositorProxy+Send>,
box receiver as Box<CompositorReceiver>)
}
/// Sets the ready state.
fn set_ready_state(&self, ready_state: ReadyState) {
self.ready_state.set(ready_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
/// Sets the render state.
fn set_render_state(&self, render_state: RenderState) {
if self.ready_state.get() == FinishedLoading &&
self.render_state.get() == RenderingRenderState &&
render_state == IdleRenderState {
// page loaded
self.event_queue.borrow_mut().push(FinishedWindowEvent);
}
self.render_state.set(render_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
//FIXME: Do nothing in GLUT now.
ScaleFactor(1.0)
}
fn native_metadata(&self) -> NativeGraphicsMetadata {
use egl::egl::GetCurrentDisplay;
NativeGraphicsMetadata {
display: GetCurrentDisplay(),
}
}
}
impl Window {
/// Helper function to set the window title in accordance with the ready state.
// fn update_window_title(&self) {
// let throbber = THROBBER[self.throbber_frame];
// match self.ready_state {
// Blank => {
// glut::set_window_title(self.glut_window, "Blank")
// }
// Loading => {
// glut::set_window_title(self.glut_window, format!("{:c} Loading. Servo", throbber))
// }
// PerformingLayout => {
// glut::set_window_title(self.glut_window, format!("{:c} Performing Layout. Servo", throbber))
// }
// FinishedLoading => {
// match self.render_state {
// RenderingRenderState => {
// glut::set_window_title(self.glut_window, format!("{:c} Rendering. Servo", throbber))
// }
// IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
// }
// }
// }
// }
/// Helper function to handle keyboard events.
fn handle_key(&self, key: u8) {
debug!("got key: {}", key);
let modifiers = glut::get_modifiers();
match key {
42 => self.load_url(),
43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32))),
50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32))),
127 => {
if (modifiers & ACTIVE_SHIFT)!= 0 {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));
}
else {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Back));
}
}
_ => {}
}
}
/// Helper function to handle a click
fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
// FIXME(tkuehn): max pixel dist should be based on pixel density
let max_pixel_dist = 10f32;
let event = match state {
glut::MOUSE_DOWN => {
self.mouse_down_point.set(Point2D(x, y));
self.mouse_down_button.set(button);
MouseWindowMouseDownEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
glut::MOUSE_UP => {
|
> panic!("I cannot recognize the type of mouse action that occured. :-(")
};
self.event_queue.borrow_mut().push(MouseWindowEventClass(event));
}
/// Helper function to pop up an alert box prompting the user to load a URL.
fn load_url(&self) {
let mut alert: Alert = AlertMethods::new("Navigate to:");
alert.add_prompt();
alert.run();
let value = alert.prompt_value();
if "" == value.as_slice() { // To avoid crashing on Linux.
self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_string()))
} else {
self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
}
}
}
struct GlutCompositorProxy {
sender: Sender<compositor_task::Msg>,
}
impl CompositorProxy for GlutCompositorProxy {
fn send(&mut self, msg: compositor_task::Msg) {
// Send a message and kick the OS event loop awake.
self.sender.send(msg);
// XXX: Need a way to unblock wait_events, like glfwPostEmptyEvent
}
fn clone_compositor_proxy(&self) -> Box<CompositorProxy+Send> {
box GlutCompositorProxy {
sender: self.sender.clone(),
} as Box<CompositorProxy+Send>
}
}
local_data_key!(TLS_KEY: Rc<Window>)
fn install_local_window(window: Rc<Window>) {
TLS_KEY.replace(Some(window));
}
fn drop_local_window() {
TLS_KEY.replace(None);
}
fn local_window() -> Rc<Window> {
TLS_KEY.get().unwrap().clone()
}
|
if self.mouse_down_button.get() == button {
let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
let pixel_dist = ((pixel_dist.x * pixel_dist.x +
pixel_dist.y * pixel_dist.y) as f32).sqrt();
if pixel_dist < max_pixel_dist {
let click_event = MouseWindowClickEvent(button as uint,
TypedPoint2D(x as f32, y as f32));
self.event_queue.borrow_mut().push(MouseWindowEventClass(click_event));
}
}
MouseWindowMouseUpEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
_ =
|
conditional_block
|
window.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 windowing implementation using GLUT.
use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver};
use compositing::windowing::{WindowEvent, WindowMethods};
use compositing::windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use compositing::windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use compositing::windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use compositing::windowing::{Forward, Back};
use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use geom::point::{Point2D, TypedPoint2D};
use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::platform::surface::NativeGraphicsMetadata;
use msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use msg::compositor_msg::{FinishedLoading, Blank, ReadyState};
use util::geometry::ScreenPx;
use glut::glut::{ACTIVE_SHIFT, WindowHeight};
use glut::glut::WindowWidth;
use glut::glut;
// static THROBBER: [char,..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];
/// The type of a window.
pub struct Window {
pub glut_window: glut::Window,
pub event_queue: RefCell<Vec<WindowEvent>>,
pub drag_origin: Point2D<c_int>,
pub mouse_down_button: Cell<c_int>,
pub mouse_down_point: Cell<Point2D<c_int>>,
pub ready_state: Cell<ReadyState>,
pub render_state: Cell<RenderState>,
pub throbber_frame: Cell<u8>,
}
impl Window {
/// Creates a new window.
pub fn new(size: TypedSize2D<DevicePixel, uint>) -> Rc<Window> {
// Create the GLUT window.
let window_size = size.to_untyped();
glut::init_window_size(window_size.width, window_size.height);
let glut_window = glut::create_window("Servo".to_string());
// Create our window object.
let window = Window {
glut_window: glut_window,
event_queue: RefCell::new(vec!()),
drag_origin: Point2D(0 as c_int, 0),
mouse_down_button: Cell::new(0),
mouse_down_point: Cell::new(Point2D(0 as c_int, 0)),
ready_state: Cell::new(Blank),
render_state: Cell::new(IdleRenderState),
throbber_frame: Cell::new(0),
};
// Register event handlers.
//Added dummy display callback to freeglut. According to freeglut ref, we should register some kind of display callback after freeglut 3.0.
struct DisplayCallbackState;
impl glut::DisplayCallback for DisplayCallbackState {
fn call(&self) {
debug!("GLUT display func registgered");
}
}
glut::display_func(box DisplayCallbackState);
struct ReshapeCallbackState;
impl glut::ReshapeCallback for ReshapeCallbackState {
fn call(&self, width: c_int, height: c_int) {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ResizeWindowEvent(TypedSize2D(width as uint, height as uint)))
}
}
glut::reshape_func(glut_window, box ReshapeCallbackState);
struct KeyboardCallbackState;
impl glut::KeyboardCallback for KeyboardCallbackState {
fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
let tmp = local_window();
tmp.handle_key(key)
}
}
glut::keyboard_func(box KeyboardCallbackState);
struct MouseCallbackSta
|
lut::MouseCallback for MouseCallbackState {
fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
if button < 3 {
let tmp = local_window();
tmp.handle_mouse(button, state, x, y);
} else {
match button {
3 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32)));
},
4 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32)));
},
_ => {}
}
}
}
}
glut::mouse_func(box MouseCallbackState);
let wrapped_window = Rc::new(window);
install_local_window(wrapped_window.clone());
wrapped_window
}
pub fn wait_events(&self) -> WindowEvent {
if!self.event_queue.borrow_mut().is_empty() {
return self.event_queue.borrow_mut().remove(0).unwrap();
}
// XXX: Need a function that blocks waiting for events, like glfwWaitEvents.
glut::check_loop();
self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent)
}
}
impl Drop for Window {
fn drop(&mut self) {
drop_local_window();
}
}
impl WindowMethods for Window {
/// Returns the size of the window in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint> {
TypedSize2D(glut::get(WindowWidth) as uint, glut::get(WindowHeight) as uint)
}
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<ScreenPx, f32> {
self.framebuffer_size().as_f32() / self.hidpi_factor()
}
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self) {
glut::swap_buffers();
}
fn create_compositor_channel(_: &Option<Rc<Window>>)
-> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) {
let (sender, receiver) = channel();
(box GlutCompositorProxy {
sender: sender,
} as Box<CompositorProxy+Send>,
box receiver as Box<CompositorReceiver>)
}
/// Sets the ready state.
fn set_ready_state(&self, ready_state: ReadyState) {
self.ready_state.set(ready_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
/// Sets the render state.
fn set_render_state(&self, render_state: RenderState) {
if self.ready_state.get() == FinishedLoading &&
self.render_state.get() == RenderingRenderState &&
render_state == IdleRenderState {
// page loaded
self.event_queue.borrow_mut().push(FinishedWindowEvent);
}
self.render_state.set(render_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
//FIXME: Do nothing in GLUT now.
ScaleFactor(1.0)
}
fn native_metadata(&self) -> NativeGraphicsMetadata {
use egl::egl::GetCurrentDisplay;
NativeGraphicsMetadata {
display: GetCurrentDisplay(),
}
}
}
impl Window {
/// Helper function to set the window title in accordance with the ready state.
// fn update_window_title(&self) {
// let throbber = THROBBER[self.throbber_frame];
// match self.ready_state {
// Blank => {
// glut::set_window_title(self.glut_window, "Blank")
// }
// Loading => {
// glut::set_window_title(self.glut_window, format!("{:c} Loading. Servo", throbber))
// }
// PerformingLayout => {
// glut::set_window_title(self.glut_window, format!("{:c} Performing Layout. Servo", throbber))
// }
// FinishedLoading => {
// match self.render_state {
// RenderingRenderState => {
// glut::set_window_title(self.glut_window, format!("{:c} Rendering. Servo", throbber))
// }
// IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
// }
// }
// }
// }
/// Helper function to handle keyboard events.
fn handle_key(&self, key: u8) {
debug!("got key: {}", key);
let modifiers = glut::get_modifiers();
match key {
42 => self.load_url(),
43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32))),
50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32))),
127 => {
if (modifiers & ACTIVE_SHIFT)!= 0 {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));
}
else {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Back));
}
}
_ => {}
}
}
/// Helper function to handle a click
fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
// FIXME(tkuehn): max pixel dist should be based on pixel density
let max_pixel_dist = 10f32;
let event = match state {
glut::MOUSE_DOWN => {
self.mouse_down_point.set(Point2D(x, y));
self.mouse_down_button.set(button);
MouseWindowMouseDownEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
glut::MOUSE_UP => {
if self.mouse_down_button.get() == button {
let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
let pixel_dist = ((pixel_dist.x * pixel_dist.x +
pixel_dist.y * pixel_dist.y) as f32).sqrt();
if pixel_dist < max_pixel_dist {
let click_event = MouseWindowClickEvent(button as uint,
TypedPoint2D(x as f32, y as f32));
self.event_queue.borrow_mut().push(MouseWindowEventClass(click_event));
}
}
MouseWindowMouseUpEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
_ => panic!("I cannot recognize the type of mouse action that occured. :-(")
};
self.event_queue.borrow_mut().push(MouseWindowEventClass(event));
}
/// Helper function to pop up an alert box prompting the user to load a URL.
fn load_url(&self) {
let mut alert: Alert = AlertMethods::new("Navigate to:");
alert.add_prompt();
alert.run();
let value = alert.prompt_value();
if "" == value.as_slice() { // To avoid crashing on Linux.
self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_string()))
} else {
self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
}
}
}
struct GlutCompositorProxy {
sender: Sender<compositor_task::Msg>,
}
impl CompositorProxy for GlutCompositorProxy {
fn send(&mut self, msg: compositor_task::Msg) {
// Send a message and kick the OS event loop awake.
self.sender.send(msg);
// XXX: Need a way to unblock wait_events, like glfwPostEmptyEvent
}
fn clone_compositor_proxy(&self) -> Box<CompositorProxy+Send> {
box GlutCompositorProxy {
sender: self.sender.clone(),
} as Box<CompositorProxy+Send>
}
}
local_data_key!(TLS_KEY: Rc<Window>)
fn install_local_window(window: Rc<Window>) {
TLS_KEY.replace(Some(window));
}
fn drop_local_window() {
TLS_KEY.replace(None);
}
fn local_window() -> Rc<Window> {
TLS_KEY.get().unwrap().clone()
}
|
te;
impl g
|
identifier_name
|
window.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 windowing implementation using GLUT.
use compositing::compositor_task::{mod, CompositorProxy, CompositorReceiver};
use compositing::windowing::{WindowEvent, WindowMethods};
use compositing::windowing::{IdleWindowEvent, ResizeWindowEvent, LoadUrlWindowEvent, MouseWindowEventClass};
use compositing::windowing::{ScrollWindowEvent, ZoomWindowEvent, NavigationWindowEvent, FinishedWindowEvent};
use compositing::windowing::{MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent};
use compositing::windowing::{Forward, Back};
use alert::{Alert, AlertMethods};
use libc::{c_int, c_uchar};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use geom::point::{Point2D, TypedPoint2D};
use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D;
use layers::geometry::DevicePixel;
use layers::platform::surface::NativeGraphicsMetadata;
use msg::compositor_msg::{IdleRenderState, RenderState, RenderingRenderState};
use msg::compositor_msg::{FinishedLoading, Blank, ReadyState};
use util::geometry::ScreenPx;
use glut::glut::{ACTIVE_SHIFT, WindowHeight};
use glut::glut::WindowWidth;
|
/// The type of a window.
pub struct Window {
pub glut_window: glut::Window,
pub event_queue: RefCell<Vec<WindowEvent>>,
pub drag_origin: Point2D<c_int>,
pub mouse_down_button: Cell<c_int>,
pub mouse_down_point: Cell<Point2D<c_int>>,
pub ready_state: Cell<ReadyState>,
pub render_state: Cell<RenderState>,
pub throbber_frame: Cell<u8>,
}
impl Window {
/// Creates a new window.
pub fn new(size: TypedSize2D<DevicePixel, uint>) -> Rc<Window> {
// Create the GLUT window.
let window_size = size.to_untyped();
glut::init_window_size(window_size.width, window_size.height);
let glut_window = glut::create_window("Servo".to_string());
// Create our window object.
let window = Window {
glut_window: glut_window,
event_queue: RefCell::new(vec!()),
drag_origin: Point2D(0 as c_int, 0),
mouse_down_button: Cell::new(0),
mouse_down_point: Cell::new(Point2D(0 as c_int, 0)),
ready_state: Cell::new(Blank),
render_state: Cell::new(IdleRenderState),
throbber_frame: Cell::new(0),
};
// Register event handlers.
//Added dummy display callback to freeglut. According to freeglut ref, we should register some kind of display callback after freeglut 3.0.
struct DisplayCallbackState;
impl glut::DisplayCallback for DisplayCallbackState {
fn call(&self) {
debug!("GLUT display func registgered");
}
}
glut::display_func(box DisplayCallbackState);
struct ReshapeCallbackState;
impl glut::ReshapeCallback for ReshapeCallbackState {
fn call(&self, width: c_int, height: c_int) {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ResizeWindowEvent(TypedSize2D(width as uint, height as uint)))
}
}
glut::reshape_func(glut_window, box ReshapeCallbackState);
struct KeyboardCallbackState;
impl glut::KeyboardCallback for KeyboardCallbackState {
fn call(&self, key: c_uchar, _x: c_int, _y: c_int) {
let tmp = local_window();
tmp.handle_key(key)
}
}
glut::keyboard_func(box KeyboardCallbackState);
struct MouseCallbackState;
impl glut::MouseCallback for MouseCallbackState {
fn call(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
if button < 3 {
let tmp = local_window();
tmp.handle_mouse(button, state, x, y);
} else {
match button {
3 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32)));
},
4 => {
let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32)));
},
_ => {}
}
}
}
}
glut::mouse_func(box MouseCallbackState);
let wrapped_window = Rc::new(window);
install_local_window(wrapped_window.clone());
wrapped_window
}
pub fn wait_events(&self) -> WindowEvent {
if!self.event_queue.borrow_mut().is_empty() {
return self.event_queue.borrow_mut().remove(0).unwrap();
}
// XXX: Need a function that blocks waiting for events, like glfwWaitEvents.
glut::check_loop();
self.event_queue.borrow_mut().remove(0).unwrap_or(IdleWindowEvent)
}
}
impl Drop for Window {
fn drop(&mut self) {
drop_local_window();
}
}
impl WindowMethods for Window {
/// Returns the size of the window in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint> {
TypedSize2D(glut::get(WindowWidth) as uint, glut::get(WindowHeight) as uint)
}
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<ScreenPx, f32> {
self.framebuffer_size().as_f32() / self.hidpi_factor()
}
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self) {
glut::swap_buffers();
}
fn create_compositor_channel(_: &Option<Rc<Window>>)
-> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) {
let (sender, receiver) = channel();
(box GlutCompositorProxy {
sender: sender,
} as Box<CompositorProxy+Send>,
box receiver as Box<CompositorReceiver>)
}
/// Sets the ready state.
fn set_ready_state(&self, ready_state: ReadyState) {
self.ready_state.set(ready_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
/// Sets the render state.
fn set_render_state(&self, render_state: RenderState) {
if self.ready_state.get() == FinishedLoading &&
self.render_state.get() == RenderingRenderState &&
render_state == IdleRenderState {
// page loaded
self.event_queue.borrow_mut().push(FinishedWindowEvent);
}
self.render_state.set(render_state);
//FIXME: set_window_title causes crash with Android version of freeGLUT. Temporarily blocked.
//self.update_window_title()
}
fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> {
//FIXME: Do nothing in GLUT now.
ScaleFactor(1.0)
}
fn native_metadata(&self) -> NativeGraphicsMetadata {
use egl::egl::GetCurrentDisplay;
NativeGraphicsMetadata {
display: GetCurrentDisplay(),
}
}
}
impl Window {
/// Helper function to set the window title in accordance with the ready state.
// fn update_window_title(&self) {
// let throbber = THROBBER[self.throbber_frame];
// match self.ready_state {
// Blank => {
// glut::set_window_title(self.glut_window, "Blank")
// }
// Loading => {
// glut::set_window_title(self.glut_window, format!("{:c} Loading. Servo", throbber))
// }
// PerformingLayout => {
// glut::set_window_title(self.glut_window, format!("{:c} Performing Layout. Servo", throbber))
// }
// FinishedLoading => {
// match self.render_state {
// RenderingRenderState => {
// glut::set_window_title(self.glut_window, format!("{:c} Rendering. Servo", throbber))
// }
// IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
// }
// }
// }
// }
/// Helper function to handle keyboard events.
fn handle_key(&self, key: u8) {
debug!("got key: {}", key);
let modifiers = glut::get_modifiers();
match key {
42 => self.load_url(),
43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0i32, 5i32))),
50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0i32, -5i32))),
127 => {
if (modifiers & ACTIVE_SHIFT)!= 0 {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));
}
else {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Back));
}
}
_ => {}
}
}
/// Helper function to handle a click
fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
// FIXME(tkuehn): max pixel dist should be based on pixel density
let max_pixel_dist = 10f32;
let event = match state {
glut::MOUSE_DOWN => {
self.mouse_down_point.set(Point2D(x, y));
self.mouse_down_button.set(button);
MouseWindowMouseDownEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
glut::MOUSE_UP => {
if self.mouse_down_button.get() == button {
let pixel_dist = self.mouse_down_point.get() - Point2D(x, y);
let pixel_dist = ((pixel_dist.x * pixel_dist.x +
pixel_dist.y * pixel_dist.y) as f32).sqrt();
if pixel_dist < max_pixel_dist {
let click_event = MouseWindowClickEvent(button as uint,
TypedPoint2D(x as f32, y as f32));
self.event_queue.borrow_mut().push(MouseWindowEventClass(click_event));
}
}
MouseWindowMouseUpEvent(button as uint, TypedPoint2D(x as f32, y as f32))
}
_ => panic!("I cannot recognize the type of mouse action that occured. :-(")
};
self.event_queue.borrow_mut().push(MouseWindowEventClass(event));
}
/// Helper function to pop up an alert box prompting the user to load a URL.
fn load_url(&self) {
let mut alert: Alert = AlertMethods::new("Navigate to:");
alert.add_prompt();
alert.run();
let value = alert.prompt_value();
if "" == value.as_slice() { // To avoid crashing on Linux.
self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_string()))
} else {
self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
}
}
}
struct GlutCompositorProxy {
sender: Sender<compositor_task::Msg>,
}
impl CompositorProxy for GlutCompositorProxy {
fn send(&mut self, msg: compositor_task::Msg) {
// Send a message and kick the OS event loop awake.
self.sender.send(msg);
// XXX: Need a way to unblock wait_events, like glfwPostEmptyEvent
}
fn clone_compositor_proxy(&self) -> Box<CompositorProxy+Send> {
box GlutCompositorProxy {
sender: self.sender.clone(),
} as Box<CompositorProxy+Send>
}
}
local_data_key!(TLS_KEY: Rc<Window>)
fn install_local_window(window: Rc<Window>) {
TLS_KEY.replace(Some(window));
}
fn drop_local_window() {
TLS_KEY.replace(None);
}
fn local_window() -> Rc<Window> {
TLS_KEY.get().unwrap().clone()
}
|
use glut::glut;
// static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];
|
random_line_split
|
instr_pmuldq.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pmuldq_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM0)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 200], OperandSize::Dword)
}
#[test]
fn pmuldq_2() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(EDI, 1659796394, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 191, 170, 123, 238, 98], OperandSize::Dword)
}
#[test]
fn pmuldq_3()
|
#[test]
fn pmuldq_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM5)), operand2: Some(Indirect(RSI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 46], OperandSize::Qword)
}
|
{
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 206], OperandSize::Qword)
}
|
identifier_body
|
instr_pmuldq.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn
|
() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM0)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 200], OperandSize::Dword)
}
#[test]
fn pmuldq_2() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(EDI, 1659796394, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 191, 170, 123, 238, 98], OperandSize::Dword)
}
#[test]
fn pmuldq_3() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 206], OperandSize::Qword)
}
#[test]
fn pmuldq_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM5)), operand2: Some(Indirect(RSI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 46], OperandSize::Qword)
}
|
pmuldq_1
|
identifier_name
|
instr_pmuldq.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn pmuldq_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM0)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 200], OperandSize::Dword)
}
#[test]
fn pmuldq_2() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(EDI, 1659796394, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 191, 170, 123, 238, 98], OperandSize::Dword)
}
|
}
#[test]
fn pmuldq_4() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM5)), operand2: Some(Indirect(RSI, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 46], OperandSize::Qword)
}
|
#[test]
fn pmuldq_3() {
run_test(&Instruction { mnemonic: Mnemonic::PMULDQ, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 40, 206], OperandSize::Qword)
|
random_line_split
|
rc.rs
|
//! A reference-counted wrapper sharing one owned trace.
//!
//! The types in this module, `TraceBox` and `TraceRc` and meant to parallel `RcBox` and `Rc` in `std::rc`.
//!
//! The first typee is an owned trace with some information about the cumulative requirements of the shared
//! handles. This is roughly how much progress has each made, so we know which "read capabilities" they have
//! collectively dropped, and when it is safe to inform the trace of such progress.
//!
//! The second type is a wrapper which presents as a `TraceReader`, but whose methods for advancing its read
//! capabilities interact with the `TraceBox` rather than directly with the owned trace. Ideally, instances
//! `TraceRc` should appear indistinguishable from the underlying trace from a reading perspective, with the
//! exception that the trace may not compact its representation as fast as if it were exclusively owned.
use std::rc::Rc;
use std::cell::RefCell;
use timely::progress::frontier::MutableAntichain;
use lattice::Lattice;
use trace::TraceReader;
use trace::cursor::Cursor;
/// A wrapper around a trace which tracks the frontiers of all referees.
///
/// This is an internal type, unlikely to be useful to higher-level programs, but exposed just in case.
/// This type is equivalent to a `RefCell`, in that it wraps the mutable state that multiple referrers
/// may influence.
pub struct TraceBox<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader
{
/// accumulated holds on times for advancement.
pub advance_frontiers: MutableAntichain<Tr::Time>,
/// accumulated holds on times for distinction.
pub through_frontiers: MutableAntichain<Tr::Time>,
/// The wrapped trace.
pub trace: Tr,
}
impl<Tr> TraceBox<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Moves an existing trace into a shareable trace wrapper.
///
/// The trace may already exist and have non-initial advance and distinguish frontiers. The boxing
/// process will fish these out and make sure that they are used for the initial read capabilities.
pub fn new(mut trace: Tr) -> Self {
let mut advance = MutableAntichain::new();
advance.update_iter(trace.advance_frontier().iter().cloned().map(|t| (t,1)));
// for time in trace.advance_frontier() {
// advance.update(time, 1);
// }
let mut through = MutableAntichain::new();
through.update_iter(trace.distinguish_frontier().iter().cloned().map(|t| (t,1)));
// for time in trace.distinguish_frontier() {
// through.update(time, 1);
// }
TraceBox {
advance_frontiers: advance,
through_frontiers: through,
trace: trace,
}
}
/// Replaces elements of `lower` with those of `upper`.
pub fn adjust_advance_frontier(&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.advance_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.advance_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.advance_frontiers.update_and(element, 1, |_,_| {}); }
// for element in lower { self.advance_frontiers.update_and(element, -1, |_,_| {}); }
self.trace.advance_by(&self.advance_frontiers.frontier());
}
/// Replaces elements of `lower` with those of `upper`.
pub fn adjust_through_frontier(&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.through_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.through_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.through_frontiers.update_and(element, 1, |_,_| {}); }
// for element in lower { self.through_frontiers.update_and(element, -1, |_,_| {}); }
self.trace.distinguish_since(&self.through_frontiers.frontier());
}
}
/// A handle to a shared trace.
///
/// As long as the handle exists, the wrapped trace should continue to exist and will not advance its
/// timestamps past the frontier maintained by the handle. The intent is that such a handle appears as
/// if it is a privately maintained trace, despite being backed by shared resources.
pub struct TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
advance_frontier: Vec<Tr::Time>,
through_frontier: Vec<Tr::Time>,
/// Wrapped trace. Please be gentle when using.
pub wrapper: Rc<RefCell<TraceBox<Tr>>>,
}
impl<Tr> TraceReader for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
type Key = Tr::Key;
type Val = Tr::Val;
type Time = Tr::Time;
type R = Tr::R;
type Batch = Tr::Batch;
type Cursor = Tr::Cursor;
/// Sets frontier to now be elements in `frontier`.
///
/// This change may not have immediately observable effects. It informs the shared trace that this
/// handle no longer requires access to times other than those in the future of `frontier`, but if
/// there are other handles to the same trace, it may not yet be able to compact.
fn advance_by(&mut self, frontier: &[Tr::Time]) {
self.wrapper.borrow_mut().adjust_advance_frontier(&self.advance_frontier[..], frontier);
self.advance_frontier = frontier.to_vec();
}
fn advance_frontier(&mut self) -> &[Tr::Time] { &self.advance_frontier[..] }
/// Allows the trace to compact batches of times before `frontier`.
fn distinguish_since(&mut self, frontier: &[Tr::Time])
|
fn distinguish_frontier(&mut self) -> &[Tr::Time] { &self.through_frontier[..] }
/// Creates a new cursor over the wrapped trace.
fn cursor_through(&mut self, frontier: &[Tr::Time]) -> Option<(Tr::Cursor, <Tr::Cursor as Cursor<Tr::Key, Tr::Val, Tr::Time, Tr::R>>::Storage)> {
::std::cell::RefCell::borrow_mut(&self.wrapper).trace.cursor_through(frontier)
}
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
::std::cell::RefCell::borrow_mut(&self.wrapper).trace.map_batches(f)
}
}
impl<Tr> TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Allocates a new handle from an existing wrapped wrapper.
pub fn make_from(trace: Tr) -> (Self, Rc<RefCell<TraceBox<Tr>>>) {
let wrapped = Rc::new(RefCell::new(TraceBox::new(trace)));
let handle = TraceRc {
advance_frontier: wrapped.borrow().advance_frontiers.frontier().to_vec(),
through_frontier: wrapped.borrow().through_frontiers.frontier().to_vec(),
wrapper: wrapped.clone(),
};
(handle, wrapped)
}
}
impl<Tr> Clone for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone,
Tr: TraceReader,
{
fn clone(&self) -> Self {
// increase ref counts for this frontier
self.wrapper.borrow_mut().adjust_advance_frontier(&[], &self.advance_frontier[..]);
self.wrapper.borrow_mut().adjust_through_frontier(&[], &self.through_frontier[..]);
TraceRc {
advance_frontier: self.advance_frontier.clone(),
through_frontier: self.through_frontier.clone(),
wrapper: self.wrapper.clone(),
}
}
}
impl<Tr> Drop for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
fn drop(&mut self) {
self.wrapper.borrow_mut().adjust_advance_frontier(&self.advance_frontier[..], &[]);
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], &[]);
self.advance_frontier = Vec::new();
self.through_frontier = Vec::new();
}
}
|
{
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], frontier);
self.through_frontier = frontier.to_vec();
}
|
identifier_body
|
rc.rs
|
//! A reference-counted wrapper sharing one owned trace.
//!
//! The types in this module, `TraceBox` and `TraceRc` and meant to parallel `RcBox` and `Rc` in `std::rc`.
//!
//! The first typee is an owned trace with some information about the cumulative requirements of the shared
//! handles. This is roughly how much progress has each made, so we know which "read capabilities" they have
//! collectively dropped, and when it is safe to inform the trace of such progress.
//!
//! The second type is a wrapper which presents as a `TraceReader`, but whose methods for advancing its read
//! capabilities interact with the `TraceBox` rather than directly with the owned trace. Ideally, instances
//! `TraceRc` should appear indistinguishable from the underlying trace from a reading perspective, with the
//! exception that the trace may not compact its representation as fast as if it were exclusively owned.
use std::rc::Rc;
use std::cell::RefCell;
use timely::progress::frontier::MutableAntichain;
use lattice::Lattice;
use trace::TraceReader;
use trace::cursor::Cursor;
/// A wrapper around a trace which tracks the frontiers of all referees.
///
/// This is an internal type, unlikely to be useful to higher-level programs, but exposed just in case.
/// This type is equivalent to a `RefCell`, in that it wraps the mutable state that multiple referrers
/// may influence.
pub struct TraceBox<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader
{
/// accumulated holds on times for advancement.
pub advance_frontiers: MutableAntichain<Tr::Time>,
/// accumulated holds on times for distinction.
pub through_frontiers: MutableAntichain<Tr::Time>,
/// The wrapped trace.
pub trace: Tr,
}
impl<Tr> TraceBox<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Moves an existing trace into a shareable trace wrapper.
///
/// The trace may already exist and have non-initial advance and distinguish frontiers. The boxing
/// process will fish these out and make sure that they are used for the initial read capabilities.
pub fn new(mut trace: Tr) -> Self {
let mut advance = MutableAntichain::new();
advance.update_iter(trace.advance_frontier().iter().cloned().map(|t| (t,1)));
// for time in trace.advance_frontier() {
// advance.update(time, 1);
// }
let mut through = MutableAntichain::new();
through.update_iter(trace.distinguish_frontier().iter().cloned().map(|t| (t,1)));
// for time in trace.distinguish_frontier() {
// through.update(time, 1);
// }
TraceBox {
advance_frontiers: advance,
through_frontiers: through,
trace: trace,
}
}
/// Replaces elements of `lower` with those of `upper`.
pub fn adjust_advance_frontier(&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.advance_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.advance_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.advance_frontiers.update_and(element, 1, |_,_| {}); }
// for element in lower { self.advance_frontiers.update_and(element, -1, |_,_| {}); }
self.trace.advance_by(&self.advance_frontiers.frontier());
}
/// Replaces elements of `lower` with those of `upper`.
pub fn adjust_through_frontier(&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.through_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.through_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.through_frontiers.update_and(element, 1, |_,_| {}); }
// for element in lower { self.through_frontiers.update_and(element, -1, |_,_| {}); }
self.trace.distinguish_since(&self.through_frontiers.frontier());
}
}
/// A handle to a shared trace.
///
/// As long as the handle exists, the wrapped trace should continue to exist and will not advance its
/// timestamps past the frontier maintained by the handle. The intent is that such a handle appears as
/// if it is a privately maintained trace, despite being backed by shared resources.
pub struct TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
advance_frontier: Vec<Tr::Time>,
through_frontier: Vec<Tr::Time>,
/// Wrapped trace. Please be gentle when using.
pub wrapper: Rc<RefCell<TraceBox<Tr>>>,
}
impl<Tr> TraceReader for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
type Key = Tr::Key;
type Val = Tr::Val;
type Time = Tr::Time;
type R = Tr::R;
type Batch = Tr::Batch;
type Cursor = Tr::Cursor;
/// Sets frontier to now be elements in `frontier`.
///
/// This change may not have immediately observable effects. It informs the shared trace that this
/// handle no longer requires access to times other than those in the future of `frontier`, but if
/// there are other handles to the same trace, it may not yet be able to compact.
fn advance_by(&mut self, frontier: &[Tr::Time]) {
self.wrapper.borrow_mut().adjust_advance_frontier(&self.advance_frontier[..], frontier);
self.advance_frontier = frontier.to_vec();
}
fn advance_frontier(&mut self) -> &[Tr::Time] { &self.advance_frontier[..] }
/// Allows the trace to compact batches of times before `frontier`.
fn distinguish_since(&mut self, frontier: &[Tr::Time]) {
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], frontier);
self.through_frontier = frontier.to_vec();
}
fn distinguish_frontier(&mut self) -> &[Tr::Time] { &self.through_frontier[..] }
/// Creates a new cursor over the wrapped trace.
fn cursor_through(&mut self, frontier: &[Tr::Time]) -> Option<(Tr::Cursor, <Tr::Cursor as Cursor<Tr::Key, Tr::Val, Tr::Time, Tr::R>>::Storage)> {
::std::cell::RefCell::borrow_mut(&self.wrapper).trace.cursor_through(frontier)
}
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
|
}
impl<Tr> TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Allocates a new handle from an existing wrapped wrapper.
pub fn make_from(trace: Tr) -> (Self, Rc<RefCell<TraceBox<Tr>>>) {
let wrapped = Rc::new(RefCell::new(TraceBox::new(trace)));
let handle = TraceRc {
advance_frontier: wrapped.borrow().advance_frontiers.frontier().to_vec(),
through_frontier: wrapped.borrow().through_frontiers.frontier().to_vec(),
wrapper: wrapped.clone(),
};
(handle, wrapped)
}
}
impl<Tr> Clone for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone,
Tr: TraceReader,
{
fn clone(&self) -> Self {
// increase ref counts for this frontier
self.wrapper.borrow_mut().adjust_advance_frontier(&[], &self.advance_frontier[..]);
self.wrapper.borrow_mut().adjust_through_frontier(&[], &self.through_frontier[..]);
TraceRc {
advance_frontier: self.advance_frontier.clone(),
through_frontier: self.through_frontier.clone(),
wrapper: self.wrapper.clone(),
}
}
}
impl<Tr> Drop for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
fn drop(&mut self) {
self.wrapper.borrow_mut().adjust_advance_frontier(&self.advance_frontier[..], &[]);
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], &[]);
self.advance_frontier = Vec::new();
self.through_frontier = Vec::new();
}
}
|
::std::cell::RefCell::borrow_mut(&self.wrapper).trace.map_batches(f)
}
|
random_line_split
|
rc.rs
|
//! A reference-counted wrapper sharing one owned trace.
//!
//! The types in this module, `TraceBox` and `TraceRc` and meant to parallel `RcBox` and `Rc` in `std::rc`.
//!
//! The first typee is an owned trace with some information about the cumulative requirements of the shared
//! handles. This is roughly how much progress has each made, so we know which "read capabilities" they have
//! collectively dropped, and when it is safe to inform the trace of such progress.
//!
//! The second type is a wrapper which presents as a `TraceReader`, but whose methods for advancing its read
//! capabilities interact with the `TraceBox` rather than directly with the owned trace. Ideally, instances
//! `TraceRc` should appear indistinguishable from the underlying trace from a reading perspective, with the
//! exception that the trace may not compact its representation as fast as if it were exclusively owned.
use std::rc::Rc;
use std::cell::RefCell;
use timely::progress::frontier::MutableAntichain;
use lattice::Lattice;
use trace::TraceReader;
use trace::cursor::Cursor;
/// A wrapper around a trace which tracks the frontiers of all referees.
///
/// This is an internal type, unlikely to be useful to higher-level programs, but exposed just in case.
/// This type is equivalent to a `RefCell`, in that it wraps the mutable state that multiple referrers
/// may influence.
pub struct TraceBox<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader
{
/// accumulated holds on times for advancement.
pub advance_frontiers: MutableAntichain<Tr::Time>,
/// accumulated holds on times for distinction.
pub through_frontiers: MutableAntichain<Tr::Time>,
/// The wrapped trace.
pub trace: Tr,
}
impl<Tr> TraceBox<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Moves an existing trace into a shareable trace wrapper.
///
/// The trace may already exist and have non-initial advance and distinguish frontiers. The boxing
/// process will fish these out and make sure that they are used for the initial read capabilities.
pub fn new(mut trace: Tr) -> Self {
let mut advance = MutableAntichain::new();
advance.update_iter(trace.advance_frontier().iter().cloned().map(|t| (t,1)));
// for time in trace.advance_frontier() {
// advance.update(time, 1);
// }
let mut through = MutableAntichain::new();
through.update_iter(trace.distinguish_frontier().iter().cloned().map(|t| (t,1)));
// for time in trace.distinguish_frontier() {
// through.update(time, 1);
// }
TraceBox {
advance_frontiers: advance,
through_frontiers: through,
trace: trace,
}
}
/// Replaces elements of `lower` with those of `upper`.
pub fn adjust_advance_frontier(&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.advance_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.advance_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.advance_frontiers.update_and(element, 1, |_,_| {}); }
// for element in lower { self.advance_frontiers.update_and(element, -1, |_,_| {}); }
self.trace.advance_by(&self.advance_frontiers.frontier());
}
/// Replaces elements of `lower` with those of `upper`.
pub fn
|
(&mut self, lower: &[Tr::Time], upper: &[Tr::Time]) {
self.through_frontiers.update_iter(upper.iter().cloned().map(|t| (t,1)));
self.through_frontiers.update_iter(lower.iter().cloned().map(|t| (t,-1)));
// for element in upper { self.through_frontiers.update_and(element, 1, |_,_| {}); }
// for element in lower { self.through_frontiers.update_and(element, -1, |_,_| {}); }
self.trace.distinguish_since(&self.through_frontiers.frontier());
}
}
/// A handle to a shared trace.
///
/// As long as the handle exists, the wrapped trace should continue to exist and will not advance its
/// timestamps past the frontier maintained by the handle. The intent is that such a handle appears as
/// if it is a privately maintained trace, despite being backed by shared resources.
pub struct TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
advance_frontier: Vec<Tr::Time>,
through_frontier: Vec<Tr::Time>,
/// Wrapped trace. Please be gentle when using.
pub wrapper: Rc<RefCell<TraceBox<Tr>>>,
}
impl<Tr> TraceReader for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
type Key = Tr::Key;
type Val = Tr::Val;
type Time = Tr::Time;
type R = Tr::R;
type Batch = Tr::Batch;
type Cursor = Tr::Cursor;
/// Sets frontier to now be elements in `frontier`.
///
/// This change may not have immediately observable effects. It informs the shared trace that this
/// handle no longer requires access to times other than those in the future of `frontier`, but if
/// there are other handles to the same trace, it may not yet be able to compact.
fn advance_by(&mut self, frontier: &[Tr::Time]) {
self.wrapper.borrow_mut().adjust_advance_frontier(&self.advance_frontier[..], frontier);
self.advance_frontier = frontier.to_vec();
}
fn advance_frontier(&mut self) -> &[Tr::Time] { &self.advance_frontier[..] }
/// Allows the trace to compact batches of times before `frontier`.
fn distinguish_since(&mut self, frontier: &[Tr::Time]) {
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], frontier);
self.through_frontier = frontier.to_vec();
}
fn distinguish_frontier(&mut self) -> &[Tr::Time] { &self.through_frontier[..] }
/// Creates a new cursor over the wrapped trace.
fn cursor_through(&mut self, frontier: &[Tr::Time]) -> Option<(Tr::Cursor, <Tr::Cursor as Cursor<Tr::Key, Tr::Val, Tr::Time, Tr::R>>::Storage)> {
::std::cell::RefCell::borrow_mut(&self.wrapper).trace.cursor_through(frontier)
}
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
::std::cell::RefCell::borrow_mut(&self.wrapper).trace.map_batches(f)
}
}
impl<Tr> TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
/// Allocates a new handle from an existing wrapped wrapper.
pub fn make_from(trace: Tr) -> (Self, Rc<RefCell<TraceBox<Tr>>>) {
let wrapped = Rc::new(RefCell::new(TraceBox::new(trace)));
let handle = TraceRc {
advance_frontier: wrapped.borrow().advance_frontiers.frontier().to_vec(),
through_frontier: wrapped.borrow().through_frontiers.frontier().to_vec(),
wrapper: wrapped.clone(),
};
(handle, wrapped)
}
}
impl<Tr> Clone for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone,
Tr: TraceReader,
{
fn clone(&self) -> Self {
// increase ref counts for this frontier
self.wrapper.borrow_mut().adjust_advance_frontier(&[], &self.advance_frontier[..]);
self.wrapper.borrow_mut().adjust_through_frontier(&[], &self.through_frontier[..]);
TraceRc {
advance_frontier: self.advance_frontier.clone(),
through_frontier: self.through_frontier.clone(),
wrapper: self.wrapper.clone(),
}
}
}
impl<Tr> Drop for TraceRc<Tr>
where
Tr::Time: Lattice+Ord+Clone+'static,
Tr: TraceReader,
{
fn drop(&mut self) {
self.wrapper.borrow_mut().adjust_advance_frontier(&self.advance_frontier[..], &[]);
self.wrapper.borrow_mut().adjust_through_frontier(&self.through_frontier[..], &[]);
self.advance_frontier = Vec::new();
self.through_frontier = Vec::new();
}
}
|
adjust_through_frontier
|
identifier_name
|
error.rs
|
use std::error::Error;
use std::fmt;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use std::str::Utf8Error;
#[derive(Debug)]
pub enum OperationError {
OverflowError,
NotANumberError,
ValueError(String),
UnknownKeyError,
WrongTypeError,
OutOfBoundsError,
IOError(io::Error),
|
impl OperationError {
fn message(&self) -> &str {
match self {
OperationError::WrongTypeError => {
"WRONGTYPE Operation against a key holding the wrong kind of value"
}
OperationError::NotANumberError => "ERR resulting score is not a number (NaN)",
OperationError::ValueError(s) => s,
_ => "ERR",
}
}
}
impl fmt::Display for OperationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.message().fmt(f)
}
}
impl Error for OperationError {
fn description(&self) -> &str {
self.message()
}
}
impl From<Utf8Error> for OperationError {
fn from(_: Utf8Error) -> OperationError {
OperationError::ValueError("ERR value is not a string".to_owned())
}
}
impl From<ParseIntError> for OperationError {
fn from(_: ParseIntError) -> OperationError {
OperationError::ValueError("ERR value is not a integer".to_owned())
}
}
impl From<ParseFloatError> for OperationError {
fn from(_: ParseFloatError) -> OperationError {
OperationError::ValueError("ERR value is not a float".to_owned())
}
}
impl From<io::Error> for OperationError {
fn from(e: io::Error) -> OperationError {
OperationError::IOError(e)
}
}
|
}
|
random_line_split
|
error.rs
|
use std::error::Error;
use std::fmt;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use std::str::Utf8Error;
#[derive(Debug)]
pub enum OperationError {
OverflowError,
NotANumberError,
ValueError(String),
UnknownKeyError,
WrongTypeError,
OutOfBoundsError,
IOError(io::Error),
}
impl OperationError {
fn message(&self) -> &str {
match self {
OperationError::WrongTypeError => {
"WRONGTYPE Operation against a key holding the wrong kind of value"
}
OperationError::NotANumberError => "ERR resulting score is not a number (NaN)",
OperationError::ValueError(s) => s,
_ => "ERR",
}
}
}
impl fmt::Display for OperationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.message().fmt(f)
}
}
impl Error for OperationError {
fn
|
(&self) -> &str {
self.message()
}
}
impl From<Utf8Error> for OperationError {
fn from(_: Utf8Error) -> OperationError {
OperationError::ValueError("ERR value is not a string".to_owned())
}
}
impl From<ParseIntError> for OperationError {
fn from(_: ParseIntError) -> OperationError {
OperationError::ValueError("ERR value is not a integer".to_owned())
}
}
impl From<ParseFloatError> for OperationError {
fn from(_: ParseFloatError) -> OperationError {
OperationError::ValueError("ERR value is not a float".to_owned())
}
}
impl From<io::Error> for OperationError {
fn from(e: io::Error) -> OperationError {
OperationError::IOError(e)
}
}
|
description
|
identifier_name
|
error.rs
|
use std::error::Error;
use std::fmt;
use std::io;
use std::num::{ParseFloatError, ParseIntError};
use std::str::Utf8Error;
#[derive(Debug)]
pub enum OperationError {
OverflowError,
NotANumberError,
ValueError(String),
UnknownKeyError,
WrongTypeError,
OutOfBoundsError,
IOError(io::Error),
}
impl OperationError {
fn message(&self) -> &str {
match self {
OperationError::WrongTypeError => {
"WRONGTYPE Operation against a key holding the wrong kind of value"
}
OperationError::NotANumberError => "ERR resulting score is not a number (NaN)",
OperationError::ValueError(s) => s,
_ => "ERR",
}
}
}
impl fmt::Display for OperationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.message().fmt(f)
}
}
impl Error for OperationError {
fn description(&self) -> &str {
self.message()
}
}
impl From<Utf8Error> for OperationError {
fn from(_: Utf8Error) -> OperationError {
OperationError::ValueError("ERR value is not a string".to_owned())
}
}
impl From<ParseIntError> for OperationError {
fn from(_: ParseIntError) -> OperationError {
OperationError::ValueError("ERR value is not a integer".to_owned())
}
}
impl From<ParseFloatError> for OperationError {
fn from(_: ParseFloatError) -> OperationError {
OperationError::ValueError("ERR value is not a float".to_owned())
}
}
impl From<io::Error> for OperationError {
fn from(e: io::Error) -> OperationError
|
}
|
{
OperationError::IOError(e)
}
|
identifier_body
|
poll_immediate.rs
|
use super::assert_future;
use core::pin::Pin;
use futures_core::task::{Context, Poll};
use futures_core::{FusedFuture, Future, Stream};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`poll_immediate`](poll_immediate()) function.
///
/// It will never return [Poll::Pending](core::task::Poll::Pending)
#[derive(Debug, Clone)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PollImmediate<T> {
#[pin]
future: Option<T>
}
}
impl<T, F> Future for PollImmediate<F>
where
F: Future<Output = T>,
{
type Output = Option<T>;
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
let mut this = self.project();
let inner =
this.future.as_mut().as_pin_mut().expect("PollImmediate polled after completion");
match inner.poll(cx) {
Poll::Ready(t) => {
this.future.set(None);
Poll::Ready(Some(t))
}
Poll::Pending => Poll::Ready(None),
}
}
}
impl<T: Future> FusedFuture for PollImmediate<T> {
fn is_terminated(&self) -> bool {
self.future.is_none()
}
}
/// A [Stream](crate::stream::Stream) implementation that can be polled repeatedly until the future is done.
/// The stream will never return [Poll::Pending](core::task::Poll::Pending)
/// so polling it in a tight loop is worse than using a blocking synchronous function.
/// ```
/// # futures::executor::block_on(async {
/// use futures::task::Poll;
/// use futures::{StreamExt, future, pin_mut};
/// use future::FusedFuture;
///
/// let f = async { 1_u32 };
/// pin_mut!(f);
/// let mut r = future::poll_immediate(f);
/// assert_eq!(r.next().await, Some(Poll::Ready(1)));
///
/// let f = async {futures::pending!(); 42_u8};
/// pin_mut!(f);
/// let mut p = future::poll_immediate(f);
/// assert_eq!(p.next().await, Some(Poll::Pending));
/// assert!(!p.is_terminated());
/// assert_eq!(p.next().await, Some(Poll::Ready(42)));
/// assert!(p.is_terminated());
/// assert_eq!(p.next().await, None);
/// # });
/// ```
impl<T, F> Stream for PollImmediate<F>
where
F: Future<Output = T>,
{
type Item = Poll<T>;
fn
|
(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
match this.future.as_mut().as_pin_mut() {
// inner is gone, so we can signal that the stream is closed.
None => Poll::Ready(None),
Some(fut) => Poll::Ready(Some(fut.poll(cx).map(|t| {
this.future.set(None);
t
}))),
}
}
}
/// Creates a future that is immediately ready with an Option of a value.
/// Specifically this means that [poll](core::future::Future::poll()) always returns [Poll::Ready](core::task::Poll::Ready).
///
/// # Caution
///
/// When consuming the future by this function, note the following:
///
/// - This function does not guarantee that the future will run to completion, so it is generally incompatible with passing the non-cancellation-safe future by value.
/// - Even if the future is cancellation-safe, creating and dropping new futures frequently may lead to performance problems.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::future;
///
/// let r = future::poll_immediate(async { 1_u32 });
/// assert_eq!(r.await, Some(1));
///
/// let p = future::poll_immediate(future::pending::<i32>());
/// assert_eq!(p.await, None);
/// # });
/// ```
///
/// ### Reusing a future
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::{future, pin_mut};
/// let f = async {futures::pending!(); 42_u8};
/// pin_mut!(f);
/// assert_eq!(None, future::poll_immediate(&mut f).await);
/// assert_eq!(42, f.await);
/// # });
/// ```
pub fn poll_immediate<F: Future>(f: F) -> PollImmediate<F> {
assert_future::<Option<F::Output>, PollImmediate<F>>(PollImmediate { future: Some(f) })
}
|
poll_next
|
identifier_name
|
poll_immediate.rs
|
use super::assert_future;
use core::pin::Pin;
use futures_core::task::{Context, Poll};
use futures_core::{FusedFuture, Future, Stream};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`poll_immediate`](poll_immediate()) function.
///
/// It will never return [Poll::Pending](core::task::Poll::Pending)
#[derive(Debug, Clone)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PollImmediate<T> {
#[pin]
future: Option<T>
}
}
impl<T, F> Future for PollImmediate<F>
where
F: Future<Output = T>,
{
type Output = Option<T>;
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
let mut this = self.project();
let inner =
this.future.as_mut().as_pin_mut().expect("PollImmediate polled after completion");
match inner.poll(cx) {
Poll::Ready(t) => {
this.future.set(None);
Poll::Ready(Some(t))
}
Poll::Pending => Poll::Ready(None),
}
}
|
impl<T: Future> FusedFuture for PollImmediate<T> {
fn is_terminated(&self) -> bool {
self.future.is_none()
}
}
/// A [Stream](crate::stream::Stream) implementation that can be polled repeatedly until the future is done.
/// The stream will never return [Poll::Pending](core::task::Poll::Pending)
/// so polling it in a tight loop is worse than using a blocking synchronous function.
/// ```
/// # futures::executor::block_on(async {
/// use futures::task::Poll;
/// use futures::{StreamExt, future, pin_mut};
/// use future::FusedFuture;
///
/// let f = async { 1_u32 };
/// pin_mut!(f);
/// let mut r = future::poll_immediate(f);
/// assert_eq!(r.next().await, Some(Poll::Ready(1)));
///
/// let f = async {futures::pending!(); 42_u8};
/// pin_mut!(f);
/// let mut p = future::poll_immediate(f);
/// assert_eq!(p.next().await, Some(Poll::Pending));
/// assert!(!p.is_terminated());
/// assert_eq!(p.next().await, Some(Poll::Ready(42)));
/// assert!(p.is_terminated());
/// assert_eq!(p.next().await, None);
/// # });
/// ```
impl<T, F> Stream for PollImmediate<F>
where
F: Future<Output = T>,
{
type Item = Poll<T>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
match this.future.as_mut().as_pin_mut() {
// inner is gone, so we can signal that the stream is closed.
None => Poll::Ready(None),
Some(fut) => Poll::Ready(Some(fut.poll(cx).map(|t| {
this.future.set(None);
t
}))),
}
}
}
/// Creates a future that is immediately ready with an Option of a value.
/// Specifically this means that [poll](core::future::Future::poll()) always returns [Poll::Ready](core::task::Poll::Ready).
///
/// # Caution
///
/// When consuming the future by this function, note the following:
///
/// - This function does not guarantee that the future will run to completion, so it is generally incompatible with passing the non-cancellation-safe future by value.
/// - Even if the future is cancellation-safe, creating and dropping new futures frequently may lead to performance problems.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::future;
///
/// let r = future::poll_immediate(async { 1_u32 });
/// assert_eq!(r.await, Some(1));
///
/// let p = future::poll_immediate(future::pending::<i32>());
/// assert_eq!(p.await, None);
/// # });
/// ```
///
/// ### Reusing a future
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::{future, pin_mut};
/// let f = async {futures::pending!(); 42_u8};
/// pin_mut!(f);
/// assert_eq!(None, future::poll_immediate(&mut f).await);
/// assert_eq!(42, f.await);
/// # });
/// ```
pub fn poll_immediate<F: Future>(f: F) -> PollImmediate<F> {
assert_future::<Option<F::Output>, PollImmediate<F>>(PollImmediate { future: Some(f) })
}
|
}
|
random_line_split
|
poll_immediate.rs
|
use super::assert_future;
use core::pin::Pin;
use futures_core::task::{Context, Poll};
use futures_core::{FusedFuture, Future, Stream};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`poll_immediate`](poll_immediate()) function.
///
/// It will never return [Poll::Pending](core::task::Poll::Pending)
#[derive(Debug, Clone)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PollImmediate<T> {
#[pin]
future: Option<T>
}
}
impl<T, F> Future for PollImmediate<F>
where
F: Future<Output = T>,
{
type Output = Option<T>;
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
let mut this = self.project();
let inner =
this.future.as_mut().as_pin_mut().expect("PollImmediate polled after completion");
match inner.poll(cx) {
Poll::Ready(t) => {
this.future.set(None);
Poll::Ready(Some(t))
}
Poll::Pending => Poll::Ready(None),
}
}
}
impl<T: Future> FusedFuture for PollImmediate<T> {
fn is_terminated(&self) -> bool {
self.future.is_none()
}
}
/// A [Stream](crate::stream::Stream) implementation that can be polled repeatedly until the future is done.
/// The stream will never return [Poll::Pending](core::task::Poll::Pending)
/// so polling it in a tight loop is worse than using a blocking synchronous function.
/// ```
/// # futures::executor::block_on(async {
/// use futures::task::Poll;
/// use futures::{StreamExt, future, pin_mut};
/// use future::FusedFuture;
///
/// let f = async { 1_u32 };
/// pin_mut!(f);
/// let mut r = future::poll_immediate(f);
/// assert_eq!(r.next().await, Some(Poll::Ready(1)));
///
/// let f = async {futures::pending!(); 42_u8};
/// pin_mut!(f);
/// let mut p = future::poll_immediate(f);
/// assert_eq!(p.next().await, Some(Poll::Pending));
/// assert!(!p.is_terminated());
/// assert_eq!(p.next().await, Some(Poll::Ready(42)));
/// assert!(p.is_terminated());
/// assert_eq!(p.next().await, None);
/// # });
/// ```
impl<T, F> Stream for PollImmediate<F>
where
F: Future<Output = T>,
{
type Item = Poll<T>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
|
}
/// Creates a future that is immediately ready with an Option of a value.
/// Specifically this means that [poll](core::future::Future::poll()) always returns [Poll::Ready](core::task::Poll::Ready).
///
/// # Caution
///
/// When consuming the future by this function, note the following:
///
/// - This function does not guarantee that the future will run to completion, so it is generally incompatible with passing the non-cancellation-safe future by value.
/// - Even if the future is cancellation-safe, creating and dropping new futures frequently may lead to performance problems.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::future;
///
/// let r = future::poll_immediate(async { 1_u32 });
/// assert_eq!(r.await, Some(1));
///
/// let p = future::poll_immediate(future::pending::<i32>());
/// assert_eq!(p.await, None);
/// # });
/// ```
///
/// ### Reusing a future
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::{future, pin_mut};
/// let f = async {futures::pending!(); 42_u8};
/// pin_mut!(f);
/// assert_eq!(None, future::poll_immediate(&mut f).await);
/// assert_eq!(42, f.await);
/// # });
/// ```
pub fn poll_immediate<F: Future>(f: F) -> PollImmediate<F> {
assert_future::<Option<F::Output>, PollImmediate<F>>(PollImmediate { future: Some(f) })
}
|
{
let mut this = self.project();
match this.future.as_mut().as_pin_mut() {
// inner is gone, so we can signal that the stream is closed.
None => Poll::Ready(None),
Some(fut) => Poll::Ready(Some(fut.poll(cx).map(|t| {
this.future.set(None);
t
}))),
}
}
|
identifier_body
|
query.rs
|
use crate::namespace::*;
use crate::sparql::pattern::Pattern;
use crate::uri::Uri;
use crate::Result;
/// Query type.
#[derive(Clone, Debug)]
pub enum SparqlQueryType {
Ask,
Select,
SelectDistinct,
SelectReduced,
SelectAll,
SelectAllDistinct,
SelectAllReduced,
Construct,
Describe,
}
/// Represents a SPARQL query that can be applied to an RDF graph.
/// `SparqlQuery`s are created when parsing a SPARQL string using `SparqlParser`.
pub struct SparqlQuery {
/// SPARQL query type.
query_type: SparqlQueryType,
/// Base URI denoted in SPARQL query.
base_uri: Option<Uri>,
|
// Variables used in the query.
variables: Vec<String>,
// Patterns used as constraints.
patterns: Vec<Box<Pattern>>,
}
impl SparqlQuery {
/// Constructor of `SparqlQuery`.
pub fn new(query_type: SparqlQueryType) -> SparqlQuery {
SparqlQuery {
query_type: query_type,
base_uri: None,
variables: Vec::new(),
patterns: Vec::new(),
namespaces: NamespaceStore::new(),
}
}
/// Add variables to the query.
/// Ordering in vector reflects position the variables appear.
pub fn add_variables(&mut self, variables: Vec<String>) {
self.variables = variables;
}
/// Add pattern to the query.
pub fn add_pattern(&mut self, pattern: Box<Pattern>) {
self.patterns.push(pattern);
}
/// Returns the type of the SPARQL query.
///
/// todo
///
pub fn get_query_type(&self) -> &SparqlQueryType {
&self.query_type
}
/// Get query variables.
///
/// todo
///
pub fn get_query_variables(&self) -> &Vec<String> {
&self.variables
}
/// Get the query patterns in the `WHERE` expression.
///
/// todo
///
// pub fn get_query_patterns(&self) -> &Vec<Pattern> {
// &self.patterns
// }
/// Returns the URI of a namespace with the provided prefix.
///
/// # Examples
///
/// todo
///
/// # Failures
///
/// - No namespace with the provided prefix exists
///
pub fn get_namespace_uri_by_prefix(&self, prefix: String) -> Result<&Uri> {
self.namespaces.get_uri_by_prefix(&prefix)
}
}
|
/// Namespaces stated in SPARQL query.
namespaces: NamespaceStore,
|
random_line_split
|
query.rs
|
use crate::namespace::*;
use crate::sparql::pattern::Pattern;
use crate::uri::Uri;
use crate::Result;
/// Query type.
#[derive(Clone, Debug)]
pub enum SparqlQueryType {
Ask,
Select,
SelectDistinct,
SelectReduced,
SelectAll,
SelectAllDistinct,
SelectAllReduced,
Construct,
Describe,
}
/// Represents a SPARQL query that can be applied to an RDF graph.
/// `SparqlQuery`s are created when parsing a SPARQL string using `SparqlParser`.
pub struct SparqlQuery {
/// SPARQL query type.
query_type: SparqlQueryType,
/// Base URI denoted in SPARQL query.
base_uri: Option<Uri>,
/// Namespaces stated in SPARQL query.
namespaces: NamespaceStore,
// Variables used in the query.
variables: Vec<String>,
// Patterns used as constraints.
patterns: Vec<Box<Pattern>>,
}
impl SparqlQuery {
/// Constructor of `SparqlQuery`.
pub fn new(query_type: SparqlQueryType) -> SparqlQuery {
SparqlQuery {
query_type: query_type,
base_uri: None,
variables: Vec::new(),
patterns: Vec::new(),
namespaces: NamespaceStore::new(),
}
}
/// Add variables to the query.
/// Ordering in vector reflects position the variables appear.
pub fn add_variables(&mut self, variables: Vec<String>) {
self.variables = variables;
}
/// Add pattern to the query.
pub fn add_pattern(&mut self, pattern: Box<Pattern>) {
self.patterns.push(pattern);
}
/// Returns the type of the SPARQL query.
///
/// todo
///
pub fn get_query_type(&self) -> &SparqlQueryType
|
/// Get query variables.
///
/// todo
///
pub fn get_query_variables(&self) -> &Vec<String> {
&self.variables
}
/// Get the query patterns in the `WHERE` expression.
///
/// todo
///
// pub fn get_query_patterns(&self) -> &Vec<Pattern> {
// &self.patterns
// }
/// Returns the URI of a namespace with the provided prefix.
///
/// # Examples
///
/// todo
///
/// # Failures
///
/// - No namespace with the provided prefix exists
///
pub fn get_namespace_uri_by_prefix(&self, prefix: String) -> Result<&Uri> {
self.namespaces.get_uri_by_prefix(&prefix)
}
}
|
{
&self.query_type
}
|
identifier_body
|
query.rs
|
use crate::namespace::*;
use crate::sparql::pattern::Pattern;
use crate::uri::Uri;
use crate::Result;
/// Query type.
#[derive(Clone, Debug)]
pub enum
|
{
Ask,
Select,
SelectDistinct,
SelectReduced,
SelectAll,
SelectAllDistinct,
SelectAllReduced,
Construct,
Describe,
}
/// Represents a SPARQL query that can be applied to an RDF graph.
/// `SparqlQuery`s are created when parsing a SPARQL string using `SparqlParser`.
pub struct SparqlQuery {
/// SPARQL query type.
query_type: SparqlQueryType,
/// Base URI denoted in SPARQL query.
base_uri: Option<Uri>,
/// Namespaces stated in SPARQL query.
namespaces: NamespaceStore,
// Variables used in the query.
variables: Vec<String>,
// Patterns used as constraints.
patterns: Vec<Box<Pattern>>,
}
impl SparqlQuery {
/// Constructor of `SparqlQuery`.
pub fn new(query_type: SparqlQueryType) -> SparqlQuery {
SparqlQuery {
query_type: query_type,
base_uri: None,
variables: Vec::new(),
patterns: Vec::new(),
namespaces: NamespaceStore::new(),
}
}
/// Add variables to the query.
/// Ordering in vector reflects position the variables appear.
pub fn add_variables(&mut self, variables: Vec<String>) {
self.variables = variables;
}
/// Add pattern to the query.
pub fn add_pattern(&mut self, pattern: Box<Pattern>) {
self.patterns.push(pattern);
}
/// Returns the type of the SPARQL query.
///
/// todo
///
pub fn get_query_type(&self) -> &SparqlQueryType {
&self.query_type
}
/// Get query variables.
///
/// todo
///
pub fn get_query_variables(&self) -> &Vec<String> {
&self.variables
}
/// Get the query patterns in the `WHERE` expression.
///
/// todo
///
// pub fn get_query_patterns(&self) -> &Vec<Pattern> {
// &self.patterns
// }
/// Returns the URI of a namespace with the provided prefix.
///
/// # Examples
///
/// todo
///
/// # Failures
///
/// - No namespace with the provided prefix exists
///
pub fn get_namespace_uri_by_prefix(&self, prefix: String) -> Result<&Uri> {
self.namespaces.get_uri_by_prefix(&prefix)
}
}
|
SparqlQueryType
|
identifier_name
|
mod.rs
|
use crate::rendering::*;
use crate::geometry::*;
/// IMPORTANT: Must form a star domain at its center
#[derive(Clone, Debug)]
pub struct Polygon {
pub corners: Vec<Point>, /// defined anti-clockwise
pub center: Point,
pub rot: Rotation, /// anti-clockwise angle w.r.t. positive z-axis
pub pos: Point3,
pub color: Color,
pub fixed: bool
}
impl Polygon {
pub fn new_regular(
corners: Vec<Point>,
center: Point,
pos: Point3,
color: Color,
fixed: bool
) -> Polygon
|
pub fn get_vertices(self) -> Vec<PolygonVertex> {
let mut output: Vec<PolygonVertex> = vec![];
let corners_it_shift = self.corners.clone().into_iter().cycle().skip(1);
for (corner1, corner2) in self.corners.into_iter().zip(corners_it_shift) {
output.push(PolygonVertex {
corner1: corner1.into(),
corner2: corner2.into(),
center: self.center.into(),
rot: self.rot.get_matrix_f32(),
pos: self.pos.into(),
color: self.color.get_array_f32(),
fixed_pos: self.fixed as u32
});
}
output
}
}
impl GliumStandardPrimitive for Polygon {
type Vertex = PolygonVertex;
fn get_shaders() -> Shaders {
Shaders::VertexGeometryFragment(
include_str!("polygon.vs"),
include_str!("polygon.ges"),
include_str!("polygon.fs")
)
}
fn get_vertex(self) -> Vec<Self::Vertex> { self.get_vertices() }
}
#[derive(Copy, Clone, Debug)]
pub struct PolygonVertex {
pub corner1: [f32; 2],
pub corner2: [f32; 2],
pub center: [f32; 2],
pub rot: [[f32; 2]; 2],
pub pos: [f32; 3],
pub color: [f32; 4],
pub fixed_pos: u32
}
implement_vertex!(PolygonVertex, corner1, corner2, center, rot, pos, color, fixed_pos);
|
{
Polygon {
corners,
center,
rot: Rotation::new(0.0),
pos,
color,
fixed,
}
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.