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
registry.rs
. Git sources can also have commits deleted through //! rebasings where registries cannot have their versions deleted. //! //! # The Index of a Registry //! //! One of the major difficulties with a registry is that hosting so many //! packages may quickly run into performance problems when dealing with //! dependency g...
} impl<'cfg> Registry for RegistrySource<'cfg> { fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> { // If this is a precise dependency, then it came from a lockfile and in // theory the registry is known to contain this version. If, however, we // come back with no summar...
y `{}`", self.source_id.url()))); let repo = try!(self.open()); // git fetch origin let url = self.source_id.url().to_string(); let refspec = "refs/heads/*:refs/remotes/origin/*"; try!(git::fetch(&repo, &url, refspec).chain_error(|| { internal(format!("failed to fetc...
identifier_body
registry.rs
Git sources can also have commits deleted through //! rebasings where registries cannot have their versions deleted. //! //! # The Index of a Registry //! //! One of the major difficulties with a registry is that hosting so many //! packages may quickly run into performance problems when dealing with //! dependency gr...
ig.index.unwrap_or(DEFAULT.to_string()); url.to_url().map_err(human) } /// Get the default url for the registry pub fn default_url() -> String { DEFAULT.to_string() } /// Decode the configuration stored within the registry. /// /// This requires that the index has been at l...
onf
identifier_name
registry.rs
. Git sources can also have commits deleted through //! rebasings where registries cannot have their versions deleted. //! //! # The Index of a Registry //! //! One of the major difficulties with a registry is that hosting so many //! packages may quickly run into performance problems when dealing with //! dependency g...
let vers = &p[dep.name().len() + 1..]; s.version().to_string() == vers } _ => true, } }); summaries.query(dep) } } impl<'cfg> Source for RegistrySource<'cfg> { fn update(&mut self) -> CargoResult<()> { /...
Some(p) if p.starts_with(dep.name()) => {
random_line_split
transcribe.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 ...
TtToken(..) => LisUnconstrained, } } /// Return the next token from the TtReader. /// EFFECT: advances the reader's token field pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { // FIXME(pcwalton): Bad copy? let ret_val = TokenAndSpan { tok: r.cur_tok.clone(), sp: r.cur_span...
{ match *t { TtDelimited(_, ref delimed) => { delimed.tts.iter().fold(LisUnconstrained, |size, tt| { size + lockstep_iter_size(tt, r) }) }, TtSequence(_, ref seq) => { seq.tts.iter().fold(LisUnconstrained, |size, tt| { size ...
identifier_body
transcribe.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, other: LockstepIterSize) -> LockstepIterSize { match self { LisUnconstrained => other, LisContradiction(_) => self, LisConstraint(l_len, ref l_id) => match other { LisUnconstrained => self.clone(), LisContradiction(_) => other, ...
add
identifier_name
transcribe.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 => {} } } } loop { /* because it's easiest, this handles `TtDelimited` not starting with a `TtToken`, even though it won't happen */ let t = { let frame = r.stack.last().unwrap(); // FIXME(pcwalton): Bad copy. fr...
{ r.cur_tok = tk; /* repeat same span, I guess */ return ret_val; }
conditional_block
transcribe.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 ...
} } }
random_line_split
collada.rs
/// Implements the logic behind converting COLLADA documents to polygon-rs meshes. extern crate parse_collada as collada; use math::*; use polygon::geometry::mesh::*; pub use self::collada::{ AnyUri, ArrayElement, Collada, GeometricElement, Geometry, Node, PrimitiveElements, UriFragmen...
(from: collada::Error) -> Error { Error::ParseColladaError(from) } } pub type Result<T> = ::std::result::Result<T, Error>; pub enum VertexSemantic { Position, Normal, TexCoord, } /// Loads all resources from a COLLADA document and adds them to the resource manager. pub fn load_resources<T: In...
from
identifier_name
collada.rs
/// Implements the logic behind converting COLLADA documents to polygon-rs meshes. extern crate parse_collada as collada; use math::*; use polygon::geometry::mesh::*; pub use self::collada::{ AnyUri, ArrayElement, Collada, GeometricElement, Geometry, Node, PrimitiveElements, UriFragmen...
mesh_builder .set_indices(&*indices) .build() .map_err(|err| Error::BuildMeshError(err)) } struct IndexMapper<'a> { offset: usize, semantic: &'a str, data: &'a [f32], } // TODO: Where even should this live? It's generally useful but I'm only using it here right now. struct GroupBy<'a, ...
let indices: Vec<u32> = (0..vertex_count).collect();
random_line_split
collada.rs
/// Implements the logic behind converting COLLADA documents to polygon-rs meshes. extern crate parse_collada as collada; use math::*; use polygon::geometry::mesh::*; pub use self::collada::{ AnyUri, ArrayElement, Collada, GeometricElement, Geometry, Node, PrimitiveElements, UriFragmen...
}
{ if self.next == self.end { return None; } let next = self.next; self.next = unsafe { self.next.offset(self.stride as isize) }; Some(unsafe { ::std::slice::from_raw_parts(next, self.stride) }) }
identifier_body
mutref.rs
#[derive(Debug)] enum List { Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } use self::List::{Cons, Nil}; use std::rc::Rc; use std::cell::RefCell; pub fn run()
{ let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); println!("a before = {:?}", a); println!("b before = {:?}", b); println!("c before = ...
identifier_body
mutref.rs
#[derive(Debug)] enum
{ Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } use self::List::{Cons, Nil}; use std::rc::Rc; use std::cell::RefCell; pub fn run() { let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = Cons(Rc:...
List
identifier_name
mutref.rs
#[derive(Debug)] enum List { Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } use self::List::{Cons, Nil}; use std::rc::Rc; use std::cell::RefCell;
let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); println!("a before = {:?}", a); println!("b before = {:?}", b); println!("c before = {:...
pub fn run() {
random_line_split
sectionalize_pass.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 ...
() { let doc = test::mk_doc( ~"#[doc = \"\ # Header\n\ Body\"]\ mod a { }"); assert!(str::contains( doc.cratemod().mods()[0].item.sections[0].body, ~"Body")); } #[test] fn should_not_create_sections_from_indented_headers() { let doc = test::mk_doc...
should_create_section_bodies
identifier_name
sectionalize_pass.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 ...
}"); assert!(doc.cratemod().impls()[0].methods[0].sections.len() == 1u); } #[cfg(test)] pub mod test { use astsrv; use attr_pass; use doc; use extract; use sectionalize_pass::run; pub fn mk_doc(source: ~str) -> doc::Doc { do astsrv::from_str(copy source) |srv| { let do...
{ }
identifier_body
sectionalize_pass.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 ...
new_desc = match copy new_desc { Some(desc) => { Some(desc + ~"\n" + *line) } None => { Some(copy *line) } }; } } } } } if ...
body: section.body + ~"\n" + *line, .. section }); } None => {
random_line_split
cargo_test.rs
use std::ffi::{OsString, OsStr}; use std::path::Path; use ops::{self, ExecEngine, ProcessEngine, Compilation}; use util::{self, CargoResult, CargoTestError, ProcessError}; pub struct TestOptions<'a> { pub compile_opts: ops::CompileOptions<'a>, pub no_run: bool, pub no_fail_fast: bool, } #[allow(depreca...
(options: &TestOptions, test_args: &[String], compilation: &Compilation) -> CargoResult<Vec<ProcessError>> { let mut errors = Vec::new(); let config = options.compile_opts.config; let libs = compilation.to_doc_test.iter().map(|package| { (package, ...
run_doc_tests
identifier_name
cargo_test.rs
use std::ffi::{OsString, OsStr}; use std::path::Path; use ops::{self, ExecEngine, ProcessEngine, Compilation}; use util::{self, CargoResult, CargoTestError, ProcessError}; pub struct TestOptions<'a> { pub compile_opts: ops::CompileOptions<'a>, pub no_run: bool, pub no_fail_fast: bool, } #[allow(depreca...
for feat in compilation.features.iter() { p.arg("--cfg").arg(&format!("feature=\"{}\"", feat)); } for (_, libs) in compilation.libraries.iter() { for &(ref target, ref lib) in libs.iter() { // Note that we can *only* doctest rlib...
{ p.arg("--test-args").arg(&test_args.connect(" ")); }
conditional_block
cargo_test.rs
use std::ffi::{OsString, OsStr}; use std::path::Path; use ops::{self, ExecEngine, ProcessEngine, Compilation}; use util::{self, CargoResult, CargoTestError, ProcessError}; pub struct TestOptions<'a> { pub compile_opts: ops::CompileOptions<'a>, pub no_run: bool, pub no_fail_fast: bool, } #[allow(depreca...
/// Run the unit and integration tests of a project. fn run_unit_tests(options: &TestOptions, test_args: &[String], compilation: &Compilation) -> CargoResult<Vec<ProcessError>> { let config = options.compile_opts.config; let cwd = options.compile_opts.conf...
{ let mut compilation = try!(ops::compile(manifest_path, &options.compile_opts)); compilation.tests.sort_by(|a, b| { (a.0.package_id(), &a.1).cmp(&(b.0.package_id(), &b.1)) }); Ok(compilation) }
identifier_body
cargo_test.rs
use std::ffi::{OsString, OsStr}; use std::path::Path; use ops::{self, ExecEngine, ProcessEngine, Compilation}; use util::{self, CargoResult, CargoTestError, ProcessError}; pub struct TestOptions<'a> { pub compile_opts: ops::CompileOptions<'a>, pub no_run: bool, pub no_fail_fast: bool, } #[allow(depreca...
arg.push(rust_dep); p.arg("-L").arg(arg); } for native_dep in compilation.native_dirs.values() { p.arg("-L").arg(native_dep); } if test_args.len() > 0 { p.arg("--test-args").arg(&test_args.connect(" ")); ...
let mut arg = OsString::from("dependency=");
random_line_split
main.rs
// #![deny(warnings)] extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; #[macro_use] extern crate clap; use clap::{Arg, App}; use std::io::{self, Write}; use futures::{Future, Stream}; use tokio_core::reactor::Core; fn
() { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .arg(Arg::with_name("URL") .help("The URL to reach") .required(true) .index(1)) .arg(Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosit...
main
identifier_name
main.rs
// #![deny(warnings)] extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; #[macro_use] extern crate clap; use clap::{Arg, App}; use std::io::{self, Write}; use futures::{Future, Stream}; use tokio_core::reactor::Core; fn main() { let matches = App::new(crate_name!()) .version...
let mut core = Core::new().unwrap(); let handle = core.handle(); let client = hyper::Client::configure() .connector(hyper_tls::HttpsConnector::new(4, &handle).unwrap()) .build(&handle); let work = client.get(url).and_then(|res| { if matches.occurrences_of("v") > 0 { // TODO: 1.1 is hard coded for now ...
{ println!("This example only works with 'http' URLs."); return; }
conditional_block
main.rs
// #![deny(warnings)] extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; #[macro_use] extern crate clap; use clap::{Arg, App}; use std::io::{self, Write}; use futures::{Future, Stream}; use tokio_core::reactor::Core; fn main()
if! ( url.scheme() == Some("http") || url.scheme() == Some("https") ) { println!("This example only works with 'http' URLs."); return; } let mut core = Core::new().unwrap(); let handle = core.handle(); let client = hyper::Client::configure() .connector(hyper_tls::HttpsConnector::new(4, &handle).unwrap()) ...
{ let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .arg(Arg::with_name("URL") .help("The URL to reach") .required(true) .index(1)) .arg(Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity")...
identifier_body
main.rs
// #![deny(warnings)] extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; #[macro_use] extern crate clap; use clap::{Arg, App}; use std::io::{self, Write}; use futures::{Future, Stream}; use tokio_core::reactor::Core; fn main() { let matches = App::new(crate_name!()) .version...
if matches.occurrences_of("v") > 0 { println!("\n\nDone."); } }); core.run(work).unwrap(); }
}).map(|_| {
random_line_split
loopback.rs
//! Serial loopback via USART1 #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::serial::Event; use blue_pill::time::Hertz;...
// IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, { loopback: Task { interrupt: USART1, priority: P1, enabled: true, }, }); fn loopback(_task: USART1, ref prio: P1, ref thr: T1) { let usart1 = USART1....
{ let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let usart1 = USART1.access(prio, thr); let serial = Serial(&*usart1); serial.init(BAUD_RATE.invert(), afio, None, gpioa, rcc); serial.listen(Event::Rxne); }
identifier_body
loopback.rs
//! Serial loopback via USART1 #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0"
#[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::serial::Event; use blue_pill::time::Hertz; use blue_pill::{Serial, stm32f103xx}; use hal::prelude::*; use rtfm::{P0, P1, T0, T1, TMax}; use stm32f103xx::interrupt::USART1; // CONFIGURATION pub const BAUD_RATE: Hertz = Hertz(115_200); // RESOURCES periph...
random_line_split
loopback.rs
//! Serial loopback via USART1 #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::serial::Event; use blue_pill::time::Hertz;...
(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let usart1 = USART1.access(prio, thr); let serial = Serial(&*usart1); serial.init(BAUD_RATE.invert(), afio, None, gpioa, rcc); serial.listen(Event::Rxne)...
init
identifier_name
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), GlobalRef::Window(window), UIEventBinding::Wrap) } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, ...
new_uninitialized
identifier_name
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let event = UIEvent::new(global.as_window(), type_, bubbles, cancelable, init.view...
random_line_split
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
event.init_event(Atom::from(&*type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ return; }
conditional_block
uievent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, view: Option<&Window>, detail: i32) -> Root<UIEvent> { let ev = UIEvent::new_uninitialized(window); ev.InitUIEvent(type_, ...
{ reflect_dom_object(box UIEvent::new_inherited(), GlobalRef::Window(window), UIEventBinding::Wrap) }
identifier_body
gradient.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // external use crate::qt; // self use super::prelude::*; pub fn
( g: &usvg::LinearGradient, opacity: usvg::Opacity, bbox: Rect, brush: &mut qt::Brush, ) { let mut grad = qt::LinearGradient::new(g.x1, g.y1, g.x2, g.y2); prepare_base(&g.base, opacity, &mut grad); brush.set_linear_gradient(grad); apply_ts(&g.base, bbox, brush); } pub fn prepare_radial...
prepare_linear
identifier_name
gradient.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // external use crate::qt; // self use super::prelude::*; pub fn prepare_linear( g: &usvg::LinearGradient, ...
{ // We don't use `QGradient::setCoordinateMode` because it works incorrectly. // // See QTBUG-67995 if g.units == usvg::Units::ObjectBoundingBox { let mut ts = usvg::Transform::from_bbox(bbox); ts.append(&g.transform); brush.set_transform(ts.to_native()); } else { b...
identifier_body
gradient.rs
use crate::qt; // self use super::prelude::*; pub fn prepare_linear( g: &usvg::LinearGradient, opacity: usvg::Opacity, bbox: Rect, brush: &mut qt::Brush, ) { let mut grad = qt::LinearGradient::new(g.x1, g.y1, g.x2, g.y2); prepare_base(&g.base, opacity, &mut grad); brush.set_linear_gradie...
// 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/. // external
random_line_split
lint-for-crate.rs
// force-host #![feature(rustc_private)] #![feature(box_syntax)] extern crate rustc_driver; extern crate rustc_hir; #[macro_use] extern crate rustc_lint; #[macro_use] extern crate rustc_session; extern crate rustc_span; extern crate rustc_ast; use rustc_driver::plugin::Registry; use rustc_lint::{LateContext, LateLin...
(reg: &mut Registry) { reg.lint_store.register_lints(&[&CRATE_NOT_OKAY]); reg.lint_store.register_late_pass(|| box Pass); }
__rustc_plugin_registrar
identifier_name
lint-for-crate.rs
// force-host #![feature(rustc_private)] #![feature(box_syntax)] extern crate rustc_driver; extern crate rustc_hir;
extern crate rustc_session; extern crate rustc_span; extern crate rustc_ast; use rustc_driver::plugin::Registry; use rustc_lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass}; use rustc_span::symbol::Symbol; use rustc_ast::attr; declare_lint! { CRATE_NOT_OKAY, Warn, "crate not marked with ...
#[macro_use] extern crate rustc_lint; #[macro_use]
random_line_split
lint-for-crate.rs
// force-host #![feature(rustc_private)] #![feature(box_syntax)] extern crate rustc_driver; extern crate rustc_hir; #[macro_use] extern crate rustc_lint; #[macro_use] extern crate rustc_session; extern crate rustc_span; extern crate rustc_ast; use rustc_driver::plugin::Registry; use rustc_lint::{LateContext, LateLin...
} } #[no_mangle] fn __rustc_plugin_registrar(reg: &mut Registry) { reg.lint_store.register_lints(&[&CRATE_NOT_OKAY]); reg.lint_store.register_late_pass(|| box Pass); }
{ cx.lint(CRATE_NOT_OKAY, |lint| { lint.build("crate is not marked with #![crate_okay]") .set_span(krate.module().inner) .emit() }); }
conditional_block
lint-for-crate.rs
// force-host #![feature(rustc_private)] #![feature(box_syntax)] extern crate rustc_driver; extern crate rustc_hir; #[macro_use] extern crate rustc_lint; #[macro_use] extern crate rustc_session; extern crate rustc_span; extern crate rustc_ast; use rustc_driver::plugin::Registry; use rustc_lint::{LateContext, LateLin...
{ reg.lint_store.register_lints(&[&CRATE_NOT_OKAY]); reg.lint_store.register_late_pass(|| box Pass); }
identifier_body
ascribe_user_type.rs
// Copyright 2016 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 perform_query( tcx: TyCtxt<'_, 'gcx, 'tcx>, canonicalized: Canonicalized<'gcx, ParamEnvAnd<'tcx, Self>>, ) -> Fallible<CanonicalizedQueryResponse<'gcx, ()>> { tcx.type_op_ascribe_user_type(canonicalized) } fn shrink_to_tcx_lifetime( v: &'a CanonicalizedQueryResponse...
{ None }
identifier_body
ascribe_user_type.rs
// Copyright 2016 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 ...
( _tcx: TyCtxt<'_, 'gcx, 'tcx>, _key: &ParamEnvAnd<'tcx, Self>, ) -> Option<Self::QueryResponse> { None } fn perform_query( tcx: TyCtxt<'_, 'gcx, 'tcx>, canonicalized: Canonicalized<'gcx, ParamEnvAnd<'tcx, Self>>, ) -> Fallible<CanonicalizedQueryResponse<'gcx, ()...
try_fast_path
identifier_name
ascribe_user_type.rs
// Copyright 2016 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 ...
} } BraceStructLiftImpl! { impl<'a, 'tcx> Lift<'tcx> for AscribeUserType<'a> { type Lifted = AscribeUserType<'tcx>; mir_ty, variance, def_id, user_substs, projs } } impl_stable_hash_for! { struct AscribeUserType<'tcx> { mir_ty, variance, def_id, user_substs, projs } }
random_line_split
coerce-unify.rs
// run-pass // Check that coercions can unify if-else, match arms and array elements. // Try to construct if-else chains, matches and arrays out of given expressions. macro_rules! check { ($last:expr $(, $rest:expr)+) => { // Last expression comes first because of whacky ifs and matches. let _ = $(...
{ check3!(foo, bar, foo as fn()); check3!(size_of::<u8>, size_of::<u16>, size_of::<usize> as fn() -> usize); let s = String::from("bar"); check2!("foo", &s); let a = [1, 2, 3]; let v = vec![1, 2, 3]; check2!(&a[..], &v); // Make sure in-array coercion still works. let _ = [("a", D...
identifier_body
coerce-unify.rs
// run-pass // Check that coercions can unify if-else, match arms and array elements. // Try to construct if-else chains, matches and arrays out of given expressions. macro_rules! check { ($last:expr $(, $rest:expr)+) => { // Last expression comes first because of whacky ifs and matches. let _ = $(...
() {} pub fn main() { check3!(foo, bar, foo as fn()); check3!(size_of::<u8>, size_of::<u16>, size_of::<usize> as fn() -> usize); let s = String::from("bar"); check2!("foo", &s); let a = [1, 2, 3]; let v = vec![1, 2, 3]; check2!(&a[..], &v); // Make sure in-array coercion still works....
bar
identifier_name
coerce-unify.rs
// run-pass // Check that coercions can unify if-else, match arms and array elements. // Try to construct if-else chains, matches and arrays out of given expressions. macro_rules! check { ($last:expr $(, $rest:expr)+) => { // Last expression comes first because of whacky ifs and matches. let _ = $(...
// Check all non-uniform cases of 2 and 3 expressions of 3 types. macro_rules! check3 { ($a:expr, $b:expr, $c:expr) => { // Delegate to check2 for cases where a type repeats. check2!($a, $b); check2!($b, $c); check2!($a, $c); // Check the remaining cases, i.e., permutations...
random_line_split
basic-types-mut-globals.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(); unsafe { B = true; I = 2; C = 'f'; I8 = 78; I16 = -26; I32 = -12; I64 = -54; U = 5; U8 = 20; U16 = 32; U32 = 16; U64 = 128; F32 = 5.75; F64 = 9.25; } _zzz(); } fn _zzz() {()}
main
identifier_name
basic-types-mut-globals.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
linear_transformation.rs
use crate::{Point, Transformation, Vector}; #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)] pub struct LinearTransformation { pub x: Vector, pub y: Vector, } impl LinearTransformation { pub fn new(x: Vector, y: Vector) -> LinearTransformation { LinearTransformation { x, y } } pub fn i...
(v: Vector) -> LinearTransformation { LinearTransformation::new(Vector::new(v.x, 0.0), Vector::new(0.0, v.y)) } pub fn uniform_scaling(k: f32) -> LinearTransformation { LinearTransformation::scaling(Vector::new(k, k)) } pub fn scale(self, v: Vector) -> LinearTransformation { Li...
scaling
identifier_name
linear_transformation.rs
use crate::{Point, Transformation, Vector}; #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)] pub struct LinearTransformation { pub x: Vector, pub y: Vector, } impl LinearTransformation { pub fn new(x: Vector, y: Vector) -> LinearTransformation { LinearTransformation { x, y } } pub fn i...
LinearTransformation::new( self.transform_vector(other.x), self.transform_vector(other.y), ) } } impl Transformation for LinearTransformation { fn transform_point(&self, p: Point) -> Point { (self.x * p.x + self.y * p.y).to_point() } fn transform_vector(...
pub fn compose(self, other: LinearTransformation) -> LinearTransformation {
random_line_split
linear_transformation.rs
use crate::{Point, Transformation, Vector}; #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)] pub struct LinearTransformation { pub x: Vector, pub y: Vector, } impl LinearTransformation { pub fn new(x: Vector, y: Vector) -> LinearTransformation { LinearTransformation { x, y } } pub fn i...
pub fn scaling(v: Vector) -> LinearTransformation { LinearTransformation::new(Vector::new(v.x, 0.0), Vector::new(0.0, v.y)) } pub fn uniform_scaling(k: f32) -> LinearTransformation { LinearTransformation::scaling(Vector::new(k, k)) } pub fn scale(self, v: Vector) -> LinearTransfo...
{ LinearTransformation::new(Vector::new(1.0, 0.0), Vector::new(0.0, 1.0)) }
identifier_body
ball_ball.rs
use std::marker::PhantomData; use na::Translate; use na; use math::{Scalar, Point, Vect}; use entities::shape::Ball; use entities::inspection::Repr; use queries::geometry::Contact; use queries::geometry::contacts_internal; use narrow_phase::{CollisionDetector, CollisionDispatcher}; /// Collision detector between two ...
(&self) -> usize { match self.contact { None => 0, Some(_) => 1 } } #[inline] fn colls(&self, out_colls: &mut Vec<Contact<P>>) { match self.contact { Some(ref c) => out_colls.push(c.clone()), None => () } } }
num_colls
identifier_name
ball_ball.rs
use std::marker::PhantomData; use na::Translate; use na; use math::{Scalar, Point, Vect}; use entities::shape::Ball; use entities::inspection::Repr; use queries::geometry::Contact; use queries::geometry::contacts_internal; use narrow_phase::{CollisionDetector, CollisionDispatcher}; /// Collision detector between two ...
contact: None, mat_type: PhantomData } } } impl<P, M> CollisionDetector<P, M> for BallBall<P, M> where P: Point, M:'static + Translate<P> { fn update(&mut self, _: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, ...
#[inline] pub fn new(prediction: <P::Vect as Vect>::Scalar) -> BallBall<P, M> { BallBall { prediction: prediction,
random_line_split
ball_ball.rs
use std::marker::PhantomData; use na::Translate; use na; use math::{Scalar, Point, Vect}; use entities::shape::Ball; use entities::inspection::Repr; use queries::geometry::Contact; use queries::geometry::contacts_internal; use narrow_phase::{CollisionDetector, CollisionDispatcher}; /// Collision detector between two ...
#[inline] fn colls(&self, out_colls: &mut Vec<Contact<P>>) { match self.contact { Some(ref c) => out_colls.push(c.clone()), None => () } } }
{ match self.contact { None => 0, Some(_) => 1 } }
identifier_body
lib.rs
// Copyright (c) 2016 Herman J. Radtke III <herman@hermanradtke.com> // // This file is part of carp-rs. // // carp-rs is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License,...
extern crate log; #[cfg(unix)] extern crate nix; extern crate rand; extern crate pcap; extern crate crypto; extern crate byteorder; use std::result; pub mod net; mod error; mod node; pub mod advert; pub mod ip_carp; pub mod config; pub mod carp; pub type Result<T> = result::Result<T, error::Error>;
random_line_split
intrinsic.rs
use super::BackendTypes; use crate::mir::operand::OperandRef; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; use rustc_target::abi::call::FnAbi;
pub trait IntrinsicCallMethods<'tcx>: BackendTypes { /// Remember to add all intrinsics here, in `compiler/rustc_typeck/src/check/mod.rs`, /// and in `library/core/src/intrinsics.rs`; if you need access to any LLVM intrinsics, /// add them to `compiler/rustc_codegen_llvm/src/context.rs`. fn codegen_intr...
random_line_split
glyph.rs
_cmp(&self, other: &DetailedGlyphRecord) -> Option<Ordering> { self.entry_offset.partial_cmp(&other.entry_offset) } } impl Ord for DetailedGlyphRecord { fn cmp(&self, other: &DetailedGlyphRecord) -> Ordering { self.entry_offset.cmp(&other.entry_offset) } } // Manages the lookup table for d...
{ spaces += 1 }
conditional_block
glyph.rs
) == id } fn is_simple_advance(advance: Au) -> bool { advance >= Au(0) && { let unsigned_au = advance.0 as u32; (unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsigned_au } } pub type DetailedGlyphCount = u16; // Getters and setters for GlyphEntry. Setter methods are functiona...
assert!(main_detail_offset + (detail_offset as usize) < self.detail_buffer.len()); &self.detail_buffer[main_detail_offset + (detail_offset as usize)] } fn ensure_sorted(&mut self) { if self.lookup_is_sorted { return; } // Sorting a unique vector is surprisin...
let i = self .detail_lookup .binary_search(&key) .expect("Invalid index not found in detailed glyph lookup table!"); let main_detail_offset = self.detail_lookup[i].detail_offset;
random_line_split
glyph.rs
fn is_initial(&self) -> bool { *self == GlyphEntry::initial() } } /// The id of a particular glyph within a font pub type GlyphId = u32; // TODO: make this more type-safe. const FLAG_CHAR_IS_SPACE: u32 = 0x40000000; #[cfg(feature = "unstable")] #[cfg(any(target_feature = "sse2", target_feature = "n...
{ assert!(glyph_count <= u16::MAX as usize); debug!( "creating complex glyph entry: starts_cluster={}, starts_ligature={}, \ glyph_count={}", starts_cluster, starts_ligature, glyph_count ); GlyphEntry::new(glyph_count as u32) }
identifier_body
glyph.rs
)] struct DetailedGlyph { id: GlyphId, // glyph's advance, in the text's direction (LTR or RTL) advance: Au, // glyph's offset from the font's em-box (from top-left) offset: Point2D<Au>, } impl DetailedGlyph { fn new(id: GlyphId, advance: Au, offset: Point2D<Au>) -> DetailedGlyph { Deta...
transmute_entry_buffer_to_u32_buffer
identifier_name
string.rs
// Copyright 2015-2017 Daniel P. Clark & array_tool Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or dist...
se { use string::SubstMarks; return t.subst_marks(mrkrs.to_vec(), "\n") } }, } }, Some(x) => { wordwrap(t, chunk, offset+x+1, mrkrs) }, } }; wordwrap(self, width+1, 0, &mut markers) } }
/ String may continue wordwrap(t, chunk, offset+1, mrkrs) // Recurse + 1 until next space } el
conditional_block
string.rs
// Copyright 2015-2017 Daniel P. Clark & array_tool Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or dist...
} } } impl<'a> Iterator for GraphemeBytesIter<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<&'a [u8]> { let mut result: Option<&[u8]> = None; let mut idx = self.offset; for _ in self.offset..self.source.len() { idx += 1; if self.offset < self.source.len() { if self....
GraphemeBytesIter { source: source, offset: 0, grapheme_count: 0,
random_line_split
string.rs
// Copyright 2015-2017 Daniel P. Clark & array_tool Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or dist...
elf, marks: Vec<usize>, chr: &'static str) -> String { let mut output = Vec::<u8>::with_capacity(self.len()); let mut count = 0; let mut last = 0; for i in 0..self.len() { let idx = i + 1; if self.is_char_boundary(idx) { if marks.contains(&count) { count += 1; las...
st_marks(&s
identifier_name
string.rs
// Copyright 2015-2017 Daniel P. Clark & array_tool Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or dist...
} }; wordwrap(t, chunk, offset+eows+1, mrkrs) }, None => { if offset+chunk < t.len() { // String may continue wordwrap(t, chunk, offset+1, mrkrs) // Recurse + 1 until next space } else { use ...
match t[offset..*vec![offset+chunk,t.len()].iter().min().unwrap()].rfind("\n") { None => { match t[offset..*vec![offset+chunk,t.len()].iter().min().unwrap()].rfind(" ") { Some(x) => { let mut eows = x; // end of white space if offset+chunk < t.len() { // ch...
identifier_body
issue-4448.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 ...
() { let (tx, rx) = channel::<&'static str>(); let t = thread::spawn(move|| { assert_eq!(rx.recv().unwrap(), "hello, world"); }); tx.send("hello, world").unwrap(); t.join().ok().unwrap(); }
main
identifier_name
issue-4448.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 ...
{ let (tx, rx) = channel::<&'static str>(); let t = thread::spawn(move|| { assert_eq!(rx.recv().unwrap(), "hello, world"); }); tx.send("hello, world").unwrap(); t.join().ok().unwrap(); }
identifier_body
prelude.rs
// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed /...
//! ``` //! use rand::prelude::*; //! # let mut r = StdRng::from_rng(thread_rng()).unwrap(); //! # let _: f32 = r.gen(); //! ``` #[doc(no_inline)] pub use crate::distributions::Distribution; #[cfg(feature = "small_rng")] #[doc(no_inline)] pub use crate::rngs::SmallRng; #[cfg(feature = "std_rng")] #[doc(no_inline)] pub...
//! common items. Unlike the standard prelude, the contents of this module must //! be imported manually: //!
random_line_split
test_create_embed.rs
#[macro_use] extern crate serde_json; extern crate serenity; use serde_json::Value; use serenity::model::{Embed, EmbedField, EmbedImage}; use serenity::utils::builder::CreateEmbed; use serenity::utils::Colour; #[test] fn
() { let embed = Embed { author: None, colour: Colour::new(0xFF0011), description: Some("This is a test description".to_owned()), fields: vec![ EmbedField { inline: false, name: "a".to_owned(), value: "b".to_owned(), ...
test_from_embed
identifier_name
test_create_embed.rs
#[macro_use] extern crate serde_json; extern crate serenity; use serde_json::Value; use serenity::model::{Embed, EmbedField, EmbedImage}; use serenity::utils::builder::CreateEmbed; use serenity::utils::Colour; #[test] fn test_from_embed() { let embed = Embed { author: None, colour: Colour::new(0xF...
}
random_line_split
test_create_embed.rs
#[macro_use] extern crate serde_json; extern crate serenity; use serde_json::Value; use serenity::model::{Embed, EmbedField, EmbedImage}; use serenity::utils::builder::CreateEmbed; use serenity::utils::Colour; #[test] fn test_from_embed()
url: "https://i.imgur.com/XfWpfCV.gif".to_owned(), width: 224, }), kind: "rich".to_owned(), provider: None, thumbnail: None, timestamp: None, title: Some("hakase".to_owned()), url: Some("https://i.imgur.com/XfWpfCV.gif".to_owned()), ...
{ let embed = Embed { author: None, colour: Colour::new(0xFF0011), description: Some("This is a test description".to_owned()), fields: vec![ EmbedField { inline: false, name: "a".to_owned(), value: "b".to_owned(), ...
identifier_body
mod.rs
#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc...
(&self, latch_state: LatchState) { // Addresses greater than 0x3fff are mirrored down match latch_state { LatchState::FirstWrite(val) => { // t:..FEDCBA........ = d:..FEDCBA // t:.X.............. = 0 let t = self.t.get() & 0b1000_0000_1111_1111...
write_ppu_addr
identifier_name
mod.rs
#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc...
IncrementAmount::One => self.address.set(self.address.get() + 1), IncrementAmount::ThirtyTwo => self.address.set(self.address.get() + 32), } val } fn ppu_data<C: Cart>(&self, cart: &C) -> u8 { let addr = self.address.get(); let val = self.read(addr, cart)...
} fn read_ppu_data<C: Cart>(&self, inc_amount: IncrementAmount, cart: &C) -> u8 { let val = self.ppu_data(cart); match inc_amount {
random_line_split
mod.rs
#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc...
fn fine_y_increment(&self) { let v = self.address.get(); let v = if v & 0x7000!= 0x7000 { // if fine Y < 7, increment fine Y v + 0x1000 } else { // if fine Y = 0... let v = v &!0x7000; // let y = coarse Y let mut y =...
{ let v = self.address.get(); // The coarse X component of v needs to be incremented when the next tile is reached. Bits // 0-4 are incremented, with overflow toggling bit 10. This means that bits 0-4 count from 0 // to 31 across a single nametable, and bit 10 selects the current nameta...
identifier_body
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
(&self) -> String { format!("{}:{}", self.0.to_string(), self.0) } } impl FromStr for ExternalReference { type Err = ConversionError; fn from_str(raw: &str) -> Result<ExternalReference, Self::Err> { let parts: Vec<&str> = raw.split(":").collect(); if parts.len() == 1 { ...
to_string
identifier_name
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
pub fn to_string(&self) -> String { format!("{}:{}", self.0.to_string(), self.0) } } impl FromStr for ExternalReference { type Err = ConversionError; fn from_str(raw: &str) -> Result<ExternalReference, Self::Err> { let parts: Vec<&str> = raw.split(":").collect(); if parts.len...
{ &self.1 }
identifier_body
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
if parts.len() > 2 { return Err(Self::Err::InvalidFormat(raw.to_string())); } let ref_type: reference_type::ReferenceType = parts[0].parse()?; Ok(ExternalReference(ref_type, parts[1].to_string())) } } impl From<ExternalReference> for String { fn from(raw: ExternalR...
return Err(Self::Err::MissingPrefix(raw.to_string())); }
random_line_split
external_reference.rs
use std::str::FromStr; use thiserror::Error; use crate::publications::reference_type; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ExternalReference(reference_type::ReferenceType, String); #[derive(Error, Debug)] pub enum ConversionError { #[error("No prefix for the reference id: `{0}`")] Missing...
let ref_type: reference_type::ReferenceType = parts[0].parse()?; Ok(ExternalReference(ref_type, parts[1].to_string())) } } impl From<ExternalReference> for String { fn from(raw: ExternalReference) -> String { format!("{}:{}", raw.0, raw.1) } }
{ return Err(Self::Err::InvalidFormat(raw.to_string())); }
conditional_block
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
for (header, packages) in tests { for (package, version, component) in packages { printer(" ", &package, false, &version, &component, &header); } } if!benches.is_empty() { println!("\nBENCHMARKS\n"); } for (header, packages) in benches { for (package,...
{ println!("\nTESTS\n"); }
conditional_block
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
fn is_reg_match(s: &str, r: &Regex) -> bool { r.captures(s).is_some() }
{ (*h.entry(header).or_insert_with(Vec::new)).push(( package.to_owned(), version.to_owned(), component.to_owned(), )); }
identifier_body
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
} for (header, packages) in benches { for (package, version, component) in packages { printer(" ", &package, false, &version, &component, &header); } } } fn printer( indent: &str, package: &str, lt0: bool, version: &str, component: &str, header: &Heade...
} if !benches.is_empty() { println!("\nBENCHMARKS\n");
random_line_split
main.rs
use std::collections::{HashMap}; use std::io::{self, BufRead}; use lazy_regex::regex; use regex::Regex; type H = HashMap<Header, Vec<(String, String, String)>>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Header { Versioned { package: String, version: String }, Missing { package: String }, } fn main()...
(h: &mut H, header: Header, package: &str, version: &str, component: &str) { (*h.entry(header).or_insert_with(Vec::new)).push(( package.to_owned(), version.to_owned(), component.to_owned(), )); } fn is_reg_match(s: &str, r: &Regex) -> bool { r.captures(s).is_some() }
insert
identifier_name
issue-23485.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 ...
{ value: i32 } impl Iterator for Counter { type Item = Token; fn next(&mut self) -> Option<Token> { let x = self.value; self.value += 1; Some(Token { value: x }) } } fn main() { let mut x: Box<Iterator<Item=Token>> = Box::new(Counter { value: 22 }); assert_eq!(x.next(...
Token
identifier_name
issue-23485.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 mut x: Box<Iterator<Item=Token>> = Box::new(Counter { value: 22 }); assert_eq!(x.next().unwrap().value, 22); }
{ let x = self.value; self.value += 1; Some(Token { value: x }) }
identifier_body
issue-23485.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
self.value += 1; Some(Token { value: x }) } } fn main() { let mut x: Box<Iterator<Item=Token>> = Box::new(Counter { value: 22 }); assert_eq!(x.next().unwrap().value, 22); }
type Item = Token; fn next(&mut self) -> Option<Token> { let x = self.value;
random_line_split
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self { Queue { vec: Vec::new() } }
/// Push element to queue pub fn push(&mut self, value: T) { self.vec.push(value); } /// Pop the last element pub fn pop(&mut self) -> Option<T> { if!self.vec.is_empty() { Some(self.vec.remove(0)) } else { None } } /// Get the length ...
random_line_split
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self { Queue { vec: Vec::new() } } /// Push element to queue pub fn
(&mut self, value: T) { self.vec.push(value); } /// Pop the last element pub fn pop(&mut self) -> Option<T> { if!self.vec.is_empty() { Some(self.vec.remove(0)) } else { None } } /// Get the length of the queue pub fn len(&self) -> usize {...
push
identifier_name
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self { Queue { vec: Vec::new() } } /// Push element to queue pub fn push(&mut self, value: T) { self.vec.p...
} /// Get the length of the queue pub fn len(&self) -> usize { self.vec.len() } } impl<T> Clone for Queue<T> where T: Clone { fn clone(&self) -> Self { Queue { vec: self.vec.clone() } } }
{ None }
conditional_block
queue.rs
use collections::vec::Vec; /// A FIFO Queue pub struct Queue<T> { /// The queue as a vector pub vec: Vec<T>, } impl<T> Queue<T> { /// Create new queue pub fn new() -> Self
/// Push element to queue pub fn push(&mut self, value: T) { self.vec.push(value); } /// Pop the last element pub fn pop(&mut self) -> Option<T> { if!self.vec.is_empty() { Some(self.vec.remove(0)) } else { None } } /// Get the lengt...
{ Queue { vec: Vec::new() } }
identifier_body
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
raft_db.add_server(*id, info.get(id).cloned().unwrap().addr).unwrap(); } Cluster { servers: servers, cluster: info.clone(), client: raft_db } } fn add_server(&mut self, id: u64, addr: SocketAddr) { if self.cluster.contains_key(&id) { println!("Server {} is alrea...
{ continue; }
conditional_block
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
// TODO (sydli): make this function less shit fn process_command(&mut self, words: Vec<String>) -> bool { if words.len() == 0 { return true; } let ref cmd = words[0]; if *cmd == String::from("get") { if words.len() <= 1 { return false; } words.get(1).ma...
{ json::encode(&Put {key:key, value:value}) .map_err(serialize_error) .and_then(|buffer| self.raft.command(&buffer.as_bytes())) }
identifier_body
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
<T: Debug>(error: T) -> RaftError { RaftError::ClientError( format!("Couldn't serialize object. Error: {:?}", error)) } fn deserialize_error <T: Debug>(error: T) -> RaftError { RaftError::ClientError( format!("Couldn't deserialize buffer. Error: {:?}", error)) } fn key_error(k...
serialize_error
identifier_name
hashmap.rs
#[macro_use] extern crate log; extern crate rusty_raft; extern crate rand; extern crate rustc_serialize; extern crate env_logger; use rand::{thread_rng, Rng}; use rusty_raft::server::{start_server, ServerHandle}; use rusty_raft::client::{RaftConnection}; use rusty_raft::client::state_machine::{ StateMachine, RaftS...
} impl StateMachine for RaftHashMap { fn command (&mut self, buffer: &[u8]) ->Result<(), RaftError> { str::from_utf8(buffer) .map_err(deserialize_error) .and_then(|string| json::decode(&string) .map_err(deserialize_error)) .map(|put: Put| ...
fn key_error(key: &String) -> RaftError { RaftError::ClientError(format!("Couldn't find key {}", key))
random_line_split
manifest.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
// Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along w...
// (at your option) any later version.
random_line_split
manifest.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....
(manifest: &Manifest) -> Result<String, String> { serde_json::to_string_pretty(manifest).map_err(|e| format!("{:?}", e)) }
serialize_manifest
identifier_name
manifest.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....
pub fn serialize_manifest(manifest: &Manifest) -> Result<String, String> { serde_json::to_string_pretty(manifest).map_err(|e| format!("{:?}", e)) }
{ serde_json::from_str::<Manifest>(&manifest).map_err(|e| format!("{:?}", e)) // TODO [todr] Manifest validation (especialy: id (used as path)) }
identifier_body
graphviz.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<'a, 'tcx> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for DataflowLabeller<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.inner.nodes() } fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.inner.edges() } fn source(&self, edge: &Edge<'a>) -> Node<'a> { self.inner.source(edge) } fn ta...
{ self.inner.edge_label(e) }
identifier_body
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String { let dfcx = &self.analysis_data.move_data.dfcx_assign; let assign_index_to_path = |assign_index| { let move_data = &self.analysis_data.move_data.move_data; let assignments = move_data.var_assignments.borrow(); let a...
dataflow_assigns_for
identifier_name
graphviz.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 dataflow_for_variant(&self, e: EntryOrExit, n: &Node, v: Variant) -> String { let cfgidx = n.val0(); match v { Loans => self.dataflow_loans_for(e, cfgidx), Moves => self.dataflow_moves_for(e, cfgidx), Assigns => self.dataflow_assigns_for(e, cfgidx), ...
} sets }
random_line_split
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
else { Err(Error::new(ErrorKind::InvalidData, "invalid ELF header")) } } /// Extracts the magic number from the PE header in a shared library. fn parse_pe_header(path: &Path) -> io::Result<u16> { let mut file = File::open(path)?; // Extract the header offset. let mut buffer = [0; 4]; let ...
{ Ok(buffer[4]) }
conditional_block
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
/// Checks that a `libclang` shared library matches the target platform. fn validate_library(path: &Path) -> Result<(), String> { if cfg!(any(target_os = "linux", target_os = "freebsd")) { let class = parse_elf_header(path).map_err(|e| e.to_string())?; if cfg!(target_pointer_width = "32") && class!...
Ok(u16::from_le_bytes(buffer)) }
random_line_split
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
(filename: &str) -> Vec<u32> { let version = if let Some(version) = filename.strip_prefix("libclang.so.") { version } else if filename.starts_with("libclang-") { &filename[9..filename.len() - 3] } else { return vec![]; }; version.split('.').map(|s| s.parse().unwrap_or(0)).co...
parse_version
identifier_name
dynamic.rs
// SPDX-License-Identifier: Apache-2.0 use std::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; //================================================ // Validation //================================================ /// Extracts the...
} } if cfg!(any( target_os = "freebsd", target_os = "haiku", target_os = "netbsd", target_os = "openbsd", )) { // Some BSD distributions don't create a `libclang.so` symlink either, // but use a different naming scheme for versioned files (e.g., ...
{ let mut files = vec![format!( "{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX )]; if cfg!(target_os = "linux") { // Some Linux distributions don't create a `libclang.so` symlink, so we // need to look for versioned files (e.g., `libclang-3.9.so`). ...
identifier_body