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 |
|---|---|---|---|---|
p_2_3_1_01.rs | // P_2_3_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | .color(model.c);
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
model.line_length = random_range(70.0, 200.0);
}
fn key_pressed(_app: &App, model: &mut Model, key: Key) {
match key {
... | random_line_split | |
p_2_3_1_01.rs | // P_2_3_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | Key::Key2 => {
model.c = rgba(0.0, 0.5, 0.64, 1.0);
}
Key::Key3 => {
model.c = rgba(0.34, 0.13, 0.5, 1.0);
}
Key::Key4 => {
model.c = rgba(0.77, 0.0, 0.48, 1.0);
}
_otherkey => (),
}
}
| model.c = rgba(0.7, 0.61, 0.0, 1.0);
}
| conditional_block |
render.rs | use ammonia::Ammonia;
use comrak;
use util::CargoResult;
/// Context for markdown to HTML rendering.
#[allow(missing_debug_implementations)]
pub struct MarkdownRenderer<'a> {
html_sanitizer: Ammonia<'a>,
}
impl<'a> MarkdownRenderer<'a> {
/// Creates a new renderer instance.
pub fn new() -> MarkdownRender... |
#[test]
fn text_with_unknown_tag() {
let text = "foo_readme\n\n<unknown>alert('Hello World')</unknown>";
let result = markdown_to_html(text).unwrap();
assert_eq!(result, "<p>foo_readme</p>\n<p>alert(\'Hello World\')</p>\n");
}
#[test]
fn text_with_inline_javascript() {
... | {
let text = "foo_readme\n\n<iframe>alert('Hello World')</iframe>";
let result = markdown_to_html(text).unwrap();
assert_eq!(
result,
"<p>foo_readme</p>\n<iframe>alert(\'Hello World\')</iframe>\n"
);
} | identifier_body |
render.rs | use ammonia::Ammonia;
use comrak;
use util::CargoResult;
/// Context for markdown to HTML rendering.
#[allow(missing_debug_implementations)]
pub struct MarkdownRenderer<'a> {
html_sanitizer: Ammonia<'a>,
}
impl<'a> MarkdownRenderer<'a> {
/// Creates a new renderer instance.
pub fn new() -> MarkdownRender... | () {
let text = "foo_readme\n\n<unknown>alert('Hello World')</unknown>";
let result = markdown_to_html(text).unwrap();
assert_eq!(result, "<p>foo_readme</p>\n<p>alert(\'Hello World\')</p>\n");
}
#[test]
fn text_with_inline_javascript() {
let text = r#"foo_readme\n\n<a href="... | text_with_unknown_tag | identifier_name |
render.rs | use ammonia::Ammonia;
use comrak;
use util::CargoResult;
/// Context for markdown to HTML rendering.
#[allow(missing_debug_implementations)]
pub struct MarkdownRenderer<'a> {
html_sanitizer: Ammonia<'a>,
}
impl<'a> MarkdownRenderer<'a> {
/// Creates a new renderer instance.
pub fn new() -> MarkdownRender... | "blockquote",
"br",
"code",
"dd",
"del",
"dl",
"dt",
"em",
"h1",
"h2",
"h3",
"hr",
"i",
"img",
"input",
"kbd",
"li",... | "b", | random_line_split |
f13-mkstemp.rs | /// Code for Figure 5.13 (Demonstrate mkstemp function)
///
/// implementation in rust was quite straight forward
/// only caveat was that the pointer to the variable on the stack
/// is not possible (or I just didn't find out how to do that and
/// didn't dare to ask on stackoverflow)
///
/// $ f13-mkstemp 2>/dev/null... | let good_template = CString::new("/tmp/dirXXXXXX").unwrap();
println!("trying to create first temp file...");
let res = make_temp(good_template.into_raw());
print_err!("{:?}", res);
// the second part with the bad template I was just
// unable to do in rust, seems that the type safety
// wa... | identifier_body | |
f13-mkstemp.rs | /// Code for Figure 5.13 (Demonstrate mkstemp function)
///
/// implementation in rust was quite straight forward
/// only caveat was that the pointer to the variable on the stack
/// is not possible (or I just didn't find out how to do that and
/// didn't dare to ask on stackoverflow)
///
/// $ f13-mkstemp 2>/dev/null... | } else {
println!("file exists");
libc::unlink(template);
}
Ok(CString::from_raw(template).into_string().unwrap())
}
}
fn main() {
let good_template = CString::new("/tmp/dirXXXXXX").unwrap();
println!("trying to create first temp file...");
let res = make_... | return Err("stat failed".to_owned());
}
| conditional_block |
f13-mkstemp.rs | /// Code for Figure 5.13 (Demonstrate mkstemp function)
///
/// implementation in rust was quite straight forward
/// only caveat was that the pointer to the variable on the stack
/// is not possible (or I just didn't find out how to do that and
/// didn't dare to ask on stackoverflow) | ///
/// $ f13-mkstemp 2>/dev/null
/// trying to create first temp file...
/// file exists
extern crate libc;
#[macro_use(print_err)]
extern crate apue;
use std::ffi::{CString, CStr};
use std::io;
use std::mem;
fn make_temp(template: *mut libc::c_char) -> Result<String, String> {
unsafe {
let fd = libc::m... | random_line_split | |
f13-mkstemp.rs | /// Code for Figure 5.13 (Demonstrate mkstemp function)
///
/// implementation in rust was quite straight forward
/// only caveat was that the pointer to the variable on the stack
/// is not possible (or I just didn't find out how to do that and
/// didn't dare to ask on stackoverflow)
///
/// $ f13-mkstemp 2>/dev/null... | {
let good_template = CString::new("/tmp/dirXXXXXX").unwrap();
println!("trying to create first temp file...");
let res = make_temp(good_template.into_raw());
print_err!("{:?}", res);
// the second part with the bad template I was just
// unable to do in rust, seems that the type safety
//... | in() | identifier_name |
seal.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 step: Uint,
/// Seal signature.
pub signature: H520,
}
/// Tendermint seal.
#[derive(Debug, PartialEq, Deserialize)]
pub struct TendermintSeal {
/// Seal round.
pub round: Uint,
/// Proposal seal signature.
pub proposal: H520,
/// Proposal seal signature.
pub precommits: Vec<H520>,
}
/// Seal variants.
#... | random_line_split | |
seal.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... | {
/// Seal step.
pub step: Uint,
/// Seal signature.
pub signature: H520,
}
/// Tendermint seal.
#[derive(Debug, PartialEq, Deserialize)]
pub struct TendermintSeal {
/// Seal round.
pub round: Uint,
/// Proposal seal signature.
pub proposal: H520,
/// Proposal seal signature.
pub precommits: Vec<H520>,
}
/... | AuthorityRoundSeal | identifier_name |
issue-22645.rs | // Copyright 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-MIT or ... | let b = Bob + 3.5;
b + 3 //~ ERROR E0277
//~^ ERROR: mismatched types
} | random_line_split | |
issue-22645.rs | // Copyright 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-MIT or ... |
}
fn main() {
let b = Bob + 3.5;
b + 3 //~ ERROR E0277
//~^ ERROR: mismatched types
}
| { Bob } | identifier_body |
issue-22645.rs | // Copyright 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-MIT or ... | (self, rhs : RHS) -> Bob { Bob }
}
fn main() {
let b = Bob + 3.5;
b + 3 //~ ERROR E0277
//~^ ERROR: mismatched types
}
| add | identifier_name |
objdump.rs | extern crate capstone;
extern crate macho;
use capstone::prelude::*;
use std::env;
use std::fs;
use std::io::Read;
use std::process;
fn main() | if segment.segname == "__TEXT" {
for section in segment.sections {
if section.sectname == "__text" {
let text = &buf[section.offset as usize
..(u64::from(section.offset) + section.size) as usize];
match cs.disasm_all(text... | {
let cs = Capstone::new()
.x86()
.mode(arch::x86::ArchMode::Mode64)
.build()
.expect("Failed to create capstone handle");
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("Usage: {} <file>", args[0]);
return;
}
let mut fh = fs... | identifier_body |
objdump.rs | extern crate capstone;
extern crate macho;
use capstone::prelude::*;
use std::env;
use std::fs;
use std::io::Read;
use std::process;
fn | () {
let cs = Capstone::new()
.x86()
.mode(arch::x86::ArchMode::Mode64)
.build()
.expect("Failed to create capstone handle");
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
println!("Usage: {} <file>", args[0]);
return;
}
let mut fh = fs::... | main | identifier_name |
objdump.rs | extern crate capstone;
extern crate macho;
use capstone::prelude::*;
use std::env;
use std::fs;
use std::io::Read;
use std::process;
fn main() {
let cs = Capstone::new()
.x86()
.mode(arch::x86::ArchMode::Mode64)
.build()
.expect("Failed to create capstone handle");
let args: Vec<_... |
let mut fh = fs::File::open(&args[1]).unwrap();
let mut buf: Vec<u8> = Vec::new();
let _ = fh.read_to_end(&mut buf);
let header = macho::MachObject::parse(&buf[..]).unwrap();
// Find the text segment
for segment in header.segments {
if segment.segname == "__TEXT" {
for sec... | {
println!("Usage: {} <file>", args[0]);
return;
} | conditional_block |
simd-intrinsic-float-minmax.rs | // run-pass
// ignore-emscripten
// Test that the simd_f{min,max} intrinsics produce the correct results.
#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct | (pub f32, pub f32, pub f32, pub f32);
extern "platform-intrinsic" {
fn simd_fmin<T>(x: T, y: T) -> T;
fn simd_fmax<T>(x: T, y: T) -> T;
}
fn main() {
let x = f32x4(1.0, 2.0, 3.0, 4.0);
let y = f32x4(2.0, 1.0, 4.0, 3.0);
#[cfg(not(any(target_arch = "mips", target_arch = "mips64")))]
let nan = ... | f32x4 | identifier_name |
simd-intrinsic-float-minmax.rs | // run-pass
// ignore-emscripten
// Test that the simd_f{min,max} intrinsics produce the correct results.
#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);
extern "platform-intrinsic" {... | assert_eq!(minn, y);
let max0 = simd_fmax(x, y);
let max1 = simd_fmax(y, x);
assert_eq!(max0, max1);
let e = f32x4(2.0, 2.0, 4.0, 4.0);
assert_eq!(max0, e);
let maxn = simd_fmax(x, n);
assert_eq!(maxn, x);
let maxn = simd_fmax(y, n);
asser... | let minn = simd_fmin(y, n); | random_line_split |
hashmap-memory.rs |
// Copyright 2012-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-M... | ctrl_clone.send(mapper_done);
}
pub fn map_reduce(inputs: Vec<String>) {
let (tx, rx) = channel();
// This task becomes the master control task. It spawns others
// to do the rest.
let mut reducers: HashMap<String, int>;
reducers = HashMap::new();
st... | {
let mut intermediates = HashMap::new();
fn emit(im: &mut HashMap<String, int>,
ctrl: Sender<ctrl_proto>, key: String,
_val: String) {
if im.contains_key(&key) {
return;
}
let (tx, rx) = channel();
println!... | identifier_body |
hashmap-memory.rs |
// Copyright 2012-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-M... | () {
map_reduce::map_reduce(
vec!("../src/test/run-pass/hashmap-memory.rs".to_string()));
}
| main | identifier_name |
hashmap-memory.rs |
// Copyright 2012-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-M... |
None => { c = 0; }
}
cc.send(c);
}
}
}
}
}
pub fn main() {
map_reduce::map_reduce(
vec!("../src/test/run-pass/hashmap-memory.rs".to_string()));
}
| { c = _c; } | conditional_block |
hashmap-memory.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | println!("sending find_reducer");
ctrl.send(find_reducer(Vec::from_slice(key.as_bytes()), tx));
println!("receiving");
let c = rx.recv();
println!("{:?}", c);
im.insert(key, c);
}
let ctrl_clone = ctrl.clone();
::map(input,... | let (tx, rx) = channel(); | random_line_split |
unsafe-cell-hides-niche.rs | // For rust-lang/rust#68303: the contents of `UnsafeCell<T>` cannot
// participate in the niche-optimization for enum discriminants. This
// test checks that an `Option<UnsafeCell<NonZeroU32>>` has the same
// size in memory as an `Option<UnsafeCell<u32>>` (namely, 8 bytes).
// run-pass
#![feature(no_niche)]
use std... | assert_eq!(size_of::<Option<Transparent<u32>>>(), 8);
assert_eq!(size_of::<Option<Transparent<N32>>>(), 4);
assert_eq!(size_of::<Option<NoNiche<u32>>>(), 8);
assert_eq!(size_of::<Option<NoNiche<N32>>>(), 8);
assert_eq!(size_of::<Option<UnsafeCell<u32>>>(), 8);
assert_eq!(size_of::<Opti... | random_line_split | |
unsafe-cell-hides-niche.rs | // For rust-lang/rust#68303: the contents of `UnsafeCell<T>` cannot
// participate in the niche-optimization for enum discriminants. This
// test checks that an `Option<UnsafeCell<NonZeroU32>>` has the same
// size in memory as an `Option<UnsafeCell<u32>>` (namely, 8 bytes).
// run-pass
#![feature(no_niche)]
use std... | <T>(T);
fn main() {
assert_eq!(size_of::<Option<Wrapper<u32>>>(), 8);
assert_eq!(size_of::<Option<Wrapper<N32>>>(), 4);
assert_eq!(size_of::<Option<Transparent<u32>>>(), 8);
assert_eq!(size_of::<Option<Transparent<N32>>>(), 4);
assert_eq!(size_of::<Option<NoNiche<u32>>>(), 8);
asser... | NoNiche | identifier_name |
haskell_import.rs | extern crate curryrs;
use std::env;
use std::ffi::CStr;
use std::path::Path;
use curryrs::hsrt;
use curryrs::types::*;
#[link(name = "HShtest-0.1.0.0-inplace", kind = "static")]
extern "C" {
pub fn triple(x: I32) -> I32;
pub fn getProgNameStr() -> Str;
}
fn | (x: I32) -> I32 {
hsrt::start();
unsafe { triple(x) }
}
#[test]
fn ffi_test() {
// TODO Use the threaded Haskell runtime to let tests run safely in
// parallel, allowing separate test functions.
assert_eq!(900, triple_num(300));
hsrt::start();
let prog_name = unsafe { getProgNameStr() };
assert!... | triple_num | identifier_name |
haskell_import.rs | extern crate curryrs;
use std::env;
use std::ffi::CStr;
use std::path::Path;
use curryrs::hsrt;
use curryrs::types::*;
#[link(name = "HShtest-0.1.0.0-inplace", kind = "static")]
extern "C" {
pub fn triple(x: I32) -> I32;
pub fn getProgNameStr() -> Str;
}
fn triple_num(x: I32) -> I32 |
#[test]
fn ffi_test() {
// TODO Use the threaded Haskell runtime to let tests run safely in
// parallel, allowing separate test functions.
assert_eq!(900, triple_num(300));
hsrt::start();
let prog_name = unsafe { getProgNameStr() };
assert!(!prog_name.is_null());
let prog_name_str = unsafe { CStr... | {
hsrt::start();
unsafe { triple(x) }
} | identifier_body |
haskell_import.rs | extern crate curryrs;
use std::env;
use std::ffi::CStr;
use std::path::Path;
use curryrs::hsrt;
use curryrs::types::*;
#[link(name = "HShtest-0.1.0.0-inplace", kind = "static")]
extern "C" {
pub fn triple(x: I32) -> I32;
pub fn getProgNameStr() -> Str;
}
fn triple_num(x: I32) -> I32 {
hsrt::start();
unsafe ... | assert!(!prog_name.is_null());
let prog_name_str = unsafe { CStr::from_ptr(prog_name) }.to_str().unwrap();
let argv0 = env::args().nth(0).unwrap();
let argv0_file_name = Path::new(&argv0).file_name().unwrap();
assert_eq!(prog_name_str, argv0_file_name.to_str().unwrap());
} | hsrt::start();
let prog_name = unsafe { getProgNameStr() }; | random_line_split |
test_slice_transform.rs | extern crate rocksdb;
use rocksdb::{DB, Options, SliceTransform};
#[test]
pub fn test_slice_transform() {
let path = "_rust_rocksdb_slicetransform_test";
let a1: Box<[u8]> = key(b"aaa1");
let a2: Box<[u8]> = key(b"aaa2");
let b1: Box<[u8]> = key(b"bbb1");
let b2: Box<[u8]> = key(b"bbb2");
fn... |
fn key(k: &[u8]) -> Box<[u8]> { k.to_vec().into_boxed_slice() }
{
let expected = vec![(cba(&a1), cba(&a1)), (cba(&a2), cba(&a2))];
let a_iterator = db.prefix_iterator(b"aaa");
assert_eq!(a_iterator.collect::<Vec<_>>(), expected)
}
{
let expected = vec![(cba(&b1), cba(... | {
input.iter().cloned().collect::<Vec<_>>().into_boxed_slice()
} | identifier_body |
test_slice_transform.rs | extern crate rocksdb;
use rocksdb::{DB, Options, SliceTransform};
#[test]
pub fn test_slice_transform() {
let path = "_rust_rocksdb_slicetransform_test";
let a1: Box<[u8]> = key(b"aaa1");
let a2: Box<[u8]> = key(b"aaa2");
let b1: Box<[u8]> = key(b"bbb1");
let b2: Box<[u8]> = key(b"bbb2");
fn... | (k: &[u8]) -> Box<[u8]> { k.to_vec().into_boxed_slice() }
{
let expected = vec![(cba(&a1), cba(&a1)), (cba(&a2), cba(&a2))];
let a_iterator = db.prefix_iterator(b"aaa");
assert_eq!(a_iterator.collect::<Vec<_>>(), expected)
}
{
let expected = vec![(cba(&b1), cba(&b1)), (cba(... | key | identifier_name |
test_slice_transform.rs | extern crate rocksdb;
use rocksdb::{DB, Options, SliceTransform};
#[test]
pub fn test_slice_transform() {
let path = "_rust_rocksdb_slicetransform_test";
let a1: Box<[u8]> = key(b"aaa1");
let a2: Box<[u8]> = key(b"aaa2");
let b1: Box<[u8]> = key(b"bbb1");
let b2: Box<[u8]> = key(b"bbb2");
fn... | fn key(k: &[u8]) -> Box<[u8]> { k.to_vec().into_boxed_slice() }
{
let expected = vec![(cba(&a1), cba(&a1)), (cba(&a2), cba(&a2))];
let a_iterator = db.prefix_iterator(b"aaa");
assert_eq!(a_iterator.collect::<Vec<_>>(), expected)
}
{
let expected = vec![(cba(&b1), cba(&b... | random_line_split | |
named_lifetime_parameters.rs | #![allow(warnings)]
// **Exercise 1.** Modify the signature of `get` to use an explicit
// lifetime name in the return type.
//
// **Exercise 2.** Change the signature of `get` to:
//
// fn get<'a>(&'a mut self, key: &'a K) -> Option<&'a V>
//
// - Which test fails to compile?
// - Can you explain why?
//
// **Exe... | () {
let mut map = Map::new();
map.insert('a', format!("alpha"));
map.insert('b', format!("beta"));
map.insert('g', format!("gamma"));
assert_eq!(map.get(&'a'), Some(&format!("alpha")));
assert_eq!(map.get(&'b'), Some(&format!("beta")));
assert_eq!(map.get(&'g'), Some(&format!("gamma")));
... | basic | identifier_name |
named_lifetime_parameters.rs | #![allow(warnings)]
// **Exercise 1.** Modify the signature of `get` to use an explicit
// lifetime name in the return type.
//
// **Exercise 2.** Change the signature of `get` to:
//
// fn get<'a>(&'a mut self, key: &'a K) -> Option<&'a V>
//
// - Which test fails to compile?
// - Can you explain why?
//
// **Exe... | {
let mut map = Map::new();
let mut string = format!("alpha");
map.insert('a', string.clone());
let r = map.get(&'a');
assert_eq!(r, Some(&string));
} | identifier_body | |
named_lifetime_parameters.rs | #![allow(warnings)]
// **Exercise 1.** Modify the signature of `get` to use an explicit
// lifetime name in the return type.
//
// **Exercise 2.** Change the signature of `get` to:
//
// fn get<'a>(&'a mut self, key: &'a K) -> Option<&'a V>
//
// - Which test fails to compile?
// - Can you explain why?
//
// **Exe... | let r = map.get(&'a');
assert_eq!(r, Some(&string));
} | fn lock_receiver() {
let mut map = Map::new();
let mut string = format!("alpha");
map.insert('a', string.clone()); | random_line_split |
mem.rs | sleep_ms(period_ms);
if chan.send(ProfilerMsg::Print).is_err() {
break;
}
}
});
}
// Always spawn the memory profiler. If there is no timer thread it won't receive regular
// `Print` events, but it w... |
Some(value as usize)
}
// Like std::macros::try!, but for Option<>.
macro_rules! option_try(
($e:expr) => (match $e { Some(e) => e, None => return None })
);
#[cfg(target_os="linux")]
fn get_proc_self_statm_field(field: usize) -> Option<usize> {
use std::fs::File;
... | {
return None;
} | conditional_block |
mem.rs | sleep_ms(period_ms);
if chan.send(ProfilerMsg::Print).is_err() {
break;
}
}
});
}
// Always spawn the memory profiler. If there is no timer thread it won't receive regular
// `Print` events, but it w... |
fn print(&mut self) {
// Fill in sizes of interior nodes, and recursively sort the sub-trees.
for (_, tree) in self.trees.iter_mut() {
tree.compute_interior_node_sizes_and_sort();
}
// Put the trees into a sorted vector. Primary sort: degenerate trees (those containing... | {
// Get the right tree, creating it if necessary.
if !self.trees.contains_key(&path[0]) {
self.trees.insert(path[0].clone(), ReportsTree::new(path[0].clone()));
}
let t = self.trees.get_mut(&path[0]).unwrap();
// Use tail() because the 0th path segment was used to f... | identifier_body |
mem.rs | sleep_ms(period_ms);
if chan.send(ProfilerMsg::Print).is_err() {
break;
}
}
});
}
// Always spawn the memory profiler. If there is no timer thread it won't receive regular
// `Print` events, but it w... | (&self, depth: i32) {
if!self.children.is_empty() {
assert_eq!(self.count, 0);
}
let mut indent_str = String::new();
for _ in 0..depth {
indent_str.push_str(" ");
}
let mebi = 1024f64 * 1024f64;
let count_str = if self.count > 1 { forma... | print | identifier_name |
mem.rs | sleep_ms(period_ms);
if chan.send(ProfilerMsg::Print).is_err() {
break;
}
}
});
}
// Always spawn the memory profiler. If there is no timer thread it won't receive regular
// `Print` events, but it ... | let mut report = |path, size| {
if let Some(size) = size {
reports.push(Report { path: path, size: size });
}
};
// Virtual and physical memory usage, as reported by the OS.
report(path!["vsi... | random_line_split | |
monomorphize.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
fn_id: ast::DefId,
psubsts: &subst::Substs<'tcx>,
ref_id: Option<ast::NodeId>)
-> (ValueRef, bool) {
debug!("monomorphic_fn(\
fn_id={}, \
real_substs={... | monomorphic_fn | identifier_name |
monomorphize.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | match ccx.monomorphized().borrow().get(&hash_id) {
Some(&val) => {
debug!("leaving monomorphic fn {}",
ty::item_path_str(ccx.tcx(), fn_id));
return (val, false);
}
None => ()
}
debug!("monomorphic_fn(\
fn_id={}, \
psubsts={... | {
debug!("monomorphic_fn(\
fn_id={}, \
real_substs={}, \
ref_id={})",
fn_id.repr(ccx.tcx()),
psubsts.repr(ccx.tcx()),
ref_id);
assert!(psubsts.types.all(|t| {
!ty::type_needs_infer(*t) && !ty::type_has_params(*t)
}));
let _ic... | identifier_body |
monomorphize.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let hash;
let s = {
let mut state = sip::SipState::new();
hash_id.hash(&mut state);
mono_ty.hash(&mut state);
hash = format!("h{}", state.result());
ccx.tcx().map.with_path(fn_id.node, |path| {
exported_name(path, hash.as_slice())
})
};
debug... | }
monomorphizing.insert(fn_id, depth + 1);
}
| random_line_split |
monomorphize.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
let mono_ty = llitem_ty.subst(ccx.tcx(), psubsts);
ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
let depth;
{
let mut monomorphizing = ccx.monomorphizing().borrow_mut();
depth = match mono... | {} | conditional_block |
rom.rs | use std::io::Write;
use std::fs::File;
#[allow(dead_code)]
pub struct INesFile {
magic: [u8; 4],
has_trainer: bool,
pub mapper: u8,
pub prg_rom_cnt: u8,
prg_rom_size: u32,
chr_rom_size: u32,
prg_ram_size: u32,
flags6: u8,
flags7: u8,
flags9: u8,
... | (bin: Vec<u8>) -> INesFile {
let header = &bin[0..16];
let m = [ header[0], header[1], header[2], header[3] ];
if m[0]!= 'N' as u8 || m[1]!= 'E' as u8 || m[2]!= 'S' as u8 || m[3]!= 0x1A {
panic!("Invalid ROM!");
}
let prg_rom_cnt = header[4];
let prg_rom_size ... | load | identifier_name |
rom.rs | use std::io::Write;
use std::fs::File;
#[allow(dead_code)]
pub struct INesFile {
magic: [u8; 4],
has_trainer: bool,
pub mapper: u8,
pub prg_rom_cnt: u8,
prg_rom_size: u32,
chr_rom_size: u32,
prg_ram_size: u32,
flags6: u8,
flags7: u8,
flags9: u8,
... | f.write_all(buf).expect("failed to write to file");
}
} | let buf = &self.prg_rom[0][..]; | random_line_split |
rom.rs | use std::io::Write;
use std::fs::File;
#[allow(dead_code)]
pub struct INesFile {
magic: [u8; 4],
has_trainer: bool,
pub mapper: u8,
pub prg_rom_cnt: u8,
prg_rom_size: u32,
chr_rom_size: u32,
prg_ram_size: u32,
flags6: u8,
flags7: u8,
flags9: u8,
... |
else {
has_trainer = false;
}
for _i in 0..prg_rom_cnt {
let mut page = [0u8; 0x4000];
for j in 0..0x4000 {
page[j] = bin[pos];
pos = pos + 1;
}
prg_rom.push(page);
}
INesFile {
... | {
has_trainer = true;
for i in 0..0x200 {
trainer[i] = bin[pos];
pos = pos + 1;
}
} | conditional_block |
rom.rs | use std::io::Write;
use std::fs::File;
#[allow(dead_code)]
pub struct INesFile {
magic: [u8; 4],
has_trainer: bool,
pub mapper: u8,
pub prg_rom_cnt: u8,
prg_rom_size: u32,
chr_rom_size: u32,
prg_ram_size: u32,
flags6: u8,
flags7: u8,
flags9: u8,
... |
}
| {
let mut f = File::create("prg0.rom").unwrap();
let buf = &self.prg_rom[0][..];
f.write_all(buf).expect("failed to write to file");
} | identifier_body |
cylinder.rs | // Copyright 2013 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... | <S> {
pub center: Point3<S>,
pub axis: Vector3<S>,
pub radius: S,
}
| Cylinder | identifier_name |
cylinder.rs | // Copyright 2013 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// 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 ... |
//! Oriented bounding cylinder
use point::Point3;
use vector::Vector3;
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
pub struct Cylinder<S> {
pub center: Point3<S>,
pub axis: Vector3<S>,
pub radius: S,
} | // See the License for the specific language governing permissions and
// limitations under the License. | random_line_split |
lib.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/. */
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate num_derive;
#[mac... | Grabbing,
EResize,
NResize,
NeResize,
NwResize,
SResize,
SeResize,
SwResize,
WResize,
EwResize,
NsResize,
NeswResize,
NwseResize,
ColResize,
RowResize,
AllScroll,
ZoomIn,
ZoomOut,
}
/// Sends messages to the embedder.
pub struct EmbedderProxy {
... | NoDrop,
NotAllowed,
Grab, | random_line_split |
lib.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/. */
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate num_derive;
#[mac... | {
pub receiver: Receiver<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>,
}
impl EmbedderReceiver {
pub fn try_recv_embedder_msg(
&mut self,
) -> Option<(Option<TopLevelBrowsingContextId>, EmbedderMsg)> {
self.receiver.try_recv().ok()
}
pub fn recv_embedder_msg(&mut self) -> (Opt... | EmbedderReceiver | identifier_name |
memchr.rs | // Original implementation taken from rust-memchr.
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
use crate::cmp;
use crate::mem;
const LO_U64: u64 = 0x0101010101010101;
const HI_U64: u64 = 0x8080808080808080;
// Use truncation.
const LO_USIZE: usize = LO_U64 as usize;
const HI_USIZE: usize = HI_U64 as usi... | (b: u8) -> usize {
(b as usize) << 8 | b as usize
}
#[cfg(not(target_pointer_width = "16"))]
#[inline]
fn repeat_byte(b: u8) -> usize {
(b as usize) * (usize::MAX / 255)
}
/// Returns the first index matching the byte `x` in `text`.
#[inline]
pub fn memchr(x: u8, text: &[u8]) -> Option<usize> {
// Fast pa... | repeat_byte | identifier_name |
memchr.rs | // Original implementation taken from rust-memchr.
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
use crate::cmp;
use crate::mem;
const LO_U64: u64 = 0x0101010101010101;
const HI_U64: u64 = 0x8080808080808080;
// Use truncation.
const LO_USIZE: usize = LO_U64 as usize;
const HI_USIZE: usize = HI_U64 as usi... |
// Search the body of the text, make sure we don't cross min_aligned_offset.
// offset is always aligned, so just testing `>` is sufficient and avoids possible
// overflow.
let repeated_x = repeat_byte(x);
let chunk_bytes = mem::size_of::<Chunk>();
while offset > min_aligned_offset {
... | {
return Some(offset + index);
} | conditional_block |
memchr.rs | // Original implementation taken from rust-memchr.
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
use crate::cmp;
use crate::mem;
const LO_U64: u64 = 0x0101010101010101;
const HI_U64: u64 = 0x8080808080808080;
// Use truncation.
const LO_USIZE: usize = LO_U64 as usize;
const HI_USIZE: usize = HI_U64 as usi... | // search the body of the text
let repeated_x = repeat_byte(x);
while offset <= len - 2 * USIZE_BYTES {
// SAFETY: the while's predicate guarantees a distance of at least 2 * usize_bytes
// between the offset and the end of the slice.
unsafe {
let u = *(ptr.add(offset) as... | {
// Scan for a single byte value by reading two `usize` words at a time.
//
// Split `text` in three parts
// - unaligned initial part, before the first word aligned address in text
// - body, scan by 2 words at a time
// - the last remaining part, < 2 word size
// search up to an aligned ... | identifier_body |
memchr.rs | // Original implementation taken from rust-memchr.
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
use crate::cmp;
use crate::mem;
const LO_U64: u64 = 0x0101010101010101;
const HI_U64: u64 = 0x8080808080808080;
// Use truncation.
const LO_USIZE: usize = LO_U64 as usize;
const HI_USIZE: usize = HI_U64 as usi... | offset += USIZE_BYTES * 2;
}
// Find the byte after the point the body loop stopped.
text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i)
}
/// Returns the last index matching the byte `x` in `text`.
pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
// Scan for a single byte... | break;
}
} | random_line_split |
edit.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 ... |
use chrono::naive::NaiveDateTime;
use libimagdiary::diary::Diary;
use libimagdiary::diaryid::DiaryId;
use libimagdiary::error::DiaryErrorKind as DEK;
use libimagdiary::error::DiaryError as DE;
use libimagdiary::error::ResultExt;
use libimagentryedit::edit::Edit;
use libimagrt::runtime::Runtime;
use libimagerror::trac... | // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::process::exit; | random_line_split |
edit.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 ... | exit(1)
})
.and_then(|id| rt.store().get(id))
.map(|opte| match opte {
Some(mut e) => e.edit_content(rt).chain_err(|| DEK::IOError),
None => Err(DE::from_kind(DEK::EntryNotInDiary)),
})
.map_err_trace()
.ok();
}
| {
let diaryname = get_diary_name(rt).unwrap_or_else(|| warn_exit("No diary name", 1));
rt.cli()
.subcommand_matches("edit")
.unwrap()
.value_of("datetime")
.and_then(DateTime::parse)
.map(|dt| dt.into())
.map(|dt: NaiveDateTime| DiaryId::from_datetime(diaryname.c... | identifier_body |
edit.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 ... | (rt: &Runtime) {
let diaryname = get_diary_name(rt).unwrap_or_else(|| warn_exit("No diary name", 1));
rt.cli()
.subcommand_matches("edit")
.unwrap()
.value_of("datetime")
.and_then(DateTime::parse)
.map(|dt| dt.into())
.map(|dt: NaiveDateTime| DiaryId::from_datetime(di... | edit | identifier_name |
main.rs | #![feature(collections)]
extern crate opencl;
use opencl::mem::CLBuffer;
use std::fmt;
fn main()
{
let ker = include_str!("demo.ocl");
println!("ker {}", ker);
let vec_a = vec![0isize, 1, 2, -3, 4, 5, 6, 7];
let vec_b = vec![-7isize, -6, 5, -4, 0, -1, 2, 3];
let ref platform = opencl::hl::get_p... | {
let mut st = String::from_str("[");
let mut first = true;
for i in slice.iter() {
if !first {
st.push_str(", ");
}
else {
first = false;
}
st.push_str(&*i.to_string())
}
st.push_str("]");
return st
} | identifier_body | |
main.rs | #![feature(collections)]
extern crate opencl;
use opencl::mem::CLBuffer;
use std::fmt;
fn main()
{
let ker = include_str!("demo.ocl");
println!("ker {}", ker);
let vec_a = vec![0isize, 1, 2, -3, 4, 5, 6, 7];
let vec_b = vec![-7isize, -6, 5, -4, 0, -1, 2, 3];
let ref platform = opencl::hl::get_p... |
else {
first = false;
}
st.push_str(&*i.to_string())
}
st.push_str("]");
return st
}
| {
st.push_str(", ");
} | conditional_block |
main.rs | #![feature(collections)]
extern crate opencl;
use opencl::mem::CLBuffer;
use std::fmt;
fn main()
{
let ker = include_str!("demo.ocl");
println!("ker {}", ker);
let vec_a = vec![0isize, 1, 2, -3, 4, 5, 6, 7];
let vec_b = vec![-7isize, -6, 5, -4, 0, -1, 2, 3];
let ref platform = opencl::hl::get_p... | return st
} | }
st.push_str(&*i.to_string())
}
st.push_str("]"); | random_line_split |
main.rs | #![feature(collections)]
extern crate opencl;
use opencl::mem::CLBuffer;
use std::fmt;
fn main()
{
let ker = include_str!("demo.ocl");
println!("ker {}", ker);
let vec_a = vec![0isize, 1, 2, -3, 4, 5, 6, 7];
let vec_b = vec![-7isize, -6, 5, -4, 0, -1, 2, 3];
let ref platform = opencl::hl::get_p... | <T: fmt::Display>(slice: &[T]) -> String {
let mut st = String::from_str("[");
let mut first = true;
for i in slice.iter() {
if!first {
st.push_str(", ");
}
else {
first = false;
}
st.push_str(&*i.to_string())
}
st.push_str("]");
... | string_from_slice | identifier_name |
static-method-on-struct-and-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// STRUCT
// lldb-command:print arg1
// lldb-check:[...]$0 = 1
// lldb-command:print arg2
// lldb-check:[...]$1 = 2
// lldb-command:continue
// ENUM
// lldb-command:print... | // gdb-check:$5 = 5 | random_line_split |
static-method-on-struct-and-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
Struct::static_method(1, 2);
Enum::static_method(-3, 4.5, 5);
}
fn zzz() {()}
| main | identifier_name |
smb2_ioctl.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
}
// IOCTL responses ASYNC don't set the tree id
pub fn smb2_ioctl_request_record<'b>(state: &mut SMBState, r: &Smb2Record<'b>)
{
match parse_smb2_request_ioctl(r.data) {
IResult::Done(_, rd) => {
SCLogDebug!("IOCTL request data: {:?}", rd);
let is_dcerpc = rd.is_pipe && match stat... | {
let mut tx = self.new_tx();
tx.hdr = hdr;
tx.type_data = Some(SMBTransactionTypeData::IOCTL(
SMBTransactionIoctl::new(func)));
tx.request_done = true;
tx.response_done = self.tc_trunc; // no response expected if tc is truncated
SCLogDebug!("SMB: TX ... | identifier_body |
smb2_ioctl.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | pub fn new_ioctl_tx(&mut self, hdr: SMBCommonHdr, func: u32)
-> (&mut SMBTransaction)
{
let mut tx = self.new_tx();
tx.hdr = hdr;
tx.type_data = Some(SMBTransactionTypeData::IOCTL(
SMBTransactionIoctl::new(func)));
tx.request_done = true;
tx.re... | impl SMBState { | random_line_split |
smb2_ioctl.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | ,
}
}
},
_ => {
let tx_key = SMBCommonHdr::new(SMBHDR_TYPE_HEADER,
r.session_id, 0, r.message_id);
SCLogDebug!("SMB2_COMMAND_IOCTL/SMB_NTSTATUS_PENDING looking for {:?}", tx_key);
match state.get_generic_tx(2, SMB2_COMMA... | { } | conditional_block |
smb2_ioctl.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | <'b>(state: &mut SMBState, r: &Smb2Record<'b>)
{
match parse_smb2_response_ioctl(r.data) {
IResult::Done(_, rd) => {
SCLogDebug!("IOCTL response data: {:?}", rd);
let is_dcerpc = rd.is_pipe && match state.get_service_for_guid(&rd.guid) {
(_, x) => x,
};
... | smb2_ioctl_response_record | identifier_name |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::sys::unsupported;
use crate::time::Duration;
pub struct Thread(!);
pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usiz... | pub unsafe fn current() -> Option<Guard> {
None
}
pub unsafe fn init() -> Option<Guard> {
None
}
}
// We currently just use our own thread-local to store our
// current thread's ID, and then we lazily initialize it to something allocated
// from a global counter.
pub fn my_id() -> u32 {... | random_line_split | |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::sys::unsupported;
use crate::time::Duration;
pub struct Thread(!);
pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usiz... | () {}
pub fn set_name(_name: &CStr) {}
pub fn sleep(dur: Duration) {
use crate::arch::wasm32;
use crate::cmp;
// Use an atomic wait to block the current thread artificially with a
// timeout listed. Note that we should never be notified (return value
// of 0) or our co... | yield_now | identifier_name |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::sys::unsupported;
use crate::time::Duration;
pub struct Thread(!);
pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usiz... |
pub fn join(self) {}
}
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
unsupported()
}
pub mod guard {
pub type Guard =!;
pub unsafe fn current() -> Option<Guard> {
None
}
pub unsafe fn init() -> Option<Guard> {
None
}
}
// We currently just use our own thre... | {
use crate::arch::wasm32;
use crate::cmp;
// Use an atomic wait to block the current thread artificially with a
// timeout listed. Note that we should never be notified (return value
// of 0) or our comparison should never fail (return value of 1) so we
// should always... | identifier_body |
fn_queries.rs | use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_target::spec::abi::Abi;
/// Whether the `def_id` is an unstable const fn and what feature gate is necessary to enable it
pub fn is_unstable_const_fn(tcx: T... | (tcx: TyCtxt<'_>, def_id: DefId) -> bool {
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
let node = tcx.hir().get(hir_id);
if let hir::Node::ForeignItem(hir::ForeignItem { kind: hir::ForeignItemKind::Fn(..),.. }) =
node
{
// Intrinsics use `rustc_const_{un,}stab... | is_const_fn_raw | identifier_name |
fn_queries.rs | use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_target::spec::abi::Abi;
/// Whether the `def_id` is an unstable const fn and what feature gate is necessary to enable it
pub fn is_unstable_const_fn(tcx: T... |
} else {
None
}
}
pub fn is_parent_const_impl_raw(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
let parent_id = tcx.hir().get_parent_node(hir_id);
matches!(
tcx.hir().get(parent_id),
hir::Node::Item(hir::Item {
kind: hir::ItemKind::Impl(hir::Impl { constness: hir::... | { None } | conditional_block |
fn_queries.rs | use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_target::spec::abi::Abi;
/// Whether the `def_id` is an unstable const fn and what feature gate is necessary to enable it
pub fn is_unstable_const_fn(tcx: T... | stab.promotable
}
None => false,
}
}
pub fn provide(providers: &mut Providers) {
*providers = Providers { is_const_fn_raw, is_promotable_const_fn,..*providers };
} | hir::Unsafety::Normal,
"don't mark const unsafe fns as promotable",
// https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682
);
} | random_line_split |
fn_queries.rs | use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::Symbol;
use rustc_target::spec::abi::Abi;
/// Whether the `def_id` is an unstable const fn and what feature gate is necessary to enable it
pub fn is_unstable_const_fn(tcx: T... | {
*providers = Providers { is_const_fn_raw, is_promotable_const_fn, ..*providers };
} | identifier_body | |
clone.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
macro_rules! clone_impl {
($t:ty) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for $t {
/// Return a deep copy of the value.
#[inline]
fn clone(&self) -> $t { *self }
}
}
}
clone_impl! { int }
clone_impl! { i8 }
clone_impl! { i16 ... | { *self } | identifier_body |
clone.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | macro_rules! extern_fn_clone {
($($A:ident),*) => (
#[unstable(feature = "core",
reason = "this may not be sufficient for fns with region parameters")]
impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType {
/// Return a copy of a function pointer
... |
clone_impl! { () }
clone_impl! { bool }
clone_impl! { char }
| random_line_split |
clone.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self) -> &'a T { *self }
}
macro_rules! clone_impl {
($t:ty) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for $t {
/// Return a deep copy of the value.
#[inline]
fn clone(&self) -> $t { *self }
}
}
}
clone_impl! { int }
clone_impl!... | clone | identifier_name |
lib.rs | #![crate_name = "librespot"] |
#![cfg_attr(feature = "cargo-clippy", allow(unused_io_amount))]
// TODO: many items from tokio-core::io have been deprecated in favour of tokio-io
#![allow(deprecated)]
#[macro_use] extern crate log;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate base64;
extern crate cryp... | random_line_split | |
spinner.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... | mut self) -> () {
unsafe {
ffi::gtk_spinner_stop(GTK_SPINNER(self.pointer))
}
}
}
impl_drop!(Spinner)
impl_TraitWidget!(Spinner)
impl_widget_events!(Spinner)
| op(& | identifier_name |
spinner.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. | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/li... | //
// rgtk is distributed in the hope that it will be useful, | random_line_split |
spinner.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 stop(&mut self) -> () {
unsafe {
ffi::gtk_spinner_stop(GTK_SPINNER(self.pointer))
}
}
}
impl_drop!(Spinner)
impl_TraitWidget!(Spinner)
impl_widget_events!(Spinner)
| unsafe {
ffi::gtk_spinner_start(GTK_SPINNER(self.pointer))
}
}
| identifier_body |
simd.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[simd]
#[deriving(Show)]
pub struct i16x8(pub i16, pub i16, pub i16, pub i16,
pub i16, pub i16, pub i16, pub i16);
#[experimental]
#[simd]
#[deriving(Show)]
pub struct i32x4(pub i32, pub i32, pub i32, pub i32);
#[experimental]
#[simd]
#[deriving(Show)]
pub struct i64x2(pub i64, pub i64);
#[experime... | #[experimental] | random_line_split |
simd.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (pub u8, pub u8, pub u8, pub u8,
pub u8, pub u8, pub u8, pub u8,
pub u8, pub u8, pub u8, pub u8,
pub u8, pub u8, pub u8, pub u8);
#[experimental]
#[simd]
#[deriving(Show)]
pub struct u16x8(pub u16, pub u16, pub u16, pub u16,
pub u16, pub u16, pub u16,... | u8x16 | identifier_name |
sampler.rs | //! # OpenTelemetry ShouldSample Interface
//!
//! ## Sampling
//!
//! Sampling is a mechanism to control the noise and overhead introduced by
//! OpenTelemetry by reducing the number of samples of traces collected and
//! sent to the backend.
//!
//! Sampling may be implemented on different stages of a trace collectio... | (
&self,
parent_context: Option<&Context>,
trace_id: TraceId,
name: &str,
span_kind: &SpanKind,
attributes: &[KeyValue],
links: &[Link],
instrumentation_library: &InstrumentationLibrary,
) -> SamplingResult {
let decision = match self {
... | should_sample | identifier_name |
sampler.rs | //! # OpenTelemetry ShouldSample Interface
//!
//! ## Sampling
//!
//! Sampling is a mechanism to control the noise and overhead introduced by
//! OpenTelemetry by reducing the number of samples of traces collected and
//! sent to the backend.
//!
//! Sampling may be implemented on different stages of a trace collectio... | else {
SamplingDecision::Drop
}
},
)
}
// Probabilistically sample the trace.
Sampler::TraceIdRatioBased(prob) => {
if *prob >= 1.0 {
SamplingDecision::RecordA... | {
SamplingDecision::RecordAndSample
} | conditional_block |
sampler.rs | //! # OpenTelemetry ShouldSample Interface
//!
//! ## Sampling
//!
//! Sampling is a mechanism to control the noise and overhead introduced by
//! OpenTelemetry by reducing the number of samples of traces collected and
//! sent to the backend.
//!
//! Sampling may be implemented on different stages of a trace collectio... | /// zero, but spans may still be sampled if their parent is.
TraceIdRatioBased(f64),
}
impl ShouldSample for Sampler {
fn should_sample(
&self,
parent_context: Option<&Context>,
trace_id: TraceId,
name: &str,
span_kind: &SpanKind,
attributes: &[KeyValue],
... | /// Respects the parent span's sampling decision or delegates a delegate sampler for root spans.
ParentBased(Box<Sampler>),
/// Sample a given fraction of traces. Fractions >= 1 will always sample. If the parent span is
/// sampled, then it's child spans will automatically be sampled. Fractions < 0 are ... | random_line_split |
const-adt-align-mismatch.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(dead_code)]
#![allow(deprecated)]
use std::mem;
#[derive(PartialEq, Debug)]
enum Foo {
A(u32),
Bar([u16; 4]),
C
}
// NOTE(eddyb) Don't make this a const, needs to be a static
// so i... | // 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 | random_line_split |
const-adt-align-mismatch.rs | // Copyright 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-MIT or ... | {
assert_eq!(FOO, Foo::C);
assert_eq!(mem::size_of::<Foo>(), 12);
assert_eq!(mem::min_align_of::<Foo>(), 4);
} | identifier_body | |
const-adt-align-mismatch.rs | // Copyright 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-MIT or ... | () {
assert_eq!(FOO, Foo::C);
assert_eq!(mem::size_of::<Foo>(), 12);
assert_eq!(mem::min_align_of::<Foo>(), 4);
}
| main | identifier_name |
truncate.rs | #![allow(unstable)]
use std::old_io as io;
use std::old_io::process::Command;
static PROGNAME: &'static str = "./truncate";
static TFILE1: &'static str = "truncate_test_1";
static TFILE2: &'static str = "truncate_test_2";
fn | (name: &str) -> io::File {
match io::File::create(&Path::new(name)) {
Ok(f) => f,
Err(_) => panic!()
}
}
#[test]
fn test_increase_file_size() {
let mut file = make_file(TFILE1);
if!Command::new(PROGNAME).args(&["-s", "+5K", TFILE1]).status().unwrap().success() {
panic!();
}
... | make_file | identifier_name |
truncate.rs | #![allow(unstable)]
use std::old_io as io;
use std::old_io::process::Command;
static PROGNAME: &'static str = "./truncate";
static TFILE1: &'static str = "truncate_test_1";
static TFILE2: &'static str = "truncate_test_2";
fn make_file(name: &str) -> io::File {
match io::File::create(&Path::new(name)) {
O... | fn test_decrease_file_size() {
let mut file = make_file(TFILE2);
file.write_all(b"1234567890").unwrap();
if!Command::new(PROGNAME).args(&["--size=-4", TFILE2]).status().unwrap().success() {
panic!();
}
file.seek(0, io::SeekEnd).unwrap();
if file.tell().unwrap()!= 6 {
println!("{:... |
#[test] | random_line_split |
truncate.rs | #![allow(unstable)]
use std::old_io as io;
use std::old_io::process::Command;
static PROGNAME: &'static str = "./truncate";
static TFILE1: &'static str = "truncate_test_1";
static TFILE2: &'static str = "truncate_test_2";
fn make_file(name: &str) -> io::File {
match io::File::create(&Path::new(name)) {
O... |
#[test]
fn test_decrease_file_size() {
let mut file = make_file(TFILE2);
file.write_all(b"1234567890").unwrap();
if!Command::new(PROGNAME).args(&["--size=-4", TFILE2]).status().unwrap().success() {
panic!();
}
file.seek(0, io::SeekEnd).unwrap();
if file.tell().unwrap()!= 6 {
pr... | {
let mut file = make_file(TFILE1);
if !Command::new(PROGNAME).args(&["-s", "+5K", TFILE1]).status().unwrap().success() {
panic!();
}
file.seek(0, io::SeekEnd).unwrap();
if file.tell().unwrap() != 5 * 1024 {
panic!();
}
io::fs::unlink(&Path::new(TFILE1)).unwrap();
} | identifier_body |
css_provider.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use std::fmt::{self, Display, Formatter};
use ffi::{self, GtkCssProvider};
use glib::tran... | else {
Err(glib::Error::wrap(error))
}
}
}
}
impl Display for CssProvider {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let tmp: String = unsafe { from_glib_full(ffi::gtk_css_provider_to_string(self.pointer)) };
write!(f, "{}", tmp)
}
}
impl_GObj... | {
Ok(CssProvider { pointer: pointer })
} | conditional_block |
css_provider.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use std::fmt::{self, Display, Formatter};
use ffi::{self, GtkCssProvider};
use glib::tran... |
pub fn get_default() -> Self {
unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_default() } }
}
pub fn get_named(name: &str, variant: &str) -> Self {
unsafe {
CssProvider { pointer: ffi::gtk_css_provider_get_named(name.to_glib_none().0,
... | {
unsafe { CssProvider { pointer: ffi::gtk_css_provider_new() } }
} | identifier_body |
css_provider.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use std::fmt::{self, Display, Formatter};
use ffi::{self, GtkCssProvider};
use glib::tran... | (path: &str) -> Result<CssProvider, glib::Error> {
unsafe {
let pointer = ffi::gtk_css_provider_new();
let mut error = ::std::ptr::null_mut();
ffi::gtk_css_provider_load_from_path(pointer, path.to_glib_none().0, &mut error);
if error.is_null() {
Ok... | load_from_path | identifier_name |
css_provider.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use std::fmt::{self, Display, Formatter};
use ffi::{self, GtkCssProvider};
use glib::tran... | pointer: *mut GtkCssProvider
}
impl ::StyleProviderTrait for CssProvider {}
impl CssProvider {
pub fn new() -> Self {
unsafe { CssProvider { pointer: ffi::gtk_css_provider_new() } }
}
pub fn get_default() -> Self {
unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_default() } ... | random_line_split | |
lib.rs | extern crate hyper;
extern crate hyper_native_tls;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
static URL: &'static str = "http://api.openaq.org";
mod entities;
pub use entities::*;
pub mod json {
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClie... |
pub fn get_fetches(fetches_query_opts: Option<GetFetchesQueryOpts>) -> Vec<Fetch> {
extract_results_with_opts!(json::get_fetches_query,
Fetch,
json::requests::FETCHES,
fetches_query_opts);
}
pub fn get_countries(countrie... | {
extract_results_with_opts!(json::get_cities_query,
City,
json::requests::CITIES,
cities_query_opts);
} | identifier_body |
lib.rs | extern crate hyper;
extern crate hyper_native_tls;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
static URL: &'static str = "http://api.openaq.org";
mod entities;
pub use entities::*;
pub mod json {
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClie... | (opts: GetCountriesQueryOpts) -> String {
return String::from("page=") + &opts.page.to_string() + "&limit=" + &opts.limit.to_string();
}
pub fn get_fetches_query(opts: GetFetchesQueryOpts) -> String {
return String::from("page=") + &opts.page.to_string() + "&limit=" + &opts.limit.to_string();
... | get_countries_query | identifier_name |
lib.rs | extern crate hyper;
extern crate hyper_native_tls;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
static URL: &'static str = "http://api.openaq.org";
mod entities;
pub use entities::*;
pub mod json {
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClie... | let opts = json::GetOpts { query: Some(countries_query) };
Some(opts)
}
};
extract_results!(Country, json::requests::COUNTRIES, get_opts);
}
pub fn get_parameters() -> Vec<Parameter> {
extract_results!(Parameter, json::requests::PARAMETERS, None);
} | None => None,
Some(o) => {
let countries_query = json::get_countries_query(o); | random_line_split |
window-properties.rs | extern crate sdl2;
use sdl2::pixels::Color;
pub fn main() | running = false
},
_ => {}
}
}
{
// Update the window title.
// &sdl_context is needed to safely access the Window and to ensure that the event loop
// isn't running (which could mutate the Window).
... | {
let mut sdl_context = sdl2::init().video().unwrap();
let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600)
.resizable()
.build()
.unwrap();
let mut renderer = window.renderer().present_vsync().build().unwrap();
let mut running = true;
let mut tick = 0;
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.