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 |
|---|---|---|---|---|
ub-nonnull.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (u32);
const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) };
//~^ ERROR it is undefined behavior to use this value
#[rustc_layout_scalar_valid_range_start(30)]
#[rustc_layout_scalar_valid_range_end(10)]
struct RestrictedRange2(u32);
const BAD_RANGE2: RestrictedRange2 = unsafe { RestrictedRange2(20) };
... | RestrictedRange1 | identifier_name |
lib.rs | #[derive(Debug, PartialEq)]
pub enum | {
InvalidInputBase,
InvalidOutputBase,
InvalidDigit(u32),
}
///
/// Convert a number between two bases.
///
/// A number is any slice of digits.
/// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize).
/// Bases are specified as unsigned integers.
///
/// Return an `Err(.)` if the conversio... | Error | identifier_name |
lib.rs | #[derive(Debug, PartialEq)]
pub enum Error {
InvalidInputBase,
InvalidOutputBase,
InvalidDigit(u32),
}
///
/// Convert a number between two bases.
///
/// A number is any slice of digits.
/// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize).
/// Bases are specified as unsigned integers.
/... | /// Input
/// number: &[4, 2]
/// from_base: 10
/// to_base: 2
/// Result
/// Ok(vec![1, 0, 1, 0, 1, 0])
///
/// The example corresponds to converting the number 42 from decimal
/// which is equivalent to 101010 in binary.
///
///
/// Notes:
/// * The empty slice ( "[]" ) is equal to the number 0.
/// * Never... | ///
/// Example: | random_line_split |
keyframes.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/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
use cssparser::{AtRuleP... | &self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse(input: &mut Parser) -> ... | pub fn percentages(&self) -> &[KeyframePercentage] { | random_line_split |
keyframes.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/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
use cssparser::{AtRuleP... |
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
... | {
block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
} | conditional_block |
keyframes.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/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
use cssparser::{AtRuleP... | <W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
let mut iter = self.selector.percentages().iter();
try!(iter.next().unwrap().to_css(dest));
for percentage in iter {
try!(write!(dest, ", "));
try!(percentage.to_css(dest));
... | to_css | identifier_name |
keyframes.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/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
use cssparser::{AtRuleP... |
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Debug, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub f... | {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = try!(input.expect_... | identifier_body |
frame.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use euclid::size::TypedSize2D;
use msg::constellation_msg::{FrameId, PipelineId};
use pipeline::Pipeline;
use scri... | None => {
warn!("Frame {:?} iterated after closure.", frame_id);
continue;
},
};
let pipeline = match self.pipelines.get(&frame.pipeline_id) {
Some(pipeline) => pipeline,
None => {
... | random_line_split | |
frame.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use euclid::size::TypedSize2D;
use msg::constellation_msg::{FrameId, PipelineId};
use pipeline::Pipeline;
use scri... | {
/// The frame id.
pub id: FrameId,
/// The size of the frame.
pub size: Option<TypedSize2D<f32, CSSPixel>>,
/// The timestamp for the current session history entry.
pub instant: Instant,
/// The pipeline for the current session history entry.
pub pipeline_id: PipelineId,
/// T... | Frame | identifier_name |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... | add_impls_for_keyword_enum!(StepPosition);
impl<H, V, D> TransformOrigin<H, V, D> {
/// Returns a new transform origin.
pub fn new(horizontal: H, vertical: V, depth: D) -> Self {
Self {
horizontal: horizontal,
vertical: vertical,
depth: depth,
}
}
}
impl... | random_line_split | |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... |
}
impl<Integer, Number> TimingFunction<Integer, Number> {
/// `ease`
#[inline]
pub fn ease() -> Self {
TimingFunction::Keyword(TimingKeyword::Ease)
}
}
impl<Integer, Number> ToCss for TimingFunction<Integer, Number>
where
Integer: ToCss,
Number: ToCss,
{
fn to_css<W>(&self, dest: ... | {
Self {
horizontal: horizontal,
vertical: vertical,
depth: depth,
}
} | identifier_body |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... | ,
TimingFunction::Frames(ref frames) => {
dest.write_str("frames(")?;
frames.to_css(dest)?;
dest.write_str(")")
},
}
}
}
impl TimingKeyword {
/// Returns the keyword as a quadruplet of Bezier point coordinates
/// `(x1, y1, x2,... | {
dest.write_str("steps(")?;
intervals.to_css(dest)?;
if position != StepPosition::End {
dest.write_str(", ")?;
position.to_css(dest)?;
}
dest.write_str(")")
} | conditional_block |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... | <Integer, Number> {
/// `linear | ease | ease-in | ease-out | ease-in-out`
Keyword(TimingKeyword),
/// `cubic-bezier(<number>, <number>, <number>, <number>)`
#[allow(missing_docs)]
CubicBezier { x1: Number, y1: Number, x2: Number, y2: Number },
/// `step-start | step-end | steps(<integer>, [ sta... | TimingFunction | identifier_name |
viewport.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! An adapter which makes widgets scrollable
use ShadowType;
use cast::GTK_VIEWPORT;
use ff... | pub fn get_shadow_type(&self) -> ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&self, ty: ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}... | let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.unwrap_pointer(), vadjustment.unwrap_pointer()) };
check_pointer!(tmp_pointer, Viewport)
}
| identifier_body |
viewport.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! An adapter which makes widgets scrollable
use ShadowType;
use cast::GTK_VIEWPORT;
use ff... | self, ty: ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!(Viewport);
impl_TraitWidget!(Viewport);
impl ::ContainerTrait for Viewport {}
impl ::BinTrait for Viewport {}
impl ::ScrollableTrait for Viewport {}
| t_shadow_type(& | identifier_name |
viewport.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! An adapter which makes widgets scrollable
use ShadowType;
use cast::GTK_VIEWPORT;
use ff... | }
pub fn get_shadow_type(&self) -> ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&self, ty: ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
... | impl Viewport {
pub fn new(hadjustment: &::Adjustment, vadjustment: &::Adjustment) -> Option<Viewport> {
let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.unwrap_pointer(), vadjustment.unwrap_pointer()) };
check_pointer!(tmp_pointer, Viewport) | random_line_split |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... | }
}
Ok(())
}
pub fn git_command(ctx: &mut Context, git: &GitInfo) -> Result<(), String>
{
try!(capsule::ensure_features(ctx, &[capsule::Git]));
let dest = PathBuf::from("/vagga/root").join(&git.path.rel());
let cache_path = try!(git_cache(&git.url));
try!(create_dir_all(&dest)
... | {
let mut cmd = Command::new("/usr/bin/git");
cmd.stdin(Stdio::null());
cmd.arg("--git-dir").arg(cache_path);
cmd.arg("--work-tree").arg(dest);
cmd.arg("reset").arg("--hard");
if let &Some(ref rev) = revision {
cmd.arg(&rev);
} else if let &Some(ref branch) = branch {
cmd.arg... | identifier_body |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... | "-exc".to_string(),
git.script.to_string()],
&workdir);
}
pub fn fetch_git_source(capsule: &mut capsule::State, settings: &Settings,
git: &GitSource)
-> Result<(), String>
{
try!(capsule::ensure(capsule, settings, &[capsule::Git]));
let cache_path = try!(git_cache(&git.url));
... | return run_command_at(ctx, &[
"/bin/sh".to_string(), | random_line_split |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... | (capsule: &mut capsule::State, settings: &Settings,
git: &GitSource)
-> Result<(), String>
{
try!(capsule::ensure(capsule, settings, &[capsule::Git]));
let cache_path = try!(git_cache(&git.url));
let dest = Path::new("/vagga/sources")
.join(cache_path.file_name().unwrap());
try!(create_di... | fetch_git_source | identifier_name |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... |
Ok(status) => {
return Err(format!("Command {:?} exited with code {}",
cmd, status));
}
Err(err) => {
return Err(format!("Error running {:?}: {}", cmd, err));
}
}
} else {
let tmppath = cache_path.w... | {} | conditional_block |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | mut left = mut_root.left.take();
Self::flatten_failed(&mut left);
let mut right = mut_root.right.take();
Self::flatten_failed(&mut right);
// while let Some(node) = left.take() {
// left = node.borrow_mut().right.take();
// mut_root.right = Some(node);
/... | rap().borrow_mut();
let | conditional_block |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | return;
}
let mut mut_root = root.as_mut().unwrap().borrow_mut();
let mut left = mut_root.left.take();
Self::flatten_failed(&mut left);
let mut right = mut_root.right.take();
Self::flatten_failed(&mut right);
// while let Some(node) = left.take() {
... | s_none() {
| identifier_name |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | ten() {
let mut root = build_one_node(TreeNode {
val: 1,
left: build_one_node(TreeNode {
val: 2,
left: build_one_node(TreeNode::new(3)),
right: build_one_node(TreeNode::new(4)),
}),
right: build_one_node(TreeNode {
... | mut_root = root.as_mut().unwrap().borrow_mut();
let mut left = mut_root.left.take();
Self::flatten_failed(&mut left);
let mut right = mut_root.right.take();
Self::flatten_failed(&mut right);
// while let Some(node) = left.take() {
// left = node.borrow_mut().right.ta... | identifier_body |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | left: None,
right: build_one_node(TreeNode {
val: 5,
left: None,
right: build_one_node(TreeNode::new(6)),
}),
}),
}),
... | val: 3,
left: None,
right: build_one_node(TreeNode {
val: 4, | random_line_split |
util.rs | /*
* Copyright 2015-2016 Ben Ashford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agree... | $ex
}
}
};
}
macro_rules! from {
($ft:ty, $dt:ident, $ev:ident, $pi:ident) => {
from_exp!($ft, $dt, $pi, $dt::$ev($pi));
};
($ft:ty, $dt:ident, $ev:ident) => {
from!($ft, $dt, $ev, from);
};
} | /// to that module
macro_rules! from_exp {
($ft:ty, $dt:ident, $pi:ident, $ex:expr) => {
impl From<$ft> for $dt {
fn from($pi: $ft) -> $dt { | random_line_split |
util.rs | /*
* Copyright 2015-2016 Ben Ashford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agree... |
}
/// Useful macro for adding a function to supply a value to an optional field
macro_rules! add_field {
($n:ident, $f:ident, $t:ty) => (
pub fn $n<T: Into<$t>>(mut self, val: T) -> Self {
self.$f = Some(val.into());
self
}
);
}
/// Useful macros for implementing `From... | {
let mut s = String::new();
for f in self {
s.push_str(f.as_ref());
s.push_str(join);
}
s.pop();
s
} | identifier_body |
util.rs | /*
* Copyright 2015-2016 Ben Ashford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agree... | (self, join: &str) -> String {
let mut s = String::new();
for f in self {
s.push_str(f.as_ref());
s.push_str(join);
}
s.pop();
s
}
}
/// Useful macro for adding a function to supply a value to an optional field
macro_rules! add_field {
($n:ident, ... | join | identifier_name |
issue-18412.rs | // Copyright 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 ... |
struct A(usize);
impl A {
fn bar(&self) -> usize { self.0 }
}
impl Foo for A {
fn foo(&self) -> usize { self.bar() }
}
fn main() {
let f = A::bar;
let g = Foo::foo;
let a = A(42);
assert_eq!(f(&a), g(&a));
} |
trait Foo {
fn foo(&self) -> usize;
} | random_line_split |
issue-18412.rs | // Copyright 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 ... | () {
let f = A::bar;
let g = Foo::foo;
let a = A(42);
assert_eq!(f(&a), g(&a));
}
| main | identifier_name |
trait-inheritance-self-in-supertype.rs | // Copyright 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 ... | (&self, other: &f64, epsilon: &f64) -> bool {
(*self - *other).abs() < *epsilon
}
}
impl Float for f64 {
fn two_pi() -> f64 { 6.28318530717958647692528676655900576_f64 }
}
fn compare<F:Float>(f1: F) -> bool {
let f2 = Float::two_pi();
f1.fuzzy_eq(&f2)
}
pub fn main() {
assert!(compare::<f... | fuzzy_eq_eps | identifier_name |
trait-inheritance-self-in-supertype.rs | // Copyright 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 ... | }
pub fn main() {
assert!(compare::<f32>(6.28318530717958647692528676655900576));
assert!(compare::<f32>(6.29));
assert!(compare::<f32>(6.3));
assert!(compare::<f32>(6.19));
assert!(!compare::<f32>(7.28318530717958647692528676655900576));
assert!(!compare::<f32>(6.18));
assert!(compare::<f... | random_line_split | |
trait-inheritance-self-in-supertype.rs | // Copyright 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 ... |
fn fuzzy_eq_eps(&self, other: &f32, epsilon: &f32) -> bool {
(*self - *other).abs() < *epsilon
}
}
impl Float for f32 {
fn two_pi() -> f32 { 6.28318530717958647692528676655900576_f32 }
}
impl FuzzyEq<f64> for f64 {
fn fuzzy_eq(&self, other: &f64) -> bool {
self.fuzzy_eq_eps(other, &(... | {
self.fuzzy_eq_eps(other, &(FUZZY_EPSILON as f32))
} | identifier_body |
issue-6892.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 | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// Ensures that destructors are run for expressions of the form "let _ = e;"
// where `e` is a type which requires a destructor.
// pretty-expanded FIXME #23616
struct Foo;
struct Bar { x: isize }
struct Baz(isize);
... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
issue-6892.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-MI... | (&mut self) {
unsafe { NUM_DROPS += 1; }
}
}
impl Drop for FooBar {
fn drop(&mut self) {
unsafe { NUM_DROPS += 1; }
}
}
fn main() {
assert_eq!(unsafe { NUM_DROPS }, 0);
{ let _x = Foo; }
assert_eq!(unsafe { NUM_DROPS }, 1);
{ let _x = Bar { x: 21 }; }
assert_eq!(unsafe {... | drop | identifier_name |
issue-6892.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-MI... | assert_eq!(unsafe { NUM_DROPS }, 11);
{ let _ = FooBar::_Bar(42); }
assert_eq!(unsafe { NUM_DROPS }, 12);
}
| {
assert_eq!(unsafe { NUM_DROPS }, 0);
{ let _x = Foo; }
assert_eq!(unsafe { NUM_DROPS }, 1);
{ let _x = Bar { x: 21 }; }
assert_eq!(unsafe { NUM_DROPS }, 2);
{ let _x = Baz(21); }
assert_eq!(unsafe { NUM_DROPS }, 3);
{ let _x = FooBar::_Foo(Foo); }
assert_eq!(unsafe { NUM_DROPS }, 5... | identifier_body |
test_metrics_fluster.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use engine_rocks::raw::{DBOptions, TitanDBOptions};
use tempfile::Builder;
use engine_rocks::util::{self as rocks_util, RocksCFOptions};
use engine_rocks::{RocksColumnFamilyOptions... |
let rtime = Duration::from_millis(300);
sleep(rtime);
metrics_flusher.stop();
}
| {
error!("failed to start metrics flusher, error = {:?}", e);
} | conditional_block |
test_metrics_fluster.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use engine_rocks::raw::{DBOptions, TitanDBOptions};
use tempfile::Builder;
use engine_rocks::util::{self as rocks_util, RocksCFOptions};
use engine_rocks::{RocksColumnFamilyOptions... | RocksColumnFamilyOptions::new(),
)];
let raft_engine = rocks_util::new_engine_opt(
raft_path.to_str().unwrap(),
RocksDBOptions::from_raw(DBOptions::new()),
cfs_opts,
)
.unwrap();
let engines = Engines::new(engine, raft_engine);
let mut metrics_flusher = MetricsFlu... | {
let path = Builder::new()
.prefix("_test_metrics_flusher")
.tempdir()
.unwrap();
let raft_path = path.path().join(Path::new("raft"));
let mut db_opt = DBOptions::new();
db_opt.set_titandb_options(&TitanDBOptions::new());
let db_opt = RocksDBOptions::from_raw(db_opt);
le... | identifier_body |
test_metrics_fluster.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use engine_rocks::raw::{DBOptions, TitanDBOptions};
use tempfile::Builder;
use engine_rocks::util::{self as rocks_util, RocksCFOptions};
use engine_rocks::{RocksColumnFamilyOptions... | () {
let path = Builder::new()
.prefix("_test_metrics_flusher")
.tempdir()
.unwrap();
let raft_path = path.path().join(Path::new("raft"));
let mut db_opt = DBOptions::new();
db_opt.set_titandb_options(&TitanDBOptions::new());
let db_opt = RocksDBOptions::from_raw(db_opt);
le... | test_metrics_flusher | identifier_name |
test_metrics_fluster.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use engine_rocks::raw::{DBOptions, TitanDBOptions};
use tempfile::Builder;
use engine_rocks::util::{self as rocks_util, RocksCFOptions};
use engine_rocks::{RocksColumnFamilyOptions... | )
.unwrap();
let engines = Engines::new(engine, raft_engine);
let mut metrics_flusher = MetricsFlusher::new(engines);
metrics_flusher.set_flush_interval(Duration::from_millis(100));
if let Err(e) = metrics_flusher.start() {
error!("failed to start metrics flusher, error = {:?}", e);
... | )];
let raft_engine = rocks_util::new_engine_opt(
raft_path.to_str().unwrap(),
RocksDBOptions::from_raw(DBOptions::new()),
cfs_opts, | random_line_split |
closing-spawned-feed.rs | use futures::{StreamExt, TryStreamExt};
use futures_timer::Delay;
use log::error;
use reql::r;
use serde_json::Value;
use std::time::Duration;
// We are using `tokio` here as an example but you can use this crate
// with any runtime
#[tokio::main]
async fn main() -> reql::Result<()> | let mut query = r.db("rethinkdb").table("jobs").changes(()).run(conn);
// Execute the query and handle the result
while let Some(change) = query.next().await {
match change {
// We are going to continue printing jobs until the feed is closed
Ok(change... | {
// Initialise the logger if you need to debug this crate
env_logger::init();
// Connect to create a RethinkDB session
let session = r.connect(()).await?;
// Manually get a connection from the session
// Usually, this is not necessary (see other examples) but in this
// case we need a han... | identifier_body |
closing-spawned-feed.rs | use futures::{StreamExt, TryStreamExt};
use futures_timer::Delay;
use log::error;
use reql::r;
use serde_json::Value;
use std::time::Duration;
// We are using `tokio` here as an example but you can use this crate
// with any runtime
#[tokio::main]
async fn main() -> reql::Result<()> {
// Initialise the logger if y... | let feed_handle = tokio::spawn(async {
// Create the query you want to run
// The query returns a `Stream` of responses from RethinkDB
let mut query = r.db("rethinkdb").table("jobs").changes(()).run(conn);
// Execute the query and handle the result
while let Some(change) = q... |
// Spawn the changefeed to run it in the background | random_line_split |
closing-spawned-feed.rs | use futures::{StreamExt, TryStreamExt};
use futures_timer::Delay;
use log::error;
use reql::r;
use serde_json::Value;
use std::time::Duration;
// We are using `tokio` here as an example but you can use this crate
// with any runtime
#[tokio::main]
async fn | () -> reql::Result<()> {
// Initialise the logger if you need to debug this crate
env_logger::init();
// Connect to create a RethinkDB session
let session = r.connect(()).await?;
// Manually get a connection from the session
// Usually, this is not necessary (see other examples) but in this
... | main | identifier_name |
basic.rs | #[cfg(all(feature = "std_rng", feature = "default_dictionary"))]
use petname::petname;
use petname::Petnames;
use rand::rngs::mock::StepRng;
#[test]
#[cfg(feature = "default_dictionary")]
fn default_petnames_has_adjectives() {
let petnames = Petnames::default();
assert_ne!(petnames.adjectives.len(), 0);
}
#[t... | assert_eq!(Vec::<String>::new(), names);
}
#[test]
fn petnames_iter_non_repeating_yields_nothing_when_no_word_lists_are_given() {
let mut rng = StepRng::new(0, 1);
let petnames = Petnames::init("a1 a2", "b1 b2", "c1 c2");
let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 0, ".").collect();... | let petnames = Petnames::init("a1 a2", "", "c1 c2");
let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 3, ".").collect(); | random_line_split |
basic.rs | #[cfg(all(feature = "std_rng", feature = "default_dictionary"))]
use petname::petname;
use petname::Petnames;
use rand::rngs::mock::StepRng;
#[test]
#[cfg(feature = "default_dictionary")]
fn default_petnames_has_adjectives() {
let petnames = Petnames::default();
assert_ne!(petnames.adjectives.len(), 0);
}
#[t... |
#[test]
fn petnames_iter_yields_names() {
let mut rng = StepRng::new(0, 1);
let petnames = Petnames::init("foo", "bar", "baz");
let names = petnames.iter(&mut rng, 3, ".");
// Definintely an Iterator...
let mut iter: Box<dyn Iterator<Item = _>> = Box::new(names);
assert_eq!(Some("bar.foo.baz".... | {
let mut rng = StepRng::new(0, 1);
let petnames = Petnames::init("a b", "c d e", "f g h i");
let names = petnames.iter(&mut rng, 3, ".");
assert_eq!(24u128, names.cardinality());
} | identifier_body |
basic.rs | #[cfg(all(feature = "std_rng", feature = "default_dictionary"))]
use petname::petname;
use petname::Petnames;
use rand::rngs::mock::StepRng;
#[test]
#[cfg(feature = "default_dictionary")]
fn default_petnames_has_adjectives() {
let petnames = Petnames::default();
assert_ne!(petnames.adjectives.len(), 0);
}
#[t... | () {
let petnames = Petnames {
adjectives: vec!["adjective"],
adverbs: vec!["adverb"],
names: vec!["name"],
};
assert_eq!(
petnames.generate(&mut StepRng::new(0, 1), 3, "-"),
"adverb-adjective-name"
);
}
#[test]
#[cfg(all(feature = "std_rng", feature = "default_d... | generate_uses_adverb_adjective_name | identifier_name |
sudoku.rs | // xfail-pretty
// 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
//... | () {
let args = os::args();
let use_default = args.len() == 1u;
let mut sudoku = if use_default {
Sudoku::from_vec(&default_sudoku)
} else {
Sudoku::read(io::stdin())
};
sudoku.solve();
sudoku.write(io::stdout());
}
| main | identifier_name |
sudoku.rs | // xfail-pretty
// 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
//... |
else {
fail!("Invalid sudoku file");
}
}
return Sudoku::new(g)
}
pub fn write(&self, writer: @io::Writer) {
for u8::range(0u8, 9u8) |row| {
writer.write_str(fmt!("%u", self.grid[row][0] as uint));
for u8::range(1u8, 9u8) |... | {
let row = uint::from_str(comps[0]).get() as u8;
let col = uint::from_str(comps[1]).get() as u8;
g[row][col] = uint::from_str(comps[2]).get() as u8;
} | conditional_block |
sudoku.rs | // xfail-pretty
// 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
//... |
}
}
// Stores available colors as simple bitfield, bit 0 is always unset
struct Colors(u16);
static heads: u16 = (1u16 << 10) - 1; /* bits 9..0 */
impl Colors {
fn new(start_color: u8) -> Colors {
// Sets bits 9..start_color
let tails =!0u16 << start_color;
return Colors(heads & tail... | {
for u8::range(0u8, 9u8) |idx| {
avail.remove(self.grid[idx][col]); /* check same column fields */
avail.remove(self.grid[row][idx]); /* check same row fields */
}
// check same block fields
let row0 = (row / 3u8) * 3u8;
let col0 = (col / 3u8) * 3u8;
... | identifier_body |
sudoku.rs | // xfail-pretty
// 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
//... | let val = **self & heads;
if (0u16 == val) {
return 0u8;
} else {
unsafe {
return cttz16(val as i16) as u8;
}
}
}
fn remove(&mut self, color: u8) {
if color!= 0u8 {
let val = **self;
let mask =!... |
fn next(&self) -> u8 { | random_line_split |
main.rs | #![crate_name = "limonite"]
#![crate_type = "bin"]
extern crate docopt;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io::{BufReader, Read};
use std::fs::File;
use std::path::Path;
use docopt::Docopt;
use lexical::lexer::Lexer;
use syntax::parser::Parser;
use semantic... | {
pub arg_file: String,
pub flag_dump: bool,
pub flag_stdin: bool,
pub flag_version: bool
}
fn main() {
env_logger::init().unwrap();
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if args.... | Args | identifier_name |
main.rs | #![crate_name = "limonite"]
#![crate_type = "bin"]
extern crate docopt;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io::{BufReader, Read};
use std::fs::File;
use std::path::Path;
use docopt::Docopt;
use lexical::lexer::Lexer;
use syntax::parser::Parser;
use semantic... |
input_string
} | random_line_split | |
main.rs | #![crate_name = "limonite"]
#![crate_type = "bin"]
extern crate docopt;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io::{BufReader, Read};
use std::fs::File;
use std::path::Path;
use docopt::Docopt;
use lexical::lexer::Lexer;
use syntax::parser::Parser;
use semantic... | {
let mut input_string = String::new();
if let Err(e) = readable.read_to_string(&mut input_string) {
panic!("Failed to read: {}", e);
}
input_string
} | identifier_body | |
main.rs | #![crate_name = "limonite"]
#![crate_type = "bin"]
extern crate docopt;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io::{BufReader, Read};
use std::fs::File;
use std::path::Path;
use docopt::Docopt;
use lexical::lexer::Lexer;
use syntax::parser::Parser;
use semantic... | else {
readable_to_string(std::io::stdin())
};
// Tokanize the input
let lexer = Lexer::new(&input_string);
// Parse & Build an AST
let mut parser = Parser::new(lexer);
let mut ast_root = match parser.parse() {
Some(ast) => ast,
None => return,
};
// TODO: Se... | {
let ref file_name = &args.arg_file;
let path = Path::new(file_name);
let file = match File::open(&path) {
Ok(f) => f,
Err(e) => panic!("Failed to open file: {}", e)
};
readable_to_string(BufReader::new(file))
} | conditional_block |
lib.rs | pub const MAX_ARGS_NUMBER: usize = 4;
pub const MAX_PLAYERS: usize = 4;
pub const MEM_SIZE: usize = 4 * 1024;
pub const IDX_MOD: usize = MEM_SIZE / 8;
pub const CHAMP_MAX_SIZE: usize = MEM_SIZE / 6;
pub const REG_NUMBER: usize = 16;
pub const REG_MAX: u8 = REG_NUMBER as u8;
pub const CYCLE_T... | {
pub magic: u32,
pub prog_name: [u8; PROG_NAME_LENGTH + 1],
pub prog_size: u32,
pub comment: [u8; COMMENT_LENGTH + 1],
}
| Header | identifier_name |
lib.rs | pub const MAX_PLAYERS: usize = 4;
pub const MEM_SIZE: usize = 4 * 1024;
pub const IDX_MOD: usize = MEM_SIZE / 8;
pub const CHAMP_MAX_SIZE: usize = MEM_SIZE / 6;
pub const REG_NUMBER: usize = 16;
pub const REG_MAX: u8 = REG_NUMBER as u8;
pub const CYCLE_TO_DIE: usize = 1536;
pub const CYCLE_D... | pub const MAX_ARGS_NUMBER: usize = 4; | random_line_split | |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | pub use rustc_back::rpath;
pub use rustc_back::svh;
pub use rustc_back::target_strs;
pub use rustc_back::x86;
pub use rustc_back::x86_64;
pub mod link;
pub mod lto;
pub mod write;
}
pub mod trans;
pub mod save;
pub mod lib {
pub use llvm;
} | pub use rustc_back::arm;
pub use rustc_back::mips;
pub use rustc_back::mipsel; | random_line_split |
GoingToZeroOrInfinity.rs |
fn going(n: i32) -> f64 {
let mut result = 0.0;
for i in 1..n+1 {
result += i as f64;
result /= i as f64;
}
result
}
fn assert_fuzzy_equals(actual: f64, expected: f64) {
let merr = 1.0e-6;
let inrange =
if expected == 0.0 {
(actual.abs() <= merr)
}... | () {
dotest(5, 1.275);
dotest(6, 1.2125);
dotest(7, 1.173214);
dotest(8, 1.146651);
}
| main | identifier_name |
GoingToZeroOrInfinity.rs |
fn going(n: i32) -> f64 {
let mut result = 0.0;
for i in 1..n+1 {
result += i as f64;
result /= i as f64;
}
result
}
fn assert_fuzzy_equals(actual: f64, expected: f64) {
let merr = 1.0e-6;
let inrange =
if expected == 0.0 {
(actual.abs() <= merr)
}... | {
dotest(5, 1.275);
dotest(6, 1.2125);
dotest(7, 1.173214);
dotest(8, 1.146651);
} | identifier_body | |
GoingToZeroOrInfinity.rs | fn going(n: i32) -> f64 {
let mut result = 0.0;
for i in 1..n+1 {
result += i as f64;
result /= i as f64;
}
result
}
fn assert_fuzzy_equals(actual: f64, expected: f64) {
let merr = 1.0e-6;
let inrange =
if expected == 0.0 { | };
if inrange == false {
println!("Expected value must be near: {:e} but was:{:e}",
expected, actual);
} else {
//println!("....... GOOD\n");
}
assert_eq!(true, inrange);
}
fn dotest(n: i32, exp: f64) -> () {
assert_fuzzy_equals(going(n), exp);
}
fn main() ... | (actual.abs() <= merr)
} else {
((actual - expected).abs() / expected <= merr) | random_line_split |
GoingToZeroOrInfinity.rs |
fn going(n: i32) -> f64 {
let mut result = 0.0;
for i in 1..n+1 {
result += i as f64;
result /= i as f64;
}
result
}
fn assert_fuzzy_equals(actual: f64, expected: f64) {
let merr = 1.0e-6;
let inrange =
if expected == 0.0 {
(actual.abs() <= merr)
}... | else {
//println!("....... GOOD\n");
}
assert_eq!(true, inrange);
}
fn dotest(n: i32, exp: f64) -> () {
assert_fuzzy_equals(going(n), exp);
}
fn main() {
dotest(5, 1.275);
dotest(6, 1.2125);
dotest(7, 1.173214);
dotest(8, 1.146651);
}
| {
println!("Expected value must be near: {:e} but was:{:e}",
expected, actual);
} | conditional_block |
mod.rs | //! Utilities to parse HTTP messages.
#![experimental]
pub use self::parser::Parser;
pub use self::parser::ParseType;
pub use self::parser::ParseError;
pub use self::parser::MessageHandler;
use std::fmt::{Formatter, FormatError, Show};
/// A list of supported HTTP versions.
#[allow(non_camel_case_types)]
#[deriving... |
}
impl Show for HttpMethod {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> {
f.pad(self.name())
}
}
pub mod parser;
#[cfg(test)] pub mod tests;
| {
self.name().char_at(pos) == c
} | identifier_body |
mod.rs | //! Utilities to parse HTTP messages.
#![experimental]
pub use self::parser::Parser;
pub use self::parser::ParseType;
pub use self::parser::ParseError;
pub use self::parser::MessageHandler;
use std::fmt::{Formatter, FormatError, Show};
/// A list of supported HTTP versions.
#[allow(non_camel_case_types)]
#[deriving... | (&self, pos: uint, c: char) -> bool {
self.name().char_at(pos) == c
}
}
impl Show for HttpMethod {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> {
f.pad(self.name())
}
}
pub mod parser;
#[cfg(test)] pub mod tests;
| hit | identifier_name |
mod.rs | //! Utilities to parse HTTP messages.
#![experimental]
pub use self::parser::Parser;
pub use self::parser::ParseType;
pub use self::parser::ParseError;
pub use self::parser::MessageHandler;
use std::fmt::{Formatter, FormatError, Show};
/// A list of supported HTTP versions.
#[allow(non_camel_case_types)]
#[deriving... | HttpLink => "LINK",
HttpLock => "LOCK",
HttpMerge => "MERGE",
HttpMkActivity => "MKACTIVITY",
HttpMkCalendar => "MKCALENDAR",
HttpMkCol => "MKCOL",
HttpMove => "MOVE",
HttpMsearch => "M... | HttpConnect => "CONNECT",
HttpCopy => "COPY",
HttpDelete => "DELETE",
HttpGet => "GET",
HttpHead => "HEAD", | random_line_split |
mod.rs | extern crate rustbox;
use rustbox::Key;
use state::Action;
pub use self::insert_mode::InsertMode;
pub use self::normal_mode::NormalMode;
pub use self::replace_mode::ReplaceMode;
mod insert_mode;
mod normal_mode;
mod replace_mode;
#[derive(Eq,PartialEq,Debug,Copy,Clone,Hash)]
pub enum ModeType {
Insert,
Norm... |
/// The name of the mode. Displayed in the bottom bar.
fn display(&self) -> &'static str;
}
| { None } | identifier_body |
mod.rs | extern crate rustbox;
use rustbox::Key;
use state::Action;
pub use self::insert_mode::InsertMode;
pub use self::normal_mode::NormalMode;
pub use self::replace_mode::ReplaceMode;
mod insert_mode;
mod normal_mode;
mod replace_mode;
#[derive(Eq,PartialEq,Debug,Copy,Clone,Hash)]
pub enum ModeType {
Insert,
Norm... | (&self) -> Option<u16> { None }
/// The name of the mode. Displayed in the bottom bar.
fn display(&self) -> &'static str;
}
| color | identifier_name |
mod.rs | extern crate rustbox;
use rustbox::Key;
use state::Action;
pub use self::insert_mode::InsertMode;
pub use self::normal_mode::NormalMode;
pub use self::replace_mode::ReplaceMode;
mod insert_mode;
mod normal_mode;
mod replace_mode;
#[derive(Eq,PartialEq,Debug,Copy,Clone,Hash)]
pub enum ModeType {
Insert,
Norm... | fn color(&self) -> Option<u16> { None }
/// The name of the mode. Displayed in the bottom bar.
fn display(&self) -> &'static str;
} | fn on_exit(&self) -> Option<Action> { None }
/// Color to use for the bottom bar. | random_line_split |
position.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.or... |
}
| {
self.0.to_css(dest)
} | identifier_body |
position.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.or... | (pub LengthOrPercentage);
impl ToCss for VerticalPosition {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
| VerticalPosition | identifier_name |
position.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`position`][position]s
//!
//! [position]: https://drafts.csswg.or... | }
}
#[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct VerticalPosition(pub LengthOrPercentage);
impl ToCss for VerticalPosition {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
} | self.0.to_css(dest) | random_line_split |
lib.rs | // Copyright (c) 2016 warheadhateus developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be cop... |
}
| {} | identifier_body |
lib.rs | // Copyright (c) 2016 warheadhateus developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be cop... | mod sender;
mod server;
mod ssh;
mod sshd;
pub use client::Client;
pub use endpoint::Udp;
pub use error::NailErr;
pub use receiver::Receiver;
pub use sender::Sender;
pub use server::{NailMessage, NailMessageHandler, Server};
pub use sshd::{SshDaemon, SshPacketHandler};
/// Convenience Result for use with `NailErr`.
p... | random_line_split | |
lib.rs | // Copyright (c) 2016 warheadhateus developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be cop... | () {}
}
| it_works | identifier_name |
sodium.rs | extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, SALTBYTES);
pub fn gen_salt() -> Salt {
S... | () {
let passwd = b"Correct Horse Battery Staple";
let salt = gen_salt();
let mut key = [0u8; 64];
let key_moderate = pwhash(&mut key, passwd, &salt, &KeyDerivationMethod::ARGON2I_MOD).unwrap();
let mut key = [0u8; 64];
let key_interactive = pwhash(&mut key, passwd, &s... | pwhash_works_for_interactive_method | identifier_name |
sodium.rs | extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, SALTBYTES);
pub fn gen_salt() -> Salt {
S... | mod tests {
use rmp_serde;
use super::*;
#[test]
fn get_salt_works() {
let salt = gen_salt();
assert_eq!(salt[..].len(), SALTBYTES)
}
#[test]
fn salt_serialize_deserialize_works() {
let salt = gen_salt();
let serialized = rmp_serde::to_vec(&salt).unwrap();
... |
#[cfg(test)] | random_line_split |
sodium.rs | extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, SALTBYTES);
pub fn gen_salt() -> Salt |
pub fn pwhash<'a>(key: &'a mut [u8], passwd: &[u8], salt: &Salt, key_derivation_method: &KeyDerivationMethod) -> Result<&'a [u8], IndyError> {
let (opslimit, memlimit) = unsafe {
match key_derivation_method {
KeyDerivationMethod::ARGON2I_MOD => (crypto_pwhash_argon2i_opslimit_moderate(), crypt... | {
Salt(pwhash::gen_salt())
} | identifier_body |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... | {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&fragment.node) {
for animation in *animations {
update_style_for_animation(animation, &mut fragment.style, Some(&mut damage));
}
... | identifier_body | |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... | (constellation_chan: &ConstellationChan<ConstellationMsg>,
running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>,
new_animations_receiver: &Receiver<Animation>,
... | update_animation_state | identifier_name |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... | use time;
/// Processes any new animations that were discovered after style recalculation.
/// Also expire any old animations that have completed, inserting them into `expired_animations`.
pub fn update_animation_state(constellation_chan: &ConstellationChan<ConstellationMsg>,
running_anim... | use script_traits::LayoutMsg as ConstellationMsg;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::mpsc::Receiver;
use style::animation::{Animation, update_style_for_animation}; | random_line_split |
animation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use gfx::display_list::OpaqueNode;
use incremental::R... |
}
for key in keys_to_remove {
running_animations.remove(&key).unwrap();
}
// Add new running animations.
for new_running_animation in new_running_animations {
match running_animations.entry(new_running_animation.node) {
Entry::Vacant(entry) => {
entry.in... | {
*running_animations = animations_still_running
} | conditional_block |
font.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 app_units::Au;
use font::{FontHandleMethods, FontMetrics, FontTableMethods};
use font::{FontTableTag, Fraction... |
fn glyph_h_advance(&self, glyph: GlyphId) -> Option<FractionalPixel> {
assert!(!self.face.is_null());
unsafe {
let res = FT_Load_Glyph(self.face,
glyph as FT_UInt,
GLYPH_LOAD_FLAGS);
if res.succeeded... | {
self.can_do_fast_shaping
} | identifier_body |
font.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 app_units::Au;
use font::{FontHandleMethods, FontMetrics, FontTableMethods};
use font::{FontTableTag, Fraction... | handle: FontContextHandle,
can_do_fast_shaping: bool,
}
impl Drop for FontHandle {
fn drop(&mut self) {
assert!(!self.face.is_null());
unsafe {
if!FT_Done_Face(self.face).succeeded() {
panic!("FT_Done_Face failed");
}
}
}
}
impl FontHandl... | random_line_split | |
font.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 app_units::Au;
use font::{FontHandleMethods, FontMetrics, FontTableMethods};
use font::{FontTableTag, Fraction... | (face: FT_Face, pt_size: Au) -> Result<(), ()>{
let char_size = pt_size.to_f64_px() * 64.0 + 0.5;
unsafe {
let result = FT_Set_Char_Size(face, char_size as FT_F26Dot6, 0, 0, 0);
if result.succeeded() { Ok(()) } else { Err(()) }
}
}
fn has_table(&self, tag: FontT... | set_char_size | identifier_name |
font.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 app_units::Au;
use font::{FontHandleMethods, FontMetrics, FontTableMethods};
use font::{FontTableTag, Fraction... | else {
default_weight
}
} else {
default_weight
}
}
}
}
fn stretchiness(&self) -> FontStretch {
// TODO(pcwalton): Implement this.
FontStretch::Normal
}
fn glyph_index(&s... | {
FontWeight::from_int(weight / 100 * 100).unwrap()
} | conditional_block |
unsendable-class.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 ... | (i:int, j: Gc<String>) -> foo {
foo {
i: i,
j: j
}
}
fn main() {
let cat = "kitty".to_string();
let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented
tx.send(foo(42, box(GC) (cat))); //~ ERROR `core::kinds::Send` is not implemented
}
| foo | identifier_name |
unsendable-class.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 ... |
fn main() {
let cat = "kitty".to_string();
let (tx, _) = channel(); //~ ERROR `core::kinds::Send` is not implemented
tx.send(foo(42, box(GC) (cat))); //~ ERROR `core::kinds::Send` is not implemented
}
| {
foo {
i: i,
j: j
}
} | identifier_body |
unsendable-class.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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.
// Test that a class with an unsendable field can't be
// sent
use std::gc::{Gc, GC};
... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
mod.rs | //! Implements a wrapper struct container for internal getter.
#[cfg(test)]
mod test {
use { Getter, Factory, AsFactoryExt };
use std::any::Any;
#[test]
fn should_get_correct_value() {
let factory = create_with_val("HAI");
assert_eq!(factory.take(), "HAI");
}
#[test]
fn c... | () {
let boxany = box create_with_val("HAI") as Box<Any>;
let downcasted = boxany.as_factory_of::<String>().unwrap();
assert_eq!(downcasted.take(), "HAI");
}
fn create_with_val(val: &str) -> Factory<String> {
Factory::new(box ValContainer { val: val.to_string() })
}
st... | should_be_able_to_downcast_from_any | identifier_name |
mod.rs | //! Implements a wrapper struct container for internal getter.
#[cfg(test)]
mod test {
use { Getter, Factory, AsFactoryExt };
use std::any::Any;
#[test]
fn should_get_correct_value() {
let factory = create_with_val("HAI");
assert_eq!(factory.take(), "HAI");
}
#[test]
fn c... |
}
}
| {
box ValContainer {
val: self.val.clone(),
}
} | identifier_body |
mod.rs | //! Implements a wrapper struct container for internal getter.
#[cfg(test)]
mod test {
use { Getter, Factory, AsFactoryExt };
use std::any::Any;
#[test]
fn should_get_correct_value() {
let factory = create_with_val("HAI"); | assert_eq!(factory.take(), "HAI");
}
#[test]
fn cloned_factory_should_get_the_same_value() {
let factory = create_with_val("HAI");
assert_eq!(factory.clone().take(), factory.take());
}
#[test]
fn should_be_able_to_downcast_from_any() {
let boxany = box create_w... | random_line_split | |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct BankSelection(u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_000... |
fn upper(&self) -> u8 {
(self.0 & 0b0110_0000) >> 5
}
fn set_lower(&mut self, val: u8) {
self.0 = (self.0 & 0b1110_0000) | (val & 0b0001_1111);
}
fn lower(&self) -> u8 {
self.0 & 0b0001_1111
}
fn rom_bank(&self) -> usize {
let bank = if self.mode() == Ban... | {
self.0 = (self.0 & 0b1001_1111) | ((val << 5) & 0b0110_0000);
} | identifier_body |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct BankSelection(u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_000... | ,
_ => {
error!("Address {:#X} not handled by MBC1", addr);
0xFF
}
}
}
fn write(&mut self, addr: u16, val: u8) {
match addr {
0x0000..=0x1FFF => {
// Writing to this space toggles RAM
// Any val... | {
// Switchable RAM bank
if self.ram_enabled {
self.ram_data[self.ram_index(addr)]
} else {
warn!("Attempted read from RAM address {:X} while RAM is disabled.", addr);
0xFF
}
} | conditional_block |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct BankSelection(u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_000... | } else {
self.ram_data[index] = val;
}
}
},
_ => error!("Attempted to write to address {:#X} not handled by MBC1", addr)
}
}
} | if self.ram_enabled {
let index = self.ram_index(addr);
if index >= self.ram_data.len() {
warn!("Attempted to write to out-of-bounds MBC1 RAM index {}, addr {:X}.", index, addr); | random_line_split |
mbc1.rs | use enum_primitive::FromPrimitive;
use log::{warn, error};
use super::Mapper;
struct | (u8);
impl BankSelection {
fn set_mode(&mut self, mode: BankMode) {
self.0 = (self.0 & 0b0111_1111) | ((mode as u8) << 7)
}
fn mode(&self) -> BankMode {
BankMode::from_u8((self.0 & 0b1000_0000) >> 7).unwrap()
}
fn set_upper(&mut self, val: u8) {
self.0 = (self.0 & 0b1001_1... | BankSelection | identifier_name |
joypad.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | (&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:08b}",!self.register.bits)
}
}
impl LowerHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:02x}",!self.register.bits)
}
}
impl UpperHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:0... | fmt | identifier_name |
joypad.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... |
}
impl LowerHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:02x}",!self.register.bits)
}
}
impl UpperHex for Joypad {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:02X}",!self.register.bits)
}
}
bitflags!(
/// P1 register
///
/// Bits are inverted... | {
write!(f, "{:08b}", !self.register.bits)
} | identifier_body |
joypad.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | _ => P1::empty(),
}
}
fn button(key: &GbKey) -> P1 {
match *key {
GbKey::A => P1::P10,
GbKey::B => P1::P11,
GbKey::Select => P1::P12,
GbKey::Start => P1::P13,
_ => P1::empty(),
}
}
} | GbKey::Down => P1::P13, | random_line_split |
prefs.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 basedir::default_config_dir;
use opts;
use resource_files::resources_dir_path;
use rustc_serialize::json::{Jso... |
pub fn as_i64(&self) -> Option<i64> {
match *self {
PrefValue::Number(x) => Some(x as i64),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
PrefValue::Number(x) => Some(x as u64),
_ => None,
}
}
}
impl... | {
match *self {
PrefValue::String(ref value) => {
Some(&value)
},
_ => None
}
} | identifier_body |
prefs.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 basedir::default_config_dir;
use opts;
use resource_files::resources_dir_path;
use rustc_serialize::json::{Jso... | (&self, name: &str, value: PrefValue) {
let mut prefs = self.0.write().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
... | set | identifier_name |
prefs.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 basedir::default_config_dir;
use opts;
use resource_files::resources_dir_path;
use rustc_serialize::json::{Jso... | Pref::WithDefault(ref default, ref override_value) => {
match *override_value {
Some(ref x) => x,
None => default
}
}
}
}
fn set(&mut self, value: PrefValue) {
// TODO - this should error if we try t... | random_line_split | |
BrightContrastFilter.rs | #pragma version(1)
#pragma rs java_package_name(cn.louispeng.imagefilter.renderscript)
// 高亮对比度特效
#include "Clamp.rsh"
// set from the java SDK level
rs_allocation gIn;
rs_allocation gOut;
rs_script gScript;
// The brightness factor.
// Should be in the range [-1.0f, 1.0f].
float gBrightnessFactor = 0.25f;
// The... |
// Modifiy contrast (multiplication)
if (ContrastFactor1!= 1.0f){
// Transform to range [-0.5f, 0.5f]
f3 = f3 - 0.5f;
// Multiply contrast factor
f3 = f3 * ContrastFactor1;
// Transform back to range [0.0f, 1.0f]
f3 = f3 + 0.5f;
f3 = FClamp01Float3(f3);
}
*v_out = r... | f3 = FClamp01Float3(f3);
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.