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
restyle_hints.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Restyle hints: an optimization to avoid unnecessarily matching selectors. #[cfg(feature = "gecko")] use crate::gecko_bindings::structs::nsRestyleHint; use crate::traversal_flags::TraversalFlags; bitflags! { /// The kind of restyle we need to do for a given element. pub struct RestyleHint: u8 { /// Do a selector match of the element. const RESTYLE_SELF = 1 << 0; /// Do a selector match of the element's descendants. const RESTYLE_DESCENDANTS = 1 << 1; /// Recascade the current element. const RECASCADE_SELF = 1 << 2; /// Recascade all descendant elements. const RECASCADE_DESCENDANTS = 1 << 3; /// Replace the style data coming from CSS transitions without updating /// any other style data. This hint is only processed in animation-only /// traversal which is prior to normal traversal. const RESTYLE_CSS_TRANSITIONS = 1 << 4; /// Replace the style data coming from CSS animations without updating /// any other style data. This hint is only processed in animation-only /// traversal which is prior to normal traversal. const RESTYLE_CSS_ANIMATIONS = 1 << 5; /// Don't re-run selector-matching on the element, only the style /// attribute has changed, and this change didn't have any other /// dependencies. const RESTYLE_STYLE_ATTRIBUTE = 1 << 6; /// Replace the style data coming from SMIL animations without updating /// any other style data. This hint is only processed in animation-only /// traversal which is prior to normal traversal. const RESTYLE_SMIL = 1 << 7; } } impl RestyleHint { /// Creates a new `RestyleHint` indicating that the current element and all /// its descendants must be fully restyled. pub fn restyle_subtree() -> Self { RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS } /// Creates a new `RestyleHint` indicating that the current element and all /// its descendants must be recascaded. pub fn recascade_subtree() -> Self { RestyleHint::RECASCADE_SELF | RestyleHint::RECASCADE_DESCENDANTS } /// Returns whether this hint invalidates the element and all its /// descendants. pub fn contains_subtree(&self) -> bool { self.contains(RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS) } /// Returns whether we need to restyle this element. pub fn has_non_animation_invalidations(&self) -> bool { self.intersects( RestyleHint::RESTYLE_SELF | RestyleHint::RECASCADE_SELF | (Self::replacements() &!Self::for_animations()), ) } /// Propagates this restyle hint to a child element. pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self { use std::mem; // In the middle of an animation only restyle, we don't need to // propagate any restyle hints, and we need to remove ourselves. if traversal_flags.for_animation_only() { self.remove_animation_hints(); return Self::empty(); } debug_assert!( !self.has_animation_hint(), "There should not be any animation restyle hints \ during normal traversal" ); // Else we should clear ourselves, and return the propagated hint. mem::replace(self, Self::empty()).propagate_for_non_animation_restyle() } /// Returns a new `CascadeHint` appropriate for children of the current /// element. fn propagate_for_non_animation_restyle(&self) -> Self { if self.contains(RestyleHint::RESTYLE_DESCENDANTS) { return Self::restyle_subtree(); } if self.contains(RestyleHint::RECASCADE_DESCENDANTS) { return Self::recascade_subtree(); } Self::empty() } /// Creates a new `RestyleHint` that indicates the element must be /// recascaded. pub fn recascade_self() -> Self { RestyleHint::RECASCADE_SELF } /// Returns a hint that contains all the replacement hints. pub fn replacements() -> Self { RestyleHint::RESTYLE_STYLE_ATTRIBUTE | Self::for_animations() } /// The replacements for the animation cascade levels. #[inline] pub fn for_animations() -> Self { RestyleHint::RESTYLE_SMIL | RestyleHint::RESTYLE_CSS_ANIMATIONS | RestyleHint::RESTYLE_CSS_TRANSITIONS } /// Returns whether the hint specifies that the currently element must be /// recascaded. pub fn has_recascade_self(&self) -> bool { self.contains(RestyleHint::RECASCADE_SELF) } /// Returns whether the hint specifies that an animation cascade level must /// be replaced. #[inline] pub fn has_animation_hint(&self) -> bool { self.intersects(Self::for_animations()) } /// Returns whether the hint specifies that an animation cascade level must /// be replaced. #[inline] pub fn has_animation_hint_or_recascade(&self) -> bool { self.intersects(Self::for_animations() | RestyleHint::RECASCADE_SELF) } /// Returns whether the hint specifies some restyle work other than an /// animation cascade level replacement. #[inline] pub fn has_non_animation_hint(&self) -> bool { !(*self &!Self::for_animations()).is_empty() } /// Returns whether the hint specifies that selector matching must be re-run /// for the element. #[inline] pub fn match_self(&self) -> bool { self.intersects(RestyleHint::RESTYLE_SELF) } /// Returns whether the hint specifies that some cascade levels must be /// replaced. #[inline] pub fn has_replacements(&self) -> bool { self.intersects(Self::replacements()) } /// Removes all of the animation-related hints. #[inline] pub fn remove_animation_hints(&mut self) { self.remove(Self::for_animations()); // While RECASCADE_SELF is not animation-specific, we only ever add and // process it during traversal. If we are here, removing animation // hints, then we are in an animation-only traversal, and we know that // any RECASCADE_SELF flag must have been set due to changes in // inherited values after restyling for animations, and thus we want to // remove it so that we don't later try to restyle the element during a // normal restyle. (We could have separate RECASCADE_SELF_NORMAL and // RECASCADE_SELF_ANIMATIONS flags to make it clear, but this isn't // currently necessary.) self.remove(RestyleHint::RECASCADE_SELF); } } impl Default for RestyleHint { fn default() -> Self { Self::empty() } } #[cfg(feature = "gecko")] impl From<nsRestyleHint> for RestyleHint { fn from(mut raw: nsRestyleHint) -> Self { let mut hint = RestyleHint::empty(); debug_assert!( raw.0 & nsRestyleHint::eRestyle_LaterSiblings.0 == 0, "Handle later siblings manually if necessary plz." ); if (raw.0 & (nsRestyleHint::eRestyle_Self.0 | nsRestyleHint::eRestyle_Subtree.0))!= 0 { raw.0 &=!nsRestyleHint::eRestyle_Self.0; hint.insert(RestyleHint::RESTYLE_SELF); } if (raw.0 & (nsRestyleHint::eRestyle_Subtree.0 | nsRestyleHint::eRestyle_SomeDescendants.0))!= 0
if (raw.0 & (nsRestyleHint::eRestyle_ForceDescendants.0 | nsRestyleHint::eRestyle_Force.0))!= 0 { raw.0 &=!nsRestyleHint::eRestyle_Force.0; hint.insert(RestyleHint::RECASCADE_SELF); } if (raw.0 & nsRestyleHint::eRestyle_ForceDescendants.0)!= 0 { raw.0 &=!nsRestyleHint::eRestyle_ForceDescendants.0; hint.insert(RestyleHint::RECASCADE_DESCENDANTS); } hint.insert(RestyleHint::from_bits_truncate(raw.0 as u8)); hint } } #[cfg(feature = "servo")] malloc_size_of_is_0!(RestyleHint); /// Asserts that all replacement hints have a matching nsRestyleHint value. #[cfg(feature = "gecko")] #[inline] pub fn assert_restyle_hints_match() { use crate::gecko_bindings::structs; macro_rules! check_restyle_hints { ( $( $a:ident => $b:path),*, ) => { if cfg!(debug_assertions) { let mut replacements = RestyleHint::replacements(); $( assert_eq!(structs::nsRestyleHint::$a.0 as usize, $b.bits() as usize, stringify!($b)); replacements.remove($b); )* assert_eq!(replacements, RestyleHint::empty(), "all RestyleHint replacement bits should have an \ assertion"); } } } check_restyle_hints! { eRestyle_CSSTransitions => RestyleHint::RESTYLE_CSS_TRANSITIONS, eRestyle_CSSAnimations => RestyleHint::RESTYLE_CSS_ANIMATIONS, eRestyle_StyleAttribute => RestyleHint::RESTYLE_STYLE_ATTRIBUTE, eRestyle_StyleAttribute_Animations => RestyleHint::RESTYLE_SMIL, } }
{ raw.0 &= !nsRestyleHint::eRestyle_Subtree.0; raw.0 &= !nsRestyleHint::eRestyle_SomeDescendants.0; hint.insert(RestyleHint::RESTYLE_DESCENDANTS); }
conditional_block
restyle_hints.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Restyle hints: an optimization to avoid unnecessarily matching selectors. #[cfg(feature = "gecko")] use crate::gecko_bindings::structs::nsRestyleHint; use crate::traversal_flags::TraversalFlags; bitflags! { /// The kind of restyle we need to do for a given element. pub struct RestyleHint: u8 { /// Do a selector match of the element. const RESTYLE_SELF = 1 << 0; /// Do a selector match of the element's descendants. const RESTYLE_DESCENDANTS = 1 << 1; /// Recascade the current element. const RECASCADE_SELF = 1 << 2; /// Recascade all descendant elements. const RECASCADE_DESCENDANTS = 1 << 3; /// Replace the style data coming from CSS transitions without updating /// any other style data. This hint is only processed in animation-only /// traversal which is prior to normal traversal. const RESTYLE_CSS_TRANSITIONS = 1 << 4; /// Replace the style data coming from CSS animations without updating /// any other style data. This hint is only processed in animation-only /// traversal which is prior to normal traversal. const RESTYLE_CSS_ANIMATIONS = 1 << 5; /// Don't re-run selector-matching on the element, only the style /// attribute has changed, and this change didn't have any other /// dependencies. const RESTYLE_STYLE_ATTRIBUTE = 1 << 6; /// Replace the style data coming from SMIL animations without updating /// any other style data. This hint is only processed in animation-only /// traversal which is prior to normal traversal. const RESTYLE_SMIL = 1 << 7; } } impl RestyleHint { /// Creates a new `RestyleHint` indicating that the current element and all /// its descendants must be fully restyled. pub fn restyle_subtree() -> Self { RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS } /// Creates a new `RestyleHint` indicating that the current element and all /// its descendants must be recascaded. pub fn recascade_subtree() -> Self { RestyleHint::RECASCADE_SELF | RestyleHint::RECASCADE_DESCENDANTS } /// Returns whether this hint invalidates the element and all its /// descendants. pub fn contains_subtree(&self) -> bool { self.contains(RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_DESCENDANTS) } /// Returns whether we need to restyle this element. pub fn
(&self) -> bool { self.intersects( RestyleHint::RESTYLE_SELF | RestyleHint::RECASCADE_SELF | (Self::replacements() &!Self::for_animations()), ) } /// Propagates this restyle hint to a child element. pub fn propagate(&mut self, traversal_flags: &TraversalFlags) -> Self { use std::mem; // In the middle of an animation only restyle, we don't need to // propagate any restyle hints, and we need to remove ourselves. if traversal_flags.for_animation_only() { self.remove_animation_hints(); return Self::empty(); } debug_assert!( !self.has_animation_hint(), "There should not be any animation restyle hints \ during normal traversal" ); // Else we should clear ourselves, and return the propagated hint. mem::replace(self, Self::empty()).propagate_for_non_animation_restyle() } /// Returns a new `CascadeHint` appropriate for children of the current /// element. fn propagate_for_non_animation_restyle(&self) -> Self { if self.contains(RestyleHint::RESTYLE_DESCENDANTS) { return Self::restyle_subtree(); } if self.contains(RestyleHint::RECASCADE_DESCENDANTS) { return Self::recascade_subtree(); } Self::empty() } /// Creates a new `RestyleHint` that indicates the element must be /// recascaded. pub fn recascade_self() -> Self { RestyleHint::RECASCADE_SELF } /// Returns a hint that contains all the replacement hints. pub fn replacements() -> Self { RestyleHint::RESTYLE_STYLE_ATTRIBUTE | Self::for_animations() } /// The replacements for the animation cascade levels. #[inline] pub fn for_animations() -> Self { RestyleHint::RESTYLE_SMIL | RestyleHint::RESTYLE_CSS_ANIMATIONS | RestyleHint::RESTYLE_CSS_TRANSITIONS } /// Returns whether the hint specifies that the currently element must be /// recascaded. pub fn has_recascade_self(&self) -> bool { self.contains(RestyleHint::RECASCADE_SELF) } /// Returns whether the hint specifies that an animation cascade level must /// be replaced. #[inline] pub fn has_animation_hint(&self) -> bool { self.intersects(Self::for_animations()) } /// Returns whether the hint specifies that an animation cascade level must /// be replaced. #[inline] pub fn has_animation_hint_or_recascade(&self) -> bool { self.intersects(Self::for_animations() | RestyleHint::RECASCADE_SELF) } /// Returns whether the hint specifies some restyle work other than an /// animation cascade level replacement. #[inline] pub fn has_non_animation_hint(&self) -> bool { !(*self &!Self::for_animations()).is_empty() } /// Returns whether the hint specifies that selector matching must be re-run /// for the element. #[inline] pub fn match_self(&self) -> bool { self.intersects(RestyleHint::RESTYLE_SELF) } /// Returns whether the hint specifies that some cascade levels must be /// replaced. #[inline] pub fn has_replacements(&self) -> bool { self.intersects(Self::replacements()) } /// Removes all of the animation-related hints. #[inline] pub fn remove_animation_hints(&mut self) { self.remove(Self::for_animations()); // While RECASCADE_SELF is not animation-specific, we only ever add and // process it during traversal. If we are here, removing animation // hints, then we are in an animation-only traversal, and we know that // any RECASCADE_SELF flag must have been set due to changes in // inherited values after restyling for animations, and thus we want to // remove it so that we don't later try to restyle the element during a // normal restyle. (We could have separate RECASCADE_SELF_NORMAL and // RECASCADE_SELF_ANIMATIONS flags to make it clear, but this isn't // currently necessary.) self.remove(RestyleHint::RECASCADE_SELF); } } impl Default for RestyleHint { fn default() -> Self { Self::empty() } } #[cfg(feature = "gecko")] impl From<nsRestyleHint> for RestyleHint { fn from(mut raw: nsRestyleHint) -> Self { let mut hint = RestyleHint::empty(); debug_assert!( raw.0 & nsRestyleHint::eRestyle_LaterSiblings.0 == 0, "Handle later siblings manually if necessary plz." ); if (raw.0 & (nsRestyleHint::eRestyle_Self.0 | nsRestyleHint::eRestyle_Subtree.0))!= 0 { raw.0 &=!nsRestyleHint::eRestyle_Self.0; hint.insert(RestyleHint::RESTYLE_SELF); } if (raw.0 & (nsRestyleHint::eRestyle_Subtree.0 | nsRestyleHint::eRestyle_SomeDescendants.0))!= 0 { raw.0 &=!nsRestyleHint::eRestyle_Subtree.0; raw.0 &=!nsRestyleHint::eRestyle_SomeDescendants.0; hint.insert(RestyleHint::RESTYLE_DESCENDANTS); } if (raw.0 & (nsRestyleHint::eRestyle_ForceDescendants.0 | nsRestyleHint::eRestyle_Force.0))!= 0 { raw.0 &=!nsRestyleHint::eRestyle_Force.0; hint.insert(RestyleHint::RECASCADE_SELF); } if (raw.0 & nsRestyleHint::eRestyle_ForceDescendants.0)!= 0 { raw.0 &=!nsRestyleHint::eRestyle_ForceDescendants.0; hint.insert(RestyleHint::RECASCADE_DESCENDANTS); } hint.insert(RestyleHint::from_bits_truncate(raw.0 as u8)); hint } } #[cfg(feature = "servo")] malloc_size_of_is_0!(RestyleHint); /// Asserts that all replacement hints have a matching nsRestyleHint value. #[cfg(feature = "gecko")] #[inline] pub fn assert_restyle_hints_match() { use crate::gecko_bindings::structs; macro_rules! check_restyle_hints { ( $( $a:ident => $b:path),*, ) => { if cfg!(debug_assertions) { let mut replacements = RestyleHint::replacements(); $( assert_eq!(structs::nsRestyleHint::$a.0 as usize, $b.bits() as usize, stringify!($b)); replacements.remove($b); )* assert_eq!(replacements, RestyleHint::empty(), "all RestyleHint replacement bits should have an \ assertion"); } } } check_restyle_hints! { eRestyle_CSSTransitions => RestyleHint::RESTYLE_CSS_TRANSITIONS, eRestyle_CSSAnimations => RestyleHint::RESTYLE_CSS_ANIMATIONS, eRestyle_StyleAttribute => RestyleHint::RESTYLE_STYLE_ATTRIBUTE, eRestyle_StyleAttribute_Animations => RestyleHint::RESTYLE_SMIL, } }
has_non_animation_invalidations
identifier_name
text.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/. */ //! Computed types for text properties. #[cfg(feature = "servo")] use properties::StyleBuilder; use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::{CSSInteger, CSSFloat}; use values::computed::{NonNegativeLength, NonNegativeNumber}; use values::computed::length::{Length, LengthOrPercentage}; use values::generics::text::InitialLetter as GenericInitialLetter; use values::generics::text::LineHeight as GenericLineHeight; use values::generics::text::Spacing; use values::specified::text::{TextOverflowSide, TextDecorationLine}; pub use values::specified::TextAlignKeyword as TextAlign; /// A computed value for the `initial-letter` property. pub type InitialLetter = GenericInitialLetter<CSSFloat, CSSInteger>; /// A computed value for the `letter-spacing` property. pub type LetterSpacing = Spacing<Length>; /// A computed value for the `word-spacing` property. pub type WordSpacing = Spacing<LengthOrPercentage>; /// A computed value for the `line-height` property. pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>; #[derive(Clone, Debug, MallocSizeOf, PartialEq)] /// text-overflow. /// When the specified value only has one side, that's the "second" /// side, and the sides are logical, so "second" means "end". The /// start side is Clip in that case. /// /// When the specified value has two sides, those are our "first" /// and "second" sides, and they are physical sides ("left" and /// "right"). pub struct TextOverflow { /// First side pub first: TextOverflowSide, /// Second side pub second: TextOverflowSide, /// True if the specified value only has one side. pub sides_are_logical: bool, } impl TextOverflow { /// Returns the initial `text-overflow` value pub fn get_initial_value() -> TextOverflow { TextOverflow { first: TextOverflowSide::Clip, second: TextOverflowSide::Clip, sides_are_logical: true, } } } impl ToCss for TextOverflow { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { if self.sides_are_logical { debug_assert_eq!(self.first, TextOverflowSide::Clip); self.second.to_css(dest)?; } else { self.first.to_css(dest)?; dest.write_str(" ")?; self.second.to_css(dest)?; } Ok(()) } } impl ToCss for TextDecorationLine { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, {
let mut has_any = false; macro_rules! write_value { ($line:path => $css:expr) => { if self.contains($line) { if has_any { dest.write_str(" ")?; } dest.write_str($css)?; has_any = true; } } } write_value!(TextDecorationLine::UNDERLINE => "underline"); write_value!(TextDecorationLine::OVERLINE => "overline"); write_value!(TextDecorationLine::LINE_THROUGH => "line-through"); write_value!(TextDecorationLine::BLINK => "blink"); if!has_any { dest.write_str("none")?; } Ok(()) } } /// A struct that represents the _used_ value of the text-decoration property. /// /// FIXME(emilio): This is done at style resolution time, though probably should /// be done at layout time, otherwise we need to account for display: contents /// and similar stuff when we implement it. /// /// FIXME(emilio): Also, should be just a bitfield instead of three bytes. #[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)] pub struct TextDecorationsInEffect { /// Whether an underline is in effect. pub underline: bool, /// Whether an overline decoration is in effect. pub overline: bool, /// Whether a line-through style is in effect. pub line_through: bool, } impl TextDecorationsInEffect { /// Computes the text-decorations in effect for a given style. #[cfg(feature = "servo")] pub fn from_style(style: &StyleBuilder) -> Self { use values::computed::Display; // Start with no declarations if this is an atomic inline-level box; // otherwise, start with the declarations in effect and add in the text // decorations that this block specifies. let mut result = match style.get_box().clone_display() { Display::InlineBlock | Display::InlineTable => Self::default(), _ => style.get_parent_inheritedtext().text_decorations_in_effect.clone(), }; let text_style = style.get_text(); result.underline |= text_style.has_underline(); result.overline |= text_style.has_overline(); result.line_through |= text_style.has_line_through(); result } }
random_line_split
text.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/. */ //! Computed types for text properties. #[cfg(feature = "servo")] use properties::StyleBuilder; use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::{CSSInteger, CSSFloat}; use values::computed::{NonNegativeLength, NonNegativeNumber}; use values::computed::length::{Length, LengthOrPercentage}; use values::generics::text::InitialLetter as GenericInitialLetter; use values::generics::text::LineHeight as GenericLineHeight; use values::generics::text::Spacing; use values::specified::text::{TextOverflowSide, TextDecorationLine}; pub use values::specified::TextAlignKeyword as TextAlign; /// A computed value for the `initial-letter` property. pub type InitialLetter = GenericInitialLetter<CSSFloat, CSSInteger>; /// A computed value for the `letter-spacing` property. pub type LetterSpacing = Spacing<Length>; /// A computed value for the `word-spacing` property. pub type WordSpacing = Spacing<LengthOrPercentage>; /// A computed value for the `line-height` property. pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>; #[derive(Clone, Debug, MallocSizeOf, PartialEq)] /// text-overflow. /// When the specified value only has one side, that's the "second" /// side, and the sides are logical, so "second" means "end". The /// start side is Clip in that case. /// /// When the specified value has two sides, those are our "first" /// and "second" sides, and they are physical sides ("left" and /// "right"). pub struct TextOverflow { /// First side pub first: TextOverflowSide, /// Second side pub second: TextOverflowSide, /// True if the specified value only has one side. pub sides_are_logical: bool, } impl TextOverflow { /// Returns the initial `text-overflow` value pub fn get_initial_value() -> TextOverflow { TextOverflow { first: TextOverflowSide::Clip, second: TextOverflowSide::Clip, sides_are_logical: true, } } } impl ToCss for TextOverflow { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { if self.sides_are_logical { debug_assert_eq!(self.first, TextOverflowSide::Clip); self.second.to_css(dest)?; } else { self.first.to_css(dest)?; dest.write_str(" ")?; self.second.to_css(dest)?; } Ok(()) } } impl ToCss for TextDecorationLine { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let mut has_any = false; macro_rules! write_value { ($line:path => $css:expr) => { if self.contains($line) { if has_any { dest.write_str(" ")?; } dest.write_str($css)?; has_any = true; } } } write_value!(TextDecorationLine::UNDERLINE => "underline"); write_value!(TextDecorationLine::OVERLINE => "overline"); write_value!(TextDecorationLine::LINE_THROUGH => "line-through"); write_value!(TextDecorationLine::BLINK => "blink"); if!has_any { dest.write_str("none")?; } Ok(()) } } /// A struct that represents the _used_ value of the text-decoration property. /// /// FIXME(emilio): This is done at style resolution time, though probably should /// be done at layout time, otherwise we need to account for display: contents /// and similar stuff when we implement it. /// /// FIXME(emilio): Also, should be just a bitfield instead of three bytes. #[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)] pub struct TextDecorationsInEffect { /// Whether an underline is in effect. pub underline: bool, /// Whether an overline decoration is in effect. pub overline: bool, /// Whether a line-through style is in effect. pub line_through: bool, } impl TextDecorationsInEffect { /// Computes the text-decorations in effect for a given style. #[cfg(feature = "servo")] pub fn
(style: &StyleBuilder) -> Self { use values::computed::Display; // Start with no declarations if this is an atomic inline-level box; // otherwise, start with the declarations in effect and add in the text // decorations that this block specifies. let mut result = match style.get_box().clone_display() { Display::InlineBlock | Display::InlineTable => Self::default(), _ => style.get_parent_inheritedtext().text_decorations_in_effect.clone(), }; let text_style = style.get_text(); result.underline |= text_style.has_underline(); result.overline |= text_style.has_overline(); result.line_through |= text_style.has_line_through(); result } }
from_style
identifier_name
text.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/. */ //! Computed types for text properties. #[cfg(feature = "servo")] use properties::StyleBuilder; use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::{CSSInteger, CSSFloat}; use values::computed::{NonNegativeLength, NonNegativeNumber}; use values::computed::length::{Length, LengthOrPercentage}; use values::generics::text::InitialLetter as GenericInitialLetter; use values::generics::text::LineHeight as GenericLineHeight; use values::generics::text::Spacing; use values::specified::text::{TextOverflowSide, TextDecorationLine}; pub use values::specified::TextAlignKeyword as TextAlign; /// A computed value for the `initial-letter` property. pub type InitialLetter = GenericInitialLetter<CSSFloat, CSSInteger>; /// A computed value for the `letter-spacing` property. pub type LetterSpacing = Spacing<Length>; /// A computed value for the `word-spacing` property. pub type WordSpacing = Spacing<LengthOrPercentage>; /// A computed value for the `line-height` property. pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>; #[derive(Clone, Debug, MallocSizeOf, PartialEq)] /// text-overflow. /// When the specified value only has one side, that's the "second" /// side, and the sides are logical, so "second" means "end". The /// start side is Clip in that case. /// /// When the specified value has two sides, those are our "first" /// and "second" sides, and they are physical sides ("left" and /// "right"). pub struct TextOverflow { /// First side pub first: TextOverflowSide, /// Second side pub second: TextOverflowSide, /// True if the specified value only has one side. pub sides_are_logical: bool, } impl TextOverflow { /// Returns the initial `text-overflow` value pub fn get_initial_value() -> TextOverflow { TextOverflow { first: TextOverflowSide::Clip, second: TextOverflowSide::Clip, sides_are_logical: true, } } } impl ToCss for TextOverflow { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write,
} impl ToCss for TextDecorationLine { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let mut has_any = false; macro_rules! write_value { ($line:path => $css:expr) => { if self.contains($line) { if has_any { dest.write_str(" ")?; } dest.write_str($css)?; has_any = true; } } } write_value!(TextDecorationLine::UNDERLINE => "underline"); write_value!(TextDecorationLine::OVERLINE => "overline"); write_value!(TextDecorationLine::LINE_THROUGH => "line-through"); write_value!(TextDecorationLine::BLINK => "blink"); if!has_any { dest.write_str("none")?; } Ok(()) } } /// A struct that represents the _used_ value of the text-decoration property. /// /// FIXME(emilio): This is done at style resolution time, though probably should /// be done at layout time, otherwise we need to account for display: contents /// and similar stuff when we implement it. /// /// FIXME(emilio): Also, should be just a bitfield instead of three bytes. #[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)] pub struct TextDecorationsInEffect { /// Whether an underline is in effect. pub underline: bool, /// Whether an overline decoration is in effect. pub overline: bool, /// Whether a line-through style is in effect. pub line_through: bool, } impl TextDecorationsInEffect { /// Computes the text-decorations in effect for a given style. #[cfg(feature = "servo")] pub fn from_style(style: &StyleBuilder) -> Self { use values::computed::Display; // Start with no declarations if this is an atomic inline-level box; // otherwise, start with the declarations in effect and add in the text // decorations that this block specifies. let mut result = match style.get_box().clone_display() { Display::InlineBlock | Display::InlineTable => Self::default(), _ => style.get_parent_inheritedtext().text_decorations_in_effect.clone(), }; let text_style = style.get_text(); result.underline |= text_style.has_underline(); result.overline |= text_style.has_overline(); result.line_through |= text_style.has_line_through(); result } }
{ if self.sides_are_logical { debug_assert_eq!(self.first, TextOverflowSide::Clip); self.second.to_css(dest)?; } else { self.first.to_css(dest)?; dest.write_str(" ")?; self.second.to_css(dest)?; } Ok(()) }
identifier_body
text.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/. */ //! Computed types for text properties. #[cfg(feature = "servo")] use properties::StyleBuilder; use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::{CSSInteger, CSSFloat}; use values::computed::{NonNegativeLength, NonNegativeNumber}; use values::computed::length::{Length, LengthOrPercentage}; use values::generics::text::InitialLetter as GenericInitialLetter; use values::generics::text::LineHeight as GenericLineHeight; use values::generics::text::Spacing; use values::specified::text::{TextOverflowSide, TextDecorationLine}; pub use values::specified::TextAlignKeyword as TextAlign; /// A computed value for the `initial-letter` property. pub type InitialLetter = GenericInitialLetter<CSSFloat, CSSInteger>; /// A computed value for the `letter-spacing` property. pub type LetterSpacing = Spacing<Length>; /// A computed value for the `word-spacing` property. pub type WordSpacing = Spacing<LengthOrPercentage>; /// A computed value for the `line-height` property. pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLength>; #[derive(Clone, Debug, MallocSizeOf, PartialEq)] /// text-overflow. /// When the specified value only has one side, that's the "second" /// side, and the sides are logical, so "second" means "end". The /// start side is Clip in that case. /// /// When the specified value has two sides, those are our "first" /// and "second" sides, and they are physical sides ("left" and /// "right"). pub struct TextOverflow { /// First side pub first: TextOverflowSide, /// Second side pub second: TextOverflowSide, /// True if the specified value only has one side. pub sides_are_logical: bool, } impl TextOverflow { /// Returns the initial `text-overflow` value pub fn get_initial_value() -> TextOverflow { TextOverflow { first: TextOverflowSide::Clip, second: TextOverflowSide::Clip, sides_are_logical: true, } } } impl ToCss for TextOverflow { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { if self.sides_are_logical { debug_assert_eq!(self.first, TextOverflowSide::Clip); self.second.to_css(dest)?; } else { self.first.to_css(dest)?; dest.write_str(" ")?; self.second.to_css(dest)?; } Ok(()) } } impl ToCss for TextDecorationLine { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let mut has_any = false; macro_rules! write_value { ($line:path => $css:expr) => { if self.contains($line) { if has_any { dest.write_str(" ")?; } dest.write_str($css)?; has_any = true; } } } write_value!(TextDecorationLine::UNDERLINE => "underline"); write_value!(TextDecorationLine::OVERLINE => "overline"); write_value!(TextDecorationLine::LINE_THROUGH => "line-through"); write_value!(TextDecorationLine::BLINK => "blink"); if!has_any
Ok(()) } } /// A struct that represents the _used_ value of the text-decoration property. /// /// FIXME(emilio): This is done at style resolution time, though probably should /// be done at layout time, otherwise we need to account for display: contents /// and similar stuff when we implement it. /// /// FIXME(emilio): Also, should be just a bitfield instead of three bytes. #[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)] pub struct TextDecorationsInEffect { /// Whether an underline is in effect. pub underline: bool, /// Whether an overline decoration is in effect. pub overline: bool, /// Whether a line-through style is in effect. pub line_through: bool, } impl TextDecorationsInEffect { /// Computes the text-decorations in effect for a given style. #[cfg(feature = "servo")] pub fn from_style(style: &StyleBuilder) -> Self { use values::computed::Display; // Start with no declarations if this is an atomic inline-level box; // otherwise, start with the declarations in effect and add in the text // decorations that this block specifies. let mut result = match style.get_box().clone_display() { Display::InlineBlock | Display::InlineTable => Self::default(), _ => style.get_parent_inheritedtext().text_decorations_in_effect.clone(), }; let text_style = style.get_text(); result.underline |= text_style.has_underline(); result.overline |= text_style.has_overline(); result.line_through |= text_style.has_line_through(); result } }
{ dest.write_str("none")?; }
conditional_block
pmf.rs
use std::slice; use itertools::Itertools; use bio::stats::LogProb; #[derive(Clone, Debug)] pub struct Entry<T: Clone> { pub value: T, pub prob: LogProb, } #[derive(Clone, Debug)] pub struct PMF<T: Clone> { inner: Vec<Entry<T>>, } impl<T: Clone + Sized> PMF<T> { /// Create a new PMF from sorted vector. pub fn new(inner: Vec<Entry<T>>) -> Self { PMF { inner } } pub fn iter(&self) -> slice::Iter<Entry<T>> { self.inner.iter() } pub fn cdf(&self) -> Vec<LogProb> { LogProb::ln_cumsum_exp(self.inner.iter().map(|e| e.prob)).collect_vec() } /// Return maximum a posteriori probability estimate (MAP). pub fn map(&self) -> &T { let mut max = self.iter().next().unwrap(); for e in self.iter() { if e.prob >= max.prob { max = e; } } &max.value } } impl<T: Clone + Sized + Copy> PMF<T> { /// Return the 95% credible interval. pub fn credible_interval(&self) -> (T, T)
} impl PMF<f32> { pub fn scale(&mut self, scale: f32) { for e in &mut self.inner { e.value *= scale; } } }
{ let cdf = self.cdf(); let lower = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.025f64.ln())).unwrap()) .unwrap_or_else(|i| i); let upper = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.975f64.ln())).unwrap()) .unwrap_or_else(|i| i); (self.inner[lower].value, self.inner[upper].value) }
identifier_body
pmf.rs
use std::slice; use itertools::Itertools; use bio::stats::LogProb; #[derive(Clone, Debug)] pub struct Entry<T: Clone> { pub value: T, pub prob: LogProb, } #[derive(Clone, Debug)] pub struct PMF<T: Clone> { inner: Vec<Entry<T>>, } impl<T: Clone + Sized> PMF<T> { /// Create a new PMF from sorted vector. pub fn new(inner: Vec<Entry<T>>) -> Self { PMF { inner } } pub fn iter(&self) -> slice::Iter<Entry<T>> { self.inner.iter() } pub fn cdf(&self) -> Vec<LogProb> {
} /// Return maximum a posteriori probability estimate (MAP). pub fn map(&self) -> &T { let mut max = self.iter().next().unwrap(); for e in self.iter() { if e.prob >= max.prob { max = e; } } &max.value } } impl<T: Clone + Sized + Copy> PMF<T> { /// Return the 95% credible interval. pub fn credible_interval(&self) -> (T, T) { let cdf = self.cdf(); let lower = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.025f64.ln())).unwrap()) .unwrap_or_else(|i| i); let upper = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.975f64.ln())).unwrap()) .unwrap_or_else(|i| i); (self.inner[lower].value, self.inner[upper].value) } } impl PMF<f32> { pub fn scale(&mut self, scale: f32) { for e in &mut self.inner { e.value *= scale; } } }
LogProb::ln_cumsum_exp(self.inner.iter().map(|e| e.prob)).collect_vec()
random_line_split
pmf.rs
use std::slice; use itertools::Itertools; use bio::stats::LogProb; #[derive(Clone, Debug)] pub struct Entry<T: Clone> { pub value: T, pub prob: LogProb, } #[derive(Clone, Debug)] pub struct PMF<T: Clone> { inner: Vec<Entry<T>>, } impl<T: Clone + Sized> PMF<T> { /// Create a new PMF from sorted vector. pub fn new(inner: Vec<Entry<T>>) -> Self { PMF { inner } } pub fn
(&self) -> slice::Iter<Entry<T>> { self.inner.iter() } pub fn cdf(&self) -> Vec<LogProb> { LogProb::ln_cumsum_exp(self.inner.iter().map(|e| e.prob)).collect_vec() } /// Return maximum a posteriori probability estimate (MAP). pub fn map(&self) -> &T { let mut max = self.iter().next().unwrap(); for e in self.iter() { if e.prob >= max.prob { max = e; } } &max.value } } impl<T: Clone + Sized + Copy> PMF<T> { /// Return the 95% credible interval. pub fn credible_interval(&self) -> (T, T) { let cdf = self.cdf(); let lower = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.025f64.ln())).unwrap()) .unwrap_or_else(|i| i); let upper = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.975f64.ln())).unwrap()) .unwrap_or_else(|i| i); (self.inner[lower].value, self.inner[upper].value) } } impl PMF<f32> { pub fn scale(&mut self, scale: f32) { for e in &mut self.inner { e.value *= scale; } } }
iter
identifier_name
pmf.rs
use std::slice; use itertools::Itertools; use bio::stats::LogProb; #[derive(Clone, Debug)] pub struct Entry<T: Clone> { pub value: T, pub prob: LogProb, } #[derive(Clone, Debug)] pub struct PMF<T: Clone> { inner: Vec<Entry<T>>, } impl<T: Clone + Sized> PMF<T> { /// Create a new PMF from sorted vector. pub fn new(inner: Vec<Entry<T>>) -> Self { PMF { inner } } pub fn iter(&self) -> slice::Iter<Entry<T>> { self.inner.iter() } pub fn cdf(&self) -> Vec<LogProb> { LogProb::ln_cumsum_exp(self.inner.iter().map(|e| e.prob)).collect_vec() } /// Return maximum a posteriori probability estimate (MAP). pub fn map(&self) -> &T { let mut max = self.iter().next().unwrap(); for e in self.iter() { if e.prob >= max.prob
} &max.value } } impl<T: Clone + Sized + Copy> PMF<T> { /// Return the 95% credible interval. pub fn credible_interval(&self) -> (T, T) { let cdf = self.cdf(); let lower = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.025f64.ln())).unwrap()) .unwrap_or_else(|i| i); let upper = cdf .binary_search_by(|p| p.partial_cmp(&LogProb(0.975f64.ln())).unwrap()) .unwrap_or_else(|i| i); (self.inner[lower].value, self.inner[upper].value) } } impl PMF<f32> { pub fn scale(&mut self, scale: f32) { for e in &mut self.inner { e.value *= scale; } } }
{ max = e; }
conditional_block
lib.rs
#![feature(test)] #![feature(plugin)] #![feature(asm)] #![feature(naked_functions)] #![plugin(dynasm)] #![allow(unused_features)] #![allow(unknown_lints)] #![allow(new_without_default)] #![allow(match_same_arms)] #[cfg(target_arch = "x86_64")] extern crate dynasmrt; #[macro_use] extern crate bitflags; #[macro_use] extern crate quick_error; #[macro_use] extern crate nom; pub extern crate sdl2; extern crate blip_buf; extern crate memmap; extern crate fnv; #[cfg(feature = "vectorize")] extern crate simd; pub mod cart; pub mod memory; pub mod mappers; pub mod ppu; pub mod apu; pub mod io; pub mod cpu; pub mod screen; pub mod audio; mod util; #[cfg(test)] mod tests; use apu::APU; use cart::Cart; use cpu::CPU; use io::IO; use ppu::PPU; use std::cell::RefCell; use std::cell::UnsafeCell; use std::rc::Rc; #[derive(Debug, Clone)] pub struct Settings { pub jit: bool, pub graphics_enabled: bool, pub sound_enabled: bool, // The following will only be used if compiled with the debug_features feature pub trace_cpu: bool, pub disassemble_functions: bool, } impl Default for Settings { fn default() -> Settings { Settings { jit: false, graphics_enabled: true, sound_enabled: true, trace_cpu: false, disassemble_functions: false, } } } pub struct EmulatorBuilder { cart: Cart, settings: Settings, pub screen: Box<screen::Screen>, pub audio_out: Box<audio::AudioOut>, pub io: Box<IO>, } impl EmulatorBuilder { pub fn new(cart: Cart, settings: Settings) -> EmulatorBuilder { EmulatorBuilder { cart: cart, settings: settings, screen: Box::new(screen::DummyScreen::default()), audio_out: Box::new(audio::DummyAudioOut), io: Box::new(io::DummyIO::Dummy), } } pub fn new_sdl( cart: Cart, settings: Settings, sdl: &sdl2::Sdl, event_pump: &Rc<RefCell<sdl2::EventPump>>, ) -> EmulatorBuilder { let sound_enabled = settings.sound_enabled; let mut builder = EmulatorBuilder::new(cart, settings); builder.screen = Box::new(screen::sdl::SDLScreen::new(sdl)); if sound_enabled { builder.audio_out = Box::new(audio::sdl::SDLAudioOut::new(sdl)); } builder.io = Box::new(io::sdl::SdlIO::new(event_pump.clone())); builder } pub fn build(self) -> Emulator { let settings = Rc::new(self.settings); let dispatcher = cpu::dispatcher::Dispatcher::new(); let cart: Rc<UnsafeCell<Cart>> = Rc::new(UnsafeCell::new(self.cart)); let ppu = PPU::new(settings.clone(), cart.clone(), self.screen); let apu = APU::new(settings.clone(), self.audio_out); let mut cpu = CPU::new(settings, ppu, apu, self.io, cart, dispatcher); cpu.init(); Emulator { cpu: cpu } } } pub struct Emulator { cpu: CPU, } impl Emulator { pub fn run_frame(&mut self) { self.cpu.run_frame(); } pub fn halted(&self) -> bool { self.cpu.halted() } #[cfg(feature = "debug_features")] pub fn mouse_pick(&self, px_x: i32, px_y: i32) { self.cpu.ppu.mouse_pick(px_x, px_y); } pub fn rendering_enabled(&self) -> bool
}
{ self.cpu.ppu.rendering_enabled() }
identifier_body
lib.rs
#![feature(test)] #![feature(plugin)] #![feature(asm)] #![feature(naked_functions)] #![plugin(dynasm)] #![allow(unused_features)] #![allow(unknown_lints)] #![allow(new_without_default)] #![allow(match_same_arms)] #[cfg(target_arch = "x86_64")] extern crate dynasmrt; #[macro_use] extern crate bitflags; #[macro_use] extern crate quick_error; #[macro_use] extern crate nom; pub extern crate sdl2; extern crate blip_buf; extern crate memmap; extern crate fnv; #[cfg(feature = "vectorize")] extern crate simd; pub mod cart; pub mod memory; pub mod mappers; pub mod ppu; pub mod apu; pub mod io; pub mod cpu; pub mod screen; pub mod audio; mod util; #[cfg(test)] mod tests; use apu::APU; use cart::Cart; use cpu::CPU; use io::IO; use ppu::PPU; use std::cell::RefCell; use std::cell::UnsafeCell; use std::rc::Rc; #[derive(Debug, Clone)] pub struct Settings { pub jit: bool, pub graphics_enabled: bool, pub sound_enabled: bool, // The following will only be used if compiled with the debug_features feature pub trace_cpu: bool, pub disassemble_functions: bool, } impl Default for Settings { fn default() -> Settings { Settings { jit: false, graphics_enabled: true, sound_enabled: true,
} } } pub struct EmulatorBuilder { cart: Cart, settings: Settings, pub screen: Box<screen::Screen>, pub audio_out: Box<audio::AudioOut>, pub io: Box<IO>, } impl EmulatorBuilder { pub fn new(cart: Cart, settings: Settings) -> EmulatorBuilder { EmulatorBuilder { cart: cart, settings: settings, screen: Box::new(screen::DummyScreen::default()), audio_out: Box::new(audio::DummyAudioOut), io: Box::new(io::DummyIO::Dummy), } } pub fn new_sdl( cart: Cart, settings: Settings, sdl: &sdl2::Sdl, event_pump: &Rc<RefCell<sdl2::EventPump>>, ) -> EmulatorBuilder { let sound_enabled = settings.sound_enabled; let mut builder = EmulatorBuilder::new(cart, settings); builder.screen = Box::new(screen::sdl::SDLScreen::new(sdl)); if sound_enabled { builder.audio_out = Box::new(audio::sdl::SDLAudioOut::new(sdl)); } builder.io = Box::new(io::sdl::SdlIO::new(event_pump.clone())); builder } pub fn build(self) -> Emulator { let settings = Rc::new(self.settings); let dispatcher = cpu::dispatcher::Dispatcher::new(); let cart: Rc<UnsafeCell<Cart>> = Rc::new(UnsafeCell::new(self.cart)); let ppu = PPU::new(settings.clone(), cart.clone(), self.screen); let apu = APU::new(settings.clone(), self.audio_out); let mut cpu = CPU::new(settings, ppu, apu, self.io, cart, dispatcher); cpu.init(); Emulator { cpu: cpu } } } pub struct Emulator { cpu: CPU, } impl Emulator { pub fn run_frame(&mut self) { self.cpu.run_frame(); } pub fn halted(&self) -> bool { self.cpu.halted() } #[cfg(feature = "debug_features")] pub fn mouse_pick(&self, px_x: i32, px_y: i32) { self.cpu.ppu.mouse_pick(px_x, px_y); } pub fn rendering_enabled(&self) -> bool { self.cpu.ppu.rendering_enabled() } }
trace_cpu: false, disassemble_functions: false,
random_line_split
lib.rs
#![feature(test)] #![feature(plugin)] #![feature(asm)] #![feature(naked_functions)] #![plugin(dynasm)] #![allow(unused_features)] #![allow(unknown_lints)] #![allow(new_without_default)] #![allow(match_same_arms)] #[cfg(target_arch = "x86_64")] extern crate dynasmrt; #[macro_use] extern crate bitflags; #[macro_use] extern crate quick_error; #[macro_use] extern crate nom; pub extern crate sdl2; extern crate blip_buf; extern crate memmap; extern crate fnv; #[cfg(feature = "vectorize")] extern crate simd; pub mod cart; pub mod memory; pub mod mappers; pub mod ppu; pub mod apu; pub mod io; pub mod cpu; pub mod screen; pub mod audio; mod util; #[cfg(test)] mod tests; use apu::APU; use cart::Cart; use cpu::CPU; use io::IO; use ppu::PPU; use std::cell::RefCell; use std::cell::UnsafeCell; use std::rc::Rc; #[derive(Debug, Clone)] pub struct Settings { pub jit: bool, pub graphics_enabled: bool, pub sound_enabled: bool, // The following will only be used if compiled with the debug_features feature pub trace_cpu: bool, pub disassemble_functions: bool, } impl Default for Settings { fn default() -> Settings { Settings { jit: false, graphics_enabled: true, sound_enabled: true, trace_cpu: false, disassemble_functions: false, } } } pub struct EmulatorBuilder { cart: Cart, settings: Settings, pub screen: Box<screen::Screen>, pub audio_out: Box<audio::AudioOut>, pub io: Box<IO>, } impl EmulatorBuilder { pub fn new(cart: Cart, settings: Settings) -> EmulatorBuilder { EmulatorBuilder { cart: cart, settings: settings, screen: Box::new(screen::DummyScreen::default()), audio_out: Box::new(audio::DummyAudioOut), io: Box::new(io::DummyIO::Dummy), } } pub fn new_sdl( cart: Cart, settings: Settings, sdl: &sdl2::Sdl, event_pump: &Rc<RefCell<sdl2::EventPump>>, ) -> EmulatorBuilder { let sound_enabled = settings.sound_enabled; let mut builder = EmulatorBuilder::new(cart, settings); builder.screen = Box::new(screen::sdl::SDLScreen::new(sdl)); if sound_enabled
builder.io = Box::new(io::sdl::SdlIO::new(event_pump.clone())); builder } pub fn build(self) -> Emulator { let settings = Rc::new(self.settings); let dispatcher = cpu::dispatcher::Dispatcher::new(); let cart: Rc<UnsafeCell<Cart>> = Rc::new(UnsafeCell::new(self.cart)); let ppu = PPU::new(settings.clone(), cart.clone(), self.screen); let apu = APU::new(settings.clone(), self.audio_out); let mut cpu = CPU::new(settings, ppu, apu, self.io, cart, dispatcher); cpu.init(); Emulator { cpu: cpu } } } pub struct Emulator { cpu: CPU, } impl Emulator { pub fn run_frame(&mut self) { self.cpu.run_frame(); } pub fn halted(&self) -> bool { self.cpu.halted() } #[cfg(feature = "debug_features")] pub fn mouse_pick(&self, px_x: i32, px_y: i32) { self.cpu.ppu.mouse_pick(px_x, px_y); } pub fn rendering_enabled(&self) -> bool { self.cpu.ppu.rendering_enabled() } }
{ builder.audio_out = Box::new(audio::sdl::SDLAudioOut::new(sdl)); }
conditional_block
lib.rs
#![feature(test)] #![feature(plugin)] #![feature(asm)] #![feature(naked_functions)] #![plugin(dynasm)] #![allow(unused_features)] #![allow(unknown_lints)] #![allow(new_without_default)] #![allow(match_same_arms)] #[cfg(target_arch = "x86_64")] extern crate dynasmrt; #[macro_use] extern crate bitflags; #[macro_use] extern crate quick_error; #[macro_use] extern crate nom; pub extern crate sdl2; extern crate blip_buf; extern crate memmap; extern crate fnv; #[cfg(feature = "vectorize")] extern crate simd; pub mod cart; pub mod memory; pub mod mappers; pub mod ppu; pub mod apu; pub mod io; pub mod cpu; pub mod screen; pub mod audio; mod util; #[cfg(test)] mod tests; use apu::APU; use cart::Cart; use cpu::CPU; use io::IO; use ppu::PPU; use std::cell::RefCell; use std::cell::UnsafeCell; use std::rc::Rc; #[derive(Debug, Clone)] pub struct Settings { pub jit: bool, pub graphics_enabled: bool, pub sound_enabled: bool, // The following will only be used if compiled with the debug_features feature pub trace_cpu: bool, pub disassemble_functions: bool, } impl Default for Settings { fn default() -> Settings { Settings { jit: false, graphics_enabled: true, sound_enabled: true, trace_cpu: false, disassemble_functions: false, } } } pub struct EmulatorBuilder { cart: Cart, settings: Settings, pub screen: Box<screen::Screen>, pub audio_out: Box<audio::AudioOut>, pub io: Box<IO>, } impl EmulatorBuilder { pub fn new(cart: Cart, settings: Settings) -> EmulatorBuilder { EmulatorBuilder { cart: cart, settings: settings, screen: Box::new(screen::DummyScreen::default()), audio_out: Box::new(audio::DummyAudioOut), io: Box::new(io::DummyIO::Dummy), } } pub fn new_sdl( cart: Cart, settings: Settings, sdl: &sdl2::Sdl, event_pump: &Rc<RefCell<sdl2::EventPump>>, ) -> EmulatorBuilder { let sound_enabled = settings.sound_enabled; let mut builder = EmulatorBuilder::new(cart, settings); builder.screen = Box::new(screen::sdl::SDLScreen::new(sdl)); if sound_enabled { builder.audio_out = Box::new(audio::sdl::SDLAudioOut::new(sdl)); } builder.io = Box::new(io::sdl::SdlIO::new(event_pump.clone())); builder } pub fn build(self) -> Emulator { let settings = Rc::new(self.settings); let dispatcher = cpu::dispatcher::Dispatcher::new(); let cart: Rc<UnsafeCell<Cart>> = Rc::new(UnsafeCell::new(self.cart)); let ppu = PPU::new(settings.clone(), cart.clone(), self.screen); let apu = APU::new(settings.clone(), self.audio_out); let mut cpu = CPU::new(settings, ppu, apu, self.io, cart, dispatcher); cpu.init(); Emulator { cpu: cpu } } } pub struct Emulator { cpu: CPU, } impl Emulator { pub fn
(&mut self) { self.cpu.run_frame(); } pub fn halted(&self) -> bool { self.cpu.halted() } #[cfg(feature = "debug_features")] pub fn mouse_pick(&self, px_x: i32, px_y: i32) { self.cpu.ppu.mouse_pick(px_x, px_y); } pub fn rendering_enabled(&self) -> bool { self.cpu.ppu.rendering_enabled() } }
run_frame
identifier_name
lib.rs
//! [Experimental] Generic programming with SIMD #![cfg_attr(test, feature(test))] #![cfg_attr(test, plugin(quickcheck_macros))] #![deny(missing_docs)] #![deny(warnings)] #![feature(core)] #![feature(plugin)] #![feature(simd)] #[cfg(test)] extern crate test as stdtest; #[cfg(test)] extern crate approx; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use traits::Simd; #[cfg(test)] mod test; #[cfg(test)] mod bench; mod f32; mod f64; pub mod traits; #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f32x4(pub f32, pub f32, pub f32, pub f32); #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f64x2(pub f64, pub f64); /// Sum the elements of a slice using SIMD ops /// /// # Benchmarks /// /// Size: 1 million elements /// /// ``` ignore /// test bench::f32::plain::sum... bench: 962914 ns/iter (+/- 64354) /// test bench::f32::simd::sum ... bench: 242686 ns/iter (+/- 11847) /// test bench::f64::plain::sum... bench: 995390 ns/iter (+/- 27834) /// test bench::f64::simd::sum ... bench: 504943 ns/iter (+/- 22928) /// ``` pub fn sum<T>(slice: &[T]) -> T where T: Simd, { use std::ops::Add; use traits::Vector; let (head, body, tail) = T::Vector::cast(slice); let sum = body.iter().map(|&x| x).fold(T::Vector::zeroed(), Add::add).sum(); let sum = head.iter().map(|&x| x).fold(sum, Add::add); tail.iter().map(|&x| x).fold(sum, Add::add) } /// "Casts" a `&[A]` into an aligned `&[B]`, the elements (both in the front and in the back) that /// don't fit in the aligned slice, will be returned as slices. unsafe fn cast<'a, A, B>(slice: &'a [A]) -> (&'a [A], &'a [B], &'a [A]) { use std::raw::Repr; use std::{raw, mem}; /// Rounds down `n` to the nearest multiple of `k` fn round_down(n: usize, k: usize) -> usize
/// Rounds up `n` to the nearest multiple of `k` fn round_up(n: usize, k: usize) -> usize { let r = n % k; if r == 0 { n } else { n + k - r } } let align_of_b = mem::align_of::<B>(); let size_of_a = mem::size_of::<A>(); let size_of_b = mem::size_of::<B>(); let raw::Slice { data: start, len } = slice.repr(); let end = start.offset(len as isize); let (head_start, tail_end) = (start as usize, end as usize); let body_start = round_up(head_start, align_of_b); let body_end = round_down(tail_end, align_of_b); if body_start >= body_end { (slice, &[], &[]) } else { let head_end = body_start; let head_len = (head_end - head_start) / size_of_a; let body_len = (body_end - body_start) / size_of_b; let tail_start = body_end; let tail_len = (tail_end - tail_start) / size_of_a; let head = mem::transmute(raw::Slice { data: head_start as *const A, len: head_len }); let body = mem::transmute(raw::Slice { data: body_start as *const B, len: body_len }); let tail = mem::transmute(raw::Slice { data: tail_start as *const A, len: tail_len }); (head, body, tail) } }
{ n - n % k }
identifier_body
lib.rs
//! [Experimental] Generic programming with SIMD #![cfg_attr(test, feature(test))] #![cfg_attr(test, plugin(quickcheck_macros))] #![deny(missing_docs)] #![deny(warnings)] #![feature(core)] #![feature(plugin)] #![feature(simd)] #[cfg(test)] extern crate test as stdtest; #[cfg(test)] extern crate approx; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use traits::Simd; #[cfg(test)] mod test; #[cfg(test)] mod bench; mod f32; mod f64;
pub struct f32x4(pub f32, pub f32, pub f32, pub f32); #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f64x2(pub f64, pub f64); /// Sum the elements of a slice using SIMD ops /// /// # Benchmarks /// /// Size: 1 million elements /// /// ``` ignore /// test bench::f32::plain::sum... bench: 962914 ns/iter (+/- 64354) /// test bench::f32::simd::sum ... bench: 242686 ns/iter (+/- 11847) /// test bench::f64::plain::sum... bench: 995390 ns/iter (+/- 27834) /// test bench::f64::simd::sum ... bench: 504943 ns/iter (+/- 22928) /// ``` pub fn sum<T>(slice: &[T]) -> T where T: Simd, { use std::ops::Add; use traits::Vector; let (head, body, tail) = T::Vector::cast(slice); let sum = body.iter().map(|&x| x).fold(T::Vector::zeroed(), Add::add).sum(); let sum = head.iter().map(|&x| x).fold(sum, Add::add); tail.iter().map(|&x| x).fold(sum, Add::add) } /// "Casts" a `&[A]` into an aligned `&[B]`, the elements (both in the front and in the back) that /// don't fit in the aligned slice, will be returned as slices. unsafe fn cast<'a, A, B>(slice: &'a [A]) -> (&'a [A], &'a [B], &'a [A]) { use std::raw::Repr; use std::{raw, mem}; /// Rounds down `n` to the nearest multiple of `k` fn round_down(n: usize, k: usize) -> usize { n - n % k } /// Rounds up `n` to the nearest multiple of `k` fn round_up(n: usize, k: usize) -> usize { let r = n % k; if r == 0 { n } else { n + k - r } } let align_of_b = mem::align_of::<B>(); let size_of_a = mem::size_of::<A>(); let size_of_b = mem::size_of::<B>(); let raw::Slice { data: start, len } = slice.repr(); let end = start.offset(len as isize); let (head_start, tail_end) = (start as usize, end as usize); let body_start = round_up(head_start, align_of_b); let body_end = round_down(tail_end, align_of_b); if body_start >= body_end { (slice, &[], &[]) } else { let head_end = body_start; let head_len = (head_end - head_start) / size_of_a; let body_len = (body_end - body_start) / size_of_b; let tail_start = body_end; let tail_len = (tail_end - tail_start) / size_of_a; let head = mem::transmute(raw::Slice { data: head_start as *const A, len: head_len }); let body = mem::transmute(raw::Slice { data: body_start as *const B, len: body_len }); let tail = mem::transmute(raw::Slice { data: tail_start as *const A, len: tail_len }); (head, body, tail) } }
pub mod traits; #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd]
random_line_split
lib.rs
//! [Experimental] Generic programming with SIMD #![cfg_attr(test, feature(test))] #![cfg_attr(test, plugin(quickcheck_macros))] #![deny(missing_docs)] #![deny(warnings)] #![feature(core)] #![feature(plugin)] #![feature(simd)] #[cfg(test)] extern crate test as stdtest; #[cfg(test)] extern crate approx; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use traits::Simd; #[cfg(test)] mod test; #[cfg(test)] mod bench; mod f32; mod f64; pub mod traits; #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f32x4(pub f32, pub f32, pub f32, pub f32); #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f64x2(pub f64, pub f64); /// Sum the elements of a slice using SIMD ops /// /// # Benchmarks /// /// Size: 1 million elements /// /// ``` ignore /// test bench::f32::plain::sum... bench: 962914 ns/iter (+/- 64354) /// test bench::f32::simd::sum ... bench: 242686 ns/iter (+/- 11847) /// test bench::f64::plain::sum... bench: 995390 ns/iter (+/- 27834) /// test bench::f64::simd::sum ... bench: 504943 ns/iter (+/- 22928) /// ``` pub fn
<T>(slice: &[T]) -> T where T: Simd, { use std::ops::Add; use traits::Vector; let (head, body, tail) = T::Vector::cast(slice); let sum = body.iter().map(|&x| x).fold(T::Vector::zeroed(), Add::add).sum(); let sum = head.iter().map(|&x| x).fold(sum, Add::add); tail.iter().map(|&x| x).fold(sum, Add::add) } /// "Casts" a `&[A]` into an aligned `&[B]`, the elements (both in the front and in the back) that /// don't fit in the aligned slice, will be returned as slices. unsafe fn cast<'a, A, B>(slice: &'a [A]) -> (&'a [A], &'a [B], &'a [A]) { use std::raw::Repr; use std::{raw, mem}; /// Rounds down `n` to the nearest multiple of `k` fn round_down(n: usize, k: usize) -> usize { n - n % k } /// Rounds up `n` to the nearest multiple of `k` fn round_up(n: usize, k: usize) -> usize { let r = n % k; if r == 0 { n } else { n + k - r } } let align_of_b = mem::align_of::<B>(); let size_of_a = mem::size_of::<A>(); let size_of_b = mem::size_of::<B>(); let raw::Slice { data: start, len } = slice.repr(); let end = start.offset(len as isize); let (head_start, tail_end) = (start as usize, end as usize); let body_start = round_up(head_start, align_of_b); let body_end = round_down(tail_end, align_of_b); if body_start >= body_end { (slice, &[], &[]) } else { let head_end = body_start; let head_len = (head_end - head_start) / size_of_a; let body_len = (body_end - body_start) / size_of_b; let tail_start = body_end; let tail_len = (tail_end - tail_start) / size_of_a; let head = mem::transmute(raw::Slice { data: head_start as *const A, len: head_len }); let body = mem::transmute(raw::Slice { data: body_start as *const B, len: body_len }); let tail = mem::transmute(raw::Slice { data: tail_start as *const A, len: tail_len }); (head, body, tail) } }
sum
identifier_name
lib.rs
//! [Experimental] Generic programming with SIMD #![cfg_attr(test, feature(test))] #![cfg_attr(test, plugin(quickcheck_macros))] #![deny(missing_docs)] #![deny(warnings)] #![feature(core)] #![feature(plugin)] #![feature(simd)] #[cfg(test)] extern crate test as stdtest; #[cfg(test)] extern crate approx; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use traits::Simd; #[cfg(test)] mod test; #[cfg(test)] mod bench; mod f32; mod f64; pub mod traits; #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f32x4(pub f32, pub f32, pub f32, pub f32); #[allow(missing_docs, non_camel_case_types)] #[derive(Clone, Copy, Debug)] #[simd] pub struct f64x2(pub f64, pub f64); /// Sum the elements of a slice using SIMD ops /// /// # Benchmarks /// /// Size: 1 million elements /// /// ``` ignore /// test bench::f32::plain::sum... bench: 962914 ns/iter (+/- 64354) /// test bench::f32::simd::sum ... bench: 242686 ns/iter (+/- 11847) /// test bench::f64::plain::sum... bench: 995390 ns/iter (+/- 27834) /// test bench::f64::simd::sum ... bench: 504943 ns/iter (+/- 22928) /// ``` pub fn sum<T>(slice: &[T]) -> T where T: Simd, { use std::ops::Add; use traits::Vector; let (head, body, tail) = T::Vector::cast(slice); let sum = body.iter().map(|&x| x).fold(T::Vector::zeroed(), Add::add).sum(); let sum = head.iter().map(|&x| x).fold(sum, Add::add); tail.iter().map(|&x| x).fold(sum, Add::add) } /// "Casts" a `&[A]` into an aligned `&[B]`, the elements (both in the front and in the back) that /// don't fit in the aligned slice, will be returned as slices. unsafe fn cast<'a, A, B>(slice: &'a [A]) -> (&'a [A], &'a [B], &'a [A]) { use std::raw::Repr; use std::{raw, mem}; /// Rounds down `n` to the nearest multiple of `k` fn round_down(n: usize, k: usize) -> usize { n - n % k } /// Rounds up `n` to the nearest multiple of `k` fn round_up(n: usize, k: usize) -> usize { let r = n % k; if r == 0 { n } else { n + k - r } } let align_of_b = mem::align_of::<B>(); let size_of_a = mem::size_of::<A>(); let size_of_b = mem::size_of::<B>(); let raw::Slice { data: start, len } = slice.repr(); let end = start.offset(len as isize); let (head_start, tail_end) = (start as usize, end as usize); let body_start = round_up(head_start, align_of_b); let body_end = round_down(tail_end, align_of_b); if body_start >= body_end
else { let head_end = body_start; let head_len = (head_end - head_start) / size_of_a; let body_len = (body_end - body_start) / size_of_b; let tail_start = body_end; let tail_len = (tail_end - tail_start) / size_of_a; let head = mem::transmute(raw::Slice { data: head_start as *const A, len: head_len }); let body = mem::transmute(raw::Slice { data: body_start as *const B, len: body_len }); let tail = mem::transmute(raw::Slice { data: tail_start as *const A, len: tail_len }); (head, body, tail) } }
{ (slice, &[], &[]) }
conditional_block
version.rs
use std::collections::HashMap; use conduit::{Request, Response}; use conduit_router::RequestParams; use diesel; use diesel::pg::Pg; use diesel::pg::upsert::*; use diesel::prelude::*; use semver; use serde_json; use time::{Duration, Timespec, now_utc, strptime}; use url; use Crate; use app::RequestApp; use db::RequestTransaction; use dependency::{Dependency, EncodableDependency}; use download::{VersionDownload, EncodableVersionDownload}; use git; use owner::{rights, Rights}; use schema::*; use user::RequestUser; use util::errors::CargoError; use util::{RequestUtils, CargoResult, human}; use license_exprs; // This is necessary to allow joining version to both crates and readme_rendering // in the render-readmes script. enable_multi_table_joins!(crates, readme_rendering); // Queryable has a custom implementation below #[derive(Clone, Identifiable, Associations, Debug)] #[belongs_to(Crate)] pub struct Version { pub id: i32, pub crate_id: i32, pub num: semver::Version, pub updated_at: Timespec, pub created_at: Timespec, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, } #[derive(Insertable, Debug)] #[table_name = "versions"] pub struct NewVersion { crate_id: i32, num: String, features: String, license: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct EncodableVersion { pub id: i32, #[serde(rename = "crate")] pub krate: String, pub num: String, pub dl_path: String, pub readme_path: String, pub updated_at: String, pub created_at: String, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, pub links: VersionLinks, } #[derive(Serialize, Deserialize, Debug)] pub struct VersionLinks { pub dependencies: String, pub version_downloads: String, pub authors: String, } #[derive(Insertable, Identifiable, Queryable, Associations, Debug, Clone, Copy)] #[belongs_to(Version)] #[table_name = "readme_rendering"] #[primary_key(version_id)] struct ReadmeRendering { version_id: i32, rendered_at: Timespec, } impl Version { pub fn encodable(self, crate_name: &str) -> EncodableVersion { let Version { id, num, updated_at, created_at, downloads, features, yanked, license, .. } = self; let num = num.to_string(); EncodableVersion { dl_path: format!("/api/v1/crates/{}/{}/download", crate_name, num), readme_path: format!("/api/v1/crates/{}/{}/readme", crate_name, num), num: num.clone(), id: id, krate: crate_name.to_string(), updated_at: ::encode_time(updated_at), created_at: ::encode_time(created_at), downloads: downloads, features: features, yanked: yanked, license: license, links: VersionLinks { dependencies: format!("/api/v1/crates/{}/{}/dependencies", crate_name, num), version_downloads: format!("/api/v1/crates/{}/{}/downloads", crate_name, num), authors: format!("/api/v1/crates/{}/{}/authors", crate_name, num), }, } } /// Returns (dependency, crate dependency name)
.select((dependencies::all_columns, crates::name)) .order((dependencies::optional, crates::name)) .load(conn) } pub fn max<T>(versions: T) -> semver::Version where T: IntoIterator<Item = semver::Version>, { versions.into_iter().max().unwrap_or_else(|| { semver::Version { major: 0, minor: 0, patch: 0, pre: vec![], build: vec![], } }) } pub fn record_readme_rendering(&self, conn: &PgConnection) -> CargoResult<()> { let rendered = ReadmeRendering { version_id: self.id, rendered_at: ::now(), }; diesel::insert(&rendered.on_conflict( readme_rendering::version_id, do_update().set(readme_rendering::rendered_at.eq( excluded( readme_rendering::rendered_at, ), )), )).into(readme_rendering::table) .execute(&*conn)?; Ok(()) } } impl NewVersion { pub fn new( crate_id: i32, num: &semver::Version, features: &HashMap<String, Vec<String>>, license: Option<String>, license_file: Option<&str>, ) -> CargoResult<Self> { let features = serde_json::to_string(features)?; let mut new_version = NewVersion { crate_id: crate_id, num: num.to_string(), features: features, license: license, }; new_version.validate_license(license_file)?; Ok(new_version) } pub fn save(&self, conn: &PgConnection, authors: &[String]) -> CargoResult<Version> { use diesel::{select, insert}; use diesel::expression::dsl::exists; use schema::versions::dsl::*; let already_uploaded = versions.filter(crate_id.eq(self.crate_id)).filter( num.eq(&self.num), ); if select(exists(already_uploaded)).get_result(conn)? { return Err(human(&format_args!( "crate version `{}` is already \ uploaded", self.num ))); } conn.transaction(|| { let version = insert(self).into(versions).get_result::<Version>(conn)?; let new_authors = authors .iter() .map(|s| { NewAuthor { version_id: version.id, name: &*s, } }) .collect::<Vec<_>>(); insert(&new_authors).into(version_authors::table).execute( conn, )?; Ok(version) }) } fn validate_license(&mut self, license_file: Option<&str>) -> CargoResult<()> { if let Some(ref license) = self.license { for part in license.split('/') { license_exprs::validate_license_expr(part).map_err(|e| { human(&format_args!( "{}; see http://opensource.org/licenses \ for options, and http://spdx.org/licenses/ \ for their identifiers", e )) })?; } } else if license_file.is_some() { // If no license is given, but a license file is given, flag this // crate as having a nonstandard license. Note that we don't // actually do anything else with license_file currently. self.license = Some(String::from("non-standard")); } Ok(()) } } #[derive(Insertable, Debug)] #[table_name = "version_authors"] struct NewAuthor<'a> { version_id: i32, name: &'a str, } impl Queryable<versions::SqlType, Pg> for Version { type Row = (i32, i32, String, Timespec, Timespec, i32, Option<String>, bool, Option<String>); fn build(row: Self::Row) -> Self { let features = row.6 .map(|s| serde_json::from_str(&s).unwrap()) .unwrap_or_else(HashMap::new); Version { id: row.0, crate_id: row.1, num: semver::Version::parse(&row.2).unwrap(), updated_at: row.3, created_at: row.4, downloads: row.5, features: features, yanked: row.7, license: row.8, } } } /// Handles the `GET /versions` route. // FIXME: where/how is this used? pub fn index(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::any; let conn = req.db_conn()?; // Extract all ids requested. let query = url::form_urlencoded::parse(req.query_string().unwrap_or("").as_bytes()); let ids = query .filter_map(|(ref a, ref b)| if *a == "ids[]" { b.parse().ok() } else { None }) .collect::<Vec<i32>>(); let versions = versions::table .inner_join(crates::table) .select((versions::all_columns, crates::name)) .filter(versions::id.eq(any(ids))) .load::<(Version, String)>(&*conn)? .into_iter() .map(|(version, crate_name)| version.encodable(&crate_name)) .collect(); #[derive(Serialize)] struct R { versions: Vec<EncodableVersion>, } Ok(req.json(&R { versions: versions })) } /// Handles the `GET /versions/:version_id` route. pub fn show(req: &mut Request) -> CargoResult<Response> { let (version, krate) = match req.params().find("crate_id") { Some(..) => version_and_crate(req)?, None => { let id = &req.params()["version_id"]; let id = id.parse().unwrap_or(0); let conn = req.db_conn()?; versions::table .find(id) .inner_join(crates::table) .select((versions::all_columns, ::krate::ALL_COLUMNS)) .first(&*conn)? } }; #[derive(Serialize)] struct R { version: EncodableVersion, } Ok(req.json(&R { version: version.encodable(&krate.name) })) } fn version_and_crate(req: &mut Request) -> CargoResult<(Version, Crate)> { let crate_name = &req.params()["crate_id"]; let semver = &req.params()["version"]; if semver::Version::parse(semver).is_err() { return Err(human(&format_args!("invalid semver: {}", semver))); }; let conn = req.db_conn()?; let krate = Crate::by_name(crate_name).first::<Crate>(&*conn)?; let version = Version::belonging_to(&krate) .filter(versions::num.eq(semver)) .first(&*conn) .map_err(|_| { human(&format_args!( "crate `{}` does not have a version `{}`", crate_name, semver )) })?; Ok((version, krate)) } /// Handles the `GET /crates/:crate_id/:version/dependencies` route. pub fn dependencies(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let deps = version.dependencies(&*conn)?; let deps = deps.into_iter() .map(|(dep, crate_name)| dep.encodable(&crate_name, None)) .collect(); #[derive(Serialize)] struct R { dependencies: Vec<EncodableDependency>, } Ok(req.json(&R { dependencies: deps })) } /// Handles the `GET /crates/:crate_id/:version/downloads` route. pub fn downloads(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::date; let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let cutoff_end_date = req.query() .get("before_date") .and_then(|d| strptime(d, "%Y-%m-%d").ok()) .unwrap_or_else(now_utc) .to_timespec(); let cutoff_start_date = cutoff_end_date + Duration::days(-89); let downloads = VersionDownload::belonging_to(&version) .filter(version_downloads::date.between( date(cutoff_start_date).. date(cutoff_end_date), )) .order(version_downloads::date) .load(&*conn)? .into_iter() .map(VersionDownload::encodable) .collect(); #[derive(Serialize)] struct R { version_downloads: Vec<EncodableVersionDownload>, } Ok(req.json(&R { version_downloads: downloads })) } /// Handles the `GET /crates/:crate_id/:version/authors` route. pub fn authors(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let names = version_authors::table .filter(version_authors::version_id.eq(version.id)) .select(version_authors::name) .order(version_authors::name) .load(&*conn)?; // It was imagined that we wold associate authors with users. // This was never implemented. This complicated return struct // is all that is left, hear for backwards compatibility. #[derive(Serialize)] struct R { users: Vec<::user::EncodablePublicUser>, meta: Meta, } #[derive(Serialize)] struct Meta { names: Vec<String>, } Ok(req.json(&R { users: vec![], meta: Meta { names: names }, })) } /// Handles the `DELETE /crates/:crate_id/:version/yank` route. /// This does not delete a crate version, it makes the crate /// version accessible only to crates that already have a /// `Cargo.lock` containing this version. /// /// Notes: /// Crate deletion is not implemented to avoid breaking builds, /// and the goal of yanking a crate is to prevent crates /// beginning to depend on the yanked crate version. pub fn yank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, true) } /// Handles the `PUT /crates/:crate_id/:version/unyank` route. pub fn unyank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, false) } /// Changes `yanked` flag on a crate version record fn modify_yank(req: &mut Request, yanked: bool) -> CargoResult<Response> { let (version, krate) = version_and_crate(req)?; let user = req.user()?; let conn = req.db_conn()?; let owners = krate.owners(&conn)?; if rights(req.app(), &owners, user)? < Rights::Publish { return Err(human("must already be an owner to yank or unyank")); } if version.yanked!= yanked { conn.transaction::<_, Box<CargoError>, _>(|| { diesel::update(&version) .set(versions::yanked.eq(yanked)) .execute(&*conn)?; git::yank(&**req.app(), &krate.name, &version.num, yanked)?; Ok(()) })?; } #[derive(Serialize)] struct R { ok: bool, } Ok(req.json(&R { ok: true })) }
pub fn dependencies(&self, conn: &PgConnection) -> QueryResult<Vec<(Dependency, String)>> { Dependency::belonging_to(self) .inner_join(crates::table)
random_line_split
version.rs
use std::collections::HashMap; use conduit::{Request, Response}; use conduit_router::RequestParams; use diesel; use diesel::pg::Pg; use diesel::pg::upsert::*; use diesel::prelude::*; use semver; use serde_json; use time::{Duration, Timespec, now_utc, strptime}; use url; use Crate; use app::RequestApp; use db::RequestTransaction; use dependency::{Dependency, EncodableDependency}; use download::{VersionDownload, EncodableVersionDownload}; use git; use owner::{rights, Rights}; use schema::*; use user::RequestUser; use util::errors::CargoError; use util::{RequestUtils, CargoResult, human}; use license_exprs; // This is necessary to allow joining version to both crates and readme_rendering // in the render-readmes script. enable_multi_table_joins!(crates, readme_rendering); // Queryable has a custom implementation below #[derive(Clone, Identifiable, Associations, Debug)] #[belongs_to(Crate)] pub struct Version { pub id: i32, pub crate_id: i32, pub num: semver::Version, pub updated_at: Timespec, pub created_at: Timespec, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, } #[derive(Insertable, Debug)] #[table_name = "versions"] pub struct NewVersion { crate_id: i32, num: String, features: String, license: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct EncodableVersion { pub id: i32, #[serde(rename = "crate")] pub krate: String, pub num: String, pub dl_path: String, pub readme_path: String, pub updated_at: String, pub created_at: String, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, pub links: VersionLinks, } #[derive(Serialize, Deserialize, Debug)] pub struct VersionLinks { pub dependencies: String, pub version_downloads: String, pub authors: String, } #[derive(Insertable, Identifiable, Queryable, Associations, Debug, Clone, Copy)] #[belongs_to(Version)] #[table_name = "readme_rendering"] #[primary_key(version_id)] struct ReadmeRendering { version_id: i32, rendered_at: Timespec, } impl Version { pub fn encodable(self, crate_name: &str) -> EncodableVersion { let Version { id, num, updated_at, created_at, downloads, features, yanked, license, .. } = self; let num = num.to_string(); EncodableVersion { dl_path: format!("/api/v1/crates/{}/{}/download", crate_name, num), readme_path: format!("/api/v1/crates/{}/{}/readme", crate_name, num), num: num.clone(), id: id, krate: crate_name.to_string(), updated_at: ::encode_time(updated_at), created_at: ::encode_time(created_at), downloads: downloads, features: features, yanked: yanked, license: license, links: VersionLinks { dependencies: format!("/api/v1/crates/{}/{}/dependencies", crate_name, num), version_downloads: format!("/api/v1/crates/{}/{}/downloads", crate_name, num), authors: format!("/api/v1/crates/{}/{}/authors", crate_name, num), }, } } /// Returns (dependency, crate dependency name) pub fn dependencies(&self, conn: &PgConnection) -> QueryResult<Vec<(Dependency, String)>> { Dependency::belonging_to(self) .inner_join(crates::table) .select((dependencies::all_columns, crates::name)) .order((dependencies::optional, crates::name)) .load(conn) } pub fn max<T>(versions: T) -> semver::Version where T: IntoIterator<Item = semver::Version>, { versions.into_iter().max().unwrap_or_else(|| { semver::Version { major: 0, minor: 0, patch: 0, pre: vec![], build: vec![], } }) } pub fn record_readme_rendering(&self, conn: &PgConnection) -> CargoResult<()> { let rendered = ReadmeRendering { version_id: self.id, rendered_at: ::now(), }; diesel::insert(&rendered.on_conflict( readme_rendering::version_id, do_update().set(readme_rendering::rendered_at.eq( excluded( readme_rendering::rendered_at, ), )), )).into(readme_rendering::table) .execute(&*conn)?; Ok(()) } } impl NewVersion { pub fn new( crate_id: i32, num: &semver::Version, features: &HashMap<String, Vec<String>>, license: Option<String>, license_file: Option<&str>, ) -> CargoResult<Self> { let features = serde_json::to_string(features)?; let mut new_version = NewVersion { crate_id: crate_id, num: num.to_string(), features: features, license: license, }; new_version.validate_license(license_file)?; Ok(new_version) } pub fn save(&self, conn: &PgConnection, authors: &[String]) -> CargoResult<Version> { use diesel::{select, insert}; use diesel::expression::dsl::exists; use schema::versions::dsl::*; let already_uploaded = versions.filter(crate_id.eq(self.crate_id)).filter( num.eq(&self.num), ); if select(exists(already_uploaded)).get_result(conn)? { return Err(human(&format_args!( "crate version `{}` is already \ uploaded", self.num ))); } conn.transaction(|| { let version = insert(self).into(versions).get_result::<Version>(conn)?; let new_authors = authors .iter() .map(|s| { NewAuthor { version_id: version.id, name: &*s, } }) .collect::<Vec<_>>(); insert(&new_authors).into(version_authors::table).execute( conn, )?; Ok(version) }) } fn validate_license(&mut self, license_file: Option<&str>) -> CargoResult<()> { if let Some(ref license) = self.license { for part in license.split('/') { license_exprs::validate_license_expr(part).map_err(|e| { human(&format_args!( "{}; see http://opensource.org/licenses \ for options, and http://spdx.org/licenses/ \ for their identifiers", e )) })?; } } else if license_file.is_some() { // If no license is given, but a license file is given, flag this // crate as having a nonstandard license. Note that we don't // actually do anything else with license_file currently. self.license = Some(String::from("non-standard")); } Ok(()) } } #[derive(Insertable, Debug)] #[table_name = "version_authors"] struct NewAuthor<'a> { version_id: i32, name: &'a str, } impl Queryable<versions::SqlType, Pg> for Version { type Row = (i32, i32, String, Timespec, Timespec, i32, Option<String>, bool, Option<String>); fn build(row: Self::Row) -> Self { let features = row.6 .map(|s| serde_json::from_str(&s).unwrap()) .unwrap_or_else(HashMap::new); Version { id: row.0, crate_id: row.1, num: semver::Version::parse(&row.2).unwrap(), updated_at: row.3, created_at: row.4, downloads: row.5, features: features, yanked: row.7, license: row.8, } } } /// Handles the `GET /versions` route. // FIXME: where/how is this used? pub fn index(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::any; let conn = req.db_conn()?; // Extract all ids requested. let query = url::form_urlencoded::parse(req.query_string().unwrap_or("").as_bytes()); let ids = query .filter_map(|(ref a, ref b)| if *a == "ids[]" { b.parse().ok() } else { None }) .collect::<Vec<i32>>(); let versions = versions::table .inner_join(crates::table) .select((versions::all_columns, crates::name)) .filter(versions::id.eq(any(ids))) .load::<(Version, String)>(&*conn)? .into_iter() .map(|(version, crate_name)| version.encodable(&crate_name)) .collect(); #[derive(Serialize)] struct R { versions: Vec<EncodableVersion>, } Ok(req.json(&R { versions: versions })) } /// Handles the `GET /versions/:version_id` route. pub fn show(req: &mut Request) -> CargoResult<Response> { let (version, krate) = match req.params().find("crate_id") { Some(..) => version_and_crate(req)?, None => { let id = &req.params()["version_id"]; let id = id.parse().unwrap_or(0); let conn = req.db_conn()?; versions::table .find(id) .inner_join(crates::table) .select((versions::all_columns, ::krate::ALL_COLUMNS)) .first(&*conn)? } }; #[derive(Serialize)] struct R { version: EncodableVersion, } Ok(req.json(&R { version: version.encodable(&krate.name) })) } fn version_and_crate(req: &mut Request) -> CargoResult<(Version, Crate)> { let crate_name = &req.params()["crate_id"]; let semver = &req.params()["version"]; if semver::Version::parse(semver).is_err()
; let conn = req.db_conn()?; let krate = Crate::by_name(crate_name).first::<Crate>(&*conn)?; let version = Version::belonging_to(&krate) .filter(versions::num.eq(semver)) .first(&*conn) .map_err(|_| { human(&format_args!( "crate `{}` does not have a version `{}`", crate_name, semver )) })?; Ok((version, krate)) } /// Handles the `GET /crates/:crate_id/:version/dependencies` route. pub fn dependencies(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let deps = version.dependencies(&*conn)?; let deps = deps.into_iter() .map(|(dep, crate_name)| dep.encodable(&crate_name, None)) .collect(); #[derive(Serialize)] struct R { dependencies: Vec<EncodableDependency>, } Ok(req.json(&R { dependencies: deps })) } /// Handles the `GET /crates/:crate_id/:version/downloads` route. pub fn downloads(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::date; let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let cutoff_end_date = req.query() .get("before_date") .and_then(|d| strptime(d, "%Y-%m-%d").ok()) .unwrap_or_else(now_utc) .to_timespec(); let cutoff_start_date = cutoff_end_date + Duration::days(-89); let downloads = VersionDownload::belonging_to(&version) .filter(version_downloads::date.between( date(cutoff_start_date).. date(cutoff_end_date), )) .order(version_downloads::date) .load(&*conn)? .into_iter() .map(VersionDownload::encodable) .collect(); #[derive(Serialize)] struct R { version_downloads: Vec<EncodableVersionDownload>, } Ok(req.json(&R { version_downloads: downloads })) } /// Handles the `GET /crates/:crate_id/:version/authors` route. pub fn authors(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let names = version_authors::table .filter(version_authors::version_id.eq(version.id)) .select(version_authors::name) .order(version_authors::name) .load(&*conn)?; // It was imagined that we wold associate authors with users. // This was never implemented. This complicated return struct // is all that is left, hear for backwards compatibility. #[derive(Serialize)] struct R { users: Vec<::user::EncodablePublicUser>, meta: Meta, } #[derive(Serialize)] struct Meta { names: Vec<String>, } Ok(req.json(&R { users: vec![], meta: Meta { names: names }, })) } /// Handles the `DELETE /crates/:crate_id/:version/yank` route. /// This does not delete a crate version, it makes the crate /// version accessible only to crates that already have a /// `Cargo.lock` containing this version. /// /// Notes: /// Crate deletion is not implemented to avoid breaking builds, /// and the goal of yanking a crate is to prevent crates /// beginning to depend on the yanked crate version. pub fn yank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, true) } /// Handles the `PUT /crates/:crate_id/:version/unyank` route. pub fn unyank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, false) } /// Changes `yanked` flag on a crate version record fn modify_yank(req: &mut Request, yanked: bool) -> CargoResult<Response> { let (version, krate) = version_and_crate(req)?; let user = req.user()?; let conn = req.db_conn()?; let owners = krate.owners(&conn)?; if rights(req.app(), &owners, user)? < Rights::Publish { return Err(human("must already be an owner to yank or unyank")); } if version.yanked!= yanked { conn.transaction::<_, Box<CargoError>, _>(|| { diesel::update(&version) .set(versions::yanked.eq(yanked)) .execute(&*conn)?; git::yank(&**req.app(), &krate.name, &version.num, yanked)?; Ok(()) })?; } #[derive(Serialize)] struct R { ok: bool, } Ok(req.json(&R { ok: true })) }
{ return Err(human(&format_args!("invalid semver: {}", semver))); }
conditional_block
version.rs
use std::collections::HashMap; use conduit::{Request, Response}; use conduit_router::RequestParams; use diesel; use diesel::pg::Pg; use diesel::pg::upsert::*; use diesel::prelude::*; use semver; use serde_json; use time::{Duration, Timespec, now_utc, strptime}; use url; use Crate; use app::RequestApp; use db::RequestTransaction; use dependency::{Dependency, EncodableDependency}; use download::{VersionDownload, EncodableVersionDownload}; use git; use owner::{rights, Rights}; use schema::*; use user::RequestUser; use util::errors::CargoError; use util::{RequestUtils, CargoResult, human}; use license_exprs; // This is necessary to allow joining version to both crates and readme_rendering // in the render-readmes script. enable_multi_table_joins!(crates, readme_rendering); // Queryable has a custom implementation below #[derive(Clone, Identifiable, Associations, Debug)] #[belongs_to(Crate)] pub struct Version { pub id: i32, pub crate_id: i32, pub num: semver::Version, pub updated_at: Timespec, pub created_at: Timespec, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, } #[derive(Insertable, Debug)] #[table_name = "versions"] pub struct NewVersion { crate_id: i32, num: String, features: String, license: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct EncodableVersion { pub id: i32, #[serde(rename = "crate")] pub krate: String, pub num: String, pub dl_path: String, pub readme_path: String, pub updated_at: String, pub created_at: String, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, pub links: VersionLinks, } #[derive(Serialize, Deserialize, Debug)] pub struct VersionLinks { pub dependencies: String, pub version_downloads: String, pub authors: String, } #[derive(Insertable, Identifiable, Queryable, Associations, Debug, Clone, Copy)] #[belongs_to(Version)] #[table_name = "readme_rendering"] #[primary_key(version_id)] struct ReadmeRendering { version_id: i32, rendered_at: Timespec, } impl Version { pub fn encodable(self, crate_name: &str) -> EncodableVersion { let Version { id, num, updated_at, created_at, downloads, features, yanked, license, .. } = self; let num = num.to_string(); EncodableVersion { dl_path: format!("/api/v1/crates/{}/{}/download", crate_name, num), readme_path: format!("/api/v1/crates/{}/{}/readme", crate_name, num), num: num.clone(), id: id, krate: crate_name.to_string(), updated_at: ::encode_time(updated_at), created_at: ::encode_time(created_at), downloads: downloads, features: features, yanked: yanked, license: license, links: VersionLinks { dependencies: format!("/api/v1/crates/{}/{}/dependencies", crate_name, num), version_downloads: format!("/api/v1/crates/{}/{}/downloads", crate_name, num), authors: format!("/api/v1/crates/{}/{}/authors", crate_name, num), }, } } /// Returns (dependency, crate dependency name) pub fn dependencies(&self, conn: &PgConnection) -> QueryResult<Vec<(Dependency, String)>> { Dependency::belonging_to(self) .inner_join(crates::table) .select((dependencies::all_columns, crates::name)) .order((dependencies::optional, crates::name)) .load(conn) } pub fn max<T>(versions: T) -> semver::Version where T: IntoIterator<Item = semver::Version>, { versions.into_iter().max().unwrap_or_else(|| { semver::Version { major: 0, minor: 0, patch: 0, pre: vec![], build: vec![], } }) } pub fn record_readme_rendering(&self, conn: &PgConnection) -> CargoResult<()> { let rendered = ReadmeRendering { version_id: self.id, rendered_at: ::now(), }; diesel::insert(&rendered.on_conflict( readme_rendering::version_id, do_update().set(readme_rendering::rendered_at.eq( excluded( readme_rendering::rendered_at, ), )), )).into(readme_rendering::table) .execute(&*conn)?; Ok(()) } } impl NewVersion { pub fn new( crate_id: i32, num: &semver::Version, features: &HashMap<String, Vec<String>>, license: Option<String>, license_file: Option<&str>, ) -> CargoResult<Self> { let features = serde_json::to_string(features)?; let mut new_version = NewVersion { crate_id: crate_id, num: num.to_string(), features: features, license: license, }; new_version.validate_license(license_file)?; Ok(new_version) } pub fn save(&self, conn: &PgConnection, authors: &[String]) -> CargoResult<Version> { use diesel::{select, insert}; use diesel::expression::dsl::exists; use schema::versions::dsl::*; let already_uploaded = versions.filter(crate_id.eq(self.crate_id)).filter( num.eq(&self.num), ); if select(exists(already_uploaded)).get_result(conn)? { return Err(human(&format_args!( "crate version `{}` is already \ uploaded", self.num ))); } conn.transaction(|| { let version = insert(self).into(versions).get_result::<Version>(conn)?; let new_authors = authors .iter() .map(|s| { NewAuthor { version_id: version.id, name: &*s, } }) .collect::<Vec<_>>(); insert(&new_authors).into(version_authors::table).execute( conn, )?; Ok(version) }) } fn validate_license(&mut self, license_file: Option<&str>) -> CargoResult<()> { if let Some(ref license) = self.license { for part in license.split('/') { license_exprs::validate_license_expr(part).map_err(|e| { human(&format_args!( "{}; see http://opensource.org/licenses \ for options, and http://spdx.org/licenses/ \ for their identifiers", e )) })?; } } else if license_file.is_some() { // If no license is given, but a license file is given, flag this // crate as having a nonstandard license. Note that we don't // actually do anything else with license_file currently. self.license = Some(String::from("non-standard")); } Ok(()) } } #[derive(Insertable, Debug)] #[table_name = "version_authors"] struct NewAuthor<'a> { version_id: i32, name: &'a str, } impl Queryable<versions::SqlType, Pg> for Version { type Row = (i32, i32, String, Timespec, Timespec, i32, Option<String>, bool, Option<String>); fn build(row: Self::Row) -> Self { let features = row.6 .map(|s| serde_json::from_str(&s).unwrap()) .unwrap_or_else(HashMap::new); Version { id: row.0, crate_id: row.1, num: semver::Version::parse(&row.2).unwrap(), updated_at: row.3, created_at: row.4, downloads: row.5, features: features, yanked: row.7, license: row.8, } } } /// Handles the `GET /versions` route. // FIXME: where/how is this used? pub fn index(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::any; let conn = req.db_conn()?; // Extract all ids requested. let query = url::form_urlencoded::parse(req.query_string().unwrap_or("").as_bytes()); let ids = query .filter_map(|(ref a, ref b)| if *a == "ids[]" { b.parse().ok() } else { None }) .collect::<Vec<i32>>(); let versions = versions::table .inner_join(crates::table) .select((versions::all_columns, crates::name)) .filter(versions::id.eq(any(ids))) .load::<(Version, String)>(&*conn)? .into_iter() .map(|(version, crate_name)| version.encodable(&crate_name)) .collect(); #[derive(Serialize)] struct R { versions: Vec<EncodableVersion>, } Ok(req.json(&R { versions: versions })) } /// Handles the `GET /versions/:version_id` route. pub fn
(req: &mut Request) -> CargoResult<Response> { let (version, krate) = match req.params().find("crate_id") { Some(..) => version_and_crate(req)?, None => { let id = &req.params()["version_id"]; let id = id.parse().unwrap_or(0); let conn = req.db_conn()?; versions::table .find(id) .inner_join(crates::table) .select((versions::all_columns, ::krate::ALL_COLUMNS)) .first(&*conn)? } }; #[derive(Serialize)] struct R { version: EncodableVersion, } Ok(req.json(&R { version: version.encodable(&krate.name) })) } fn version_and_crate(req: &mut Request) -> CargoResult<(Version, Crate)> { let crate_name = &req.params()["crate_id"]; let semver = &req.params()["version"]; if semver::Version::parse(semver).is_err() { return Err(human(&format_args!("invalid semver: {}", semver))); }; let conn = req.db_conn()?; let krate = Crate::by_name(crate_name).first::<Crate>(&*conn)?; let version = Version::belonging_to(&krate) .filter(versions::num.eq(semver)) .first(&*conn) .map_err(|_| { human(&format_args!( "crate `{}` does not have a version `{}`", crate_name, semver )) })?; Ok((version, krate)) } /// Handles the `GET /crates/:crate_id/:version/dependencies` route. pub fn dependencies(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let deps = version.dependencies(&*conn)?; let deps = deps.into_iter() .map(|(dep, crate_name)| dep.encodable(&crate_name, None)) .collect(); #[derive(Serialize)] struct R { dependencies: Vec<EncodableDependency>, } Ok(req.json(&R { dependencies: deps })) } /// Handles the `GET /crates/:crate_id/:version/downloads` route. pub fn downloads(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::date; let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let cutoff_end_date = req.query() .get("before_date") .and_then(|d| strptime(d, "%Y-%m-%d").ok()) .unwrap_or_else(now_utc) .to_timespec(); let cutoff_start_date = cutoff_end_date + Duration::days(-89); let downloads = VersionDownload::belonging_to(&version) .filter(version_downloads::date.between( date(cutoff_start_date).. date(cutoff_end_date), )) .order(version_downloads::date) .load(&*conn)? .into_iter() .map(VersionDownload::encodable) .collect(); #[derive(Serialize)] struct R { version_downloads: Vec<EncodableVersionDownload>, } Ok(req.json(&R { version_downloads: downloads })) } /// Handles the `GET /crates/:crate_id/:version/authors` route. pub fn authors(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let names = version_authors::table .filter(version_authors::version_id.eq(version.id)) .select(version_authors::name) .order(version_authors::name) .load(&*conn)?; // It was imagined that we wold associate authors with users. // This was never implemented. This complicated return struct // is all that is left, hear for backwards compatibility. #[derive(Serialize)] struct R { users: Vec<::user::EncodablePublicUser>, meta: Meta, } #[derive(Serialize)] struct Meta { names: Vec<String>, } Ok(req.json(&R { users: vec![], meta: Meta { names: names }, })) } /// Handles the `DELETE /crates/:crate_id/:version/yank` route. /// This does not delete a crate version, it makes the crate /// version accessible only to crates that already have a /// `Cargo.lock` containing this version. /// /// Notes: /// Crate deletion is not implemented to avoid breaking builds, /// and the goal of yanking a crate is to prevent crates /// beginning to depend on the yanked crate version. pub fn yank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, true) } /// Handles the `PUT /crates/:crate_id/:version/unyank` route. pub fn unyank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, false) } /// Changes `yanked` flag on a crate version record fn modify_yank(req: &mut Request, yanked: bool) -> CargoResult<Response> { let (version, krate) = version_and_crate(req)?; let user = req.user()?; let conn = req.db_conn()?; let owners = krate.owners(&conn)?; if rights(req.app(), &owners, user)? < Rights::Publish { return Err(human("must already be an owner to yank or unyank")); } if version.yanked!= yanked { conn.transaction::<_, Box<CargoError>, _>(|| { diesel::update(&version) .set(versions::yanked.eq(yanked)) .execute(&*conn)?; git::yank(&**req.app(), &krate.name, &version.num, yanked)?; Ok(()) })?; } #[derive(Serialize)] struct R { ok: bool, } Ok(req.json(&R { ok: true })) }
show
identifier_name
version.rs
use std::collections::HashMap; use conduit::{Request, Response}; use conduit_router::RequestParams; use diesel; use diesel::pg::Pg; use diesel::pg::upsert::*; use diesel::prelude::*; use semver; use serde_json; use time::{Duration, Timespec, now_utc, strptime}; use url; use Crate; use app::RequestApp; use db::RequestTransaction; use dependency::{Dependency, EncodableDependency}; use download::{VersionDownload, EncodableVersionDownload}; use git; use owner::{rights, Rights}; use schema::*; use user::RequestUser; use util::errors::CargoError; use util::{RequestUtils, CargoResult, human}; use license_exprs; // This is necessary to allow joining version to both crates and readme_rendering // in the render-readmes script. enable_multi_table_joins!(crates, readme_rendering); // Queryable has a custom implementation below #[derive(Clone, Identifiable, Associations, Debug)] #[belongs_to(Crate)] pub struct Version { pub id: i32, pub crate_id: i32, pub num: semver::Version, pub updated_at: Timespec, pub created_at: Timespec, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, } #[derive(Insertable, Debug)] #[table_name = "versions"] pub struct NewVersion { crate_id: i32, num: String, features: String, license: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct EncodableVersion { pub id: i32, #[serde(rename = "crate")] pub krate: String, pub num: String, pub dl_path: String, pub readme_path: String, pub updated_at: String, pub created_at: String, pub downloads: i32, pub features: HashMap<String, Vec<String>>, pub yanked: bool, pub license: Option<String>, pub links: VersionLinks, } #[derive(Serialize, Deserialize, Debug)] pub struct VersionLinks { pub dependencies: String, pub version_downloads: String, pub authors: String, } #[derive(Insertable, Identifiable, Queryable, Associations, Debug, Clone, Copy)] #[belongs_to(Version)] #[table_name = "readme_rendering"] #[primary_key(version_id)] struct ReadmeRendering { version_id: i32, rendered_at: Timespec, } impl Version { pub fn encodable(self, crate_name: &str) -> EncodableVersion { let Version { id, num, updated_at, created_at, downloads, features, yanked, license, .. } = self; let num = num.to_string(); EncodableVersion { dl_path: format!("/api/v1/crates/{}/{}/download", crate_name, num), readme_path: format!("/api/v1/crates/{}/{}/readme", crate_name, num), num: num.clone(), id: id, krate: crate_name.to_string(), updated_at: ::encode_time(updated_at), created_at: ::encode_time(created_at), downloads: downloads, features: features, yanked: yanked, license: license, links: VersionLinks { dependencies: format!("/api/v1/crates/{}/{}/dependencies", crate_name, num), version_downloads: format!("/api/v1/crates/{}/{}/downloads", crate_name, num), authors: format!("/api/v1/crates/{}/{}/authors", crate_name, num), }, } } /// Returns (dependency, crate dependency name) pub fn dependencies(&self, conn: &PgConnection) -> QueryResult<Vec<(Dependency, String)>> { Dependency::belonging_to(self) .inner_join(crates::table) .select((dependencies::all_columns, crates::name)) .order((dependencies::optional, crates::name)) .load(conn) } pub fn max<T>(versions: T) -> semver::Version where T: IntoIterator<Item = semver::Version>, { versions.into_iter().max().unwrap_or_else(|| { semver::Version { major: 0, minor: 0, patch: 0, pre: vec![], build: vec![], } }) } pub fn record_readme_rendering(&self, conn: &PgConnection) -> CargoResult<()> { let rendered = ReadmeRendering { version_id: self.id, rendered_at: ::now(), }; diesel::insert(&rendered.on_conflict( readme_rendering::version_id, do_update().set(readme_rendering::rendered_at.eq( excluded( readme_rendering::rendered_at, ), )), )).into(readme_rendering::table) .execute(&*conn)?; Ok(()) } } impl NewVersion { pub fn new( crate_id: i32, num: &semver::Version, features: &HashMap<String, Vec<String>>, license: Option<String>, license_file: Option<&str>, ) -> CargoResult<Self> { let features = serde_json::to_string(features)?; let mut new_version = NewVersion { crate_id: crate_id, num: num.to_string(), features: features, license: license, }; new_version.validate_license(license_file)?; Ok(new_version) } pub fn save(&self, conn: &PgConnection, authors: &[String]) -> CargoResult<Version> { use diesel::{select, insert}; use diesel::expression::dsl::exists; use schema::versions::dsl::*; let already_uploaded = versions.filter(crate_id.eq(self.crate_id)).filter( num.eq(&self.num), ); if select(exists(already_uploaded)).get_result(conn)? { return Err(human(&format_args!( "crate version `{}` is already \ uploaded", self.num ))); } conn.transaction(|| { let version = insert(self).into(versions).get_result::<Version>(conn)?; let new_authors = authors .iter() .map(|s| { NewAuthor { version_id: version.id, name: &*s, } }) .collect::<Vec<_>>(); insert(&new_authors).into(version_authors::table).execute( conn, )?; Ok(version) }) } fn validate_license(&mut self, license_file: Option<&str>) -> CargoResult<()> { if let Some(ref license) = self.license { for part in license.split('/') { license_exprs::validate_license_expr(part).map_err(|e| { human(&format_args!( "{}; see http://opensource.org/licenses \ for options, and http://spdx.org/licenses/ \ for their identifiers", e )) })?; } } else if license_file.is_some() { // If no license is given, but a license file is given, flag this // crate as having a nonstandard license. Note that we don't // actually do anything else with license_file currently. self.license = Some(String::from("non-standard")); } Ok(()) } } #[derive(Insertable, Debug)] #[table_name = "version_authors"] struct NewAuthor<'a> { version_id: i32, name: &'a str, } impl Queryable<versions::SqlType, Pg> for Version { type Row = (i32, i32, String, Timespec, Timespec, i32, Option<String>, bool, Option<String>); fn build(row: Self::Row) -> Self
} /// Handles the `GET /versions` route. // FIXME: where/how is this used? pub fn index(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::any; let conn = req.db_conn()?; // Extract all ids requested. let query = url::form_urlencoded::parse(req.query_string().unwrap_or("").as_bytes()); let ids = query .filter_map(|(ref a, ref b)| if *a == "ids[]" { b.parse().ok() } else { None }) .collect::<Vec<i32>>(); let versions = versions::table .inner_join(crates::table) .select((versions::all_columns, crates::name)) .filter(versions::id.eq(any(ids))) .load::<(Version, String)>(&*conn)? .into_iter() .map(|(version, crate_name)| version.encodable(&crate_name)) .collect(); #[derive(Serialize)] struct R { versions: Vec<EncodableVersion>, } Ok(req.json(&R { versions: versions })) } /// Handles the `GET /versions/:version_id` route. pub fn show(req: &mut Request) -> CargoResult<Response> { let (version, krate) = match req.params().find("crate_id") { Some(..) => version_and_crate(req)?, None => { let id = &req.params()["version_id"]; let id = id.parse().unwrap_or(0); let conn = req.db_conn()?; versions::table .find(id) .inner_join(crates::table) .select((versions::all_columns, ::krate::ALL_COLUMNS)) .first(&*conn)? } }; #[derive(Serialize)] struct R { version: EncodableVersion, } Ok(req.json(&R { version: version.encodable(&krate.name) })) } fn version_and_crate(req: &mut Request) -> CargoResult<(Version, Crate)> { let crate_name = &req.params()["crate_id"]; let semver = &req.params()["version"]; if semver::Version::parse(semver).is_err() { return Err(human(&format_args!("invalid semver: {}", semver))); }; let conn = req.db_conn()?; let krate = Crate::by_name(crate_name).first::<Crate>(&*conn)?; let version = Version::belonging_to(&krate) .filter(versions::num.eq(semver)) .first(&*conn) .map_err(|_| { human(&format_args!( "crate `{}` does not have a version `{}`", crate_name, semver )) })?; Ok((version, krate)) } /// Handles the `GET /crates/:crate_id/:version/dependencies` route. pub fn dependencies(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let deps = version.dependencies(&*conn)?; let deps = deps.into_iter() .map(|(dep, crate_name)| dep.encodable(&crate_name, None)) .collect(); #[derive(Serialize)] struct R { dependencies: Vec<EncodableDependency>, } Ok(req.json(&R { dependencies: deps })) } /// Handles the `GET /crates/:crate_id/:version/downloads` route. pub fn downloads(req: &mut Request) -> CargoResult<Response> { use diesel::expression::dsl::date; let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let cutoff_end_date = req.query() .get("before_date") .and_then(|d| strptime(d, "%Y-%m-%d").ok()) .unwrap_or_else(now_utc) .to_timespec(); let cutoff_start_date = cutoff_end_date + Duration::days(-89); let downloads = VersionDownload::belonging_to(&version) .filter(version_downloads::date.between( date(cutoff_start_date).. date(cutoff_end_date), )) .order(version_downloads::date) .load(&*conn)? .into_iter() .map(VersionDownload::encodable) .collect(); #[derive(Serialize)] struct R { version_downloads: Vec<EncodableVersionDownload>, } Ok(req.json(&R { version_downloads: downloads })) } /// Handles the `GET /crates/:crate_id/:version/authors` route. pub fn authors(req: &mut Request) -> CargoResult<Response> { let (version, _) = version_and_crate(req)?; let conn = req.db_conn()?; let names = version_authors::table .filter(version_authors::version_id.eq(version.id)) .select(version_authors::name) .order(version_authors::name) .load(&*conn)?; // It was imagined that we wold associate authors with users. // This was never implemented. This complicated return struct // is all that is left, hear for backwards compatibility. #[derive(Serialize)] struct R { users: Vec<::user::EncodablePublicUser>, meta: Meta, } #[derive(Serialize)] struct Meta { names: Vec<String>, } Ok(req.json(&R { users: vec![], meta: Meta { names: names }, })) } /// Handles the `DELETE /crates/:crate_id/:version/yank` route. /// This does not delete a crate version, it makes the crate /// version accessible only to crates that already have a /// `Cargo.lock` containing this version. /// /// Notes: /// Crate deletion is not implemented to avoid breaking builds, /// and the goal of yanking a crate is to prevent crates /// beginning to depend on the yanked crate version. pub fn yank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, true) } /// Handles the `PUT /crates/:crate_id/:version/unyank` route. pub fn unyank(req: &mut Request) -> CargoResult<Response> { modify_yank(req, false) } /// Changes `yanked` flag on a crate version record fn modify_yank(req: &mut Request, yanked: bool) -> CargoResult<Response> { let (version, krate) = version_and_crate(req)?; let user = req.user()?; let conn = req.db_conn()?; let owners = krate.owners(&conn)?; if rights(req.app(), &owners, user)? < Rights::Publish { return Err(human("must already be an owner to yank or unyank")); } if version.yanked!= yanked { conn.transaction::<_, Box<CargoError>, _>(|| { diesel::update(&version) .set(versions::yanked.eq(yanked)) .execute(&*conn)?; git::yank(&**req.app(), &krate.name, &version.num, yanked)?; Ok(()) })?; } #[derive(Serialize)] struct R { ok: bool, } Ok(req.json(&R { ok: true })) }
{ let features = row.6 .map(|s| serde_json::from_str(&s).unwrap()) .unwrap_or_else(HashMap::new); Version { id: row.0, crate_id: row.1, num: semver::Version::parse(&row.2).unwrap(), updated_at: row.3, created_at: row.4, downloads: row.5, features: features, yanked: row.7, license: row.8, } }
identifier_body
netc.rs
// Copyright 2016 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 type in_addr_t = u32; pub type in_port_t = u16; pub type socklen_t = u32; pub type sa_family_t = u16; pub const AF_INET: sa_family_t = 2; pub const AF_INET6: sa_family_t = 23; #[derive(Copy, Clone)] #[repr(C)] pub struct in_addr { pub s_addr: in_addr_t, } #[derive(Copy, Clone)] #[repr(align(4))] #[repr(C)] pub struct in6_addr { pub s6_addr: [u8; 16], } #[derive(Copy, Clone)] #[repr(C)] pub struct sockaddr { pub sa_family: sa_family_t, pub sa_data: [u8; 14], } #[derive(Copy, Clone)] #[repr(C)] pub struct
{ pub sin_family: sa_family_t, pub sin_port: in_port_t, pub sin_addr: in_addr, pub sin_zero: [u8; 8], } #[derive(Copy, Clone)] #[repr(C)] pub struct sockaddr_in6 { pub sin6_family: sa_family_t, pub sin6_port: in_port_t, pub sin6_flowinfo: u32, pub sin6_addr: in6_addr, pub sin6_scope_id: u32, }
sockaddr_in
identifier_name
netc.rs
// Copyright 2016 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 type in_addr_t = u32; pub type in_port_t = u16; pub type socklen_t = u32; pub type sa_family_t = u16; pub const AF_INET: sa_family_t = 2; pub const AF_INET6: sa_family_t = 23;
pub s_addr: in_addr_t, } #[derive(Copy, Clone)] #[repr(align(4))] #[repr(C)] pub struct in6_addr { pub s6_addr: [u8; 16], } #[derive(Copy, Clone)] #[repr(C)] pub struct sockaddr { pub sa_family: sa_family_t, pub sa_data: [u8; 14], } #[derive(Copy, Clone)] #[repr(C)] pub struct sockaddr_in { pub sin_family: sa_family_t, pub sin_port: in_port_t, pub sin_addr: in_addr, pub sin_zero: [u8; 8], } #[derive(Copy, Clone)] #[repr(C)] pub struct sockaddr_in6 { pub sin6_family: sa_family_t, pub sin6_port: in_port_t, pub sin6_flowinfo: u32, pub sin6_addr: in6_addr, pub sin6_scope_id: u32, }
#[derive(Copy, Clone)] #[repr(C)] pub struct in_addr {
random_line_split
psar.rs
use std::f64::NAN; use error::Err; /// Parabolic SAR /// iaf : increment acceleration factor / starting acceleration. Usually 0.02 /// maxaf : max acceleration factor. Usually 0.2 /// Hypothesis : assuming long for initial conditions /// Formula : pub fn
(high: &[f64], low: &[f64], iaf: f64, maxaf: f64) -> Result<Vec<f64>, Err> { let mut psar = vec![NAN; high.len()]; if high.len() < 2 { return Err(Err::NotEnoughtData); }; let mut long = false; if high[0] + low[0] <= high[1] + low[1] { long = true; } let mut sar; let mut extreme; if long { extreme = high[0]; sar = low[0]; } else { extreme = low[0]; sar = high[0]; } psar[0] = sar; let mut af = iaf; for i in 1..high.len() { sar = (extreme - sar) * af + sar; if long { if i >= 2 && (sar > low[i - 2]) { sar = low[i - 2] }; if sar > low[i - 1] { sar = low[i - 1] }; if af < maxaf && high[i] > extreme { af += iaf; if af > maxaf { af = maxaf }; } if high[i] > extreme { extreme = high[i]; } } else { if i >= 2 && sar < high[i - 2] { sar = high[i - 2] }; if sar < high[i - 1] { sar = high[i - 1] }; if af < maxaf && low[i] < extreme { af += iaf; if af > maxaf { af = maxaf }; } if low[i] < extreme { extreme = low[i] }; } if long && low[i] < sar ||!long && high[i] > sar { af = iaf; sar = extreme; long =!long; if!long { extreme = low[i]; } else { extreme = high[i]; } } psar[i] = sar; } Ok(psar) }
psar
identifier_name
psar.rs
use std::f64::NAN; use error::Err; /// Parabolic SAR /// iaf : increment acceleration factor / starting acceleration. Usually 0.02 /// maxaf : max acceleration factor. Usually 0.2 /// Hypothesis : assuming long for initial conditions /// Formula : pub fn psar(high: &[f64], low: &[f64], iaf: f64, maxaf: f64) -> Result<Vec<f64>, Err>
sar = high[0]; } psar[0] = sar; let mut af = iaf; for i in 1..high.len() { sar = (extreme - sar) * af + sar; if long { if i >= 2 && (sar > low[i - 2]) { sar = low[i - 2] }; if sar > low[i - 1] { sar = low[i - 1] }; if af < maxaf && high[i] > extreme { af += iaf; if af > maxaf { af = maxaf }; } if high[i] > extreme { extreme = high[i]; } } else { if i >= 2 && sar < high[i - 2] { sar = high[i - 2] }; if sar < high[i - 1] { sar = high[i - 1] }; if af < maxaf && low[i] < extreme { af += iaf; if af > maxaf { af = maxaf }; } if low[i] < extreme { extreme = low[i] }; } if long && low[i] < sar ||!long && high[i] > sar { af = iaf; sar = extreme; long =!long; if!long { extreme = low[i]; } else { extreme = high[i]; } } psar[i] = sar; } Ok(psar) }
{ let mut psar = vec![NAN; high.len()]; if high.len() < 2 { return Err(Err::NotEnoughtData); }; let mut long = false; if high[0] + low[0] <= high[1] + low[1] { long = true; } let mut sar; let mut extreme; if long { extreme = high[0]; sar = low[0]; } else { extreme = low[0];
identifier_body
psar.rs
use std::f64::NAN; use error::Err; /// Parabolic SAR /// iaf : increment acceleration factor / starting acceleration. Usually 0.02 /// maxaf : max acceleration factor. Usually 0.2 /// Hypothesis : assuming long for initial conditions /// Formula : pub fn psar(high: &[f64], low: &[f64], iaf: f64, maxaf: f64) -> Result<Vec<f64>, Err> { let mut psar = vec![NAN; high.len()]; if high.len() < 2 { return Err(Err::NotEnoughtData); }; let mut long = false; if high[0] + low[0] <= high[1] + low[1] { long = true; } let mut sar; let mut extreme; if long { extreme = high[0]; sar = low[0]; } else { extreme = low[0]; sar = high[0]; } psar[0] = sar; let mut af = iaf; for i in 1..high.len() { sar = (extreme - sar) * af + sar; if long { if i >= 2 && (sar > low[i - 2]) { sar = low[i - 2] }; if sar > low[i - 1] { sar = low[i - 1] }; if af < maxaf && high[i] > extreme { af += iaf; if af > maxaf { af = maxaf }; } if high[i] > extreme { extreme = high[i]; } } else { if i >= 2 && sar < high[i - 2] { sar = high[i - 2] }; if sar < high[i - 1] { sar = high[i - 1] }; if af < maxaf && low[i] < extreme { af += iaf; if af > maxaf { af = maxaf }; } if low[i] < extreme { extreme = low[i] }; } if long && low[i] < sar ||!long && high[i] > sar
psar[i] = sar; } Ok(psar) }
{ af = iaf; sar = extreme; long = !long; if !long { extreme = low[i]; } else { extreme = high[i]; } }
conditional_block
psar.rs
use std::f64::NAN; use error::Err; /// Parabolic SAR /// iaf : increment acceleration factor / starting acceleration. Usually 0.02 /// maxaf : max acceleration factor. Usually 0.2 /// Hypothesis : assuming long for initial conditions /// Formula : pub fn psar(high: &[f64], low: &[f64], iaf: f64, maxaf: f64) -> Result<Vec<f64>, Err> { let mut psar = vec![NAN; high.len()]; if high.len() < 2 { return Err(Err::NotEnoughtData); }; let mut long = false; if high[0] + low[0] <= high[1] + low[1] { long = true; } let mut sar; let mut extreme; if long { extreme = high[0]; sar = low[0]; } else { extreme = low[0]; sar = high[0]; } psar[0] = sar; let mut af = iaf; for i in 1..high.len() { sar = (extreme - sar) * af + sar; if long { if i >= 2 && (sar > low[i - 2]) { sar = low[i - 2] }; if sar > low[i - 1] { sar = low[i - 1] }; if af < maxaf && high[i] > extreme { af += iaf; if af > maxaf { af = maxaf }; } if high[i] > extreme {
extreme = high[i]; } } else { if i >= 2 && sar < high[i - 2] { sar = high[i - 2] }; if sar < high[i - 1] { sar = high[i - 1] }; if af < maxaf && low[i] < extreme { af += iaf; if af > maxaf { af = maxaf }; } if low[i] < extreme { extreme = low[i] }; } if long && low[i] < sar ||!long && high[i] > sar { af = iaf; sar = extreme; long =!long; if!long { extreme = low[i]; } else { extreme = high[i]; } } psar[i] = sar; } Ok(psar) }
random_line_split
angle.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/. */ //! Specified angles. use cssparser::{Parser, Token}; use parser::{ParserContext, Parse}; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; use values::CSSFloat; use values::computed::{Context, ToComputedValue}; use values::computed::angle::Angle as ComputedAngle; use values::specified::calc::CalcNode; /// A specified angle. /// /// Computed angles are essentially same as specified ones except for `calc()` /// value serialization. Therefore we are storing a computed angle inside /// to hold the actual value and its unit. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)] pub struct Angle { value: ComputedAngle, was_calc: bool, } impl ToCss for Angle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { if self.was_calc { dest.write_str("calc(")?; } self.value.to_css(dest)?; if self.was_calc { dest.write_str(")")?; } Ok(()) } } impl ToComputedValue for Angle { type ComputedValue = ComputedAngle; fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue { self.value } fn from_computed_value(computed: &Self::ComputedValue) -> Self { Angle { value: *computed, was_calc: false, } } } impl Angle { /// Creates an angle with the given value in degrees. pub fn from_degrees(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Deg(value), was_calc } } /// Creates an angle with the given value in gradians. pub fn from_gradians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Grad(value), was_calc } } /// Creates an angle with the given value in turns. pub fn from_turns(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Turn(value), was_calc } } /// Creates an angle with the given value in radians. pub fn from_radians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Rad(value), was_calc } } /// Returns the amount of radians this angle represents. #[inline] pub fn radians(self) -> f32 { self.value.radians() } /// Returns the amount of degrees this angle represents. #[inline] pub fn
(self) -> f32 { use std::f32::consts::PI; self.radians() * 360. / (2. * PI) } /// Returns `0deg`. pub fn zero() -> Self { Self::from_degrees(0.0, false) } /// Returns an `Angle` parsed from a `calc()` expression. pub fn from_calc(radians: CSSFloat) -> Self { Angle { value: ComputedAngle::Rad(radians), was_calc: true, } } } impl AsRef<ComputedAngle> for Angle { #[inline] fn as_ref(&self) -> &ComputedAngle { &self.value } } /// Whether to allow parsing an unitless zero as a valid angle. /// /// This should always be `No`, except for exceptions like: /// /// https://github.com/w3c/fxtf-drafts/issues/228 /// /// See also: https://github.com/w3c/csswg-drafts/issues/1162. enum AllowUnitlessZeroAngle { Yes, No, } impl Parse for Angle { /// Parses an angle according to CSS-VALUES § 6.1. fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Self::parse_internal(context, input, AllowUnitlessZeroAngle::No) } } impl Angle { /// Parse an `<angle>` value given a value and an unit. pub fn parse_dimension( value: CSSFloat, unit: &str, from_calc: bool, ) -> Result<Angle, ()> { let angle = match_ignore_ascii_case! { unit, "deg" => Angle::from_degrees(value, from_calc), "grad" => Angle::from_gradians(value, from_calc), "turn" => Angle::from_turns(value, from_calc), "rad" => Angle::from_radians(value, from_calc), _ => return Err(()) }; Ok(angle) } /// Parse an `<angle>` allowing unitless zero to represent a zero angle. /// /// See the comment in `AllowUnitlessZeroAngle` for why. pub fn parse_with_unitless<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Self::parse_internal(context, input, AllowUnitlessZeroAngle::Yes) } fn parse_internal<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_unitless_zero: AllowUnitlessZeroAngle, ) -> Result<Self, ParseError<'i>> { // FIXME: remove clone() when lifetimes are non-lexical let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit,.. } => { Angle::parse_dimension(value, unit, /* from_calc = */ false) } Token::Number { value,.. } if value == 0. => { match allow_unitless_zero { AllowUnitlessZeroAngle::Yes => Ok(Angle::zero()), AllowUnitlessZeroAngle::No => Err(()), } }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { return input.parse_nested_block(|i| CalcNode::parse_angle(context, i)) } _ => Err(()) }.map_err(|()| input.new_unexpected_token_error(token.clone())) } }
degrees
identifier_name
angle.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/. */ //! Specified angles. use cssparser::{Parser, Token}; use parser::{ParserContext, Parse}; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; use values::CSSFloat; use values::computed::{Context, ToComputedValue}; use values::computed::angle::Angle as ComputedAngle; use values::specified::calc::CalcNode; /// A specified angle. /// /// Computed angles are essentially same as specified ones except for `calc()` /// value serialization. Therefore we are storing a computed angle inside /// to hold the actual value and its unit. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)] pub struct Angle { value: ComputedAngle, was_calc: bool, } impl ToCss for Angle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { if self.was_calc { dest.write_str("calc(")?; } self.value.to_css(dest)?; if self.was_calc { dest.write_str(")")?; } Ok(()) } } impl ToComputedValue for Angle { type ComputedValue = ComputedAngle; fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue
fn from_computed_value(computed: &Self::ComputedValue) -> Self { Angle { value: *computed, was_calc: false, } } } impl Angle { /// Creates an angle with the given value in degrees. pub fn from_degrees(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Deg(value), was_calc } } /// Creates an angle with the given value in gradians. pub fn from_gradians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Grad(value), was_calc } } /// Creates an angle with the given value in turns. pub fn from_turns(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Turn(value), was_calc } } /// Creates an angle with the given value in radians. pub fn from_radians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Rad(value), was_calc } } /// Returns the amount of radians this angle represents. #[inline] pub fn radians(self) -> f32 { self.value.radians() } /// Returns the amount of degrees this angle represents. #[inline] pub fn degrees(self) -> f32 { use std::f32::consts::PI; self.radians() * 360. / (2. * PI) } /// Returns `0deg`. pub fn zero() -> Self { Self::from_degrees(0.0, false) } /// Returns an `Angle` parsed from a `calc()` expression. pub fn from_calc(radians: CSSFloat) -> Self { Angle { value: ComputedAngle::Rad(radians), was_calc: true, } } } impl AsRef<ComputedAngle> for Angle { #[inline] fn as_ref(&self) -> &ComputedAngle { &self.value } } /// Whether to allow parsing an unitless zero as a valid angle. /// /// This should always be `No`, except for exceptions like: /// /// https://github.com/w3c/fxtf-drafts/issues/228 /// /// See also: https://github.com/w3c/csswg-drafts/issues/1162. enum AllowUnitlessZeroAngle { Yes, No, } impl Parse for Angle { /// Parses an angle according to CSS-VALUES § 6.1. fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Self::parse_internal(context, input, AllowUnitlessZeroAngle::No) } } impl Angle { /// Parse an `<angle>` value given a value and an unit. pub fn parse_dimension( value: CSSFloat, unit: &str, from_calc: bool, ) -> Result<Angle, ()> { let angle = match_ignore_ascii_case! { unit, "deg" => Angle::from_degrees(value, from_calc), "grad" => Angle::from_gradians(value, from_calc), "turn" => Angle::from_turns(value, from_calc), "rad" => Angle::from_radians(value, from_calc), _ => return Err(()) }; Ok(angle) } /// Parse an `<angle>` allowing unitless zero to represent a zero angle. /// /// See the comment in `AllowUnitlessZeroAngle` for why. pub fn parse_with_unitless<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Self::parse_internal(context, input, AllowUnitlessZeroAngle::Yes) } fn parse_internal<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_unitless_zero: AllowUnitlessZeroAngle, ) -> Result<Self, ParseError<'i>> { // FIXME: remove clone() when lifetimes are non-lexical let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit,.. } => { Angle::parse_dimension(value, unit, /* from_calc = */ false) } Token::Number { value,.. } if value == 0. => { match allow_unitless_zero { AllowUnitlessZeroAngle::Yes => Ok(Angle::zero()), AllowUnitlessZeroAngle::No => Err(()), } }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { return input.parse_nested_block(|i| CalcNode::parse_angle(context, i)) } _ => Err(()) }.map_err(|()| input.new_unexpected_token_error(token.clone())) } }
{ self.value }
identifier_body
angle.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/. */ //! Specified angles. use cssparser::{Parser, Token}; use parser::{ParserContext, Parse}; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::fmt::{self, Write}; use style_traits::{CssWriter, ParseError, ToCss}; use values::CSSFloat; use values::computed::{Context, ToComputedValue}; use values::computed::angle::Angle as ComputedAngle; use values::specified::calc::CalcNode; /// A specified angle. /// /// Computed angles are essentially same as specified ones except for `calc()` /// value serialization. Therefore we are storing a computed angle inside /// to hold the actual value and its unit. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)] pub struct Angle { value: ComputedAngle, was_calc: bool, } impl ToCss for Angle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { if self.was_calc { dest.write_str("calc(")?; } self.value.to_css(dest)?; if self.was_calc { dest.write_str(")")?; } Ok(()) } } impl ToComputedValue for Angle { type ComputedValue = ComputedAngle; fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue { self.value } fn from_computed_value(computed: &Self::ComputedValue) -> Self { Angle { value: *computed, was_calc: false, } } } impl Angle { /// Creates an angle with the given value in degrees. pub fn from_degrees(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Deg(value), was_calc } } /// Creates an angle with the given value in gradians. pub fn from_gradians(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Grad(value), was_calc } } /// Creates an angle with the given value in turns. pub fn from_turns(value: CSSFloat, was_calc: bool) -> Self { Angle { value: ComputedAngle::Turn(value), was_calc } } /// Creates an angle with the given value in radians. pub fn from_radians(value: CSSFloat, was_calc: bool) -> Self {
Angle { value: ComputedAngle::Rad(value), was_calc } } /// Returns the amount of radians this angle represents. #[inline] pub fn radians(self) -> f32 { self.value.radians() } /// Returns the amount of degrees this angle represents. #[inline] pub fn degrees(self) -> f32 { use std::f32::consts::PI; self.radians() * 360. / (2. * PI) } /// Returns `0deg`. pub fn zero() -> Self { Self::from_degrees(0.0, false) } /// Returns an `Angle` parsed from a `calc()` expression. pub fn from_calc(radians: CSSFloat) -> Self { Angle { value: ComputedAngle::Rad(radians), was_calc: true, } } } impl AsRef<ComputedAngle> for Angle { #[inline] fn as_ref(&self) -> &ComputedAngle { &self.value } } /// Whether to allow parsing an unitless zero as a valid angle. /// /// This should always be `No`, except for exceptions like: /// /// https://github.com/w3c/fxtf-drafts/issues/228 /// /// See also: https://github.com/w3c/csswg-drafts/issues/1162. enum AllowUnitlessZeroAngle { Yes, No, } impl Parse for Angle { /// Parses an angle according to CSS-VALUES § 6.1. fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Self::parse_internal(context, input, AllowUnitlessZeroAngle::No) } } impl Angle { /// Parse an `<angle>` value given a value and an unit. pub fn parse_dimension( value: CSSFloat, unit: &str, from_calc: bool, ) -> Result<Angle, ()> { let angle = match_ignore_ascii_case! { unit, "deg" => Angle::from_degrees(value, from_calc), "grad" => Angle::from_gradians(value, from_calc), "turn" => Angle::from_turns(value, from_calc), "rad" => Angle::from_radians(value, from_calc), _ => return Err(()) }; Ok(angle) } /// Parse an `<angle>` allowing unitless zero to represent a zero angle. /// /// See the comment in `AllowUnitlessZeroAngle` for why. pub fn parse_with_unitless<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Self::parse_internal(context, input, AllowUnitlessZeroAngle::Yes) } fn parse_internal<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_unitless_zero: AllowUnitlessZeroAngle, ) -> Result<Self, ParseError<'i>> { // FIXME: remove clone() when lifetimes are non-lexical let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit,.. } => { Angle::parse_dimension(value, unit, /* from_calc = */ false) } Token::Number { value,.. } if value == 0. => { match allow_unitless_zero { AllowUnitlessZeroAngle::Yes => Ok(Angle::zero()), AllowUnitlessZeroAngle::No => Err(()), } }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { return input.parse_nested_block(|i| CalcNode::parse_angle(context, i)) } _ => Err(()) }.map_err(|()| input.new_unexpected_token_error(token.clone())) } }
random_line_split
helper.rs
use std::time::Duration; use xpath_reader::Reader; /// Note that the requirement of the `var` (variant) token is rather ugly but /// required, /// which is a limitation of the current Rust macro implementation. /// /// Note that the macro wont expand if you miss ommit the last comma. /// If this macro is ever extracted into a library this should be fixed. /// /// - https://github.com/rust-lang/rust/issues/24189 /// - https://github.com/rust-lang/rust/issues/42838 macro_rules! enum_mb_xml { ( $(#[$attr:meta])* pub enum $enum:ident { $( $(#[$attr2:meta])* var $variant:ident = $str:expr ),+ , } ) => { $(#[$attr])* #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum $enum { $( $(#[$attr2])* $variant, )+ } impl FromXml for $enum { fn from_xml<'d>(reader: &'d Reader<'d>) -> Result<Self, ::xpath_reader::Error> { match String::from_xml(reader)?.as_str() { $( $str => Ok($enum::$variant), )+ s => Err( ::xpath_reader::Error::custom_msg( format!("Unknown `{}` value: '{}'", stringify!($enum), s) ) ) } } } impl ::std::fmt::Display for $enum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let s = match *self { $( $enum::$variant => $str, )+ }; write!(f, "{}", s) } } } } macro_rules! enum_mb_xml_optional { ( $(#[$attr:meta])* pub enum $enum:ident { $( $(#[$attr2:meta])* var $variant:ident = $str:expr ),+ , } ) => { $(#[$attr])* #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum $enum { $( $(#[$attr2])* $variant, )+ } impl FromXmlOptional for $enum { fn from_xml_optional<'d>(reader: &'d Reader<'d>) -> Result<Option<Self>, ::xpath_reader::Error> { let s = Option::<String>::from_xml(reader)?; if let Some(s) = s { match s.as_ref() { $( $str => Ok(Some($enum::$variant)), )+ s => Err( ::xpath_reader::Error::custom_msg( format!("Unknown `{}` value: '{}'", stringify!($enum), s) ) ) } } else { Ok(None) } } } impl ::std::fmt::Display for $enum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let s = match *self { $( $enum::$variant => $str, )+ }; write!(f, "{}", s) } } } } pub fn
<'d>( reader: &'d Reader<'d>, path: &str, ) -> Result<Option<Duration>, ::xpath_reader::Error> { let s: Option<String> = reader.read(path)?; match s { Some(millis) => Ok(Some(Duration::from_millis( millis.parse().map_err(::xpath_reader::Error::custom_err)?, ))), None => Ok(None), } }
read_mb_duration
identifier_name
helper.rs
use std::time::Duration; use xpath_reader::Reader; /// Note that the requirement of the `var` (variant) token is rather ugly but /// required, /// which is a limitation of the current Rust macro implementation. /// /// Note that the macro wont expand if you miss ommit the last comma. /// If this macro is ever extracted into a library this should be fixed. /// /// - https://github.com/rust-lang/rust/issues/24189 /// - https://github.com/rust-lang/rust/issues/42838 macro_rules! enum_mb_xml { ( $(#[$attr:meta])* pub enum $enum:ident { $( $(#[$attr2:meta])* var $variant:ident = $str:expr ),+ , } ) => { $(#[$attr])* #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum $enum { $( $(#[$attr2])* $variant, )+ } impl FromXml for $enum { fn from_xml<'d>(reader: &'d Reader<'d>) -> Result<Self, ::xpath_reader::Error> { match String::from_xml(reader)?.as_str() { $( $str => Ok($enum::$variant), )+ s => Err( ::xpath_reader::Error::custom_msg( format!("Unknown `{}` value: '{}'", stringify!($enum), s)
} impl ::std::fmt::Display for $enum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let s = match *self { $( $enum::$variant => $str, )+ }; write!(f, "{}", s) } } } } macro_rules! enum_mb_xml_optional { ( $(#[$attr:meta])* pub enum $enum:ident { $( $(#[$attr2:meta])* var $variant:ident = $str:expr ),+ , } ) => { $(#[$attr])* #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum $enum { $( $(#[$attr2])* $variant, )+ } impl FromXmlOptional for $enum { fn from_xml_optional<'d>(reader: &'d Reader<'d>) -> Result<Option<Self>, ::xpath_reader::Error> { let s = Option::<String>::from_xml(reader)?; if let Some(s) = s { match s.as_ref() { $( $str => Ok(Some($enum::$variant)), )+ s => Err( ::xpath_reader::Error::custom_msg( format!("Unknown `{}` value: '{}'", stringify!($enum), s) ) ) } } else { Ok(None) } } } impl ::std::fmt::Display for $enum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let s = match *self { $( $enum::$variant => $str, )+ }; write!(f, "{}", s) } } } } pub fn read_mb_duration<'d>( reader: &'d Reader<'d>, path: &str, ) -> Result<Option<Duration>, ::xpath_reader::Error> { let s: Option<String> = reader.read(path)?; match s { Some(millis) => Ok(Some(Duration::from_millis( millis.parse().map_err(::xpath_reader::Error::custom_err)?, ))), None => Ok(None), } }
) ) } }
random_line_split
helper.rs
use std::time::Duration; use xpath_reader::Reader; /// Note that the requirement of the `var` (variant) token is rather ugly but /// required, /// which is a limitation of the current Rust macro implementation. /// /// Note that the macro wont expand if you miss ommit the last comma. /// If this macro is ever extracted into a library this should be fixed. /// /// - https://github.com/rust-lang/rust/issues/24189 /// - https://github.com/rust-lang/rust/issues/42838 macro_rules! enum_mb_xml { ( $(#[$attr:meta])* pub enum $enum:ident { $( $(#[$attr2:meta])* var $variant:ident = $str:expr ),+ , } ) => { $(#[$attr])* #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum $enum { $( $(#[$attr2])* $variant, )+ } impl FromXml for $enum { fn from_xml<'d>(reader: &'d Reader<'d>) -> Result<Self, ::xpath_reader::Error> { match String::from_xml(reader)?.as_str() { $( $str => Ok($enum::$variant), )+ s => Err( ::xpath_reader::Error::custom_msg( format!("Unknown `{}` value: '{}'", stringify!($enum), s) ) ) } } } impl ::std::fmt::Display for $enum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let s = match *self { $( $enum::$variant => $str, )+ }; write!(f, "{}", s) } } } } macro_rules! enum_mb_xml_optional { ( $(#[$attr:meta])* pub enum $enum:ident { $( $(#[$attr2:meta])* var $variant:ident = $str:expr ),+ , } ) => { $(#[$attr])* #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum $enum { $( $(#[$attr2])* $variant, )+ } impl FromXmlOptional for $enum { fn from_xml_optional<'d>(reader: &'d Reader<'d>) -> Result<Option<Self>, ::xpath_reader::Error> { let s = Option::<String>::from_xml(reader)?; if let Some(s) = s { match s.as_ref() { $( $str => Ok(Some($enum::$variant)), )+ s => Err( ::xpath_reader::Error::custom_msg( format!("Unknown `{}` value: '{}'", stringify!($enum), s) ) ) } } else { Ok(None) } } } impl ::std::fmt::Display for $enum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let s = match *self { $( $enum::$variant => $str, )+ }; write!(f, "{}", s) } } } } pub fn read_mb_duration<'d>( reader: &'d Reader<'d>, path: &str, ) -> Result<Option<Duration>, ::xpath_reader::Error>
{ let s: Option<String> = reader.read(path)?; match s { Some(millis) => Ok(Some(Duration::from_millis( millis.parse().map_err(::xpath_reader::Error::custom_err)?, ))), None => Ok(None), } }
identifier_body
shootout-spectralnorm.rs
use core::from_str::FromStr; use core::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32 { (i+j) * (i+j+1) / 2 + i + 1 } fn dot(v: &[f64], u: &[f64]) -> f64 { let mut sum = 0.0; for v.eachi |i, &v_i| { sum += v_i * u[i]; } sum } fn mult_Av(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(i as i32, j as i32) as f64); } *out_i = sum; } } fn mult_Atv(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(j as i32, i as i32) as f64); } *out_i = sum; } } fn mult_AtAv(v: &mut [f64], out: &mut [f64], tmp: &mut [f64]) { mult_Av(v, tmp); mult_Atv(tmp, out); } #[fixed_stack_segment] fn main() { let n: uint = FromStr::from_str(os::args()[1]).get(); let mut u = vec::from_elem(n, 1f64), v = u.clone(), tmp = u.clone();
} println(fmt!("%.9f", f64::sqrt(dot(u,v) / dot(v,v)) as float)); }
for 8.times { mult_AtAv(u, v, tmp); mult_AtAv(v, u, tmp);
random_line_split
shootout-spectralnorm.rs
use core::from_str::FromStr; use core::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32 { (i+j) * (i+j+1) / 2 + i + 1 } fn dot(v: &[f64], u: &[f64]) -> f64 { let mut sum = 0.0; for v.eachi |i, &v_i| { sum += v_i * u[i]; } sum } fn mult_Av(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(i as i32, j as i32) as f64); } *out_i = sum; } } fn mult_Atv(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(j as i32, i as i32) as f64); } *out_i = sum; } } fn
(v: &mut [f64], out: &mut [f64], tmp: &mut [f64]) { mult_Av(v, tmp); mult_Atv(tmp, out); } #[fixed_stack_segment] fn main() { let n: uint = FromStr::from_str(os::args()[1]).get(); let mut u = vec::from_elem(n, 1f64), v = u.clone(), tmp = u.clone(); for 8.times { mult_AtAv(u, v, tmp); mult_AtAv(v, u, tmp); } println(fmt!("%.9f", f64::sqrt(dot(u,v) / dot(v,v)) as float)); }
mult_AtAv
identifier_name
shootout-spectralnorm.rs
use core::from_str::FromStr; use core::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32
fn dot(v: &[f64], u: &[f64]) -> f64 { let mut sum = 0.0; for v.eachi |i, &v_i| { sum += v_i * u[i]; } sum } fn mult_Av(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(i as i32, j as i32) as f64); } *out_i = sum; } } fn mult_Atv(v: &mut [f64], out: &mut [f64]) { for vec::eachi_mut(out) |i, out_i| { let mut sum = 0.0; for vec::eachi_mut(v) |j, &v_j| { sum += v_j / (A(j as i32, i as i32) as f64); } *out_i = sum; } } fn mult_AtAv(v: &mut [f64], out: &mut [f64], tmp: &mut [f64]) { mult_Av(v, tmp); mult_Atv(tmp, out); } #[fixed_stack_segment] fn main() { let n: uint = FromStr::from_str(os::args()[1]).get(); let mut u = vec::from_elem(n, 1f64), v = u.clone(), tmp = u.clone(); for 8.times { mult_AtAv(u, v, tmp); mult_AtAv(v, u, tmp); } println(fmt!("%.9f", f64::sqrt(dot(u,v) / dot(v,v)) as float)); }
{ (i+j) * (i+j+1) / 2 + i + 1 }
identifier_body
request_proxy.rs
use std::io::Read; use std::net::SocketAddr; use conduit;
#[allow(missing_debug_implementations)] pub struct RequestProxy<'a> { pub other: &'a mut (Request + 'a), pub path: Option<&'a str>, pub method: Option<conduit::Method>, } impl<'a> Request for RequestProxy<'a> { fn http_version(&self) -> semver::Version { self.other.http_version() } fn conduit_version(&self) -> semver::Version { self.other.conduit_version() } fn method(&self) -> conduit::Method { self.method.clone().unwrap_or_else( || self.other.method().clone(), ) } fn scheme(&self) -> conduit::Scheme { self.other.scheme() } fn host(&self) -> conduit::Host { self.other.host() } fn virtual_root(&self) -> Option<&str> { self.other.virtual_root() } fn path(&self) -> &str { self.path.map(|s| &*s).unwrap_or_else(|| self.other.path()) } fn query_string(&self) -> Option<&str> { self.other.query_string() } fn remote_addr(&self) -> SocketAddr { self.other.remote_addr() } fn content_length(&self) -> Option<u64> { self.other.content_length() } fn headers(&self) -> &conduit::Headers { self.other.headers() } fn body(&mut self) -> &mut Read { self.other.body() } fn extensions(&self) -> &conduit::Extensions { self.other.extensions() } fn mut_extensions(&mut self) -> &mut conduit::Extensions { self.other.mut_extensions() } }
use conduit::Request; use semver; // Can't derive Debug because of Request.
random_line_split
request_proxy.rs
use std::io::Read; use std::net::SocketAddr; use conduit; use conduit::Request; use semver; // Can't derive Debug because of Request. #[allow(missing_debug_implementations)] pub struct RequestProxy<'a> { pub other: &'a mut (Request + 'a), pub path: Option<&'a str>, pub method: Option<conduit::Method>, } impl<'a> Request for RequestProxy<'a> { fn http_version(&self) -> semver::Version { self.other.http_version() } fn conduit_version(&self) -> semver::Version { self.other.conduit_version() } fn method(&self) -> conduit::Method { self.method.clone().unwrap_or_else( || self.other.method().clone(), ) } fn scheme(&self) -> conduit::Scheme
fn host(&self) -> conduit::Host { self.other.host() } fn virtual_root(&self) -> Option<&str> { self.other.virtual_root() } fn path(&self) -> &str { self.path.map(|s| &*s).unwrap_or_else(|| self.other.path()) } fn query_string(&self) -> Option<&str> { self.other.query_string() } fn remote_addr(&self) -> SocketAddr { self.other.remote_addr() } fn content_length(&self) -> Option<u64> { self.other.content_length() } fn headers(&self) -> &conduit::Headers { self.other.headers() } fn body(&mut self) -> &mut Read { self.other.body() } fn extensions(&self) -> &conduit::Extensions { self.other.extensions() } fn mut_extensions(&mut self) -> &mut conduit::Extensions { self.other.mut_extensions() } }
{ self.other.scheme() }
identifier_body
request_proxy.rs
use std::io::Read; use std::net::SocketAddr; use conduit; use conduit::Request; use semver; // Can't derive Debug because of Request. #[allow(missing_debug_implementations)] pub struct RequestProxy<'a> { pub other: &'a mut (Request + 'a), pub path: Option<&'a str>, pub method: Option<conduit::Method>, } impl<'a> Request for RequestProxy<'a> { fn http_version(&self) -> semver::Version { self.other.http_version() } fn conduit_version(&self) -> semver::Version { self.other.conduit_version() } fn method(&self) -> conduit::Method { self.method.clone().unwrap_or_else( || self.other.method().clone(), ) } fn scheme(&self) -> conduit::Scheme { self.other.scheme() } fn host(&self) -> conduit::Host { self.other.host() } fn virtual_root(&self) -> Option<&str> { self.other.virtual_root() } fn path(&self) -> &str { self.path.map(|s| &*s).unwrap_or_else(|| self.other.path()) } fn query_string(&self) -> Option<&str> { self.other.query_string() } fn remote_addr(&self) -> SocketAddr { self.other.remote_addr() } fn
(&self) -> Option<u64> { self.other.content_length() } fn headers(&self) -> &conduit::Headers { self.other.headers() } fn body(&mut self) -> &mut Read { self.other.body() } fn extensions(&self) -> &conduit::Extensions { self.other.extensions() } fn mut_extensions(&mut self) -> &mut conduit::Extensions { self.other.mut_extensions() } }
content_length
identifier_name
main.rs
// Task : Guess number game // Date : 10 Sept 2016 // Author : Vigneshwer extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn main()
match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too big"), Ordering::Equal => { println!("Win"); break; } } } }
{ println!("Guess the Number game!"); let secret_number = rand::thread_rng().gen_range(1,101); // println!("You secret number is {}", secret_number); loop { println!("Enter the number in your mind"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess: u32 =match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; print!("You guessed: {}",guess);
identifier_body
main.rs
// Task : Guess number game // Date : 10 Sept 2016 // Author : Vigneshwer extern crate rand; use std::io; use std::cmp::Ordering; use rand::Rng; fn
() { println!("Guess the Number game!"); let secret_number = rand::thread_rng().gen_range(1,101); // println!("You secret number is {}", secret_number); loop { println!("Enter the number in your mind"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess: u32 =match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; print!("You guessed: {}",guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too big"), Ordering::Equal => { println!("Win"); break; } } } }
main
identifier_name
main.rs
// Task : Guess number game
use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Guess the Number game!"); let secret_number = rand::thread_rng().gen_range(1,101); // println!("You secret number is {}", secret_number); loop { println!("Enter the number in your mind"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess: u32 =match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; print!("You guessed: {}",guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too big"), Ordering::Equal => { println!("Win"); break; } } } }
// Date : 10 Sept 2016 // Author : Vigneshwer extern crate rand;
random_line_split
text_run.rs
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 api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform, LayoutVector2D, RasterPixelScale, DevicePixelScale}; use crate::scene_building::{CreateShadow, IsVisible}; use crate::frame_builder::FrameBuildingState; use crate::glyph_rasterizer::{FontInstance, FontTransform, GlyphKey, FONT_SIZE_LIMIT}; use crate::gpu_cache::GpuCache; use crate::intern; use crate::internal_types::LayoutPrimitiveInfo; use crate::picture::SurfaceInfo; use crate::prim_store::{PrimitiveOpacity, PrimitiveScratchBuffer}; use crate::prim_store::{PrimitiveStore, PrimKeyCommonData, PrimTemplateCommonData}; use crate::renderer::{MAX_VERTEX_TEXTURE_WIDTH}; use crate::resource_cache::{ResourceCache}; use crate::util::{MatrixHelpers}; use crate::prim_store::{InternablePrimitive, PrimitiveInstanceKind}; use crate::spatial_tree::{SpatialTree, SpatialNodeIndex}; use crate::space::SpaceSnapper; use crate::util::PrimaryArc; use std::ops; use std::sync::Arc; use super::storage; /// A run of glyphs, with associated font information. #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, Eq, MallocSizeOf, PartialEq, Hash)] pub struct TextRunKey { pub common: PrimKeyCommonData, pub font: FontInstance, pub glyphs: PrimaryArc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl TextRunKey { pub fn new( info: &LayoutPrimitiveInfo, text_run: TextRun, ) -> Self { TextRunKey { common: info.into(), font: text_run.font, glyphs: PrimaryArc(text_run.glyphs), shadow: text_run.shadow, requested_raster_space: text_run.requested_raster_space, } } } impl intern::InternDebug for TextRunKey {} #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(MallocSizeOf)] pub struct TextRunTemplate { pub common: PrimTemplateCommonData, pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, } impl ops::Deref for TextRunTemplate { type Target = PrimTemplateCommonData; fn deref(&self) -> &Self::Target { &self.common } } impl ops::DerefMut for TextRunTemplate { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.common } } impl From<TextRunKey> for TextRunTemplate { fn from(item: TextRunKey) -> Self { let common = PrimTemplateCommonData::with_key_common(item.common); TextRunTemplate { common, font: item.font, glyphs: item.glyphs.0, } } } impl TextRunTemplate { /// Update the GPU cache for a given primitive template. This may be called multiple /// times per frame, by each primitive reference that refers to this interned /// template. The initial request call to the GPU cache ensures that work is only /// done if the cache entry is invalid (due to first use or eviction). pub fn update( &mut self, frame_state: &mut FrameBuildingState, ) { self.write_prim_gpu_blocks(frame_state); self.opacity = PrimitiveOpacity::translucent(); } fn write_prim_gpu_blocks( &mut self, frame_state: &mut FrameBuildingState, ) { // corresponds to `fetch_glyph` in the shaders if let Some(mut request) = frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle)
// Ensure the last block is added in the case // of an odd number of glyphs. if (self.glyphs.len() & 1)!= 0 { request.push(gpu_block); } assert!(request.current_used_block_num() <= MAX_VERTEX_TEXTURE_WIDTH); } } } pub type TextRunDataHandle = intern::Handle<TextRun>; #[derive(Debug, MallocSizeOf)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct TextRun { pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl intern::Internable for TextRun { type Key = TextRunKey; type StoreData = TextRunTemplate; type InternData = (); const PROFILE_COUNTER: usize = crate::profiler::INTERNED_TEXT_RUNS; } impl InternablePrimitive for TextRun { fn into_key( self, info: &LayoutPrimitiveInfo, ) -> TextRunKey { TextRunKey::new( info, self, ) } fn make_instance_kind( key: TextRunKey, data_handle: TextRunDataHandle, prim_store: &mut PrimitiveStore, reference_frame_relative_offset: LayoutVector2D, ) -> PrimitiveInstanceKind { let run_index = prim_store.text_runs.push(TextRunPrimitive { used_font: key.font.clone(), glyph_keys_range: storage::Range::empty(), reference_frame_relative_offset, snapped_reference_frame_relative_offset: reference_frame_relative_offset, shadow: key.shadow, raster_scale: 1.0, requested_raster_space: key.requested_raster_space, }); PrimitiveInstanceKind::TextRun{ data_handle, run_index } } } impl CreateShadow for TextRun { fn create_shadow( &self, shadow: &Shadow, blur_is_noop: bool, current_raster_space: RasterSpace, ) -> Self { let mut font = FontInstance { color: shadow.color.into(), ..self.font.clone() }; if shadow.blur_radius > 0.0 { font.disable_subpixel_aa(); } let requested_raster_space = if blur_is_noop { current_raster_space } else { RasterSpace::Local(1.0) }; TextRun { font, glyphs: self.glyphs.clone(), shadow: true, requested_raster_space, } } } impl IsVisible for TextRun { fn is_visible(&self) -> bool { self.font.color.a > 0 } } #[derive(Debug)] #[cfg_attr(feature = "capture", derive(Serialize))] pub struct TextRunPrimitive { pub used_font: FontInstance, pub glyph_keys_range: storage::Range<GlyphKey>, pub reference_frame_relative_offset: LayoutVector2D, pub snapped_reference_frame_relative_offset: LayoutVector2D, pub shadow: bool, pub raster_scale: f32, pub requested_raster_space: RasterSpace, } impl TextRunPrimitive { pub fn update_font_instance( &mut self, specified_font: &FontInstance, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, transform: &LayoutToWorldTransform, mut allow_subpixel: bool, raster_space: RasterSpace, spatial_tree: &SpatialTree, ) -> bool { // If local raster space is specified, include that in the scale // of the glyphs that get rasterized. // TODO(gw): Once we support proper local space raster modes, this // will implicitly be part of the device pixel ratio for // the (cached) local space surface, and so this code // will no longer be required. let raster_scale = raster_space.local_scale().unwrap_or(1.0).max(0.001); let dps = surface.device_pixel_scale.0; let font_size = specified_font.size.to_f32_px(); // Small floating point error can accumulate in the raster * device_pixel scale. // Round that to the nearest 100th of a scale factor to remove this error while // still allowing reasonably accurate scale factors when a pinch-zoom is stopped // at a fractional amount. let quantized_scale = (dps * raster_scale * 100.0).round() / 100.0; let mut device_font_size = font_size * quantized_scale; // Check there is a valid transform that doesn't exceed the font size limit. // Ensure the font is supposed to be rasterized in screen-space. // Only support transforms that can be coerced to simple 2D transforms. // Add texture padding to the rasterized glyph buffer when one anticipates // the glyph will need to be scaled when rendered. let (use_subpixel_aa, transform_glyphs, texture_padding, oversized) = if raster_space!= RasterSpace::Screen || transform.has_perspective_component() ||!transform.has_2d_inverse() { (false, false, true, device_font_size > FONT_SIZE_LIMIT) } else if transform.exceeds_2d_scale((FONT_SIZE_LIMIT / device_font_size) as f64) { (false, false, true, true) } else { (true,!transform.is_simple_2d_translation(), false, false) }; let font_transform = if transform_glyphs { // Get the font transform matrix (skew / scale) from the complete transform. // Fold in the device pixel scale. self.raster_scale = 1.0; FontTransform::from(transform) } else { if oversized { // Font sizes larger than the limit need to be scaled, thus can't use subpixels. // In this case we adjust the font size and raster space to ensure // we rasterize at the limit, to minimize the amount of scaling. let limited_raster_scale = FONT_SIZE_LIMIT / (font_size * dps); device_font_size = FONT_SIZE_LIMIT; // Record the raster space the text needs to be snapped in. The original raster // scale would have been too big. self.raster_scale = limited_raster_scale; } else { // Record the raster space the text needs to be snapped in. We may have changed // from RasterSpace::Screen due to a transform with perspective or without a 2d // inverse, or it may have been RasterSpace::Local all along. self.raster_scale = raster_scale; } // Rasterize the glyph without any transform FontTransform::identity() }; // TODO(aosmond): Snapping really ought to happen during scene building // as much as possible. This will allow clips to be already adjusted // based on the snapping requirements of the primitive. This may affect // complex clips that create a different task, and when we rasterize // glyphs without the transform (because the shader doesn't have the // snap offsets to adjust its clip). These rects are fairly conservative // to begin with and do not appear to be causing significant issues at // this time. self.snapped_reference_frame_relative_offset = if transform_glyphs { // Don't touch the reference frame relative offset. We'll let the // shader do the snapping in device pixels. self.reference_frame_relative_offset } else { // TODO(dp): The SurfaceInfo struct needs to be updated to use RasterPixelScale // rather than DevicePixelScale, however this is a large chunk of // work that will be done as a follow up patch. let raster_pixel_scale = RasterPixelScale::new(surface.device_pixel_scale.0); // There may be an animation, so snap the reference frame relative // offset such that it excludes the impact, if any. let snap_to_device = SpaceSnapper::new_with_target( surface.raster_spatial_node_index, spatial_node_index, raster_pixel_scale, spatial_tree, ); snap_to_device.snap_point(&self.reference_frame_relative_offset.to_point()).to_vector() }; let mut flags = specified_font.flags; if transform_glyphs { flags |= FontInstanceFlags::TRANSFORM_GLYPHS; } if texture_padding { flags |= FontInstanceFlags::TEXTURE_PADDING; } // If the transform or device size is different, then the caller of // this method needs to know to rebuild the glyphs. let cache_dirty = self.used_font.transform!= font_transform || self.used_font.size!= device_font_size.into() || self.used_font.flags!= flags; // Construct used font instance from the specified font instance self.used_font = FontInstance { transform: font_transform, size: device_font_size.into(), flags, ..specified_font.clone() }; // If we are using special estimated background subpixel blending, then // we can allow it regardless of what the surface says. allow_subpixel |= self.used_font.bg_color.a!= 0; // If using local space glyphs, we don't want subpixel AA. if!allow_subpixel ||!use_subpixel_aa { self.used_font.disable_subpixel_aa(); // Disable subpixel positioning for oversized glyphs to avoid // thrashing the glyph cache with many subpixel variations of // big glyph textures. A possible subpixel positioning error // is small relative to the maximum font size and thus should // not be very noticeable. if oversized { self.used_font.disable_subpixel_position(); } } cache_dirty } /// Gets the raster space to use when rendering this primitive. /// Usually this would be the requested raster space. However, if /// the primitive's spatial node or one of its ancestors is being pinch zoomed /// then we round it. This prevents us rasterizing glyphs for every minor /// change in zoom level, as that would be too expensive. fn get_raster_space_for_prim( &self, prim_spatial_node_index: SpatialNodeIndex, low_quality_pinch_zoom: bool, device_pixel_scale: DevicePixelScale, spatial_tree: &SpatialTree, ) -> RasterSpace { let prim_spatial_node = spatial_tree.get_spatial_node(prim_spatial_node_index); if prim_spatial_node.is_ancestor_or_self_zooming { if low_quality_pinch_zoom { // In low-quality mode, we set the scale to be 1.0. However, the device-pixel // scale selected for the zoom will be taken into account in the caller to this // function when it's converted from local -> device pixels. Since in this mode // the device-pixel scale is constant during the zoom, this gives the desired // performance while also allowing the scale to be adjusted to a new factor at // the end of a pinch-zoom. RasterSpace::Local(1.0) } else { let root_spatial_node_index = spatial_tree.root_reference_frame_index(); // For high-quality mode, we quantize the exact scale factor as before. However, // we want to _undo_ the effect of the device-pixel scale on the picture cache // tiles (which changes now that they are raster roots). Divide the rounded value // by the device-pixel scale so that the local -> device conversion has no effect. let scale_factors = spatial_tree .get_relative_transform(prim_spatial_node_index, root_spatial_node_index) .scale_factors(); // Round the scale up to the nearest power of 2, but don't exceed 8. let scale = scale_factors.0.max(scale_factors.1).min(8.0).max(1.0); let rounded_up = 2.0f32.powf(scale.log2().ceil()); RasterSpace::Local(rounded_up / device_pixel_scale.0) } } else { // Assume that if we have a RasterSpace::Local, it is frequently changing, in which // case we want to undo the device-pixel scale, as we do above. match self.requested_raster_space { RasterSpace::Local(scale) => RasterSpace::Local(scale / device_pixel_scale.0), RasterSpace::Screen => RasterSpace::Screen, } } } pub fn request_resources( &mut self, prim_offset: LayoutVector2D, specified_font: &FontInstance, glyphs: &[GlyphInstance], transform: &LayoutToWorldTransform, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, allow_subpixel: bool, low_quality_pinch_zoom: bool, resource_cache: &mut ResourceCache, gpu_cache: &mut GpuCache, spatial_tree: &SpatialTree, scratch: &mut PrimitiveScratchBuffer, ) { let raster_space = self.get_raster_space_for_prim( spatial_node_index, low_quality_pinch_zoom, surface.device_pixel_scale, spatial_tree, ); let cache_dirty = self.update_font_instance( specified_font, surface, spatial_node_index, transform, allow_subpixel, raster_space, spatial_tree, ); if self.glyph_keys_range.is_empty() || cache_dirty { let subpx_dir = self.used_font.get_subpx_dir(); let dps = surface.device_pixel_scale.0; let transform = match raster_space { RasterSpace::Local(scale) => FontTransform::new(scale * dps, 0.0, 0.0, scale * dps), RasterSpace::Screen => self.used_font.transform.scale(dps), }; self.glyph_keys_range = scratch.glyph_keys.extend( glyphs.iter().map(|src| { let src_point = src.point + prim_offset; let device_offset = transform.transform(&src_point); GlyphKey::new(src.index, device_offset, subpx_dir) })); } resource_cache.request_glyphs( self.used_font.clone(), &scratch.glyph_keys[self.glyph_keys_range], gpu_cache, ); } } /// These are linux only because FontInstancePlatformOptions varies in size by platform. #[test] #[cfg(target_os = "linux")] fn test_struct_sizes() { use std::mem; // The sizes of these structures are critical for performance on a number of // talos stress tests. If you get a failure here on CI, there's two possibilities: // (a) You made a structure smaller than it currently is. Great work! Update the // test expectations and move on. // (b) You made a structure larger. This is not necessarily a problem, but should only // be done with care, and after checking if talos performance regresses badly. assert_eq!(mem::size_of::<TextRun>(), 64, "TextRun size changed"); assert_eq!(mem::size_of::<TextRunTemplate>(), 80, "TextRunTemplate size changed"); assert_eq!(mem::size_of::<TextRunKey>(), 80, "TextRunKey size changed"); assert_eq!(
{ request.push(ColorF::from(self.font.color).premultiplied()); // this is the only case where we need to provide plain color to GPU let bg_color = ColorF::from(self.font.bg_color); request.push([bg_color.r, bg_color.g, bg_color.b, 1.0]); let mut gpu_block = [0.0; 4]; for (i, src) in self.glyphs.iter().enumerate() { // Two glyphs are packed per GPU block. if (i & 1) == 0 { gpu_block[0] = src.point.x; gpu_block[1] = src.point.y; } else { gpu_block[2] = src.point.x; gpu_block[3] = src.point.y; request.push(gpu_block); } }
conditional_block
text_run.rs
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 api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform, LayoutVector2D, RasterPixelScale, DevicePixelScale}; use crate::scene_building::{CreateShadow, IsVisible}; use crate::frame_builder::FrameBuildingState; use crate::glyph_rasterizer::{FontInstance, FontTransform, GlyphKey, FONT_SIZE_LIMIT}; use crate::gpu_cache::GpuCache; use crate::intern; use crate::internal_types::LayoutPrimitiveInfo; use crate::picture::SurfaceInfo; use crate::prim_store::{PrimitiveOpacity, PrimitiveScratchBuffer}; use crate::prim_store::{PrimitiveStore, PrimKeyCommonData, PrimTemplateCommonData}; use crate::renderer::{MAX_VERTEX_TEXTURE_WIDTH}; use crate::resource_cache::{ResourceCache}; use crate::util::{MatrixHelpers}; use crate::prim_store::{InternablePrimitive, PrimitiveInstanceKind}; use crate::spatial_tree::{SpatialTree, SpatialNodeIndex}; use crate::space::SpaceSnapper; use crate::util::PrimaryArc; use std::ops; use std::sync::Arc; use super::storage; /// A run of glyphs, with associated font information. #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, Eq, MallocSizeOf, PartialEq, Hash)] pub struct TextRunKey { pub common: PrimKeyCommonData, pub font: FontInstance, pub glyphs: PrimaryArc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl TextRunKey { pub fn new( info: &LayoutPrimitiveInfo, text_run: TextRun, ) -> Self { TextRunKey { common: info.into(), font: text_run.font, glyphs: PrimaryArc(text_run.glyphs), shadow: text_run.shadow, requested_raster_space: text_run.requested_raster_space, } } } impl intern::InternDebug for TextRunKey {} #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(MallocSizeOf)] pub struct TextRunTemplate { pub common: PrimTemplateCommonData, pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, } impl ops::Deref for TextRunTemplate { type Target = PrimTemplateCommonData; fn deref(&self) -> &Self::Target { &self.common } } impl ops::DerefMut for TextRunTemplate { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.common } } impl From<TextRunKey> for TextRunTemplate { fn from(item: TextRunKey) -> Self { let common = PrimTemplateCommonData::with_key_common(item.common); TextRunTemplate { common, font: item.font, glyphs: item.glyphs.0, } } } impl TextRunTemplate { /// Update the GPU cache for a given primitive template. This may be called multiple /// times per frame, by each primitive reference that refers to this interned /// template. The initial request call to the GPU cache ensures that work is only /// done if the cache entry is invalid (due to first use or eviction). pub fn update( &mut self, frame_state: &mut FrameBuildingState, ) { self.write_prim_gpu_blocks(frame_state); self.opacity = PrimitiveOpacity::translucent(); } fn write_prim_gpu_blocks( &mut self,
request.push(ColorF::from(self.font.color).premultiplied()); // this is the only case where we need to provide plain color to GPU let bg_color = ColorF::from(self.font.bg_color); request.push([bg_color.r, bg_color.g, bg_color.b, 1.0]); let mut gpu_block = [0.0; 4]; for (i, src) in self.glyphs.iter().enumerate() { // Two glyphs are packed per GPU block. if (i & 1) == 0 { gpu_block[0] = src.point.x; gpu_block[1] = src.point.y; } else { gpu_block[2] = src.point.x; gpu_block[3] = src.point.y; request.push(gpu_block); } } // Ensure the last block is added in the case // of an odd number of glyphs. if (self.glyphs.len() & 1)!= 0 { request.push(gpu_block); } assert!(request.current_used_block_num() <= MAX_VERTEX_TEXTURE_WIDTH); } } } pub type TextRunDataHandle = intern::Handle<TextRun>; #[derive(Debug, MallocSizeOf)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct TextRun { pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl intern::Internable for TextRun { type Key = TextRunKey; type StoreData = TextRunTemplate; type InternData = (); const PROFILE_COUNTER: usize = crate::profiler::INTERNED_TEXT_RUNS; } impl InternablePrimitive for TextRun { fn into_key( self, info: &LayoutPrimitiveInfo, ) -> TextRunKey { TextRunKey::new( info, self, ) } fn make_instance_kind( key: TextRunKey, data_handle: TextRunDataHandle, prim_store: &mut PrimitiveStore, reference_frame_relative_offset: LayoutVector2D, ) -> PrimitiveInstanceKind { let run_index = prim_store.text_runs.push(TextRunPrimitive { used_font: key.font.clone(), glyph_keys_range: storage::Range::empty(), reference_frame_relative_offset, snapped_reference_frame_relative_offset: reference_frame_relative_offset, shadow: key.shadow, raster_scale: 1.0, requested_raster_space: key.requested_raster_space, }); PrimitiveInstanceKind::TextRun{ data_handle, run_index } } } impl CreateShadow for TextRun { fn create_shadow( &self, shadow: &Shadow, blur_is_noop: bool, current_raster_space: RasterSpace, ) -> Self { let mut font = FontInstance { color: shadow.color.into(), ..self.font.clone() }; if shadow.blur_radius > 0.0 { font.disable_subpixel_aa(); } let requested_raster_space = if blur_is_noop { current_raster_space } else { RasterSpace::Local(1.0) }; TextRun { font, glyphs: self.glyphs.clone(), shadow: true, requested_raster_space, } } } impl IsVisible for TextRun { fn is_visible(&self) -> bool { self.font.color.a > 0 } } #[derive(Debug)] #[cfg_attr(feature = "capture", derive(Serialize))] pub struct TextRunPrimitive { pub used_font: FontInstance, pub glyph_keys_range: storage::Range<GlyphKey>, pub reference_frame_relative_offset: LayoutVector2D, pub snapped_reference_frame_relative_offset: LayoutVector2D, pub shadow: bool, pub raster_scale: f32, pub requested_raster_space: RasterSpace, } impl TextRunPrimitive { pub fn update_font_instance( &mut self, specified_font: &FontInstance, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, transform: &LayoutToWorldTransform, mut allow_subpixel: bool, raster_space: RasterSpace, spatial_tree: &SpatialTree, ) -> bool { // If local raster space is specified, include that in the scale // of the glyphs that get rasterized. // TODO(gw): Once we support proper local space raster modes, this // will implicitly be part of the device pixel ratio for // the (cached) local space surface, and so this code // will no longer be required. let raster_scale = raster_space.local_scale().unwrap_or(1.0).max(0.001); let dps = surface.device_pixel_scale.0; let font_size = specified_font.size.to_f32_px(); // Small floating point error can accumulate in the raster * device_pixel scale. // Round that to the nearest 100th of a scale factor to remove this error while // still allowing reasonably accurate scale factors when a pinch-zoom is stopped // at a fractional amount. let quantized_scale = (dps * raster_scale * 100.0).round() / 100.0; let mut device_font_size = font_size * quantized_scale; // Check there is a valid transform that doesn't exceed the font size limit. // Ensure the font is supposed to be rasterized in screen-space. // Only support transforms that can be coerced to simple 2D transforms. // Add texture padding to the rasterized glyph buffer when one anticipates // the glyph will need to be scaled when rendered. let (use_subpixel_aa, transform_glyphs, texture_padding, oversized) = if raster_space!= RasterSpace::Screen || transform.has_perspective_component() ||!transform.has_2d_inverse() { (false, false, true, device_font_size > FONT_SIZE_LIMIT) } else if transform.exceeds_2d_scale((FONT_SIZE_LIMIT / device_font_size) as f64) { (false, false, true, true) } else { (true,!transform.is_simple_2d_translation(), false, false) }; let font_transform = if transform_glyphs { // Get the font transform matrix (skew / scale) from the complete transform. // Fold in the device pixel scale. self.raster_scale = 1.0; FontTransform::from(transform) } else { if oversized { // Font sizes larger than the limit need to be scaled, thus can't use subpixels. // In this case we adjust the font size and raster space to ensure // we rasterize at the limit, to minimize the amount of scaling. let limited_raster_scale = FONT_SIZE_LIMIT / (font_size * dps); device_font_size = FONT_SIZE_LIMIT; // Record the raster space the text needs to be snapped in. The original raster // scale would have been too big. self.raster_scale = limited_raster_scale; } else { // Record the raster space the text needs to be snapped in. We may have changed // from RasterSpace::Screen due to a transform with perspective or without a 2d // inverse, or it may have been RasterSpace::Local all along. self.raster_scale = raster_scale; } // Rasterize the glyph without any transform FontTransform::identity() }; // TODO(aosmond): Snapping really ought to happen during scene building // as much as possible. This will allow clips to be already adjusted // based on the snapping requirements of the primitive. This may affect // complex clips that create a different task, and when we rasterize // glyphs without the transform (because the shader doesn't have the // snap offsets to adjust its clip). These rects are fairly conservative // to begin with and do not appear to be causing significant issues at // this time. self.snapped_reference_frame_relative_offset = if transform_glyphs { // Don't touch the reference frame relative offset. We'll let the // shader do the snapping in device pixels. self.reference_frame_relative_offset } else { // TODO(dp): The SurfaceInfo struct needs to be updated to use RasterPixelScale // rather than DevicePixelScale, however this is a large chunk of // work that will be done as a follow up patch. let raster_pixel_scale = RasterPixelScale::new(surface.device_pixel_scale.0); // There may be an animation, so snap the reference frame relative // offset such that it excludes the impact, if any. let snap_to_device = SpaceSnapper::new_with_target( surface.raster_spatial_node_index, spatial_node_index, raster_pixel_scale, spatial_tree, ); snap_to_device.snap_point(&self.reference_frame_relative_offset.to_point()).to_vector() }; let mut flags = specified_font.flags; if transform_glyphs { flags |= FontInstanceFlags::TRANSFORM_GLYPHS; } if texture_padding { flags |= FontInstanceFlags::TEXTURE_PADDING; } // If the transform or device size is different, then the caller of // this method needs to know to rebuild the glyphs. let cache_dirty = self.used_font.transform!= font_transform || self.used_font.size!= device_font_size.into() || self.used_font.flags!= flags; // Construct used font instance from the specified font instance self.used_font = FontInstance { transform: font_transform, size: device_font_size.into(), flags, ..specified_font.clone() }; // If we are using special estimated background subpixel blending, then // we can allow it regardless of what the surface says. allow_subpixel |= self.used_font.bg_color.a!= 0; // If using local space glyphs, we don't want subpixel AA. if!allow_subpixel ||!use_subpixel_aa { self.used_font.disable_subpixel_aa(); // Disable subpixel positioning for oversized glyphs to avoid // thrashing the glyph cache with many subpixel variations of // big glyph textures. A possible subpixel positioning error // is small relative to the maximum font size and thus should // not be very noticeable. if oversized { self.used_font.disable_subpixel_position(); } } cache_dirty } /// Gets the raster space to use when rendering this primitive. /// Usually this would be the requested raster space. However, if /// the primitive's spatial node or one of its ancestors is being pinch zoomed /// then we round it. This prevents us rasterizing glyphs for every minor /// change in zoom level, as that would be too expensive. fn get_raster_space_for_prim( &self, prim_spatial_node_index: SpatialNodeIndex, low_quality_pinch_zoom: bool, device_pixel_scale: DevicePixelScale, spatial_tree: &SpatialTree, ) -> RasterSpace { let prim_spatial_node = spatial_tree.get_spatial_node(prim_spatial_node_index); if prim_spatial_node.is_ancestor_or_self_zooming { if low_quality_pinch_zoom { // In low-quality mode, we set the scale to be 1.0. However, the device-pixel // scale selected for the zoom will be taken into account in the caller to this // function when it's converted from local -> device pixels. Since in this mode // the device-pixel scale is constant during the zoom, this gives the desired // performance while also allowing the scale to be adjusted to a new factor at // the end of a pinch-zoom. RasterSpace::Local(1.0) } else { let root_spatial_node_index = spatial_tree.root_reference_frame_index(); // For high-quality mode, we quantize the exact scale factor as before. However, // we want to _undo_ the effect of the device-pixel scale on the picture cache // tiles (which changes now that they are raster roots). Divide the rounded value // by the device-pixel scale so that the local -> device conversion has no effect. let scale_factors = spatial_tree .get_relative_transform(prim_spatial_node_index, root_spatial_node_index) .scale_factors(); // Round the scale up to the nearest power of 2, but don't exceed 8. let scale = scale_factors.0.max(scale_factors.1).min(8.0).max(1.0); let rounded_up = 2.0f32.powf(scale.log2().ceil()); RasterSpace::Local(rounded_up / device_pixel_scale.0) } } else { // Assume that if we have a RasterSpace::Local, it is frequently changing, in which // case we want to undo the device-pixel scale, as we do above. match self.requested_raster_space { RasterSpace::Local(scale) => RasterSpace::Local(scale / device_pixel_scale.0), RasterSpace::Screen => RasterSpace::Screen, } } } pub fn request_resources( &mut self, prim_offset: LayoutVector2D, specified_font: &FontInstance, glyphs: &[GlyphInstance], transform: &LayoutToWorldTransform, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, allow_subpixel: bool, low_quality_pinch_zoom: bool, resource_cache: &mut ResourceCache, gpu_cache: &mut GpuCache, spatial_tree: &SpatialTree, scratch: &mut PrimitiveScratchBuffer, ) { let raster_space = self.get_raster_space_for_prim( spatial_node_index, low_quality_pinch_zoom, surface.device_pixel_scale, spatial_tree, ); let cache_dirty = self.update_font_instance( specified_font, surface, spatial_node_index, transform, allow_subpixel, raster_space, spatial_tree, ); if self.glyph_keys_range.is_empty() || cache_dirty { let subpx_dir = self.used_font.get_subpx_dir(); let dps = surface.device_pixel_scale.0; let transform = match raster_space { RasterSpace::Local(scale) => FontTransform::new(scale * dps, 0.0, 0.0, scale * dps), RasterSpace::Screen => self.used_font.transform.scale(dps), }; self.glyph_keys_range = scratch.glyph_keys.extend( glyphs.iter().map(|src| { let src_point = src.point + prim_offset; let device_offset = transform.transform(&src_point); GlyphKey::new(src.index, device_offset, subpx_dir) })); } resource_cache.request_glyphs( self.used_font.clone(), &scratch.glyph_keys[self.glyph_keys_range], gpu_cache, ); } } /// These are linux only because FontInstancePlatformOptions varies in size by platform. #[test] #[cfg(target_os = "linux")] fn test_struct_sizes() { use std::mem; // The sizes of these structures are critical for performance on a number of // talos stress tests. If you get a failure here on CI, there's two possibilities: // (a) You made a structure smaller than it currently is. Great work! Update the // test expectations and move on. // (b) You made a structure larger. This is not necessarily a problem, but should only // be done with care, and after checking if talos performance regresses badly. assert_eq!(mem::size_of::<TextRun>(), 64, "TextRun size changed"); assert_eq!(mem::size_of::<TextRunTemplate>(), 80, "TextRunTemplate size changed"); assert_eq!(mem::size_of::<TextRunKey>(), 80, "TextRunKey size changed"); assert_eq!(mem::
frame_state: &mut FrameBuildingState, ) { // corresponds to `fetch_glyph` in the shaders if let Some(mut request) = frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle) {
random_line_split
text_run.rs
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 api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform, LayoutVector2D, RasterPixelScale, DevicePixelScale}; use crate::scene_building::{CreateShadow, IsVisible}; use crate::frame_builder::FrameBuildingState; use crate::glyph_rasterizer::{FontInstance, FontTransform, GlyphKey, FONT_SIZE_LIMIT}; use crate::gpu_cache::GpuCache; use crate::intern; use crate::internal_types::LayoutPrimitiveInfo; use crate::picture::SurfaceInfo; use crate::prim_store::{PrimitiveOpacity, PrimitiveScratchBuffer}; use crate::prim_store::{PrimitiveStore, PrimKeyCommonData, PrimTemplateCommonData}; use crate::renderer::{MAX_VERTEX_TEXTURE_WIDTH}; use crate::resource_cache::{ResourceCache}; use crate::util::{MatrixHelpers}; use crate::prim_store::{InternablePrimitive, PrimitiveInstanceKind}; use crate::spatial_tree::{SpatialTree, SpatialNodeIndex}; use crate::space::SpaceSnapper; use crate::util::PrimaryArc; use std::ops; use std::sync::Arc; use super::storage; /// A run of glyphs, with associated font information. #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, Eq, MallocSizeOf, PartialEq, Hash)] pub struct TextRunKey { pub common: PrimKeyCommonData, pub font: FontInstance, pub glyphs: PrimaryArc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl TextRunKey { pub fn new( info: &LayoutPrimitiveInfo, text_run: TextRun, ) -> Self { TextRunKey { common: info.into(), font: text_run.font, glyphs: PrimaryArc(text_run.glyphs), shadow: text_run.shadow, requested_raster_space: text_run.requested_raster_space, } } } impl intern::InternDebug for TextRunKey {} #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(MallocSizeOf)] pub struct TextRunTemplate { pub common: PrimTemplateCommonData, pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, } impl ops::Deref for TextRunTemplate { type Target = PrimTemplateCommonData; fn deref(&self) -> &Self::Target { &self.common } } impl ops::DerefMut for TextRunTemplate { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.common } } impl From<TextRunKey> for TextRunTemplate { fn from(item: TextRunKey) -> Self { let common = PrimTemplateCommonData::with_key_common(item.common); TextRunTemplate { common, font: item.font, glyphs: item.glyphs.0, } } } impl TextRunTemplate { /// Update the GPU cache for a given primitive template. This may be called multiple /// times per frame, by each primitive reference that refers to this interned /// template. The initial request call to the GPU cache ensures that work is only /// done if the cache entry is invalid (due to first use or eviction). pub fn update( &mut self, frame_state: &mut FrameBuildingState, ) { self.write_prim_gpu_blocks(frame_state); self.opacity = PrimitiveOpacity::translucent(); } fn write_prim_gpu_blocks( &mut self, frame_state: &mut FrameBuildingState, ) { // corresponds to `fetch_glyph` in the shaders if let Some(mut request) = frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle) { request.push(ColorF::from(self.font.color).premultiplied()); // this is the only case where we need to provide plain color to GPU let bg_color = ColorF::from(self.font.bg_color); request.push([bg_color.r, bg_color.g, bg_color.b, 1.0]); let mut gpu_block = [0.0; 4]; for (i, src) in self.glyphs.iter().enumerate() { // Two glyphs are packed per GPU block. if (i & 1) == 0 { gpu_block[0] = src.point.x; gpu_block[1] = src.point.y; } else { gpu_block[2] = src.point.x; gpu_block[3] = src.point.y; request.push(gpu_block); } } // Ensure the last block is added in the case // of an odd number of glyphs. if (self.glyphs.len() & 1)!= 0 { request.push(gpu_block); } assert!(request.current_used_block_num() <= MAX_VERTEX_TEXTURE_WIDTH); } } } pub type TextRunDataHandle = intern::Handle<TextRun>; #[derive(Debug, MallocSizeOf)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct TextRun { pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl intern::Internable for TextRun { type Key = TextRunKey; type StoreData = TextRunTemplate; type InternData = (); const PROFILE_COUNTER: usize = crate::profiler::INTERNED_TEXT_RUNS; } impl InternablePrimitive for TextRun { fn into_key( self, info: &LayoutPrimitiveInfo, ) -> TextRunKey { TextRunKey::new( info, self, ) } fn make_instance_kind( key: TextRunKey, data_handle: TextRunDataHandle, prim_store: &mut PrimitiveStore, reference_frame_relative_offset: LayoutVector2D, ) -> PrimitiveInstanceKind { let run_index = prim_store.text_runs.push(TextRunPrimitive { used_font: key.font.clone(), glyph_keys_range: storage::Range::empty(), reference_frame_relative_offset, snapped_reference_frame_relative_offset: reference_frame_relative_offset, shadow: key.shadow, raster_scale: 1.0, requested_raster_space: key.requested_raster_space, }); PrimitiveInstanceKind::TextRun{ data_handle, run_index } } } impl CreateShadow for TextRun { fn create_shadow( &self, shadow: &Shadow, blur_is_noop: bool, current_raster_space: RasterSpace, ) -> Self { let mut font = FontInstance { color: shadow.color.into(), ..self.font.clone() }; if shadow.blur_radius > 0.0 { font.disable_subpixel_aa(); } let requested_raster_space = if blur_is_noop { current_raster_space } else { RasterSpace::Local(1.0) }; TextRun { font, glyphs: self.glyphs.clone(), shadow: true, requested_raster_space, } } } impl IsVisible for TextRun { fn is_visible(&self) -> bool { self.font.color.a > 0 } } #[derive(Debug)] #[cfg_attr(feature = "capture", derive(Serialize))] pub struct TextRunPrimitive { pub used_font: FontInstance, pub glyph_keys_range: storage::Range<GlyphKey>, pub reference_frame_relative_offset: LayoutVector2D, pub snapped_reference_frame_relative_offset: LayoutVector2D, pub shadow: bool, pub raster_scale: f32, pub requested_raster_space: RasterSpace, } impl TextRunPrimitive { pub fn update_font_instance( &mut self, specified_font: &FontInstance, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, transform: &LayoutToWorldTransform, mut allow_subpixel: bool, raster_space: RasterSpace, spatial_tree: &SpatialTree, ) -> bool { // If local raster space is specified, include that in the scale // of the glyphs that get rasterized. // TODO(gw): Once we support proper local space raster modes, this // will implicitly be part of the device pixel ratio for // the (cached) local space surface, and so this code // will no longer be required. let raster_scale = raster_space.local_scale().unwrap_or(1.0).max(0.001); let dps = surface.device_pixel_scale.0; let font_size = specified_font.size.to_f32_px(); // Small floating point error can accumulate in the raster * device_pixel scale. // Round that to the nearest 100th of a scale factor to remove this error while // still allowing reasonably accurate scale factors when a pinch-zoom is stopped // at a fractional amount. let quantized_scale = (dps * raster_scale * 100.0).round() / 100.0; let mut device_font_size = font_size * quantized_scale; // Check there is a valid transform that doesn't exceed the font size limit. // Ensure the font is supposed to be rasterized in screen-space. // Only support transforms that can be coerced to simple 2D transforms. // Add texture padding to the rasterized glyph buffer when one anticipates // the glyph will need to be scaled when rendered. let (use_subpixel_aa, transform_glyphs, texture_padding, oversized) = if raster_space!= RasterSpace::Screen || transform.has_perspective_component() ||!transform.has_2d_inverse() { (false, false, true, device_font_size > FONT_SIZE_LIMIT) } else if transform.exceeds_2d_scale((FONT_SIZE_LIMIT / device_font_size) as f64) { (false, false, true, true) } else { (true,!transform.is_simple_2d_translation(), false, false) }; let font_transform = if transform_glyphs { // Get the font transform matrix (skew / scale) from the complete transform. // Fold in the device pixel scale. self.raster_scale = 1.0; FontTransform::from(transform) } else { if oversized { // Font sizes larger than the limit need to be scaled, thus can't use subpixels. // In this case we adjust the font size and raster space to ensure // we rasterize at the limit, to minimize the amount of scaling. let limited_raster_scale = FONT_SIZE_LIMIT / (font_size * dps); device_font_size = FONT_SIZE_LIMIT; // Record the raster space the text needs to be snapped in. The original raster // scale would have been too big. self.raster_scale = limited_raster_scale; } else { // Record the raster space the text needs to be snapped in. We may have changed // from RasterSpace::Screen due to a transform with perspective or without a 2d // inverse, or it may have been RasterSpace::Local all along. self.raster_scale = raster_scale; } // Rasterize the glyph without any transform FontTransform::identity() }; // TODO(aosmond): Snapping really ought to happen during scene building // as much as possible. This will allow clips to be already adjusted // based on the snapping requirements of the primitive. This may affect // complex clips that create a different task, and when we rasterize // glyphs without the transform (because the shader doesn't have the // snap offsets to adjust its clip). These rects are fairly conservative // to begin with and do not appear to be causing significant issues at // this time. self.snapped_reference_frame_relative_offset = if transform_glyphs { // Don't touch the reference frame relative offset. We'll let the // shader do the snapping in device pixels. self.reference_frame_relative_offset } else { // TODO(dp): The SurfaceInfo struct needs to be updated to use RasterPixelScale // rather than DevicePixelScale, however this is a large chunk of // work that will be done as a follow up patch. let raster_pixel_scale = RasterPixelScale::new(surface.device_pixel_scale.0); // There may be an animation, so snap the reference frame relative // offset such that it excludes the impact, if any. let snap_to_device = SpaceSnapper::new_with_target( surface.raster_spatial_node_index, spatial_node_index, raster_pixel_scale, spatial_tree, ); snap_to_device.snap_point(&self.reference_frame_relative_offset.to_point()).to_vector() }; let mut flags = specified_font.flags; if transform_glyphs { flags |= FontInstanceFlags::TRANSFORM_GLYPHS; } if texture_padding { flags |= FontInstanceFlags::TEXTURE_PADDING; } // If the transform or device size is different, then the caller of // this method needs to know to rebuild the glyphs. let cache_dirty = self.used_font.transform!= font_transform || self.used_font.size!= device_font_size.into() || self.used_font.flags!= flags; // Construct used font instance from the specified font instance self.used_font = FontInstance { transform: font_transform, size: device_font_size.into(), flags, ..specified_font.clone() }; // If we are using special estimated background subpixel blending, then // we can allow it regardless of what the surface says. allow_subpixel |= self.used_font.bg_color.a!= 0; // If using local space glyphs, we don't want subpixel AA. if!allow_subpixel ||!use_subpixel_aa { self.used_font.disable_subpixel_aa(); // Disable subpixel positioning for oversized glyphs to avoid // thrashing the glyph cache with many subpixel variations of // big glyph textures. A possible subpixel positioning error // is small relative to the maximum font size and thus should // not be very noticeable. if oversized { self.used_font.disable_subpixel_position(); } } cache_dirty } /// Gets the raster space to use when rendering this primitive. /// Usually this would be the requested raster space. However, if /// the primitive's spatial node or one of its ancestors is being pinch zoomed /// then we round it. This prevents us rasterizing glyphs for every minor /// change in zoom level, as that would be too expensive. fn get_raster_space_for_prim( &self, prim_spatial_node_index: SpatialNodeIndex, low_quality_pinch_zoom: bool, device_pixel_scale: DevicePixelScale, spatial_tree: &SpatialTree, ) -> RasterSpace
.scale_factors(); // Round the scale up to the nearest power of 2, but don't exceed 8. let scale = scale_factors.0.max(scale_factors.1).min(8.0).max(1.0); let rounded_up = 2.0f32.powf(scale.log2().ceil()); RasterSpace::Local(rounded_up / device_pixel_scale.0) } } else { // Assume that if we have a RasterSpace::Local, it is frequently changing, in which // case we want to undo the device-pixel scale, as we do above. match self.requested_raster_space { RasterSpace::Local(scale) => RasterSpace::Local(scale / device_pixel_scale.0), RasterSpace::Screen => RasterSpace::Screen, } } } pub fn request_resources( &mut self, prim_offset: LayoutVector2D, specified_font: &FontInstance, glyphs: &[GlyphInstance], transform: &LayoutToWorldTransform, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, allow_subpixel: bool, low_quality_pinch_zoom: bool, resource_cache: &mut ResourceCache, gpu_cache: &mut GpuCache, spatial_tree: &SpatialTree, scratch: &mut PrimitiveScratchBuffer, ) { let raster_space = self.get_raster_space_for_prim( spatial_node_index, low_quality_pinch_zoom, surface.device_pixel_scale, spatial_tree, ); let cache_dirty = self.update_font_instance( specified_font, surface, spatial_node_index, transform, allow_subpixel, raster_space, spatial_tree, ); if self.glyph_keys_range.is_empty() || cache_dirty { let subpx_dir = self.used_font.get_subpx_dir(); let dps = surface.device_pixel_scale.0; let transform = match raster_space { RasterSpace::Local(scale) => FontTransform::new(scale * dps, 0.0, 0.0, scale * dps), RasterSpace::Screen => self.used_font.transform.scale(dps), }; self.glyph_keys_range = scratch.glyph_keys.extend( glyphs.iter().map(|src| { let src_point = src.point + prim_offset; let device_offset = transform.transform(&src_point); GlyphKey::new(src.index, device_offset, subpx_dir) })); } resource_cache.request_glyphs( self.used_font.clone(), &scratch.glyph_keys[self.glyph_keys_range], gpu_cache, ); } } /// These are linux only because FontInstancePlatformOptions varies in size by platform. #[test] #[cfg(target_os = "linux")] fn test_struct_sizes() { use std::mem; // The sizes of these structures are critical for performance on a number of // talos stress tests. If you get a failure here on CI, there's two possibilities: // (a) You made a structure smaller than it currently is. Great work! Update the // test expectations and move on. // (b) You made a structure larger. This is not necessarily a problem, but should only // be done with care, and after checking if talos performance regresses badly. assert_eq!(mem::size_of::<TextRun>(), 64, "TextRun size changed"); assert_eq!(mem::size_of::<TextRunTemplate>(), 80, "TextRunTemplate size changed"); assert_eq!(mem::size_of::<TextRunKey>(), 80, "TextRunKey size changed"); assert_eq!(
{ let prim_spatial_node = spatial_tree.get_spatial_node(prim_spatial_node_index); if prim_spatial_node.is_ancestor_or_self_zooming { if low_quality_pinch_zoom { // In low-quality mode, we set the scale to be 1.0. However, the device-pixel // scale selected for the zoom will be taken into account in the caller to this // function when it's converted from local -> device pixels. Since in this mode // the device-pixel scale is constant during the zoom, this gives the desired // performance while also allowing the scale to be adjusted to a new factor at // the end of a pinch-zoom. RasterSpace::Local(1.0) } else { let root_spatial_node_index = spatial_tree.root_reference_frame_index(); // For high-quality mode, we quantize the exact scale factor as before. However, // we want to _undo_ the effect of the device-pixel scale on the picture cache // tiles (which changes now that they are raster roots). Divide the rounded value // by the device-pixel scale so that the local -> device conversion has no effect. let scale_factors = spatial_tree .get_relative_transform(prim_spatial_node_index, root_spatial_node_index)
identifier_body
text_run.rs
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 api::{ColorF, FontInstanceFlags, GlyphInstance, RasterSpace, Shadow}; use api::units::{LayoutToWorldTransform, LayoutVector2D, RasterPixelScale, DevicePixelScale}; use crate::scene_building::{CreateShadow, IsVisible}; use crate::frame_builder::FrameBuildingState; use crate::glyph_rasterizer::{FontInstance, FontTransform, GlyphKey, FONT_SIZE_LIMIT}; use crate::gpu_cache::GpuCache; use crate::intern; use crate::internal_types::LayoutPrimitiveInfo; use crate::picture::SurfaceInfo; use crate::prim_store::{PrimitiveOpacity, PrimitiveScratchBuffer}; use crate::prim_store::{PrimitiveStore, PrimKeyCommonData, PrimTemplateCommonData}; use crate::renderer::{MAX_VERTEX_TEXTURE_WIDTH}; use crate::resource_cache::{ResourceCache}; use crate::util::{MatrixHelpers}; use crate::prim_store::{InternablePrimitive, PrimitiveInstanceKind}; use crate::spatial_tree::{SpatialTree, SpatialNodeIndex}; use crate::space::SpaceSnapper; use crate::util::PrimaryArc; use std::ops; use std::sync::Arc; use super::storage; /// A run of glyphs, with associated font information. #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(Debug, Clone, Eq, MallocSizeOf, PartialEq, Hash)] pub struct TextRunKey { pub common: PrimKeyCommonData, pub font: FontInstance, pub glyphs: PrimaryArc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl TextRunKey { pub fn new( info: &LayoutPrimitiveInfo, text_run: TextRun, ) -> Self { TextRunKey { common: info.into(), font: text_run.font, glyphs: PrimaryArc(text_run.glyphs), shadow: text_run.shadow, requested_raster_space: text_run.requested_raster_space, } } } impl intern::InternDebug for TextRunKey {} #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] #[derive(MallocSizeOf)] pub struct TextRunTemplate { pub common: PrimTemplateCommonData, pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, } impl ops::Deref for TextRunTemplate { type Target = PrimTemplateCommonData; fn
(&self) -> &Self::Target { &self.common } } impl ops::DerefMut for TextRunTemplate { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.common } } impl From<TextRunKey> for TextRunTemplate { fn from(item: TextRunKey) -> Self { let common = PrimTemplateCommonData::with_key_common(item.common); TextRunTemplate { common, font: item.font, glyphs: item.glyphs.0, } } } impl TextRunTemplate { /// Update the GPU cache for a given primitive template. This may be called multiple /// times per frame, by each primitive reference that refers to this interned /// template. The initial request call to the GPU cache ensures that work is only /// done if the cache entry is invalid (due to first use or eviction). pub fn update( &mut self, frame_state: &mut FrameBuildingState, ) { self.write_prim_gpu_blocks(frame_state); self.opacity = PrimitiveOpacity::translucent(); } fn write_prim_gpu_blocks( &mut self, frame_state: &mut FrameBuildingState, ) { // corresponds to `fetch_glyph` in the shaders if let Some(mut request) = frame_state.gpu_cache.request(&mut self.common.gpu_cache_handle) { request.push(ColorF::from(self.font.color).premultiplied()); // this is the only case where we need to provide plain color to GPU let bg_color = ColorF::from(self.font.bg_color); request.push([bg_color.r, bg_color.g, bg_color.b, 1.0]); let mut gpu_block = [0.0; 4]; for (i, src) in self.glyphs.iter().enumerate() { // Two glyphs are packed per GPU block. if (i & 1) == 0 { gpu_block[0] = src.point.x; gpu_block[1] = src.point.y; } else { gpu_block[2] = src.point.x; gpu_block[3] = src.point.y; request.push(gpu_block); } } // Ensure the last block is added in the case // of an odd number of glyphs. if (self.glyphs.len() & 1)!= 0 { request.push(gpu_block); } assert!(request.current_used_block_num() <= MAX_VERTEX_TEXTURE_WIDTH); } } } pub type TextRunDataHandle = intern::Handle<TextRun>; #[derive(Debug, MallocSizeOf)] #[cfg_attr(feature = "capture", derive(Serialize))] #[cfg_attr(feature = "replay", derive(Deserialize))] pub struct TextRun { pub font: FontInstance, #[ignore_malloc_size_of = "Measured via PrimaryArc"] pub glyphs: Arc<Vec<GlyphInstance>>, pub shadow: bool, pub requested_raster_space: RasterSpace, } impl intern::Internable for TextRun { type Key = TextRunKey; type StoreData = TextRunTemplate; type InternData = (); const PROFILE_COUNTER: usize = crate::profiler::INTERNED_TEXT_RUNS; } impl InternablePrimitive for TextRun { fn into_key( self, info: &LayoutPrimitiveInfo, ) -> TextRunKey { TextRunKey::new( info, self, ) } fn make_instance_kind( key: TextRunKey, data_handle: TextRunDataHandle, prim_store: &mut PrimitiveStore, reference_frame_relative_offset: LayoutVector2D, ) -> PrimitiveInstanceKind { let run_index = prim_store.text_runs.push(TextRunPrimitive { used_font: key.font.clone(), glyph_keys_range: storage::Range::empty(), reference_frame_relative_offset, snapped_reference_frame_relative_offset: reference_frame_relative_offset, shadow: key.shadow, raster_scale: 1.0, requested_raster_space: key.requested_raster_space, }); PrimitiveInstanceKind::TextRun{ data_handle, run_index } } } impl CreateShadow for TextRun { fn create_shadow( &self, shadow: &Shadow, blur_is_noop: bool, current_raster_space: RasterSpace, ) -> Self { let mut font = FontInstance { color: shadow.color.into(), ..self.font.clone() }; if shadow.blur_radius > 0.0 { font.disable_subpixel_aa(); } let requested_raster_space = if blur_is_noop { current_raster_space } else { RasterSpace::Local(1.0) }; TextRun { font, glyphs: self.glyphs.clone(), shadow: true, requested_raster_space, } } } impl IsVisible for TextRun { fn is_visible(&self) -> bool { self.font.color.a > 0 } } #[derive(Debug)] #[cfg_attr(feature = "capture", derive(Serialize))] pub struct TextRunPrimitive { pub used_font: FontInstance, pub glyph_keys_range: storage::Range<GlyphKey>, pub reference_frame_relative_offset: LayoutVector2D, pub snapped_reference_frame_relative_offset: LayoutVector2D, pub shadow: bool, pub raster_scale: f32, pub requested_raster_space: RasterSpace, } impl TextRunPrimitive { pub fn update_font_instance( &mut self, specified_font: &FontInstance, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, transform: &LayoutToWorldTransform, mut allow_subpixel: bool, raster_space: RasterSpace, spatial_tree: &SpatialTree, ) -> bool { // If local raster space is specified, include that in the scale // of the glyphs that get rasterized. // TODO(gw): Once we support proper local space raster modes, this // will implicitly be part of the device pixel ratio for // the (cached) local space surface, and so this code // will no longer be required. let raster_scale = raster_space.local_scale().unwrap_or(1.0).max(0.001); let dps = surface.device_pixel_scale.0; let font_size = specified_font.size.to_f32_px(); // Small floating point error can accumulate in the raster * device_pixel scale. // Round that to the nearest 100th of a scale factor to remove this error while // still allowing reasonably accurate scale factors when a pinch-zoom is stopped // at a fractional amount. let quantized_scale = (dps * raster_scale * 100.0).round() / 100.0; let mut device_font_size = font_size * quantized_scale; // Check there is a valid transform that doesn't exceed the font size limit. // Ensure the font is supposed to be rasterized in screen-space. // Only support transforms that can be coerced to simple 2D transforms. // Add texture padding to the rasterized glyph buffer when one anticipates // the glyph will need to be scaled when rendered. let (use_subpixel_aa, transform_glyphs, texture_padding, oversized) = if raster_space!= RasterSpace::Screen || transform.has_perspective_component() ||!transform.has_2d_inverse() { (false, false, true, device_font_size > FONT_SIZE_LIMIT) } else if transform.exceeds_2d_scale((FONT_SIZE_LIMIT / device_font_size) as f64) { (false, false, true, true) } else { (true,!transform.is_simple_2d_translation(), false, false) }; let font_transform = if transform_glyphs { // Get the font transform matrix (skew / scale) from the complete transform. // Fold in the device pixel scale. self.raster_scale = 1.0; FontTransform::from(transform) } else { if oversized { // Font sizes larger than the limit need to be scaled, thus can't use subpixels. // In this case we adjust the font size and raster space to ensure // we rasterize at the limit, to minimize the amount of scaling. let limited_raster_scale = FONT_SIZE_LIMIT / (font_size * dps); device_font_size = FONT_SIZE_LIMIT; // Record the raster space the text needs to be snapped in. The original raster // scale would have been too big. self.raster_scale = limited_raster_scale; } else { // Record the raster space the text needs to be snapped in. We may have changed // from RasterSpace::Screen due to a transform with perspective or without a 2d // inverse, or it may have been RasterSpace::Local all along. self.raster_scale = raster_scale; } // Rasterize the glyph without any transform FontTransform::identity() }; // TODO(aosmond): Snapping really ought to happen during scene building // as much as possible. This will allow clips to be already adjusted // based on the snapping requirements of the primitive. This may affect // complex clips that create a different task, and when we rasterize // glyphs without the transform (because the shader doesn't have the // snap offsets to adjust its clip). These rects are fairly conservative // to begin with and do not appear to be causing significant issues at // this time. self.snapped_reference_frame_relative_offset = if transform_glyphs { // Don't touch the reference frame relative offset. We'll let the // shader do the snapping in device pixels. self.reference_frame_relative_offset } else { // TODO(dp): The SurfaceInfo struct needs to be updated to use RasterPixelScale // rather than DevicePixelScale, however this is a large chunk of // work that will be done as a follow up patch. let raster_pixel_scale = RasterPixelScale::new(surface.device_pixel_scale.0); // There may be an animation, so snap the reference frame relative // offset such that it excludes the impact, if any. let snap_to_device = SpaceSnapper::new_with_target( surface.raster_spatial_node_index, spatial_node_index, raster_pixel_scale, spatial_tree, ); snap_to_device.snap_point(&self.reference_frame_relative_offset.to_point()).to_vector() }; let mut flags = specified_font.flags; if transform_glyphs { flags |= FontInstanceFlags::TRANSFORM_GLYPHS; } if texture_padding { flags |= FontInstanceFlags::TEXTURE_PADDING; } // If the transform or device size is different, then the caller of // this method needs to know to rebuild the glyphs. let cache_dirty = self.used_font.transform!= font_transform || self.used_font.size!= device_font_size.into() || self.used_font.flags!= flags; // Construct used font instance from the specified font instance self.used_font = FontInstance { transform: font_transform, size: device_font_size.into(), flags, ..specified_font.clone() }; // If we are using special estimated background subpixel blending, then // we can allow it regardless of what the surface says. allow_subpixel |= self.used_font.bg_color.a!= 0; // If using local space glyphs, we don't want subpixel AA. if!allow_subpixel ||!use_subpixel_aa { self.used_font.disable_subpixel_aa(); // Disable subpixel positioning for oversized glyphs to avoid // thrashing the glyph cache with many subpixel variations of // big glyph textures. A possible subpixel positioning error // is small relative to the maximum font size and thus should // not be very noticeable. if oversized { self.used_font.disable_subpixel_position(); } } cache_dirty } /// Gets the raster space to use when rendering this primitive. /// Usually this would be the requested raster space. However, if /// the primitive's spatial node or one of its ancestors is being pinch zoomed /// then we round it. This prevents us rasterizing glyphs for every minor /// change in zoom level, as that would be too expensive. fn get_raster_space_for_prim( &self, prim_spatial_node_index: SpatialNodeIndex, low_quality_pinch_zoom: bool, device_pixel_scale: DevicePixelScale, spatial_tree: &SpatialTree, ) -> RasterSpace { let prim_spatial_node = spatial_tree.get_spatial_node(prim_spatial_node_index); if prim_spatial_node.is_ancestor_or_self_zooming { if low_quality_pinch_zoom { // In low-quality mode, we set the scale to be 1.0. However, the device-pixel // scale selected for the zoom will be taken into account in the caller to this // function when it's converted from local -> device pixels. Since in this mode // the device-pixel scale is constant during the zoom, this gives the desired // performance while also allowing the scale to be adjusted to a new factor at // the end of a pinch-zoom. RasterSpace::Local(1.0) } else { let root_spatial_node_index = spatial_tree.root_reference_frame_index(); // For high-quality mode, we quantize the exact scale factor as before. However, // we want to _undo_ the effect of the device-pixel scale on the picture cache // tiles (which changes now that they are raster roots). Divide the rounded value // by the device-pixel scale so that the local -> device conversion has no effect. let scale_factors = spatial_tree .get_relative_transform(prim_spatial_node_index, root_spatial_node_index) .scale_factors(); // Round the scale up to the nearest power of 2, but don't exceed 8. let scale = scale_factors.0.max(scale_factors.1).min(8.0).max(1.0); let rounded_up = 2.0f32.powf(scale.log2().ceil()); RasterSpace::Local(rounded_up / device_pixel_scale.0) } } else { // Assume that if we have a RasterSpace::Local, it is frequently changing, in which // case we want to undo the device-pixel scale, as we do above. match self.requested_raster_space { RasterSpace::Local(scale) => RasterSpace::Local(scale / device_pixel_scale.0), RasterSpace::Screen => RasterSpace::Screen, } } } pub fn request_resources( &mut self, prim_offset: LayoutVector2D, specified_font: &FontInstance, glyphs: &[GlyphInstance], transform: &LayoutToWorldTransform, surface: &SurfaceInfo, spatial_node_index: SpatialNodeIndex, allow_subpixel: bool, low_quality_pinch_zoom: bool, resource_cache: &mut ResourceCache, gpu_cache: &mut GpuCache, spatial_tree: &SpatialTree, scratch: &mut PrimitiveScratchBuffer, ) { let raster_space = self.get_raster_space_for_prim( spatial_node_index, low_quality_pinch_zoom, surface.device_pixel_scale, spatial_tree, ); let cache_dirty = self.update_font_instance( specified_font, surface, spatial_node_index, transform, allow_subpixel, raster_space, spatial_tree, ); if self.glyph_keys_range.is_empty() || cache_dirty { let subpx_dir = self.used_font.get_subpx_dir(); let dps = surface.device_pixel_scale.0; let transform = match raster_space { RasterSpace::Local(scale) => FontTransform::new(scale * dps, 0.0, 0.0, scale * dps), RasterSpace::Screen => self.used_font.transform.scale(dps), }; self.glyph_keys_range = scratch.glyph_keys.extend( glyphs.iter().map(|src| { let src_point = src.point + prim_offset; let device_offset = transform.transform(&src_point); GlyphKey::new(src.index, device_offset, subpx_dir) })); } resource_cache.request_glyphs( self.used_font.clone(), &scratch.glyph_keys[self.glyph_keys_range], gpu_cache, ); } } /// These are linux only because FontInstancePlatformOptions varies in size by platform. #[test] #[cfg(target_os = "linux")] fn test_struct_sizes() { use std::mem; // The sizes of these structures are critical for performance on a number of // talos stress tests. If you get a failure here on CI, there's two possibilities: // (a) You made a structure smaller than it currently is. Great work! Update the // test expectations and move on. // (b) You made a structure larger. This is not necessarily a problem, but should only // be done with care, and after checking if talos performance regresses badly. assert_eq!(mem::size_of::<TextRun>(), 64, "TextRun size changed"); assert_eq!(mem::size_of::<TextRunTemplate>(), 80, "TextRunTemplate size changed"); assert_eq!(mem::size_of::<TextRunKey>(), 80, "TextRunKey size changed"); assert_eq!(
deref
identifier_name
keyboard.rs
use serde::Deserialize; use smithay::wayland::seat::Keysym; pub use smithay::{ backend::input::KeyState, wayland::seat::{keysyms as KeySyms, ModifiersState as KeyModifiers}, }; use xkbcommon::xkb; #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub enum KeyModifier { Ctrl, Alt, Shift, Logo, CapsLock, NumLock, } impl std::ops::AddAssign<KeyModifier> for KeyModifiers { fn add_assign(&mut self, rhs: KeyModifier) { match rhs { KeyModifier::Ctrl => self.ctrl = true, KeyModifier::Alt => self.alt = true, KeyModifier::Shift => self.shift = true, KeyModifier::Logo => self.logo = true, KeyModifier::CapsLock => self.caps_lock = true, KeyModifier::NumLock => self.num_lock = true, }; } } impl std::ops::BitOr for KeyModifier { type Output = KeyModifiers; fn bitor(self, rhs: KeyModifier) -> Self::Output { let mut modifiers = self.into(); modifiers += rhs; modifiers } } impl Into<KeyModifiers> for KeyModifier { fn into(self) -> KeyModifiers { let mut modifiers = KeyModifiers { ctrl: false, alt: false, shift: false, caps_lock: false, logo: false, num_lock: false, }; modifiers += self; modifiers } } #[derive(Deserialize)] #[serde(transparent)] struct
(Vec<KeyModifier>); impl From<KeyModifiersDef> for KeyModifiers { fn from(src: KeyModifiersDef) -> Self { src.0.into_iter().fold( KeyModifiers { ctrl: false, alt: false, shift: false, caps_lock: false, logo: false, num_lock: false, }, |mut modis, modi| { modis += modi; modis }, ) } } #[allow(non_snake_case)] fn deserialize_KeyModifiers<'de, D>(deserializer: D) -> Result<KeyModifiers, D::Error> where D: serde::Deserializer<'de>, { KeyModifiersDef::deserialize(deserializer).map(Into::into) } #[allow(non_snake_case)] fn deserialize_Keysym<'de, D>(deserializer: D) -> Result<Keysym, D::Error> where D: serde::Deserializer<'de>, { use serde::de::{Error, Unexpected}; let name = String::deserialize(deserializer)?; //let name = format!("KEY_{}", code); match xkb::keysym_from_name(&name, xkb::KEYSYM_NO_FLAGS) { KeySyms::KEY_NoSymbol => match xkb::keysym_from_name(&name, xkb::KEYSYM_CASE_INSENSITIVE) { KeySyms::KEY_NoSymbol => Err(<D::Error as Error>::invalid_value( Unexpected::Str(&name), &"One of the keysym names of xkbcommon.h without the 'KEY_' prefix", )), x => { slog_scope::warn!( "Key-Binding '{}' only matched case insensitive for {:?}", name, xkb::keysym_get_name(x) ); Ok(x) } }, x => Ok(x), } } /// Describtion of a key combination that might be /// handled by the compositor. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct KeyPattern { /// What modifiers are expected to be pressed alongside the key #[serde(deserialize_with = "deserialize_KeyModifiers")] pub modifiers: KeyModifiers, /// The actual key, that was pressed #[serde(deserialize_with = "deserialize_Keysym")] pub key: u32, } impl KeyPattern { pub fn new(modifiers: impl Into<KeyModifiers>, key: u32) -> KeyPattern { KeyPattern { modifiers: modifiers.into(), key, } } }
KeyModifiersDef
identifier_name
keyboard.rs
use serde::Deserialize; use smithay::wayland::seat::Keysym; pub use smithay::{ backend::input::KeyState, wayland::seat::{keysyms as KeySyms, ModifiersState as KeyModifiers}, }; use xkbcommon::xkb; #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub enum KeyModifier { Ctrl, Alt, Shift, Logo, CapsLock, NumLock, } impl std::ops::AddAssign<KeyModifier> for KeyModifiers { fn add_assign(&mut self, rhs: KeyModifier) { match rhs { KeyModifier::Ctrl => self.ctrl = true, KeyModifier::Alt => self.alt = true, KeyModifier::Shift => self.shift = true, KeyModifier::Logo => self.logo = true, KeyModifier::CapsLock => self.caps_lock = true, KeyModifier::NumLock => self.num_lock = true, }; } } impl std::ops::BitOr for KeyModifier { type Output = KeyModifiers; fn bitor(self, rhs: KeyModifier) -> Self::Output { let mut modifiers = self.into(); modifiers += rhs; modifiers } } impl Into<KeyModifiers> for KeyModifier { fn into(self) -> KeyModifiers { let mut modifiers = KeyModifiers { ctrl: false, alt: false, shift: false, caps_lock: false, logo: false, num_lock: false, }; modifiers += self; modifiers } } #[derive(Deserialize)] #[serde(transparent)] struct KeyModifiersDef(Vec<KeyModifier>); impl From<KeyModifiersDef> for KeyModifiers { fn from(src: KeyModifiersDef) -> Self { src.0.into_iter().fold( KeyModifiers { ctrl: false, alt: false, shift: false, caps_lock: false, logo: false, num_lock: false, }, |mut modis, modi| { modis += modi; modis }, ) } } #[allow(non_snake_case)] fn deserialize_KeyModifiers<'de, D>(deserializer: D) -> Result<KeyModifiers, D::Error> where D: serde::Deserializer<'de>, { KeyModifiersDef::deserialize(deserializer).map(Into::into) } #[allow(non_snake_case)] fn deserialize_Keysym<'de, D>(deserializer: D) -> Result<Keysym, D::Error> where D: serde::Deserializer<'de>, {
match xkb::keysym_from_name(&name, xkb::KEYSYM_NO_FLAGS) { KeySyms::KEY_NoSymbol => match xkb::keysym_from_name(&name, xkb::KEYSYM_CASE_INSENSITIVE) { KeySyms::KEY_NoSymbol => Err(<D::Error as Error>::invalid_value( Unexpected::Str(&name), &"One of the keysym names of xkbcommon.h without the 'KEY_' prefix", )), x => { slog_scope::warn!( "Key-Binding '{}' only matched case insensitive for {:?}", name, xkb::keysym_get_name(x) ); Ok(x) } }, x => Ok(x), } } /// Describtion of a key combination that might be /// handled by the compositor. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct KeyPattern { /// What modifiers are expected to be pressed alongside the key #[serde(deserialize_with = "deserialize_KeyModifiers")] pub modifiers: KeyModifiers, /// The actual key, that was pressed #[serde(deserialize_with = "deserialize_Keysym")] pub key: u32, } impl KeyPattern { pub fn new(modifiers: impl Into<KeyModifiers>, key: u32) -> KeyPattern { KeyPattern { modifiers: modifiers.into(), key, } } }
use serde::de::{Error, Unexpected}; let name = String::deserialize(deserializer)?; //let name = format!("KEY_{}", code);
random_line_split
combaseapi.rs
// Copyright © 2016 winapi-rs developers // 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. //! Base Component Object Model defintions. use shared::basetsd::UINT64; use shared::minwindef::DWORD; use shared::wtypesbase::{ CLSCTX, CLSCTX_INPROC_HANDLER, CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, }; use um::objidlbase::LPMALLOC; use um::winnt::HRESULT; pub const CLSCTX_INPROC: CLSCTX = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER; pub const CLSCTX_ALL: CLSCTX = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER; pub const CLSCTX_SERVER: CLSCTX = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER; ENUM!{enum REGCLS { REGCLS_SINGLEUSE = 0, REGCLS_MULTIPLEUSE = 1, REGCLS_MULTI_SEPARATE = 2, REGCLS_SUSPENDED = 4, REGCLS_SURROGATE = 8, REGCLS_AGILE = 0x10, }} ENUM!{enum COINITBASE { COINITBASE_MULTITHREADED = 0x0, }} EXTERN!{stdcall fn CoGetMalloc(
ppMalloc: *mut LPMALLOC ) -> HRESULT} STRUCT!{struct ServerInformation { dwServerPid: DWORD, dwServerTid: DWORD, ui64ServerAddress: UINT64, }} pub type PServerInformation = *mut ServerInformation; DECLARE_HANDLE!(CO_MTA_USAGE_COOKIE, CO_MTA_USAGE_COOKIE__);
dwMemContext: DWORD,
random_line_split
error.rs
use std::io; use std::fmt; use std::error::Error; /// Result type for using with [`EmuleadError`]. pub type EmuleadResult<T> = Result<T, EmuleadError>; /// Error type using for the project errors. #[derive(Debug)] pub enum EmuleadError { /// IO Error Io(io::Error), /// Rotate bytes error used in [`network::rotate_bytes_right`] RotateBytes(usize) } impl fmt::Display for EmuleadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &EmuleadError::Io(ref err) => write!(f, "IO error: {}", err), err => write!(f, "Error: {}", err.description()) } } } impl Error for EmuleadError { fn description(&self) -> &str { match *self { EmuleadError::Io(ref err) => err.description(), EmuleadError::RotateBytes(_) => "Rotate shift must be in 0-8 bits." } } fn cause(&self) -> Option<&Error> { match *self { EmuleadError::Io(ref err) => Some(err), _ => None } } } impl From<io::Error> for EmuleadError {
} }
fn from(err: io::Error) -> EmuleadError { EmuleadError::Io(err)
random_line_split
error.rs
use std::io; use std::fmt; use std::error::Error; /// Result type for using with [`EmuleadError`]. pub type EmuleadResult<T> = Result<T, EmuleadError>; /// Error type using for the project errors. #[derive(Debug)] pub enum EmuleadError { /// IO Error Io(io::Error), /// Rotate bytes error used in [`network::rotate_bytes_right`] RotateBytes(usize) } impl fmt::Display for EmuleadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &EmuleadError::Io(ref err) => write!(f, "IO error: {}", err), err => write!(f, "Error: {}", err.description()) } } } impl Error for EmuleadError { fn description(&self) -> &str { match *self { EmuleadError::Io(ref err) => err.description(), EmuleadError::RotateBytes(_) => "Rotate shift must be in 0-8 bits." } } fn
(&self) -> Option<&Error> { match *self { EmuleadError::Io(ref err) => Some(err), _ => None } } } impl From<io::Error> for EmuleadError { fn from(err: io::Error) -> EmuleadError { EmuleadError::Io(err) } }
cause
identifier_name
error.rs
use std::io; use std::fmt; use std::error::Error; /// Result type for using with [`EmuleadError`]. pub type EmuleadResult<T> = Result<T, EmuleadError>; /// Error type using for the project errors. #[derive(Debug)] pub enum EmuleadError { /// IO Error Io(io::Error), /// Rotate bytes error used in [`network::rotate_bytes_right`] RotateBytes(usize) } impl fmt::Display for EmuleadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &EmuleadError::Io(ref err) => write!(f, "IO error: {}", err), err => write!(f, "Error: {}", err.description()) } } } impl Error for EmuleadError { fn description(&self) -> &str { match *self { EmuleadError::Io(ref err) => err.description(), EmuleadError::RotateBytes(_) => "Rotate shift must be in 0-8 bits." } } fn cause(&self) -> Option<&Error>
} impl From<io::Error> for EmuleadError { fn from(err: io::Error) -> EmuleadError { EmuleadError::Io(err) } }
{ match *self { EmuleadError::Io(ref err) => Some(err), _ => None } }
identifier_body
middlewares.rs
use config::Config; use db; use hyper::header::UserAgent; use hyper::method::Method; use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use nickel::status::StatusCode; use plugin::Extensible; use r2d2::{Config as PoolConfig, Pool}; use r2d2_postgres::{PostgresConnectionManager as Manager, TlsMode}; use std::error::Error; use std::io::Write; use std::str; use std::sync::Arc; use super::extensions::{IpAddrExtension, PostgresExtension}; use typemap::Key; use uuid::Uuid; pub struct ConfigMiddleware { config: Arc<Config>, } impl ConfigMiddleware { pub fn new(config: Arc<Config>) -> ConfigMiddleware { ConfigMiddleware { config: config } } } impl Key for ConfigMiddleware { type Value = Arc<Config>; } impl<D> Middleware<D> for ConfigMiddleware { fn
<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<ConfigMiddleware>(self.config.clone()); Ok(Continue(rep)) } } pub struct PostgresMiddleware { pub pool: Pool<Manager>, } impl PostgresMiddleware { pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = Manager::new(db_url, TlsMode::None)?; let pool = Pool::new(PoolConfig::default(), manager)?; Ok(PostgresMiddleware { pool: pool }) } } impl Key for PostgresMiddleware { type Value = Pool<Manager>; } impl<D> Middleware<D> for PostgresMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } pub struct AuthMiddleware; impl<D> Middleware<D> for AuthMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { let (is_create_token, is_exists_token, is_api) = req.path_without_query().map(|p| ( p == "/api/tokens", p.starts_with("/api/tokens/"), p.starts_with("/api")) ).unwrap_or((false, false, false)); if (is_create_token && req.origin.method == Method::Post) || (is_exists_token && req.origin.method == Method::Head) ||!is_api { Ok(Continue(res)) } else if match req.origin.headers.get_raw("x-auth-token") { Some(header) if header.len() > 0 => { let value = try_with!(res, str::from_utf8(&header[0]).map_err(|err| (StatusCode::BadRequest, err))); let value = try_with!(res, value.parse::<Uuid>().map_err(|err| (StatusCode::BadRequest, err))); let conn = try_with!(res, req.pg_conn()); let ip = req.ip_addr(); let user_agent = req.origin.headers.get::<UserAgent>(); try_with!(res, db::tokens::exists( &*conn, &value, &format!("{}", ip), user_agent.map(|h| &h.0).unwrap_or(&String::new()) ).map_err(|err| (StatusCode::InternalServerError, err))) } _ => false, } { Ok(Continue(res)) } else { res.set(StatusCode::Forbidden); res.set(MediaType::Json); let mut stream = res.start()?; if let Err(err) = stream.write_all(r#"{"data": "Access denied", "success": false}"#.as_bytes()) { stream.bail(format!("[AuthMiddleware] Unable to halt request: {}", err)) } else { Ok(Halt(stream)) } } } }
invoke
identifier_name
middlewares.rs
use config::Config; use db; use hyper::header::UserAgent; use hyper::method::Method; use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use nickel::status::StatusCode; use plugin::Extensible; use r2d2::{Config as PoolConfig, Pool}; use r2d2_postgres::{PostgresConnectionManager as Manager, TlsMode}; use std::error::Error; use std::io::Write; use std::str; use std::sync::Arc; use super::extensions::{IpAddrExtension, PostgresExtension}; use typemap::Key; use uuid::Uuid; pub struct ConfigMiddleware { config: Arc<Config>, } impl ConfigMiddleware { pub fn new(config: Arc<Config>) -> ConfigMiddleware { ConfigMiddleware { config: config } } } impl Key for ConfigMiddleware { type Value = Arc<Config>; } impl<D> Middleware<D> for ConfigMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<ConfigMiddleware>(self.config.clone()); Ok(Continue(rep)) } } pub struct PostgresMiddleware { pub pool: Pool<Manager>, } impl PostgresMiddleware { pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = Manager::new(db_url, TlsMode::None)?; let pool = Pool::new(PoolConfig::default(), manager)?; Ok(PostgresMiddleware { pool: pool }) } } impl Key for PostgresMiddleware { type Value = Pool<Manager>; } impl<D> Middleware<D> for PostgresMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } pub struct AuthMiddleware; impl<D> Middleware<D> for AuthMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { let (is_create_token, is_exists_token, is_api) = req.path_without_query().map(|p| ( p == "/api/tokens", p.starts_with("/api/tokens/"), p.starts_with("/api")) ).unwrap_or((false, false, false)); if (is_create_token && req.origin.method == Method::Post) || (is_exists_token && req.origin.method == Method::Head) ||!is_api { Ok(Continue(res)) } else if match req.origin.headers.get_raw("x-auth-token") { Some(header) if header.len() > 0 => { let value = try_with!(res, str::from_utf8(&header[0]).map_err(|err| (StatusCode::BadRequest, err))); let value = try_with!(res, value.parse::<Uuid>().map_err(|err| (StatusCode::BadRequest, err))); let conn = try_with!(res, req.pg_conn()); let ip = req.ip_addr(); let user_agent = req.origin.headers.get::<UserAgent>(); try_with!(res, db::tokens::exists( &*conn, &value, &format!("{}", ip), user_agent.map(|h| &h.0).unwrap_or(&String::new()) ).map_err(|err| (StatusCode::InternalServerError, err))) } _ => false, } { Ok(Continue(res)) } else
} }
{ res.set(StatusCode::Forbidden); res.set(MediaType::Json); let mut stream = res.start()?; if let Err(err) = stream.write_all(r#"{"data": "Access denied", "success": false}"#.as_bytes()) { stream.bail(format!("[AuthMiddleware] Unable to halt request: {}", err)) } else { Ok(Halt(stream)) } }
conditional_block
middlewares.rs
use config::Config; use db; use hyper::header::UserAgent; use hyper::method::Method; use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use nickel::status::StatusCode; use plugin::Extensible; use r2d2::{Config as PoolConfig, Pool}; use r2d2_postgres::{PostgresConnectionManager as Manager, TlsMode}; use std::error::Error; use std::io::Write; use std::str; use std::sync::Arc; use super::extensions::{IpAddrExtension, PostgresExtension}; use typemap::Key; use uuid::Uuid; pub struct ConfigMiddleware { config: Arc<Config>, } impl ConfigMiddleware { pub fn new(config: Arc<Config>) -> ConfigMiddleware
} impl Key for ConfigMiddleware { type Value = Arc<Config>; } impl<D> Middleware<D> for ConfigMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<ConfigMiddleware>(self.config.clone()); Ok(Continue(rep)) } } pub struct PostgresMiddleware { pub pool: Pool<Manager>, } impl PostgresMiddleware { pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = Manager::new(db_url, TlsMode::None)?; let pool = Pool::new(PoolConfig::default(), manager)?; Ok(PostgresMiddleware { pool: pool }) } } impl Key for PostgresMiddleware { type Value = Pool<Manager>; } impl<D> Middleware<D> for PostgresMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } pub struct AuthMiddleware; impl<D> Middleware<D> for AuthMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { let (is_create_token, is_exists_token, is_api) = req.path_without_query().map(|p| ( p == "/api/tokens", p.starts_with("/api/tokens/"), p.starts_with("/api")) ).unwrap_or((false, false, false)); if (is_create_token && req.origin.method == Method::Post) || (is_exists_token && req.origin.method == Method::Head) ||!is_api { Ok(Continue(res)) } else if match req.origin.headers.get_raw("x-auth-token") { Some(header) if header.len() > 0 => { let value = try_with!(res, str::from_utf8(&header[0]).map_err(|err| (StatusCode::BadRequest, err))); let value = try_with!(res, value.parse::<Uuid>().map_err(|err| (StatusCode::BadRequest, err))); let conn = try_with!(res, req.pg_conn()); let ip = req.ip_addr(); let user_agent = req.origin.headers.get::<UserAgent>(); try_with!(res, db::tokens::exists( &*conn, &value, &format!("{}", ip), user_agent.map(|h| &h.0).unwrap_or(&String::new()) ).map_err(|err| (StatusCode::InternalServerError, err))) } _ => false, } { Ok(Continue(res)) } else { res.set(StatusCode::Forbidden); res.set(MediaType::Json); let mut stream = res.start()?; if let Err(err) = stream.write_all(r#"{"data": "Access denied", "success": false}"#.as_bytes()) { stream.bail(format!("[AuthMiddleware] Unable to halt request: {}", err)) } else { Ok(Halt(stream)) } } } }
{ ConfigMiddleware { config: config } }
identifier_body
middlewares.rs
use config::Config; use db; use hyper::header::UserAgent; use hyper::method::Method; use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response}; use nickel::status::StatusCode; use plugin::Extensible; use r2d2::{Config as PoolConfig, Pool}; use r2d2_postgres::{PostgresConnectionManager as Manager, TlsMode}; use std::error::Error; use std::io::Write; use std::str; use std::sync::Arc; use super::extensions::{IpAddrExtension, PostgresExtension}; use typemap::Key; use uuid::Uuid; pub struct ConfigMiddleware { config: Arc<Config>, } impl ConfigMiddleware { pub fn new(config: Arc<Config>) -> ConfigMiddleware { ConfigMiddleware { config: config } } } impl Key for ConfigMiddleware { type Value = Arc<Config>; } impl<D> Middleware<D> for ConfigMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<ConfigMiddleware>(self.config.clone()); Ok(Continue(rep)) } } pub struct PostgresMiddleware { pub pool: Pool<Manager>, } impl PostgresMiddleware { pub fn new(db_url: &str) -> Result<PostgresMiddleware, Box<Error>> { let manager = Manager::new(db_url, TlsMode::None)?; let pool = Pool::new(PoolConfig::default(), manager)?; Ok(PostgresMiddleware { pool: pool }) } } impl Key for PostgresMiddleware { type Value = Pool<Manager>; } impl<D> Middleware<D> for PostgresMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } pub struct AuthMiddleware; impl<D> Middleware<D> for AuthMiddleware { fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, mut res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { let (is_create_token, is_exists_token, is_api) = req.path_without_query().map(|p| ( p == "/api/tokens", p.starts_with("/api/tokens/"), p.starts_with("/api")) ).unwrap_or((false, false, false)); if (is_create_token && req.origin.method == Method::Post) || (is_exists_token && req.origin.method == Method::Head) ||!is_api { Ok(Continue(res)) } else if match req.origin.headers.get_raw("x-auth-token") { Some(header) if header.len() > 0 => { let value = try_with!(res, str::from_utf8(&header[0]).map_err(|err| (StatusCode::BadRequest, err))); let value = try_with!(res, value.parse::<Uuid>().map_err(|err| (StatusCode::BadRequest, err))); let conn = try_with!(res, req.pg_conn()); let ip = req.ip_addr(); let user_agent = req.origin.headers.get::<UserAgent>(); try_with!(res, db::tokens::exists( &*conn, &value, &format!("{}", ip), user_agent.map(|h| &h.0).unwrap_or(&String::new()) ).map_err(|err| (StatusCode::InternalServerError, err)))
} { Ok(Continue(res)) } else { res.set(StatusCode::Forbidden); res.set(MediaType::Json); let mut stream = res.start()?; if let Err(err) = stream.write_all(r#"{"data": "Access denied", "success": false}"#.as_bytes()) { stream.bail(format!("[AuthMiddleware] Unable to halt request: {}", err)) } else { Ok(Halt(stream)) } } } }
} _ => false,
random_line_split
version.rs
use std::str::FromStr; use cargo_edit::VersionExt; use crate::errors::*; #[derive(Clone, Debug)] pub enum TargetVersion { Relative(BumpLevel), Absolute(semver::Version), } impl TargetVersion { pub fn bump( &self, current: &semver::Version, metadata: Option<&str>, ) -> CargoResult<Option<semver::Version>> { match self { TargetVersion::Relative(bump_level) => { let mut potential_version = current.to_owned(); bump_level.bump_version(&mut potential_version, metadata)?; if potential_version!= *current { let version = potential_version; Ok(Some(version)) } else { Ok(None) } } TargetVersion::Absolute(version) => { if current < version { let mut version = version.clone(); if version.build.is_empty() { if let Some(metadata) = metadata { version.build = semver::BuildMetadata::new(metadata)?; } else { version.build = current.build.clone(); } } Ok(Some(version)) } else if current == version { Ok(None) } else { Err(version_downgrade_err(current, version)) } } } } } impl Default for TargetVersion { fn default() -> Self
} #[derive(Debug, Clone, Copy)] pub enum BumpLevel { Major, Minor, Patch, /// Strip all pre-release flags Release, Rc, Beta, Alpha, } impl BumpLevel { pub fn variants() -> &'static [&'static str] { &["major", "minor", "patch", "release", "rc", "beta", "alpha"] } } impl FromStr for BumpLevel { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "major" => Ok(BumpLevel::Major), "minor" => Ok(BumpLevel::Minor), "patch" => Ok(BumpLevel::Patch), "release" => Ok(BumpLevel::Release), "rc" => Ok(BumpLevel::Rc), "beta" => Ok(BumpLevel::Beta), "alpha" => Ok(BumpLevel::Alpha), _ => Err(String::from( "[valid values: major, minor, patch, rc, beta, alpha]", )), } } } impl BumpLevel { pub fn bump_version( self, version: &mut semver::Version, metadata: Option<&str>, ) -> CargoResult<()> { match self { BumpLevel::Major => { version.increment_major(); } BumpLevel::Minor => { version.increment_minor(); } BumpLevel::Patch => { if!version.is_prerelease() { version.increment_patch(); } else { version.pre = semver::Prerelease::EMPTY; } } BumpLevel::Release => { if version.is_prerelease() { version.pre = semver::Prerelease::EMPTY; } } BumpLevel::Rc => { version.increment_rc()?; } BumpLevel::Beta => { version.increment_beta()?; } BumpLevel::Alpha => { version.increment_alpha()?; } }; if let Some(metadata) = metadata { version.metadata(metadata)?; } Ok(()) } }
{ TargetVersion::Relative(BumpLevel::Release) }
identifier_body
version.rs
use std::str::FromStr; use cargo_edit::VersionExt; use crate::errors::*; #[derive(Clone, Debug)] pub enum TargetVersion { Relative(BumpLevel), Absolute(semver::Version), } impl TargetVersion { pub fn bump( &self, current: &semver::Version, metadata: Option<&str>, ) -> CargoResult<Option<semver::Version>> { match self { TargetVersion::Relative(bump_level) => { let mut potential_version = current.to_owned(); bump_level.bump_version(&mut potential_version, metadata)?; if potential_version!= *current { let version = potential_version; Ok(Some(version)) } else { Ok(None) } } TargetVersion::Absolute(version) => { if current < version { let mut version = version.clone(); if version.build.is_empty() { if let Some(metadata) = metadata { version.build = semver::BuildMetadata::new(metadata)?; } else { version.build = current.build.clone(); } } Ok(Some(version)) } else if current == version { Ok(None) } else { Err(version_downgrade_err(current, version)) } } } } } impl Default for TargetVersion { fn default() -> Self { TargetVersion::Relative(BumpLevel::Release) } } #[derive(Debug, Clone, Copy)] pub enum BumpLevel { Major, Minor, Patch, /// Strip all pre-release flags Release, Rc, Beta, Alpha, } impl BumpLevel { pub fn variants() -> &'static [&'static str] { &["major", "minor", "patch", "release", "rc", "beta", "alpha"] } } impl FromStr for BumpLevel { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "major" => Ok(BumpLevel::Major), "minor" => Ok(BumpLevel::Minor), "patch" => Ok(BumpLevel::Patch), "release" => Ok(BumpLevel::Release), "rc" => Ok(BumpLevel::Rc), "beta" => Ok(BumpLevel::Beta), "alpha" => Ok(BumpLevel::Alpha), _ => Err(String::from( "[valid values: major, minor, patch, rc, beta, alpha]", )), } } } impl BumpLevel { pub fn bump_version( self, version: &mut semver::Version, metadata: Option<&str>, ) -> CargoResult<()> { match self { BumpLevel::Major => { version.increment_major(); } BumpLevel::Minor => { version.increment_minor(); } BumpLevel::Patch => { if!version.is_prerelease() { version.increment_patch(); } else { version.pre = semver::Prerelease::EMPTY; } } BumpLevel::Release => { if version.is_prerelease() { version.pre = semver::Prerelease::EMPTY; } } BumpLevel::Rc => { version.increment_rc()?;
version.increment_alpha()?; } }; if let Some(metadata) = metadata { version.metadata(metadata)?; } Ok(()) } }
} BumpLevel::Beta => { version.increment_beta()?; } BumpLevel::Alpha => {
random_line_split
version.rs
use std::str::FromStr; use cargo_edit::VersionExt; use crate::errors::*; #[derive(Clone, Debug)] pub enum TargetVersion { Relative(BumpLevel), Absolute(semver::Version), } impl TargetVersion { pub fn bump( &self, current: &semver::Version, metadata: Option<&str>, ) -> CargoResult<Option<semver::Version>> { match self { TargetVersion::Relative(bump_level) => { let mut potential_version = current.to_owned(); bump_level.bump_version(&mut potential_version, metadata)?; if potential_version!= *current { let version = potential_version; Ok(Some(version)) } else { Ok(None) } } TargetVersion::Absolute(version) => { if current < version { let mut version = version.clone(); if version.build.is_empty() { if let Some(metadata) = metadata { version.build = semver::BuildMetadata::new(metadata)?; } else { version.build = current.build.clone(); } } Ok(Some(version)) } else if current == version { Ok(None) } else { Err(version_downgrade_err(current, version)) } } } } } impl Default for TargetVersion { fn default() -> Self { TargetVersion::Relative(BumpLevel::Release) } } #[derive(Debug, Clone, Copy)] pub enum BumpLevel { Major, Minor, Patch, /// Strip all pre-release flags Release, Rc, Beta, Alpha, } impl BumpLevel { pub fn variants() -> &'static [&'static str] { &["major", "minor", "patch", "release", "rc", "beta", "alpha"] } } impl FromStr for BumpLevel { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "major" => Ok(BumpLevel::Major), "minor" => Ok(BumpLevel::Minor), "patch" => Ok(BumpLevel::Patch), "release" => Ok(BumpLevel::Release), "rc" => Ok(BumpLevel::Rc), "beta" => Ok(BumpLevel::Beta), "alpha" => Ok(BumpLevel::Alpha), _ => Err(String::from( "[valid values: major, minor, patch, rc, beta, alpha]", )), } } } impl BumpLevel { pub fn
( self, version: &mut semver::Version, metadata: Option<&str>, ) -> CargoResult<()> { match self { BumpLevel::Major => { version.increment_major(); } BumpLevel::Minor => { version.increment_minor(); } BumpLevel::Patch => { if!version.is_prerelease() { version.increment_patch(); } else { version.pre = semver::Prerelease::EMPTY; } } BumpLevel::Release => { if version.is_prerelease() { version.pre = semver::Prerelease::EMPTY; } } BumpLevel::Rc => { version.increment_rc()?; } BumpLevel::Beta => { version.increment_beta()?; } BumpLevel::Alpha => { version.increment_alpha()?; } }; if let Some(metadata) = metadata { version.metadata(metadata)?; } Ok(()) } }
bump_version
identifier_name
filetable.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::Selector; use cell::RefCell; use col::Vec; use core::{fmt, mem}; use com::{VecSink, SliceSource}; use dtu::EpId; use errors::{Code, Error}; use io::Serial; use rc::Rc; use serialize::Sink; use vfs::{File, FileRef, GenericFile}; use vpe::VPE; pub type Fd = usize; const MAX_EPS: usize = 4; pub const MAX_FILES: usize = 32; pub type FileHandle = Rc<RefCell<File>>; struct FileEP { fd: Fd, ep: EpId, } #[derive(Default)] pub struct FileTable { file_ep_victim: usize, file_ep_count: usize, file_eps: [Option<FileEP>; MAX_EPS], files: [Option<FileHandle>; MAX_FILES], } impl FileTable { pub fn add(&mut self, file: FileHandle) -> Result<FileRef, Error> { self.alloc(file.clone()).map(|fd| FileRef::new(file, fd)) } pub fn alloc(&mut self, file: FileHandle) -> Result<Fd, Error> { for fd in 0..MAX_FILES { if self.files[fd].is_none() { self.set(fd, file); return Ok(fd); } } Err(Error::new(Code::NoSpace)) } pub fn get(&self, fd: Fd) -> Option<FileHandle> { match self.files[fd] { Some(ref f) => Some(f.clone()), None => None, } } pub fn set(&mut self, fd: Fd, file: FileHandle) { file.borrow_mut().set_fd(fd); self.files[fd] = Some(file); } pub fn remove(&mut self, fd: Fd) { let find_file_ep = |files: &[Option<FileEP>], fd| -> Option<usize> { for i in 0..MAX_EPS { if let Some(ref fep) = files[i] { if fep.fd == fd { return Some(i); } } } None }; if let Some(ref mut f) = mem::replace(&mut self.files[fd], None) { f.borrow_mut().close(); // remove from multiplexing table if let Some(idx) = find_file_ep(&self.file_eps, fd) { log!(FILES, "FileEPs[{}] = --", idx); self.file_eps[idx] = None; self.file_ep_count -= 1; } } } pub(crate) fn request_ep(&mut self, fd: Fd) -> Result<EpId, Error> { if self.file_ep_count < MAX_EPS { if let Ok(ep) = VPE::cur().alloc_ep() {
log!( FILES, "FileEPs[{}] = EP:{},FD:{}", i, ep, fd ); self.file_eps[i] = Some(FileEP { fd: fd, ep: ep, }); self.file_ep_count += 1; return Ok(ep); } } } } // TODO be smarter here let mut i = self.file_ep_victim; for _ in 0..MAX_EPS { if let Some(ref mut fep) = self.file_eps[i] { log!( FILES, "FileEPs[{}] = EP:{},FD: switching from {} to {}", i, fep.ep, fep.fd, fd ); let file = self.files[fep.fd].as_ref().unwrap(); file.borrow_mut().evict(); fep.fd = fd; self.file_ep_victim = (i + 1) % MAX_EPS; return Ok(fep.ep); } i = (i + 1) % MAX_EPS; } Err(Error::new(Code::NoSpace)) } pub fn collect_caps(&self, vpe: Selector, dels: &mut Vec<Selector>, max_sel: &mut Selector) -> Result<(), Error> { for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { f.borrow().exchange_caps(vpe, dels, max_sel)?; } } Ok(()) } pub fn serialize(&self, s: &mut VecSink) { let count = self.files.iter().filter(|&f| f.is_some()).count(); s.push(&count); for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { let file = f.borrow(); s.push(&fd); s.push(&file.file_type()); file.serialize(s); } } } pub fn unserialize(s: &mut SliceSource) -> FileTable { let mut ft = FileTable::default(); let count = s.pop(); for _ in 0..count { let fd: Fd = s.pop(); let file_type: u8 = s.pop(); ft.set(fd, match file_type { b'F' => GenericFile::unserialize(s), b'S' => Serial::new(), _ => panic!("Unexpected file type {}", file_type), }); } ft } } impl fmt::Debug for FileTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FileTable[\n")?; for fd in 0..MAX_FILES { if let Some(ref file) = self.files[fd] { write!(f, " {} -> {:?}\n", fd, file)?; } } write!(f, "]") } } pub fn deinit() { let ft = VPE::cur().files(); for fd in 0..MAX_FILES { ft.remove(fd); } }
for i in 0..MAX_EPS { if self.file_eps[i].is_none() {
random_line_split
filetable.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::Selector; use cell::RefCell; use col::Vec; use core::{fmt, mem}; use com::{VecSink, SliceSource}; use dtu::EpId; use errors::{Code, Error}; use io::Serial; use rc::Rc; use serialize::Sink; use vfs::{File, FileRef, GenericFile}; use vpe::VPE; pub type Fd = usize; const MAX_EPS: usize = 4; pub const MAX_FILES: usize = 32; pub type FileHandle = Rc<RefCell<File>>; struct FileEP { fd: Fd, ep: EpId, } #[derive(Default)] pub struct FileTable { file_ep_victim: usize, file_ep_count: usize, file_eps: [Option<FileEP>; MAX_EPS], files: [Option<FileHandle>; MAX_FILES], } impl FileTable { pub fn add(&mut self, file: FileHandle) -> Result<FileRef, Error> { self.alloc(file.clone()).map(|fd| FileRef::new(file, fd)) } pub fn alloc(&mut self, file: FileHandle) -> Result<Fd, Error> { for fd in 0..MAX_FILES { if self.files[fd].is_none() { self.set(fd, file); return Ok(fd); } } Err(Error::new(Code::NoSpace)) } pub fn get(&self, fd: Fd) -> Option<FileHandle> { match self.files[fd] { Some(ref f) => Some(f.clone()), None => None, } } pub fn set(&mut self, fd: Fd, file: FileHandle) { file.borrow_mut().set_fd(fd); self.files[fd] = Some(file); } pub fn remove(&mut self, fd: Fd) { let find_file_ep = |files: &[Option<FileEP>], fd| -> Option<usize> { for i in 0..MAX_EPS { if let Some(ref fep) = files[i] { if fep.fd == fd { return Some(i); } } } None }; if let Some(ref mut f) = mem::replace(&mut self.files[fd], None) { f.borrow_mut().close(); // remove from multiplexing table if let Some(idx) = find_file_ep(&self.file_eps, fd) { log!(FILES, "FileEPs[{}] = --", idx); self.file_eps[idx] = None; self.file_ep_count -= 1; } } } pub(crate) fn request_ep(&mut self, fd: Fd) -> Result<EpId, Error> { if self.file_ep_count < MAX_EPS { if let Ok(ep) = VPE::cur().alloc_ep() { for i in 0..MAX_EPS { if self.file_eps[i].is_none() { log!( FILES, "FileEPs[{}] = EP:{},FD:{}", i, ep, fd ); self.file_eps[i] = Some(FileEP { fd: fd, ep: ep, }); self.file_ep_count += 1; return Ok(ep); } } } } // TODO be smarter here let mut i = self.file_ep_victim; for _ in 0..MAX_EPS { if let Some(ref mut fep) = self.file_eps[i] { log!( FILES, "FileEPs[{}] = EP:{},FD: switching from {} to {}", i, fep.ep, fep.fd, fd ); let file = self.files[fep.fd].as_ref().unwrap(); file.borrow_mut().evict(); fep.fd = fd; self.file_ep_victim = (i + 1) % MAX_EPS; return Ok(fep.ep); } i = (i + 1) % MAX_EPS; } Err(Error::new(Code::NoSpace)) } pub fn collect_caps(&self, vpe: Selector, dels: &mut Vec<Selector>, max_sel: &mut Selector) -> Result<(), Error> { for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { f.borrow().exchange_caps(vpe, dels, max_sel)?; } } Ok(()) } pub fn
(&self, s: &mut VecSink) { let count = self.files.iter().filter(|&f| f.is_some()).count(); s.push(&count); for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { let file = f.borrow(); s.push(&fd); s.push(&file.file_type()); file.serialize(s); } } } pub fn unserialize(s: &mut SliceSource) -> FileTable { let mut ft = FileTable::default(); let count = s.pop(); for _ in 0..count { let fd: Fd = s.pop(); let file_type: u8 = s.pop(); ft.set(fd, match file_type { b'F' => GenericFile::unserialize(s), b'S' => Serial::new(), _ => panic!("Unexpected file type {}", file_type), }); } ft } } impl fmt::Debug for FileTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FileTable[\n")?; for fd in 0..MAX_FILES { if let Some(ref file) = self.files[fd] { write!(f, " {} -> {:?}\n", fd, file)?; } } write!(f, "]") } } pub fn deinit() { let ft = VPE::cur().files(); for fd in 0..MAX_FILES { ft.remove(fd); } }
serialize
identifier_name
filetable.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::Selector; use cell::RefCell; use col::Vec; use core::{fmt, mem}; use com::{VecSink, SliceSource}; use dtu::EpId; use errors::{Code, Error}; use io::Serial; use rc::Rc; use serialize::Sink; use vfs::{File, FileRef, GenericFile}; use vpe::VPE; pub type Fd = usize; const MAX_EPS: usize = 4; pub const MAX_FILES: usize = 32; pub type FileHandle = Rc<RefCell<File>>; struct FileEP { fd: Fd, ep: EpId, } #[derive(Default)] pub struct FileTable { file_ep_victim: usize, file_ep_count: usize, file_eps: [Option<FileEP>; MAX_EPS], files: [Option<FileHandle>; MAX_FILES], } impl FileTable { pub fn add(&mut self, file: FileHandle) -> Result<FileRef, Error>
pub fn alloc(&mut self, file: FileHandle) -> Result<Fd, Error> { for fd in 0..MAX_FILES { if self.files[fd].is_none() { self.set(fd, file); return Ok(fd); } } Err(Error::new(Code::NoSpace)) } pub fn get(&self, fd: Fd) -> Option<FileHandle> { match self.files[fd] { Some(ref f) => Some(f.clone()), None => None, } } pub fn set(&mut self, fd: Fd, file: FileHandle) { file.borrow_mut().set_fd(fd); self.files[fd] = Some(file); } pub fn remove(&mut self, fd: Fd) { let find_file_ep = |files: &[Option<FileEP>], fd| -> Option<usize> { for i in 0..MAX_EPS { if let Some(ref fep) = files[i] { if fep.fd == fd { return Some(i); } } } None }; if let Some(ref mut f) = mem::replace(&mut self.files[fd], None) { f.borrow_mut().close(); // remove from multiplexing table if let Some(idx) = find_file_ep(&self.file_eps, fd) { log!(FILES, "FileEPs[{}] = --", idx); self.file_eps[idx] = None; self.file_ep_count -= 1; } } } pub(crate) fn request_ep(&mut self, fd: Fd) -> Result<EpId, Error> { if self.file_ep_count < MAX_EPS { if let Ok(ep) = VPE::cur().alloc_ep() { for i in 0..MAX_EPS { if self.file_eps[i].is_none() { log!( FILES, "FileEPs[{}] = EP:{},FD:{}", i, ep, fd ); self.file_eps[i] = Some(FileEP { fd: fd, ep: ep, }); self.file_ep_count += 1; return Ok(ep); } } } } // TODO be smarter here let mut i = self.file_ep_victim; for _ in 0..MAX_EPS { if let Some(ref mut fep) = self.file_eps[i] { log!( FILES, "FileEPs[{}] = EP:{},FD: switching from {} to {}", i, fep.ep, fep.fd, fd ); let file = self.files[fep.fd].as_ref().unwrap(); file.borrow_mut().evict(); fep.fd = fd; self.file_ep_victim = (i + 1) % MAX_EPS; return Ok(fep.ep); } i = (i + 1) % MAX_EPS; } Err(Error::new(Code::NoSpace)) } pub fn collect_caps(&self, vpe: Selector, dels: &mut Vec<Selector>, max_sel: &mut Selector) -> Result<(), Error> { for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { f.borrow().exchange_caps(vpe, dels, max_sel)?; } } Ok(()) } pub fn serialize(&self, s: &mut VecSink) { let count = self.files.iter().filter(|&f| f.is_some()).count(); s.push(&count); for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { let file = f.borrow(); s.push(&fd); s.push(&file.file_type()); file.serialize(s); } } } pub fn unserialize(s: &mut SliceSource) -> FileTable { let mut ft = FileTable::default(); let count = s.pop(); for _ in 0..count { let fd: Fd = s.pop(); let file_type: u8 = s.pop(); ft.set(fd, match file_type { b'F' => GenericFile::unserialize(s), b'S' => Serial::new(), _ => panic!("Unexpected file type {}", file_type), }); } ft } } impl fmt::Debug for FileTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FileTable[\n")?; for fd in 0..MAX_FILES { if let Some(ref file) = self.files[fd] { write!(f, " {} -> {:?}\n", fd, file)?; } } write!(f, "]") } } pub fn deinit() { let ft = VPE::cur().files(); for fd in 0..MAX_FILES { ft.remove(fd); } }
{ self.alloc(file.clone()).map(|fd| FileRef::new(file, fd)) }
identifier_body
filetable.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::Selector; use cell::RefCell; use col::Vec; use core::{fmt, mem}; use com::{VecSink, SliceSource}; use dtu::EpId; use errors::{Code, Error}; use io::Serial; use rc::Rc; use serialize::Sink; use vfs::{File, FileRef, GenericFile}; use vpe::VPE; pub type Fd = usize; const MAX_EPS: usize = 4; pub const MAX_FILES: usize = 32; pub type FileHandle = Rc<RefCell<File>>; struct FileEP { fd: Fd, ep: EpId, } #[derive(Default)] pub struct FileTable { file_ep_victim: usize, file_ep_count: usize, file_eps: [Option<FileEP>; MAX_EPS], files: [Option<FileHandle>; MAX_FILES], } impl FileTable { pub fn add(&mut self, file: FileHandle) -> Result<FileRef, Error> { self.alloc(file.clone()).map(|fd| FileRef::new(file, fd)) } pub fn alloc(&mut self, file: FileHandle) -> Result<Fd, Error> { for fd in 0..MAX_FILES { if self.files[fd].is_none() { self.set(fd, file); return Ok(fd); } } Err(Error::new(Code::NoSpace)) } pub fn get(&self, fd: Fd) -> Option<FileHandle> { match self.files[fd] { Some(ref f) => Some(f.clone()), None => None, } } pub fn set(&mut self, fd: Fd, file: FileHandle) { file.borrow_mut().set_fd(fd); self.files[fd] = Some(file); } pub fn remove(&mut self, fd: Fd) { let find_file_ep = |files: &[Option<FileEP>], fd| -> Option<usize> { for i in 0..MAX_EPS { if let Some(ref fep) = files[i] { if fep.fd == fd { return Some(i); } } } None }; if let Some(ref mut f) = mem::replace(&mut self.files[fd], None) { f.borrow_mut().close(); // remove from multiplexing table if let Some(idx) = find_file_ep(&self.file_eps, fd) { log!(FILES, "FileEPs[{}] = --", idx); self.file_eps[idx] = None; self.file_ep_count -= 1; } } } pub(crate) fn request_ep(&mut self, fd: Fd) -> Result<EpId, Error> { if self.file_ep_count < MAX_EPS { if let Ok(ep) = VPE::cur().alloc_ep()
} // TODO be smarter here let mut i = self.file_ep_victim; for _ in 0..MAX_EPS { if let Some(ref mut fep) = self.file_eps[i] { log!( FILES, "FileEPs[{}] = EP:{},FD: switching from {} to {}", i, fep.ep, fep.fd, fd ); let file = self.files[fep.fd].as_ref().unwrap(); file.borrow_mut().evict(); fep.fd = fd; self.file_ep_victim = (i + 1) % MAX_EPS; return Ok(fep.ep); } i = (i + 1) % MAX_EPS; } Err(Error::new(Code::NoSpace)) } pub fn collect_caps(&self, vpe: Selector, dels: &mut Vec<Selector>, max_sel: &mut Selector) -> Result<(), Error> { for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { f.borrow().exchange_caps(vpe, dels, max_sel)?; } } Ok(()) } pub fn serialize(&self, s: &mut VecSink) { let count = self.files.iter().filter(|&f| f.is_some()).count(); s.push(&count); for fd in 0..MAX_FILES { if let Some(ref f) = self.files[fd] { let file = f.borrow(); s.push(&fd); s.push(&file.file_type()); file.serialize(s); } } } pub fn unserialize(s: &mut SliceSource) -> FileTable { let mut ft = FileTable::default(); let count = s.pop(); for _ in 0..count { let fd: Fd = s.pop(); let file_type: u8 = s.pop(); ft.set(fd, match file_type { b'F' => GenericFile::unserialize(s), b'S' => Serial::new(), _ => panic!("Unexpected file type {}", file_type), }); } ft } } impl fmt::Debug for FileTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FileTable[\n")?; for fd in 0..MAX_FILES { if let Some(ref file) = self.files[fd] { write!(f, " {} -> {:?}\n", fd, file)?; } } write!(f, "]") } } pub fn deinit() { let ft = VPE::cur().files(); for fd in 0..MAX_FILES { ft.remove(fd); } }
{ for i in 0..MAX_EPS { if self.file_eps[i].is_none() { log!( FILES, "FileEPs[{}] = EP:{},FD:{}", i, ep, fd ); self.file_eps[i] = Some(FileEP { fd: fd, ep: ep, }); self.file_ep_count += 1; return Ok(ep); } } }
conditional_block
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus>
pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x)) } pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) } pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn default_float_rounding_mode(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } } impl Drop for CodeObject { fn drop(&mut self) { unsafe { hsa_code_object_destroy(self.handle); } } }
{ get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) }
identifier_body
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) } pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x))
pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn default_float_rounding_mode(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } } impl Drop for CodeObject { fn drop(&mut self) { unsafe { hsa_code_object_destroy(self.handle); } } }
} pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) }
random_line_split
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) } pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x)) } pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) } pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn
(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } } impl Drop for CodeObject { fn drop(&mut self) { unsafe { hsa_code_object_destroy(self.handle); } } }
default_float_rounding_mode
identifier_name
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn
(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs) { let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border) * progress * progress, 0.0) } InnerState::Settling(progress) => { (render_args.height as Scalar - border, border * (1.0 - progress) * Progress::sin(progress * 64.0)) } InnerState::Done => (render_args.height as Scalar - border, 0.0), }; { let points = 16; let pixels = text::points_to_pixels(points); let VMetrics { ascent, descent,.. } = glyphs.font .v_metrics(Scale::uniform(pixels)); let fps_text = format!("{} FPS", state.fps); let mut draw = |text, x: &Fn(Rect<f32>) -> Scalar, y| { let bounding_box = text::bounding_box(&glyphs.font, pixels, text) .unwrap(); let transform = context.transform.trans(x(bounding_box), y); piston_window::text(white, points, text, glyphs, transform, graphics); }; draw("Games, Inc.", &|bounding_box| border - bounding_box.min.x as Scalar, border + ascent as Scalar + shake); draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, render_args.height as Scalar - border + descent as Scalar + shake); } let text = "COUNTDOWN"; let points = 128; let pixels = text::points_to_pixels(points); let bounding_box = text::bounding_box(&glyphs.font, pixels, text).unwrap(); let transform = context.transform .trans(render_args.width as Scalar / 2.0 - (bounding_box.min.x + bounding_box.width() / 2.0) as Scalar, title + shake + glyphs.font.v_metrics(Scale::uniform(pixels)).descent as Scalar); piston_window::text(white, points, text, glyphs, transform, graphics); }
draw
identifier_name
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn draw(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs) { let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border) * progress * progress, 0.0) } InnerState::Settling(progress) => { (render_args.height as Scalar - border, border * (1.0 - progress) * Progress::sin(progress * 64.0)) } InnerState::Done => (render_args.height as Scalar - border, 0.0), }; { let points = 16; let pixels = text::points_to_pixels(points); let VMetrics { ascent, descent,.. } = glyphs.font .v_metrics(Scale::uniform(pixels)); let fps_text = format!("{} FPS", state.fps); let mut draw = |text, x: &Fn(Rect<f32>) -> Scalar, y| { let bounding_box = text::bounding_box(&glyphs.font, pixels, text) .unwrap(); let transform = context.transform.trans(x(bounding_box), y); piston_window::text(white, points, text, glyphs, transform, graphics); }; draw("Games, Inc.", &|bounding_box| border - bounding_box.min.x as Scalar, border + ascent as Scalar + shake);
}, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, render_args.height as Scalar - border + descent as Scalar + shake); } let text = "COUNTDOWN"; let points = 128; let pixels = text::points_to_pixels(points); let bounding_box = text::bounding_box(&glyphs.font, pixels, text).unwrap(); let transform = context.transform .trans(render_args.width as Scalar / 2.0 - (bounding_box.min.x + bounding_box.width() / 2.0) as Scalar, title + shake + glyphs.font.v_metrics(Scale::uniform(pixels)).descent as Scalar); piston_window::text(white, points, text, glyphs, transform, graphics); }
draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar
random_line_split
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn draw(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs)
let pixels = text::points_to_pixels(points); let VMetrics { ascent, descent,.. } = glyphs.font .v_metrics(Scale::uniform(pixels)); let fps_text = format!("{} FPS", state.fps); let mut draw = |text, x: &Fn(Rect<f32>) -> Scalar, y| { let bounding_box = text::bounding_box(&glyphs.font, pixels, text) .unwrap(); let transform = context.transform.trans(x(bounding_box), y); piston_window::text(white, points, text, glyphs, transform, graphics); }; draw("Games, Inc.", &|bounding_box| border - bounding_box.min.x as Scalar, border + ascent as Scalar + shake); draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar }, render_args.height as Scalar - border + descent as Scalar + shake); } let text = "COUNTDOWN"; let points = 128; let pixels = text::points_to_pixels(points); let bounding_box = text::bounding_box(&glyphs.font, pixels, text).unwrap(); let transform = context.transform .trans(render_args.width as Scalar / 2.0 - (bounding_box.min.x + bounding_box.width() / 2.0) as Scalar, title + shake + glyphs.font.v_metrics(Scale::uniform(pixels)).descent as Scalar); piston_window::text(white, points, text, glyphs, transform, graphics); }
{ let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border) * progress * progress, 0.0) } InnerState::Settling(progress) => { (render_args.height as Scalar - border, border * (1.0 - progress) * Progress::sin(progress * 64.0)) } InnerState::Done => (render_args.height as Scalar - border, 0.0), }; { let points = 16;
identifier_body
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len {
y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if!from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count()!= 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
random_line_split
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0
//println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len { y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if!from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count()!= 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
{ //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect();
conditional_block
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool
//println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len { y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if!from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count()!= 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
{ // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { None => {
identifier_body
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn
(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); return rule.val.iter().eq(x.iter()); }, Some(ref mask) => { //println!("\tMask == Some, len == {}", mask.len()); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); let mut x: Vec<u8> = file.iter() .skip(bound_min) // Skip to start of area .take(bound_max - bound_min) // Take until end of area - region length .map(|&x| x).collect(); // Convert to vector let mut val: Vec<u8> = rule.val.iter().map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); assert_eq!(x.len(), mask.len()); for i in 0..std::cmp::min(x.len(), mask.len()) { x[i] &= mask[i]; val[i] = val[i] & mask[i]; } //println!("\t & {:?} => {:?}", mask, x); return rule.val.iter().eq(x.iter()); } } } else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("{:?}, {:?}, {:?}\n", file, testarea, rule.val); // Search down until we find a hit let mut y = Vec::<u8>::with_capacity(testarea.len()); for x in testarea.windows(rule.val_len as usize) { y.clear(); // Apply mask to value let ref rule_mask = rule.mask; match *rule_mask { Some(ref mask) => { for i in 0..rule.val_len { y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = graph[node]; // Check root if!from_u8_singlerule(&file, rule) { return false; } // Return if that was the only test if n.clone().count() == 0 { return true; } // Otherwise next indent level is lower, so continue } // Check subrules recursively for y in n { let ref rule = graph[y]; if from_u8_singlerule(&file, rule) { // Check next indent level if needed if graph.neighbors_directed(y, Outgoing).count()!= 0 { return from_u8_walker(file, mimetype, graph, y, false); // Next indent level is lower, so this must be it } else { return true; } } } false }
from_u8_singlerule
identifier_name
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) =>
mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
{ ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) }
conditional_block
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn check_scope(&self, max_scope: ty::Region) -> R
fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
{ //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } }
identifier_body
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region, cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn
(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
check_scope
identifier_name
lifetime.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. use borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty; use rustc::util::ppaux::Repr; use syntax::ast; use syntax::codemap::Span; type R = Result<(),()>; pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, loan_region: ty::Region, _: ty::BorrowKind) -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. debug!("guarantee_lifetime(cmt={}, loan_region={})", cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx)); let ctxt = GuaranteeLifetimeContext {bccx: bccx, item_scope: item_scope, span: span, cause: cause, loan_region: loan_region,
cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the enclosing item item_scope: region::CodeExtent, span: Span, cause: euv::LoanCause, loan_region: ty::Region, cmt_original: mc::cmt<'tcx> } impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> { fn check(&self, cmt: &mc::cmt<'tcx>, discr_scope: Option<ast::NodeId>) -> R { //! Main routine. Walks down `cmt` until we find the //! "guarantor". Reports an error if `self.loan_region` is //! larger than scope of `cmt`. debug!("guarantee_lifetime.check(cmt={}, loan_region={})", cmt.repr(self.bccx.tcx), self.loan_region.repr(self.bccx.tcx)); match cmt.cat { mc::cat_rvalue(..) | mc::cat_local(..) | // L-Local mc::cat_upvar(..) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | // L-Deref-Borrowed mc::cat_deref(_, _, mc::Implicit(..)) | mc::cat_deref(_, _, mc::UnsafePtr(..)) => { self.check_scope(self.scope(cmt)) } mc::cat_static_item => { Ok(()) } mc::cat_downcast(ref base, _) | mc::cat_deref(ref base, _, mc::Unique) | // L-Deref-Send mc::cat_interior(ref base, _) => { // L-Field self.check(base, discr_scope) } } } fn check_scope(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if!self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } fn scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { temp_scope } mc::cat_upvar(..) => { ty::ReScope(self.item_scope) } mc::cat_static_item => { ty::ReStatic } mc::cat_local(local_id) => { ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) } mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref cmt, _, mc::Unique) | mc::cat_interior(ref cmt, _) => { self.scope(cmt) } } } fn report_error(&self, code: bckerr_code) { self.bccx.report(BckError { cmt: self.cmt_original.clone(), span: self.span, cause: self.cause, code: code }); } }
random_line_split
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } } impl<T: Clone> Foo for T { default fn foo(&self) -> &'static str { "generic Clone" } } impl<T, U> Foo for (T, U) where T: Clone, U: Clone { default fn foo(&self) -> &'static str { "generic pair" } } impl<T: Clone> Foo for (T, T) { default fn foo(&self) -> &'static str { "generic uniform pair" } } impl Foo for (u8, u32) { default fn foo(&self) -> &'static str { "(u8, u32)" } } impl Foo for (u8, u8) { default fn foo(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "String" } } impl Foo for i32 { fn foo(&self) -> &'static str { "i32" } } struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)]
assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); assert!(MarkedAndClone.foo() == "generic Clone + MyMarker"); }
struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() {
random_line_split
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } } impl<T: Clone> Foo for T { default fn foo(&self) -> &'static str { "generic Clone" } } impl<T, U> Foo for (T, U) where T: Clone, U: Clone { default fn foo(&self) -> &'static str { "generic pair" } } impl<T: Clone> Foo for (T, T) { default fn foo(&self) -> &'static str { "generic uniform pair" } } impl Foo for (u8, u32) { default fn foo(&self) -> &'static str { "(u8, u32)" } } impl Foo for (u8, u8) { default fn
(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "String" } } impl Foo for i32 { fn foo(&self) -> &'static str { "i32" } } struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)] struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() { assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); assert!(MarkedAndClone.foo() == "generic Clone + MyMarker"); }
foo
identifier_name
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } } impl<T: Clone> Foo for T { default fn foo(&self) -> &'static str { "generic Clone" } } impl<T, U> Foo for (T, U) where T: Clone, U: Clone { default fn foo(&self) -> &'static str { "generic pair" } } impl<T: Clone> Foo for (T, T) { default fn foo(&self) -> &'static str { "generic uniform pair" } } impl Foo for (u8, u32) { default fn foo(&self) -> &'static str { "(u8, u32)" } } impl Foo for (u8, u8) { default fn foo(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "String" } } impl Foo for i32 { fn foo(&self) -> &'static str
} struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)] struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() { assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); assert!((0u8, 0u32).foo() == "(u8, u32)"); assert!((0u8, 0u8).foo() == "(u8, u8)"); assert!(MarkedAndClone.foo() == "generic Clone + MyMarker"); }
{ "i32" }
identifier_body
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Sample>{ MiniObject::new_from_gst_miniobject(sample as *mut GstMiniObject) .map(|miniobject| Sample{ sample: miniobject }) } /// Get the buffer associated with sample or None when there is no buffer. pub fn
(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer!= ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /// Get the caps associated with sample or None when there's no caps pub fn caps(&self) -> Option<Caps>{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps!= ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } } /// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ let buffer = match self.buffer(){ Some(buffer) => buffer, None => return None }; let vi = match self.caps(){ Some(caps) => match caps.video_info(){ Some(vi) => vi, None => return None }, None => return None }; unsafe{ VideoFrame::new(vi, buffer) } } pub unsafe fn gst_sample(&self) -> *const GstSample{ self.sample.gst_miniobject() as *const GstSample } pub unsafe fn gst_sample_mut(&mut self) -> *mut GstSample{ self.sample.gst_miniobject_mut() as *mut GstSample } } impl ::Transfer<GstSample> for Sample{ unsafe fn transfer(self) -> *mut GstSample{ self.sample.transfer() as *mut GstSample } } impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
buffer
identifier_name
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Sample>{ MiniObject::new_from_gst_miniobject(sample as *mut GstMiniObject) .map(|miniobject| Sample{ sample: miniobject }) } /// Get the buffer associated with sample or None when there is no buffer. pub fn buffer(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer!= ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /// Get the caps associated with sample or None when there's no caps pub fn caps(&self) -> Option<Caps>
/// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ let buffer = match self.buffer(){ Some(buffer) => buffer, None => return None }; let vi = match self.caps(){ Some(caps) => match caps.video_info(){ Some(vi) => vi, None => return None }, None => return None }; unsafe{ VideoFrame::new(vi, buffer) } } pub unsafe fn gst_sample(&self) -> *const GstSample{ self.sample.gst_miniobject() as *const GstSample } pub unsafe fn gst_sample_mut(&mut self) -> *mut GstSample{ self.sample.gst_miniobject_mut() as *mut GstSample } } impl ::Transfer<GstSample> for Sample{ unsafe fn transfer(self) -> *mut GstSample{ self.sample.transfer() as *mut GstSample } } impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps != ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } }
identifier_body
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Sample>{ MiniObject::new_from_gst_miniobject(sample as *mut GstMiniObject) .map(|miniobject| Sample{ sample: miniobject }) } /// Get the buffer associated with sample or None when there is no buffer. pub fn buffer(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer!= ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /// Get the caps associated with sample or None when there's no caps pub fn caps(&self) -> Option<Caps>{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps!= ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } } /// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ let buffer = match self.buffer(){ Some(buffer) => buffer, None => return None }; let vi = match self.caps(){ Some(caps) => match caps.video_info(){ Some(vi) => vi, None => return None }, None => return None }; unsafe{ VideoFrame::new(vi, buffer) } } pub unsafe fn gst_sample(&self) -> *const GstSample{ self.sample.gst_miniobject() as *const GstSample } pub unsafe fn gst_sample_mut(&mut self) -> *mut GstSample{ self.sample.gst_miniobject_mut() as *mut GstSample } } impl ::Transfer<GstSample> for Sample{ unsafe fn transfer(self) -> *mut GstSample{
impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
self.sample.transfer() as *mut GstSample } }
random_line_split
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode { Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value { Value::I32(self.to_i32()) } pub fn
(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, InvalidInput => ErrorCode::InvalidInput, _ => ErrorCode::Generic } } }
to_i32
identifier_name
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode { Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value
pub fn to_i32(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, InvalidInput => ErrorCode::InvalidInput, _ => ErrorCode::Generic } } }
{ Value::I32(self.to_i32()) }
identifier_body
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode {
Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value { Value::I32(self.to_i32()) } pub fn to_i32(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, InvalidInput => ErrorCode::InvalidInput, _ => ErrorCode::Generic } } }
random_line_split
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str>
pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"]; let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) }; println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0.. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
{ (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() }
identifier_body
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0.. desc.len()).filter(|i| flags & (1 << i)!= 0).map(|i| desc[i]).collect() } pub fn
(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"]; let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) }; println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0.. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
enumerate_devices
identifier_name
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0.. desc.len()).filter(|i| flags & (1 << i)!= 0).map(|i| desc[i]).collect() } pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"];
println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0.. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) };
random_line_split
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0.. desc.len()).filter(|i| flags & (1 << i)!= 0).map(|i| desc[i]).collect() } pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISlavePointer", "XISlaveKeyboard", "XIFloatingSlave"]; let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) }; println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0.. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str = match _type { xinput2::XIKeyClass => { let key_c: &xinput2::XIKeyClassInfo = unsafe { mem::transmute(class) }; format!("{} keycodes", key_c.num_keycodes) } xinput2::XIButtonClass => { let but_c: &xinput2::XIButtonClassInfo = unsafe { mem::transmute(class) }; let atoms = unsafe { slice::from_raw_parts(but_c.labels, but_c.num_buttons as usize) }; let buttons: Vec<(_, _)> = atoms.iter().map(|&atom| { if atom!= 0 { unsafe { let ptr = xlib::XGetAtomName(display, atom); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } } else { CString::new("(null)").unwrap() } }).enumerate().map(|(i, s)| (i+1, s)).collect(); format!("{} buttons {:?}", but_c.num_buttons, buttons) }, xinput2::XIValuatorClass => { let val_c: &xinput2::XIValuatorClassInfo = unsafe { mem::transmute(class) }; let name = if val_c.label!= 0
else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { let scr_c: &xinput2::XIScrollClassInfo = unsafe { mem::transmute(class) }; format!("number {}, stype {}, incr {}, flags={}", scr_c.number, scr_c.scroll_type, scr_c.increment, scr_c.flags) }, xinput2::XITouchClass => { let tou_c: &xinput2::XITouchClassInfo = unsafe { mem::transmute(class) }; format!("mode {}, num_touches {}", tou_c.mode, tou_c.num_touches) }, _ => unreachable!() }; println!(" class: {} ({})", dev_class[_type as usize], ci_str); } } unsafe{ xinput2::XIFreeDeviceInfo(devices_ptr); } println!("---"); }
{ unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } }
conditional_block
float.rs
use crate::msgpack::encode::*; #[test] fn pass_pack_f32()
#[test] fn pass_pack_f64() { use std::f64; let mut buf = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; write_f64(&mut &mut buf[..], f64::INFINITY).ok().unwrap(); assert_eq!([0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buf); }
{ let mut buf = [0x00, 0x00, 0x00, 0x00, 0x00]; write_f32(&mut &mut buf[..], 3.4028234e38_f32).ok().unwrap(); assert_eq!([0xca, 0x7f, 0x7f, 0xff, 0xff], buf); }
identifier_body
float.rs
use crate::msgpack::encode::*; #[test] fn pass_pack_f32() { let mut buf = [0x00, 0x00, 0x00, 0x00, 0x00];
write_f32(&mut &mut buf[..], 3.4028234e38_f32).ok().unwrap(); assert_eq!([0xca, 0x7f, 0x7f, 0xff, 0xff], buf); } #[test] fn pass_pack_f64() { use std::f64; let mut buf = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; write_f64(&mut &mut buf[..], f64::INFINITY).ok().unwrap(); assert_eq!([0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buf); }
random_line_split
float.rs
use crate::msgpack::encode::*; #[test] fn pass_pack_f32() { let mut buf = [0x00, 0x00, 0x00, 0x00, 0x00]; write_f32(&mut &mut buf[..], 3.4028234e38_f32).ok().unwrap(); assert_eq!([0xca, 0x7f, 0x7f, 0xff, 0xff], buf); } #[test] fn
() { use std::f64; let mut buf = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; write_f64(&mut &mut buf[..], f64::INFINITY).ok().unwrap(); assert_eq!([0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buf); }
pass_pack_f64
identifier_name
lib.rs
//! Get information concerning the build target. macro_rules! return_cfg { ($i:ident : $s:expr) => ( if cfg!($i = $s) { return $s; } ); ($i:ident : $s:expr, $($t:expr),+) => ( return_cfg!($i: $s); return_cfg!($i: $($t),+) ); } /// Collection of functions to give information on the build target. pub struct Target; impl Target { /// Architecture; given by `target_arch`. pub fn arch() -> &'static str { return_cfg!(target_arch: "x86", "x86_64", "mips", "powerpc", "arm", "aarch64"); "unknown" } /// Endianness; given by `target_endian`. pub fn endian() -> &'static str { return_cfg!(target_endian: "little", "big"); "" } /// Toolchain environment; given by `target_environment`. pub fn env() -> &'static str { return_cfg!(target_env: "musl", "msvc", "gnu"); "" } /// OS familt; given by `target_family`. pub fn family() -> &'static str { return_cfg!(target_family: "unix", "windows"); "unknown" } /// Operating system; given by `target_os`. pub fn os() -> &'static str
/// Pointer width; given by `target_pointer_width`. pub fn pointer_width() -> &'static str { return_cfg!(target_pointer_width: "32", "64"); "unknown" } // TODO: enable once it's not experimental API. // pub fn vendor() -> &'static str { // return_cfg!(target_vendor: "apple", "pc"); // "unknown" // } }
{ return_cfg!(target_os: "windows", "macos", "ios", "linux", "android", "freebsd", "dragonfly", "bitrig", "openbsd", "netbsd"); "unknown" }
identifier_body
lib.rs
macro_rules! return_cfg { ($i:ident : $s:expr) => ( if cfg!($i = $s) { return $s; } ); ($i:ident : $s:expr, $($t:expr),+) => ( return_cfg!($i: $s); return_cfg!($i: $($t),+) ); } /// Collection of functions to give information on the build target. pub struct Target; impl Target { /// Architecture; given by `target_arch`. pub fn arch() -> &'static str { return_cfg!(target_arch: "x86", "x86_64", "mips", "powerpc", "arm", "aarch64"); "unknown" } /// Endianness; given by `target_endian`. pub fn endian() -> &'static str { return_cfg!(target_endian: "little", "big"); "" } /// Toolchain environment; given by `target_environment`. pub fn env() -> &'static str { return_cfg!(target_env: "musl", "msvc", "gnu"); "" } /// OS familt; given by `target_family`. pub fn family() -> &'static str { return_cfg!(target_family: "unix", "windows"); "unknown" } /// Operating system; given by `target_os`. pub fn os() -> &'static str { return_cfg!(target_os: "windows", "macos", "ios", "linux", "android", "freebsd", "dragonfly", "bitrig", "openbsd", "netbsd"); "unknown" } /// Pointer width; given by `target_pointer_width`. pub fn pointer_width() -> &'static str { return_cfg!(target_pointer_width: "32", "64"); "unknown" } // TODO: enable once it's not experimental API. // pub fn vendor() -> &'static str { // return_cfg!(target_vendor: "apple", "pc"); // "unknown" // } }
//! Get information concerning the build target.
random_line_split
lib.rs
//! Get information concerning the build target. macro_rules! return_cfg { ($i:ident : $s:expr) => ( if cfg!($i = $s) { return $s; } ); ($i:ident : $s:expr, $($t:expr),+) => ( return_cfg!($i: $s); return_cfg!($i: $($t),+) ); } /// Collection of functions to give information on the build target. pub struct Target; impl Target { /// Architecture; given by `target_arch`. pub fn arch() -> &'static str { return_cfg!(target_arch: "x86", "x86_64", "mips", "powerpc", "arm", "aarch64"); "unknown" } /// Endianness; given by `target_endian`. pub fn endian() -> &'static str { return_cfg!(target_endian: "little", "big"); "" } /// Toolchain environment; given by `target_environment`. pub fn env() -> &'static str { return_cfg!(target_env: "musl", "msvc", "gnu"); "" } /// OS familt; given by `target_family`. pub fn family() -> &'static str { return_cfg!(target_family: "unix", "windows"); "unknown" } /// Operating system; given by `target_os`. pub fn os() -> &'static str { return_cfg!(target_os: "windows", "macos", "ios", "linux", "android", "freebsd", "dragonfly", "bitrig", "openbsd", "netbsd"); "unknown" } /// Pointer width; given by `target_pointer_width`. pub fn
() -> &'static str { return_cfg!(target_pointer_width: "32", "64"); "unknown" } // TODO: enable once it's not experimental API. // pub fn vendor() -> &'static str { // return_cfg!(target_vendor: "apple", "pc"); // "unknown" // } }
pointer_width
identifier_name
fs.rs
use std::env; use std::fs; #[derive(Debug, Copy, Clone)] pub enum LlamaFile { SdCardImg, NandImg, NandCid, AesKeyDb, Otp, Boot9, Boot11, } #[cfg(not(target_os = "windows"))] fn make_filepath(filename: &str) -> String { format!("{}/.config/llama/{}", env::var("HOME").unwrap(), filename) } #[cfg(target_os = "windows")] fn make_filepath(filename: &str) -> String { format!("{}/llama/{}", env::var("APPDATA").unwrap(), filename) } fn get_path(lf: LlamaFile) -> String { let filename = match lf { LlamaFile::SdCardImg => "sd.fat", LlamaFile::NandImg => "nand.bin", LlamaFile::NandCid => "nand-cid.bin", LlamaFile::AesKeyDb => "aeskeydb.bin", LlamaFile::Otp => "otp.bin", LlamaFile::Boot9 => "boot9.bin", LlamaFile::Boot11 => "boot11.bin", }; make_filepath(filename) } pub fn open_file(lf: LlamaFile) -> Result<fs::File, String> { let path = get_path(lf); let res = fs::OpenOptions::new().read(true).write(true).open(path.as_str()); match res { Ok(file) => Ok(file), Err(_) => Err(format!("Could not open file `{}`", path)) } } pub fn create_file<F>(lf: LlamaFile, initializer: F) -> Result<fs::File, String> where F: FnOnce(&mut fs::File) { let path = get_path(lf); let res = fs::OpenOptions::new() .read(true).write(true) .create(true).truncate(true) .open(path.as_str()); let mut file = match res { Ok(file) => file, Err(x) => return Err(format!("Could not create file `{}`; {:?}", path, x)) }; initializer(&mut file);
}
Ok(file)
random_line_split
fs.rs
use std::env; use std::fs; #[derive(Debug, Copy, Clone)] pub enum
{ SdCardImg, NandImg, NandCid, AesKeyDb, Otp, Boot9, Boot11, } #[cfg(not(target_os = "windows"))] fn make_filepath(filename: &str) -> String { format!("{}/.config/llama/{}", env::var("HOME").unwrap(), filename) } #[cfg(target_os = "windows")] fn make_filepath(filename: &str) -> String { format!("{}/llama/{}", env::var("APPDATA").unwrap(), filename) } fn get_path(lf: LlamaFile) -> String { let filename = match lf { LlamaFile::SdCardImg => "sd.fat", LlamaFile::NandImg => "nand.bin", LlamaFile::NandCid => "nand-cid.bin", LlamaFile::AesKeyDb => "aeskeydb.bin", LlamaFile::Otp => "otp.bin", LlamaFile::Boot9 => "boot9.bin", LlamaFile::Boot11 => "boot11.bin", }; make_filepath(filename) } pub fn open_file(lf: LlamaFile) -> Result<fs::File, String> { let path = get_path(lf); let res = fs::OpenOptions::new().read(true).write(true).open(path.as_str()); match res { Ok(file) => Ok(file), Err(_) => Err(format!("Could not open file `{}`", path)) } } pub fn create_file<F>(lf: LlamaFile, initializer: F) -> Result<fs::File, String> where F: FnOnce(&mut fs::File) { let path = get_path(lf); let res = fs::OpenOptions::new() .read(true).write(true) .create(true).truncate(true) .open(path.as_str()); let mut file = match res { Ok(file) => file, Err(x) => return Err(format!("Could not create file `{}`; {:?}", path, x)) }; initializer(&mut file); Ok(file) }
LlamaFile
identifier_name
fat_type.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Loaded representation for runtime types. use diem_types::{account_address::AccountAddress, vm_status::StatusCode}; use move_core_types::{ identifier::Identifier, language_storage::{StructTag, TypeTag}, value::{MoveStructLayout, MoveTypeLayout}, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::convert::TryInto; use vm::{ errors::{PartialVMError, PartialVMResult}, file_format::AbilitySet, }; #[derive(Debug, Clone, Copy)] pub(crate) struct WrappedAbilitySet(pub AbilitySet); impl Serialize for WrappedAbilitySet { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.0.into_u8().serialize(serializer) } } impl<'de> Deserialize<'de> for WrappedAbilitySet { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let byte = u8::deserialize(deserializer)?; Ok(WrappedAbilitySet(AbilitySet::from_u8(byte).ok_or_else( || serde::de::Error::custom(format!("Invalid ability set: {:X}", byte)), )?)) } } /// VM representation of a struct type in Move. #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct FatStructType { pub address: AccountAddress, pub module: Identifier, pub name: Identifier, pub abilities: WrappedAbilitySet, pub ty_args: Vec<FatType>, pub layout: Vec<FatType>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) enum FatType { Bool, U8, U64, U128, Address, Signer, Vector(Box<FatType>), Struct(Box<FatStructType>), Reference(Box<FatType>), MutableReference(Box<FatType>), TyParam(usize), } impl FatStructType { pub fn subst(&self, ty_args: &[FatType]) -> PartialVMResult<FatStructType> { Ok(Self { address: self.address, module: self.module.clone(),
.ty_args .iter() .map(|ty| ty.subst(ty_args)) .collect::<PartialVMResult<_>>()?, layout: self .layout .iter() .map(|ty| ty.subst(ty_args)) .collect::<PartialVMResult<_>>()?, }) } pub fn struct_tag(&self) -> PartialVMResult<StructTag> { let ty_args = self .ty_args .iter() .map(|ty| ty.type_tag()) .collect::<PartialVMResult<Vec<_>>>()?; Ok(StructTag { address: self.address, module: self.module.clone(), name: self.name.clone(), type_params: ty_args, }) } } impl FatType { pub fn subst(&self, ty_args: &[FatType]) -> PartialVMResult<FatType> { use FatType::*; let res = match self { TyParam(idx) => match ty_args.get(*idx) { Some(ty) => ty.clone(), None => { return Err( PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR) .with_message(format!( "fat type substitution failed: index out of bounds -- len {} got {}", ty_args.len(), idx )), ); } }, Bool => Bool, U8 => U8, U64 => U64, U128 => U128, Address => Address, Signer => Signer, Vector(ty) => Vector(Box::new(ty.subst(ty_args)?)), Reference(ty) => Reference(Box::new(ty.subst(ty_args)?)), MutableReference(ty) => MutableReference(Box::new(ty.subst(ty_args)?)), Struct(struct_ty) => Struct(Box::new(struct_ty.subst(ty_args)?)), }; Ok(res) } pub fn type_tag(&self) -> PartialVMResult<TypeTag> { use FatType::*; let res = match self { Bool => TypeTag::Bool, U8 => TypeTag::U8, U64 => TypeTag::U64, U128 => TypeTag::U128, Address => TypeTag::Address, Signer => TypeTag::Signer, Vector(ty) => TypeTag::Vector(Box::new(ty.type_tag()?)), Struct(struct_ty) => TypeTag::Struct(struct_ty.struct_tag()?), Reference(_) | MutableReference(_) | TyParam(_) => { return Err( PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR) .with_message(format!("cannot derive type tag for {:?}", self)), ) } }; Ok(res) } } impl TryInto<MoveStructLayout> for &FatStructType { type Error = PartialVMError; fn try_into(self) -> Result<MoveStructLayout, Self::Error> { Ok(MoveStructLayout::new( self.layout .iter() .map(|ty| ty.try_into()) .collect::<PartialVMResult<Vec<_>>>()?, )) } } impl TryInto<MoveTypeLayout> for &FatType { type Error = PartialVMError; fn try_into(self) -> Result<MoveTypeLayout, Self::Error> { Ok(match self { FatType::Address => MoveTypeLayout::Address, FatType::U8 => MoveTypeLayout::U8, FatType::U64 => MoveTypeLayout::U64, FatType::U128 => MoveTypeLayout::U128, FatType::Bool => MoveTypeLayout::Bool, FatType::Vector(v) => MoveTypeLayout::Vector(Box::new(v.as_ref().try_into()?)), FatType::Struct(s) => MoveTypeLayout::Struct(MoveStructLayout::new( s.layout .iter() .map(|ty| ty.try_into()) .collect::<PartialVMResult<Vec<_>>>()?, )), FatType::Signer => MoveTypeLayout::Signer, _ => return Err(PartialVMError::new(StatusCode::ABORT_TYPE_MISMATCH_ERROR)), }) } }
name: self.name.clone(), abilities: self.abilities, ty_args: self
random_line_split