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
simd-generics.rs
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(simd)] use std::ops; #[simd] struct f32x4(f32, f32, f32, f32); fn add<T: ops::Add<T, T>>(lhs: T, rhs: T) -> T { lhs + rhs } impl ops::Add<f32x4, f32x4> for f32x4 { fn add(&self, rhs: &f32x4) -> f32x4 { *self + *rhs } } pub fn main() { let lr = f32x4(1.0f32, 2.0f32, 3.0f32, 4.0f32); // lame-o let f32x4(x, y, z, w) = add(lr, lr); assert_eq!(x, 2.0f32); assert_eq!(y, 4.0f32); assert_eq!(z, 6.0f32); assert_eq!(w, 8.0f32); }
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
simd-generics.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(simd)] use std::ops; #[simd] struct f32x4(f32, f32, f32, f32); fn
<T: ops::Add<T, T>>(lhs: T, rhs: T) -> T { lhs + rhs } impl ops::Add<f32x4, f32x4> for f32x4 { fn add(&self, rhs: &f32x4) -> f32x4 { *self + *rhs } } pub fn main() { let lr = f32x4(1.0f32, 2.0f32, 3.0f32, 4.0f32); // lame-o let f32x4(x, y, z, w) = add(lr, lr); assert_eq!(x, 2.0f32); assert_eq!(y, 4.0f32); assert_eq!(z, 6.0f32); assert_eq!(w, 8.0f32); }
add
identifier_name
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_name="UserInterface") %> <%helpers:longhand name="cursor" boxed="${product == 'gecko'}" animation_value_type="discrete" spec="https://drafts.csswg.org/css-ui/#cursor"> pub use self::computed_value::T as SpecifiedValue; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; pub mod computed_value { #[cfg(feature = "gecko")] use std::fmt; #[cfg(feature = "gecko")] use style_traits::ToCss; use style_traits::cursor::Cursor; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum Keyword { Auto, Cursor(Cursor), } #[cfg(not(feature = "gecko"))] pub type T = Keyword; #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Image { pub url: SpecifiedUrl, pub hotspot: Option<(f32, f32)>, } #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct T { pub images: Vec<Image>, pub keyword: Keyword, } #[cfg(feature = "gecko")] impl ToCss for Image { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.url.to_css(dest)?; if let Some((x, y)) = self.hotspot { dest.write_str(" ")?; x.to_css(dest)?; dest.write_str(" ")?; y.to_css(dest)?; } Ok(()) } } #[cfg(feature = "gecko")] impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { for url in &self.images { url.to_css(dest)?; dest.write_str(", ")?; } self.keyword.to_css(dest) } } } #[cfg(not(feature = "gecko"))] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::Keyword::Auto } #[cfg(feature = "gecko")] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { images: vec![], keyword: computed_value::Keyword::Auto } } impl Parse for computed_value::Keyword { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Keyword, ParseError<'i>> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor; let location = input.current_source_location(); let ident = input.expect_ident()?; if ident.eq_ignore_ascii_case("auto") { Ok(computed_value::Keyword::Auto) } else { Cursor::from_css_keyword(&ident) .map(computed_value::Keyword::Cursor) .map_err(|()| location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))) } } } #[cfg(feature = "gecko")] fn
<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Image, ParseError<'i>> { Ok(computed_value::Image { url: SpecifiedUrl::parse(context, input)?, hotspot: match input.try(|input| input.expect_number()) { Ok(number) => Some((number, input.expect_number()?)), Err(_) => None, }, }) } #[cfg(not(feature = "gecko"))] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { computed_value::Keyword::parse(context, input) } /// cursor: [<url> [<number> <number>]?]# [auto | default |...] #[cfg(feature = "gecko")] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { let mut images = vec![]; loop { match input.try(|input| parse_image(context, input)) { Ok(mut image) => { image.url.build_image_value(); images.push(image) } Err(_) => break, } input.expect_comma()?; } Ok(computed_value::T { images: images, keyword: computed_value::Keyword::parse(context, input)?, }) } </%helpers:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${helpers.single_keyword("pointer-events", "auto none", animation_value_type="discrete", extra_gecko_values="visiblepainted visiblefill visiblestroke visible painted fill stroke all", flags="APPLIES_TO_PLACEHOLDER", spec="https://www.w3.org/TR/SVG11/interact.html#PointerEventsProperty")} ${helpers.single_keyword("-moz-user-input", "auto none enabled disabled", products="gecko", gecko_ffi_name="mUserInput", gecko_enum_prefix="StyleUserInput", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-input)")} ${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko", gecko_ffi_name="mUserModify", gecko_enum_prefix="StyleUserModify", needs_conversion=True, animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-modify)")} ${helpers.single_keyword("-moz-user-focus", "none ignore normal select-after select-before select-menu select-same select-all", products="gecko", gecko_ffi_name="mUserFocus", gecko_enum_prefix="StyleUserFocus", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-focus)")} ${helpers.predefined_type( "caret-color", "ColorOrAuto", "Either::Second(Auto)", spec="https://drafts.csswg.org/css-ui/#caret-color", animation_value_type="Either<AnimatedColor, Auto>", boxed=True, ignored_when_colors_disabled=True, products="gecko", )} ${helpers.predefined_type( "-moz-font-smoothing-background-color", "RGBAColor", "RGBA::transparent()", animation_value_type="AnimatedRGBA", products="gecko", gecko_ffi_name="mFontSmoothingBackgroundColor", internal=True, spec="None (Nonstandard internal property)" )}
parse_image
identifier_name
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_name="UserInterface") %> <%helpers:longhand name="cursor" boxed="${product == 'gecko'}" animation_value_type="discrete" spec="https://drafts.csswg.org/css-ui/#cursor"> pub use self::computed_value::T as SpecifiedValue; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; pub mod computed_value { #[cfg(feature = "gecko")] use std::fmt; #[cfg(feature = "gecko")] use style_traits::ToCss; use style_traits::cursor::Cursor; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; #[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)] pub enum Keyword { Auto, Cursor(Cursor), } #[cfg(not(feature = "gecko"))] pub type T = Keyword; #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Image { pub url: SpecifiedUrl, pub hotspot: Option<(f32, f32)>, } #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct T { pub images: Vec<Image>, pub keyword: Keyword, } #[cfg(feature = "gecko")] impl ToCss for Image { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.url.to_css(dest)?; if let Some((x, y)) = self.hotspot { dest.write_str(" ")?; x.to_css(dest)?; dest.write_str(" ")?; y.to_css(dest)?; } Ok(()) } } #[cfg(feature = "gecko")] impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { for url in &self.images { url.to_css(dest)?; dest.write_str(", ")?; } self.keyword.to_css(dest) } } } #[cfg(not(feature = "gecko"))] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::Keyword::Auto } #[cfg(feature = "gecko")] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { images: vec![], keyword: computed_value::Keyword::Auto } } impl Parse for computed_value::Keyword { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Keyword, ParseError<'i>> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor; let location = input.current_source_location(); let ident = input.expect_ident()?; if ident.eq_ignore_ascii_case("auto") { Ok(computed_value::Keyword::Auto) } else { Cursor::from_css_keyword(&ident) .map(computed_value::Keyword::Cursor) .map_err(|()| location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))) } } } #[cfg(feature = "gecko")] fn parse_image<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Image, ParseError<'i>> { Ok(computed_value::Image { url: SpecifiedUrl::parse(context, input)?, hotspot: match input.try(|input| input.expect_number()) { Ok(number) => Some((number, input.expect_number()?)), Err(_) => None, }, }) } #[cfg(not(feature = "gecko"))] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { computed_value::Keyword::parse(context, input) } /// cursor: [<url> [<number> <number>]?]# [auto | default |...] #[cfg(feature = "gecko")] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { let mut images = vec![]; loop { match input.try(|input| parse_image(context, input)) { Ok(mut image) => { image.url.build_image_value(); images.push(image) } Err(_) => break, } input.expect_comma()?; } Ok(computed_value::T { images: images, keyword: computed_value::Keyword::parse(context, input)?, }) }
</%helpers:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${helpers.single_keyword("pointer-events", "auto none", animation_value_type="discrete", extra_gecko_values="visiblepainted visiblefill visiblestroke visible painted fill stroke all", flags="APPLIES_TO_PLACEHOLDER", spec="https://www.w3.org/TR/SVG11/interact.html#PointerEventsProperty")} ${helpers.single_keyword("-moz-user-input", "auto none enabled disabled", products="gecko", gecko_ffi_name="mUserInput", gecko_enum_prefix="StyleUserInput", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-input)")} ${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko", gecko_ffi_name="mUserModify", gecko_enum_prefix="StyleUserModify", needs_conversion=True, animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-modify)")} ${helpers.single_keyword("-moz-user-focus", "none ignore normal select-after select-before select-menu select-same select-all", products="gecko", gecko_ffi_name="mUserFocus", gecko_enum_prefix="StyleUserFocus", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-focus)")} ${helpers.predefined_type( "caret-color", "ColorOrAuto", "Either::Second(Auto)", spec="https://drafts.csswg.org/css-ui/#caret-color", animation_value_type="Either<AnimatedColor, Auto>", boxed=True, ignored_when_colors_disabled=True, products="gecko", )} ${helpers.predefined_type( "-moz-font-smoothing-background-color", "RGBAColor", "RGBA::transparent()", animation_value_type="AnimatedRGBA", products="gecko", gecko_ffi_name="mFontSmoothingBackgroundColor", internal=True, spec="None (Nonstandard internal property)" )}
random_line_split
issue-1655.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. // error-pattern:expected one of `!` or `[`, found `vec` mod blade_runner { #vec[doc( brief = "Blade Runner is probably the best movie ever", desc = "I like that in the world of Blade Runner it is always raining, and that it's always night time. And Aliens was also a really good movie. Alien 3 was crap though."
}
)]
random_line_split
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* with the // `#[derive(RustcEncodable, RustcDecodable)]` macros. In theory both of these // can be behind a #[cfg_attr], but that unfortunately doesn't work for two // reasons: // // 1. rust-lang/rust#32957 - means the include! of this module doesn't expand // the RustcDecodable/RustcEncodable blocks. // 2. serde-rs/serde#148 - means that Serialize/Deserialize won't get expanded. // // We just hack around it by doing #[cfg_attr] manually essentially. Our build // script will just strip the `//~ HACKn` prefixes here if the corresponding // feature is enabled. /// Representation of an owned and self-contained backtrace. /// /// This structure can be used to capture a backtrace at various points in a /// program and later used to inspect what the backtrace was at that time. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct Backtrace { frames: Vec<BacktraceFrame>, } /// Captured version of a frame in a backtrace. /// /// This type is returned as a list from `Backtrace::frames` and represents one /// stack frame in a captured backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceFrame { ip: usize, symbol_address: usize, symbols: Vec<BacktraceSymbol>, } /// Captured version of a symbol in a backtrace. /// /// This type is returned as a list from `BacktraceFrame::symbols` and /// represents the metadata for a symbol in a backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceSymbol { name: Option<Vec<u8>>, addr: Option<usize>, filename: Option<PathBuf>, lineno: Option<u32>, } impl Backtrace { /// Captures a backtrace at the callsite of this function, returning an /// owned representation. /// /// This function is useful for representing a backtrace as an object in /// Rust. This returned value can be sent across threads and printed /// elsewhere, and thie purpose of this value is to be entirely self /// contained. /// /// # Examples /// /// ``` /// use backtrace::Backtrace; /// /// let current_backtrace = Backtrace::new(); /// ``` pub fn new() -> Backtrace { let mut frames = Vec::new(); trace(|frame| { let mut symbols = Vec::new(); resolve(frame.ip(), |symbol| { symbols.push(BacktraceSymbol { name: symbol.name().map(|m| m.as_bytes().to_vec()), addr: symbol.addr().map(|a| a as usize), filename: symbol.filename().map(|m| m.to_path_buf()), lineno: symbol.lineno(), }); }); frames.push(BacktraceFrame { ip: frame.ip() as usize, symbol_address: frame.symbol_address() as usize, symbols: symbols, }); true }); Backtrace { frames: frames } } /// Returns the frames from when this backtrace was captured. /// /// The first entry of this slice is likely the function `Backtrace::new`, /// and the last frame is likely something about how this thread or the main /// function started. pub fn frames(&self) -> &[BacktraceFrame] { &self.frames } } impl From<Vec<BacktraceFrame>> for Backtrace { fn from(frames: Vec<BacktraceFrame>) -> Self { Backtrace { frames: frames } } } impl Into<Vec<BacktraceFrame>> for Backtrace { fn into(self) -> Vec<BacktraceFrame> { self.frames } } impl BacktraceFrame { /// Same as `Frame::ip` pub fn ip(&self) -> *mut c_void { self.ip as *mut c_void } /// Same as `Frame::symbol_address` pub fn symbol_address(&self) -> *mut c_void { self.symbol_address as *mut c_void } } impl BacktraceFrame { /// Returns the list of symbols that this frame corresponds to. /// /// Normally there is only one symbol per frame, but sometimes if a number /// of functions are inlined into one frame then multiple symbols will be /// returned. The first symbol listed is the "innermost function", whereas /// the last symbol is the outermost (last caller). pub fn symbols(&self) -> &[BacktraceSymbol] { &self.symbols } } impl BacktraceSymbol { /// Same as `Symbol::name` pub fn name(&self) -> Option<SymbolName> { self.name.as_ref().map(|s| SymbolName::new(s)) } /// Same as `Symbol::addr` pub fn
(&self) -> Option<*mut c_void> { self.addr.map(|s| s as *mut c_void) } /// Same as `Symbol::filename` pub fn filename(&self) -> Option<&Path> { self.filename.as_ref().map(|p| &**p) } /// Same as `Symbol::lineno` pub fn lineno(&self) -> Option<u32> { self.lineno } } impl fmt::Debug for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let hex_width = mem::size_of::<usize>() * 2 + 2; try!(write!(fmt, "stack backtrace:")); for (idx, frame) in self.frames().iter().enumerate() { let ip = frame.ip(); try!(write!(fmt, "\n{:4}: {:2$?}", idx, ip, hex_width)); if frame.symbols.len() == 0 { try!(write!(fmt, " - <no info>")); } for (idx, symbol) in frame.symbols().iter().enumerate() { if idx!= 0 { try!(write!(fmt, "\n {:1$}", "", hex_width)); } if let Some(name) = symbol.name() { try!(write!(fmt, " - {}", name)); } else { try!(write!(fmt, " - <unknown>")); } if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) { try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); } } } Ok(()) } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } }
addr
identifier_name
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* with the // `#[derive(RustcEncodable, RustcDecodable)]` macros. In theory both of these // can be behind a #[cfg_attr], but that unfortunately doesn't work for two // reasons: // // 1. rust-lang/rust#32957 - means the include! of this module doesn't expand // the RustcDecodable/RustcEncodable blocks. // 2. serde-rs/serde#148 - means that Serialize/Deserialize won't get expanded. // // We just hack around it by doing #[cfg_attr] manually essentially. Our build // script will just strip the `//~ HACKn` prefixes here if the corresponding // feature is enabled. /// Representation of an owned and self-contained backtrace. /// /// This structure can be used to capture a backtrace at various points in a /// program and later used to inspect what the backtrace was at that time. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct Backtrace { frames: Vec<BacktraceFrame>, } /// Captured version of a frame in a backtrace. /// /// This type is returned as a list from `Backtrace::frames` and represents one /// stack frame in a captured backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceFrame { ip: usize, symbol_address: usize, symbols: Vec<BacktraceSymbol>, } /// Captured version of a symbol in a backtrace. /// /// This type is returned as a list from `BacktraceFrame::symbols` and /// represents the metadata for a symbol in a backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceSymbol { name: Option<Vec<u8>>, addr: Option<usize>, filename: Option<PathBuf>, lineno: Option<u32>, } impl Backtrace { /// Captures a backtrace at the callsite of this function, returning an /// owned representation. /// /// This function is useful for representing a backtrace as an object in /// Rust. This returned value can be sent across threads and printed /// elsewhere, and thie purpose of this value is to be entirely self /// contained. /// /// # Examples /// /// ``` /// use backtrace::Backtrace; /// /// let current_backtrace = Backtrace::new(); /// ``` pub fn new() -> Backtrace { let mut frames = Vec::new(); trace(|frame| { let mut symbols = Vec::new(); resolve(frame.ip(), |symbol| { symbols.push(BacktraceSymbol { name: symbol.name().map(|m| m.as_bytes().to_vec()), addr: symbol.addr().map(|a| a as usize), filename: symbol.filename().map(|m| m.to_path_buf()), lineno: symbol.lineno(), }); }); frames.push(BacktraceFrame { ip: frame.ip() as usize, symbol_address: frame.symbol_address() as usize, symbols: symbols, }); true }); Backtrace { frames: frames } } /// Returns the frames from when this backtrace was captured. /// /// The first entry of this slice is likely the function `Backtrace::new`, /// and the last frame is likely something about how this thread or the main /// function started. pub fn frames(&self) -> &[BacktraceFrame] { &self.frames } } impl From<Vec<BacktraceFrame>> for Backtrace { fn from(frames: Vec<BacktraceFrame>) -> Self { Backtrace { frames: frames } } } impl Into<Vec<BacktraceFrame>> for Backtrace { fn into(self) -> Vec<BacktraceFrame> { self.frames } } impl BacktraceFrame { /// Same as `Frame::ip` pub fn ip(&self) -> *mut c_void { self.ip as *mut c_void } /// Same as `Frame::symbol_address` pub fn symbol_address(&self) -> *mut c_void
} impl BacktraceFrame { /// Returns the list of symbols that this frame corresponds to. /// /// Normally there is only one symbol per frame, but sometimes if a number /// of functions are inlined into one frame then multiple symbols will be /// returned. The first symbol listed is the "innermost function", whereas /// the last symbol is the outermost (last caller). pub fn symbols(&self) -> &[BacktraceSymbol] { &self.symbols } } impl BacktraceSymbol { /// Same as `Symbol::name` pub fn name(&self) -> Option<SymbolName> { self.name.as_ref().map(|s| SymbolName::new(s)) } /// Same as `Symbol::addr` pub fn addr(&self) -> Option<*mut c_void> { self.addr.map(|s| s as *mut c_void) } /// Same as `Symbol::filename` pub fn filename(&self) -> Option<&Path> { self.filename.as_ref().map(|p| &**p) } /// Same as `Symbol::lineno` pub fn lineno(&self) -> Option<u32> { self.lineno } } impl fmt::Debug for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let hex_width = mem::size_of::<usize>() * 2 + 2; try!(write!(fmt, "stack backtrace:")); for (idx, frame) in self.frames().iter().enumerate() { let ip = frame.ip(); try!(write!(fmt, "\n{:4}: {:2$?}", idx, ip, hex_width)); if frame.symbols.len() == 0 { try!(write!(fmt, " - <no info>")); } for (idx, symbol) in frame.symbols().iter().enumerate() { if idx!= 0 { try!(write!(fmt, "\n {:1$}", "", hex_width)); } if let Some(name) = symbol.name() { try!(write!(fmt, " - {}", name)); } else { try!(write!(fmt, " - <unknown>")); } if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) { try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); } } } Ok(()) } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } }
{ self.symbol_address as *mut c_void }
identifier_body
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* with the // `#[derive(RustcEncodable, RustcDecodable)]` macros. In theory both of these // can be behind a #[cfg_attr], but that unfortunately doesn't work for two // reasons: // // 1. rust-lang/rust#32957 - means the include! of this module doesn't expand // the RustcDecodable/RustcEncodable blocks. // 2. serde-rs/serde#148 - means that Serialize/Deserialize won't get expanded. // // We just hack around it by doing #[cfg_attr] manually essentially. Our build // script will just strip the `//~ HACKn` prefixes here if the corresponding // feature is enabled. /// Representation of an owned and self-contained backtrace. /// /// This structure can be used to capture a backtrace at various points in a /// program and later used to inspect what the backtrace was at that time. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct Backtrace { frames: Vec<BacktraceFrame>, } /// Captured version of a frame in a backtrace. /// /// This type is returned as a list from `Backtrace::frames` and represents one /// stack frame in a captured backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceFrame { ip: usize, symbol_address: usize, symbols: Vec<BacktraceSymbol>, } /// Captured version of a symbol in a backtrace. /// /// This type is returned as a list from `BacktraceFrame::symbols` and /// represents the metadata for a symbol in a backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceSymbol { name: Option<Vec<u8>>, addr: Option<usize>, filename: Option<PathBuf>, lineno: Option<u32>, } impl Backtrace { /// Captures a backtrace at the callsite of this function, returning an /// owned representation. /// /// This function is useful for representing a backtrace as an object in /// Rust. This returned value can be sent across threads and printed /// elsewhere, and thie purpose of this value is to be entirely self /// contained. /// /// # Examples /// /// ``` /// use backtrace::Backtrace; ///
trace(|frame| { let mut symbols = Vec::new(); resolve(frame.ip(), |symbol| { symbols.push(BacktraceSymbol { name: symbol.name().map(|m| m.as_bytes().to_vec()), addr: symbol.addr().map(|a| a as usize), filename: symbol.filename().map(|m| m.to_path_buf()), lineno: symbol.lineno(), }); }); frames.push(BacktraceFrame { ip: frame.ip() as usize, symbol_address: frame.symbol_address() as usize, symbols: symbols, }); true }); Backtrace { frames: frames } } /// Returns the frames from when this backtrace was captured. /// /// The first entry of this slice is likely the function `Backtrace::new`, /// and the last frame is likely something about how this thread or the main /// function started. pub fn frames(&self) -> &[BacktraceFrame] { &self.frames } } impl From<Vec<BacktraceFrame>> for Backtrace { fn from(frames: Vec<BacktraceFrame>) -> Self { Backtrace { frames: frames } } } impl Into<Vec<BacktraceFrame>> for Backtrace { fn into(self) -> Vec<BacktraceFrame> { self.frames } } impl BacktraceFrame { /// Same as `Frame::ip` pub fn ip(&self) -> *mut c_void { self.ip as *mut c_void } /// Same as `Frame::symbol_address` pub fn symbol_address(&self) -> *mut c_void { self.symbol_address as *mut c_void } } impl BacktraceFrame { /// Returns the list of symbols that this frame corresponds to. /// /// Normally there is only one symbol per frame, but sometimes if a number /// of functions are inlined into one frame then multiple symbols will be /// returned. The first symbol listed is the "innermost function", whereas /// the last symbol is the outermost (last caller). pub fn symbols(&self) -> &[BacktraceSymbol] { &self.symbols } } impl BacktraceSymbol { /// Same as `Symbol::name` pub fn name(&self) -> Option<SymbolName> { self.name.as_ref().map(|s| SymbolName::new(s)) } /// Same as `Symbol::addr` pub fn addr(&self) -> Option<*mut c_void> { self.addr.map(|s| s as *mut c_void) } /// Same as `Symbol::filename` pub fn filename(&self) -> Option<&Path> { self.filename.as_ref().map(|p| &**p) } /// Same as `Symbol::lineno` pub fn lineno(&self) -> Option<u32> { self.lineno } } impl fmt::Debug for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let hex_width = mem::size_of::<usize>() * 2 + 2; try!(write!(fmt, "stack backtrace:")); for (idx, frame) in self.frames().iter().enumerate() { let ip = frame.ip(); try!(write!(fmt, "\n{:4}: {:2$?}", idx, ip, hex_width)); if frame.symbols.len() == 0 { try!(write!(fmt, " - <no info>")); } for (idx, symbol) in frame.symbols().iter().enumerate() { if idx!= 0 { try!(write!(fmt, "\n {:1$}", "", hex_width)); } if let Some(name) = symbol.name() { try!(write!(fmt, " - {}", name)); } else { try!(write!(fmt, " - <unknown>")); } if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) { try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); } } } Ok(()) } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } }
/// let current_backtrace = Backtrace::new(); /// ``` pub fn new() -> Backtrace { let mut frames = Vec::new();
random_line_split
capture.rs
use std::fmt; use std::mem; use std::os::raw::c_void; use std::path::{Path, PathBuf}; use {trace, resolve, SymbolName}; // Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to // compile on stable for serde support, but we also want to use // #[derive(Serialize, Deserialize)] macros *along* with the // `#[derive(RustcEncodable, RustcDecodable)]` macros. In theory both of these // can be behind a #[cfg_attr], but that unfortunately doesn't work for two // reasons: // // 1. rust-lang/rust#32957 - means the include! of this module doesn't expand // the RustcDecodable/RustcEncodable blocks. // 2. serde-rs/serde#148 - means that Serialize/Deserialize won't get expanded. // // We just hack around it by doing #[cfg_attr] manually essentially. Our build // script will just strip the `//~ HACKn` prefixes here if the corresponding // feature is enabled. /// Representation of an owned and self-contained backtrace. /// /// This structure can be used to capture a backtrace at various points in a /// program and later used to inspect what the backtrace was at that time. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct Backtrace { frames: Vec<BacktraceFrame>, } /// Captured version of a frame in a backtrace. /// /// This type is returned as a list from `Backtrace::frames` and represents one /// stack frame in a captured backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceFrame { ip: usize, symbol_address: usize, symbols: Vec<BacktraceSymbol>, } /// Captured version of a symbol in a backtrace. /// /// This type is returned as a list from `BacktraceFrame::symbols` and /// represents the metadata for a symbol in a backtrace. #[derive(Clone)] //~ HACK1 #[derive(RustcDecodable, RustcEncodable)] //~ HACK2 #[derive(Deserialize, Serialize)] pub struct BacktraceSymbol { name: Option<Vec<u8>>, addr: Option<usize>, filename: Option<PathBuf>, lineno: Option<u32>, } impl Backtrace { /// Captures a backtrace at the callsite of this function, returning an /// owned representation. /// /// This function is useful for representing a backtrace as an object in /// Rust. This returned value can be sent across threads and printed /// elsewhere, and thie purpose of this value is to be entirely self /// contained. /// /// # Examples /// /// ``` /// use backtrace::Backtrace; /// /// let current_backtrace = Backtrace::new(); /// ``` pub fn new() -> Backtrace { let mut frames = Vec::new(); trace(|frame| { let mut symbols = Vec::new(); resolve(frame.ip(), |symbol| { symbols.push(BacktraceSymbol { name: symbol.name().map(|m| m.as_bytes().to_vec()), addr: symbol.addr().map(|a| a as usize), filename: symbol.filename().map(|m| m.to_path_buf()), lineno: symbol.lineno(), }); }); frames.push(BacktraceFrame { ip: frame.ip() as usize, symbol_address: frame.symbol_address() as usize, symbols: symbols, }); true }); Backtrace { frames: frames } } /// Returns the frames from when this backtrace was captured. /// /// The first entry of this slice is likely the function `Backtrace::new`, /// and the last frame is likely something about how this thread or the main /// function started. pub fn frames(&self) -> &[BacktraceFrame] { &self.frames } } impl From<Vec<BacktraceFrame>> for Backtrace { fn from(frames: Vec<BacktraceFrame>) -> Self { Backtrace { frames: frames } } } impl Into<Vec<BacktraceFrame>> for Backtrace { fn into(self) -> Vec<BacktraceFrame> { self.frames } } impl BacktraceFrame { /// Same as `Frame::ip` pub fn ip(&self) -> *mut c_void { self.ip as *mut c_void } /// Same as `Frame::symbol_address` pub fn symbol_address(&self) -> *mut c_void { self.symbol_address as *mut c_void } } impl BacktraceFrame { /// Returns the list of symbols that this frame corresponds to. /// /// Normally there is only one symbol per frame, but sometimes if a number /// of functions are inlined into one frame then multiple symbols will be /// returned. The first symbol listed is the "innermost function", whereas /// the last symbol is the outermost (last caller). pub fn symbols(&self) -> &[BacktraceSymbol] { &self.symbols } } impl BacktraceSymbol { /// Same as `Symbol::name` pub fn name(&self) -> Option<SymbolName> { self.name.as_ref().map(|s| SymbolName::new(s)) } /// Same as `Symbol::addr` pub fn addr(&self) -> Option<*mut c_void> { self.addr.map(|s| s as *mut c_void) } /// Same as `Symbol::filename` pub fn filename(&self) -> Option<&Path> { self.filename.as_ref().map(|p| &**p) } /// Same as `Symbol::lineno` pub fn lineno(&self) -> Option<u32> { self.lineno } } impl fmt::Debug for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let hex_width = mem::size_of::<usize>() * 2 + 2; try!(write!(fmt, "stack backtrace:")); for (idx, frame) in self.frames().iter().enumerate() { let ip = frame.ip(); try!(write!(fmt, "\n{:4}: {:2$?}", idx, ip, hex_width)); if frame.symbols.len() == 0 { try!(write!(fmt, " - <no info>")); } for (idx, symbol) in frame.symbols().iter().enumerate() { if idx!= 0 { try!(write!(fmt, "\n {:1$}", "", hex_width)); } if let Some(name) = symbol.name() { try!(write!(fmt, " - {}", name)); } else { try!(write!(fmt, " - <unknown>")); } if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno())
} } Ok(()) } } impl Default for Backtrace { fn default() -> Backtrace { Backtrace::new() } }
{ try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); }
conditional_block
regions-trait-2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test #5723 // Test that you cannot escape a reference // into a trait. struct ctxt { v: usize } trait get_ctxt { fn get_ctxt(&self) -> &'a ctxt; } struct has_ctxt<'a> { c: &'a ctxt } impl<'a> get_ctxt for has_ctxt<'a> { fn get_ctxt(&self) -> &'a ctxt { self.c } } fn make_gc() -> @get_ctxt { let ctxt = ctxt { v: 22 }; let hc = has_ctxt { c: &ctxt }; return @hc as @get_ctxt; //~^ ERROR source contains reference } fn
() { make_gc().get_ctxt().v; }
main
identifier_name
regions-trait-2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test #5723 // Test that you cannot escape a reference // into a trait. struct ctxt { v: usize } trait get_ctxt { fn get_ctxt(&self) -> &'a ctxt; } struct has_ctxt<'a> { c: &'a ctxt }
let ctxt = ctxt { v: 22 }; let hc = has_ctxt { c: &ctxt }; return @hc as @get_ctxt; //~^ ERROR source contains reference } fn main() { make_gc().get_ctxt().v; }
impl<'a> get_ctxt for has_ctxt<'a> { fn get_ctxt(&self) -> &'a ctxt { self.c } } fn make_gc() -> @get_ctxt {
random_line_split
ast.rs
#[derive(Debug, PartialEq, Clone)] pub enum Expr { Binary(Box<Expr>, Op, Box<Expr>), Number(f64), Str(String), Name(String), Call(Box<Expr>, Vec<Box<Expr>>), Lambda(Vec<String>, Box<Expr>), Pull, FinishedPipe, Block(Vec<Box<Expr>>), If(Box<Expr>, Box<Expr>, Box<Expr>), While(Box<Expr>, Box<Expr>), Assignment(String, Box<Expr>), Push(Box<Expr>), Bool(bool), Return(Box<Expr>), Neg(Box<Expr>), Index(Box<Expr>, Box<Expr>), //Attribute(Box<Expr>, String), } #[derive(Debug, PartialEq, Clone)] pub enum Op { Plus, Minus, Times, Slash, Pipe, Percent, Greater, Lesser, Equals, NotEquals, And, Or, } #[derive(Debug, PartialEq, Clone)] pub enum Top { Use(String), Definition(Definition), } #[derive(Debug, PartialEq, Clone)] pub struct Prototype { pub name: String, pub args: Vec<String>, } impl Prototype { pub fn new(name: String, args: Vec<String>) -> Prototype { Prototype { name: name, args: args, } } } #[derive(Debug, PartialEq, Clone)] pub struct
{ pub prototype: Prototype, pub body: Box<Expr>, } impl Definition { pub fn new(prototype: Prototype, body: Box<Expr>) -> Definition { Definition { prototype: prototype, body: body, } } }
Definition
identifier_name
ast.rs
#[derive(Debug, PartialEq, Clone)] pub enum Expr { Binary(Box<Expr>, Op, Box<Expr>), Number(f64), Str(String), Name(String), Call(Box<Expr>, Vec<Box<Expr>>), Lambda(Vec<String>, Box<Expr>), Pull, FinishedPipe, Block(Vec<Box<Expr>>), If(Box<Expr>, Box<Expr>, Box<Expr>), While(Box<Expr>, Box<Expr>), Assignment(String, Box<Expr>), Push(Box<Expr>), Bool(bool), Return(Box<Expr>), Neg(Box<Expr>), Index(Box<Expr>, Box<Expr>), //Attribute(Box<Expr>, String), } #[derive(Debug, PartialEq, Clone)] pub enum Op { Plus, Minus, Times, Slash, Pipe, Percent, Greater, Lesser, Equals, NotEquals, And, Or, } #[derive(Debug, PartialEq, Clone)] pub enum Top { Use(String), Definition(Definition), } #[derive(Debug, PartialEq, Clone)] pub struct Prototype { pub name: String, pub args: Vec<String>, } impl Prototype { pub fn new(name: String, args: Vec<String>) -> Prototype { Prototype { name: name, args: args, } } }
#[derive(Debug, PartialEq, Clone)] pub struct Definition { pub prototype: Prototype, pub body: Box<Expr>, } impl Definition { pub fn new(prototype: Prototype, body: Box<Expr>) -> Definition { Definition { prototype: prototype, body: body, } } }
random_line_split
reader.rs
use std::path::Component; use migration::Migration; pub fn read_migrations(pattern: &str) -> Result<HashMap<String, Vec<Migration>>, String> { let mut migration_files = HashMap::new(); let entries = glob(pattern).map_err(|err| format!("Failed to read {} due {}", pattern, err))?; for entry in entries { let path = entry.map_err(|err| { format!( "Failed to read entry {} in {}", err.description(), err.path().display() ) })?; let folder = path.components().nth(1).ok_or(format!( "Could not find keyspace folder name from {}", path.display() ))?; let keyspace = match folder { Component::Normal(keyspace) => keyspace .to_str() .map(|k| k.to_string()) .ok_or(format!("Couldn't make string out of {:?}", keyspace)), _ => Err(format!( "There is no keyspace folder in path {}", path.display() )), }?; info!("File {:?} in keyspace {:?}", path.display(), keyspace); let migration = Migration::read_from(&path).map_err(|err| format!("{}: {}", path.display(), err))?; migration_files .entry(keyspace) .or_insert_with(|| vec![]) .push(migration) } Ok(migration_files) } #[cfg(test)] mod tests { use super::*; #[test] fn read_migration_files() { let read = read_migrations("./migrations/one/*.cql"); assert!(read.is_ok()); let migrations_map = read.unwrap(); assert_eq!(1, migrations_map.len()); let migrations = migrations_map.get("one").unwrap(); assert_eq!(2, migrations.len()); } }
use glob::glob; use std::collections::HashMap; use std::error::Error;
random_line_split
reader.rs
use glob::glob; use std::collections::HashMap; use std::error::Error; use std::path::Component; use migration::Migration; pub fn read_migrations(pattern: &str) -> Result<HashMap<String, Vec<Migration>>, String>
.to_str() .map(|k| k.to_string()) .ok_or(format!("Couldn't make string out of {:?}", keyspace)), _ => Err(format!( "There is no keyspace folder in path {}", path.display() )), }?; info!("File {:?} in keyspace {:?}", path.display(), keyspace); let migration = Migration::read_from(&path).map_err(|err| format!("{}: {}", path.display(), err))?; migration_files .entry(keyspace) .or_insert_with(|| vec![]) .push(migration) } Ok(migration_files) } #[cfg(test)] mod tests { use super::*; #[test] fn read_migration_files() { let read = read_migrations("./migrations/one/*.cql"); assert!(read.is_ok()); let migrations_map = read.unwrap(); assert_eq!(1, migrations_map.len()); let migrations = migrations_map.get("one").unwrap(); assert_eq!(2, migrations.len()); } }
{ let mut migration_files = HashMap::new(); let entries = glob(pattern).map_err(|err| format!("Failed to read {} due {}", pattern, err))?; for entry in entries { let path = entry.map_err(|err| { format!( "Failed to read entry {} in {}", err.description(), err.path().display() ) })?; let folder = path.components().nth(1).ok_or(format!( "Could not find keyspace folder name from {}", path.display() ))?; let keyspace = match folder { Component::Normal(keyspace) => keyspace
identifier_body
reader.rs
use glob::glob; use std::collections::HashMap; use std::error::Error; use std::path::Component; use migration::Migration; pub fn
(pattern: &str) -> Result<HashMap<String, Vec<Migration>>, String> { let mut migration_files = HashMap::new(); let entries = glob(pattern).map_err(|err| format!("Failed to read {} due {}", pattern, err))?; for entry in entries { let path = entry.map_err(|err| { format!( "Failed to read entry {} in {}", err.description(), err.path().display() ) })?; let folder = path.components().nth(1).ok_or(format!( "Could not find keyspace folder name from {}", path.display() ))?; let keyspace = match folder { Component::Normal(keyspace) => keyspace .to_str() .map(|k| k.to_string()) .ok_or(format!("Couldn't make string out of {:?}", keyspace)), _ => Err(format!( "There is no keyspace folder in path {}", path.display() )), }?; info!("File {:?} in keyspace {:?}", path.display(), keyspace); let migration = Migration::read_from(&path).map_err(|err| format!("{}: {}", path.display(), err))?; migration_files .entry(keyspace) .or_insert_with(|| vec![]) .push(migration) } Ok(migration_files) } #[cfg(test)] mod tests { use super::*; #[test] fn read_migration_files() { let read = read_migrations("./migrations/one/*.cql"); assert!(read.is_ok()); let migrations_map = read.unwrap(); assert_eq!(1, migrations_map.len()); let migrations = migrations_map.get("one").unwrap(); assert_eq!(2, migrations.len()); } }
read_migrations
identifier_name
color.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 color values. use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError}; #[cfg(feature = "gecko")] use gecko_bindings::structs::nscolor; use itoa; use parser::{ParserContext, Parse}; #[cfg(feature = "gecko")] use properties::longhands::color::SystemColor; use std::fmt; use std::io::Write; use style_traits::{ToCss, ParseError, StyleParseError, ValueParseError}; use super::AllowQuirks; use values::computed::{Color as ComputedColor, Context, ToComputedValue}; /// Specified color value #[derive(Clone, PartialEq, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// A special color keyword value used in Gecko #[cfg(feature = "gecko")] Special(gecko::SpecialColorKeyword), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } no_viewport_percentage!(Color); #[cfg(feature = "gecko")] mod gecko { use style_traits::ToCss; define_css_keyword_enum! { SpecialColorKeyword: "-moz-default-color" => MozDefaultColor, "-moz-default-background-color" => MozDefaultBackgroundColor, "-moz-hyperlinktext" => MozHyperlinktext, "-moz-activehyperlinktext" => MozActiveHyperlinktext, "-moz-visitedhyperlinktext" => MozVisitedHyperlinktext, } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } impl Parse for Color { fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = match input.next() { Ok(&Token::Ident(ref s)) => Some(s.to_lowercase().into_boxed_str()), _ => None, }; input.reset(&start); match input.try(CSSParserColor::parse) { Ok(value) => Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor, CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored, }, }), Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(SystemColor::parse) { return Ok(Color::System(system)); } else if let Ok(c) = gecko::SpecialColorKeyword::parse(input) { return Ok(Color::Special(c)); } } match e { BasicParseError::UnexpectedToken(t) => Err(StyleParseError::ValueError(ValueParseError::InvalidColor(t)).into()), e => Err(e.into()) } } } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored),.. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba,.. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::Special(special) => special.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense /// to handle a cssparser::Color here. This should really be done in /// cssparser directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| { match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), } }) } impl Color { /// Returns currentcolor value. #[inline] pub fn currentcolor() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn rgba(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk pub fn parse_quirky<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if!allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(|rgba| Color::rgba(rgba)) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer),.. } => { (integer, None) }, Token::Dimension { int_value: Some(integer), ref unit,.. } => { (integer, Some(unit)) }, Token::Ident(ref ident) => { if ident.len()!= 3 && ident.len()!= 6 { return Err(StyleParseError::UnspecifiedError.into()); } return parse_hash_color(ident.as_bytes()) .map_err(|()| StyleParseError::UnspecifiedError.into()); } ref t => { return Err(BasicParseError::UnexpectedToken(t.clone()).into()); }, }; if value < 0 { return Err(StyleParseError::UnspecifiedError.into()); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(StyleParseError::UnspecifiedError.into()) }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(StyleParseError::UnspecifiedError.into()); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]).write(unit.as_bytes()).unwrap(); } debug_assert!(written == 6); parse_hash_color(&serialization).map_err(|()| StyleParseError::UnspecifiedError.into()) } /// Returns false if the color is completely transparent, and /// true otherwise. pub fn is_non_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed,.. } => parsed.alpha!= 0, _ => true, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, _context: &Context) -> ComputedColor { match *self { Color::CurrentColor => ComputedColor::currentcolor(), Color::Numeric { ref parsed,.. } => ComputedColor::rgba(*parsed), Color::Complex(ref complex) => *complex, #[cfg(feature = "gecko")] Color::System(system) => convert_nscolor_to_computedcolor(system.to_computed_value(_context)), #[cfg(feature = "gecko")] Color::Special(special) => { use self::gecko::SpecialColorKeyword as Keyword; let pres_context = _context.device().pres_context(); convert_nscolor_to_computedcolor(match special { Keyword::MozDefaultColor => pres_context.mDefaultColor, Keyword::MozDefaultBackgroundColor => pres_context.mBackgroundColor, Keyword::MozHyperlinktext => pres_context.mLinkColor, Keyword::MozActiveHyperlinktext => pres_context.mActiveLinkColor, Keyword::MozVisitedHyperlinktext => pres_context.mVisitedLinkColor, }) } #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { use dom::TElement; use gecko::wrapper::GeckoElement; use gecko_bindings::bindings::Gecko_GetBody; let pres_context = _context.device().pres_context(); let body = unsafe { Gecko_GetBody(pres_context) }.map(GeckoElement); let data = body.as_ref().and_then(|wrap| wrap.borrow_data()); if let Some(data) = data { ComputedColor::rgba(data.styles.primary() .get_color() .clone_color()) } else { convert_nscolor_to_computedcolor(pres_context.mDefaultColor) } }, } } fn from_computed_value(computed: &ComputedColor) -> Self
} /// Specified color value, but resolved to just RGBA for computed value /// with value from color property at the same context. #[derive(Clone, Debug, PartialEq, ToCss)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct RGBAColor(pub Color); no_viewport_percentage!(RGBAColor); impl Parse for RGBAColor { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Color::parse(context, input).map(RGBAColor) } } impl ToComputedValue for RGBAColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0.to_computed_value(context) .to_rgba(context.style().get_color().clone_color()) } fn from_computed_value(computed: &RGBA) -> Self { RGBAColor(Color::rgba(*computed)) } } impl From<Color> for RGBAColor { fn from(color: Color) -> RGBAColor { RGBAColor(color) } }
{ if computed.is_numeric() { Color::rgba(computed.color) } else if computed.is_currentcolor() { Color::currentcolor() } else { Color::Complex(*computed) } }
identifier_body
color.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 color values. use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError}; #[cfg(feature = "gecko")] use gecko_bindings::structs::nscolor; use itoa; use parser::{ParserContext, Parse}; #[cfg(feature = "gecko")] use properties::longhands::color::SystemColor; use std::fmt; use std::io::Write; use style_traits::{ToCss, ParseError, StyleParseError, ValueParseError}; use super::AllowQuirks; use values::computed::{Color as ComputedColor, Context, ToComputedValue}; /// Specified color value #[derive(Clone, PartialEq, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// A special color keyword value used in Gecko #[cfg(feature = "gecko")] Special(gecko::SpecialColorKeyword), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } no_viewport_percentage!(Color); #[cfg(feature = "gecko")] mod gecko { use style_traits::ToCss; define_css_keyword_enum! { SpecialColorKeyword: "-moz-default-color" => MozDefaultColor, "-moz-default-background-color" => MozDefaultBackgroundColor, "-moz-hyperlinktext" => MozHyperlinktext, "-moz-activehyperlinktext" => MozActiveHyperlinktext, "-moz-visitedhyperlinktext" => MozVisitedHyperlinktext, } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } impl Parse for Color { fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = match input.next() { Ok(&Token::Ident(ref s)) => Some(s.to_lowercase().into_boxed_str()), _ => None, }; input.reset(&start); match input.try(CSSParserColor::parse) { Ok(value) => Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor, CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored, }, }), Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(SystemColor::parse) { return Ok(Color::System(system)); } else if let Ok(c) = gecko::SpecialColorKeyword::parse(input) { return Ok(Color::Special(c)); } } match e { BasicParseError::UnexpectedToken(t) => Err(StyleParseError::ValueError(ValueParseError::InvalidColor(t)).into()), e => Err(e.into()) } } } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored),.. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba,.. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::Special(special) => special.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense /// to handle a cssparser::Color here. This should really be done in /// cssparser directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| { match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), } }) } impl Color { /// Returns currentcolor value. #[inline] pub fn currentcolor() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn
(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk pub fn parse_quirky<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if!allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(|rgba| Color::rgba(rgba)) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer),.. } => { (integer, None) }, Token::Dimension { int_value: Some(integer), ref unit,.. } => { (integer, Some(unit)) }, Token::Ident(ref ident) => { if ident.len()!= 3 && ident.len()!= 6 { return Err(StyleParseError::UnspecifiedError.into()); } return parse_hash_color(ident.as_bytes()) .map_err(|()| StyleParseError::UnspecifiedError.into()); } ref t => { return Err(BasicParseError::UnexpectedToken(t.clone()).into()); }, }; if value < 0 { return Err(StyleParseError::UnspecifiedError.into()); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(StyleParseError::UnspecifiedError.into()) }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(StyleParseError::UnspecifiedError.into()); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]).write(unit.as_bytes()).unwrap(); } debug_assert!(written == 6); parse_hash_color(&serialization).map_err(|()| StyleParseError::UnspecifiedError.into()) } /// Returns false if the color is completely transparent, and /// true otherwise. pub fn is_non_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed,.. } => parsed.alpha!= 0, _ => true, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, _context: &Context) -> ComputedColor { match *self { Color::CurrentColor => ComputedColor::currentcolor(), Color::Numeric { ref parsed,.. } => ComputedColor::rgba(*parsed), Color::Complex(ref complex) => *complex, #[cfg(feature = "gecko")] Color::System(system) => convert_nscolor_to_computedcolor(system.to_computed_value(_context)), #[cfg(feature = "gecko")] Color::Special(special) => { use self::gecko::SpecialColorKeyword as Keyword; let pres_context = _context.device().pres_context(); convert_nscolor_to_computedcolor(match special { Keyword::MozDefaultColor => pres_context.mDefaultColor, Keyword::MozDefaultBackgroundColor => pres_context.mBackgroundColor, Keyword::MozHyperlinktext => pres_context.mLinkColor, Keyword::MozActiveHyperlinktext => pres_context.mActiveLinkColor, Keyword::MozVisitedHyperlinktext => pres_context.mVisitedLinkColor, }) } #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { use dom::TElement; use gecko::wrapper::GeckoElement; use gecko_bindings::bindings::Gecko_GetBody; let pres_context = _context.device().pres_context(); let body = unsafe { Gecko_GetBody(pres_context) }.map(GeckoElement); let data = body.as_ref().and_then(|wrap| wrap.borrow_data()); if let Some(data) = data { ComputedColor::rgba(data.styles.primary() .get_color() .clone_color()) } else { convert_nscolor_to_computedcolor(pres_context.mDefaultColor) } }, } } fn from_computed_value(computed: &ComputedColor) -> Self { if computed.is_numeric() { Color::rgba(computed.color) } else if computed.is_currentcolor() { Color::currentcolor() } else { Color::Complex(*computed) } } } /// Specified color value, but resolved to just RGBA for computed value /// with value from color property at the same context. #[derive(Clone, Debug, PartialEq, ToCss)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct RGBAColor(pub Color); no_viewport_percentage!(RGBAColor); impl Parse for RGBAColor { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Color::parse(context, input).map(RGBAColor) } } impl ToComputedValue for RGBAColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0.to_computed_value(context) .to_rgba(context.style().get_color().clone_color()) } fn from_computed_value(computed: &RGBA) -> Self { RGBAColor(Color::rgba(*computed)) } } impl From<Color> for RGBAColor { fn from(color: Color) -> RGBAColor { RGBAColor(color) } }
rgba
identifier_name
color.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Color as CSSParserColor, Parser, RGBA, Token, BasicParseError}; #[cfg(feature = "gecko")] use gecko_bindings::structs::nscolor; use itoa; use parser::{ParserContext, Parse}; #[cfg(feature = "gecko")] use properties::longhands::color::SystemColor; use std::fmt; use std::io::Write; use style_traits::{ToCss, ParseError, StyleParseError, ValueParseError}; use super::AllowQuirks; use values::computed::{Color as ComputedColor, Context, ToComputedValue}; /// Specified color value #[derive(Clone, PartialEq, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// A special color keyword value used in Gecko #[cfg(feature = "gecko")] Special(gecko::SpecialColorKeyword), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } no_viewport_percentage!(Color); #[cfg(feature = "gecko")] mod gecko { use style_traits::ToCss; define_css_keyword_enum! { SpecialColorKeyword: "-moz-default-color" => MozDefaultColor, "-moz-default-background-color" => MozDefaultBackgroundColor, "-moz-hyperlinktext" => MozHyperlinktext, "-moz-activehyperlinktext" => MozActiveHyperlinktext, "-moz-visitedhyperlinktext" => MozVisitedHyperlinktext, } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } impl Parse for Color { fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = match input.next() { Ok(&Token::Ident(ref s)) => Some(s.to_lowercase().into_boxed_str()), _ => None, }; input.reset(&start); match input.try(CSSParserColor::parse) { Ok(value) => Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor, CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored, }, }), Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(SystemColor::parse) { return Ok(Color::System(system)); } else if let Ok(c) = gecko::SpecialColorKeyword::parse(input) { return Ok(Color::Special(c)); } } match e { BasicParseError::UnexpectedToken(t) => Err(StyleParseError::ValueError(ValueParseError::InvalidColor(t)).into()), e => Err(e.into()) } } } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored),.. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba,.. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::Special(special) => special.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense /// to handle a cssparser::Color here. This should really be done in /// cssparser directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| { match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), } }) } impl Color { /// Returns currentcolor value. #[inline] pub fn currentcolor() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn rgba(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk pub fn parse_quirky<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if!allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(|rgba| Color::rgba(rgba)) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer),.. } => { (integer, None) }, Token::Dimension { int_value: Some(integer), ref unit,.. } => { (integer, Some(unit)) }, Token::Ident(ref ident) => { if ident.len()!= 3 && ident.len()!= 6 { return Err(StyleParseError::UnspecifiedError.into()); } return parse_hash_color(ident.as_bytes()) .map_err(|()| StyleParseError::UnspecifiedError.into()); } ref t => { return Err(BasicParseError::UnexpectedToken(t.clone()).into()); }, }; if value < 0 { return Err(StyleParseError::UnspecifiedError.into()); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(StyleParseError::UnspecifiedError.into()) }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(StyleParseError::UnspecifiedError.into()); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]).write(unit.as_bytes()).unwrap(); } debug_assert!(written == 6); parse_hash_color(&serialization).map_err(|()| StyleParseError::UnspecifiedError.into()) } /// Returns false if the color is completely transparent, and /// true otherwise. pub fn is_non_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed,.. } => parsed.alpha!= 0, _ => true, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, _context: &Context) -> ComputedColor { match *self { Color::CurrentColor => ComputedColor::currentcolor(), Color::Numeric { ref parsed,.. } => ComputedColor::rgba(*parsed), Color::Complex(ref complex) => *complex, #[cfg(feature = "gecko")] Color::System(system) => convert_nscolor_to_computedcolor(system.to_computed_value(_context)), #[cfg(feature = "gecko")] Color::Special(special) => { use self::gecko::SpecialColorKeyword as Keyword; let pres_context = _context.device().pres_context(); convert_nscolor_to_computedcolor(match special { Keyword::MozDefaultColor => pres_context.mDefaultColor, Keyword::MozDefaultBackgroundColor => pres_context.mBackgroundColor, Keyword::MozHyperlinktext => pres_context.mLinkColor, Keyword::MozActiveHyperlinktext => pres_context.mActiveLinkColor, Keyword::MozVisitedHyperlinktext => pres_context.mVisitedLinkColor, }) } #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { use dom::TElement; use gecko::wrapper::GeckoElement; use gecko_bindings::bindings::Gecko_GetBody; let pres_context = _context.device().pres_context(); let body = unsafe { Gecko_GetBody(pres_context) }.map(GeckoElement); let data = body.as_ref().and_then(|wrap| wrap.borrow_data()); if let Some(data) = data { ComputedColor::rgba(data.styles.primary() .get_color() .clone_color()) } else { convert_nscolor_to_computedcolor(pres_context.mDefaultColor) } }, } } fn from_computed_value(computed: &ComputedColor) -> Self { if computed.is_numeric() { Color::rgba(computed.color) } else if computed.is_currentcolor() { Color::currentcolor() } else { Color::Complex(*computed) } } } /// Specified color value, but resolved to just RGBA for computed value /// with value from color property at the same context. #[derive(Clone, Debug, PartialEq, ToCss)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct RGBAColor(pub Color); no_viewport_percentage!(RGBAColor); impl Parse for RGBAColor { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Color::parse(context, input).map(RGBAColor) } } impl ToComputedValue for RGBAColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0.to_computed_value(context) .to_rgba(context.style().get_color().clone_color()) } fn from_computed_value(computed: &RGBA) -> Self { RGBAColor(Color::rgba(*computed)) } } impl From<Color> for RGBAColor { fn from(color: Color) -> RGBAColor { RGBAColor(color) } }
//! Specified color values.
random_line_split
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root, in a predictable way. pub(crate) fn mkroot<P: AsRef<Path>>(p: P) -> Result<()> { let p = p.as_ref(); let verpath = p.join("etc/.mkrootversion"); let v: u32 = if verpath.exists() { let s = std::fs::read_to_string(&verpath)?; let v: u32 = s.trim_end().parse()?; v + 1 } else
; mkvroot(p, v) } // Like mkroot but supports an explicit version pub(crate) fn mkvroot<P: AsRef<Path>>(p: P, v: u32) -> Result<()> { let p = p.as_ref(); for v in &["usr/bin", "etc"] { std::fs::create_dir_all(p.join(v))?; } let verpath = p.join("etc/.mkrootversion"); write_file(&verpath, &format!("{}", v))?; write_file(p.join("usr/bin/somebinary"), &format!("somebinary v{}", v))?; write_file(p.join("etc/someconf"), &format!("someconf v{}", v))?; write_file(p.join("usr/bin/vmod2"), &format!("somebinary v{}", v % 2))?; write_file(p.join("usr/bin/vmod3"), &format!("somebinary v{}", v % 3))?; Ok(()) } /// Returns `true` if a file is ELF; see https://en.wikipedia.org/wiki/Executable_and_Linkable_Format pub(crate) fn is_elf(f: &mut File) -> Result<bool> { let mut buf = [0; 5]; let n = f.read_at(&mut buf, 0)?; if n < buf.len() { anyhow::bail!("Failed to read expected {} bytes", buf.len()); } Ok(buf[0] == 0x7F && &buf[1..4] == b"ELF") } pub(crate) fn mutate_one_executable_to( f: &mut File, name: &std::ffi::OsStr, dest: &openat::Dir, ) -> Result<()> { let mut destf = dest .write_file(name, 0o755) .context("Failed to open for write")?; f.copy_to(&destf).context("Failed to copy")?; // ELF is OK with us just appending some junk let extra = rand::thread_rng() .sample_iter(&rand::distributions::Alphanumeric) .take(10) .collect::<String>(); destf .write_all(extra.as_bytes()) .context("Failed to append extra data")?; Ok(()) } /// Find ELF files in the srcdir, write new copies to dest (only percentage) pub(crate) fn mutate_executables_to( src: &openat::Dir, dest: &openat::Dir, percentage: u32, ) -> Result<u32> { use nix::sys::stat::Mode as NixMode; assert!(percentage > 0 && percentage <= 100); let mut mutated = 0; for entry in src.list_dir(".")? { let entry = entry?; if src.get_file_type(&entry)?!= openat::SimpleType::File { continue; } let meta = src.metadata(entry.file_name())?; let st = meta.stat(); let mode = NixMode::from_bits_truncate(st.st_mode); // Must be executable if!mode.intersects(NixMode::S_IXUSR | NixMode::S_IXGRP | NixMode::S_IXOTH) { continue; } // Not suid if mode.intersects(NixMode::S_ISUID | NixMode::S_ISGID) { continue; } // Greater than 1k in size if st.st_size < 1024 { continue; } let mut f = src.open_file(entry.file_name())?; if!is_elf(&mut f)? { continue; } if!rand::thread_rng().gen_ratio(percentage, 100) { continue; } mutate_one_executable_to(&mut f, entry.file_name(), dest) .with_context(|| format!("Failed updating {:?}", entry.file_name()))?; mutated += 1; } Ok(mutated) } // Given an ostree ref, use the running root filesystem as a source, update // `percentage` percent of binary (ELF) files pub(crate) fn update_os_tree<P: AsRef<Path>>( repo_path: P, ostref: &str, percentage: u32, ) -> Result<()> { assert!(percentage > 0 && percentage <= 100); let repo_path = repo_path.as_ref(); let tempdir = tempfile::tempdir_in(repo_path.join("tmp"))?; let mut mutated = 0; { let tempdir = openat::Dir::open(tempdir.path())?; let binary_dirs = &["usr/bin", "usr/sbin", "usr/lib", "usr/lib64"]; let rootfs = openat::Dir::open("/")?; for v in binary_dirs { let v = *v; if let Some(src) = rootfs.sub_dir_optional(v)? { tempdir.ensure_dir("usr", 0o755)?; tempdir.ensure_dir(v, 0o755)?; let dest = tempdir.sub_dir(v)?; mutated += mutate_executables_to(&src, &dest, percentage) .with_context(|| format!("Replacing binaries in {}", v))?; } } } assert!(mutated > 0); println!("Mutated ELF files: {}", mutated); bash!("ostree --repo={repo} commit --consume -b {ostref} --base={ostref} --tree=dir={tempdir} --owner-uid 0 --owner-gid 0 --selinux-policy-from-base --link-checkout-speedup --no-bindings --no-xattrs", repo = repo_path, ostref = ostref, tempdir = tempdir.path()).context("Failed to commit updated content")?; Ok(()) }
{ 0 }
conditional_block
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root, in a predictable way. pub(crate) fn mkroot<P: AsRef<Path>>(p: P) -> Result<()> { let p = p.as_ref(); let verpath = p.join("etc/.mkrootversion"); let v: u32 = if verpath.exists() { let s = std::fs::read_to_string(&verpath)?; let v: u32 = s.trim_end().parse()?; v + 1 } else { 0 }; mkvroot(p, v) } // Like mkroot but supports an explicit version pub(crate) fn mkvroot<P: AsRef<Path>>(p: P, v: u32) -> Result<()> { let p = p.as_ref(); for v in &["usr/bin", "etc"] { std::fs::create_dir_all(p.join(v))?; } let verpath = p.join("etc/.mkrootversion"); write_file(&verpath, &format!("{}", v))?; write_file(p.join("usr/bin/somebinary"), &format!("somebinary v{}", v))?; write_file(p.join("etc/someconf"), &format!("someconf v{}", v))?; write_file(p.join("usr/bin/vmod2"), &format!("somebinary v{}", v % 2))?; write_file(p.join("usr/bin/vmod3"), &format!("somebinary v{}", v % 3))?; Ok(()) } /// Returns `true` if a file is ELF; see https://en.wikipedia.org/wiki/Executable_and_Linkable_Format pub(crate) fn is_elf(f: &mut File) -> Result<bool> { let mut buf = [0; 5]; let n = f.read_at(&mut buf, 0)?; if n < buf.len() { anyhow::bail!("Failed to read expected {} bytes", buf.len()); } Ok(buf[0] == 0x7F && &buf[1..4] == b"ELF") }
) -> Result<()> { let mut destf = dest .write_file(name, 0o755) .context("Failed to open for write")?; f.copy_to(&destf).context("Failed to copy")?; // ELF is OK with us just appending some junk let extra = rand::thread_rng() .sample_iter(&rand::distributions::Alphanumeric) .take(10) .collect::<String>(); destf .write_all(extra.as_bytes()) .context("Failed to append extra data")?; Ok(()) } /// Find ELF files in the srcdir, write new copies to dest (only percentage) pub(crate) fn mutate_executables_to( src: &openat::Dir, dest: &openat::Dir, percentage: u32, ) -> Result<u32> { use nix::sys::stat::Mode as NixMode; assert!(percentage > 0 && percentage <= 100); let mut mutated = 0; for entry in src.list_dir(".")? { let entry = entry?; if src.get_file_type(&entry)?!= openat::SimpleType::File { continue; } let meta = src.metadata(entry.file_name())?; let st = meta.stat(); let mode = NixMode::from_bits_truncate(st.st_mode); // Must be executable if!mode.intersects(NixMode::S_IXUSR | NixMode::S_IXGRP | NixMode::S_IXOTH) { continue; } // Not suid if mode.intersects(NixMode::S_ISUID | NixMode::S_ISGID) { continue; } // Greater than 1k in size if st.st_size < 1024 { continue; } let mut f = src.open_file(entry.file_name())?; if!is_elf(&mut f)? { continue; } if!rand::thread_rng().gen_ratio(percentage, 100) { continue; } mutate_one_executable_to(&mut f, entry.file_name(), dest) .with_context(|| format!("Failed updating {:?}", entry.file_name()))?; mutated += 1; } Ok(mutated) } // Given an ostree ref, use the running root filesystem as a source, update // `percentage` percent of binary (ELF) files pub(crate) fn update_os_tree<P: AsRef<Path>>( repo_path: P, ostref: &str, percentage: u32, ) -> Result<()> { assert!(percentage > 0 && percentage <= 100); let repo_path = repo_path.as_ref(); let tempdir = tempfile::tempdir_in(repo_path.join("tmp"))?; let mut mutated = 0; { let tempdir = openat::Dir::open(tempdir.path())?; let binary_dirs = &["usr/bin", "usr/sbin", "usr/lib", "usr/lib64"]; let rootfs = openat::Dir::open("/")?; for v in binary_dirs { let v = *v; if let Some(src) = rootfs.sub_dir_optional(v)? { tempdir.ensure_dir("usr", 0o755)?; tempdir.ensure_dir(v, 0o755)?; let dest = tempdir.sub_dir(v)?; mutated += mutate_executables_to(&src, &dest, percentage) .with_context(|| format!("Replacing binaries in {}", v))?; } } } assert!(mutated > 0); println!("Mutated ELF files: {}", mutated); bash!("ostree --repo={repo} commit --consume -b {ostref} --base={ostref} --tree=dir={tempdir} --owner-uid 0 --owner-gid 0 --selinux-policy-from-base --link-checkout-speedup --no-bindings --no-xattrs", repo = repo_path, ostref = ostref, tempdir = tempdir.path()).context("Failed to commit updated content")?; Ok(()) }
pub(crate) fn mutate_one_executable_to( f: &mut File, name: &std::ffi::OsStr, dest: &openat::Dir,
random_line_split
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root, in a predictable way. pub(crate) fn mkroot<P: AsRef<Path>>(p: P) -> Result<()> { let p = p.as_ref(); let verpath = p.join("etc/.mkrootversion"); let v: u32 = if verpath.exists() { let s = std::fs::read_to_string(&verpath)?; let v: u32 = s.trim_end().parse()?; v + 1 } else { 0 }; mkvroot(p, v) } // Like mkroot but supports an explicit version pub(crate) fn mkvroot<P: AsRef<Path>>(p: P, v: u32) -> Result<()> { let p = p.as_ref(); for v in &["usr/bin", "etc"] { std::fs::create_dir_all(p.join(v))?; } let verpath = p.join("etc/.mkrootversion"); write_file(&verpath, &format!("{}", v))?; write_file(p.join("usr/bin/somebinary"), &format!("somebinary v{}", v))?; write_file(p.join("etc/someconf"), &format!("someconf v{}", v))?; write_file(p.join("usr/bin/vmod2"), &format!("somebinary v{}", v % 2))?; write_file(p.join("usr/bin/vmod3"), &format!("somebinary v{}", v % 3))?; Ok(()) } /// Returns `true` if a file is ELF; see https://en.wikipedia.org/wiki/Executable_and_Linkable_Format pub(crate) fn is_elf(f: &mut File) -> Result<bool> { let mut buf = [0; 5]; let n = f.read_at(&mut buf, 0)?; if n < buf.len() { anyhow::bail!("Failed to read expected {} bytes", buf.len()); } Ok(buf[0] == 0x7F && &buf[1..4] == b"ELF") } pub(crate) fn mutate_one_executable_to( f: &mut File, name: &std::ffi::OsStr, dest: &openat::Dir, ) -> Result<()> { let mut destf = dest .write_file(name, 0o755) .context("Failed to open for write")?; f.copy_to(&destf).context("Failed to copy")?; // ELF is OK with us just appending some junk let extra = rand::thread_rng() .sample_iter(&rand::distributions::Alphanumeric) .take(10) .collect::<String>(); destf .write_all(extra.as_bytes()) .context("Failed to append extra data")?; Ok(()) } /// Find ELF files in the srcdir, write new copies to dest (only percentage) pub(crate) fn
( src: &openat::Dir, dest: &openat::Dir, percentage: u32, ) -> Result<u32> { use nix::sys::stat::Mode as NixMode; assert!(percentage > 0 && percentage <= 100); let mut mutated = 0; for entry in src.list_dir(".")? { let entry = entry?; if src.get_file_type(&entry)?!= openat::SimpleType::File { continue; } let meta = src.metadata(entry.file_name())?; let st = meta.stat(); let mode = NixMode::from_bits_truncate(st.st_mode); // Must be executable if!mode.intersects(NixMode::S_IXUSR | NixMode::S_IXGRP | NixMode::S_IXOTH) { continue; } // Not suid if mode.intersects(NixMode::S_ISUID | NixMode::S_ISGID) { continue; } // Greater than 1k in size if st.st_size < 1024 { continue; } let mut f = src.open_file(entry.file_name())?; if!is_elf(&mut f)? { continue; } if!rand::thread_rng().gen_ratio(percentage, 100) { continue; } mutate_one_executable_to(&mut f, entry.file_name(), dest) .with_context(|| format!("Failed updating {:?}", entry.file_name()))?; mutated += 1; } Ok(mutated) } // Given an ostree ref, use the running root filesystem as a source, update // `percentage` percent of binary (ELF) files pub(crate) fn update_os_tree<P: AsRef<Path>>( repo_path: P, ostref: &str, percentage: u32, ) -> Result<()> { assert!(percentage > 0 && percentage <= 100); let repo_path = repo_path.as_ref(); let tempdir = tempfile::tempdir_in(repo_path.join("tmp"))?; let mut mutated = 0; { let tempdir = openat::Dir::open(tempdir.path())?; let binary_dirs = &["usr/bin", "usr/sbin", "usr/lib", "usr/lib64"]; let rootfs = openat::Dir::open("/")?; for v in binary_dirs { let v = *v; if let Some(src) = rootfs.sub_dir_optional(v)? { tempdir.ensure_dir("usr", 0o755)?; tempdir.ensure_dir(v, 0o755)?; let dest = tempdir.sub_dir(v)?; mutated += mutate_executables_to(&src, &dest, percentage) .with_context(|| format!("Replacing binaries in {}", v))?; } } } assert!(mutated > 0); println!("Mutated ELF files: {}", mutated); bash!("ostree --repo={repo} commit --consume -b {ostref} --base={ostref} --tree=dir={tempdir} --owner-uid 0 --owner-gid 0 --selinux-policy-from-base --link-checkout-speedup --no-bindings --no-xattrs", repo = repo_path, ostref = ostref, tempdir = tempdir.path()).context("Failed to commit updated content")?; Ok(()) }
mutate_executables_to
identifier_name
treegen.rs
use anyhow::{Context, Result}; use openat_ext::{FileExt, OpenatDirExt}; use rand::Rng; use sh_inline::bash; use std::fs::File; use std::io::prelude::*; use std::os::unix::fs::FileExt as UnixFileExt; use std::path::Path; use crate::test::*; /// Each time this is invoked it changes file contents /// in the target root, in a predictable way. pub(crate) fn mkroot<P: AsRef<Path>>(p: P) -> Result<()> { let p = p.as_ref(); let verpath = p.join("etc/.mkrootversion"); let v: u32 = if verpath.exists() { let s = std::fs::read_to_string(&verpath)?; let v: u32 = s.trim_end().parse()?; v + 1 } else { 0 }; mkvroot(p, v) } // Like mkroot but supports an explicit version pub(crate) fn mkvroot<P: AsRef<Path>>(p: P, v: u32) -> Result<()> { let p = p.as_ref(); for v in &["usr/bin", "etc"] { std::fs::create_dir_all(p.join(v))?; } let verpath = p.join("etc/.mkrootversion"); write_file(&verpath, &format!("{}", v))?; write_file(p.join("usr/bin/somebinary"), &format!("somebinary v{}", v))?; write_file(p.join("etc/someconf"), &format!("someconf v{}", v))?; write_file(p.join("usr/bin/vmod2"), &format!("somebinary v{}", v % 2))?; write_file(p.join("usr/bin/vmod3"), &format!("somebinary v{}", v % 3))?; Ok(()) } /// Returns `true` if a file is ELF; see https://en.wikipedia.org/wiki/Executable_and_Linkable_Format pub(crate) fn is_elf(f: &mut File) -> Result<bool>
pub(crate) fn mutate_one_executable_to( f: &mut File, name: &std::ffi::OsStr, dest: &openat::Dir, ) -> Result<()> { let mut destf = dest .write_file(name, 0o755) .context("Failed to open for write")?; f.copy_to(&destf).context("Failed to copy")?; // ELF is OK with us just appending some junk let extra = rand::thread_rng() .sample_iter(&rand::distributions::Alphanumeric) .take(10) .collect::<String>(); destf .write_all(extra.as_bytes()) .context("Failed to append extra data")?; Ok(()) } /// Find ELF files in the srcdir, write new copies to dest (only percentage) pub(crate) fn mutate_executables_to( src: &openat::Dir, dest: &openat::Dir, percentage: u32, ) -> Result<u32> { use nix::sys::stat::Mode as NixMode; assert!(percentage > 0 && percentage <= 100); let mut mutated = 0; for entry in src.list_dir(".")? { let entry = entry?; if src.get_file_type(&entry)?!= openat::SimpleType::File { continue; } let meta = src.metadata(entry.file_name())?; let st = meta.stat(); let mode = NixMode::from_bits_truncate(st.st_mode); // Must be executable if!mode.intersects(NixMode::S_IXUSR | NixMode::S_IXGRP | NixMode::S_IXOTH) { continue; } // Not suid if mode.intersects(NixMode::S_ISUID | NixMode::S_ISGID) { continue; } // Greater than 1k in size if st.st_size < 1024 { continue; } let mut f = src.open_file(entry.file_name())?; if!is_elf(&mut f)? { continue; } if!rand::thread_rng().gen_ratio(percentage, 100) { continue; } mutate_one_executable_to(&mut f, entry.file_name(), dest) .with_context(|| format!("Failed updating {:?}", entry.file_name()))?; mutated += 1; } Ok(mutated) } // Given an ostree ref, use the running root filesystem as a source, update // `percentage` percent of binary (ELF) files pub(crate) fn update_os_tree<P: AsRef<Path>>( repo_path: P, ostref: &str, percentage: u32, ) -> Result<()> { assert!(percentage > 0 && percentage <= 100); let repo_path = repo_path.as_ref(); let tempdir = tempfile::tempdir_in(repo_path.join("tmp"))?; let mut mutated = 0; { let tempdir = openat::Dir::open(tempdir.path())?; let binary_dirs = &["usr/bin", "usr/sbin", "usr/lib", "usr/lib64"]; let rootfs = openat::Dir::open("/")?; for v in binary_dirs { let v = *v; if let Some(src) = rootfs.sub_dir_optional(v)? { tempdir.ensure_dir("usr", 0o755)?; tempdir.ensure_dir(v, 0o755)?; let dest = tempdir.sub_dir(v)?; mutated += mutate_executables_to(&src, &dest, percentage) .with_context(|| format!("Replacing binaries in {}", v))?; } } } assert!(mutated > 0); println!("Mutated ELF files: {}", mutated); bash!("ostree --repo={repo} commit --consume -b {ostref} --base={ostref} --tree=dir={tempdir} --owner-uid 0 --owner-gid 0 --selinux-policy-from-base --link-checkout-speedup --no-bindings --no-xattrs", repo = repo_path, ostref = ostref, tempdir = tempdir.path()).context("Failed to commit updated content")?; Ok(()) }
{ let mut buf = [0; 5]; let n = f.read_at(&mut buf, 0)?; if n < buf.len() { anyhow::bail!("Failed to read expected {} bytes", buf.len()); } Ok(buf[0] == 0x7F && &buf[1..4] == b"ELF") }
identifier_body
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace()
.filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() ) .collect::<Vec<_>>() .len(); println!("Part 1: Total was {}", total); } fn part_2(input: &String) { //I am not skill enough with iterator adaptors to use.as_slice().chunks(3) //so we will do things the lazy way. sad let mut triangles = vec![vec![0; 3]; 3]; let mut read_lines = 3; let mut total = 0; //total good triangles for line in input.lines().map(|l| l.to_string()).collect::<Vec<String>>().iter() { let values = line.trim().split_whitespace().map(|v| v.parse::<i32>().unwrap()).collect::<Vec<_>>(); //println!("Values are {:?}", values); triangles[0][3 - read_lines] = values[0]; triangles[1][3 - read_lines] = values[1]; triangles[2][3 - read_lines] = values[2]; read_lines = read_lines - 1; if read_lines == 0 { //process our triangles let good = triangles .iter() .filter(|v| { //println!("filtering {:?}", v); v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() } ) .collect::<Vec<_>>() .len(); //println!("Found {} good ones from this set", good); total = total + good; read_lines = 3; //reset } } println!("Part 2: there are {} good triangles", total); } fn main() { let mut file = File::open("./data").expect("could not open file"); let mut input = String::new(); file.read_to_string(&mut input).expect("could not read file"); part_1(&input); part_2(&input); }
.map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>())
random_line_split
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace() .map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>()) .filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() ) .collect::<Vec<_>>() .len(); println!("Part 1: Total was {}", total); } fn part_2(input: &String) { //I am not skill enough with iterator adaptors to use.as_slice().chunks(3) //so we will do things the lazy way. sad let mut triangles = vec![vec![0; 3]; 3]; let mut read_lines = 3; let mut total = 0; //total good triangles for line in input.lines().map(|l| l.to_string()).collect::<Vec<String>>().iter() { let values = line.trim().split_whitespace().map(|v| v.parse::<i32>().unwrap()).collect::<Vec<_>>(); //println!("Values are {:?}", values); triangles[0][3 - read_lines] = values[0]; triangles[1][3 - read_lines] = values[1]; triangles[2][3 - read_lines] = values[2]; read_lines = read_lines - 1; if read_lines == 0
} println!("Part 2: there are {} good triangles", total); } fn main() { let mut file = File::open("./data").expect("could not open file"); let mut input = String::new(); file.read_to_string(&mut input).expect("could not read file"); part_1(&input); part_2(&input); }
{ //process our triangles let good = triangles .iter() .filter(|v| { //println!("filtering {:?}", v); v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() } ) .collect::<Vec<_>>() .len(); //println!("Found {} good ones from this set", good); total = total + good; read_lines = 3; //reset }
conditional_block
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace() .map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>()) .filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() ) .collect::<Vec<_>>() .len(); println!("Part 1: Total was {}", total); } fn
(input: &String) { //I am not skill enough with iterator adaptors to use.as_slice().chunks(3) //so we will do things the lazy way. sad let mut triangles = vec![vec![0; 3]; 3]; let mut read_lines = 3; let mut total = 0; //total good triangles for line in input.lines().map(|l| l.to_string()).collect::<Vec<String>>().iter() { let values = line.trim().split_whitespace().map(|v| v.parse::<i32>().unwrap()).collect::<Vec<_>>(); //println!("Values are {:?}", values); triangles[0][3 - read_lines] = values[0]; triangles[1][3 - read_lines] = values[1]; triangles[2][3 - read_lines] = values[2]; read_lines = read_lines - 1; if read_lines == 0 { //process our triangles let good = triangles .iter() .filter(|v| { //println!("filtering {:?}", v); v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() } ) .collect::<Vec<_>>() .len(); //println!("Found {} good ones from this set", good); total = total + good; read_lines = 3; //reset } } println!("Part 2: there are {} good triangles", total); } fn main() { let mut file = File::open("./data").expect("could not open file"); let mut input = String::new(); file.read_to_string(&mut input).expect("could not read file"); part_1(&input); part_2(&input); }
part_2
identifier_name
main.rs
use std::io::Read; use std::fs::File; fn part_1(input: &String) { let total = input.lines() .map(|l| l .trim() .split_whitespace() .map(|v| v.parse::<i32>().unwrap()) .collect::<Vec<_>>()) .filter(|v| v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() ) .collect::<Vec<_>>() .len(); println!("Part 1: Total was {}", total); } fn part_2(input: &String)
) .collect::<Vec<_>>() .len(); //println!("Found {} good ones from this set", good); total = total + good; read_lines = 3; //reset } } println!("Part 2: there are {} good triangles", total); } fn main() { let mut file = File::open("./data").expect("could not open file"); let mut input = String::new(); file.read_to_string(&mut input).expect("could not read file"); part_1(&input); part_2(&input); }
{ //I am not skill enough with iterator adaptors to use .as_slice().chunks(3) //so we will do things the lazy way. sad let mut triangles = vec![vec![0; 3]; 3]; let mut read_lines = 3; let mut total = 0; //total good triangles for line in input.lines().map(|l| l.to_string()).collect::<Vec<String>>().iter() { let values = line.trim().split_whitespace().map(|v| v.parse::<i32>().unwrap()).collect::<Vec<_>>(); //println!("Values are {:?}", values); triangles[0][3 - read_lines] = values[0]; triangles[1][3 - read_lines] = values[1]; triangles[2][3 - read_lines] = values[2]; read_lines = read_lines - 1; if read_lines == 0 { //process our triangles let good = triangles .iter() .filter(|v| { //println!("filtering {:?}", v); v.iter().fold(0, |sum, x| sum + x) > 2 * v.iter().max().unwrap() }
identifier_body
encryption_session.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use std::fmt::{Debug, Formatter, Error as FmtError}; use std::time; use std::sync::Arc; use parking_lot::{Condvar, Mutex}; use ethkey::{self, Public, Signature}; use key_server_cluster::{Error, NodeId, SessionId, KeyStorage, DocumentKeyShare}; use key_server_cluster::cluster::Cluster; use key_server_cluster::cluster_sessions::ClusterSession; use key_server_cluster::message::{Message, EncryptionMessage, InitializeEncryptionSession, ConfirmEncryptionInitialization, EncryptionSessionError}; /// Encryption session API. pub trait Session: Send + Sync +'static { /// Get encryption session state. fn state(&self) -> SessionState; /// Wait until session is completed. Returns distributely generated secret key. fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error>; } /// Encryption (distributed key generation) session. /// Based on "ECDKG: A Distributed Key Generation Protocol Based on Elliptic Curve Discrete Logarithm" paper: /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.124.4128&rep=rep1&type=pdf /// Brief overview: /// 1) initialization: master node (which has received request for storing the secret) initializes the session on all other nodes /// 2) master node sends common_point + encrypted_point to all other nodes /// 3) common_point + encrypted_point are saved on all nodes /// 4) in case of error, previous values are restored pub struct SessionImpl { /// Unique session id. id: SessionId, /// Public identifier of this node. self_node_id: NodeId, /// Encrypted data. encrypted_data: Option<DocumentKeyShare>, /// Key storage. key_storage: Arc<KeyStorage>, /// Cluster which allows this node to send messages to other nodes in the cluster. cluster: Arc<Cluster>, /// Session nonce. nonce: u64, /// SessionImpl completion condvar. completed: Condvar, /// Mutable session data. data: Mutex<SessionData>, } /// SessionImpl creation parameters pub struct SessionParams { /// SessionImpl identifier. pub id: SessionId, /// Id of node, on which this session is running. pub self_node_id: Public, /// Encrypted data (result of running generation_session::SessionImpl). pub encrypted_data: Option<DocumentKeyShare>, /// Key storage. pub key_storage: Arc<KeyStorage>, /// Cluster pub cluster: Arc<Cluster>, /// Session nonce. pub nonce: u64, } /// Mutable data of encryption (distributed key generation) session. #[derive(Debug)] struct SessionData { /// Current state of the session. state: SessionState, /// Nodes-specific data. nodes: BTreeMap<NodeId, NodeData>, /// Encryption session result. result: Option<Result<(), Error>>, } /// Mutable node-specific data. #[derive(Debug, Clone)] struct NodeData { // === Values, filled during initialization phase === /// Flags marking that node has confirmed session initialization. pub initialization_confirmed: bool, } /// Encryption (distributed key generation) session state. #[derive(Debug, Clone, PartialEq)] pub enum SessionState { // === Initialization states === /// Every node starts in this state. WaitingForInitialization, /// Master node waits for every other node to confirm initialization. WaitingForInitializationConfirm, // === Final states of the session === /// Encryption data is saved. Finished, /// Failed to save encryption data. Failed, } impl SessionImpl { /// Create new encryption session. pub fn new(params: SessionParams) -> Result<Self, Error> { check_encrypted_data(&params.encrypted_data)?; Ok(SessionImpl { id: params.id, self_node_id: params.self_node_id, encrypted_data: params.encrypted_data, key_storage: params.key_storage, cluster: params.cluster, nonce: params.nonce, completed: Condvar::new(), data: Mutex::new(SessionData { state: SessionState::WaitingForInitialization, nodes: BTreeMap::new(), result: None, }), }) } /// Get this node Id. pub fn node(&self) -> &NodeId { &self.self_node_id } /// Start new session initialization. This must be called on master node. pub fn initialize(&self, requestor_signature: Signature, common_point: Public, encrypted_point: Public) -> Result<(), Error> { let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // update state data.state = SessionState::WaitingForInitializationConfirm; data.nodes.extend(self.cluster.nodes().into_iter().map(|n| (n, NodeData { initialization_confirmed: &n == self.node(), }))); // TODO: id signature is not enough here, as it was already used in key generation // TODO: there could be situation when some nodes have failed to store encrypted data // => potential problems during restore. some confirmation step is needed (2pc)? // save encryption data if let Some(mut encrypted_data) = self.encrypted_data.clone() { // check that the requester is the author of the encrypted data let requestor_public = ethkey::recover(&requestor_signature, &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } encrypted_data.common_point = Some(common_point.clone()); encrypted_data.encrypted_point = Some(encrypted_point.clone()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // start initialization if data.nodes.len() > 1 { self.cluster.broadcast(Message::Encryption(EncryptionMessage::InitializeEncryptionSession(InitializeEncryptionSession { session: self.id.clone().into(), session_nonce: self.nonce, requestor_signature: requestor_signature.into(), common_point: common_point.into(), encrypted_point: encrypted_point.into(), }))) } else { data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } /// When session initialization message is received. pub fn on_initialize_session(&self, sender: NodeId, message: &InitializeEncryptionSession) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // check that the requester is the author of the encrypted data if let Some(mut encrypted_data) = self.encrypted_data.clone() { let requestor_public = ethkey::recover(&message.requestor_signature.clone().into(), &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } // save encryption data encrypted_data.common_point = Some(message.common_point.clone().into()); encrypted_data.encrypted_point = Some(message.encrypted_point.clone().into()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // update state data.state = SessionState::Finished; // send confirmation back to master node self.cluster.send(&sender, Message::Encryption(EncryptionMessage::ConfirmEncryptionInitialization(ConfirmEncryptionInitialization { session: self.id.clone().into(), session_nonce: self.nonce, }))) } /// When session initialization confirmation message is reeived. pub fn on_confirm_initialization(&self, sender: NodeId, message: &ConfirmEncryptionInitialization) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); debug_assert!(data.nodes.contains_key(&sender)); // check if all nodes have confirmed initialization data.nodes.get_mut(&sender) .expect("message is received from cluster; nodes contains all cluster nodes; qed") .initialization_confirmed = true; if!data.nodes.values().all(|n| n.initialization_confirmed) { return Ok(()); } // update state data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } impl ClusterSession for SessionImpl { type Id = SessionId; fn type_name() -> &'static str
fn id(&self) -> SessionId { self.id.clone() } fn is_finished(&self) -> bool { let data = self.data.lock(); data.state == SessionState::Failed || data.state == SessionState::Finished } fn on_node_timeout(&self, node: &NodeId) { let mut data = self.data.lock(); warn!("{}: encryption session failed because {} connection has timeouted", self.node(), node); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_timeout(&self) { let mut data = self.data.lock(); warn!("{}: encryption session failed with timeout", self.node()); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_error(&self, node: &NodeId, error: Error) { // error in encryption session is considered fatal // => broadcast error if error occured on this node if *node == self.self_node_id { // do not bother processing send error, as we already processing error let _ = self.cluster.broadcast(Message::Encryption(EncryptionMessage::EncryptionSessionError(EncryptionSessionError { session: self.id.clone().into(), session_nonce: self.nonce, error: error.clone().into(), }))); } let mut data = self.data.lock(); warn!("{}: encryption session failed with error: {} from {}", self.node(), error, node); data.state = SessionState::Failed; data.result = Some(Err(error)); self.completed.notify_all(); } fn on_message(&self, sender: &NodeId, message: &Message) -> Result<(), Error> { if Some(self.nonce)!= message.session_nonce() { return Err(Error::ReplayProtection); } match message { &Message::Encryption(ref message) => match message { &EncryptionMessage::InitializeEncryptionSession(ref message) => self.on_initialize_session(sender.clone(), message), &EncryptionMessage::ConfirmEncryptionInitialization(ref message) => self.on_confirm_initialization(sender.clone(), message), &EncryptionMessage::EncryptionSessionError(ref message) => { self.on_session_error(sender, Error::Io(message.error.clone().into())); Ok(()) }, }, _ => unreachable!("cluster checks message to be correct before passing; qed"), } } } impl Session for SessionImpl { fn state(&self) -> SessionState { self.data.lock().state.clone() } fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error> { let mut data = self.data.lock(); if!data.result.is_some() { match timeout { None => self.completed.wait(&mut data), Some(timeout) => { self.completed.wait_for(&mut data, timeout); }, } } data.result.as_ref() .expect("checked above or waited for completed; completed is only signaled when result.is_some(); qed") .clone() } } impl Debug for SessionImpl { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "Encryption session {} on {}", self.id, self.self_node_id) } } fn check_encrypted_data(encrypted_data: &Option<DocumentKeyShare>) -> Result<(), Error> { if let &Some(ref encrypted_data) = encrypted_data { // check that common_point and encrypted_point are still not set yet if encrypted_data.common_point.is_some() || encrypted_data.encrypted_point.is_some() { return Err(Error::CompletedSessionId); } } Ok(()) }
{ "encryption" }
identifier_body
encryption_session.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use std::fmt::{Debug, Formatter, Error as FmtError}; use std::time; use std::sync::Arc;
use key_server_cluster::cluster_sessions::ClusterSession; use key_server_cluster::message::{Message, EncryptionMessage, InitializeEncryptionSession, ConfirmEncryptionInitialization, EncryptionSessionError}; /// Encryption session API. pub trait Session: Send + Sync +'static { /// Get encryption session state. fn state(&self) -> SessionState; /// Wait until session is completed. Returns distributely generated secret key. fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error>; } /// Encryption (distributed key generation) session. /// Based on "ECDKG: A Distributed Key Generation Protocol Based on Elliptic Curve Discrete Logarithm" paper: /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.124.4128&rep=rep1&type=pdf /// Brief overview: /// 1) initialization: master node (which has received request for storing the secret) initializes the session on all other nodes /// 2) master node sends common_point + encrypted_point to all other nodes /// 3) common_point + encrypted_point are saved on all nodes /// 4) in case of error, previous values are restored pub struct SessionImpl { /// Unique session id. id: SessionId, /// Public identifier of this node. self_node_id: NodeId, /// Encrypted data. encrypted_data: Option<DocumentKeyShare>, /// Key storage. key_storage: Arc<KeyStorage>, /// Cluster which allows this node to send messages to other nodes in the cluster. cluster: Arc<Cluster>, /// Session nonce. nonce: u64, /// SessionImpl completion condvar. completed: Condvar, /// Mutable session data. data: Mutex<SessionData>, } /// SessionImpl creation parameters pub struct SessionParams { /// SessionImpl identifier. pub id: SessionId, /// Id of node, on which this session is running. pub self_node_id: Public, /// Encrypted data (result of running generation_session::SessionImpl). pub encrypted_data: Option<DocumentKeyShare>, /// Key storage. pub key_storage: Arc<KeyStorage>, /// Cluster pub cluster: Arc<Cluster>, /// Session nonce. pub nonce: u64, } /// Mutable data of encryption (distributed key generation) session. #[derive(Debug)] struct SessionData { /// Current state of the session. state: SessionState, /// Nodes-specific data. nodes: BTreeMap<NodeId, NodeData>, /// Encryption session result. result: Option<Result<(), Error>>, } /// Mutable node-specific data. #[derive(Debug, Clone)] struct NodeData { // === Values, filled during initialization phase === /// Flags marking that node has confirmed session initialization. pub initialization_confirmed: bool, } /// Encryption (distributed key generation) session state. #[derive(Debug, Clone, PartialEq)] pub enum SessionState { // === Initialization states === /// Every node starts in this state. WaitingForInitialization, /// Master node waits for every other node to confirm initialization. WaitingForInitializationConfirm, // === Final states of the session === /// Encryption data is saved. Finished, /// Failed to save encryption data. Failed, } impl SessionImpl { /// Create new encryption session. pub fn new(params: SessionParams) -> Result<Self, Error> { check_encrypted_data(&params.encrypted_data)?; Ok(SessionImpl { id: params.id, self_node_id: params.self_node_id, encrypted_data: params.encrypted_data, key_storage: params.key_storage, cluster: params.cluster, nonce: params.nonce, completed: Condvar::new(), data: Mutex::new(SessionData { state: SessionState::WaitingForInitialization, nodes: BTreeMap::new(), result: None, }), }) } /// Get this node Id. pub fn node(&self) -> &NodeId { &self.self_node_id } /// Start new session initialization. This must be called on master node. pub fn initialize(&self, requestor_signature: Signature, common_point: Public, encrypted_point: Public) -> Result<(), Error> { let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // update state data.state = SessionState::WaitingForInitializationConfirm; data.nodes.extend(self.cluster.nodes().into_iter().map(|n| (n, NodeData { initialization_confirmed: &n == self.node(), }))); // TODO: id signature is not enough here, as it was already used in key generation // TODO: there could be situation when some nodes have failed to store encrypted data // => potential problems during restore. some confirmation step is needed (2pc)? // save encryption data if let Some(mut encrypted_data) = self.encrypted_data.clone() { // check that the requester is the author of the encrypted data let requestor_public = ethkey::recover(&requestor_signature, &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } encrypted_data.common_point = Some(common_point.clone()); encrypted_data.encrypted_point = Some(encrypted_point.clone()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // start initialization if data.nodes.len() > 1 { self.cluster.broadcast(Message::Encryption(EncryptionMessage::InitializeEncryptionSession(InitializeEncryptionSession { session: self.id.clone().into(), session_nonce: self.nonce, requestor_signature: requestor_signature.into(), common_point: common_point.into(), encrypted_point: encrypted_point.into(), }))) } else { data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } /// When session initialization message is received. pub fn on_initialize_session(&self, sender: NodeId, message: &InitializeEncryptionSession) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // check that the requester is the author of the encrypted data if let Some(mut encrypted_data) = self.encrypted_data.clone() { let requestor_public = ethkey::recover(&message.requestor_signature.clone().into(), &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } // save encryption data encrypted_data.common_point = Some(message.common_point.clone().into()); encrypted_data.encrypted_point = Some(message.encrypted_point.clone().into()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // update state data.state = SessionState::Finished; // send confirmation back to master node self.cluster.send(&sender, Message::Encryption(EncryptionMessage::ConfirmEncryptionInitialization(ConfirmEncryptionInitialization { session: self.id.clone().into(), session_nonce: self.nonce, }))) } /// When session initialization confirmation message is reeived. pub fn on_confirm_initialization(&self, sender: NodeId, message: &ConfirmEncryptionInitialization) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); debug_assert!(data.nodes.contains_key(&sender)); // check if all nodes have confirmed initialization data.nodes.get_mut(&sender) .expect("message is received from cluster; nodes contains all cluster nodes; qed") .initialization_confirmed = true; if!data.nodes.values().all(|n| n.initialization_confirmed) { return Ok(()); } // update state data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } impl ClusterSession for SessionImpl { type Id = SessionId; fn type_name() -> &'static str { "encryption" } fn id(&self) -> SessionId { self.id.clone() } fn is_finished(&self) -> bool { let data = self.data.lock(); data.state == SessionState::Failed || data.state == SessionState::Finished } fn on_node_timeout(&self, node: &NodeId) { let mut data = self.data.lock(); warn!("{}: encryption session failed because {} connection has timeouted", self.node(), node); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_timeout(&self) { let mut data = self.data.lock(); warn!("{}: encryption session failed with timeout", self.node()); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_error(&self, node: &NodeId, error: Error) { // error in encryption session is considered fatal // => broadcast error if error occured on this node if *node == self.self_node_id { // do not bother processing send error, as we already processing error let _ = self.cluster.broadcast(Message::Encryption(EncryptionMessage::EncryptionSessionError(EncryptionSessionError { session: self.id.clone().into(), session_nonce: self.nonce, error: error.clone().into(), }))); } let mut data = self.data.lock(); warn!("{}: encryption session failed with error: {} from {}", self.node(), error, node); data.state = SessionState::Failed; data.result = Some(Err(error)); self.completed.notify_all(); } fn on_message(&self, sender: &NodeId, message: &Message) -> Result<(), Error> { if Some(self.nonce)!= message.session_nonce() { return Err(Error::ReplayProtection); } match message { &Message::Encryption(ref message) => match message { &EncryptionMessage::InitializeEncryptionSession(ref message) => self.on_initialize_session(sender.clone(), message), &EncryptionMessage::ConfirmEncryptionInitialization(ref message) => self.on_confirm_initialization(sender.clone(), message), &EncryptionMessage::EncryptionSessionError(ref message) => { self.on_session_error(sender, Error::Io(message.error.clone().into())); Ok(()) }, }, _ => unreachable!("cluster checks message to be correct before passing; qed"), } } } impl Session for SessionImpl { fn state(&self) -> SessionState { self.data.lock().state.clone() } fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error> { let mut data = self.data.lock(); if!data.result.is_some() { match timeout { None => self.completed.wait(&mut data), Some(timeout) => { self.completed.wait_for(&mut data, timeout); }, } } data.result.as_ref() .expect("checked above or waited for completed; completed is only signaled when result.is_some(); qed") .clone() } } impl Debug for SessionImpl { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "Encryption session {} on {}", self.id, self.self_node_id) } } fn check_encrypted_data(encrypted_data: &Option<DocumentKeyShare>) -> Result<(), Error> { if let &Some(ref encrypted_data) = encrypted_data { // check that common_point and encrypted_point are still not set yet if encrypted_data.common_point.is_some() || encrypted_data.encrypted_point.is_some() { return Err(Error::CompletedSessionId); } } Ok(()) }
use parking_lot::{Condvar, Mutex}; use ethkey::{self, Public, Signature}; use key_server_cluster::{Error, NodeId, SessionId, KeyStorage, DocumentKeyShare}; use key_server_cluster::cluster::Cluster;
random_line_split
encryption_session.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use std::fmt::{Debug, Formatter, Error as FmtError}; use std::time; use std::sync::Arc; use parking_lot::{Condvar, Mutex}; use ethkey::{self, Public, Signature}; use key_server_cluster::{Error, NodeId, SessionId, KeyStorage, DocumentKeyShare}; use key_server_cluster::cluster::Cluster; use key_server_cluster::cluster_sessions::ClusterSession; use key_server_cluster::message::{Message, EncryptionMessage, InitializeEncryptionSession, ConfirmEncryptionInitialization, EncryptionSessionError}; /// Encryption session API. pub trait Session: Send + Sync +'static { /// Get encryption session state. fn state(&self) -> SessionState; /// Wait until session is completed. Returns distributely generated secret key. fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error>; } /// Encryption (distributed key generation) session. /// Based on "ECDKG: A Distributed Key Generation Protocol Based on Elliptic Curve Discrete Logarithm" paper: /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.124.4128&rep=rep1&type=pdf /// Brief overview: /// 1) initialization: master node (which has received request for storing the secret) initializes the session on all other nodes /// 2) master node sends common_point + encrypted_point to all other nodes /// 3) common_point + encrypted_point are saved on all nodes /// 4) in case of error, previous values are restored pub struct SessionImpl { /// Unique session id. id: SessionId, /// Public identifier of this node. self_node_id: NodeId, /// Encrypted data. encrypted_data: Option<DocumentKeyShare>, /// Key storage. key_storage: Arc<KeyStorage>, /// Cluster which allows this node to send messages to other nodes in the cluster. cluster: Arc<Cluster>, /// Session nonce. nonce: u64, /// SessionImpl completion condvar. completed: Condvar, /// Mutable session data. data: Mutex<SessionData>, } /// SessionImpl creation parameters pub struct SessionParams { /// SessionImpl identifier. pub id: SessionId, /// Id of node, on which this session is running. pub self_node_id: Public, /// Encrypted data (result of running generation_session::SessionImpl). pub encrypted_data: Option<DocumentKeyShare>, /// Key storage. pub key_storage: Arc<KeyStorage>, /// Cluster pub cluster: Arc<Cluster>, /// Session nonce. pub nonce: u64, } /// Mutable data of encryption (distributed key generation) session. #[derive(Debug)] struct SessionData { /// Current state of the session. state: SessionState, /// Nodes-specific data. nodes: BTreeMap<NodeId, NodeData>, /// Encryption session result. result: Option<Result<(), Error>>, } /// Mutable node-specific data. #[derive(Debug, Clone)] struct NodeData { // === Values, filled during initialization phase === /// Flags marking that node has confirmed session initialization. pub initialization_confirmed: bool, } /// Encryption (distributed key generation) session state. #[derive(Debug, Clone, PartialEq)] pub enum SessionState { // === Initialization states === /// Every node starts in this state. WaitingForInitialization, /// Master node waits for every other node to confirm initialization. WaitingForInitializationConfirm, // === Final states of the session === /// Encryption data is saved. Finished, /// Failed to save encryption data. Failed, } impl SessionImpl { /// Create new encryption session. pub fn new(params: SessionParams) -> Result<Self, Error> { check_encrypted_data(&params.encrypted_data)?; Ok(SessionImpl { id: params.id, self_node_id: params.self_node_id, encrypted_data: params.encrypted_data, key_storage: params.key_storage, cluster: params.cluster, nonce: params.nonce, completed: Condvar::new(), data: Mutex::new(SessionData { state: SessionState::WaitingForInitialization, nodes: BTreeMap::new(), result: None, }), }) } /// Get this node Id. pub fn node(&self) -> &NodeId { &self.self_node_id } /// Start new session initialization. This must be called on master node. pub fn initialize(&self, requestor_signature: Signature, common_point: Public, encrypted_point: Public) -> Result<(), Error> { let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // update state data.state = SessionState::WaitingForInitializationConfirm; data.nodes.extend(self.cluster.nodes().into_iter().map(|n| (n, NodeData { initialization_confirmed: &n == self.node(), }))); // TODO: id signature is not enough here, as it was already used in key generation // TODO: there could be situation when some nodes have failed to store encrypted data // => potential problems during restore. some confirmation step is needed (2pc)? // save encryption data if let Some(mut encrypted_data) = self.encrypted_data.clone()
// start initialization if data.nodes.len() > 1 { self.cluster.broadcast(Message::Encryption(EncryptionMessage::InitializeEncryptionSession(InitializeEncryptionSession { session: self.id.clone().into(), session_nonce: self.nonce, requestor_signature: requestor_signature.into(), common_point: common_point.into(), encrypted_point: encrypted_point.into(), }))) } else { data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } /// When session initialization message is received. pub fn on_initialize_session(&self, sender: NodeId, message: &InitializeEncryptionSession) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // check that the requester is the author of the encrypted data if let Some(mut encrypted_data) = self.encrypted_data.clone() { let requestor_public = ethkey::recover(&message.requestor_signature.clone().into(), &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } // save encryption data encrypted_data.common_point = Some(message.common_point.clone().into()); encrypted_data.encrypted_point = Some(message.encrypted_point.clone().into()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // update state data.state = SessionState::Finished; // send confirmation back to master node self.cluster.send(&sender, Message::Encryption(EncryptionMessage::ConfirmEncryptionInitialization(ConfirmEncryptionInitialization { session: self.id.clone().into(), session_nonce: self.nonce, }))) } /// When session initialization confirmation message is reeived. pub fn on_confirm_initialization(&self, sender: NodeId, message: &ConfirmEncryptionInitialization) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); debug_assert!(data.nodes.contains_key(&sender)); // check if all nodes have confirmed initialization data.nodes.get_mut(&sender) .expect("message is received from cluster; nodes contains all cluster nodes; qed") .initialization_confirmed = true; if!data.nodes.values().all(|n| n.initialization_confirmed) { return Ok(()); } // update state data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } impl ClusterSession for SessionImpl { type Id = SessionId; fn type_name() -> &'static str { "encryption" } fn id(&self) -> SessionId { self.id.clone() } fn is_finished(&self) -> bool { let data = self.data.lock(); data.state == SessionState::Failed || data.state == SessionState::Finished } fn on_node_timeout(&self, node: &NodeId) { let mut data = self.data.lock(); warn!("{}: encryption session failed because {} connection has timeouted", self.node(), node); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_timeout(&self) { let mut data = self.data.lock(); warn!("{}: encryption session failed with timeout", self.node()); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_error(&self, node: &NodeId, error: Error) { // error in encryption session is considered fatal // => broadcast error if error occured on this node if *node == self.self_node_id { // do not bother processing send error, as we already processing error let _ = self.cluster.broadcast(Message::Encryption(EncryptionMessage::EncryptionSessionError(EncryptionSessionError { session: self.id.clone().into(), session_nonce: self.nonce, error: error.clone().into(), }))); } let mut data = self.data.lock(); warn!("{}: encryption session failed with error: {} from {}", self.node(), error, node); data.state = SessionState::Failed; data.result = Some(Err(error)); self.completed.notify_all(); } fn on_message(&self, sender: &NodeId, message: &Message) -> Result<(), Error> { if Some(self.nonce)!= message.session_nonce() { return Err(Error::ReplayProtection); } match message { &Message::Encryption(ref message) => match message { &EncryptionMessage::InitializeEncryptionSession(ref message) => self.on_initialize_session(sender.clone(), message), &EncryptionMessage::ConfirmEncryptionInitialization(ref message) => self.on_confirm_initialization(sender.clone(), message), &EncryptionMessage::EncryptionSessionError(ref message) => { self.on_session_error(sender, Error::Io(message.error.clone().into())); Ok(()) }, }, _ => unreachable!("cluster checks message to be correct before passing; qed"), } } } impl Session for SessionImpl { fn state(&self) -> SessionState { self.data.lock().state.clone() } fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error> { let mut data = self.data.lock(); if!data.result.is_some() { match timeout { None => self.completed.wait(&mut data), Some(timeout) => { self.completed.wait_for(&mut data, timeout); }, } } data.result.as_ref() .expect("checked above or waited for completed; completed is only signaled when result.is_some(); qed") .clone() } } impl Debug for SessionImpl { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "Encryption session {} on {}", self.id, self.self_node_id) } } fn check_encrypted_data(encrypted_data: &Option<DocumentKeyShare>) -> Result<(), Error> { if let &Some(ref encrypted_data) = encrypted_data { // check that common_point and encrypted_point are still not set yet if encrypted_data.common_point.is_some() || encrypted_data.encrypted_point.is_some() { return Err(Error::CompletedSessionId); } } Ok(()) }
{ // check that the requester is the author of the encrypted data let requestor_public = ethkey::recover(&requestor_signature, &self.id)?; if encrypted_data.author != requestor_public { return Err(Error::AccessDenied); } encrypted_data.common_point = Some(common_point.clone()); encrypted_data.encrypted_point = Some(encrypted_point.clone()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; }
conditional_block
encryption_session.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::collections::BTreeMap; use std::fmt::{Debug, Formatter, Error as FmtError}; use std::time; use std::sync::Arc; use parking_lot::{Condvar, Mutex}; use ethkey::{self, Public, Signature}; use key_server_cluster::{Error, NodeId, SessionId, KeyStorage, DocumentKeyShare}; use key_server_cluster::cluster::Cluster; use key_server_cluster::cluster_sessions::ClusterSession; use key_server_cluster::message::{Message, EncryptionMessage, InitializeEncryptionSession, ConfirmEncryptionInitialization, EncryptionSessionError}; /// Encryption session API. pub trait Session: Send + Sync +'static { /// Get encryption session state. fn state(&self) -> SessionState; /// Wait until session is completed. Returns distributely generated secret key. fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error>; } /// Encryption (distributed key generation) session. /// Based on "ECDKG: A Distributed Key Generation Protocol Based on Elliptic Curve Discrete Logarithm" paper: /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.124.4128&rep=rep1&type=pdf /// Brief overview: /// 1) initialization: master node (which has received request for storing the secret) initializes the session on all other nodes /// 2) master node sends common_point + encrypted_point to all other nodes /// 3) common_point + encrypted_point are saved on all nodes /// 4) in case of error, previous values are restored pub struct SessionImpl { /// Unique session id. id: SessionId, /// Public identifier of this node. self_node_id: NodeId, /// Encrypted data. encrypted_data: Option<DocumentKeyShare>, /// Key storage. key_storage: Arc<KeyStorage>, /// Cluster which allows this node to send messages to other nodes in the cluster. cluster: Arc<Cluster>, /// Session nonce. nonce: u64, /// SessionImpl completion condvar. completed: Condvar, /// Mutable session data. data: Mutex<SessionData>, } /// SessionImpl creation parameters pub struct SessionParams { /// SessionImpl identifier. pub id: SessionId, /// Id of node, on which this session is running. pub self_node_id: Public, /// Encrypted data (result of running generation_session::SessionImpl). pub encrypted_data: Option<DocumentKeyShare>, /// Key storage. pub key_storage: Arc<KeyStorage>, /// Cluster pub cluster: Arc<Cluster>, /// Session nonce. pub nonce: u64, } /// Mutable data of encryption (distributed key generation) session. #[derive(Debug)] struct SessionData { /// Current state of the session. state: SessionState, /// Nodes-specific data. nodes: BTreeMap<NodeId, NodeData>, /// Encryption session result. result: Option<Result<(), Error>>, } /// Mutable node-specific data. #[derive(Debug, Clone)] struct NodeData { // === Values, filled during initialization phase === /// Flags marking that node has confirmed session initialization. pub initialization_confirmed: bool, } /// Encryption (distributed key generation) session state. #[derive(Debug, Clone, PartialEq)] pub enum SessionState { // === Initialization states === /// Every node starts in this state. WaitingForInitialization, /// Master node waits for every other node to confirm initialization. WaitingForInitializationConfirm, // === Final states of the session === /// Encryption data is saved. Finished, /// Failed to save encryption data. Failed, } impl SessionImpl { /// Create new encryption session. pub fn new(params: SessionParams) -> Result<Self, Error> { check_encrypted_data(&params.encrypted_data)?; Ok(SessionImpl { id: params.id, self_node_id: params.self_node_id, encrypted_data: params.encrypted_data, key_storage: params.key_storage, cluster: params.cluster, nonce: params.nonce, completed: Condvar::new(), data: Mutex::new(SessionData { state: SessionState::WaitingForInitialization, nodes: BTreeMap::new(), result: None, }), }) } /// Get this node Id. pub fn
(&self) -> &NodeId { &self.self_node_id } /// Start new session initialization. This must be called on master node. pub fn initialize(&self, requestor_signature: Signature, common_point: Public, encrypted_point: Public) -> Result<(), Error> { let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // update state data.state = SessionState::WaitingForInitializationConfirm; data.nodes.extend(self.cluster.nodes().into_iter().map(|n| (n, NodeData { initialization_confirmed: &n == self.node(), }))); // TODO: id signature is not enough here, as it was already used in key generation // TODO: there could be situation when some nodes have failed to store encrypted data // => potential problems during restore. some confirmation step is needed (2pc)? // save encryption data if let Some(mut encrypted_data) = self.encrypted_data.clone() { // check that the requester is the author of the encrypted data let requestor_public = ethkey::recover(&requestor_signature, &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } encrypted_data.common_point = Some(common_point.clone()); encrypted_data.encrypted_point = Some(encrypted_point.clone()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // start initialization if data.nodes.len() > 1 { self.cluster.broadcast(Message::Encryption(EncryptionMessage::InitializeEncryptionSession(InitializeEncryptionSession { session: self.id.clone().into(), session_nonce: self.nonce, requestor_signature: requestor_signature.into(), common_point: common_point.into(), encrypted_point: encrypted_point.into(), }))) } else { data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } /// When session initialization message is received. pub fn on_initialize_session(&self, sender: NodeId, message: &InitializeEncryptionSession) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); // check state if data.state!= SessionState::WaitingForInitialization { return Err(Error::InvalidStateForRequest); } // check that the requester is the author of the encrypted data if let Some(mut encrypted_data) = self.encrypted_data.clone() { let requestor_public = ethkey::recover(&message.requestor_signature.clone().into(), &self.id)?; if encrypted_data.author!= requestor_public { return Err(Error::AccessDenied); } // save encryption data encrypted_data.common_point = Some(message.common_point.clone().into()); encrypted_data.encrypted_point = Some(message.encrypted_point.clone().into()); self.key_storage.update(self.id.clone(), encrypted_data) .map_err(|e| Error::KeyStorage(e.into()))?; } // update state data.state = SessionState::Finished; // send confirmation back to master node self.cluster.send(&sender, Message::Encryption(EncryptionMessage::ConfirmEncryptionInitialization(ConfirmEncryptionInitialization { session: self.id.clone().into(), session_nonce: self.nonce, }))) } /// When session initialization confirmation message is reeived. pub fn on_confirm_initialization(&self, sender: NodeId, message: &ConfirmEncryptionInitialization) -> Result<(), Error> { debug_assert!(self.id == *message.session); debug_assert!(&sender!= self.node()); let mut data = self.data.lock(); debug_assert!(data.nodes.contains_key(&sender)); // check if all nodes have confirmed initialization data.nodes.get_mut(&sender) .expect("message is received from cluster; nodes contains all cluster nodes; qed") .initialization_confirmed = true; if!data.nodes.values().all(|n| n.initialization_confirmed) { return Ok(()); } // update state data.state = SessionState::Finished; data.result = Some(Ok(())); self.completed.notify_all(); Ok(()) } } impl ClusterSession for SessionImpl { type Id = SessionId; fn type_name() -> &'static str { "encryption" } fn id(&self) -> SessionId { self.id.clone() } fn is_finished(&self) -> bool { let data = self.data.lock(); data.state == SessionState::Failed || data.state == SessionState::Finished } fn on_node_timeout(&self, node: &NodeId) { let mut data = self.data.lock(); warn!("{}: encryption session failed because {} connection has timeouted", self.node(), node); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_timeout(&self) { let mut data = self.data.lock(); warn!("{}: encryption session failed with timeout", self.node()); data.state = SessionState::Failed; data.result = Some(Err(Error::NodeDisconnected)); self.completed.notify_all(); } fn on_session_error(&self, node: &NodeId, error: Error) { // error in encryption session is considered fatal // => broadcast error if error occured on this node if *node == self.self_node_id { // do not bother processing send error, as we already processing error let _ = self.cluster.broadcast(Message::Encryption(EncryptionMessage::EncryptionSessionError(EncryptionSessionError { session: self.id.clone().into(), session_nonce: self.nonce, error: error.clone().into(), }))); } let mut data = self.data.lock(); warn!("{}: encryption session failed with error: {} from {}", self.node(), error, node); data.state = SessionState::Failed; data.result = Some(Err(error)); self.completed.notify_all(); } fn on_message(&self, sender: &NodeId, message: &Message) -> Result<(), Error> { if Some(self.nonce)!= message.session_nonce() { return Err(Error::ReplayProtection); } match message { &Message::Encryption(ref message) => match message { &EncryptionMessage::InitializeEncryptionSession(ref message) => self.on_initialize_session(sender.clone(), message), &EncryptionMessage::ConfirmEncryptionInitialization(ref message) => self.on_confirm_initialization(sender.clone(), message), &EncryptionMessage::EncryptionSessionError(ref message) => { self.on_session_error(sender, Error::Io(message.error.clone().into())); Ok(()) }, }, _ => unreachable!("cluster checks message to be correct before passing; qed"), } } } impl Session for SessionImpl { fn state(&self) -> SessionState { self.data.lock().state.clone() } fn wait(&self, timeout: Option<time::Duration>) -> Result<(), Error> { let mut data = self.data.lock(); if!data.result.is_some() { match timeout { None => self.completed.wait(&mut data), Some(timeout) => { self.completed.wait_for(&mut data, timeout); }, } } data.result.as_ref() .expect("checked above or waited for completed; completed is only signaled when result.is_some(); qed") .clone() } } impl Debug for SessionImpl { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { write!(f, "Encryption session {} on {}", self.id, self.self_node_id) } } fn check_encrypted_data(encrypted_data: &Option<DocumentKeyShare>) -> Result<(), Error> { if let &Some(ref encrypted_data) = encrypted_data { // check that common_point and encrypted_point are still not set yet if encrypted_data.common_point.is_some() || encrypted_data.encrypted_point.is_some() { return Err(Error::CompletedSessionId); } } Ok(()) }
node
identifier_name
pipe.rs
use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use crate::sys_common::IntoInner; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut fds = [0; 2]; // The only known way right now to create atomically set the CLOEXEC flag is // to use the `pipe2` syscall. This was added to Linux in 2.6.27, glibc 2.9 // and musl 0.9.3, and some other targets also have it. cfg_if::cfg_if! { if #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd", target_os = "redox" ))] { unsafe { cvt(libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC))?; Ok((AnonPipe(FileDesc::from_raw_fd(fds[0])), AnonPipe(FileDesc::from_raw_fd(fds[1])))) } } else { unsafe { cvt(libc::pipe(fds.as_mut_ptr()))?; let fd0 = FileDesc::from_raw_fd(fds[0]); let fd1 = FileDesc::from_raw_fd(fds[1]); fd0.set_cloexec()?; fd1.set_cloexec()?; Ok((AnonPipe(fd0), AnonPipe(fd1))) } } } } impl AnonPipe { pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { self.0.read_vectored(bufs) } #[inline] pub fn is_read_vectored(&self) -> bool { self.0.is_read_vectored() } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { self.0.write_vectored(bufs) } #[inline] pub fn is_write_vectored(&self) -> bool { self.0.is_write_vectored() } } impl IntoInner<FileDesc> for AnonPipe { fn into_inner(self) -> FileDesc { self.0 } } pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> { // Set both pipes into nonblocking mode as we're gonna be reading from both // in the `select` loop below, and we wouldn't want one to block the other! let p1 = p1.into_inner(); let p2 = p2.into_inner(); p1.set_nonblocking(true)?; p2.set_nonblocking(true)?; let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() }; fds[0].fd = p1.as_raw_fd(); fds[0].events = libc::POLLIN; fds[1].fd = p2.as_raw_fd(); fds[1].events = libc::POLLIN; loop { // wait for either pipe to become readable using `poll` cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?; if fds[0].revents!= 0 && read(&p1, v1)? { p2.set_nonblocking(false)?; return p2.read_to_end(v2).map(drop); } if fds[1].revents!= 0 && read(&p2, v2)? { p1.set_nonblocking(false)?; return p1.read_to_end(v1).map(drop); } } // Read as much as we can from each pipe, ignoring EWOULDBLOCK or // EAGAIN. If we hit EOF, then this will happen because the underlying // reader will return Ok(0), in which case we'll see `Ok` ourselves. In // this case we flip the other fd back into blocking mode and read // whatever's leftover on that file descriptor. fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> { match fd.read_to_end(dst) { Ok(_) => Ok(true), Err(e) => { if e.raw_os_error() == Some(libc::EWOULDBLOCK) || e.raw_os_error() == Some(libc::EAGAIN) { Ok(false) } else { Err(e) } } } } } impl AsRawFd for AnonPipe { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl AsFd for AnonPipe { fn as_fd(&self) -> BorrowedFd<'_> { self.0.as_fd() } } impl IntoRawFd for AnonPipe { fn
(self) -> RawFd { self.0.into_raw_fd() } } impl FromRawFd for AnonPipe { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { Self(FromRawFd::from_raw_fd(raw_fd)) } }
into_raw_fd
identifier_name
pipe.rs
use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use crate::sys_common::IntoInner; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut fds = [0; 2]; // The only known way right now to create atomically set the CLOEXEC flag is // to use the `pipe2` syscall. This was added to Linux in 2.6.27, glibc 2.9 // and musl 0.9.3, and some other targets also have it.
target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd", target_os = "redox" ))] { unsafe { cvt(libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC))?; Ok((AnonPipe(FileDesc::from_raw_fd(fds[0])), AnonPipe(FileDesc::from_raw_fd(fds[1])))) } } else { unsafe { cvt(libc::pipe(fds.as_mut_ptr()))?; let fd0 = FileDesc::from_raw_fd(fds[0]); let fd1 = FileDesc::from_raw_fd(fds[1]); fd0.set_cloexec()?; fd1.set_cloexec()?; Ok((AnonPipe(fd0), AnonPipe(fd1))) } } } } impl AnonPipe { pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { self.0.read_vectored(bufs) } #[inline] pub fn is_read_vectored(&self) -> bool { self.0.is_read_vectored() } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { self.0.write_vectored(bufs) } #[inline] pub fn is_write_vectored(&self) -> bool { self.0.is_write_vectored() } } impl IntoInner<FileDesc> for AnonPipe { fn into_inner(self) -> FileDesc { self.0 } } pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> { // Set both pipes into nonblocking mode as we're gonna be reading from both // in the `select` loop below, and we wouldn't want one to block the other! let p1 = p1.into_inner(); let p2 = p2.into_inner(); p1.set_nonblocking(true)?; p2.set_nonblocking(true)?; let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() }; fds[0].fd = p1.as_raw_fd(); fds[0].events = libc::POLLIN; fds[1].fd = p2.as_raw_fd(); fds[1].events = libc::POLLIN; loop { // wait for either pipe to become readable using `poll` cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?; if fds[0].revents!= 0 && read(&p1, v1)? { p2.set_nonblocking(false)?; return p2.read_to_end(v2).map(drop); } if fds[1].revents!= 0 && read(&p2, v2)? { p1.set_nonblocking(false)?; return p1.read_to_end(v1).map(drop); } } // Read as much as we can from each pipe, ignoring EWOULDBLOCK or // EAGAIN. If we hit EOF, then this will happen because the underlying // reader will return Ok(0), in which case we'll see `Ok` ourselves. In // this case we flip the other fd back into blocking mode and read // whatever's leftover on that file descriptor. fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> { match fd.read_to_end(dst) { Ok(_) => Ok(true), Err(e) => { if e.raw_os_error() == Some(libc::EWOULDBLOCK) || e.raw_os_error() == Some(libc::EAGAIN) { Ok(false) } else { Err(e) } } } } } impl AsRawFd for AnonPipe { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl AsFd for AnonPipe { fn as_fd(&self) -> BorrowedFd<'_> { self.0.as_fd() } } impl IntoRawFd for AnonPipe { fn into_raw_fd(self) -> RawFd { self.0.into_raw_fd() } } impl FromRawFd for AnonPipe { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { Self(FromRawFd::from_raw_fd(raw_fd)) } }
cfg_if::cfg_if! { if #[cfg(any( target_os = "dragonfly",
random_line_split
pipe.rs
use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use crate::sys_common::IntoInner; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut fds = [0; 2]; // The only known way right now to create atomically set the CLOEXEC flag is // to use the `pipe2` syscall. This was added to Linux in 2.6.27, glibc 2.9 // and musl 0.9.3, and some other targets also have it. cfg_if::cfg_if! { if #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd", target_os = "redox" ))] { unsafe { cvt(libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC))?; Ok((AnonPipe(FileDesc::from_raw_fd(fds[0])), AnonPipe(FileDesc::from_raw_fd(fds[1])))) } } else { unsafe { cvt(libc::pipe(fds.as_mut_ptr()))?; let fd0 = FileDesc::from_raw_fd(fds[0]); let fd1 = FileDesc::from_raw_fd(fds[1]); fd0.set_cloexec()?; fd1.set_cloexec()?; Ok((AnonPipe(fd0), AnonPipe(fd1))) } } } } impl AnonPipe { pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { self.0.read_vectored(bufs) } #[inline] pub fn is_read_vectored(&self) -> bool { self.0.is_read_vectored() } pub fn write(&self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { self.0.write_vectored(bufs) } #[inline] pub fn is_write_vectored(&self) -> bool { self.0.is_write_vectored() } } impl IntoInner<FileDesc> for AnonPipe { fn into_inner(self) -> FileDesc { self.0 } } pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> { // Set both pipes into nonblocking mode as we're gonna be reading from both // in the `select` loop below, and we wouldn't want one to block the other! let p1 = p1.into_inner(); let p2 = p2.into_inner(); p1.set_nonblocking(true)?; p2.set_nonblocking(true)?; let mut fds: [libc::pollfd; 2] = unsafe { mem::zeroed() }; fds[0].fd = p1.as_raw_fd(); fds[0].events = libc::POLLIN; fds[1].fd = p2.as_raw_fd(); fds[1].events = libc::POLLIN; loop { // wait for either pipe to become readable using `poll` cvt_r(|| unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) })?; if fds[0].revents!= 0 && read(&p1, v1)? { p2.set_nonblocking(false)?; return p2.read_to_end(v2).map(drop); } if fds[1].revents!= 0 && read(&p2, v2)? { p1.set_nonblocking(false)?; return p1.read_to_end(v1).map(drop); } } // Read as much as we can from each pipe, ignoring EWOULDBLOCK or // EAGAIN. If we hit EOF, then this will happen because the underlying // reader will return Ok(0), in which case we'll see `Ok` ourselves. In // this case we flip the other fd back into blocking mode and read // whatever's leftover on that file descriptor. fn read(fd: &FileDesc, dst: &mut Vec<u8>) -> Result<bool, io::Error> { match fd.read_to_end(dst) { Ok(_) => Ok(true), Err(e) => { if e.raw_os_error() == Some(libc::EWOULDBLOCK) || e.raw_os_error() == Some(libc::EAGAIN) { Ok(false) } else { Err(e) } } } } } impl AsRawFd for AnonPipe { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl AsFd for AnonPipe { fn as_fd(&self) -> BorrowedFd<'_>
} impl IntoRawFd for AnonPipe { fn into_raw_fd(self) -> RawFd { self.0.into_raw_fd() } } impl FromRawFd for AnonPipe { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { Self(FromRawFd::from_raw_fd(raw_fd)) } }
{ self.0.as_fd() }
identifier_body
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn new(color: Color, x: f32, dot_width: f32, dot_height: f32, num_dots: i32) -> Net { return Net { color: color, x: x, dot_width: dot_width, dot_height: dot_height, num_dots: num_dots }; } } impl Drawable for Net { fn draw(&self, ui: &mut Ui) { let dot_x = self.x; let num_gaps = self.num_dots - 1; for i in 0..self.num_dots + num_gaps + 1 { if i % 2 == 0
} } }
{ let dot_y = i as f32 * self.dot_height; ui.renderer.set_draw_color(self.color); let dot_rect = Rect::new_unwrap(dot_x as i32, dot_y as i32, self.dot_width as u32, self.dot_height as u32); ui.renderer.fill_rect(dot_rect); }
conditional_block
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn new(color: Color, x: f32, dot_width: f32, dot_height: f32, num_dots: i32) -> Net { return Net { color: color, x: x, dot_width: dot_width, dot_height: dot_height, num_dots: num_dots }; } } impl Drawable for Net { fn draw(&self, ui: &mut Ui) { let dot_x = self.x; let num_gaps = self.num_dots - 1; for i in 0..self.num_dots + num_gaps + 1 { if i % 2 == 0 { let dot_y = i as f32 * self.dot_height; ui.renderer.set_draw_color(self.color); let dot_rect = Rect::new_unwrap(dot_x as i32, dot_y as i32, self.dot_width as u32, self.dot_height as u32); ui.renderer.fill_rect(dot_rect); }
} } }
random_line_split
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn
(color: Color, x: f32, dot_width: f32, dot_height: f32, num_dots: i32) -> Net { return Net { color: color, x: x, dot_width: dot_width, dot_height: dot_height, num_dots: num_dots }; } } impl Drawable for Net { fn draw(&self, ui: &mut Ui) { let dot_x = self.x; let num_gaps = self.num_dots - 1; for i in 0..self.num_dots + num_gaps + 1 { if i % 2 == 0 { let dot_y = i as f32 * self.dot_height; ui.renderer.set_draw_color(self.color); let dot_rect = Rect::new_unwrap(dot_x as i32, dot_y as i32, self.dot_width as u32, self.dot_height as u32); ui.renderer.fill_rect(dot_rect); } } } }
new
identifier_name
net.rs
use pongo::ui::{Drawable,Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; pub struct Net { pub color: Color, pub x: f32, // x pixel coordinate of top left corner pub dot_width: f32, pub dot_height: f32, pub num_dots: i32 } impl Net { pub fn new(color: Color, x: f32, dot_width: f32, dot_height: f32, num_dots: i32) -> Net
} impl Drawable for Net { fn draw(&self, ui: &mut Ui) { let dot_x = self.x; let num_gaps = self.num_dots - 1; for i in 0..self.num_dots + num_gaps + 1 { if i % 2 == 0 { let dot_y = i as f32 * self.dot_height; ui.renderer.set_draw_color(self.color); let dot_rect = Rect::new_unwrap(dot_x as i32, dot_y as i32, self.dot_width as u32, self.dot_height as u32); ui.renderer.fill_rect(dot_rect); } } } }
{ return Net { color: color, x: x, dot_width: dot_width, dot_height: dot_height, num_dots: num_dots }; }
identifier_body
borrowck-borrowed-uniq-rvalue.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. //buggy.rs use std::hashmap::HashMap; fn main()
{ let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); buggy_map.insert(42, &*~1); //~ ERROR borrowed value does not live long enough // but it is ok if we use a temporary let tmp = ~2; buggy_map.insert(43, &*tmp); }
identifier_body
borrowck-borrowed-uniq-rvalue.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. //buggy.rs use std::hashmap::HashMap; fn
() { let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); buggy_map.insert(42, &*~1); //~ ERROR borrowed value does not live long enough // but it is ok if we use a temporary let tmp = ~2; buggy_map.insert(43, &*tmp); }
main
identifier_name
borrowck-borrowed-uniq-rvalue.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. //buggy.rs use std::hashmap::HashMap; fn main() { let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); buggy_map.insert(42, &*~1); //~ ERROR borrowed value does not live long enough
// but it is ok if we use a temporary let tmp = ~2; buggy_map.insert(43, &*tmp); }
random_line_split
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Collection types. */ #![crate_id = "collections#0.11.0-pre"] #![experimental] #![crate_type = "rlib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/", html_playground_url = "http://play.rust-lang.org/")] #![feature(macro_rules, managed_boxes, default_type_params, phase, globs)] #![feature(unsafe_destructor)] #![no_std] #[phase(plugin, link)] extern crate core; extern crate alloc; #[cfg(test)] extern crate native; #[cfg(test)] extern crate test; #[cfg(test)] extern crate debug; #[cfg(test)] #[phase(plugin, link)] extern crate std; #[cfg(test)] #[phase(plugin, link)] extern crate log; use core::prelude::*; pub use core::collections::Collection; pub use bitv::{Bitv, BitvSet}; pub use btree::BTree; pub use dlist::DList; pub use enum_set::EnumSet; pub use priority_queue::PriorityQueue; pub use ringbuf::RingBuf; pub use smallintmap::SmallIntMap; pub use string::String; pub use treemap::{TreeMap, TreeSet}; pub use trie::{TrieMap, TrieSet}; pub use vec::Vec; mod macros; pub mod bitv; pub mod btree; pub mod dlist; pub mod enum_set; pub mod priority_queue; pub mod ringbuf; pub mod smallintmap; pub mod treemap; pub mod trie; pub mod slice; pub mod str; pub mod string; pub mod vec; pub mod hash; // Internal unicode fiddly bits for the str module mod unicode; mod deque; /// A trait to represent mutable containers pub trait Mutable: Collection { /// Clear the container, removing all values. fn clear(&mut self); } /// A map is a key-value store where values may be looked up by their keys. This /// trait provides basic operations to operate on these stores. pub trait Map<K, V>: Collection { /// Return a reference to the value corresponding to the key fn find<'a>(&'a self, key: &K) -> Option<&'a V>; /// Return true if the map contains a value for the specified key #[inline] fn contains_key(&self, key: &K) -> bool
} /// This trait provides basic operations to modify the contents of a map. pub trait MutableMap<K, V>: Map<K, V> + Mutable { /// Insert a key-value pair into the map. An existing value for a /// key is replaced by the new value. Return true if the key did /// not already exist in the map. #[inline] fn insert(&mut self, key: K, value: V) -> bool { self.swap(key, value).is_none() } /// Remove a key-value pair from the map. Return true if the key /// was present in the map, otherwise false. #[inline] fn remove(&mut self, key: &K) -> bool { self.pop(key).is_some() } /// Insert a key-value pair from the map. If the key already had a value /// present in the map, that value is returned. Otherwise None is returned. fn swap(&mut self, k: K, v: V) -> Option<V>; /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. fn pop(&mut self, k: &K) -> Option<V>; /// Return a mutable reference to the value corresponding to the key fn find_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V>; } /// A set is a group of objects which are each distinct from one another. This /// trait represents actions which can be performed on sets to iterate over /// them. pub trait Set<T>: Collection { /// Return true if the set contains a value fn contains(&self, value: &T) -> bool; /// Return true if the set has no elements in common with `other`. /// This is equivalent to checking for an empty intersection. fn is_disjoint(&self, other: &Self) -> bool; /// Return true if the set is a subset of another fn is_subset(&self, other: &Self) -> bool; /// Return true if the set is a superset of another fn is_superset(&self, other: &Self) -> bool { other.is_subset(self) } // FIXME #8154: Add difference, sym. difference, intersection and union iterators } /// This trait represents actions which can be performed on sets to mutate /// them. pub trait MutableSet<T>: Set<T> + Mutable { /// Add a value to the set. Return true if the value was not already /// present in the set. fn insert(&mut self, value: T) -> bool; /// Remove a value from the set. Return true if the value was /// present in the set. fn remove(&mut self, value: &T) -> bool; } /// A double-ended sequence that allows querying, insertion and deletion at both /// ends. pub trait Deque<T> : Mutable { /// Provide a reference to the front element, or None if the sequence is /// empty fn front<'a>(&'a self) -> Option<&'a T>; /// Provide a mutable reference to the front element, or None if the /// sequence is empty fn front_mut<'a>(&'a mut self) -> Option<&'a mut T>; /// Provide a reference to the back element, or None if the sequence is /// empty fn back<'a>(&'a self) -> Option<&'a T>; /// Provide a mutable reference to the back element, or None if the sequence /// is empty fn back_mut<'a>(&'a mut self) -> Option<&'a mut T>; /// Insert an element first in the sequence fn push_front(&mut self, elt: T); /// Insert an element last in the sequence fn push_back(&mut self, elt: T); /// Remove the last element and return it, or None if the sequence is empty fn pop_back(&mut self) -> Option<T>; /// Remove the first element and return it, or None if the sequence is empty fn pop_front(&mut self) -> Option<T>; } // FIXME(#14344) this shouldn't be necessary #[doc(hidden)] pub fn fixme_14344_be_sure_to_link_to_collections() {} #[cfg(not(test))] mod std { pub use core::fmt; // necessary for fail!() pub use core::option; // necessary for fail!() pub use core::clone; // deriving(Clone) pub use core::cmp; // deriving(Eq, Ord, etc.) pub use hash; // deriving(Hash) }
{ self.find(key).is_some() }
identifier_body
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Collection types. */ #![crate_id = "collections#0.11.0-pre"] #![experimental] #![crate_type = "rlib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/", html_playground_url = "http://play.rust-lang.org/")] #![feature(macro_rules, managed_boxes, default_type_params, phase, globs)] #![feature(unsafe_destructor)] #![no_std] #[phase(plugin, link)] extern crate core; extern crate alloc; #[cfg(test)] extern crate native; #[cfg(test)] extern crate test; #[cfg(test)] extern crate debug; #[cfg(test)] #[phase(plugin, link)] extern crate std; #[cfg(test)] #[phase(plugin, link)] extern crate log; use core::prelude::*; pub use core::collections::Collection; pub use bitv::{Bitv, BitvSet}; pub use btree::BTree; pub use dlist::DList; pub use enum_set::EnumSet; pub use priority_queue::PriorityQueue; pub use ringbuf::RingBuf; pub use smallintmap::SmallIntMap; pub use string::String; pub use treemap::{TreeMap, TreeSet}; pub use trie::{TrieMap, TrieSet}; pub use vec::Vec; mod macros; pub mod bitv; pub mod btree; pub mod dlist; pub mod enum_set; pub mod priority_queue; pub mod ringbuf; pub mod smallintmap; pub mod treemap; pub mod trie; pub mod slice; pub mod str; pub mod string; pub mod vec; pub mod hash; // Internal unicode fiddly bits for the str module mod unicode; mod deque; /// A trait to represent mutable containers pub trait Mutable: Collection { /// Clear the container, removing all values. fn clear(&mut self); } /// A map is a key-value store where values may be looked up by their keys. This /// trait provides basic operations to operate on these stores. pub trait Map<K, V>: Collection { /// Return a reference to the value corresponding to the key fn find<'a>(&'a self, key: &K) -> Option<&'a V>; /// Return true if the map contains a value for the specified key #[inline] fn
(&self, key: &K) -> bool { self.find(key).is_some() } } /// This trait provides basic operations to modify the contents of a map. pub trait MutableMap<K, V>: Map<K, V> + Mutable { /// Insert a key-value pair into the map. An existing value for a /// key is replaced by the new value. Return true if the key did /// not already exist in the map. #[inline] fn insert(&mut self, key: K, value: V) -> bool { self.swap(key, value).is_none() } /// Remove a key-value pair from the map. Return true if the key /// was present in the map, otherwise false. #[inline] fn remove(&mut self, key: &K) -> bool { self.pop(key).is_some() } /// Insert a key-value pair from the map. If the key already had a value /// present in the map, that value is returned. Otherwise None is returned. fn swap(&mut self, k: K, v: V) -> Option<V>; /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. fn pop(&mut self, k: &K) -> Option<V>; /// Return a mutable reference to the value corresponding to the key fn find_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V>; } /// A set is a group of objects which are each distinct from one another. This /// trait represents actions which can be performed on sets to iterate over /// them. pub trait Set<T>: Collection { /// Return true if the set contains a value fn contains(&self, value: &T) -> bool; /// Return true if the set has no elements in common with `other`. /// This is equivalent to checking for an empty intersection. fn is_disjoint(&self, other: &Self) -> bool; /// Return true if the set is a subset of another fn is_subset(&self, other: &Self) -> bool; /// Return true if the set is a superset of another fn is_superset(&self, other: &Self) -> bool { other.is_subset(self) } // FIXME #8154: Add difference, sym. difference, intersection and union iterators } /// This trait represents actions which can be performed on sets to mutate /// them. pub trait MutableSet<T>: Set<T> + Mutable { /// Add a value to the set. Return true if the value was not already /// present in the set. fn insert(&mut self, value: T) -> bool; /// Remove a value from the set. Return true if the value was /// present in the set. fn remove(&mut self, value: &T) -> bool; } /// A double-ended sequence that allows querying, insertion and deletion at both /// ends. pub trait Deque<T> : Mutable { /// Provide a reference to the front element, or None if the sequence is /// empty fn front<'a>(&'a self) -> Option<&'a T>; /// Provide a mutable reference to the front element, or None if the /// sequence is empty fn front_mut<'a>(&'a mut self) -> Option<&'a mut T>; /// Provide a reference to the back element, or None if the sequence is /// empty fn back<'a>(&'a self) -> Option<&'a T>; /// Provide a mutable reference to the back element, or None if the sequence /// is empty fn back_mut<'a>(&'a mut self) -> Option<&'a mut T>; /// Insert an element first in the sequence fn push_front(&mut self, elt: T); /// Insert an element last in the sequence fn push_back(&mut self, elt: T); /// Remove the last element and return it, or None if the sequence is empty fn pop_back(&mut self) -> Option<T>; /// Remove the first element and return it, or None if the sequence is empty fn pop_front(&mut self) -> Option<T>; } // FIXME(#14344) this shouldn't be necessary #[doc(hidden)] pub fn fixme_14344_be_sure_to_link_to_collections() {} #[cfg(not(test))] mod std { pub use core::fmt; // necessary for fail!() pub use core::option; // necessary for fail!() pub use core::clone; // deriving(Clone) pub use core::cmp; // deriving(Eq, Ord, etc.) pub use hash; // deriving(Hash) }
contains_key
identifier_name
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Collection types. */ #![crate_id = "collections#0.11.0-pre"] #![experimental] #![crate_type = "rlib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/", html_playground_url = "http://play.rust-lang.org/")] #![feature(macro_rules, managed_boxes, default_type_params, phase, globs)] #![feature(unsafe_destructor)] #![no_std] #[phase(plugin, link)] extern crate core; extern crate alloc; #[cfg(test)] extern crate native; #[cfg(test)] extern crate test; #[cfg(test)] extern crate debug; #[cfg(test)] #[phase(plugin, link)] extern crate std; #[cfg(test)] #[phase(plugin, link)] extern crate log; use core::prelude::*; pub use core::collections::Collection; pub use bitv::{Bitv, BitvSet}; pub use btree::BTree; pub use dlist::DList; pub use enum_set::EnumSet; pub use priority_queue::PriorityQueue; pub use ringbuf::RingBuf; pub use smallintmap::SmallIntMap; pub use string::String; pub use treemap::{TreeMap, TreeSet}; pub use trie::{TrieMap, TrieSet}; pub use vec::Vec; mod macros; pub mod bitv; pub mod btree; pub mod dlist; pub mod enum_set; pub mod priority_queue; pub mod ringbuf; pub mod smallintmap; pub mod treemap; pub mod trie; pub mod slice; pub mod str; pub mod string; pub mod vec; pub mod hash; // Internal unicode fiddly bits for the str module mod unicode; mod deque; /// A trait to represent mutable containers pub trait Mutable: Collection { /// Clear the container, removing all values. fn clear(&mut self); } /// A map is a key-value store where values may be looked up by their keys. This
/// Return true if the map contains a value for the specified key #[inline] fn contains_key(&self, key: &K) -> bool { self.find(key).is_some() } } /// This trait provides basic operations to modify the contents of a map. pub trait MutableMap<K, V>: Map<K, V> + Mutable { /// Insert a key-value pair into the map. An existing value for a /// key is replaced by the new value. Return true if the key did /// not already exist in the map. #[inline] fn insert(&mut self, key: K, value: V) -> bool { self.swap(key, value).is_none() } /// Remove a key-value pair from the map. Return true if the key /// was present in the map, otherwise false. #[inline] fn remove(&mut self, key: &K) -> bool { self.pop(key).is_some() } /// Insert a key-value pair from the map. If the key already had a value /// present in the map, that value is returned. Otherwise None is returned. fn swap(&mut self, k: K, v: V) -> Option<V>; /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. fn pop(&mut self, k: &K) -> Option<V>; /// Return a mutable reference to the value corresponding to the key fn find_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V>; } /// A set is a group of objects which are each distinct from one another. This /// trait represents actions which can be performed on sets to iterate over /// them. pub trait Set<T>: Collection { /// Return true if the set contains a value fn contains(&self, value: &T) -> bool; /// Return true if the set has no elements in common with `other`. /// This is equivalent to checking for an empty intersection. fn is_disjoint(&self, other: &Self) -> bool; /// Return true if the set is a subset of another fn is_subset(&self, other: &Self) -> bool; /// Return true if the set is a superset of another fn is_superset(&self, other: &Self) -> bool { other.is_subset(self) } // FIXME #8154: Add difference, sym. difference, intersection and union iterators } /// This trait represents actions which can be performed on sets to mutate /// them. pub trait MutableSet<T>: Set<T> + Mutable { /// Add a value to the set. Return true if the value was not already /// present in the set. fn insert(&mut self, value: T) -> bool; /// Remove a value from the set. Return true if the value was /// present in the set. fn remove(&mut self, value: &T) -> bool; } /// A double-ended sequence that allows querying, insertion and deletion at both /// ends. pub trait Deque<T> : Mutable { /// Provide a reference to the front element, or None if the sequence is /// empty fn front<'a>(&'a self) -> Option<&'a T>; /// Provide a mutable reference to the front element, or None if the /// sequence is empty fn front_mut<'a>(&'a mut self) -> Option<&'a mut T>; /// Provide a reference to the back element, or None if the sequence is /// empty fn back<'a>(&'a self) -> Option<&'a T>; /// Provide a mutable reference to the back element, or None if the sequence /// is empty fn back_mut<'a>(&'a mut self) -> Option<&'a mut T>; /// Insert an element first in the sequence fn push_front(&mut self, elt: T); /// Insert an element last in the sequence fn push_back(&mut self, elt: T); /// Remove the last element and return it, or None if the sequence is empty fn pop_back(&mut self) -> Option<T>; /// Remove the first element and return it, or None if the sequence is empty fn pop_front(&mut self) -> Option<T>; } // FIXME(#14344) this shouldn't be necessary #[doc(hidden)] pub fn fixme_14344_be_sure_to_link_to_collections() {} #[cfg(not(test))] mod std { pub use core::fmt; // necessary for fail!() pub use core::option; // necessary for fail!() pub use core::clone; // deriving(Clone) pub use core::cmp; // deriving(Eq, Ord, etc.) pub use hash; // deriving(Hash) }
/// trait provides basic operations to operate on these stores. pub trait Map<K, V>: Collection { /// Return a reference to the value corresponding to the key fn find<'a>(&'a self, key: &K) -> Option<&'a V>;
random_line_split
text-fields-attribute.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ EditableSignals, Inhibit, prelude::EntryExt, prelude::LabelExt, prelude::OrientableExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::Widget; use relm_derive::{Msg, widget}; use self::Msg::*; pub struct Model { content: String, } #[derive(Msg)] pub enum Msg { Change(String, usize), Quit, } #[widget] impl Widget for Win { fn model() -> Model { Model { content: String::new(), } } fn update(&mut self, event: Msg) { match event { Change(text, len) => { self.model.content = text.chars().rev().collect(); self.model.content += &format!(" ({})", len); }, Quit => gtk::main_quit(), } } view! {
changed(entry) => { let text = entry.text().to_string(); let len = text.len(); Change(text, len) }, placeholder_text: Some("Text to reverse"), }, #[name="label"] gtk::Label { text: &self.model.content, }, }, delete_event(_, _) => (Quit, Inhibit(false)), } } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gdk::keys::constants as key; use gtk::prelude::LabelExt; use gtk_test::assert_text; use relm_test::{enter_key, enter_keys}; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let entry = &widgets.entry; let label = &widgets.label; assert_text!(label, ""); enter_keys(entry, "test"); assert_text!(label, "tset (4)"); enter_key(entry, key::BackSpace); assert_text!(label, "set (3)"); enter_key(entry, key::Home); //enter_key(entry, key::Delete); // TODO: when supported by enigo. enter_keys(entry, "a"); assert_text!(label, "seta (4)"); enter_key(entry, key::End); enter_keys(entry, "a"); //assert_text!(label, "aseta (5)"); // FIXME } }
gtk::Window { gtk::Box { orientation: Vertical, #[name="entry"] gtk::Entry {
random_line_split
text-fields-attribute.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ EditableSignals, Inhibit, prelude::EntryExt, prelude::LabelExt, prelude::OrientableExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::Widget; use relm_derive::{Msg, widget}; use self::Msg::*; pub struct
{ content: String, } #[derive(Msg)] pub enum Msg { Change(String, usize), Quit, } #[widget] impl Widget for Win { fn model() -> Model { Model { content: String::new(), } } fn update(&mut self, event: Msg) { match event { Change(text, len) => { self.model.content = text.chars().rev().collect(); self.model.content += &format!(" ({})", len); }, Quit => gtk::main_quit(), } } view! { gtk::Window { gtk::Box { orientation: Vertical, #[name="entry"] gtk::Entry { changed(entry) => { let text = entry.text().to_string(); let len = text.len(); Change(text, len) }, placeholder_text: Some("Text to reverse"), }, #[name="label"] gtk::Label { text: &self.model.content, }, }, delete_event(_, _) => (Quit, Inhibit(false)), } } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gdk::keys::constants as key; use gtk::prelude::LabelExt; use gtk_test::assert_text; use relm_test::{enter_key, enter_keys}; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let entry = &widgets.entry; let label = &widgets.label; assert_text!(label, ""); enter_keys(entry, "test"); assert_text!(label, "tset (4)"); enter_key(entry, key::BackSpace); assert_text!(label, "set (3)"); enter_key(entry, key::Home); //enter_key(entry, key::Delete); // TODO: when supported by enigo. enter_keys(entry, "a"); assert_text!(label, "seta (4)"); enter_key(entry, key::End); enter_keys(entry, "a"); //assert_text!(label, "aseta (5)"); // FIXME } }
Model
identifier_name
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_name="UserInterface") %> <%helpers:longhand name="cursor" boxed="${product == 'gecko'}" animation_value_type="discrete" spec="https://drafts.csswg.org/css-ui/#cursor"> pub use self::computed_value::T as SpecifiedValue; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; pub mod computed_value { #[cfg(feature = "gecko")] use std::fmt; #[cfg(feature = "gecko")] use style_traits::ToCss; use style_traits::cursor::Cursor; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue, ToCss)] pub enum Keyword { Auto, Cursor(Cursor), } #[cfg(not(feature = "gecko"))] pub type T = Keyword; #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Image { pub url: SpecifiedUrl, pub hotspot: Option<(f32, f32)>, } #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct T { pub images: Vec<Image>, pub keyword: Keyword, } #[cfg(feature = "gecko")] impl ToCss for Image { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.url.to_css(dest)?; if let Some((x, y)) = self.hotspot { dest.write_str(" ")?; x.to_css(dest)?; dest.write_str(" ")?; y.to_css(dest)?; } Ok(()) } } #[cfg(feature = "gecko")] impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { for url in &self.images { url.to_css(dest)?; dest.write_str(", ")?; } self.keyword.to_css(dest) } } } #[cfg(not(feature = "gecko"))] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::Keyword::Auto } #[cfg(feature = "gecko")] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { images: vec![], keyword: computed_value::Keyword::Auto } } impl Parse for computed_value::Keyword { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
let ident = input.expect_ident()?; if ident.eq_ignore_ascii_case("auto") { Ok(computed_value::Keyword::Auto) } else { Cursor::from_css_keyword(&ident) .map(computed_value::Keyword::Cursor) .map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into()) } } } #[cfg(feature = "gecko")] fn parse_image<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Image, ParseError<'i>> { Ok(computed_value::Image { url: SpecifiedUrl::parse(context, input)?, hotspot: match input.try(|input| input.expect_number()) { Ok(number) => Some((number, input.expect_number()?)), Err(_) => None, }, }) } #[cfg(not(feature = "gecko"))] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { computed_value::Keyword::parse(context, input) } /// cursor: [<url> [<number> <number>]?]# [auto | default |...] #[cfg(feature = "gecko")] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { let mut images = vec![]; loop { match input.try(|input| parse_image(context, input)) { Ok(mut image) => { image.url.build_image_value(); images.push(image) } Err(_) => break, } input.expect_comma()?; } Ok(computed_value::T { images: images, keyword: computed_value::Keyword::parse(context, input)?, }) } </%helpers:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${helpers.single_keyword("pointer-events", "auto none", animation_value_type="discrete", extra_gecko_values="visiblepainted visiblefill visiblestroke visible painted fill stroke all", flags="APPLIES_TO_PLACEHOLDER", spec="https://www.w3.org/TR/SVG11/interact.html#PointerEventsProperty")} ${helpers.single_keyword("-moz-user-input", "auto none enabled disabled", products="gecko", gecko_ffi_name="mUserInput", gecko_enum_prefix="StyleUserInput", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-input)")} ${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko", gecko_ffi_name="mUserModify", gecko_enum_prefix="StyleUserModify", needs_conversion=True, animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-modify)")} ${helpers.single_keyword("-moz-user-focus", "none ignore normal select-after select-before select-menu select-same select-all", products="gecko", gecko_ffi_name="mUserFocus", gecko_enum_prefix="StyleUserFocus", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-focus)")} ${helpers.predefined_type( "caret-color", "ColorOrAuto", "Either::Second(Auto)", spec="https://drafts.csswg.org/css-ui/#caret-color", animation_value_type="Either<AnimatedColor, Auto>", boxed=True, ignored_when_colors_disabled=True, products="gecko", )}
-> Result<computed_value::Keyword, ParseError<'i>> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor;
random_line_split
pointing.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_name="UserInterface") %> <%helpers:longhand name="cursor" boxed="${product == 'gecko'}" animation_value_type="discrete" spec="https://drafts.csswg.org/css-ui/#cursor"> pub use self::computed_value::T as SpecifiedValue; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; pub mod computed_value { #[cfg(feature = "gecko")] use std::fmt; #[cfg(feature = "gecko")] use style_traits::ToCss; use style_traits::cursor::Cursor; #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, Copy, Debug, PartialEq, ToComputedValue, ToCss)] pub enum Keyword { Auto, Cursor(Cursor), } #[cfg(not(feature = "gecko"))] pub type T = Keyword; #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct Image { pub url: SpecifiedUrl, pub hotspot: Option<(f32, f32)>, } #[cfg(feature = "gecko")] #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue)] pub struct T { pub images: Vec<Image>, pub keyword: Keyword, } #[cfg(feature = "gecko")] impl ToCss for Image { fn
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.url.to_css(dest)?; if let Some((x, y)) = self.hotspot { dest.write_str(" ")?; x.to_css(dest)?; dest.write_str(" ")?; y.to_css(dest)?; } Ok(()) } } #[cfg(feature = "gecko")] impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { for url in &self.images { url.to_css(dest)?; dest.write_str(", ")?; } self.keyword.to_css(dest) } } } #[cfg(not(feature = "gecko"))] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::Keyword::Auto } #[cfg(feature = "gecko")] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { images: vec![], keyword: computed_value::Keyword::Auto } } impl Parse for computed_value::Keyword { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Keyword, ParseError<'i>> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor; let ident = input.expect_ident()?; if ident.eq_ignore_ascii_case("auto") { Ok(computed_value::Keyword::Auto) } else { Cursor::from_css_keyword(&ident) .map(computed_value::Keyword::Cursor) .map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into()) } } } #[cfg(feature = "gecko")] fn parse_image<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Image, ParseError<'i>> { Ok(computed_value::Image { url: SpecifiedUrl::parse(context, input)?, hotspot: match input.try(|input| input.expect_number()) { Ok(number) => Some((number, input.expect_number()?)), Err(_) => None, }, }) } #[cfg(not(feature = "gecko"))] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { computed_value::Keyword::parse(context, input) } /// cursor: [<url> [<number> <number>]?]# [auto | default |...] #[cfg(feature = "gecko")] pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { let mut images = vec![]; loop { match input.try(|input| parse_image(context, input)) { Ok(mut image) => { image.url.build_image_value(); images.push(image) } Err(_) => break, } input.expect_comma()?; } Ok(computed_value::T { images: images, keyword: computed_value::Keyword::parse(context, input)?, }) } </%helpers:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${helpers.single_keyword("pointer-events", "auto none", animation_value_type="discrete", extra_gecko_values="visiblepainted visiblefill visiblestroke visible painted fill stroke all", flags="APPLIES_TO_PLACEHOLDER", spec="https://www.w3.org/TR/SVG11/interact.html#PointerEventsProperty")} ${helpers.single_keyword("-moz-user-input", "auto none enabled disabled", products="gecko", gecko_ffi_name="mUserInput", gecko_enum_prefix="StyleUserInput", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-input)")} ${helpers.single_keyword("-moz-user-modify", "read-only read-write write-only", products="gecko", gecko_ffi_name="mUserModify", gecko_enum_prefix="StyleUserModify", needs_conversion=True, animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-modify)")} ${helpers.single_keyword("-moz-user-focus", "none ignore normal select-after select-before select-menu select-same select-all", products="gecko", gecko_ffi_name="mUserFocus", gecko_enum_prefix="StyleUserFocus", animation_value_type="discrete", spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-user-focus)")} ${helpers.predefined_type( "caret-color", "ColorOrAuto", "Either::Second(Auto)", spec="https://drafts.csswg.org/css-ui/#caret-color", animation_value_type="Either<AnimatedColor, Auto>", boxed=True, ignored_when_colors_disabled=True, products="gecko", )}
to_css
identifier_name
clone.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The `Clone` trait for types that cannot be 'implicitly copied' //! //! In Rust, some simple types are "implicitly copyable" and when you //! assign them or pass them as arguments, the receiver will get a copy, //! leaving the original value in place. These types do not require //! allocation to copy and do not have finalizers (i.e. they do not //! contain owned boxes or implement `Drop`), so the compiler considers //! them cheap and safe to copy. For other types copies must be made //! explicitly, by convention implementing the `Clone` trait and calling //! the `clone` method. #![unstable] use kinds::Sized; /// A common trait for cloning an object. pub trait Clone { /// Returns a copy of the value. fn clone(&self) -> Self; /// Perform copy-assignment from `source`. /// /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality, /// but can be overridden to reuse the resources of `a` to avoid unnecessary /// allocations. #[inline(always)] #[experimental = "this function is mostly unused"] fn clone_from(&mut self, source: &Self)
} impl<'a, Sized? T> Clone for &'a T { /// Return a shallow copy of the reference. #[inline] fn clone(&self) -> &'a T { *self } } macro_rules! clone_impl( ($t:ty) => { impl Clone for $t { /// Return a deep copy of the value. #[inline] fn clone(&self) -> $t { *self } } } ) clone_impl!(int) clone_impl!(i8) clone_impl!(i16) clone_impl!(i32) clone_impl!(i64) clone_impl!(uint) clone_impl!(u8) clone_impl!(u16) clone_impl!(u32) clone_impl!(u64) clone_impl!(f32) clone_impl!(f64) clone_impl!(()) clone_impl!(bool) clone_impl!(char) macro_rules! extern_fn_clone( ($($A:ident),*) => ( #[experimental = "this may not be sufficient for fns with region parameters"] impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType { /// Return a copy of a function pointer #[inline] fn clone(&self) -> extern "Rust" fn($($A),*) -> ReturnType { *self } } ) ) extern_fn_clone!() extern_fn_clone!(A) extern_fn_clone!(A, B) extern_fn_clone!(A, B, C) extern_fn_clone!(A, B, C, D) extern_fn_clone!(A, B, C, D, E) extern_fn_clone!(A, B, C, D, E, F) extern_fn_clone!(A, B, C, D, E, F, G) extern_fn_clone!(A, B, C, D, E, F, G, H)
{ *self = source.clone() }
identifier_body
clone.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The `Clone` trait for types that cannot be 'implicitly copied' //! //! In Rust, some simple types are "implicitly copyable" and when you //! assign them or pass them as arguments, the receiver will get a copy, //! leaving the original value in place. These types do not require //! allocation to copy and do not have finalizers (i.e. they do not //! contain owned boxes or implement `Drop`), so the compiler considers //! them cheap and safe to copy. For other types copies must be made //! explicitly, by convention implementing the `Clone` trait and calling //! the `clone` method. #![unstable] use kinds::Sized; /// A common trait for cloning an object. pub trait Clone { /// Returns a copy of the value. fn clone(&self) -> Self; /// Perform copy-assignment from `source`. /// /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality, /// but can be overridden to reuse the resources of `a` to avoid unnecessary /// allocations. #[inline(always)] #[experimental = "this function is mostly unused"] fn clone_from(&mut self, source: &Self) { *self = source.clone() } } impl<'a, Sized? T> Clone for &'a T { /// Return a shallow copy of the reference. #[inline] fn
(&self) -> &'a T { *self } } macro_rules! clone_impl( ($t:ty) => { impl Clone for $t { /// Return a deep copy of the value. #[inline] fn clone(&self) -> $t { *self } } } ) clone_impl!(int) clone_impl!(i8) clone_impl!(i16) clone_impl!(i32) clone_impl!(i64) clone_impl!(uint) clone_impl!(u8) clone_impl!(u16) clone_impl!(u32) clone_impl!(u64) clone_impl!(f32) clone_impl!(f64) clone_impl!(()) clone_impl!(bool) clone_impl!(char) macro_rules! extern_fn_clone( ($($A:ident),*) => ( #[experimental = "this may not be sufficient for fns with region parameters"] impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType { /// Return a copy of a function pointer #[inline] fn clone(&self) -> extern "Rust" fn($($A),*) -> ReturnType { *self } } ) ) extern_fn_clone!() extern_fn_clone!(A) extern_fn_clone!(A, B) extern_fn_clone!(A, B, C) extern_fn_clone!(A, B, C, D) extern_fn_clone!(A, B, C, D, E) extern_fn_clone!(A, B, C, D, E, F) extern_fn_clone!(A, B, C, D, E, F, G) extern_fn_clone!(A, B, C, D, E, F, G, H)
clone
identifier_name
clone.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The `Clone` trait for types that cannot be 'implicitly copied' //! //! In Rust, some simple types are "implicitly copyable" and when you //! assign them or pass them as arguments, the receiver will get a copy, //! leaving the original value in place. These types do not require //! allocation to copy and do not have finalizers (i.e. they do not //! contain owned boxes or implement `Drop`), so the compiler considers //! them cheap and safe to copy. For other types copies must be made //! explicitly, by convention implementing the `Clone` trait and calling //! the `clone` method. #![unstable] use kinds::Sized; /// A common trait for cloning an object. pub trait Clone { /// Returns a copy of the value. fn clone(&self) -> Self; /// Perform copy-assignment from `source`. /// /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality, /// but can be overridden to reuse the resources of `a` to avoid unnecessary /// allocations. #[inline(always)] #[experimental = "this function is mostly unused"] fn clone_from(&mut self, source: &Self) { *self = source.clone() } } impl<'a, Sized? T> Clone for &'a T { /// Return a shallow copy of the reference. #[inline] fn clone(&self) -> &'a T { *self } } macro_rules! clone_impl( ($t:ty) => { impl Clone for $t { /// Return a deep copy of the value. #[inline] fn clone(&self) -> $t { *self } } } ) clone_impl!(int) clone_impl!(i8)
clone_impl!(uint) clone_impl!(u8) clone_impl!(u16) clone_impl!(u32) clone_impl!(u64) clone_impl!(f32) clone_impl!(f64) clone_impl!(()) clone_impl!(bool) clone_impl!(char) macro_rules! extern_fn_clone( ($($A:ident),*) => ( #[experimental = "this may not be sufficient for fns with region parameters"] impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType { /// Return a copy of a function pointer #[inline] fn clone(&self) -> extern "Rust" fn($($A),*) -> ReturnType { *self } } ) ) extern_fn_clone!() extern_fn_clone!(A) extern_fn_clone!(A, B) extern_fn_clone!(A, B, C) extern_fn_clone!(A, B, C, D) extern_fn_clone!(A, B, C, D, E) extern_fn_clone!(A, B, C, D, E, F) extern_fn_clone!(A, B, C, D, E, F, G) extern_fn_clone!(A, B, C, D, E, F, G, H)
clone_impl!(i16) clone_impl!(i32) clone_impl!(i64)
random_line_split
preempt.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test // This checks that preemption works. // note: halfway done porting to modern rust use std::comm; fn starve_main(alive: Receiver<isize>) { println!("signalling main"); alive.recv(); println!("starving main"); let mut i: isize = 0; loop { i += 1; } } pub fn main()
{ let (port, chan) = stream(); println!("main started"); spawn(move|| { starve_main(port); }); let mut i: isize = 0; println!("main waiting for alive signal"); chan.send(i); println!("main got alive signal"); while i < 50 { println!("main iterated"); i += 1; } println!("main completed"); }
identifier_body
preempt.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test // This checks that preemption works.
// note: halfway done porting to modern rust use std::comm; fn starve_main(alive: Receiver<isize>) { println!("signalling main"); alive.recv(); println!("starving main"); let mut i: isize = 0; loop { i += 1; } } pub fn main() { let (port, chan) = stream(); println!("main started"); spawn(move|| { starve_main(port); }); let mut i: isize = 0; println!("main waiting for alive signal"); chan.send(i); println!("main got alive signal"); while i < 50 { println!("main iterated"); i += 1; } println!("main completed"); }
random_line_split
preempt.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-test // This checks that preemption works. // note: halfway done porting to modern rust use std::comm; fn starve_main(alive: Receiver<isize>) { println!("signalling main"); alive.recv(); println!("starving main"); let mut i: isize = 0; loop { i += 1; } } pub fn
() { let (port, chan) = stream(); println!("main started"); spawn(move|| { starve_main(port); }); let mut i: isize = 0; println!("main waiting for alive signal"); chan.send(i); println!("main got alive signal"); while i < 50 { println!("main iterated"); i += 1; } println!("main completed"); }
main
identifier_name
doepdmab.rs
#[doc = "Register `DOEPDMAB` reader"] pub struct R(crate::R<DOEPDMAB_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DOEPDMAB_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DOEPDMAB_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DOEPDMAB_SPEC>) -> Self { R(reader) } } #[doc = "Field `DMABufferAddr` reader - DMA Buffer Address"] pub struct
(crate::FieldReader<u32, u32>); impl DMABUFFERADDR_R { pub(crate) fn new(bits: u32) -> Self { DMABUFFERADDR_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DMABUFFERADDR_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:31 - DMA Buffer Address"] #[inline(always)] pub fn dmabuffer_addr(&self) -> DMABUFFERADDR_R { DMABUFFERADDR_R::new((self.bits & 0xffff_ffff) as u32) } } #[doc = "Device Endpoint DMA Buffer Address Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [doepdmab](index.html) module"] pub struct DOEPDMAB_SPEC; impl crate::RegisterSpec for DOEPDMAB_SPEC { type Ux = u32; } #[doc = "`read()` method returns [doepdmab::R](R) reader structure"] impl crate::Readable for DOEPDMAB_SPEC { type Reader = R; } #[doc = "`reset()` method sets DOEPDMAB to value 0"] impl crate::Resettable for DOEPDMAB_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
DMABUFFERADDR_R
identifier_name
doepdmab.rs
#[doc = "Register `DOEPDMAB` reader"] pub struct R(crate::R<DOEPDMAB_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DOEPDMAB_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DOEPDMAB_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DOEPDMAB_SPEC>) -> Self { R(reader) }
pub(crate) fn new(bits: u32) -> Self { DMABUFFERADDR_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DMABUFFERADDR_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:31 - DMA Buffer Address"] #[inline(always)] pub fn dmabuffer_addr(&self) -> DMABUFFERADDR_R { DMABUFFERADDR_R::new((self.bits & 0xffff_ffff) as u32) } } #[doc = "Device Endpoint DMA Buffer Address Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [doepdmab](index.html) module"] pub struct DOEPDMAB_SPEC; impl crate::RegisterSpec for DOEPDMAB_SPEC { type Ux = u32; } #[doc = "`read()` method returns [doepdmab::R](R) reader structure"] impl crate::Readable for DOEPDMAB_SPEC { type Reader = R; } #[doc = "`reset()` method sets DOEPDMAB to value 0"] impl crate::Resettable for DOEPDMAB_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
} #[doc = "Field `DMABufferAddr` reader - DMA Buffer Address"] pub struct DMABUFFERADDR_R(crate::FieldReader<u32, u32>); impl DMABUFFERADDR_R {
random_line_split
lib.rs
//! A library of Conflict-free Replicated Data Types. //! //! ###### Further Reading //! //! 1. [_A comprehensive study of Convergent and Commutative Replicated Data Types_](http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf) (Shapiro, et al.) //! 2. [_An Optimized Conflict-free Replicated Set_](http://arxiv.org/pdf/1210.3368.pdf) (Bieniusa, et al.) #![cfg_attr(test, feature(custom_attribute, plugin))] #![cfg_attr(test, plugin(quickcheck_macros))] #[cfg(any(quickcheck, test))] extern crate quickcheck; #[cfg(any(quickcheck, test))] extern crate rand; pub mod counter; pub mod register; pub mod set; mod pn; #[cfg(test)] pub mod test; /// A Conflict-free Replicated Data Type. /// /// Conflict-free replicated data types (also called convergent and commutative /// replicated data types) allow for concurrent updates to distributed replicas /// with strong eventual consistency and without coordination. /// /// ###### Replication /// /// Updates to CRDTs can be shared with replicas in two ways: state-based /// replication and operation-based replication. With state-based replication, /// the entire state of the mutated CRDT is merged into remote replicas in order /// to restore consistency. With operation-based replication, only the mutating /// operation is applied to remote replicas in order to restore consistency. /// Operation-based replication is lighter weight in terms of the amount of /// data which must be transmitted to replicas per mutation, but has the /// requirement that all operations must be reliably broadcast and applied to /// remote replicas. State-based replication schemes can maintain (eventual) /// consistency merely by guaranteeing that state based replication will /// (eventually) happen. Shapiro, et al. have shown that state-based CRDTs are /// equivalent to operation-based CRDTs. The CRDTs exposed by this library /// allow for either state-based or operation-based replication, or a mix of /// both. /// /// When possible, operation-based replication is idempotent, so applying an /// operation to a replica multiple times will have no effect. Consult the /// individual CRDT documentation to determine if operation-based replication is /// idempotent. State-based replication is always idempotent. /// /// ###### Partial Ordering /// /// Replicas of a CRDT are partially-ordered over the set of possible /// operations. If all operations applied to replica `B` have been applied to /// `A` (or, somewhat equivalently, if `B` has been merged into `A`), then /// `A <= B`. /// /// ###### Equality /// /// Equality among CRDT replicas does not take into account the replica ID, if /// it exists. Only the operation history is taken into account. pub trait Crdt : Clone + Eq + PartialOrd { type Operation: Clone; /// Merge a replica into this CRDT. /// /// This method is used to perform state-based replication. fn merge(&mut self, other: Self); /// Apply an operation to this CRDT. /// /// This method is used to perform operation-based replication. fn apply(&mut self, op: Self::Operation); } /// The Id of an individual replica of a Crdt. /// /// Some CRDTs require a `u64` replica ID upon creation. The replica ID **must** /// be unique among replicas, so it should be taken from unique per-replica /// configuration, or from a source of strong coordination such as /// [ZooKeeper](http://zookeeper.apache.org/) or [etcd](https://github.com/coreos/etcd). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ReplicaId(u64); impl ReplicaId { pub fn id(self) -> u64 { self.0 } } impl From<u64> for ReplicaId { fn from(val: u64) -> ReplicaId { ReplicaId(val) } } #[cfg(any(quickcheck, test))] impl quickcheck::Arbitrary for ReplicaId { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> ReplicaId { ReplicaId(quickcheck::Arbitrary::arbitrary(g)) } fn shrink(&self) -> Box<Iterator<Item=ReplicaId> +'static> { Box::new(self.id().shrink().map(|id| ReplicaId(id))) } } /// Generate a replica ID suitable for local testing. /// /// The replica ID is guaranteed to be unique within the processes. This /// function should **not** be used for generating replica IDs in a distributed /// system. #[cfg(any(quickcheck, test))] pub fn gen_replica_id() -> ReplicaId { use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static mut REPLICA_COUNT: AtomicUsize = ATOMIC_USIZE_INIT; let id = unsafe { REPLICA_COUNT.fetch_add(1, Ordering::SeqCst) as u64 }; ReplicaId(id) } /// The Id for an individual operation on a CRDT. /// /// Some CRDTs require the user to provide a transaction ID when performing /// mutating operations. Transaction IDs provided to an individual replica /// **must** be monotonically increasing across operations. Transaction IDs /// across replicas **must** be unique, and **should** be as close to globally /// monotonically increasing as possible. Unlike replicas IDs, these /// requirements do not require strong coordination among replicas. See /// [Snowflake](https://github.com/twitter/snowflake) for an example of /// distributed, uncoordinated ID generation which meets the requirements. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TransactionId(u64); impl TransactionId { pub fn id(self) -> u64 { self.0 } } impl From<u64> for TransactionId { fn from(val: u64) -> TransactionId { TransactionId(val) } } #[cfg(any(quickcheck, test))] impl quickcheck::Arbitrary for TransactionId {
} }
fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> TransactionId { TransactionId(quickcheck::Arbitrary::arbitrary(g)) } fn shrink(&self) -> Box<Iterator<Item=TransactionId> + 'static> { Box::new(self.id().shrink().map(|id| TransactionId(id)))
random_line_split
lib.rs
//! A library of Conflict-free Replicated Data Types. //! //! ###### Further Reading //! //! 1. [_A comprehensive study of Convergent and Commutative Replicated Data Types_](http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf) (Shapiro, et al.) //! 2. [_An Optimized Conflict-free Replicated Set_](http://arxiv.org/pdf/1210.3368.pdf) (Bieniusa, et al.) #![cfg_attr(test, feature(custom_attribute, plugin))] #![cfg_attr(test, plugin(quickcheck_macros))] #[cfg(any(quickcheck, test))] extern crate quickcheck; #[cfg(any(quickcheck, test))] extern crate rand; pub mod counter; pub mod register; pub mod set; mod pn; #[cfg(test)] pub mod test; /// A Conflict-free Replicated Data Type. /// /// Conflict-free replicated data types (also called convergent and commutative /// replicated data types) allow for concurrent updates to distributed replicas /// with strong eventual consistency and without coordination. /// /// ###### Replication /// /// Updates to CRDTs can be shared with replicas in two ways: state-based /// replication and operation-based replication. With state-based replication, /// the entire state of the mutated CRDT is merged into remote replicas in order /// to restore consistency. With operation-based replication, only the mutating /// operation is applied to remote replicas in order to restore consistency. /// Operation-based replication is lighter weight in terms of the amount of /// data which must be transmitted to replicas per mutation, but has the /// requirement that all operations must be reliably broadcast and applied to /// remote replicas. State-based replication schemes can maintain (eventual) /// consistency merely by guaranteeing that state based replication will /// (eventually) happen. Shapiro, et al. have shown that state-based CRDTs are /// equivalent to operation-based CRDTs. The CRDTs exposed by this library /// allow for either state-based or operation-based replication, or a mix of /// both. /// /// When possible, operation-based replication is idempotent, so applying an /// operation to a replica multiple times will have no effect. Consult the /// individual CRDT documentation to determine if operation-based replication is /// idempotent. State-based replication is always idempotent. /// /// ###### Partial Ordering /// /// Replicas of a CRDT are partially-ordered over the set of possible /// operations. If all operations applied to replica `B` have been applied to /// `A` (or, somewhat equivalently, if `B` has been merged into `A`), then /// `A <= B`. /// /// ###### Equality /// /// Equality among CRDT replicas does not take into account the replica ID, if /// it exists. Only the operation history is taken into account. pub trait Crdt : Clone + Eq + PartialOrd { type Operation: Clone; /// Merge a replica into this CRDT. /// /// This method is used to perform state-based replication. fn merge(&mut self, other: Self); /// Apply an operation to this CRDT. /// /// This method is used to perform operation-based replication. fn apply(&mut self, op: Self::Operation); } /// The Id of an individual replica of a Crdt. /// /// Some CRDTs require a `u64` replica ID upon creation. The replica ID **must** /// be unique among replicas, so it should be taken from unique per-replica /// configuration, or from a source of strong coordination such as /// [ZooKeeper](http://zookeeper.apache.org/) or [etcd](https://github.com/coreos/etcd). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ReplicaId(u64); impl ReplicaId { pub fn id(self) -> u64 { self.0 } } impl From<u64> for ReplicaId { fn from(val: u64) -> ReplicaId { ReplicaId(val) } } #[cfg(any(quickcheck, test))] impl quickcheck::Arbitrary for ReplicaId { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> ReplicaId { ReplicaId(quickcheck::Arbitrary::arbitrary(g)) } fn shrink(&self) -> Box<Iterator<Item=ReplicaId> +'static> { Box::new(self.id().shrink().map(|id| ReplicaId(id))) } } /// Generate a replica ID suitable for local testing. /// /// The replica ID is guaranteed to be unique within the processes. This /// function should **not** be used for generating replica IDs in a distributed /// system. #[cfg(any(quickcheck, test))] pub fn gen_replica_id() -> ReplicaId { use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static mut REPLICA_COUNT: AtomicUsize = ATOMIC_USIZE_INIT; let id = unsafe { REPLICA_COUNT.fetch_add(1, Ordering::SeqCst) as u64 }; ReplicaId(id) } /// The Id for an individual operation on a CRDT. /// /// Some CRDTs require the user to provide a transaction ID when performing /// mutating operations. Transaction IDs provided to an individual replica /// **must** be monotonically increasing across operations. Transaction IDs /// across replicas **must** be unique, and **should** be as close to globally /// monotonically increasing as possible. Unlike replicas IDs, these /// requirements do not require strong coordination among replicas. See /// [Snowflake](https://github.com/twitter/snowflake) for an example of /// distributed, uncoordinated ID generation which meets the requirements. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TransactionId(u64); impl TransactionId { pub fn id(self) -> u64 { self.0 } } impl From<u64> for TransactionId { fn from(val: u64) -> TransactionId { TransactionId(val) } } #[cfg(any(quickcheck, test))] impl quickcheck::Arbitrary for TransactionId { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> TransactionId { TransactionId(quickcheck::Arbitrary::arbitrary(g)) } fn
(&self) -> Box<Iterator<Item=TransactionId> +'static> { Box::new(self.id().shrink().map(|id| TransactionId(id))) } }
shrink
identifier_name
lib.rs
//! A library of Conflict-free Replicated Data Types. //! //! ###### Further Reading //! //! 1. [_A comprehensive study of Convergent and Commutative Replicated Data Types_](http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf) (Shapiro, et al.) //! 2. [_An Optimized Conflict-free Replicated Set_](http://arxiv.org/pdf/1210.3368.pdf) (Bieniusa, et al.) #![cfg_attr(test, feature(custom_attribute, plugin))] #![cfg_attr(test, plugin(quickcheck_macros))] #[cfg(any(quickcheck, test))] extern crate quickcheck; #[cfg(any(quickcheck, test))] extern crate rand; pub mod counter; pub mod register; pub mod set; mod pn; #[cfg(test)] pub mod test; /// A Conflict-free Replicated Data Type. /// /// Conflict-free replicated data types (also called convergent and commutative /// replicated data types) allow for concurrent updates to distributed replicas /// with strong eventual consistency and without coordination. /// /// ###### Replication /// /// Updates to CRDTs can be shared with replicas in two ways: state-based /// replication and operation-based replication. With state-based replication, /// the entire state of the mutated CRDT is merged into remote replicas in order /// to restore consistency. With operation-based replication, only the mutating /// operation is applied to remote replicas in order to restore consistency. /// Operation-based replication is lighter weight in terms of the amount of /// data which must be transmitted to replicas per mutation, but has the /// requirement that all operations must be reliably broadcast and applied to /// remote replicas. State-based replication schemes can maintain (eventual) /// consistency merely by guaranteeing that state based replication will /// (eventually) happen. Shapiro, et al. have shown that state-based CRDTs are /// equivalent to operation-based CRDTs. The CRDTs exposed by this library /// allow for either state-based or operation-based replication, or a mix of /// both. /// /// When possible, operation-based replication is idempotent, so applying an /// operation to a replica multiple times will have no effect. Consult the /// individual CRDT documentation to determine if operation-based replication is /// idempotent. State-based replication is always idempotent. /// /// ###### Partial Ordering /// /// Replicas of a CRDT are partially-ordered over the set of possible /// operations. If all operations applied to replica `B` have been applied to /// `A` (or, somewhat equivalently, if `B` has been merged into `A`), then /// `A <= B`. /// /// ###### Equality /// /// Equality among CRDT replicas does not take into account the replica ID, if /// it exists. Only the operation history is taken into account. pub trait Crdt : Clone + Eq + PartialOrd { type Operation: Clone; /// Merge a replica into this CRDT. /// /// This method is used to perform state-based replication. fn merge(&mut self, other: Self); /// Apply an operation to this CRDT. /// /// This method is used to perform operation-based replication. fn apply(&mut self, op: Self::Operation); } /// The Id of an individual replica of a Crdt. /// /// Some CRDTs require a `u64` replica ID upon creation. The replica ID **must** /// be unique among replicas, so it should be taken from unique per-replica /// configuration, or from a source of strong coordination such as /// [ZooKeeper](http://zookeeper.apache.org/) or [etcd](https://github.com/coreos/etcd). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ReplicaId(u64); impl ReplicaId { pub fn id(self) -> u64 { self.0 } } impl From<u64> for ReplicaId { fn from(val: u64) -> ReplicaId { ReplicaId(val) } } #[cfg(any(quickcheck, test))] impl quickcheck::Arbitrary for ReplicaId { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> ReplicaId { ReplicaId(quickcheck::Arbitrary::arbitrary(g)) } fn shrink(&self) -> Box<Iterator<Item=ReplicaId> +'static> { Box::new(self.id().shrink().map(|id| ReplicaId(id))) } } /// Generate a replica ID suitable for local testing. /// /// The replica ID is guaranteed to be unique within the processes. This /// function should **not** be used for generating replica IDs in a distributed /// system. #[cfg(any(quickcheck, test))] pub fn gen_replica_id() -> ReplicaId
/// The Id for an individual operation on a CRDT. /// /// Some CRDTs require the user to provide a transaction ID when performing /// mutating operations. Transaction IDs provided to an individual replica /// **must** be monotonically increasing across operations. Transaction IDs /// across replicas **must** be unique, and **should** be as close to globally /// monotonically increasing as possible. Unlike replicas IDs, these /// requirements do not require strong coordination among replicas. See /// [Snowflake](https://github.com/twitter/snowflake) for an example of /// distributed, uncoordinated ID generation which meets the requirements. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TransactionId(u64); impl TransactionId { pub fn id(self) -> u64 { self.0 } } impl From<u64> for TransactionId { fn from(val: u64) -> TransactionId { TransactionId(val) } } #[cfg(any(quickcheck, test))] impl quickcheck::Arbitrary for TransactionId { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> TransactionId { TransactionId(quickcheck::Arbitrary::arbitrary(g)) } fn shrink(&self) -> Box<Iterator<Item=TransactionId> +'static> { Box::new(self.id().shrink().map(|id| TransactionId(id))) } }
{ use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static mut REPLICA_COUNT: AtomicUsize = ATOMIC_USIZE_INIT; let id = unsafe { REPLICA_COUNT.fetch_add(1, Ordering::SeqCst) as u64 }; ReplicaId(id) }
identifier_body
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use image::io::Reader as ImageReader; use image::GenericImageView; fn main() -> Result<(), Box<dyn Error>> { let export_dir = "examples/mobilenetv3"; let model_file: PathBuf = [export_dir, "saved_model.pb"].iter().collect(); if!model_file.exists()
// Create input variables for our addition let mut x = Tensor::new(&[1, 224, 224, 3]); let img = ImageReader::open("examples/mobilenetv3/sample.png")?.decode()?; for (i, (_, _, pixel)) in img.pixels().enumerate() { x[3 * i] = pixel.0[0] as f32; x[3 * i + 1] = pixel.0[1] as f32; x[3 * i + 2] = pixel.0[2] as f32; } // Load the saved model exported by zenn_savedmodel.py. let mut graph = Graph::new(); let bundle = SavedModelBundle::load(&SessionOptions::new(), &["serve"], &mut graph, export_dir)?; let session = &bundle.session; // get in/out operations let signature = bundle .meta_graph_def() .get_signature(DEFAULT_SERVING_SIGNATURE_DEF_KEY)?; let x_info = signature.get_input("input_1")?; let op_x = &graph.operation_by_name_required(&x_info.name().name)?; let output_info = signature.get_output("Predictions")?; let op_output = &graph.operation_by_name_required(&output_info.name().name)?; // Run the graph. let mut args = SessionRunArgs::new(); args.add_feed(op_x, 0, &x); let token_output = args.request_fetch(op_output, 0); session.run(&mut args)?; // Check the output. let output: Tensor<f32> = args.fetch(token_output)?; // Calculate argmax of the output let (max_idx, _max_val) = output .iter() .enumerate() .fold((0, output[0]), |(idx_max, val_max), (idx, val)| { if &val_max > val { (idx_max, val_max) } else { (idx, *val) } }); // This index is expected to be identical with that of the Python code, // but this is not guaranteed due to floating operations. println!("argmax={}", max_idx); Ok(()) }
{ return Err(Box::new( Status::new_set( Code::NotFound, &format!( "Run 'python examples/mobilenetv3/create_model.py' to generate \ {} and try again.", model_file.display() ), ) .unwrap(), )); }
conditional_block
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use image::io::Reader as ImageReader; use image::GenericImageView; fn main() -> Result<(), Box<dyn Error>> { let export_dir = "examples/mobilenetv3"; let model_file: PathBuf = [export_dir, "saved_model.pb"].iter().collect(); if!model_file.exists() { return Err(Box::new( Status::new_set( Code::NotFound, &format!( "Run 'python examples/mobilenetv3/create_model.py' to generate \ {} and try again.", model_file.display() ), ) .unwrap(), )); } // Create input variables for our addition let mut x = Tensor::new(&[1, 224, 224, 3]); let img = ImageReader::open("examples/mobilenetv3/sample.png")?.decode()?; for (i, (_, _, pixel)) in img.pixels().enumerate() { x[3 * i] = pixel.0[0] as f32; x[3 * i + 1] = pixel.0[1] as f32; x[3 * i + 2] = pixel.0[2] as f32;
SavedModelBundle::load(&SessionOptions::new(), &["serve"], &mut graph, export_dir)?; let session = &bundle.session; // get in/out operations let signature = bundle .meta_graph_def() .get_signature(DEFAULT_SERVING_SIGNATURE_DEF_KEY)?; let x_info = signature.get_input("input_1")?; let op_x = &graph.operation_by_name_required(&x_info.name().name)?; let output_info = signature.get_output("Predictions")?; let op_output = &graph.operation_by_name_required(&output_info.name().name)?; // Run the graph. let mut args = SessionRunArgs::new(); args.add_feed(op_x, 0, &x); let token_output = args.request_fetch(op_output, 0); session.run(&mut args)?; // Check the output. let output: Tensor<f32> = args.fetch(token_output)?; // Calculate argmax of the output let (max_idx, _max_val) = output .iter() .enumerate() .fold((0, output[0]), |(idx_max, val_max), (idx, val)| { if &val_max > val { (idx_max, val_max) } else { (idx, *val) } }); // This index is expected to be identical with that of the Python code, // but this is not guaranteed due to floating operations. println!("argmax={}", max_idx); Ok(()) }
} // Load the saved model exported by zenn_savedmodel.py. let mut graph = Graph::new(); let bundle =
random_line_split
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use image::io::Reader as ImageReader; use image::GenericImageView; fn
() -> Result<(), Box<dyn Error>> { let export_dir = "examples/mobilenetv3"; let model_file: PathBuf = [export_dir, "saved_model.pb"].iter().collect(); if!model_file.exists() { return Err(Box::new( Status::new_set( Code::NotFound, &format!( "Run 'python examples/mobilenetv3/create_model.py' to generate \ {} and try again.", model_file.display() ), ) .unwrap(), )); } // Create input variables for our addition let mut x = Tensor::new(&[1, 224, 224, 3]); let img = ImageReader::open("examples/mobilenetv3/sample.png")?.decode()?; for (i, (_, _, pixel)) in img.pixels().enumerate() { x[3 * i] = pixel.0[0] as f32; x[3 * i + 1] = pixel.0[1] as f32; x[3 * i + 2] = pixel.0[2] as f32; } // Load the saved model exported by zenn_savedmodel.py. let mut graph = Graph::new(); let bundle = SavedModelBundle::load(&SessionOptions::new(), &["serve"], &mut graph, export_dir)?; let session = &bundle.session; // get in/out operations let signature = bundle .meta_graph_def() .get_signature(DEFAULT_SERVING_SIGNATURE_DEF_KEY)?; let x_info = signature.get_input("input_1")?; let op_x = &graph.operation_by_name_required(&x_info.name().name)?; let output_info = signature.get_output("Predictions")?; let op_output = &graph.operation_by_name_required(&output_info.name().name)?; // Run the graph. let mut args = SessionRunArgs::new(); args.add_feed(op_x, 0, &x); let token_output = args.request_fetch(op_output, 0); session.run(&mut args)?; // Check the output. let output: Tensor<f32> = args.fetch(token_output)?; // Calculate argmax of the output let (max_idx, _max_val) = output .iter() .enumerate() .fold((0, output[0]), |(idx_max, val_max), (idx, val)| { if &val_max > val { (idx_max, val_max) } else { (idx, *val) } }); // This index is expected to be identical with that of the Python code, // but this is not guaranteed due to floating operations. println!("argmax={}", max_idx); Ok(()) }
main
identifier_name
mobilenetv3.rs
use std::error::Error; use std::path::PathBuf; use std::result::Result; use tensorflow::Code; use tensorflow::Graph; use tensorflow::SavedModelBundle; use tensorflow::SessionOptions; use tensorflow::SessionRunArgs; use tensorflow::Status; use tensorflow::Tensor; use tensorflow::DEFAULT_SERVING_SIGNATURE_DEF_KEY; use image::io::Reader as ImageReader; use image::GenericImageView; fn main() -> Result<(), Box<dyn Error>>
for (i, (_, _, pixel)) in img.pixels().enumerate() { x[3 * i] = pixel.0[0] as f32; x[3 * i + 1] = pixel.0[1] as f32; x[3 * i + 2] = pixel.0[2] as f32; } // Load the saved model exported by zenn_savedmodel.py. let mut graph = Graph::new(); let bundle = SavedModelBundle::load(&SessionOptions::new(), &["serve"], &mut graph, export_dir)?; let session = &bundle.session; // get in/out operations let signature = bundle .meta_graph_def() .get_signature(DEFAULT_SERVING_SIGNATURE_DEF_KEY)?; let x_info = signature.get_input("input_1")?; let op_x = &graph.operation_by_name_required(&x_info.name().name)?; let output_info = signature.get_output("Predictions")?; let op_output = &graph.operation_by_name_required(&output_info.name().name)?; // Run the graph. let mut args = SessionRunArgs::new(); args.add_feed(op_x, 0, &x); let token_output = args.request_fetch(op_output, 0); session.run(&mut args)?; // Check the output. let output: Tensor<f32> = args.fetch(token_output)?; // Calculate argmax of the output let (max_idx, _max_val) = output .iter() .enumerate() .fold((0, output[0]), |(idx_max, val_max), (idx, val)| { if &val_max > val { (idx_max, val_max) } else { (idx, *val) } }); // This index is expected to be identical with that of the Python code, // but this is not guaranteed due to floating operations. println!("argmax={}", max_idx); Ok(()) }
{ let export_dir = "examples/mobilenetv3"; let model_file: PathBuf = [export_dir, "saved_model.pb"].iter().collect(); if !model_file.exists() { return Err(Box::new( Status::new_set( Code::NotFound, &format!( "Run 'python examples/mobilenetv3/create_model.py' to generate \ {} and try again.", model_file.display() ), ) .unwrap(), )); } // Create input variables for our addition let mut x = Tensor::new(&[1, 224, 224, 3]); let img = ImageReader::open("examples/mobilenetv3/sample.png")?.decode()?;
identifier_body
mod.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 values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn
(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, HeapSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
new
identifier_name
mod.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 values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool
/// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, HeapSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
{ self.is_root_element }
identifier_body
mod.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 values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else
if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, HeapSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
{ dest.write_str("auto, ")?; }
conditional_block
mod.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 values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber {
#[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, HeapSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
random_line_split
mod.rs
#[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unknown_lints)] #[allow(clippy::all)] mod grammar { // During the build step, `build.rs` will output the generated parser to `OUT_DIR` to avoid // adding it to the source directory, so we just directly include the generated parser here. // // Even with `.gitignore` and the `exclude` in the `Cargo.toml`, the generated parser can still // end up in the source directory. This could happen when `cargo build` builds the file out of // the Cargo cache (`$HOME/.cargo/registrysrc`), and the build script would then put its output // in that cached source directory because of https://github.com/lalrpop/lalrpop/issues/280. // Later runs of `cargo vendor` then copy the source from that directory, including the // generated file. include!(concat!(env!("OUT_DIR"), "/parser/grammar.rs")); } /// Contains all structures related to the AST for the WebIDL grammar. pub mod ast; /// Contains the visitor trait needed to traverse the AST and helper walk functions. pub mod visitor; pub use lalrpop_util::ParseError; use lexer::{LexicalError, Token}; /// The result that is returned when an input string is parsed. If the parse succeeds, the `Ok` /// result will be a vector of definitions representing the AST. If the parse fails, the `Err` will /// be either an error from the lexer or the parser. pub type ParseResult = Result<ast::AST, ParseError<usize, Token, LexicalError>>; /// Parses a given input string and returns an AST. /// /// # Example /// /// ``` /// use webidl::*; /// use webidl::ast::*; /// /// let result = parse_string("[Attribute] interface Node { };"); /// /// assert_eq!(result, /// Ok(vec![Definition::Interface(Interface::NonPartial(NonPartialInterface { /// extended_attributes: vec![ /// ExtendedAttribute::NoArguments( /// Other::Identifier("Attribute".to_string()))], /// inherits: None, /// members: vec![], /// name: "Node".to_string() /// }))])); /// ``` pub fn
(input: &str) -> ParseResult { grammar::DefinitionsParser::new().parse(::Lexer::new(input)) }
parse_string
identifier_name
mod.rs
#[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unknown_lints)] #[allow(clippy::all)] mod grammar { // During the build step, `build.rs` will output the generated parser to `OUT_DIR` to avoid // adding it to the source directory, so we just directly include the generated parser here. // // Even with `.gitignore` and the `exclude` in the `Cargo.toml`, the generated parser can still // end up in the source directory. This could happen when `cargo build` builds the file out of // the Cargo cache (`$HOME/.cargo/registrysrc`), and the build script would then put its output // in that cached source directory because of https://github.com/lalrpop/lalrpop/issues/280. // Later runs of `cargo vendor` then copy the source from that directory, including the // generated file. include!(concat!(env!("OUT_DIR"), "/parser/grammar.rs")); } /// Contains all structures related to the AST for the WebIDL grammar. pub mod ast; /// Contains the visitor trait needed to traverse the AST and helper walk functions. pub mod visitor; pub use lalrpop_util::ParseError; use lexer::{LexicalError, Token}; /// The result that is returned when an input string is parsed. If the parse succeeds, the `Ok` /// result will be a vector of definitions representing the AST. If the parse fails, the `Err` will /// be either an error from the lexer or the parser. pub type ParseResult = Result<ast::AST, ParseError<usize, Token, LexicalError>>; /// Parses a given input string and returns an AST. /// /// # Example /// /// ``` /// use webidl::*; /// use webidl::ast::*; /// /// let result = parse_string("[Attribute] interface Node { };"); /// /// assert_eq!(result, /// Ok(vec![Definition::Interface(Interface::NonPartial(NonPartialInterface { /// extended_attributes: vec![ /// ExtendedAttribute::NoArguments( /// Other::Identifier("Attribute".to_string()))], /// inherits: None, /// members: vec![], /// name: "Node".to_string() /// }))])); /// ``` pub fn parse_string(input: &str) -> ParseResult
{ grammar::DefinitionsParser::new().parse(::Lexer::new(input)) }
identifier_body
mod.rs
#[cfg_attr(rustfmt, rustfmt_skip)] #[allow(unknown_lints)] #[allow(clippy::all)] mod grammar { // During the build step, `build.rs` will output the generated parser to `OUT_DIR` to avoid // adding it to the source directory, so we just directly include the generated parser here. // // Even with `.gitignore` and the `exclude` in the `Cargo.toml`, the generated parser can still // end up in the source directory. This could happen when `cargo build` builds the file out of // the Cargo cache (`$HOME/.cargo/registrysrc`), and the build script would then put its output // in that cached source directory because of https://github.com/lalrpop/lalrpop/issues/280. // Later runs of `cargo vendor` then copy the source from that directory, including the // generated file. include!(concat!(env!("OUT_DIR"), "/parser/grammar.rs")); } /// Contains all structures related to the AST for the WebIDL grammar. pub mod ast; /// Contains the visitor trait needed to traverse the AST and helper walk functions. pub mod visitor; pub use lalrpop_util::ParseError; use lexer::{LexicalError, Token}; /// The result that is returned when an input string is parsed. If the parse succeeds, the `Ok` /// result will be a vector of definitions representing the AST. If the parse fails, the `Err` will /// be either an error from the lexer or the parser. pub type ParseResult = Result<ast::AST, ParseError<usize, Token, LexicalError>>; /// Parses a given input string and returns an AST. /// /// # Example /// /// ``` /// use webidl::*; /// use webidl::ast::*; /// /// let result = parse_string("[Attribute] interface Node { };"); /// /// assert_eq!(result, /// Ok(vec![Definition::Interface(Interface::NonPartial(NonPartialInterface { /// extended_attributes: vec![ /// ExtendedAttribute::NoArguments( /// Other::Identifier("Attribute".to_string()))], /// inherits: None, /// members: vec![],
pub fn parse_string(input: &str) -> ParseResult { grammar::DefinitionsParser::new().parse(::Lexer::new(input)) }
/// name: "Node".to_string() /// }))])); /// ```
random_line_split
specialization-translate-projections-with-params.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Ensure that provided items are inherited properly even when impls vary in // type parameters *and* rely on projections, and the type parameters are input // types on the trait. #![feature(specialization)] trait Trait<T> { fn convert(&self) -> T; } trait WithAssoc { type Item; fn as_item(&self) -> &Self::Item; } impl<T, U> Trait<U> for T where T: WithAssoc<Item=U>, U: Clone { fn convert(&self) -> U { self.as_item().clone() } } impl WithAssoc for u8 { type Item = u8; fn
(&self) -> &u8 { self } } impl Trait<u8> for u8 {} fn main() { assert!(3u8.convert() == 3u8); }
as_item
identifier_name
specialization-translate-projections-with-params.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Ensure that provided items are inherited properly even when impls vary in // type parameters *and* rely on projections, and the type parameters are input // types on the trait. #![feature(specialization)] trait Trait<T> { fn convert(&self) -> T; } trait WithAssoc { type Item; fn as_item(&self) -> &Self::Item; } impl<T, U> Trait<U> for T where T: WithAssoc<Item=U>, U: Clone { fn convert(&self) -> U { self.as_item().clone() } } impl WithAssoc for u8 { type Item = u8; fn as_item(&self) -> &u8 { self } } impl Trait<u8> for u8 {} fn main()
{ assert!(3u8.convert() == 3u8); }
identifier_body
specialization-translate-projections-with-params.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Ensure that provided items are inherited properly even when impls vary in // type parameters *and* rely on projections, and the type parameters are input // types on the trait. #![feature(specialization)] trait Trait<T> { fn convert(&self) -> T; } trait WithAssoc { type Item; fn as_item(&self) -> &Self::Item; } impl<T, U> Trait<U> for T where T: WithAssoc<Item=U>, U: Clone { fn convert(&self) -> U { self.as_item().clone() } } impl WithAssoc for u8 {
} impl Trait<u8> for u8 {} fn main() { assert!(3u8.convert() == 3u8); }
type Item = u8; fn as_item(&self) -> &u8 { self }
random_line_split
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! A box with a centered child // FIXME: add missing methods (3.12) use gtk::cast::{GTK_HEADER_BAR}; use gtk::{mod, ffi}; use std::string; /// GtkHeaderBar — A box with a centered child struct_Widget!(HeaderBar) impl HeaderBar { pub fn new() -> Option<HeaderBar> { let tmp_pointer = unsafe { ffi::gtk_header_bar_new() }; check_pointer!(tmp_pointer, HeaderBar) } pub fn set_title(&mut self, title: &str) { unsafe { title.with_c_str(|c_str| { ffi::gtk_header_bar_set_title(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_title(&self) -> Option<String> { let c_title = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_title.is_null() {
lse { Some(unsafe { string::raw::from_buf(c_title as *const u8) }) } } pub fn set_subtitle(&mut self, subtitle: &str) { unsafe { subtitle.with_c_str(|c_str| { ffi::gtk_header_bar_set_subtitle(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_subtitle(&self) -> Option<String> { let c_subtitle = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_subtitle.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_subtitle as *const u8) }) } } pub fn set_custom_title<T: gtk::WidgetTrait>(&mut self, title_widget: Option<&T>) { unsafe { ffi::gtk_header_bar_set_custom_title(GTK_HEADER_BAR(self.pointer), get_widget!(title_widget)) } } pub fn get_custom_title<T: gtk::WidgetTrait>(&self) -> Option<T> { let tmp_pointer = unsafe { ffi::gtk_header_bar_get_custom_title(GTK_HEADER_BAR(self.pointer)) }; if tmp_pointer.is_null() { None } else { Some(ffi::FFIWidget::wrap(tmp_pointer)) } } pub fn pack_start<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_start(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn pack_end<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_end(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn is_show_close_button(&self) -> bool { unsafe { ffi::to_bool(ffi::gtk_header_bar_get_show_close_button(GTK_HEADER_BAR(self.pointer))) } } pub fn set_show_close_button(&mut self, setting: bool) { unsafe { ffi::gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(self.pointer), ffi::to_gboolean(setting)) } } } impl_drop!(HeaderBar) impl_TraitWidget!(HeaderBar) impl gtk::ContainerTrait for HeaderBar {} impl_widget_events!(HeaderBar)
None } e
conditional_block
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! A box with a centered child // FIXME: add missing methods (3.12) use gtk::cast::{GTK_HEADER_BAR}; use gtk::{mod, ffi}; use std::string; /// GtkHeaderBar — A box with a centered child struct_Widget!(HeaderBar) impl HeaderBar { pub fn new() -> Option<HeaderBar> { let tmp_pointer = unsafe { ffi::gtk_header_bar_new() }; check_pointer!(tmp_pointer, HeaderBar) } pub fn set_title(&mut self, title: &str) { unsafe { title.with_c_str(|c_str| { ffi::gtk_header_bar_set_title(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_title(&self) -> Option<String> { let c_title = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_title.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_title as *const u8) }) } } pub fn set_subtitle(&mut self, subtitle: &str) { unsafe { subtitle.with_c_str(|c_str| { ffi::gtk_header_bar_set_subtitle(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_subtitle(&self) -> Option<String> { let c_subtitle = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_subtitle.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_subtitle as *const u8) }) } } pub fn set_custom_title<T: gtk::WidgetTrait>(&mut self, title_widget: Option<&T>) { unsafe { ffi::gtk_header_bar_set_custom_title(GTK_HEADER_BAR(self.pointer), get_widget!(title_widget)) } } pub fn get_custom_title<T: gtk::WidgetTrait>(&self) -> Option<T> { let tmp_pointer = unsafe { ffi::gtk_header_bar_get_custom_title(GTK_HEADER_BAR(self.pointer)) }; if tmp_pointer.is_null() { None } else { Some(ffi::FFIWidget::wrap(tmp_pointer)) } } pub fn pack_start<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_start(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn pack_end<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_end(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn is_show_close_button(&self) -> bool { unsafe { ffi::to_bool(ffi::gtk_header_bar_get_show_close_button(GTK_HEADER_BAR(self.pointer))) } }
ffi::gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(self.pointer), ffi::to_gboolean(setting)) } } } impl_drop!(HeaderBar) impl_TraitWidget!(HeaderBar) impl gtk::ContainerTrait for HeaderBar {} impl_widget_events!(HeaderBar)
pub fn set_show_close_button(&mut self, setting: bool) { unsafe {
random_line_split
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! A box with a centered child // FIXME: add missing methods (3.12) use gtk::cast::{GTK_HEADER_BAR}; use gtk::{mod, ffi}; use std::string; /// GtkHeaderBar — A box with a centered child struct_Widget!(HeaderBar) impl HeaderBar { pub fn new() -> Option<HeaderBar> { let tmp_pointer = unsafe { ffi::gtk_header_bar_new() }; check_pointer!(tmp_pointer, HeaderBar) } pub fn set_title(&mut self, title: &str) { unsafe { title.with_c_str(|c_str| { ffi::gtk_header_bar_set_title(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_title(&self) -> Option<String> { let c_title = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_title.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_title as *const u8) }) } } pub fn set_subtitle(&mut self, subtitle: &str) { unsafe { subtitle.with_c_str(|c_str| { ffi::gtk_header_bar_set_subtitle(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_subtitle(&self) -> Option<String> { let c_subtitle = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_subtitle.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_subtitle as *const u8) }) } } pub fn set_custom_title<T: gtk::WidgetTrait>(&mut self, title_widget: Option<&T>) { unsafe { ffi::gtk_header_bar_set_custom_title(GTK_HEADER_BAR(self.pointer), get_widget!(title_widget)) } } pub fn get_custom_title<T: gtk::WidgetTrait>(&self) -> Option<T> { let tmp_pointer = unsafe { ffi::gtk_header_bar_get_custom_title(GTK_HEADER_BAR(self.pointer)) }; if tmp_pointer.is_null() { None } else { Some(ffi::FFIWidget::wrap(tmp_pointer)) } } pub fn pack_start<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_start(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn pack_end<T: gtk::WidgetTrait>(&mut self, child: &T) {
pub fn is_show_close_button(&self) -> bool { unsafe { ffi::to_bool(ffi::gtk_header_bar_get_show_close_button(GTK_HEADER_BAR(self.pointer))) } } pub fn set_show_close_button(&mut self, setting: bool) { unsafe { ffi::gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(self.pointer), ffi::to_gboolean(setting)) } } } impl_drop!(HeaderBar) impl_TraitWidget!(HeaderBar) impl gtk::ContainerTrait for HeaderBar {} impl_widget_events!(HeaderBar)
unsafe { ffi::gtk_header_bar_pack_end(GTK_HEADER_BAR(self.pointer), child.get_widget()) } }
identifier_body
header_bar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! A box with a centered child // FIXME: add missing methods (3.12) use gtk::cast::{GTK_HEADER_BAR}; use gtk::{mod, ffi}; use std::string; /// GtkHeaderBar — A box with a centered child struct_Widget!(HeaderBar) impl HeaderBar { pub fn new() -> Option<HeaderBar> { let tmp_pointer = unsafe { ffi::gtk_header_bar_new() }; check_pointer!(tmp_pointer, HeaderBar) } pub fn se
mut self, title: &str) { unsafe { title.with_c_str(|c_str| { ffi::gtk_header_bar_set_title(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_title(&self) -> Option<String> { let c_title = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_title.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_title as *const u8) }) } } pub fn set_subtitle(&mut self, subtitle: &str) { unsafe { subtitle.with_c_str(|c_str| { ffi::gtk_header_bar_set_subtitle(GTK_HEADER_BAR(self.pointer), c_str) }) } } pub fn get_subtitle(&self) -> Option<String> { let c_subtitle = unsafe { ffi::gtk_header_bar_get_title(GTK_HEADER_BAR(self.pointer)) }; if c_subtitle.is_null() { None } else { Some(unsafe { string::raw::from_buf(c_subtitle as *const u8) }) } } pub fn set_custom_title<T: gtk::WidgetTrait>(&mut self, title_widget: Option<&T>) { unsafe { ffi::gtk_header_bar_set_custom_title(GTK_HEADER_BAR(self.pointer), get_widget!(title_widget)) } } pub fn get_custom_title<T: gtk::WidgetTrait>(&self) -> Option<T> { let tmp_pointer = unsafe { ffi::gtk_header_bar_get_custom_title(GTK_HEADER_BAR(self.pointer)) }; if tmp_pointer.is_null() { None } else { Some(ffi::FFIWidget::wrap(tmp_pointer)) } } pub fn pack_start<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_start(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn pack_end<T: gtk::WidgetTrait>(&mut self, child: &T) { unsafe { ffi::gtk_header_bar_pack_end(GTK_HEADER_BAR(self.pointer), child.get_widget()) } } pub fn is_show_close_button(&self) -> bool { unsafe { ffi::to_bool(ffi::gtk_header_bar_get_show_close_button(GTK_HEADER_BAR(self.pointer))) } } pub fn set_show_close_button(&mut self, setting: bool) { unsafe { ffi::gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(self.pointer), ffi::to_gboolean(setting)) } } } impl_drop!(HeaderBar) impl_TraitWidget!(HeaderBar) impl gtk::ContainerTrait for HeaderBar {} impl_widget_events!(HeaderBar)
t_title(&
identifier_name
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialState}, range::{range, recognize, take}, }, skip_many, skip_many1, stream::{easy, PartialStream, RangeStream, StreamErrorFor}, Parser, }, futures::prelude::*, partial_io::PartialOp, tokio_util::codec::{Decoder, FramedRead}, }; // Workaround partial_io not working with tokio-0.2 #[path = "../tests/support/mod.rs"] mod support; use support::*; pub struct LanguageServerDecoder { state: AnyPartialState, content_length_parses: Rc<Cell<i32>>, } impl Default for LanguageServerDecoder { fn default() -> Self { LanguageServerDecoder { state: Default::default(), content_length_parses: Rc::new(Cell::new(0)), } } } /// Parses blocks of data with length headers /// /// ``` /// Content-Length: 18 /// /// { "some": "data" } /// ``` // The `content_length_parses` parameter only exists to demonstrate that `content_length` only // gets parsed once per message fn decode_parser<'a, Input>( content_length_parses: Rc<Cell<i32>>, ) -> impl Parser<Input, Output = Vec<u8>, PartialState = AnyPartialState> + 'a where Input: RangeStream<Token = u8, Range = &'a [u8]> + 'a, // Necessary due to rust-lang/rust#24159 Input::Error: ParseError<Input::Token, Input::Range, Input::Position>, { let content_length = range(&b"Content-Length: "[..]) .with(recognize(skip_many1(digit())).and_then(|digits: &[u8]| { str::from_utf8(digits) .unwrap() .parse::<usize>() // Convert the error from `.parse` into an error combine understands .map_err(StreamErrorFor::<Input>::other) })) .map(move |x| { content_length_parses.set(content_length_parses.get() + 1); x }); // `any_partial_state` boxes the state which hides the type and lets us store it in // `self` any_partial_state( ( skip_many(range(&b"\r\n"[..])), content_length, range(&b"\r\n\r\n"[..]).map(|_| ()), ) .then_partial(|&mut (_, message_length, _)| { take(message_length).map(|bytes: &[u8]| bytes.to_owned()) }), ) } impl Decoder for LanguageServerDecoder { type Item = String; type Error = Box<dyn std::error::Error + Send + Sync>; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { println!("Decoding `{:?}`", str::from_utf8(src).unwrap_or("NOT UTF8")); let (opt, removed_len) = combine::stream::decode( decode_parser(self.content_length_parses.clone()), // easy::Stream gives us nice error messages // (the same error messages that combine has had since its inception) // PartialStream lets the parser know that more input should be // expected if end of input is unexpectedly reached &mut easy::Stream(PartialStream(&src[..])), &mut self.state, ) .map_err(|err| { // Since err contains references into `src` we must replace these before // we can return an error or call `advance` to remove the input we // just committed let err = err .map_range(|r| { str::from_utf8(r) .ok() .map_or_else(|| format!("{:?}", r), |s| s.to_string()) }) .map_position(|p| p.translate_position(&src[..])); format!("{}\nIn input: `{}`", err, str::from_utf8(src).unwrap()) })?; println!( "Accepted {} bytes: `{:?}`", removed_len, str::from_utf8(&src[..removed_len]).unwrap_or("NOT UTF8") ); // Remove the input we just committed. // Ideally this would be done automatically by the call to // `stream::decode` but it does unfortunately not work due // to lifetime issues (Non lexical lifetimes might fix it!) src.advance(removed_len); match opt { // `None` means we did not have enough input and we require that the // caller of `decode` supply more before calling us again None =>
// `Some` means that a message was successfully decoded // (and that we are ready to start decoding the next message) Some(output) => { let value = String::from_utf8(output)?; println!("Decoded `{}`", value); Ok(Some(value)) } } } } #[tokio::main] async fn main() { let input = "Content-Length: 6\r\n\ \r\n\ 123456\r\n\ Content-Length: 4\r\n\ \r\n\ true"; let seq = vec![ PartialOp::Limited(20), PartialOp::Limited(1), PartialOp::Limited(2), PartialOp::Limited(3), ]; let reader = &mut Cursor::new(input.as_bytes()); // Using the `partial_io` crate we emulate the partial reads that would happen when reading // asynchronously from an io device. let partial_reader = PartialAsyncRead::new(reader, seq); let decoder = LanguageServerDecoder::default(); let content_length_parses = decoder.content_length_parses.clone(); let result = FramedRead::new(partial_reader, decoder).try_collect().await; assert!(result.as_ref().is_ok(), "{}", result.unwrap_err()); let values: Vec<_> = result.unwrap(); let expected_values = ["123456", "true"]; assert_eq!(values, expected_values); assert_eq!(content_length_parses.get(), expected_values.len() as i32); println!("Successfully parsed: `{}`", input); println!( "Found {} items and never repeated a completed parse!", values.len(), ); println!("Result: {:?}", values); }
{ println!("Requesting more input!"); Ok(None) }
conditional_block
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialState}, range::{range, recognize, take}, }, skip_many, skip_many1, stream::{easy, PartialStream, RangeStream, StreamErrorFor}, Parser, }, futures::prelude::*, partial_io::PartialOp, tokio_util::codec::{Decoder, FramedRead}, }; // Workaround partial_io not working with tokio-0.2 #[path = "../tests/support/mod.rs"] mod support; use support::*; pub struct LanguageServerDecoder { state: AnyPartialState, content_length_parses: Rc<Cell<i32>>, } impl Default for LanguageServerDecoder { fn default() -> Self { LanguageServerDecoder { state: Default::default(), content_length_parses: Rc::new(Cell::new(0)), } } } /// Parses blocks of data with length headers /// /// ``` /// Content-Length: 18 /// /// { "some": "data" } /// ``` // The `content_length_parses` parameter only exists to demonstrate that `content_length` only // gets parsed once per message fn decode_parser<'a, Input>( content_length_parses: Rc<Cell<i32>>, ) -> impl Parser<Input, Output = Vec<u8>, PartialState = AnyPartialState> + 'a where Input: RangeStream<Token = u8, Range = &'a [u8]> + 'a, // Necessary due to rust-lang/rust#24159 Input::Error: ParseError<Input::Token, Input::Range, Input::Position>, { let content_length = range(&b"Content-Length: "[..]) .with(recognize(skip_many1(digit())).and_then(|digits: &[u8]| { str::from_utf8(digits) .unwrap() .parse::<usize>() // Convert the error from `.parse` into an error combine understands .map_err(StreamErrorFor::<Input>::other) })) .map(move |x| { content_length_parses.set(content_length_parses.get() + 1); x }); // `any_partial_state` boxes the state which hides the type and lets us store it in // `self` any_partial_state( ( skip_many(range(&b"\r\n"[..])), content_length, range(&b"\r\n\r\n"[..]).map(|_| ()), ) .then_partial(|&mut (_, message_length, _)| { take(message_length).map(|bytes: &[u8]| bytes.to_owned()) }), ) } impl Decoder for LanguageServerDecoder { type Item = String; type Error = Box<dyn std::error::Error + Send + Sync>; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { println!("Decoding `{:?}`", str::from_utf8(src).unwrap_or("NOT UTF8")); let (opt, removed_len) = combine::stream::decode( decode_parser(self.content_length_parses.clone()), // easy::Stream gives us nice error messages // (the same error messages that combine has had since its inception) // PartialStream lets the parser know that more input should be // expected if end of input is unexpectedly reached &mut easy::Stream(PartialStream(&src[..])), &mut self.state, ) .map_err(|err| { // Since err contains references into `src` we must replace these before // we can return an error or call `advance` to remove the input we // just committed let err = err .map_range(|r| { str::from_utf8(r) .ok() .map_or_else(|| format!("{:?}", r), |s| s.to_string()) }) .map_position(|p| p.translate_position(&src[..])); format!("{}\nIn input: `{}`", err, str::from_utf8(src).unwrap()) })?; println!( "Accepted {} bytes: `{:?}`", removed_len, str::from_utf8(&src[..removed_len]).unwrap_or("NOT UTF8") );
// Ideally this would be done automatically by the call to // `stream::decode` but it does unfortunately not work due // to lifetime issues (Non lexical lifetimes might fix it!) src.advance(removed_len); match opt { // `None` means we did not have enough input and we require that the // caller of `decode` supply more before calling us again None => { println!("Requesting more input!"); Ok(None) } // `Some` means that a message was successfully decoded // (and that we are ready to start decoding the next message) Some(output) => { let value = String::from_utf8(output)?; println!("Decoded `{}`", value); Ok(Some(value)) } } } } #[tokio::main] async fn main() { let input = "Content-Length: 6\r\n\ \r\n\ 123456\r\n\ Content-Length: 4\r\n\ \r\n\ true"; let seq = vec![ PartialOp::Limited(20), PartialOp::Limited(1), PartialOp::Limited(2), PartialOp::Limited(3), ]; let reader = &mut Cursor::new(input.as_bytes()); // Using the `partial_io` crate we emulate the partial reads that would happen when reading // asynchronously from an io device. let partial_reader = PartialAsyncRead::new(reader, seq); let decoder = LanguageServerDecoder::default(); let content_length_parses = decoder.content_length_parses.clone(); let result = FramedRead::new(partial_reader, decoder).try_collect().await; assert!(result.as_ref().is_ok(), "{}", result.unwrap_err()); let values: Vec<_> = result.unwrap(); let expected_values = ["123456", "true"]; assert_eq!(values, expected_values); assert_eq!(content_length_parses.get(), expected_values.len() as i32); println!("Successfully parsed: `{}`", input); println!( "Found {} items and never repeated a completed parse!", values.len(), ); println!("Result: {:?}", values); }
// Remove the input we just committed.
random_line_split
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialState}, range::{range, recognize, take}, }, skip_many, skip_many1, stream::{easy, PartialStream, RangeStream, StreamErrorFor}, Parser, }, futures::prelude::*, partial_io::PartialOp, tokio_util::codec::{Decoder, FramedRead}, }; // Workaround partial_io not working with tokio-0.2 #[path = "../tests/support/mod.rs"] mod support; use support::*; pub struct LanguageServerDecoder { state: AnyPartialState, content_length_parses: Rc<Cell<i32>>, } impl Default for LanguageServerDecoder { fn default() -> Self
} /// Parses blocks of data with length headers /// /// ``` /// Content-Length: 18 /// /// { "some": "data" } /// ``` // The `content_length_parses` parameter only exists to demonstrate that `content_length` only // gets parsed once per message fn decode_parser<'a, Input>( content_length_parses: Rc<Cell<i32>>, ) -> impl Parser<Input, Output = Vec<u8>, PartialState = AnyPartialState> + 'a where Input: RangeStream<Token = u8, Range = &'a [u8]> + 'a, // Necessary due to rust-lang/rust#24159 Input::Error: ParseError<Input::Token, Input::Range, Input::Position>, { let content_length = range(&b"Content-Length: "[..]) .with(recognize(skip_many1(digit())).and_then(|digits: &[u8]| { str::from_utf8(digits) .unwrap() .parse::<usize>() // Convert the error from `.parse` into an error combine understands .map_err(StreamErrorFor::<Input>::other) })) .map(move |x| { content_length_parses.set(content_length_parses.get() + 1); x }); // `any_partial_state` boxes the state which hides the type and lets us store it in // `self` any_partial_state( ( skip_many(range(&b"\r\n"[..])), content_length, range(&b"\r\n\r\n"[..]).map(|_| ()), ) .then_partial(|&mut (_, message_length, _)| { take(message_length).map(|bytes: &[u8]| bytes.to_owned()) }), ) } impl Decoder for LanguageServerDecoder { type Item = String; type Error = Box<dyn std::error::Error + Send + Sync>; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { println!("Decoding `{:?}`", str::from_utf8(src).unwrap_or("NOT UTF8")); let (opt, removed_len) = combine::stream::decode( decode_parser(self.content_length_parses.clone()), // easy::Stream gives us nice error messages // (the same error messages that combine has had since its inception) // PartialStream lets the parser know that more input should be // expected if end of input is unexpectedly reached &mut easy::Stream(PartialStream(&src[..])), &mut self.state, ) .map_err(|err| { // Since err contains references into `src` we must replace these before // we can return an error or call `advance` to remove the input we // just committed let err = err .map_range(|r| { str::from_utf8(r) .ok() .map_or_else(|| format!("{:?}", r), |s| s.to_string()) }) .map_position(|p| p.translate_position(&src[..])); format!("{}\nIn input: `{}`", err, str::from_utf8(src).unwrap()) })?; println!( "Accepted {} bytes: `{:?}`", removed_len, str::from_utf8(&src[..removed_len]).unwrap_or("NOT UTF8") ); // Remove the input we just committed. // Ideally this would be done automatically by the call to // `stream::decode` but it does unfortunately not work due // to lifetime issues (Non lexical lifetimes might fix it!) src.advance(removed_len); match opt { // `None` means we did not have enough input and we require that the // caller of `decode` supply more before calling us again None => { println!("Requesting more input!"); Ok(None) } // `Some` means that a message was successfully decoded // (and that we are ready to start decoding the next message) Some(output) => { let value = String::from_utf8(output)?; println!("Decoded `{}`", value); Ok(Some(value)) } } } } #[tokio::main] async fn main() { let input = "Content-Length: 6\r\n\ \r\n\ 123456\r\n\ Content-Length: 4\r\n\ \r\n\ true"; let seq = vec![ PartialOp::Limited(20), PartialOp::Limited(1), PartialOp::Limited(2), PartialOp::Limited(3), ]; let reader = &mut Cursor::new(input.as_bytes()); // Using the `partial_io` crate we emulate the partial reads that would happen when reading // asynchronously from an io device. let partial_reader = PartialAsyncRead::new(reader, seq); let decoder = LanguageServerDecoder::default(); let content_length_parses = decoder.content_length_parses.clone(); let result = FramedRead::new(partial_reader, decoder).try_collect().await; assert!(result.as_ref().is_ok(), "{}", result.unwrap_err()); let values: Vec<_> = result.unwrap(); let expected_values = ["123456", "true"]; assert_eq!(values, expected_values); assert_eq!(content_length_parses.get(), expected_values.len() as i32); println!("Successfully parsed: `{}`", input); println!( "Found {} items and never repeated a completed parse!", values.len(), ); println!("Result: {:?}", values); }
{ LanguageServerDecoder { state: Default::default(), content_length_parses: Rc::new(Cell::new(0)), } }
identifier_body
async.rs
#![cfg(feature = "std")] use std::{cell::Cell, io::Cursor, rc::Rc, str}; use {futures_03_dep as futures, tokio_dep as tokio}; use { bytes::{Buf, BytesMut}, combine::{ error::{ParseError, StreamError}, parser::{ byte::digit, combinator::{any_partial_state, AnyPartialState}, range::{range, recognize, take}, }, skip_many, skip_many1, stream::{easy, PartialStream, RangeStream, StreamErrorFor}, Parser, }, futures::prelude::*, partial_io::PartialOp, tokio_util::codec::{Decoder, FramedRead}, }; // Workaround partial_io not working with tokio-0.2 #[path = "../tests/support/mod.rs"] mod support; use support::*; pub struct
{ state: AnyPartialState, content_length_parses: Rc<Cell<i32>>, } impl Default for LanguageServerDecoder { fn default() -> Self { LanguageServerDecoder { state: Default::default(), content_length_parses: Rc::new(Cell::new(0)), } } } /// Parses blocks of data with length headers /// /// ``` /// Content-Length: 18 /// /// { "some": "data" } /// ``` // The `content_length_parses` parameter only exists to demonstrate that `content_length` only // gets parsed once per message fn decode_parser<'a, Input>( content_length_parses: Rc<Cell<i32>>, ) -> impl Parser<Input, Output = Vec<u8>, PartialState = AnyPartialState> + 'a where Input: RangeStream<Token = u8, Range = &'a [u8]> + 'a, // Necessary due to rust-lang/rust#24159 Input::Error: ParseError<Input::Token, Input::Range, Input::Position>, { let content_length = range(&b"Content-Length: "[..]) .with(recognize(skip_many1(digit())).and_then(|digits: &[u8]| { str::from_utf8(digits) .unwrap() .parse::<usize>() // Convert the error from `.parse` into an error combine understands .map_err(StreamErrorFor::<Input>::other) })) .map(move |x| { content_length_parses.set(content_length_parses.get() + 1); x }); // `any_partial_state` boxes the state which hides the type and lets us store it in // `self` any_partial_state( ( skip_many(range(&b"\r\n"[..])), content_length, range(&b"\r\n\r\n"[..]).map(|_| ()), ) .then_partial(|&mut (_, message_length, _)| { take(message_length).map(|bytes: &[u8]| bytes.to_owned()) }), ) } impl Decoder for LanguageServerDecoder { type Item = String; type Error = Box<dyn std::error::Error + Send + Sync>; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { println!("Decoding `{:?}`", str::from_utf8(src).unwrap_or("NOT UTF8")); let (opt, removed_len) = combine::stream::decode( decode_parser(self.content_length_parses.clone()), // easy::Stream gives us nice error messages // (the same error messages that combine has had since its inception) // PartialStream lets the parser know that more input should be // expected if end of input is unexpectedly reached &mut easy::Stream(PartialStream(&src[..])), &mut self.state, ) .map_err(|err| { // Since err contains references into `src` we must replace these before // we can return an error or call `advance` to remove the input we // just committed let err = err .map_range(|r| { str::from_utf8(r) .ok() .map_or_else(|| format!("{:?}", r), |s| s.to_string()) }) .map_position(|p| p.translate_position(&src[..])); format!("{}\nIn input: `{}`", err, str::from_utf8(src).unwrap()) })?; println!( "Accepted {} bytes: `{:?}`", removed_len, str::from_utf8(&src[..removed_len]).unwrap_or("NOT UTF8") ); // Remove the input we just committed. // Ideally this would be done automatically by the call to // `stream::decode` but it does unfortunately not work due // to lifetime issues (Non lexical lifetimes might fix it!) src.advance(removed_len); match opt { // `None` means we did not have enough input and we require that the // caller of `decode` supply more before calling us again None => { println!("Requesting more input!"); Ok(None) } // `Some` means that a message was successfully decoded // (and that we are ready to start decoding the next message) Some(output) => { let value = String::from_utf8(output)?; println!("Decoded `{}`", value); Ok(Some(value)) } } } } #[tokio::main] async fn main() { let input = "Content-Length: 6\r\n\ \r\n\ 123456\r\n\ Content-Length: 4\r\n\ \r\n\ true"; let seq = vec![ PartialOp::Limited(20), PartialOp::Limited(1), PartialOp::Limited(2), PartialOp::Limited(3), ]; let reader = &mut Cursor::new(input.as_bytes()); // Using the `partial_io` crate we emulate the partial reads that would happen when reading // asynchronously from an io device. let partial_reader = PartialAsyncRead::new(reader, seq); let decoder = LanguageServerDecoder::default(); let content_length_parses = decoder.content_length_parses.clone(); let result = FramedRead::new(partial_reader, decoder).try_collect().await; assert!(result.as_ref().is_ok(), "{}", result.unwrap_err()); let values: Vec<_> = result.unwrap(); let expected_values = ["123456", "true"]; assert_eq!(values, expected_values); assert_eq!(content_length_parses.get(), expected_values.len() as i32); println!("Successfully parsed: `{}`", input); println!( "Found {} items and never repeated a completed parse!", values.len(), ); println!("Result: {:?}", values); }
LanguageServerDecoder
identifier_name
vec-must-not-hide-type-from-dropck.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Checking that `Vec<T>` cannot hide lifetimes within `T` when `T` // implements `Drop` and might access methods of values that have // since been deallocated. // // In this case, the values in question hold (non-zero) unique-ids // that zero themselves out when dropped, and are wrapped in another // type with a destructor that asserts that the ids it references are // indeed non-zero (i.e., effectively checking that the id's are not // dropped while there are still any outstanding references). // // However, the values in question are also formed into a // cyclic-structure, ensuring that there is no way for all of the // conditions above to be satisfied, meaning that if the dropck is // sound, it should reject this code. #![feature(unsafe_destructor)] use std::cell::Cell; use id::Id; mod s { #![allow(unstable)] use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering}; static S_COUNT: AtomicUint = ATOMIC_UINT_INIT; /// generates globally unique count (global across the current /// process, that is) pub fn next_count() -> usize { S_COUNT.fetch_add(1, Ordering::SeqCst) + 1 } } mod id { use s; /// Id represents a globally unique identifier (global across the /// current process, that is). When dropped, it automatically /// clears its `count` field, but leaves `orig_count` untouched, /// so that if there are subsequent (erroneous) invocations of its /// method (which is unsound), we can observe it by seeing that /// the `count` is 0 while the `orig_count` is non-zero. #[derive(Debug)] pub struct Id { orig_count: usize, count: usize, } impl Id { /// Creates an `Id` with a globally unique count. pub fn new() -> Id { let c = s::next_count(); println!("building Id {}", c); Id { orig_count: c, count: c } } /// returns the `count` of self; should be non-zero if /// everything is working. pub fn count(&self) -> usize { println!("Id::count on {} returns {}", self.orig_count, self.count); self.count } } impl Drop for Id { fn drop(&mut self) { println!("dropping Id {}", self.count); self.count = 0; } } } trait HasId { fn count(&self) -> usize; } #[derive(Debug)] struct CheckId<T:HasId> { v: T } #[allow(non_snake_case)] fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } }
} } #[derive(Debug)] struct C<'a> { id: Id, v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>, } impl<'a> HasId for Cell<Option<&'a C<'a>>> { fn count(&self) -> usize { match self.get() { None => 1, Some(c) => c.id.count(), } } } impl<'a> C<'a> { fn new() -> C<'a> { C { id: Id::new(), v: Vec::new() } } } fn f() { let (mut c1, mut c2); c1 = C::new(); c2 = C::new(); c1.v.push(CheckId(Cell::new(None))); c2.v.push(CheckId(Cell::new(None))); c1.v[0].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough c2.v[0].v.set(Some(&c1)); //~ ERROR `c1` does not live long enough } fn main() { f(); }
#[unsafe_destructor] impl<T:HasId> Drop for CheckId<T> { fn drop(&mut self) { assert!(self.v.count() > 0);
random_line_split
vec-must-not-hide-type-from-dropck.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Checking that `Vec<T>` cannot hide lifetimes within `T` when `T` // implements `Drop` and might access methods of values that have // since been deallocated. // // In this case, the values in question hold (non-zero) unique-ids // that zero themselves out when dropped, and are wrapped in another // type with a destructor that asserts that the ids it references are // indeed non-zero (i.e., effectively checking that the id's are not // dropped while there are still any outstanding references). // // However, the values in question are also formed into a // cyclic-structure, ensuring that there is no way for all of the // conditions above to be satisfied, meaning that if the dropck is // sound, it should reject this code. #![feature(unsafe_destructor)] use std::cell::Cell; use id::Id; mod s { #![allow(unstable)] use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering}; static S_COUNT: AtomicUint = ATOMIC_UINT_INIT; /// generates globally unique count (global across the current /// process, that is) pub fn next_count() -> usize { S_COUNT.fetch_add(1, Ordering::SeqCst) + 1 } } mod id { use s; /// Id represents a globally unique identifier (global across the /// current process, that is). When dropped, it automatically /// clears its `count` field, but leaves `orig_count` untouched, /// so that if there are subsequent (erroneous) invocations of its /// method (which is unsound), we can observe it by seeing that /// the `count` is 0 while the `orig_count` is non-zero. #[derive(Debug)] pub struct Id { orig_count: usize, count: usize, } impl Id { /// Creates an `Id` with a globally unique count. pub fn new() -> Id { let c = s::next_count(); println!("building Id {}", c); Id { orig_count: c, count: c } } /// returns the `count` of self; should be non-zero if /// everything is working. pub fn count(&self) -> usize { println!("Id::count on {} returns {}", self.orig_count, self.count); self.count } } impl Drop for Id { fn drop(&mut self) { println!("dropping Id {}", self.count); self.count = 0; } } } trait HasId { fn count(&self) -> usize; } #[derive(Debug)] struct CheckId<T:HasId> { v: T } #[allow(non_snake_case)] fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } } #[unsafe_destructor] impl<T:HasId> Drop for CheckId<T> { fn drop(&mut self) { assert!(self.v.count() > 0); } } #[derive(Debug)] struct C<'a> { id: Id, v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>, } impl<'a> HasId for Cell<Option<&'a C<'a>>> { fn
(&self) -> usize { match self.get() { None => 1, Some(c) => c.id.count(), } } } impl<'a> C<'a> { fn new() -> C<'a> { C { id: Id::new(), v: Vec::new() } } } fn f() { let (mut c1, mut c2); c1 = C::new(); c2 = C::new(); c1.v.push(CheckId(Cell::new(None))); c2.v.push(CheckId(Cell::new(None))); c1.v[0].v.set(Some(&c2)); //~ ERROR `c2` does not live long enough c2.v[0].v.set(Some(&c1)); //~ ERROR `c1` does not live long enough } fn main() { f(); }
count
identifier_name
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value); /// Key type. /// /// Keys have 2 types of binary representation - raw and encoded. The raw /// representation is for public interface, the encoded representation is for /// internal storage. We can get both representations from an instance of this /// type. /// /// Orthogonal to binary representation, keys may or may not embed a timestamp, /// but this information is transparent to this type, the caller must use it /// consistently. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Key(Vec<u8>); /// Core functions for `Key`. impl Key { /// Creates a key from raw bytes. #[inline] pub fn from_raw(key: &[u8]) -> Key { // adding extra length for appending timestamp let len = codec::bytes::max_encoded_bytes_size(key.len()) + codec::number::U64_SIZE; let mut encoded = Vec::with_capacity(len); encoded.encode_bytes(key, false).unwrap(); Key(encoded) } /// Creates a key from raw bytes but returns None if the key is an empty slice. #[inline] pub fn from_raw_maybe_unbounded(key: &[u8]) -> Option<Key> { if key.is_empty() { None } else { Some(Key::from_raw(key)) } } /// Gets and moves the raw representation of this key. #[inline] pub fn into_raw(self) -> Result<Vec<u8>, codec::Error> { let mut k = self.0; bytes::decode_bytes_in_place(&mut k, false)?; Ok(k) } /// Gets the raw representation of this key. #[inline] pub fn to_raw(&self) -> Result<Vec<u8>, codec::Error> { bytes::decode_bytes(&mut self.0.as_slice(), false) } /// Creates a key from encoded bytes vector. #[inline] pub fn from_encoded(encoded_key: Vec<u8>) -> Key { Key(encoded_key) } /// Creates a key with reserved capacity for timestamp from encoded bytes slice. #[inline] pub fn from_encoded_slice(encoded_key: &[u8]) -> Key { let mut k = Vec::with_capacity(encoded_key.len() + number::U64_SIZE); k.extend_from_slice(encoded_key); Key(k) } /// Gets the encoded representation of this key. #[inline] pub fn as_encoded(&self) -> &Vec<u8> { &self.0 } /// Gets and moves the encoded representation of this key. #[inline] pub fn into_encoded(self) -> Vec<u8> { self.0 } /// Creates a new key by appending a `u64` timestamp to this key. #[inline] pub fn append_ts(mut self, ts: TimeStamp) -> Key { self.0.encode_u64_desc(ts.into_inner()).unwrap(); self } /// Gets the timestamp contained in this key. /// /// Preconditions: the caller must ensure this is actually a timestamped /// key. #[inline] pub fn decode_ts(&self) -> Result<TimeStamp, codec::Error> { Self::decode_ts_from(&self.0) } /// Creates a new key by truncating the timestamp from this key. /// /// Preconditions: the caller must ensure this is actually a timestamped key. #[inline] pub fn truncate_ts(mut self) -> Result<Key, codec::Error> { let len = self.0.len(); if len < number::U64_SIZE { // TODO: IMHO, this should be an assertion failure instead of // returning an error. If this happens, it indicates a bug in // the caller module, have to make code change to fix it. // // Even if it passed the length check, it still could be buggy, // a better way is to introduce a type `TimestampedKey`, and // functions to convert between `TimestampedKey` and `Key`. // `TimestampedKey` is in a higher (MVCC) layer, while `Key` is // in the core storage engine layer. Err(codec::Error::KeyLength) } else { self.0.truncate(len - number::U64_SIZE); Ok(self) } } /// Split a ts encoded key, return the user key and timestamp. #[inline] pub fn split_on_ts_for(key: &[u8]) -> Result<(&[u8], TimeStamp), codec::Error> { if key.len() < number::U64_SIZE { Err(codec::Error::KeyLength) } else { let pos = key.len() - number::U64_SIZE; let k = &key[..pos]; let mut ts = &key[pos..]; Ok((k, number::decode_u64_desc(&mut ts)?.into())) } } /// Extract the user key from a ts encoded key. #[inline] pub fn truncate_ts_for(key: &[u8]) -> Result<&[u8], codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } Ok(&key[..key.len() - number::U64_SIZE]) } /// Decode the timestamp from a ts encoded key. #[inline] pub fn decode_ts_from(key: &[u8]) -> Result<TimeStamp, codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } let mut ts = &key[len - number::U64_SIZE..]; Ok(number::decode_u64_desc(&mut ts)?.into()) } /// Whether the user key part of a ts encoded key `ts_encoded_key` equals to the encoded /// user key `user_key`. /// /// There is an optimization in this function, which is to compare the last 8 encoded bytes /// first before comparing the rest. It is because in TiDB many records are ended with an 8 /// byte row id and in many situations only this part is different when calling this function. // // TODO: If the last 8 byte is memory aligned, it would be better. #[inline] pub fn is_user_key_eq(ts_encoded_key: &[u8], user_key: &[u8]) -> bool { let user_key_len = user_key.len(); if ts_encoded_key.len()!= user_key_len + number::U64_SIZE { return false; } if user_key_len >= number::U64_SIZE { // We compare last 8 bytes as u64 first, then compare the rest. // TODO: Can we just use == to check the left part and right part? `memcmp` might // be smart enough. let left = NativeEndian::read_u64(&ts_encoded_key[user_key_len - 8..]); let right = NativeEndian::read_u64(&user_key[user_key_len - 8..]); if left!= right { return false; } ts_encoded_key[..user_key_len - 8] == user_key[..user_key_len - 8] } else { ts_encoded_key[..user_key_len] == user_key[..] } } /// Returns whether the encoded key is encoded from `raw_key`. pub fn is_encoded_from(&self, raw_key: &[u8]) -> bool { bytes::is_encoded_from(&self.0, raw_key, false) } /// TiDB uses the same hash algorithm. pub fn gen_hash(&self) -> u64 { farmhash::fingerprint64(&self.to_raw().unwrap()) } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> usize { self.0.len() } } impl Clone for Key { fn clone(&self) -> Self { // default clone implemention use self.len() to reserve capacity // for the sake of appending ts, we need to reserve more let mut key = Vec::with_capacity(self.0.capacity()); key.extend_from_slice(&self.0); Key(key) } } impl Debug for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } impl Display for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } #[derive(Debug, Copy, Clone, PartialEq)] pub enum MutationType { Put, Delete, Lock, Insert, Other, } /// A row mutation. #[derive(Debug, Clone)] pub enum RawMutation {
/// Delete `Key`. Delete { key: Key }, } impl RawMutation { pub fn key(&self) -> &Key { match self { RawMutation::Put { ref key, value: _, ttl: _, } => key, RawMutation::Delete { ref key } => key, } } } /// A row mutation. #[derive(Debug, Clone)] pub enum Mutation { /// Put `Value` into `Key`, overwriting any existing value. Put((Key, Value)), /// Delete `Key`. Delete(Key), /// Set a lock on `Key`. Lock(Key), /// Put `Value` into `Key` if `Key` does not yet exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. Insert((Key, Value)), /// Check `key` must be not exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. CheckNotExists(Key), } impl Mutation { pub fn key(&self) -> &Key { match self { Mutation::Put((ref key, _)) => key, Mutation::Delete(ref key) => key, Mutation::Lock(ref key) => key, Mutation::Insert((ref key, _)) => key, Mutation::CheckNotExists(ref key) => key, } } pub fn mutation_type(&self) -> MutationType { match self { Mutation::Put(_) => MutationType::Put, Mutation::Delete(_) => MutationType::Delete, Mutation::Lock(_) => MutationType::Lock, Mutation::Insert(_) => MutationType::Insert, _ => MutationType::Other, } } pub fn into_key_value(self) -> (Key, Option<Value>) { match self { Mutation::Put((key, value)) => (key, Some(value)), Mutation::Delete(key) => (key, None), Mutation::Lock(key) => (key, None), Mutation::Insert((key, value)) => (key, Some(value)), Mutation::CheckNotExists(key) => (key, None), } } pub fn should_not_exists(&self) -> bool { matches!(self, Mutation::Insert(_) | Mutation::CheckNotExists(_)) } pub fn should_not_write(&self) -> bool { matches!(self, Mutation::CheckNotExists(_)) } } impl From<kvrpcpb::Mutation> for Mutation { fn from(mut m: kvrpcpb::Mutation) -> Mutation { match m.get_op() { kvrpcpb::Op::Put => Mutation::Put((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::Del => Mutation::Delete(Key::from_raw(m.get_key())), kvrpcpb::Op::Lock => Mutation::Lock(Key::from_raw(m.get_key())), kvrpcpb::Op::Insert => Mutation::Insert((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::CheckNotExists => Mutation::CheckNotExists(Key::from_raw(m.get_key())), _ => panic!("mismatch Op in prewrite mutations"), } } } /// `OldValue` is used by cdc to read the previous value associated with some key during the prewrite process #[derive(Debug, Clone, PartialEq)] pub enum OldValue { /// A real `OldValue` Value { value: Value }, /// A timestamp of an old value in case a value is not inlined in Write ValueTimeStamp { start_ts: TimeStamp }, /// `None` means we don't found a previous value None, /// `Unspecified` means one of the following: /// - The user doesn't care about the previous value /// - We don't sure if there is a previous value Unspecified, } impl Default for OldValue { fn default() -> Self { OldValue::Unspecified } } impl OldValue { pub fn valid(&self) -> bool { !matches!(self, OldValue::Unspecified) } pub fn size(&self) -> usize { let value_size = match self { OldValue::Value { value } => value.len(), _ => 0, }; value_size + std::mem::size_of::<OldValue>() } } // Returned by MvccTxn when extra_op is set to kvrpcpb::ExtraOp::ReadOldValue. // key with current ts -> (short value of the prev txn, start ts of the prev txn). // The value of the map will be None when the mutation is `Insert`. // MutationType is the type of mutation of the current write. pub type OldValues = HashMap<Key, (OldValue, Option<MutationType>)>; // Extra data fields filled by kvrpcpb::ExtraOp. #[derive(Default, Debug, Clone)] pub struct TxnExtra { pub old_values: OldValues, // Marks that this transaction is a 1PC transaction. RaftKv should set this flag // in the raft command request. pub one_pc: bool, } impl TxnExtra { pub fn is_empty(&self) -> bool { self.old_values.is_empty() } } pub trait TxnExtraScheduler: Send + Sync { fn schedule(&self, txn_extra: TxnExtra); } bitflags! { /// Additional flags for a write batch. /// They should be set in the `flags` field in `RaftRequestHeader`. pub struct WriteBatchFlags: u64 { /// Indicates this request is from a 1PC transaction. /// It helps CDC recognize 1PC transactions and handle them correctly. const ONE_PC = 0b00000001; /// Indicates this request is from a stale read-only transaction. const STALE_READ = 0b00000010; } } impl WriteBatchFlags { /// Convert from underlying bit representation /// panic if it contains bits that do not correspond to a flag pub fn from_bits_check(bits: u64) -> WriteBatchFlags { match WriteBatchFlags::from_bits(bits) { None => panic!("unrecognized flags: {:b}", bits), // zero or more flags Some(f) => f, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_flags() { assert!(WriteBatchFlags::from_bits_check(0).is_empty()); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::ONE_PC.bits()), WriteBatchFlags::ONE_PC ); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::STALE_READ.bits()), WriteBatchFlags::STALE_READ ); } #[test] fn test_flags_panic() { for _ in 0..100 { assert!( panic_hook::recover_safe(|| { // r must be an invalid flags if it is not zero let r = rand::random::<u64>() &!WriteBatchFlags::all().bits(); WriteBatchFlags::from_bits_check(r); if r == 0 { panic!("panic for zero"); } }) .is_err() ); } } #[test] fn test_is_user_key_eq() { // make a short name to keep format for the test. fn eq(a: &[u8], b: &[u8]) -> bool { Key::is_user_key_eq(a, b) } assert_eq!(false, eq(b"", b"")); assert_eq!(false, eq(b"12345", b"")); assert_eq!(true, eq(b"12345678", b"")); assert_eq!(true, eq(b"x12345678", b"x")); assert_eq!(false, eq(b"x12345", b"x")); // user key len == 3 assert_eq!(true, eq(b"xyz12345678", b"xyz")); assert_eq!(true, eq(b"xyz________", b"xyz")); assert_eq!(false, eq(b"xyy12345678", b"xyz")); assert_eq!(false, eq(b"yyz12345678", b"xyz")); assert_eq!(false, eq(b"xyz12345678", b"xy")); assert_eq!(false, eq(b"xyy12345678", b"xy")); assert_eq!(false, eq(b"yyz12345678", b"xy")); // user key len == 7 assert_eq!(true, eq(b"abcdefg12345678", b"abcdefg")); assert_eq!(true, eq(b"abcdefgzzzzzzzz", b"abcdefg")); assert_eq!(false, eq(b"abcdefg12345678", b"abcdef")); assert_eq!(false, eq(b"abcdefg12345678", b"bcdefg")); assert_eq!(false, eq(b"abcdefv12345678", b"abcdefg")); assert_eq!(false, eq(b"vbcdefg12345678", b"abcdefg")); assert_eq!(false, eq(b"abccefg12345678", b"abcdefg")); // user key len == 8 assert_eq!(true, eq(b"abcdefgh12345678", b"abcdefgh")); assert_eq!(true, eq(b"abcdefghyyyyyyyy", b"abcdefgh")); assert_eq!(false, eq(b"abcdefgh12345678", b"abcdefg")); assert_eq!(false, eq(b"abcdefgh12345678", b"bcdefgh")); assert_eq!(false, eq(b"abcdefgz12345678", b"abcdefgh")); assert_eq!(false, eq(b"zbcdefgh12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcddfgh12345678", b"abcdefgh")); // user key len == 9 assert_eq!(true, eq(b"abcdefghi12345678", b"abcdefghi")); assert_eq!(true, eq(b"abcdefghixxxxxxxx", b"abcdefghi")); assert_eq!(false, eq(b"abcdefghi12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcdefghi12345678", b"bcdefghi")); assert_eq!(false, eq(b"abcdefghy12345678", b"abcdefghi")); assert_eq!(false, eq(b"ybcdefghi12345678", b"abcdefghi")); assert_eq!(false, eq(b"abcddfghi12345678", b"abcdefghi")); // user key len == 11 assert_eq!(true, eq(b"abcdefghijk87654321", b"abcdefghijk")); assert_eq!(true, eq(b"abcdefghijkabcdefgh", b"abcdefghijk")); assert_eq!(false, eq(b"abcdefghijk87654321", b"abcdefghij")); assert_eq!(false, eq(b"abcdefghijk87654321", b"bcdefghijk")); assert_eq!(false, eq(b"abcdefghijx87654321", b"abcdefghijk")); assert_eq!(false, eq(b"xbcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abxdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"axcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abcdeffhijk87654321", b"abcdefghijk")); } #[test] fn test_is_encoded_from() { for raw_len in 0..=24 { let raw: Vec<u8> = (0..raw_len).collect(); let encoded = Key::from_raw(&raw); assert!(encoded.is_encoded_from(&raw)); let encoded_len = encoded.as_encoded().len(); // Should return false if we modify one byte in raw for i in 0..raw.len() { let mut invalid_raw = raw.clone(); invalid_raw[i] = raw[i].wrapping_add(1); assert!(!encoded.is_encoded_from(&invalid_raw)); } // Should return false if we modify one byte in encoded for i in 0..encoded_len { let mut invalid_encoded = encoded.clone(); invalid_encoded.0[i] = encoded.0[i].wrapping_add(1); assert!(!invalid_encoded.is_encoded_from(&raw)); } // Should return false if encoded length is not a multiple of 9 let mut invalid_encoded = encoded.clone(); invalid_encoded.0.pop(); assert!(!invalid_encoded.is_encoded_from(&raw)); // Should return false if encoded has less or more chunks let shorter_encoded = Key::from_encoded_slice(&encoded.0[..encoded_len - 9]); assert!(!shorter_encoded.is_encoded_from(&raw)); let mut longer_encoded = encoded.as_encoded().clone(); longer_encoded.extend(&[0, 0, 0, 0, 0, 0, 0, 0, 0xFF]); let longer_encoded = Key::from_encoded(longer_encoded); assert!(!longer_encoded.is_encoded_from(&raw)); // Should return false if raw is longer or shorter
/// Put `Value` into `Key` with TTL. The TTL will overwrite the existing TTL value. Put { key: Key, value: Value, ttl: u64 },
random_line_split
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value); /// Key type. /// /// Keys have 2 types of binary representation - raw and encoded. The raw /// representation is for public interface, the encoded representation is for /// internal storage. We can get both representations from an instance of this /// type. /// /// Orthogonal to binary representation, keys may or may not embed a timestamp, /// but this information is transparent to this type, the caller must use it /// consistently. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Key(Vec<u8>); /// Core functions for `Key`. impl Key { /// Creates a key from raw bytes. #[inline] pub fn from_raw(key: &[u8]) -> Key { // adding extra length for appending timestamp let len = codec::bytes::max_encoded_bytes_size(key.len()) + codec::number::U64_SIZE; let mut encoded = Vec::with_capacity(len); encoded.encode_bytes(key, false).unwrap(); Key(encoded) } /// Creates a key from raw bytes but returns None if the key is an empty slice. #[inline] pub fn from_raw_maybe_unbounded(key: &[u8]) -> Option<Key> { if key.is_empty() { None } else { Some(Key::from_raw(key)) } } /// Gets and moves the raw representation of this key. #[inline] pub fn into_raw(self) -> Result<Vec<u8>, codec::Error> { let mut k = self.0; bytes::decode_bytes_in_place(&mut k, false)?; Ok(k) } /// Gets the raw representation of this key. #[inline] pub fn to_raw(&self) -> Result<Vec<u8>, codec::Error> { bytes::decode_bytes(&mut self.0.as_slice(), false) } /// Creates a key from encoded bytes vector. #[inline] pub fn from_encoded(encoded_key: Vec<u8>) -> Key { Key(encoded_key) } /// Creates a key with reserved capacity for timestamp from encoded bytes slice. #[inline] pub fn from_encoded_slice(encoded_key: &[u8]) -> Key { let mut k = Vec::with_capacity(encoded_key.len() + number::U64_SIZE); k.extend_from_slice(encoded_key); Key(k) } /// Gets the encoded representation of this key. #[inline] pub fn as_encoded(&self) -> &Vec<u8> { &self.0 } /// Gets and moves the encoded representation of this key. #[inline] pub fn into_encoded(self) -> Vec<u8> { self.0 } /// Creates a new key by appending a `u64` timestamp to this key. #[inline] pub fn append_ts(mut self, ts: TimeStamp) -> Key { self.0.encode_u64_desc(ts.into_inner()).unwrap(); self } /// Gets the timestamp contained in this key. /// /// Preconditions: the caller must ensure this is actually a timestamped /// key. #[inline] pub fn decode_ts(&self) -> Result<TimeStamp, codec::Error> { Self::decode_ts_from(&self.0) } /// Creates a new key by truncating the timestamp from this key. /// /// Preconditions: the caller must ensure this is actually a timestamped key. #[inline] pub fn truncate_ts(mut self) -> Result<Key, codec::Error> { let len = self.0.len(); if len < number::U64_SIZE { // TODO: IMHO, this should be an assertion failure instead of // returning an error. If this happens, it indicates a bug in // the caller module, have to make code change to fix it. // // Even if it passed the length check, it still could be buggy, // a better way is to introduce a type `TimestampedKey`, and // functions to convert between `TimestampedKey` and `Key`. // `TimestampedKey` is in a higher (MVCC) layer, while `Key` is // in the core storage engine layer. Err(codec::Error::KeyLength) } else { self.0.truncate(len - number::U64_SIZE); Ok(self) } } /// Split a ts encoded key, return the user key and timestamp. #[inline] pub fn split_on_ts_for(key: &[u8]) -> Result<(&[u8], TimeStamp), codec::Error> { if key.len() < number::U64_SIZE { Err(codec::Error::KeyLength) } else { let pos = key.len() - number::U64_SIZE; let k = &key[..pos]; let mut ts = &key[pos..]; Ok((k, number::decode_u64_desc(&mut ts)?.into())) } } /// Extract the user key from a ts encoded key. #[inline] pub fn truncate_ts_for(key: &[u8]) -> Result<&[u8], codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } Ok(&key[..key.len() - number::U64_SIZE]) } /// Decode the timestamp from a ts encoded key. #[inline] pub fn decode_ts_from(key: &[u8]) -> Result<TimeStamp, codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } let mut ts = &key[len - number::U64_SIZE..]; Ok(number::decode_u64_desc(&mut ts)?.into()) } /// Whether the user key part of a ts encoded key `ts_encoded_key` equals to the encoded /// user key `user_key`. /// /// There is an optimization in this function, which is to compare the last 8 encoded bytes /// first before comparing the rest. It is because in TiDB many records are ended with an 8 /// byte row id and in many situations only this part is different when calling this function. // // TODO: If the last 8 byte is memory aligned, it would be better. #[inline] pub fn is_user_key_eq(ts_encoded_key: &[u8], user_key: &[u8]) -> bool { let user_key_len = user_key.len(); if ts_encoded_key.len()!= user_key_len + number::U64_SIZE { return false; } if user_key_len >= number::U64_SIZE { // We compare last 8 bytes as u64 first, then compare the rest. // TODO: Can we just use == to check the left part and right part? `memcmp` might // be smart enough. let left = NativeEndian::read_u64(&ts_encoded_key[user_key_len - 8..]); let right = NativeEndian::read_u64(&user_key[user_key_len - 8..]); if left!= right { return false; } ts_encoded_key[..user_key_len - 8] == user_key[..user_key_len - 8] } else { ts_encoded_key[..user_key_len] == user_key[..] } } /// Returns whether the encoded key is encoded from `raw_key`. pub fn is_encoded_from(&self, raw_key: &[u8]) -> bool { bytes::is_encoded_from(&self.0, raw_key, false) } /// TiDB uses the same hash algorithm. pub fn gen_hash(&self) -> u64 { farmhash::fingerprint64(&self.to_raw().unwrap()) } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> usize { self.0.len() } } impl Clone for Key { fn clone(&self) -> Self { // default clone implemention use self.len() to reserve capacity // for the sake of appending ts, we need to reserve more let mut key = Vec::with_capacity(self.0.capacity()); key.extend_from_slice(&self.0); Key(key) } } impl Debug for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } impl Display for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } #[derive(Debug, Copy, Clone, PartialEq)] pub enum MutationType { Put, Delete, Lock, Insert, Other, } /// A row mutation. #[derive(Debug, Clone)] pub enum RawMutation { /// Put `Value` into `Key` with TTL. The TTL will overwrite the existing TTL value. Put { key: Key, value: Value, ttl: u64 }, /// Delete `Key`. Delete { key: Key }, } impl RawMutation { pub fn key(&self) -> &Key { match self { RawMutation::Put { ref key, value: _, ttl: _, } => key, RawMutation::Delete { ref key } => key, } } } /// A row mutation. #[derive(Debug, Clone)] pub enum Mutation { /// Put `Value` into `Key`, overwriting any existing value. Put((Key, Value)), /// Delete `Key`. Delete(Key), /// Set a lock on `Key`. Lock(Key), /// Put `Value` into `Key` if `Key` does not yet exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. Insert((Key, Value)), /// Check `key` must be not exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. CheckNotExists(Key), } impl Mutation { pub fn key(&self) -> &Key { match self { Mutation::Put((ref key, _)) => key, Mutation::Delete(ref key) => key, Mutation::Lock(ref key) => key, Mutation::Insert((ref key, _)) => key, Mutation::CheckNotExists(ref key) => key, } } pub fn mutation_type(&self) -> MutationType { match self { Mutation::Put(_) => MutationType::Put, Mutation::Delete(_) => MutationType::Delete, Mutation::Lock(_) => MutationType::Lock, Mutation::Insert(_) => MutationType::Insert, _ => MutationType::Other, } } pub fn into_key_value(self) -> (Key, Option<Value>) { match self { Mutation::Put((key, value)) => (key, Some(value)), Mutation::Delete(key) => (key, None), Mutation::Lock(key) => (key, None), Mutation::Insert((key, value)) => (key, Some(value)), Mutation::CheckNotExists(key) => (key, None), } } pub fn should_not_exists(&self) -> bool { matches!(self, Mutation::Insert(_) | Mutation::CheckNotExists(_)) } pub fn should_not_write(&self) -> bool { matches!(self, Mutation::CheckNotExists(_)) } } impl From<kvrpcpb::Mutation> for Mutation { fn from(mut m: kvrpcpb::Mutation) -> Mutation { match m.get_op() { kvrpcpb::Op::Put => Mutation::Put((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::Del => Mutation::Delete(Key::from_raw(m.get_key())), kvrpcpb::Op::Lock => Mutation::Lock(Key::from_raw(m.get_key())), kvrpcpb::Op::Insert => Mutation::Insert((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::CheckNotExists => Mutation::CheckNotExists(Key::from_raw(m.get_key())), _ => panic!("mismatch Op in prewrite mutations"), } } } /// `OldValue` is used by cdc to read the previous value associated with some key during the prewrite process #[derive(Debug, Clone, PartialEq)] pub enum OldValue { /// A real `OldValue` Value { value: Value }, /// A timestamp of an old value in case a value is not inlined in Write ValueTimeStamp { start_ts: TimeStamp }, /// `None` means we don't found a previous value None, /// `Unspecified` means one of the following: /// - The user doesn't care about the previous value /// - We don't sure if there is a previous value Unspecified, } impl Default for OldValue { fn default() -> Self { OldValue::Unspecified } } impl OldValue { pub fn valid(&self) -> bool { !matches!(self, OldValue::Unspecified) } pub fn size(&self) -> usize
} // Returned by MvccTxn when extra_op is set to kvrpcpb::ExtraOp::ReadOldValue. // key with current ts -> (short value of the prev txn, start ts of the prev txn). // The value of the map will be None when the mutation is `Insert`. // MutationType is the type of mutation of the current write. pub type OldValues = HashMap<Key, (OldValue, Option<MutationType>)>; // Extra data fields filled by kvrpcpb::ExtraOp. #[derive(Default, Debug, Clone)] pub struct TxnExtra { pub old_values: OldValues, // Marks that this transaction is a 1PC transaction. RaftKv should set this flag // in the raft command request. pub one_pc: bool, } impl TxnExtra { pub fn is_empty(&self) -> bool { self.old_values.is_empty() } } pub trait TxnExtraScheduler: Send + Sync { fn schedule(&self, txn_extra: TxnExtra); } bitflags! { /// Additional flags for a write batch. /// They should be set in the `flags` field in `RaftRequestHeader`. pub struct WriteBatchFlags: u64 { /// Indicates this request is from a 1PC transaction. /// It helps CDC recognize 1PC transactions and handle them correctly. const ONE_PC = 0b00000001; /// Indicates this request is from a stale read-only transaction. const STALE_READ = 0b00000010; } } impl WriteBatchFlags { /// Convert from underlying bit representation /// panic if it contains bits that do not correspond to a flag pub fn from_bits_check(bits: u64) -> WriteBatchFlags { match WriteBatchFlags::from_bits(bits) { None => panic!("unrecognized flags: {:b}", bits), // zero or more flags Some(f) => f, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_flags() { assert!(WriteBatchFlags::from_bits_check(0).is_empty()); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::ONE_PC.bits()), WriteBatchFlags::ONE_PC ); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::STALE_READ.bits()), WriteBatchFlags::STALE_READ ); } #[test] fn test_flags_panic() { for _ in 0..100 { assert!( panic_hook::recover_safe(|| { // r must be an invalid flags if it is not zero let r = rand::random::<u64>() &!WriteBatchFlags::all().bits(); WriteBatchFlags::from_bits_check(r); if r == 0 { panic!("panic for zero"); } }) .is_err() ); } } #[test] fn test_is_user_key_eq() { // make a short name to keep format for the test. fn eq(a: &[u8], b: &[u8]) -> bool { Key::is_user_key_eq(a, b) } assert_eq!(false, eq(b"", b"")); assert_eq!(false, eq(b"12345", b"")); assert_eq!(true, eq(b"12345678", b"")); assert_eq!(true, eq(b"x12345678", b"x")); assert_eq!(false, eq(b"x12345", b"x")); // user key len == 3 assert_eq!(true, eq(b"xyz12345678", b"xyz")); assert_eq!(true, eq(b"xyz________", b"xyz")); assert_eq!(false, eq(b"xyy12345678", b"xyz")); assert_eq!(false, eq(b"yyz12345678", b"xyz")); assert_eq!(false, eq(b"xyz12345678", b"xy")); assert_eq!(false, eq(b"xyy12345678", b"xy")); assert_eq!(false, eq(b"yyz12345678", b"xy")); // user key len == 7 assert_eq!(true, eq(b"abcdefg12345678", b"abcdefg")); assert_eq!(true, eq(b"abcdefgzzzzzzzz", b"abcdefg")); assert_eq!(false, eq(b"abcdefg12345678", b"abcdef")); assert_eq!(false, eq(b"abcdefg12345678", b"bcdefg")); assert_eq!(false, eq(b"abcdefv12345678", b"abcdefg")); assert_eq!(false, eq(b"vbcdefg12345678", b"abcdefg")); assert_eq!(false, eq(b"abccefg12345678", b"abcdefg")); // user key len == 8 assert_eq!(true, eq(b"abcdefgh12345678", b"abcdefgh")); assert_eq!(true, eq(b"abcdefghyyyyyyyy", b"abcdefgh")); assert_eq!(false, eq(b"abcdefgh12345678", b"abcdefg")); assert_eq!(false, eq(b"abcdefgh12345678", b"bcdefgh")); assert_eq!(false, eq(b"abcdefgz12345678", b"abcdefgh")); assert_eq!(false, eq(b"zbcdefgh12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcddfgh12345678", b"abcdefgh")); // user key len == 9 assert_eq!(true, eq(b"abcdefghi12345678", b"abcdefghi")); assert_eq!(true, eq(b"abcdefghixxxxxxxx", b"abcdefghi")); assert_eq!(false, eq(b"abcdefghi12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcdefghi12345678", b"bcdefghi")); assert_eq!(false, eq(b"abcdefghy12345678", b"abcdefghi")); assert_eq!(false, eq(b"ybcdefghi12345678", b"abcdefghi")); assert_eq!(false, eq(b"abcddfghi12345678", b"abcdefghi")); // user key len == 11 assert_eq!(true, eq(b"abcdefghijk87654321", b"abcdefghijk")); assert_eq!(true, eq(b"abcdefghijkabcdefgh", b"abcdefghijk")); assert_eq!(false, eq(b"abcdefghijk87654321", b"abcdefghij")); assert_eq!(false, eq(b"abcdefghijk87654321", b"bcdefghijk")); assert_eq!(false, eq(b"abcdefghijx87654321", b"abcdefghijk")); assert_eq!(false, eq(b"xbcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abxdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"axcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abcdeffhijk87654321", b"abcdefghijk")); } #[test] fn test_is_encoded_from() { for raw_len in 0..=24 { let raw: Vec<u8> = (0..raw_len).collect(); let encoded = Key::from_raw(&raw); assert!(encoded.is_encoded_from(&raw)); let encoded_len = encoded.as_encoded().len(); // Should return false if we modify one byte in raw for i in 0..raw.len() { let mut invalid_raw = raw.clone(); invalid_raw[i] = raw[i].wrapping_add(1); assert!(!encoded.is_encoded_from(&invalid_raw)); } // Should return false if we modify one byte in encoded for i in 0..encoded_len { let mut invalid_encoded = encoded.clone(); invalid_encoded.0[i] = encoded.0[i].wrapping_add(1); assert!(!invalid_encoded.is_encoded_from(&raw)); } // Should return false if encoded length is not a multiple of 9 let mut invalid_encoded = encoded.clone(); invalid_encoded.0.pop(); assert!(!invalid_encoded.is_encoded_from(&raw)); // Should return false if encoded has less or more chunks let shorter_encoded = Key::from_encoded_slice(&encoded.0[..encoded_len - 9]); assert!(!shorter_encoded.is_encoded_from(&raw)); let mut longer_encoded = encoded.as_encoded().clone(); longer_encoded.extend(&[0, 0, 0, 0, 0, 0, 0, 0, 0xFF]); let longer_encoded = Key::from_encoded(longer_encoded); assert!(!longer_encoded.is_encoded_from(&raw)); // Should return false if raw is longer or shorter
{ let value_size = match self { OldValue::Value { value } => value.len(), _ => 0, }; value_size + std::mem::size_of::<OldValue>() }
identifier_body
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value); /// Key type. /// /// Keys have 2 types of binary representation - raw and encoded. The raw /// representation is for public interface, the encoded representation is for /// internal storage. We can get both representations from an instance of this /// type. /// /// Orthogonal to binary representation, keys may or may not embed a timestamp, /// but this information is transparent to this type, the caller must use it /// consistently. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Key(Vec<u8>); /// Core functions for `Key`. impl Key { /// Creates a key from raw bytes. #[inline] pub fn from_raw(key: &[u8]) -> Key { // adding extra length for appending timestamp let len = codec::bytes::max_encoded_bytes_size(key.len()) + codec::number::U64_SIZE; let mut encoded = Vec::with_capacity(len); encoded.encode_bytes(key, false).unwrap(); Key(encoded) } /// Creates a key from raw bytes but returns None if the key is an empty slice. #[inline] pub fn from_raw_maybe_unbounded(key: &[u8]) -> Option<Key> { if key.is_empty() { None } else { Some(Key::from_raw(key)) } } /// Gets and moves the raw representation of this key. #[inline] pub fn into_raw(self) -> Result<Vec<u8>, codec::Error> { let mut k = self.0; bytes::decode_bytes_in_place(&mut k, false)?; Ok(k) } /// Gets the raw representation of this key. #[inline] pub fn to_raw(&self) -> Result<Vec<u8>, codec::Error> { bytes::decode_bytes(&mut self.0.as_slice(), false) } /// Creates a key from encoded bytes vector. #[inline] pub fn from_encoded(encoded_key: Vec<u8>) -> Key { Key(encoded_key) } /// Creates a key with reserved capacity for timestamp from encoded bytes slice. #[inline] pub fn from_encoded_slice(encoded_key: &[u8]) -> Key { let mut k = Vec::with_capacity(encoded_key.len() + number::U64_SIZE); k.extend_from_slice(encoded_key); Key(k) } /// Gets the encoded representation of this key. #[inline] pub fn as_encoded(&self) -> &Vec<u8> { &self.0 } /// Gets and moves the encoded representation of this key. #[inline] pub fn into_encoded(self) -> Vec<u8> { self.0 } /// Creates a new key by appending a `u64` timestamp to this key. #[inline] pub fn append_ts(mut self, ts: TimeStamp) -> Key { self.0.encode_u64_desc(ts.into_inner()).unwrap(); self } /// Gets the timestamp contained in this key. /// /// Preconditions: the caller must ensure this is actually a timestamped /// key. #[inline] pub fn decode_ts(&self) -> Result<TimeStamp, codec::Error> { Self::decode_ts_from(&self.0) } /// Creates a new key by truncating the timestamp from this key. /// /// Preconditions: the caller must ensure this is actually a timestamped key. #[inline] pub fn truncate_ts(mut self) -> Result<Key, codec::Error> { let len = self.0.len(); if len < number::U64_SIZE { // TODO: IMHO, this should be an assertion failure instead of // returning an error. If this happens, it indicates a bug in // the caller module, have to make code change to fix it. // // Even if it passed the length check, it still could be buggy, // a better way is to introduce a type `TimestampedKey`, and // functions to convert between `TimestampedKey` and `Key`. // `TimestampedKey` is in a higher (MVCC) layer, while `Key` is // in the core storage engine layer. Err(codec::Error::KeyLength) } else { self.0.truncate(len - number::U64_SIZE); Ok(self) } } /// Split a ts encoded key, return the user key and timestamp. #[inline] pub fn split_on_ts_for(key: &[u8]) -> Result<(&[u8], TimeStamp), codec::Error> { if key.len() < number::U64_SIZE { Err(codec::Error::KeyLength) } else
} /// Extract the user key from a ts encoded key. #[inline] pub fn truncate_ts_for(key: &[u8]) -> Result<&[u8], codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } Ok(&key[..key.len() - number::U64_SIZE]) } /// Decode the timestamp from a ts encoded key. #[inline] pub fn decode_ts_from(key: &[u8]) -> Result<TimeStamp, codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } let mut ts = &key[len - number::U64_SIZE..]; Ok(number::decode_u64_desc(&mut ts)?.into()) } /// Whether the user key part of a ts encoded key `ts_encoded_key` equals to the encoded /// user key `user_key`. /// /// There is an optimization in this function, which is to compare the last 8 encoded bytes /// first before comparing the rest. It is because in TiDB many records are ended with an 8 /// byte row id and in many situations only this part is different when calling this function. // // TODO: If the last 8 byte is memory aligned, it would be better. #[inline] pub fn is_user_key_eq(ts_encoded_key: &[u8], user_key: &[u8]) -> bool { let user_key_len = user_key.len(); if ts_encoded_key.len()!= user_key_len + number::U64_SIZE { return false; } if user_key_len >= number::U64_SIZE { // We compare last 8 bytes as u64 first, then compare the rest. // TODO: Can we just use == to check the left part and right part? `memcmp` might // be smart enough. let left = NativeEndian::read_u64(&ts_encoded_key[user_key_len - 8..]); let right = NativeEndian::read_u64(&user_key[user_key_len - 8..]); if left!= right { return false; } ts_encoded_key[..user_key_len - 8] == user_key[..user_key_len - 8] } else { ts_encoded_key[..user_key_len] == user_key[..] } } /// Returns whether the encoded key is encoded from `raw_key`. pub fn is_encoded_from(&self, raw_key: &[u8]) -> bool { bytes::is_encoded_from(&self.0, raw_key, false) } /// TiDB uses the same hash algorithm. pub fn gen_hash(&self) -> u64 { farmhash::fingerprint64(&self.to_raw().unwrap()) } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> usize { self.0.len() } } impl Clone for Key { fn clone(&self) -> Self { // default clone implemention use self.len() to reserve capacity // for the sake of appending ts, we need to reserve more let mut key = Vec::with_capacity(self.0.capacity()); key.extend_from_slice(&self.0); Key(key) } } impl Debug for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } impl Display for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } #[derive(Debug, Copy, Clone, PartialEq)] pub enum MutationType { Put, Delete, Lock, Insert, Other, } /// A row mutation. #[derive(Debug, Clone)] pub enum RawMutation { /// Put `Value` into `Key` with TTL. The TTL will overwrite the existing TTL value. Put { key: Key, value: Value, ttl: u64 }, /// Delete `Key`. Delete { key: Key }, } impl RawMutation { pub fn key(&self) -> &Key { match self { RawMutation::Put { ref key, value: _, ttl: _, } => key, RawMutation::Delete { ref key } => key, } } } /// A row mutation. #[derive(Debug, Clone)] pub enum Mutation { /// Put `Value` into `Key`, overwriting any existing value. Put((Key, Value)), /// Delete `Key`. Delete(Key), /// Set a lock on `Key`. Lock(Key), /// Put `Value` into `Key` if `Key` does not yet exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. Insert((Key, Value)), /// Check `key` must be not exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. CheckNotExists(Key), } impl Mutation { pub fn key(&self) -> &Key { match self { Mutation::Put((ref key, _)) => key, Mutation::Delete(ref key) => key, Mutation::Lock(ref key) => key, Mutation::Insert((ref key, _)) => key, Mutation::CheckNotExists(ref key) => key, } } pub fn mutation_type(&self) -> MutationType { match self { Mutation::Put(_) => MutationType::Put, Mutation::Delete(_) => MutationType::Delete, Mutation::Lock(_) => MutationType::Lock, Mutation::Insert(_) => MutationType::Insert, _ => MutationType::Other, } } pub fn into_key_value(self) -> (Key, Option<Value>) { match self { Mutation::Put((key, value)) => (key, Some(value)), Mutation::Delete(key) => (key, None), Mutation::Lock(key) => (key, None), Mutation::Insert((key, value)) => (key, Some(value)), Mutation::CheckNotExists(key) => (key, None), } } pub fn should_not_exists(&self) -> bool { matches!(self, Mutation::Insert(_) | Mutation::CheckNotExists(_)) } pub fn should_not_write(&self) -> bool { matches!(self, Mutation::CheckNotExists(_)) } } impl From<kvrpcpb::Mutation> for Mutation { fn from(mut m: kvrpcpb::Mutation) -> Mutation { match m.get_op() { kvrpcpb::Op::Put => Mutation::Put((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::Del => Mutation::Delete(Key::from_raw(m.get_key())), kvrpcpb::Op::Lock => Mutation::Lock(Key::from_raw(m.get_key())), kvrpcpb::Op::Insert => Mutation::Insert((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::CheckNotExists => Mutation::CheckNotExists(Key::from_raw(m.get_key())), _ => panic!("mismatch Op in prewrite mutations"), } } } /// `OldValue` is used by cdc to read the previous value associated with some key during the prewrite process #[derive(Debug, Clone, PartialEq)] pub enum OldValue { /// A real `OldValue` Value { value: Value }, /// A timestamp of an old value in case a value is not inlined in Write ValueTimeStamp { start_ts: TimeStamp }, /// `None` means we don't found a previous value None, /// `Unspecified` means one of the following: /// - The user doesn't care about the previous value /// - We don't sure if there is a previous value Unspecified, } impl Default for OldValue { fn default() -> Self { OldValue::Unspecified } } impl OldValue { pub fn valid(&self) -> bool { !matches!(self, OldValue::Unspecified) } pub fn size(&self) -> usize { let value_size = match self { OldValue::Value { value } => value.len(), _ => 0, }; value_size + std::mem::size_of::<OldValue>() } } // Returned by MvccTxn when extra_op is set to kvrpcpb::ExtraOp::ReadOldValue. // key with current ts -> (short value of the prev txn, start ts of the prev txn). // The value of the map will be None when the mutation is `Insert`. // MutationType is the type of mutation of the current write. pub type OldValues = HashMap<Key, (OldValue, Option<MutationType>)>; // Extra data fields filled by kvrpcpb::ExtraOp. #[derive(Default, Debug, Clone)] pub struct TxnExtra { pub old_values: OldValues, // Marks that this transaction is a 1PC transaction. RaftKv should set this flag // in the raft command request. pub one_pc: bool, } impl TxnExtra { pub fn is_empty(&self) -> bool { self.old_values.is_empty() } } pub trait TxnExtraScheduler: Send + Sync { fn schedule(&self, txn_extra: TxnExtra); } bitflags! { /// Additional flags for a write batch. /// They should be set in the `flags` field in `RaftRequestHeader`. pub struct WriteBatchFlags: u64 { /// Indicates this request is from a 1PC transaction. /// It helps CDC recognize 1PC transactions and handle them correctly. const ONE_PC = 0b00000001; /// Indicates this request is from a stale read-only transaction. const STALE_READ = 0b00000010; } } impl WriteBatchFlags { /// Convert from underlying bit representation /// panic if it contains bits that do not correspond to a flag pub fn from_bits_check(bits: u64) -> WriteBatchFlags { match WriteBatchFlags::from_bits(bits) { None => panic!("unrecognized flags: {:b}", bits), // zero or more flags Some(f) => f, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_flags() { assert!(WriteBatchFlags::from_bits_check(0).is_empty()); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::ONE_PC.bits()), WriteBatchFlags::ONE_PC ); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::STALE_READ.bits()), WriteBatchFlags::STALE_READ ); } #[test] fn test_flags_panic() { for _ in 0..100 { assert!( panic_hook::recover_safe(|| { // r must be an invalid flags if it is not zero let r = rand::random::<u64>() &!WriteBatchFlags::all().bits(); WriteBatchFlags::from_bits_check(r); if r == 0 { panic!("panic for zero"); } }) .is_err() ); } } #[test] fn test_is_user_key_eq() { // make a short name to keep format for the test. fn eq(a: &[u8], b: &[u8]) -> bool { Key::is_user_key_eq(a, b) } assert_eq!(false, eq(b"", b"")); assert_eq!(false, eq(b"12345", b"")); assert_eq!(true, eq(b"12345678", b"")); assert_eq!(true, eq(b"x12345678", b"x")); assert_eq!(false, eq(b"x12345", b"x")); // user key len == 3 assert_eq!(true, eq(b"xyz12345678", b"xyz")); assert_eq!(true, eq(b"xyz________", b"xyz")); assert_eq!(false, eq(b"xyy12345678", b"xyz")); assert_eq!(false, eq(b"yyz12345678", b"xyz")); assert_eq!(false, eq(b"xyz12345678", b"xy")); assert_eq!(false, eq(b"xyy12345678", b"xy")); assert_eq!(false, eq(b"yyz12345678", b"xy")); // user key len == 7 assert_eq!(true, eq(b"abcdefg12345678", b"abcdefg")); assert_eq!(true, eq(b"abcdefgzzzzzzzz", b"abcdefg")); assert_eq!(false, eq(b"abcdefg12345678", b"abcdef")); assert_eq!(false, eq(b"abcdefg12345678", b"bcdefg")); assert_eq!(false, eq(b"abcdefv12345678", b"abcdefg")); assert_eq!(false, eq(b"vbcdefg12345678", b"abcdefg")); assert_eq!(false, eq(b"abccefg12345678", b"abcdefg")); // user key len == 8 assert_eq!(true, eq(b"abcdefgh12345678", b"abcdefgh")); assert_eq!(true, eq(b"abcdefghyyyyyyyy", b"abcdefgh")); assert_eq!(false, eq(b"abcdefgh12345678", b"abcdefg")); assert_eq!(false, eq(b"abcdefgh12345678", b"bcdefgh")); assert_eq!(false, eq(b"abcdefgz12345678", b"abcdefgh")); assert_eq!(false, eq(b"zbcdefgh12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcddfgh12345678", b"abcdefgh")); // user key len == 9 assert_eq!(true, eq(b"abcdefghi12345678", b"abcdefghi")); assert_eq!(true, eq(b"abcdefghixxxxxxxx", b"abcdefghi")); assert_eq!(false, eq(b"abcdefghi12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcdefghi12345678", b"bcdefghi")); assert_eq!(false, eq(b"abcdefghy12345678", b"abcdefghi")); assert_eq!(false, eq(b"ybcdefghi12345678", b"abcdefghi")); assert_eq!(false, eq(b"abcddfghi12345678", b"abcdefghi")); // user key len == 11 assert_eq!(true, eq(b"abcdefghijk87654321", b"abcdefghijk")); assert_eq!(true, eq(b"abcdefghijkabcdefgh", b"abcdefghijk")); assert_eq!(false, eq(b"abcdefghijk87654321", b"abcdefghij")); assert_eq!(false, eq(b"abcdefghijk87654321", b"bcdefghijk")); assert_eq!(false, eq(b"abcdefghijx87654321", b"abcdefghijk")); assert_eq!(false, eq(b"xbcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abxdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"axcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abcdeffhijk87654321", b"abcdefghijk")); } #[test] fn test_is_encoded_from() { for raw_len in 0..=24 { let raw: Vec<u8> = (0..raw_len).collect(); let encoded = Key::from_raw(&raw); assert!(encoded.is_encoded_from(&raw)); let encoded_len = encoded.as_encoded().len(); // Should return false if we modify one byte in raw for i in 0..raw.len() { let mut invalid_raw = raw.clone(); invalid_raw[i] = raw[i].wrapping_add(1); assert!(!encoded.is_encoded_from(&invalid_raw)); } // Should return false if we modify one byte in encoded for i in 0..encoded_len { let mut invalid_encoded = encoded.clone(); invalid_encoded.0[i] = encoded.0[i].wrapping_add(1); assert!(!invalid_encoded.is_encoded_from(&raw)); } // Should return false if encoded length is not a multiple of 9 let mut invalid_encoded = encoded.clone(); invalid_encoded.0.pop(); assert!(!invalid_encoded.is_encoded_from(&raw)); // Should return false if encoded has less or more chunks let shorter_encoded = Key::from_encoded_slice(&encoded.0[..encoded_len - 9]); assert!(!shorter_encoded.is_encoded_from(&raw)); let mut longer_encoded = encoded.as_encoded().clone(); longer_encoded.extend(&[0, 0, 0, 0, 0, 0, 0, 0, 0xFF]); let longer_encoded = Key::from_encoded(longer_encoded); assert!(!longer_encoded.is_encoded_from(&raw)); // Should return false if raw is longer or shorter
{ let pos = key.len() - number::U64_SIZE; let k = &key[..pos]; let mut ts = &key[pos..]; Ok((k, number::decode_u64_desc(&mut ts)?.into())) }
conditional_block
types.rs
pub fn is_short_value(value: &[u8]) -> bool { value.len() <= SHORT_VALUE_MAX_LEN } /// Value type which is essentially raw bytes. pub type Value = Vec<u8>; /// Key-value pair type. /// /// The value is simply raw bytes; the key is a little bit tricky, which is /// encoded bytes. pub type KvPair = (Vec<u8>, Value); /// Key type. /// /// Keys have 2 types of binary representation - raw and encoded. The raw /// representation is for public interface, the encoded representation is for /// internal storage. We can get both representations from an instance of this /// type. /// /// Orthogonal to binary representation, keys may or may not embed a timestamp, /// but this information is transparent to this type, the caller must use it /// consistently. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Key(Vec<u8>); /// Core functions for `Key`. impl Key { /// Creates a key from raw bytes. #[inline] pub fn from_raw(key: &[u8]) -> Key { // adding extra length for appending timestamp let len = codec::bytes::max_encoded_bytes_size(key.len()) + codec::number::U64_SIZE; let mut encoded = Vec::with_capacity(len); encoded.encode_bytes(key, false).unwrap(); Key(encoded) } /// Creates a key from raw bytes but returns None if the key is an empty slice. #[inline] pub fn from_raw_maybe_unbounded(key: &[u8]) -> Option<Key> { if key.is_empty() { None } else { Some(Key::from_raw(key)) } } /// Gets and moves the raw representation of this key. #[inline] pub fn into_raw(self) -> Result<Vec<u8>, codec::Error> { let mut k = self.0; bytes::decode_bytes_in_place(&mut k, false)?; Ok(k) } /// Gets the raw representation of this key. #[inline] pub fn to_raw(&self) -> Result<Vec<u8>, codec::Error> { bytes::decode_bytes(&mut self.0.as_slice(), false) } /// Creates a key from encoded bytes vector. #[inline] pub fn from_encoded(encoded_key: Vec<u8>) -> Key { Key(encoded_key) } /// Creates a key with reserved capacity for timestamp from encoded bytes slice. #[inline] pub fn from_encoded_slice(encoded_key: &[u8]) -> Key { let mut k = Vec::with_capacity(encoded_key.len() + number::U64_SIZE); k.extend_from_slice(encoded_key); Key(k) } /// Gets the encoded representation of this key. #[inline] pub fn as_encoded(&self) -> &Vec<u8> { &self.0 } /// Gets and moves the encoded representation of this key. #[inline] pub fn into_encoded(self) -> Vec<u8> { self.0 } /// Creates a new key by appending a `u64` timestamp to this key. #[inline] pub fn append_ts(mut self, ts: TimeStamp) -> Key { self.0.encode_u64_desc(ts.into_inner()).unwrap(); self } /// Gets the timestamp contained in this key. /// /// Preconditions: the caller must ensure this is actually a timestamped /// key. #[inline] pub fn decode_ts(&self) -> Result<TimeStamp, codec::Error> { Self::decode_ts_from(&self.0) } /// Creates a new key by truncating the timestamp from this key. /// /// Preconditions: the caller must ensure this is actually a timestamped key. #[inline] pub fn
(mut self) -> Result<Key, codec::Error> { let len = self.0.len(); if len < number::U64_SIZE { // TODO: IMHO, this should be an assertion failure instead of // returning an error. If this happens, it indicates a bug in // the caller module, have to make code change to fix it. // // Even if it passed the length check, it still could be buggy, // a better way is to introduce a type `TimestampedKey`, and // functions to convert between `TimestampedKey` and `Key`. // `TimestampedKey` is in a higher (MVCC) layer, while `Key` is // in the core storage engine layer. Err(codec::Error::KeyLength) } else { self.0.truncate(len - number::U64_SIZE); Ok(self) } } /// Split a ts encoded key, return the user key and timestamp. #[inline] pub fn split_on_ts_for(key: &[u8]) -> Result<(&[u8], TimeStamp), codec::Error> { if key.len() < number::U64_SIZE { Err(codec::Error::KeyLength) } else { let pos = key.len() - number::U64_SIZE; let k = &key[..pos]; let mut ts = &key[pos..]; Ok((k, number::decode_u64_desc(&mut ts)?.into())) } } /// Extract the user key from a ts encoded key. #[inline] pub fn truncate_ts_for(key: &[u8]) -> Result<&[u8], codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } Ok(&key[..key.len() - number::U64_SIZE]) } /// Decode the timestamp from a ts encoded key. #[inline] pub fn decode_ts_from(key: &[u8]) -> Result<TimeStamp, codec::Error> { let len = key.len(); if len < number::U64_SIZE { return Err(codec::Error::KeyLength); } let mut ts = &key[len - number::U64_SIZE..]; Ok(number::decode_u64_desc(&mut ts)?.into()) } /// Whether the user key part of a ts encoded key `ts_encoded_key` equals to the encoded /// user key `user_key`. /// /// There is an optimization in this function, which is to compare the last 8 encoded bytes /// first before comparing the rest. It is because in TiDB many records are ended with an 8 /// byte row id and in many situations only this part is different when calling this function. // // TODO: If the last 8 byte is memory aligned, it would be better. #[inline] pub fn is_user_key_eq(ts_encoded_key: &[u8], user_key: &[u8]) -> bool { let user_key_len = user_key.len(); if ts_encoded_key.len()!= user_key_len + number::U64_SIZE { return false; } if user_key_len >= number::U64_SIZE { // We compare last 8 bytes as u64 first, then compare the rest. // TODO: Can we just use == to check the left part and right part? `memcmp` might // be smart enough. let left = NativeEndian::read_u64(&ts_encoded_key[user_key_len - 8..]); let right = NativeEndian::read_u64(&user_key[user_key_len - 8..]); if left!= right { return false; } ts_encoded_key[..user_key_len - 8] == user_key[..user_key_len - 8] } else { ts_encoded_key[..user_key_len] == user_key[..] } } /// Returns whether the encoded key is encoded from `raw_key`. pub fn is_encoded_from(&self, raw_key: &[u8]) -> bool { bytes::is_encoded_from(&self.0, raw_key, false) } /// TiDB uses the same hash algorithm. pub fn gen_hash(&self) -> u64 { farmhash::fingerprint64(&self.to_raw().unwrap()) } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> usize { self.0.len() } } impl Clone for Key { fn clone(&self) -> Self { // default clone implemention use self.len() to reserve capacity // for the sake of appending ts, we need to reserve more let mut key = Vec::with_capacity(self.0.capacity()); key.extend_from_slice(&self.0); Key(key) } } impl Debug for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } impl Display for Key { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &log_wrappers::Value::key(&self.0)) } } #[derive(Debug, Copy, Clone, PartialEq)] pub enum MutationType { Put, Delete, Lock, Insert, Other, } /// A row mutation. #[derive(Debug, Clone)] pub enum RawMutation { /// Put `Value` into `Key` with TTL. The TTL will overwrite the existing TTL value. Put { key: Key, value: Value, ttl: u64 }, /// Delete `Key`. Delete { key: Key }, } impl RawMutation { pub fn key(&self) -> &Key { match self { RawMutation::Put { ref key, value: _, ttl: _, } => key, RawMutation::Delete { ref key } => key, } } } /// A row mutation. #[derive(Debug, Clone)] pub enum Mutation { /// Put `Value` into `Key`, overwriting any existing value. Put((Key, Value)), /// Delete `Key`. Delete(Key), /// Set a lock on `Key`. Lock(Key), /// Put `Value` into `Key` if `Key` does not yet exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. Insert((Key, Value)), /// Check `key` must be not exist. /// /// Returns `kvrpcpb::KeyError::AlreadyExists` if the key already exists. CheckNotExists(Key), } impl Mutation { pub fn key(&self) -> &Key { match self { Mutation::Put((ref key, _)) => key, Mutation::Delete(ref key) => key, Mutation::Lock(ref key) => key, Mutation::Insert((ref key, _)) => key, Mutation::CheckNotExists(ref key) => key, } } pub fn mutation_type(&self) -> MutationType { match self { Mutation::Put(_) => MutationType::Put, Mutation::Delete(_) => MutationType::Delete, Mutation::Lock(_) => MutationType::Lock, Mutation::Insert(_) => MutationType::Insert, _ => MutationType::Other, } } pub fn into_key_value(self) -> (Key, Option<Value>) { match self { Mutation::Put((key, value)) => (key, Some(value)), Mutation::Delete(key) => (key, None), Mutation::Lock(key) => (key, None), Mutation::Insert((key, value)) => (key, Some(value)), Mutation::CheckNotExists(key) => (key, None), } } pub fn should_not_exists(&self) -> bool { matches!(self, Mutation::Insert(_) | Mutation::CheckNotExists(_)) } pub fn should_not_write(&self) -> bool { matches!(self, Mutation::CheckNotExists(_)) } } impl From<kvrpcpb::Mutation> for Mutation { fn from(mut m: kvrpcpb::Mutation) -> Mutation { match m.get_op() { kvrpcpb::Op::Put => Mutation::Put((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::Del => Mutation::Delete(Key::from_raw(m.get_key())), kvrpcpb::Op::Lock => Mutation::Lock(Key::from_raw(m.get_key())), kvrpcpb::Op::Insert => Mutation::Insert((Key::from_raw(m.get_key()), m.take_value())), kvrpcpb::Op::CheckNotExists => Mutation::CheckNotExists(Key::from_raw(m.get_key())), _ => panic!("mismatch Op in prewrite mutations"), } } } /// `OldValue` is used by cdc to read the previous value associated with some key during the prewrite process #[derive(Debug, Clone, PartialEq)] pub enum OldValue { /// A real `OldValue` Value { value: Value }, /// A timestamp of an old value in case a value is not inlined in Write ValueTimeStamp { start_ts: TimeStamp }, /// `None` means we don't found a previous value None, /// `Unspecified` means one of the following: /// - The user doesn't care about the previous value /// - We don't sure if there is a previous value Unspecified, } impl Default for OldValue { fn default() -> Self { OldValue::Unspecified } } impl OldValue { pub fn valid(&self) -> bool { !matches!(self, OldValue::Unspecified) } pub fn size(&self) -> usize { let value_size = match self { OldValue::Value { value } => value.len(), _ => 0, }; value_size + std::mem::size_of::<OldValue>() } } // Returned by MvccTxn when extra_op is set to kvrpcpb::ExtraOp::ReadOldValue. // key with current ts -> (short value of the prev txn, start ts of the prev txn). // The value of the map will be None when the mutation is `Insert`. // MutationType is the type of mutation of the current write. pub type OldValues = HashMap<Key, (OldValue, Option<MutationType>)>; // Extra data fields filled by kvrpcpb::ExtraOp. #[derive(Default, Debug, Clone)] pub struct TxnExtra { pub old_values: OldValues, // Marks that this transaction is a 1PC transaction. RaftKv should set this flag // in the raft command request. pub one_pc: bool, } impl TxnExtra { pub fn is_empty(&self) -> bool { self.old_values.is_empty() } } pub trait TxnExtraScheduler: Send + Sync { fn schedule(&self, txn_extra: TxnExtra); } bitflags! { /// Additional flags for a write batch. /// They should be set in the `flags` field in `RaftRequestHeader`. pub struct WriteBatchFlags: u64 { /// Indicates this request is from a 1PC transaction. /// It helps CDC recognize 1PC transactions and handle them correctly. const ONE_PC = 0b00000001; /// Indicates this request is from a stale read-only transaction. const STALE_READ = 0b00000010; } } impl WriteBatchFlags { /// Convert from underlying bit representation /// panic if it contains bits that do not correspond to a flag pub fn from_bits_check(bits: u64) -> WriteBatchFlags { match WriteBatchFlags::from_bits(bits) { None => panic!("unrecognized flags: {:b}", bits), // zero or more flags Some(f) => f, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_flags() { assert!(WriteBatchFlags::from_bits_check(0).is_empty()); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::ONE_PC.bits()), WriteBatchFlags::ONE_PC ); assert_eq!( WriteBatchFlags::from_bits_check(WriteBatchFlags::STALE_READ.bits()), WriteBatchFlags::STALE_READ ); } #[test] fn test_flags_panic() { for _ in 0..100 { assert!( panic_hook::recover_safe(|| { // r must be an invalid flags if it is not zero let r = rand::random::<u64>() &!WriteBatchFlags::all().bits(); WriteBatchFlags::from_bits_check(r); if r == 0 { panic!("panic for zero"); } }) .is_err() ); } } #[test] fn test_is_user_key_eq() { // make a short name to keep format for the test. fn eq(a: &[u8], b: &[u8]) -> bool { Key::is_user_key_eq(a, b) } assert_eq!(false, eq(b"", b"")); assert_eq!(false, eq(b"12345", b"")); assert_eq!(true, eq(b"12345678", b"")); assert_eq!(true, eq(b"x12345678", b"x")); assert_eq!(false, eq(b"x12345", b"x")); // user key len == 3 assert_eq!(true, eq(b"xyz12345678", b"xyz")); assert_eq!(true, eq(b"xyz________", b"xyz")); assert_eq!(false, eq(b"xyy12345678", b"xyz")); assert_eq!(false, eq(b"yyz12345678", b"xyz")); assert_eq!(false, eq(b"xyz12345678", b"xy")); assert_eq!(false, eq(b"xyy12345678", b"xy")); assert_eq!(false, eq(b"yyz12345678", b"xy")); // user key len == 7 assert_eq!(true, eq(b"abcdefg12345678", b"abcdefg")); assert_eq!(true, eq(b"abcdefgzzzzzzzz", b"abcdefg")); assert_eq!(false, eq(b"abcdefg12345678", b"abcdef")); assert_eq!(false, eq(b"abcdefg12345678", b"bcdefg")); assert_eq!(false, eq(b"abcdefv12345678", b"abcdefg")); assert_eq!(false, eq(b"vbcdefg12345678", b"abcdefg")); assert_eq!(false, eq(b"abccefg12345678", b"abcdefg")); // user key len == 8 assert_eq!(true, eq(b"abcdefgh12345678", b"abcdefgh")); assert_eq!(true, eq(b"abcdefghyyyyyyyy", b"abcdefgh")); assert_eq!(false, eq(b"abcdefgh12345678", b"abcdefg")); assert_eq!(false, eq(b"abcdefgh12345678", b"bcdefgh")); assert_eq!(false, eq(b"abcdefgz12345678", b"abcdefgh")); assert_eq!(false, eq(b"zbcdefgh12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcddfgh12345678", b"abcdefgh")); // user key len == 9 assert_eq!(true, eq(b"abcdefghi12345678", b"abcdefghi")); assert_eq!(true, eq(b"abcdefghixxxxxxxx", b"abcdefghi")); assert_eq!(false, eq(b"abcdefghi12345678", b"abcdefgh")); assert_eq!(false, eq(b"abcdefghi12345678", b"bcdefghi")); assert_eq!(false, eq(b"abcdefghy12345678", b"abcdefghi")); assert_eq!(false, eq(b"ybcdefghi12345678", b"abcdefghi")); assert_eq!(false, eq(b"abcddfghi12345678", b"abcdefghi")); // user key len == 11 assert_eq!(true, eq(b"abcdefghijk87654321", b"abcdefghijk")); assert_eq!(true, eq(b"abcdefghijkabcdefgh", b"abcdefghijk")); assert_eq!(false, eq(b"abcdefghijk87654321", b"abcdefghij")); assert_eq!(false, eq(b"abcdefghijk87654321", b"bcdefghijk")); assert_eq!(false, eq(b"abcdefghijx87654321", b"abcdefghijk")); assert_eq!(false, eq(b"xbcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abxdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"axcdefghijk87654321", b"abcdefghijk")); assert_eq!(false, eq(b"abcdeffhijk87654321", b"abcdefghijk")); } #[test] fn test_is_encoded_from() { for raw_len in 0..=24 { let raw: Vec<u8> = (0..raw_len).collect(); let encoded = Key::from_raw(&raw); assert!(encoded.is_encoded_from(&raw)); let encoded_len = encoded.as_encoded().len(); // Should return false if we modify one byte in raw for i in 0..raw.len() { let mut invalid_raw = raw.clone(); invalid_raw[i] = raw[i].wrapping_add(1); assert!(!encoded.is_encoded_from(&invalid_raw)); } // Should return false if we modify one byte in encoded for i in 0..encoded_len { let mut invalid_encoded = encoded.clone(); invalid_encoded.0[i] = encoded.0[i].wrapping_add(1); assert!(!invalid_encoded.is_encoded_from(&raw)); } // Should return false if encoded length is not a multiple of 9 let mut invalid_encoded = encoded.clone(); invalid_encoded.0.pop(); assert!(!invalid_encoded.is_encoded_from(&raw)); // Should return false if encoded has less or more chunks let shorter_encoded = Key::from_encoded_slice(&encoded.0[..encoded_len - 9]); assert!(!shorter_encoded.is_encoded_from(&raw)); let mut longer_encoded = encoded.as_encoded().clone(); longer_encoded.extend(&[0, 0, 0, 0, 0, 0, 0, 0, 0xFF]); let longer_encoded = Key::from_encoded(longer_encoded); assert!(!longer_encoded.is_encoded_from(&raw)); // Should return false if raw is longer or shorter
truncate_ts
identifier_name
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub struct Mutex<T: Sized> { inner: Arc<MutexInner<T>>, } struct MutexInner<T: Sized> { raw: RawMutex, data: UnsafeCell<T>, } struct RawMutex { state: AtomicBool, } unsafe impl<T: Send> Send for Mutex<T> {} unsafe impl<T: Send> Sync for Mutex<T> {} unsafe impl<T: Send> Send for MutexInner<T> {} unsafe impl<T: Send> Sync for MutexInner<T> {} pub struct AsyncMutexGuard<T: Sized> { mutex: Arc<MutexInner<T>> } pub struct MutexGuard<T: Sized> { mutex: Arc<MutexInner<T>>, } impl RawMutex { fn new() -> RawMutex { RawMutex { state: AtomicBool::new(false), } } fn try_lock(&self) -> bool { let prev_val = self.state.compare_and_swap(false, true, Ordering::Relaxed); let success = prev_val == false; //println!("raw locking {}", prev_val); return success; } fn lock(&self) { while self.state.compare_and_swap(false, true, Ordering::Relaxed) { while self.state.load(Ordering::Relaxed) { cpu_relax(); } } } fn unlock(&self) { assert!(self.state.compare_and_swap(true, false, Ordering::Relaxed)) } } impl<T: Sized> Future for AsyncMutexGuard<T> { type Item = MutexGuard<T>; type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if self.mutex.raw.try_lock() { Ok(Async::Ready(MutexGuard { mutex: self.mutex.clone(), })) } else
} } impl<T> Mutex<T> { pub fn new(val: T) -> Mutex<T> { Mutex { inner: Arc::new(MutexInner { raw: RawMutex::new(), data: UnsafeCell::new(val), }), } } pub fn lock_async(&self) -> AsyncMutexGuard<T> { AsyncMutexGuard { mutex: self.inner.clone(), } } pub fn lock(&self) -> MutexGuard<T> { self.inner.raw.lock(); MutexGuard { mutex: self.inner.clone(), } } } impl<T> MutexGuard<T> { #[inline] pub fn mutate(&self) -> &mut T { unsafe { &mut *self.mutex.data.get() } } } impl<T> Deref for MutexGuard<T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.mutex.data.get() } } } impl<T> DerefMut for MutexGuard<T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.mutate() } } impl<T: Sized> Drop for MutexGuard<T> { #[inline] fn drop(&mut self) { self.mutex.raw.unlock(); } } #[cfg(test)] mod tests { extern crate rayon; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); use self::rayon::iter::IntoParallelIterator; use self::rayon::prelude::*; use super::*; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use utils::fut_exec::wait; #[test] fn basic() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); mutex .lock_async() .map(|mut m| { m.insert(1, 2); m.insert(2, 3) }) .wait() .unwrap(); mutex .lock_async() .map(|m| assert_eq!(m.get(&1).unwrap(), &2)) .wait() .unwrap(); assert_eq!(*mutex.lock().get(&1).unwrap(), 2); assert_eq!(*mutex.lock().get(&2).unwrap(), 3); } #[test] fn parallel() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); (0..1000).collect::<Vec<_>>().into_par_iter().for_each(|i| { wait(mutex.lock_async().map(move |mut m| { m.insert(i, i + 1); m.insert(i + 1, i + 2); })) .unwrap(); wait( mutex .lock_async() .map(move |m| assert_eq!(m.get(&i).unwrap(), &(i + 1))), ) .unwrap(); }); (0..1000).for_each(|i| { assert_eq!(*mutex.lock().get(&i).unwrap(), i + 1); assert_eq!(*mutex.lock().get(&(i + 1)).unwrap(), i + 2); }) } #[test] fn smoke() { let m = Mutex::new(()); drop(m.lock()); drop(m.lock()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); let _t = thread::spawn(move || { let lock = arc2.lock(); let lock2 = lock.lock(); assert_eq!(*lock2, 1); tx.send(()).unwrap(); }); rx.recv().unwrap(); } #[test] fn test_mutexguard_send() { fn send<T: Send>(_: T) {} let mutex = Mutex::new(()); send(mutex.lock()); } #[test] fn test_mutexguard_sync() { fn sync<T: Sync>(_: T) {} let mutex = Mutex::new(()); sync(mutex.lock()); } #[test] fn lots_and_lots() { const J: u32 = 1000; const K: u32 = 3; let m = Arc::new(Mutex::new(0)); fn inc(m: &Mutex<u32>) { for _ in 0..J { *m.lock() += 1; } } let (tx, rx) = channel(); for _ in 0..K { let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); } drop(tx); for _ in 0..2 * K { rx.recv().unwrap(); } assert_eq!(*m.lock(), J * K * 2); } }
{ task::current().notify(); Ok(Async::NotReady) }
conditional_block
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub struct Mutex<T: Sized> { inner: Arc<MutexInner<T>>, } struct MutexInner<T: Sized> { raw: RawMutex, data: UnsafeCell<T>, } struct RawMutex { state: AtomicBool, } unsafe impl<T: Send> Send for Mutex<T> {} unsafe impl<T: Send> Sync for Mutex<T> {} unsafe impl<T: Send> Send for MutexInner<T> {} unsafe impl<T: Send> Sync for MutexInner<T> {} pub struct AsyncMutexGuard<T: Sized> { mutex: Arc<MutexInner<T>> } pub struct MutexGuard<T: Sized> { mutex: Arc<MutexInner<T>>, } impl RawMutex { fn new() -> RawMutex { RawMutex { state: AtomicBool::new(false), } } fn try_lock(&self) -> bool { let prev_val = self.state.compare_and_swap(false, true, Ordering::Relaxed); let success = prev_val == false; //println!("raw locking {}", prev_val); return success; } fn lock(&self) { while self.state.compare_and_swap(false, true, Ordering::Relaxed) { while self.state.load(Ordering::Relaxed) { cpu_relax(); } } } fn unlock(&self) { assert!(self.state.compare_and_swap(true, false, Ordering::Relaxed)) } } impl<T: Sized> Future for AsyncMutexGuard<T> { type Item = MutexGuard<T>; type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if self.mutex.raw.try_lock() { Ok(Async::Ready(MutexGuard { mutex: self.mutex.clone(), })) } else { task::current().notify(); Ok(Async::NotReady) } } } impl<T> Mutex<T> { pub fn new(val: T) -> Mutex<T> { Mutex { inner: Arc::new(MutexInner { raw: RawMutex::new(), data: UnsafeCell::new(val), }), } } pub fn lock_async(&self) -> AsyncMutexGuard<T> { AsyncMutexGuard { mutex: self.inner.clone(), } } pub fn lock(&self) -> MutexGuard<T> { self.inner.raw.lock(); MutexGuard { mutex: self.inner.clone(), } } } impl<T> MutexGuard<T> { #[inline] pub fn mutate(&self) -> &mut T { unsafe { &mut *self.mutex.data.get() } } } impl<T> Deref for MutexGuard<T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.mutex.data.get() } } } impl<T> DerefMut for MutexGuard<T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.mutate() } } impl<T: Sized> Drop for MutexGuard<T> { #[inline] fn drop(&mut self) { self.mutex.raw.unlock(); } } #[cfg(test)] mod tests { extern crate rayon; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); use self::rayon::iter::IntoParallelIterator; use self::rayon::prelude::*; use super::*; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use utils::fut_exec::wait; #[test] fn basic() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); mutex .lock_async() .map(|mut m| { m.insert(1, 2); m.insert(2, 3) }) .wait() .unwrap(); mutex .lock_async() .map(|m| assert_eq!(m.get(&1).unwrap(), &2)) .wait() .unwrap(); assert_eq!(*mutex.lock().get(&1).unwrap(), 2); assert_eq!(*mutex.lock().get(&2).unwrap(), 3); } #[test] fn parallel() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); (0..1000).collect::<Vec<_>>().into_par_iter().for_each(|i| { wait(mutex.lock_async().map(move |mut m| { m.insert(i, i + 1); m.insert(i + 1, i + 2); })) .unwrap(); wait( mutex .lock_async() .map(move |m| assert_eq!(m.get(&i).unwrap(), &(i + 1))), ) .unwrap(); });
#[test] fn smoke() { let m = Mutex::new(()); drop(m.lock()); drop(m.lock()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); let _t = thread::spawn(move || { let lock = arc2.lock(); let lock2 = lock.lock(); assert_eq!(*lock2, 1); tx.send(()).unwrap(); }); rx.recv().unwrap(); } #[test] fn test_mutexguard_send() { fn send<T: Send>(_: T) {} let mutex = Mutex::new(()); send(mutex.lock()); } #[test] fn test_mutexguard_sync() { fn sync<T: Sync>(_: T) {} let mutex = Mutex::new(()); sync(mutex.lock()); } #[test] fn lots_and_lots() { const J: u32 = 1000; const K: u32 = 3; let m = Arc::new(Mutex::new(0)); fn inc(m: &Mutex<u32>) { for _ in 0..J { *m.lock() += 1; } } let (tx, rx) = channel(); for _ in 0..K { let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); } drop(tx); for _ in 0..2 * K { rx.recv().unwrap(); } assert_eq!(*m.lock(), J * K * 2); } }
(0..1000).for_each(|i| { assert_eq!(*mutex.lock().get(&i).unwrap(), i + 1); assert_eq!(*mutex.lock().get(&(i + 1)).unwrap(), i + 2); }) }
random_line_split
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub struct Mutex<T: Sized> { inner: Arc<MutexInner<T>>, } struct MutexInner<T: Sized> { raw: RawMutex, data: UnsafeCell<T>, } struct RawMutex { state: AtomicBool, } unsafe impl<T: Send> Send for Mutex<T> {} unsafe impl<T: Send> Sync for Mutex<T> {} unsafe impl<T: Send> Send for MutexInner<T> {} unsafe impl<T: Send> Sync for MutexInner<T> {} pub struct AsyncMutexGuard<T: Sized> { mutex: Arc<MutexInner<T>> } pub struct MutexGuard<T: Sized> { mutex: Arc<MutexInner<T>>, } impl RawMutex { fn new() -> RawMutex { RawMutex { state: AtomicBool::new(false), } } fn try_lock(&self) -> bool { let prev_val = self.state.compare_and_swap(false, true, Ordering::Relaxed); let success = prev_val == false; //println!("raw locking {}", prev_val); return success; } fn lock(&self) { while self.state.compare_and_swap(false, true, Ordering::Relaxed) { while self.state.load(Ordering::Relaxed) { cpu_relax(); } } } fn unlock(&self) { assert!(self.state.compare_and_swap(true, false, Ordering::Relaxed)) } } impl<T: Sized> Future for AsyncMutexGuard<T> { type Item = MutexGuard<T>; type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if self.mutex.raw.try_lock() { Ok(Async::Ready(MutexGuard { mutex: self.mutex.clone(), })) } else { task::current().notify(); Ok(Async::NotReady) } } } impl<T> Mutex<T> { pub fn new(val: T) -> Mutex<T> { Mutex { inner: Arc::new(MutexInner { raw: RawMutex::new(), data: UnsafeCell::new(val), }), } } pub fn lock_async(&self) -> AsyncMutexGuard<T> { AsyncMutexGuard { mutex: self.inner.clone(), } } pub fn lock(&self) -> MutexGuard<T>
} impl<T> MutexGuard<T> { #[inline] pub fn mutate(&self) -> &mut T { unsafe { &mut *self.mutex.data.get() } } } impl<T> Deref for MutexGuard<T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.mutex.data.get() } } } impl<T> DerefMut for MutexGuard<T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.mutate() } } impl<T: Sized> Drop for MutexGuard<T> { #[inline] fn drop(&mut self) { self.mutex.raw.unlock(); } } #[cfg(test)] mod tests { extern crate rayon; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); use self::rayon::iter::IntoParallelIterator; use self::rayon::prelude::*; use super::*; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use utils::fut_exec::wait; #[test] fn basic() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); mutex .lock_async() .map(|mut m| { m.insert(1, 2); m.insert(2, 3) }) .wait() .unwrap(); mutex .lock_async() .map(|m| assert_eq!(m.get(&1).unwrap(), &2)) .wait() .unwrap(); assert_eq!(*mutex.lock().get(&1).unwrap(), 2); assert_eq!(*mutex.lock().get(&2).unwrap(), 3); } #[test] fn parallel() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); (0..1000).collect::<Vec<_>>().into_par_iter().for_each(|i| { wait(mutex.lock_async().map(move |mut m| { m.insert(i, i + 1); m.insert(i + 1, i + 2); })) .unwrap(); wait( mutex .lock_async() .map(move |m| assert_eq!(m.get(&i).unwrap(), &(i + 1))), ) .unwrap(); }); (0..1000).for_each(|i| { assert_eq!(*mutex.lock().get(&i).unwrap(), i + 1); assert_eq!(*mutex.lock().get(&(i + 1)).unwrap(), i + 2); }) } #[test] fn smoke() { let m = Mutex::new(()); drop(m.lock()); drop(m.lock()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); let _t = thread::spawn(move || { let lock = arc2.lock(); let lock2 = lock.lock(); assert_eq!(*lock2, 1); tx.send(()).unwrap(); }); rx.recv().unwrap(); } #[test] fn test_mutexguard_send() { fn send<T: Send>(_: T) {} let mutex = Mutex::new(()); send(mutex.lock()); } #[test] fn test_mutexguard_sync() { fn sync<T: Sync>(_: T) {} let mutex = Mutex::new(()); sync(mutex.lock()); } #[test] fn lots_and_lots() { const J: u32 = 1000; const K: u32 = 3; let m = Arc::new(Mutex::new(0)); fn inc(m: &Mutex<u32>) { for _ in 0..J { *m.lock() += 1; } } let (tx, rx) = channel(); for _ in 0..K { let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); } drop(tx); for _ in 0..2 * K { rx.recv().unwrap(); } assert_eq!(*m.lock(), J * K * 2); } }
{ self.inner.raw.lock(); MutexGuard { mutex: self.inner.clone(), } }
identifier_body
mutex.rs
// a simple spin lock based async mutex use super::cpu_relax; use futures::prelude::*; use futures::task; use std::cell::RefCell; use std::cell::UnsafeCell; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; #[derive(Clone)] pub struct Mutex<T: Sized> { inner: Arc<MutexInner<T>>, } struct MutexInner<T: Sized> { raw: RawMutex, data: UnsafeCell<T>, } struct RawMutex { state: AtomicBool, } unsafe impl<T: Send> Send for Mutex<T> {} unsafe impl<T: Send> Sync for Mutex<T> {} unsafe impl<T: Send> Send for MutexInner<T> {} unsafe impl<T: Send> Sync for MutexInner<T> {} pub struct AsyncMutexGuard<T: Sized> { mutex: Arc<MutexInner<T>> } pub struct MutexGuard<T: Sized> { mutex: Arc<MutexInner<T>>, } impl RawMutex { fn new() -> RawMutex { RawMutex { state: AtomicBool::new(false), } } fn try_lock(&self) -> bool { let prev_val = self.state.compare_and_swap(false, true, Ordering::Relaxed); let success = prev_val == false; //println!("raw locking {}", prev_val); return success; } fn
(&self) { while self.state.compare_and_swap(false, true, Ordering::Relaxed) { while self.state.load(Ordering::Relaxed) { cpu_relax(); } } } fn unlock(&self) { assert!(self.state.compare_and_swap(true, false, Ordering::Relaxed)) } } impl<T: Sized> Future for AsyncMutexGuard<T> { type Item = MutexGuard<T>; type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if self.mutex.raw.try_lock() { Ok(Async::Ready(MutexGuard { mutex: self.mutex.clone(), })) } else { task::current().notify(); Ok(Async::NotReady) } } } impl<T> Mutex<T> { pub fn new(val: T) -> Mutex<T> { Mutex { inner: Arc::new(MutexInner { raw: RawMutex::new(), data: UnsafeCell::new(val), }), } } pub fn lock_async(&self) -> AsyncMutexGuard<T> { AsyncMutexGuard { mutex: self.inner.clone(), } } pub fn lock(&self) -> MutexGuard<T> { self.inner.raw.lock(); MutexGuard { mutex: self.inner.clone(), } } } impl<T> MutexGuard<T> { #[inline] pub fn mutate(&self) -> &mut T { unsafe { &mut *self.mutex.data.get() } } } impl<T> Deref for MutexGuard<T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &*self.mutex.data.get() } } } impl<T> DerefMut for MutexGuard<T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.mutate() } } impl<T: Sized> Drop for MutexGuard<T> { #[inline] fn drop(&mut self) { self.mutex.raw.unlock(); } } #[cfg(test)] mod tests { extern crate rayon; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); use self::rayon::iter::IntoParallelIterator; use self::rayon::prelude::*; use super::*; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use utils::fut_exec::wait; #[test] fn basic() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); mutex .lock_async() .map(|mut m| { m.insert(1, 2); m.insert(2, 3) }) .wait() .unwrap(); mutex .lock_async() .map(|m| assert_eq!(m.get(&1).unwrap(), &2)) .wait() .unwrap(); assert_eq!(*mutex.lock().get(&1).unwrap(), 2); assert_eq!(*mutex.lock().get(&2).unwrap(), 3); } #[test] fn parallel() { let map: HashMap<i32, i32> = HashMap::new(); let mutex = Mutex::new(map); (0..1000).collect::<Vec<_>>().into_par_iter().for_each(|i| { wait(mutex.lock_async().map(move |mut m| { m.insert(i, i + 1); m.insert(i + 1, i + 2); })) .unwrap(); wait( mutex .lock_async() .map(move |m| assert_eq!(m.get(&i).unwrap(), &(i + 1))), ) .unwrap(); }); (0..1000).for_each(|i| { assert_eq!(*mutex.lock().get(&i).unwrap(), i + 1); assert_eq!(*mutex.lock().get(&(i + 1)).unwrap(), i + 2); }) } #[test] fn smoke() { let m = Mutex::new(()); drop(m.lock()); drop(m.lock()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); let _t = thread::spawn(move || { let lock = arc2.lock(); let lock2 = lock.lock(); assert_eq!(*lock2, 1); tx.send(()).unwrap(); }); rx.recv().unwrap(); } #[test] fn test_mutexguard_send() { fn send<T: Send>(_: T) {} let mutex = Mutex::new(()); send(mutex.lock()); } #[test] fn test_mutexguard_sync() { fn sync<T: Sync>(_: T) {} let mutex = Mutex::new(()); sync(mutex.lock()); } #[test] fn lots_and_lots() { const J: u32 = 1000; const K: u32 = 3; let m = Arc::new(Mutex::new(0)); fn inc(m: &Mutex<u32>) { for _ in 0..J { *m.lock() += 1; } } let (tx, rx) = channel(); for _ in 0..K { let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); } drop(tx); for _ in 0..2 * K { rx.recv().unwrap(); } assert_eq!(*m.lock(), J * K * 2); } }
lock
identifier_name
aggregate_ordering.rs
use crate::expression::functions::sql_function; use crate::sql_types::{IntoNullable, SingleValue, SqlOrd, SqlType};
impl<T> SqlOrdAggregate for T where T: SqlOrd + IntoNullable + SingleValue, T::Nullable: SqlType + SingleValue, { type Ret = T::Nullable; } sql_function! { /// Represents a SQL `MAX` function. This function can only take types which are /// ordered. /// /// # Examples /// /// ```rust /// # include!("../../doctest_setup.rs"); /// # use diesel::dsl::*; /// # /// # fn main() { /// # use schema::animals::dsl::*; /// # let connection = establish_connection(); /// assert_eq!(Ok(Some(8)), animals.select(max(legs)).first(&connection)); /// # } #[aggregate] fn max<ST: SqlOrdAggregate>(expr: ST) -> ST::Ret; } sql_function! { /// Represents a SQL `MIN` function. This function can only take types which are /// ordered. /// /// # Examples /// /// ```rust /// # include!("../../doctest_setup.rs"); /// # use diesel::dsl::*; /// # /// # fn main() { /// # use schema::animals::dsl::*; /// # let connection = establish_connection(); /// assert_eq!(Ok(Some(4)), animals.select(min(legs)).first(&connection)); /// # } #[aggregate] fn min<ST: SqlOrdAggregate>(expr: ST) -> ST::Ret; }
pub trait SqlOrdAggregate: SingleValue { type Ret: SqlType + SingleValue; }
random_line_split
tee.rs
#![crate_name = "tee"] #![feature(phase)] #![feature(macro_rules)] /* * This file is part of the uutils coreutils package. * * (c) Aleksander Bielawski <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[phase(plugin, link)] extern crate log; use std::io::{println, stdin, stdout, Append, File, Truncate, Write}; use std::io::{IoResult}; use std::io::util::{copy, NullWriter, MultiWriter}; use std::os; use getopts::{getopts, optflag, usage}; static NAME: &'static str = "tee"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> int { match options(args.as_slice()).and_then(exec) { Ok(_) => 0, Err(_) => 1 } } #[allow(dead_code)] struct Options { program: String, append: bool, ignore_interrupts: bool, print_and_exit: Option<String>, files: Box<Vec<Path>> } fn options(args: &[String]) -> Result<Options, ()> { let opts = [ optflag("a", "append", "append to the given FILEs, do not overwrite"), optflag("i", "ignore-interrupts", "ignore interrupt signals"), optflag("h", "help", "display this help and exit"), optflag("V", "version", "output version information and exit"), ]; let args: Vec<String> = args.iter().map(|x| x.to_string()).collect(); getopts(args.tail(), &opts).map_err(|e| format!("{}", e)).and_then(|m| { let version = format!("{} {}", NAME, VERSION); let program = args[0].as_slice(); let arguments = "[OPTION]... [FILE]..."; let brief = "Copy standard input to each FILE, and also to standard output."; let comment = "If a FILE is -, copy again to standard output."; let help = format!("{}\n\nUsage:\n {} {}\n\n{}\n{}", version, program, arguments, usage(brief, &opts), comment); let mut names = m.free.clone().into_iter().collect::<Vec<String>>(); names.push("-".to_string()); let to_print = if m.opt_present("help") { Some(help) } else if m.opt_present("version") { Some(version) } else { None }; Ok(Options { program: program.to_string(), append: m.opt_present("append"), ignore_interrupts: m.opt_present("ignore-interrupts"), print_and_exit: to_print, files: box names.iter().map(|name| Path::new(name.clone())).collect() }) }).map_err(|message| warn(message.as_slice())) } fn exec(options: Options) -> Result<(), ()> { match options.print_and_exit { Some(text) => Ok(println(text.as_slice())), None => tee(options) } } fn tee(options: Options) -> Result<(), ()> { let writers = options.files.iter().map(|path| open(path, options.append)).collect(); let output = &mut MultiWriter::new(writers); let input = &mut NamedReader { inner: box stdin() as Box<Reader> }; if copy(input, output).is_err() || output.flush().is_err() { Err(()) } else { Ok(()) } } fn open(path: &Path, append: bool) -> Box<Writer+'static> { let inner = if *path == Path::new("-") { box stdout() as Box<Writer> } else { let mode = if append { Append } else { Truncate }; match File::open_mode(path, mode, Write) { Ok(file) => box file as Box<Writer>, Err(_) => box NullWriter as Box<Writer> } }; box NamedWriter { inner: inner, path: box path.clone() } as Box<Writer> } struct
{ inner: Box<Writer+'static>, path: Box<Path> } impl Writer for NamedWriter { fn write(&mut self, buf: &[u8]) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.write(buf); if val.is_err() { self.inner = box NullWriter as Box<Writer>; } val }) } fn flush(&mut self) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.flush(); if val.is_err() { self.inner = box NullWriter as Box<Writer>; } val }) } } struct NamedReader { inner: Box<Reader+'static> } impl Reader for NamedReader { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { with_path(&Path::new("stdin"), || { self.inner.read(buf) }) } } fn with_path<T>(path: &Path, cb: || -> IoResult<T>) -> IoResult<T> { match cb() { Err(f) => { warn(format!("{}: {}", path.display(), f.to_string()).as_slice()); Err(f) } okay => okay } } fn warn(message: &str) { error!("{}: {}", os::args()[0], message); }
NamedWriter
identifier_name
tee.rs
#![crate_name = "tee"] #![feature(phase)] #![feature(macro_rules)] /* * This file is part of the uutils coreutils package. * * (c) Aleksander Bielawski <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[phase(plugin, link)] extern crate log; use std::io::{println, stdin, stdout, Append, File, Truncate, Write}; use std::io::{IoResult}; use std::io::util::{copy, NullWriter, MultiWriter}; use std::os; use getopts::{getopts, optflag, usage}; static NAME: &'static str = "tee"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> int { match options(args.as_slice()).and_then(exec) { Ok(_) => 0, Err(_) => 1 } } #[allow(dead_code)] struct Options { program: String, append: bool, ignore_interrupts: bool, print_and_exit: Option<String>, files: Box<Vec<Path>> } fn options(args: &[String]) -> Result<Options, ()> { let opts = [ optflag("a", "append", "append to the given FILEs, do not overwrite"), optflag("i", "ignore-interrupts", "ignore interrupt signals"), optflag("h", "help", "display this help and exit"), optflag("V", "version", "output version information and exit"), ]; let args: Vec<String> = args.iter().map(|x| x.to_string()).collect(); getopts(args.tail(), &opts).map_err(|e| format!("{}", e)).and_then(|m| { let version = format!("{} {}", NAME, VERSION); let program = args[0].as_slice(); let arguments = "[OPTION]... [FILE]..."; let brief = "Copy standard input to each FILE, and also to standard output."; let comment = "If a FILE is -, copy again to standard output."; let help = format!("{}\n\nUsage:\n {} {}\n\n{}\n{}", version, program, arguments, usage(brief, &opts), comment); let mut names = m.free.clone().into_iter().collect::<Vec<String>>(); names.push("-".to_string()); let to_print = if m.opt_present("help") { Some(help) } else if m.opt_present("version") { Some(version) } else { None }; Ok(Options { program: program.to_string(), append: m.opt_present("append"), ignore_interrupts: m.opt_present("ignore-interrupts"), print_and_exit: to_print, files: box names.iter().map(|name| Path::new(name.clone())).collect() }) }).map_err(|message| warn(message.as_slice())) } fn exec(options: Options) -> Result<(), ()> { match options.print_and_exit { Some(text) => Ok(println(text.as_slice())), None => tee(options) } } fn tee(options: Options) -> Result<(), ()> { let writers = options.files.iter().map(|path| open(path, options.append)).collect(); let output = &mut MultiWriter::new(writers); let input = &mut NamedReader { inner: box stdin() as Box<Reader> }; if copy(input, output).is_err() || output.flush().is_err() { Err(()) } else { Ok(()) } } fn open(path: &Path, append: bool) -> Box<Writer+'static> { let inner = if *path == Path::new("-") { box stdout() as Box<Writer> } else { let mode = if append { Append } else
; match File::open_mode(path, mode, Write) { Ok(file) => box file as Box<Writer>, Err(_) => box NullWriter as Box<Writer> } }; box NamedWriter { inner: inner, path: box path.clone() } as Box<Writer> } struct NamedWriter { inner: Box<Writer+'static>, path: Box<Path> } impl Writer for NamedWriter { fn write(&mut self, buf: &[u8]) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.write(buf); if val.is_err() { self.inner = box NullWriter as Box<Writer>; } val }) } fn flush(&mut self) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.flush(); if val.is_err() { self.inner = box NullWriter as Box<Writer>; } val }) } } struct NamedReader { inner: Box<Reader+'static> } impl Reader for NamedReader { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { with_path(&Path::new("stdin"), || { self.inner.read(buf) }) } } fn with_path<T>(path: &Path, cb: || -> IoResult<T>) -> IoResult<T> { match cb() { Err(f) => { warn(format!("{}: {}", path.display(), f.to_string()).as_slice()); Err(f) } okay => okay } } fn warn(message: &str) { error!("{}: {}", os::args()[0], message); }
{ Truncate }
conditional_block
tee.rs
#![crate_name = "tee"] #![feature(phase)] #![feature(macro_rules)] /* * This file is part of the uutils coreutils package. * * (c) Aleksander Bielawski <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; #[phase(plugin, link)] extern crate log; use std::io::{println, stdin, stdout, Append, File, Truncate, Write}; use std::io::{IoResult}; use std::io::util::{copy, NullWriter, MultiWriter}; use std::os; use getopts::{getopts, optflag, usage}; static NAME: &'static str = "tee"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> int { match options(args.as_slice()).and_then(exec) { Ok(_) => 0, Err(_) => 1 } } #[allow(dead_code)] struct Options {
program: String, append: bool, ignore_interrupts: bool, print_and_exit: Option<String>, files: Box<Vec<Path>> } fn options(args: &[String]) -> Result<Options, ()> { let opts = [ optflag("a", "append", "append to the given FILEs, do not overwrite"), optflag("i", "ignore-interrupts", "ignore interrupt signals"), optflag("h", "help", "display this help and exit"), optflag("V", "version", "output version information and exit"), ]; let args: Vec<String> = args.iter().map(|x| x.to_string()).collect(); getopts(args.tail(), &opts).map_err(|e| format!("{}", e)).and_then(|m| { let version = format!("{} {}", NAME, VERSION); let program = args[0].as_slice(); let arguments = "[OPTION]... [FILE]..."; let brief = "Copy standard input to each FILE, and also to standard output."; let comment = "If a FILE is -, copy again to standard output."; let help = format!("{}\n\nUsage:\n {} {}\n\n{}\n{}", version, program, arguments, usage(brief, &opts), comment); let mut names = m.free.clone().into_iter().collect::<Vec<String>>(); names.push("-".to_string()); let to_print = if m.opt_present("help") { Some(help) } else if m.opt_present("version") { Some(version) } else { None }; Ok(Options { program: program.to_string(), append: m.opt_present("append"), ignore_interrupts: m.opt_present("ignore-interrupts"), print_and_exit: to_print, files: box names.iter().map(|name| Path::new(name.clone())).collect() }) }).map_err(|message| warn(message.as_slice())) } fn exec(options: Options) -> Result<(), ()> { match options.print_and_exit { Some(text) => Ok(println(text.as_slice())), None => tee(options) } } fn tee(options: Options) -> Result<(), ()> { let writers = options.files.iter().map(|path| open(path, options.append)).collect(); let output = &mut MultiWriter::new(writers); let input = &mut NamedReader { inner: box stdin() as Box<Reader> }; if copy(input, output).is_err() || output.flush().is_err() { Err(()) } else { Ok(()) } } fn open(path: &Path, append: bool) -> Box<Writer+'static> { let inner = if *path == Path::new("-") { box stdout() as Box<Writer> } else { let mode = if append { Append } else { Truncate }; match File::open_mode(path, mode, Write) { Ok(file) => box file as Box<Writer>, Err(_) => box NullWriter as Box<Writer> } }; box NamedWriter { inner: inner, path: box path.clone() } as Box<Writer> } struct NamedWriter { inner: Box<Writer+'static>, path: Box<Path> } impl Writer for NamedWriter { fn write(&mut self, buf: &[u8]) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.write(buf); if val.is_err() { self.inner = box NullWriter as Box<Writer>; } val }) } fn flush(&mut self) -> IoResult<()> { with_path(&*self.path.clone(), || { let val = self.inner.flush(); if val.is_err() { self.inner = box NullWriter as Box<Writer>; } val }) } } struct NamedReader { inner: Box<Reader+'static> } impl Reader for NamedReader { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { with_path(&Path::new("stdin"), || { self.inner.read(buf) }) } } fn with_path<T>(path: &Path, cb: || -> IoResult<T>) -> IoResult<T> { match cb() { Err(f) => { warn(format!("{}: {}", path.display(), f.to_string()).as_slice()); Err(f) } okay => okay } } fn warn(message: &str) { error!("{}: {}", os::args()[0], message); }
random_line_split
pact_builder.rs
use pact_matching::models::*; use super::interaction_builder::InteractionBuilder; use crate::prelude::*; /// Builder for `Pact` objects. /// /// ``` /// use pact_consumer::prelude::*; /// use pact_consumer::*; /// /// let pact = PactBuilder::new("Greeting Client", "Greeting Server") /// .interaction("asks for a greeting", |i| { /// i.request.path("/greeting/hello"); /// i.response /// .header("Content-Type", "application/json") /// .json_body(json_pattern!({ "message": "hello" })); /// }) /// .build(); /// /// // The request method and response status default as follows. /// assert_eq!(pact.interactions[0].request.method, "GET"); /// assert_eq!(pact.interactions[0].response.status, 200); /// ```
pact: RequestResponsePact, } impl PactBuilder { /// Create a new `PactBuilder`, specifying the names of the service /// consuming the API and the service providing it. pub fn new<C, P>(consumer: C, provider: P) -> Self where C: Into<String>, P: Into<String>, { let mut pact = RequestResponsePact::default(); pact.consumer = Consumer { name: consumer.into(), }; pact.provider = Provider { name: provider.into(), }; PactBuilder { pact } } /// Add a new `Interaction` to the `Pact`. pub fn interaction<D, F>(&mut self, description: D, build_fn: F) -> &mut Self where D: Into<String>, F: FnOnce(&mut InteractionBuilder), { let mut interaction = InteractionBuilder::new(description.into()); build_fn(&mut interaction); self.push_interaction(interaction.build()) } /// Directly add a pre-built `Interaction` to our `Pact`. Normally it's /// easier to use `interaction` instead of this function. pub fn push_interaction(&mut self, interaction: RequestResponseInteraction) -> &mut Self { self.pact.interactions.push(interaction); self } /// Return the `Pact` we've built. pub fn build(&self) -> RequestResponsePact { self.pact.clone() } } impl StartMockServer for PactBuilder { fn start_mock_server(&self) -> ValidatingMockServer { ValidatingMockServer::start(self.build()) } }
pub struct PactBuilder {
random_line_split
pact_builder.rs
use pact_matching::models::*; use super::interaction_builder::InteractionBuilder; use crate::prelude::*; /// Builder for `Pact` objects. /// /// ``` /// use pact_consumer::prelude::*; /// use pact_consumer::*; /// /// let pact = PactBuilder::new("Greeting Client", "Greeting Server") /// .interaction("asks for a greeting", |i| { /// i.request.path("/greeting/hello"); /// i.response /// .header("Content-Type", "application/json") /// .json_body(json_pattern!({ "message": "hello" })); /// }) /// .build(); /// /// // The request method and response status default as follows. /// assert_eq!(pact.interactions[0].request.method, "GET"); /// assert_eq!(pact.interactions[0].response.status, 200); /// ``` pub struct PactBuilder { pact: RequestResponsePact, } impl PactBuilder { /// Create a new `PactBuilder`, specifying the names of the service /// consuming the API and the service providing it. pub fn new<C, P>(consumer: C, provider: P) -> Self where C: Into<String>, P: Into<String>, { let mut pact = RequestResponsePact::default(); pact.consumer = Consumer { name: consumer.into(), }; pact.provider = Provider { name: provider.into(), }; PactBuilder { pact } } /// Add a new `Interaction` to the `Pact`. pub fn interaction<D, F>(&mut self, description: D, build_fn: F) -> &mut Self where D: Into<String>, F: FnOnce(&mut InteractionBuilder), { let mut interaction = InteractionBuilder::new(description.into()); build_fn(&mut interaction); self.push_interaction(interaction.build()) } /// Directly add a pre-built `Interaction` to our `Pact`. Normally it's /// easier to use `interaction` instead of this function. pub fn
(&mut self, interaction: RequestResponseInteraction) -> &mut Self { self.pact.interactions.push(interaction); self } /// Return the `Pact` we've built. pub fn build(&self) -> RequestResponsePact { self.pact.clone() } } impl StartMockServer for PactBuilder { fn start_mock_server(&self) -> ValidatingMockServer { ValidatingMockServer::start(self.build()) } }
push_interaction
identifier_name
main.rs
use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn
(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); thread::sleep(Duration::from_millis(150)); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep(Duration::from_millis(1000)); println!("{} is done eating", self.name); } } struct Table { forks: Vec<Mutex<()>>, } fn main() { let table = Arc::new(Table { forks: vec![Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(())], }); let philosophers = vec![Philosopher::new("Judith Butler", 0, 1), Philosopher::new("Gilles Deleuze", 1, 2), Philosopher::new("Karl Marx", 2, 3), Philosopher::new("Emma Goldman", 3, 4), Philosopher::new("Michel Foucault", 0, 4)]; let handles: Vec<_> = philosophers .into_iter() .map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }) .collect(); // collect() can return any type, so Vec<_> is needed for let in the above for h in handles { h.join().unwrap(); } }
new
identifier_name
main.rs
use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); thread::sleep(Duration::from_millis(150)); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep(Duration::from_millis(1000)); println!("{} is done eating", self.name); } } struct Table { forks: Vec<Mutex<()>>, } fn main() { let table = Arc::new(Table { forks: vec![Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(())], }); let philosophers = vec![Philosopher::new("Judith Butler", 0, 1),
let handles: Vec<_> = philosophers .into_iter() .map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }) .collect(); // collect() can return any type, so Vec<_> is needed for let in the above for h in handles { h.join().unwrap(); } }
Philosopher::new("Gilles Deleuze", 1, 2), Philosopher::new("Karl Marx", 2, 3), Philosopher::new("Emma Goldman", 3, 4), Philosopher::new("Michel Foucault", 0, 4)];
random_line_split
fixed_bug_long_thin_box_one_shot_manifold3.rs
/*! * # Expected behaviour: * The box stands vertically until it falls asleep. * The box should not fall (horizontally) on the ground. * The box should not traverse the ground. * * # Symptoms: * The long, thin, box fails to collide with the plane: it just ignores it. * * # Cause: * The one shot contact manifold generator was incorrect in this case. This generator rotated the * object wrt its center to sample the contact manifold. If the object is long and the theoretical * contact surface is small, all contacts will be invalidated whenever the incremental contact * manifold will get a new point from the one-shot generator. * * # Solution: * Rotate the object wrt the contact center, not wrt the object center. * * # Limitations of the solution: * This will create only a three-points manifold for a small axis-alligned cube, instead of four. */ extern crate nalgebra as na; extern crate ncollide3d; extern crate nphysics3d; extern crate nphysics_testbed3d; use na::{Point3, Vector3}; use ncollide3d::shape::{Cuboid, Plane, ShapeHandle}; use nphysics3d::object::{ColliderDesc, RigidBodyDesc}; use nphysics3d::world::World; use nphysics_testbed3d::Testbed; fn main()
let geom = ShapeHandle::new(Cuboid::new(Vector3::new(rad, rad * 10.0, rad))); let collider_desc = ColliderDesc::new(geom).density(r!(1.0)); RigidBodyDesc::new() .collider(&collider_desc) .translation(Vector3::new(x, y, z)) .build(&mut world); /* * Set up the testbed. */ let mut testbed = Testbed::new(world); testbed.look_at(Point3::new(-30.0, 30.0, -30.0), Point3::new(0.0, 0.0, 0.0)); testbed.run(); }
{ /* * World */ let mut world = World::new(); world.set_gravity(Vector3::new(r!(0.0), r!(-9.81), r!(0.0))); /* * Plane */ let ground_shape = ShapeHandle::new(Plane::new(Vector3::y_axis())); ColliderDesc::new(ground_shape).build(&mut world); /* * Create the box */ let rad = r!(0.1); let x = rad; let y = rad + 10.0; let z = rad;
identifier_body