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
macro_import.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...
(&mut self, item: &ast::Item) { // We're only interested in `extern crate`. match item.node { ast::ItemExternCrate(_) => {} _ => { visit::walk_item(self, item); return; } } // Parse the attributes relating to macros. ...
visit_item
identifier_name
macro_import.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...
// do nothing. } } impl<'a> MacroLoader<'a> { fn load_macros<'b>(&mut self, vi: &ast::Item, import: Option<MacroSelection>, reexport: MacroSelection) { if let Some(sel) = import.as_ref() { if sel.is_empty() && reex...
} fn visit_mac(&mut self, _: &ast::Mac) { // bummer... can't see macro imports inside macros.
random_line_split
macro_import.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...
pub type MacroSelection = HashMap<token::InternedString, Span>; // note that macros aren't expanded yet, and therefore macros can't add macro imports. impl<'a, 'v> Visitor<'v> for MacroLoader<'a> { fn visit_item(&mut self, item: &ast::Item) { // We're only interested in `extern crate`. match item...
{ let mut loader = MacroLoader::new(sess); // We need to error on `#[macro_use] extern crate` when it isn't at the // crate root, because `$crate` won't work properly. Identify these by // spans, because the crate map isn't set up yet. for item in &krate.module.items { if let ast::ItemExter...
identifier_body
macro_import.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...
"macro_use" => { let names = attr.meta_item_list(); if names.is_none() { // no names => load all import = None; } if let (Some(sel), Some(names)) = (import.as_mut(), names) { ...
{ self.sess.span_err(attr.span, "#[plugin] on `extern crate` is deprecated"); self.sess.fileline_help(attr.span, &format!("use a crate attribute instead, \ i.e. #![plugin({})]", ...
conditional_block
htmldialogelement.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding...
(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn SetReturnValue(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } // https://ht...
ReturnValue
identifier_name
htmldialogelement.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding...
// Step 3 if let Some(new_value) = return_value { *self.return_value.borrow_mut() = new_value; } // TODO: Step 4 implement pending dialog stack removal // Step 5 win.task_manager() .dom_manipulation_task_source() .queue_simple_event(t...
{ return; }
conditional_block
htmldialogelement.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding...
HTMLDialogElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), return_value: DomRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &...
document: &Document, ) -> HTMLDialogElement {
random_line_split
htmldialogelement.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding...
// Step 5 win.task_manager() .dom_manipulation_task_source() .queue_simple_event(target, atom!("close"), &win); } }
{ let element = self.upcast::<Element>(); let target = self.upcast::<EventTarget>(); let win = window_from_node(self); // Step 1 & 2 if element .remove_attribute(&ns!(), &local_name!("open")) .is_none() { return; } // ...
identifier_body
channelmergernode.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::audionode::{AudioNode, MAX_CHANNEL_COUNT}; use crate::dom::baseaudiocontext::BaseAudioContext; us...
if options.numberOfInputs < 1 || options.numberOfInputs > MAX_CHANNEL_COUNT { return Err(Error::IndexSize); } let node = AudioNode::new_inherited( AudioNodeInit::ChannelMergerNode(options.into()), context, node_options, options.numbe...
{ return Err(Error::InvalidState); }
conditional_block
channelmergernode.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::audionode::{AudioNode, MAX_CHANNEL_COUNT}; use crate::dom::baseaudiocontext::BaseAudioContext; us...
if node_options.count!= 1 || node_options.mode!= ChannelCountMode::Explicit { return Err(Error::InvalidState); } if options.numberOfInputs < 1 || options.numberOfInputs > MAX_CHANNEL_COUNT { return Err(Error::IndexSize); } let node = AudioNode::new_inher...
ChannelCountMode::Explicit, ChannelInterpretation::Speakers, );
random_line_split
channelmergernode.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::audionode::{AudioNode, MAX_CHANNEL_COUNT}; use crate::dom::baseaudiocontext::BaseAudioContext; us...
(options: &'a ChannelMergerOptions) -> Self { Self { channels: options.numberOfInputs as u8, } } }
from
identifier_name
channelmergernode.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::audionode::{AudioNode, MAX_CHANNEL_COUNT}; use crate::dom::baseaudiocontext::BaseAudioContext; us...
}
{ Self { channels: options.numberOfInputs as u8, } }
identifier_body
sph_shabal.rs
extern crate libc; use std::default::Default; #[repr(C)] pub struct sph_shabal_context { pub buf: [u8; 64], pub ptr: libc::size_t, pub a: [u32; 12], pub b: [u32; 16], pub c: [u32; 16], pub w_high: u32, pub w_low: u32, } impl Default for sph_shabal_context { fn default() -> sph_shabal_...
(input: &[u8]) -> [u8; 32] { let mut output: [u8; 32] = [0; 32]; unsafe { let mut shabal_ctx: sph_shabal_context = Default::default(); let shabal_ctx_ptr: *mut libc::c_void = &mut shabal_ctx as *mut _ as *mut libc::c_void; sph_shabal256_init(shabal_ctx_ptr); sph_shabal256(shabal_...
shabal256
identifier_name
sph_shabal.rs
extern crate libc; use std::default::Default; #[repr(C)] pub struct sph_shabal_context { pub buf: [u8; 64], pub ptr: libc::size_t, pub a: [u32; 12], pub b: [u32; 16], pub c: [u32; 16], pub w_high: u32, pub w_low: u32,
impl Default for sph_shabal_context { fn default() -> sph_shabal_context { sph_shabal_context { buf: [0u8; 64], ptr: 0, a: [0u32; 12], b: [0u32; 16], c: [0u32; 16], w_high: 0, w_low: 0, } } } pub fn shabal256(i...
}
random_line_split
mod.rs
use super::ObjectSafetyViolation; use crate::infer::InferCtxt; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::Symbol; use rustc_span::{MultiSpan, Span}; use std::...
} let has_multi_span =!multi_span.is_empty(); let mut note_span = MultiSpan::from_spans(multi_span.clone()); if let (Some(trait_span), true) = (trait_span, has_multi_span) { note_span .push_span_label(trait_span, "this trait cannot be made into an object...".to_string()); } f...
{ let spans = violation.spans(); let msg = if trait_span.is_none() || spans.is_empty() { format!("the trait cannot be made into an object because {}", violation.error_msg()) } else { format!("...because {}", violation.error_msg()) }; ...
conditional_block
mod.rs
use super::ObjectSafetyViolation; use crate::infer::InferCtxt; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::Symbol; use rustc_span::{MultiSpan, Span}; use std::...
if let ObjectSafetyViolation::SizedSelf(sp) = &violation { if!sp.is_empty() { // Do not report `SizedSelf` without spans pointing at `SizedSelf` obligations // with a `Span`. reported_violations.insert(ObjectSafetyViolation::SizedSelf(vec![].into())); ...
{ let trait_str = tcx.def_path_str(trait_def_id); let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node { hir::Node::Item(item) => Some(item.ident.span), _ => None, }); let span = tcx.sess.source_map().guess_head_span(span); let mut err = struct_span_err!( ...
identifier_body
mod.rs
use super::ObjectSafetyViolation; use crate::infer::InferCtxt; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::Symbol; use rustc_span::{MultiSpan, Span}; use std::...
} } } let has_multi_span =!multi_span.is_empty(); let mut note_span = MultiSpan::from_spans(multi_span.clone()); if let (Some(trait_span), true) = (trait_span, has_multi_span) { note_span .push_span_label(trait_span, "this trait cannot be made into an object...".to...
violation.solution(&mut err);
random_line_split
mod.rs
use super::ObjectSafetyViolation; use crate::infer::InferCtxt; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::Symbol; use rustc_span::{MultiSpan, Span}; use std::...
( &self, error_span: Span, item_name: Symbol, _impl_item_def_id: DefId, trait_item_def_id: DefId, requirement: &dyn fmt::Display, ) -> DiagnosticBuilder<'tcx> { let msg = "impl has stricter requirements than trait"; let sp = self.tcx.sess.source_map()....
report_extra_impl_obligation
identifier_name
coord.rs
use std::ops::*; use std::fmt; #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)] pub struct Coord<T>(pub T, pub T); impl<T> Coord<T> { pub const fn squared(value: T) -> Self where T: Copy { Coord(value, value) } pub fn sum(self) -> T where T: Add<Output=T> { let Coord(x, y) = self; ...
}
{ let coord = Coord(5,6); assert_eq!(5, coord.0); assert_eq!(6, coord.1); }
identifier_body
coord.rs
use std::ops::*; use std::fmt; #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)] pub struct Coord<T>(pub T, pub T); impl<T> Coord<T> { pub const fn squared(value: T) -> Self where T: Copy { Coord(value, value) } pub fn sum(self) -> T where T: Add<Output=T> { let Coord(x, y) = self; ...
<U>(self, mut func: impl FnMut(T) -> U) -> Coord<U> { let Coord(x, y) = self; Coord(func(x), func(y)) } } impl<T: fmt::Debug> fmt::Debug for Coord<T> { fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:?}, {:?})", self.0, self.1) } } impl<T: fmt::Display> fmt::D...
map
identifier_name
coord.rs
use std::ops::*; use std::fmt; #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)] pub struct Coord<T>(pub T, pub T); impl<T> Coord<T> { pub const fn squared(value: T) -> Self where T: Copy { Coord(value, value) } pub fn sum(self) -> T where T: Add<Output=T> { let Coord(x, y) = self; ...
use super::*; #[test] fn sanity() { let coord = Coord(5,6); assert_eq!(5, coord.0); assert_eq!(6, coord.1); } }
#[cfg(test)] mod tests {
random_line_split
enum.rs
// Task : To explain enum in rust // Author : Vigneshwer // Version : 1.0 // Date : 3 Dec 2016 fn main() { let hulk = Hero::Strong(100); let fasty = Hero::Fast; //converting from let spiderman = Hero::Info { name: "spiderman".to_owned(), secret: "peter parker".to_owned(), }; g...
(h: Hero) { match h { Hero::Fast => println!("Fast"), Hero::Strong(i) => println!("Lifts {} tons", i), Hero::Info { name, secret } => { println!(" name is : {0} secret is : {1}", name, secret); } } }
get_info
identifier_name
enum.rs
fn main() { let hulk = Hero::Strong(100); let fasty = Hero::Fast; //converting from let spiderman = Hero::Info { name: "spiderman".to_owned(), secret: "peter parker".to_owned(), }; get_info(spiderman); get_info(hulk); get_info(fasty); } // declaring the enum enum Hero...
// Task : To explain enum in rust // Author : Vigneshwer // Version : 1.0 // Date : 3 Dec 2016
random_line_split
enum.rs
// Task : To explain enum in rust // Author : Vigneshwer // Version : 1.0 // Date : 3 Dec 2016 fn main()
// declaring the enum enum Hero { Fast, Strong(i32), Info { name: String, secret: String }, } // function to perform for each types fn get_info(h: Hero) { match h { Hero::Fast => println!("Fast"), Hero::Strong(i) => println!("Lifts {} tons", i), Hero::Info { name, secret } => ...
{ let hulk = Hero::Strong(100); let fasty = Hero::Fast; //converting from let spiderman = Hero::Info { name: "spiderman".to_owned(), secret: "peter parker".to_owned(), }; get_info(spiderman); get_info(hulk); get_info(fasty); }
identifier_body
lib.rs
//! This library provides wrappers for LLVM that are memory-safe and follow //! Rust idioms.
//! //! The original LLVM reference is available [here](http://llvm.org/doxygen/) //! but take note that this isn't as thorough as this documentation. extern crate llvm_sys as ffi; extern crate libc; extern crate cbox; #[macro_use] mod macros; mod buffer; mod block; mod builder; mod compile; mod context; mod engine; ...
random_line_split
example.rs
#[derive(Debug, PartialEq, Eq)] pub struct Palindrome { pub factors: Vec<(u64, u64)>, } impl Palindrome { /// Create a palindrome with the given factors pub fn new(mut a: u64, mut b: u64) -> Palindrome { if a > b { std::mem::swap(&mut a, &mut b); } Palindrome { ...
Some((mut minp, mut maxp)) => { match (a * b).cmp(&minp.value()) { std::cmp::Ordering::Greater => {} std::cmp::Ordering::Less => minp = Palindrome::new(a, b), std::cmp::Ordering::Equal => minp...
result = match result { None => Some((Palindrome::new(a, b), Palindrome::new(a, b))),
random_line_split
example.rs
#[derive(Debug, PartialEq, Eq)] pub struct
{ pub factors: Vec<(u64, u64)>, } impl Palindrome { /// Create a palindrome with the given factors pub fn new(mut a: u64, mut b: u64) -> Palindrome { if a > b { std::mem::swap(&mut a, &mut b); } Palindrome { factors: vec![(a, b)], } } /// Re...
Palindrome
identifier_name
example.rs
#[derive(Debug, PartialEq, Eq)] pub struct Palindrome { pub factors: Vec<(u64, u64)>, } impl Palindrome { /// Create a palindrome with the given factors pub fn new(mut a: u64, mut b: u64) -> Palindrome { if a > b { std::mem::swap(&mut a, &mut b); } Palindrome { ...
/// Insert a new set of factors into an existing palindrome pub fn insert(&mut self, mut a: u64, mut b: u64) { if a > b { std::mem::swap(&mut a, &mut b); } self.factors.push((a, b)); self.factors.sort_unstable(); self.factors.dedup(); } } /// return the...
{ // this could in theory panic with a bounds error, but the length of // self.factors is known to start at 1 and is only ever increased self.factors[0].0 * self.factors[0].1 }
identifier_body
privacy1.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 B { fn foo() -> Self; } impl B for int { fn foo() -> int { 3 } } pub enum Enum { Pub } mod baz { pub struct A; impl A { pub fn foo() {} fn bar() {} pub fn foo2(&self) {} fn bar2(&self) {} } ...
{}
identifier_body
privacy1.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() {} pub fn foo2(&self) {} fn bar2(&self) {} } // both of these are re-exported by `bar`, but only one should be // validly re-exported pub fn foo() {} fn bar() {} } extern { fn epriv(); pub fn epub(); ...
foo
identifier_name
privacy1.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 ...
::bar::baz::A.foo2(); //~ ERROR: struct `A` is inaccessible //~^ NOTE: module `baz` is private ::bar::baz::A.bar2(); //~ ERROR: struct `A` is inaccessible //~^ ERROR: method `bar2` is private //~^^ NOTE: ...
::bar::A.bar2(); //~ ERROR: method `bar2` is private ::bar::baz::A::foo(); //~ ERROR: method `foo` is inaccessible //~^ NOTE: module `baz` is private ::bar::baz::A::bar(); //~ ERROR: method `bar` is private
random_line_split
extract.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use cpython::Python; /// Trait for extracting a Rust object from a Python wrapper class. /// /// A common pattern when writing bindings for ...
(&self, py: Python) -> Self::Inner { self.extract_inner_ref(py).clone() } }
extract_inner
identifier_name
extract.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the
*/ use cpython::Python; /// Trait for extracting a Rust object from a Python wrapper class. /// /// A common pattern when writing bindings for Rust objects is to define /// a Python wrapper class using the `py_class!` macro, with the underlying /// Rust object stored as a data field within the Python object. /// ///...
* GNU General Public License version 2.
random_line_split
extract.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use cpython::Python; /// Trait for extracting a Rust object from a Python wrapper class. /// /// A common pattern when writing bindings for ...
}
{ self.extract_inner_ref(py).clone() }
identifier_body
cell.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use log::error; use super::Output; use lumol_core::System; /// The `CellOutput` writes all the component...
mpl Output for CellOutput { #[allow(clippy::non_ascii_literal)] fn setup(&mut self, _: &System) { writeln_or_log!(self, "# Unit cell of the simulation"); writeln_or_log!(self, "# Step A/Å B/Å C/Å α/deg β/deg γ/deg"); } fn write(&mut self, system: &System) { writeln_or_log!(self,...
Ok(CellOutput { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) } } i
identifier_body
cell.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use log::error; use super::Output; use lumol_core::System; /// The `CellOutput` writes all the component...
fn cell() { test_output( |path| Box::new(CellOutput::new(path).unwrap()), "# Unit cell of the simulation # Step A/Å B/Å C/Å α/deg β/deg γ/deg 42 10 10 10 90 90 90 ", ); } }
use super::*; use super::super::tests::test_output; #[test]
random_line_split
cell.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use log::error; use super::Output; use lumol_core::System; /// The `CellOutput` writes all the component...
self, _: &System) { writeln_or_log!(self, "# Unit cell of the simulation"); writeln_or_log!(self, "# Step A/Å B/Å C/Å α/deg β/deg γ/deg"); } fn write(&mut self, system: &System) { writeln_or_log!(self, "{} {} {} {} {} {} {}", system.step, system.cell.a(), ...
(&mut
identifier_name
issue-34053.rs
// run-pass use std::sync::atomic::{AtomicUsize, Ordering}; static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0); struct A(i32); impl Drop for A { fn drop(&mut self)
} static FOO: A = A(123); const BAR: A = A(456); impl A { const BAZ: A = A(789); } fn main() { assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0); assert_eq!(&FOO.0, &123); assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0); assert_eq!(BAR.0, 456); assert_eq!(DROP_COUNTER.load(Ordering::SeqC...
{ // update global drop count DROP_COUNTER.fetch_add(1, Ordering::SeqCst); }
identifier_body
issue-34053.rs
// run-pass use std::sync::atomic::{AtomicUsize, Ordering}; static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0); struct A(i32); impl Drop for A { fn
(&mut self) { // update global drop count DROP_COUNTER.fetch_add(1, Ordering::SeqCst); } } static FOO: A = A(123); const BAR: A = A(456); impl A { const BAZ: A = A(789); } fn main() { assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0); assert_eq!(&FOO.0, &123); assert_eq!(DROP_COU...
drop
identifier_name
issue-34053.rs
// run-pass use std::sync::atomic::{AtomicUsize, Ordering};
fn drop(&mut self) { // update global drop count DROP_COUNTER.fetch_add(1, Ordering::SeqCst); } } static FOO: A = A(123); const BAR: A = A(456); impl A { const BAZ: A = A(789); } fn main() { assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0); assert_eq!(&FOO.0, &123); assert_e...
static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0); struct A(i32); impl Drop for A {
random_line_split
solution.rs
use std::env; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; fn is_triangle(mut triangle: Vec<i32>) -> bool { triangle.sort(); return triangle[0] + triangle[1] > triangle[2]; } fn main() { let args: Vec<String> = env::args().collect(); let f = File::open(&args[1]).expect("Could n...
.filter(|s|!s.is_empty()) .map(|s| s.parse().unwrap()) .collect(); for num in &numbers { all_nums.push(*num); } if is_triangle(numbers) { horizontal += 1; } } let mut vertical = 0; for i in 0..(all_nums.len() / 9) ...
for line in reader.lines() { let numbers: Vec<i32> = line.unwrap() .split(' ') .map(|s| s.trim())
random_line_split
solution.rs
use std::env; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; fn is_triangle(mut triangle: Vec<i32>) -> bool { triangle.sort(); return triangle[0] + triangle[1] > triangle[2]; } fn
() { let args: Vec<String> = env::args().collect(); let f = File::open(&args[1]).expect("Could not open file"); let reader = BufReader::new(f); let mut horizontal = 0; let mut all_nums: Vec<i32> = Vec::new(); for line in reader.lines() { let numbers: Vec<i32> = line.unwrap() ...
main
identifier_name
solution.rs
use std::env; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; fn is_triangle(mut triangle: Vec<i32>) -> bool { triangle.sort(); return triangle[0] + triangle[1] > triangle[2]; } fn main() { let args: Vec<String> = env::args().collect(); let f = File::open(&args[1]).expect("Could n...
} } println!("{} triangles possible horizontally", horizontal); println!("{} triangles possible vertically", vertical); }
{ vertical += 1; }
conditional_block
solution.rs
use std::env; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; fn is_triangle(mut triangle: Vec<i32>) -> bool
fn main() { let args: Vec<String> = env::args().collect(); let f = File::open(&args[1]).expect("Could not open file"); let reader = BufReader::new(f); let mut horizontal = 0; let mut all_nums: Vec<i32> = Vec::new(); for line in reader.lines() { let numbers: Vec<i32> = line.unwrap() ...
{ triangle.sort(); return triangle[0] + triangle[1] > triangle[2]; }
identifier_body
main.rs
mod common; mod color; mod math; mod ppm; mod renderer; mod shade_record; mod shape; mod tracer; mod view_plane; mod world; use std::cell::RefCell; use std::rc::Rc; use color::RGBColor; use renderer::Renderer; use tracer::{Tracer, MultipleObjects}; use view_plane::ViewPlane; use world::World; fn
() { let mut view_plane = ViewPlane::new(300, 300, 1.0, 1.0, RGBColor::new(0.5, 0.5, 0.5)); let world = Rc::new(RefCell::new(World::new())); let tracer = Box::new(MultipleObjects::new(world.clone())) as Box<Tracer>; let renderer = Renderer::new(tracer); world.borrow().build(); renderer.render_w...
main
identifier_name
main.rs
mod common; mod color; mod math; mod ppm; mod renderer; mod shade_record; mod shape; mod tracer; mod view_plane; mod world; use std::cell::RefCell; use std::rc::Rc; use color::RGBColor; use renderer::Renderer; use tracer::{Tracer, MultipleObjects}; use view_plane::ViewPlane; use world::World; fn main()
{ let mut view_plane = ViewPlane::new(300, 300, 1.0, 1.0, RGBColor::new(0.5 , 0.5, 0.5)); let world = Rc::new(RefCell::new(World::new())); let tracer = Box::new(MultipleObjects::new(world.clone())) as Box<Tracer>; let renderer = Renderer::new(tracer); world.borrow().build(); renderer.render_wor...
identifier_body
main.rs
mod common; mod color; mod math; mod ppm; mod renderer; mod shade_record; mod shape; mod tracer;
use std::rc::Rc; use color::RGBColor; use renderer::Renderer; use tracer::{Tracer, MultipleObjects}; use view_plane::ViewPlane; use world::World; fn main() { let mut view_plane = ViewPlane::new(300, 300, 1.0, 1.0, RGBColor::new(0.5, 0.5, 0.5)); let world = Rc::new(RefCell::new(World::new())); let tracer = ...
mod view_plane; mod world; use std::cell::RefCell;
random_line_split
streaming.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
pub struct StreamingHandler<R: io::Read> { buffer: [u8; BUFFER_SIZE], buffer_leftover: usize, status: StatusCode, content: io::BufReader<R>, mimetype: Mime, safe_to_embed_on: Option<(String, u16)>, } impl<R: io::Read> StreamingHandler<R> { pub fn new(content: R, status: StatusCode, mimetype: Mime, embeddable_on...
const BUFFER_SIZE: usize = 1024;
random_line_split
streaming.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
(content: R, status: StatusCode, mimetype: Mime, embeddable_on: Option<(String, u16)>) -> Self { StreamingHandler { buffer: [0; BUFFER_SIZE], buffer_leftover: 0, status: status, content: io::BufReader::new(content), mimetype: mimetype, safe_to_embed_on: embeddable_on, } } pub fn set_initial_con...
new
identifier_name
multiple.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-format_strings: true // Test of lots of random stuff. // FIXME split this into multiple, self-contained tests. #[attr1] extern crate foo; #[attr2] #[attr3] extern crate foo; #[attr1] extern crate foo; #[attr2] #[attr3] extern crate foo; use...
HttpVersion, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, ) { } fn deconstruct( foo: Bar, ) -> ( SocketAddr, Method, Headers, RequestUri, HttpVersion, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, ) { } #[rustfmt::skip] mod a{ fn foo(x: T) { let x: ...
RequestUri,
random_line_split
multiple.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-format_strings: true // Test of lots of random stuff. // FIXME split this into multiple, self-contained tests. #[attr1] extern crate foo; #[attr2] #[attr3] extern crate foo; #[attr1] extern crate foo; #[attr2] #[attr3] extern crate foo; use...
}
{ let x: T = dfasdf; }
identifier_body
multiple.rs
// rustfmt-normalize_comments: true // rustfmt-wrap_comments: true // rustfmt-format_strings: true // Test of lots of random stuff. // FIXME split this into multiple, self-contained tests. #[attr1] extern crate foo; #[attr2] #[attr3] extern crate foo; #[attr1] extern crate foo; #[attr2] #[attr3] extern crate foo; use...
(self) -> Dog {} } /// The `nodes` and `edges` method each return instantiations of /// `Cow<[T]>` to leave implementers the freedom to create /// entirely new vectors or to pass back slices into internally owned /// vectors. pub trait GraphWalk<'a, N, E> { /// Returns all the nodes in this graph. fn nodes(&'...
f3
identifier_name
managed_process.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/. // Assumes Unix use libc::{self, c_int}; use std::thread; use std::thread::JoinHandle; use std::sync::{Arc, Mutex, R...
else { Ok(t) } } /// Check the return value of a libc function, but, retry the given function if /// the returned error is EINTR (Interrupted) fn c_rv_retry<F>(mut f: F) -> Result<c_int> where F: FnMut() -> c_int { loop { match c_rv(f()) { Err(ref e) if e.kind() == ErrorKind::I...
{ Err(Error::last_os_error()) }
conditional_block
managed_process.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/. // Assumes Unix use libc::{self, c_int}; use std::thread; use std::thread::JoinHandle; use std::sync::{Arc, Mutex, R...
(restart_threshold_secs: u64) -> Self { Backoff::new(Duration::from_secs(restart_threshold_secs)) } fn next_backoff(&mut self) -> Duration { let end_time = Instant::now(); let duration_to_backoff = if let Some(start_time) = self.start_time { if (end_time - start_time) < sel...
from_secs
identifier_name
managed_process.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/. // Assumes Unix use libc::{self, c_int}; use std::thread; use std::thread::JoinHandle; use std::sync::{Arc, Mutex, R...
/// Create a new ManagedProcess and start it. /// /// # Examples /// /// use tunnel_controller::ManagedProcess; /// use std::process::Command; /// /// let process = ManagedProcess::start(|| { /// Command::new("echo") /// .arg("Hello") /// .arg("World...
} impl ManagedProcess {
random_line_split
regions-close-object-into-object.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 ...
<'a, T:'static>(v: Box<A<T>>) -> Box<X+'static> { box B(&*v) as Box<X> //~ ERROR cannot infer } fn h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> { box B(&*v) as Box<X> } fn i<'a, T, U>(v: Box<A<U>>) -> Box<X+'static> { box B(&*v) as Box<X> //~ ERROR cannot infer } fn main() {}
g
identifier_name
regions-close-object-into-object.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 i<'a, T, U>(v: Box<A<U>>) -> Box<X+'static> { box B(&*v) as Box<X> //~ ERROR cannot infer } fn main() {}
fn h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> { box B(&*v) as Box<X> }
random_line_split
regions-close-object-into-object.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 h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> { box B(&*v) as Box<X> } fn i<'a, T, U>(v: Box<A<U>>) -> Box<X+'static> { box B(&*v) as Box<X> //~ ERROR cannot infer } fn main() {}
{ box B(&*v) as Box<X> //~ ERROR cannot infer }
identifier_body
mod.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 pub mod device; pub mod event_handler; pub mod persist; pub mod test_utils; mod utils; use vm_memory::GuestMemoryError; pub use self::device::Balloon; pub use self::device::BalloonConfig; pub use self::d...
{ AddressTranslation, MalformedRange, MadviseFail(std::io::Error), MmapFail(std::io::Error), RegionNotFound, } pub type Result<T> = std::result::Result<T, Error>;
RemoveRegionError
identifier_name
mod.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 pub mod device; pub mod event_handler; pub mod persist; pub mod test_utils; mod utils; use vm_memory::GuestMemoryError; pub use self::device::Balloon; pub use self::device::BalloonConfig; pub use self::d...
const VIRTIO_BALLOON_S_MINFLT: u16 = 3; const VIRTIO_BALLOON_S_MEMFREE: u16 = 4; const VIRTIO_BALLOON_S_MEMTOT: u16 = 5; const VIRTIO_BALLOON_S_AVAIL: u16 = 6; const VIRTIO_BALLOON_S_CACHES: u16 = 7; const VIRTIO_BALLOON_S_HTLB_PGALLOC: u16 = 8; const VIRTIO_BALLOON_S_HTLB_PGFAIL: u16 = 9; #[derive(Debug)] pub enum Er...
// The statistics tags. const VIRTIO_BALLOON_S_SWAP_IN: u16 = 0; const VIRTIO_BALLOON_S_SWAP_OUT: u16 = 1; const VIRTIO_BALLOON_S_MAJFLT: u16 = 2;
random_line_split
renderer.rs
use crate::papers::{DocumentSpec, Workspace}; use crate::prelude::*; use futures::{compat::*, StreamExt}; use slog::{debug, error}; use std::process::Command; use tokio::{fs::File, io::AsyncWrite}; use tokio_process::CommandExt; /// The name of the downloaded template inside our Tera instance. const TEMPLATE_NAME: &st...
debug!(&self.workspace.logger(), "LaTeX succeeded. Stdout:\n{}", stdout); Ok(()) } /// Report failure and move on. async fn report_failure(&self, error: failure::Error) -> Result<(), ()> { error!( self.workspace.logger(), "Error rendering document: {:?}.",...
{ return Err(format_err!("LaTeX failed. Stdout:\n{}", stdout)); }
conditional_block
renderer.rs
use crate::papers::{DocumentSpec, Workspace}; use crate::prelude::*; use futures::{compat::*, StreamExt}; use slog::{debug, error}; use std::process::Command; use tokio::{fs::File, io::AsyncWrite}; use tokio_process::CommandExt; /// The name of the downloaded template inside our Tera instance. const TEMPLATE_NAME: &st...
(&self) -> Result<(), failure::Error> { let rendered_template = self .tera .render(TEMPLATE_NAME, &self.document_spec.variables()) .map_err(|err| format_err!("Rendering error: {}.", err))?; debug!( self.workspace.logger(), "Writing template to {:...
render_template
identifier_name
renderer.rs
use crate::papers::{DocumentSpec, Workspace}; use crate::prelude::*; use futures::{compat::*, StreamExt}; use slog::{debug, error}; use std::process::Command; use tokio::{fs::File, io::AsyncWrite}; use tokio_process::CommandExt; /// The name of the downloaded template inside our Tera instance. const TEMPLATE_NAME: &st...
debug!( self.workspace.logger(), "Template successfully written to {:?}.", &self.template_path() ); Ok(()) } async fn run_latex(&self) -> Result<(), failure::Error> { debug!( &self.workspace.logger(), "Value of templ...
{ let rendered_template = self .tera .render(TEMPLATE_NAME, &self.document_spec.variables()) .map_err(|err| format_err!("Rendering error: {}.", err))?; debug!( self.workspace.logger(), "Writing template to {:?}.", &self.template_pa...
identifier_body
renderer.rs
use crate::papers::{DocumentSpec, Workspace}; use crate::prelude::*; use futures::{compat::*, StreamExt}; use slog::{debug, error}; use std::process::Command; use tokio::{fs::File, io::AsyncWrite}; use tokio_process::CommandExt; /// The name of the downloaded template inside our Tera instance. const TEMPLATE_NAME: &st...
"Value of template_path: {:?}.", self.template_path() ); debug!( &self.workspace.logger(), "Rendered template exists: {:?}.", self.template_path().exists() ); debug!(&self.workspace.logger(), "Spawning latex."); let lat...
async fn run_latex(&self) -> Result<(), failure::Error> { debug!( &self.workspace.logger(),
random_line_split
main.rs
#![feature(slicing_syntax)] #![feature(box_syntax)] extern crate getopts; #[macro_use] extern crate linked_list; use std::io; use std::mem; use std::iter::repeat; use lib::{ SEle, Env, LamOrFn, ScmAlert, ScmAlertMode, scheme_alert, scheme_stdlib}; use lib::scm_macro::PrecompileEnv; mod input; mod lib; mod pa...
/// How many more closing parens there are than opening parens fn close_paren_surplus(ts: &[parse::Token]) -> i32 { use parse::Token::{OpenParen, CloseParen}; ts.iter().fold(0i32, |acc, t| match *t { OpenParen => acc-1, CloseParen => acc+1, _ => acc }) } fn interactive_shell(env: &mut Env, macro_env: &...
{ slc.iter().map(|s| s.to_string()).collect() }
identifier_body
main.rs
#![feature(slicing_syntax)] #![feature(box_syntax)] extern crate getopts; #[macro_use] extern crate linked_list; use std::io; use std::mem; use std::iter::repeat; use lib::{ SEle, Env, LamOrFn, ScmAlert, ScmAlertMode, scheme_alert, scheme_stdlib}; use lib::scm_macro::PrecompileEnv; mod input; mod lib; mod pa...
(ts: &[parse::Token]) -> i32 { use parse::Token::{OpenParen, CloseParen}; ts.iter().fold(0i32, |acc, t| match *t { OpenParen => acc-1, CloseParen => acc+1, _ => acc }) } fn interactive_shell(env: &mut Env, macro_env: &mut PrecompileEnv) { print!("scheme-rs interactive shell. Copyright (C) 2014 Johan Jo...
close_paren_surplus
identifier_name
main.rs
#![feature(slicing_syntax)] #![feature(box_syntax)] extern crate getopts; #[macro_use] extern crate linked_list; use std::io; use std::mem; use std::iter::repeat; use lib::{ SEle, Env, LamOrFn, ScmAlert, ScmAlertMode, scheme_alert, scheme_stdlib}; use lib::scm_macro::PrecompileEnv; mod input; mod lib; mod pa...
/// How many more closing parens there are than opening parens fn close_paren_surplus(ts: &[parse::Token]) -> i32 { use parse::Token::{OpenParen, CloseParen}; ts.iter().fold(0i32, |acc, t| match *t { OpenParen => acc-1, CloseParen => acc+1, _ => acc }) } fn interactive_shell(env: &mut Env, macro_env: &m...
slc.iter().map(|s| s.to_string()).collect() }
random_line_split
main.rs
#![feature(slicing_syntax)] #![feature(box_syntax)] extern crate getopts; #[macro_use] extern crate linked_list; use std::io; use std::mem; use std::iter::repeat; use lib::{ SEle, Env, LamOrFn, ScmAlert, ScmAlertMode, scheme_alert, scheme_stdlib}; use lib::scm_macro::PrecompileEnv; mod input; mod lib; mod pa...
else { token_buf.push((line_n, tokens)); { let parsed_and_expanded = parse::parse_token_lines( mem::replace(&mut token_buf, Vec::with_capacity(3))) .into_iter().map(|e| macro_env.expand(e)).collect(); print!("{}\n>> ", env.eval_sequence(parsed_and_expanded)); } line_n = 1; rparen_surp...
{ scheme_alert(ScmAlert::Unexp(")"), &ScmAlertMode::Warn); token_buf.clear(); line_n = 1; rparen_surplus = 0; print!(">> "); }
conditional_block
documenttype.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::DocumentTypeBinding; use dom::bindings::codegen::Bindings::DocumentTypeBindi...
fn SystemId(self) -> DOMString { self.system_id.clone() } // http://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(self) { let node: JSRef<Node> = NodeCast::from_ref(self); node.remove_self(); } }
{ self.public_id.clone() }
identifier_body
documenttype.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::DocumentTypeBinding; use dom::bindings::codegen::Bindings::DocumentTypeBindi...
(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::DocumentType) } } impl DocumentType { fn new_inherited(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>, document: JSRef<Documen...
is_documenttype
identifier_name
documenttype.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::DocumentTypeBinding; use dom::bindings::codegen::Bindings::DocumentTypeBindi...
fn PublicId(self) -> DOMString { self.public_id.clone() } fn SystemId(self) -> DOMString { self.system_id.clone() } // http://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(self) { let node: JSRef<Node> = NodeCast::from_ref(self); node.remove_self(); } ...
self.name.clone() }
random_line_split
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
pub fn release(&self) { let refcount = self.refcount.get(); assert!(refcount > 0) self.refcount.set(refcount - 1); if refcount == 1 { let cx = self.global.root().root_ref().get_cx(); unsafe { JS_RemoveObjectRoot(cx, self.reflector().rootable(...
{ let refcount = self.refcount.get(); if refcount == 0 { let cx = self.global.root().root_ref().get_cx(); unsafe { JS_AddObjectRoot(cx, self.reflector().rootable()); } } self.refcount.set(refcount + 1); TrustedWorkerAddress(self...
identifier_body
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
} fn SetOnmessage(self, listener: Option<EventHandlerNonNull>) { let eventtarget: JSRef<EventTarget> = EventTargetCast::from_ref(self); eventtarget.set_event_handler_common("message", listener) } } impl Reflectable for Worker { fn reflector<'a>(&'a self) -> &'a Reflector { self...
random_line_split
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
<'a>(&'a self) -> &'a Reflector { self.eventtarget.reflector() } }
reflector
identifier_name
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
self.refcount.set(refcount + 1); TrustedWorkerAddress(self as *const Worker as *const c_void) } pub fn release(&self) { let refcount = self.refcount.get(); assert!(refcount > 0) self.refcount.set(refcount - 1); if refcount == 1 { let cx = self.global...
{ let cx = self.global.root().root_ref().get_cx(); unsafe { JS_AddObjectRoot(cx, self.reflector().rootable()); } }
conditional_block
builtin.rs
use lexer::Span; use interpreter::*; use std::io; use std::io::prelude::*; impl<'a> Interpreter<'a> { pub fn builtin_print(&'a self, context: *mut InterpreterContext<'a>, args: &[Box<Expression>], span: Span) -> Res...
use parser::ast::*;
random_line_split
builtin.rs
use parser::ast::*; use lexer::Span; use interpreter::*; use std::io; use std::io::prelude::*; impl<'a> Interpreter<'a> { pub fn builtin_print(&'a self, context: *mut InterpreterContext<'a>, args: &[Box<Expression>], span: Span) ...
}; Ok(Value::Nil) } pub fn builtin_readln(&self, args: &[Box<Expression>], span: Span) -> Result<Value> { if args.len()!= 0 { return Err(Error { kind: ErrorKind::InvalidArgCount, span: span, }); }; let mut line =...
{ if args.len() != 1 { return Err(Error { kind: ErrorKind::InvalidArgCount, span: span, }); }; match try!(self.value_from_expression(context, args.get(0).unwrap())) { Value::String(s) => print!("{}", s), Value::Inte...
identifier_body
builtin.rs
use parser::ast::*; use lexer::Span; use interpreter::*; use std::io; use std::io::prelude::*; impl<'a> Interpreter<'a> { pub fn
(&'a self, context: *mut InterpreterContext<'a>, args: &[Box<Expression>], span: Span) -> Result<Value> { if args.len()!= 1 { return Err(Error { kind: ErrorKind::InvalidArgCount, ...
builtin_print
identifier_name
name.rs
use lazy_static::lazy_static; use regex::Regex; use serde::Deserialize; use std::fs; #[derive(Debug, Deserialize)] struct FirstName { male: Vec<Vec<String>>, female: Vec<Vec<String>>, } #[derive(Debug, Deserialize)] struct Data { first_name: FirstName, last_name: Vec<Vec<String>>, } lazy_static! { static r...
() { let name = gimei::name(); let items = &DATA.last_name; assert!(items.iter().any(|x| x[0] == name.last.kanji)); assert!(items.iter().any(|x| x[1] == name.last.hiragana)); assert!(items.iter().any(|x| x[2] == name.last.katakana)); } #[test] fn to_kanji() { let name = gimei::name(); let re = Regex::ne...
last_name
identifier_name
name.rs
use lazy_static::lazy_static; use regex::Regex; use serde::Deserialize; use std::fs; #[derive(Debug, Deserialize)] struct FirstName { male: Vec<Vec<String>>, female: Vec<Vec<String>>, } #[derive(Debug, Deserialize)] struct Data { first_name: FirstName, last_name: Vec<Vec<String>>, } lazy_static! { static r...
fn female_first_name() { let name = gimei::female(); let items = &DATA.first_name.female; assert!(items.iter().any(|x| x[0] == name.first.kanji)); assert!(items.iter().any(|x| x[1] == name.first.hiragana)); assert!(items.iter().any(|x| x[2] == name.first.katakana)); } #[test] fn last_name() { let name = g...
assert!(items.iter().any(|x| x[2] == name.first.katakana)); } #[test]
random_line_split
name.rs
use lazy_static::lazy_static; use regex::Regex; use serde::Deserialize; use std::fs; #[derive(Debug, Deserialize)] struct FirstName { male: Vec<Vec<String>>, female: Vec<Vec<String>>, } #[derive(Debug, Deserialize)] struct Data { first_name: FirstName, last_name: Vec<Vec<String>>, } lazy_static! { static r...
#[test] fn is_male() { let male_name = gimei::male(); assert!(male_name.is_male()); let female_name = gimei::female(); assert!(!female_name.is_male()); } #[test] fn is_female() { let male_name = gimei::male(); assert!(!male_name.is_female()); let female_name = gimei::female(); assert!(female_name.i...
{ let name = gimei::name(); let re = Regex::new(r"^\p{Katakana}+\s\p{Katakana}+$").unwrap(); assert!(re.is_match(&name.to_katakana())); }
identifier_body
for_kv_map.rs
use super::FOR_KV_MAP; use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then}; use clippy_utils::source::snippet; use clippy_utils::sugg; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::visitors::LocalUsedVisitor; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; use r...
{ match *pat { PatKind::Wild => true, PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => { !LocalUsedVisitor::new(cx, id).check_expr(body) }, _ => false, } }
identifier_body
for_kv_map.rs
use super::FOR_KV_MAP; use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then}; use clippy_utils::source::snippet; use clippy_utils::sugg; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::visitors::LocalUsedVisitor; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; use r...
<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool { match *pat { PatKind::Wild => true, PatKind::Binding(_, id, ident, None) if ident.as_str().starts_with('_') => { !LocalUsedVisitor::new(cx, id).check_expr(body) }, _ => false, } }
pat_is_wild
identifier_name
for_kv_map.rs
use super::FOR_KV_MAP; use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then}; use clippy_utils::source::snippet; use clippy_utils::sugg; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::visitors::LocalUsedVisitor; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; use r...
let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() { ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) { (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", ty, mutbl), (_, value) if pat_is_wild(...
if let PatKind::Tuple(pat, _) = pat.kind { if pat.len() == 2 { let arg_span = arg.span;
random_line_split
borrowck-uniq-via-box.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn borrow(_v: &int) {} fn box_mut(v: @mut ~int) { borrow(*v); //~ ERROR illegal borrow unless pure } fn box_mut_rec(v: @mut Rec) { borrow(v.f); //~ ERROR illegal borrow unless pure } fn box_mut_recs(v: @mut Outer) { borrow(v.f.g.h); //~ ERROR illegal borrow unless pure } fn box_imm(v: @~int) { borro...
h: ~int, }
random_line_split
borrowck-uniq-via-box.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 ...
{ }
identifier_body
borrowck-uniq-via-box.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 ...
(v: @Rec) { borrow(v.f); // OK } fn box_imm_recs(v: @Outer) { borrow(v.f.g.h); // OK } fn main() { }
box_imm_rec
identifier_name
build.rs
extern crate serde_codegen; extern crate serde_json; extern crate glob; use std::env; use std::fs; use std::path::Path; /// generate an enum of Events fn main() { for entry in glob::glob("src/**/*.rs.in").expect("Failed to read glob pattern") { println!("cargo:rerun-if-changed={}", entry.unwrap().display(...
for entry in glob::glob("**/*.rs.in").expect("Failed to read glob pattern") { match entry { Ok(src) => { let mut dst = Path::new(&out_dir).join(&src); // Change ".rs.in" to ".rs". dst.set_file_name(src.file_stem().expect("Failed to get file stem"...
// Switch to our `src` directory so that we have the right base for our // globs, and so that we won't need to strip `src/` off every path. env::set_current_dir("src").unwrap();
random_line_split
build.rs
extern crate serde_codegen; extern crate serde_json; extern crate glob; use std::env; use std::fs; use std::path::Path; /// generate an enum of Events fn main() { for entry in glob::glob("src/**/*.rs.in").expect("Failed to read glob pattern") { println!("cargo:rerun-if-changed={}", entry.unwrap().display(...
Err(e) => { panic!("Error globbing: {}", e); } } } }
{ let mut dst = Path::new(&out_dir).join(&src); // Change ".rs.in" to ".rs". dst.set_file_name(src.file_stem().expect("Failed to get file stem")); dst.set_extension("rs"); // Make sure our target directory exists. We only need ...
conditional_block
build.rs
extern crate serde_codegen; extern crate serde_json; extern crate glob; use std::env; use std::fs; use std::path::Path; /// generate an enum of Events fn main()
// Make sure our target directory exists. We only need // this if there are extra nested sudirectories under src/. fs::create_dir_all(dst.parent().unwrap()).unwrap(); // Process our source file. serde_codegen::expand(&src, &dst).unwrap();...
{ for entry in glob::glob("src/**/*.rs.in").expect("Failed to read glob pattern") { println!("cargo:rerun-if-changed={}", entry.unwrap().display()); } let out_dir = env::var_os("OUT_DIR").unwrap(); // Switch to our `src` directory so that we have the right base for our // globs, and so tha...
identifier_body
build.rs
extern crate serde_codegen; extern crate serde_json; extern crate glob; use std::env; use std::fs; use std::path::Path; /// generate an enum of Events fn
() { for entry in glob::glob("src/**/*.rs.in").expect("Failed to read glob pattern") { println!("cargo:rerun-if-changed={}", entry.unwrap().display()); } let out_dir = env::var_os("OUT_DIR").unwrap(); // Switch to our `src` directory so that we have the right base for our // globs, and so ...
main
identifier_name
mod.rs
//! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your mi...
fn previously_run_migration_versions<Conn>(conn: &Conn) -> QueryResult<HashSet<String>> where Conn: Connection, String: FromSql<VarChar, Conn::Backend>, { __diesel_schema_migrations.select(version) .load(conn) .map(|r| r.collect()) } fn latest_run_migration_version<Conn>(conn: &Conn) -> Que...
{ conn.silence_notices(|| { conn.execute("CREATE TABLE IF NOT EXISTS __diesel_schema_migrations ( version VARCHAR PRIMARY KEY NOT NULL, run_on TIMESTAMP NOT NULL DEFAULT 'now' )") }) }
identifier_body
mod.rs
//! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your mi...
//! - 20160107082941_create_posts //! - up.sql //! - down.sql //! ``` //! //! ```sql //! -- 20151219180527_create_users/up.sql //! CREATE TABLE users ( //! id SERIAL PRIMARY KEY, //! name VARCHAR NOT NULL, //! hair_color VARCHAR //! ); //! ``` //! //! ```sql //! -- 20151219180527_create_users/down.sql //!...
//! ```text //! # Directory Structure //! - 20151219180527_create_users //! - up.sql //! - down.sql
random_line_split
mod.rs
//! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your mi...
<Conn: Connection>(conn: &Conn, ver: &str, output: &mut Write) -> Result<(), RunMigrationsError> where for<'a> &'a NewMigration<'a>: Insertable<__diesel_schema_migrations, Conn::Backend>, { migration_with_version(ver) .map_err(|e| e.into()) .and_then(|m| run_migration(conn, m, output)) } ...
run_migration_with_version
identifier_name
document_condition.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
Err(()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => ...
Ok(UrlMatchingFunction::Url(url)) } else {
conditional_block
document_condition.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
f, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; serialize...
>(&sel
identifier_name
document_condition.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Ur...
let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => Geck...
identifier_body
document_condition.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS C...
}) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<UrlMatchingFunction, ()> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { ...
while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) })
random_line_split
nvic.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Harris <mail@bharr.is> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 /...
(irqn: usize) { get_reg().iser[irqn / 32].clear_iser(irqn % 32); } /// Disable an interrupt pub fn disable_irq(irqn: usize) { get_reg().icer[irqn / 32].clear_icer(irqn % 32); } /// Return whether the given interrupt is enabled pub fn is_enabled(irqn: usize) -> bool { get_reg().iser[irqn / 32].iser(irqn % 32) } ...
enable_irq
identifier_name
nvic.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Harris <mail@bharr.is> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 /...
/// Return whether the given interrupt is pending pub fn is_pending(irqn: usize) -> bool { get_reg().ispr[irqn / 32].ispr(irqn % 32) } /// Return whether the given interrupt is active pub fn is_active(irqn: usize) -> bool { get_reg().iabr[irqn / 32].iabr(irqn % 32) } /// Set the priority for the given interrupt...
{ get_reg().icpr[irqn / 32].clear_icpr(irqn % 32); }
identifier_body