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 |
|---|---|---|---|---|
modify.rs | use std::collections::HashSet;
use std::convert::AsRef;
use std::hash::Hash;
use std::io;
use lber::structures::{Tag, Enumerated, Sequence, Set, OctetString};
use lber::common::TagClass;
use futures::{future, Future};
use tokio_service::Service;
use ldap::{Ldap, LdapOp, next_req_controls};
use result::LdapResult;
/... | Mod::Delete(attr, set) => (1, attr, set),
Mod::Replace(attr, set) => (2, attr, set),
};
if set.is_empty() && is_add {
any_add_empty = true;
}
... | let (num, attr, set) = match m {
Mod::Add(attr, set) => { is_add = true; (0, attr, set) }, | random_line_split |
modify.rs | use std::collections::HashSet;
use std::convert::AsRef;
use std::hash::Hash;
use std::io;
use lber::structures::{Tag, Enumerated, Sequence, Set, OctetString};
use lber::common::TagClass;
use futures::{future, Future};
use tokio_service::Service;
use ldap::{Ldap, LdapOp, next_req_controls};
use result::LdapResult;
/... |
let fut = self.call(LdapOp::Single(req, next_req_controls(self)))
.and_then(|response| {
let (mut result, controls) = (LdapResult::from(response.0), response.1);
result.ctrls = controls;
Ok(result)
});
Box::new(fut)
}
}
| {
return Box::new(future::err(io::Error::new(io::ErrorKind::Other, "empty value set for Add")));
} | conditional_block |
modify.rs | use std::collections::HashSet;
use std::convert::AsRef;
use std::hash::Hash;
use std::io;
use lber::structures::{Tag, Enumerated, Sequence, Set, OctetString};
use lber::common::TagClass;
use futures::{future, Future};
use tokio_service::Service;
use ldap::{Ldap, LdapOp, next_req_controls};
use result::LdapResult;
/... | }
let op = Tag::Enumerated(Enumerated {
inner: num,
.. Default::default()
});
let part_attr = Tag::Sequence(Sequence {
inner: vec![
... | {
let mut any_add_empty = false;
let req = Tag::Sequence(Sequence {
id: 6,
class: TagClass::Application,
inner: vec![
Tag::OctetString(OctetString {
inner: Vec::from(dn.as_bytes()),
.. Default::default()
... | identifier_body |
error.rs | use std::{fmt, error};
#[derive(Debug)]
pub enum ServerError {
UnableToSavePost,
UnspecifiedDatabaseUrl,
UnableToConnectWithDatabase(String),
UnableToLoadPosts,
UnableToDeletePosts,
UnableToPublishPost(i32),
UnableToGetPost(i32)
}
#[allow(unused_variables)]
impl ServerError {
fn desc(&... |
}
impl error::Error for ServerError {
fn description(&self) -> &str {
self.desc()
}
}
impl fmt::Display for ServerError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.desc().fmt(formatter)
}
}
| {
match *self {
ServerError::UnableToSavePost => "Error saving post",
ServerError::UnspecifiedDatabaseUrl => "Database URL is unspecified",
ServerError::UnableToConnectWithDatabase(ref url) => "Error connecting to database",
ServerError::UnableToLoadPosts => "Unab... | identifier_body |
error.rs | use std::{fmt, error};
#[derive(Debug)]
pub enum ServerError {
UnableToSavePost,
UnspecifiedDatabaseUrl,
UnableToConnectWithDatabase(String),
UnableToLoadPosts,
UnableToDeletePosts,
UnableToPublishPost(i32),
UnableToGetPost(i32)
}
#[allow(unused_variables)]
impl ServerError {
fn desc(&... | fn description(&self) -> &str {
self.desc()
}
}
impl fmt::Display for ServerError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.desc().fmt(formatter)
}
} | }
impl error::Error for ServerError { | random_line_split |
error.rs | use std::{fmt, error};
#[derive(Debug)]
pub enum ServerError {
UnableToSavePost,
UnspecifiedDatabaseUrl,
UnableToConnectWithDatabase(String),
UnableToLoadPosts,
UnableToDeletePosts,
UnableToPublishPost(i32),
UnableToGetPost(i32)
}
#[allow(unused_variables)]
impl ServerError {
fn desc(&... | (&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.desc().fmt(formatter)
}
}
| fmt | identifier_name |
lint-dead-code-1.rs | // Copyright 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 ... |
fn bar() { //~ ERROR: code is never used
foo();
}
| { //~ ERROR: code is never used
bar();
let unused_enum = foo2;
} | identifier_body |
lint-dead-code-1.rs | // Copyright 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 ... | }
mod foo2 {
pub struct Bar2;
}
pub static pub_static: int = 0;
static priv_static: int = 0; //~ ERROR: code is never used
static used_static: int = 0;
pub static used_static2: int = used_static;
pub fn pub_fn() {
used_fn();
let used_struct1 = UsedStruct1 { x: 1 };
let used_struct2 = UsedStruct2(1);
... |
pub use foo2::Bar2;
mod foo {
pub struct Bar; //~ ERROR: code is never used | random_line_split |
lint-dead-code-1.rs | // Copyright 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 ... | { x: int }
struct UsedStruct2(int);
struct UsedStruct3;
struct UsedStruct4;
// this struct is never used directly, but its method is, so we don't want
// to warn it
struct SemiUsedStruct;
impl SemiUsedStruct {
fn la_la_la() {}
}
pub enum pub_enum { foo1, bar1 }
enum priv_enum { foo2, bar2 } //~ ERROR: code is nev... | UsedStruct1 | identifier_name |
posting.rs | use amount::MixedAmount; | use std::fmt::Error;
use std::result::Result;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClearedStatus {
Uncleared,
Pending,
Cleared
}
impl Display for ClearedStatus {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
&ClearedStatus::Uncleared => write!(f, "... | use transaction::Transaction;
use std::fmt::Display;
use std::fmt::Formatter; | random_line_split |
posting.rs | use amount::MixedAmount;
use transaction::Transaction;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error;
use std::result::Result;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClearedStatus {
Uncleared,
Pending,
Cleared
}
impl Display for ClearedStatus {
fn fmt(&self, f: &mut Form... |
pub fn status(&self) -> ClearedStatus {
match self.status.clone() {
ClearedStatus::Uncleared => match self.transaction.clone() {
Some(t) => t.status,
_ => ClearedStatus::Uncleared
},
s => s
}
}
pub fn all_tags(&self) -> V... | {
postings.iter().map(|x| x.clone().amount).sum()
} | identifier_body |
posting.rs | use amount::MixedAmount;
use transaction::Transaction;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error;
use std::result::Result;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ClearedStatus {
Uncleared,
Pending,
Cleared
}
impl Display for ClearedStatus {
fn fmt(&self, f: &mut Form... | (String, String);
#[derive(Clone, PartialEq, Eq)]
pub enum PostingType {
Regular,
Virtual,
BalancedVirtual
}
#[derive(Clone, PartialEq, Eq)]
pub struct Posting {
pub status: ClearedStatus,
pub amount: MixedAmount,
pub posting_type: PostingType,
pub tags: Vec<Tag>,
pub balance_assertion... | Tag | identifier_name |
mp4.rs | #![no_main]
use libfuzzer_sys::fuzz_target;
use mp4parse_capi::*;
use std::convert::TryInto;
use std::io::Read;
type CursorType<'a> = std::io::Cursor<&'a [u8]>;
extern "C" fn vec_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut CursorType = unsafe { &mut *(userdata ... | Ok(n) => n.try_into().expect("invalid conversion"),
Err(_) => -1,
}
}
fuzz_target!(|data: &[u8]| {
let mut cursor: CursorType = std::io::Cursor::new(data);
let io = Mp4parseIo {
read: Some(vec_read),
userdata: &mut cursor as *mut _ as *mut std::os::raw::c_void,
};
un... | random_line_split | |
mp4.rs | #![no_main]
use libfuzzer_sys::fuzz_target;
use mp4parse_capi::*;
use std::convert::TryInto;
use std::io::Read;
type CursorType<'a> = std::io::Cursor<&'a [u8]>;
extern "C" fn | (buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut CursorType = unsafe { &mut *(userdata as *mut _) };
let buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(buf) {
Ok(n) => n.try_into().expect("invalid conversion"),
Err(_) ... | vec_read | identifier_name |
mp4.rs | #![no_main]
use libfuzzer_sys::fuzz_target;
use mp4parse_capi::*;
use std::convert::TryInto;
use std::io::Read;
type CursorType<'a> = std::io::Cursor<&'a [u8]>;
extern "C" fn vec_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize |
fuzz_target!(|data: &[u8]| {
let mut cursor: CursorType = std::io::Cursor::new(data);
let io = Mp4parseIo {
read: Some(vec_read),
userdata: &mut cursor as *mut _ as *mut std::os::raw::c_void,
};
unsafe {
let mut context = std::ptr::null_mut();
if mp4parse_new(&io, &mut ... | {
let input: &mut CursorType = unsafe { &mut *(userdata as *mut _) };
let buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(buf) {
Ok(n) => n.try_into().expect("invalid conversion"),
Err(_) => -1,
}
} | identifier_body |
ui.rs | extern crate rustbox;
use self::rustbox::{Color, Style, RustBox};
use super::board::{Board, HEIGHT, WIDTH};
use super::tetromino::{Tetromino, TetrominoType};
use super::window::Window;
// Default scaling factor for the board
const SCALE: usize = 2;
// Default values for styling terminal output
const DEFAULT_STYLE: ... | (&self, board: &Board) {
// Start at 2 because only 20 of the board's rows should be displayed
for y in 2..HEIGHT {
for x in 0..WIDTH {
match board.field()[y][x] {
// When printing the board, offset x and y to compensate
// for the Wi... | print_board | identifier_name |
ui.rs | use self::rustbox::{Color, Style, RustBox};
use super::board::{Board, HEIGHT, WIDTH};
use super::tetromino::{Tetromino, TetrominoType};
use super::window::Window;
// Default scaling factor for the board
const SCALE: usize = 2;
// Default values for styling terminal output
const DEFAULT_STYLE: Style = rustbox::RB_NOR... | extern crate rustbox;
| random_line_split | |
ui.rs | extern crate rustbox;
use self::rustbox::{Color, Style, RustBox};
use super::board::{Board, HEIGHT, WIDTH};
use super::tetromino::{Tetromino, TetrominoType};
use super::window::Window;
// Default scaling factor for the board
const SCALE: usize = 2;
// Default values for styling terminal output
const DEFAULT_STYLE: ... | / Prints the player's score
pub fn print_score(&self, score: usize) {
self.score.print(0, 0, DEFAULT_STYLE, DEFAULT_FG, DEFAULT_BG, &format!("{:}", score));
}
/// Prints the difficulty level
pub fn print_level(&self, level: usize) {
self.level.print(0, 0, DEFAULT_STYLE, DEFAULT_FG, DEFA... | window.clear();
window.print_borders(DEFAULT_STYLE, DEFAULT_FG, DEFAULT_BG);
for &mino in tetromino.minos().iter() {
let color = self.get_tetromino_color(&tetromino.tetromino_type());
window.print_char(((mino.x as usize) * SCALE + 2), (mino.y + 1) as usize, DEFAULT_STYLE, ... | identifier_body |
pull_request.rs |
#[derive(Clone, Debug)]
pub struct PullRequest {
action: String,
number: u64,
repository: String,
sha: String,
url: String,
author: String,
}
impl PullRequest {
pub fn action(&self) -> String {
self.action.clone()
}
pub fn number(&self) -> u64 {
self.number
}
... | extern crate json;
use std::fmt;
use std::str::FromStr; | random_line_split | |
pull_request.rs | extern crate json;
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct PullRequest {
action: String,
number: u64,
repository: String,
sha: String,
url: String,
author: String,
}
impl PullRequest {
pub fn action(&self) -> String {
self.action.clone()
}
... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
"provided string is not a valid Push payload".fmt(f)
}
}
impl FromStr for PullRequest {
type Err = ParseError;
fn from_str(payload: &str) -> Result<PullRequest, ParseError> {
debug!("parse pull_request");
if let Ok(parsed) = json::pa... | fmt | identifier_name |
pull_request.rs | extern crate json;
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct PullRequest {
action: String,
number: u64,
repository: String,
sha: String,
url: String,
author: String,
}
impl PullRequest {
pub fn action(&self) -> String {
self.action.clone()
}
... |
debug!("{:?}", event);
Ok(event)
}
else {
Err(ParseError { _priv: () })
}
}
}
mod test {
#[test]
fn test_parse() {
use super::PullRequest;
use std::str::FromStr;
let payload = include_str!("pull_request.json");
let event... | {
let action = parsed["action"].as_str();
let number = parsed["number"].as_u64();
let repository = parsed["repository"]["full_name"].as_str();
let sha = parsed["pull_request"]["head"]["sha"].as_str();
let url = parsed["pull_request"]["head"]["repo"]["clone_url... | conditional_block |
pull_request.rs | extern crate json;
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct PullRequest {
action: String,
number: u64,
repository: String,
sha: String,
url: String,
author: String,
}
impl PullRequest {
pub fn action(&self) -> String {
self.action.clone()
}
... | author: author.unwrap().to_owned(),
};
debug!("{:?}", event);
Ok(event)
} else {
Err(ParseError { _priv: () })
}
}
}
mod test {
#[test]
fn test_parse() {
use super::PullRequest;
use std::str::FromStr;
... | {
debug!("parse pull_request");
if let Ok(parsed) = json::parse(payload) {
let action = parsed["action"].as_str();
let number = parsed["number"].as_u64();
let repository = parsed["repository"]["full_name"].as_str();
let sha = parsed["pull_request"]["head"]... | identifier_body |
merkletree.rs | use errors::prelude::*;
use services::ledger::merkletree::proof::{Lemma, Proof};
use services::ledger::merkletree::tree::{LeavesIntoIterator, LeavesIterator, Tree, TreeLeafData};
use utils::crypto::hash::{Hash, HASHBYTES};
/// A Merkle tree is a binary tree, with values of type `T` at the leafs,
/// and where every in... |
let node = Tree::Node {
hash: combined_hash.to_vec(),
left: Box::new(left),
right: Box::new(right)
};
next.push(node);
nodes_count+=1;
}
}
... | let combined_hash = Hash::hash_nodes(
left.hash(),
right.hash()
)?; | random_line_split |
merkletree.rs | use errors::prelude::*;
use services::ledger::merkletree::proof::{Lemma, Proof};
use services::ledger::merkletree::tree::{LeavesIntoIterator, LeavesIterator, Tree, TreeLeafData};
use utils::crypto::hash::{Hash, HASHBYTES};
/// A Merkle tree is a binary tree, with values of type `T` at the leafs,
/// and where every in... |
let count = values.len();
let mut nodes_count = 0;
let mut height = 0;
let mut cur = Vec::with_capacity(count);
for v in values {
let leaf = Tree::new_leaf(v)?;
cur.push(leaf);
}
while cur.len() > 1 {
let mut next = Vec::... | {
return Ok(MerkleTree {
root: Tree::empty(Hash::hash_empty()?),
height: 0,
count: 0,
nodes_count: 0
});
} | conditional_block |
merkletree.rs | use errors::prelude::*;
use services::ledger::merkletree::proof::{Lemma, Proof};
use services::ledger::merkletree::tree::{LeavesIntoIterator, LeavesIterator, Tree, TreeLeafData};
use utils::crypto::hash::{Hash, HASHBYTES};
/// A Merkle tree is a binary tree, with values of type `T` at the leafs,
/// and where every in... | (self) -> Self::IntoIter {
self.root.iter()
}
}
| into_iter | identifier_name |
class-method-cross-crate.rs | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:cci... | // 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. | random_line_split | |
class-method-cross-crate.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... | () {
let nyan : cat = cat(52, 99);
let kitty = cat(1000, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak();
}
| main | identifier_name |
class-method-cross-crate.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... | {
let nyan : cat = cat(52, 99);
let kitty = cat(1000, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak();
} | identifier_body | |
prelude.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 use slice::{PartialEqSlicePrelude, OrdSlicePrelude};
pub use slice::{AsSlice, SlicePrelude}; | pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4};
pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12}; | random_line_split |
theme_config.rs | use std::collections::HashMap;
use ron::{de::from_str, Value};
use serde_derive::{Deserialize, Serialize};
use crate::theming::config::StyleConfig;
pub static BASE_STYLE: &str = "base";
pub static RESOURCE_KEY: &str = "$";
/// Used to store and read properties that could be requested by a | #[serde(default)]
pub styles: HashMap<String, StyleConfig>,
#[serde(default)]
pub resources: HashMap<String, Value>,
}
impl<'a> ThemeConfig {
/// Extends the given theme with another theme. Replaces the
/// current name with the new choosen name `other`. If `other`
/// contains a style wit... | /// given property name and a selector.
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
#[serde(rename = "Theme")]
pub struct ThemeConfig { | random_line_split |
theme_config.rs | use std::collections::HashMap;
use ron::{de::from_str, Value};
use serde_derive::{Deserialize, Serialize};
use crate::theming::config::StyleConfig;
pub static BASE_STYLE: &str = "base";
pub static RESOURCE_KEY: &str = "$";
/// Used to store and read properties that could be requested by a
/// given property name an... | (s: &str) -> Self {
from_str(s).unwrap()
}
}
| from | identifier_name |
theme_config.rs | use std::collections::HashMap;
use ron::{de::from_str, Value};
use serde_derive::{Deserialize, Serialize};
use crate::theming::config::StyleConfig;
pub static BASE_STYLE: &str = "base";
pub static RESOURCE_KEY: &str = "$";
/// Used to store and read properties that could be requested by a
/// given property name an... |
}
| {
from_str(s).unwrap()
} | identifier_body |
cssgroupingrule.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 crate::dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods;
use crate::dom::bindi... |
pub fn parent_stylesheet(&self) -> &CSSStyleSheet {
self.cssrule.parent_stylesheet()
}
pub fn shared_lock(&self) -> &SharedRwLock {
self.cssrule.shared_lock()
}
}
impl CSSGroupingRuleMethods for CSSGroupingRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-cssrules
... | {
let parent_stylesheet = self.upcast::<CSSRule>().parent_stylesheet();
self.rulelist.or_init(|| {
CSSRuleList::new(
self.global().as_window(),
parent_stylesheet,
RulesSource::Rules(self.rules.clone()),
)
})
} | identifier_body |
cssgroupingrule.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 crate::dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods;
use crate::dom::bindi... | use crate::dom::cssrulelist::{CSSRuleList, RulesSource};
use crate::dom::cssstylesheet::CSSStyleSheet;
use dom_struct::dom_struct;
use servo_arc::Arc;
use style::shared_lock::{Locked, SharedRwLock};
use style::stylesheets::CssRules as StyleCssRules;
#[dom_struct]
pub struct CSSGroupingRule {
cssrule: CSSRule,
... | use crate::dom::cssrule::CSSRule; | random_line_split |
cssgroupingrule.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 crate::dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods;
use crate::dom::bindi... | (&self) -> DomRoot<CSSRuleList> {
// XXXManishearth check origin clean flag
self.rulelist()
}
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-insertrule
fn InsertRule(&self, rule: DOMString, index: u32) -> Fallible<u32> {
self.rulelist().insert_rule(&rule, index, /* nested */... | CssRules | identifier_name |
build.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/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "bindgen")]
extern crate bindgen;
#[cfg(feature = "bindgen"... | let script = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("properties").join("build.py");
let product = if cfg!(feature = "gecko") { "gecko" } else { "servo" };
let status = Command::new(&*PYTHON)
.arg(&script)
.arg(product)
.arg("style-crate")
.status()
... | random_line_split | |
build.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/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "bindgen")]
extern crate bindgen;
#[cfg(feature = "bindgen"... |
if Command::new("python.exe").arg("--version").output().is_ok() {
return "python.exe".to_owned();
}
panic!(concat!("Can't find python (tried python2.7.exe, python27.exe, and python.exe)! ",
"Try fixing PATH or setting the PYTHON env var"));
}
#[cfg(not(windows))]
fn find_pytho... | {
return "python27.exe".to_owned();
} | conditional_block |
build.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/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "bindgen")]
extern crate bindgen;
#[cfg(feature = "bindgen"... | if!status.success() {
exit(1)
}
}
fn main() {
let gecko = cfg!(feature = "gecko");
let servo = cfg!(feature = "servo");
if!(gecko || servo) {
panic!("The style crate requires enabling one of its'servo' or 'gecko' feature flags");
}
if gecko && servo {
panic!("The st... | {
for entry in WalkDir::new("properties") {
let entry = entry.unwrap();
match entry.path().extension().and_then(|e| e.to_str()) {
Some("mako") | Some("rs") | Some("py") | Some("zip") => {
println!("cargo:rerun-if-changed={}", entry.path().display());
}
... | identifier_body |
build.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/. */
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "bindgen")]
extern crate bindgen;
#[cfg(feature = "bindgen"... | () {
for entry in WalkDir::new("properties") {
let entry = entry.unwrap();
match entry.path().extension().and_then(|e| e.to_str()) {
Some("mako") | Some("rs") | Some("py") | Some("zip") => {
println!("cargo:rerun-if-changed={}", entry.path().display());
}
... | generate_properties | identifier_name |
template-fun-ty.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo {
pub _address: u8,
}
pub type Foo_FunctionPtr<T> =
::std::option::Option<unsafe extern "C" fn() -> T>;
#[repr(C)]
#[derive(... | {
pub _address: u8,
}
pub type RefPtr_Proxy_member_function<R, Args> =
::std::option::Option<unsafe extern "C" fn(arg1: Args) -> R>;
pub type Returner<T> = ::std::option::Option<unsafe extern "C" fn() -> T>;
| RefPtr_Proxy | identifier_name |
template-fun-ty.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Foo {
pub _address: u8,
}
pub type Foo_FunctionPtr<T> =
::std::option::Option<unsafe extern "C" fn() -> T>;
#[repr(C)]
#[derive(... | }
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RefPtr_Proxy {
pub _address: u8,
}
pub type RefPtr_Proxy_member_function<R, Args> =
::std::option::Option<unsafe extern "C" fn(arg1: Args) -> R>;
pub type Returner<T> = ::std::option::Option<unsafe extern "C" fn() -> T>; | pub struct RefPtr {
pub _address: u8, | random_line_split |
upload.rs | extern crate mig;
#[macro_use]
extern crate log;
extern crate env_logger;
use mig::quic::threaded::{QuicConnection};
| let args = ::std::env::args;
if args().len()!= 2 || args().nth(1) == Some("--help".to_string()) {
println!("Usage: upload clientip:port < file");
return;
}
let address = args().nth(1).unwrap();
let connection = match QuicConnection::new(&*address) {
Ok(connection) => {
... |
fn main() {
env_logger::init().unwrap();
| random_line_split |
upload.rs | extern crate mig;
#[macro_use]
extern crate log;
extern crate env_logger;
use mig::quic::threaded::{QuicConnection};
fn | () {
env_logger::init().unwrap();
let args = ::std::env::args;
if args().len()!= 2 || args().nth(1) == Some("--help".to_string()) {
println!("Usage: upload clientip:port < file");
return;
}
let address = args().nth(1).unwrap();
let connection = match QuicConnection::new(&*addr... | main | identifier_name |
upload.rs | extern crate mig;
#[macro_use]
extern crate log;
extern crate env_logger;
use mig::quic::threaded::{QuicConnection};
fn main() |
info!("Running client connected to {}", address);
let mut stream = connection.get_stream(2);
info!("Got stream 2. Copying from the stream to stdout.");
//std::io::copy(&mut stream, &mut std::io::stdout());
std::io::copy(&mut std::io::stdin(), &mut stream).unwrap();
info!("Finished uploading... | {
env_logger::init().unwrap();
let args = ::std::env::args;
if args().len() != 2 || args().nth(1) == Some("--help".to_string()) {
println!("Usage: upload clientip:port < file");
return;
}
let address = args().nth(1).unwrap();
let connection = match QuicConnection::new(&*addres... | identifier_body |
main.rs | extern crate regex;
use regex::Regex;
const MIN_BOUND: u32 = 0;
const MAX_BOUND: u32 = 10;//((1u64 << 32) - 1) as u32;
#[derive(Debug)]
struct Range {
lo: u32,
hi: u32,
}
impl Range {
fn default() -> Range {
Range {
lo: MIN_BOUND,
hi: MAX_BOUND,
}
}
fn new(... |
}
}
fn mark_off(a: &mut[bool; MAX_BOUND as usize], r: Range) {
for i in r {
a[i as usize] = false;
}
}
fn main() {
let test_input = "5-8\n0-2\n4-7";
let ranges = test_input.lines().map(Range::parse);
let mut a = [true; MAX_BOUND as usize];
for r in ranges {
println!("{:?}"... | {
Some(lo)
} | conditional_block |
main.rs | extern crate regex;
use regex::Regex;
const MIN_BOUND: u32 = 0;
const MAX_BOUND: u32 = 10;//((1u64 << 32) - 1) as u32;
#[derive(Debug)]
struct Range {
lo: u32,
hi: u32,
}
impl Range {
fn default() -> Range {
Range {
lo: MIN_BOUND,
hi: MAX_BOUND,
}
}
fn new(... | fn mark_off(a: &mut[bool; MAX_BOUND as usize], r: Range) {
for i in r {
a[i as usize] = false;
}
}
fn main() {
let test_input = "5-8\n0-2\n4-7";
let ranges = test_input.lines().map(Range::parse);
let mut a = [true; MAX_BOUND as usize];
for r in ranges {
println!("{:?}", r);
... | random_line_split | |
main.rs | extern crate regex;
use regex::Regex;
const MIN_BOUND: u32 = 0;
const MAX_BOUND: u32 = 10;//((1u64 << 32) - 1) as u32;
#[derive(Debug)]
struct Range {
lo: u32,
hi: u32,
}
impl Range {
fn | () -> Range {
Range {
lo: MIN_BOUND,
hi: MAX_BOUND,
}
}
fn new(lo: u32, hi: u32) -> Range {
assert!(lo <= hi);
Range { lo: lo, hi: hi }
}
fn parse(s: &str) -> Range {
let re: Regex = Regex::new(r"^(\d+)-(\d+)$").unwrap();
match re.c... | default | identifier_name |
main.rs | extern crate regex;
use regex::Regex;
const MIN_BOUND: u32 = 0;
const MAX_BOUND: u32 = 10;//((1u64 << 32) - 1) as u32;
#[derive(Debug)]
struct Range {
lo: u32,
hi: u32,
}
impl Range {
fn default() -> Range {
Range {
lo: MIN_BOUND,
hi: MAX_BOUND,
}
}
fn new(... |
fn parse(s: &str) -> Range {
let re: Regex = Regex::new(r"^(\d+)-(\d+)$").unwrap();
match re.captures(s) {
None => Range::default(),
Some(caps) => {
match (caps.at(1), caps.at(2)) {
(Some(a), Some(b)) => {
Range::ne... | {
assert!(lo <= hi);
Range { lo: lo, hi: hi }
} | identifier_body |
mod.rs | extern mod std;
use std::io::fs::{File, mkdir_recursive};
use std::{os, ptr, str};
use std::io::{Reader, io_error};
use std::path::Path;
use std::libc::{c_void};
use std::unstable::atomics::{AtomicBool, Acquire, Release, INIT_ATOMIC_BOOL};
use nspr::raw::nspr::*;
use super::nss::raw::*;
static mut NSS_INIT_START: A... | () -> NSS {
NSS { nss_ctx: None, nss_cert_mod: None, cfg_dir: None, }
}
pub fn set_cfg_dir(&mut self, cfg_dir: &str)
{
self.cfg_dir = Some(cfg_dir.to_owned());
}
pub fn nodb_init(&mut self) -> SECStatus {
unsafe {
if(self.start_init() == SECSuccess) { return SECSuccess; }
if(NSS_NoDB_Init(ptr::nu... | new | identifier_name |
mod.rs | extern mod std;
use std::io::fs::{File, mkdir_recursive};
use std::{os, ptr, str};
use std::io::{Reader, io_error};
use std::path::Path;
use std::libc::{c_void};
use std::unstable::atomics::{AtomicBool, Acquire, Release, INIT_ATOMIC_BOOL};
use nspr::raw::nspr::*;
use super::nss::raw::*;
static mut NSS_INIT_START: A... |
if(NSS_NoDB_Init(ptr::null()) == SECFailure){
fail!("NSS is borked!");
}
self.finish_init()
}
}
fn start_init(&mut self) -> SECStatus {
unsafe {
if(NSS_IsInitialized() == PRTrue ) { return SECSuccess; }
if NSS_INIT_START.swap(true, Acquire) { while!NSS_INIT_END.load(Release)... | { return SECSuccess; } | conditional_block |
mod.rs | extern mod std;
use std::io::fs::{File, mkdir_recursive};
use std::{os, ptr, str};
use std::io::{Reader, io_error};
use std::path::Path;
use std::libc::{c_void};
use std::unstable::atomics::{AtomicBool, Acquire, Release, INIT_ATOMIC_BOOL};
use nspr::raw::nspr::*;
use super::nss::raw::*;
static mut NSS_INIT_START: A... |
if(cfg_path.exists()) {
nss_path.with_c_str(|nssdb| self.nss_ctx = Some(NSS_InitContext(nssdb, ptr::null(), ptr::null(), ptr::null(), ptr::null(), NSS_INIT_PK11RELOAD)));
}
if(NSS_IsInitialized() == PRFalse) {
if(NSS_NoDB_Init(ptr::null()) == SECFailure){
fai... | else {
cfg_path = Path::init("/etc/pki/nssdb");
nss_path = format!("sql:{}", system_path.as_str().unwrap());
}
} | random_line_split |
mod.rs | extern mod std;
use std::io::fs::{File, mkdir_recursive};
use std::{os, ptr, str};
use std::io::{Reader, io_error};
use std::path::Path;
use std::libc::{c_void};
use std::unstable::atomics::{AtomicBool, Acquire, Release, INIT_ATOMIC_BOOL};
use nspr::raw::nspr::*;
use super::nss::raw::*;
static mut NSS_INIT_START: A... |
pub fn init(&mut self) -> SECStatus {
unsafe {
if(self.start_init() == SECSuccess) { return SECSuccess; }
self.cfg_dir = match self.cfg_dir {
None => Some(os::getenv("SSL_DIR").unwrap_or(format!("{}/.pki/nssdb", os::getenv("HOME").unwrap_or(~".")).to_owned())),
Some(ref s) => Some(s.to_ow... | {
unsafe {
if(NSS_IsInitialized() == PRTrue ) { return SECSuccess; }
if NSS_INIT_START.swap(true, Acquire) { while !NSS_INIT_END.load(Release) { std::task::deschedule(); } }
SECFailure //Not really...
}
} | identifier_body |
gradient.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericEndingShape and GenericGradientItem.
use app_units::Au;
use crate::... |
/// Returns the distance to the nearest or farthest sides depending on the comparator.
///
/// The first return value is horizontal distance the second vertical distance.
fn distance_to_sides<F>(size: &Size2D<Au>, center: &Point2D<Au>, cmp: F) -> Size2D<Au>
where
F: Fn(Au, Au) -> Au,
{
let top_side = center.y;... |
let dist = distance_to_sides(size, center, cmp);
Au::from_f32_px(dist.width.to_f32_px().hypot(dist.height.to_f32_px()))
}
| identifier_body |
gradient.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericEndingShape and GenericGradientItem.
use app_units::Au;
use crate::... | F>(size: &Size2D<Au>, center: &Point2D<Au>, cmp: F) -> Au
where
F: Fn(Au, Au) -> Au,
{
let dist = distance_to_sides(size, center, cmp);
Au::from_f32_px(dist.width.to_f32_px().hypot(dist.height.to_f32_px()))
}
/// Returns the distance to the nearest or farthest sides depending on the comparator.
///
/// The... | istance_to_corner< | identifier_name |
gradient.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericEndingShape and GenericGradientItem.
use app_units::Au;
use crate::... | stop_run = Some(StopRun {
start_offset,
end_offset,
start_index: i - 1,
stop_count: end_index,
})
}
let stop_run = stop_run.unwrap();
l... | random_line_split | |
performance.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use rustc_serialize::json;
... | _ => ActorMessageStatus::Ignored,
})
}
}
impl PerformanceActor {
pub fn new(name: String) -> PerformanceActor {
PerformanceActor {
name: name,
}
}
} | ActorMessageStatus::Processed
}, | random_line_split |
performance.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use protocol::JsonPacketStream;
use rustc_serialize::json;
... | (name: String) -> PerformanceActor {
PerformanceActor {
name: name,
}
}
}
| new | identifier_name |
tcp-stress.rs | // Copyright 2012-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-MI... | ,
Err(e) => debug!("{}", e)
}
tx.send(()).unwrap();
});
}
// Wait for all clients to exit, but don't wait for the server to exit. The
// server just runs infinitely.
drop(tx);
for _ in 0..1000 {
rx.recv().unwrap();
}
unsafe { libc::exi... | {
let mut stream = stream;
stream.write(&[1]);
let mut buf = [0];
stream.read(&mut buf);
} | conditional_block |
tcp-stress.rs | // Copyright 2012-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-MI... | }
};
stream.read_byte();
stream.write(&[2]);
}
});
let addr = rx.recv().unwrap();
let (tx, rx) = channel();
for _ in 0..1000 {
let tx = tx.clone();
Builder::new().stack_size(64 * 1024).spawn(move|| {
match TcpStream... | {
// This test has a chance to time out, try to not let it time out
thread::spawn(move|| -> () {
use std::old_io::timer;
timer::sleep(Duration::milliseconds(30 * 1000));
println!("timed out!");
unsafe { libc::exit(1) }
});
let (tx, rx) = channel();
thread::spawn(move... | identifier_body |
tcp-stress.rs | // Copyright 2012-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-MI... | };
stream.read_byte();
stream.write(&[2]);
}
});
let addr = rx.recv().unwrap();
let (tx, rx) = channel();
for _ in 0..1000 {
let tx = tx.clone();
Builder::new().stack_size(64 * 1024).spawn(move|| {
match TcpStream::connect(addr) {
... | continue;
} | random_line_split |
tcp-stress.rs | // Copyright 2012-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-MI... | () {
// This test has a chance to time out, try to not let it time out
thread::spawn(move|| -> () {
use std::old_io::timer;
timer::sleep(Duration::milliseconds(30 * 1000));
println!("timed out!");
unsafe { libc::exit(1) }
});
let (tx, rx) = channel();
thread::spawn(m... | main | identifier_name |
stateful_eval.rs | use std::sync::{Mutex, Arc};
use std::result::Result;
use std::error::Error;
use serde_json::*;
use gossyp_base::*;
use gossyp_base::basic::*;
use super::binding_environment::*;
use super::script_interpreter::*;
use super::bind_statement::*;
use super::evaluate_statement::*;
use super::script::*;
use super::bound_scr... | () {
let eval = StatefulEvalTool::new();
let env = EmptyEnvironment::new();
// var x = 1
let assign_x = eval.evaluate_unbound_statement(&Script::Var(ScriptToken::identifier("x"), Expression::Number(ScriptToken::number("1"))), &env);
assert!(assign_x.is_ok());
// ... | can_bind_variable_using_stateful_tool | identifier_name |
stateful_eval.rs | use std::sync::{Mutex, Arc};
use std::result::Result;
use std::error::Error;
use serde_json::*;
use gossyp_base::*;
use gossyp_base::basic::*;
use super::binding_environment::*;
use super::script_interpreter::*;
use super::bind_statement::*;
use super::evaluate_statement::*;
use super::script::*;
use super::bound_scr... |
#[cfg(test)]
mod test {
use super::*;
#[test]
fn can_bind_variable_using_stateful_tool() {
let eval = StatefulEvalTool::new();
let env = EmptyEnvironment::new();
// var x = 1
let assign_x = eval.evaluate_unbound_statement(&Script::Var(ScriptToken::identifier("x"), ... | {
define_new_tool(environment, &eval_name, Box::new(StatefulEvalTool::new()))?;
Ok(())
} | identifier_body |
stateful_eval.rs | use std::sync::{Mutex, Arc};
use std::result::Result;
use std::error::Error;
use serde_json::*;
use gossyp_base::*;
use gossyp_base::basic::*;
use super::binding_environment::*;
use super::script_interpreter::*;
use super::bind_statement::*;
use super::evaluate_statement::*;
use super::script::*;
use super::bound_scr... | Ok(script) => self.evaluate_unbound_statement(&script, environment),
Err(script_error) => Err(json![{
"error": "JSON input decode failed",
"description": script_error.description(),
}])
}
}
}
///
/// Tool function that c... | .map(|statements| Script::Sequence(statements));
match script { | random_line_split |
utils.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 rustc::front::map as ast_map;
use rustc::lint::LateContext;
use rustc::middle::def;
use rustc::middle::def_id:... | }
/// check if a DefId's path matches the given absolute type path
/// usage e.g. with
/// `match_def_path(cx, id, &["core", "option", "Option"])`
pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
cx.tcx.with_path(def_id, |iter| iter.map(|elem| elem.name())
.zip(path.iter()).a... | {
match map.find(map.get_parent(id)) {
Some(ast_map::NodeImplItem(itm)) => {
match itm.node {
hir::MethodImplItem(ref sig, _) => sig.unsafety == hir::Unsafety::Unsafe,
_ => false
}
},
Some(ast_map::NodeItem(itm)) => {
match ... | identifier_body |
utils.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 rustc::lint::LateContext;
use rustc::middle::def;
use rustc::middle::def_id::DefId;
use rustc_front::hir;
use syntax::ast;
use syntax::attr::mark_used;
use syntax::ptr::P;
/// Matches a type with a provided string, and returns its type parameters if successful
///
/// Try not to use this for types defined in crat... |
use rustc::front::map as ast_map; | random_line_split |
utils.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 rustc::front::map as ast_map;
use rustc::lint::LateContext;
use rustc::middle::def;
use rustc::middle::def_id:... | (cx: &LateContext, did: DefId, value: &str) -> bool {
cx.tcx.get_attrs(did).iter().any(|attr| {
match attr.node.value.node {
ast::MetaNameValue(ref name, ref val) if &**name == "servo_lang" => {
match val.node {
ast::LitStr(ref v, _) if &**v == value => {
... | match_lang_did | identifier_name |
imagedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::ImageDataBinding;
use crate::dom::bindings::codegen::Bindings::Image... | width: width,
height: height,
data: Heap::default(),
});
if let Some(jsobject) = opt_jsobject {
(*imagedata).data.set(jsobject);
} else {
let len = width * height * 4;
let cx = global.get_cx();
rooted!(in (cx) l... | }
let imagedata = Box::new(ImageData {
reflector_: Reflector::new(), | random_line_split |
imagedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::ImageDataBinding;
use crate::dom::bindings::codegen::Bindings::Image... |
}
let height = opt_height.unwrap();
if height == 0 {
return Err(Error::IndexSize);
}
let imagedata = Box::new(ImageData {
reflector_: Reflector::new(),
width: width,
height: height,
data: Heap::default(),
});
... | {
opt_height = Some(height);
} | conditional_block |
imagedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::ImageDataBinding;
use crate::dom::bindings::codegen::Bindings::Image... |
// https://html.spec.whatwg.org/multipage/#dom-imagedata-height
fn Height(&self) -> u32 {
self.height
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-imagedata-data
unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> {
NonNull::new(self.data.ge... | {
self.width
} | identifier_body |
imagedata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::ImageDataBinding;
use crate::dom::bindings::codegen::Bindings::Image... | (global: &GlobalScope, width: u32, height: u32) -> Fallible<DomRoot<Self>> {
unsafe { Self::new_with_jsobject(global, width, Some(height), None) }
}
// https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4
#[allow(unsafe_code)]
#[allow(unused_variables)]
pub unsafe fn C... | Constructor | identifier_name |
bench.rs | use std::io::process::ExitStatus;
use cargo::ops;
use cargo::core::MultiShell;
use cargo::util::{CliResult, CliError, CargoError};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use docopt;
docopt!(Options, "
Execute all benchmarks of a local package
Usage:
cargo bench [options] [--] [<args>...]... | match err {
None => Ok(None),
Some(err) => {
Err(match err.exit {
Some(ExitStatus(i)) => CliError::new("", i as uint),
_ => CliError::from_boxed(err.mark_human(), 101)
})
}
}
}
| {
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
shell.set_verbose(options.flag_verbose);
let mut ops = ops::TestOptions {
no_run: options.flag_no_run,
compile_opts: ops::CompileOptions {
update: false,
env: "bench",
shell: shell... | identifier_body |
bench.rs | use std::io::process::ExitStatus;
use cargo::ops;
use cargo::core::MultiShell;
use cargo::util::{CliResult, CliError, CargoError};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use docopt;
docopt!(Options, "
Execute all benchmarks of a local package
Usage:
cargo bench [options] [--] [<args>...]... | (options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
shell.set_verbose(options.flag_verbose);
let mut ops = ops::TestOptions {
no_run: options.flag_no_run,
compile_opts: ops::CompileOptions {
... | execute | identifier_name |
bench.rs | use std::io::process::ExitStatus;
use cargo::ops;
use cargo::core::MultiShell;
use cargo::util::{CliResult, CliError, CargoError};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
use docopt;
docopt!(Options, "
Execute all benchmarks of a local package
Usage:
cargo bench [options] [--] [<args>...]... | Err(match err.exit {
Some(ExitStatus(i)) => CliError::new("", i as uint),
_ => CliError::from_boxed(err.mark_human(), 101)
})
}
}
} | random_line_split | |
match_single_binding.rs | // run-rustfix
#![warn(clippy::match_single_binding)]
#![allow(unused_variables, clippy::many_single_char_names, clippy::toplevel_ref_arg)]
struct Point {
x: i32,
y: i32,
}
fn coords() -> Point {
Point { x: 1, y: 2 }
}
macro_rules! foo {
($param:expr) => {
match $param {
_ => pri... | () {
let a = 1;
let b = 2;
let c = 3;
// Lint
match (a, b, c) {
(x, y, z) => {
println!("{} {} {}", x, y, z);
},
}
// Lint
match (a, b, c) {
(x, y, z) => println!("{} {} {}", x, y, z),
}
// Ok
foo!(a);
// Ok
match a {
2 => p... | main | identifier_name |
match_single_binding.rs | // run-rustfix
#![warn(clippy::match_single_binding)]
#![allow(unused_variables, clippy::many_single_char_names, clippy::toplevel_ref_arg)]
struct Point {
x: i32,
y: i32,
}
fn coords() -> Point {
Point { x: 1, y: 2 }
}
macro_rules! foo {
($param:expr) => {
match $param {
_ => pri... | }
// Ok
let d = Some(5);
match d {
Some(d) => println!("{}", d),
_ => println!("None"),
}
// Lint
match a {
_ => println!("whatever"),
}
// Lint
match a {
_ => {
let x = 29;
println!("x has a value of {}", x);
},
... | {
let a = 1;
let b = 2;
let c = 3;
// Lint
match (a, b, c) {
(x, y, z) => {
println!("{} {} {}", x, y, z);
},
}
// Lint
match (a, b, c) {
(x, y, z) => println!("{} {} {}", x, y, z),
}
// Ok
foo!(a);
// Ok
match a {
2 => prin... | identifier_body |
match_single_binding.rs | // run-rustfix
#![warn(clippy::match_single_binding)]
#![allow(unused_variables, clippy::many_single_char_names, clippy::toplevel_ref_arg)]
struct Point {
x: i32,
y: i32,
}
fn coords() -> Point {
Point { x: 1, y: 2 } | match $param {
_ => println!("whatever"),
}
};
}
fn main() {
let a = 1;
let b = 2;
let c = 3;
// Lint
match (a, b, c) {
(x, y, z) => {
println!("{} {} {}", x, y, z);
},
}
// Lint
match (a, b, c) {
(x, y, z) => println!(... | }
macro_rules! foo {
($param:expr) => { | random_line_split |
builtin-superkinds-double-superkind.rs | // Copyright 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 ... | trait Foo : Send+Share { }
impl <T: Share> Foo for (T,) { } //~ ERROR cannot implement this trait
impl <T: Send> Foo for (T,T) { } //~ ERROR cannot implement this trait
impl <T: Send+Share> Foo for (T,T,T) { } // (ok)
fn main() { } | random_line_split | |
builtin-superkinds-double-superkind.rs | // Copyright 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 ... | { } | identifier_body | |
builtin-superkinds-double-superkind.rs | // Copyright 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 ... | () { }
| main | identifier_name |
lib.rs | //! Rust library for Pico encoding.
//!
//! This is a library implementing the Pico file encoding used for storing
//! malware. See http://mons-pico.github.io/ for details on this.
extern crate md5;
extern crate rand;
#[warn(missing_docs)]
pub mod constants;
pub mod errors;
mod pico;
pub mod file;
mod crypt;
mod in... |
/// Obtain the major version number for the encoding implemented by this
/// library. See also `minor`.
pub fn major() -> u16 { MAJOR }
/// Obtain the minor version number for the encoding implemented by this
/// library. See also `major`.
pub fn minor() -> u16 { MINOR }
#[test]
fn check_version() {
assert_eq... | { MAGIC } | identifier_body |
lib.rs | //! Rust library for Pico encoding.
//!
//! This is a library implementing the Pico file encoding used for storing
//! malware. See http://mons-pico.github.io/ for details on this.
extern crate md5;
extern crate rand;
#[warn(missing_docs)]
pub mod constants;
pub mod errors;
mod pico;
pub mod file;
mod crypt;
mod in... | pub fn magic() -> u16 { MAGIC }
/// Obtain the major version number for the encoding implemented by this
/// library. See also `minor`.
pub fn major() -> u16 { MAJOR }
/// Obtain the minor version number for the encoding implemented by this
/// library. See also `major`.
pub fn minor() -> u16 { MINOR }
#[test]
fn ... | /// ``` | random_line_split |
lib.rs | //! Rust library for Pico encoding.
//!
//! This is a library implementing the Pico file encoding used for storing
//! malware. See http://mons-pico.github.io/ for details on this.
extern crate md5;
extern crate rand;
#[warn(missing_docs)]
pub mod constants;
pub mod errors;
mod pico;
pub mod file;
mod crypt;
mod in... | () {
assert_eq!(magic(), MAGIC);
}
| check_magic | identifier_name |
timer.rs | use cpu;
use mem;
#[derive(Default)]
pub struct Timer {
div_counter: u8,
timer_counter: u16,
} | pub fn on_clock(&mut self, mem: &mut mem::Mem) {
self.update_div(mem);
self.update_timer(mem);
}
fn update_div(&mut self, mem: &mut mem::Mem) {
self.div_counter = self.div_counter.overflowing_add(1).0;
if self.div_counter == 0 {
let div = mem.read_reg(mem::RegAdd... |
impl Timer { | random_line_split |
timer.rs | use cpu;
use mem;
#[derive(Default)]
pub struct Timer {
div_counter: u8,
timer_counter: u16,
}
impl Timer {
pub fn | (&mut self, mem: &mut mem::Mem) {
self.update_div(mem);
self.update_timer(mem);
}
fn update_div(&mut self, mem: &mut mem::Mem) {
self.div_counter = self.div_counter.overflowing_add(1).0;
if self.div_counter == 0 {
let div = mem.read_reg(mem::RegAddr::DIV);
... | on_clock | identifier_name |
timer.rs | use cpu;
use mem;
#[derive(Default)]
pub struct Timer {
div_counter: u8,
timer_counter: u16,
}
impl Timer {
pub fn on_clock(&mut self, mem: &mut mem::Mem) |
fn update_div(&mut self, mem: &mut mem::Mem) {
self.div_counter = self.div_counter.overflowing_add(1).0;
if self.div_counter == 0 {
let div = mem.read_reg(mem::RegAddr::DIV);
let (new_div, _) = div.overflowing_add(1);
mem.write_reg(mem::RegAddr::DIV, new_div);
... | {
self.update_div(mem);
self.update_timer(mem);
} | identifier_body |
fasta_reader.rs | use crate::common::Region;
use anyhow::Context;
use anyhow::Result;
use bio::io::fasta;
use itertools::Itertools;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
pub fn read_fasta<P: AsRef<Path> + std::fmt::Debug>(
path: P,
region: &Region,
compensate_0_basing: bool,
) -> Result<V... | (path: &Path) -> Result<HashMap<String, u64>> {
let index = fasta::Index::with_fasta_file(&path).context("error reading input FASTA")?;
let sequences = index.sequences();
Ok(sequences
.iter()
.map(|s| (s.name.to_owned(), s.len))
.collect())
}
#[derive(Serialize, Clone, Debug, PartialEq... | get_fasta_lengths | identifier_name |
fasta_reader.rs | use crate::common::Region;
use anyhow::Context;
use anyhow::Result;
use bio::io::fasta;
use itertools::Itertools;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
pub fn read_fasta<P: AsRef<Path> + std::fmt::Debug>(
path: P,
region: &Region,
compensate_0_basing: bool,
) -> Result<V... |
for a in seq {
let base = char::from(a);
let marker = base.to_uppercase().collect_vec().pop().unwrap();
let b = Nucleobase {
position: ind,
marker_type: marker,
row: 0,
repeat: base.is_lowercase(),
};
fasta.push(b);
ind... | {
ind += 1;
} | conditional_block |
fasta_reader.rs | use crate::common::Region;
use anyhow::Context;
use anyhow::Result;
use bio::io::fasta;
use itertools::Itertools;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
pub fn read_fasta<P: AsRef<Path> + std::fmt::Debug>(
path: P,
region: &Region,
compensate_0_basing: bool,
) -> Result<V... |
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Nucleobase {
position: u64,
marker_type: char,
row: u8,
repeat: bool,
}
impl Nucleobase {
pub fn get_marker_type(&self) -> char {
self.marker_type
}
}
| {
let index = fasta::Index::with_fasta_file(&path).context("error reading input FASTA")?;
let sequences = index.sequences();
Ok(sequences
.iter()
.map(|s| (s.name.to_owned(), s.len))
.collect())
} | identifier_body |
fasta_reader.rs | use crate::common::Region;
use anyhow::Context; | use itertools::Itertools;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
pub fn read_fasta<P: AsRef<Path> + std::fmt::Debug>(
path: P,
region: &Region,
compensate_0_basing: bool,
) -> Result<Vec<Nucleobase>> {
let mut reader = fasta::IndexedReader::from_file(&path).unwrap();
... | use anyhow::Result;
use bio::io::fasta; | random_line_split |
unique.rs | use crate::convert::From;
use crate::fmt;
use crate::marker::{PhantomData, Unsize};
use crate::mem;
use crate::ops::{CoerceUnsized, DispatchFromDyn};
/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
/// of this wrapper owns the referent. Useful for building abstractions like
/// `Box<T>`,... |
}
/// Acquires the underlying `*mut` pointer.
#[inline]
pub const fn as_ptr(self) -> *mut T {
self.pointer as *mut T
}
/// Dereferences the content.
///
/// The resulting lifetime is bound to self so this behaves "as if"
/// it were actually an instance of T that is gettin... | {
None
} | conditional_block |
unique.rs | use crate::convert::From;
use crate::fmt;
use crate::marker::{PhantomData, Unsize};
use crate::mem;
use crate::ops::{CoerceUnsized, DispatchFromDyn};
/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
/// of this wrapper owns the referent. Useful for building abstractions like
/// `Box<T>`,... | (&self) -> Self {
*self
}
}
#[unstable(feature = "ptr_internals", issue = "none")]
impl<T:?Sized> Copy for Unique<T> {}
#[unstable(feature = "ptr_internals", issue = "none")]
impl<T:?Sized, U:?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> {}
#[unstable(feature = "ptr_internals", issue ... | clone | identifier_name |
unique.rs | use crate::convert::From;
use crate::fmt;
use crate::marker::{PhantomData, Unsize};
use crate::mem;
use crate::ops::{CoerceUnsized, DispatchFromDyn};
/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
/// of this wrapper owns the referent. Useful for building abstractions like
/// `Box<T>`,... | /// unenforced by the type system; the abstraction using the
/// `Unique` must enforce it.
#[unstable(feature = "ptr_internals", issue = "none")]
unsafe impl<T: Send +?Sized> Send for Unique<T> {}
/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
/// reference is unaliased. Note that this aliasin... |
/// `Unique` pointers are `Send` if `T` is `Send` because the data they
/// reference is unaliased. Note that this aliasing invariant is | random_line_split |
unique.rs | use crate::convert::From;
use crate::fmt;
use crate::marker::{PhantomData, Unsize};
use crate::mem;
use crate::ops::{CoerceUnsized, DispatchFromDyn};
/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
/// of this wrapper owns the referent. Useful for building abstractions like
/// `Box<T>`,... |
}
| {
// SAFETY: A mutable reference cannot be null
unsafe { Unique { pointer: reference as *mut T, _marker: PhantomData } }
} | identifier_body |
window.rs | use std::ops::{Bound, Range, RangeBounds};
/// A owned window around an underlying buffer.
///
/// Normally slices work great for considering sub-portions of a buffer, but
/// unfortunately a slice is a *borrowed* type in Rust which has an associated
/// lifetime. When working with future and async I/O these lifetimes... | <T> {
inner: T,
range: Range<usize>,
}
impl<T: AsRef<[u8]>> Window<T> {
/// Creates a new window around the buffer `t` defaulting to the entire
/// slice.
///
/// Further methods can be called on the returned `Window<T>` to alter the
/// window into the data provided.
pub fn new(t: T) -... | Window | identifier_name |
window.rs | use std::ops::{Bound, Range, RangeBounds};
/// A owned window around an underlying buffer.
///
/// Normally slices work great for considering sub-portions of a buffer, but
/// unfortunately a slice is a *borrowed* type in Rust which has an associated
/// lifetime. When working with future and async I/O these lifetimes... |
}
| {
&mut self.inner.as_mut()[self.range.start..self.range.end]
} | identifier_body |
window.rs | use std::ops::{Bound, Range, RangeBounds};
/// A owned window around an underlying buffer.
/// | /// always appropriate, and are sometimes difficult to store in tasks. This
/// type strives to fill this gap by providing an "owned slice" around an
/// underlying buffer of bytes.
///
/// A `Window<T>` wraps an underlying buffer, `T`, and has configurable
/// start/end indexes to alter the behavior of the `AsRef<[u8]... | /// Normally slices work great for considering sub-portions of a buffer, but
/// unfortunately a slice is a *borrowed* type in Rust which has an associated
/// lifetime. When working with future and async I/O these lifetimes are not | random_line_split |
issue-5554.rs | // Copyright 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 ... | macro_rules! constants {
() => {
let _ : X<int> = Default::default();
}
}
pub fn main() {
constants!();
} | }
}
| random_line_split |
issue-5554.rs | // Copyright 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 ... | () {
constants!();
}
| main | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! This module provides algorithms for accessing and updating a Merkle Accumulator structure
//! persisted in a key-value store. Note that this doesn't write to the storage directly, rather,
//! it reads from i... | Self {
reader,
num_leaves,
hasher: PhantomData,
}
}
/// implementation for pub interface `MerkleAccumulator::append`
fn append(&self, new_leaves: &[HashValue]) -> Result<(HashValue, Vec<Node>)> {
// Deal with the case where new_leaves is empty
... | R: HashReader,
H: CryptoHasher,
{
fn new(reader: &'a R, num_leaves: LeafCount) -> Self { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.