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 |
|---|---|---|---|---|
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use e... | (&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inl... | as_mut_block | identifier_name |
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use e... |
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
... | {
self.block_flow.repair_style(new_style)
} | identifier_body |
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use e... | self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
} | }
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { | random_line_split |
factory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
#[test]
fn test_create_vm() {
let _vm = Factory::default().create(U256::zero());
}
/// Create tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test(
(ignorejit => $name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
fn $name_jit()... | {
Factory {
evm: VMType::Interpreter,
evm_cache: Arc::new(SharedCache::default()),
}
} | identifier_body |
factory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | ,
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create fresh instance of VM
/// Might choose implementation d... | {
Box::new(super::jit::JitEvm::default())
} | conditional_block |
factory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (gas: U256) -> bool {
gas == U256::from(gas.low_u64() as usize)
}
}
impl Default for Factory {
/// Returns jitvm factory
#[cfg(all(feature = "jit", not(test)))]
fn default() -> Factory {
Factory {
evm: VMType::Jit,
evm_cache: Arc::new(SharedCache::default()),
}
}
/// Returns native rust evm factory
... | can_fit_in_usize | identifier_name |
factory.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | /// RUST EVM
Interpreter
}
impl fmt::Display for VMType {
#[cfg(feature="jit")]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Jit => "JIT",
VMType::Interpreter => "INT"
})
}
#[cfg(not(feature="jit"))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {... | /// Type of EVM to use.
pub enum VMType {
/// JIT EVM
#[cfg(feature = "jit")]
Jit, | random_line_split |
opaque_types.rs | use rustc_data_structures::vec_map::VecMap;
use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span;
use rustc_trait_selection::opaque_types::InferCtxtExt;
use super::RegionInferenceContext;
impl<'tcx> RegionInferenceContext<'tcx> {
/// Resolv... | subst_regions.sort();
subst_regions.dedup();
let universal_concrete_type =
infcx.tcx.fold_regions(concrete_type, &mut false, |region, _| match *region {
ty::ReVar(vid) => subst_regions
.iter()
... | {
opaque_ty_decls
.into_iter()
.map(|(opaque_type_key, concrete_type)| {
let substs = opaque_type_key.substs;
debug!(?concrete_type, ?substs);
let mut subst_regions = vec![self.universal_regions.fr_static];
let universal_su... | identifier_body |
opaque_types.rs | use rustc_data_structures::vec_map::VecMap;
use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span;
use rustc_trait_selection::opaque_types::InferCtxtExt;
use super::RegionInferenceContext;
impl<'tcx> RegionInferenceContext<'tcx> {
/// Resolv... | opaque_ty_decls: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>,
span: Span,
) -> VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>> {
opaque_ty_decls
.into_iter()
.map(|(opaque_type_key, concrete_type)| {
let substs = opaque_type_key.substs;
debug!(?concrete_... | #[instrument(skip(self, infcx))]
pub(in crate::borrow_check) fn infer_opaque_types(
&self,
infcx: &InferCtxt<'_, 'tcx>, | random_line_split |
opaque_types.rs | use rustc_data_structures::vec_map::VecMap;
use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span;
use rustc_trait_selection::opaque_types::InferCtxtExt;
use super::RegionInferenceContext;
impl<'tcx> RegionInferenceContext<'tcx> {
/// Resolv... | <T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
where
T: TypeFoldable<'tcx>,
{
tcx.fold_regions(ty, &mut false, |region, _| match *region {
ty::ReVar(vid) => {
// Find something that we can name
let upper_bound = self.approx_universal_upper_bound(vid);
... | name_regions | identifier_name |
signer.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | p.push(CODES_FILENAME);
let _ = restrict_permissions_owner(&p, true, false);
p
}
pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> {
Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message)
}
pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf:... | }
pub fn codes_path(path: &Path) -> PathBuf {
let mut p = path.to_owned(); | random_line_split |
signer.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> rpc_apis::SignerService {
let signer_path = ws_conf.signer_path.clone();
let signer_enabled = ui_conf.enabled;
rpc_apis::SignerService::new(move || {
generate_new_token(&signer_path).map_err(|e| format!("{:?}", e))
}, signer_enabled)
}
pub fn c... | new_service | identifier_name |
signer.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> {
Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message)
}
pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> Result<NewToken, String> {
let code = generate_new_toke... | {
let mut p = path.to_owned();
p.push(CODES_FILENAME);
let _ = restrict_permissions_owner(&p, true, false);
p
} | identifier_body |
trait.rs | // Test traits
trait Foo {
fn bar(x: i32 ) -> Baz< U> |
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
fn baz(&mut self ) -> i32 ;
fn... | { Baz::new()
} | identifier_body |
trait.rs | // Test traits
trait Foo {
fn | (x: i32 ) -> Baz< U> { Baz::new()
}
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
... | bar | identifier_name |
trait.rs | // Test traits
trait Foo {
fn bar(x: i32 ) -> Baz< U> { Baz::new()
}
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetTyp... | trait Ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T> where T: Foo {}
trait FooBar<T> : Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt where J: Bar { fn test(); }
trait WhereList<T, J> where T: Foo, J: Bar {} | }
trait Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T>
where T: Foo {}
| random_line_split |
18.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn | () -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Terrain {
Open,
Trees,
Lumberyard
}
type Point = (isize, isize);
type Landsca... | get_input | identifier_name |
18.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn get_input() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
... | fn get_neighbors((x, y): Point, landscape: &Landscape) -> Vec<Point> {
(x - 1..x + 2)
.flat_map(|x| (y - 1..y + 2).map(move |y| (x, y)))
.filter(|&p| p!= (x, y) && landscape.contains_key(&p))
.collect()
}
fn evolve(landscape: &Landscape) -> Landscape {
landscape.iter()
.map(|(&p, &terrain)| {
... | })
}
| random_line_split |
18.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn get_input() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
... | Terrain::Lumberyard => {
if neighbors.iter().any(|n| landscape[n] == Terrain::Lumberyard)
&& neighbors.iter().any(|n| landscape[n] == Terrain::Trees) {
Terrain::Lumberyard
} else {
Terrain::Open
}
... | {
landscape.iter()
.map(|(&p, &terrain)| {
let neighbors = get_neighbors(p, &landscape);
(p, match terrain {
Terrain::Open => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Trees).count() >= 3 {
Terrain::Trees
} else {
... | identifier_body |
lib.rs | //! This crate is a Rust library for using the [Serde](https://github.com/serde-rs/serde)
//! serialization framework with bencode data.
//!
//! # Examples
//!
//! ```
//! use serde_derive::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
//! struct Product {
//! name: Strin... | //! assert_eq!(
//! deserialized,
//! Product {
//! name: "Apple".to_string(),
//! price: 130,
//! }
//! );
//!
//! Ok(())
//! }
//! ```
pub mod de;
pub mod error;
pub mod ser;
pub mod value;
pub use de::{from_bytes, from_str, Deserializer};
pub use error::{... | //! let deserialized: Product = serde_bencode::from_str(&serialized)?;
//! | random_line_split |
day14.rs | use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);... | }
pub fn part2(input: &mut dyn Read) -> String {
parts_common(input, 40)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/14.txt");
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 1588);
}
... | .to_string()
}
pub fn part1(input: &mut dyn Read) -> String {
parts_common(input, 10) | random_line_split |
day14.rs | use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);... | (pairs: Pairs, rules: &Rules) -> Pairs {
let mut new_pairs = Pairs::default();
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
let product = rules[first][second] as usize;
new_pairs[first][product] += count;
new... | update | identifier_name |
day14.rs | use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);... |
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 2188189693529u64);
}
}
| {
test_implementation(part1, SAMPLE, 1588);
} | identifier_body |
placessidebar.rs | // This file is part of rgtk.
//
// rgtk 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, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_local_only(&self, local_only: bool) {
unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(local_onl... | t_show_connect_to_server(& | identifier_name |
placessidebar.rs | // This file is part of rgtk.
//
// rgtk 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, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) {
unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.get_widget()), flags) }
}
pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags {
unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.get_wi... | let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesSidebar)
}
| identifier_body |
placessidebar.rs | // This file is part of rgtk.
//
// rgtk 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, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
impl_widget_events!(PlacesSidebar) | random_line_split | |
compare_xz.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn decode_xz_lzmars(compressed: &[u8]) -> Result<Vec<u8>> {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)... | Ok(decomp)
}
fuzz_target!(|data: &[u8]| {
let result_lzmars = decode_xz_lzmars(data);
let result_xz2 = decode_xz_xz2(data);
match (result_lzmars, result_xz2) {
(Err(_), Err(_)) => (), // both failed, so behavior matches
(Ok(_), Err(_)) => panic!("lzma-rs succeeded but xz2 failed"),
... | random_line_split | |
compare_xz.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn decode_xz_lzmars(compressed: &[u8]) -> Result<Vec<u8>> |
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
// create new XZ decompression stream with 8Gb memory limit and checksum verification disabled
let xz_stream =
stream::Stream::new_stream_decoder(8 * 1024 *... | {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
} | identifier_body |
compare_xz.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn | (compressed: &[u8]) -> Result<Vec<u8>> {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
}
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut d... | decode_xz_lzmars | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R,... | }
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&self) -> MAR {
let bits = {
const MASK: u32 = 4294967295;
const... | self.w | random_line_split |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R,... | (&mut self) -> _MAW {
_MAW { w: self }
}
}
| ma | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R,... |
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&mut self) -> _MAW {
_MAW { w: self }
}
}
| {
self.bits = bits;
self
} | identifier_body |
invoke-function.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | (client: &Client, arn: &str) -> Result<(), Error> {
client.invoke().function_name(arn).send().await?;
println!("Invoked function.");
Ok(())
}
// snippet-end:[lambda.rust.invoke-function]
/// Invokes a Lambda function by its ARN.
/// # Arguments
///
/// * `-a ARN` - The ARN of the Lambda function.
/// * `... | run_function | identifier_name |
invoke-function.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
| struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The AWS Lambda function's Amazon Resource Name (ARN).
#[structopt(short, long)]
arn: String,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
// ... | use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)] | random_line_split |
invoke-function.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
run_function(&client, &arn).await
}
| {
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Lambda function ARN: {}", arn);
println!();
} | conditional_block |
main.rs | use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum Instruction {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruct... | *entry /= 2;
head + 1
},
Instruction::Triple(r) => {
let entry = computer.entry(r).or_insert(0);
*entry *= 3;
head + 1
},
Instruction::Increment(r) => {
let entry = computer.entry(r).or_insert(0);
*entry ... | match instructions[head as usize] {
Instruction::Half(r) => {
let entry = computer.entry(r).or_insert(0); | random_line_split |
main.rs | use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum Instruction {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruct... |
else { head + 1 }
},
Instruction::JumpIfOne(r, offset) => {
if *computer.get(&r).unwrap_or(&0) == 1 { head + offset }
else { head + 1 }
}
}
}
fn execute_program(computer: &mut Computer, program: &Vec<Instruction>) {
let mut head: i32 = 0;
loop {
... | { head + offset } | conditional_block |
main.rs | use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum | {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruction(computer: &mut Computer, instructions: &Vec<Instruction>, head: i32) -> i32 {
match instructions[head as usize] {
Instruction::Half(r) =>... | Instruction | identifier_name |
host_common.rs | //
// Copyright 2021 The Project Oak Authors
//
// 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 law o... |
pub fn wait_for_signal(&self) -> Signal {
for _ in 0..SIGNAL_REPS {
let signal = Signal::from(unsafe { *self.signal });
if signal!= Signal::Idle {
return signal;
}
thread::sleep(Duration::from_millis(SIGNAL_WAIT));
}
panic!("co... | random_line_split | |
host_common.rs | //
// Copyright 2021 The Project Oak Authors
//
// 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 law o... | (shared_ro: cptr, shared_rw: cptr, index: usize) -> Self {
assert!(index == HUNTER_SIGNAL_INDEX || index == RUNNER_SIGNAL_INDEX);
Self {
shared_ro,
shared_rw,
index,
signal: unsafe { shared_rw.add(index) as *mut u8 },
}
}
pub fn wait_for_s... | new | identifier_name |
host_common.rs | //
// Copyright 2021 The Project Oak Authors
//
// 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 law o... |
// Aligns to next largest page boundary, unless ptr is already aligned.
pub fn page_align(ptr: i64) -> i64 {
((ptr - 1) &!(PAGE_SIZE - 1)) + PAGE_SIZE
}
| {
let cname = CString::new(name).unwrap();
let (open_flags, map_flags) = match read_only {
false => (O_RDWR, PROT_READ | PROT_WRITE),
true => (O_RDONLY, PROT_READ),
};
unsafe {
let fd = libc::shm_open(cname.as_ptr(), open_flags, S_IRUSR | S_IWUSR);
if fd == -1 {
... | identifier_body |
host_common.rs | //
// Copyright 2021 The Project Oak Authors
//
// 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 law o... |
if!self.shared_rw.is_null()
&& libc::munmap(self.shared_rw, READ_WRITE_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_rw");
}
}
}
}
// Uses the libc POSIX API to map in a shared memory buffer.
pub fn map_buffer(aligned_ptr: i64, name: ... | {
println!("munmap failed for shared_ro");
} | conditional_block |
dependency_format.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: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
| attempt_static | identifier_name |
dependency_format.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 formats = HashMap::new();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum... | {} | conditional_block |
dependency_format.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 attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
| {
match m.find(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locati... | identifier_body |
dependency_format.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 ... | // Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_cr... | random_line_split | |
parameter_number_and_kind.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 ... | () {}
| main | identifier_name |
parameter_number_and_kind.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(generic_associated_types)]
//~^ WARNING the feature `generic_associated_types... | random_line_split | |
label_parsers.rs | use crate::asm::Token;
use nom::types::CompleteStr;
use nom::{alphanumeric, multispace};
named!(pub label_decl<CompleteStr, Token>,
ws!(
do_parse!(
name: alphanumeric >>
tag!(":") >>
opt!(multispace) >>
(
Token::LabelDecl{name: name.to_string... |
}
| {
let result = label_ref(CompleteStr("@test"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelRef {
name: "test".to_string()
}
);
let result = label_ref(CompleteStr("test"));
... | identifier_body |
label_parsers.rs | use crate::asm::Token;
use nom::types::CompleteStr;
use nom::{alphanumeric, multispace};
named!(pub label_decl<CompleteStr, Token>,
ws!(
do_parse!(
name: alphanumeric >>
tag!(":") >>
opt!(multispace) >>
(
Token::LabelDecl{name: name.to_string... | () {
let result = label_ref(CompleteStr("@test"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelRef {
name: "test".to_string()
}
);
let result = label_ref(CompleteStr("test")... | test_parse_label_ref | identifier_name |
label_parsers.rs | use crate::asm::Token;
use nom::types::CompleteStr;
use nom::{alphanumeric, multispace};
named!(pub label_decl<CompleteStr, Token>,
ws!(
do_parse!(
name: alphanumeric >>
tag!(":") >>
opt!(multispace) >>
(
Token::LabelDecl{name: name.to_string... | token,
Token::LabelRef {
name: "test".to_string()
}
);
let result = label_ref(CompleteStr("test"));
assert!(result.is_err());
}
} | random_line_split | |
cfg.rs | use std::path::PathBuf;
use std::collections::HashMap;
use std::env;
use util::ini::{Ini, IniParser};
pub struct ProgramConfig {
config: Ini,
}
/// Encapsulates program config, which is stored per-prefix
/// in.ini files.
impl ProgramConfig {
/// Try loading config file by prefix.
pub fn factory(prefix: ... | (&self) -> Option<String> {
self.config.get("wine")
}
}
| get_wine | identifier_name |
cfg.rs | use std::path::PathBuf;
use std::collections::HashMap;
use std::env;
use util::ini::{Ini, IniParser};
pub struct ProgramConfig {
config: Ini,
} | pub fn factory(prefix: &str) -> Option<Self> {
let mut path = env::var_os("HOME")
.and_then(|home| {
home.into_string().and_then(|s| {
Ok(PathBuf::from(s + "/.config/winerunner"))
}).ok()
}).unwrap();
path.push(format!("{}.i... |
/// Encapsulates program config, which is stored per-prefix
/// in .ini files.
impl ProgramConfig {
/// Try loading config file by prefix. | random_line_split |
cfg.rs | use std::path::PathBuf;
use std::collections::HashMap;
use std::env;
use util::ini::{Ini, IniParser};
pub struct ProgramConfig {
config: Ini,
}
/// Encapsulates program config, which is stored per-prefix
/// in.ini files.
impl ProgramConfig {
/// Try loading config file by prefix.
pub fn factory(prefix: ... |
}
/// Get env section for file, if present.
pub fn get_env(&self) -> Option<HashMap<String, String>> {
self.config.get_section("env")
}
pub fn get_wine(&self) -> Option<String> {
self.config.get("wine")
}
}
| {
None
} | conditional_block |
main.rs | #![feature(lang_items, alloc_error_handler)]
#![no_std] | use data_encoding::Encoding;
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
struct Fd(libc::c_int);
impl core::fmt::Write for Fd {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
unsafe {
libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len());
}
... | #![no_main]
use core::fmt::Write; | random_line_split |
main.rs | #![feature(lang_items, alloc_error_handler)]
#![no_std]
#![no_main]
use core::fmt::Write;
use data_encoding::Encoding;
#[lang = "eh_personality"]
extern "C" fn eh_personality() |
struct Fd(libc::c_int);
impl core::fmt::Write for Fd {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
unsafe {
libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len());
}
Ok(())
}
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! {
... | {} | identifier_body |
main.rs | #![feature(lang_items, alloc_error_handler)]
#![no_std]
#![no_main]
use core::fmt::Write;
use data_encoding::Encoding;
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
struct Fd(libc::c_int);
impl core::fmt::Write for Fd {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
unsafe {
... | (&self, ptr: *mut u8, _: Layout) {
libc::free(ptr as *mut libc::c_void)
}
}
#[alloc_error_handler]
fn foo(_: Layout) ->! {
loop {}
}
#[global_allocator]
static GLOBAL: Malloc = Malloc;
}
fn test_encode(encoding: &Encoding, input: &[u8], output: &mut [u8], result: &... | dealloc | identifier_name |
main.rs | // https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Closures
////////////////////////////////////////////////////////////////////////... | () -> Box<Fn(i32) -> i32> {
let num = 5;
Box::new(move |x| x + num)
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
}
| factory | identifier_name |
main.rs | // https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Closures
////////////////////////////////////////////////////////////////////////... | ////////////////////////////////////////////////////////////////////////////////
// Function pointers ans closures
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//fn add_one(i: i32) -> i32 {
// i + 1
//}
//let f = add_one;
//let answer... | //assert_eq!(3, answer);
| random_line_split |
main.rs | // https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Closures
////////////////////////////////////////////////////////////////////////... |
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
////////////////////////////////////////////////////////////////////////////////
// Closures and their environment
let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
// l... | { x + 1 } | identifier_body |
vec.rs | //! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// d... |
}
fn split(self, mut idx: usize) -> (Self, Self) {
if idx > self.len { idx = self.len }
(
VecSplit { items: self.items.clone(), start: self.start, len: idx},
VecSplit { items: self.items, start: self.start + idx, len: self.len - idx }
)
}
fn size_hint(&self) -> (usize, Option<usize... | { None } | conditional_block |
vec.rs | //! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// d... | <T> {
// keeps the data alive until it is consumed.
items: Arc<NoDropVec<T>>,
start: usize,
len: usize,
}
impl<T> IntoIterator for VecSplit<T> {
type IntoIter = Iter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
let cur_ptr = unsafe { self.items.inner.as_ptr().offset(self.start as isize) };
let... | VecSplit | identifier_name |
vec.rs | //! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// d... |
}
// required by Arc. VecSplit/Iter never actually uses the data in the vector
// except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,
end: *mut... | {
unsafe { self.inner.set_len(0) }
} | identifier_body |
vec.rs | //! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// d... | // except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,
end: *mut T,
}
impl<T> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Opt... | }
// required by Arc. VecSplit/Iter never actually uses the data in the vector | random_line_split |
stream.rs | // Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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-... |
}
| {
Box::new(Symmetric::new(&"000102030405060708090a0b0c0d0e0f"
.from_hex()
.ok()
.unwrap(),
Some(&"000000000000000000000000"
.fr... | identifier_body |
stream.rs | // Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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-... |
self.buffer.read(buffer)
}
}
impl Clone for Stream<net::TcpStream> {
fn clone(&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.cipher.box_clone())
}
}
impl From<cipher::Error> for io::Error {
fn from(error: cipher::Error) -> Self {
io::Error::new(io::ErrorKin... | {
let encrypted_size = try!(reader::read_size(&mut self.parent));
let mut encrypted_bytes = iter::repeat(0u8).take(encrypted_size).collect::<Vec<u8>>();
try!(self.parent.read_exact(&mut encrypted_bytes));
let decrypted_bytes = try!(self.cipher.decrypt(&encrypted_bytes))... | conditional_block |
stream.rs | // Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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-... |
let decrypted_bytes = try!(self.cipher.decrypt(&encrypted_bytes));
self.buffer = io::Cursor::new(decrypted_bytes);
}
self.buffer.read(buffer)
}
}
impl Clone for Stream<net::TcpStream> {
fn clone(&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.... | if self.buffer.position() as usize >= self.buffer.get_ref().len() {
let encrypted_size = try!(reader::read_size(&mut self.parent));
let mut encrypted_bytes = iter::repeat(0u8).take(encrypted_size).collect::<Vec<u8>>();
try!(self.parent.read_exact(&mut encrypted_bytes)); | random_line_split |
stream.rs | // Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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-... | (&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.cipher.box_clone())
}
}
impl From<cipher::Error> for io::Error {
fn from(error: cipher::Error) -> Self {
io::Error::new(io::ErrorKind::Other, format!("cipher error: {:?}", error))
}
}
#[cfg(test)]
mod tests {
use std::... | clone | identifier_name |
handlebars_templates.rs | extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub ... |
};
if hb.get_template(name).is_none() {
error_!("Handlebars template '{}' does not exist.", name);
return None;
}
match hb.render(name, context) {
Ok(string) => Some(string),
Err(e) => {
error_!("Error rendering Handlebars template '{}': {}", name, e);
... | {
error_!("Internal error: `render` called before handlebars init.");
return None;
} | conditional_block |
handlebars_templates.rs | extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub ... | } | random_line_split | |
handlebars_templates.rs | extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub ... |
pub fn render<T>(name: &str, _info: &TemplateInfo, context: &T) -> Option<String>
where T: Serialize
{
let hb = match unsafe { HANDLEBARS.as_ref() } {
Some(hb) => hb,
None => {
error_!("Internal error: `render` called before handlebars init.");
return None;
}
... | {
if HANDLEBARS.is_some() {
error_!("Internal error: reregistering handlebars!");
return false;
}
let mut hb = Handlebars::new();
let mut success = true;
for &(name, info) in templates {
let path = &info.full_path;
if let Err(e) = hb.register_template_file(name, path... | identifier_body |
handlebars_templates.rs | extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub ... | (templates: &[(&str, &TemplateInfo)]) -> bool {
if HANDLEBARS.is_some() {
error_!("Internal error: reregistering handlebars!");
return false;
}
let mut hb = Handlebars::new();
let mut success = true;
for &(name, info) in templates {
let path = &info.full_path;
if let... | register | identifier_name |
core_type_forms.rs | "), (named "res", (call "kind"))])),
);
// types
let fn_type = type_defn_complex(
"fn",
form_pat!((delim "[", "[",
[ (star (named "param", (call "Type"))), (lit "->"),
(named "ret", (call "Type") ) ])),
LiteralLike, // synth is normal
Both(
... | Remove "Ident" entirely.
// HACK: "Ident" and "DefaultAtom" are just not walked; this should probably be three-armed
false
} else {
ic | conditional_block | |
core_type_forms.rs | Form {
name: n(form_name),
grammar: Rc::new(p),
type_compare: tc,
synth_type: Positive(sy),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked),
})
}
thread_local! {
// Not needed by the user.
// An internal type to keep the compiler from tr... |
if let Node(f, _, exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref forall_type__pa... | random_line_split | |
core_type_forms.rs | {
name: n(form_name),
grammar: Rc::new(p),
type_compare: tc,
synth_type: Positive(sy),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked),
})
}
thread_local! {
// Not needed by the user.
// An internal type to keep the compiler from trying... | > SynEnv {
// Regarding the value/type/kind hierarchy, Benjamin Pierce generously assures us that
// "For programming languages... three levels have proved sufficient."
// kinds (TODO #3: actually use these)
let _type_kind = simple_form("Type", form_pat!((lit "*")));
let _higher_kind = simple_form(... | _core_syn_env_types() - | identifier_name |
core_type_forms.rs | read_local! {
// Not needed by the user.
// An internal type to keep the compiler from trying to dig into the `Expr` in `Expr<X>`.
pub static primitive_type : Rc<Form> = Rc::new(Form {
name: n("primitive_type"),
grammar: Rc::new(form_pat!([(named "name", atom)])),
type_compare: Both(... | Rc::new(Form {
name: n(form_name),
grammar: Rc::new(p),
type_compare: tc,
synth_type: Positive(sy),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked),
})
}
th | identifier_body | |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use util::ppaux::Repr;
use util::ppaux;
use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;
use std::cell::RefCell;
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
pub mod... | use util::common::time; | random_line_split |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (ccx: &CrateCtxt,
start_id: ast::NodeId,
start_span: Span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match start_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(start_id) {
Some(ast_map::NodeItem(it... | check_start_fn_ty | identifier_name |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
time(time_passes, "type checking", (), |_|
check::check_item_types(&ccx));
check_for_entry_fn(&ccx);
tcx.sess.abort_if_errors();
}
#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
| {
let time_passes = tcx.sess.time_passes();
let ccx = CrateCtxt {
trait_map: trait_map,
all_traits: RefCell::new(None),
tcx: tcx
};
time(time_passes, "type collecting", (), |_|
collect::collect_item_types(tcx));
// this ensures that later parts of type checking can... | identifier_body |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Bin... | {
span_err!(ccx.tcx.sess, main_span, E0131,
"main function is not allowed to have type parameters");
return;
} | conditional_block |
regions-bounds.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 ... | //~| lifetime mismatch
}
fn a_fn3<'a,'b>(e: a_class<'a>) -> a_class<'b> {
return e; //~ ERROR mismatched types
//~| expected `a_class<'b>`
//~| found `a_class<'a>`
//~| lifetime mismatch
}
fn main() { } | return e; //~ ERROR mismatched types
//~| expected `an_enum<'b>`
//~| found `an_enum<'a>` | random_line_split |
regions-bounds.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 ... | <'a,'b>(e: a_class<'a>) -> a_class<'b> {
return e; //~ ERROR mismatched types
//~| expected `a_class<'b>`
//~| found `a_class<'a>`
//~| lifetime mismatch
}
fn main() { }
| a_fn3 | identifier_name |
regions-bounds.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 main() { }
| {
return e; //~ ERROR mismatched types
//~| expected `a_class<'b>`
//~| found `a_class<'a>`
//~| lifetime mismatch
} | identifier_body |
mod.rs |
use std::thread;
use std::io::Read;
use std::sync::{Arc, Mutex};
use collector;
use gvim;
use lister;
pub fn | (stocks: collector::Stocks, conditions: &lister::ConditionSet, keys: &[String], expressions: &[String]) -> String {
let instances = lister::list(&Some(stocks), conditions);
let buffer = Arc::new(Mutex::new(String::new()));
let handles: Vec<_> =
instances.iter().map(|instance| {
trace!(... | broadcast | identifier_name |
mod.rs |
use std::thread;
use std::io::Read;
use std::sync::{Arc, Mutex};
use collector;
use gvim;
use lister;
pub fn broadcast(stocks: collector::Stocks, conditions: &lister::ConditionSet, keys: &[String], expressions: &[String]) -> String | })
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
{
let buffer = buffer.lock().unwrap();
(*buffer).to_owned()
}
}
| {
let instances = lister::list(&Some(stocks), conditions);
let buffer = Arc::new(Mutex::new(String::new()));
let handles: Vec<_> =
instances.iter().map(|instance| {
trace!("broadcast: {}", instance.servername);
let (keys, expressions, instance, buffer) = (keys.to_vec(), ex... | identifier_body |
mod.rs | use std::thread;
use std::io::Read;
use std::sync::{Arc, Mutex};
use collector;
use gvim;
use lister;
pub fn broadcast(stocks: collector::Stocks, conditions: &lister::ConditionSet, keys: &[String], expressions: &[String]) -> String {
let instances = lister::list(&Some(stocks), conditions); | let handles: Vec<_> =
instances.iter().map(|instance| {
trace!("broadcast: {}", instance.servername);
let (keys, expressions, instance, buffer) = (keys.to_vec(), expressions.to_vec(), instance.clone(), buffer.clone());
thread::spawn(move || {
gvim::remot... |
let buffer = Arc::new(Mutex::new(String::new()));
| random_line_split |
css_section.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOr... |
}
| {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
}
} | identifier_body |
css_section.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOr... | (&self) -> Option<gio::File> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_file(self.to_glib_none().0))
}
}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
... | get_file | identifier_name |
css_section.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOr... | }
}
} | pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0) | random_line_split |
utils.rs | // Copyright 2015 click2stream, Inc.
//
// 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 law or agreed... | (sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000)!= 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!checksum as u16
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(... | sum_to_checksum | identifier_name |
utils.rs | // Copyright 2015 click2stream, Inc.
//
// 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 law or agreed... | impl Serialize for Box<[u8]> {
fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {
w.write_all(self.as_ref())
}
}
/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.
pub fn sum_type<T: Sized>(data: &T) -> u32 {
let size = mem::size_of::<T>();
let ptr = data as *con... | pub trait Serialize {
/// Serialize this object using a given writer.
fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;
}
| random_line_split |
utils.rs | // Copyright 2015 click2stream, Inc.
//
// 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 law or agreed... | else {
sum
}
}
/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.
pub fn sum_to_checksum(sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000)!= 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!che... | {
sum.wrapping_add((slice[size - 1] as u32) << 8)
} | conditional_block |
utils.rs | // Copyright 2015 click2stream, Inc.
//
// 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 law or agreed... |
}
| {
assert_eq!(!0x0000_3333, sum_to_checksum(0x1111_2222));
} | identifier_body |
token.rs | DotDotDot,
Comma,
Semi,
Colon,
ModSep,
RArrow,
LArrow,
FatArrow,
Pound,
Dollar,
Question,
/// An opening delimeter, eg. `{`
OpenDelim(DelimToken),
/// A closing delimeter, eg. `}`
CloseDelim(DelimToken),
/* Literals */
LitByte(ast::Name),
LitChar(... | /* Structural symbols */
At,
Dot,
DotDot, | random_line_split | |
token.rs | * carry, and don't really want to allocate a new ident for
// them. Instead, users could extract that from the associated span.
/// Whitespace
Whitespace,
/// Comment
Comment,
Shebang(ast::Name),
Eof,
}
impl Token {
/// Returns `true` if the token can appear at the start of an express... |
/// Returns `true` if the token is an interpolated path.
pub fn is_path(&self) -> bool {
match *self {
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is a path that is not followed by a `::`
//... | {
match *self {
Ident(_, _) => true,
_ => false,
}
} | identifier_body |
token.rs | {
/// `::` follows the identifier with no whitespace in-between.
ModName,
Plain,
}
#[allow(non_camel_case_types)]
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
pub enum Token {
/* Expression-operator symbols. */
Eq,
Lt,
Le,
EqEq,
Ne,
Ge,
Gt,
AndAnd... | IdentStyle | identifier_name | |
release_activity_updater.rs | use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn update_release_activity() -> Result<()> {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::w... | let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
... | random_line_split | |
release_activity_updater.rs | use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn | () -> Result<()> {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
let rows = conn.query(
&format!(
"SELECT COUNT(*)
... | update_release_activity | identifier_name |
release_activity_updater.rs | use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn update_release_activity() -> Result<()> | "SELECT COUNT(*)
FROM releases
WHERE is_library = TRUE AND
build_status = FALSE AND
release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
... | {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases... | identifier_body |
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::ha... | <K,V> {
entries: Vec<Option<(K,V)>>,
k0: u64,
k1: u64,
}
impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> {
pub fn new(cache_size: usize) -> SimpleHashCache<K,V> {
let mut r = rand::thread_rng();
SimpleHashCache {
entries: repeat(None).take(cache_size).collect(),
... | SimpleHashCache | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.