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 |
|---|---|---|---|---|
redundant_field_names.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::{meets_msrv, msrvs};
use rustc_ast::ast::{Expr, ExprKind};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_semver::RustcVersion;
use rustc_session::{declare_tool_lint... | REDUNDANT_FIELD_NAMES,
field.span,
"redundant field names in struct initialization",
"replace it with",
field.ident.to_string(),
Applicability::MachineA... | {
if !meets_msrv(self.msrv.as_ref(), &msrvs::FIELD_INIT_SHORTHAND) {
return;
}
if in_external_macro(cx.sess, expr.span) {
return;
}
if let ExprKind::Struct(ref se) = expr.kind {
for field in &se.fields {
if field.is_shorthand {... | identifier_body |
redundant_field_names.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::{meets_msrv, msrvs};
use rustc_ast::ast::{Expr, ExprKind};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_semver::RustcVersion;
use rustc_session::{declare_tool_lint... |
if let ExprKind::Struct(ref se) = expr.kind {
for field in &se.fields {
if field.is_shorthand {
continue;
}
if let ExprKind::Path(None, path) = &field.expr.kind {
if path.segments.len() == 1
... | {
return;
} | conditional_block |
redundant_field_names.rs | use clippy_utils::diagnostics::span_lint_and_sugg; | use rustc_middle::lint::in_external_macro;
use rustc_semver::RustcVersion;
use rustc_session::{declare_tool_lint, impl_lint_pass};
declare_clippy_lint! {
/// ### What it does
/// Checks for fields in struct literals where shorthands
/// could be used.
///
/// ### Why is this bad?
/// If the fie... | use clippy_utils::{meets_msrv, msrvs};
use rustc_ast::ast::{Expr, ExprKind};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass}; | random_line_split |
redundant_field_names.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::{meets_msrv, msrvs};
use rustc_ast::ast::{Expr, ExprKind};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_semver::RustcVersion;
use rustc_session::{declare_tool_lint... | {
msrv: Option<RustcVersion>,
}
impl RedundantFieldNames {
#[must_use]
pub fn new(msrv: Option<RustcVersion>) -> Self {
Self { msrv }
}
}
impl_lint_pass!(RedundantFieldNames => [REDUNDANT_FIELD_NAMES]);
impl EarlyLintPass for RedundantFieldNames {
fn check_expr(&mut self, cx: &EarlyConte... | RedundantFieldNames | identifier_name |
snmpv3.rs | use crate::rparser::*;
use crate::snmp::parse_pdu_enveloppe_version;
use crate::{gen_get_variants, Variant};
use snmp_parser::{parse_snmp_v3, SecurityModel};
pub struct SNMPv3Builder {}
impl RBuilder for SNMPv3Builder {
fn build(&self) -> Box<dyn RParser> |
fn get_l4_probe(&self) -> Option<ProbeL4> {
Some(snmpv3_probe)
}
}
pub struct SNMPv3Parser<'a> {
_name: Option<&'a [u8]>,
version: u8,
req_flags: u8,
security_model: SecurityModel,
}
impl<'a> From<SecurityModel> for Variant<'a> {
fn from(input: SecurityModel) -> Self {
inp... | {
Box::new(SNMPv3Parser::new(b"SNMPv3"))
} | identifier_body |
snmpv3.rs | use crate::rparser::*;
use crate::snmp::parse_pdu_enveloppe_version;
use crate::{gen_get_variants, Variant};
use snmp_parser::{parse_snmp_v3, SecurityModel};
pub struct SNMPv3Builder {}
impl RBuilder for SNMPv3Builder {
fn build(&self) -> Box<dyn RParser> {
Box::new(SNMPv3Parser::new(b"SNMPv3"))
}
... | (&mut self, data: &[u8], _direction: Direction) -> ParseResult {
match parse_snmp_v3(data) {
Ok((_rem, r)) => {
debug!("parse_snmp_v3: {:?}", r);
self.version = r.version as u8;
self.req_flags = r.header_data.msg_flags;
self.security_mo... | parse_l4 | identifier_name |
snmpv3.rs | use crate::rparser::*;
use crate::snmp::parse_pdu_enveloppe_version;
use crate::{gen_get_variants, Variant};
use snmp_parser::{parse_snmp_v3, SecurityModel};
pub struct SNMPv3Builder {}
impl RBuilder for SNMPv3Builder {
fn build(&self) -> Box<dyn RParser> {
Box::new(SNMPv3Parser::new(b"SNMPv3"))
}
... |
}
}
gen_get_variants! {SNMPv3Parser, "snmpv3.",
version => into,
encrypted => |s| { Some(Variant::Bool(s.req_flags & 0b010!= 0)) },
security_model => into,
}
}
pub fn snmpv3_probe(i: &[u8], _l4info: &L4Info) -> ProbeResult {
if i.len() <= 2 {
return ProbeResu... | {
warn!("parse_snmp_v3 failed: {:?}", e);
ParseResult::Error
} | conditional_block |
snmpv3.rs | use crate::rparser::*;
use crate::snmp::parse_pdu_enveloppe_version;
use crate::{gen_get_variants, Variant};
use snmp_parser::{parse_snmp_v3, SecurityModel};
pub struct SNMPv3Builder {}
impl RBuilder for SNMPv3Builder {
fn build(&self) -> Box<dyn RParser> {
Box::new(SNMPv3Parser::new(b"SNMPv3"))
}
... | version: u8,
req_flags: u8,
security_model: SecurityModel,
}
impl<'a> From<SecurityModel> for Variant<'a> {
fn from(input: SecurityModel) -> Self {
input.0.into()
}
}
impl<'a> SNMPv3Parser<'a> {
pub fn new(name: &'a [u8]) -> SNMPv3Parser<'a> {
SNMPv3Parser {
_name: ... | }
pub struct SNMPv3Parser<'a> {
_name: Option<&'a [u8]>, | random_line_split |
xc_private_method_lib.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 ... | Variant1(x) |
Variant2(x) => x
}
}
} | random_line_split | |
xc_private_method_lib.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 ... | {
Variant1(int),
Variant2(int)
}
impl Enum {
fn static_meth_enum() -> Enum {
Variant2(10)
}
fn meth_enum(&self) -> int {
match *self {
Variant1(x) |
Variant2(x) => x
}
}
}
| Enum | identifier_name |
xc_private_method_lib.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 meth_struct(&self) -> int {
self.x
}
}
pub enum Enum {
Variant1(int),
Variant2(int)
}
impl Enum {
fn static_meth_enum() -> Enum {
Variant2(10)
}
fn meth_enum(&self) -> int {
match *self {
Variant1(x) |
Variant2(x) => x
}
}
}... | {
Struct { x: 1 }
} | identifier_body |
mod.rs | use epoll::*;
use error::Result;
use handler::*;
use libc_sys::{sched_param, sched_setscheduler, rlimit, prlimit, RLIMIT_RTPRIO};
pub use nix::sys::signal::{Signal, SigSet};
use nix::sys::signalfd::{SignalFd, SFD_NONBLOCK};
use nix::{unistd, Errno};
use prop::*;
use std::os::unix::io::AsRawFd;
mod builder;
pub use se... | (mut prop: P, sig_h: S, sig_mask: SigSet, sched_opt: Option<(sched_policy, sched_param)>) -> Result<()> {
sched_opt.map(|(sched_policy, sched_param_i)| {
// set sched policy
unsafe {
let mut rlim = rlimit {
rlim_cur: sched_param_i.sched_priority as u64,
rlim_max: sched_param... | run | identifier_name |
mod.rs | use epoll::*;
use error::Result;
use handler::*;
use libc_sys::{sched_param, sched_setscheduler, rlimit, prlimit, RLIMIT_RTPRIO};
pub use nix::sys::signal::{Signal, SigSet};
use nix::sys::signalfd::{SignalFd, SFD_NONBLOCK};
use nix::{unistd, Errno};
use prop::*;
use std::os::unix::io::AsRawFd;
mod builder;
pub use se... |
}
| {
if ev.data == self.sigfd.as_raw_fd() as u64 {
match self.sigfd.read_signal() {
Ok(Some(sig)) => {
self.sig_h.on_next(Signal::from_c_int(sig.ssi_signo as i32).unwrap());
match self.sig_h.next() {
DaemonCmd::Reload => self.prop.reload(),
DaemonCmd::Shutdown ... | identifier_body |
mod.rs | use epoll::*;
use error::Result;
use handler::*;
use libc_sys::{sched_param, sched_setscheduler, rlimit, prlimit, RLIMIT_RTPRIO};
pub use nix::sys::signal::{Signal, SigSet};
use nix::sys::signalfd::{SignalFd, SFD_NONBLOCK};
use nix::{unistd, Errno};
use prop::*; | mod builder;
pub use self::builder::sched_policy;
pub use libc_sys::{SCHED_FIFO, SCHED_RR, SCHED_OTHER};
/// WIP: New-style daemon
/// http://man7.org/linux/man-pages/man7/daemon.7.html
///
/// Missing:
/// - Force exposing daemon interface via D-Bus along with a D-Bus service activation
/// configuration file
/// ... | use std::os::unix::io::AsRawFd;
| random_line_split |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use dom::bindings::js::Root;
use dom::bindings:... | document: &Document) -> Root<HTMLParagraphElement> {
Node::reflect_node(box HTMLParagraphElement::new_inherited(local_name, prefix, document),
document,
HTMLParagraphElementBinding::Wrap)
}
} | random_line_split | |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use dom::bindings::js::Root;
use dom::bindings:... | {
htmlelement: HTMLElement
}
impl HTMLParagraphElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLParagraphElement {
HTMLParagraphElement {
htmlelement:
HTMLElement::new_inherite... | HTMLParagraphElement | identifier_name |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use dom::bindings::js::Root;
use dom::bindings:... |
}
| {
Node::reflect_node(box HTMLParagraphElement::new_inherited(local_name, prefix, document),
document,
HTMLParagraphElementBinding::Wrap)
} | identifier_body |
blob.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::BlobBinding;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;... | }
impl BlobMethods for Blob {
// https://dev.w3.org/2006/webapi/FileAPI/#dfn-size
fn Size(&self) -> u64 {
match self.bytes {
None => 0,
Some(ref bytes) => bytes.len() as u64
}
}
// https://dev.w3.org/2006/webapi/FileAPI/#dfn-type
fn Type(&self) -> DOMString ... | impl Blob {
pub fn read_out_buffer(&self, send: Sender<Vec<u8>>) {
send.send(self.bytes.clone().unwrap_or(vec![])).unwrap();
} | random_line_split |
blob.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::BlobBinding;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;... | (string: &DOMString) -> bool {
// Step 5.1 in Sec 5.1 of File API spec
// http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob
return string.chars().all(|c| { c >= '\x20' && c <= '\x7E' })
}
impl Blob {
pub fn new_inherited(global: GlobalRef, type_: BlobTypeId,
bytes: Option<... | is_ascii_printable | identifier_name |
blob.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::BlobBinding;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;... |
// Step 2
self.isClosed_.set(true);
// TODO Step 3 if Blob URL Store is implemented
}
}
impl FileDerived for Blob {
fn is_file(&self) -> bool {
match self.type_ {
BlobTypeId::File => true,
_ => false
}
}
}
| {
return;
} | conditional_block |
blob.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::BlobBinding;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;... |
}
impl BlobMethods for Blob {
// https://dev.w3.org/2006/webapi/FileAPI/#dfn-size
fn Size(&self) -> u64 {
match self.bytes {
None => 0,
Some(ref bytes) => bytes.len() as u64
}
}
// https://dev.w3.org/2006/webapi/FileAPI/#dfn-type
fn Type(&self) -> DOMString... | {
send.send(self.bytes.clone().unwrap_or(vec![])).unwrap();
} | identifier_body |
ldd.rs | extern crate glob;
extern crate clap;
extern crate elfkit;
use std::fs::{File};
use elfkit::Elf;
use std::path::Path;
use std::collections::HashSet;
use std::io::{self};
use std::io::BufReader;
use std::io::BufRead;
use glob::glob;
struct Ldd {
sysroot: String,
lpaths: Vec<String>,
visited: Hash... | }
if a.chars().last().unwrap()!= '/' {
a.push('/');
}
if b.chars().nth(0).unwrap() == '/' {
return a + &b[1..];
}
return a + b;
}
impl Ldd {
fn recurse(&mut self, path: &str) {
let mut f = File::open(path).unwrap();
let mut elf = Elf::from_reader(&mut f).unw... | if a.len() < 1 {
return a; | random_line_split |
ldd.rs | extern crate glob;
extern crate clap;
extern crate elfkit;
use std::fs::{File};
use elfkit::Elf;
use std::path::Path;
use std::collections::HashSet;
use std::io::{self};
use std::io::BufReader;
use std::io::BufRead;
use glob::glob;
struct Ldd {
sysroot: String,
lpaths: Vec<String>,
visited: Hash... | }
}
}
}
}
for dep in &mut deps {
let mut found = false;
for lpath in self.lpaths.iter() {
let joined = join_paths(&lpath, &dep);
let joined = Path::new(&joined);
... | {
let mut f = File::open(path).unwrap();
let mut elf = Elf::from_reader(&mut f).unwrap();
let mut deps = Vec::new();
for shndx in 0..elf.sections.len() {
if elf.sections[shndx].header.shtype == elfkit::types::SectionType::DYNAMIC {
elf.load(shndx, &mut f).unw... | identifier_body |
ldd.rs | extern crate glob;
extern crate clap;
extern crate elfkit;
use std::fs::{File};
use elfkit::Elf;
use std::path::Path;
use std::collections::HashSet;
use std::io::{self};
use std::io::BufReader;
use std::io::BufRead;
use glob::glob;
struct Ldd {
sysroot: String,
lpaths: Vec<String>,
visited: Hash... | (&mut self, path: &str) {
let mut f = File::open(path).unwrap();
let mut elf = Elf::from_reader(&mut f).unwrap();
let mut deps = Vec::new();
for shndx in 0..elf.sections.len() {
if elf.sections[shndx].header.shtype == elfkit::types::SectionType::DYNAMIC {
elf... | recurse | identifier_name |
mem.rs | assert!(jemalloc_heap_allocated_size.is_none());
jemalloc_heap_allocated_size = Some(report.size);
} else if report.path[0] == SYSTEM_HEAP_ALLOCATED_STR {
assert!(system_heap_allocated_size.is_none());
sy... | {
vec![]
} | identifier_body | |
mem.rs | _reports(request)
});
mem_profiler_chan.send(ProfilerMsg::RegisterReporter("system".to_owned(),
Reporter(system_reporter_sender)));
mem_profiler_chan
}
pub fn new(port: IpcReceiver<ProfilerMsg>) -> Profiler {
Profiler... | ProfilerMsg::RegisterReporter(name, reporter) => {
// Panic if it has already been registered.
let name_clone = name.clone();
match self.reporters.insert(name, reporter) {
None => true,
Some(_) => panic!(format!("Registe... | }
fn handle_msg(&mut self, msg: ProfilerMsg) -> bool {
match msg { | random_line_split |
mem.rs | reports(request)
});
mem_profiler_chan.send(ProfilerMsg::RegisterReporter("system".to_owned(),
Reporter(system_reporter_sender)));
mem_profiler_chan
}
pub fn new(port: IpcReceiver<ProfilerMsg>) -> Profiler {
Profiler ... | (&mut self) {
// Fill in sizes of interior nodes, and recursively sort the sub-trees.
for (_, tree) in &mut self.trees {
tree.compute_interior_node_sizes_and_sort();
}
// Put the trees into a sorted vector. Primary sort: degenerate trees (those containing a
// single... | print | identifier_name |
attr.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 ... | (&self) -> Attribute {
if self.node.is_sugared_doc {
let comment = self.value_str().unwrap();
let meta = mk_name_value_item_str(@"doc",
strip_doc_comment_decoration(comment).to_managed());
mk_attr(meta)
} else {
... | desugar_doc | identifier_name |
attr.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 ... | },
_ => None
}
}
fn meta_item_list<'a>(&'a self) -> Option<&'a [@MetaItem]> {
match self.node {
MetaList(_, ref l) => Some(l.as_slice()),
_ => None
}
}
fn name_str_pair(&self) -> Option<(@str, @str)> {
self.value_str().map... | } | random_line_split |
attr.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 ... |
pub fn mk_word_item(name: @str) -> @MetaItem {
@dummy_spanned(MetaWord(name))
}
pub fn mk_attr(item: @MetaItem) -> Attribute {
dummy_spanned(Attribute_ {
style: ast::AttrInner,
value: item,
is_sugared_doc: false,
})
}
pub fn mk_sugared_doc_attr(text: @str, lo: BytePos, hi: BytePo... | {
@dummy_spanned(MetaList(name, items))
} | identifier_body |
tests.rs | #![deny(warnings)]
#![allow(unstable)]
extern crate cargo;
extern crate flate2;
extern crate git2;
extern crate hamcrest;
extern crate serialize;
extern crate tar;
extern crate term;
extern crate url;
#[macro_use]
extern crate log;
mod support;
macro_rules! test {
($name:ident $expr:expr) => (
#[test]
... | mod test_cargo_compile_path_deps;
mod test_cargo_compile_plugins;
mod test_cargo_cross_compile;
mod test_cargo_doc;
mod test_cargo_features;
mod test_cargo_fetch;
mod test_cargo_freshness;
mod test_cargo_generate_lockfile;
mod test_cargo_new;
mod test_cargo_package;
mod test_cargo_profiles;
mod test_cargo_publish;
mod ... | mod test_cargo_compile_git_deps;
mod test_cargo_compile_old_custom_build; | random_line_split |
moves-based-on-type-block-bad.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 main() {
let s = S { x: ~Bar(~42) };
loop {
f(&s, |hellothere| {
match hellothere.x { //~ ERROR cannot move out
~Foo(_) => {}
~Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here
~Baz => {}
}
... | {
g(s)
} | identifier_body |
moves-based-on-type-block-bad.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 s = S { x: ~Bar(~42) };
loop {
f(&s, |hellothere| {
match hellothere.x { //~ ERROR cannot move out
~Foo(_) => {}
~Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here
~Baz => {}
}
})
}... | main | identifier_name |
moves-based-on-type-block-bad.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 main() {
let s = S { x: ~Bar(~42) };
loop {
f(&s, |hellothere| {
match hellothere.x { //~ ERROR cannot move out
~Foo(_) => {}
~Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here
~Baz => {}
}
... | g(s)
} | random_line_split |
lib.rs | use std::collections::HashMap;
#[derive(Default)]
pub struct School(HashMap<u8, Vec<String>>);
impl School {
pub fn new() -> School {
School(HashMap::new())
}
/// Vector of all distinct grades in ascending order
pub fn grades(&self) -> Vec<u8> |
/// Vector of all names or None if no names are found
pub fn grade(&self, grade: u8) -> Option<&Vec<String>> {
self.0.get(&grade)
}
/// Add name and grade combination to School
pub fn add(&mut self, grade: u8, name: &str) {
let val = self.0.entry(grade).or_insert_with(Vec::new);
... | {
// map to convert & to value
let mut ret: Vec<u8> = self.0.keys().cloned().collect();
// must be in order
ret.sort();
ret
} | identifier_body |
lib.rs | use std::collections::HashMap;
#[derive(Default)]
pub struct School(HashMap<u8, Vec<String>>);
impl School {
pub fn | () -> School {
School(HashMap::new())
}
/// Vector of all distinct grades in ascending order
pub fn grades(&self) -> Vec<u8> {
// map to convert & to value
let mut ret: Vec<u8> = self.0.keys().cloned().collect();
// must be in order
ret.sort();
ret
}
... | new | identifier_name |
lib.rs | use std::collections::HashMap;
#[derive(Default)]
pub struct School(HashMap<u8, Vec<String>>);
impl School {
pub fn new() -> School {
School(HashMap::new())
}
/// Vector of all distinct grades in ascending order
pub fn grades(&self) -> Vec<u8> {
// map to convert & to value
le... | ret
}
/// Vector of all names or None if no names are found
pub fn grade(&self, grade: u8) -> Option<&Vec<String>> {
self.0.get(&grade)
}
/// Add name and grade combination to School
pub fn add(&mut self, grade: u8, name: &str) {
let val = self.0.entry(grade).or_insert_... | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... |
#[allow(unsafe_code)]
pub fn lock<'a>(&'a self) -> LockResult<()> {
let (guard, result) = match self.mutex.lock() {
Ok(guard) => (guard, Ok(())),
Err(err) => (err.into_inner(), Err(PoisonError::new(()))),
};
unsafe { self.set_guard_and_owner(guard); }
res... | {
let guard_ptr = &mut *self.guard.get();
let old_owner = self.owner();
self.owner.store(None, Ordering::Relaxed);
// Make sure we release the lock before checking the assertions.
// We protect logging by a re-entrant lock, so we don't want
// to do any incidental logging... | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... |
Ok(self.mk_guard())
}
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
trace!("{:?} Try locking.", ThreadId::current());
if self.mutex.owner()!= Some(ThreadId::current()) {
trace!("{:?} Becoming owner?", ThreadId::current());
if let Err(err) = s... | {
trace!("{:?} Becoming owner.", ThreadId::current());
if let Err(_) = self.mutex.lock() {
trace!("{:?} Poison!", ThreadId::current());
return Err(PoisonError::new(self.mk_guard()));
}
trace!("{:?} Became owner.", ThreadId::current());
... | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... | (&self, value: Option<ThreadId>, ordering: Ordering) -> Option<ThreadId> {
let number = value.map(|id| id.0.get()).unwrap_or(0);
let number = self.0.swap(number, ordering);
NonZeroUsize::new(number).map(ThreadId)
}
}
/// A type for hand-over-hand mutexes.
///
/// These support `lock` and `u... | swap | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... | unsafe { self.set_guard_and_owner(guard); }
result
}
#[allow(unsafe_code)]
pub fn try_lock(&self) -> TryLockResult<()> {
let (guard, result) = match self.mutex.try_lock() {
Ok(guard) => (guard, Ok(())),
Err(TryLockError::WouldBlock) => return Err(TryLockError:... | Err(err) => (err.into_inner(), Err(PoisonError::new(()))),
}; | random_line_split |
city.rs | extern crate rustc_serialize;
use rustc_serialize::json::{Json, ToJson};
use std::fmt;
use std::collections::BTreeMap;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct City{
pub name: String,
pub coordinates: (f64, f64),
}
impl PartialEq for City {
fn eq(&self, other: &City) -> bool {
self.coordinate... | (&self) -> Json {
let mut d = BTreeMap::new();
d.insert("name".to_string(), self.name.to_json());
d.insert("coordinates".to_string(), self.coordinates.to_json());
Json::Object(d)
}
} | to_json | identifier_name |
city.rs | extern crate rustc_serialize;
use rustc_serialize::json::{Json, ToJson};
use std::fmt;
use std::collections::BTreeMap;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct City{
pub name: String,
pub coordinates: (f64, f64),
}
impl PartialEq for City {
fn eq(&self, other: &City) -> bool {
self.coordinate... | }
impl ToJson for City {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
d.insert("name".to_string(), self.name.to_json());
d.insert("coordinates".to_string(), self.coordinates.to_json());
Json::Object(d)
}
} | } | random_line_split |
city.rs | extern crate rustc_serialize;
use rustc_serialize::json::{Json, ToJson};
use std::fmt;
use std::collections::BTreeMap;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct City{
pub name: String,
pub coordinates: (f64, f64),
}
impl PartialEq for City {
fn eq(&self, other: &City) -> bool {
self.coordinate... |
}
impl fmt::Display for City {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "Name:{},X:{},Y:{}", self.name, self.coordinates.0, self.coordinates.1)
}
}
impl ToJson for City {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
d.insert("name".to_string(), ... | {
self.coordinates.0 != other.coordinates.0 || self.coordinates.1 != other.coordinates.1
} | identifier_body |
dst-dtor-1.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 Foo;
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROP_RAN = true; }
}
}
trait Trait {}
impl Trait for Foo {}
struct Fat<T:?Sized> {
f: T
}
pub fn main() {
{
let _x: Box<Fat<Trait>> = box Fat { f: Foo };
}
unsafe {
assert!(DROP_RAN);
}
} | random_line_split | |
dst-dtor-1.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 ... |
}
trait Trait {}
impl Trait for Foo {}
struct Fat<T:?Sized> {
f: T
}
pub fn main() {
{
let _x: Box<Fat<Trait>> = box Fat { f: Foo };
}
unsafe {
assert!(DROP_RAN);
}
}
| {
unsafe { DROP_RAN = true; }
} | identifier_body |
dst-dtor-1.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 ... | ;
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROP_RAN = true; }
}
}
trait Trait {}
impl Trait for Foo {}
struct Fat<T:?Sized> {
f: T
}
pub fn main() {
{
let _x: Box<Fat<Trait>> = box Fat { f: Foo };
}
unsafe {
assert!(DROP_RAN);
}
}
| Foo | identifier_name |
handle.rs | pub mod prelude {
pub use super::{Handle,HandleMut};
}
/// Types that manages access to a resource.
///
/// This trait is intended to be used by structs that manage the ownership of a resource from a C
/// library. Often, a pointer to the resource is needed to implement methods in other modules that
/// wrap the s... | pub trait HandleMut<T>: Handle<T> {
unsafe fn as_mut_ptr(&mut self) -> *mut T;
} | random_line_split | |
flexuin_fill2.rs | grid_pattern = {
{0, 0.028, "C", "floatiss_"},
{0.024, 0.040, "B", "floatiss_"},
{0.024, 0.028, "C", "floatiss_"},
{0.024, 0.028, "B", "floatiss_"},
{0.024, 0.028, "C", "floatiss_"},
{0.024, 0.028, "B", "floatiss_"},
{0.024, 0.028, "C", "floatiss_"},
{0.024, 0.074, "B", "floatiss_"},
... | //far_fill_density_target = 1.0;
density_window_size = 2.1;
path = "./";
half_dr_end_to_end = 0.028;
//write_milkyway_output = false;
//mw_cellname = "";
//mw_library = "";
//mw_path = "";
//mw_view = "FILL";
//mw_append = true;
//region_grids = {};
// use_fill_markers = true;
consider_off_grid = false;
write_out_c_tr... | //no_extend_cells_list = {"cx*",};
//near_fill_density_target = 1.0; | random_line_split |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... |
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let ... | let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
} | random_line_split |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... | : Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcou... | dref<T | identifier_name |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... |
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>
}
impl LiveDOMReferences {
/// Set up ... | let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
... | identifier_body |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... | let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be ... | // there could have been a new reference taken since
// this message was dispatched.
return;
}
| conditional_block |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = self.cleanup_dir();
}
}
// the tests for this module need to change the path using change_dir,
// and this doesn't play nicely with other tests so these unit tests are located
// in src/test/run-pass/tempfile.rs
| {
match self.path {
Some(ref p) => fs::remove_dir_all(p),
None => Ok(())
}
} | identifier_body |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // and this doesn't play nicely with other tests so these unit tests are located
// in src/test/run-pass/tempfile.rs | // the tests for this module need to change the path using change_dir, | random_line_split |
lib.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
path: Option<PathBuf>,
}
// How many times should we (re)try finding an unused random name? It should be
// enough that an attacker will run out of luck before we run out of patience.
const NUM_RETRIES: u32 = 1 << 31;
// How many characters should we include in a random file name? It needs to
// be enough to di... | TempDir | identifier_name |
thread_local_dummy.rs | // Copyright 2014-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... | <R, F>(&'static self, cb: F) -> R where F: FnOnce(&T) -> R {
unsafe {
let ptr = *self.inner.get();
assert!(!ptr.is_null(), "cannot access a scoped thread local \
variable without calling `set` first");
cb(&*ptr)
... | with | identifier_name |
thread_local_dummy.rs | // Copyright 2014-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... | pub fn with<R, F>(&'static self, cb: F) -> R where F: FnOnce(&T) -> R {
unsafe {
let ptr = *self.inner.get();
assert!(!ptr.is_null(), "cannot access a scoped thread local \
variable without calling `set` first");
cb... | }
cb()
}
| random_line_split |
thread_local_dummy.rs | // Copyright 2014-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... |
unsafe fn init(&self) -> &T {
let value = (self.init)();
let ptr = self.inner.get();
*ptr = Some(value);
(*ptr).as_ref().unwrap()
}
#[unstable(feature = "std_misc",
reason = "state querying was recently added")]
pub fn state(&'static self) -> State {... | {
unsafe {
f(match *self.inner.get() {
Some(ref inner) => inner,
None => self.init(),
})
}
} | identifier_body |
lib.rs | //! Implementation of JSON Web Tokens.
//!
//! # Example
//!
//! ```rust
//! #![allow(unstable)]
//!
//! extern crate jwt;
//! use jwt::Claims;
//! use jwt::jws::hs256::{encode, decode};
//!
//! fn main() {
//! let mut claims = Claims::new();
//! claims.insert_unsafe("com.example.my-claim", "value".to_string()... |
}
| {
if a.len() != b.len() { return false; }
let mut r: u8 = 0;
for i in (0..a.len()) {
r |= a[i] ^ b[i];
}
r == 0
} | identifier_body |
lib.rs | //! Implementation of JSON Web Tokens.
//!
//! # Example
//!
//! ```rust
//! #![allow(unstable)]
//!
//! extern crate jwt;
//! use jwt::Claims;
//! use jwt::jws::hs256::{encode, decode};
//!
//! fn main() {
//! let mut claims = Claims::new();
//! claims.insert_unsafe("com.example.my-claim", "value".to_string()... | (a: &[u8], b: &[u8]) -> bool {
if a.len()!= b.len() { return false; }
let mut r: u8 = 0;
for i in (0..a.len()) {
r |= a[i] ^ b[i];
}
r == 0
}
}
| safe_cmp | identifier_name |
lib.rs | //! Implementation of JSON Web Tokens.
//!
//! # Example
//!
//! ```rust
//! #![allow(unstable)]
//!
//! extern crate jwt;
//! use jwt::Claims;
//! use jwt::jws::hs256::{encode, decode};
//!
//! fn main() {
//! let mut claims = Claims::new();
//! claims.insert_unsafe("com.example.my-claim", "value".to_string()... |
let mut r: u8 = 0;
for i in (0..a.len()) {
r |= a[i] ^ b[i];
}
r == 0
}
}
| { return false; } | conditional_block |
lib.rs | //! Implementation of JSON Web Tokens.
//!
//! # Example
//!
//! ```rust
//! #![allow(unstable)]
//!
//! extern crate jwt;
//! use jwt::Claims;
//! use jwt::jws::hs256::{encode, decode};
//!
//! fn main() {
//! let mut claims = Claims::new();
//! claims.insert_unsafe("com.example.my-claim", "value".to_string()... | }
r == 0
}
} | r |= a[i] ^ b[i]; | random_line_split |
rustwin.rs | // Wraps GLUT in an event queue using Rust enums
// hides use of callbacks acessing a global, allows users to poll input events from
// a user implemented mainloop.
// provides a tablet/console oriented MVC framework
//use r3d::Vec2f;
use common::*;
#[deriving(Show,Clone,PartialEq)]
pub struct Window{handle:i32} //... | // println!("pop event from {:?}", g_rustwin);
// println!("pos={:?}",g_cursor);
let mut rw=&mut g_rustwin;
if rw.head==rw.tail {
EventNone
} else {
let ev=rw.event_queue.get(rw.tail).unwrap().clone();
rw.tail=(rw.tail+1)&255;
ev
}
}
}
/// Sample main loop wrapper. Possible to write a mainloop ... | unsafe {
if g_init_input==false {init_input() }
glut::glutMainLoopEvent(); | random_line_split |
rustwin.rs | // Wraps GLUT in an event queue using Rust enums
// hides use of callbacks acessing a global, allows users to poll input events from
// a user implemented mainloop.
// provides a tablet/console oriented MVC framework
//use r3d::Vec2f;
use common::*;
#[deriving(Show,Clone,PartialEq)]
pub struct Window{handle:i32} //... |
pub fn init_input() {
unsafe {
g_init_input=true;
glut::glutMouseFunc(mouse);
glut::glutMotionFunc(motion);
glut::glutPassiveMotionFunc(passive_motion);
glut::glutKeyboardFunc(keyboard);
glut::glutKeyboardUpFunc(keyboard_up);
glut::glutSpecialFunc(special);
glut::glutSpecialUpFunc(special_up);
glut... | {
ev_println(format!("specialKeyUp:{} at {}",k,(x,y)));
// todo - translate special key into modifiers, thru glut enum
unsafe{
g_key_modifiers&=special_key_to_mask(k);
push_event(KeyUp(curr_win(), k as Key_t,g_key_modifiers,(x,y)));
}
} | identifier_body |
rustwin.rs | // Wraps GLUT in an event queue using Rust enums
// hides use of callbacks acessing a global, allows users to poll input events from
// a user implemented mainloop.
// provides a tablet/console oriented MVC framework
//use r3d::Vec2f;
use common::*;
#[deriving(Show,Clone,PartialEq)]
pub struct Window{handle:i32} //... | (w:&Window)->bool { *w==g_root_window }
pub fn get_key_state(k:char)->i32 { unsafe { if g_keys[(k as uint) & 255] {1} else {0} } }
pub struct Joypad {
sticks:[Vec2f,..2],
buttons:i32,
press:i32,
unpress:i32
// rumble? tilt? accelerometers?
}
impl Joypad {
pub fn new()->Joypad {
Joypad{
sticks:[zero(),zero(... | is_root_window | identifier_name |
ray.rs | use glium::{Program, Display, VertexBuffer, Surface, DrawParameters};
use glium::{Depth, Blend};
use glium::DepthTest::IfLessOrEqual;
use glium::BlendingFunction::Addition;
use glium::LinearBlendingFactor::{SourceAlpha, OneMinusSourceAlpha};
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
... | target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &DrawParameters {
blend: Blend {
color: Addition {
source: SourceAlpha,
destination: OneMinusSourceAlpha
},
alpha: Addition {
source: SourceAlpha,
destination: OneMinusSourc... | {
match state {
&game::Ray::Static { position, orientation, width, border, .. } | &game::Ray::Dynamic { position, orientation, width, border, .. } => {
let mvp = support.scene().to_mat() *
support.scene().position(position) *
support.scene().orientation(orientation) *
support.scene().scale(width... | identifier_body |
ray.rs | use glium::{Program, Display, VertexBuffer, Surface, DrawParameters};
use glium::{Depth, Blend};
use glium::DepthTest::IfLessOrEqual;
use glium::BlendingFunction::Addition;
use glium::LinearBlendingFactor::{SourceAlpha, OneMinusSourceAlpha};
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
... | varying vec2 v_position;
void main() {
// get the texel from the background video or visualizer
vec4 texel = texture2D(background,
vec2(gl_FragCoord.x / width, gl_FragCoord.y / height));
// invert color
vec3 pixel = vec3(1.0 - texel.r, 1.0 - texel.g, 1.0 - texel.b);
... | uniform float height;
uniform float border;
uniform vec4 color;
| random_line_split |
ray.rs | use glium::{Program, Display, VertexBuffer, Surface, DrawParameters};
use glium::{Depth, Blend};
use glium::DepthTest::IfLessOrEqual;
use glium::BlendingFunction::Addition;
use glium::LinearBlendingFactor::{SourceAlpha, OneMinusSourceAlpha};
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
... | <S: Surface>(&self, target: &mut S, support: &Support, state: &Self::State) {
match state {
&game::Ray::Static { position, orientation, width, border,.. } | &game::Ray::Dynamic { position, orientation, width, border,.. } => {
let mvp = support.scene().to_mat() *
support.scene().position(position) *
s... | render | identifier_name |
simd.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let f64x2 = f64x2(64.5f64, 65.5f64);
zzz();
}
#[inline(never)]
fn zzz() { () } |
let f32x4 = f32x4(60.5f32, 61.5f32, 62.5f32, 63.5f32); | random_line_split |
simd.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | { () } | identifier_body | |
simd.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () { () }
| zzz | identifier_name |
account_db.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | } | random_line_split | |
account_db.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (&mut self, _key: H256, _value: DBValue) {
unimplemented!()
}
fn remove(&mut self, _key: &H256) {
unimplemented!()
}
}
/// DB backend wrapper for Account trie
pub struct AccountDBMut<'db> {
db: &'db mut HashDB,
address_hash: H256,
}
impl<'db> AccountDBMut<'db> {
/// Create a new AccountDB from an address.
... | emplace | identifier_name |
account_db.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
struct WrappingMut<'db>(&'db mut HashDB);
impl<'db> HashDB for WrappingMut<'db>{
fn keys(&self) -> HashMap<H256, i32> {
unimplemented!()
}
fn get(&self, key: &H256) -> Option<DBValue> {
if key == &SHA3_NULL_RLP {
return Some(DBValue::from_slice(&NULL_RLP_STATIC));
}
self.0.get(key)
}
fn contains(... | {
unimplemented!()
} | identifier_body |
account_db.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
self.0.get(key)
}
fn contains(&self, key: &H256) -> bool {
if key == &SHA3_NULL_RLP {
return true;
}
self.0.contains(key)
}
fn insert(&mut self, _value: &[u8]) -> H256 {
unimplemented!()
}
fn emplace(&mut self, _key: H256, _value: DBValue) {
unimplemented!()
}
fn remove(&mut self, _key: &H25... | {
return Some(DBValue::from_slice(&NULL_RLP_STATIC));
} | conditional_block |
main.rs | extern crate getopts;
use getopts::Options;
use std::env;
use std::io::{self, Write};
use std::net::{IpAddr, TcpStream};
use std::str::FromStr;
use std::sync::mpsc::{Sender, channel};
use std::thread;
// Max possible port
const MAX: u16 = 65535;
fn main() {
let args: Vec<String> = env::args().collect();
let ... | println!("{} is open", v);
}
}
// scan scans ports at an IP address and sends any open ports it finds back on its
// channel. scan exits once MAX has been reached.
fn scan(tx: Sender<u16>, start_port: u16, addr: IpAddr, num_threads: u16) {
let mut port: u16 = start_port + 1;
loop {
match ... | println!("");
out.sort();
for v in out { | random_line_split |
main.rs | extern crate getopts;
use getopts::Options;
use std::env;
use std::io::{self, Write};
use std::net::{IpAddr, TcpStream};
use std::str::FromStr;
use std::sync::mpsc::{Sender, channel};
use std::thread;
// Max possible port
const MAX: u16 = 65535;
fn main() {
let args: Vec<String> = env::args().collect();
let ... | }
}
| {
let mut port: u16 = start_port + 1;
loop {
match TcpStream::connect((addr, port)) {
Ok(_) => {
// Found open port, indicate progress and send to main thread
print!(".");
io::stdout().flush().unwrap();
tx.send(port).unwrap();
... | identifier_body |
main.rs | extern crate getopts;
use getopts::Options;
use std::env;
use std::io::{self, Write};
use std::net::{IpAddr, TcpStream};
use std::str::FromStr;
use std::sync::mpsc::{Sender, channel};
use std::thread;
// Max possible port
const MAX: u16 = 65535;
fn main() {
let args: Vec<String> = env::args().collect();
let ... | (tx: Sender<u16>, start_port: u16, addr: IpAddr, num_threads: u16) {
let mut port: u16 = start_port + 1;
loop {
match TcpStream::connect((addr, port)) {
Ok(_) => {
// Found open port, indicate progress and send to main thread
print!(".");
io::... | scan | identifier_name |
xz.rs | use crate::decode;
use crate::encode::lzma2;
use crate::encode::util;
use crate::xz::{footer, header, CheckMethod, StreamFlags};
use byteorder::{LittleEndian, WriteBytesExt};
use crc::{crc32, Hasher32};
use std::io;
use std::io::Write;
pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()>
where
... | );
let padding_size = ((unpadded_size ^ 0x03) + 1) & 0x03;
let padding = vec![0; padding_size];
output.write_all(padding.as_slice())?;
// Checksum = None (cf. above)
Ok((unpadded_size, unpacked_size))
}
fn write_index<W>(output: &mut W, unpadded_size: usize, unpacked_size: usize) -> io::Resul... | unpacked_size | random_line_split |
xz.rs | use crate::decode;
use crate::encode::lzma2;
use crate::encode::util;
use crate::xz::{footer, header, CheckMethod, StreamFlags};
use byteorder::{LittleEndian, WriteBytesExt};
use crc::{crc32, Hasher32};
use std::io;
use std::io::Write;
pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()>
where
... | digested.write_all(padding.as_slice())?;
}
let crc32 = digest.sum32();
count_output.write_u32::<LittleEndian>(crc32)?;
Ok(count_output.count())
}
fn write_multibyte<W>(output: &mut W, mut value: u64) -> io::Result<()>
where
W: io::Write,
{
loop {
let byte = (value & 0x7F) as ... | {
let mut count_output = util::CountWrite::new(output);
let mut digest = crc32::Digest::new(crc32::IEEE);
{
let mut digested = util::HasherWrite::new(&mut count_output, &mut digest);
digested.write_u8(0)?; // No more block
let num_records = 1;
write_multibyte(&mut digested, ... | identifier_body |
xz.rs | use crate::decode;
use crate::encode::lzma2;
use crate::encode::util;
use crate::xz::{footer, header, CheckMethod, StreamFlags};
use byteorder::{LittleEndian, WriteBytesExt};
use crc::{crc32, Hasher32};
use std::io;
use std::io::Write;
pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()>
where
... | else {
output.write_u8(0x80 | byte)?;
}
}
Ok(())
}
| {
output.write_u8(byte)?;
break;
} | conditional_block |
xz.rs | use crate::decode;
use crate::encode::lzma2;
use crate::encode::util;
use crate::xz::{footer, header, CheckMethod, StreamFlags};
use byteorder::{LittleEndian, WriteBytesExt};
use crc::{crc32, Hasher32};
use std::io;
use std::io::Write;
pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()>
where
... | <R, W>(input: &mut R, output: &mut W) -> io::Result<(usize, usize)>
where
R: io::BufRead,
W: io::Write,
{
let (unpadded_size, unpacked_size) = {
let mut count_output = util::CountWrite::new(output);
// Block header
let mut digest = crc32::Digest::new(crc32::IEEE);
{
... | write_block | identifier_name |
mod.rs | pub mod event;
use crate::Opt;
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use diesel_migrations::{
find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database,
};
use r2d2::{Pool, PooledConnection};
use std::error::Error;
pub type DatabasePool = Pool<Con... |
pub fn run_migrations(db_pool: &DatabasePool) {
let connection = db_pool.get().expect("Could not connect to database");
setup_database(&connection).expect("Could not set up database");
let migrations_dir = find_migrations_directory().expect("Could not find migrations directory");
let migrations = m... | {
let db_manager: ConnectionManager<PgConnection> = ConnectionManager::new(&opt.database);
let db_pool: Pool<ConnectionManager<PgConnection>> =
Pool::builder().max_size(15).build(db_manager)?;
Ok(db_pool)
} | identifier_body |
mod.rs | pub mod event;
use crate::Opt;
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use diesel_migrations::{
find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database,
};
use r2d2::{Pool, PooledConnection};
use std::error::Error;
pub type DatabasePool = Pool<Con... | else {
eprintln!(
"No database migrations available in \"{}\".",
migrations_dir.to_string_lossy()
);
}
run_pending_migrations(&connection).expect("Could not run database migrations");
}
| {
println!("Migrations:");
for (migration, applied) in migrations {
println!(
" [{}] {}",
if applied { "X" } else { " " },
migration
.file_path()
.and_then(|p| p.file_name())
.map(|p|... | conditional_block |
mod.rs | pub mod event;
use crate::Opt;
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use diesel_migrations::{
find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database,
};
use r2d2::{Pool, PooledConnection};
use std::error::Error;
pub type DatabasePool = Pool<Con... | (opt: &Opt) -> Result<DatabasePool, Box<dyn Error>> {
let db_manager: ConnectionManager<PgConnection> = ConnectionManager::new(&opt.database);
let db_pool: Pool<ConnectionManager<PgConnection>> =
Pool::builder().max_size(15).build(db_manager)?;
Ok(db_pool)
}
pub fn run_migrations(db_pool: &Database... | create_pool | identifier_name |
mod.rs | pub mod event;
use crate::Opt;
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use diesel_migrations::{
find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database,
};
use r2d2::{Pool, PooledConnection};
use std::error::Error;
pub type DatabasePool = Pool<Con... | }
run_pending_migrations(&connection).expect("Could not run database migrations");
} | eprintln!(
"No database migrations available in \"{}\".",
migrations_dir.to_string_lossy()
); | random_line_split |
script_msg.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 AnimationState;
use CompositorEvent;
use DocumentState;
use IFrameLoadInfo;
use IFrameLoadInfoWithData;
use La... | }
/// A log entry reported to the constellation
/// We don't report all log entries, just serious ones.
/// We need a separate type for this because `LogLevel` isn't serializable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum LogEntry {
/// Panic, with a reason and backtrace
Panic(String, String),
... | random_line_split | |
script_msg.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 AnimationState;
use CompositorEvent;
use DocumentState;
use IFrameLoadInfo;
use IFrameLoadInfoWithData;
use La... | {
/// Provide the constellation with a means of communicating with the Service Worker Manager
OwnSender(IpcSender<ServiceWorkerMsg>),
}
| SWManagerMsg | identifier_name |
resource_thread.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/. */
//! A thread that takes a URL and streams back the binary data.
use about_loader;
use chrome_loader;
use cookie;
u... | {
pub user_name: String,
pub password: String,
}
impl AuthCache {
pub fn new() -> AuthCache {
AuthCache {
version: 1,
entries: HashMap::new()
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCache {
pub version: u32,
pub entries: H... | AuthCacheEntry | identifier_name |
resource_thread.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/. */
//! A thread that takes a URL and streams back the binary data.
use about_loader;
use chrome_loader;
use cookie;
u... | }
break;
}
}
}
}
}
pub fn write_json_to_file<T: Encodable>(data: &T, profile_dir: &str, filename: &str) {
let json_encoded: String;
match json::encode(&data) {
Ok(d) => json_encoded = d,
Err(_) => return,
}
... | Err(_) => warn!("Error writing hsts list to disk"),
} | random_line_split |
animate.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 cg;
use darling::util::IdentList;
use quote::Tokens;
use syn::{DeriveInput, Path};
use synstructure::{Structur... | }
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics ::values::animated::Animate for #name #ty_generics #where_clause {
#[allow(unused_variables, unused_imports)]
#[inline]
... | match_body.append_all(quote! { _ => Err(()) }); | random_line_split |
animate.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 cg;
use darling::util::IdentList;
use quote::Tokens;
use syn::{DeriveInput, Path};
use synstructure::{Structur... |
}));
Ok(quote! {
(&#this_pattern, &#other_pattern) => {
#computations
Ok(#result_value)
}
})
}
#[darling(attributes(animate), default)]
#[derive(Default, FromDeriveInput)]
struct AnimateInputAttrs {
fallback: Option<Path>,
}
#[darling(attributes(animation), def... | {
quote! {
let #result =
::values::animated::Animate::animate(#this, #other, procedure)?;
}
} | conditional_block |
animate.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 cg;
use darling::util::IdentList;
use quote::Tokens;
use syn::{DeriveInput, Path};
use synstructure::{Structur... | (mut input: DeriveInput) -> Tokens {
let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input);
let no_bound = animation_input_attrs.no_bound.unwrap_or_default();
let mut where_clause = input.generics.where_clause.take();
for param in input.generics.type_params() {
if!no_b... | derive | identifier_name |
print-tree-actions.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... |
fn create_element(&mut self, name: QualName, _attrs: Vec<Attribute>) -> uint {
let id = self.get_id();
println!("Created {:?} as {}", name, id);
self.names.insert(id, name);
id
}
fn create_comment(&mut self, text: String) -> uint {
let id = self.get_id();
p... | {
self.names.get(&target).expect("not an element").clone()
} | identifier_body |
print-tree-actions.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... | }
impl Sink {
fn get_id(&mut self) -> uint {
let id = self.next_id;
self.next_id += 1;
id
}
}
impl TreeSink for Sink {
type Handle = uint;
fn parse_error(&mut self, msg: CowString<'static>) {
println!("Parse error: {}", msg);
}
fn get_document(&mut self) -> ui... | struct Sink {
next_id: uint,
names: HashMap<uint, QualName>, | random_line_split |
print-tree-actions.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... | () {
let sink = Sink {
next_id: 1,
names: HashMap::new(),
};
let input = io::stdin().read_to_string().unwrap();
parse_to(sink, one_input(input), Default::default());
}
| main | identifier_name |
issue-24081.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
issue-24081.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
type Add = bool;
struct Sub { x: f32 }
enum Mul { A, B }
mod Div { }
trait Rem { }
fn main() {} | use std::ops::Add; //~ ERROR import `Add` conflicts with type in this module
use std::ops::Sub; //~ ERROR import `Sub` conflicts with type in this module
use std::ops::Mul; //~ ERROR import `Mul` conflicts with type in this module
use std::ops::Div; //~ ERROR import `Div` conflicts with existing submodule
use std::ops:... | random_line_split |
plugin.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 ... | <T, F>(f: F) -> T where
F: FnOnce(&mut BTreeMap<Name, Span>) -> T,
{
USED_DIAGNOSTICS.with(move |slot| {
f(&mut *slot.borrow_mut())
})
}
pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
span: Span,
token_tree: &[TokenTre... | with_used_diagnostics | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.