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
traveling_salesman_problem.rs
use graph::Graph; use adjacency_matrix::AdjacencyMatrix; pub fn traveling_salesman_problem(g: &Graph) -> Vec<usize>
// construct_tour incrementally inserts the furthest vertex to create a tour. fn construct_tour(m: &AdjacencyMatrix) -> Vec<usize> { let mut tour = vec![0]; while tour.len() < m.size() { let (x, index) = furthest_vertex(&tour, m); tour.insert(index, x); } tour } // furthest_vertex ret...
{ if g.vertex_count == 0 { return vec![]; } let m = AdjacencyMatrix::from_graph(&g); optimize_tour(&construct_tour(&m), &m) }
identifier_body
rpath.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// be moved as long as the crates they link against don't move. let abs_rpaths = get_absolute_rpaths(libs); // And a final backup rpath to the global library location. let fallback_rpaths = ~[get_install_prefix_rpath(target_triple)]; fn log_rpaths(desc: &str, rpaths: &[~str]) { debug2!("{}...
let rel_rpaths = get_rpaths_relative_to_output(os, output, libs); // Make backup absolute paths to the libraries. Binaries can
random_line_split
rpath.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[test] #[cfg(target_os = "macos")] fn test_rpath_relative() { let o = session::OsMacos; let res = get_rpath_relative_to_output(o, &Path::new("bin/rustc"), &Path::new("lib/libstd.so")); as...
{ let o = session::OsFreebsd; let res = get_rpath_relative_to_output(o, &Path::new("bin/rustc"), &Path::new("lib/libstd.so")); assert_eq!(res.as_slice(), "$ORIGIN/../lib"); }
identifier_body
rpath.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let o = session::OsLinux; let res = get_rpath_relative_to_output(o, &Path::new("bin/rustc"), &Path::new("lib/libstd.so")); assert_eq!(res.as_slice(), "$ORIGIN/../lib"); } #[test] #[cfg(target_os = "freebsd")] fn test_rpath_relative() { let o = session::OsFreeb...
test_rpath_relative
identifier_name
masses.rs
use std::ops::{Add, Sub, Mul, Div}; use std::fmt; use units::ConvertibleUnit; use units::UnitValue; /// Units used to denote masses in the game #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub enum MU { mg, g, kg, tons, ktons, mtons, earth_mass, jupiter_mass, sun_...
(&self) -> (f64, MU) { match *self { MU::mg => (0.001, MU::g), MU::g => (0.001, MU::kg), MU::kg => (0.001, MU::tons), MU::tons => (0.001, MU::ktons), MU::ktons => (0.001, MU::mtons), MU::mtons ...
up
identifier_name
masses.rs
use std::ops::{Add, Sub, Mul, Div}; use std::fmt; use units::ConvertibleUnit; use units::UnitValue; /// Units used to denote masses in the game
tons, ktons, mtons, earth_mass, jupiter_mass, sun_mass } impl fmt::Display for MU { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let u_str = match *self { MU::mg => "Milli Gram", MU::g => "Gram", MU::kg =>...
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub enum MU { mg, g, kg,
random_line_split
dijkstra.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, IntoEdges, VisitMap, Visitable}; use crate::algo::Measure; use crate::scored::MinScored; /// \[Generic\] Dijkstra's shortest path algorithm. /// /// Compute the len...
/// /// graph.extend_with_edges(&[ /// (a, b), /// (b, c), /// (c, d), /// (d, a), /// (e, f), /// (b, e), /// (f, g), /// (g, h), /// (h, e) /// ]); /// // a ----> b ----> e ----> f /// // ^ | ^ | /// // | v | v /// // d <---- c h <---- g //...
/// let g = graph.add_node(()); /// let h = graph.add_node(()); /// // z will be in another connected component /// let z = graph.add_node(());
random_line_split
dijkstra.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, IntoEdges, VisitMap, Visitable}; use crate::algo::Measure; use crate::scored::MinScored; /// \[Generic\] Dijkstra's shortest path algorithm. /// /// Compute the len...
<G, F, K>( graph: G, start: G::NodeId, goal: Option<G::NodeId>, mut edge_cost: F, ) -> HashMap<G::NodeId, K> where G: IntoEdges + Visitable, G::NodeId: Eq + Hash, F: FnMut(G::EdgeRef) -> K, K: Measure + Copy, { let mut visited = graph.visit_map(); let mut scores = HashMap::new();...
dijkstra
identifier_name
dijkstra.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, IntoEdges, VisitMap, Visitable}; use crate::algo::Measure; use crate::scored::MinScored; /// \[Generic\] Dijkstra's shortest path algorithm. /// /// Compute the len...
if goal.as_ref() == Some(&node) { break; } for edge in graph.edges(node) { let next = edge.target(); if visited.is_visited(&next) { continue; } let next_score = node_score + edge_cost(edge); match scores.ent...
{ continue; }
conditional_block
dijkstra.rs
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{BinaryHeap, HashMap}; use std::hash::Hash; use super::visit::{EdgeRef, IntoEdges, VisitMap, Visitable}; use crate::algo::Measure; use crate::scored::MinScored; /// \[Generic\] Dijkstra's shortest path algorithm. /// /// Compute the len...
let next_score = node_score + edge_cost(edge); match scores.entry(next) { Occupied(ent) => { if next_score < *ent.get() { *ent.into_mut() = next_score; visit_next.push(MinScored(next_score, next)); ...
{ let mut visited = graph.visit_map(); let mut scores = HashMap::new(); //let mut predecessor = HashMap::new(); let mut visit_next = BinaryHeap::new(); let zero_score = K::default(); scores.insert(start, zero_score); visit_next.push(MinScored(zero_score, start)); while let Some(MinScored...
identifier_body
dst-dtor-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; impl Drop for Foo { fn drop(&mut self) { unsafe { DROP_RAN += 1; } } } struct Fat<T:?Sized> { f: T } pub fn main() { { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _x: Box<Fat<[Foo]>> = Box::<Fat<[Foo; 3]>>::new(Fat { f: [Foo, Foo, Foo] }); ...
Foo
identifier_name
dst-dtor-2.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 ...
{ { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _x: Box<Fat<[Foo]>> = Box::<Fat<[Foo; 3]>>::new(Fat { f: [Foo, Foo, Foo] }); } unsafe { assert!(DROP_RAN == 3); } }
identifier_body
dst-dtor-2.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. static mut DROP_...
random_line_split
breaks.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
(()); impl Metric<BreaksInfo> for BreaksBaseMetric { fn measure(_: &BreaksInfo, len: usize) -> usize { len } fn to_base_units(_: &BreaksLeaf, in_measured_units: usize) -> usize { in_measured_units } fn from_base_units(_: &BreaksLeaf, in_base_units: usize) -> usize { in_bas...
BreaksBaseMetric
identifier_name
breaks.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
pub fn build(mut self) -> Breaks { self.b.push(Node::from_leaf(self.leaf)); self.b.build() } } #[cfg(test)] mod tests { use breaks::{BreaksLeaf, BreaksInfo, BreaksMetric, BreakBuilder}; use tree::{Node, Cursor}; use interval::Interval; fn gen(n: usize) -> Node<BreaksInfo> { ...
{ self.leaf.len += len; }
identifier_body
breaks.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
fn next(l: &BreaksLeaf, offset: usize) -> Option<usize> { BreaksMetric::next(l, offset) } fn can_fragment() -> bool { true } } // Additional functions specific to breaks impl Breaks { // a length with no break, useful in edit operations; for // other use cases, use the builder. pub f...
fn prev(l: &BreaksLeaf, offset: usize) -> Option<usize> { BreaksMetric::prev(l, offset) }
random_line_split
breaks.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
} None } fn can_fragment() -> bool { true } } #[derive(Copy, Clone)] pub struct BreaksBaseMetric(()); impl Metric<BreaksInfo> for BreaksBaseMetric { fn measure(_: &BreaksInfo, len: usize) -> usize { len } fn to_base_units(_: &BreaksLeaf, in_measured_units: usize) -> usiz...
{ return Some(l.data[i]); }
conditional_block
mod.rs
// Copyright (C) 2020-2021 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish...
{ pub comments: bool, pub reporting: bool, } pub struct ServerContext { pub config: ServerConfig, pub datastore: Datastore, pub features: Features, pub session_store: session::SessionStore, pub config_repo: Arc<ConfigRepo>, pub event_services: Option<serde_json::Value>, } impl ServerC...
Features
identifier_name
mod.rs
// Copyright (C) 2020-2021 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish...
pub enum AuthenticationType { Anonymous, Username, UsernamePassword, } impl ToString for AuthenticationType { fn to_string(&self) -> String { let s = match self { AuthenticationType::Anonymous => "anonymous", AuthenticationType::Username => "username", Authen...
pub mod session; #[derive(Debug, Clone, PartialEq)]
random_line_split
mod.rs
extern crate serde; extern crate serde_json; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use self::serde::de::DeserializeOwned; #[allow(dead_code)] pub fn
<T>(path: &str) -> T where T: DeserializeOwned, { let json_string = read_json_file(path); serde_json::from_str::<T>(&json_string).unwrap() } #[allow(dead_code)] pub fn read_json_file(filename: &str) -> String { // Create a path to the desired file let path = Path::new(filename); let display = p...
load_doc
identifier_name
mod.rs
extern crate serde; extern crate serde_json; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use self::serde::de::DeserializeOwned; #[allow(dead_code)] pub fn load_doc<T>(path: &str) -> T where T: DeserializeOwned,
#[allow(dead_code)] pub fn read_json_file(filename: &str) -> String { // Create a path to the desired file let path = Path::new(filename); let display = path.display(); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)), ...
{ let json_string = read_json_file(path); serde_json::from_str::<T>(&json_string).unwrap() }
identifier_body
mod.rs
extern crate serde; extern crate serde_json; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use self::serde::de::DeserializeOwned; #[allow(dead_code)] pub fn load_doc<T>(path: &str) -> T where T: DeserializeOwned, { let json_string = read_json_file(path); serde_js...
let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)), Ok(file) => file, }; // Read the file contents into a string, returns `io::Result<usize>` let mut s = String::new(); if let Err(why) = file.read_to_string(&mut s) ...
pub fn read_json_file(filename: &str) -> String { // Create a path to the desired file let path = Path::new(filename); let display = path.display();
random_line_split
regions-outlives-nominal-type-struct-type.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,'b> { f: &'a Foo<&'b i32> //~ ERROR reference has a longer lifetime } } fn main() { }
Bar
identifier_name
regions-outlives-nominal-type-struct-type.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
// option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a nominal type (like `Foo<'a>`) outlives `'b` if its // arguments (like `'a`) outlive `'b`. // // Rule OutlivesNominalType from RFC 1214. // compile-pass #![feature(rustc_attrs)] #![allow(dead_code)] mo...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
lib.rs
// // GLSL Mathematics for Rust. // // Copyright (c) 2015 The glm-rs authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the right...
//! //! ~~~ignore //! let v2 = vec2(1., 2.); //! // compile error: this function takes 3 parameters but 2 parameters were supplied [E0061] //! let v3 = vec3(v2, 3.); //! ~~~ //! This will be fixed in future version by introducing functions like //! ```no_run fn vec21(x: Vec2, y: f32) -> Vec3```, in which ...
//! convenient constructor functions can't be implemented. For example, //! you can't do this,
random_line_split
codegen.rs
#![feature(plugin_registrar, rustc_private, slice_patterns, plugin)] #![plugin(quasi_macros)] extern crate rustc_plugin; extern crate syntax; #[macro_use] extern crate lazy_static; extern crate quasi; use std::collections::HashMap; use std::sync::Mutex; use syntax::ast::{MetaItem, Ident, ItemImpl, ImplItemKind, Toke...
} fn handle(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult +'static> { let (session, ch_ref, id, buffer) = match args { [TokenTree::Token(_, Token::Ident(session, _)), TokenTree::Token(_, Token::Comma), TokenTree::Token(_, Token::Ident(ch_ref, _)), TokenTree::T...
{ if let ItemImpl(_, _, _, _, _, ref list) = item.node { for impl_item in list { if let ImplItemKind::Method(ref sig, _) = impl_item.node { let mut table = HANDLERS.lock().unwrap(); if let Ty_::TyPath(_, ref path) = sig.decl.inputs[2].ty.node {...
conditional_block
codegen.rs
#![feature(plugin_registrar, rustc_private, slice_patterns, plugin)] #![plugin(quasi_macros)] extern crate rustc_plugin; extern crate syntax; #[macro_use] extern crate lazy_static; extern crate quasi; use std::collections::HashMap; use std::sync::Mutex; use syntax::ast::{MetaItem, Ident, ItemImpl, ImplItemKind, Toke...
(reg: &mut rustc_plugin::Registry) { use syntax::parse::token::intern; use syntax::ext::base::MultiDecorator; reg.register_syntax_extension( intern("register_handlers"), MultiDecorator(Box::new(register_handlers)) ); reg.register_macro("handle", handle); }
plugin_registrar
identifier_name
codegen.rs
#![feature(plugin_registrar, rustc_private, slice_patterns, plugin)] #![plugin(quasi_macros)] extern crate rustc_plugin; extern crate syntax; #[macro_use] extern crate lazy_static; extern crate quasi; use std::collections::HashMap; use std::sync::Mutex; use syntax::ast::{MetaItem, Ident, ItemImpl, ImplItemKind, Toke...
attrs: Vec::new(), pats: vec![cx.pat_wild(sp)], guard: Some(guard), body: body, }); } let unit = quote_expr!(cx, Ok(())); arms.push(Arm { attrs: Vec::new(), pats: vec![cx.pat_wild(sp)], guard: None, body: unit, }); ...
$session.$handler($ch_ref, try!($name::deserialize(&mut $buffer))) ); arms.push(Arm {
random_line_split
codegen.rs
#![feature(plugin_registrar, rustc_private, slice_patterns, plugin)] #![plugin(quasi_macros)] extern crate rustc_plugin; extern crate syntax; #[macro_use] extern crate lazy_static; extern crate quasi; use std::collections::HashMap; use std::sync::Mutex; use syntax::ast::{MetaItem, Ident, ItemImpl, ImplItemKind, Toke...
let handler = hdl.1; let guard = quote_expr!(cx, $id == $name::id()); let body = quote_expr!( cx, $session.$handler($ch_ref, try!($name::deserialize(&mut $buffer))) ); arms.push(Arm { attrs: Vec::new(), pats: vec![cx.pat_wild(sp)]...
{ let (session, ch_ref, id, buffer) = match args { [TokenTree::Token(_, Token::Ident(session, _)), TokenTree::Token(_, Token::Comma), TokenTree::Token(_, Token::Ident(ch_ref, _)), TokenTree::Token(_, Token::Comma), TokenTree::Token(_, Token::Ident(id, _)), TokenT...
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] use std::iter::Peekable; use std::str::CharIndices; type Inde...
(input: &str) -> Result<Vec<&str>, String> { if!input.contains("graphql`") { return Ok(vec![]); } let mut res = vec![]; let mut it = input.char_indices().peekable(); 'code: while let Some((i, c)) = it.next() { match c { 'g' => { for expected in ['r', 'a', ...
parse_chunks
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] use std::iter::Peekable; use std::str::CharIndices; type Inde...
fn consume_string(it: &mut IndexedCharIter<'_>, quote: char) { while let Some((_, c)) = it.next() { match c { '\\' => { it.next(); } '\'' | '"' if c == quote => { return; } '\n' | '\r' => { // Unexp...
{ while let Some((_, c)) = it.next() { if c == '*' { if let Some((_, '/')) = it.peek() { it.next(); break; } } } }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] use std::iter::Peekable; use std::str::CharIndices; type Inde...
} } } } fn consume_string(it: &mut IndexedCharIter<'_>, quote: char) { while let Some((_, c)) = it.next() { match c { '\\' => { it.next(); } '\'' | '"' if c == quote => { return; } '\n' | '\r...
break;
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] use std::iter::Peekable; use std::str::CharIndices; type Inde...
}, _ => {} }; } Ok(res) } fn consume_identifier(it: &mut IndexedCharIter<'_>) { for (_, c) in it { match c { 'a'..='z' | 'A'..='Z' | '_' | '0'..='9' => {} _ => { return; } } } } fn consume_line_comment...
{}
conditional_block
proto.rs
/*
* you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHO...
* Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
issue-18783.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut y = 1_usize; let c = RefCell::new(vec![]); Push::push(&c, box || y = 0); Push::push(&c, box || y = 0); //~^ ERROR cannot borrow `y` as mutable more than once at a time } trait Push<'c> { fn push<'f: 'c>(&self, push: Box<FnMut() + 'f>); } impl<'c> Push<'c> for RefCell<Vec<Box<FnMut() ...
ufcs
identifier_name
issue-18783.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 ufcs() { let mut y = 1_usize; let c = RefCell::new(vec![]); Push::push(&c, box || y = 0); Push::push(&c, box || y = 0); //~^ ERROR cannot borrow `y` as mutable more than once at a time } trait Push<'c> { fn push<'f: 'c>(&self, push: Box<FnMut() + 'f>); } impl<'c> Push<'c> for RefCell<Vec<Box...
{ let mut y = 1_usize; let c = RefCell::new(vec![]); c.push(box || y = 0); c.push(box || y = 0); //~^ ERROR cannot borrow `y` as mutable more than once at a time }
identifier_body
issue-18783.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
trait Push<'c> { fn push<'f: 'c>(&self, push: Box<FnMut() + 'f>); } impl<'c> Push<'c> for RefCell<Vec<Box<FnMut() + 'c>>> { fn push<'f: 'c>(&self, fun: Box<FnMut() + 'f>) { self.borrow_mut().push(fun) } }
//~^ ERROR cannot borrow `y` as mutable more than once at a time }
random_line_split
help_command.rs
use crate::actions::ActionOutput; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::utils::{format_columns, highlight, process_highlights, split_lines}; use super::command_registry::CommandRegistry; use super::CommandHelpers; /// Shows in-game help. pub fn help...
.unwrap_or(false); if command_name == "commands" { let command_names = helpers.command_registry.command_names(); push_output_string!( output, player_ref, process_highlights(&format!( "\n\ Here is a list of all the commands ...
.map(|player| player.is_admin())
random_line_split
help_command.rs
use crate::actions::ActionOutput; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::utils::{format_columns, highlight, process_highlights, split_lines}; use super::command_registry::CommandRegistry; use super::CommandHelpers; /// Shows in-game help. pub fn help...
(command_name: &str, admin_registry: &CommandRegistry) -> Option<String> { match command_name { "admin-commands" => Some(process_highlights(&format!( "\n\ Here is a list of all the commands you can use as an admin:\n\ \n\ *Remember: with great power comes grea...
show_admin_help
identifier_name
help_command.rs
use crate::actions::ActionOutput; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::utils::{format_columns, highlight, process_highlights, split_lines}; use super::command_registry::CommandRegistry; use super::CommandHelpers; /// Shows in-game help. pub fn help...
} if output.is_empty() { push_output_string!( output, player_ref, process_highlights(&format!( "The command \"{}\" is not recognized.\n\ Type *help commands* to see a list of all commands.\n", command_name ...
{ admin_help.push('\n'); push_output_string!(output, player_ref, admin_help); }
conditional_block
help_command.rs
use crate::actions::ActionOutput; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::utils::{format_columns, highlight, process_highlights, split_lines}; use super::command_registry::CommandRegistry; use super::CommandHelpers; /// Shows in-game help. pub fn help...
"admin-tips" => Some(process_highlights( "\n\ *Admin Tips*\n\ \n\ Now that you are an admin, you can actively modify the game world. It should go \ without saying that with great power, comes great responsibility. Especially because \ many ...
{ match command_name { "admin-commands" => Some(process_highlights(&format!( "\n\ Here is a list of all the commands you can use as an admin:\n\ \n\ *Remember: with great power comes great responsibility!*\n\ \n\ {}\ \n\ ...
identifier_body
build.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(path, io, env)] use std::env; use std::old_path::Path; use std::old_io::process::{Command, ProcessExit...
else { "python" }; let style = Path::new(file!()).dir_path(); let mako = style.join("Mako-0.9.1.zip"); let template = style.join("properties.mako.rs"); let result = Command::new(python) .env("PYTHONPATH", mako.as_str().unwrap()) .env("TEMPLATE", template.as_str().unwrap()) ...
{ "python2.7" }
conditional_block
build.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(path, io, env)] use std::env; use std::old_path::Path; use std::old_io::process::{Command, ProcessExit...
() { let python = if Command::new("python2.7").arg("--version").status() == Ok(ProcessExit::ExitStatus(0)) { "python2.7" } else { "python" }; let style = Path::new(file!()).dir_path(); let mako = style.join("Mako-0.9.1.zip"); let template = style.join("properties.mako.rs"); l...
main
identifier_name
build.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(path, io, env)] use std::env; use std::old_path::Path; use std::old_io::process::{Command, ProcessExit...
.stderr(StdioContainer::InheritFd(2)) .output() .unwrap(); assert_eq!(result.status, ProcessExit::ExitStatus(0)); let out = Path::new(env::var_string("OUT_DIR").unwrap()); File::create(&out.join("properties.rs")).unwrap().write_all(&*result.output).unwrap(); }
.arg("-c") .arg("from os import environ; from mako.template import Template; print(Template(filename=environ['TEMPLATE']).render())")
random_line_split
build.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(path, io, env)] use std::env; use std::old_path::Path; use std::old_io::process::{Command, ProcessExit...
}
{ let python = if Command::new("python2.7").arg("--version").status() == Ok(ProcessExit::ExitStatus(0)) { "python2.7" } else { "python" }; let style = Path::new(file!()).dir_path(); let mako = style.join("Mako-0.9.1.zip"); let template = style.join("properties.mako.rs"); let ...
identifier_body
traits.rs
//! Interfaces on which this library is built. use serde::{Deserialize, Serialize}; /// Trait represents global state of the /// entire simulation which can be updated /// independently from any particular cell. /// Consider to store there as much as you can /// because this data will be created only once /// and wil...
} /// Grid stores cells and updates them. Also /// grid contains global evolution state. pub trait Grid { /// Grid wants to work with them. type Cell: Cell; /// Grid knows how to work with them. type Coord: Coord; /// One step in evolution. fn update(&mut self); /// Getter for evolution ...
{ 0 }
identifier_body
traits.rs
//! Interfaces on which this library is built. use serde::{Deserialize, Serialize}; /// Trait represents global state of the /// entire simulation which can be updated /// independently from any particular cell. /// Consider to store there as much as you can /// because this data will be created only once /// and wil...
(&self) -> i32 { 0 } } /// Grid stores cells and updates them. Also /// grid contains global evolution state. pub trait Grid { /// Grid wants to work with them. type Cell: Cell; /// Grid knows how to work with them. type Coord: Coord; /// One step in evolution. fn update(&mut self); /// G...
z
identifier_name
traits.rs
//! Interfaces on which this library is built. use serde::{Deserialize, Serialize}; /// Trait represents global state of the /// entire simulation which can be updated /// independently from any particular cell. /// Consider to store there as much as you can /// because this data will be created only once /// and wil...
/// in grid. Cell can mutate itself. Grid should pass /// neighbors, previous version of this Cell and the /// global state. fn update<'a, I>(&'a mut self, old: &'a Self, neighbors: I, &Self::State) where I: Iterator<Item = Option<&'a Self>>; /// Constructs Cell with given coord. fn wit...
/// This method is called for every instance of Cell
random_line_split
sync_mutex_owned.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "sync")] #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as maybe_tokio_test; #[cfg(not(target_arch = "wasm32"))] use tokio::test as maybe_tokio_test; use tokio::sync::...
m1.lock_owned().await; }) .await .expect("Mutex is locked"); } /// This test is similar to `aborted_future_1` but this time the /// aborted future is waiting for the lock. #[tokio::test] #[cfg(feature = "full")] async fn aborted_future_2() { use std::time::Duration; use tokio::time::timeout;...
{ use std::time::Duration; use tokio::time::{interval, timeout}; let m1: Arc<Mutex<usize>> = Arc::new(Mutex::new(0)); { let m2 = m1.clone(); // Try to lock mutex in a future that is aborted prematurely timeout(Duration::from_millis(1u64), async move { let iv = interv...
identifier_body
sync_mutex_owned.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "sync")] #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as maybe_tokio_test; #[cfg(not(target_arch = "wasm32"))] use tokio::test as maybe_tokio_test; use tokio::sync::...
() { let l = Arc::new(Mutex::new(100)); let mut t1 = spawn(l.clone().lock_owned()); let mut t2 = spawn(l.lock_owned()); let g = assert_ready!(t1.poll()); // We can't now acquire the lease since it's already held in g assert_pending!(t2.poll()); // But once g unlocks, we can acquire it ...
readiness
identifier_name
sync_mutex_owned.rs
#![warn(rust_2018_idioms)] #![cfg(feature = "sync")] #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as maybe_tokio_test; #[cfg(not(target_arch = "wasm32"))] use tokio::test as maybe_tokio_test; use tokio::sync::...
*g = 98; } { let mut t = spawn(l.lock_owned()); let g = assert_ready!(t.poll()); assert_eq!(&*g, &98); } } #[test] fn readiness() { let l = Arc::new(Mutex::new(100)); let mut t1 = spawn(l.clone().lock_owned()); let mut t2 = spawn(l.lock_owned()); let g = ass...
} { let mut t = spawn(l.clone().lock_owned()); let mut g = assert_ready!(t.poll()); assert_eq!(&*g, &99);
random_line_split
formatter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; /// Writes file name into the writer, removes the character which not match `[a-zA-Z0-9\.-_]` pub fn write_file_name<W>(writer: &mut W, file_name: &str) -> io::Result<()> where W: io::Write +?Sized, { let mut start = 0; let by...
Ok(()) } /// According to [RFC: Unified Log Format], it returns `true` when this byte stream contains /// the following characters, which means this input stream needs to be JSON encoded. /// Otherwise, it returns `false`. /// /// - U+0000 (NULL) ~ U+0020 (SPACE) /// - U+0022 (QUOTATION MARK) /// - U+003D (EQUALS...
{ writer.write_all((&file_name[start..]).as_bytes())?; }
conditional_block
formatter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; /// Writes file name into the writer, removes the character which not match `[a-zA-Z0-9\.-_]` pub fn write_file_name<W>(writer: &mut W, file_name: &str) -> io::Result<()> where W: io::Write +?Sized, { let mut start = 0; let by...
(bytes: &[u8]) -> bool { for &byte in bytes { if byte <= 0x20 || byte == 0x22 || byte == 0x3D || byte == 0x5B || byte == 0x5D { return true; } } false } /// According to [RFC: Unified Log Format], escapes the given data and writes it into a writer. /// If there is no character [...
need_json_encode
identifier_name
formatter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; /// Writes file name into the writer, removes the character which not match `[a-zA-Z0-9\.-_]` pub fn write_file_name<W>(writer: &mut W, file_name: &str) -> io::Result<()> where W: io::Write +?Sized, { let mut start = 0; let by...
pub fn write_escaped_str<W>(writer: &mut W, value: &str) -> io::Result<()> where W: io::Write +?Sized, { if!need_json_encode(value.as_bytes()) { writer.write_all(value.as_bytes())?; } else { serde_json::to_writer(writer, value)?; } Ok(()) } #[cfg(test)] mod tests { use super::*;...
random_line_split
formatter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; /// Writes file name into the writer, removes the character which not match `[a-zA-Z0-9\.-_]` pub fn write_file_name<W>(writer: &mut W, file_name: &str) -> io::Result<()> where W: io::Write +?Sized, { let mut start = 0; let by...
expect ); } } #[test] fn test_write_file_name() { let mut s = vec![]; write_file_name( &mut s, "+=!@#$%^&*(){}|:\"<>/?\u{000f} 老虎 tiger 🐅\r\n\\-_1234567890.rs", ) .unwrap(); assert_eq!("tiger-_1234567890.rs...
{ let cases = [ ("abc", false), ("a b", true), ("a=b", true), ("a[b", true), ("a]b", true), ("\u{000f}", true), ("💖", false), ("�", false), ("\u{7fff}\u{ffff}", false), ("欢迎", false), ...
identifier_body
binary.rs
use super::*; use erlang_nif_sys::*; use std::mem::uninitialized; use std::slice::{from_raw_parts, from_raw_parts_mut}; impl<'a> FromTerm<CTerm> for &'a[u8] { fn from_term(env: &mut Env, term: CTerm) -> Result<Self> { unsafe { let mut binary = uninitialized(); match enif_inspect_binary(env, term, &mut binary...
/// Creat a new binary Term and a mutable slice referring to its contents. pub fn new_binary(env: &mut Env, size: usize) -> (Term, &mut [u8]) { unsafe { let mut cterm = uninitialized(); let ptr = enif_make_new_binary(env, size, &mut cterm); let term = cterm.as_term(env); // maybe wrap in checked term (term, f...
_ => Ok(from_raw_parts(binary.data, binary.size)) } } } }
random_line_split
binary.rs
use super::*; use erlang_nif_sys::*; use std::mem::uninitialized; use std::slice::{from_raw_parts, from_raw_parts_mut}; impl<'a> FromTerm<CTerm> for &'a[u8] { fn from_term(env: &mut Env, term: CTerm) -> Result<Self> { unsafe { let mut binary = uninitialized(); match enif_inspect_binary(env, term, &mut binary...
{ unsafe { let mut cterm = uninitialized(); let ptr = enif_make_new_binary(env, size, &mut cterm); let term = cterm.as_term(env); // maybe wrap in checked term (term, from_raw_parts_mut(ptr,size)) } }
identifier_body
binary.rs
use super::*; use erlang_nif_sys::*; use std::mem::uninitialized; use std::slice::{from_raw_parts, from_raw_parts_mut}; impl<'a> FromTerm<CTerm> for &'a[u8] { fn
(env: &mut Env, term: CTerm) -> Result<Self> { unsafe { let mut binary = uninitialized(); match enif_inspect_binary(env, term, &mut binary) { 0 => Err(Error::Badarg), _ => Ok(from_raw_parts(binary.data, binary.size)) } } } } /// Creat a new binary Term and a mutable slice referring to its content...
from_term
identifier_name
highlight.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 ...
} try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap(); if ...
{}
conditional_block
highlight.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 ...
(sess: &parse::ParseSess, mut lexer: lexer::StringReader, class: Option<&str>, id: Option<&str>, out: &mut Writer) -> old_io::IoResult<()> { use syntax::parse::lexer::Reader; try!(write!(out, "<pre ")); match id { Some(id) => try!(write!(out, "id='{}' ", id)), None => {} ...
doit
identifier_name
highlight.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 ...
/// Exhausts the `lexer` writing the output into `out`. /// /// The general structure for this method is to iterate over each token, /// possibly giving it an HTML span with a class specifying what flavor of token /// it's used. All source code emission is done as slices from the source map, /// not from the tokens t...
{ debug!("highlighting: ================\n{}\n==============", src); let sess = parse::new_parse_sess(); let fm = parse::string_to_filemap(&sess, src.to_string(), "<stdin>".to_string()); let mut out = Vec::new(); doit(&sess...
identifier_body
highlight.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 ...
token::Literal(lit, _suf) => { match lit { // text literals token::Byte(..) | token::Char(..) | token::Binary(..) | token::BinaryRaw(..) | token::Str_(..) | token::StrRaw(..) => "string", ...
}
random_line_split
lib.rs
//! Manage extended attributes. //! //! Note: This library *does not* follow symlinks. extern crate libc; mod sys; mod util; mod error; use std::os::unix::io::AsRawFd; use std::ffi::OsStr; use std::io; use std::fs::File; use std::path::Path; pub use sys::{XAttrs, SUPPORTED_PLATFORM}; pub use error::UnsupportedPlatfo...
<N, P>(path: P, name: N, value: &[u8]) -> io::Result<()> where P: AsRef<Path>, N: AsRef<OsStr> { sys::set_path(path.as_ref(), name.as_ref(), value) } /// Remove an extended attribute from the specified file. pub fn remove<N, P>(path: P, name: N) -> io::Result<()> where P: AsRef<Path>, N...
set
identifier_name
lib.rs
//! Manage extended attributes. //! //! Note: This library *does not* follow symlinks. extern crate libc; mod sys; mod util; mod error; use std::os::unix::io::AsRawFd; use std::ffi::OsStr; use std::io; use std::fs::File; use std::path::Path; pub use sys::{XAttrs, SUPPORTED_PLATFORM}; pub use error::UnsupportedPlatfo...
{ sys::list_path(path.as_ref()) } pub trait FileExt: AsRawFd { /// Get an extended attribute for the specified file. fn get_xattr<N>(&self, name: N) -> io::Result<Option<Vec<u8>>> where N: AsRef<OsStr> { util::extract_noattr(sys::get_fd(self.as_raw_fd(), name.as_ref())) } /// S...
pub fn list<P>(path: P) -> io::Result<XAttrs> where P: AsRef<Path>
random_line_split
lib.rs
//! Manage extended attributes. //! //! Note: This library *does not* follow symlinks. extern crate libc; mod sys; mod util; mod error; use std::os::unix::io::AsRawFd; use std::ffi::OsStr; use std::io; use std::fs::File; use std::path::Path; pub use sys::{XAttrs, SUPPORTED_PLATFORM}; pub use error::UnsupportedPlatfo...
pub trait FileExt: AsRawFd { /// Get an extended attribute for the specified file. fn get_xattr<N>(&self, name: N) -> io::Result<Option<Vec<u8>>> where N: AsRef<OsStr> { util::extract_noattr(sys::get_fd(self.as_raw_fd(), name.as_ref())) } /// Set an extended attribute on the speci...
{ sys::list_path(path.as_ref()) }
identifier_body
execution_config.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::config::{Error, RootPath, SecureBackend}; use diem_types::transaction::Transaction; use serde::{Deserialize, Serialize}; use std::{ fs::File, io::{Read, Write}, net::SocketAddr, path::PathBuf, }; const GENESI...
(&mut self, data_dir: PathBuf) { if let SecureBackend::OnDiskStorage(backend) = &mut self.backend { backend.set_data_dir(data_dir); } } } /// Defines how execution correctness should be run #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "snake_case", tag...
set_data_dir
identifier_name
execution_config.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::config::{Error, RootPath, SecureBackend}; use diem_types::transaction::Transaction; use serde::{Deserialize, Serialize}; use std::{ fs::File, io::{Read, Write}, net::SocketAddr, path::PathBuf, }; const GENESI...
let result = config.load(&root_dir); assert!(result.is_ok()); assert_eq!(config.genesis, Some(fake_genesis)); } fn generate_config() -> (ExecutionConfig, TempPath) { let temp_dir = TempPath::new(); temp_dir.create_as_dir().expect("error creating tempdir"); let ex...
random_line_split
execution_config.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::config::{Error, RootPath, SecureBackend}; use diem_types::transaction::Transaction; use serde::{Deserialize, Serialize}; use std::{ fs::File, io::{Read, Write}, net::SocketAddr, path::PathBuf, }; const GENESI...
} } /// Defines how execution correctness should be run #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "snake_case", tag = "type")] pub enum ExecutionCorrectnessService { /// This runs execution correctness in the same thread as event processor. Local, /// This is the ...
{ backend.set_data_dir(data_dir); }
conditional_block
execution_config.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::config::{Error, RootPath, SecureBackend}; use diem_types::transaction::Transaction; use serde::{Deserialize, Serialize}; use std::{ fs::File, io::{Read, Write}, net::SocketAddr, path::PathBuf, }; const GENESI...
pub fn set_data_dir(&mut self, data_dir: PathBuf) { if let SecureBackend::OnDiskStorage(backend) = &mut self.backend { backend.set_data_dir(data_dir); } } } /// Defines how execution correctness should be run #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(renam...
{ if let Some(genesis) = &self.genesis { if self.genesis_file_location.as_os_str().is_empty() { self.genesis_file_location = PathBuf::from(GENESIS_DEFAULT); } let path = root_dir.full_path(&self.genesis_file_location); let mut file = File::create(&...
identifier_body
scope.rs
use std::any::Any; use std::marker::PhantomData; use std::sync::atomic::{AtomicPtr, Ordering}; use std::sync::Arc; use std::{mem, ptr}; use super::job::HeapJob; use super::latch::{CountLatch, Latch}; use super::scheduler::{Scheduler, WorkerThread}; use super::unwind; /// Represents a fork-join scope which can be used...
<F>(&self, func: F) where F: FnOnce(&Scope<'s>) + Send +'s, { unsafe { if let Some(ref scheduler) = self.scheduler { self.latch.increment(); let job = Box::new(HeapJob::new(move || { let _v = self.execute(func); }))...
spawn
identifier_name
scope.rs
use std::any::Any; use std::marker::PhantomData; use std::sync::atomic::{AtomicPtr, Ordering}; use std::sync::Arc; use std::{mem, ptr}; use super::job::HeapJob; use super::latch::{CountLatch, Latch}; use super::scheduler::{Scheduler, WorkerThread}; use super::unwind; /// Represents a fork-join scope which can be used...
} } } pub(crate) unsafe fn wait_until_completed(&self, worker: &WorkerThread) { // wait for job counter to reach 0: worker.wait_until(&self.latch); // propagate panic, if any occurred; at this point, all outstanding jobs have completed, // so we can use a r...
{ match unwind::halt_unwinding(move || func(self)) { Ok(r) => { self.latch.set(); Some(r) } Err(err) => { // capture the first error we see, free the rest let nil = ptr::null_mut(); let mut err = ...
identifier_body
scope.rs
use std::any::Any; use std::marker::PhantomData; use std::sync::atomic::{AtomicPtr, Ordering}; use std::sync::Arc; use std::{mem, ptr}; use super::job::HeapJob; use super::latch::{CountLatch, Latch}; use super::scheduler::{Scheduler, WorkerThread}; use super::unwind; /// Represents a fork-join scope which can be used...
/// Spawns a job into the fork-join scope `self`. This job will execute sometime before /// the fork-join scope completes. The job is specified as a closure, and this closure /// receives its own reference to `self` as argument. This can be used to inject new jobs /// into `self`. pub fn spawn<F>(...
latch: CountLatch::new(), marker: PhantomData::default(), panic: AtomicPtr::new(ptr::null_mut()), } }
random_line_split
regions-outlives-nominal-type-enum-type.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,'b> { V(&'a Foo<&'b i32>) } } fn main() { }
Bar
identifier_name
regions-outlives-nominal-type-enum-type.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
// option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a nominal type (like `Foo<'a>`) outlives `'b` if its // arguments (like `'a`) outlive `'b`. // // Rule OutlivesNominalType from RFC 1214. // compile-pass #![feature(rustc_attrs)] #![allow(dead_code)] mo...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
bar.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// except according to those terms. #![feature(panic_handler, alloc_error_handler)] #![crate_type = "cdylib"] #![no_std] use core::alloc::*; struct B; unsafe impl GlobalAlloc for B { unsafe fn alloc(&self, x: Layout) -> *mut u8 { 1 as *mut u8 } unsafe fn dealloc(&self, ptr: *mut u8, x: Layout) ...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
bar.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ loop {} }
identifier_body
bar.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(_: &core::panic::PanicInfo) ->! { loop {} }
b
identifier_name
cssimportrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSImportRuleBinding; use crate::dom::bindings::reflector::reflect_d...
#[allow(unrooted_must_root)] pub fn new( window: &Window, parent_stylesheet: &CSSStyleSheet, import_rule: Arc<Locked<ImportRule>>, ) -> DomRoot<Self> { reflect_dom_object( Box::new(Self::new_inherited(parent_stylesheet, import_rule)), window, ...
{ CSSImportRule { cssrule: CSSRule::new_inherited(parent_stylesheet), import_rule: import_rule, } }
identifier_body
cssimportrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSImportRuleBinding; use crate::dom::bindings::reflector::reflect_d...
(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.import_rule .read_with(&guard) .to_css_string(&guard) .into() } }
get_css
identifier_name
cssimportrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CSSImportRuleBinding; use crate::dom::bindings::reflector::reflect_d...
use style::stylesheets::ImportRule; #[dom_struct] pub struct CSSImportRule { cssrule: CSSRule, #[ignore_malloc_size_of = "Arc"] import_rule: Arc<Locked<ImportRule>>, } impl CSSImportRule { fn new_inherited( parent_stylesheet: &CSSStyleSheet, import_rule: Arc<Locked<ImportRule>>, ) ...
use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard};
random_line_split
acronym.rs
extern crate acronym; #[test] fn basic() { assert_eq!(acronym::abbreviate("Portable Network Graphics"), "PNG"); } #[test] fn lowercase_words() { assert_eq!(acronym::abbreviate("Ruby on Rails"), "ROR"); } #[test] fn
() { assert_eq!(acronym::abbreviate("HyperText Markup Language"), "HTML"); } #[test] fn punctuation() { assert_eq!(acronym::abbreviate("First In, First Out"), "FIFO"); } #[test] fn all_caps_words() { assert_eq!(acronym::abbreviate("PHP: Hypertext Preprocessor"), "PHP"); } #[test] fn non_acronym_all_caps_...
camelcase
identifier_name
acronym.rs
extern crate acronym; #[test] fn basic() { assert_eq!(acronym::abbreviate("Portable Network Graphics"), "PNG"); } #[test] fn lowercase_words() { assert_eq!(acronym::abbreviate("Ruby on Rails"), "ROR"); } #[test] fn camelcase() { assert_eq!(acronym::abbreviate("HyperText Markup Language"), "HTML"); } #[t...
assert_eq!(acronym::abbreviate("Complementary metal-oxide semiconductor"), "CMOS"); }
#[test] fn hyphenated() {
random_line_split
acronym.rs
extern crate acronym; #[test] fn basic() { assert_eq!(acronym::abbreviate("Portable Network Graphics"), "PNG"); } #[test] fn lowercase_words() { assert_eq!(acronym::abbreviate("Ruby on Rails"), "ROR"); } #[test] fn camelcase() { assert_eq!(acronym::abbreviate("HyperText Markup Language"), "HTML"); } #[t...
#[test] fn hyphenated() { assert_eq!(acronym::abbreviate("Complementary metal-oxide semiconductor"), "CMOS"); }
{ assert_eq!(acronym::abbreviate("GNU Image Manipulation Program"), "GIMP"); }
identifier_body
domrect.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::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec...
fn Right(self) -> f32 { self.right } fn Width(self) -> f32 { (self.right - self.left).abs() } fn Height(self) -> f32 { (self.bottom - self.top).abs() } } impl Reflectable for DOMRect { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }...
{ self.left }
identifier_body
domrect.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::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec...
bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), } } pub fn new(window: JSRef<Window>, top: Au, bottom: Au, left: Au, right: Au) -> T...
left: Au, right: Au) -> DOMRect { DOMRect { top: top.to_nearest_px() as f32,
random_line_split
domrect.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::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec...
(self) -> f32 { self.top } fn Bottom(self) -> f32 { self.bottom } fn Left(self) -> f32 { self.left } fn Right(self) -> f32 { self.right } fn Width(self) -> f32 { (self.right - self.left).abs() } fn Height(self) -> f32 { (self.b...
Top
identifier_name
structured-compare.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 ne(&self, other: &foo) -> bool {!(*self).eq(other) } } pub fn main() { let a = (1, 2, 3); let b = (1, 2, 3); assert_eq!(a, b); assert!((a!= (1, 2, 4))); assert!((a < (1, 2, 4))); assert!((a <= (1, 2, 4))); assert!(((1, 2, 4) > a)); assert!(((1, 2, 4) >= a)); let x = large; ...
{ ((*self) as uint) == ((*other) as uint) }
identifier_body
structured-compare.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: &foo) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &foo) -> bool {!(*self).eq(other) } } pub fn main() { let a = (1, 2, 3); let b = (1, 2, 3); assert_eq!(a, b); assert!((a!= (1, 2, 4))); assert!((a < (1, 2, 4))); assert!((a <= (1, 2, 4))...
eq
identifier_name
structured-compare.rs
// Copyright 2012 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum foo { large,...
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread need...
fn process_response_eof(&mut self, response: Result<(), NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout( url: ServoUrl, node: &Node, id: Pe...
{ self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload)); }
identifier_body
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread need...
pipeline_id: Some(document.global().pipeline_id()), ..FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document .loader_mut() .fetch_async_background(request, action_sender); }
random_line_split
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread need...
(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache .notify_pending_response(self.id, FetchResponseMsg:...
process_response
identifier_name
http_loader.rs
::task::spawn_named; use util::resource_files::resources_dir_path; use util::opts; use url::{Url, UrlParser}; use uuid; use std::borrow::ToOwned; use std::boxed::FnBox; pub fn factory(resource_mgr_chan: IpcSender<ControlMsg>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: ...
let s = format!("The {} scheme with view-source is not supported", url.scheme); send_error(url, s, start_chan); return; } }; } // Loop to handle redirects. loop { iters = iters + 1; if &*url.scheme!= "https" && request_mus...
{ // FIXME: At the time of writing this FIXME, servo didn't have any central // location for configuration. If you're reading this and such a // repository DOES exist, please update this constant to use it. let max_redirects = 50; let mut iters = 0; let mut url = load_data.url.clon...
identifier_body
http_loader.rs
::task::spawn_named; use util::resource_files::resources_dir_path; use util::opts; use url::{Url, UrlParser}; use uuid; use std::borrow::ToOwned; use std::boxed::FnBox; pub fn factory(resource_mgr_chan: IpcSender<ControlMsg>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: ...
_ => { let s = format!("The {} scheme with view-source is not supported", url.scheme); send_error(url, s, start_chan); return; } }; } // Loop to handle redirects. loop { iters = iters + 1; if &*url.scheme!= "h...
{}
conditional_block
http_loader.rs
::task::spawn_named; use util::resource_files::resources_dir_path; use util::opts; use url::{Url, UrlParser}; use uuid; use std::borrow::ToOwned; use std::boxed::FnBox; pub fn factory(resource_mgr_chan: IpcSender<ControlMsg>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: ...
{ Payload(Vec<u8>), EOF, } fn read_block<R: Read>(reader: &mut R) -> Result<ReadResult, ()> { let mut buf = vec![0; 1024]; match reader.read(&mut buf) { Ok(len) if len > 0 => { unsafe { buf.set_len(len); } Ok(ReadResult::Payload(buf)) } Ok(_) => Ok(Read...
ReadResult
identifier_name
http_loader.rs
util::task::spawn_named; use util::resource_files::resources_dir_path; use util::opts; use url::{Url, UrlParser}; use uuid; use std::borrow::ToOwned; use std::boxed::FnBox; pub fn factory(resource_mgr_chan: IpcSender<ControlMsg>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_l...
} } } if response.status.class() == StatusClass::Redirection { match response.headers.get::<Location>() { Some(&Location(ref new_url)) => { // CORS (https://fetch.spec.whatwg.org/#http-fetch, status section, point 9, 10) ...
ControlMsg::SetHSTSEntryForHost( host.to_string(), include_subdomains, header.max_age ) ).unwrap();
random_line_split
adt-brace-enums.rs
// Copyright 2017 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 c = 66; SomeEnum::SomeVariant { t: &c }; } fn annot_underscore() { let c = 66; SomeEnum::SomeVariant::<_> { t: &c }; } fn annot_reference_any_lifetime() { let c = 66; SomeEnum::SomeVariant::<&u32> { t: &c }; } fn annot_reference_static_lifetime() { let c = 66; SomeEnum::SomeV...
no_annot
identifier_name
adt-brace-enums.rs
// Copyright 2017 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 annot_underscore() { let c = 66; SomeEnum::SomeVariant::<_> { t: &c }; } fn annot_reference_any_lifetime() { let c = 66; SomeEnum::SomeVariant::<&u32> { t: &c }; } fn annot_reference_static_lifetime() { let c = 66; SomeEnum::SomeVariant::<&'static u32> { t: &c }; //~ ERROR } fn annot_refe...
SomeEnum::SomeVariant { t: &c }; }
random_line_split
adt-brace-enums.rs
// Copyright 2017 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 annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) { let _closure = || { let c = 66; SomeEnum::SomeVariant::<&'a u32> { t: &c }; //~ ERROR }; } fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) { let _closure = || { SomeEnum::SomeVariant::<&'a u32> { t: c }...
{ SomeEnum::SomeVariant::<&'a u32> { t: c }; }
identifier_body
comment4.rs
#![allow(dead_code)] // bar //! Doc comment fn test() { // comment // comment2 code(); /* leave this comment alone! * ok? */ /* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a * diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam * viverra ne...
/* Regression test for issue #956 (some very important text) */ /* fn debug_function() { println!("hello"); } // */ #[link_section=".vectors"] #[no_mangle] // Test this attribute is preserved. #[cfg_attr(rustfmt, rustfmt::skip)] pub static ISSUE_1284: [i32; 16] = [];
{}
identifier_body