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 |
|---|---|---|---|---|
hrtb-higher-ranker-supertraits-transitive.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
trait Baz
: for<'ccx> Bar<'ccx>
{
fn dummy(&self);
}
trait Qux
: Bar<'static>
{
fn dummy(&self);
}
fn want_foo_for_any_tcx<F>(f: &F)
where F : for<'tcx> Foo<'tcx>
{
}
fn want_bar_for_any_ccx<B>(b: &B)
where B : for<'ccx> Bar<'ccx>
{
}
fn want_baz<B>(b: &B)
where B : Baz
{
want_foo... | random_line_split | |
hrtb-higher-ranker-supertraits-transitive.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 ... | <B>(b: &B)
where B : Baz
{
want_foo_for_any_tcx(b);
want_bar_for_any_ccx(b);
}
fn want_qux<B>(b: &B)
where B : Qux
{
want_foo_for_any_tcx(b);
want_bar_for_any_ccx(b); //~ ERROR E0277
}
fn main() {}
| want_baz | identifier_name |
hrtb-higher-ranker-supertraits-transitive.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {}
| {
want_foo_for_any_tcx(b);
want_bar_for_any_ccx(b); //~ ERROR E0277
} | identifier_body |
event_loop.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use super::error::{Error, Result};
use base::{
error, warn, wrap_descriptor, AsRawDescriptor, Descriptor, EpollContext, EpollEvents, Event,
Raw... | () {
let (l, j) = EventLoop::start("test".to_string(), None).unwrap();
let (self_evt, evt) = match Event::new().and_then(|e| Ok((e.try_clone()?, e))) {
Ok(v) => v,
Err(e) => {
error!("failed creating Event pair: {:?}", e);
return;
}
... | event_loop_test | identifier_name |
event_loop.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use super::error::{Error, Result};
use base::{
error, warn, wrap_descriptor, AsRawDescriptor, Descriptor, EpollContext, EpollEvents, Event,
Raw... |
/// A fail handle will do the clean up when we cannot recover from some error.
pub trait FailHandle: Send + Sync {
/// Fail the code.
fn fail(&self);
/// Returns true if already failed.
fn failed(&self) -> bool;
}
impl FailHandle for Option<Arc<dyn FailHandle>> {
fn fail(&self) {
match sel... | use std::collections::BTreeMap;
use std::mem::drop;
use std::sync::{Arc, Weak};
use std::thread;
use sync::Mutex; | random_line_split |
lights.rs | use crate::geometry::direction::Direction;
use crate::geometry::ray::Ray;
use crate::geometry::vector::Vector4;
use rand::prelude::ThreadRng;
use rand::Rng;
pub trait Light : Sync {
fn emit(&self, rng: &mut ThreadRng) -> Ray;
fn energy_total(&self) -> f64;
}
pub struct IntervalLight {
from: Vector4,
... | }
impl Light for IntervalLight {
fn emit(&self, rng: &mut ThreadRng) -> Ray {
let d: f64 = rng.gen_range(0.0, 1.0);
let start = self.from + (self.to - self.from) * d;
let direction: Direction = Direction::random(rng, 1.0);
return Ray { start, direction };
}
fn energy_tota... | random_line_split | |
lights.rs | use crate::geometry::direction::Direction;
use crate::geometry::ray::Ray;
use crate::geometry::vector::Vector4;
use rand::prelude::ThreadRng;
use rand::Rng;
pub trait Light : Sync {
fn emit(&self, rng: &mut ThreadRng) -> Ray;
fn energy_total(&self) -> f64;
}
pub struct IntervalLight {
from: Vector4,
... |
}
| {
return self.energy;
} | identifier_body |
lights.rs | use crate::geometry::direction::Direction;
use crate::geometry::ray::Ray;
use crate::geometry::vector::Vector4;
use rand::prelude::ThreadRng;
use rand::Rng;
pub trait Light : Sync {
fn emit(&self, rng: &mut ThreadRng) -> Ray;
fn energy_total(&self) -> f64;
}
pub struct | {
from: Vector4,
to: Vector4,
energy: f64
}
impl IntervalLight {
pub fn new(from: Vector4, to: Vector4, energy: f64) -> Box<dyn Light> {
return Box::new(IntervalLight { from, to, energy });
}
}
impl Light for IntervalLight {
fn emit(&self, rng: &mut ThreadRng) -> Ray {
let d: ... | IntervalLight | identifier_name |
cols.rs | use transposed::{Cols, ColsMut};
use {Col, ColMut};
impl<'a, T> DoubleEndedIterator for Cols<'a, T> {
fn next_back(&mut self) -> Option<Col<'a, T>> {
self.0.next_back().map(|r| Col(r.0))
}
}
impl<'a, T> Iterator for Cols<'a, T> {
type Item = Col<'a, T>;
fn next(&mut self) -> Option<Col<'a, T>... | type Item = ColMut<'a, T>;
fn next(&mut self) -> Option<ColMut<'a, T>> {
self.0.next().map(|r| ColMut(Col((r.0).0)))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
} | impl<'a, T> Iterator for ColsMut<'a, T> { | random_line_split |
cols.rs | use transposed::{Cols, ColsMut};
use {Col, ColMut};
impl<'a, T> DoubleEndedIterator for Cols<'a, T> {
fn next_back(&mut self) -> Option<Col<'a, T>> {
self.0.next_back().map(|r| Col(r.0))
}
}
impl<'a, T> Iterator for Cols<'a, T> {
type Item = Col<'a, T>;
fn next(&mut self) -> Option<Col<'a, T>... | (&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<'a, T> DoubleEndedIterator for ColsMut<'a, T> {
fn next_back(&mut self) -> Option<ColMut<'a, T>> {
self.0.next_back().map(|r| ColMut(Col((r.0).0)))
}
}
impl<'a, T> Iterator for ColsMut<'a, T> {
type Item = ColMut<'a, T>;
... | size_hint | identifier_name |
cols.rs | use transposed::{Cols, ColsMut};
use {Col, ColMut};
impl<'a, T> DoubleEndedIterator for Cols<'a, T> {
fn next_back(&mut self) -> Option<Col<'a, T>> {
self.0.next_back().map(|r| Col(r.0))
}
}
impl<'a, T> Iterator for Cols<'a, T> {
type Item = Col<'a, T>;
fn next(&mut self) -> Option<Col<'a, T>... |
}
| {
self.0.size_hint()
} | identifier_body |
test_stats.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::Arc;
use kvproto::kvrpcpb::*;
use pd_client::PdClient;
use test_raftstore::*;
use tikv_util::config::*;
fn check_available<T: Simulator>(cluster: &mut Cluster<T>) | if stats.get_available()!= last_available {
return;
}
}
panic!("available not changed")
}
fn test_simple_store_stats<T: Simulator>(cluster: &mut Cluster<T>) {
let pd_client = Arc::clone(&cluster.pd_client);
cluster.cfg.raft_store.pd_store_heartbeat_tick_interval = Readabl... | {
let pd_client = Arc::clone(&cluster.pd_client);
let engine = cluster.get_engine(1);
let raft_engine = cluster.get_raft_engine(1);
let stats = pd_client.get_store_stats(1).unwrap();
assert_eq!(stats.get_region_count(), 2);
let value = vec![0; 1024];
for i in 0..1000 {
let last_ava... | identifier_body |
test_stats.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::Arc;
use kvproto::kvrpcpb::*;
use pd_client::PdClient;
use test_raftstore::*;
use tikv_util::config::*;
fn check_available<T: Simulator>(cluster: &mut Cluster<T>) {
let pd_client = Arc::clone(&cluster.pd_client);
let engine = c... |
}
let engine = cluster.get_engine(1);
let raft_engine = cluster.get_raft_engine(1);
raft_engine.flush(true).unwrap();
engine.flush(true).unwrap();
let last_stats = pd_client.get_store_stats(1).unwrap();
assert_eq!(last_stats.get_region_count(), 1);
cluster.must_put(b"k1", b"v1");
... | {
break;
} | conditional_block |
test_stats.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::Arc;
use kvproto::kvrpcpb::*;
use pd_client::PdClient;
use test_raftstore::*;
use tikv_util::config::*;
fn check_available<T: Simulator>(cluster: &mut Cluster<T>) {
let pd_client = Arc::clone(&cluster.pd_client);
let engine = c... | <T: Simulator>(cluster: &mut Cluster<T>) {
let pd_client = Arc::clone(&cluster.pd_client);
cluster.cfg.raft_store.pd_store_heartbeat_tick_interval = ReadableDuration::millis(20);
cluster.run();
// wait store reports stats.
for _ in 0..100 {
sleep_ms(20);
if pd_client.get_store_sta... | test_simple_store_stats | identifier_name |
test_stats.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use std::sync::Arc;
use kvproto::kvrpcpb::*;
use pd_client::PdClient;
use test_raftstore::*;
use tikv_util::config::*;
fn check_available<T: Simulator>(cluster: &mut Cluster<T>) {
let pd_client = Arc::clone(&cluster.pd_client);
let engine = c... | let mut put_req = RawPutRequest::default();
put_req.set_context(ctx.clone());
put_req.key = k.clone();
put_req.value = v.clone();
let put_resp = client.raw_put(&put_req).unwrap();
assert!(!put_resp.has_region_error());
assert!(put_resp.error.is_empty());
for _i in 0..100 {
// Raw... | });
let (k, v) = (b"key".to_vec(), b"v2".to_vec());
// Raw put | random_line_split |
aux2bib.rs | #[macro_use(crate_version, crate_authors)]
extern crate clap;
use inspirer;
use inspirer::InspirerError;
use std::error::Error;
use human_panic::setup_panic;
#[macro_use]
extern crate slog;
use slog::DrainExt;
use slog_term;
use clap::{App, Arg};
fn main() |
fn run(root_logger: &slog::Logger) -> Result<(), InspirerError> {
info!(root_logger, "Application started");
// Initialize instance of InspirerLib
let lib = inspirer::Inspirer::init(Some(root_logger.new(o!())));
// Define CLI
let matches = App::new("aux2bib")
.version(crate_version!())
... | {
setup_panic!();
// Initialize logging
let drain = slog_term::streamer().stderr().build().fuse();
let root_logger = slog::Logger::root(drain, o!("version" => crate_version!()));
if let Err(ref e) = run(&root_logger) {
match e {
_ => error!(root_logger, e.to_string();
... | identifier_body |
aux2bib.rs | #[macro_use(crate_version, crate_authors)]
extern crate clap;
use inspirer;
use inspirer::InspirerError;
use std::error::Error;
use human_panic::setup_panic;
#[macro_use]
extern crate slog;
use slog::DrainExt;
use slog_term;
use clap::{App, Arg}; | let drain = slog_term::streamer().stderr().build().fuse();
let root_logger = slog::Logger::root(drain, o!("version" => crate_version!()));
if let Err(ref e) = run(&root_logger) {
match e {
_ => error!(root_logger, e.to_string();
"error" => format!("{}", match e.sourc... |
fn main() {
setup_panic!();
// Initialize logging | random_line_split |
aux2bib.rs | #[macro_use(crate_version, crate_authors)]
extern crate clap;
use inspirer;
use inspirer::InspirerError;
use std::error::Error;
use human_panic::setup_panic;
#[macro_use]
extern crate slog;
use slog::DrainExt;
use slog_term;
use clap::{App, Arg};
fn | () {
setup_panic!();
// Initialize logging
let drain = slog_term::streamer().stderr().build().fuse();
let root_logger = slog::Logger::root(drain, o!("version" => crate_version!()));
if let Err(ref e) = run(&root_logger) {
match e {
_ => error!(root_logger, e.to_string();
... | main | identifier_name |
aux2bib.rs | #[macro_use(crate_version, crate_authors)]
extern crate clap;
use inspirer;
use inspirer::InspirerError;
use std::error::Error;
use human_panic::setup_panic;
#[macro_use]
extern crate slog;
use slog::DrainExt;
use slog_term;
use clap::{App, Arg};
fn main() {
setup_panic!();
// Initialize logging
let d... |
}
fn run(root_logger: &slog::Logger) -> Result<(), InspirerError> {
info!(root_logger, "Application started");
// Initialize instance of InspirerLib
let lib = inspirer::Inspirer::init(Some(root_logger.new(o!())));
// Define CLI
let matches = App::new("aux2bib")
.version(crate_version!())
... | {
match e {
_ => error!(root_logger, e.to_string();
"error" => format!("{}", match e.source(){
Some(e) => e.to_string(),
None => String::new(),
})
),
}
::std::process::exit(1);
} | conditional_block |
cosmogony2mimir.rs | /// This module contains the definition for bano2mimir configuration and command line arguments.
use mimir::domain::model::configuration::ContainerConfig;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::env;
use std::path::PathBuf;
use mimir::adapters::secondary::elasticsearch::Elasticsear... | {
/// Defines the config directory
///
/// This directory must contain 'elasticsearch' and 'cosmogony2mimir' subdirectories.
#[clap(parse(from_os_str), short = 'c', long = "config-dir")]
pub config_dir: PathBuf,
/// Defines the run mode in {testing, dev, prod,...}
///
/// If no run mod... | Opts | identifier_name |
cosmogony2mimir.rs | /// This module contains the definition for bano2mimir configuration and command line arguments.
use mimir::domain::model::configuration::ContainerConfig;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::env;
use std::path::PathBuf;
use mimir::adapters::secondary::elasticsearch::Elasticsear... | about = "Parsing Cosmogony document and indexing its content in Elasticsearch",
version = VERSION,
author = AUTHORS
)]
pub struct Opts {
/// Defines the config directory
///
/// This directory must contain 'elasticsearch' and 'cosmogony2mimir' subdirectories.
#[clap(parse(from_os_str), s... |
#[derive(Debug, clap::Parser)]
#[clap(
name = "cosmogony2mimir", | random_line_split |
python.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publis... |
/// Temporarily releases the GIL, thus allowing other Python threads to run.
pub fn allow_threads<T, F>(self, f: F) -> T where F : Send + FnOnce() -> T {
// The `Send` bound on the closure prevents the user from
// transferring the `Python` token into the closure.
unsafe {
... | {
GILGuard::acquire()
} | identifier_body |
python.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publis... | }
/// ToPythonPointer for borrowed Python pointers.
impl <'a, T> ToPythonPointer for &'a T where T: PythonObject {
#[inline]
fn as_ptr(&self) -> *mut ffi::PyObject {
self.as_object().as_ptr()
}
#[inline]
fn steal_ptr(self, py: Python) -> *mut ffi::PyObject {
self.as_object().clone_... | #[inline]
fn steal_ptr(self, _py: Python) -> *mut ffi::PyObject {
self.steal_ptr()
} | random_line_split |
python.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publis... | (self) -> PyObject {
unsafe { PyObject::from_borrowed_ptr(self, ffi::Py_None()) }
}
/// Gets the Python builtin value `True`.
#[allow(non_snake_case)] // the Python keyword starts with uppercase
#[inline]
pub fn True(self) -> PyBool {
unsafe { PyObject::from_borrowed_ptr(self, ffi::... | None | identifier_name |
bob.rs | fn process_response_case(phrase: &str, expected_response: &str) {
assert_eq!(bob::reply(phrase), expected_response);
}
#[test]
/// stating something
fn test_stating_something() {
process_response_case("Tom-ay-to, tom-aaaah-to.", "Whatever.");
}
#[test]
#[ignore]
/// ending with whitespace
fn test_ending_with_... | #[ignore]
/// question with no letters
fn test_question_with_no_letters() {
process_response_case("4?", "Sure.");
}
#[test]
#[ignore]
/// no letters
fn test_no_letters() {
process_response_case("1, 2, 3", "Whatever.");
}
#[test]
#[ignore]
/// statement containing question mark
fn test_statement_containing_que... | random_line_split | |
bob.rs | fn process_response_case(phrase: &str, expected_response: &str) {
assert_eq!(bob::reply(phrase), expected_response);
}
#[test]
/// stating something
fn test_stating_something() {
process_response_case("Tom-ay-to, tom-aaaah-to.", "Whatever.");
}
#[test]
#[ignore]
/// ending with whitespace
fn test_ending_with_... |
#[test]
#[ignore]
/// statement containing question mark
fn test_statement_containing_question_mark() {
process_response_case("Ending with? means a question.", "Whatever.");
}
//NEW
#[test]
#[ignore]
/// multiple line question
fn test_multiple_line_question() {
process_response_case(
"\rDoes this cry... | {
process_response_case("1, 2, 3", "Whatever.");
} | identifier_body |
bob.rs | fn process_response_case(phrase: &str, expected_response: &str) {
assert_eq!(bob::reply(phrase), expected_response);
}
#[test]
/// stating something
fn test_stating_something() {
process_response_case("Tom-ay-to, tom-aaaah-to.", "Whatever.");
}
#[test]
#[ignore]
/// ending with whitespace
fn test_ending_with_... | () {
process_response_case("WATCH OUT!", "Whoa, chill out!");
}
#[test]
#[ignore]
/// non-letters with question
fn test_nonletters_with_question() {
process_response_case(":)?", "Sure.");
}
#[test]
#[ignore]
/// shouting gibberish
fn test_shouting_gibberish() {
process_response_case("FCECDFCAAB", "Whoa, c... | test_shouting | identifier_name |
random_negative_integers.rs | use itertools::Itertools;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base::random::EXAMPLE_SEED;
use malachite_base_test_util::stats::common_values_map::common_values_map;
use malachite_base_test_util::stats::median;
use malachite_base_test_util::sta... |
#[test]
#[should_panic]
fn random_negative_integers_fail_2() {
random_negative_integers(EXAMPLE_SEED, 2, 3);
}
| {
random_negative_integers(EXAMPLE_SEED, 1, 0);
} | identifier_body |
random_negative_integers.rs | use itertools::Itertools;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base::random::EXAMPLE_SEED;
use malachite_base_test_util::stats::common_values_map::common_values_map;
use malachite_base_test_util::stats::median;
use malachite_base_test_util::sta... | () {
// mean bits = 65/64
let values = &["-1"; 20];
let common_values = &[
("-1", 984681),
("-3", 7622),
("-2", 7455),
("-5", 73),
("-6", 66),
("-7", 54),
("-4", 44),
("-8", 2),
("-10", 2),
("-14", 1),
];
let sample_medi... | test_random_negative_integers | identifier_name |
random_negative_integers.rs | use itertools::Itertools;
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
use malachite_base::random::EXAMPLE_SEED;
use malachite_base_test_util::stats::common_values_map::common_values_map;
use malachite_base_test_util::stats::median;
use malachite_base_test_util::sta... | fn random_negative_integers_helper(
mean_bits_numerator: u64,
mean_bits_denominator: u64,
expected_values: &[&str],
expected_common_values: &[(&str, usize)],
expected_sample_median: (&str, Option<&str>),
expected_sample_moment_stats: MomentStats,
) {
let xs = random_negative_integers(EXAMPLE... | use malachite_nz_test_util::integer::IntegerCheckedToF64Wrapper;
| random_line_split |
style.rs | //! Code for applying CSS styles to the DOM.
//!
//! This is not very interesting at the moment. It will get much more
//! complicated if I add support for compound selectors.
use dom::{Node, NodeType, ElementData};
use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity};
use std::collections::HashM... |
/// A single CSS rule and the specificity of its most specific matching selector.
type MatchedRule<'a> = (Specificity, &'a Rule);
/// Find all CSS rules that match the given element.
fn matching_rules<'a>(elem: &ElementData, stylesheet: &'a Stylesheet) -> Vec<MatchedRule<'a>> {
// For now, we just do a linear sc... | {
let mut values = HashMap::new();
let mut rules = matching_rules(elem, stylesheet);
// Go through the rules from lowest to highest specificity.
rules.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
for &(_, rule) in rules.iter() {
for declaration in rule.declarations.iter() {
values.ins... | identifier_body |
style.rs | //! Code for applying CSS styles to the DOM.
//!
//! This is not very interesting at the moment. It will get much more
//! complicated if I add support for compound selectors.
use dom::{Node, NodeType, ElementData};
use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity};
use std::collections::HashM... | <'a> {
pub node: &'a Node,
pub specified_values: PropertyMap,
pub children: Vec<StyledNode<'a>>,
}
#[derive(PartialEq)]
pub enum Display {
Inline,
Block,
None,
}
impl<'a> StyledNode<'a> {
/// Return the specified value of a property if it exists, otherwise `None`.
pub fn value(&self, n... | StyledNode | identifier_name |
style.rs | //! Code for applying CSS styles to the DOM.
//!
//! This is not very interesting at the moment. It will get much more
//! complicated if I add support for compound selectors.
use dom::{Node, NodeType, ElementData};
use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity};
use std::collections::HashM... | /// Find all CSS rules that match the given element.
fn matching_rules<'a>(elem: &ElementData, stylesheet: &'a Stylesheet) -> Vec<MatchedRule<'a>> {
// For now, we just do a linear scan of all the rules. For large
// documents, it would be more efficient to store the rules in hash tables
// based on tag na... |
/// A single CSS rule and the specificity of its most specific matching selector.
type MatchedRule<'a> = (Specificity, &'a Rule);
| random_line_split |
lib.rs | use serde;
use serde::{Serialize, Deserialize};
fn str_from_size_buffer(name_size: usize, name: *const u8) -> Option<&'static str>
{
let name = unsafe { std::slice::from_raw_parts(name, name_size)};
std::str::from_utf8(name).map_or(None,Some)
}
#[derive(Serialize, Deserialize, Debug)]
struct PrepareInstallMod... | }
fn parse_message(content_type: u64, msg_type: u64, len: usize, data: *const u8) -> Messages
{
let msg_content_type = unsafe{std::mem::transmute::<u64, ContentType>(content_type)};
let buffer = unsafe { std::slice::from_raw_parts(data, len)};
match msg_type
{
1 =>
{
let bu... | random_line_split | |
lib.rs | use serde;
use serde::{Serialize, Deserialize};
fn str_from_size_buffer(name_size: usize, name: *const u8) -> Option<&'static str>
{
let name = unsafe { std::slice::from_raw_parts(name, name_size)};
std::str::from_utf8(name).map_or(None,Some)
}
#[derive(Serialize, Deserialize, Debug)]
struct PrepareInstallMod... |
#[derive(Debug)]
enum Messages
{
Unknown (&'static [u8]),
PrepareInstallModule(PrepareInstallModule)
}
#[no_mangle]
pub extern "C" fn print_hello_from_rust(msg_content_type: u64,
msg_type: u64,
buffer_size: usize,
buffer: *const u8,
) {
println!("Message: {:?} {:?} {:?} {:?}", msg_content_typ... | {
let msg_content_type = unsafe{std::mem::transmute::<u64, ContentType>(content_type)};
let buffer = unsafe { std::slice::from_raw_parts(data, len)};
match msg_type
{
1 =>
{
let buffer = unsafe { std::str::from_utf8_unchecked(buffer) };
Messages::PrepareInstallMo... | identifier_body |
lib.rs | use serde;
use serde::{Serialize, Deserialize};
fn str_from_size_buffer(name_size: usize, name: *const u8) -> Option<&'static str>
{
let name = unsafe { std::slice::from_raw_parts(name, name_size)};
std::str::from_utf8(name).map_or(None,Some)
}
#[derive(Serialize, Deserialize, Debug)]
struct PrepareInstallMod... | (msg_content_type: u64,
msg_type: u64,
buffer_size: usize,
buffer: *const u8,
) {
println!("Message: {:?} {:?} {:?} {:?}", msg_content_type, msg_type, buffer_size, buffer);
let msg = parse_message(msg_content_type, msg_type, buffer_size, buffer);
println!("Message: {:?}", msg);
}
| print_hello_from_rust | identifier_name |
check-static-values-constraints.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 ... |
// Test variadic constructor for structs. The base struct should be examined
// as well as every field present in the constructor.
// This example shouldn't fail because all the fields are safe.
static STATIC8: SafeStruct = SafeStruct{field1: SafeEnum::Variant1,
..SafeStruct{fiel... | static STATIC7: SafeStruct = SafeStruct{field1: SafeEnum::Variant1,
field2: SafeEnum::Variant3(WithDtor)};
//~^ ERROR statics are not allowed to have destructors | random_line_split |
check-static-values-constraints.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let y = { static x: Box<int> = box 3; x };
//~^ ERROR statics are not allowed to have custom pointers
} | identifier_body | |
check-static-values-constraints.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 ... | {
Variant1,
Variant2(int),
Variant3(WithDtor),
Variant4(String)
}
// These should be ok
static STATIC1: SafeEnum = SafeEnum::Variant1;
static STATIC2: SafeEnum = SafeEnum::Variant2(0);
// This one should fail
static STATIC3: SafeEnum = SafeEnum::Variant3(WithDtor);
//~^ ERROR statics are not allowed ... | SafeEnum | identifier_name |
mod.rs | //! This is a simple "Flat" rendering pipeline.
//! It doesn't support blended objects and uses front-to-back ordering.
//! The pipeline is meant for simple applications and fall-back paths.
use std::marker::PhantomData;
use gfx;
use gfx_phase;
use gfx_scene;
/// A short typedef for the phase.
pub type Phase<R> = gfx... | {
/// Failed to create a texture.
Texture(gfx::tex::TextureError),
/// Failed to link a program.
Program(gfx::ProgramError),
}
impl From<gfx::tex::TextureError> for Error {
fn from(e: gfx::tex::TextureError) -> Error {
Error::Texture(e)
}
}
impl From<gfx::ProgramError> for Error {
... | Error | identifier_name |
mod.rs | //! This is a simple "Flat" rendering pipeline.
//! It doesn't support blended objects and uses front-to-back ordering.
//! The pipeline is meant for simple applications and fall-back paths.
use std::marker::PhantomData;
use gfx;
use gfx_phase;
use gfx_scene;
/// A short typedef for the phase.
pub type Phase<R> = gfx... |
}
impl From<gfx::ProgramError> for Error {
fn from(e: gfx::ProgramError) -> Error {
Error::Program(e)
}
}
/// The core technique of the pipeline.
pub struct Technique<R: gfx::Resources> {
program: gfx::handle::Program<R>,
program_textured: gfx::handle::Program<R>,
state: gfx::DrawState,
... | {
Error::Texture(e)
} | identifier_body |
mod.rs | //! This is a simple "Flat" rendering pipeline.
//! It doesn't support blended objects and uses front-to-back ordering.
//! The pipeline is meant for simple applications and fall-back paths.
use std::marker::PhantomData;
use gfx;
use gfx_phase;
use gfx_scene;
/// A short typedef for the phase.
pub type Phase<R> = gfx... | pub struct Technique<R: gfx::Resources> {
program: gfx::handle::Program<R>,
program_textured: gfx::handle::Program<R>,
state: gfx::DrawState,
/// The default texture used for materials that don't have it.
pub default_texture: gfx::handle::Texture<R>,
}
impl<R: gfx::Resources> Technique<R> {
///... | /// The core technique of the pipeline. | random_line_split |
arc.rs | in range(0u, 10) {
//! let five = five.clone();
//!
//! Thread::spawn(move || {
//! println!("{:?}", five);
//! });
//! }
//! ```
//!
//! Sharing mutable data safely between tasks with a `Mutex`:
//!
//! ```
//! use std::sync::{Arc, Mutex};
//! use std::thread::Thread;
//!
//! let five = Arc::new(M... |
}
}
}
}
#[test]
fn manually_share_arc() {
let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
let arc_v = Arc::new(v);
let (tx, rx) = channel();
let _t = Thread::spawn(move || {
let arc_v: Arc<Vec<int>> = rx.recv().unwrap();
... | {
(*c).fetch_add(1, SeqCst);
} | conditional_block |
arc.rs | for _ in range(0u, 10) {
//! let five = five.clone();
//!
//! Thread::spawn(move || {
//! println!("{:?}", five);
//! });
//! }
//! ```
//!
//! Sharing mutable data safely between tasks with a `Mutex`:
//!
//! ```
//! use std::sync::{Arc, Mutex};
//! use std::thread::Thread;
//!
//! let five = Arc:... | data: data,
};
Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
}
/// Downgrades the `Arc<T>` to a `Weak<T>` reference.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
///
/// let weak_five = five.do... | // Start the weak pointer count as 1 which is the weak pointer that's
// held by all the strong pointers (kinda), see std/rc.rs for more info
let x = box ArcInner {
strong: atomic::AtomicUint::new(1),
weak: atomic::AtomicUint::new(1), | random_line_split |
arc.rs | in range(0u, 10) {
//! let five = five.clone();
//!
//! Thread::spawn(move || {
//! println!("{:?}", five);
//! });
//! }
//! ```
//!
//! Sharing mutable data safely between tasks with a `Mutex`:
//!
//! ```
//! use std::sync::{Arc, Mutex};
//! use std::thread::Thread;
//!
//! let five = Arc::new(M... |
}
#[stable]
impl<T: PartialEq> PartialEq for Arc<T> {
/// Equality for two `Arc<T>`s.
///
/// Two `Arc<T>`s are equal if their inner value are equal.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
///
/// let five = Arc::new(5i);
///
/// five == Arc::new(5i);
... | {
let ptr = *self._ptr;
// see comments above for why this check is here
if ptr.is_null() { return }
// If we find out that we were the last weak pointer, then its time to deallocate the data
// entirely. See the discussion in Arc::drop() about the memory orderings
if s... | identifier_body |
arc.rs | in range(0u, 10) {
//! let five = five.clone();
//!
//! Thread::spawn(move || {
//! println!("{:?}", five);
//! });
//! }
//! ```
//!
//! Sharing mutable data safely between tasks with a `Mutex`:
//!
//! ```
//! use std::sync::{Arc, Mutex};
//! use std::thread::Thread;
//!
//! let five = Arc::new(M... | (&self) -> &ArcInner<T> {
// This unsafety is ok because while this arc is alive we're guaranteed that the inner
// pointer is valid. Furthermore, we know that the `ArcInner` structure itself is `Sync`
// because the inner data is `Sync` as well, so we're ok loaning out an immutable pointer
... | inner | identifier_name |
misc.rs | //! Misc tests | use reversi::turn::*;
/// Checks `turn::check_move` method on starting turn.
#[test]
fn test_first_turn() {
let first_turn = Turn::first_turn();
for row in 0..BOARD_SIZE {
for col in 0..BOARD_SIZE {
let coord = Coord::new(row, col);
assert_eq!(first_turn.check_move(coord).is_ok(... |
extern crate reversi;
use reversi::board::*; | random_line_split |
misc.rs | //! Misc tests
extern crate reversi;
use reversi::board::*;
use reversi::turn::*;
/// Checks `turn::check_move` method on starting turn.
#[test]
fn test_first_turn() |
#[test]
fn test_second_turn() {
let mut second_turn = Turn::first_turn();
second_turn.make_move(Coord::new(2, 3)).expect("Is this move illegal?");
for row in 0..BOARD_SIZE {
for col in 0..BOARD_SIZE {
let coord = Coord::new(row, col);
assert_eq!(second_turn.check_move(coord... | {
let first_turn = Turn::first_turn();
for row in 0..BOARD_SIZE {
for col in 0..BOARD_SIZE {
let coord = Coord::new(row, col);
assert_eq!(first_turn.check_move(coord).is_ok(), match coord.get_row_col() {
(2, 3) | (3, 2) | (4, 5) | (5, 4) => true,
_... | identifier_body |
misc.rs | //! Misc tests
extern crate reversi;
use reversi::board::*;
use reversi::turn::*;
/// Checks `turn::check_move` method on starting turn.
#[test]
fn test_first_turn() {
let first_turn = Turn::first_turn();
for row in 0..BOARD_SIZE {
for col in 0..BOARD_SIZE {
let coord = Coord::new(row, co... | () {
let mut second_turn = Turn::first_turn();
second_turn.make_move(Coord::new(2, 3)).expect("Is this move illegal?");
for row in 0..BOARD_SIZE {
for col in 0..BOARD_SIZE {
let coord = Coord::new(row, col);
assert_eq!(second_turn.check_move(coord).is_ok(), match coord.get_ro... | test_second_turn | identifier_name |
pubcomp.rs | use std::io::{Read, Write};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct PubcompPacket {
fixed_header: FixedHeader,
packet_identifier: Packe... | self.packet_identifier.0
}
pub fn set_packet_identifier(&mut self, pkid: u16) {
self.packet_identifier.0 = pkid;
}
}
impl<'a> Packet<'a> for PubcompPacket {
type Payload = ();
fn fixed_header(&self) -> &FixedHeader {
&self.fixed_header
}
fn payload(&self) -> &Self... | pub fn packet_identifier(&self) -> u16 { | random_line_split |
pubcomp.rs | use std::io::{Read, Write};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct PubcompPacket {
fixed_header: FixedHeader,
packet_identifier: Packe... |
fn payload(&self) -> &Self::Payload {
&self.payload
}
fn encode_variable_headers<W: Write>(&self, writer: &mut W) -> Result<(), PacketError<'a, Self>> {
try!(self.packet_identifier.encode(writer));
Ok(())
}
fn encoded_variable_headers_length(&self) -> u32 {
self.... | {
&self.fixed_header
} | identifier_body |
pubcomp.rs | use std::io::{Read, Write};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct PubcompPacket {
fixed_header: FixedHeader,
packet_identifier: Packe... | (&self) -> u32 {
self.packet_identifier.encoded_length()
}
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<'a, Self>> {
let packet_identifier: PacketIdentifier = try!(PacketIdentifier::decode(reader));
Ok(PubcompPacket {
fixed... | encoded_variable_headers_length | identifier_name |
accept_encoding.rs | use header::{Encoding, QualityItem};
header! {
#[doc="`Accept-Encoding` header, defined in"]
#[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.4)"]
#[doc=""]
#[doc="The `Accept-Encoding` header field can be used by user agents to"]
#[doc="indicate what response content-codings are"]
... |
}
| {
let a: AcceptEncoding = Header::parse_header([b"gzip;q=1.0, identity; q=0.5".to_vec()].as_ref()).unwrap();
let b = AcceptEncoding(vec![
qitem(Encoding::Gzip),
QualityItem::new(Encoding::Identity, Quality(500)),
]);
assert_eq!(a, b);
} | identifier_body |
accept_encoding.rs | use header::{Encoding, QualityItem};
header! {
#[doc="`Accept-Encoding` header, defined in"]
#[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.4)"]
#[doc=""]
#[doc="The `Accept-Encoding` header field can be used by user agents to"]
#[doc="indicate what response content-codings are"]
... | () {
let a: AcceptEncoding = Header::parse_header([b"gzip;q=1.0, identity; q=0.5".to_vec()].as_ref()).unwrap();
let b = AcceptEncoding(vec![
qitem(Encoding::Gzip),
QualityItem::new(Encoding::Identity, Quality(500)),
]);
assert_eq!(a, b);
}
}
| test_parse_header | identifier_name |
accept_encoding.rs | use header::{Encoding, QualityItem};
| #[doc="The `Accept-Encoding` header field can be used by user agents to"]
#[doc="indicate what response content-codings are"]
#[doc="acceptable in the response. An `identity` token is used as a synonym"]
#[doc="for \"no encoding\" in order to communicate when no encoding is"]
#[doc="preferred."]
... | header! {
#[doc="`Accept-Encoding` header, defined in"]
#[doc="[RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.4)"]
#[doc=""] | random_line_split |
texture.rs | // Copyright 2017 The gltf Library Developers
//
// 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
// exce... |
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Texture {
/// The texture's format.
#[serde(default)]
pub format: Format,
/// The texture's internal format.
#[serde(rename = "internalFormat")]
#[serde(default)]
pub internal_format: Format,
/// The ID of the sampler use... | {
TexelType::U8
} | identifier_body |
texture.rs | // Copyright 2017 The gltf Library Developers
//
// 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
// exce... | () -> Wrap {
Wrap::Repeat
}
}
enum_number! {
Format {
Alpha = 6406,
Rgb = 6407,
Rgba = 6408,
Luminance = 6409,
LuminanceAlpha = 6410,
}
}
impl Default for Format {
fn default() -> Format {
Format::Rgba
}
}
enum_number! {
Target {
... | default | identifier_name |
texture.rs | // Copyright 2017 The gltf Library Developers
//
// 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
// exce... | } | ///
/// This is not necessarily unique, e.g., a texture and a buffer could have
/// the same name, or two textures could even have the same name.
pub name: Option<String>, | random_line_split |
error_codes_check.rs | //! Checks that all error codes have at least one test to prevent having error
//! codes that are silently not thrown by the compiler anymore.
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::read_to_string;
use std::path::Path;
use regex::Regex;
// A few of those error codes can't be tested but all ... |
} else if s.starts_with("#### Note: this error code is no longer emitted by the compiler") {
if!found_error_code {
error_codes.get_mut(&err_code).map(|x| x.has_test = true);
found_error_code = true;
}
}
}
invalid_compile_fail_format
}
fn ... | {
invalid_compile_fail_format = true;
} | conditional_block |
error_codes_check.rs | //! Checks that all error codes have at least one test to prevent having error
//! codes that are silently not thrown by the compiler anymore.
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::read_to_string;
use std::path::Path;
use regex::Regex;
// A few of those error codes can't be tested but all ... | reached_no_explanation = true;
}
}
}
fn extract_error_codes_from_tests(f: &str, error_codes: &mut HashMap<String, ErrorCodeStatus>) {
for line in f.lines() {
let s = line.trim();
if s.starts_with("error[E") || s.starts_with("warning[E") {
let err_code = match s.s... | // this check should *never* fail!
error_codes.insert(err_code, ErrorCodeStatus::default());
}
} else if s == ";" { | random_line_split |
error_codes_check.rs | //! Checks that all error codes have at least one test to prevent having error
//! codes that are silently not thrown by the compiler anymore.
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::read_to_string;
use std::path::Path;
use regex::Regex;
// A few of those error codes can't be tested but all ... | (
f: &str,
error_codes: &mut HashMap<String, ErrorCodeStatus>,
regex: &Regex,
) {
for line in f.lines() {
if line.trim_start().starts_with("//") {
continue;
}
for cap in regex.captures_iter(line) {
if let Some(error_code) = cap.get(1) {
err... | extract_error_codes_from_source | identifier_name |
error_codes_check.rs | //! Checks that all error codes have at least one test to prevent having error
//! codes that are silently not thrown by the compiler anymore.
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::read_to_string;
use std::path::Path;
use regex::Regex;
// A few of those error codes can't be tested but all ... | found_explanations += 1;
} else if entry.path().extension() == Some(OsStr::new("stderr")) {
extract_error_codes_from_tests(contents, &mut error_codes);
found_tests += 1;
} else if entry.path().extension() == Some(OsStr::new("rs")) {
... | {
let mut errors = Vec::new();
let mut found_explanations = 0;
let mut found_tests = 0;
let mut error_codes: HashMap<String, ErrorCodeStatus> = HashMap::new();
// We want error codes which match the following cases:
//
// * foo(a, E0111, a)
// * foo(a, E0111)
// * foo(E0111, a)
/... | identifier_body |
to_url.rs | use url::Url;
use std::path::Path;
pub trait ToUrl {
fn to_url(self) -> Result<Url, String>;
}
impl ToUrl for Url {
fn to_url(self) -> Result<Url, String> {
Ok(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Result<Url, String> |
}
impl<'a> ToUrl for &'a str {
fn to_url(self) -> Result<Url, String> {
Url::parse(self).map_err(|s| {
format!("invalid url `{}`: {}", self, s)
})
}
}
impl<'a> ToUrl for &'a Path {
fn to_url(self) -> Result<Url, String> {
Url::from_file_path(self).map_err(|()| {
... | {
Ok(self.clone())
} | identifier_body |
to_url.rs | use url::Url;
use std::path::Path;
pub trait ToUrl {
fn to_url(self) -> Result<Url, String>;
}
impl ToUrl for Url {
fn to_url(self) -> Result<Url, String> {
Ok(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Result<Url, String> {
Ok(self.clone())
}
}
impl<'a> ToUrl for ... | })
}
} | fn to_url(self) -> Result<Url, String> {
Url::from_file_path(self).map_err(|()| {
format!("invalid path url `{}`", self.display()) | random_line_split |
to_url.rs | use url::Url;
use std::path::Path;
pub trait ToUrl {
fn to_url(self) -> Result<Url, String>;
}
impl ToUrl for Url {
fn to_url(self) -> Result<Url, String> {
Ok(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Result<Url, String> {
Ok(self.clone())
}
}
impl<'a> ToUrl for ... | (self) -> Result<Url, String> {
Url::parse(self).map_err(|s| {
format!("invalid url `{}`: {}", self, s)
})
}
}
impl<'a> ToUrl for &'a Path {
fn to_url(self) -> Result<Url, String> {
Url::from_file_path(self).map_err(|()| {
format!("invalid path url `{}`", self.di... | to_url | identifier_name |
appsrc.rs | use ffi::*;
use ::Transfer;
use ::Element;
use ::Caps;
use std::mem;
use reference::Reference;
use std::ops::{Deref, DerefMut};
pub struct AppSrc{
appsrc: ::Element
}
unsafe impl Sync for AppSrc {}
unsafe impl Send for AppSrc {}
impl AppSrc{
pub fn new(name: &str) -> Option<AppSrc>{
let appsrc = ::E... | /// unknown caps, in which case no caps should be set. This is typically true of file-like
/// sources that push raw byte buffers.
pub fn set_caps(&mut self, caps: &Caps){
unsafe{
gst_app_src_set_caps(self.gst_appsrc_mut(), caps.gst_caps());
}
}
pub fn caps(&self) -> Opt... | /// match the caps OR be left unspecified.
///
/// Before operating an `AppSrc`, the `caps` property MUST be set to fixed caps describing
/// the format of the data that will be pushed with appsrc EXCEPT when pushing buffers with | random_line_split |
appsrc.rs | use ffi::*;
use ::Transfer;
use ::Element;
use ::Caps;
use std::mem;
use reference::Reference;
use std::ops::{Deref, DerefMut};
pub struct AppSrc{
appsrc: ::Element
}
unsafe impl Sync for AppSrc {}
unsafe impl Send for AppSrc {}
impl AppSrc{
pub fn new(name: &str) -> Option<AppSrc>{
let appsrc = ::E... |
}
impl ::Transfer for AppSrc{
unsafe fn transfer(self) -> *mut GstElement{
self.appsrc.transfer()
}
}
impl Reference for AppSrc{
fn reference(&self) -> AppSrc{
AppSrc{ appsrc: self.appsrc.reference() }
}
}
| {
&mut self.appsrc
} | identifier_body |
appsrc.rs | use ffi::*;
use ::Transfer;
use ::Element;
use ::Caps;
use std::mem;
use reference::Reference;
use std::ops::{Deref, DerefMut};
pub struct | {
appsrc: ::Element
}
unsafe impl Sync for AppSrc {}
unsafe impl Send for AppSrc {}
impl AppSrc{
pub fn new(name: &str) -> Option<AppSrc>{
let appsrc = ::Element::new("appsrc",name);
match appsrc{
Some(appsrc) => Some(AppSrc{appsrc: appsrc}),
None => None
}
... | AppSrc | identifier_name |
lib.rs | // @generated by Thrift for src/module.thrift
// This file is probably not the place you want to edit!
#![recursion_limit = "100000000"]
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused_crate_dependencies)]
include!("impl_my_things.rs");
include!("my/other/thing.rs");
pub use self::errors... | {
pub foo: ::std::primitive::i32,
pub bar: ::std::string::String,
// This field forces `..Default::default()` when instantiating this
// struct, to make code future-proof against new fields added later to
// the definition in Thrift. If you don't want this, add the annotation
... | MyStruct | identifier_name |
lib.rs | // @generated by Thrift for src/module.thrift
// This file is probably not the place you want to edit!
#![recursion_limit = "100000000"]
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused_crate_dependencies)]
include!("impl_my_things.rs");
include!("my/other/thing.rs");
pub use self::errors... |
}
impl<P> ::fbthrift::Deserialize<P> for self::MyStruct
where
P: ::fbthrift::ProtocolReader,
{
fn read(p: &mut P) -> ::anyhow::Result<Self> {
static FIELDS: &[::fbthrift::Field] = &[
::fbthrift::Field::new("bar", ::fbthrift::TType::String, 2),
... | {
p.write_struct_begin("MyStruct");
p.write_field_begin("foo", ::fbthrift::TType::I32, 1);
::fbthrift::Serialize::write(&self.foo, p);
p.write_field_end();
p.write_field_begin("bar", ::fbthrift::TType::String, 2);
::fbthrift::Serialize::write(&self... | identifier_body |
lib.rs | // @generated by Thrift for src/module.thrift
// This file is probably not the place you want to edit!
#![recursion_limit = "100000000"]
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused_crate_dependencies)]
include!("impl_my_things.rs");
include!("my/other/thing.rs");
pub use self::errors... | impl ::std::default::Default for self::MyStruct {
fn default() -> Self {
Self {
foo: ::std::default::Default::default(),
bar: ::std::default::Default::default(),
_dot_dot_Default_default: self::dot_dot::OtherFields(()),
}
}
... | random_line_split | |
mod.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/. */
//! The code to expose the DOM to JavaScript through IDL bindings.
//!
//! Exposing a DOM object to JavaScript
//!... | //! -------------------------------------
//!
//! A WebIDL attribute is turned into a pair of methods: one for the getter and
//! one for the setter. A readonly attribute only has a getter and no setter.
//!
//! The getter's name is the name of the attribute with the first letter
//! converted to uppercase. It has `Get... | random_line_split | |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the compo... |
pub mod platform {
#[cfg(target_os = "macos")]
pub use platform::macos::deinit;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(not(target_os = "macos"))]
pub fn deinit() {}
}
#[cfg(not(target_os = "android"))]
fn install_crash_handler() {
use backtrace::Backtrace;
use sig::ffi::Sig... | use std::panic;
use std::process;
use std::rc::Rc;
use std::thread; | random_line_split |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the compo... | else {
if opts::get().is_running_problem_test && ::std::env::var("RUST_LOG").is_err() {
::std::env::set_var("RUST_LOG", "compositing::constellation");
}
None
};
// TODO: once log-panics is released, can this be replaced by
// log_panics::init()?
panic::set_hook(Box... | {
Some(token)
} | conditional_block |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the compo... | },
Err(e) => {
debug!("Failed to open params file '{}': {}",
params_file.to_str().unwrap(),
Error::description(&e));
vec!["servo".to_owned(), "http://en.wikipedia.org/wiki/Rust".to_owned()]
},
}
}
#[cfg(not(target_os = "android"... | {
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
let mut params_file = config::basedir::default_config_dir().unwrap();
params_file.push("android_params");
match File::open(params_file.to_str().unwrap()) {
Ok(f) => {
let mut vec = Vec::new();
... | identifier_body |
main.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/. */
//! The `servo` test application.
//!
//! Creates a `Servo` instance with a simple implementation of
//! the compo... | (app: *mut ()) {
android_injected_glue::android_main2(app as *mut _, move |_, _| main());
}
| android_main | identifier_name |
error.rs | //! Types representing various errors that can occur in a Rocket application.
use std::{io, fmt};
use std::sync::atomic::{Ordering, AtomicBool};
use http::hyper;
/// [unstable] Error type for Rocket. Likely to change.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Error {
/// The request method was ... | (kind: LaunchErrorKind) -> LaunchError {
LaunchError::new(kind)
}
}
impl From<hyper::Error> for LaunchError {
#[inline]
fn from(error: hyper::Error) -> LaunchError {
match error {
hyper::Error::Io(e) => LaunchError::new(LaunchErrorKind::Io(e)),
e => LaunchError::new(... | from | identifier_name |
error.rs | //! Types representing various errors that can occur in a Rocket application.
use std::{io, fmt};
use std::sync::atomic::{Ordering, AtomicBool};
use http::hyper;
/// [unstable] Error type for Rocket. Likely to change.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Error {
/// The request method was ... | LaunchError::new(LaunchErrorKind::Io(error))
}
}
impl fmt::Display for LaunchErrorKind {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LaunchErrorKind::Io(ref e) => write!(f, "I/O error: {}", e),
LaunchErrorKind::Collision => write!(f... | #[inline]
fn from(error: io::Error) -> LaunchError { | random_line_split |
error.rs | //! Types representing various errors that can occur in a Rocket application.
use std::{io, fmt};
use std::sync::atomic::{Ordering, AtomicBool};
use http::hyper;
/// [unstable] Error type for Rocket. Likely to change.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Error {
/// The request method was ... |
LaunchErrorKind::FailedFairing => {
error!("Rocket failed to launch due to a failing fairing.");
panic!("launch fairing failure");
}
LaunchErrorKind::Unknown(ref e) => {
error!("Rocket failed to launch due to an unknown error.");
... | {
error!("Rocket failed to launch due to routing collisions.");
panic!("route collisions detected");
} | conditional_block |
mouse.rs | //! Checking the state of mouse-related properties, namely the mouse cursor's position, `n`-clicks and scrolling.
use geometry::Point;
use bear_lib_terminal_sys as ffi;
/// Amount of steps the mouse wheel scrolled in the last [`Event::MouseScroll`](../../enum.Event.html#variant.MouseScroll).
///
/// Negative values... |
/// Get the mouse cursor's position in cells.
pub fn position() -> Point {
Point::new(ffi::state(ffi::TK_MOUSE_X), ffi::state(ffi::TK_MOUSE_Y))
}
/// Get the mouse cursor's position in pixels.
pub fn pixel_position() -> Point {
Point::new(ffi::state(ffi::TK_MOUSE_PIXEL_X), ffi::state(ffi::TK_MOUSE_PIXEL_Y))
}
/// ... | ///
/// Positive values indicate a "down" scroll.
pub fn scroll() -> i32 {
ffi::state(ffi::TK_MOUSE_WHEEL)
} | random_line_split |
mouse.rs | //! Checking the state of mouse-related properties, namely the mouse cursor's position, `n`-clicks and scrolling.
use geometry::Point;
use bear_lib_terminal_sys as ffi;
/// Amount of steps the mouse wheel scrolled in the last [`Event::MouseScroll`](../../enum.Event.html#variant.MouseScroll).
///
/// Negative values... | () -> i32 {
ffi::state(ffi::TK_MOUSE_WHEEL)
}
/// Get the mouse cursor's position in cells.
pub fn position() -> Point {
Point::new(ffi::state(ffi::TK_MOUSE_X), ffi::state(ffi::TK_MOUSE_Y))
}
/// Get the mouse cursor's position in pixels.
pub fn pixel_position() -> Point {
Point::new(ffi::state(ffi::TK_MOUSE_PIXEL... | scroll | identifier_name |
mouse.rs | //! Checking the state of mouse-related properties, namely the mouse cursor's position, `n`-clicks and scrolling.
use geometry::Point;
use bear_lib_terminal_sys as ffi;
/// Amount of steps the mouse wheel scrolled in the last [`Event::MouseScroll`](../../enum.Event.html#variant.MouseScroll).
///
/// Negative values... | {
ffi::state(ffi::TK_MOUSE_CLICKS)
} | identifier_body | |
functions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | BuiltinScalarFunction::Log => math_expressions::ln,
BuiltinScalarFunction::Log2 => math_expressions::log2,
BuiltinScalarFunction::Log10 => math_expressions::log10,
BuiltinScalarFunction::Floor => math_expressions::floor,
BuiltinScalarFunction::Ceil => math_expressions::ceil,
... | BuiltinScalarFunction::Acos => math_expressions::acos,
BuiltinScalarFunction::Atan => math_expressions::atan,
BuiltinScalarFunction::Exp => math_expressions::exp, | random_line_split |
functions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | {
/// arbitrary number of arguments of an common type out of a list of valid types
// A function such as `concat` is `Variadic(vec![DataType::Utf8, DataType::LargeUtf8])`
Variadic(Vec<DataType>),
/// arbitrary number of arguments of an arbitrary but equal type
// A function such as `array` is `Vari... | Signature | identifier_name |
functions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
}
impl fmt::Display for ScalarFunctionExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}({})",
self.name,
self.args
.iter()
.map(|e| format!("{}", e))
.collect::<Vec<String>>()
... | {
Self {
fun,
name: name.to_owned(),
args,
return_type: return_type.clone(),
}
} | identifier_body |
main.rs | let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn sum_of_squares(n: usize) -> usize {
(1..(n + 1)).map(|... | macro_rules! timeit {
($func:expr) => ({ | random_line_split | |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn sum_of_squares(n:... | (n: usize) -> usize {
(1..(n + 1)).fold(0, |acc, item| acc + item).pow(2)
}
fn s_s(n: usize) -> usize {
square_of_sums(n) - sum_of_squares(n)
}
timeit!(s_s(100));
}
| square_of_sums | identifier_name |
main.rs | macro_rules! timeit {
($func:expr) => ({
let t1 = std::time::Instant::now();
println!("{:?}", $func);
let t2 = std::time::Instant::now().duration_since(t1);
println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00);
})
}
fn main() {
fn sum_of_squares(n:... |
timeit!(s_s(100));
}
| {
square_of_sums(n) - sum_of_squares(n)
} | identifier_body |
test.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... |
if has_test_attr &&!has_test_signature(i) {
let sess = cx.sess;
sess.span_err(
i.span,
"functions used as tests must have signature fn() -> ()."
);
}
return has_test_attr && has_test_signature(i);
}
fn is_bench_fn(cx: &TestCtxt, i: @ast::Item) -> bool {
... | {
match &i.node {
&ast::ItemFn(ref decl, _, _, ref generics, _) => {
let no_output = match decl.output.node {
ast::TyNil => true,
_ => false
};
decl.inputs.is_empty()
&& no_output
&& !generics.is_parame... | identifier_body |
test.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... | <T>(t: T) -> codemap::Spanned<T> {
codemap::Spanned { node: t, span: DUMMY_SP }
}
fn path_node(ids: Vec<ast::Ident> ) -> ast::Path {
ast::Path {
span: DUMMY_SP,
global: false,
segments: ids.move_iter().map(|identifier| ast::PathSegment {
identifier: identifier,
l... | nospan | identifier_name |
test.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 res = fold::noop_fold_item(i, self);
self.cx.path.borrow_mut().pop();
res
}
fn fold_mod(&mut self, m: &ast::Mod) -> ast::Mod {
// Remove any #[main] from the AST so it doesn't clash with
// the one we're going to add. Only if compiling an ex... | {
debug!("this is a test function");
let test = Test {
span: i.span,
path: self.cx.path.borrow().clone(),
bench: is_bench_fn(&self.cx, i),
ignore: is_ignored(&self.cx, i),
... | conditional_block |
test.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... | ast::TyNil => true,
_ => false
};
decl.inputs.is_empty()
&& no_output
&&!generics.is_parameterized()
}
_ => false
}
}
if has_test_attr &&!has_test_signature(i) {
let sess = cx.sess;
... | let no_output = match decl.output.node { | random_line_split |
length.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/. */
//! Animation implementation for various length-related types.
use super::{Animate, Procedure};
use crate::value... | percentage,
AllowedNumericType::All,
))
}
}
| {
let animate_percentage_half = |this: Option<Percentage>, other: Option<Percentage>| {
if this.is_none() && other.is_none() {
return Ok(None);
}
let this = this.unwrap_or_default();
let other = other.unwrap_or_default();
Ok(Some(this.a... | identifier_body |
length.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/. */
//! Animation implementation for various length-related types.
use super::{Animate, Procedure};
use crate::value... |
let this = this.unwrap_or_default();
let other = other.unwrap_or_default();
Ok(Some(this.animate(&other, procedure)?))
};
let length = self
.unclamped_length()
.animate(&other.unclamped_length(), procedure)?;
let percentage =
... | {
return Ok(None);
} | conditional_block |
length.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/. */
//! Animation implementation for various length-related types.
use super::{Animate, Procedure};
use crate::value... | // Gets clamped as needed after the animation if needed, so no need to
// specify any particular AllowedNumericType.
Ok(LengthPercentage::new_calc(
length,
percentage,
AllowedNumericType::All,
))
}
} | random_line_split | |
length.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/. */
//! Animation implementation for various length-related types.
use super::{Animate, Procedure};
use crate::value... | (&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
let animate_percentage_half = |this: Option<Percentage>, other: Option<Percentage>| {
if this.is_none() && other.is_none() {
return Ok(None);
}
let this = this.unwrap_or_default();
l... | animate | identifier_name |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... |
self.detail.set(detail.get());
event.InitEvent(type_, can_bubble, cancelable);
}
}
| {
return;
} | conditional_block |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... | type_: DOMString,
bubbles: bool,
cancelable: bool,
detail: HandleValue) -> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.r().InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail);
ev
}
pu... | random_line_split | |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... |
}
| {
let event = EventCast::from_ref(self);
if event.dispatching() {
return;
}
self.detail.set(detail.get());
event.InitEvent(type_, can_bubble, cancelable);
} | identifier_body |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... | (global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit) -> Fallible<Root<CustomEvent>>{
Ok(CustomEvent::new(global,
type_,
init.parent.bubbles,
init.parent.... | Constructor | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.