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 |
|---|---|---|---|---|
cmd.rs | use types::{ToRedisArgs, FromRedisValue, Value, RedisResult,
ErrorKind, from_redis_value};
use connection::ConnectionLike;
#[derive(Clone)]
enum Arg<'a> {
Simple(Vec<u8>),
Cursor,
Borrowed(&'a [u8]),
}
/// Represents redis commands.
#[derive(Clone)]
pub struct Cmd {
args: Vec<Arg<'static>... |
/// Instructs the pipeline to ignore the return value of this command.
/// It will still be ensured that it is not an error, but any successful
/// result is just thrown away. This makes result processing through
/// tuples much easier because you do not need to handle all the items
/// you do no... | {
{
let cmd = self.get_last_command();
cmd.arg(arg);
}
self
} | identifier_body |
cmd.rs | use types::{ToRedisArgs, FromRedisValue, Value, RedisResult,
ErrorKind, from_redis_value};
use connection::ConnectionLike;
#[derive(Clone)]
enum Arg<'a> {
Simple(Vec<u8>),
Cursor,
Borrowed(&'a [u8]),
}
/// Represents redis commands.
#[derive(Clone)]
pub struct Cmd {
args: Vec<Arg<'static>... | (&mut self, cmd: &Cmd) -> &mut Pipeline {
self.commands.push(cmd.clone());
self
}
#[inline]
fn get_last_command(&mut self) -> &mut Cmd {
let idx = match self.commands.len() {
0 => panic!("No command on stack"),
x => x - 1,
};
&mut self.command... | add_command | identifier_name |
cmd.rs | use types::{ToRedisArgs, FromRedisValue, Value, RedisResult,
ErrorKind, from_redis_value};
use connection::ConnectionLike;
#[derive(Clone)]
enum Arg<'a> {
Simple(Vec<u8>),
Cursor,
Borrowed(&'a [u8]),
}
/// Represents redis commands.
#[derive(Clone)]
pub struct Cmd {
args: Vec<Arg<'static>... | /// .cmd("GET").arg("key_1")
/// .cmd("GET").arg("key_2").query(&con).unwrap();
/// ```
#[inline]
pub fn query<T: FromRedisValue>(&self, con: &ConnectionLike) -> RedisResult<T> {
from_redis_value(&(
if self.commands.len() == 0 {
Value::Bulk(vec![])
... | /// .cmd("SET").arg("key_1").arg(42).ignore()
/// .cmd("SET").arg("key_2").arg(43).ignore() | random_line_split |
palettesort.rs | use ::color::Color;
/// Sort neighboring colors in the image to be neighbors in the palette as well.
///
/// Fairly silly and useless, but makes the palette (especially of ordered dithered images)
/// look a lot more tidy.
pub fn sort_palette(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) {
let nu... | let mut available: Vec<usize> = (0..num_colors).filter(|&i| i!= best_index).collect();
let mut prev_index = best_index;
while available.len() > 0 {
let mut best_index = available[0];
let mut best_count = 0;
for &index in &available {
let count = neighbors[prev_index][inde... | mapping.push(best_index); | random_line_split |
palettesort.rs | use ::color::Color;
/// Sort neighboring colors in the image to be neighbors in the palette as well.
///
/// Fairly silly and useless, but makes the palette (especially of ordered dithered images)
/// look a lot more tidy.
pub fn sort_palette(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) {
let nu... |
}
mapping.push(best_index);
let mut available: Vec<usize> = (0..num_colors).filter(|&i| i!= best_index).collect();
let mut prev_index = best_index;
while available.len() > 0 {
let mut best_index = available[0];
let mut best_count = 0;
for &index in &available {
l... | {
best_index = index;
best_count = count;
} | conditional_block |
palettesort.rs | use ::color::Color;
/// Sort neighboring colors in the image to be neighbors in the palette as well.
///
/// Fairly silly and useless, but makes the palette (especially of ordered dithered images)
/// look a lot more tidy.
pub fn sort_palette(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) | }
}
mapping.push(best_index);
let mut available: Vec<usize> = (0..num_colors).filter(|&i| i!= best_index).collect();
let mut prev_index = best_index;
while available.len() > 0 {
let mut best_index = available[0];
let mut best_count = 0;
for &index in &available {
... | {
let num_colors = palette.len();
let mut counts: Vec<usize> = (0..num_colors).map(|_| 0).collect();
let mut neighbors: Vec<Vec<usize>> =
(0..num_colors).map(|_| (0..num_colors).map(|_| 0).collect()).collect();
let mut last_index = 0;
for &index in image {
let index = index as usize;... | identifier_body |
palettesort.rs | use ::color::Color;
/// Sort neighboring colors in the image to be neighbors in the palette as well.
///
/// Fairly silly and useless, but makes the palette (especially of ordered dithered images)
/// look a lot more tidy.
pub fn | (palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) {
let num_colors = palette.len();
let mut counts: Vec<usize> = (0..num_colors).map(|_| 0).collect();
let mut neighbors: Vec<Vec<usize>> =
(0..num_colors).map(|_| (0..num_colors).map(|_| 0).collect()).collect();
let mut last_index =... | sort_palette | identifier_name |
shape_intrinsic_tag_then_rec.rs | // xfail-fast
// 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
// <... |
struct X { sp: Span, path: path }
pub fn main() {
let sp: Span = Span {lo: 57451u, hi: 57542u, expanded_from: os_none};
let t: @ty = @Spanned { data: 3u, span: sp };
let p_: Path_ = Path_ { global: true, idents: ~[~"hi"], types: ~[t] };
let p: path = Spanned { data: p_, span: sp };
let x = X { sp:... | type path = Spanned<Path_>;
type ty = Spanned<ty_>; | random_line_split |
shape_intrinsic_tag_then_rec.rs | // xfail-fast
// 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
// <... | { sp: Span, path: path }
pub fn main() {
let sp: Span = Span {lo: 57451u, hi: 57542u, expanded_from: os_none};
let t: @ty = @Spanned { data: 3u, span: sp };
let p_: Path_ = Path_ { global: true, idents: ~[~"hi"], types: ~[t] };
let p: path = Spanned { data: p_, span: sp };
let x = X { sp: sp, path... | X | identifier_name |
mod.rs | use bytecode::{ByteCodeModule};
use bytecode::function::{ByteCodeFunction};
mod emptyblocks;
mod unusedfunctions;
mod returnvalueoptimization;
use self::emptyblocks::remove_empty_blocks;
use self::unusedfunctions::eliminate_unused_functions;
use self::returnvalueoptimization::return_value_optimization;
#[derive(Clon... | for func in module.functions.values_mut() {
if!func.external {
optimize_function(func, lvl);
}
}
}
#[cfg(test)]
mod test
{
use super::*;
use bytecode::test::generate_byte_code;
use bytecode::instruction::Instruction;
use bytecode::function::ByteCodeFunction;
use ... | pub fn optimize_module(module: &mut ByteCodeModule, lvl: OptimizationLevel)
{
eliminate_unused_functions(module);
return_value_optimization(module); | random_line_split |
mod.rs | use bytecode::{ByteCodeModule};
use bytecode::function::{ByteCodeFunction};
mod emptyblocks;
mod unusedfunctions;
mod returnvalueoptimization;
use self::emptyblocks::remove_empty_blocks;
use self::unusedfunctions::eliminate_unused_functions;
use self::returnvalueoptimization::return_value_optimization;
#[derive(Clon... |
}
}
#[cfg(test)]
mod test
{
use super::*;
use bytecode::test::generate_byte_code;
use bytecode::instruction::Instruction;
use bytecode::function::ByteCodeFunction;
use ast::{sig, Type};
use span::Span;
#[test]
fn test_block_elimination()
{
let func_sig = sig("foo", Typ... | {
optimize_function(func, lvl);
} | conditional_block |
mod.rs | use bytecode::{ByteCodeModule};
use bytecode::function::{ByteCodeFunction};
mod emptyblocks;
mod unusedfunctions;
mod returnvalueoptimization;
use self::emptyblocks::remove_empty_blocks;
use self::unusedfunctions::eliminate_unused_functions;
use self::returnvalueoptimization::return_value_optimization;
#[derive(Clon... | (module: &mut ByteCodeModule, lvl: OptimizationLevel)
{
eliminate_unused_functions(module);
return_value_optimization(module);
for func in module.functions.values_mut() {
if!func.external {
optimize_function(func, lvl);
}
}
}
#[cfg(test)]
mod test
{
use super::*;
use... | optimize_module | identifier_name |
str_suffix.rs | #![allow(unused)]
use std::{mem, str};
/// Str-like type where the first 0-2 bytes may point into a UTF-8 characters but all bytes
/// following those are guaranteed to represent a valid UTF-8 string (`str`). Relying on this
/// property we can iterate over the `StrSuffix` byte-by-byte as we would on a `[u8]` without... | (&self) -> &[u8] {
&self.0
}
pub fn iter(&self) -> Iter {
Iter(self)
}
}
pub struct Iter<'a>(&'a StrSuffix);
impl<'a> Iterator for Iter<'a> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
if let Some((b, rest)) = self.0.split_first() {
self.0 = rest;
... | as_bytes | identifier_name |
str_suffix.rs | #![allow(unused)]
use std::{mem, str};
/// Str-like type where the first 0-2 bytes may point into a UTF-8 characters but all bytes
/// following those are guaranteed to represent a valid UTF-8 string (`str`). Relying on this
/// property we can iterate over the `StrSuffix` byte-by-byte as we would on a `[u8]` without... |
pub fn split_first(&self) -> Option<(u8, &Self)> {
if self.is_empty() {
None
} else {
Some((self.0[0], self.suffix(1)))
}
}
pub fn try_as_str(&self) -> Option<&str> {
self.get(0)
}
fn get(&self, index: usize) -> Option<&str> {
if se... | {
self.0.first().cloned()
} | identifier_body |
str_suffix.rs | #![allow(unused)]
use std::{mem, str};
/// Str-like type where the first 0-2 bytes may point into a UTF-8 characters but all bytes
/// following those are guaranteed to represent a valid UTF-8 string (`str`). Relying on this
/// property we can iterate over the `StrSuffix` byte-by-byte as we would on a `[u8]` without... |
fn bytes_prefix(&self) -> &[u8] {
for i in 0..(self.len().min(3)) {
if Self::is_char_boundary_byte(self.0[i]) {
return &self.0[..i];
}
}
&self.0[..0]
}
pub fn restore_char(&self, prefix: &[u8]) -> char {
assert!(prefix.len() <= 4);
... | } | random_line_split |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... | () {
let slice: &[T] = &[0xffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 4294967295);
}
}
| as_unsigned_test1 | identifier_name |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... |
}
| {
let slice: &[T] = &[0xffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 4294967295);
} | identifier_body |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... | // }
// }
// impl_int_slices! { u32, i32 }
type U = u32;
type S = i32;
type T = S;
#[test]
#[allow(overflowing_literals)]
fn as_unsigned_test1() {
let slice: &[T] = &[0xffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 4294967295);
}
} | // impl_int_slice! { $u, $s, $u }
// impl_int_slice! { $u, $s, $s } | random_line_split |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... |
#[rustversion::beta]
fn rename_beta_stderr(from: impl AsRef<Path>, to: impl AsRef<Path>) -> io::Result<()> {
fs::copy(from, to)?;
Ok(())
}
#[rustversion::not(beta)]
fn rename_beta_stderr(_: impl AsRef<Path>, _: impl AsRef<Path>) -> io::Result<()> {
Ok(())
}
| {
for entry in WalkDir::new(path) {
let entry = entry?;
if entry.path().extension().and_then(OsStr::to_str) == Some("beta") {
let renamed = entry.path().with_extension("");
// Unconditionally remove a corresponding `.stderr` file for a `.stderr.beta`
// file if ... | identifier_body |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... | (_: impl AsRef<Path>, _: impl AsRef<Path>) -> io::Result<()> {
Ok(())
}
| rename_beta_stderr | identifier_name |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... |
rename_beta_stderr(entry.path(), renamed)?;
}
}
Ok(())
}
#[rustversion::beta]
fn rename_beta_stderr(from: impl AsRef<Path>, to: impl AsRef<Path>) -> io::Result<()> {
fs::copy(from, to)?;
Ok(())
}
#[rustversion::not(beta)]
fn rename_beta_stderr(_: impl AsRef<Path>, _: impl AsRef... | {
fs::remove_file(&renamed)?;
} | conditional_block |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... | //
// The approach we use is to run the test on all compilers, but only check stderr
// output on beta (which is the next stable release). We do this by default ignoring
// any `.stderr` files in the `compile-fail` directory, and copying `.stderr.beta` files
// when we happen to be running on a beta compiler.
fn prepa... | // having some message to check makes sure user-facing errors are sensical. | random_line_split |
common.rs | use std::{
borrow::Cow,
collections::HashMap,
};
use parse_wiki_text::Node;
use crate::{Parameters, OtherTemplate};
// Why? Because MediaWiki (and thus Wikipedia) titles are case-sensitive in all
// but the first character.
pub fn uppercase_first_letter(string: &str) -> Cow<'_, str> {
if let Some(first_c... | }
fn remove_final_utc(timestamp: &str) -> &str {
if timestamp.ends_with(" (UTC)") {
×tamp[..timestamp.len() - 6]
} else {
timestamp
}
}
pub fn fuzzy_parse_timestamp(timestamp: &str) -> Result<chrono::naive::NaiveDateTime, dtparse::ParseError> {
dtparse::parse(remove_final_utc(time... | } | random_line_split |
common.rs | use std::{
borrow::Cow,
collections::HashMap,
};
use parse_wiki_text::Node;
use crate::{Parameters, OtherTemplate};
// Why? Because MediaWiki (and thus Wikipedia) titles are case-sensitive in all
// but the first character.
pub fn uppercase_first_letter(string: &str) -> Cow<'_, str> {
if let Some(first_c... |
pub fn fuzzy_parse_timestamp(timestamp: &str) -> Result<chrono::naive::NaiveDateTime, dtparse::ParseError> {
dtparse::parse(remove_final_utc(timestamp)).map(|(date, _time)| date)
}
pub fn make_map(params: &[(&str, &str)]) -> HashMap<String, String> {
params.iter().map(|(k, v)| (k.to_string(), v.to_string()))... | {
if timestamp.ends_with(" (UTC)") {
×tamp[..timestamp.len() - 6]
} else {
timestamp
}
} | identifier_body |
common.rs | use std::{
borrow::Cow,
collections::HashMap,
};
use parse_wiki_text::Node;
use crate::{Parameters, OtherTemplate};
// Why? Because MediaWiki (and thus Wikipedia) titles are case-sensitive in all
// but the first character.
pub fn uppercase_first_letter(string: &str) -> Cow<'_, str> {
if let Some(first_c... | <'a, 'b>(template: &'a OtherTemplate, key1: impl Into<Cow<'b, str>>) -> &'a str {
template.named.get(key1.into().as_ref()).map_or("", String::as_ref).trim()
}
#[derive(Clone, Copy)]
pub enum WikitextTransform { RequirePureText, GetTextContent, KeepMarkup }
pub fn nodes_to_text<'a>(nodes: &[Node<'a>], transform: W... | get_template_param | identifier_name |
interop_xz_encode.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
| use xz2::stream;
fn encode_xz_lzmars(x: &[u8]) -> Result<Vec<u8>> {
let mut compressed: Vec<u8> = Vec::new();
lzma_rs::xz_compress(&mut std::io::BufReader::new(x), &mut compressed)?;
Ok(compressed)
}
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
... | use lzma_rs::error::Result;
use std::io::Read; | random_line_split |
interop_xz_encode.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn encode_xz_lzmars(x: &[u8]) -> Result<Vec<u8>> {
let mut compressed: Vec<u8> = Vec::new();
lzma_rs::xz_compress(&mut std::io::BufReader::new(x), &mut compressed)?;
Ok(compressed)
}
fn | (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 * 1024 * 1024, stre... | decode_xz_xz2 | identifier_name |
interop_xz_encode.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn encode_xz_lzmars(x: &[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 compressed: Vec<u8> = Vec::new();
lzma_rs::xz_compress(&mut std::io::BufReader::new(x), &mut compressed)?;
Ok(compressed)
} | identifier_body |
select.rs | use iterator_type::IteratorType;
use rmpv::Value;
use utils::serialize;
use request_type_key::RequestTypeKey;
use code::Code;
use action::Action;
#[derive(Debug)]
pub struct Select {
pub space: u64,
pub index: u64,
pub limit: u64,
pub offset: u64,
pub iterator: IteratorType,
pub keys: Vec<Value... |
}
| {
(RequestTypeKey::Select,
serialize(Value::Map(vec![(Value::from(Code::SpaceId as u8), Value::from(self.space)),
(Value::from(Code::IndexId as u8), Value::from(self.index)),
(Value::from(Code::Limit as u8), Value::from(self.limit)),... | identifier_body |
select.rs | use iterator_type::IteratorType;
use rmpv::Value;
use utils::serialize;
use request_type_key::RequestTypeKey;
use code::Code;
use action::Action;
#[derive(Debug)]
pub struct Select {
pub space: u64,
pub index: u64,
pub limit: u64,
pub offset: u64,
pub iterator: IteratorType,
pub keys: Vec<Value... | (&self) -> (RequestTypeKey, Vec<u8>) {
(RequestTypeKey::Select,
serialize(Value::Map(vec![(Value::from(Code::SpaceId as u8), Value::from(self.space)),
(Value::from(Code::IndexId as u8), Value::from(self.index)),
(Value::from(Code::Li... | get | identifier_name |
select.rs | use iterator_type::IteratorType;
use rmpv::Value;
use utils::serialize; | use code::Code;
use action::Action;
#[derive(Debug)]
pub struct Select {
pub space: u64,
pub index: u64,
pub limit: u64,
pub offset: u64,
pub iterator: IteratorType,
pub keys: Vec<Value>,
}
impl Action for Select {
fn get(&self) -> (RequestTypeKey, Vec<u8>) {
(RequestTypeKey::Selec... | use request_type_key::RequestTypeKey; | random_line_split |
slog.rs | use slog::{self, info, o, warn, Drain};
fn main() | info!(root, "test info log {}", "key1"; "log-key" => true);
warn!(root, "a warning, no color!");
}
| {
let decorator = slog_term::TermDecorator::new().build();
let drain_full = slog_term::FullFormat::new(decorator)
.use_file_location()
.use_original_order()
.build()
.fuse();
let drain_full = slog_async::Async::new(drain_full).build().fuse();
let root = slog::Logger::root... | identifier_body |
slog.rs | use slog::{self, info, o, warn, Drain};
fn | () {
let decorator = slog_term::TermDecorator::new().build();
let drain_full = slog_term::FullFormat::new(decorator)
.use_file_location()
.use_original_order()
.build()
.fuse();
let drain_full = slog_async::Async::new(drain_full).build().fuse();
let root = slog::Logger::root(... | main | identifier_name |
slog.rs | use slog::{self, info, o, warn, Drain};
fn main() {
let decorator = slog_term::TermDecorator::new().build();
let drain_full = slog_term::FullFormat::new(decorator)
.use_file_location()
.use_original_order() | let drain_full = slog_async::Async::new(drain_full).build().fuse();
let root = slog::Logger::root(drain_full, o!("key1" => "value1", "key2" => "value2"));
info!(root, "test info log {}", "key1"; "log-key" => true);
warn!(root, "a warning!");
std::thread::sleep(std::time::Duration::from_millis(10));... | .build()
.fuse(); | random_line_split |
TestLgamma.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 app... | return lgamma(inV);
}
float2 __attribute__((kernel)) testLgammaFloat2Float2(float2 inV) {
return lgamma(inV);
}
float3 __attribute__((kernel)) testLgammaFloat3Float3(float3 inV) {
return lgamma(inV);
}
float4 __attribute__((kernel)) testLgammaFloat4Float4(float4 inV) {
return lgamma(inV);
}
rs_alloca... | float __attribute__((kernel)) testLgammaFloatFloat(float inV) { | random_line_split |
union-smoke.rs | // min-lldb-version: 310
// ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155 | // === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print u
// gdbg-check:$1 = {a = {__0 = 2 '\002', __1 = 2 '\002'}, b = 514}
// gdbr-check:$1 = union_smoke::U {a: (2, 2), b: 514}
// gdb-command:print union_smoke::SU
// gdbg-check:$2 =... |
// ignore-gdb-version: 7.11.90 - 7.12.9
// compile-flags:-g
| random_line_split |
union-smoke.rs | // min-lldb-version: 310
// ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// ignore-gdb-version: 7.11.90 - 7.12.9
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:pr... | () {()}
| zzz | identifier_name |
union-smoke.rs | // min-lldb-version: 310
// ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// ignore-gdb-version: 7.11.90 - 7.12.9
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:pr... | {()} | identifier_body | |
struct_with_anon_struct_pointer.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo {
pub bar: *mut foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 ... | () {
assert_eq!(
::std::mem::size_of::<foo__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(foo__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<foo__bindgen_ty_1>(),
4usize,
concat!("Alignment of ", stringify!(foo__bindgen_ty_1))
);
asse... | bindgen_test_layout_foo__bindgen_ty_1 | identifier_name |
struct_with_anon_struct_pointer.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo {
pub bar: *mut foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 ... | stringify!(a)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<foo__bindgen_ty_1>())).b as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(foo__bindgen_ty_1),
"::",
stringify!(b)... | {
assert_eq!(
::std::mem::size_of::<foo__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(foo__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<foo__bindgen_ty_1>(),
4usize,
concat!("Alignment of ", stringify!(foo__bindgen_ty_1))
);
assert_... | identifier_body |
struct_with_anon_struct_pointer.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo {
pub bar: *mut foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 ... | concat!(
"Offset of field: ",
stringify!(foo__bindgen_ty_1),
"::",
stringify!(a)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<foo__bindgen_ty_1>())).b as *const _ as usize
},
4usize,
concat!(
... | random_line_split | |
manticore_protocol_cerberus_KeyExchange__req_to_wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//!! DO NOT EDIT!!
// To regenerate this file, run `fuzz/generate_proto_tests.py`.
#![no_main]
#![allow(non_snake_case)]
use libfuzzer_sys::fuzz_target;
use manticore... |
fuzz_target!(|data: AsStatic<'static, Req<'static>>| {
let mut out = [0u8; 1024];
let _ = Req::borrow(&data).to_wire(&mut &mut out[..]);
}); |
use manticore::protocol::cerberus::KeyExchange as C;
type Req<'a> = <C as Command<'a>>::Req; | random_line_split |
rtcpeerconnectioniceevent.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::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (&self) -> Option<DOMString> {
self.url.clone()
}
/// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| GetUrl | identifier_name |
rtcpeerconnectioniceevent.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::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
/// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
self.url.clone()
} | identifier_body |
rtcpeerconnectioniceevent.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::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::globalscope::GlobalScope;
use crate::dom::rtcicecandidate::RTCIceCandidate;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct RTCPeerConnectionIceEvent {
event: Event,
... | use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{Dom, DomRoot}; | random_line_split |
error.rs | #[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Couldn't find or open file: {}",.0)]
FileNotFound(String),
#[error("Error while building path: {}",.0)]
InvalidPath(String), | /// Any errors regarding the certificate setup.
#[error("Invalid or malformed certificate: {}",.0)]
CertificateFailure(String),
#[error("{}",.0)]
Connection(String),
#[error("Got an empty payload")]
EmptyPayload,
#[error("Couldn't deserialize message:\n{}",.0)]
MessageDeserializat... | random_line_split | |
error.rs | #[derive(thiserror::Error, Debug)]
pub enum | {
#[error("Couldn't find or open file: {}",.0)]
FileNotFound(String),
#[error("Error while building path: {}",.0)]
InvalidPath(String),
/// Any errors regarding the certificate setup.
#[error("Invalid or malformed certificate: {}",.0)]
CertificateFailure(String),
#[error("{}",.0)]
... | Error | identifier_name |
issue-17662.rs | //
// 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.
// aux-build:iss... | // 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. | random_line_split | |
issue-17662.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> uint { 5_usize }
}
pub fn main() {
assert_eq!(i::foo(&Bar { m: marker::PhantomData }), 5);
}
| foo | identifier_name |
play_card.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use runes::play_minion::PlayMinion;
use runes::set_mana::SetMana;
use hlua;
// the play_minion rune is called when you play a minion
// out of your hand. It will call battle_cry if it has one
// and it will remove the card f... |
fn to_json(&self) -> String {
json::encode(self).unwrap().replace("{", "{\"runeType\":\"PlayCard\",")
}
fn into_box(&self) -> Box<Rune> {
Box::new(self.clone())
}
}
| {
return true;
} | identifier_body |
play_card.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use runes::play_minion::PlayMinion;
use runes::set_mana::SetMana;
use hlua;
// the play_minion rune is called when you play a minion
// out of your hand. It will call battle_cry if it has one
// and it will remove the card f... | (card_uid: UID,
controller_uid: UID,
field_index: usize,
target_uid: UID)
-> PlayCard {
PlayCard {
card_uid: card_uid,
controller_uid: controller_uid,
field_index: field_index,
target_uid: target_uid,
... | new | identifier_name |
play_card.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use runes::play_minion::PlayMinion;
use runes::set_mana::SetMana;
use hlua;
// the play_minion rune is called when you play a minion
// out of your hand. It will call battle_cry if it has one
// and it will remove the card f... | fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool {
return true;
}
fn to_json(&self) -> String {
json::encode(self).unwrap().replace("{", "{\"runeType\":\"PlayCard\",")
}
fn into_box(&self) -> Box<Rune> {
Box::new(self.clone())
}
} |
game_state.stage_rune(Box::new(pm));
}
| random_line_split |
main.rs |
use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
c... |
}
Spinlock { buffer }
}
fn get_value_after(&self, value: usize) -> Option<usize> {
if let Some((idx, _)) = self.buffer.iter().enumerate().find(
|&(_idx, val)| *val == value,
)
{
let pos = (idx + 1) % self.buffer.len();
self.buffer.i... | {
println!("*** {}", i);
} | conditional_block |
main.rs |
use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
c... | () {
let lock = Spinlock::new(3, 3);
assert_eq!(vec![0, 2, 3, 1], lock.buffer);
let lock = Spinlock::new(3, 2017);
println!("{:?}", lock.buffer);
assert_eq!(Some(638), lock.get_value_after(2017));
}
#[test]
fn spinlock_special_case_test() {
assert_eq!(Som... | spinlock_test | identifier_name |
main.rs | use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
cu... | lock_len += 1;
}
val
}
fn main() {
let mut args = env::args();
args.next();
let step_size = args.next().expect("missing argument").parse().expect(
"parse error",
);
let lock = Spinlock::new(step_size, 2017);
println!(
"Short lock: The value right after 2017... |
if curr_pos == 1 {
val = Some(i);
}
| random_line_split |
main.rs |
use std::env;
struct Spinlock {
buffer: Vec<usize>,
}
impl Spinlock {
fn new(step_size: usize, num_insertions: usize) -> Spinlock {
let mut buffer = Vec::with_capacity(num_insertions + 1);
buffer.push(0);
let mut curr_pos = 0;
for i in 1..(num_insertions + 1) {
c... |
fn main() {
let mut args = env::args();
args.next();
let step_size = args.next().expect("missing argument").parse().expect(
"parse error",
);
let lock = Spinlock::new(step_size, 2017);
println!(
"Short lock: The value right after 2017 is {}.",
lock.get_value_after(... | {
let mut val = None;
let mut curr_pos = 0;
let mut lock_len = 1;
for i in 1..(num_insertions + 1) {
curr_pos = (curr_pos + step_size) % lock_len + 1;
if curr_pos == 1 {
val = Some(i);
}
lock_len += 1;
}
val
} | identifier_body |
file_reading.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::domexception::DOMErrorName;
use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaDa... | (&self) -> FileReadingTaskSource {
FileReadingTaskSource(self.0.clone(), self.1.clone())
}
}
impl TaskSource for FileReadingTaskSource {
const NAME: TaskSourceName = TaskSourceName::FileReading;
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
) ->... | clone | identifier_name |
file_reading.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaData};
use msg::constellation_msg::PipelineId;
use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory, ScriptChan};
use std::sync::Arc;
use task::{TaskCanceller, TaskOnce};
use task_source::{TaskSource, TaskSourceName};
#[derive(JSTrac... | * 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::domexception::DOMErrorName; | random_line_split |
file_reading.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::domexception::DOMErrorName;
use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaDa... |
}
impl TaskOnce for FileReadingTask {
fn run_once(self) {
self.handle_task();
}
}
#[allow(dead_code)]
pub enum FileReadingTask {
ProcessRead(TrustedFileReader, GenerationId),
ProcessReadData(TrustedFileReader, GenerationId),
ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName),... | {
self.0.send(CommonScriptMsg::Task(
ScriptThreadEventCategory::FileRead,
Box::new(canceller.wrap_task(task)),
Some(self.1),
))
} | identifier_body |
errors.rs | #![allow(unknown_lints)]
use crate::core::{TargetKind, Workspace};
use crate::ops::CompileOptions;
use anyhow::Error;
use std::fmt;
use std::path::PathBuf;
use std::process::{ExitStatus, Output};
use std::str;
pub type CargoResult<T> = anyhow::Result<T>;
// TODO: should delete this trait and just use `with_context` ... |
pub fn code(code: i32) -> CliError {
CliError {
error: None,
exit_code: code,
}
}
}
impl From<anyhow::Error> for CliError {
fn from(err: anyhow::Error) -> CliError {
CliError::new(err, 101)
}
}
impl From<clap::Error> for CliError {
fn from(err: cla... | {
CliError {
error: Some(error),
exit_code: code,
}
} | identifier_body |
errors.rs | #![allow(unknown_lints)]
use crate::core::{TargetKind, Workspace};
use crate::ops::CompileOptions;
use anyhow::Error;
use std::fmt;
use std::path::PathBuf;
use std::process::{ExitStatus, Output};
use std::str;
pub type CargoResult<T> = anyhow::Result<T>;
// TODO: should delete this trait and just use `with_context` ... | pub type CliResult = Result<(), CliError>;
#[derive(Debug)]
/// The CLI error is the error type used at Cargo's CLI-layer.
///
/// All errors from the lib side of Cargo will get wrapped with this error.
/// Other errors (such as command-line argument validation) will create this
/// directly.
pub struct CliError {
... | // =============================================================================
// CLI errors
| random_line_split |
errors.rs | #![allow(unknown_lints)]
use crate::core::{TargetKind, Workspace};
use crate::ops::CompileOptions;
use anyhow::Error;
use std::fmt;
use std::path::PathBuf;
use std::process::{ExitStatus, Output};
use std::str;
pub type CargoResult<T> = anyhow::Result<T>;
// TODO: should delete this trait and just use `with_context` ... | (&self) -> ManifestCauses<'_> {
ManifestCauses { current: self }
}
}
impl std::error::Error for ManifestError {
fn source(&self) -> Option<&(dyn std::error::Error +'static)> {
self.cause.source()
}
}
impl fmt::Debug for ManifestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::... | manifest_causes | identifier_name |
expr.rs | // Expressions
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later ... | (&self) -> Prec {
match *self {
Expr::Id (ref i) => i.prec(),
Expr::Int (ref i) => i.prec(),
Expr::Reg (ref r) => r.prec(),
Expr::Unary (ref u) => u.prec(),
Expr::Binary (ref b) => b.prec(),
Expr::Deref (ref d) => d.prec(),
... | prec | identifier_name |
expr.rs | // Expressions
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later ... |
#[test]
fn fmt_reg() {
let e = Expr::Reg(Reg::new("a"));
let s = format!("{}", e);
assert_eq!(s, "a");
}
}
| {
let e = Expr::Int(Int::from(42));
let s = format!("{}", e);
assert_eq!(s, "0x2A");
} | identifier_body |
expr.rs | // Expressions
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later ... |
#[test]
fn prec() {
let e = Binary::new(
BinaryOp::Add,
Expr::Id(Id::new("a")),
Expr::Id(Id::new("b"))
);
assert_eq!(e.prec(), Prec::Additive);
}
#[test]
fn fmt_id() {
let e = Expr::Id(Id::new("a"));
let s = format!("{}", ... | use super::*; | random_line_split |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% f... | };
dest.write_str(s)
}
}
impl ToComputedValue for SystemColor {
type ComputedValue = u32; // nscolor
#[inline]
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
unsafe {
Gecko_GetLookAndFeelSystemColor(
... | % for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(), | random_line_split |
stack_overflow.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | pub struct Handler {
_data: *mut libc::c_void
}
impl Handler {
pub unsafe fn new() -> Handler {
make_handler()
}
}
impl Drop for Handler {
fn drop(&mut self) {
unsafe {
drop_handler(self);
}
}
}
#[cfg(any(target_os = "linux",
target_os = "macos",
... | pub use self::imp::{init, cleanup};
| random_line_split |
stack_overflow.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (signum: libc::c_int,
info: *mut siginfo,
_data: *mut libc::c_void) {
// We can not return from a SIGSEGV or SIGBUS signal.
// See: https://www.gnu.org/software/libc/manual/html_node/Handler-Returns.html
unsafe fn term(s... | signal_handler | identifier_name |
stack_overflow.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
PAGE_SIZE = psize as uint;
let mut action: sigaction = mem::zeroed();
action.sa_flags = SA_SIGINFO | SA_ONSTACK;
action.sa_sigaction = signal_handler as sighandler_t;
sigaction(SIGSEGV, &action, ptr::null_mut());
sigaction(SIGBUS, &action, ptr::null_mut());
le... | {
panic!("failed to get page size");
} | conditional_block |
generic-tup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// 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.
fn get_third<T>(... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
generic-tup.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 ... | <T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; }
pub fn main() {
info!(get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
}
| get_third | identifier_name |
generic-tup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
info!(get_third((1, 2, 3)));
assert_eq!(get_third((1, 2, 3)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
}
| { let (_, _, x) = t; return x; } | identifier_body |
tests.rs | use rocket::local::Client;
use rocket::http::{Status, ContentType};
use std::io::Read;
use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let mut res = client.get("/").dispatch();
... | {
// Delete the upload file before we begin.
let _ = fs::remove_file("/tmp/upload.txt");
// Do the upload. Make sure we get the expected results.
let client = Client::new(super::rocket()).unwrap();
let mut res = client.post("/upload")
.header(ContentType::Plain)
.body(UPLOAD_CONTENT... | identifier_body | |
tests.rs | use rocket::local::Client;
use rocket::http::{Status, ContentType}; | use std::io::Read;
use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let mut res = client.get("/").dispatch();
assert_eq!(res.body_string(), Some(super::index().to_string()));
}
... | random_line_split | |
tests.rs | use rocket::local::Client;
use rocket::http::{Status, ContentType};
use std::io::Read;
use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let mut res = client.get("/").dispatch();
... | () {
// Delete the upload file before we begin.
let _ = fs::remove_file("/tmp/upload.txt");
// Do the upload. Make sure we get the expected results.
let client = Client::new(super::rocket()).unwrap();
let mut res = client.post("/upload")
.header(ContentType::Plain)
.body(UPLOAD_CONTEN... | test_raw_upload | identifier_name |
cci_no_inline_lib.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 ... | <F>(v: Vec<uint>, mut f: F) where F: FnMut(uint) {
let mut i = 0u;
let n = v.len();
while i < n {
f(v[i]);
i += 1u;
}
}
| iter | identifier_name |
cci_no_inline_lib.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 ... | #![crate_name="cci_no_inline_lib"]
// same as cci_iter_lib, more-or-less, but not marked inline
pub fn iter<F>(v: Vec<uint>, mut f: F) where F: FnMut(uint) {
let mut i = 0u;
let n = v.len();
while i < n {
f(v[i]);
i += 1u;
}
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
cci_no_inline_lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut i = 0u;
let n = v.len();
while i < n {
f(v[i]);
i += 1u;
}
} | identifier_body | |
create.rs | // https://rustbyexample.com/std_misc/file/create.html
// http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html
// $ mkdir out
// $ rustc create.rs &&./create
// $ cat out/lorem_ipsum.txt
// create.rs
static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eius... | use std::path::Path;
fn main() {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// Open a file in write-only mode, returns `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
... | random_line_split | |
create.rs | // https://rustbyexample.com/std_misc/file/create.html
// http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html
// $ mkdir out
// $ rustc create.rs &&./create
// $ cat out/lorem_ipsum.txt
// create.rs
static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eius... | }
| {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// Open a file in write-only mode, returns `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
why.d... | identifier_body |
create.rs | // https://rustbyexample.com/std_misc/file/create.html
// http://rust-lang-ja.org/rust-by-example/std_misc/file/create.html
// $ mkdir out
// $ rustc create.rs &&./create
// $ cat out/lorem_ipsum.txt
// create.rs
static LOREM_IPSUM: &'static str =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eius... | () {
let path = Path::new("out/lorem_ipsum.txt");
let display = path.display();
// Open a file in write-only mode, returns `io::Result<File>`
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
wh... | main | identifier_name |
yield-while-local-borrowed.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 ... |
unsafe fn borrow_local() {
// Not OK to yield with a borrow of a temporary.
//
// (This error occurs because the region shows up in the type of
// `b` and gets extended by region inference.)
let mut b = move || {
let a = 3;
{
let b = &a;
//~^ ERROR borrow ma... | {
// No error here -- `a` is not in scope at the point of `yield`.
let mut b = move || {
{
let a = &mut 3;
}
yield();
};
b.resume();
} | identifier_body |
yield-while-local-borrowed.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 ... | b.resume();
}
unsafe fn borrow_local() {
// Not OK to yield with a borrow of a temporary.
//
// (This error occurs because the region shows up in the type of
// `b` and gets extended by region inference.)
let mut b = move || {
let a = 3;
{
let b = &a;
//~... | yield();
}; | random_line_split |
yield-while-local-borrowed.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 ... | () {
// Not OK to yield with a borrow of a temporary.
//
// (This error occurs because the region shows up in the type of
// `b` and gets extended by region inference.)
let mut b = move || {
let a = &mut 3;
//~^ ERROR borrow may still be in use when generator yields (Ast)
//~... | borrow_local_inline | identifier_name |
thread_pool.rs | use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
enum Message {
NewJob(Job),
Terminate,
}
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
trait FnBox {
fn call_box(self: Box<Self>);
}
impl<F: FnOnce()> FnBox for F {
fn call_box(se... | (&mut self) {
println!("Sending terminate message to all workers.");
for _ in &mut self.workers {
self.sender.send(Message::Terminate).unwrap();
}
println!("Shutting down all workers.");
for worker in &mut self.workers {
println!("Shutting down worker {... | drop | identifier_name |
thread_pool.rs | use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
enum Message {
NewJob(Job),
Terminate,
}
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
trait FnBox {
fn call_box(self: Box<Self>);
}
impl<F: FnOnce()> FnBox for F {
fn call_box(se... |
Message::Terminate => {
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}
| {
job.call_box();
} | conditional_block |
thread_pool.rs | use std::sync::mpsc;
use std::sync::Arc; | enum Message {
NewJob(Job),
Terminate,
}
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
trait FnBox {
fn call_box(self: Box<Self>);
}
impl<F: FnOnce()> FnBox for F {
fn call_box(self: Box<F>) {
(*self)()
}
}
type Job = Box<dyn FnBox + Send +'static... | use std::sync::Mutex;
use std::thread;
| random_line_split |
thread_pool.rs | use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
enum Message {
NewJob(Job),
Terminate,
}
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
trait FnBox {
fn call_box(self: Box<Self>);
}
impl<F: FnOnce()> FnBox for F {
fn call_box(se... |
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send +'static,
{
let job = Box::new(f);
self.sender.send(Message::NewJob(job)).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
println!("Sending terminate message to all workers.");
for _ in... | {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { work... | identifier_body |
with_position.rs | use std::iter::{Fuse,Peekable};
/// An iterator adaptor that wraps each element in an [`Position`](../enum.Position.html).
///
/// Iterator element type is `Position<I::Item>`.
///
/// See [`.with_position()`](../trait.Itertools.html#method.with_position) for more information.
#[must_use = "iterator adaptors are lazy ... |
/// A value yielded by `WithPosition`.
/// Indicates the position of this element in the iterator results.
///
/// See [`.with_position()`](trait.Itertools.html#method.with_position) for more information.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Position<T> {
/// This is the first element.
First(T),
... | {
WithPosition {
handled_first: false,
peekable: iter.fuse().peekable(),
}
} | identifier_body |
with_position.rs | use std::iter::{Fuse,Peekable};
/// An iterator adaptor that wraps each element in an [`Position`](../enum.Position.html).
///
/// Iterator element type is `Position<I::Item>`.
///
/// See [`.with_position()`](../trait.Itertools.html#method.with_position) for more information.
#[must_use = "iterator adaptors are lazy ... | }
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.peekable.size_hint()
}
}
impl<I> ExactSizeIterator for WithPosition<I>
where I: ExactSizeIterator,
{ } | // Iterator is finished.
None => None, | random_line_split |
with_position.rs | use std::iter::{Fuse,Peekable};
/// An iterator adaptor that wraps each element in an [`Position`](../enum.Position.html).
///
/// Iterator element type is `Position<I::Item>`.
///
/// See [`.with_position()`](../trait.Itertools.html#method.with_position) for more information.
#[must_use = "iterator adaptors are lazy ... | (&self) -> (usize, Option<usize>) {
self.peekable.size_hint()
}
}
impl<I> ExactSizeIterator for WithPosition<I>
where I: ExactSizeIterator,
{ }
| size_hint | identifier_name |
type_of.rs | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::named_ty::*;
use middle::subst;
use trans::adt;
use trans::common::*;
use trans::foreign;
use trans::machine;
use middle::ty::{self, RegionEscape, Ty};
use util::ppaux;
u... | }
}
// A "sizing type" is an LLVM type, the size and alignment of which are
// guaranteed to be equivalent to what you would get out of `type_of()`. It's
// useful because:
//
// (1) It may be cheaper to compute the sizing type than the full type if all
// you're interested in is the size and/or alignment;
//
... | random_line_split | |
type_of.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::named_ty::*;
use middle::subst;
use trans::adt;
use trans::common::*;
use trans::foreign;
use trans::machine;
use middle::ty::{self, RegionEscape, Ty};
use util::ppaux;
use... | <'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
what: named_ty,
did: ast::DefId,
tps: &[Ty<'tcx>])
-> String {
let name = match what {
a_struct => "struct",
an_enum => "enum",
... | llvm_type_name | identifier_name |
type_of.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::named_ty::*;
use middle::subst;
use trans::adt;
use trans::common::*;
use trans::foreign;
use trans::machine;
use middle::ty::{self, RegionEscape, Ty};
use util::ppaux;
use... | Some(&llty) => return llty,
None => ()
}
debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty);
assert!(!t.has_escaping_regions());
// Replace any typedef'd types with their equivalent non-typedef
// type. This ensures that all LLVM nominal types that contain
// Rust types are de... | {
fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
// It is possible to end up here with a sized type. This happens with a
// struct which might be unsized, but is monomorphised to a sized type.
// In this case we'll fake a fat pointer with no unsize info ... | identifier_body |
type_of.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::named_ty::*;
use middle::subst;
use trans::adt;
use trans::common::*;
use trans::foreign;
use trans::machine;
use middle::ty::{self, RegionEscape, Ty};
use util::ppaux;
use... |
ty::ty_bool => Type::bool(cx),
ty::ty_char => Type::char(cx),
ty::ty_int(t) => Type::int_from_ty(cx, t),
ty::ty_uint(t) => Type::uint_from_ty(cx, t),
ty::ty_float(t) => Type::float_from_ty(cx, t),
ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty,..}) | ty::ty_ptr(ty::mt{ty,.... | {
cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type",
ppaux::ty_to_string(cx.tcx(), t))[])
} | conditional_block |
reflector.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 syntax::ast;
use syntax::ast::MetaItem;
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtx... | } | random_line_split | |
reflector.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 syntax::ast;
use syntax::ast::MetaItem;
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtx... | impl_item.map(|it| push(Annotatable::Item(it)))
},
// Or just call it on the first field (supertype).
None => {
let field_name = def.fields[0].node.ident();
let impl_item = quote_item!(cx,
... | {
if let &Annotatable::Item(ref item) = annotatable {
if let ast::ItemStruct(ref def, _) = item.node {
let struct_name = item.ident;
// This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time
match def.fields.iter().find(
... | identifier_body |
reflector.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 syntax::ast;
use syntax::ast::MetaItem;
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtx... | (cx: &mut ExtCtxt, span: Span, _: &MetaItem, annotatable: &Annotatable,
push: &mut FnMut(Annotatable)) {
if let &Annotatable::Item(ref item) = annotatable {
if let ast::ItemStruct(ref def, _) = item.node {
let struct_name = item.ident;
// This path has to be h... | expand_reflector | identifier_name |
ub-nonnull.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 ... | {} | identifier_body | |
ub-nonnull.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 ... | struct RestrictedRange1(u32);
const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) };
//~^ ERROR it is undefined behavior to use this value
#[rustc_layout_scalar_valid_range_start(30)]
#[rustc_layout_scalar_valid_range_end(10)]
struct RestrictedRange2(u32);
const BAD_RANGE2: RestrictedRange2 = unsafe { R... | #[rustc_layout_scalar_valid_range_end(30)] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.