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 |
---|---|---|---|---|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of stylesheets.
//!
//! [computed]: https://drafts.csswg.org/css-cascade/#computed
//! [specified]: https://drafts.csswg.org/css-cascade/#specified
//!
//! In particular, this crate contains the definitions of supported properties,
//! the code to parse them into specified values and calculate the computed
//! values based on the specified values, as well as the code to serialize both
//! specified and computed values.
//!
//! The main entry point is [`recalc_style_at`][recalc_style_at].
//!
//! [recalc_style_at]: traversal/fn.recalc_style_at.html
//!
//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
//! crates.
//!
//! [cssparser]:../cssparser/index.html
//! [selectors]:../selectors/index.html
#![deny(missing_docs)]
extern crate app_units;
extern crate arrayvec;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)] extern crate byteorder;
#[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate debug_unreachable;
extern crate euclid;
extern crate fallible;
extern crate fnv;
#[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache;
extern crate hashglobe;
extern crate itertools;
extern crate itoa;
#[cfg(feature = "servo")] #[macro_use] extern crate html5ever;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use] extern crate malloc_size_of;
#[macro_use] extern crate malloc_size_of_derive;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate matches;
#[cfg(feature = "gecko")]
pub extern crate nsstring;
#[cfg(feature = "gecko")] extern crate num_cpus;
extern crate num_integer;
extern crate num_traits;
extern crate ordered_float;
extern crate owning_ref;
extern crate parking_lot;
extern crate precomputed_hash;
extern crate rayon;
extern crate selectors;
#[cfg(feature = "servo")] #[macro_use] extern crate serde;
pub extern crate servo_arc;
#[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms;
#[cfg(feature = "servo")] extern crate servo_config;
#[cfg(feature = "servo")] extern crate servo_url;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")] extern crate string_cache;
#[macro_use]
extern crate style_derive;
extern crate style_traits;
extern crate time;
extern crate uluru;
extern crate unicode_bidi;
#[allow(unused_extern_crates)]
extern crate unicode_segmentation;
extern crate void;
#[macro_use]
mod macros;
#[cfg(feature = "servo")] pub mod animation;
pub mod applicable_declarations;
#[allow(missing_docs)] // TODO.
#[cfg(feature = "servo")] pub mod attr;
pub mod bezier;
pub mod bloom;
pub mod context;
pub mod counter_style;
pub mod custom_properties;
pub mod data;
pub mod dom;
pub mod dom_apis;
pub mod driver;
pub mod element_state;
#[cfg(feature = "servo")] mod encoding_support;
pub mod error_reporting;
pub mod font_face;
pub mod font_metrics;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cache;
pub mod rule_tree;
pub mod scoped_tls;
pub mod selector_map;
pub mod selector_parser;
pub mod shared_lock;
pub mod sharing;
pub mod str;
pub mod style_adjuster;
pub mod style_resolver;
pub mod stylesheet_set;
pub mod stylesheets;
pub mod stylist;
pub mod thread_state;
pub mod timer;
pub mod traversal;
pub mod traversal_flags;
#[macro_use]
#[allow(non_camel_case_types)]
pub mod values;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
#[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName;
#[cfg(feature = "servo")] pub use servo_atoms::Atom;
#[cfg(feature = "servo")] pub use html5ever::Prefix;
#[cfg(feature = "servo")] pub use html5ever::LocalName;
#[cfg(feature = "servo")] pub use html5ever::Namespace;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
#[deny(missing_docs)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
// uses a macro from properties
#[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo;
#[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)]
|
include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use properties::longhands::$name::computed_value as $name;
)+
// Don't use a side-specific name needlessly:
pub use properties::longhands::border_top_style::computed_value as border_style;
}
}
}
longhand_properties_idents!(reexport_computed_values);
/// Serializes as CSS a comma-separated list of any `T` that supports being
/// serialized as CSS.
pub fn serialize_comma_separated_list<W, T>(
dest: &mut CssWriter<W>,
list: &[T],
) -> fmt::Result
where
W: Write,
T: ToCss,
{
if list.is_empty() {
return Ok(());
}
list[0].to_css(dest)?;
for item in list.iter().skip(1) {
dest.write_str(", ")?;
item.to_css(dest)?;
}
Ok(())
}
#[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom;
#[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom;
/// Extension methods for selectors::attr::CaseSensitivity
pub trait CaseSensitivityExt {
/// Return whether two atoms compare equal according to this case sensitivity.
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
}
impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
}
|
pub mod gecko_properties {
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of stylesheets.
//!
//! [computed]: https://drafts.csswg.org/css-cascade/#computed
//! [specified]: https://drafts.csswg.org/css-cascade/#specified
//!
//! In particular, this crate contains the definitions of supported properties,
//! the code to parse them into specified values and calculate the computed
//! values based on the specified values, as well as the code to serialize both
//! specified and computed values.
//!
//! The main entry point is [`recalc_style_at`][recalc_style_at].
//!
//! [recalc_style_at]: traversal/fn.recalc_style_at.html
//!
//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
//! crates.
//!
//! [cssparser]:../cssparser/index.html
//! [selectors]:../selectors/index.html
#![deny(missing_docs)]
extern crate app_units;
extern crate arrayvec;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)] extern crate byteorder;
#[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate debug_unreachable;
extern crate euclid;
extern crate fallible;
extern crate fnv;
#[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache;
extern crate hashglobe;
extern crate itertools;
extern crate itoa;
#[cfg(feature = "servo")] #[macro_use] extern crate html5ever;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use] extern crate malloc_size_of;
#[macro_use] extern crate malloc_size_of_derive;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate matches;
#[cfg(feature = "gecko")]
pub extern crate nsstring;
#[cfg(feature = "gecko")] extern crate num_cpus;
extern crate num_integer;
extern crate num_traits;
extern crate ordered_float;
extern crate owning_ref;
extern crate parking_lot;
extern crate precomputed_hash;
extern crate rayon;
extern crate selectors;
#[cfg(feature = "servo")] #[macro_use] extern crate serde;
pub extern crate servo_arc;
#[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms;
#[cfg(feature = "servo")] extern crate servo_config;
#[cfg(feature = "servo")] extern crate servo_url;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")] extern crate string_cache;
#[macro_use]
extern crate style_derive;
extern crate style_traits;
extern crate time;
extern crate uluru;
extern crate unicode_bidi;
#[allow(unused_extern_crates)]
extern crate unicode_segmentation;
extern crate void;
#[macro_use]
mod macros;
#[cfg(feature = "servo")] pub mod animation;
pub mod applicable_declarations;
#[allow(missing_docs)] // TODO.
#[cfg(feature = "servo")] pub mod attr;
pub mod bezier;
pub mod bloom;
pub mod context;
pub mod counter_style;
pub mod custom_properties;
pub mod data;
pub mod dom;
pub mod dom_apis;
pub mod driver;
pub mod element_state;
#[cfg(feature = "servo")] mod encoding_support;
pub mod error_reporting;
pub mod font_face;
pub mod font_metrics;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cache;
pub mod rule_tree;
pub mod scoped_tls;
pub mod selector_map;
pub mod selector_parser;
pub mod shared_lock;
pub mod sharing;
pub mod str;
pub mod style_adjuster;
pub mod style_resolver;
pub mod stylesheet_set;
pub mod stylesheets;
pub mod stylist;
pub mod thread_state;
pub mod timer;
pub mod traversal;
pub mod traversal_flags;
#[macro_use]
#[allow(non_camel_case_types)]
pub mod values;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
#[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName;
#[cfg(feature = "servo")] pub use servo_atoms::Atom;
#[cfg(feature = "servo")] pub use html5ever::Prefix;
#[cfg(feature = "servo")] pub use html5ever::LocalName;
#[cfg(feature = "servo")] pub use html5ever::Namespace;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
#[deny(missing_docs)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
// uses a macro from properties
#[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo;
#[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)]
pub mod gecko_properties {
include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use properties::longhands::$name::computed_value as $name;
)+
// Don't use a side-specific name needlessly:
pub use properties::longhands::border_top_style::computed_value as border_style;
}
}
}
longhand_properties_idents!(reexport_computed_values);
/// Serializes as CSS a comma-separated list of any `T` that supports being
/// serialized as CSS.
pub fn
|
<W, T>(
dest: &mut CssWriter<W>,
list: &[T],
) -> fmt::Result
where
W: Write,
T: ToCss,
{
if list.is_empty() {
return Ok(());
}
list[0].to_css(dest)?;
for item in list.iter().skip(1) {
dest.write_str(", ")?;
item.to_css(dest)?;
}
Ok(())
}
#[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom;
#[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom;
/// Extension methods for selectors::attr::CaseSensitivity
pub trait CaseSensitivityExt {
/// Return whether two atoms compare equal according to this case sensitivity.
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
}
impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
}
|
serialize_comma_separated_list
|
identifier_name
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of stylesheets.
//!
//! [computed]: https://drafts.csswg.org/css-cascade/#computed
//! [specified]: https://drafts.csswg.org/css-cascade/#specified
//!
//! In particular, this crate contains the definitions of supported properties,
//! the code to parse them into specified values and calculate the computed
//! values based on the specified values, as well as the code to serialize both
//! specified and computed values.
//!
//! The main entry point is [`recalc_style_at`][recalc_style_at].
//!
//! [recalc_style_at]: traversal/fn.recalc_style_at.html
//!
//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
//! crates.
//!
//! [cssparser]:../cssparser/index.html
//! [selectors]:../selectors/index.html
#![deny(missing_docs)]
extern crate app_units;
extern crate arrayvec;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)] extern crate byteorder;
#[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate debug_unreachable;
extern crate euclid;
extern crate fallible;
extern crate fnv;
#[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache;
extern crate hashglobe;
extern crate itertools;
extern crate itoa;
#[cfg(feature = "servo")] #[macro_use] extern crate html5ever;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use] extern crate malloc_size_of;
#[macro_use] extern crate malloc_size_of_derive;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate matches;
#[cfg(feature = "gecko")]
pub extern crate nsstring;
#[cfg(feature = "gecko")] extern crate num_cpus;
extern crate num_integer;
extern crate num_traits;
extern crate ordered_float;
extern crate owning_ref;
extern crate parking_lot;
extern crate precomputed_hash;
extern crate rayon;
extern crate selectors;
#[cfg(feature = "servo")] #[macro_use] extern crate serde;
pub extern crate servo_arc;
#[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms;
#[cfg(feature = "servo")] extern crate servo_config;
#[cfg(feature = "servo")] extern crate servo_url;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")] extern crate string_cache;
#[macro_use]
extern crate style_derive;
extern crate style_traits;
extern crate time;
extern crate uluru;
extern crate unicode_bidi;
#[allow(unused_extern_crates)]
extern crate unicode_segmentation;
extern crate void;
#[macro_use]
mod macros;
#[cfg(feature = "servo")] pub mod animation;
pub mod applicable_declarations;
#[allow(missing_docs)] // TODO.
#[cfg(feature = "servo")] pub mod attr;
pub mod bezier;
pub mod bloom;
pub mod context;
pub mod counter_style;
pub mod custom_properties;
pub mod data;
pub mod dom;
pub mod dom_apis;
pub mod driver;
pub mod element_state;
#[cfg(feature = "servo")] mod encoding_support;
pub mod error_reporting;
pub mod font_face;
pub mod font_metrics;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko;
#[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cache;
pub mod rule_tree;
pub mod scoped_tls;
pub mod selector_map;
pub mod selector_parser;
pub mod shared_lock;
pub mod sharing;
pub mod str;
pub mod style_adjuster;
pub mod style_resolver;
pub mod stylesheet_set;
pub mod stylesheets;
pub mod stylist;
pub mod thread_state;
pub mod timer;
pub mod traversal;
pub mod traversal_flags;
#[macro_use]
#[allow(non_camel_case_types)]
pub mod values;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
#[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix;
#[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName;
#[cfg(feature = "servo")] pub use servo_atoms::Atom;
#[cfg(feature = "servo")] pub use html5ever::Prefix;
#[cfg(feature = "servo")] pub use html5ever::LocalName;
#[cfg(feature = "servo")] pub use html5ever::Namespace;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
#[deny(missing_docs)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
// uses a macro from properties
#[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo;
#[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)]
pub mod gecko_properties {
include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use properties::longhands::$name::computed_value as $name;
)+
// Don't use a side-specific name needlessly:
pub use properties::longhands::border_top_style::computed_value as border_style;
}
}
}
longhand_properties_idents!(reexport_computed_values);
/// Serializes as CSS a comma-separated list of any `T` that supports being
/// serialized as CSS.
pub fn serialize_comma_separated_list<W, T>(
dest: &mut CssWriter<W>,
list: &[T],
) -> fmt::Result
where
W: Write,
T: ToCss,
{
if list.is_empty() {
return Ok(());
}
list[0].to_css(dest)?;
for item in list.iter().skip(1) {
dest.write_str(", ")?;
item.to_css(dest)?;
}
Ok(())
}
#[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom;
#[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom;
/// Extension methods for selectors::attr::CaseSensitivity
pub trait CaseSensitivityExt {
/// Return whether two atoms compare equal according to this case sensitivity.
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
}
impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool
|
}
|
{
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
|
identifier_body
|
event_box.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkEventBox — A widget used to catch events for widgets which do not have their own window
use cast::{GTK_EVENT_BOX};
use ffi;
use glib::{to_bool, to_gboolean};
struct_Widget!(EventBox);
impl EventBox {
pub fn new() -> Option<EventBox> {
let tmp_pointer = unsafe { ffi::gtk_event_box_new() };
check_pointer!(tmp_pointer, EventBox)
}
pub fn set_above_child(&self, above_child: bool) {
unsafe {
ffi::gtk_event_box_set_above_child(GTK_EVENT_BOX(self.pointer), to_gboolean(above_child))
}
}
pub fn get_above_child(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_above_child(GTK_EVENT_BOX(self.pointer))) }
}
pub fn set_visible_window(&self, visible_window: bool) {
unsafe {
ffi::gtk_event_box_set_visible_window(GTK_EVENT_BOX(self.pointer), to_gboolean(visible_window))
}
}
pub fn ge
|
self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) }
}
}
impl_drop!(EventBox);
impl_TraitWidget!(EventBox);
impl ::ContainerTrait for EventBox {}
impl ::BinTrait for EventBox {}
|
t_visible_window(&
|
identifier_name
|
event_box.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkEventBox — A widget used to catch events for widgets which do not have their own window
use cast::{GTK_EVENT_BOX};
use ffi;
use glib::{to_bool, to_gboolean};
struct_Widget!(EventBox);
impl EventBox {
pub fn new() -> Option<EventBox> {
let tmp_pointer = unsafe { ffi::gtk_event_box_new() };
check_pointer!(tmp_pointer, EventBox)
}
pub fn set_above_child(&self, above_child: bool) {
unsafe {
ffi::gtk_event_box_set_above_child(GTK_EVENT_BOX(self.pointer), to_gboolean(above_child))
}
}
pub fn get_above_child(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_above_child(GTK_EVENT_BOX(self.pointer))) }
}
pub fn set_visible_window(&self, visible_window: bool) {
unsafe {
ffi::gtk_event_box_set_visible_window(GTK_EVENT_BOX(self.pointer), to_gboolean(visible_window))
}
}
|
}
impl_drop!(EventBox);
impl_TraitWidget!(EventBox);
impl ::ContainerTrait for EventBox {}
impl ::BinTrait for EventBox {}
|
pub fn get_visible_window(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) }
}
|
random_line_split
|
event_box.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkEventBox — A widget used to catch events for widgets which do not have their own window
use cast::{GTK_EVENT_BOX};
use ffi;
use glib::{to_bool, to_gboolean};
struct_Widget!(EventBox);
impl EventBox {
pub fn new() -> Option<EventBox> {
let tmp_pointer = unsafe { ffi::gtk_event_box_new() };
check_pointer!(tmp_pointer, EventBox)
}
pub fn set_above_child(&self, above_child: bool) {
|
pub fn get_above_child(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_above_child(GTK_EVENT_BOX(self.pointer))) }
}
pub fn set_visible_window(&self, visible_window: bool) {
unsafe {
ffi::gtk_event_box_set_visible_window(GTK_EVENT_BOX(self.pointer), to_gboolean(visible_window))
}
}
pub fn get_visible_window(&self) -> bool {
unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) }
}
}
impl_drop!(EventBox);
impl_TraitWidget!(EventBox);
impl ::ContainerTrait for EventBox {}
impl ::BinTrait for EventBox {}
|
unsafe {
ffi::gtk_event_box_set_above_child(GTK_EVENT_BOX(self.pointer), to_gboolean(above_child))
}
}
|
identifier_body
|
dpapi.rs
|
// 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! Data Protection API Prototypes and Definitions
use shared::minwindef::{BOOL, BYTE, DWORD, LPVOID};
use shared::windef::HWND;
use um::wincrypt::DATA_BLOB;
use um::winnt::{LPCWSTR, LPWSTR, PSID, PVOID};
pub const szFORCE_KEY_PROTECTION: &'static str = "ForceKeyProtection";
pub const dwFORCE_KEY_PROTECTION_DISABLED: DWORD = 0x0;
pub const dwFORCE_KEY_PROTECTION_USER_SELECT: DWORD = 0x1;
pub const dwFORCE_KEY_PROTECTION_HIGH: DWORD = 0x2;
STRUCT!{struct CRYPTPROTECT_PROMPTSTRUCT {
cbSize: DWORD,
dwPromptFlags: DWORD,
hwndApp: HWND,
szPrompt: LPCWSTR,
}}
pub type PCRYPTPROTECT_PROMPTSTRUCT = *mut CRYPTPROTECT_PROMPTSTRUCT;
pub const CRYPTPROTECT_PROMPT_ON_UNPROTECT: DWORD = 0x1;
pub const CRYPTPROTECT_PROMPT_ON_PROTECT: DWORD = 0x2;
pub const CRYPTPROTECT_PROMPT_RESERVED: DWORD = 0x04;
pub const CRYPTPROTECT_PROMPT_STRONG: DWORD = 0x08;
pub const CRYPTPROTECT_PROMPT_REQUIRE_STRONG: DWORD = 0x10;
pub const CRYPTPROTECT_UI_FORBIDDEN: DWORD = 0x1;
pub const CRYPTPROTECT_LOCAL_MACHINE: DWORD = 0x4;
pub const CRYPTPROTECT_CRED_SYNC: DWORD = 0x8;
pub const CRYPTPROTECT_AUDIT: DWORD = 0x10;
pub const CRYPTPROTECT_NO_RECOVERY: DWORD = 0x20;
pub const CRYPTPROTECT_VERIFY_PROTECTION: DWORD = 0x40;
pub const CRYPTPROTECT_CRED_REGENERATE: DWORD = 0x80;
pub const CRYPTPROTECT_FIRST_RESERVED_FLAGVAL: DWORD = 0x0FFFFFFF;
pub const CRYPTPROTECT_LAST_RESERVED_FLAGVAL: DWORD = 0xFFFFFFFF;
extern "system" {
pub fn CryptProtectData(
pDataIn: *mut DATA_BLOB,
szDataDescr: LPCWSTR,
pOptionalEntropy: *mut DATA_BLOB,
pvReserved: PVOID,
pPromptStruct: *mut CRYPTPROTECT_PROMPTSTRUCT,
dwFlags: DWORD,
pDataOut: *mut DATA_BLOB,
) -> BOOL;
pub fn CryptUnprotectData(
|
pOptionalEntropy: *mut DATA_BLOB,
pvReserved: PVOID,
pPromptStruct: *mut CRYPTPROTECT_PROMPTSTRUCT,
dwFlags: DWORD,
pDataOut: *mut DATA_BLOB,
) -> BOOL;
pub fn CryptProtectDataNoUI(
pDataIn: *mut DATA_BLOB,
szDataDescr: LPCWSTR,
pOptionalEntropy: *mut DATA_BLOB,
pvReserved: PVOID,
pPromptStruct: *mut CRYPTPROTECT_PROMPTSTRUCT,
dwFlags: DWORD,
pbOptionalPassword: *const BYTE,
cbOptionalPassword: DWORD,
pDataOut: *mut DATA_BLOB,
) -> BOOL;
pub fn CryptUnprotectDataNoUI(
pDataIn: *mut DATA_BLOB,
ppszDataDescr: *mut LPWSTR,
pOptionalEntropy: *mut DATA_BLOB,
pvReserved: PVOID,
pPromptStruct: *mut CRYPTPROTECT_PROMPTSTRUCT,
dwFlags: DWORD,
pbOptionalPassword: *const BYTE,
cbOptionalPassword: DWORD,
pDataOut: *mut DATA_BLOB,
) -> BOOL;
pub fn CryptUpdateProtectedState(
pOldSid: PSID,
pwszOldPassword: LPCWSTR,
dwFlags: DWORD,
pdwSuccessCount: *mut DWORD,
pdwFailureCount: *mut DWORD,
) -> BOOL;
}
pub const CRYPTPROTECTMEMORY_BLOCK_SIZE: DWORD = 16;
pub const CRYPTPROTECTMEMORY_SAME_PROCESS: DWORD = 0x00;
pub const CRYPTPROTECTMEMORY_CROSS_PROCESS: DWORD = 0x01;
pub const CRYPTPROTECTMEMORY_SAME_LOGON: DWORD = 0x02;
extern "system" {
pub fn CryptProtectMemory(
pDataIn: LPVOID,
cbDataIn: DWORD,
dwFlags: DWORD,
) -> BOOL;
pub fn CryptUnprotectMemory(
pDataIn: LPVOID,
cbDataIn: DWORD,
dwFlags: DWORD,
) -> BOOL;
}
|
pDataIn: *mut DATA_BLOB,
ppszDataDescr: *mut LPWSTR,
|
random_line_split
|
htmltableelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods;
use dom::bindings::codegen::Bindings::HTMLTableElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableCaptionElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLTableElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Rootable, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmltablecaptionelement::HTMLTableCaptionElement;
use dom::node::{Node, NodeHelpers, NodeTypeId};
use dom::virtualmethods::VirtualMethods;
use util::str::{self, DOMString, LengthOrPercentageOrAuto};
use cssparser::RGBA;
use string_cache::Atom;
use std::cell::Cell;
#[dom_struct]
pub struct HTMLTableElement {
htmlelement: HTMLElement,
background_color: Cell<Option<RGBA>>,
border: Cell<Option<u32>>,
cellspacing: Cell<Option<u32>>,
width: Cell<LengthOrPercentageOrAuto>,
}
impl HTMLTableElementDerived for EventTarget {
fn is_htmltableelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)))
}
}
impl HTMLTableElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> HTMLTableElement {
HTMLTableElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableElement,
localName,
prefix,
document),
background_color: Cell::new(None),
border: Cell::new(None),
cellspacing: Cell::new(None),
width: Cell::new(LengthOrPercentageOrAuto::Auto),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableElement> {
let element = HTMLTableElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableElementBinding::Wrap)
}
}
impl<'a> HTMLTableElementMethods for JSRef<'a, HTMLTableElement> {
// https://www.whatwg.org/html/#dom-table-caption
fn GetCaption(self) -> Option<Temporary<HTMLTableCaptionElement>> {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.children()
.map(|c| c.root())
.filter_map(|c| {
HTMLTableCaptionElementCast::to_ref(c.r()).map(Temporary::from_rooted)
})
.next()
}
// https://www.whatwg.org/html/#dom-table-caption
fn SetCaption(self, new_caption: Option<JSRef<HTMLTableCaptionElement>>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let old_caption = self.GetCaption();
match old_caption {
Some(htmlelem) => {
let htmlelem_root = htmlelem.root();
let old_caption_node: JSRef<Node> = NodeCast::from_ref(htmlelem_root.r());
assert!(node.RemoveChild(old_caption_node).is_ok());
}
None => ()
}
new_caption.map(|caption| {
let new_caption_node: JSRef<Node> = NodeCast::from_ref(caption);
assert!(node.AppendChild(new_caption_node).is_ok());
});
}
}
pub trait HTMLTableElementHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_border(&self) -> Option<u32>;
fn get_cellspacing(&self) -> Option<u32>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLTableElementHelpers for HTMLTableElement {
fn get_background_color(&self) -> Option<RGBA> {
self.background_color.get()
}
fn get_border(&self) -> Option<u32> {
self.border.get()
}
fn get_cellspacing(&self) -> Option<u32> {
self.cellspacing.get()
}
fn get_width(&self) -> LengthOrPercentageOrAuto {
self.width.get()
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>)
|
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => self.background_color.set(None),
&atom!("border") => self.border.set(None),
&atom!("cellspacing") => self.cellspacing.set(None),
&atom!("width") => self.width.set(LengthOrPercentageOrAuto::Auto),
_ => ()
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match local_name {
&atom!("border") => AttrValue::from_u32(value, 1),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
|
{
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => {
self.background_color.set(str::parse_legacy_color(&attr.value()).ok())
}
&atom!("border") => {
// According to HTML5 § 14.3.9, invalid values map to 1px.
self.border.set(Some(str::parse_unsigned_integer(attr.value()
.chars()).unwrap_or(1)))
}
&atom!("cellspacing") => {
self.cellspacing.set(str::parse_unsigned_integer(attr.value().chars()))
}
&atom!("width") => self.width.set(str::parse_length(&attr.value())),
_ => ()
}
|
identifier_body
|
htmltableelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods;
use dom::bindings::codegen::Bindings::HTMLTableElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableCaptionElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLTableElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Rootable, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmltablecaptionelement::HTMLTableCaptionElement;
use dom::node::{Node, NodeHelpers, NodeTypeId};
use dom::virtualmethods::VirtualMethods;
use util::str::{self, DOMString, LengthOrPercentageOrAuto};
use cssparser::RGBA;
use string_cache::Atom;
use std::cell::Cell;
#[dom_struct]
pub struct HTMLTableElement {
htmlelement: HTMLElement,
background_color: Cell<Option<RGBA>>,
border: Cell<Option<u32>>,
cellspacing: Cell<Option<u32>>,
width: Cell<LengthOrPercentageOrAuto>,
}
impl HTMLTableElementDerived for EventTarget {
fn is_htmltableelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)))
}
}
impl HTMLTableElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> HTMLTableElement {
HTMLTableElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableElement,
localName,
prefix,
document),
background_color: Cell::new(None),
border: Cell::new(None),
cellspacing: Cell::new(None),
width: Cell::new(LengthOrPercentageOrAuto::Auto),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableElement> {
let element = HTMLTableElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableElementBinding::Wrap)
}
}
impl<'a> HTMLTableElementMethods for JSRef<'a, HTMLTableElement> {
// https://www.whatwg.org/html/#dom-table-caption
fn GetCaption(self) -> Option<Temporary<HTMLTableCaptionElement>> {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.children()
.map(|c| c.root())
.filter_map(|c| {
HTMLTableCaptionElementCast::to_ref(c.r()).map(Temporary::from_rooted)
})
.next()
}
// https://www.whatwg.org/html/#dom-table-caption
fn SetCaption(self, new_caption: Option<JSRef<HTMLTableCaptionElement>>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let old_caption = self.GetCaption();
match old_caption {
Some(htmlelem) => {
let htmlelem_root = htmlelem.root();
let old_caption_node: JSRef<Node> = NodeCast::from_ref(htmlelem_root.r());
assert!(node.RemoveChild(old_caption_node).is_ok());
}
None => ()
}
new_caption.map(|caption| {
let new_caption_node: JSRef<Node> = NodeCast::from_ref(caption);
assert!(node.AppendChild(new_caption_node).is_ok());
});
}
}
pub trait HTMLTableElementHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_border(&self) -> Option<u32>;
fn get_cellspacing(&self) -> Option<u32>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLTableElementHelpers for HTMLTableElement {
fn get_background_color(&self) -> Option<RGBA> {
self.background_color.get()
}
fn
|
(&self) -> Option<u32> {
self.border.get()
}
fn get_cellspacing(&self) -> Option<u32> {
self.cellspacing.get()
}
fn get_width(&self) -> LengthOrPercentageOrAuto {
self.width.get()
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => {
self.background_color.set(str::parse_legacy_color(&attr.value()).ok())
}
&atom!("border") => {
// According to HTML5 § 14.3.9, invalid values map to 1px.
self.border.set(Some(str::parse_unsigned_integer(attr.value()
.chars()).unwrap_or(1)))
}
&atom!("cellspacing") => {
self.cellspacing.set(str::parse_unsigned_integer(attr.value().chars()))
}
&atom!("width") => self.width.set(str::parse_length(&attr.value())),
_ => ()
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => self.background_color.set(None),
&atom!("border") => self.border.set(None),
&atom!("cellspacing") => self.cellspacing.set(None),
&atom!("width") => self.width.set(LengthOrPercentageOrAuto::Auto),
_ => ()
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match local_name {
&atom!("border") => AttrValue::from_u32(value, 1),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
|
get_border
|
identifier_name
|
htmltableelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTMLTableElementMethods;
use dom::bindings::codegen::Bindings::HTMLTableElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTableCaptionElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLTableElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Rootable, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmltablecaptionelement::HTMLTableCaptionElement;
use dom::node::{Node, NodeHelpers, NodeTypeId};
use dom::virtualmethods::VirtualMethods;
use util::str::{self, DOMString, LengthOrPercentageOrAuto};
use cssparser::RGBA;
use string_cache::Atom;
use std::cell::Cell;
#[dom_struct]
pub struct HTMLTableElement {
htmlelement: HTMLElement,
background_color: Cell<Option<RGBA>>,
border: Cell<Option<u32>>,
cellspacing: Cell<Option<u32>>,
width: Cell<LengthOrPercentageOrAuto>,
}
impl HTMLTableElementDerived for EventTarget {
fn is_htmltableelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)))
}
}
impl HTMLTableElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> HTMLTableElement {
HTMLTableElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableElement,
localName,
prefix,
document),
background_color: Cell::new(None),
border: Cell::new(None),
cellspacing: Cell::new(None),
width: Cell::new(LengthOrPercentageOrAuto::Auto),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>)
-> Temporary<HTMLTableElement> {
let element = HTMLTableElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableElementBinding::Wrap)
}
}
impl<'a> HTMLTableElementMethods for JSRef<'a, HTMLTableElement> {
// https://www.whatwg.org/html/#dom-table-caption
fn GetCaption(self) -> Option<Temporary<HTMLTableCaptionElement>> {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.children()
.map(|c| c.root())
.filter_map(|c| {
HTMLTableCaptionElementCast::to_ref(c.r()).map(Temporary::from_rooted)
})
.next()
}
// https://www.whatwg.org/html/#dom-table-caption
fn SetCaption(self, new_caption: Option<JSRef<HTMLTableCaptionElement>>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let old_caption = self.GetCaption();
match old_caption {
Some(htmlelem) => {
let htmlelem_root = htmlelem.root();
let old_caption_node: JSRef<Node> = NodeCast::from_ref(htmlelem_root.r());
assert!(node.RemoveChild(old_caption_node).is_ok());
}
None => ()
}
new_caption.map(|caption| {
let new_caption_node: JSRef<Node> = NodeCast::from_ref(caption);
assert!(node.AppendChild(new_caption_node).is_ok());
});
}
}
pub trait HTMLTableElementHelpers {
fn get_background_color(&self) -> Option<RGBA>;
fn get_border(&self) -> Option<u32>;
fn get_cellspacing(&self) -> Option<u32>;
fn get_width(&self) -> LengthOrPercentageOrAuto;
}
impl HTMLTableElementHelpers for HTMLTableElement {
fn get_background_color(&self) -> Option<RGBA> {
self.background_color.get()
}
fn get_border(&self) -> Option<u32> {
self.border.get()
|
fn get_width(&self) -> LengthOrPercentageOrAuto {
self.width.get()
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => {
self.background_color.set(str::parse_legacy_color(&attr.value()).ok())
}
&atom!("border") => {
// According to HTML5 § 14.3.9, invalid values map to 1px.
self.border.set(Some(str::parse_unsigned_integer(attr.value()
.chars()).unwrap_or(1)))
}
&atom!("cellspacing") => {
self.cellspacing.set(str::parse_unsigned_integer(attr.value().chars()))
}
&atom!("width") => self.width.set(str::parse_length(&attr.value())),
_ => ()
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("bgcolor") => self.background_color.set(None),
&atom!("border") => self.border.set(None),
&atom!("cellspacing") => self.cellspacing.set(None),
&atom!("width") => self.width.set(LengthOrPercentageOrAuto::Auto),
_ => ()
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match local_name {
&atom!("border") => AttrValue::from_u32(value, 1),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
|
}
fn get_cellspacing(&self) -> Option<u32> {
self.cellspacing.get()
}
|
random_line_split
|
object-lifetime-default-from-rptr-mut.rs
|
// run-pass
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct SomeStruct<'a> {
t: &'a mut dyn Test,
u: &'a mut (dyn Test+'a),
}
fn a<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn
|
<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn main() {
}
|
b
|
identifier_name
|
object-lifetime-default-from-rptr-mut.rs
|
// run-pass
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
|
trait Test {
fn foo(&self) { }
}
struct SomeStruct<'a> {
t: &'a mut dyn Test,
u: &'a mut (dyn Test+'a),
}
fn a<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn b<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn main() {
}
|
random_line_split
|
|
object-lifetime-default-from-rptr-mut.rs
|
// run-pass
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
// pretty-expanded FIXME #23616
#![allow(dead_code)]
trait Test {
fn foo(&self) { }
}
struct SomeStruct<'a> {
t: &'a mut dyn Test,
u: &'a mut (dyn Test+'a),
}
fn a<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.t = t;
}
fn b<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>)
|
fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) {
ss.u = t;
}
fn main() {
}
|
{
ss.t = t;
}
|
identifier_body
|
time.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::inner::SteadyTime;
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
use sync::{Once, ONCE_INIT};
|
extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
}
}
pub fn ns(&self) -> u64 {
let info = info();
self.t * info.numer as u64 / info.denom as u64
}
}
fn info() -> &'static libc::mach_timebase_info {
static mut INFO: libc::mach_timebase_info = libc::mach_timebase_info {
numer: 0,
denom: 0,
};
static ONCE: Once = ONCE_INIT;
unsafe {
ONCE.call_once(|| {
mach_timebase_info(&mut INFO);
});
&INFO
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let info = info();
let diff = self.t as i64 - other.t as i64;
Duration::nanoseconds(diff * info.numer as i64 / info.denom as i64)
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
const NSEC_PER_SEC: i64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig's RT extensions are in the C library, not a separate librt
// OpenBSD provide it via libc
#[cfg(not(any(target_os = "android",
target_os = "bitrig",
target_os = "openbsd")))]
#[link(name = "rt")]
extern {}
extern {
fn clock_gettime(clk_id: libc::c_int, tp: *mut libc::timespec) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime {
t: libc::timespec {
tv_sec: 0,
tv_nsec: 0,
}
};
unsafe {
assert_eq!(0, clock_gettime(libc::CLOCK_MONOTONIC, &mut t.t));
}
t
}
pub fn ns(&self) -> u64 {
self.t.tv_sec as u64 * NSEC_PER_SEC as u64 + self.t.tv_nsec as u64
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
if self.t.tv_nsec >= other.t.tv_nsec {
Duration::seconds(self.t.tv_sec as i64 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 - other.t.tv_nsec as i64)
} else {
Duration::seconds(self.t.tv_sec as i64 - 1 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 + NSEC_PER_SEC -
other.t.tv_nsec as i64)
}
}
}
}
|
pub struct SteadyTime {
t: u64
}
|
random_line_split
|
time.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::inner::SteadyTime;
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
use sync::{Once, ONCE_INIT};
pub struct SteadyTime {
t: u64
}
extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
}
}
pub fn ns(&self) -> u64 {
let info = info();
self.t * info.numer as u64 / info.denom as u64
}
}
fn info() -> &'static libc::mach_timebase_info {
static mut INFO: libc::mach_timebase_info = libc::mach_timebase_info {
numer: 0,
denom: 0,
};
static ONCE: Once = ONCE_INIT;
unsafe {
ONCE.call_once(|| {
mach_timebase_info(&mut INFO);
});
&INFO
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let info = info();
let diff = self.t as i64 - other.t as i64;
Duration::nanoseconds(diff * info.numer as i64 / info.denom as i64)
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
const NSEC_PER_SEC: i64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig's RT extensions are in the C library, not a separate librt
// OpenBSD provide it via libc
#[cfg(not(any(target_os = "android",
target_os = "bitrig",
target_os = "openbsd")))]
#[link(name = "rt")]
extern {}
extern {
fn clock_gettime(clk_id: libc::c_int, tp: *mut libc::timespec) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime {
t: libc::timespec {
tv_sec: 0,
tv_nsec: 0,
}
};
unsafe {
assert_eq!(0, clock_gettime(libc::CLOCK_MONOTONIC, &mut t.t));
}
t
}
pub fn ns(&self) -> u64 {
self.t.tv_sec as u64 * NSEC_PER_SEC as u64 + self.t.tv_nsec as u64
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
if self.t.tv_nsec >= other.t.tv_nsec {
Duration::seconds(self.t.tv_sec as i64 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 - other.t.tv_nsec as i64)
} else
|
}
}
}
|
{
Duration::seconds(self.t.tv_sec as i64 - 1 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 + NSEC_PER_SEC -
other.t.tv_nsec as i64)
}
|
conditional_block
|
time.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::inner::SteadyTime;
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
use sync::{Once, ONCE_INIT};
pub struct SteadyTime {
t: u64
}
extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
}
}
pub fn ns(&self) -> u64 {
let info = info();
self.t * info.numer as u64 / info.denom as u64
}
}
fn info() -> &'static libc::mach_timebase_info {
static mut INFO: libc::mach_timebase_info = libc::mach_timebase_info {
numer: 0,
denom: 0,
};
static ONCE: Once = ONCE_INIT;
unsafe {
ONCE.call_once(|| {
mach_timebase_info(&mut INFO);
});
&INFO
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration
|
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
const NSEC_PER_SEC: i64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig's RT extensions are in the C library, not a separate librt
// OpenBSD provide it via libc
#[cfg(not(any(target_os = "android",
target_os = "bitrig",
target_os = "openbsd")))]
#[link(name = "rt")]
extern {}
extern {
fn clock_gettime(clk_id: libc::c_int, tp: *mut libc::timespec) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime {
t: libc::timespec {
tv_sec: 0,
tv_nsec: 0,
}
};
unsafe {
assert_eq!(0, clock_gettime(libc::CLOCK_MONOTONIC, &mut t.t));
}
t
}
pub fn ns(&self) -> u64 {
self.t.tv_sec as u64 * NSEC_PER_SEC as u64 + self.t.tv_nsec as u64
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
if self.t.tv_nsec >= other.t.tv_nsec {
Duration::seconds(self.t.tv_sec as i64 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 - other.t.tv_nsec as i64)
} else {
Duration::seconds(self.t.tv_sec as i64 - 1 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 + NSEC_PER_SEC -
other.t.tv_nsec as i64)
}
}
}
}
|
{
let info = info();
let diff = self.t as i64 - other.t as i64;
Duration::nanoseconds(diff * info.numer as i64 / info.denom as i64)
}
|
identifier_body
|
time.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::inner::SteadyTime;
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
use sync::{Once, ONCE_INIT};
pub struct
|
{
t: u64
}
extern {
pub fn mach_absolute_time() -> u64;
pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
}
}
pub fn ns(&self) -> u64 {
let info = info();
self.t * info.numer as u64 / info.denom as u64
}
}
fn info() -> &'static libc::mach_timebase_info {
static mut INFO: libc::mach_timebase_info = libc::mach_timebase_info {
numer: 0,
denom: 0,
};
static ONCE: Once = ONCE_INIT;
unsafe {
ONCE.call_once(|| {
mach_timebase_info(&mut INFO);
});
&INFO
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
let info = info();
let diff = self.t as i64 - other.t as i64;
Duration::nanoseconds(diff * info.numer as i64 / info.denom as i64)
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
const NSEC_PER_SEC: i64 = 1_000_000_000;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig's RT extensions are in the C library, not a separate librt
// OpenBSD provide it via libc
#[cfg(not(any(target_os = "android",
target_os = "bitrig",
target_os = "openbsd")))]
#[link(name = "rt")]
extern {}
extern {
fn clock_gettime(clk_id: libc::c_int, tp: *mut libc::timespec) -> libc::c_int;
}
impl SteadyTime {
pub fn now() -> SteadyTime {
let mut t = SteadyTime {
t: libc::timespec {
tv_sec: 0,
tv_nsec: 0,
}
};
unsafe {
assert_eq!(0, clock_gettime(libc::CLOCK_MONOTONIC, &mut t.t));
}
t
}
pub fn ns(&self) -> u64 {
self.t.tv_sec as u64 * NSEC_PER_SEC as u64 + self.t.tv_nsec as u64
}
}
impl<'a> Sub for &'a SteadyTime {
type Output = Duration;
fn sub(self, other: &SteadyTime) -> Duration {
if self.t.tv_nsec >= other.t.tv_nsec {
Duration::seconds(self.t.tv_sec as i64 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 - other.t.tv_nsec as i64)
} else {
Duration::seconds(self.t.tv_sec as i64 - 1 - other.t.tv_sec as i64) +
Duration::nanoseconds(self.t.tv_nsec as i64 + NSEC_PER_SEC -
other.t.tv_nsec as i64)
}
}
}
}
|
SteadyTime
|
identifier_name
|
keyframes_rule.rs
|
_properties::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use style_traits::{PARSING_MODE_DEFAULT, ToCss, ParseError, StyleParseError};
use style_traits::PropertyDeclarationParseError;
use stylesheets::{CssRuleType, StylesheetContents};
use stylesheets::rule_parser::VendorPrefix;
use values::{KeyframesName, serialize_percentage};
/// A [`@keyframes`][keyframes] rule.
///
/// [keyframes]: https://drafts.csswg.org/css-animations/#keyframes
#[derive(Debug)]
pub struct KeyframesRule {
/// The name of the current animation.
pub name: KeyframesName,
/// The keyframes specified for this CSS rule.
pub keyframes: Vec<Arc<Locked<Keyframe>>>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for KeyframesRule {
// Serialization of KeyframesRule is not specced.
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@keyframes ")?;
self.name.to_css(dest)?;
dest.write_str(" {")?;
let iter = self.keyframes.iter();
for lock in iter {
dest.write_str("\n")?;
let keyframe = lock.read_with(&guard);
keyframe.to_css(guard, dest)?;
}
dest.write_str("\n}")
}
}
impl KeyframesRule {
/// Returns the index of the last keyframe that matches the given selector.
/// If the selector is not valid, or no keyframe is found, returns None.
///
/// Related spec:
/// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule
pub fn find_rule(&self, guard: &SharedRwLockReadGuard, selector: &str) -> Option<usize> {
let mut input = ParserInput::new(selector);
if let Ok(selector) = Parser::new(&mut input).parse_entirely(KeyframeSelector::parse) {
for (i, keyframe) in self.keyframes.iter().enumerate().rev() {
if keyframe.read_with(guard).selector == selector {
return Some(i);
}
}
}
None
}
}
impl DeepCloneWithLock for KeyframesRule {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
KeyframesRule {
name: self.name.clone(),
keyframes: self.keyframes.iter()
.map(|x| {
Arc::new(lock.wrap(
x.read_with(guard).deep_clone_with_lock(lock, guard, params)
))
})
.collect(),
vendor_prefix: self.vendor_prefix.clone(),
source_location: self.source_location.clone(),
}
}
}
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
serialize_percentage(self.0, dest)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentage, ParseError<'i>> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = input.expect_percentage()?;
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(StyleParseError::UnspecifiedError.into());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl ToCss for KeyframeSelector {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?;
for percentage in iter {
dest.write_str(", ")?;
percentage.to_css(dest)?;
}
Ok(())
}
}
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
self.selector.to_css(dest)?;
dest.write_str(" { ")?;
self.block.read_with(guard).to_css(dest)?;
dest.write_str(" }")?;
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse<'i>(
css: &'i str,
parent_stylesheet_contents: &StylesheetContents,
lock: &SharedRwLock,
) -> Result<Arc<Locked<Self>>, ParseError<'i>> {
let url_data = parent_stylesheet_contents.url_data.read();
let error_reporter = NullReporter;
let namespaces = parent_stylesheet_contents.namespaces.read();
let mut context = ParserContext::new(
parent_stylesheet_contents.origin,
&url_data,
Some(CssRuleType::Keyframe),
PARSING_MODE_DEFAULT,
parent_stylesheet_contents.quirks_mode
);
let error_context = ParserErrorContext { error_reporter: &error_reporter };
context.namespaces = Some(&*namespaces);
let mut input = ParserInput::new(css);
let mut input = Parser::new(&mut input);
let mut declarations = SourcePropertyDeclaration::new();
let mut rule_parser = KeyframeListParser {
context: &context,
error_context: &error_context,
shared_lock: &lock,
declarations: &mut declarations,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
impl DeepCloneWithLock for Keyframe {
/// Deep clones this Keyframe.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
_params: &DeepCloneParams,
) -> Keyframe {
Keyframe {
selector: self.selector.clone(),
block: Arc::new(lock.wrap(self.block.read_with(guard).clone())),
source_location: self.source_location.clone(),
}
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "gecko",
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile")]
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
|
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|prop_decl| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let (declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<AnimatableLonghand>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<AnimatableLonghand> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for (declaration, importance) in block.declaration_importance_iter() {
assert!(!importance.important());
if let Some(property) = AnimatableLonghand::from_declaration(declaration) {
// Skip the 'display' property because although it is animatable from SMIL,
// it should not be animatable from CSS Animations or Web Animations.
if property!= AnimatableLonghand::Display &&
!seen.has_animatable_longhand_bit(&property) {
seen.set_animatable_longhand_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
/// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a, R: 'a> {
context: &'a ParserContext<'a>,
error_context: &'a ParserErrorContext<'a, R>,
shared_lock: &'a SharedRwLock,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list<R>(
context: &ParserContext,
error_context: &ParserErrorContext<R>,
input: &mut Parser,
shared_lock: &SharedRwLock
) -> Vec<Arc<Locked<Keyframe>>>
where R: ParseErrorReporter
{
debug_assert!(context.namespaces.is_some(),
"Parsing a keyframe list from a context without namespaces?");
let mut declarations = SourcePropertyDeclaration::new();
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
error_context: error_context,
shared_lock: shared_lock,
declarations: &mut declarations,
}).filter_map(Result::ok).collect()
}
impl<'a, 'i, R> AtRuleParser<'i> for KeyframeListParser<'a, R> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
}
/// A wrapper to wraps the KeyframeSelector with its source location
struct KeyframeSelectorParserPrelude {
selector: KeyframeSelector,
source_location: SourceLocation,
}
impl<'a, 'i, R: ParseErrorReporter> QualifiedRuleParser<'i> for KeyframeListParser<'a, R> {
type Prelude = KeyframeSelectorParserPrelude;
type QualifiedRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_prelude<'t>(&mut self, input: &mut Parser<'i, 't>) -> Result<Self::Prelude, ParseError<'i>> {
let start_position = input.position();
let start_location = input.current_source_location();
match KeyframeSelector::parse(input) {
Ok(sel) => {
Ok(KeyframeSelectorParserPrelude {
selector: sel,
source_location: start_location,
})
},
Err(e) => {
let error = ContextualParseError::InvalidKeyframeRule(input.slice_from(start_position), e.clone());
self.context.log_css_error(self.error_context, start_location, error);
Err(e)
}
}
}
fn parse_block<'t>(&mut self, prelude: Self::Prelude, input: &mut Parser<'i, 't>)
-> Result<Self::QualifiedRule, ParseError<'i>> {
let context =
ParserContext::new_with_rule_type(
self.context,
CssRuleType::Keyframe,
self.context.namespaces.unwrap(),
);
let parser = KeyframeDeclarationParser {
context: &context,
declarations: self.declarations,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) => {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
}
Err(err) => {
iter.parser.declarations.clear();
let error = ContextualParseError::UnsupportedKeyframePropertyDeclaration(err.slice, err.error);
context.log_css_error(self.error_context, err.location, error);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude.selector,
block: Arc::new(self.shared_lock.wrap(block)),
source_location: prelude.source_location,
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
|
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
|
random_line_split
|
keyframes_rule.rs
|
::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use style_traits::{PARSING_MODE_DEFAULT, ToCss, ParseError, StyleParseError};
use style_traits::PropertyDeclarationParseError;
use stylesheets::{CssRuleType, StylesheetContents};
use stylesheets::rule_parser::VendorPrefix;
use values::{KeyframesName, serialize_percentage};
/// A [`@keyframes`][keyframes] rule.
///
/// [keyframes]: https://drafts.csswg.org/css-animations/#keyframes
#[derive(Debug)]
pub struct KeyframesRule {
/// The name of the current animation.
pub name: KeyframesName,
/// The keyframes specified for this CSS rule.
pub keyframes: Vec<Arc<Locked<Keyframe>>>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for KeyframesRule {
// Serialization of KeyframesRule is not specced.
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@keyframes ")?;
self.name.to_css(dest)?;
dest.write_str(" {")?;
let iter = self.keyframes.iter();
for lock in iter {
dest.write_str("\n")?;
let keyframe = lock.read_with(&guard);
keyframe.to_css(guard, dest)?;
}
dest.write_str("\n}")
}
}
impl KeyframesRule {
/// Returns the index of the last keyframe that matches the given selector.
/// If the selector is not valid, or no keyframe is found, returns None.
///
/// Related spec:
/// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule
pub fn find_rule(&self, guard: &SharedRwLockReadGuard, selector: &str) -> Option<usize> {
let mut input = ParserInput::new(selector);
if let Ok(selector) = Parser::new(&mut input).parse_entirely(KeyframeSelector::parse) {
for (i, keyframe) in self.keyframes.iter().enumerate().rev() {
if keyframe.read_with(guard).selector == selector {
return Some(i);
}
}
}
None
}
}
impl DeepCloneWithLock for KeyframesRule {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
KeyframesRule {
name: self.name.clone(),
keyframes: self.keyframes.iter()
.map(|x| {
Arc::new(lock.wrap(
x.read_with(guard).deep_clone_with_lock(lock, guard, params)
))
})
.collect(),
vendor_prefix: self.vendor_prefix.clone(),
source_location: self.source_location.clone(),
}
}
}
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
serialize_percentage(self.0, dest)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentage, ParseError<'i>> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = input.expect_percentage()?;
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(StyleParseError::UnspecifiedError.into());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl ToCss for KeyframeSelector {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?;
for percentage in iter {
dest.write_str(", ")?;
percentage.to_css(dest)?;
}
Ok(())
}
}
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn
|
(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
self.selector.to_css(dest)?;
dest.write_str(" { ")?;
self.block.read_with(guard).to_css(dest)?;
dest.write_str(" }")?;
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse<'i>(
css: &'i str,
parent_stylesheet_contents: &StylesheetContents,
lock: &SharedRwLock,
) -> Result<Arc<Locked<Self>>, ParseError<'i>> {
let url_data = parent_stylesheet_contents.url_data.read();
let error_reporter = NullReporter;
let namespaces = parent_stylesheet_contents.namespaces.read();
let mut context = ParserContext::new(
parent_stylesheet_contents.origin,
&url_data,
Some(CssRuleType::Keyframe),
PARSING_MODE_DEFAULT,
parent_stylesheet_contents.quirks_mode
);
let error_context = ParserErrorContext { error_reporter: &error_reporter };
context.namespaces = Some(&*namespaces);
let mut input = ParserInput::new(css);
let mut input = Parser::new(&mut input);
let mut declarations = SourcePropertyDeclaration::new();
let mut rule_parser = KeyframeListParser {
context: &context,
error_context: &error_context,
shared_lock: &lock,
declarations: &mut declarations,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
impl DeepCloneWithLock for Keyframe {
/// Deep clones this Keyframe.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
_params: &DeepCloneParams,
) -> Keyframe {
Keyframe {
selector: self.selector.clone(),
block: Arc::new(lock.wrap(self.block.read_with(guard).clone())),
source_location: self.source_location.clone(),
}
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "gecko",
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile")]
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|prop_decl| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let (declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<AnimatableLonghand>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<AnimatableLonghand> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for (declaration, importance) in block.declaration_importance_iter() {
assert!(!importance.important());
if let Some(property) = AnimatableLonghand::from_declaration(declaration) {
// Skip the 'display' property because although it is animatable from SMIL,
// it should not be animatable from CSS Animations or Web Animations.
if property!= AnimatableLonghand::Display &&
!seen.has_animatable_longhand_bit(&property) {
seen.set_animatable_longhand_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
/// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a, R: 'a> {
context: &'a ParserContext<'a>,
error_context: &'a ParserErrorContext<'a, R>,
shared_lock: &'a SharedRwLock,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list<R>(
context: &ParserContext,
error_context: &ParserErrorContext<R>,
input: &mut Parser,
shared_lock: &SharedRwLock
) -> Vec<Arc<Locked<Keyframe>>>
where R: ParseErrorReporter
{
debug_assert!(context.namespaces.is_some(),
"Parsing a keyframe list from a context without namespaces?");
let mut declarations = SourcePropertyDeclaration::new();
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
error_context: error_context,
shared_lock: shared_lock,
declarations: &mut declarations,
}).filter_map(Result::ok).collect()
}
impl<'a, 'i, R> AtRuleParser<'i> for KeyframeListParser<'a, R> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
}
/// A wrapper to wraps the KeyframeSelector with its source location
struct KeyframeSelectorParserPrelude {
selector: KeyframeSelector,
source_location: SourceLocation,
}
impl<'a, 'i, R: ParseErrorReporter> QualifiedRuleParser<'i> for KeyframeListParser<'a, R> {
type Prelude = KeyframeSelectorParserPrelude;
type QualifiedRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_prelude<'t>(&mut self, input: &mut Parser<'i, 't>) -> Result<Self::Prelude, ParseError<'i>> {
let start_position = input.position();
let start_location = input.current_source_location();
match KeyframeSelector::parse(input) {
Ok(sel) => {
Ok(KeyframeSelectorParserPrelude {
selector: sel,
source_location: start_location,
})
},
Err(e) => {
let error = ContextualParseError::InvalidKeyframeRule(input.slice_from(start_position), e.clone());
self.context.log_css_error(self.error_context, start_location, error);
Err(e)
}
}
}
fn parse_block<'t>(&mut self, prelude: Self::Prelude, input: &mut Parser<'i, 't>)
-> Result<Self::QualifiedRule, ParseError<'i>> {
let context =
ParserContext::new_with_rule_type(
self.context,
CssRuleType::Keyframe,
self.context.namespaces.unwrap(),
);
let parser = KeyframeDeclarationParser {
context: &context,
declarations: self.declarations,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) => {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
}
Err(err) => {
iter.parser.declarations.clear();
let error = ContextualParseError::UnsupportedKeyframePropertyDeclaration(err.slice, err.error);
context.log_css_error(self.error_context, err.location, error);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude.selector,
block: Arc::new(self.shared_lock.wrap(block)),
source_location: prelude.source_location,
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
|
percentages
|
identifier_name
|
keyframes_rule.rs
|
::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use style_traits::{PARSING_MODE_DEFAULT, ToCss, ParseError, StyleParseError};
use style_traits::PropertyDeclarationParseError;
use stylesheets::{CssRuleType, StylesheetContents};
use stylesheets::rule_parser::VendorPrefix;
use values::{KeyframesName, serialize_percentage};
/// A [`@keyframes`][keyframes] rule.
///
/// [keyframes]: https://drafts.csswg.org/css-animations/#keyframes
#[derive(Debug)]
pub struct KeyframesRule {
/// The name of the current animation.
pub name: KeyframesName,
/// The keyframes specified for this CSS rule.
pub keyframes: Vec<Arc<Locked<Keyframe>>>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for KeyframesRule {
// Serialization of KeyframesRule is not specced.
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@keyframes ")?;
self.name.to_css(dest)?;
dest.write_str(" {")?;
let iter = self.keyframes.iter();
for lock in iter {
dest.write_str("\n")?;
let keyframe = lock.read_with(&guard);
keyframe.to_css(guard, dest)?;
}
dest.write_str("\n}")
}
}
impl KeyframesRule {
/// Returns the index of the last keyframe that matches the given selector.
/// If the selector is not valid, or no keyframe is found, returns None.
///
/// Related spec:
/// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule
pub fn find_rule(&self, guard: &SharedRwLockReadGuard, selector: &str) -> Option<usize> {
let mut input = ParserInput::new(selector);
if let Ok(selector) = Parser::new(&mut input).parse_entirely(KeyframeSelector::parse) {
for (i, keyframe) in self.keyframes.iter().enumerate().rev() {
if keyframe.read_with(guard).selector == selector {
return Some(i);
}
}
}
None
}
}
impl DeepCloneWithLock for KeyframesRule {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
KeyframesRule {
name: self.name.clone(),
keyframes: self.keyframes.iter()
.map(|x| {
Arc::new(lock.wrap(
x.read_with(guard).deep_clone_with_lock(lock, guard, params)
))
})
.collect(),
vendor_prefix: self.vendor_prefix.clone(),
source_location: self.source_location.clone(),
}
}
}
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
serialize_percentage(self.0, dest)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentage, ParseError<'i>> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = input.expect_percentage()?;
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(StyleParseError::UnspecifiedError.into());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl ToCss for KeyframeSelector {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?;
for percentage in iter {
dest.write_str(", ")?;
percentage.to_css(dest)?;
}
Ok(())
}
}
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
self.selector.to_css(dest)?;
dest.write_str(" { ")?;
self.block.read_with(guard).to_css(dest)?;
dest.write_str(" }")?;
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse<'i>(
css: &'i str,
parent_stylesheet_contents: &StylesheetContents,
lock: &SharedRwLock,
) -> Result<Arc<Locked<Self>>, ParseError<'i>> {
let url_data = parent_stylesheet_contents.url_data.read();
let error_reporter = NullReporter;
let namespaces = parent_stylesheet_contents.namespaces.read();
let mut context = ParserContext::new(
parent_stylesheet_contents.origin,
&url_data,
Some(CssRuleType::Keyframe),
PARSING_MODE_DEFAULT,
parent_stylesheet_contents.quirks_mode
);
let error_context = ParserErrorContext { error_reporter: &error_reporter };
context.namespaces = Some(&*namespaces);
let mut input = ParserInput::new(css);
let mut input = Parser::new(&mut input);
let mut declarations = SourcePropertyDeclaration::new();
let mut rule_parser = KeyframeListParser {
context: &context,
error_context: &error_context,
shared_lock: &lock,
declarations: &mut declarations,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
impl DeepCloneWithLock for Keyframe {
/// Deep clones this Keyframe.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
_params: &DeepCloneParams,
) -> Keyframe {
Keyframe {
selector: self.selector.clone(),
block: Arc::new(lock.wrap(self.block.read_with(guard).clone())),
source_location: self.source_location.clone(),
}
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "gecko",
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile")]
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|prop_decl| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let (declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<AnimatableLonghand>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<AnimatableLonghand> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for (declaration, importance) in block.declaration_importance_iter() {
assert!(!importance.important());
if let Some(property) = AnimatableLonghand::from_declaration(declaration) {
// Skip the 'display' property because although it is animatable from SMIL,
// it should not be animatable from CSS Animations or Web Animations.
if property!= AnimatableLonghand::Display &&
!seen.has_animatable_longhand_bit(&property) {
seen.set_animatable_longhand_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
/// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a, R: 'a> {
context: &'a ParserContext<'a>,
error_context: &'a ParserErrorContext<'a, R>,
shared_lock: &'a SharedRwLock,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list<R>(
context: &ParserContext,
error_context: &ParserErrorContext<R>,
input: &mut Parser,
shared_lock: &SharedRwLock
) -> Vec<Arc<Locked<Keyframe>>>
where R: ParseErrorReporter
{
debug_assert!(context.namespaces.is_some(),
"Parsing a keyframe list from a context without namespaces?");
let mut declarations = SourcePropertyDeclaration::new();
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
error_context: error_context,
shared_lock: shared_lock,
declarations: &mut declarations,
}).filter_map(Result::ok).collect()
}
impl<'a, 'i, R> AtRuleParser<'i> for KeyframeListParser<'a, R> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
}
/// A wrapper to wraps the KeyframeSelector with its source location
struct KeyframeSelectorParserPrelude {
selector: KeyframeSelector,
source_location: SourceLocation,
}
impl<'a, 'i, R: ParseErrorReporter> QualifiedRuleParser<'i> for KeyframeListParser<'a, R> {
type Prelude = KeyframeSelectorParserPrelude;
type QualifiedRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_prelude<'t>(&mut self, input: &mut Parser<'i, 't>) -> Result<Self::Prelude, ParseError<'i>> {
let start_position = input.position();
let start_location = input.current_source_location();
match KeyframeSelector::parse(input) {
Ok(sel) => {
Ok(KeyframeSelectorParserPrelude {
selector: sel,
source_location: start_location,
})
},
Err(e) => {
let error = ContextualParseError::InvalidKeyframeRule(input.slice_from(start_position), e.clone());
self.context.log_css_error(self.error_context, start_location, error);
Err(e)
}
}
}
fn parse_block<'t>(&mut self, prelude: Self::Prelude, input: &mut Parser<'i, 't>)
-> Result<Self::QualifiedRule, ParseError<'i>> {
let context =
ParserContext::new_with_rule_type(
self.context,
CssRuleType::Keyframe,
self.context.namespaces.unwrap(),
);
let parser = KeyframeDeclarationParser {
context: &context,
declarations: self.declarations,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) =>
|
Err(err) => {
iter.parser.declarations.clear();
let error = ContextualParseError::UnsupportedKeyframePropertyDeclaration(err.slice, err.error);
context.log_css_error(self.error_context, err.location, error);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude.selector,
block: Arc::new(self.shared_lock.wrap(block)),
source_location: prelude.source_location,
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
|
{
block.extend(iter.parser.declarations.drain(), Importance::Normal);
}
|
conditional_block
|
keyframes_rule.rs
|
::AnimatableLonghand;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use style_traits::{PARSING_MODE_DEFAULT, ToCss, ParseError, StyleParseError};
use style_traits::PropertyDeclarationParseError;
use stylesheets::{CssRuleType, StylesheetContents};
use stylesheets::rule_parser::VendorPrefix;
use values::{KeyframesName, serialize_percentage};
/// A [`@keyframes`][keyframes] rule.
///
/// [keyframes]: https://drafts.csswg.org/css-animations/#keyframes
#[derive(Debug)]
pub struct KeyframesRule {
/// The name of the current animation.
pub name: KeyframesName,
/// The keyframes specified for this CSS rule.
pub keyframes: Vec<Arc<Locked<Keyframe>>>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for KeyframesRule {
// Serialization of KeyframesRule is not specced.
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
dest.write_str("@keyframes ")?;
self.name.to_css(dest)?;
dest.write_str(" {")?;
let iter = self.keyframes.iter();
for lock in iter {
dest.write_str("\n")?;
let keyframe = lock.read_with(&guard);
keyframe.to_css(guard, dest)?;
}
dest.write_str("\n}")
}
}
impl KeyframesRule {
/// Returns the index of the last keyframe that matches the given selector.
/// If the selector is not valid, or no keyframe is found, returns None.
///
/// Related spec:
/// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule
pub fn find_rule(&self, guard: &SharedRwLockReadGuard, selector: &str) -> Option<usize> {
let mut input = ParserInput::new(selector);
if let Ok(selector) = Parser::new(&mut input).parse_entirely(KeyframeSelector::parse) {
for (i, keyframe) in self.keyframes.iter().enumerate().rev() {
if keyframe.read_with(guard).selector == selector {
return Some(i);
}
}
}
None
}
}
impl DeepCloneWithLock for KeyframesRule {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
KeyframesRule {
name: self.name.clone(),
keyframes: self.keyframes.iter()
.map(|x| {
Arc::new(lock.wrap(
x.read_with(guard).deep_clone_with_lock(lock, guard, params)
))
})
.collect(),
vendor_prefix: self.vendor_prefix.clone(),
source_location: self.source_location.clone(),
}
}
}
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write
|
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentage, ParseError<'i>> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = input.expect_percentage()?;
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(StyleParseError::UnspecifiedError.into());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl ToCss for KeyframeSelector {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
iter.next().unwrap().to_css(dest)?;
for percentage in iter {
dest.write_str(", ")?;
percentage.to_css(dest)?;
}
Ok(())
}
}
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
self.selector.to_css(dest)?;
dest.write_str(" { ")?;
self.block.read_with(guard).to_css(dest)?;
dest.write_str(" }")?;
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse<'i>(
css: &'i str,
parent_stylesheet_contents: &StylesheetContents,
lock: &SharedRwLock,
) -> Result<Arc<Locked<Self>>, ParseError<'i>> {
let url_data = parent_stylesheet_contents.url_data.read();
let error_reporter = NullReporter;
let namespaces = parent_stylesheet_contents.namespaces.read();
let mut context = ParserContext::new(
parent_stylesheet_contents.origin,
&url_data,
Some(CssRuleType::Keyframe),
PARSING_MODE_DEFAULT,
parent_stylesheet_contents.quirks_mode
);
let error_context = ParserErrorContext { error_reporter: &error_reporter };
context.namespaces = Some(&*namespaces);
let mut input = ParserInput::new(css);
let mut input = Parser::new(&mut input);
let mut declarations = SourcePropertyDeclaration::new();
let mut rule_parser = KeyframeListParser {
context: &context,
error_context: &error_context,
shared_lock: &lock,
declarations: &mut declarations,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
impl DeepCloneWithLock for Keyframe {
/// Deep clones this Keyframe.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
_params: &DeepCloneParams,
) -> Keyframe {
Keyframe {
selector: self.selector.clone(),
block: Arc::new(lock.wrap(self.block.read_with(guard).clone())),
source_location: self.source_location.clone(),
}
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "gecko",
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile")]
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|prop_decl| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let (declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<AnimatableLonghand>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<AnimatableLonghand> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for (declaration, importance) in block.declaration_importance_iter() {
assert!(!importance.important());
if let Some(property) = AnimatableLonghand::from_declaration(declaration) {
// Skip the 'display' property because although it is animatable from SMIL,
// it should not be animatable from CSS Animations or Web Animations.
if property!= AnimatableLonghand::Display &&
!seen.has_animatable_longhand_bit(&property) {
seen.set_animatable_longhand_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
/// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a, R: 'a> {
context: &'a ParserContext<'a>,
error_context: &'a ParserErrorContext<'a, R>,
shared_lock: &'a SharedRwLock,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list<R>(
context: &ParserContext,
error_context: &ParserErrorContext<R>,
input: &mut Parser,
shared_lock: &SharedRwLock
) -> Vec<Arc<Locked<Keyframe>>>
where R: ParseErrorReporter
{
debug_assert!(context.namespaces.is_some(),
"Parsing a keyframe list from a context without namespaces?");
let mut declarations = SourcePropertyDeclaration::new();
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
error_context: error_context,
shared_lock: shared_lock,
declarations: &mut declarations,
}).filter_map(Result::ok).collect()
}
impl<'a, 'i, R> AtRuleParser<'i> for KeyframeListParser<'a, R> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
}
/// A wrapper to wraps the KeyframeSelector with its source location
struct KeyframeSelectorParserPrelude {
selector: KeyframeSelector,
source_location: SourceLocation,
}
impl<'a, 'i, R: ParseErrorReporter> QualifiedRuleParser<'i> for KeyframeListParser<'a, R> {
type Prelude = KeyframeSelectorParserPrelude;
type QualifiedRule = Arc<Locked<Keyframe>>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_prelude<'t>(&mut self, input: &mut Parser<'i, 't>) -> Result<Self::Prelude, ParseError<'i>> {
let start_position = input.position();
let start_location = input.current_source_location();
match KeyframeSelector::parse(input) {
Ok(sel) => {
Ok(KeyframeSelectorParserPrelude {
selector: sel,
source_location: start_location,
})
},
Err(e) => {
let error = ContextualParseError::InvalidKeyframeRule(input.slice_from(start_position), e.clone());
self.context.log_css_error(self.error_context, start_location, error);
Err(e)
}
}
}
fn parse_block<'t>(&mut self, prelude: Self::Prelude, input: &mut Parser<'i, 't>)
-> Result<Self::QualifiedRule, ParseError<'i>> {
let context =
ParserContext::new_with_rule_type(
self.context,
CssRuleType::Keyframe,
self.context.namespaces.unwrap(),
);
let parser = KeyframeDeclarationParser {
context: &context,
declarations: self.declarations,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) => {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
}
Err(err) => {
iter.parser.declarations.clear();
let error = ContextualParseError::UnsupportedKeyframePropertyDeclaration(err.slice, err.error);
context.log_css_error(self.error_context, err.location, error);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude.selector,
block: Arc::new(self.shared_lock.wrap(block)),
source_location: prelude.source_location,
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
|
{
serialize_percentage(self.0, dest)
}
|
identifier_body
|
unit_graph.rs
|
use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct UndeclaredUnit<'a>(UnitName<'a>);
/// Attempt to insert a unit twice
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DuplicateUnit<'a>(UnitName<'a>);
#[derive(Debug, Clone)]
pub struct ConversionPath {
start: CanonicalUnit,
end: CanonicalUnit,
ratio_path: Vec<ConversionRatio>,
}
impl ConversionPath {
/// Reduces the path into the factor that transforms start to end
pub fn conversion_factor(self) -> BigDecimal {
let mut factor = BigDecimal::one();
let mut current = self.start;
for ratio in self.ratio_path {
if ratio.left.unit == current {
factor *= ratio.right.value / ratio.left.value;
current = ratio.right.unit;
}
else if ratio.right.unit == current {
factor *= ratio.left.value / ratio.right.value;
current = ratio.left.unit;
}
else {
unreachable!();
}
}
factor
}
}
#[derive(Debug, Clone)]
pub struct UnitGraph<'a> {
unit_ids: HashMap<UnitName<'a>, UnitID>,
units: Vec<(UnitName<'a>, Span<'a>)>,
graph_ids: HashMap<CanonicalUnit, NodeIndex<DefaultIx>>,
conversions: UnGraph<CanonicalUnit, ConversionRatio>,
}
impl<'a> Default for UnitGraph<'a> {
fn default() -> Self {
let mut graph = UnitGraph {
unit_ids: Default::default(),
units: Default::default(),
graph_ids: Default::default(),
conversions: Default::default(),
};
graph.insert_unit(UnitName::unitless(), Span::new(CompleteStr("")))
.unwrap_or_else(|_| unreachable!("'_ was already declared"));
graph
}
}
impl<'a> UnitGraph<'a> {
/// Returns a unit representing when a quantity is unitless
///
/// In lion programs, this is denoted '_
pub fn unitless(&self) -> UnitID {
self.unit_id(&UnitName::unitless())
.unwrap_or_else(|_| unreachable!("bug: '_ was not defined"))
}
/// Returns the unique unit ID for the given unit name.
/// Returns an Err if the name was not already a defined unit
///
/// **Note:** name must be given without "'", i.e. to lookup 'foo, use unit_id("foo")
pub fn unit_id(&self, name: &UnitName<'a>) -> Result<UnitID, UndeclaredUnit> {
self.unit_ids.get(name).cloned().ok_or_else(|| UndeclaredUnit(name.clone()))
}
/// Returns the unit name for the given unit ID
///
/// # Panics
///
/// Panics if the unit ID was not declared since that should not be possible
pub fn unit_name(&self, unit: UnitID) -> &UnitName<'a>
|
/// Creates the given unit if it does not exist yet
///
/// If it does exist, this function will return an error
pub fn insert_unit(&mut self, name: UnitName<'a>, span: Span<'a>) -> Result<UnitID, DuplicateUnit<'a>> {
if self.unit_ids.contains_key(&name) {
return Err(DuplicateUnit(name));
}
let id = self.unit_ids.len();
assert!(self.unit_ids.insert(name.clone(), id).is_none(),
"bug: failed to detect duplicate declaration");
self.units.push((name, span));
let node = CanonicalUnit::from(id);
let graph_id = self.conversions.add_node(node.clone());
assert!(self.graph_ids.insert(node, graph_id).is_none(),
"bug: failed to detect duplicate declaration");
Ok(id)
}
/// Adds the given conversion ratio to the graph
pub fn add_conversion(&mut self, ratio: ConversionRatio) {
let left_id = if!self.graph_ids.contains_key(&ratio.left.unit) {
self.conversions.add_node(ratio.left.unit.clone())
} else { self.graph_ids[&ratio.left.unit] };
let right_id = if!self.graph_ids.contains_key(&ratio.right.unit) {
self.conversions.add_node(ratio.right.unit.clone())
} else { self.graph_ids[&ratio.right.unit] };
self.conversions.update_edge(left_id, right_id, ratio);
}
pub fn conversion_path(&self, start_unit: &CanonicalUnit, end_unit: &CanonicalUnit) -> Option<ConversionPath> {
let start = match self.graph_ids.get(start_unit) {
Some(node) => *node,
None => return None,
};
let end = match self.graph_ids.get(end_unit) {
Some(node) => *node,
None => return None,
};
let mut queue = VecDeque::new();
queue.push_back(vec![start]);
let mut seen = HashSet::new();
let node_path = loop {
let path = match queue.pop_front() {
Some(path) => path,
None => return None, // Ran out of nodes to search
};
let node = path.last().cloned().unwrap();
if seen.contains(&node) {
continue;
}
seen.insert(node);
if node == end {
break path;
}
for adj in self.conversions.neighbors(node) {
let mut adj_path = path.clone();
adj_path.push(adj);
queue.push_back(adj_path);
}
};
let mut ratio_path = Vec::new();
let mut last = node_path[0];
for &node in &node_path[1..] {
let edge_id = self.conversions.find_edge(last, node).unwrap();
let ratio = self.conversions.edge_weight(edge_id).cloned().unwrap();
ratio_path.push(ratio);
last = node;
}
Some(ConversionPath {start: start_unit.clone(), end: end_unit.clone(), ratio_path})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unitless_exists() {
let units = UnitGraph::default();
// Test to make sure that if we lookup unitless from elsewhere in the AST we get the same
// value back as calling units.unitless()
assert_eq!(units.unitless(), units.unit_id(&UnitName::unitless()).unwrap());
// Check that the unit name of the return value of units.unitless() is unitless
assert_eq!(units.unit_name(units.unitless()), &UnitName::unitless());
}
}
|
{
match self.units.get(unit) {
Some(&(ref name, _)) => name,
None => unreachable!("Looked up an ID that did not exist"),
}
}
|
identifier_body
|
unit_graph.rs
|
use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct UndeclaredUnit<'a>(UnitName<'a>);
/// Attempt to insert a unit twice
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DuplicateUnit<'a>(UnitName<'a>);
#[derive(Debug, Clone)]
pub struct ConversionPath {
start: CanonicalUnit,
end: CanonicalUnit,
ratio_path: Vec<ConversionRatio>,
}
impl ConversionPath {
/// Reduces the path into the factor that transforms start to end
pub fn conversion_factor(self) -> BigDecimal {
let mut factor = BigDecimal::one();
let mut current = self.start;
for ratio in self.ratio_path {
if ratio.left.unit == current {
factor *= ratio.right.value / ratio.left.value;
current = ratio.right.unit;
}
else if ratio.right.unit == current {
factor *= ratio.left.value / ratio.right.value;
current = ratio.left.unit;
}
else {
unreachable!();
}
}
factor
}
}
#[derive(Debug, Clone)]
pub struct UnitGraph<'a> {
unit_ids: HashMap<UnitName<'a>, UnitID>,
units: Vec<(UnitName<'a>, Span<'a>)>,
graph_ids: HashMap<CanonicalUnit, NodeIndex<DefaultIx>>,
conversions: UnGraph<CanonicalUnit, ConversionRatio>,
}
impl<'a> Default for UnitGraph<'a> {
fn default() -> Self {
let mut graph = UnitGraph {
unit_ids: Default::default(),
units: Default::default(),
graph_ids: Default::default(),
conversions: Default::default(),
};
graph.insert_unit(UnitName::unitless(), Span::new(CompleteStr("")))
.unwrap_or_else(|_| unreachable!("'_ was already declared"));
graph
}
}
impl<'a> UnitGraph<'a> {
/// Returns a unit representing when a quantity is unitless
///
/// In lion programs, this is denoted '_
pub fn unitless(&self) -> UnitID {
self.unit_id(&UnitName::unitless())
.unwrap_or_else(|_| unreachable!("bug: '_ was not defined"))
}
/// Returns the unique unit ID for the given unit name.
/// Returns an Err if the name was not already a defined unit
///
/// **Note:** name must be given without "'", i.e. to lookup 'foo, use unit_id("foo")
pub fn unit_id(&self, name: &UnitName<'a>) -> Result<UnitID, UndeclaredUnit> {
self.unit_ids.get(name).cloned().ok_or_else(|| UndeclaredUnit(name.clone()))
}
/// Returns the unit name for the given unit ID
///
/// # Panics
///
/// Panics if the unit ID was not declared since that should not be possible
pub fn unit_name(&self, unit: UnitID) -> &UnitName<'a> {
match self.units.get(unit) {
Some(&(ref name, _)) => name,
None => unreachable!("Looked up an ID that did not exist"),
}
}
/// Creates the given unit if it does not exist yet
///
/// If it does exist, this function will return an error
pub fn insert_unit(&mut self, name: UnitName<'a>, span: Span<'a>) -> Result<UnitID, DuplicateUnit<'a>> {
if self.unit_ids.contains_key(&name) {
return Err(DuplicateUnit(name));
}
let id = self.unit_ids.len();
assert!(self.unit_ids.insert(name.clone(), id).is_none(),
|
let node = CanonicalUnit::from(id);
let graph_id = self.conversions.add_node(node.clone());
assert!(self.graph_ids.insert(node, graph_id).is_none(),
"bug: failed to detect duplicate declaration");
Ok(id)
}
/// Adds the given conversion ratio to the graph
pub fn add_conversion(&mut self, ratio: ConversionRatio) {
let left_id = if!self.graph_ids.contains_key(&ratio.left.unit) {
self.conversions.add_node(ratio.left.unit.clone())
} else { self.graph_ids[&ratio.left.unit] };
let right_id = if!self.graph_ids.contains_key(&ratio.right.unit) {
self.conversions.add_node(ratio.right.unit.clone())
} else { self.graph_ids[&ratio.right.unit] };
self.conversions.update_edge(left_id, right_id, ratio);
}
pub fn conversion_path(&self, start_unit: &CanonicalUnit, end_unit: &CanonicalUnit) -> Option<ConversionPath> {
let start = match self.graph_ids.get(start_unit) {
Some(node) => *node,
None => return None,
};
let end = match self.graph_ids.get(end_unit) {
Some(node) => *node,
None => return None,
};
let mut queue = VecDeque::new();
queue.push_back(vec![start]);
let mut seen = HashSet::new();
let node_path = loop {
let path = match queue.pop_front() {
Some(path) => path,
None => return None, // Ran out of nodes to search
};
let node = path.last().cloned().unwrap();
if seen.contains(&node) {
continue;
}
seen.insert(node);
if node == end {
break path;
}
for adj in self.conversions.neighbors(node) {
let mut adj_path = path.clone();
adj_path.push(adj);
queue.push_back(adj_path);
}
};
let mut ratio_path = Vec::new();
let mut last = node_path[0];
for &node in &node_path[1..] {
let edge_id = self.conversions.find_edge(last, node).unwrap();
let ratio = self.conversions.edge_weight(edge_id).cloned().unwrap();
ratio_path.push(ratio);
last = node;
}
Some(ConversionPath {start: start_unit.clone(), end: end_unit.clone(), ratio_path})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unitless_exists() {
let units = UnitGraph::default();
// Test to make sure that if we lookup unitless from elsewhere in the AST we get the same
// value back as calling units.unitless()
assert_eq!(units.unitless(), units.unit_id(&UnitName::unitless()).unwrap());
// Check that the unit name of the return value of units.unitless() is unitless
assert_eq!(units.unit_name(units.unitless()), &UnitName::unitless());
}
}
|
"bug: failed to detect duplicate declaration");
self.units.push((name, span));
|
random_line_split
|
unit_graph.rs
|
use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct UndeclaredUnit<'a>(UnitName<'a>);
/// Attempt to insert a unit twice
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DuplicateUnit<'a>(UnitName<'a>);
#[derive(Debug, Clone)]
pub struct ConversionPath {
start: CanonicalUnit,
end: CanonicalUnit,
ratio_path: Vec<ConversionRatio>,
}
impl ConversionPath {
/// Reduces the path into the factor that transforms start to end
pub fn conversion_factor(self) -> BigDecimal {
let mut factor = BigDecimal::one();
let mut current = self.start;
for ratio in self.ratio_path {
if ratio.left.unit == current {
factor *= ratio.right.value / ratio.left.value;
current = ratio.right.unit;
}
else if ratio.right.unit == current
|
else {
unreachable!();
}
}
factor
}
}
#[derive(Debug, Clone)]
pub struct UnitGraph<'a> {
unit_ids: HashMap<UnitName<'a>, UnitID>,
units: Vec<(UnitName<'a>, Span<'a>)>,
graph_ids: HashMap<CanonicalUnit, NodeIndex<DefaultIx>>,
conversions: UnGraph<CanonicalUnit, ConversionRatio>,
}
impl<'a> Default for UnitGraph<'a> {
fn default() -> Self {
let mut graph = UnitGraph {
unit_ids: Default::default(),
units: Default::default(),
graph_ids: Default::default(),
conversions: Default::default(),
};
graph.insert_unit(UnitName::unitless(), Span::new(CompleteStr("")))
.unwrap_or_else(|_| unreachable!("'_ was already declared"));
graph
}
}
impl<'a> UnitGraph<'a> {
/// Returns a unit representing when a quantity is unitless
///
/// In lion programs, this is denoted '_
pub fn unitless(&self) -> UnitID {
self.unit_id(&UnitName::unitless())
.unwrap_or_else(|_| unreachable!("bug: '_ was not defined"))
}
/// Returns the unique unit ID for the given unit name.
/// Returns an Err if the name was not already a defined unit
///
/// **Note:** name must be given without "'", i.e. to lookup 'foo, use unit_id("foo")
pub fn unit_id(&self, name: &UnitName<'a>) -> Result<UnitID, UndeclaredUnit> {
self.unit_ids.get(name).cloned().ok_or_else(|| UndeclaredUnit(name.clone()))
}
/// Returns the unit name for the given unit ID
///
/// # Panics
///
/// Panics if the unit ID was not declared since that should not be possible
pub fn unit_name(&self, unit: UnitID) -> &UnitName<'a> {
match self.units.get(unit) {
Some(&(ref name, _)) => name,
None => unreachable!("Looked up an ID that did not exist"),
}
}
/// Creates the given unit if it does not exist yet
///
/// If it does exist, this function will return an error
pub fn insert_unit(&mut self, name: UnitName<'a>, span: Span<'a>) -> Result<UnitID, DuplicateUnit<'a>> {
if self.unit_ids.contains_key(&name) {
return Err(DuplicateUnit(name));
}
let id = self.unit_ids.len();
assert!(self.unit_ids.insert(name.clone(), id).is_none(),
"bug: failed to detect duplicate declaration");
self.units.push((name, span));
let node = CanonicalUnit::from(id);
let graph_id = self.conversions.add_node(node.clone());
assert!(self.graph_ids.insert(node, graph_id).is_none(),
"bug: failed to detect duplicate declaration");
Ok(id)
}
/// Adds the given conversion ratio to the graph
pub fn add_conversion(&mut self, ratio: ConversionRatio) {
let left_id = if!self.graph_ids.contains_key(&ratio.left.unit) {
self.conversions.add_node(ratio.left.unit.clone())
} else { self.graph_ids[&ratio.left.unit] };
let right_id = if!self.graph_ids.contains_key(&ratio.right.unit) {
self.conversions.add_node(ratio.right.unit.clone())
} else { self.graph_ids[&ratio.right.unit] };
self.conversions.update_edge(left_id, right_id, ratio);
}
pub fn conversion_path(&self, start_unit: &CanonicalUnit, end_unit: &CanonicalUnit) -> Option<ConversionPath> {
let start = match self.graph_ids.get(start_unit) {
Some(node) => *node,
None => return None,
};
let end = match self.graph_ids.get(end_unit) {
Some(node) => *node,
None => return None,
};
let mut queue = VecDeque::new();
queue.push_back(vec![start]);
let mut seen = HashSet::new();
let node_path = loop {
let path = match queue.pop_front() {
Some(path) => path,
None => return None, // Ran out of nodes to search
};
let node = path.last().cloned().unwrap();
if seen.contains(&node) {
continue;
}
seen.insert(node);
if node == end {
break path;
}
for adj in self.conversions.neighbors(node) {
let mut adj_path = path.clone();
adj_path.push(adj);
queue.push_back(adj_path);
}
};
let mut ratio_path = Vec::new();
let mut last = node_path[0];
for &node in &node_path[1..] {
let edge_id = self.conversions.find_edge(last, node).unwrap();
let ratio = self.conversions.edge_weight(edge_id).cloned().unwrap();
ratio_path.push(ratio);
last = node;
}
Some(ConversionPath {start: start_unit.clone(), end: end_unit.clone(), ratio_path})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unitless_exists() {
let units = UnitGraph::default();
// Test to make sure that if we lookup unitless from elsewhere in the AST we get the same
// value back as calling units.unitless()
assert_eq!(units.unitless(), units.unit_id(&UnitName::unitless()).unwrap());
// Check that the unit name of the return value of units.unitless() is unitless
assert_eq!(units.unit_name(units.unitless()), &UnitName::unitless());
}
}
|
{
factor *= ratio.left.value / ratio.right.value;
current = ratio.left.unit;
}
|
conditional_block
|
unit_graph.rs
|
use std::collections::{HashMap, VecDeque, HashSet};
use nom::types::CompleteStr;
use petgraph::graph::{UnGraph, NodeIndex, DefaultIx};
use bigdecimal::BigDecimal;
use num_traits::One;
use crate::canonical::CanonicalUnit;
use crate::ast::*;
use crate::ir::ConversionRatio;
pub type UnitID = usize;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct UndeclaredUnit<'a>(UnitName<'a>);
/// Attempt to insert a unit twice
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DuplicateUnit<'a>(UnitName<'a>);
#[derive(Debug, Clone)]
pub struct
|
{
start: CanonicalUnit,
end: CanonicalUnit,
ratio_path: Vec<ConversionRatio>,
}
impl ConversionPath {
/// Reduces the path into the factor that transforms start to end
pub fn conversion_factor(self) -> BigDecimal {
let mut factor = BigDecimal::one();
let mut current = self.start;
for ratio in self.ratio_path {
if ratio.left.unit == current {
factor *= ratio.right.value / ratio.left.value;
current = ratio.right.unit;
}
else if ratio.right.unit == current {
factor *= ratio.left.value / ratio.right.value;
current = ratio.left.unit;
}
else {
unreachable!();
}
}
factor
}
}
#[derive(Debug, Clone)]
pub struct UnitGraph<'a> {
unit_ids: HashMap<UnitName<'a>, UnitID>,
units: Vec<(UnitName<'a>, Span<'a>)>,
graph_ids: HashMap<CanonicalUnit, NodeIndex<DefaultIx>>,
conversions: UnGraph<CanonicalUnit, ConversionRatio>,
}
impl<'a> Default for UnitGraph<'a> {
fn default() -> Self {
let mut graph = UnitGraph {
unit_ids: Default::default(),
units: Default::default(),
graph_ids: Default::default(),
conversions: Default::default(),
};
graph.insert_unit(UnitName::unitless(), Span::new(CompleteStr("")))
.unwrap_or_else(|_| unreachable!("'_ was already declared"));
graph
}
}
impl<'a> UnitGraph<'a> {
/// Returns a unit representing when a quantity is unitless
///
/// In lion programs, this is denoted '_
pub fn unitless(&self) -> UnitID {
self.unit_id(&UnitName::unitless())
.unwrap_or_else(|_| unreachable!("bug: '_ was not defined"))
}
/// Returns the unique unit ID for the given unit name.
/// Returns an Err if the name was not already a defined unit
///
/// **Note:** name must be given without "'", i.e. to lookup 'foo, use unit_id("foo")
pub fn unit_id(&self, name: &UnitName<'a>) -> Result<UnitID, UndeclaredUnit> {
self.unit_ids.get(name).cloned().ok_or_else(|| UndeclaredUnit(name.clone()))
}
/// Returns the unit name for the given unit ID
///
/// # Panics
///
/// Panics if the unit ID was not declared since that should not be possible
pub fn unit_name(&self, unit: UnitID) -> &UnitName<'a> {
match self.units.get(unit) {
Some(&(ref name, _)) => name,
None => unreachable!("Looked up an ID that did not exist"),
}
}
/// Creates the given unit if it does not exist yet
///
/// If it does exist, this function will return an error
pub fn insert_unit(&mut self, name: UnitName<'a>, span: Span<'a>) -> Result<UnitID, DuplicateUnit<'a>> {
if self.unit_ids.contains_key(&name) {
return Err(DuplicateUnit(name));
}
let id = self.unit_ids.len();
assert!(self.unit_ids.insert(name.clone(), id).is_none(),
"bug: failed to detect duplicate declaration");
self.units.push((name, span));
let node = CanonicalUnit::from(id);
let graph_id = self.conversions.add_node(node.clone());
assert!(self.graph_ids.insert(node, graph_id).is_none(),
"bug: failed to detect duplicate declaration");
Ok(id)
}
/// Adds the given conversion ratio to the graph
pub fn add_conversion(&mut self, ratio: ConversionRatio) {
let left_id = if!self.graph_ids.contains_key(&ratio.left.unit) {
self.conversions.add_node(ratio.left.unit.clone())
} else { self.graph_ids[&ratio.left.unit] };
let right_id = if!self.graph_ids.contains_key(&ratio.right.unit) {
self.conversions.add_node(ratio.right.unit.clone())
} else { self.graph_ids[&ratio.right.unit] };
self.conversions.update_edge(left_id, right_id, ratio);
}
pub fn conversion_path(&self, start_unit: &CanonicalUnit, end_unit: &CanonicalUnit) -> Option<ConversionPath> {
let start = match self.graph_ids.get(start_unit) {
Some(node) => *node,
None => return None,
};
let end = match self.graph_ids.get(end_unit) {
Some(node) => *node,
None => return None,
};
let mut queue = VecDeque::new();
queue.push_back(vec![start]);
let mut seen = HashSet::new();
let node_path = loop {
let path = match queue.pop_front() {
Some(path) => path,
None => return None, // Ran out of nodes to search
};
let node = path.last().cloned().unwrap();
if seen.contains(&node) {
continue;
}
seen.insert(node);
if node == end {
break path;
}
for adj in self.conversions.neighbors(node) {
let mut adj_path = path.clone();
adj_path.push(adj);
queue.push_back(adj_path);
}
};
let mut ratio_path = Vec::new();
let mut last = node_path[0];
for &node in &node_path[1..] {
let edge_id = self.conversions.find_edge(last, node).unwrap();
let ratio = self.conversions.edge_weight(edge_id).cloned().unwrap();
ratio_path.push(ratio);
last = node;
}
Some(ConversionPath {start: start_unit.clone(), end: end_unit.clone(), ratio_path})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unitless_exists() {
let units = UnitGraph::default();
// Test to make sure that if we lookup unitless from elsewhere in the AST we get the same
// value back as calling units.unitless()
assert_eq!(units.unitless(), units.unit_id(&UnitName::unitless()).unwrap());
// Check that the unit name of the return value of units.unitless() is unitless
assert_eq!(units.unit_name(units.unitless()), &UnitName::unitless());
}
}
|
ConversionPath
|
identifier_name
|
errors.rs
|
// Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::error;
use std::error::Error as ErrorT;
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
pub enum AsciiError {
ControlChar(usize),
NonAscii(char),
}
impl error::Error for AsciiError {
fn cause(&self) -> Option<&error::Error> {
None
}
fn description(&self) -> &str
|
}
impl fmt::Display for AsciiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AsciiError::ControlChar(pos) => write!(f, "{} at position {}", self.description(), pos),
AsciiError::NonAscii(ch) => write!(f, "{} ({})", self.description(), ch),
}
}
}
|
{
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
}
|
identifier_body
|
errors.rs
|
// Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::error;
use std::error::Error as ErrorT;
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
pub enum AsciiError {
ControlChar(usize),
NonAscii(char),
}
impl error::Error for AsciiError {
fn cause(&self) -> Option<&error::Error> {
None
}
fn
|
(&self) -> &str {
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
}
}
impl fmt::Display for AsciiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AsciiError::ControlChar(pos) => write!(f, "{} at position {}", self.description(), pos),
AsciiError::NonAscii(ch) => write!(f, "{} ({})", self.description(), ch),
}
}
}
|
description
|
identifier_name
|
errors.rs
|
// Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::error;
use std::error::Error as ErrorT;
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
pub enum AsciiError {
ControlChar(usize),
NonAscii(char),
}
|
fn cause(&self) -> Option<&error::Error> {
None
}
fn description(&self) -> &str {
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
}
}
impl fmt::Display for AsciiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AsciiError::ControlChar(pos) => write!(f, "{} at position {}", self.description(), pos),
AsciiError::NonAscii(ch) => write!(f, "{} ({})", self.description(), ch),
}
}
}
|
impl error::Error for AsciiError {
|
random_line_split
|
modules.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/>.
use std::sync::Arc;
use std::path::Path;
use ethcore::client::BlockChainClient;
use hypervisor::Hypervisor;
use ethsync::{SyncConfig, NetworkConfiguration, NetworkError, Params};
use ethcore::snapshot::SnapshotService;
use light::Provider;
#[cfg(not(feature="ipc"))]
use self::no_ipc_deps::*;
#[cfg(not(feature="ipc"))]
use ethcore_logger::Config as LogConfig;
#[cfg(feature="ipc")]
use self::ipc_deps::*;
#[cfg(feature="ipc")]
pub mod service_urls {
use std::path::PathBuf;
pub const CLIENT: &'static str = "parity-chain.ipc";
pub const SNAPSHOT: &'static str = "parity-snapshot.ipc";
pub const SYNC: &'static str = "parity-sync.ipc";
pub const SYNC_NOTIFY: &'static str = "parity-sync-notify.ipc";
pub const NETWORK_MANAGER: &'static str = "parity-manage-net.ipc";
pub const SYNC_CONTROL: &'static str = "parity-sync-control.ipc";
pub const LIGHT_PROVIDER: &'static str = "parity-light-provider.ipc";
#[cfg(feature="stratum")]
pub const STRATUM: &'static str = "parity-stratum.ipc";
#[cfg(feature="stratum")]
pub const MINING_JOB_DISPATCHER: &'static str = "parity-mining-jobs.ipc";
pub fn with_base(data_dir: &str, service_path: &str) -> String {
let mut path = PathBuf::from(data_dir);
path.push(service_path);
format!("ipc://{}", path.to_str().unwrap())
}
}
#[cfg(not(feature="ipc"))]
mod no_ipc_deps {
pub use ethsync::{EthSync, SyncProvider, ManageNetwork};
pub use ethcore::client::ChainNotify;
}
#[cfg(feature="ipc")]
pub type SyncModules = (
GuardedSocket<SyncClient<NanoSocket>>,
GuardedSocket<NetworkManagerClient<NanoSocket>>,
GuardedSocket<ChainNotifyClient<NanoSocket>>
);
#[cfg(not(feature="ipc"))]
pub type SyncModules = (Arc<SyncProvider>, Arc<ManageNetwork>, Arc<ChainNotify>);
#[cfg(feature="ipc")]
mod ipc_deps {
pub use ethsync::remote::{SyncClient, NetworkManagerClient};
pub use ethsync::ServiceConfiguration;
pub use ethcore::client::remote::ChainNotifyClient;
pub use hypervisor::{SYNC_MODULE_ID, BootArgs, HYPERVISOR_IPC_URL};
pub use nanoipc::{GuardedSocket, NanoSocket, generic_client, fast_client};
pub use ipc::IpcSocket;
pub use ipc::binary::serialize;
pub use light::remote::LightProviderClient;
}
#[cfg(feature="ipc")]
pub fn hypervisor(base_path: &Path) -> Option<Hypervisor> {
Some(Hypervisor
::with_url(&service_urls::with_base(base_path.to_str().unwrap(), HYPERVISOR_IPC_URL))
.io_path(base_path.to_str().unwrap()))
}
#[cfg(not(feature="ipc"))]
pub fn hypervisor(_: &Path) -> Option<Hypervisor> {
None
}
#[cfg(feature="ipc")]
fn
|
(io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config).expect("Any binary-derived struct is serializable by definition");
// client service url and logging settings are passed in command line
let mut cli_args = Vec::new();
cli_args.push("sync".to_owned());
if!log_settings.color { cli_args.push("--no-color".to_owned()); }
if let Some(ref mode) = log_settings.mode {
cli_args.push("-l".to_owned());
cli_args.push(mode.to_owned());
}
if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
_provider: Arc<Provider>,
log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let mut hypervisor = hypervisor_ref.take().expect("There should be hypervisor for ipc configuration");
let args = sync_arguments(&hypervisor.io_path, sync_cfg, net_cfg, log_settings);
hypervisor = hypervisor.module(SYNC_MODULE_ID, args);
hypervisor.start();
hypervisor.wait_for_startup();
let sync_client = generic_client::<SyncClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC)).unwrap();
let notify_client = generic_client::<ChainNotifyClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC_NOTIFY)).unwrap();
let manage_client = generic_client::<NetworkManagerClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::NETWORK_MANAGER)).unwrap();
let provider_client = generic_client::<LightProviderClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::LIGHT_PROVIDER)).unwrap();
*hypervisor_ref = Some(hypervisor);
Ok((sync_client, manage_client, notify_client))
}
#[cfg(not(feature="ipc"))]
pub fn sync
(
_hypervisor: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
client: Arc<BlockChainClient>,
snapshot_service: Arc<SnapshotService>,
provider: Arc<Provider>,
_log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let eth_sync = try!(EthSync::new(Params {
config: sync_cfg,
chain: client,
provider: provider,
snapshot_service: snapshot_service,
network_config: net_cfg,
}));
Ok((eth_sync.clone() as Arc<SyncProvider>, eth_sync.clone() as Arc<ManageNetwork>, eth_sync.clone() as Arc<ChainNotify>))
}
|
sync_arguments
|
identifier_name
|
modules.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/>.
use std::sync::Arc;
use std::path::Path;
use ethcore::client::BlockChainClient;
use hypervisor::Hypervisor;
use ethsync::{SyncConfig, NetworkConfiguration, NetworkError, Params};
use ethcore::snapshot::SnapshotService;
use light::Provider;
#[cfg(not(feature="ipc"))]
use self::no_ipc_deps::*;
#[cfg(not(feature="ipc"))]
use ethcore_logger::Config as LogConfig;
#[cfg(feature="ipc")]
use self::ipc_deps::*;
#[cfg(feature="ipc")]
pub mod service_urls {
use std::path::PathBuf;
pub const CLIENT: &'static str = "parity-chain.ipc";
pub const SNAPSHOT: &'static str = "parity-snapshot.ipc";
pub const SYNC: &'static str = "parity-sync.ipc";
pub const SYNC_NOTIFY: &'static str = "parity-sync-notify.ipc";
pub const NETWORK_MANAGER: &'static str = "parity-manage-net.ipc";
pub const SYNC_CONTROL: &'static str = "parity-sync-control.ipc";
pub const LIGHT_PROVIDER: &'static str = "parity-light-provider.ipc";
#[cfg(feature="stratum")]
pub const STRATUM: &'static str = "parity-stratum.ipc";
#[cfg(feature="stratum")]
pub const MINING_JOB_DISPATCHER: &'static str = "parity-mining-jobs.ipc";
pub fn with_base(data_dir: &str, service_path: &str) -> String {
let mut path = PathBuf::from(data_dir);
path.push(service_path);
format!("ipc://{}", path.to_str().unwrap())
}
}
#[cfg(not(feature="ipc"))]
mod no_ipc_deps {
pub use ethsync::{EthSync, SyncProvider, ManageNetwork};
pub use ethcore::client::ChainNotify;
}
#[cfg(feature="ipc")]
pub type SyncModules = (
GuardedSocket<SyncClient<NanoSocket>>,
GuardedSocket<NetworkManagerClient<NanoSocket>>,
GuardedSocket<ChainNotifyClient<NanoSocket>>
);
#[cfg(not(feature="ipc"))]
pub type SyncModules = (Arc<SyncProvider>, Arc<ManageNetwork>, Arc<ChainNotify>);
#[cfg(feature="ipc")]
mod ipc_deps {
pub use ethsync::remote::{SyncClient, NetworkManagerClient};
pub use ethsync::ServiceConfiguration;
pub use ethcore::client::remote::ChainNotifyClient;
pub use hypervisor::{SYNC_MODULE_ID, BootArgs, HYPERVISOR_IPC_URL};
pub use nanoipc::{GuardedSocket, NanoSocket, generic_client, fast_client};
pub use ipc::IpcSocket;
pub use ipc::binary::serialize;
pub use light::remote::LightProviderClient;
}
#[cfg(feature="ipc")]
pub fn hypervisor(base_path: &Path) -> Option<Hypervisor> {
Some(Hypervisor
::with_url(&service_urls::with_base(base_path.to_str().unwrap(), HYPERVISOR_IPC_URL))
.io_path(base_path.to_str().unwrap()))
}
#[cfg(not(feature="ipc"))]
pub fn hypervisor(_: &Path) -> Option<Hypervisor> {
None
}
#[cfg(feature="ipc")]
fn sync_arguments(io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config).expect("Any binary-derived struct is serializable by definition");
// client service url and logging settings are passed in command line
let mut cli_args = Vec::new();
cli_args.push("sync".to_owned());
if!log_settings.color { cli_args.push("--no-color".to_owned()); }
if let Some(ref mode) = log_settings.mode {
cli_args.push("-l".to_owned());
cli_args.push(mode.to_owned());
}
|
if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
_provider: Arc<Provider>,
log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let mut hypervisor = hypervisor_ref.take().expect("There should be hypervisor for ipc configuration");
let args = sync_arguments(&hypervisor.io_path, sync_cfg, net_cfg, log_settings);
hypervisor = hypervisor.module(SYNC_MODULE_ID, args);
hypervisor.start();
hypervisor.wait_for_startup();
let sync_client = generic_client::<SyncClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC)).unwrap();
let notify_client = generic_client::<ChainNotifyClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC_NOTIFY)).unwrap();
let manage_client = generic_client::<NetworkManagerClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::NETWORK_MANAGER)).unwrap();
let provider_client = generic_client::<LightProviderClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::LIGHT_PROVIDER)).unwrap();
*hypervisor_ref = Some(hypervisor);
Ok((sync_client, manage_client, notify_client))
}
#[cfg(not(feature="ipc"))]
pub fn sync
(
_hypervisor: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
client: Arc<BlockChainClient>,
snapshot_service: Arc<SnapshotService>,
provider: Arc<Provider>,
_log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let eth_sync = try!(EthSync::new(Params {
config: sync_cfg,
chain: client,
provider: provider,
snapshot_service: snapshot_service,
network_config: net_cfg,
}));
Ok((eth_sync.clone() as Arc<SyncProvider>, eth_sync.clone() as Arc<ManageNetwork>, eth_sync.clone() as Arc<ChainNotify>))
}
|
random_line_split
|
|
modules.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/>.
use std::sync::Arc;
use std::path::Path;
use ethcore::client::BlockChainClient;
use hypervisor::Hypervisor;
use ethsync::{SyncConfig, NetworkConfiguration, NetworkError, Params};
use ethcore::snapshot::SnapshotService;
use light::Provider;
#[cfg(not(feature="ipc"))]
use self::no_ipc_deps::*;
#[cfg(not(feature="ipc"))]
use ethcore_logger::Config as LogConfig;
#[cfg(feature="ipc")]
use self::ipc_deps::*;
#[cfg(feature="ipc")]
pub mod service_urls {
use std::path::PathBuf;
pub const CLIENT: &'static str = "parity-chain.ipc";
pub const SNAPSHOT: &'static str = "parity-snapshot.ipc";
pub const SYNC: &'static str = "parity-sync.ipc";
pub const SYNC_NOTIFY: &'static str = "parity-sync-notify.ipc";
pub const NETWORK_MANAGER: &'static str = "parity-manage-net.ipc";
pub const SYNC_CONTROL: &'static str = "parity-sync-control.ipc";
pub const LIGHT_PROVIDER: &'static str = "parity-light-provider.ipc";
#[cfg(feature="stratum")]
pub const STRATUM: &'static str = "parity-stratum.ipc";
#[cfg(feature="stratum")]
pub const MINING_JOB_DISPATCHER: &'static str = "parity-mining-jobs.ipc";
pub fn with_base(data_dir: &str, service_path: &str) -> String {
let mut path = PathBuf::from(data_dir);
path.push(service_path);
format!("ipc://{}", path.to_str().unwrap())
}
}
#[cfg(not(feature="ipc"))]
mod no_ipc_deps {
pub use ethsync::{EthSync, SyncProvider, ManageNetwork};
pub use ethcore::client::ChainNotify;
}
#[cfg(feature="ipc")]
pub type SyncModules = (
GuardedSocket<SyncClient<NanoSocket>>,
GuardedSocket<NetworkManagerClient<NanoSocket>>,
GuardedSocket<ChainNotifyClient<NanoSocket>>
);
#[cfg(not(feature="ipc"))]
pub type SyncModules = (Arc<SyncProvider>, Arc<ManageNetwork>, Arc<ChainNotify>);
#[cfg(feature="ipc")]
mod ipc_deps {
pub use ethsync::remote::{SyncClient, NetworkManagerClient};
pub use ethsync::ServiceConfiguration;
pub use ethcore::client::remote::ChainNotifyClient;
pub use hypervisor::{SYNC_MODULE_ID, BootArgs, HYPERVISOR_IPC_URL};
pub use nanoipc::{GuardedSocket, NanoSocket, generic_client, fast_client};
pub use ipc::IpcSocket;
pub use ipc::binary::serialize;
pub use light::remote::LightProviderClient;
}
#[cfg(feature="ipc")]
pub fn hypervisor(base_path: &Path) -> Option<Hypervisor> {
Some(Hypervisor
::with_url(&service_urls::with_base(base_path.to_str().unwrap(), HYPERVISOR_IPC_URL))
.io_path(base_path.to_str().unwrap()))
}
#[cfg(not(feature="ipc"))]
pub fn hypervisor(_: &Path) -> Option<Hypervisor> {
None
}
#[cfg(feature="ipc")]
fn sync_arguments(io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs
|
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
_provider: Arc<Provider>,
log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let mut hypervisor = hypervisor_ref.take().expect("There should be hypervisor for ipc configuration");
let args = sync_arguments(&hypervisor.io_path, sync_cfg, net_cfg, log_settings);
hypervisor = hypervisor.module(SYNC_MODULE_ID, args);
hypervisor.start();
hypervisor.wait_for_startup();
let sync_client = generic_client::<SyncClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC)).unwrap();
let notify_client = generic_client::<ChainNotifyClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC_NOTIFY)).unwrap();
let manage_client = generic_client::<NetworkManagerClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::NETWORK_MANAGER)).unwrap();
let provider_client = generic_client::<LightProviderClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::LIGHT_PROVIDER)).unwrap();
*hypervisor_ref = Some(hypervisor);
Ok((sync_client, manage_client, notify_client))
}
#[cfg(not(feature="ipc"))]
pub fn sync
(
_hypervisor: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
client: Arc<BlockChainClient>,
snapshot_service: Arc<SnapshotService>,
provider: Arc<Provider>,
_log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let eth_sync = try!(EthSync::new(Params {
config: sync_cfg,
chain: client,
provider: provider,
snapshot_service: snapshot_service,
network_config: net_cfg,
}));
Ok((eth_sync.clone() as Arc<SyncProvider>, eth_sync.clone() as Arc<ManageNetwork>, eth_sync.clone() as Arc<ChainNotify>))
}
|
{
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config).expect("Any binary-derived struct is serializable by definition");
// client service url and logging settings are passed in command line
let mut cli_args = Vec::new();
cli_args.push("sync".to_owned());
if !log_settings.color { cli_args.push("--no-color".to_owned()); }
if let Some(ref mode) = log_settings.mode {
cli_args.push("-l".to_owned());
cli_args.push(mode.to_owned());
}
if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
|
identifier_body
|
modules.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/>.
use std::sync::Arc;
use std::path::Path;
use ethcore::client::BlockChainClient;
use hypervisor::Hypervisor;
use ethsync::{SyncConfig, NetworkConfiguration, NetworkError, Params};
use ethcore::snapshot::SnapshotService;
use light::Provider;
#[cfg(not(feature="ipc"))]
use self::no_ipc_deps::*;
#[cfg(not(feature="ipc"))]
use ethcore_logger::Config as LogConfig;
#[cfg(feature="ipc")]
use self::ipc_deps::*;
#[cfg(feature="ipc")]
pub mod service_urls {
use std::path::PathBuf;
pub const CLIENT: &'static str = "parity-chain.ipc";
pub const SNAPSHOT: &'static str = "parity-snapshot.ipc";
pub const SYNC: &'static str = "parity-sync.ipc";
pub const SYNC_NOTIFY: &'static str = "parity-sync-notify.ipc";
pub const NETWORK_MANAGER: &'static str = "parity-manage-net.ipc";
pub const SYNC_CONTROL: &'static str = "parity-sync-control.ipc";
pub const LIGHT_PROVIDER: &'static str = "parity-light-provider.ipc";
#[cfg(feature="stratum")]
pub const STRATUM: &'static str = "parity-stratum.ipc";
#[cfg(feature="stratum")]
pub const MINING_JOB_DISPATCHER: &'static str = "parity-mining-jobs.ipc";
pub fn with_base(data_dir: &str, service_path: &str) -> String {
let mut path = PathBuf::from(data_dir);
path.push(service_path);
format!("ipc://{}", path.to_str().unwrap())
}
}
#[cfg(not(feature="ipc"))]
mod no_ipc_deps {
pub use ethsync::{EthSync, SyncProvider, ManageNetwork};
pub use ethcore::client::ChainNotify;
}
#[cfg(feature="ipc")]
pub type SyncModules = (
GuardedSocket<SyncClient<NanoSocket>>,
GuardedSocket<NetworkManagerClient<NanoSocket>>,
GuardedSocket<ChainNotifyClient<NanoSocket>>
);
#[cfg(not(feature="ipc"))]
pub type SyncModules = (Arc<SyncProvider>, Arc<ManageNetwork>, Arc<ChainNotify>);
#[cfg(feature="ipc")]
mod ipc_deps {
pub use ethsync::remote::{SyncClient, NetworkManagerClient};
pub use ethsync::ServiceConfiguration;
pub use ethcore::client::remote::ChainNotifyClient;
pub use hypervisor::{SYNC_MODULE_ID, BootArgs, HYPERVISOR_IPC_URL};
pub use nanoipc::{GuardedSocket, NanoSocket, generic_client, fast_client};
pub use ipc::IpcSocket;
pub use ipc::binary::serialize;
pub use light::remote::LightProviderClient;
}
#[cfg(feature="ipc")]
pub fn hypervisor(base_path: &Path) -> Option<Hypervisor> {
Some(Hypervisor
::with_url(&service_urls::with_base(base_path.to_str().unwrap(), HYPERVISOR_IPC_URL))
.io_path(base_path.to_str().unwrap()))
}
#[cfg(not(feature="ipc"))]
pub fn hypervisor(_: &Path) -> Option<Hypervisor> {
None
}
#[cfg(feature="ipc")]
fn sync_arguments(io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config).expect("Any binary-derived struct is serializable by definition");
// client service url and logging settings are passed in command line
let mut cli_args = Vec::new();
cli_args.push("sync".to_owned());
if!log_settings.color { cli_args.push("--no-color".to_owned()); }
if let Some(ref mode) = log_settings.mode
|
if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
_provider: Arc<Provider>,
log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let mut hypervisor = hypervisor_ref.take().expect("There should be hypervisor for ipc configuration");
let args = sync_arguments(&hypervisor.io_path, sync_cfg, net_cfg, log_settings);
hypervisor = hypervisor.module(SYNC_MODULE_ID, args);
hypervisor.start();
hypervisor.wait_for_startup();
let sync_client = generic_client::<SyncClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC)).unwrap();
let notify_client = generic_client::<ChainNotifyClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC_NOTIFY)).unwrap();
let manage_client = generic_client::<NetworkManagerClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::NETWORK_MANAGER)).unwrap();
let provider_client = generic_client::<LightProviderClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::LIGHT_PROVIDER)).unwrap();
*hypervisor_ref = Some(hypervisor);
Ok((sync_client, manage_client, notify_client))
}
#[cfg(not(feature="ipc"))]
pub fn sync
(
_hypervisor: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
client: Arc<BlockChainClient>,
snapshot_service: Arc<SnapshotService>,
provider: Arc<Provider>,
_log_settings: &LogConfig,
)
-> Result<SyncModules, NetworkError>
{
let eth_sync = try!(EthSync::new(Params {
config: sync_cfg,
chain: client,
provider: provider,
snapshot_service: snapshot_service,
network_config: net_cfg,
}));
Ok((eth_sync.clone() as Arc<SyncProvider>, eth_sync.clone() as Arc<ManageNetwork>, eth_sync.clone() as Arc<ChainNotify>))
}
|
{
cli_args.push("-l".to_owned());
cli_args.push(mode.to_owned());
}
|
conditional_block
|
memory.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
use std;
use std::ffi::CString;
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::os::unix::io::IntoRawFd;
use std::path::{Path, PathBuf};
use std::ptr;
use serde_derive::{Serialize, Deserialize};
use log::{trace, debug, info, warn, error, log, LevelFilter};
use crate::constants;
/// Represents a file backed memory mapping
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryMapping {
pub filename: PathBuf,
pub addr: usize,
pub len: usize,
}
impl MemoryMapping {
pub fn new(filename: &Path, addr: usize, len: usize) -> MemoryMapping {
MemoryMapping {
filename: PathBuf::from(filename),
addr,
len,
}
}
}
#[cfg(target_pointer_width = "64")]
type StatSize = i64;
#[cfg(target_pointer_width = "32")]
type StatSize = i32;
/// Cache the file `filename` into the systems page cache
/// This currently performs the following actions:
/// * Open file `filename` and query it's size.
/// Return an Err if file exceeds the max. prefetch size
/// * Give the system's kernel a readahead hint via readahead(2) syscall
/// * Additionally mmap(2) the file
/// * Call posix_fadvise(2) with `POSIX_FADV_WILLNEED` | `POSIX_FADV_SEQUENTIAL`
/// to give the kernel a hint on how we are about to use that file
/// * Call madvise(2) with `MADV_WILLNEED` | `MADV_SEQUENTIAL` | `MADV_MERGEABLE`
/// to give the kernel a hint on how we are about to use that memory mapping
/// * Call mlock(2) if `with_mlock` is set to `true` to prevent
/// eviction of the files pages from the page cache
///
/// Returns a `MemoryMapping` representing the newly created file backed mapping
/// or an Err if the requested actions could not be performed
pub fn cache_file(filename: &Path, with_mlock: bool) -> Result<MemoryMapping> {
trace!("Caching file: {:?}", filename);
let file = File::open(filename)?;
let fd = file.into_raw_fd();
// We are interested in file size
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
unsafe {
libc::fstat(fd, &mut stat);
};
if stat.st_mode & libc::S_ISUID == libc::S_ISUID || stat.st_mode & libc::S_ISGID == libc::S_ISGID {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Not prefetching SUID/SGID files!");
Err(custom_error)
} else if stat.st_size > constants::MAX_ALLOWED_PREFETCH_SIZE as StatSize {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Maximum allowed file size for prefetching exceeded!");
Err(custom_error)
} else {
// Manually fault in all pages
let result = unsafe { libc::readahead(fd, 0, stat.st_size as usize) };
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called readahead() for: {:?}", filename);
// Call to readahead succeeded, now mmap() and mlock() if requested
let addr = unsafe {
libc::mmap(
ptr::null_mut(),
stat.st_size as usize,
libc::PROT_READ,
libc::MAP_SHARED,
fd,
0,
)
};
if addr < ptr::null_mut() {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mmap() for: {:?}", filename);
// If we are on a 64 bit architecture
#[cfg(target_pointer_width = "64")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i64,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
// If we are on a 32 bit architecture
#[cfg(target_pointer_width = "32")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i32,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called posix_fadvise() for: {:?}", filename);
let result = unsafe {
libc::madvise(
addr as *mut libc::c_void,
stat.st_size as usize,
libc::MADV_WILLNEED | libc::MADV_SEQUENTIAL | libc::MADV_MERGEABLE,
)
};
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called madvise() for: {:?}", filename);
if with_mlock {
let result = unsafe { libc::mlock(addr as *mut libc::c_void, stat.st_size as usize) };
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mlock() for: {:?}", filename);
let result = unsafe { libc::close(fd) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called close() for: {:?}", filename);
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
} else {
// We don't perform a call to mlock()
// Try to close the file descriptor
unsafe { libc::close(fd) };
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
}
}
}
}
}
/// Unmaps a memory mapping that was previously created by `cache_file(...)`
pub fn free_mapping(mapping: &MemoryMapping) -> bool {
let result = unsafe { libc::munmap(mapping.addr as *mut libc::c_void, mapping.len) };
result == 0
}
/// Prime the kernel's dentry caches by reading the metadata of the file `filename`
pub fn prime_metadata_cache(filename: &Path) -> Result<()> {
trace!("Caching metadata of file: {:?}", filename);
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
let f = unsafe { CString::from_vec_unchecked(filename.to_string_lossy().into_owned().into()) };
let result = unsafe { libc::stat(f.as_ptr(), &mut stat) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else
|
}
|
{
trace!("Successfully called stat() for: {:?}", filename);
Ok(())
}
|
conditional_block
|
memory.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
use std;
use std::ffi::CString;
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::os::unix::io::IntoRawFd;
use std::path::{Path, PathBuf};
use std::ptr;
use serde_derive::{Serialize, Deserialize};
use log::{trace, debug, info, warn, error, log, LevelFilter};
use crate::constants;
/// Represents a file backed memory mapping
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryMapping {
pub filename: PathBuf,
pub addr: usize,
pub len: usize,
}
impl MemoryMapping {
pub fn new(filename: &Path, addr: usize, len: usize) -> MemoryMapping {
MemoryMapping {
filename: PathBuf::from(filename),
addr,
len,
}
}
}
#[cfg(target_pointer_width = "64")]
type StatSize = i64;
#[cfg(target_pointer_width = "32")]
type StatSize = i32;
/// Cache the file `filename` into the systems page cache
/// This currently performs the following actions:
/// * Open file `filename` and query it's size.
/// Return an Err if file exceeds the max. prefetch size
/// * Give the system's kernel a readahead hint via readahead(2) syscall
/// * Additionally mmap(2) the file
/// * Call posix_fadvise(2) with `POSIX_FADV_WILLNEED` | `POSIX_FADV_SEQUENTIAL`
/// to give the kernel a hint on how we are about to use that file
/// * Call madvise(2) with `MADV_WILLNEED` | `MADV_SEQUENTIAL` | `MADV_MERGEABLE`
/// to give the kernel a hint on how we are about to use that memory mapping
/// * Call mlock(2) if `with_mlock` is set to `true` to prevent
/// eviction of the files pages from the page cache
///
/// Returns a `MemoryMapping` representing the newly created file backed mapping
/// or an Err if the requested actions could not be performed
pub fn cache_file(filename: &Path, with_mlock: bool) -> Result<MemoryMapping>
|
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Maximum allowed file size for prefetching exceeded!");
Err(custom_error)
} else {
// Manually fault in all pages
let result = unsafe { libc::readahead(fd, 0, stat.st_size as usize) };
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called readahead() for: {:?}", filename);
// Call to readahead succeeded, now mmap() and mlock() if requested
let addr = unsafe {
libc::mmap(
ptr::null_mut(),
stat.st_size as usize,
libc::PROT_READ,
libc::MAP_SHARED,
fd,
0,
)
};
if addr < ptr::null_mut() {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mmap() for: {:?}", filename);
// If we are on a 64 bit architecture
#[cfg(target_pointer_width = "64")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i64,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
// If we are on a 32 bit architecture
#[cfg(target_pointer_width = "32")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i32,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called posix_fadvise() for: {:?}", filename);
let result = unsafe {
libc::madvise(
addr as *mut libc::c_void,
stat.st_size as usize,
libc::MADV_WILLNEED | libc::MADV_SEQUENTIAL | libc::MADV_MERGEABLE,
)
};
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called madvise() for: {:?}", filename);
if with_mlock {
let result = unsafe { libc::mlock(addr as *mut libc::c_void, stat.st_size as usize) };
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mlock() for: {:?}", filename);
let result = unsafe { libc::close(fd) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called close() for: {:?}", filename);
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
} else {
// We don't perform a call to mlock()
// Try to close the file descriptor
unsafe { libc::close(fd) };
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
}
}
}
}
}
/// Unmaps a memory mapping that was previously created by `cache_file(...)`
pub fn free_mapping(mapping: &MemoryMapping) -> bool {
let result = unsafe { libc::munmap(mapping.addr as *mut libc::c_void, mapping.len) };
result == 0
}
/// Prime the kernel's dentry caches by reading the metadata of the file `filename`
pub fn prime_metadata_cache(filename: &Path) -> Result<()> {
trace!("Caching metadata of file: {:?}", filename);
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
let f = unsafe { CString::from_vec_unchecked(filename.to_string_lossy().into_owned().into()) };
let result = unsafe { libc::stat(f.as_ptr(), &mut stat) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called stat() for: {:?}", filename);
Ok(())
}
}
|
{
trace!("Caching file: {:?}", filename);
let file = File::open(filename)?;
let fd = file.into_raw_fd();
// We are interested in file size
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
unsafe {
libc::fstat(fd, &mut stat);
};
if stat.st_mode & libc::S_ISUID == libc::S_ISUID || stat.st_mode & libc::S_ISGID == libc::S_ISGID {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Not prefetching SUID/SGID files!");
Err(custom_error)
} else if stat.st_size > constants::MAX_ALLOWED_PREFETCH_SIZE as StatSize {
// Try to close the file descriptor
|
identifier_body
|
memory.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
use std;
use std::ffi::CString;
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::os::unix::io::IntoRawFd;
use std::path::{Path, PathBuf};
use std::ptr;
use serde_derive::{Serialize, Deserialize};
use log::{trace, debug, info, warn, error, log, LevelFilter};
use crate::constants;
/// Represents a file backed memory mapping
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryMapping {
pub filename: PathBuf,
pub addr: usize,
pub len: usize,
}
impl MemoryMapping {
pub fn new(filename: &Path, addr: usize, len: usize) -> MemoryMapping {
MemoryMapping {
filename: PathBuf::from(filename),
addr,
len,
}
}
}
#[cfg(target_pointer_width = "64")]
type StatSize = i64;
#[cfg(target_pointer_width = "32")]
type StatSize = i32;
/// Cache the file `filename` into the systems page cache
/// This currently performs the following actions:
/// * Open file `filename` and query it's size.
/// Return an Err if file exceeds the max. prefetch size
/// * Give the system's kernel a readahead hint via readahead(2) syscall
/// * Additionally mmap(2) the file
/// * Call posix_fadvise(2) with `POSIX_FADV_WILLNEED` | `POSIX_FADV_SEQUENTIAL`
/// to give the kernel a hint on how we are about to use that file
/// * Call madvise(2) with `MADV_WILLNEED` | `MADV_SEQUENTIAL` | `MADV_MERGEABLE`
/// to give the kernel a hint on how we are about to use that memory mapping
/// * Call mlock(2) if `with_mlock` is set to `true` to prevent
/// eviction of the files pages from the page cache
///
/// Returns a `MemoryMapping` representing the newly created file backed mapping
/// or an Err if the requested actions could not be performed
pub fn cache_file(filename: &Path, with_mlock: bool) -> Result<MemoryMapping> {
trace!("Caching file: {:?}", filename);
let file = File::open(filename)?;
let fd = file.into_raw_fd();
// We are interested in file size
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
unsafe {
libc::fstat(fd, &mut stat);
};
if stat.st_mode & libc::S_ISUID == libc::S_ISUID || stat.st_mode & libc::S_ISGID == libc::S_ISGID {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Not prefetching SUID/SGID files!");
Err(custom_error)
} else if stat.st_size > constants::MAX_ALLOWED_PREFETCH_SIZE as StatSize {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Maximum allowed file size for prefetching exceeded!");
Err(custom_error)
} else {
// Manually fault in all pages
let result = unsafe { libc::readahead(fd, 0, stat.st_size as usize) };
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called readahead() for: {:?}", filename);
// Call to readahead succeeded, now mmap() and mlock() if requested
let addr = unsafe {
libc::mmap(
ptr::null_mut(),
stat.st_size as usize,
libc::PROT_READ,
libc::MAP_SHARED,
fd,
0,
)
};
if addr < ptr::null_mut() {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mmap() for: {:?}", filename);
// If we are on a 64 bit architecture
#[cfg(target_pointer_width = "64")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i64,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
// If we are on a 32 bit architecture
#[cfg(target_pointer_width = "32")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i32,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
|
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called posix_fadvise() for: {:?}", filename);
let result = unsafe {
libc::madvise(
addr as *mut libc::c_void,
stat.st_size as usize,
libc::MADV_WILLNEED | libc::MADV_SEQUENTIAL | libc::MADV_MERGEABLE,
)
};
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called madvise() for: {:?}", filename);
if with_mlock {
let result = unsafe { libc::mlock(addr as *mut libc::c_void, stat.st_size as usize) };
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mlock() for: {:?}", filename);
let result = unsafe { libc::close(fd) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called close() for: {:?}", filename);
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
} else {
// We don't perform a call to mlock()
// Try to close the file descriptor
unsafe { libc::close(fd) };
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
}
}
}
}
}
/// Unmaps a memory mapping that was previously created by `cache_file(...)`
pub fn free_mapping(mapping: &MemoryMapping) -> bool {
let result = unsafe { libc::munmap(mapping.addr as *mut libc::c_void, mapping.len) };
result == 0
}
/// Prime the kernel's dentry caches by reading the metadata of the file `filename`
pub fn prime_metadata_cache(filename: &Path) -> Result<()> {
trace!("Caching metadata of file: {:?}", filename);
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
let f = unsafe { CString::from_vec_unchecked(filename.to_string_lossy().into_owned().into()) };
let result = unsafe { libc::stat(f.as_ptr(), &mut stat) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called stat() for: {:?}", filename);
Ok(())
}
}
|
random_line_split
|
|
memory.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
use std;
use std::ffi::CString;
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::os::unix::io::IntoRawFd;
use std::path::{Path, PathBuf};
use std::ptr;
use serde_derive::{Serialize, Deserialize};
use log::{trace, debug, info, warn, error, log, LevelFilter};
use crate::constants;
/// Represents a file backed memory mapping
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct
|
{
pub filename: PathBuf,
pub addr: usize,
pub len: usize,
}
impl MemoryMapping {
pub fn new(filename: &Path, addr: usize, len: usize) -> MemoryMapping {
MemoryMapping {
filename: PathBuf::from(filename),
addr,
len,
}
}
}
#[cfg(target_pointer_width = "64")]
type StatSize = i64;
#[cfg(target_pointer_width = "32")]
type StatSize = i32;
/// Cache the file `filename` into the systems page cache
/// This currently performs the following actions:
/// * Open file `filename` and query it's size.
/// Return an Err if file exceeds the max. prefetch size
/// * Give the system's kernel a readahead hint via readahead(2) syscall
/// * Additionally mmap(2) the file
/// * Call posix_fadvise(2) with `POSIX_FADV_WILLNEED` | `POSIX_FADV_SEQUENTIAL`
/// to give the kernel a hint on how we are about to use that file
/// * Call madvise(2) with `MADV_WILLNEED` | `MADV_SEQUENTIAL` | `MADV_MERGEABLE`
/// to give the kernel a hint on how we are about to use that memory mapping
/// * Call mlock(2) if `with_mlock` is set to `true` to prevent
/// eviction of the files pages from the page cache
///
/// Returns a `MemoryMapping` representing the newly created file backed mapping
/// or an Err if the requested actions could not be performed
pub fn cache_file(filename: &Path, with_mlock: bool) -> Result<MemoryMapping> {
trace!("Caching file: {:?}", filename);
let file = File::open(filename)?;
let fd = file.into_raw_fd();
// We are interested in file size
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
unsafe {
libc::fstat(fd, &mut stat);
};
if stat.st_mode & libc::S_ISUID == libc::S_ISUID || stat.st_mode & libc::S_ISGID == libc::S_ISGID {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Not prefetching SUID/SGID files!");
Err(custom_error)
} else if stat.st_size > constants::MAX_ALLOWED_PREFETCH_SIZE as StatSize {
// Try to close the file descriptor
unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Maximum allowed file size for prefetching exceeded!");
Err(custom_error)
} else {
// Manually fault in all pages
let result = unsafe { libc::readahead(fd, 0, stat.st_size as usize) };
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called readahead() for: {:?}", filename);
// Call to readahead succeeded, now mmap() and mlock() if requested
let addr = unsafe {
libc::mmap(
ptr::null_mut(),
stat.st_size as usize,
libc::PROT_READ,
libc::MAP_SHARED,
fd,
0,
)
};
if addr < ptr::null_mut() {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mmap() for: {:?}", filename);
// If we are on a 64 bit architecture
#[cfg(target_pointer_width = "64")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i64,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
// If we are on a 32 bit architecture
#[cfg(target_pointer_width = "32")]
let result = unsafe {
libc::posix_fadvise(
fd,
0,
stat.st_size as i32,
libc::POSIX_FADV_WILLNEED | libc::POSIX_FADV_SEQUENTIAL,
)
};
if result < 0 {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called posix_fadvise() for: {:?}", filename);
let result = unsafe {
libc::madvise(
addr as *mut libc::c_void,
stat.st_size as usize,
libc::MADV_WILLNEED | libc::MADV_SEQUENTIAL | libc::MADV_MERGEABLE,
)
};
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called madvise() for: {:?}", filename);
if with_mlock {
let result = unsafe { libc::mlock(addr as *mut libc::c_void, stat.st_size as usize) };
if result < 0 as libc::c_int {
// Try to close the file descriptor
unsafe { libc::close(fd) };
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called mlock() for: {:?}", filename);
let result = unsafe { libc::close(fd) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called close() for: {:?}", filename);
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
} else {
// We don't perform a call to mlock()
// Try to close the file descriptor
unsafe { libc::close(fd) };
let mapping = MemoryMapping::new(filename, addr as usize, stat.st_size as usize);
Ok(mapping)
}
}
}
}
}
}
}
/// Unmaps a memory mapping that was previously created by `cache_file(...)`
pub fn free_mapping(mapping: &MemoryMapping) -> bool {
let result = unsafe { libc::munmap(mapping.addr as *mut libc::c_void, mapping.len) };
result == 0
}
/// Prime the kernel's dentry caches by reading the metadata of the file `filename`
pub fn prime_metadata_cache(filename: &Path) -> Result<()> {
trace!("Caching metadata of file: {:?}", filename);
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
let f = unsafe { CString::from_vec_unchecked(filename.to_string_lossy().into_owned().into()) };
let result = unsafe { libc::stat(f.as_ptr(), &mut stat) };
if result < 0 as libc::c_int {
Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called stat() for: {:?}", filename);
Ok(())
}
}
|
MemoryMapping
|
identifier_name
|
dropck_tarena_cycle_checked.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Reject mixing cyclic structure and Drop when using TypedArena.
//
// (Compare against compile-fail/dropck_vec_cycle_checked.rs)
//
// (Also compare against compile-fail/dropck_tarena_unsound_drop.rs,
// which is a reduction of this code to more directly show the reason
// for the error message we see here.)
#![allow(unstable)]
#![feature(const_fn)]
extern crate arena;
use arena::TypedArena;
use std::cell::Cell;
use id::Id;
mod s {
#![allow(unstable)]
use std::sync::atomic::{AtomicUsize, Ordering};
static S_COUNT: AtomicUsize = AtomicUsize::new(0);
pub fn next_count() -> usize {
S_COUNT.fetch_add(1, Ordering::SeqCst) + 1
}
}
mod id {
use s;
#[derive(Debug)]
pub struct Id {
orig_count: usize,
count: usize,
}
impl Id {
pub fn new() -> Id {
let c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop for Id {
fn drop(&mut self) {
println!("dropping Id {}", self.count);
self.count = 0;
}
}
}
trait HasId {
fn count(&self) -> usize;
}
#[derive(Debug)]
struct CheckId<T:HasId> {
v: T
}
#[allow(non_snake_case)]
fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } }
impl<T:HasId> Drop for CheckId<T> {
fn drop(&mut self) {
assert!(self.v.count() > 0);
}
}
#[derive(Debug)]
struct C<'a> {
id: Id,
v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
}
impl<'a> HasId for Cell<Option<&'a C<'a>>> {
fn
|
(&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
C { id: Id::new(), v: Vec::new() }
}
}
fn f<'a>(arena: &'a TypedArena<C<'a>>) {
let c1 = arena.alloc(C::new());
let c2 = arena.alloc(C::new());
let c3 = arena.alloc(C::new());
c1.v.push(CheckId(Cell::new(None)));
c1.v.push(CheckId(Cell::new(None)));
c2.v.push(CheckId(Cell::new(None)));
c2.v.push(CheckId(Cell::new(None)));
c3.v.push(CheckId(Cell::new(None)));
c3.v.push(CheckId(Cell::new(None)));
c1.v[0].v.set(Some(c2));
c1.v[1].v.set(Some(c3));
c2.v[0].v.set(Some(c2));
c2.v[1].v.set(Some(c3));
c3.v[0].v.set(Some(c1));
c3.v[1].v.set(Some(c2));
}
fn main() {
let arena = TypedArena::new();
f(&arena); //~ ERROR `arena` does not live long enough
}
|
count
|
identifier_name
|
dropck_tarena_cycle_checked.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Reject mixing cyclic structure and Drop when using TypedArena.
//
// (Compare against compile-fail/dropck_vec_cycle_checked.rs)
//
// (Also compare against compile-fail/dropck_tarena_unsound_drop.rs,
// which is a reduction of this code to more directly show the reason
// for the error message we see here.)
#![allow(unstable)]
#![feature(const_fn)]
extern crate arena;
use arena::TypedArena;
use std::cell::Cell;
use id::Id;
mod s {
#![allow(unstable)]
use std::sync::atomic::{AtomicUsize, Ordering};
static S_COUNT: AtomicUsize = AtomicUsize::new(0);
pub fn next_count() -> usize {
S_COUNT.fetch_add(1, Ordering::SeqCst) + 1
}
}
mod id {
use s;
#[derive(Debug)]
pub struct Id {
orig_count: usize,
count: usize,
}
|
let c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop for Id {
fn drop(&mut self) {
println!("dropping Id {}", self.count);
self.count = 0;
}
}
}
trait HasId {
fn count(&self) -> usize;
}
#[derive(Debug)]
struct CheckId<T:HasId> {
v: T
}
#[allow(non_snake_case)]
fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } }
impl<T:HasId> Drop for CheckId<T> {
fn drop(&mut self) {
assert!(self.v.count() > 0);
}
}
#[derive(Debug)]
struct C<'a> {
id: Id,
v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
}
impl<'a> HasId for Cell<Option<&'a C<'a>>> {
fn count(&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
C { id: Id::new(), v: Vec::new() }
}
}
fn f<'a>(arena: &'a TypedArena<C<'a>>) {
let c1 = arena.alloc(C::new());
let c2 = arena.alloc(C::new());
let c3 = arena.alloc(C::new());
c1.v.push(CheckId(Cell::new(None)));
c1.v.push(CheckId(Cell::new(None)));
c2.v.push(CheckId(Cell::new(None)));
c2.v.push(CheckId(Cell::new(None)));
c3.v.push(CheckId(Cell::new(None)));
c3.v.push(CheckId(Cell::new(None)));
c1.v[0].v.set(Some(c2));
c1.v[1].v.set(Some(c3));
c2.v[0].v.set(Some(c2));
c2.v[1].v.set(Some(c3));
c3.v[0].v.set(Some(c1));
c3.v[1].v.set(Some(c2));
}
fn main() {
let arena = TypedArena::new();
f(&arena); //~ ERROR `arena` does not live long enough
}
|
impl Id {
pub fn new() -> Id {
|
random_line_split
|
tessellation.rs
|
#[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn main() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the vertex buffer, which contains all the vertices that we will draw
let vertex_buffer = {
#[derive(Copy, Clone)]
|
glium::VertexBuffer::new(&display,
vec![
Vertex { position: [-0.5, -0.5] },
Vertex { position: [ 0.0, 0.5] },
Vertex { position: [ 0.5, -0.5] },
]
)
};
// building the index buffer
let index_buffer = glium::IndexBuffer::new(&display,
PrimitiveType::Patches { vertices_per_patch: 3 },
vec![0u16, 1, 2]);
// compiling shaders and linking them together
let program = glium::Program::new(&display,
glium::program::SourceCode {
vertex_shader: "
#version 140
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment_shader: "
#version 140
in vec3 color;
out vec4 f_color;
void main() {
f_color = vec4(color, 1.0);
}
",
geometry_shader: Some("
#version 330
uniform mat4 matrix;
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;
out vec3 color;
float rand(vec2 co) {
return fract(sin(dot(co.xy,vec2(12.9898,78.233))) * 43758.5453);
}
void main() {
vec3 all_color = vec3(
rand(gl_in[0].gl_Position.xy + gl_in[1].gl_Position.yz),
rand(gl_in[1].gl_Position.yx + gl_in[2].gl_Position.zx),
rand(gl_in[0].gl_Position.xz + gl_in[2].gl_Position.zy)
);
gl_Position = matrix * gl_in[0].gl_Position;
color = all_color;
EmitVertex();
gl_Position = matrix * gl_in[1].gl_Position;
color = all_color;
EmitVertex();
gl_Position = matrix * gl_in[2].gl_Position;
color = all_color;
EmitVertex();
}
"),
tessellation_control_shader: Some("
#version 400
layout(vertices = 3) out;
uniform int tess_level = 5;
void main() {
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
gl_TessLevelOuter[0] = tess_level;
gl_TessLevelOuter[1] = tess_level;
gl_TessLevelOuter[2] = tess_level;
gl_TessLevelInner[0] = tess_level;
}
"),
tessellation_evaluation_shader: Some("
#version 400
layout(triangles, equal_spacing) in;
void main() {
vec3 position = vec3(gl_TessCoord.x) * gl_in[0].gl_Position.xyz +
vec3(gl_TessCoord.y) * gl_in[1].gl_Position.xyz +
vec3(gl_TessCoord.z) * gl_in[2].gl_Position.xyz;
gl_Position = vec4(position, 1.0);
}
"),
}).unwrap();
// level of tessellation
let mut tess_level: i32 = 5;
println!("The current tessellation level is {} ; use the Up and Down keys to change it", tess_level);
// the main loop
support::start_loop(|| {
// building the uniforms
let uniforms = uniform! {
matrix: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0f32]
],
tess_level: tess_level
};
// drawing a frame
let mut target = display.draw();
target.clear_color(0.0, 0.0, 0.0, 0.0);
target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap();
target.finish().unwrap();
// polling and handling the events received by the window
for event in display.poll_events() {
match event {
glutin::Event::Closed => return support::Action::Stop,
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Up)) => {
tess_level += 1;
println!("New tessellation level: {}", tess_level);
},
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Down)) => {
if tess_level >= 2 {
tess_level -= 1;
println!("New tessellation level: {}", tess_level);
}
},
_ => ()
}
}
support::Action::Continue
});
}
|
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
|
random_line_split
|
tessellation.rs
|
#[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn main() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the vertex buffer, which contains all the vertices that we will draw
let vertex_buffer = {
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
glium::VertexBuffer::new(&display,
vec![
Vertex { position: [-0.5, -0.5] },
Vertex { position: [ 0.0, 0.5] },
Vertex { position: [ 0.5, -0.5] },
]
)
};
// building the index buffer
let index_buffer = glium::IndexBuffer::new(&display,
PrimitiveType::Patches { vertices_per_patch: 3 },
vec![0u16, 1, 2]);
// compiling shaders and linking them together
let program = glium::Program::new(&display,
glium::program::SourceCode {
vertex_shader: "
#version 140
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment_shader: "
#version 140
in vec3 color;
out vec4 f_color;
void main() {
f_color = vec4(color, 1.0);
}
",
geometry_shader: Some("
#version 330
uniform mat4 matrix;
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;
out vec3 color;
float rand(vec2 co) {
return fract(sin(dot(co.xy,vec2(12.9898,78.233))) * 43758.5453);
}
void main() {
vec3 all_color = vec3(
rand(gl_in[0].gl_Position.xy + gl_in[1].gl_Position.yz),
rand(gl_in[1].gl_Position.yx + gl_in[2].gl_Position.zx),
rand(gl_in[0].gl_Position.xz + gl_in[2].gl_Position.zy)
);
gl_Position = matrix * gl_in[0].gl_Position;
color = all_color;
EmitVertex();
gl_Position = matrix * gl_in[1].gl_Position;
color = all_color;
EmitVertex();
gl_Position = matrix * gl_in[2].gl_Position;
color = all_color;
EmitVertex();
}
"),
tessellation_control_shader: Some("
#version 400
layout(vertices = 3) out;
uniform int tess_level = 5;
void main() {
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
gl_TessLevelOuter[0] = tess_level;
gl_TessLevelOuter[1] = tess_level;
gl_TessLevelOuter[2] = tess_level;
gl_TessLevelInner[0] = tess_level;
}
"),
tessellation_evaluation_shader: Some("
#version 400
layout(triangles, equal_spacing) in;
void main() {
vec3 position = vec3(gl_TessCoord.x) * gl_in[0].gl_Position.xyz +
vec3(gl_TessCoord.y) * gl_in[1].gl_Position.xyz +
vec3(gl_TessCoord.z) * gl_in[2].gl_Position.xyz;
gl_Position = vec4(position, 1.0);
}
"),
}).unwrap();
// level of tessellation
let mut tess_level: i32 = 5;
println!("The current tessellation level is {} ; use the Up and Down keys to change it", tess_level);
// the main loop
support::start_loop(|| {
// building the uniforms
let uniforms = uniform! {
matrix: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0f32]
],
tess_level: tess_level
};
// drawing a frame
let mut target = display.draw();
target.clear_color(0.0, 0.0, 0.0, 0.0);
target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap();
target.finish().unwrap();
// polling and handling the events received by the window
for event in display.poll_events() {
match event {
glutin::Event::Closed => return support::Action::Stop,
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Up)) => {
tess_level += 1;
println!("New tessellation level: {}", tess_level);
},
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Down)) =>
|
,
_ => ()
}
}
support::Action::Continue
});
}
|
{
if tess_level >= 2 {
tess_level -= 1;
println!("New tessellation level: {}", tess_level);
}
}
|
conditional_block
|
tessellation.rs
|
#[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn
|
() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the vertex buffer, which contains all the vertices that we will draw
let vertex_buffer = {
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
glium::VertexBuffer::new(&display,
vec![
Vertex { position: [-0.5, -0.5] },
Vertex { position: [ 0.0, 0.5] },
Vertex { position: [ 0.5, -0.5] },
]
)
};
// building the index buffer
let index_buffer = glium::IndexBuffer::new(&display,
PrimitiveType::Patches { vertices_per_patch: 3 },
vec![0u16, 1, 2]);
// compiling shaders and linking them together
let program = glium::Program::new(&display,
glium::program::SourceCode {
vertex_shader: "
#version 140
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment_shader: "
#version 140
in vec3 color;
out vec4 f_color;
void main() {
f_color = vec4(color, 1.0);
}
",
geometry_shader: Some("
#version 330
uniform mat4 matrix;
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;
out vec3 color;
float rand(vec2 co) {
return fract(sin(dot(co.xy,vec2(12.9898,78.233))) * 43758.5453);
}
void main() {
vec3 all_color = vec3(
rand(gl_in[0].gl_Position.xy + gl_in[1].gl_Position.yz),
rand(gl_in[1].gl_Position.yx + gl_in[2].gl_Position.zx),
rand(gl_in[0].gl_Position.xz + gl_in[2].gl_Position.zy)
);
gl_Position = matrix * gl_in[0].gl_Position;
color = all_color;
EmitVertex();
gl_Position = matrix * gl_in[1].gl_Position;
color = all_color;
EmitVertex();
gl_Position = matrix * gl_in[2].gl_Position;
color = all_color;
EmitVertex();
}
"),
tessellation_control_shader: Some("
#version 400
layout(vertices = 3) out;
uniform int tess_level = 5;
void main() {
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
gl_TessLevelOuter[0] = tess_level;
gl_TessLevelOuter[1] = tess_level;
gl_TessLevelOuter[2] = tess_level;
gl_TessLevelInner[0] = tess_level;
}
"),
tessellation_evaluation_shader: Some("
#version 400
layout(triangles, equal_spacing) in;
void main() {
vec3 position = vec3(gl_TessCoord.x) * gl_in[0].gl_Position.xyz +
vec3(gl_TessCoord.y) * gl_in[1].gl_Position.xyz +
vec3(gl_TessCoord.z) * gl_in[2].gl_Position.xyz;
gl_Position = vec4(position, 1.0);
}
"),
}).unwrap();
// level of tessellation
let mut tess_level: i32 = 5;
println!("The current tessellation level is {} ; use the Up and Down keys to change it", tess_level);
// the main loop
support::start_loop(|| {
// building the uniforms
let uniforms = uniform! {
matrix: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0f32]
],
tess_level: tess_level
};
// drawing a frame
let mut target = display.draw();
target.clear_color(0.0, 0.0, 0.0, 0.0);
target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap();
target.finish().unwrap();
// polling and handling the events received by the window
for event in display.poll_events() {
match event {
glutin::Event::Closed => return support::Action::Stop,
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Up)) => {
tess_level += 1;
println!("New tessellation level: {}", tess_level);
},
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Down)) => {
if tess_level >= 2 {
tess_level -= 1;
println!("New tessellation level: {}", tess_level);
}
},
_ => ()
}
}
support::Action::Continue
});
}
|
main
|
identifier_name
|
utils.rs
|
extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
|
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-access-numeric-constants-using-the-float-trait
pub trait Castd {
fn d(self: &Self) -> f64;
}
impl Castd for f32 {
fn d(self: &Self) -> f64 {*self as f64}
}
impl Castd for i32 {
fn d(self: &Self) -> f64 {*self as f64}
}
pub trait FloatConst {
fn pi() -> Self;
}
impl FloatConst for f32 {
fn pi() -> Self { f32::consts::PI }
}
impl FloatConst for f64 {
fn pi() -> Self { f64::consts::PI }
}
pub fn linspace_vec<'a, T: 'a>(start: T, stop: T, len: usize) ->
Vec<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
// let mut v = Vec::<T>::with_capacity(len);
//
// for i in 0..len {
// v.push(zero);
// }
let mut v = vec![zero; len];
let mut c = zero;
//**** SLOW ****
// for x in v.iter_mut() {
// *x = start + c*dx;
// c = c + one;
// }
//**** FAST ****
let ptr: *mut T = v.as_mut_ptr();
unsafe {
for ii in 0..len {
let x = ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
}
return v
}
pub fn kaiser<T>(length: usize, alpha: T) -> heapslice::HeapSlice<T> where T: Float+FloatConst {
let length_t: T = num::cast(length).unwrap();
let one = T::one();
let two: T = num::cast(2).unwrap();
let mut n = linspace_heapslice(T::zero(), (length_t-one), length);
for ni in n.iter_mut() {
let mut tmp= two*(*ni)/(length_t-one)-one;
tmp = T::pi()*alpha* ( one- tmp.powf(two) ).sqrt();
let tmpf64: f64 = num::cast(tmp).unwrap();
let grr: f64 = num::cast(T::pi()*alpha).unwrap();
let tmp2 = rgsl::bessel::I0(tmpf64) / rgsl::bessel::I0( grr );
*ni=num::cast(tmp2).unwrap();
}
return n
}
pub fn linspace_heapslice<'a, T: 'a>(start: T, stop: T, len: usize) -> heapslice::HeapSlice<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
let mut fb: heapslice::HeapSlice<T> = heapslice::HeapSlice::<T>::new();
fb.allocate(len);
unsafe {
let mut c = zero;
for ii in 0..len {
let x = fb.ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
return fb
}
}
// **********************************************
// pub trait ToSinc<T> {
// fn sinc(self: &mut Self) -> &mut Self;
// }
// pub trait TestTrait: Sized {
// fn test_in_place(&mut self);
// fn test(mut self) -> Self {
// self.test_in_place();
// self
// }
// }
//
// impl<'a> TestTrait for &'a mut [i32] {
// fn test_in_place(self: &mut Self) {
// for x in (**self).iter_mut() {
// *x=*x*3;
// }
// }
// // fn test(self: mut Self) -> Self {
// // self.test_in
// // }
// }
// pub fn test(x: i32) -> i32 {
// let y=2*x;
// y
// }
//
// pub fn test2(x: Vec<i32>) {
// let y=x[0];
// }
pub trait ToSinc {
fn sinc(self: Self) -> Self;
}
// **********************************************
// pub fn sinc<T: ToSinc<T>>(y: &mut T) -> &mut T {
// y.sinc()
// }
pub fn sinc<T: ToSinc>(y: T) -> T {
y.sinc()
}
// **********************************************
// impl ToSinc<f64> for f64 {
// fn sinc(self: &mut Self) -> &mut Self {
// if *self!= 0f64 {
// *self = (*self*f64::consts::PI).sin()/(*self*f64::consts::PI);
// } else {
// *self = 1f64;
// }
// self
// }
// }
impl<'a> ToSinc for f64 {
fn sinc(self) -> Self {
let new: f64;
if self!= 0f64 {
let new = (self*f64::consts::PI).sin()/(self*f64::consts::PI);
return new
} else {
let new = 1f64;
return new
}
}
}
// **********************************************
// impl<'a> ToSinc<&'a mut [f64]> for &'a mut [f64] {
// fn sinc(self: &mut Self) -> &mut Self {
// for yi in (**self).iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// self
// }
// }
impl<'a> ToSinc for &'a mut [f64] {
fn sinc(self) -> Self {
for yi in (*self).iter_mut() {
if *yi!= 0f64 {
*yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
} else {
*yi = 1f64;
}
}
self
}
}
// **********************************************
// pub fn sinc2(y: &mut f64) -> &mut f64 {
// if *y!= 0f64 {
// *y = (*y*f64::consts::PI).sin()/(*y*f64::pi());
// } else {
// *y = 1f64;
// }
// y
// }
//
// pub fn sinc(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// y
// }
// pub fn linspace(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::pi()).sin()/(*yi*f64::pi());
// } else {
// *yi = 1f64;
// }
// }
// y
// }
|
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
|
random_line_split
|
utils.rs
|
extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-access-numeric-constants-using-the-float-trait
pub trait Castd {
fn d(self: &Self) -> f64;
}
impl Castd for f32 {
fn d(self: &Self) -> f64 {*self as f64}
}
impl Castd for i32 {
fn d(self: &Self) -> f64 {*self as f64}
}
pub trait FloatConst {
fn pi() -> Self;
}
impl FloatConst for f32 {
fn pi() -> Self { f32::consts::PI }
}
impl FloatConst for f64 {
fn pi() -> Self { f64::consts::PI }
}
pub fn linspace_vec<'a, T: 'a>(start: T, stop: T, len: usize) ->
Vec<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
// let mut v = Vec::<T>::with_capacity(len);
//
// for i in 0..len {
// v.push(zero);
// }
let mut v = vec![zero; len];
let mut c = zero;
//**** SLOW ****
// for x in v.iter_mut() {
// *x = start + c*dx;
// c = c + one;
// }
//**** FAST ****
let ptr: *mut T = v.as_mut_ptr();
unsafe {
for ii in 0..len {
let x = ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
}
return v
}
pub fn kaiser<T>(length: usize, alpha: T) -> heapslice::HeapSlice<T> where T: Float+FloatConst {
let length_t: T = num::cast(length).unwrap();
let one = T::one();
let two: T = num::cast(2).unwrap();
let mut n = linspace_heapslice(T::zero(), (length_t-one), length);
for ni in n.iter_mut() {
let mut tmp= two*(*ni)/(length_t-one)-one;
tmp = T::pi()*alpha* ( one- tmp.powf(two) ).sqrt();
let tmpf64: f64 = num::cast(tmp).unwrap();
let grr: f64 = num::cast(T::pi()*alpha).unwrap();
let tmp2 = rgsl::bessel::I0(tmpf64) / rgsl::bessel::I0( grr );
*ni=num::cast(tmp2).unwrap();
}
return n
}
pub fn linspace_heapslice<'a, T: 'a>(start: T, stop: T, len: usize) -> heapslice::HeapSlice<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
let mut fb: heapslice::HeapSlice<T> = heapslice::HeapSlice::<T>::new();
fb.allocate(len);
unsafe {
let mut c = zero;
for ii in 0..len {
let x = fb.ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
return fb
}
}
// **********************************************
// pub trait ToSinc<T> {
// fn sinc(self: &mut Self) -> &mut Self;
// }
// pub trait TestTrait: Sized {
// fn test_in_place(&mut self);
// fn test(mut self) -> Self {
// self.test_in_place();
// self
// }
// }
//
// impl<'a> TestTrait for &'a mut [i32] {
// fn test_in_place(self: &mut Self) {
// for x in (**self).iter_mut() {
// *x=*x*3;
// }
// }
// // fn test(self: mut Self) -> Self {
// // self.test_in
// // }
// }
// pub fn test(x: i32) -> i32 {
// let y=2*x;
// y
// }
//
// pub fn test2(x: Vec<i32>) {
// let y=x[0];
// }
pub trait ToSinc {
fn sinc(self: Self) -> Self;
}
// **********************************************
// pub fn sinc<T: ToSinc<T>>(y: &mut T) -> &mut T {
// y.sinc()
// }
pub fn sinc<T: ToSinc>(y: T) -> T {
y.sinc()
}
// **********************************************
// impl ToSinc<f64> for f64 {
// fn sinc(self: &mut Self) -> &mut Self {
// if *self!= 0f64 {
// *self = (*self*f64::consts::PI).sin()/(*self*f64::consts::PI);
// } else {
// *self = 1f64;
// }
// self
// }
// }
impl<'a> ToSinc for f64 {
fn sinc(self) -> Self {
let new: f64;
if self!= 0f64 {
let new = (self*f64::consts::PI).sin()/(self*f64::consts::PI);
return new
} else {
let new = 1f64;
return new
}
}
}
// **********************************************
// impl<'a> ToSinc<&'a mut [f64]> for &'a mut [f64] {
// fn sinc(self: &mut Self) -> &mut Self {
// for yi in (**self).iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// self
// }
// }
impl<'a> ToSinc for &'a mut [f64] {
fn sinc(self) -> Self {
for yi in (*self).iter_mut() {
if *yi!= 0f64 {
*yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
} else
|
}
self
}
}
// **********************************************
// pub fn sinc2(y: &mut f64) -> &mut f64 {
// if *y!= 0f64 {
// *y = (*y*f64::consts::PI).sin()/(*y*f64::pi());
// } else {
// *y = 1f64;
// }
// y
// }
//
// pub fn sinc(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// y
// }
// pub fn linspace(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::pi()).sin()/(*yi*f64::pi());
// } else {
// *yi = 1f64;
// }
// }
// y
// }
|
{
*yi = 1f64;
}
|
conditional_block
|
utils.rs
|
extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-access-numeric-constants-using-the-float-trait
pub trait Castd {
fn d(self: &Self) -> f64;
}
impl Castd for f32 {
fn d(self: &Self) -> f64 {*self as f64}
}
impl Castd for i32 {
fn d(self: &Self) -> f64
|
}
pub trait FloatConst {
fn pi() -> Self;
}
impl FloatConst for f32 {
fn pi() -> Self { f32::consts::PI }
}
impl FloatConst for f64 {
fn pi() -> Self { f64::consts::PI }
}
pub fn linspace_vec<'a, T: 'a>(start: T, stop: T, len: usize) ->
Vec<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
// let mut v = Vec::<T>::with_capacity(len);
//
// for i in 0..len {
// v.push(zero);
// }
let mut v = vec![zero; len];
let mut c = zero;
//**** SLOW ****
// for x in v.iter_mut() {
// *x = start + c*dx;
// c = c + one;
// }
//**** FAST ****
let ptr: *mut T = v.as_mut_ptr();
unsafe {
for ii in 0..len {
let x = ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
}
return v
}
pub fn kaiser<T>(length: usize, alpha: T) -> heapslice::HeapSlice<T> where T: Float+FloatConst {
let length_t: T = num::cast(length).unwrap();
let one = T::one();
let two: T = num::cast(2).unwrap();
let mut n = linspace_heapslice(T::zero(), (length_t-one), length);
for ni in n.iter_mut() {
let mut tmp= two*(*ni)/(length_t-one)-one;
tmp = T::pi()*alpha* ( one- tmp.powf(two) ).sqrt();
let tmpf64: f64 = num::cast(tmp).unwrap();
let grr: f64 = num::cast(T::pi()*alpha).unwrap();
let tmp2 = rgsl::bessel::I0(tmpf64) / rgsl::bessel::I0( grr );
*ni=num::cast(tmp2).unwrap();
}
return n
}
pub fn linspace_heapslice<'a, T: 'a>(start: T, stop: T, len: usize) -> heapslice::HeapSlice<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
let mut fb: heapslice::HeapSlice<T> = heapslice::HeapSlice::<T>::new();
fb.allocate(len);
unsafe {
let mut c = zero;
for ii in 0..len {
let x = fb.ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
return fb
}
}
// **********************************************
// pub trait ToSinc<T> {
// fn sinc(self: &mut Self) -> &mut Self;
// }
// pub trait TestTrait: Sized {
// fn test_in_place(&mut self);
// fn test(mut self) -> Self {
// self.test_in_place();
// self
// }
// }
//
// impl<'a> TestTrait for &'a mut [i32] {
// fn test_in_place(self: &mut Self) {
// for x in (**self).iter_mut() {
// *x=*x*3;
// }
// }
// // fn test(self: mut Self) -> Self {
// // self.test_in
// // }
// }
// pub fn test(x: i32) -> i32 {
// let y=2*x;
// y
// }
//
// pub fn test2(x: Vec<i32>) {
// let y=x[0];
// }
pub trait ToSinc {
fn sinc(self: Self) -> Self;
}
// **********************************************
// pub fn sinc<T: ToSinc<T>>(y: &mut T) -> &mut T {
// y.sinc()
// }
pub fn sinc<T: ToSinc>(y: T) -> T {
y.sinc()
}
// **********************************************
// impl ToSinc<f64> for f64 {
// fn sinc(self: &mut Self) -> &mut Self {
// if *self!= 0f64 {
// *self = (*self*f64::consts::PI).sin()/(*self*f64::consts::PI);
// } else {
// *self = 1f64;
// }
// self
// }
// }
impl<'a> ToSinc for f64 {
fn sinc(self) -> Self {
let new: f64;
if self!= 0f64 {
let new = (self*f64::consts::PI).sin()/(self*f64::consts::PI);
return new
} else {
let new = 1f64;
return new
}
}
}
// **********************************************
// impl<'a> ToSinc<&'a mut [f64]> for &'a mut [f64] {
// fn sinc(self: &mut Self) -> &mut Self {
// for yi in (**self).iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// self
// }
// }
impl<'a> ToSinc for &'a mut [f64] {
fn sinc(self) -> Self {
for yi in (*self).iter_mut() {
if *yi!= 0f64 {
*yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
} else {
*yi = 1f64;
}
}
self
}
}
// **********************************************
// pub fn sinc2(y: &mut f64) -> &mut f64 {
// if *y!= 0f64 {
// *y = (*y*f64::consts::PI).sin()/(*y*f64::pi());
// } else {
// *y = 1f64;
// }
// y
// }
//
// pub fn sinc(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// y
// }
// pub fn linspace(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::pi()).sin()/(*yi*f64::pi());
// } else {
// *yi = 1f64;
// }
// }
// y
// }
|
{*self as f64}
|
identifier_body
|
utils.rs
|
extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-access-numeric-constants-using-the-float-trait
pub trait Castd {
fn d(self: &Self) -> f64;
}
impl Castd for f32 {
fn d(self: &Self) -> f64 {*self as f64}
}
impl Castd for i32 {
fn d(self: &Self) -> f64 {*self as f64}
}
pub trait FloatConst {
fn pi() -> Self;
}
impl FloatConst for f32 {
fn pi() -> Self { f32::consts::PI }
}
impl FloatConst for f64 {
fn pi() -> Self { f64::consts::PI }
}
pub fn linspace_vec<'a, T: 'a>(start: T, stop: T, len: usize) ->
Vec<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
// let mut v = Vec::<T>::with_capacity(len);
//
// for i in 0..len {
// v.push(zero);
// }
let mut v = vec![zero; len];
let mut c = zero;
//**** SLOW ****
// for x in v.iter_mut() {
// *x = start + c*dx;
// c = c + one;
// }
//**** FAST ****
let ptr: *mut T = v.as_mut_ptr();
unsafe {
for ii in 0..len {
let x = ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
}
return v
}
pub fn kaiser<T>(length: usize, alpha: T) -> heapslice::HeapSlice<T> where T: Float+FloatConst {
let length_t: T = num::cast(length).unwrap();
let one = T::one();
let two: T = num::cast(2).unwrap();
let mut n = linspace_heapslice(T::zero(), (length_t-one), length);
for ni in n.iter_mut() {
let mut tmp= two*(*ni)/(length_t-one)-one;
tmp = T::pi()*alpha* ( one- tmp.powf(two) ).sqrt();
let tmpf64: f64 = num::cast(tmp).unwrap();
let grr: f64 = num::cast(T::pi()*alpha).unwrap();
let tmp2 = rgsl::bessel::I0(tmpf64) / rgsl::bessel::I0( grr );
*ni=num::cast(tmp2).unwrap();
}
return n
}
pub fn linspace_heapslice<'a, T: 'a>(start: T, stop: T, len: usize) -> heapslice::HeapSlice<T>
where T: Float {
let zero: T = T::zero();
let one: T = T::one();
let len_t_minus1: T = num::cast(len-1).unwrap();
let dx = (stop-start)/len_t_minus1;
let mut fb: heapslice::HeapSlice<T> = heapslice::HeapSlice::<T>::new();
fb.allocate(len);
unsafe {
let mut c = zero;
for ii in 0..len {
let x = fb.ptr.offset((ii as isize));
*x = start + c*dx;
c = c + one;
}
return fb
}
}
// **********************************************
// pub trait ToSinc<T> {
// fn sinc(self: &mut Self) -> &mut Self;
// }
// pub trait TestTrait: Sized {
// fn test_in_place(&mut self);
// fn test(mut self) -> Self {
// self.test_in_place();
// self
// }
// }
//
// impl<'a> TestTrait for &'a mut [i32] {
// fn test_in_place(self: &mut Self) {
// for x in (**self).iter_mut() {
// *x=*x*3;
// }
// }
// // fn test(self: mut Self) -> Self {
// // self.test_in
// // }
// }
// pub fn test(x: i32) -> i32 {
// let y=2*x;
// y
// }
//
// pub fn test2(x: Vec<i32>) {
// let y=x[0];
// }
pub trait ToSinc {
fn sinc(self: Self) -> Self;
}
// **********************************************
// pub fn sinc<T: ToSinc<T>>(y: &mut T) -> &mut T {
// y.sinc()
// }
pub fn sinc<T: ToSinc>(y: T) -> T {
y.sinc()
}
// **********************************************
// impl ToSinc<f64> for f64 {
// fn sinc(self: &mut Self) -> &mut Self {
// if *self!= 0f64 {
// *self = (*self*f64::consts::PI).sin()/(*self*f64::consts::PI);
// } else {
// *self = 1f64;
// }
// self
// }
// }
impl<'a> ToSinc for f64 {
fn sinc(self) -> Self {
let new: f64;
if self!= 0f64 {
let new = (self*f64::consts::PI).sin()/(self*f64::consts::PI);
return new
} else {
let new = 1f64;
return new
}
}
}
// **********************************************
// impl<'a> ToSinc<&'a mut [f64]> for &'a mut [f64] {
// fn sinc(self: &mut Self) -> &mut Self {
// for yi in (**self).iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// self
// }
// }
impl<'a> ToSinc for &'a mut [f64] {
fn
|
(self) -> Self {
for yi in (*self).iter_mut() {
if *yi!= 0f64 {
*yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
} else {
*yi = 1f64;
}
}
self
}
}
// **********************************************
// pub fn sinc2(y: &mut f64) -> &mut f64 {
// if *y!= 0f64 {
// *y = (*y*f64::consts::PI).sin()/(*y*f64::pi());
// } else {
// *y = 1f64;
// }
// y
// }
//
// pub fn sinc(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
// } else {
// *yi = 1f64;
// }
// }
// y
// }
// pub fn linspace(y: &mut [f64]) -> &mut [f64] {
// for yi in y.iter_mut() {
// if *yi!= 0f64 {
// *yi = (*yi*f64::pi()).sin()/(*yi*f64::pi());
// } else {
// *yi = 1f64;
// }
// }
// y
// }
|
sinc
|
identifier_name
|
p052.rs
|
//! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 10;
let repeat = 6;
let mut n = 0;
let mut order = 1;
let mut limit = (order - 1) / repeat;
loop {
n += 1;
if n > limit {
// skip if the num of digits of n * repeat is not the same with n.
n = order;
order *= radix;
limit = (order - 1) / repeat;
}
let ds = n.into_digit_histogram();
// n * 5 must contains 0 or 5.
if ds[0] == 0 && ds[5] == 0 { continue }
// n * 2, n * 4 must contains some evens.
if ds[0] == 0 && ds[2] == 0 && ds[4] == 0 && ds[6] == 0 && ds[8] == 0 {
continue
}
if ds!= (n * 2).into_digit_histogram() { continue }
if ds!= (n * 3).into_digit_histogram() { continue }
if ds!= (n * 4).into_digit_histogram() { continue }
if ds!= (n * 5).into_digit_histogram() { continue }
if ds!= (n * 6).into_digit_histogram() { continue }
return n
}
}
fn solve() -> String
|
problem!("142857", solve);
|
{
compute().to_string()
}
|
identifier_body
|
p052.rs
|
//! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 10;
let repeat = 6;
let mut n = 0;
let mut order = 1;
let mut limit = (order - 1) / repeat;
loop {
n += 1;
if n > limit {
// skip if the num of digits of n * repeat is not the same with n.
n = order;
order *= radix;
limit = (order - 1) / repeat;
}
let ds = n.into_digit_histogram();
// n * 5 must contains 0 or 5.
if ds[0] == 0 && ds[5] == 0 { continue }
// n * 2, n * 4 must contains some evens.
if ds[0] == 0 && ds[2] == 0 && ds[4] == 0 && ds[6] == 0 && ds[8] == 0 {
continue
}
if ds!= (n * 2).into_digit_histogram() { continue }
if ds!= (n * 3).into_digit_histogram() { continue }
if ds!= (n * 4).into_digit_histogram() { continue }
if ds!= (n * 5).into_digit_histogram() { continue }
|
return n
}
}
fn solve() -> String {
compute().to_string()
}
problem!("142857", solve);
|
if ds != (n * 6).into_digit_histogram() { continue }
|
random_line_split
|
p052.rs
|
//! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 10;
let repeat = 6;
let mut n = 0;
let mut order = 1;
let mut limit = (order - 1) / repeat;
loop {
n += 1;
if n > limit {
// skip if the num of digits of n * repeat is not the same with n.
n = order;
order *= radix;
limit = (order - 1) / repeat;
}
let ds = n.into_digit_histogram();
// n * 5 must contains 0 or 5.
if ds[0] == 0 && ds[5] == 0 { continue }
// n * 2, n * 4 must contains some evens.
if ds[0] == 0 && ds[2] == 0 && ds[4] == 0 && ds[6] == 0 && ds[8] == 0 {
continue
}
if ds!= (n * 2).into_digit_histogram() { continue }
if ds!= (n * 3).into_digit_histogram() { continue }
if ds!= (n * 4).into_digit_histogram() { continue }
if ds!= (n * 5).into_digit_histogram() { continue }
if ds!= (n * 6).into_digit_histogram() { continue }
return n
}
}
fn
|
() -> String {
compute().to_string()
}
problem!("142857", solve);
|
solve
|
identifier_name
|
p052.rs
|
//! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 10;
let repeat = 6;
let mut n = 0;
let mut order = 1;
let mut limit = (order - 1) / repeat;
loop {
n += 1;
if n > limit {
// skip if the num of digits of n * repeat is not the same with n.
n = order;
order *= radix;
limit = (order - 1) / repeat;
}
let ds = n.into_digit_histogram();
// n * 5 must contains 0 or 5.
if ds[0] == 0 && ds[5] == 0 { continue }
// n * 2, n * 4 must contains some evens.
if ds[0] == 0 && ds[2] == 0 && ds[4] == 0 && ds[6] == 0 && ds[8] == 0 {
continue
}
if ds!= (n * 2).into_digit_histogram() { continue }
if ds!= (n * 3).into_digit_histogram() { continue }
if ds!= (n * 4).into_digit_histogram()
|
if ds!= (n * 5).into_digit_histogram() { continue }
if ds!= (n * 6).into_digit_histogram() { continue }
return n
}
}
fn solve() -> String {
compute().to_string()
}
problem!("142857", solve);
|
{ continue }
|
conditional_block
|
cdn.rs
|
use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
return Loader {
prefix: prefix.to_owned(),
cache_dir: cache_dir.to_owned(),
client: hyper::Client::new()
};
}
pub fn default() -> Loader {
return Loader::new("http://developers.eveonline.com/ccpwgl/assetpath/967762", ".cache");
}
fn load_from_cache(&self, path: &str) -> Option<(String, Vec<u8>)> {
let file = self.cache_dir.clone() + path;
let mut f = match fs::File::open(file) {
Ok(f) => io::BufReader::new(f), _ => return None
};
let mut mime = String::new();
f.read_line(&mut mime).unwrap();
return Some((mime.trim().to_owned(), load_from_stream(&mut f)));
}
fn load_from_cdn(&self, path: &str) -> Option<(String, Vec<u8>)>
|
let data = load_from_stream(&mut response);
let file = self.cache_dir.clone() + path;
fs::create_dir_all(path::Path::new(file.as_str()).parent().unwrap()).unwrap();
let mut f = fs::File::create(file).unwrap();
write_to_stream(&mut f, &mime, &data);
return Some((mime, data));
}
}
impl resource_loaders::ResourceLoader for Loader {
fn load(&self, path: &str) -> Option<(String, Vec<u8>)> {
let result = self.load_from_cache(path);
return match result {
None => self.load_from_cdn(path),
Some(s) => Some(s)
};
}
}
fn load_from_stream(read: &mut Read) -> Vec<u8> {
let mut body = Vec::new();
read.read_to_end(&mut body).unwrap();
return body;
}
fn write_to_stream(write: &mut Write, mime: &String, data: &Vec<u8>) {
write.write_all(format!("{}\n", mime).as_bytes()).unwrap();
write.write_all(data.as_slice()).unwrap();
}
|
{
let url = self.prefix.clone() + path;
let mut response = match self.client.get(&url).send() {
Ok(r) => r, _ => return None
};
if response.status != hyper::status::StatusCode::Ok {
return None;
}
let mime = resource_loaders::path_to_mime(path).map(|x| x.to_owned()).unwrap_or_else(|| {
let headers = response.headers.clone();
match headers.get::<hyper::header::ContentType>() {
Some(&hyper::header::ContentType(ref s)) => s.clone(),
None => "application/octet-stream".parse().unwrap()
}.to_string()
});
|
identifier_body
|
cdn.rs
|
use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
return Loader {
prefix: prefix.to_owned(),
cache_dir: cache_dir.to_owned(),
client: hyper::Client::new()
};
}
pub fn default() -> Loader {
return Loader::new("http://developers.eveonline.com/ccpwgl/assetpath/967762", ".cache");
}
|
let mut f = match fs::File::open(file) {
Ok(f) => io::BufReader::new(f), _ => return None
};
let mut mime = String::new();
f.read_line(&mut mime).unwrap();
return Some((mime.trim().to_owned(), load_from_stream(&mut f)));
}
fn load_from_cdn(&self, path: &str) -> Option<(String, Vec<u8>)> {
let url = self.prefix.clone() + path;
let mut response = match self.client.get(&url).send() {
Ok(r) => r, _ => return None
};
if response.status!= hyper::status::StatusCode::Ok {
return None;
}
let mime = resource_loaders::path_to_mime(path).map(|x| x.to_owned()).unwrap_or_else(|| {
let headers = response.headers.clone();
match headers.get::<hyper::header::ContentType>() {
Some(&hyper::header::ContentType(ref s)) => s.clone(),
None => "application/octet-stream".parse().unwrap()
}.to_string()
});
let data = load_from_stream(&mut response);
let file = self.cache_dir.clone() + path;
fs::create_dir_all(path::Path::new(file.as_str()).parent().unwrap()).unwrap();
let mut f = fs::File::create(file).unwrap();
write_to_stream(&mut f, &mime, &data);
return Some((mime, data));
}
}
impl resource_loaders::ResourceLoader for Loader {
fn load(&self, path: &str) -> Option<(String, Vec<u8>)> {
let result = self.load_from_cache(path);
return match result {
None => self.load_from_cdn(path),
Some(s) => Some(s)
};
}
}
fn load_from_stream(read: &mut Read) -> Vec<u8> {
let mut body = Vec::new();
read.read_to_end(&mut body).unwrap();
return body;
}
fn write_to_stream(write: &mut Write, mime: &String, data: &Vec<u8>) {
write.write_all(format!("{}\n", mime).as_bytes()).unwrap();
write.write_all(data.as_slice()).unwrap();
}
|
fn load_from_cache(&self, path: &str) -> Option<(String, Vec<u8>)> {
let file = self.cache_dir.clone() + path;
|
random_line_split
|
cdn.rs
|
use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
return Loader {
prefix: prefix.to_owned(),
cache_dir: cache_dir.to_owned(),
client: hyper::Client::new()
};
}
pub fn default() -> Loader {
return Loader::new("http://developers.eveonline.com/ccpwgl/assetpath/967762", ".cache");
}
fn load_from_cache(&self, path: &str) -> Option<(String, Vec<u8>)> {
let file = self.cache_dir.clone() + path;
let mut f = match fs::File::open(file) {
Ok(f) => io::BufReader::new(f), _ => return None
};
let mut mime = String::new();
f.read_line(&mut mime).unwrap();
return Some((mime.trim().to_owned(), load_from_stream(&mut f)));
}
fn load_from_cdn(&self, path: &str) -> Option<(String, Vec<u8>)> {
let url = self.prefix.clone() + path;
let mut response = match self.client.get(&url).send() {
Ok(r) => r, _ => return None
};
if response.status!= hyper::status::StatusCode::Ok {
return None;
}
let mime = resource_loaders::path_to_mime(path).map(|x| x.to_owned()).unwrap_or_else(|| {
let headers = response.headers.clone();
match headers.get::<hyper::header::ContentType>() {
Some(&hyper::header::ContentType(ref s)) => s.clone(),
None => "application/octet-stream".parse().unwrap()
}.to_string()
});
let data = load_from_stream(&mut response);
let file = self.cache_dir.clone() + path;
fs::create_dir_all(path::Path::new(file.as_str()).parent().unwrap()).unwrap();
let mut f = fs::File::create(file).unwrap();
write_to_stream(&mut f, &mime, &data);
return Some((mime, data));
}
}
impl resource_loaders::ResourceLoader for Loader {
fn load(&self, path: &str) -> Option<(String, Vec<u8>)> {
let result = self.load_from_cache(path);
return match result {
None => self.load_from_cdn(path),
Some(s) => Some(s)
};
}
}
fn load_from_stream(read: &mut Read) -> Vec<u8> {
let mut body = Vec::new();
read.read_to_end(&mut body).unwrap();
return body;
}
fn
|
(write: &mut Write, mime: &String, data: &Vec<u8>) {
write.write_all(format!("{}\n", mime).as_bytes()).unwrap();
write.write_all(data.as_slice()).unwrap();
}
|
write_to_stream
|
identifier_name
|
jstraceable.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty};
use syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef};
use syntax::ptr::P;
pub fn expand_dom_struct(cx: &mut ExtCtxt, sp: Span, _: &MetaItem, anno: Annotatable) -> Annotatable {
if let Annotatable::Item(item) = anno
|
else {
cx.span_err(sp, "#[dom_struct] applied to something other than a struct");
anno
}
}
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not
/// implement the method.
pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::new(),
generics: ty::LifetimeBounds::empty(),
methods: vec![
MethodDef {
name: "trace",
generics: ty::LifetimeBounds::empty(),
explicit_self: ty::borrowed_explicit_self(),
args: vec!(ty::Ptr(box ty::Literal(ty::Path::new(vec!("js","jsapi","JSTracer"))),
ty::Raw(ast::MutMutable))),
ret_ty: ty::nil_ty(),
attributes: vec![quote_attr!(cx, #[inline])],
is_unsafe: false,
combine_substructure: combine_substructure(box jstraceable_substructure)
}
],
associated_types: vec![],
};
trait_def.expand(cx, mitem, item, push)
}
// Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated
fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let state_expr = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`")
};
let trace_ident = substr.method_ident;
let call_trace = |span, thing_expr| {
let expr = cx.expr_method_call(span, thing_expr, trace_ident, vec!(state_expr.clone()));
cx.stmt_expr(expr)
};
let mut stmts = Vec::new();
let fields = match *substr.fields {
Struct(ref fs) | EnumMatching(_, _, ref fs) => fs,
_ => cx.span_bug(trait_span, "impossible substructure in `jstraceable`")
};
for &FieldInfo { ref self_, span,.. } in fields {
stmts.push(call_trace(span, self_.clone()));
}
cx.expr_block(cx.block(trait_span, stmts, None))
}
|
{
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for internal usage
item2.attrs.push(quote_attr!(cx, #[_generate_reflector]));
// #[dom_struct] gets consumed, so this lets us keep around a residue
// Do NOT register a modifier/decorator on this attribute
item2.attrs.push(quote_attr!(cx, #[_dom_struct_marker]));
Annotatable::Item(P(item2))
}
|
conditional_block
|
jstraceable.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty};
use syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef};
use syntax::ptr::P;
pub fn expand_dom_struct(cx: &mut ExtCtxt, sp: Span, _: &MetaItem, anno: Annotatable) -> Annotatable
|
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not
/// implement the method.
pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::new(),
generics: ty::LifetimeBounds::empty(),
methods: vec![
MethodDef {
name: "trace",
generics: ty::LifetimeBounds::empty(),
explicit_self: ty::borrowed_explicit_self(),
args: vec!(ty::Ptr(box ty::Literal(ty::Path::new(vec!("js","jsapi","JSTracer"))),
ty::Raw(ast::MutMutable))),
ret_ty: ty::nil_ty(),
attributes: vec![quote_attr!(cx, #[inline])],
is_unsafe: false,
combine_substructure: combine_substructure(box jstraceable_substructure)
}
],
associated_types: vec![],
};
trait_def.expand(cx, mitem, item, push)
}
// Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated
fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let state_expr = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`")
};
let trace_ident = substr.method_ident;
let call_trace = |span, thing_expr| {
let expr = cx.expr_method_call(span, thing_expr, trace_ident, vec!(state_expr.clone()));
cx.stmt_expr(expr)
};
let mut stmts = Vec::new();
let fields = match *substr.fields {
Struct(ref fs) | EnumMatching(_, _, ref fs) => fs,
_ => cx.span_bug(trait_span, "impossible substructure in `jstraceable`")
};
for &FieldInfo { ref self_, span,.. } in fields {
stmts.push(call_trace(span, self_.clone()));
}
cx.expr_block(cx.block(trait_span, stmts, None))
}
|
{
if let Annotatable::Item(item) = anno {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for internal usage
item2.attrs.push(quote_attr!(cx, #[_generate_reflector]));
// #[dom_struct] gets consumed, so this lets us keep around a residue
// Do NOT register a modifier/decorator on this attribute
item2.attrs.push(quote_attr!(cx, #[_dom_struct_marker]));
Annotatable::Item(P(item2))
} else {
cx.span_err(sp, "#[dom_struct] applied to something other than a struct");
anno
}
}
|
identifier_body
|
jstraceable.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty};
use syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef};
use syntax::ptr::P;
pub fn expand_dom_struct(cx: &mut ExtCtxt, sp: Span, _: &MetaItem, anno: Annotatable) -> Annotatable {
if let Annotatable::Item(item) = anno {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for internal usage
item2.attrs.push(quote_attr!(cx, #[_generate_reflector]));
// #[dom_struct] gets consumed, so this lets us keep around a residue
// Do NOT register a modifier/decorator on this attribute
item2.attrs.push(quote_attr!(cx, #[_dom_struct_marker]));
Annotatable::Item(P(item2))
} else {
cx.span_err(sp, "#[dom_struct] applied to something other than a struct");
anno
}
}
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not
/// implement the method.
pub fn expand_jstraceable(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::new(),
generics: ty::LifetimeBounds::empty(),
methods: vec![
MethodDef {
name: "trace",
generics: ty::LifetimeBounds::empty(),
explicit_self: ty::borrowed_explicit_self(),
args: vec!(ty::Ptr(box ty::Literal(ty::Path::new(vec!("js","jsapi","JSTracer"))),
ty::Raw(ast::MutMutable))),
ret_ty: ty::nil_ty(),
attributes: vec![quote_attr!(cx, #[inline])],
is_unsafe: false,
combine_substructure: combine_substructure(box jstraceable_substructure)
}
],
associated_types: vec![],
};
trait_def.expand(cx, mitem, item, push)
}
// Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated
fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let state_expr = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`")
};
let trace_ident = substr.method_ident;
let call_trace = |span, thing_expr| {
let expr = cx.expr_method_call(span, thing_expr, trace_ident, vec!(state_expr.clone()));
cx.stmt_expr(expr)
};
let mut stmts = Vec::new();
let fields = match *substr.fields {
|
for &FieldInfo { ref self_, span,.. } in fields {
stmts.push(call_trace(span, self_.clone()));
}
cx.expr_block(cx.block(trait_span, stmts, None))
}
|
Struct(ref fs) | EnumMatching(_, _, ref fs) => fs,
_ => cx.span_bug(trait_span, "impossible substructure in `jstraceable`")
};
|
random_line_split
|
jstraceable.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ast;
use syntax::ast::{MetaItem, Expr};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty};
use syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef};
use syntax::ptr::P;
pub fn expand_dom_struct(cx: &mut ExtCtxt, sp: Span, _: &MetaItem, anno: Annotatable) -> Annotatable {
if let Annotatable::Item(item) = anno {
let mut item2 = (*item).clone();
item2.attrs.push(quote_attr!(cx, #[must_root]));
item2.attrs.push(quote_attr!(cx, #[privatize]));
item2.attrs.push(quote_attr!(cx, #[derive(JSTraceable)]));
// The following attributes are only for internal usage
item2.attrs.push(quote_attr!(cx, #[_generate_reflector]));
// #[dom_struct] gets consumed, so this lets us keep around a residue
// Do NOT register a modifier/decorator on this attribute
item2.attrs.push(quote_attr!(cx, #[_dom_struct_marker]));
Annotatable::Item(P(item2))
} else {
cx.span_err(sp, "#[dom_struct] applied to something other than a struct");
anno
}
}
/// Provides the hook to expand `#[derive(JSTraceable)]` into an implementation of `JSTraceable`
///
/// The expansion basically calls `trace()` on all of the fields of the struct/enum, erroring if they do not
/// implement the method.
pub fn
|
(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::new(),
generics: ty::LifetimeBounds::empty(),
methods: vec![
MethodDef {
name: "trace",
generics: ty::LifetimeBounds::empty(),
explicit_self: ty::borrowed_explicit_self(),
args: vec!(ty::Ptr(box ty::Literal(ty::Path::new(vec!("js","jsapi","JSTracer"))),
ty::Raw(ast::MutMutable))),
ret_ty: ty::nil_ty(),
attributes: vec![quote_attr!(cx, #[inline])],
is_unsafe: false,
combine_substructure: combine_substructure(box jstraceable_substructure)
}
],
associated_types: vec![],
};
trait_def.expand(cx, mitem, item, push)
}
// Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated
fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let state_expr = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`")
};
let trace_ident = substr.method_ident;
let call_trace = |span, thing_expr| {
let expr = cx.expr_method_call(span, thing_expr, trace_ident, vec!(state_expr.clone()));
cx.stmt_expr(expr)
};
let mut stmts = Vec::new();
let fields = match *substr.fields {
Struct(ref fs) | EnumMatching(_, _, ref fs) => fs,
_ => cx.span_bug(trait_span, "impossible substructure in `jstraceable`")
};
for &FieldInfo { ref self_, span,.. } in fields {
stmts.push(call_trace(span, self_.clone()));
}
cx.expr_block(cx.block(trait_span, stmts, None))
}
|
expand_jstraceable
|
identifier_name
|
signus.rs
|
use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_string(), ::utils::constants::VERKEY.to_string()));
}
let my_did_json = json!({"seed": seed, "method_name": method_name});
did::create_and_store_my_did(get_wallet_handle(), &my_did_json.to_string())
.wait()
.map_err(VcxError::from)
}
pub fn get_local_verkey(did: &str) -> VcxResult<String> {
if settings::indy_mocks_enabled()
|
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
}
|
{
return Ok(::utils::constants::VERKEY.to_string());
}
|
conditional_block
|
signus.rs
|
use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_string(), ::utils::constants::VERKEY.to_string()));
}
let my_did_json = json!({"seed": seed, "method_name": method_name});
|
did::create_and_store_my_did(get_wallet_handle(), &my_did_json.to_string())
.wait()
.map_err(VcxError::from)
}
pub fn get_local_verkey(did: &str) -> VcxResult<String> {
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
}
|
random_line_split
|
|
signus.rs
|
use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn
|
(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_string(), ::utils::constants::VERKEY.to_string()));
}
let my_did_json = json!({"seed": seed, "method_name": method_name});
did::create_and_store_my_did(get_wallet_handle(), &my_did_json.to_string())
.wait()
.map_err(VcxError::from)
}
pub fn get_local_verkey(did: &str) -> VcxResult<String> {
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
}
|
create_and_store_my_did
|
identifier_name
|
signus.rs
|
use futures::Future;
use indy::did;
use settings;
use utils::libindy::wallet::get_wallet_handle;
use error::prelude::*;
pub fn create_and_store_my_did(seed: Option<&str>, method_name: Option<&str>) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() {
return Ok((::utils::constants::DID.to_string(), ::utils::constants::VERKEY.to_string()));
}
let my_did_json = json!({"seed": seed, "method_name": method_name});
did::create_and_store_my_did(get_wallet_handle(), &my_did_json.to_string())
.wait()
.map_err(VcxError::from)
}
pub fn get_local_verkey(did: &str) -> VcxResult<String>
|
{
if settings::indy_mocks_enabled() {
return Ok(::utils::constants::VERKEY.to_string());
}
did::key_for_local_did(get_wallet_handle(), did)
.wait()
.map_err(VcxError::from)
}
|
identifier_body
|
|
test_common.rs
|
// Copyright 2015-2017 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/>.
pub use bigint::prelude::U256;
pub use bigint::hash::H256;
pub use util::*;
use std::collections::HashSet;
use std::io::Read;
use std::fs::{File, read_dir};
use std::path::Path;
use std::ffi::OsString;
pub fn run_test_path(p: &Path, skip: &[&'static str], runner: fn (json_data: &[u8]) -> Vec<String>) {
let path = Path::new(p);
let s: HashSet<OsString> = skip.iter().map(|s| {
let mut os: OsString = s.into();
os.push(".json");
os
}).collect();
if path.is_dir() {
for p in read_dir(path).unwrap().filter_map(|e| {
let e = e.unwrap();
if s.contains(&e.file_name()) {
None
} else {
Some(e.path())
}}) {
run_test_path(&p, skip, runner)
}
} else {
let mut path = p.to_path_buf();
path.set_extension("json");
run_test_file(&path, runner)
}
}
pub fn run_test_file(path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>)
|
macro_rules! test {
($name: expr, $skip: expr) => {
::json_tests::test_common::run_test_path(::std::path::Path::new(concat!("res/ethereum/tests/", $name)), &$skip, do_json_test);
}
}
#[macro_export]
macro_rules! declare_test {
(skip => $arr: expr, $id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, $arr);
}
};
(ignore => $id: ident, $name: expr) => {
#[ignore]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
(heavy => $id: ident, $name: expr) => {
#[cfg(feature = "test-heavy")]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
($id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
}
}
|
{
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
}
|
identifier_body
|
test_common.rs
|
// Copyright 2015-2017 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/>.
pub use bigint::prelude::U256;
pub use bigint::hash::H256;
pub use util::*;
use std::collections::HashSet;
use std::io::Read;
use std::fs::{File, read_dir};
use std::path::Path;
use std::ffi::OsString;
pub fn run_test_path(p: &Path, skip: &[&'static str], runner: fn (json_data: &[u8]) -> Vec<String>) {
let path = Path::new(p);
let s: HashSet<OsString> = skip.iter().map(|s| {
let mut os: OsString = s.into();
os.push(".json");
os
}).collect();
if path.is_dir() {
for p in read_dir(path).unwrap().filter_map(|e| {
let e = e.unwrap();
if s.contains(&e.file_name()) {
None
} else
|
}) {
run_test_path(&p, skip, runner)
}
} else {
let mut path = p.to_path_buf();
path.set_extension("json");
run_test_file(&path, runner)
}
}
pub fn run_test_file(path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
}
macro_rules! test {
($name: expr, $skip: expr) => {
::json_tests::test_common::run_test_path(::std::path::Path::new(concat!("res/ethereum/tests/", $name)), &$skip, do_json_test);
}
}
#[macro_export]
macro_rules! declare_test {
(skip => $arr: expr, $id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, $arr);
}
};
(ignore => $id: ident, $name: expr) => {
#[ignore]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
(heavy => $id: ident, $name: expr) => {
#[cfg(feature = "test-heavy")]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
($id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
}
}
|
{
Some(e.path())
}
|
conditional_block
|
test_common.rs
|
// Copyright 2015-2017 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/>.
pub use bigint::prelude::U256;
pub use bigint::hash::H256;
pub use util::*;
use std::collections::HashSet;
use std::io::Read;
use std::fs::{File, read_dir};
use std::path::Path;
use std::ffi::OsString;
pub fn run_test_path(p: &Path, skip: &[&'static str], runner: fn (json_data: &[u8]) -> Vec<String>) {
let path = Path::new(p);
let s: HashSet<OsString> = skip.iter().map(|s| {
let mut os: OsString = s.into();
os.push(".json");
os
}).collect();
if path.is_dir() {
for p in read_dir(path).unwrap().filter_map(|e| {
let e = e.unwrap();
if s.contains(&e.file_name()) {
None
} else {
Some(e.path())
}}) {
run_test_path(&p, skip, runner)
}
} else {
let mut path = p.to_path_buf();
path.set_extension("json");
run_test_file(&path, runner)
}
}
pub fn run_test_file(path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
}
macro_rules! test {
($name: expr, $skip: expr) => {
::json_tests::test_common::run_test_path(::std::path::Path::new(concat!("res/ethereum/tests/", $name)), &$skip, do_json_test);
}
}
#[macro_export]
macro_rules! declare_test {
(skip => $arr: expr, $id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, $arr);
}
};
(ignore => $id: ident, $name: expr) => {
#[ignore]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
(heavy => $id: ident, $name: expr) => {
#[cfg(feature = "test-heavy")]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
($id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
|
}
}
|
random_line_split
|
|
test_common.rs
|
// Copyright 2015-2017 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/>.
pub use bigint::prelude::U256;
pub use bigint::hash::H256;
pub use util::*;
use std::collections::HashSet;
use std::io::Read;
use std::fs::{File, read_dir};
use std::path::Path;
use std::ffi::OsString;
pub fn run_test_path(p: &Path, skip: &[&'static str], runner: fn (json_data: &[u8]) -> Vec<String>) {
let path = Path::new(p);
let s: HashSet<OsString> = skip.iter().map(|s| {
let mut os: OsString = s.into();
os.push(".json");
os
}).collect();
if path.is_dir() {
for p in read_dir(path).unwrap().filter_map(|e| {
let e = e.unwrap();
if s.contains(&e.file_name()) {
None
} else {
Some(e.path())
}}) {
run_test_path(&p, skip, runner)
}
} else {
let mut path = p.to_path_buf();
path.set_extension("json");
run_test_file(&path, runner)
}
}
pub fn
|
(path: &Path, runner: fn (json_data: &[u8]) -> Vec<String>) {
let mut data = Vec::new();
let mut file = File::open(&path).expect("Error opening test file");
file.read_to_end(&mut data).expect("Error reading test file");
let results = runner(&data);
let empty: [String; 0] = [];
assert_eq!(results, empty);
}
macro_rules! test {
($name: expr, $skip: expr) => {
::json_tests::test_common::run_test_path(::std::path::Path::new(concat!("res/ethereum/tests/", $name)), &$skip, do_json_test);
}
}
#[macro_export]
macro_rules! declare_test {
(skip => $arr: expr, $id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, $arr);
}
};
(ignore => $id: ident, $name: expr) => {
#[ignore]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
(heavy => $id: ident, $name: expr) => {
#[cfg(feature = "test-heavy")]
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
};
($id: ident, $name: expr) => {
#[test]
#[allow(non_snake_case)]
fn $id() {
test!($name, []);
}
}
}
|
run_test_file
|
identifier_name
|
extern-types-pointer-cast.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(dead_code)]
// Test that pointers to extern types can be cast from/to usize,
// despite being!Sized.
#![feature(extern_types)]
extern {
type A;
}
struct Foo {
x: u8,
tail: A,
}
struct Bar<T:?Sized> {
x: u8,
tail: T,
}
#[cfg(target_pointer_width = "32")]
const MAGIC: usize = 0xdeadbeef;
#[cfg(target_pointer_width = "64")]
const MAGIC: usize = 0x12345678deadbeef;
|
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
}
|
fn main() {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
|
random_line_split
|
extern-types-pointer-cast.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(dead_code)]
// Test that pointers to extern types can be cast from/to usize,
// despite being!Sized.
#![feature(extern_types)]
extern {
type A;
}
struct Foo {
x: u8,
tail: A,
}
struct Bar<T:?Sized> {
x: u8,
tail: T,
}
#[cfg(target_pointer_width = "32")]
const MAGIC: usize = 0xdeadbeef;
#[cfg(target_pointer_width = "64")]
const MAGIC: usize = 0x12345678deadbeef;
fn main()
|
{
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
}
|
identifier_body
|
|
extern-types-pointer-cast.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(dead_code)]
// Test that pointers to extern types can be cast from/to usize,
// despite being!Sized.
#![feature(extern_types)]
extern {
type A;
}
struct Foo {
x: u8,
tail: A,
}
struct Bar<T:?Sized> {
x: u8,
tail: T,
}
#[cfg(target_pointer_width = "32")]
const MAGIC: usize = 0xdeadbeef;
#[cfg(target_pointer_width = "64")]
const MAGIC: usize = 0x12345678deadbeef;
fn
|
() {
assert_eq!((MAGIC as *const A) as usize, MAGIC);
assert_eq!((MAGIC as *const Foo) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<A>) as usize, MAGIC);
assert_eq!((MAGIC as *const Bar<Bar<A>>) as usize, MAGIC);
}
|
main
|
identifier_name
|
num.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates the IDL restricted float type.
#[derive(JSTraceable,Clone,Eq,PartialEq)]
pub struct Finite<T: Float>(T);
unsafe impl<T: Float> Zeroable for Finite<T> {}
impl<T: Float> Finite<T> {
/// Create a new `Finite<T: Float>` safely.
pub fn
|
(value: T) -> Option<Finite<T>> {
if value.is_finite() {
Some(Finite(value))
} else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value.");
Finite(value)
}
}
impl<T: Float> Deref for Finite<T> {
type Target = T;
fn deref(&self) -> &T {
let &Finite(ref value) = self;
value
}
}
|
new
|
identifier_name
|
num.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates the IDL restricted float type.
#[derive(JSTraceable,Clone,Eq,PartialEq)]
pub struct Finite<T: Float>(T);
unsafe impl<T: Float> Zeroable for Finite<T> {}
impl<T: Float> Finite<T> {
/// Create a new `Finite<T: Float>` safely.
pub fn new(value: T) -> Option<Finite<T>> {
if value.is_finite() {
Some(Finite(value))
} else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value.");
Finite(value)
}
}
|
type Target = T;
fn deref(&self) -> &T {
let &Finite(ref value) = self;
value
}
}
|
impl<T: Float> Deref for Finite<T> {
|
random_line_split
|
num.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Finite<T>` struct.
use core::nonzero::Zeroable;
use num::Float;
use std::ops::Deref;
/// Encapsulates the IDL restricted float type.
#[derive(JSTraceable,Clone,Eq,PartialEq)]
pub struct Finite<T: Float>(T);
unsafe impl<T: Float> Zeroable for Finite<T> {}
impl<T: Float> Finite<T> {
/// Create a new `Finite<T: Float>` safely.
pub fn new(value: T) -> Option<Finite<T>> {
if value.is_finite()
|
else {
None
}
}
/// Create a new `Finite<T: Float>`.
#[inline]
pub fn wrap(value: T) -> Finite<T> {
assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value.");
Finite(value)
}
}
impl<T: Float> Deref for Finite<T> {
type Target = T;
fn deref(&self) -> &T {
let &Finite(ref value) = self;
value
}
}
|
{
Some(Finite(value))
}
|
conditional_block
|
jupyter_message.rs
|
// Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::connection::{Connection, HmacSha256};
use anyhow::{anyhow, bail, Result};
use chrono::Utc;
use generic_array::GenericArray;
use json::{self, JsonValue};
use std::{self, fmt};
use uuid::Uuid;
struct RawMessage {
zmq_identities: Vec<Vec<u8>>,
jparts: Vec<Vec<u8>>,
}
impl RawMessage {
pub(crate) fn read(connection: &Connection) -> Result<RawMessage> {
Self::from_multipart(connection.socket.recv_multipart(0)?, connection)
}
pub(crate) fn from_multipart(
mut multipart: Vec<Vec<u8>>,
connection: &Connection,
) -> Result<RawMessage> {
let delimiter_index = multipart
.iter()
.position(|part| &part[..] == DELIMITER)
.ok_or_else(|| anyhow!("Missing delimeter"))?;
let jparts: Vec<_> = multipart.drain(delimiter_index + 2..).collect();
let hmac = multipart.pop().unwrap();
// Remove delimiter, so that what's left is just the identities.
multipart.pop();
let zmq_identities = multipart;
let raw_message = RawMessage {
zmq_identities,
jparts,
};
if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
raw_message.digest(&mut mac);
use hmac::Mac;
if let Err(error) = mac.verify(GenericArray::from_slice(&hex::decode(&hmac)?)) {
bail!("{}", error);
}
}
Ok(raw_message)
}
fn send(self, connection: &Connection) -> Result<()> {
use hmac::Mac;
let hmac = if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
self.digest(&mut mac);
hex::encode(mac.finalize().into_bytes().as_slice())
} else {
String::new()
};
let mut parts: Vec<&[u8]> = Vec::new();
for part in &self.zmq_identities {
parts.push(part);
}
parts.push(DELIMITER);
parts.push(hmac.as_bytes());
for part in &self.jparts {
parts.push(part);
}
connection.socket.send_multipart(&parts, 0)?;
Ok(())
}
fn digest(&self, mac: &mut HmacSha256) {
use hmac::Mac;
for part in &self.jparts {
mac.update(part);
}
}
}
#[derive(Clone)]
pub(crate) struct JupyterMessage {
zmq_identities: Vec<Vec<u8>>,
header: JsonValue,
parent_header: JsonValue,
metadata: JsonValue,
content: JsonValue,
}
const DELIMITER: &[u8] = b"<IDS|MSG>";
impl JupyterMessage {
pub(crate) fn read(connection: &Connection) -> Result<JupyterMessage> {
Self::from_raw_message(RawMessage::read(connection)?)
}
fn from_raw_message(raw_message: RawMessage) -> Result<JupyterMessage> {
fn message_to_json(message: &[u8]) -> Result<JsonValue> {
Ok(json::parse(std::str::from_utf8(message)?)?)
}
if raw_message.jparts.len() < 4 {
bail!("Insufficient message parts {}", raw_message.jparts.len());
}
Ok(JupyterMessage {
zmq_identities: raw_message.zmq_identities,
header: message_to_json(&raw_message.jparts[0])?,
parent_header: message_to_json(&raw_message.jparts[1])?,
metadata: message_to_json(&raw_message.jparts[2])?,
content: message_to_json(&raw_message.jparts[3])?,
})
}
pub(crate) fn message_type(&self) -> &str {
self.header["msg_type"].as_str().unwrap_or("")
}
pub(crate) fn code(&self) -> &str {
self.content["code"].as_str().unwrap_or("")
}
pub(crate) fn cursor_pos(&self) -> usize {
self.content["cursor_pos"].as_usize().unwrap_or_default()
}
pub(crate) fn target_name(&self) -> &str {
self.content["target_name"].as_str().unwrap_or("")
}
pub(crate) fn data(&self) -> &JsonValue {
&self.content["data"]
}
pub(crate) fn comm_id(&self) -> &str {
self.content["comm_id"].as_str().unwrap_or("")
}
|
header["msg_type"] = JsonValue::String(msg_type.to_owned());
header["username"] = JsonValue::String("kernel".to_owned());
header["msg_id"] = JsonValue::String(Uuid::new_v4().to_string());
header["date"] = JsonValue::String(Utc::now().to_rfc3339());
JupyterMessage {
zmq_identities: Vec::new(),
header,
parent_header: self.header.clone(),
metadata: JsonValue::new_object(),
content: JsonValue::new_object(),
}
}
// Creates a reply to this message. This is a child with the message type determined
// automatically by replacing "request" with "reply". ZMQ identities are transferred.
pub(crate) fn new_reply(&self) -> JupyterMessage {
let mut reply = self.new_message(&self.message_type().replace("_request", "_reply"));
reply.zmq_identities = self.zmq_identities.clone();
reply
}
#[must_use = "Need to send this message for it to have any effect"]
pub(crate) fn comm_close_message(&self) -> JupyterMessage {
self.new_message("comm_close").with_content(object! {
"comm_id" => self.comm_id()
})
}
pub(crate) fn get_content(&self) -> &JsonValue {
&self.content
}
pub(crate) fn with_content(mut self, content: JsonValue) -> JupyterMessage {
self.content = content;
self
}
pub(crate) fn with_message_type(mut self, msg_type: &str) -> JupyterMessage {
self.header["msg_type"] = JsonValue::String(msg_type.to_owned());
self
}
pub(crate) fn without_parent_header(mut self) -> JupyterMessage {
self.parent_header = object! {};
self
}
pub(crate) fn send(&self, connection: &Connection) -> Result<()> {
// If performance is a concern, we can probably avoid the clone and to_vec calls with a bit
// of refactoring.
let raw_message = RawMessage {
zmq_identities: self.zmq_identities.clone(),
jparts: vec![
self.header.dump().as_bytes().to_vec(),
self.parent_header.dump().as_bytes().to_vec(),
self.metadata.dump().as_bytes().to_vec(),
self.content.dump().as_bytes().to_vec(),
],
};
raw_message.send(connection)
}
}
impl fmt::Debug for JupyterMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "\nHEADER {}", self.header.pretty(2))?;
writeln!(f, "PARENT_HEADER {}", self.parent_header.pretty(2))?;
writeln!(f, "METADATA {}", self.metadata.pretty(2))?;
writeln!(f, "CONTENT {}\n", self.content.pretty(2))?;
Ok(())
}
}
|
// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone();
|
random_line_split
|
jupyter_message.rs
|
// Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::connection::{Connection, HmacSha256};
use anyhow::{anyhow, bail, Result};
use chrono::Utc;
use generic_array::GenericArray;
use json::{self, JsonValue};
use std::{self, fmt};
use uuid::Uuid;
struct RawMessage {
zmq_identities: Vec<Vec<u8>>,
jparts: Vec<Vec<u8>>,
}
impl RawMessage {
pub(crate) fn read(connection: &Connection) -> Result<RawMessage> {
Self::from_multipart(connection.socket.recv_multipart(0)?, connection)
}
pub(crate) fn from_multipart(
mut multipart: Vec<Vec<u8>>,
connection: &Connection,
) -> Result<RawMessage> {
let delimiter_index = multipart
.iter()
.position(|part| &part[..] == DELIMITER)
.ok_or_else(|| anyhow!("Missing delimeter"))?;
let jparts: Vec<_> = multipart.drain(delimiter_index + 2..).collect();
let hmac = multipart.pop().unwrap();
// Remove delimiter, so that what's left is just the identities.
multipart.pop();
let zmq_identities = multipart;
let raw_message = RawMessage {
zmq_identities,
jparts,
};
if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
raw_message.digest(&mut mac);
use hmac::Mac;
if let Err(error) = mac.verify(GenericArray::from_slice(&hex::decode(&hmac)?)) {
bail!("{}", error);
}
}
Ok(raw_message)
}
fn send(self, connection: &Connection) -> Result<()> {
use hmac::Mac;
let hmac = if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
self.digest(&mut mac);
hex::encode(mac.finalize().into_bytes().as_slice())
} else {
String::new()
};
let mut parts: Vec<&[u8]> = Vec::new();
for part in &self.zmq_identities {
parts.push(part);
}
parts.push(DELIMITER);
parts.push(hmac.as_bytes());
for part in &self.jparts {
parts.push(part);
}
connection.socket.send_multipart(&parts, 0)?;
Ok(())
}
fn digest(&self, mac: &mut HmacSha256) {
use hmac::Mac;
for part in &self.jparts {
mac.update(part);
}
}
}
#[derive(Clone)]
pub(crate) struct JupyterMessage {
zmq_identities: Vec<Vec<u8>>,
header: JsonValue,
parent_header: JsonValue,
metadata: JsonValue,
content: JsonValue,
}
const DELIMITER: &[u8] = b"<IDS|MSG>";
impl JupyterMessage {
pub(crate) fn read(connection: &Connection) -> Result<JupyterMessage>
|
fn from_raw_message(raw_message: RawMessage) -> Result<JupyterMessage> {
fn message_to_json(message: &[u8]) -> Result<JsonValue> {
Ok(json::parse(std::str::from_utf8(message)?)?)
}
if raw_message.jparts.len() < 4 {
bail!("Insufficient message parts {}", raw_message.jparts.len());
}
Ok(JupyterMessage {
zmq_identities: raw_message.zmq_identities,
header: message_to_json(&raw_message.jparts[0])?,
parent_header: message_to_json(&raw_message.jparts[1])?,
metadata: message_to_json(&raw_message.jparts[2])?,
content: message_to_json(&raw_message.jparts[3])?,
})
}
pub(crate) fn message_type(&self) -> &str {
self.header["msg_type"].as_str().unwrap_or("")
}
pub(crate) fn code(&self) -> &str {
self.content["code"].as_str().unwrap_or("")
}
pub(crate) fn cursor_pos(&self) -> usize {
self.content["cursor_pos"].as_usize().unwrap_or_default()
}
pub(crate) fn target_name(&self) -> &str {
self.content["target_name"].as_str().unwrap_or("")
}
pub(crate) fn data(&self) -> &JsonValue {
&self.content["data"]
}
pub(crate) fn comm_id(&self) -> &str {
self.content["comm_id"].as_str().unwrap_or("")
}
// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone();
header["msg_type"] = JsonValue::String(msg_type.to_owned());
header["username"] = JsonValue::String("kernel".to_owned());
header["msg_id"] = JsonValue::String(Uuid::new_v4().to_string());
header["date"] = JsonValue::String(Utc::now().to_rfc3339());
JupyterMessage {
zmq_identities: Vec::new(),
header,
parent_header: self.header.clone(),
metadata: JsonValue::new_object(),
content: JsonValue::new_object(),
}
}
// Creates a reply to this message. This is a child with the message type determined
// automatically by replacing "request" with "reply". ZMQ identities are transferred.
pub(crate) fn new_reply(&self) -> JupyterMessage {
let mut reply = self.new_message(&self.message_type().replace("_request", "_reply"));
reply.zmq_identities = self.zmq_identities.clone();
reply
}
#[must_use = "Need to send this message for it to have any effect"]
pub(crate) fn comm_close_message(&self) -> JupyterMessage {
self.new_message("comm_close").with_content(object! {
"comm_id" => self.comm_id()
})
}
pub(crate) fn get_content(&self) -> &JsonValue {
&self.content
}
pub(crate) fn with_content(mut self, content: JsonValue) -> JupyterMessage {
self.content = content;
self
}
pub(crate) fn with_message_type(mut self, msg_type: &str) -> JupyterMessage {
self.header["msg_type"] = JsonValue::String(msg_type.to_owned());
self
}
pub(crate) fn without_parent_header(mut self) -> JupyterMessage {
self.parent_header = object! {};
self
}
pub(crate) fn send(&self, connection: &Connection) -> Result<()> {
// If performance is a concern, we can probably avoid the clone and to_vec calls with a bit
// of refactoring.
let raw_message = RawMessage {
zmq_identities: self.zmq_identities.clone(),
jparts: vec![
self.header.dump().as_bytes().to_vec(),
self.parent_header.dump().as_bytes().to_vec(),
self.metadata.dump().as_bytes().to_vec(),
self.content.dump().as_bytes().to_vec(),
],
};
raw_message.send(connection)
}
}
impl fmt::Debug for JupyterMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "\nHEADER {}", self.header.pretty(2))?;
writeln!(f, "PARENT_HEADER {}", self.parent_header.pretty(2))?;
writeln!(f, "METADATA {}", self.metadata.pretty(2))?;
writeln!(f, "CONTENT {}\n", self.content.pretty(2))?;
Ok(())
}
}
|
{
Self::from_raw_message(RawMessage::read(connection)?)
}
|
identifier_body
|
jupyter_message.rs
|
// Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::connection::{Connection, HmacSha256};
use anyhow::{anyhow, bail, Result};
use chrono::Utc;
use generic_array::GenericArray;
use json::{self, JsonValue};
use std::{self, fmt};
use uuid::Uuid;
struct RawMessage {
zmq_identities: Vec<Vec<u8>>,
jparts: Vec<Vec<u8>>,
}
impl RawMessage {
pub(crate) fn read(connection: &Connection) -> Result<RawMessage> {
Self::from_multipart(connection.socket.recv_multipart(0)?, connection)
}
pub(crate) fn from_multipart(
mut multipart: Vec<Vec<u8>>,
connection: &Connection,
) -> Result<RawMessage> {
let delimiter_index = multipart
.iter()
.position(|part| &part[..] == DELIMITER)
.ok_or_else(|| anyhow!("Missing delimeter"))?;
let jparts: Vec<_> = multipart.drain(delimiter_index + 2..).collect();
let hmac = multipart.pop().unwrap();
// Remove delimiter, so that what's left is just the identities.
multipart.pop();
let zmq_identities = multipart;
let raw_message = RawMessage {
zmq_identities,
jparts,
};
if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
raw_message.digest(&mut mac);
use hmac::Mac;
if let Err(error) = mac.verify(GenericArray::from_slice(&hex::decode(&hmac)?)) {
bail!("{}", error);
}
}
Ok(raw_message)
}
fn send(self, connection: &Connection) -> Result<()> {
use hmac::Mac;
let hmac = if let Some(mac_template) = &connection.mac
|
else {
String::new()
};
let mut parts: Vec<&[u8]> = Vec::new();
for part in &self.zmq_identities {
parts.push(part);
}
parts.push(DELIMITER);
parts.push(hmac.as_bytes());
for part in &self.jparts {
parts.push(part);
}
connection.socket.send_multipart(&parts, 0)?;
Ok(())
}
fn digest(&self, mac: &mut HmacSha256) {
use hmac::Mac;
for part in &self.jparts {
mac.update(part);
}
}
}
#[derive(Clone)]
pub(crate) struct JupyterMessage {
zmq_identities: Vec<Vec<u8>>,
header: JsonValue,
parent_header: JsonValue,
metadata: JsonValue,
content: JsonValue,
}
const DELIMITER: &[u8] = b"<IDS|MSG>";
impl JupyterMessage {
pub(crate) fn read(connection: &Connection) -> Result<JupyterMessage> {
Self::from_raw_message(RawMessage::read(connection)?)
}
fn from_raw_message(raw_message: RawMessage) -> Result<JupyterMessage> {
fn message_to_json(message: &[u8]) -> Result<JsonValue> {
Ok(json::parse(std::str::from_utf8(message)?)?)
}
if raw_message.jparts.len() < 4 {
bail!("Insufficient message parts {}", raw_message.jparts.len());
}
Ok(JupyterMessage {
zmq_identities: raw_message.zmq_identities,
header: message_to_json(&raw_message.jparts[0])?,
parent_header: message_to_json(&raw_message.jparts[1])?,
metadata: message_to_json(&raw_message.jparts[2])?,
content: message_to_json(&raw_message.jparts[3])?,
})
}
pub(crate) fn message_type(&self) -> &str {
self.header["msg_type"].as_str().unwrap_or("")
}
pub(crate) fn code(&self) -> &str {
self.content["code"].as_str().unwrap_or("")
}
pub(crate) fn cursor_pos(&self) -> usize {
self.content["cursor_pos"].as_usize().unwrap_or_default()
}
pub(crate) fn target_name(&self) -> &str {
self.content["target_name"].as_str().unwrap_or("")
}
pub(crate) fn data(&self) -> &JsonValue {
&self.content["data"]
}
pub(crate) fn comm_id(&self) -> &str {
self.content["comm_id"].as_str().unwrap_or("")
}
// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone();
header["msg_type"] = JsonValue::String(msg_type.to_owned());
header["username"] = JsonValue::String("kernel".to_owned());
header["msg_id"] = JsonValue::String(Uuid::new_v4().to_string());
header["date"] = JsonValue::String(Utc::now().to_rfc3339());
JupyterMessage {
zmq_identities: Vec::new(),
header,
parent_header: self.header.clone(),
metadata: JsonValue::new_object(),
content: JsonValue::new_object(),
}
}
// Creates a reply to this message. This is a child with the message type determined
// automatically by replacing "request" with "reply". ZMQ identities are transferred.
pub(crate) fn new_reply(&self) -> JupyterMessage {
let mut reply = self.new_message(&self.message_type().replace("_request", "_reply"));
reply.zmq_identities = self.zmq_identities.clone();
reply
}
#[must_use = "Need to send this message for it to have any effect"]
pub(crate) fn comm_close_message(&self) -> JupyterMessage {
self.new_message("comm_close").with_content(object! {
"comm_id" => self.comm_id()
})
}
pub(crate) fn get_content(&self) -> &JsonValue {
&self.content
}
pub(crate) fn with_content(mut self, content: JsonValue) -> JupyterMessage {
self.content = content;
self
}
pub(crate) fn with_message_type(mut self, msg_type: &str) -> JupyterMessage {
self.header["msg_type"] = JsonValue::String(msg_type.to_owned());
self
}
pub(crate) fn without_parent_header(mut self) -> JupyterMessage {
self.parent_header = object! {};
self
}
pub(crate) fn send(&self, connection: &Connection) -> Result<()> {
// If performance is a concern, we can probably avoid the clone and to_vec calls with a bit
// of refactoring.
let raw_message = RawMessage {
zmq_identities: self.zmq_identities.clone(),
jparts: vec![
self.header.dump().as_bytes().to_vec(),
self.parent_header.dump().as_bytes().to_vec(),
self.metadata.dump().as_bytes().to_vec(),
self.content.dump().as_bytes().to_vec(),
],
};
raw_message.send(connection)
}
}
impl fmt::Debug for JupyterMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "\nHEADER {}", self.header.pretty(2))?;
writeln!(f, "PARENT_HEADER {}", self.parent_header.pretty(2))?;
writeln!(f, "METADATA {}", self.metadata.pretty(2))?;
writeln!(f, "CONTENT {}\n", self.content.pretty(2))?;
Ok(())
}
}
|
{
let mut mac = mac_template.clone();
self.digest(&mut mac);
hex::encode(mac.finalize().into_bytes().as_slice())
}
|
conditional_block
|
jupyter_message.rs
|
// Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::connection::{Connection, HmacSha256};
use anyhow::{anyhow, bail, Result};
use chrono::Utc;
use generic_array::GenericArray;
use json::{self, JsonValue};
use std::{self, fmt};
use uuid::Uuid;
struct RawMessage {
zmq_identities: Vec<Vec<u8>>,
jparts: Vec<Vec<u8>>,
}
impl RawMessage {
pub(crate) fn
|
(connection: &Connection) -> Result<RawMessage> {
Self::from_multipart(connection.socket.recv_multipart(0)?, connection)
}
pub(crate) fn from_multipart(
mut multipart: Vec<Vec<u8>>,
connection: &Connection,
) -> Result<RawMessage> {
let delimiter_index = multipart
.iter()
.position(|part| &part[..] == DELIMITER)
.ok_or_else(|| anyhow!("Missing delimeter"))?;
let jparts: Vec<_> = multipart.drain(delimiter_index + 2..).collect();
let hmac = multipart.pop().unwrap();
// Remove delimiter, so that what's left is just the identities.
multipart.pop();
let zmq_identities = multipart;
let raw_message = RawMessage {
zmq_identities,
jparts,
};
if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
raw_message.digest(&mut mac);
use hmac::Mac;
if let Err(error) = mac.verify(GenericArray::from_slice(&hex::decode(&hmac)?)) {
bail!("{}", error);
}
}
Ok(raw_message)
}
fn send(self, connection: &Connection) -> Result<()> {
use hmac::Mac;
let hmac = if let Some(mac_template) = &connection.mac {
let mut mac = mac_template.clone();
self.digest(&mut mac);
hex::encode(mac.finalize().into_bytes().as_slice())
} else {
String::new()
};
let mut parts: Vec<&[u8]> = Vec::new();
for part in &self.zmq_identities {
parts.push(part);
}
parts.push(DELIMITER);
parts.push(hmac.as_bytes());
for part in &self.jparts {
parts.push(part);
}
connection.socket.send_multipart(&parts, 0)?;
Ok(())
}
fn digest(&self, mac: &mut HmacSha256) {
use hmac::Mac;
for part in &self.jparts {
mac.update(part);
}
}
}
#[derive(Clone)]
pub(crate) struct JupyterMessage {
zmq_identities: Vec<Vec<u8>>,
header: JsonValue,
parent_header: JsonValue,
metadata: JsonValue,
content: JsonValue,
}
const DELIMITER: &[u8] = b"<IDS|MSG>";
impl JupyterMessage {
pub(crate) fn read(connection: &Connection) -> Result<JupyterMessage> {
Self::from_raw_message(RawMessage::read(connection)?)
}
fn from_raw_message(raw_message: RawMessage) -> Result<JupyterMessage> {
fn message_to_json(message: &[u8]) -> Result<JsonValue> {
Ok(json::parse(std::str::from_utf8(message)?)?)
}
if raw_message.jparts.len() < 4 {
bail!("Insufficient message parts {}", raw_message.jparts.len());
}
Ok(JupyterMessage {
zmq_identities: raw_message.zmq_identities,
header: message_to_json(&raw_message.jparts[0])?,
parent_header: message_to_json(&raw_message.jparts[1])?,
metadata: message_to_json(&raw_message.jparts[2])?,
content: message_to_json(&raw_message.jparts[3])?,
})
}
pub(crate) fn message_type(&self) -> &str {
self.header["msg_type"].as_str().unwrap_or("")
}
pub(crate) fn code(&self) -> &str {
self.content["code"].as_str().unwrap_or("")
}
pub(crate) fn cursor_pos(&self) -> usize {
self.content["cursor_pos"].as_usize().unwrap_or_default()
}
pub(crate) fn target_name(&self) -> &str {
self.content["target_name"].as_str().unwrap_or("")
}
pub(crate) fn data(&self) -> &JsonValue {
&self.content["data"]
}
pub(crate) fn comm_id(&self) -> &str {
self.content["comm_id"].as_str().unwrap_or("")
}
// Creates a new child message of this message. ZMQ identities are not transferred.
pub(crate) fn new_message(&self, msg_type: &str) -> JupyterMessage {
let mut header = self.header.clone();
header["msg_type"] = JsonValue::String(msg_type.to_owned());
header["username"] = JsonValue::String("kernel".to_owned());
header["msg_id"] = JsonValue::String(Uuid::new_v4().to_string());
header["date"] = JsonValue::String(Utc::now().to_rfc3339());
JupyterMessage {
zmq_identities: Vec::new(),
header,
parent_header: self.header.clone(),
metadata: JsonValue::new_object(),
content: JsonValue::new_object(),
}
}
// Creates a reply to this message. This is a child with the message type determined
// automatically by replacing "request" with "reply". ZMQ identities are transferred.
pub(crate) fn new_reply(&self) -> JupyterMessage {
let mut reply = self.new_message(&self.message_type().replace("_request", "_reply"));
reply.zmq_identities = self.zmq_identities.clone();
reply
}
#[must_use = "Need to send this message for it to have any effect"]
pub(crate) fn comm_close_message(&self) -> JupyterMessage {
self.new_message("comm_close").with_content(object! {
"comm_id" => self.comm_id()
})
}
pub(crate) fn get_content(&self) -> &JsonValue {
&self.content
}
pub(crate) fn with_content(mut self, content: JsonValue) -> JupyterMessage {
self.content = content;
self
}
pub(crate) fn with_message_type(mut self, msg_type: &str) -> JupyterMessage {
self.header["msg_type"] = JsonValue::String(msg_type.to_owned());
self
}
pub(crate) fn without_parent_header(mut self) -> JupyterMessage {
self.parent_header = object! {};
self
}
pub(crate) fn send(&self, connection: &Connection) -> Result<()> {
// If performance is a concern, we can probably avoid the clone and to_vec calls with a bit
// of refactoring.
let raw_message = RawMessage {
zmq_identities: self.zmq_identities.clone(),
jparts: vec![
self.header.dump().as_bytes().to_vec(),
self.parent_header.dump().as_bytes().to_vec(),
self.metadata.dump().as_bytes().to_vec(),
self.content.dump().as_bytes().to_vec(),
],
};
raw_message.send(connection)
}
}
impl fmt::Debug for JupyterMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "\nHEADER {}", self.header.pretty(2))?;
writeln!(f, "PARENT_HEADER {}", self.parent_header.pretty(2))?;
writeln!(f, "METADATA {}", self.metadata.pretty(2))?;
writeln!(f, "CONTENT {}\n", self.content.pretty(2))?;
Ok(())
}
}
|
read
|
identifier_name
|
json_port.rs
|
// see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use erl_ext::{Eterm, Error};
fn main() {
let in_f = io::stdin();
let out_f = io::stdout();
match read_write_loop(in_f, out_f) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: '{}'", err),
Ok(()) => () // unreachable in this example
};
}
fn read_write_loop<R: io::Read, W: io::Write>(mut r: R, mut w: W) -> Result<(), Error> {
loop {
// {packet, 2}
let _in_packet_size = r.read_u16::<BigEndian>();
{
let mut decoder = erl_ext::Decoder::new(&mut r);
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
// incoming message should be simple `binary()`
let response = match term {
Eterm::Binary(bytes) => {
bytes_to_json(bytes)
},
_ =>
// {error, not_binary}
Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("not_binary"))
))
};
// Temp buffer to calculate response term size
let mut wrtr = Vec::new();
|
try!(encoder.encode_term(response));
try!(encoder.flush());
}
// response packet size
let out_packet_size = wrtr.len() as u16;
try!(w.write_u16::<BigEndian>(out_packet_size));
// response term itself
try!(w.write_all(wrtr.as_ref()));
try!(w.flush());
}
}
}
fn bytes_to_json(json_bytes: Vec<u8>) -> erl_ext::Eterm {
// Vec<u8> to utf-8 String
let json_string = match String::from_utf8(json_bytes) {
Ok(s) => s,
Err(_) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("bad_utf8"))))
};
// &str to json::Json
let json_obj = match Json::from_str(json_string.as_ref()) {
Ok(o) => o,
Err(json::ParserError::SyntaxError(err_kind, line, col)) => {
let err_str = json::error_str(err_kind);
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::String(format!("{}; line:{}, col:{}", err_str, line, col).into_bytes())
))
},
Err(json::ParserError::IoError(err)) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::String(format!("IoError: {}", err).into_bytes())
))
};
// json::Json to erl_ext::Eterm
Eterm::Tuple(vec!(Eterm::Atom(String::from("ok")), json_to_erl(json_obj)))
}
fn json_to_erl(json: json::Json) -> erl_ext::Eterm {
/*
-type json() :: float() | binary() | bool()
| [json()] | #{binary() => json()}.
Json | Erlang
-------+------------------
-0.23 | -0.23 // float()
"wasd" | <<"wasd">> // binary()
true | true // bool()
[] | [] // [json()]
{} | {} // #{binary() => json()}
null | 'undefined'
*/
match json {
Json::F64(num) => Eterm::Float(num),
Json::I64(num) if (num <= (i32::max_value() as i64) && num >= (i32::min_value() as i64)) =>
Eterm::Integer(num as i32),
Json::I64(num) =>
Eterm::BigNum(num.to_bigint().unwrap()),
Json::U64(num) => {
match num.to_i32() {
Some(i32_num) => Eterm::Integer(i32_num),
None => Eterm::BigNum(FromPrimitive::from_u64(num).unwrap())
}
},
Json::String(string) => Eterm::Binary(string.into_bytes()),
Json::Boolean(true) => Eterm::Atom(String::from("true")),
Json::Boolean(false) => Eterm::Atom(String::from("false")),
Json::Array(lst) => {
let mut eterm_lst: erl_ext::List =
lst.into_iter().map(json_to_erl).collect();
eterm_lst.push(Eterm::Nil);
Eterm::List(eterm_lst)
},
Json::Object(obj) => {
let eterm_map: erl_ext::Map =
obj.into_iter().map(
|(k, v)| {
let ek = Eterm::Binary(k.into_bytes());
let ev = json_to_erl(v);
(ek, ev)
}).collect();
Eterm::Map(eterm_map)
},
Json::Null => Eterm::Atom(String::from("undefined")),
}
}
|
{
// encode response term
let mut encoder = erl_ext::Encoder::new(&mut wrtr,
true, true, true);
try!(encoder.write_prelude());
|
random_line_split
|
json_port.rs
|
// see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use erl_ext::{Eterm, Error};
fn main()
|
fn read_write_loop<R: io::Read, W: io::Write>(mut r: R, mut w: W) -> Result<(), Error> {
loop {
// {packet, 2}
let _in_packet_size = r.read_u16::<BigEndian>();
{
let mut decoder = erl_ext::Decoder::new(&mut r);
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
// incoming message should be simple `binary()`
let response = match term {
Eterm::Binary(bytes) => {
bytes_to_json(bytes)
},
_ =>
// {error, not_binary}
Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("not_binary"))
))
};
// Temp buffer to calculate response term size
let mut wrtr = Vec::new();
{
// encode response term
let mut encoder = erl_ext::Encoder::new(&mut wrtr,
true, true, true);
try!(encoder.write_prelude());
try!(encoder.encode_term(response));
try!(encoder.flush());
}
// response packet size
let out_packet_size = wrtr.len() as u16;
try!(w.write_u16::<BigEndian>(out_packet_size));
// response term itself
try!(w.write_all(wrtr.as_ref()));
try!(w.flush());
}
}
}
fn bytes_to_json(json_bytes: Vec<u8>) -> erl_ext::Eterm {
// Vec<u8> to utf-8 String
let json_string = match String::from_utf8(json_bytes) {
Ok(s) => s,
Err(_) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("bad_utf8"))))
};
// &str to json::Json
let json_obj = match Json::from_str(json_string.as_ref()) {
Ok(o) => o,
Err(json::ParserError::SyntaxError(err_kind, line, col)) => {
let err_str = json::error_str(err_kind);
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::String(format!("{}; line:{}, col:{}", err_str, line, col).into_bytes())
))
},
Err(json::ParserError::IoError(err)) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::String(format!("IoError: {}", err).into_bytes())
))
};
// json::Json to erl_ext::Eterm
Eterm::Tuple(vec!(Eterm::Atom(String::from("ok")), json_to_erl(json_obj)))
}
fn json_to_erl(json: json::Json) -> erl_ext::Eterm {
/*
-type json() :: float() | binary() | bool()
| [json()] | #{binary() => json()}.
Json | Erlang
-------+------------------
-0.23 | -0.23 // float()
"wasd" | <<"wasd">> // binary()
true | true // bool()
[] | [] // [json()]
{} | {} // #{binary() => json()}
null | 'undefined'
*/
match json {
Json::F64(num) => Eterm::Float(num),
Json::I64(num) if (num <= (i32::max_value() as i64) && num >= (i32::min_value() as i64)) =>
Eterm::Integer(num as i32),
Json::I64(num) =>
Eterm::BigNum(num.to_bigint().unwrap()),
Json::U64(num) => {
match num.to_i32() {
Some(i32_num) => Eterm::Integer(i32_num),
None => Eterm::BigNum(FromPrimitive::from_u64(num).unwrap())
}
},
Json::String(string) => Eterm::Binary(string.into_bytes()),
Json::Boolean(true) => Eterm::Atom(String::from("true")),
Json::Boolean(false) => Eterm::Atom(String::from("false")),
Json::Array(lst) => {
let mut eterm_lst: erl_ext::List =
lst.into_iter().map(json_to_erl).collect();
eterm_lst.push(Eterm::Nil);
Eterm::List(eterm_lst)
},
Json::Object(obj) => {
let eterm_map: erl_ext::Map =
obj.into_iter().map(
|(k, v)| {
let ek = Eterm::Binary(k.into_bytes());
let ev = json_to_erl(v);
(ek, ev)
}).collect();
Eterm::Map(eterm_map)
},
Json::Null => Eterm::Atom(String::from("undefined")),
}
}
|
{
let in_f = io::stdin();
let out_f = io::stdout();
match read_write_loop(in_f, out_f) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: '{}'", err),
Ok(()) => () // unreachable in this example
};
}
|
identifier_body
|
json_port.rs
|
// see json_port.erl
extern crate erl_ext;
extern crate rustc_serialize;
extern crate num;
extern crate byteorder;
// use std::num::ToPrimitive;
use std::io;
use std::io::Write;
use num::bigint::ToBigInt;
use num::traits::FromPrimitive;
use num::traits::ToPrimitive;
use rustc_serialize::json::{self, Json};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use erl_ext::{Eterm, Error};
fn main() {
let in_f = io::stdin();
let out_f = io::stdout();
match read_write_loop(in_f, out_f) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: '{}'", err),
Ok(()) => () // unreachable in this example
};
}
fn read_write_loop<R: io::Read, W: io::Write>(mut r: R, mut w: W) -> Result<(), Error> {
loop {
// {packet, 2}
let _in_packet_size = r.read_u16::<BigEndian>();
{
let mut decoder = erl_ext::Decoder::new(&mut r);
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
// incoming message should be simple `binary()`
let response = match term {
Eterm::Binary(bytes) => {
bytes_to_json(bytes)
},
_ =>
// {error, not_binary}
Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("not_binary"))
))
};
// Temp buffer to calculate response term size
let mut wrtr = Vec::new();
{
// encode response term
let mut encoder = erl_ext::Encoder::new(&mut wrtr,
true, true, true);
try!(encoder.write_prelude());
try!(encoder.encode_term(response));
try!(encoder.flush());
}
// response packet size
let out_packet_size = wrtr.len() as u16;
try!(w.write_u16::<BigEndian>(out_packet_size));
// response term itself
try!(w.write_all(wrtr.as_ref()));
try!(w.flush());
}
}
}
fn
|
(json_bytes: Vec<u8>) -> erl_ext::Eterm {
// Vec<u8> to utf-8 String
let json_string = match String::from_utf8(json_bytes) {
Ok(s) => s,
Err(_) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::Atom(String::from("bad_utf8"))))
};
// &str to json::Json
let json_obj = match Json::from_str(json_string.as_ref()) {
Ok(o) => o,
Err(json::ParserError::SyntaxError(err_kind, line, col)) => {
let err_str = json::error_str(err_kind);
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::String(format!("{}; line:{}, col:{}", err_str, line, col).into_bytes())
))
},
Err(json::ParserError::IoError(err)) =>
return Eterm::Tuple(vec!(
Eterm::Atom(String::from("error")),
Eterm::String(format!("IoError: {}", err).into_bytes())
))
};
// json::Json to erl_ext::Eterm
Eterm::Tuple(vec!(Eterm::Atom(String::from("ok")), json_to_erl(json_obj)))
}
fn json_to_erl(json: json::Json) -> erl_ext::Eterm {
/*
-type json() :: float() | binary() | bool()
| [json()] | #{binary() => json()}.
Json | Erlang
-------+------------------
-0.23 | -0.23 // float()
"wasd" | <<"wasd">> // binary()
true | true // bool()
[] | [] // [json()]
{} | {} // #{binary() => json()}
null | 'undefined'
*/
match json {
Json::F64(num) => Eterm::Float(num),
Json::I64(num) if (num <= (i32::max_value() as i64) && num >= (i32::min_value() as i64)) =>
Eterm::Integer(num as i32),
Json::I64(num) =>
Eterm::BigNum(num.to_bigint().unwrap()),
Json::U64(num) => {
match num.to_i32() {
Some(i32_num) => Eterm::Integer(i32_num),
None => Eterm::BigNum(FromPrimitive::from_u64(num).unwrap())
}
},
Json::String(string) => Eterm::Binary(string.into_bytes()),
Json::Boolean(true) => Eterm::Atom(String::from("true")),
Json::Boolean(false) => Eterm::Atom(String::from("false")),
Json::Array(lst) => {
let mut eterm_lst: erl_ext::List =
lst.into_iter().map(json_to_erl).collect();
eterm_lst.push(Eterm::Nil);
Eterm::List(eterm_lst)
},
Json::Object(obj) => {
let eterm_map: erl_ext::Map =
obj.into_iter().map(
|(k, v)| {
let ek = Eterm::Binary(k.into_bytes());
let ev = json_to_erl(v);
(ek, ev)
}).collect();
Eterm::Map(eterm_map)
},
Json::Null => Eterm::Atom(String::from("undefined")),
}
}
|
bytes_to_json
|
identifier_name
|
framed_rectangle.rs
|
use {
Backend,
Color,
Colorable,
Dimensions,
Frameable,
Scalar,
Sizeable,
Widget,
};
use widget;
/// A filled rectangle widget that may or may not have some frame.
#[derive(Copy, Clone, Debug)]
pub struct
|
{
/// Data necessary and common for all widget builder types.
pub common: widget::CommonBuilder,
/// Unique styling for the **FramedRectangle**.
pub style: Style,
}
/// Unique kind for the Widget.
pub const KIND: widget::Kind = "FramedRectangle";
widget_style!{
KIND;
/// Unique styling for the **FramedRectangle** widget.
style Style {
/// Shape styling for the inner rectangle.
- color: Color { theme.shape_color }
/// The thickness of the frame.
- frame: Scalar { theme.frame_width }
/// The color of the frame.
- frame_color: Color { theme.frame_color }
}
}
impl FramedRectangle {
/// Build a new **FramedRectangle**.
pub fn new(dim: Dimensions) -> Self {
FramedRectangle {
common: widget::CommonBuilder::new(),
style: Style::new(),
}.wh(dim)
}
builder_method!(pub with_style { style = Style });
}
impl Widget for FramedRectangle {
type State = ();
type Style = Style;
fn common(&self) -> &widget::CommonBuilder {
&self.common
}
fn common_mut(&mut self) -> &mut widget::CommonBuilder {
&mut self.common
}
fn unique_kind(&self) -> &'static str {
KIND
}
fn init_state(&self) -> () {
()
}
fn style(&self) -> Style {
self.style.clone()
}
/// Update the state of the Rectangle.
fn update<B: Backend>(self, _args: widget::UpdateArgs<Self, B>) {
// Nothing to update here!
}
}
impl Colorable for FramedRectangle {
builder_method!(color { style.color = Some(Color) });
}
impl Frameable for FramedRectangle {
builder_methods!{
frame { style.frame = Some(Scalar) }
frame_color { style.frame_color = Some(Color) }
}
}
|
FramedRectangle
|
identifier_name
|
framed_rectangle.rs
|
use {
Backend,
Color,
Colorable,
Dimensions,
Frameable,
Scalar,
Sizeable,
Widget,
};
use widget;
/// A filled rectangle widget that may or may not have some frame.
#[derive(Copy, Clone, Debug)]
pub struct FramedRectangle {
/// Data necessary and common for all widget builder types.
pub common: widget::CommonBuilder,
/// Unique styling for the **FramedRectangle**.
pub style: Style,
}
/// Unique kind for the Widget.
pub const KIND: widget::Kind = "FramedRectangle";
|
/// Shape styling for the inner rectangle.
- color: Color { theme.shape_color }
/// The thickness of the frame.
- frame: Scalar { theme.frame_width }
/// The color of the frame.
- frame_color: Color { theme.frame_color }
}
}
impl FramedRectangle {
/// Build a new **FramedRectangle**.
pub fn new(dim: Dimensions) -> Self {
FramedRectangle {
common: widget::CommonBuilder::new(),
style: Style::new(),
}.wh(dim)
}
builder_method!(pub with_style { style = Style });
}
impl Widget for FramedRectangle {
type State = ();
type Style = Style;
fn common(&self) -> &widget::CommonBuilder {
&self.common
}
fn common_mut(&mut self) -> &mut widget::CommonBuilder {
&mut self.common
}
fn unique_kind(&self) -> &'static str {
KIND
}
fn init_state(&self) -> () {
()
}
fn style(&self) -> Style {
self.style.clone()
}
/// Update the state of the Rectangle.
fn update<B: Backend>(self, _args: widget::UpdateArgs<Self, B>) {
// Nothing to update here!
}
}
impl Colorable for FramedRectangle {
builder_method!(color { style.color = Some(Color) });
}
impl Frameable for FramedRectangle {
builder_methods!{
frame { style.frame = Some(Scalar) }
frame_color { style.frame_color = Some(Color) }
}
}
|
widget_style!{
KIND;
/// Unique styling for the **FramedRectangle** widget.
style Style {
|
random_line_split
|
lib.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(rustc_private, plugin_registrar)]
extern crate syntax;
extern crate syntax_ext;
extern crate rustc_plugin;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax_ext::deriving::generic::*;
use syntax_ext::deriving::generic::ty::*;
use syntax::parse::token;
use syntax::ptr::P;
use rustc_plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(token::intern("derive_Rand"),
base::MultiDecorator(Box::new(expand_deriving_rand)));
}
pub fn expand_deriving_rand(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!(
MethodDef {
name: "rand",
is_unsafe: false,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("R",
vec!( Path::new(vec!("rand", "Rng")) )))
},
explicit_self: None,
args: vec!(
Ptr(Box::new(Literal(Path::new_local("R"))),
Borrowed(None, ast::Mutability::Mutable))
),
ret_ty: Self_,
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, &mut |i| push(i))
}
fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let rng = if substr.nonself_args.len() == 1
|
else {
cx.bug("Incorrect number of arguments to `rand` in `derive(Rand)`")
};
let rand_ident = vec!(
cx.ident_of("rand"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
rand_ident.clone(),
vec!(rng.clone()))
};
return match *substr.fields {
StaticStruct(_, ref summary) => {
let path = cx.path_ident(trait_span, substr.type_ident);
rand_thing(cx, trait_span, path, summary, rand_call)
}
StaticEnum(_, ref variants) => {
if variants.is_empty() {
cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants");
// let compilation continue
return cx.expr_usize(trait_span, 0);
}
let variant_count = cx.expr_usize(trait_span, variants.len());
let rand_name = cx.path_all(trait_span,
true,
rand_ident.clone(),
Vec::new(),
Vec::new(),
Vec::new());
let rand_name = cx.expr_path(rand_name);
// ::rand::Rand::rand(rng)
let rv_call = cx.expr_call(trait_span,
rand_name,
vec!(rng.clone()));
// need to specify the usize-ness of the random number
let usize_ty = cx.ty_ident(trait_span, cx.ident_of("usize"));
let value_ident = cx.ident_of("__value");
let let_statement = cx.stmt_let_typed(trait_span,
false,
value_ident,
usize_ty,
rv_call);
// rand() % variants.len()
let value_ref = cx.expr_ident(trait_span, value_ident);
let rand_variant = cx.expr_binary(trait_span,
ast::BinOpKind::Rem,
value_ref,
variant_count);
let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| {
let i_expr = cx.expr_usize(v_span, i);
let pat = cx.pat_lit(v_span, i_expr);
let path = cx.path(v_span, vec![substr.type_ident, ident]);
let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp));
cx.arm(v_span, vec!( pat ), thing)
}).collect::<Vec<ast::Arm> >();
// _ => {} at the end. Should never occur
arms.push(cx.arm_unreachable(trait_span));
let match_expr = cx.expr_match(trait_span, rand_variant, arms);
let block = cx.block(trait_span, vec!( let_statement.unwrap() ), Some(match_expr));
cx.expr_block(block)
}
_ => cx.bug("Non-static method in `derive(Rand)`")
};
fn rand_thing<F>(cx: &mut ExtCtxt,
trait_span: Span,
ctor_path: ast::Path,
summary: &StaticFields,
mut rand_call: F)
-> P<Expr> where
F: FnMut(&mut ExtCtxt, Span) -> P<Expr>,
{
let path = cx.expr_path(ctor_path.clone());
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
path
} else {
let exprs = fields.iter().map(|span| rand_call(cx, *span)).collect();
cx.expr_call(trait_span, path, exprs)
}
}
Named(ref fields) => {
let rand_fields = fields.iter().map(|&(ident, span)| {
let e = rand_call(cx, span);
cx.field_imm(span, ident, e)
}).collect();
cx.expr_struct(trait_span, ctor_path, rand_fields)
}
}
}
}
|
{
&substr.nonself_args[0]
}
|
conditional_block
|
lib.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(rustc_private, plugin_registrar)]
extern crate syntax;
extern crate syntax_ext;
extern crate rustc_plugin;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax_ext::deriving::generic::*;
use syntax_ext::deriving::generic::ty::*;
use syntax::parse::token;
use syntax::ptr::P;
use rustc_plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(token::intern("derive_Rand"),
base::MultiDecorator(Box::new(expand_deriving_rand)));
}
pub fn expand_deriving_rand(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!(
MethodDef {
name: "rand",
is_unsafe: false,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("R",
vec!( Path::new(vec!("rand", "Rng")) )))
},
explicit_self: None,
args: vec!(
Ptr(Box::new(Literal(Path::new_local("R"))),
Borrowed(None, ast::Mutability::Mutable))
),
ret_ty: Self_,
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, &mut |i| push(i))
}
fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let rng = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.bug("Incorrect number of arguments to `rand` in `derive(Rand)`")
};
let rand_ident = vec!(
cx.ident_of("rand"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
rand_ident.clone(),
vec!(rng.clone()))
};
return match *substr.fields {
StaticStruct(_, ref summary) => {
let path = cx.path_ident(trait_span, substr.type_ident);
rand_thing(cx, trait_span, path, summary, rand_call)
}
StaticEnum(_, ref variants) => {
if variants.is_empty() {
cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants");
// let compilation continue
return cx.expr_usize(trait_span, 0);
}
let variant_count = cx.expr_usize(trait_span, variants.len());
let rand_name = cx.path_all(trait_span,
true,
rand_ident.clone(),
Vec::new(),
Vec::new(),
Vec::new());
let rand_name = cx.expr_path(rand_name);
// ::rand::Rand::rand(rng)
let rv_call = cx.expr_call(trait_span,
rand_name,
vec!(rng.clone()));
// need to specify the usize-ness of the random number
let usize_ty = cx.ty_ident(trait_span, cx.ident_of("usize"));
let value_ident = cx.ident_of("__value");
let let_statement = cx.stmt_let_typed(trait_span,
false,
value_ident,
usize_ty,
rv_call);
// rand() % variants.len()
let value_ref = cx.expr_ident(trait_span, value_ident);
let rand_variant = cx.expr_binary(trait_span,
ast::BinOpKind::Rem,
value_ref,
variant_count);
let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| {
let i_expr = cx.expr_usize(v_span, i);
let pat = cx.pat_lit(v_span, i_expr);
let path = cx.path(v_span, vec![substr.type_ident, ident]);
let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp));
cx.arm(v_span, vec!( pat ), thing)
}).collect::<Vec<ast::Arm> >();
// _ => {} at the end. Should never occur
arms.push(cx.arm_unreachable(trait_span));
let match_expr = cx.expr_match(trait_span, rand_variant, arms);
let block = cx.block(trait_span, vec!( let_statement.unwrap() ), Some(match_expr));
cx.expr_block(block)
}
_ => cx.bug("Non-static method in `derive(Rand)`")
};
fn
|
<F>(cx: &mut ExtCtxt,
trait_span: Span,
ctor_path: ast::Path,
summary: &StaticFields,
mut rand_call: F)
-> P<Expr> where
F: FnMut(&mut ExtCtxt, Span) -> P<Expr>,
{
let path = cx.expr_path(ctor_path.clone());
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
path
} else {
let exprs = fields.iter().map(|span| rand_call(cx, *span)).collect();
cx.expr_call(trait_span, path, exprs)
}
}
Named(ref fields) => {
let rand_fields = fields.iter().map(|&(ident, span)| {
let e = rand_call(cx, span);
cx.field_imm(span, ident, e)
}).collect();
cx.expr_struct(trait_span, ctor_path, rand_fields)
}
}
}
}
|
rand_thing
|
identifier_name
|
lib.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(rustc_private, plugin_registrar)]
extern crate syntax;
extern crate syntax_ext;
extern crate rustc_plugin;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax_ext::deriving::generic::*;
use syntax_ext::deriving::generic::ty::*;
use syntax::parse::token;
use syntax::ptr::P;
use rustc_plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(token::intern("derive_Rand"),
base::MultiDecorator(Box::new(expand_deriving_rand)));
}
|
push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!(
MethodDef {
name: "rand",
is_unsafe: false,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("R",
vec!( Path::new(vec!("rand", "Rng")) )))
},
explicit_self: None,
args: vec!(
Ptr(Box::new(Literal(Path::new_local("R"))),
Borrowed(None, ast::Mutability::Mutable))
),
ret_ty: Self_,
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, &mut |i| push(i))
}
fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let rng = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.bug("Incorrect number of arguments to `rand` in `derive(Rand)`")
};
let rand_ident = vec!(
cx.ident_of("rand"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
rand_ident.clone(),
vec!(rng.clone()))
};
return match *substr.fields {
StaticStruct(_, ref summary) => {
let path = cx.path_ident(trait_span, substr.type_ident);
rand_thing(cx, trait_span, path, summary, rand_call)
}
StaticEnum(_, ref variants) => {
if variants.is_empty() {
cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants");
// let compilation continue
return cx.expr_usize(trait_span, 0);
}
let variant_count = cx.expr_usize(trait_span, variants.len());
let rand_name = cx.path_all(trait_span,
true,
rand_ident.clone(),
Vec::new(),
Vec::new(),
Vec::new());
let rand_name = cx.expr_path(rand_name);
// ::rand::Rand::rand(rng)
let rv_call = cx.expr_call(trait_span,
rand_name,
vec!(rng.clone()));
// need to specify the usize-ness of the random number
let usize_ty = cx.ty_ident(trait_span, cx.ident_of("usize"));
let value_ident = cx.ident_of("__value");
let let_statement = cx.stmt_let_typed(trait_span,
false,
value_ident,
usize_ty,
rv_call);
// rand() % variants.len()
let value_ref = cx.expr_ident(trait_span, value_ident);
let rand_variant = cx.expr_binary(trait_span,
ast::BinOpKind::Rem,
value_ref,
variant_count);
let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| {
let i_expr = cx.expr_usize(v_span, i);
let pat = cx.pat_lit(v_span, i_expr);
let path = cx.path(v_span, vec![substr.type_ident, ident]);
let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp));
cx.arm(v_span, vec!( pat ), thing)
}).collect::<Vec<ast::Arm> >();
// _ => {} at the end. Should never occur
arms.push(cx.arm_unreachable(trait_span));
let match_expr = cx.expr_match(trait_span, rand_variant, arms);
let block = cx.block(trait_span, vec!( let_statement.unwrap() ), Some(match_expr));
cx.expr_block(block)
}
_ => cx.bug("Non-static method in `derive(Rand)`")
};
fn rand_thing<F>(cx: &mut ExtCtxt,
trait_span: Span,
ctor_path: ast::Path,
summary: &StaticFields,
mut rand_call: F)
-> P<Expr> where
F: FnMut(&mut ExtCtxt, Span) -> P<Expr>,
{
let path = cx.expr_path(ctor_path.clone());
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
path
} else {
let exprs = fields.iter().map(|span| rand_call(cx, *span)).collect();
cx.expr_call(trait_span, path, exprs)
}
}
Named(ref fields) => {
let rand_fields = fields.iter().map(|&(ident, span)| {
let e = rand_call(cx, span);
cx.field_imm(span, ident, e)
}).collect();
cx.expr_struct(trait_span, ctor_path, rand_fields)
}
}
}
}
|
pub fn expand_deriving_rand(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
|
random_line_split
|
lib.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(rustc_private, plugin_registrar)]
extern crate syntax;
extern crate syntax_ext;
extern crate rustc_plugin;
use syntax::ast::{MetaItem, Expr};
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, Annotatable};
use syntax::ext::build::AstBuilder;
use syntax_ext::deriving::generic::*;
use syntax_ext::deriving::generic::ty::*;
use syntax::parse::token;
use syntax::ptr::P;
use rustc_plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(token::intern("derive_Rand"),
base::MultiDecorator(Box::new(expand_deriving_rand)));
}
pub fn expand_deriving_rand(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
|
Borrowed(None, ast::Mutability::Mutable))
),
ret_ty: Self_,
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, &item, &mut |i| push(i))
}
fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let rng = if substr.nonself_args.len() == 1 {
&substr.nonself_args[0]
} else {
cx.bug("Incorrect number of arguments to `rand` in `derive(Rand)`")
};
let rand_ident = vec!(
cx.ident_of("rand"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
rand_ident.clone(),
vec!(rng.clone()))
};
return match *substr.fields {
StaticStruct(_, ref summary) => {
let path = cx.path_ident(trait_span, substr.type_ident);
rand_thing(cx, trait_span, path, summary, rand_call)
}
StaticEnum(_, ref variants) => {
if variants.is_empty() {
cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants");
// let compilation continue
return cx.expr_usize(trait_span, 0);
}
let variant_count = cx.expr_usize(trait_span, variants.len());
let rand_name = cx.path_all(trait_span,
true,
rand_ident.clone(),
Vec::new(),
Vec::new(),
Vec::new());
let rand_name = cx.expr_path(rand_name);
// ::rand::Rand::rand(rng)
let rv_call = cx.expr_call(trait_span,
rand_name,
vec!(rng.clone()));
// need to specify the usize-ness of the random number
let usize_ty = cx.ty_ident(trait_span, cx.ident_of("usize"));
let value_ident = cx.ident_of("__value");
let let_statement = cx.stmt_let_typed(trait_span,
false,
value_ident,
usize_ty,
rv_call);
// rand() % variants.len()
let value_ref = cx.expr_ident(trait_span, value_ident);
let rand_variant = cx.expr_binary(trait_span,
ast::BinOpKind::Rem,
value_ref,
variant_count);
let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| {
let i_expr = cx.expr_usize(v_span, i);
let pat = cx.pat_lit(v_span, i_expr);
let path = cx.path(v_span, vec![substr.type_ident, ident]);
let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp));
cx.arm(v_span, vec!( pat ), thing)
}).collect::<Vec<ast::Arm> >();
// _ => {} at the end. Should never occur
arms.push(cx.arm_unreachable(trait_span));
let match_expr = cx.expr_match(trait_span, rand_variant, arms);
let block = cx.block(trait_span, vec!( let_statement.unwrap() ), Some(match_expr));
cx.expr_block(block)
}
_ => cx.bug("Non-static method in `derive(Rand)`")
};
fn rand_thing<F>(cx: &mut ExtCtxt,
trait_span: Span,
ctor_path: ast::Path,
summary: &StaticFields,
mut rand_call: F)
-> P<Expr> where
F: FnMut(&mut ExtCtxt, Span) -> P<Expr>,
{
let path = cx.expr_path(ctor_path.clone());
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
path
} else {
let exprs = fields.iter().map(|span| rand_call(cx, *span)).collect();
cx.expr_call(trait_span, path, exprs)
}
}
Named(ref fields) => {
let rand_fields = fields.iter().map(|&(ident, span)| {
let e = rand_call(cx, span);
cx.field_imm(span, ident, e)
}).collect();
cx.expr_struct(trait_span, ctor_path, rand_fields)
}
}
}
}
|
{
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!(
MethodDef {
name: "rand",
is_unsafe: false,
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("R",
vec!( Path::new(vec!("rand", "Rng")) )))
},
explicit_self: None,
args: vec!(
Ptr(Box::new(Literal(Path::new_local("R"))),
|
identifier_body
|
sanity.rs
|
use WinVersion;
use super::Cache;
pub fn
|
(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Features with upper limits on versions.
- Features that *do not* target the desktop.
*/
let mut suspect = vec![];
if let Some(ref parts) = feat.parts {
if (parts.clone() & Partitions::DesktopApp).is_empty() {
suspect.push("non-desktop-app");
}
}
if let Some(ref winver) = feat.winver {
if!winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect.len()!= 0 {
warn!("suspect feature set: {}:{}: {} {:?}",
path, line, suspect.join(", "), feat);
}
});
if weird_vers.len() > 0 {
warn!("suspect versions:");
for ver in weird_vers {
warn!(".. 0x{:08x} - {:?}",
ver, WinVersion::from_u32_round_up(ver));
}
}
}
|
sanity_check_features
|
identifier_name
|
sanity.rs
|
use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Features with upper limits on versions.
- Features that *do not* target the desktop.
*/
let mut suspect = vec![];
if let Some(ref parts) = feat.parts {
if (parts.clone() & Partitions::DesktopApp).is_empty() {
suspect.push("non-desktop-app");
}
}
if let Some(ref winver) = feat.winver {
if!winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect.len()!= 0 {
warn!("suspect feature set: {}:{}: {} {:?}",
path, line, suspect.join(", "), feat);
}
});
if weird_vers.len() > 0 {
warn!("suspect versions:");
for ver in weird_vers {
warn!(".. 0x{:08x} - {:?}",
ver, WinVersion::from_u32_round_up(ver));
}
|
}
|
}
|
random_line_split
|
sanity.rs
|
use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Features with upper limits on versions.
- Features that *do not* target the desktop.
*/
let mut suspect = vec![];
if let Some(ref parts) = feat.parts {
if (parts.clone() & Partitions::DesktopApp).is_empty()
|
}
if let Some(ref winver) = feat.winver {
if!winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect.len()!= 0 {
warn!("suspect feature set: {}:{}: {} {:?}",
path, line, suspect.join(", "), feat);
}
});
if weird_vers.len() > 0 {
warn!("suspect versions:");
for ver in weird_vers {
warn!(".. 0x{:08x} - {:?}",
ver, WinVersion::from_u32_round_up(ver));
}
}
}
|
{
suspect.push("non-desktop-app");
}
|
conditional_block
|
sanity.rs
|
use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache)
|
}
}
if let Some(ref winver) = feat.winver {
if!winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect.len()!= 0 {
warn!("suspect feature set: {}:{}: {} {:?}",
path, line, suspect.join(", "), feat);
}
});
if weird_vers.len() > 0 {
warn!("suspect versions:");
for ver in weird_vers {
warn!(".. 0x{:08x} - {:?}",
ver, WinVersion::from_u32_round_up(ver));
}
}
}
|
{
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Features with upper limits on versions.
- Features that *do not* target the desktop.
*/
let mut suspect = vec![];
if let Some(ref parts) = feat.parts {
if (parts.clone() & Partitions::DesktopApp).is_empty() {
suspect.push("non-desktop-app");
|
identifier_body
|
lib.rs
|
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating a [`Poll`], which reads events from the OS and
//! put them into [`Events`]. You can handle IO events from the OS with it.
//!
//! For more detail, see [`Poll`].
//!
//! [`Poll`]: struct.Poll.html
//! [`Events`]: struct.Events.html
//!
//! # Example
//!
//! ```
//! use mio::*;
//! use mio::net::{TcpListener, TcpStream};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = "127.0.0.1:13265".parse().unwrap();
//!
//! // Setup the server socket
//! let server = TcpListener::bind(&addr).unwrap();
//!
//! // Create a poll instance
//! let poll = Poll::new().unwrap();
//!
//! // Start listening for incoming connections
//! poll.register(&server, SERVER, Ready::readable(),
//! PollOpt::edge()).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpStream::connect(&addr).unwrap();
//!
//! // Register the socket
//! poll.register(&sock, CLIENT, Ready::readable(),
//! PollOpt::edge()).unwrap();
//!
//! // Create storage for events
//! let mut events = Events::with_capacity(1024);
//!
//! loop {
//! poll.poll(&mut events, None).unwrap();
//!
//! for event in events.iter() {
//! match event.token() {
//! SERVER => {
//! // Accept and drop the socket immediately, this will close
//! // the socket and notify the client of the EOF.
//! let _ = server.accept();
|
//! CLIENT => {
//! // The server just shuts down the socket, let's just exit
//! // from our event loop.
//! return;
//! }
//! _ => unreachable!(),
//! }
//! }
//! }
//!
//! ```
#![doc(html_root_url = "https://docs.rs/mio/0.6.12")]
#![crate_name = "mio"]
#![deny(warnings, missing_docs, missing_debug_implementations)]
extern crate lazycell;
extern crate net2;
extern crate iovec;
#[cfg(target_os = "fuchsia")]
extern crate fuchsia_zircon as zircon;
#[cfg(target_os = "fuchsia")]
extern crate fuchsia_zircon_sys as zircon_sys;
#[cfg(unix)]
extern crate libc;
#[cfg(windows)]
extern crate miow;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
#[macro_use]
extern crate log;
mod event_imp;
mod io;
mod poll;
mod sys;
mod token;
pub mod net;
#[deprecated(since = "0.6.5", note = "use mio-extras instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod channel;
#[deprecated(since = "0.6.5", note = "use mio-extras instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod timer;
#[deprecated(since = "0.6.5", note = "update to use `Poll`")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod deprecated;
#[deprecated(since = "0.6.5", note = "use iovec crate directly")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use iovec::IoVec;
#[deprecated(since = "0.6.6", note = "use net module instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod tcp {
pub use net::{TcpListener, TcpStream};
pub use std::net::Shutdown;
}
#[deprecated(since = "0.6.6", note = "use net module instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod udp;
pub use poll::{
Poll,
Registration,
SetReadiness,
};
pub use event_imp::{
PollOpt,
Ready,
};
pub use token::Token;
pub mod event {
//! Readiness event types and utilities.
pub use super::poll::{Events, Iter};
pub use super::event_imp::{Event, Evented};
}
pub use event::{
Events,
};
#[deprecated(since = "0.6.5", note = "use events:: instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use event::{Event, Evented};
#[deprecated(since = "0.6.5", note = "use events::Iter instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use poll::Iter as EventsIter;
#[deprecated(since = "0.6.5", note = "std::io::Error can avoid the allocation now")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use io::deprecated::would_block;
#[cfg(all(unix, not(target_os = "fuchsia")))]
pub mod unix {
//! Unix only extensions
pub use sys::{
EventedFd,
};
pub use sys::unix::UnixReady;
}
#[cfg(target_os = "fuchsia")]
pub mod fuchsia {
//! Fuchsia-only extensions
//!
//! # Stability
//!
//! This module depends on the [magenta-sys crate](https://crates.io/crates/magenta-sys)
//! and so might introduce breaking changes, even on minor releases,
//! so long as that crate remains unstable.
pub use sys::{
EventedHandle,
};
pub use sys::fuchsia::{FuchsiaReady, zx_signals_t};
}
/// Windows-only extensions to the mio crate.
///
/// Mio on windows is currently implemented with IOCP for a high-performance
/// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample
/// bindings for the system to connect networking types to asynchronous I/O. On
/// Unix this scheme is then also extensible to all other file descriptors with
/// the `EventedFd` type, but on Windows no such analog is available. The
/// purpose of this module, however, is to similarly provide a mechanism for
/// foreign I/O types to get hooked up into the IOCP event loop.
///
/// This module provides two types for interfacing with a custom IOCP handle:
///
/// * `Binding` - this type is intended to govern binding with mio's `Poll`
/// type. Each I/O object should contain an instance of `Binding` that's
/// interfaced with for the implementation of the `Evented` trait. The
/// `register`, `reregister`, and `deregister` methods for the `Evented` trait
/// all have rough analogs with `Binding`.
///
/// Note that this type **does not handle readiness**. That is, this type does
/// not handle whether sockets are readable/writable/etc. It's intended that
/// IOCP types will internally manage this state with a `SetReadiness` type
/// from the `poll` module. The `SetReadiness` is typically lazily created on
/// the first time that `Evented::register` is called and then stored in the
/// I/O object.
///
/// Also note that for types which represent streams of bytes the mio
/// interface of *readiness* doesn't map directly to the Windows model of
/// *completion*. This means that types will have to perform internal
/// buffering to ensure that a readiness interface can be provided. For a
/// sample implementation see the TCP/UDP modules in mio itself.
///
/// * `Overlapped` - this type is intended to be used as the concrete instances
/// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for
/// safety, that all asynchronous operations are initiated with an instance of
/// `Overlapped` and not another instantiation of `OVERLAPPED`.
///
/// Mio's `Overlapped` type is created with a function pointer that receives
/// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is
/// defined in the `winapi` crate. Whenever a completion is posted to an IOCP
/// object the `OVERLAPPED` that was signaled will be interpreted as
/// `Overlapped` in the mio crate and this function pointer will be invoked.
/// Through this function pointer, and through the `OVERLAPPED` pointer,
/// implementations can handle management of I/O events.
///
/// When put together these two types enable custom Windows handles to be
/// registered with mio's event loops. The `Binding` type is used to associate
/// handles and the `Overlapped` type is used to execute I/O operations. When
/// the I/O operations are completed a custom function pointer is called which
/// typically modifies a `SetReadiness` set by `Evented` methods which will get
/// later hooked into the mio event loop.
#[cfg(windows)]
pub mod windows {
pub use sys::{Overlapped, Binding};
}
#[cfg(feature = "with-deprecated")]
mod convert {
use std::time::Duration;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// Convert a `Duration` to milliseconds, rounding up and saturating at
/// `u64::MAX`.
///
/// The saturating is fine because `u64::MAX` milliseconds are still many
/// million years.
pub fn millis(duration: Duration) -> u64 {
// Round up.
let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
}
}
|
//! }
|
random_line_split
|
lib.rs
|
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating a [`Poll`], which reads events from the OS and
//! put them into [`Events`]. You can handle IO events from the OS with it.
//!
//! For more detail, see [`Poll`].
//!
//! [`Poll`]: struct.Poll.html
//! [`Events`]: struct.Events.html
//!
//! # Example
//!
//! ```
//! use mio::*;
//! use mio::net::{TcpListener, TcpStream};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = "127.0.0.1:13265".parse().unwrap();
//!
//! // Setup the server socket
//! let server = TcpListener::bind(&addr).unwrap();
//!
//! // Create a poll instance
//! let poll = Poll::new().unwrap();
//!
//! // Start listening for incoming connections
//! poll.register(&server, SERVER, Ready::readable(),
//! PollOpt::edge()).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpStream::connect(&addr).unwrap();
//!
//! // Register the socket
//! poll.register(&sock, CLIENT, Ready::readable(),
//! PollOpt::edge()).unwrap();
//!
//! // Create storage for events
//! let mut events = Events::with_capacity(1024);
//!
//! loop {
//! poll.poll(&mut events, None).unwrap();
//!
//! for event in events.iter() {
//! match event.token() {
//! SERVER => {
//! // Accept and drop the socket immediately, this will close
//! // the socket and notify the client of the EOF.
//! let _ = server.accept();
//! }
//! CLIENT => {
//! // The server just shuts down the socket, let's just exit
//! // from our event loop.
//! return;
//! }
//! _ => unreachable!(),
//! }
//! }
//! }
//!
//! ```
#![doc(html_root_url = "https://docs.rs/mio/0.6.12")]
#![crate_name = "mio"]
#![deny(warnings, missing_docs, missing_debug_implementations)]
extern crate lazycell;
extern crate net2;
extern crate iovec;
#[cfg(target_os = "fuchsia")]
extern crate fuchsia_zircon as zircon;
#[cfg(target_os = "fuchsia")]
extern crate fuchsia_zircon_sys as zircon_sys;
#[cfg(unix)]
extern crate libc;
#[cfg(windows)]
extern crate miow;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
#[macro_use]
extern crate log;
mod event_imp;
mod io;
mod poll;
mod sys;
mod token;
pub mod net;
#[deprecated(since = "0.6.5", note = "use mio-extras instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod channel;
#[deprecated(since = "0.6.5", note = "use mio-extras instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod timer;
#[deprecated(since = "0.6.5", note = "update to use `Poll`")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod deprecated;
#[deprecated(since = "0.6.5", note = "use iovec crate directly")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use iovec::IoVec;
#[deprecated(since = "0.6.6", note = "use net module instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod tcp {
pub use net::{TcpListener, TcpStream};
pub use std::net::Shutdown;
}
#[deprecated(since = "0.6.6", note = "use net module instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod udp;
pub use poll::{
Poll,
Registration,
SetReadiness,
};
pub use event_imp::{
PollOpt,
Ready,
};
pub use token::Token;
pub mod event {
//! Readiness event types and utilities.
pub use super::poll::{Events, Iter};
pub use super::event_imp::{Event, Evented};
}
pub use event::{
Events,
};
#[deprecated(since = "0.6.5", note = "use events:: instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use event::{Event, Evented};
#[deprecated(since = "0.6.5", note = "use events::Iter instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use poll::Iter as EventsIter;
#[deprecated(since = "0.6.5", note = "std::io::Error can avoid the allocation now")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use io::deprecated::would_block;
#[cfg(all(unix, not(target_os = "fuchsia")))]
pub mod unix {
//! Unix only extensions
pub use sys::{
EventedFd,
};
pub use sys::unix::UnixReady;
}
#[cfg(target_os = "fuchsia")]
pub mod fuchsia {
//! Fuchsia-only extensions
//!
//! # Stability
//!
//! This module depends on the [magenta-sys crate](https://crates.io/crates/magenta-sys)
//! and so might introduce breaking changes, even on minor releases,
//! so long as that crate remains unstable.
pub use sys::{
EventedHandle,
};
pub use sys::fuchsia::{FuchsiaReady, zx_signals_t};
}
/// Windows-only extensions to the mio crate.
///
/// Mio on windows is currently implemented with IOCP for a high-performance
/// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample
/// bindings for the system to connect networking types to asynchronous I/O. On
/// Unix this scheme is then also extensible to all other file descriptors with
/// the `EventedFd` type, but on Windows no such analog is available. The
/// purpose of this module, however, is to similarly provide a mechanism for
/// foreign I/O types to get hooked up into the IOCP event loop.
///
/// This module provides two types for interfacing with a custom IOCP handle:
///
/// * `Binding` - this type is intended to govern binding with mio's `Poll`
/// type. Each I/O object should contain an instance of `Binding` that's
/// interfaced with for the implementation of the `Evented` trait. The
/// `register`, `reregister`, and `deregister` methods for the `Evented` trait
/// all have rough analogs with `Binding`.
///
/// Note that this type **does not handle readiness**. That is, this type does
/// not handle whether sockets are readable/writable/etc. It's intended that
/// IOCP types will internally manage this state with a `SetReadiness` type
/// from the `poll` module. The `SetReadiness` is typically lazily created on
/// the first time that `Evented::register` is called and then stored in the
/// I/O object.
///
/// Also note that for types which represent streams of bytes the mio
/// interface of *readiness* doesn't map directly to the Windows model of
/// *completion*. This means that types will have to perform internal
/// buffering to ensure that a readiness interface can be provided. For a
/// sample implementation see the TCP/UDP modules in mio itself.
///
/// * `Overlapped` - this type is intended to be used as the concrete instances
/// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for
/// safety, that all asynchronous operations are initiated with an instance of
/// `Overlapped` and not another instantiation of `OVERLAPPED`.
///
/// Mio's `Overlapped` type is created with a function pointer that receives
/// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is
/// defined in the `winapi` crate. Whenever a completion is posted to an IOCP
/// object the `OVERLAPPED` that was signaled will be interpreted as
/// `Overlapped` in the mio crate and this function pointer will be invoked.
/// Through this function pointer, and through the `OVERLAPPED` pointer,
/// implementations can handle management of I/O events.
///
/// When put together these two types enable custom Windows handles to be
/// registered with mio's event loops. The `Binding` type is used to associate
/// handles and the `Overlapped` type is used to execute I/O operations. When
/// the I/O operations are completed a custom function pointer is called which
/// typically modifies a `SetReadiness` set by `Evented` methods which will get
/// later hooked into the mio event loop.
#[cfg(windows)]
pub mod windows {
pub use sys::{Overlapped, Binding};
}
#[cfg(feature = "with-deprecated")]
mod convert {
use std::time::Duration;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// Convert a `Duration` to milliseconds, rounding up and saturating at
/// `u64::MAX`.
///
/// The saturating is fine because `u64::MAX` milliseconds are still many
/// million years.
pub fn millis(duration: Duration) -> u64
|
}
|
{
// Round up.
let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
}
|
identifier_body
|
lib.rs
|
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating a [`Poll`], which reads events from the OS and
//! put them into [`Events`]. You can handle IO events from the OS with it.
//!
//! For more detail, see [`Poll`].
//!
//! [`Poll`]: struct.Poll.html
//! [`Events`]: struct.Events.html
//!
//! # Example
//!
//! ```
//! use mio::*;
//! use mio::net::{TcpListener, TcpStream};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = "127.0.0.1:13265".parse().unwrap();
//!
//! // Setup the server socket
//! let server = TcpListener::bind(&addr).unwrap();
//!
//! // Create a poll instance
//! let poll = Poll::new().unwrap();
//!
//! // Start listening for incoming connections
//! poll.register(&server, SERVER, Ready::readable(),
//! PollOpt::edge()).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpStream::connect(&addr).unwrap();
//!
//! // Register the socket
//! poll.register(&sock, CLIENT, Ready::readable(),
//! PollOpt::edge()).unwrap();
//!
//! // Create storage for events
//! let mut events = Events::with_capacity(1024);
//!
//! loop {
//! poll.poll(&mut events, None).unwrap();
//!
//! for event in events.iter() {
//! match event.token() {
//! SERVER => {
//! // Accept and drop the socket immediately, this will close
//! // the socket and notify the client of the EOF.
//! let _ = server.accept();
//! }
//! CLIENT => {
//! // The server just shuts down the socket, let's just exit
//! // from our event loop.
//! return;
//! }
//! _ => unreachable!(),
//! }
//! }
//! }
//!
//! ```
#![doc(html_root_url = "https://docs.rs/mio/0.6.12")]
#![crate_name = "mio"]
#![deny(warnings, missing_docs, missing_debug_implementations)]
extern crate lazycell;
extern crate net2;
extern crate iovec;
#[cfg(target_os = "fuchsia")]
extern crate fuchsia_zircon as zircon;
#[cfg(target_os = "fuchsia")]
extern crate fuchsia_zircon_sys as zircon_sys;
#[cfg(unix)]
extern crate libc;
#[cfg(windows)]
extern crate miow;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
#[macro_use]
extern crate log;
mod event_imp;
mod io;
mod poll;
mod sys;
mod token;
pub mod net;
#[deprecated(since = "0.6.5", note = "use mio-extras instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod channel;
#[deprecated(since = "0.6.5", note = "use mio-extras instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod timer;
#[deprecated(since = "0.6.5", note = "update to use `Poll`")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod deprecated;
#[deprecated(since = "0.6.5", note = "use iovec crate directly")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use iovec::IoVec;
#[deprecated(since = "0.6.6", note = "use net module instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod tcp {
pub use net::{TcpListener, TcpStream};
pub use std::net::Shutdown;
}
#[deprecated(since = "0.6.6", note = "use net module instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub mod udp;
pub use poll::{
Poll,
Registration,
SetReadiness,
};
pub use event_imp::{
PollOpt,
Ready,
};
pub use token::Token;
pub mod event {
//! Readiness event types and utilities.
pub use super::poll::{Events, Iter};
pub use super::event_imp::{Event, Evented};
}
pub use event::{
Events,
};
#[deprecated(since = "0.6.5", note = "use events:: instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use event::{Event, Evented};
#[deprecated(since = "0.6.5", note = "use events::Iter instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use poll::Iter as EventsIter;
#[deprecated(since = "0.6.5", note = "std::io::Error can avoid the allocation now")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub use io::deprecated::would_block;
#[cfg(all(unix, not(target_os = "fuchsia")))]
pub mod unix {
//! Unix only extensions
pub use sys::{
EventedFd,
};
pub use sys::unix::UnixReady;
}
#[cfg(target_os = "fuchsia")]
pub mod fuchsia {
//! Fuchsia-only extensions
//!
//! # Stability
//!
//! This module depends on the [magenta-sys crate](https://crates.io/crates/magenta-sys)
//! and so might introduce breaking changes, even on minor releases,
//! so long as that crate remains unstable.
pub use sys::{
EventedHandle,
};
pub use sys::fuchsia::{FuchsiaReady, zx_signals_t};
}
/// Windows-only extensions to the mio crate.
///
/// Mio on windows is currently implemented with IOCP for a high-performance
/// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample
/// bindings for the system to connect networking types to asynchronous I/O. On
/// Unix this scheme is then also extensible to all other file descriptors with
/// the `EventedFd` type, but on Windows no such analog is available. The
/// purpose of this module, however, is to similarly provide a mechanism for
/// foreign I/O types to get hooked up into the IOCP event loop.
///
/// This module provides two types for interfacing with a custom IOCP handle:
///
/// * `Binding` - this type is intended to govern binding with mio's `Poll`
/// type. Each I/O object should contain an instance of `Binding` that's
/// interfaced with for the implementation of the `Evented` trait. The
/// `register`, `reregister`, and `deregister` methods for the `Evented` trait
/// all have rough analogs with `Binding`.
///
/// Note that this type **does not handle readiness**. That is, this type does
/// not handle whether sockets are readable/writable/etc. It's intended that
/// IOCP types will internally manage this state with a `SetReadiness` type
/// from the `poll` module. The `SetReadiness` is typically lazily created on
/// the first time that `Evented::register` is called and then stored in the
/// I/O object.
///
/// Also note that for types which represent streams of bytes the mio
/// interface of *readiness* doesn't map directly to the Windows model of
/// *completion*. This means that types will have to perform internal
/// buffering to ensure that a readiness interface can be provided. For a
/// sample implementation see the TCP/UDP modules in mio itself.
///
/// * `Overlapped` - this type is intended to be used as the concrete instances
/// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for
/// safety, that all asynchronous operations are initiated with an instance of
/// `Overlapped` and not another instantiation of `OVERLAPPED`.
///
/// Mio's `Overlapped` type is created with a function pointer that receives
/// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is
/// defined in the `winapi` crate. Whenever a completion is posted to an IOCP
/// object the `OVERLAPPED` that was signaled will be interpreted as
/// `Overlapped` in the mio crate and this function pointer will be invoked.
/// Through this function pointer, and through the `OVERLAPPED` pointer,
/// implementations can handle management of I/O events.
///
/// When put together these two types enable custom Windows handles to be
/// registered with mio's event loops. The `Binding` type is used to associate
/// handles and the `Overlapped` type is used to execute I/O operations. When
/// the I/O operations are completed a custom function pointer is called which
/// typically modifies a `SetReadiness` set by `Evented` methods which will get
/// later hooked into the mio event loop.
#[cfg(windows)]
pub mod windows {
pub use sys::{Overlapped, Binding};
}
#[cfg(feature = "with-deprecated")]
mod convert {
use std::time::Duration;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// Convert a `Duration` to milliseconds, rounding up and saturating at
/// `u64::MAX`.
///
/// The saturating is fine because `u64::MAX` milliseconds are still many
/// million years.
pub fn
|
(duration: Duration) -> u64 {
// Round up.
let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
}
}
|
millis
|
identifier_name
|
main.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(label_break_value)]
|
#[macro_use]
extern crate log;
mod app;
mod audio;
mod debug;
mod device;
mod exception;
mod macros;
mod memory;
mod null_output;
mod palette;
mod sound_buffer;
mod util;
mod video_buffer;
mod video_renderer;
use core::alloc::Layout;
use core::panic::PanicInfo;
use cortex_a::asm;
use linked_list_allocator::LockedHeap;
use crate::device::console::{Console, Output};
use crate::device::interrupt::{InterruptControl, Irq};
use crate::util::sync::NullLock;
#[global_allocator]
static ALLOCATOR: LockedHeap = LockedHeap::empty();
static DMA_ALLOCATOR: LockedHeap = LockedHeap::empty();
static mut CONSOLE: Console = Console::new();
static IRQ_CONTROL: NullLock<InterruptControl> = NullLock::new(InterruptControl::new());
fn start() ->! {
extern "C" {
//noinspection RsStaticConstNaming
static __exception_vectors_start: u64;
}
print!("Initializing console...\n");
{
let dma_range = memory::dma_heap_range();
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mbox::new_with_buffer(memory::map::MBOX_BASE, dma_range.0, 64);
let uart = device::uart::Uart::new(memory::map::UART_BASE);
uart.init(&mut mbox, &gpio).unwrap();
unsafe {
CONSOLE.set_output(Output::Uart(uart));
}
}
print!("Installing exception handlers...\n");
unsafe {
use cortex_a::{barrier, regs::*};
let vectors = &__exception_vectors_start as *const _ as u64;
VBAR_EL1.set(vectors);
barrier::isb(barrier::SY);
}
print!("Initializing MMU...\n");
unsafe {
memory::mmu::init_page_table();
memory::mmu::init();
}
print!("Initializing heap...\n");
unsafe {
let heap_range = memory::app_heap_range();
let dma_range = memory::dma_heap_range();
ALLOCATOR
.lock()
.init(heap_range.0, heap_range.1 - heap_range.0);
DMA_ALLOCATOR
.lock()
.init(dma_range.0, dma_range.1 - dma_range.0);
}
memory::print_mmap();
match main() {
Ok(_) => (),
Err(err) => print!("ERROR: {}\n", err),
};
loop {
asm::wfe()
}
}
fn main() -> Result<(), &'static str> {
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mbox::build(memory::map::MBOX_BASE)?;
print!("Initializing logger...\n");
let logger = util::logger::SimpleLogger::new();
logger.init().map_err(|_| "failed to initialize log")?;
let max_clock = device::board::get_max_clock_rate(&mut mbox, device::board::Clock::Arm)?;
print!("Setting ARM clock speed to {}\n", max_clock);
device::board::set_clock_speed(&mut mbox, device::board::Clock::Arm, max_clock)?;
print!("Initializing interrupts...\n");
IRQ_CONTROL.lock(|ctl| {
ctl.init();
});
print!("Initializing SD...\n");
let mut sd = device::sd::Sd::new(memory::map::EMMC_BASE);
sd.init(&gpio).map_err(|_| "failed to initialize sdcard")?;
print!("Initializing FAT32...\n");
let fat32 = device::fat32::Fat32::mount(sd, 0)?;
fat32.info();
print!("Starting app...\n");
let mut app = app::App::build(&gpio, &fat32)?;
crate::IRQ_CONTROL.lock(|ctl| {
ctl.register(Irq::Dma0, app.audio_engine.make_irq_handler());
ctl.enable(Irq::Dma0);
});
app.autostart(&fat32)?;
app.run()?;
util::logger::shutdown().map_err(|_| "failed to shutdown log")
}
#[alloc_error_handler]
fn on_oom(_layout: Layout) ->! {
print!("ERROR: Out of memory!\n");
loop {
asm::wfe()
}
}
#[panic_handler]
fn on_panic(info: &PanicInfo) ->! {
//interrupt::disable();
print!("ERROR: {}\n", info);
loop {
asm::wfe()
}
}
raspi3_boot::entry!(start);
|
#![feature(range_contains)]
extern crate alloc;
|
random_line_split
|
main.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(label_break_value)]
#![feature(range_contains)]
extern crate alloc;
#[macro_use]
extern crate log;
mod app;
mod audio;
mod debug;
mod device;
mod exception;
mod macros;
mod memory;
mod null_output;
mod palette;
mod sound_buffer;
mod util;
mod video_buffer;
mod video_renderer;
use core::alloc::Layout;
use core::panic::PanicInfo;
use cortex_a::asm;
use linked_list_allocator::LockedHeap;
use crate::device::console::{Console, Output};
use crate::device::interrupt::{InterruptControl, Irq};
use crate::util::sync::NullLock;
#[global_allocator]
static ALLOCATOR: LockedHeap = LockedHeap::empty();
static DMA_ALLOCATOR: LockedHeap = LockedHeap::empty();
static mut CONSOLE: Console = Console::new();
static IRQ_CONTROL: NullLock<InterruptControl> = NullLock::new(InterruptControl::new());
fn start() ->! {
extern "C" {
//noinspection RsStaticConstNaming
static __exception_vectors_start: u64;
}
print!("Initializing console...\n");
{
let dma_range = memory::dma_heap_range();
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mbox::new_with_buffer(memory::map::MBOX_BASE, dma_range.0, 64);
let uart = device::uart::Uart::new(memory::map::UART_BASE);
uart.init(&mut mbox, &gpio).unwrap();
unsafe {
CONSOLE.set_output(Output::Uart(uart));
}
}
print!("Installing exception handlers...\n");
unsafe {
use cortex_a::{barrier, regs::*};
let vectors = &__exception_vectors_start as *const _ as u64;
VBAR_EL1.set(vectors);
barrier::isb(barrier::SY);
}
print!("Initializing MMU...\n");
unsafe {
memory::mmu::init_page_table();
memory::mmu::init();
}
print!("Initializing heap...\n");
unsafe {
let heap_range = memory::app_heap_range();
let dma_range = memory::dma_heap_range();
ALLOCATOR
.lock()
.init(heap_range.0, heap_range.1 - heap_range.0);
DMA_ALLOCATOR
.lock()
.init(dma_range.0, dma_range.1 - dma_range.0);
}
memory::print_mmap();
match main() {
Ok(_) => (),
Err(err) => print!("ERROR: {}\n", err),
};
loop {
asm::wfe()
}
}
fn main() -> Result<(), &'static str> {
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mbox::build(memory::map::MBOX_BASE)?;
print!("Initializing logger...\n");
let logger = util::logger::SimpleLogger::new();
logger.init().map_err(|_| "failed to initialize log")?;
let max_clock = device::board::get_max_clock_rate(&mut mbox, device::board::Clock::Arm)?;
print!("Setting ARM clock speed to {}\n", max_clock);
device::board::set_clock_speed(&mut mbox, device::board::Clock::Arm, max_clock)?;
print!("Initializing interrupts...\n");
IRQ_CONTROL.lock(|ctl| {
ctl.init();
});
print!("Initializing SD...\n");
let mut sd = device::sd::Sd::new(memory::map::EMMC_BASE);
sd.init(&gpio).map_err(|_| "failed to initialize sdcard")?;
print!("Initializing FAT32...\n");
let fat32 = device::fat32::Fat32::mount(sd, 0)?;
fat32.info();
print!("Starting app...\n");
let mut app = app::App::build(&gpio, &fat32)?;
crate::IRQ_CONTROL.lock(|ctl| {
ctl.register(Irq::Dma0, app.audio_engine.make_irq_handler());
ctl.enable(Irq::Dma0);
});
app.autostart(&fat32)?;
app.run()?;
util::logger::shutdown().map_err(|_| "failed to shutdown log")
}
#[alloc_error_handler]
fn on_oom(_layout: Layout) ->! {
print!("ERROR: Out of memory!\n");
loop {
asm::wfe()
}
}
#[panic_handler]
fn
|
(info: &PanicInfo) ->! {
//interrupt::disable();
print!("ERROR: {}\n", info);
loop {
asm::wfe()
}
}
raspi3_boot::entry!(start);
|
on_panic
|
identifier_name
|
main.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(label_break_value)]
#![feature(range_contains)]
extern crate alloc;
#[macro_use]
extern crate log;
mod app;
mod audio;
mod debug;
mod device;
mod exception;
mod macros;
mod memory;
mod null_output;
mod palette;
mod sound_buffer;
mod util;
mod video_buffer;
mod video_renderer;
use core::alloc::Layout;
use core::panic::PanicInfo;
use cortex_a::asm;
use linked_list_allocator::LockedHeap;
use crate::device::console::{Console, Output};
use crate::device::interrupt::{InterruptControl, Irq};
use crate::util::sync::NullLock;
#[global_allocator]
static ALLOCATOR: LockedHeap = LockedHeap::empty();
static DMA_ALLOCATOR: LockedHeap = LockedHeap::empty();
static mut CONSOLE: Console = Console::new();
static IRQ_CONTROL: NullLock<InterruptControl> = NullLock::new(InterruptControl::new());
fn start() ->!
|
let vectors = &__exception_vectors_start as *const _ as u64;
VBAR_EL1.set(vectors);
barrier::isb(barrier::SY);
}
print!("Initializing MMU...\n");
unsafe {
memory::mmu::init_page_table();
memory::mmu::init();
}
print!("Initializing heap...\n");
unsafe {
let heap_range = memory::app_heap_range();
let dma_range = memory::dma_heap_range();
ALLOCATOR
.lock()
.init(heap_range.0, heap_range.1 - heap_range.0);
DMA_ALLOCATOR
.lock()
.init(dma_range.0, dma_range.1 - dma_range.0);
}
memory::print_mmap();
match main() {
Ok(_) => (),
Err(err) => print!("ERROR: {}\n", err),
};
loop {
asm::wfe()
}
}
fn main() -> Result<(), &'static str> {
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mbox::build(memory::map::MBOX_BASE)?;
print!("Initializing logger...\n");
let logger = util::logger::SimpleLogger::new();
logger.init().map_err(|_| "failed to initialize log")?;
let max_clock = device::board::get_max_clock_rate(&mut mbox, device::board::Clock::Arm)?;
print!("Setting ARM clock speed to {}\n", max_clock);
device::board::set_clock_speed(&mut mbox, device::board::Clock::Arm, max_clock)?;
print!("Initializing interrupts...\n");
IRQ_CONTROL.lock(|ctl| {
ctl.init();
});
print!("Initializing SD...\n");
let mut sd = device::sd::Sd::new(memory::map::EMMC_BASE);
sd.init(&gpio).map_err(|_| "failed to initialize sdcard")?;
print!("Initializing FAT32...\n");
let fat32 = device::fat32::Fat32::mount(sd, 0)?;
fat32.info();
print!("Starting app...\n");
let mut app = app::App::build(&gpio, &fat32)?;
crate::IRQ_CONTROL.lock(|ctl| {
ctl.register(Irq::Dma0, app.audio_engine.make_irq_handler());
ctl.enable(Irq::Dma0);
});
app.autostart(&fat32)?;
app.run()?;
util::logger::shutdown().map_err(|_| "failed to shutdown log")
}
#[alloc_error_handler]
fn on_oom(_layout: Layout) ->! {
print!("ERROR: Out of memory!\n");
loop {
asm::wfe()
}
}
#[panic_handler]
fn on_panic(info: &PanicInfo) ->! {
//interrupt::disable();
print!("ERROR: {}\n", info);
loop {
asm::wfe()
}
}
raspi3_boot::entry!(start);
|
{
extern "C" {
//noinspection RsStaticConstNaming
static __exception_vectors_start: u64;
}
print!("Initializing console ...\n");
{
let dma_range = memory::dma_heap_range();
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mbox::new_with_buffer(memory::map::MBOX_BASE, dma_range.0, 64);
let uart = device::uart::Uart::new(memory::map::UART_BASE);
uart.init(&mut mbox, &gpio).unwrap();
unsafe {
CONSOLE.set_output(Output::Uart(uart));
}
}
print!("Installing exception handlers ...\n");
unsafe {
use cortex_a::{barrier, regs::*};
|
identifier_body
|
json.rs
|
use std::collections::HashMap;
use std::fmt;
use std::mem;
use serde::de::{self, Deserializer, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::bail;
use crate::errors::FinchResult;
use crate::filtering::FilterParams;
pub use crate::serialization::mash::{read_mash_file, write_mash_file};
use crate::serialization::Sketch;
use crate::sketch_schemes::{KmerCount, SketchParams};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JsonSketch {
pub name: String,
pub seq_length: Option<u64>,
pub num_valid_kmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
pub hashes: Vec<KmerCount>,
}
impl JsonSketch {
pub fn new(
name: &str,
length: u64,
n_kmers: u64,
kmercounts: Vec<KmerCount>,
filters: &HashMap<String, String>,
) -> Self {
JsonSketch {
name: String::from(name),
seq_length: Some(length),
num_valid_kmers: Some(n_kmers),
comment: Some(String::from("")),
filters: Some(filters.clone()),
hashes: kmercounts,
}
}
pub fn len(&self) -> usize {
self.hashes.len()
}
pub fn is_empty(&self) -> bool {
self.hashes.is_empty()
}
}
impl Serialize for JsonSketch {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hash_list = Vec::with_capacity(self.hashes.len());
let mut kmer_list = Vec::with_capacity(self.hashes.len());
let mut count_list = Vec::with_capacity(self.hashes.len());
for hash in &self.hashes {
hash_list.push(hash.hash.to_string());
kmer_list.push(String::from_utf8(hash.kmer.clone()).unwrap());
count_list.push(hash.count);
}
let mut state = serializer.serialize_struct("Sketch", 8)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("seqLength", &self.seq_length)?;
state.serialize_field("numValidKmers", &self.num_valid_kmers)?;
state.serialize_field("comment", &self.comment)?;
state.serialize_field("filters", &self.filters)?;
state.serialize_field("hashes", &hash_list)?;
state.serialize_field("kmers", &kmer_list)?;
state.serialize_field("counts", &count_list)?;
state.end()
}
}
impl<'de> Deserialize<'de> for JsonSketch {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[allow(non_snake_case)]
#[derive(Deserialize)]
struct BaseJsonSketch {
pub name: String,
pub seqLength: Option<u64>,
pub numValidKmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
hashes: Vec<QuotedU64>,
kmers: Option<Vec<String>>,
counts: Option<Vec<u32>>,
}
let mut jsketch = BaseJsonSketch::deserialize(deserializer)?;
let mut kmercount_list = Vec::with_capacity(jsketch.hashes.len());
for i in 0..jsketch.hashes.len() {
let hash = jsketch.hashes[i].0;
let kmer = match &mut jsketch.kmers {
Some(v) => mem::replace(&mut v[i], String::new()).into_bytes(),
None => Vec::new(),
};
let count = match &jsketch.counts {
Some(v) => v[i],
None => 1,
};
kmercount_list.push(KmerCount {
hash,
kmer,
count,
extra_count: count / 2,
label: None,
});
}
Ok(JsonSketch {
name: jsketch.name,
seq_length: jsketch.seqLength,
num_valid_kmers: jsketch.numValidKmers,
comment: jsketch.comment,
filters: jsketch.filters,
hashes: kmercount_list,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MultiSketch {
pub kmer: u8,
pub alphabet: String,
#[serde(rename = "preserveCase")]
pub preserve_case: bool,
pub canonical: bool,
#[serde(rename = "sketchSize")]
pub sketch_size: u32,
#[serde(rename = "hashType")]
pub hash_type: String,
#[serde(rename = "hashBits")]
pub hash_bits: u16,
#[serde(rename = "hashSeed")]
pub hash_seed: u64,
pub scale: Option<f64>,
pub sketches: Vec<JsonSketch>,
}
impl MultiSketch {
pub fn get_params(&self) -> FinchResult<SketchParams> {
Ok(match (&*self.hash_type, self.scale) {
("MurmurHash3_x64_128", None) => {
if self.hash_bits!= 64 {
bail!(
"Multisketch has incompatible hash size ({}!= 64)",
self.hash_bits
);
}
SketchParams::Mash {
kmers_to_sketch: self.sketch_size as usize,
final_size: self.sketch_size as usize,
no_strict: true,
kmer_length: self.kmer,
hash_seed: self.hash_seed,
}
}
("MurmurHash3_x64_128", Some(scale)) => {
if self.hash_bits!= 64 {
bail!(
"Multisketch has incompatible hash size ({}!= 64)",
self.hash_bits
);
}
SketchParams::Scaled {
kmers_to_sketch: self.sketch_size as usize,
kmer_length: self.kmer,
scale,
hash_seed: self.hash_seed,
}
}
("None", _) => SketchParams::AllCounts {
kmer_length: self.kmer,
},
(x, _) => bail!("{} sketch type is not supported", x),
})
}
pub fn from_sketches(sketches: &[Sketch]) -> FinchResult<Self>
|
pub fn to_sketches(&self) -> FinchResult<Vec<Sketch>> {
let empty_hashmap = HashMap::new();
let mut sketches = Vec::with_capacity(self.sketches.len());
let sketch_params = self.get_params()?;
for sketch in &self.sketches {
let filters = sketch.filters.as_ref().unwrap_or(&empty_hashmap);
let filter_params = FilterParams::from_serialized(filters)?;
sketches.push(Sketch {
name: sketch.name.clone(),
seq_length: sketch.seq_length.unwrap_or(0),
num_valid_kmers: sketch.num_valid_kmers.unwrap_or(0),
comment: sketch.comment.clone().unwrap_or_else(|| "".to_string()),
hashes: sketch.hashes.clone(),
filter_params,
sketch_params: sketch_params.clone(),
});
}
Ok(sketches)
}
}
struct QuotedU64(u64);
impl<'de> Deserialize<'de> for QuotedU64 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct QuotedU64Visitor;
impl<'de> Visitor<'de> for QuotedU64Visitor {
type Value = QuotedU64;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("usize as a json string")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
value.parse().map(QuotedU64).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(QuotedU64Visitor)
}
}
|
{
let json_sketches: Vec<JsonSketch> = sketches.iter().map(|x| (*x).clone().into()).collect();
let sketch_params = SketchParams::from_sketches(&sketches)?;
// TODO: the scale isn't actually harmonized between the sketches at
// this point; it probably should be?
let (hash_type, hash_bits, hash_seed, scale) = sketch_params.hash_info();
Ok(MultiSketch {
alphabet: "ACGT".to_string(),
preserve_case: false,
canonical: true,
sketch_size: sketch_params.expected_size() as u32,
kmer: sketch_params.k(),
hash_type: hash_type.to_string(),
hash_bits,
hash_seed,
scale,
sketches: json_sketches,
})
}
|
identifier_body
|
json.rs
|
use std::collections::HashMap;
use std::fmt;
use std::mem;
use serde::de::{self, Deserializer, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::bail;
use crate::errors::FinchResult;
use crate::filtering::FilterParams;
pub use crate::serialization::mash::{read_mash_file, write_mash_file};
use crate::serialization::Sketch;
use crate::sketch_schemes::{KmerCount, SketchParams};
|
pub num_valid_kmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
pub hashes: Vec<KmerCount>,
}
impl JsonSketch {
pub fn new(
name: &str,
length: u64,
n_kmers: u64,
kmercounts: Vec<KmerCount>,
filters: &HashMap<String, String>,
) -> Self {
JsonSketch {
name: String::from(name),
seq_length: Some(length),
num_valid_kmers: Some(n_kmers),
comment: Some(String::from("")),
filters: Some(filters.clone()),
hashes: kmercounts,
}
}
pub fn len(&self) -> usize {
self.hashes.len()
}
pub fn is_empty(&self) -> bool {
self.hashes.is_empty()
}
}
impl Serialize for JsonSketch {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hash_list = Vec::with_capacity(self.hashes.len());
let mut kmer_list = Vec::with_capacity(self.hashes.len());
let mut count_list = Vec::with_capacity(self.hashes.len());
for hash in &self.hashes {
hash_list.push(hash.hash.to_string());
kmer_list.push(String::from_utf8(hash.kmer.clone()).unwrap());
count_list.push(hash.count);
}
let mut state = serializer.serialize_struct("Sketch", 8)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("seqLength", &self.seq_length)?;
state.serialize_field("numValidKmers", &self.num_valid_kmers)?;
state.serialize_field("comment", &self.comment)?;
state.serialize_field("filters", &self.filters)?;
state.serialize_field("hashes", &hash_list)?;
state.serialize_field("kmers", &kmer_list)?;
state.serialize_field("counts", &count_list)?;
state.end()
}
}
impl<'de> Deserialize<'de> for JsonSketch {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[allow(non_snake_case)]
#[derive(Deserialize)]
struct BaseJsonSketch {
pub name: String,
pub seqLength: Option<u64>,
pub numValidKmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
hashes: Vec<QuotedU64>,
kmers: Option<Vec<String>>,
counts: Option<Vec<u32>>,
}
let mut jsketch = BaseJsonSketch::deserialize(deserializer)?;
let mut kmercount_list = Vec::with_capacity(jsketch.hashes.len());
for i in 0..jsketch.hashes.len() {
let hash = jsketch.hashes[i].0;
let kmer = match &mut jsketch.kmers {
Some(v) => mem::replace(&mut v[i], String::new()).into_bytes(),
None => Vec::new(),
};
let count = match &jsketch.counts {
Some(v) => v[i],
None => 1,
};
kmercount_list.push(KmerCount {
hash,
kmer,
count,
extra_count: count / 2,
label: None,
});
}
Ok(JsonSketch {
name: jsketch.name,
seq_length: jsketch.seqLength,
num_valid_kmers: jsketch.numValidKmers,
comment: jsketch.comment,
filters: jsketch.filters,
hashes: kmercount_list,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MultiSketch {
pub kmer: u8,
pub alphabet: String,
#[serde(rename = "preserveCase")]
pub preserve_case: bool,
pub canonical: bool,
#[serde(rename = "sketchSize")]
pub sketch_size: u32,
#[serde(rename = "hashType")]
pub hash_type: String,
#[serde(rename = "hashBits")]
pub hash_bits: u16,
#[serde(rename = "hashSeed")]
pub hash_seed: u64,
pub scale: Option<f64>,
pub sketches: Vec<JsonSketch>,
}
impl MultiSketch {
pub fn get_params(&self) -> FinchResult<SketchParams> {
Ok(match (&*self.hash_type, self.scale) {
("MurmurHash3_x64_128", None) => {
if self.hash_bits!= 64 {
bail!(
"Multisketch has incompatible hash size ({}!= 64)",
self.hash_bits
);
}
SketchParams::Mash {
kmers_to_sketch: self.sketch_size as usize,
final_size: self.sketch_size as usize,
no_strict: true,
kmer_length: self.kmer,
hash_seed: self.hash_seed,
}
}
("MurmurHash3_x64_128", Some(scale)) => {
if self.hash_bits!= 64 {
bail!(
"Multisketch has incompatible hash size ({}!= 64)",
self.hash_bits
);
}
SketchParams::Scaled {
kmers_to_sketch: self.sketch_size as usize,
kmer_length: self.kmer,
scale,
hash_seed: self.hash_seed,
}
}
("None", _) => SketchParams::AllCounts {
kmer_length: self.kmer,
},
(x, _) => bail!("{} sketch type is not supported", x),
})
}
pub fn from_sketches(sketches: &[Sketch]) -> FinchResult<Self> {
let json_sketches: Vec<JsonSketch> = sketches.iter().map(|x| (*x).clone().into()).collect();
let sketch_params = SketchParams::from_sketches(&sketches)?;
// TODO: the scale isn't actually harmonized between the sketches at
// this point; it probably should be?
let (hash_type, hash_bits, hash_seed, scale) = sketch_params.hash_info();
Ok(MultiSketch {
alphabet: "ACGT".to_string(),
preserve_case: false,
canonical: true,
sketch_size: sketch_params.expected_size() as u32,
kmer: sketch_params.k(),
hash_type: hash_type.to_string(),
hash_bits,
hash_seed,
scale,
sketches: json_sketches,
})
}
pub fn to_sketches(&self) -> FinchResult<Vec<Sketch>> {
let empty_hashmap = HashMap::new();
let mut sketches = Vec::with_capacity(self.sketches.len());
let sketch_params = self.get_params()?;
for sketch in &self.sketches {
let filters = sketch.filters.as_ref().unwrap_or(&empty_hashmap);
let filter_params = FilterParams::from_serialized(filters)?;
sketches.push(Sketch {
name: sketch.name.clone(),
seq_length: sketch.seq_length.unwrap_or(0),
num_valid_kmers: sketch.num_valid_kmers.unwrap_or(0),
comment: sketch.comment.clone().unwrap_or_else(|| "".to_string()),
hashes: sketch.hashes.clone(),
filter_params,
sketch_params: sketch_params.clone(),
});
}
Ok(sketches)
}
}
struct QuotedU64(u64);
impl<'de> Deserialize<'de> for QuotedU64 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct QuotedU64Visitor;
impl<'de> Visitor<'de> for QuotedU64Visitor {
type Value = QuotedU64;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("usize as a json string")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
value.parse().map(QuotedU64).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(QuotedU64Visitor)
}
}
|
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JsonSketch {
pub name: String,
pub seq_length: Option<u64>,
|
random_line_split
|
json.rs
|
use std::collections::HashMap;
use std::fmt;
use std::mem;
use serde::de::{self, Deserializer, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::bail;
use crate::errors::FinchResult;
use crate::filtering::FilterParams;
pub use crate::serialization::mash::{read_mash_file, write_mash_file};
use crate::serialization::Sketch;
use crate::sketch_schemes::{KmerCount, SketchParams};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JsonSketch {
pub name: String,
pub seq_length: Option<u64>,
pub num_valid_kmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
pub hashes: Vec<KmerCount>,
}
impl JsonSketch {
pub fn new(
name: &str,
length: u64,
n_kmers: u64,
kmercounts: Vec<KmerCount>,
filters: &HashMap<String, String>,
) -> Self {
JsonSketch {
name: String::from(name),
seq_length: Some(length),
num_valid_kmers: Some(n_kmers),
comment: Some(String::from("")),
filters: Some(filters.clone()),
hashes: kmercounts,
}
}
pub fn len(&self) -> usize {
self.hashes.len()
}
pub fn is_empty(&self) -> bool {
self.hashes.is_empty()
}
}
impl Serialize for JsonSketch {
fn
|
<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hash_list = Vec::with_capacity(self.hashes.len());
let mut kmer_list = Vec::with_capacity(self.hashes.len());
let mut count_list = Vec::with_capacity(self.hashes.len());
for hash in &self.hashes {
hash_list.push(hash.hash.to_string());
kmer_list.push(String::from_utf8(hash.kmer.clone()).unwrap());
count_list.push(hash.count);
}
let mut state = serializer.serialize_struct("Sketch", 8)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("seqLength", &self.seq_length)?;
state.serialize_field("numValidKmers", &self.num_valid_kmers)?;
state.serialize_field("comment", &self.comment)?;
state.serialize_field("filters", &self.filters)?;
state.serialize_field("hashes", &hash_list)?;
state.serialize_field("kmers", &kmer_list)?;
state.serialize_field("counts", &count_list)?;
state.end()
}
}
impl<'de> Deserialize<'de> for JsonSketch {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[allow(non_snake_case)]
#[derive(Deserialize)]
struct BaseJsonSketch {
pub name: String,
pub seqLength: Option<u64>,
pub numValidKmers: Option<u64>,
pub comment: Option<String>,
pub filters: Option<HashMap<String, String>>,
hashes: Vec<QuotedU64>,
kmers: Option<Vec<String>>,
counts: Option<Vec<u32>>,
}
let mut jsketch = BaseJsonSketch::deserialize(deserializer)?;
let mut kmercount_list = Vec::with_capacity(jsketch.hashes.len());
for i in 0..jsketch.hashes.len() {
let hash = jsketch.hashes[i].0;
let kmer = match &mut jsketch.kmers {
Some(v) => mem::replace(&mut v[i], String::new()).into_bytes(),
None => Vec::new(),
};
let count = match &jsketch.counts {
Some(v) => v[i],
None => 1,
};
kmercount_list.push(KmerCount {
hash,
kmer,
count,
extra_count: count / 2,
label: None,
});
}
Ok(JsonSketch {
name: jsketch.name,
seq_length: jsketch.seqLength,
num_valid_kmers: jsketch.numValidKmers,
comment: jsketch.comment,
filters: jsketch.filters,
hashes: kmercount_list,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MultiSketch {
pub kmer: u8,
pub alphabet: String,
#[serde(rename = "preserveCase")]
pub preserve_case: bool,
pub canonical: bool,
#[serde(rename = "sketchSize")]
pub sketch_size: u32,
#[serde(rename = "hashType")]
pub hash_type: String,
#[serde(rename = "hashBits")]
pub hash_bits: u16,
#[serde(rename = "hashSeed")]
pub hash_seed: u64,
pub scale: Option<f64>,
pub sketches: Vec<JsonSketch>,
}
impl MultiSketch {
pub fn get_params(&self) -> FinchResult<SketchParams> {
Ok(match (&*self.hash_type, self.scale) {
("MurmurHash3_x64_128", None) => {
if self.hash_bits!= 64 {
bail!(
"Multisketch has incompatible hash size ({}!= 64)",
self.hash_bits
);
}
SketchParams::Mash {
kmers_to_sketch: self.sketch_size as usize,
final_size: self.sketch_size as usize,
no_strict: true,
kmer_length: self.kmer,
hash_seed: self.hash_seed,
}
}
("MurmurHash3_x64_128", Some(scale)) => {
if self.hash_bits!= 64 {
bail!(
"Multisketch has incompatible hash size ({}!= 64)",
self.hash_bits
);
}
SketchParams::Scaled {
kmers_to_sketch: self.sketch_size as usize,
kmer_length: self.kmer,
scale,
hash_seed: self.hash_seed,
}
}
("None", _) => SketchParams::AllCounts {
kmer_length: self.kmer,
},
(x, _) => bail!("{} sketch type is not supported", x),
})
}
pub fn from_sketches(sketches: &[Sketch]) -> FinchResult<Self> {
let json_sketches: Vec<JsonSketch> = sketches.iter().map(|x| (*x).clone().into()).collect();
let sketch_params = SketchParams::from_sketches(&sketches)?;
// TODO: the scale isn't actually harmonized between the sketches at
// this point; it probably should be?
let (hash_type, hash_bits, hash_seed, scale) = sketch_params.hash_info();
Ok(MultiSketch {
alphabet: "ACGT".to_string(),
preserve_case: false,
canonical: true,
sketch_size: sketch_params.expected_size() as u32,
kmer: sketch_params.k(),
hash_type: hash_type.to_string(),
hash_bits,
hash_seed,
scale,
sketches: json_sketches,
})
}
pub fn to_sketches(&self) -> FinchResult<Vec<Sketch>> {
let empty_hashmap = HashMap::new();
let mut sketches = Vec::with_capacity(self.sketches.len());
let sketch_params = self.get_params()?;
for sketch in &self.sketches {
let filters = sketch.filters.as_ref().unwrap_or(&empty_hashmap);
let filter_params = FilterParams::from_serialized(filters)?;
sketches.push(Sketch {
name: sketch.name.clone(),
seq_length: sketch.seq_length.unwrap_or(0),
num_valid_kmers: sketch.num_valid_kmers.unwrap_or(0),
comment: sketch.comment.clone().unwrap_or_else(|| "".to_string()),
hashes: sketch.hashes.clone(),
filter_params,
sketch_params: sketch_params.clone(),
});
}
Ok(sketches)
}
}
struct QuotedU64(u64);
impl<'de> Deserialize<'de> for QuotedU64 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct QuotedU64Visitor;
impl<'de> Visitor<'de> for QuotedU64Visitor {
type Value = QuotedU64;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("usize as a json string")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
value.parse().map(QuotedU64).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(QuotedU64Visitor)
}
}
|
serialize
|
identifier_name
|
exhaustive_natural_range.rs
|
use itertools::Itertools;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::strings::ToDebugString;
use malachite_nz::natural::exhaustive::exhaustive_natural_range;
use malachite_nz::natural::Natural;
fn expected_range_len(a: &Natural, b: &Natural) -> usize {
usize::exact_from(b) - usize::exact_from(a)
}
fn exhaustive_natural_range_helper(a: Natural, b: Natural, values: &str) {
let xs = exhaustive_natural_range(a.clone(), b.clone())
.take(20)
.collect_vec()
.to_debug_string();
assert_eq!(xs, values);
let len = expected_range_len(&a, &b);
assert_eq!(exhaustive_natural_range(a.clone(), b.clone()).count(), len);
let mut init = exhaustive_natural_range(a, b)
.rev()
.skip(len.saturating_sub(20))
.collect_vec();
init.reverse();
assert_eq!(xs, init.to_debug_string());
}
#[test]
fn
|
() {
exhaustive_natural_range_helper(Natural::ZERO, Natural::ZERO, "[]");
exhaustive_natural_range_helper(Natural::ZERO, Natural::ONE, "[0]");
exhaustive_natural_range_helper(
Natural::ZERO,
Natural::exact_from(10),
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]",
);
exhaustive_natural_range_helper(
Natural::exact_from(10),
Natural::exact_from(20),
"[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]",
);
exhaustive_natural_range_helper(
Natural::exact_from(10),
Natural::exact_from(100),
"[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]",
);
}
#[test]
#[should_panic]
fn exhaustive_natural_range_fail() {
exhaustive_natural_range(Natural::ONE, Natural::ZERO);
}
|
test_exhaustive_natural_range
|
identifier_name
|
exhaustive_natural_range.rs
|
use itertools::Itertools;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::strings::ToDebugString;
use malachite_nz::natural::exhaustive::exhaustive_natural_range;
use malachite_nz::natural::Natural;
fn expected_range_len(a: &Natural, b: &Natural) -> usize {
usize::exact_from(b) - usize::exact_from(a)
}
fn exhaustive_natural_range_helper(a: Natural, b: Natural, values: &str) {
let xs = exhaustive_natural_range(a.clone(), b.clone())
.take(20)
.collect_vec()
.to_debug_string();
assert_eq!(xs, values);
let len = expected_range_len(&a, &b);
assert_eq!(exhaustive_natural_range(a.clone(), b.clone()).count(), len);
let mut init = exhaustive_natural_range(a, b)
.rev()
.skip(len.saturating_sub(20))
.collect_vec();
init.reverse();
assert_eq!(xs, init.to_debug_string());
}
#[test]
fn test_exhaustive_natural_range() {
exhaustive_natural_range_helper(Natural::ZERO, Natural::ZERO, "[]");
exhaustive_natural_range_helper(Natural::ZERO, Natural::ONE, "[0]");
exhaustive_natural_range_helper(
Natural::ZERO,
Natural::exact_from(10),
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]",
);
exhaustive_natural_range_helper(
Natural::exact_from(10),
Natural::exact_from(20),
"[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]",
);
exhaustive_natural_range_helper(
Natural::exact_from(10),
Natural::exact_from(100),
"[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]",
);
}
#[test]
#[should_panic]
fn exhaustive_natural_range_fail()
|
{
exhaustive_natural_range(Natural::ONE, Natural::ZERO);
}
|
identifier_body
|
|
exhaustive_natural_range.rs
|
use itertools::Itertools;
use malachite_base::num::basic::traits::{One, Zero};
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::strings::ToDebugString;
use malachite_nz::natural::exhaustive::exhaustive_natural_range;
use malachite_nz::natural::Natural;
fn expected_range_len(a: &Natural, b: &Natural) -> usize {
usize::exact_from(b) - usize::exact_from(a)
}
fn exhaustive_natural_range_helper(a: Natural, b: Natural, values: &str) {
let xs = exhaustive_natural_range(a.clone(), b.clone())
.take(20)
|
assert_eq!(xs, values);
let len = expected_range_len(&a, &b);
assert_eq!(exhaustive_natural_range(a.clone(), b.clone()).count(), len);
let mut init = exhaustive_natural_range(a, b)
.rev()
.skip(len.saturating_sub(20))
.collect_vec();
init.reverse();
assert_eq!(xs, init.to_debug_string());
}
#[test]
fn test_exhaustive_natural_range() {
exhaustive_natural_range_helper(Natural::ZERO, Natural::ZERO, "[]");
exhaustive_natural_range_helper(Natural::ZERO, Natural::ONE, "[0]");
exhaustive_natural_range_helper(
Natural::ZERO,
Natural::exact_from(10),
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]",
);
exhaustive_natural_range_helper(
Natural::exact_from(10),
Natural::exact_from(20),
"[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]",
);
exhaustive_natural_range_helper(
Natural::exact_from(10),
Natural::exact_from(100),
"[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]",
);
}
#[test]
#[should_panic]
fn exhaustive_natural_range_fail() {
exhaustive_natural_range(Natural::ONE, Natural::ZERO);
}
|
.collect_vec()
.to_debug_string();
|
random_line_split
|
generic-tuple-style-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:set print union on
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print case1
// gdb-check:$1 = {{RUST$ENUM$DISR = Case1, 0, 31868, 31868, 31868, 31868}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}, {RUST$ENUM$DISR = Case1, 0, 8970181431921507452}}
// gdb-command:print case2
// gdb-check:$2 = {{RUST$ENUM$DISR = Case2, 0, 4369, 4369, 4369, 4369}, {RUST$ENUM$DISR = Case2, 0, 286331153, 286331153}, {RUST$ENUM$DISR = Case2, 0, 1229782938247303441}}
// gdb-command:print case3
// gdb-check:$3 = {{RUST$ENUM$DISR = Case3, 0, 22873, 22873, 22873, 22873}, {RUST$ENUM$DISR = Case3, 0, 1499027801, 1499027801}, {RUST$ENUM$DISR = Case3, 0, 6438275382588823897}}
// gdb-command:print univariant
|
// gdb-check:$4 = {{-1}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print case1
// lldb-check:[...]$0 = Case1(0, 31868, 31868, 31868, 31868)
// lldb-command:print case2
// lldb-check:[...]$1 = Case2(0, 286331153, 286331153)
// lldb-command:print case3
// lldb-check:[...]$2 = Case3(0, 6438275382588823897)
// lldb-command:print univariant
// lldb-check:[...]$3 = TheOnlyCase(-1)
// NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
// substituted with something of size `xx` bits and the same alignment as an integer type of the
// same size.
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular<T16, T32, T64> {
Case1(T64, T16, T16, T16, T16),
Case2(T64, T32, T32),
Case3(T64, T64)
}
enum Univariant<T64> {
TheOnlyCase(T64)
}
fn main() {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1: Regular<u16, u32, u64> = Case1(0_u64, 31868_u16, 31868_u16, 31868_u16, 31868_u16);
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2: Regular<i16, i32, i64> = Case2(0_i64, 286331153_i32, 286331153_i32);
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3: Regular<i16, i32, i64> = Case3(0_i64, 6438275382588823897_i64);
let univariant = TheOnlyCase(-1_i64);
zzz(); // #break
}
fn zzz() { () }
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.