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 |
|---|---|---|---|---|
regex.rs | // Copyright (c) 2018 The predicates-rs Project 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 distr... | use crate::utils;
use crate::Predicate;
/// An error that occurred during parsing or compiling a regular expression.
pub type RegexError = regex::Error;
/// Predicate that uses regex matching
///
/// This is created by the `predicate::str::is_match`.
#[derive(Debug, Clone)]
pub struct RegexPredicate {
re: regex::... | // except according to those terms.
use std::fmt;
use crate::reflection; | random_line_split |
packed-struct-vec.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#9116) Bus error
use std::mem;
#[repr(packed)]
#[derive(Copy, PartialEq, Debug)]
struct Foo {
bar: u8,
baz: u64
}
pub ... | random_line_split | |
packed-struct-vec.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... | () {
let foos = [Foo { bar: 1, baz: 2 }; 10];
assert_eq!(mem::size_of::<[Foo; 10]>(), 90);
for i in 0u..10 {
assert_eq!(foos[i], Foo { bar: 1, baz: 2});
}
for &foo in &foos {
assert_eq!(foo, Foo { bar: 1, baz: 2 });
}
}
| main | identifier_name |
mod.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | use core::unicode::property::Pattern_White_Space;
use rustc::ty;
use syntax_pos::Span;
pub mod borrowck_errors;
pub mod elaborate_drops;
pub mod def_use;
pub mod patch;
mod alignment;
mod graphviz;
pub(crate) mod pretty;
pub mod liveness;
pub mod collect_writes;
pub use self::alignment::is_disaligned;
pub use self::... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
mod.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'cx, 'gcx, 'tcx>(
tcx: ty::TyCtxt<'cx, 'gcx, 'tcx>,
binding_span: Span,
) -> Option<(String)> {
let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap();
if hi_src.starts_with("ref")
&& hi_src["ref".len()..].starts_with(Pattern_White_Space)
{
let replacement = forma... | suggest_ref_mut | identifier_name |
mod.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| {
None
} | conditional_block |
mod.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap();
if hi_src.starts_with("ref")
&& hi_src["ref".len()..].starts_with(Pattern_White_Space)
{
let replacement = format!("ref mut{}", &hi_src["ref".len()..]);
Some(replacement)
} else {
None
}
} | identifier_body | |
block_status.rs | // Copyright 2015, 2016 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 la... | {
/// Part of the blockchain.
InChain,
/// Queued for import.
Queued,
/// Known as bad.
Bad,
/// Unknown.
Unknown,
}
impl From<QueueStatus> for BlockStatus {
fn from(status: QueueStatus) -> Self {
match status {
QueueStatus::Queued => BlockStatus::Queued,
QueueStatus::Bad => BlockStatus::Bad,
Queu... | BlockStatus | identifier_name |
block_status.rs | // Copyright 2015, 2016 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 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//!... | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful, | random_line_split |
config.rs | use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use crate::types::*;
use serde_json;
use pombase_rc_string::RcString;
// configuration for extension display names and for the "Target of" section
#[derive(Deserialize, Clone, Debug)]
pub struct Exten... | (&self) -> Option<ConfigOrganism> {
if let Some(load_organism_taxonid) = self.load_organism_taxonid {
let org = self.organism_by_taxonid(load_organism_taxonid);
if org.is_none() {
panic!("can't find configuration for load_organism_taxonid: {}",
load... | load_organism | identifier_name |
config.rs | use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use crate::types::*;
use serde_json;
use pombase_rc_string::RcString;
// configuration for extension display names and for the "Target of" section
#[derive(Deserialize, Clone, Debug)]
pub struct Exten... |
#[derive(Deserialize, Clone, Debug)]
pub struct MacromolecularComplexesConfig {
pub parent_complex_termid: RcString,
pub excluded_terms: HashSet<RcString>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct RNAcentralConfig {
// SO termids of RNA features to export
pub export_so_ids: HashSet<RcString>,... | pub link: Option<RcString>,
}
pub type DatabaseName = RcString;
pub type DatabaseAliases = HashMap<DatabaseName, DatabaseName>; | random_line_split |
config.rs | use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use crate::types::*;
use serde_json;
use pombase_rc_string::RcString;
// configuration for extension display names and for the "Target of" section
#[derive(Deserialize, Clone, Debug)]
pub struct Exten... |
} else {
CvConfig {
feature_type: "gene".into(),
..empty_cv_config
}
}
}
}
pub fn organism_by_taxonid(&self, lookup_taxonid: u32) -> Option<ConfigOrganism> {
for org in &self.organisms {
... | {
CvConfig {
feature_type: "genotype".into(),
..empty_cv_config
}
} | conditional_block |
align_of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of;
// pub fn align_of<T>() -> usize {
// unsafe { intrinsics::min_align_of::<T>() }
// }
macro_rules! align_of_test {
($T:ty, $size:expr) => ({
let size: usize = align_of::<$T>();
assert_eq!(size, ... | () {
struct A;
align_of_test!( A, 1 );
}
#[test]
fn align_of_test2() {
align_of_test!( u8, 1 );
align_of_test!( u16, 2 );
align_of_test!( u32, 4 );
align_of_test!( u64, 8 );
align_of_test!( i8, 1 );
align_of_test!( i16, 2 );
align_of_test!( i32, 4 );
align_of_test!( i64, 8 );
align_of_test!( f... | align_of_test1 | identifier_name |
align_of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of;
// pub fn align_of<T>() -> usize {
// unsafe { intrinsics::min_align_of::<T>() }
// } | let size: usize = align_of::<$T>();
assert_eq!(size, $size);
})
}
#[test]
fn align_of_test1() {
struct A;
align_of_test!( A, 1 );
}
#[test]
fn align_of_test2() {
align_of_test!( u8, 1 );
align_of_test!( u16, 2 );
align_of_test!( u32, 4 );
align_of_test!( u64, 8 );
align_of_... |
macro_rules! align_of_test {
($T:ty, $size:expr) => ({ | random_line_split |
align_of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of;
// pub fn align_of<T>() -> usize {
// unsafe { intrinsics::min_align_of::<T>() }
// }
macro_rules! align_of_test {
($T:ty, $size:expr) => ({
let size: usize = align_of::<$T>();
assert_eq!(size, ... |
#[test]
fn align_of_test2() {
align_of_test!( u8, 1 );
align_of_test!( u16, 2 );
align_of_test!( u32, 4 );
align_of_test!( u64, 8 );
align_of_test!( i8, 1 );
align_of_test!( i16, 2 );
align_of_test!( i32, 4 );
align_of_test!( i64, 8 );
align_of_test!( f32, 4 );
align_of_test!( f64, 8 );
align_of_... | {
struct A;
align_of_test!( A, 1 );
} | identifier_body |
popstateevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (window: &Window) -> DomRoot<PopStateEvent> {
reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window)
}
pub fn new(
window: &Window,
type_: Atom,
bubbles: bool,
cancelable: bool,
state: HandleValue,
) -> DomRoot<PopStateEvent> {
let ev = ... | new_uninitialized | identifier_name |
popstateevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
// https://html.spec.whatwg.org/multipage/#the-popstateevent-interface
#[dom_struct]
pub struct PopStateEvent {
event: Event,
#[ignore_malloc_size_of = "Defined in rust-mozjs"]
state: Heap<JSVal>,
}
impl PopStateEvent {
fn new_inherited() -> PopStateEvent {
PopStateEvent {
event: E... | use js::rust::HandleValue;
use servo_atoms::Atom; | random_line_split |
popstateevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
pub fn new_uninitialized(window: &Window) -> DomRoot<PopStateEvent> {
reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window)
}
pub fn new(
window: &Window,
type_: Atom,
bubbles: bool,
cancelable: bool,
state: HandleValue,
) -> DomRoot<PopS... | {
PopStateEvent {
event: Event::new_inherited(),
state: Heap::default(),
}
} | identifier_body |
debug.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | <T: Debug>(&mut self, field_name: &str, field_value: &T) {
self.add_string(field_name, format!("{:?}", field_value));
}
pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) {
let spaces = self.spaces.to_string();
let repeat = self.repeat + 1;
self.add_st... | add_debug | identifier_name |
debug.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | pub struct IndentedStructFormatter {
name: String,
fields: Vec<(String, String)>,
spaces: String,
repeat: usize,
}
impl IndentedStructFormatter {
pub fn new(name: &str, spaces: &str, repeat: usize) -> Self {
Self {
name: name.to_string(),
fields: Vec::new(),
... | its!($value, " ", 0)
};
);
| random_line_split |
debug.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... |
pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) {
let spaces = self.spaces.to_string();
let repeat = self.repeat + 1;
self.add_string(field_name, its!(field_value, &spaces, repeat));
}
pub fn fmt(&mut self) -> String {
let indent = self.spaces... | {
self.add_string(field_name, format!("{:?}", field_value));
} | identifier_body |
issue_371.rs | //! Checks that `executor.look_ahead().field_name()` is correct in presence of
//! multiple query fields.
//! See [#371](https://github.com/graphql-rust/juniper/issues/371) for details.
//!
//! Original author of this test is [@davidpdrsn](https://github.com/davidpdrsn).
use juniper::{
graphql_object, graphql_vars... | () {
let query = "{ countries { id } }";
let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context)
.await
.unwrap();
assert_eq!(errors.len(), 0);
}
#[tokio::test]
async fn both()... | countries | identifier_name |
issue_371.rs | //! Checks that `executor.look_ahead().field_name()` is correct in presence of
//! multiple query fields.
//! See [#371](https://github.com/graphql-rust/juniper/issues/371) for details.
//!
//! Original author of this test is [@davidpdrsn](https://github.com/davidpdrsn).
use juniper::{
graphql_object, graphql_vars... |
#[tokio::test]
async fn countries() {
let query = "{ countries { id } }";
let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new());
let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context)
.await
.unwrap();
assert_eq!(errors.len(), 0);... |
assert_eq!(errors.len(), 0);
} | random_line_split |
colour.rs | use super::request::*;
use std::cmp::Ordering;
/// HSB colour representation - hue, saturation, brightness (aka value).
/// Aka HSV (LIFX terminology) - hue, saturation, value.
/// This is not the same as HSL as used in CSS.
/// LIFX uses HSB aka HSV, not HSL.
#[derive(Debug)]
pub struct HSB {
pub hue: u16,
... | () {
assert_eq!(360, hue_word_to_degrees(65535));
assert_eq!(0, hue_word_to_degrees(0));
assert_eq!(180, hue_word_to_degrees(32768));
}
#[test]
fn test_saturation_percent_to_word() {
assert_eq!([0x80, 0x00], saturation_percent_to_word(50));
}
#[test]
fn test_rgb... | test_hue_word_to_degrees | identifier_name |
colour.rs | use super::request::*;
use std::cmp::Ordering;
/// HSB colour representation - hue, saturation, brightness (aka value).
/// Aka HSV (LIFX terminology) - hue, saturation, value.
/// This is not the same as HSL as used in CSS.
/// LIFX uses HSB aka HSV, not HSL.
#[derive(Debug)]
pub struct HSB {
pub hue: u16,
... | saturation: 100,
brightness: 50,
}
}
"coral" => {
HSB {
hue: 16,
saturation: 100,
brightness: 66,
}
}
"cornflower" => {
HSB {
hue: 219,
... | {
let colour: &str = &(s.to_lowercase());
match colour {
"beige" => {
HSB {
hue: 60,
saturation: 56,
brightness: 91,
}
}
"blue" => {
HSB {
hue: 240,
saturation: 100,
... | identifier_body |
colour.rs | use super::request::*;
use std::cmp::Ordering;
/// HSB colour representation - hue, saturation, brightness (aka value).
/// Aka HSV (LIFX terminology) - hue, saturation, value.
/// This is not the same as HSL as used in CSS.
/// LIFX uses HSB aka HSV, not HSL.
#[derive(Debug)]
pub struct HSB {
pub hue: u16,
... | HSB {
hue: 120,
saturation: 100,
brightness: 50,
}
}
"red" => {
HSB {
hue: 0,
saturation: 100,
brightness: 50,
}
}
"slate_gray" => {
... | brightness: 50,
}
}
"green" => { | random_line_split |
vec_conversion.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/. */
extern crate js;
use js::conversions::ConversionBehavior;
use js::conversions::FromJSValConvertible;
use js::conv... | ptr::null_mut(), h_option, &c_option);
let global_root = Rooted::new(cx, global);
let global = global_root.handle();
let _ac = JSAutoCompartment::new(cx, global.get());
assert!(JS_InitStandardClasses(cx, global));
let mut rval = RootedVal... | let cx = rt.cx();
let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook;
let c_option = CompartmentOptions::default();
let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, | random_line_split |
vec_conversion.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/. */
extern crate js;
use js::conversions::ConversionBehavior;
use js::conversions::FromJSValConvertible;
use js::conv... | orig_vec.to_jsval(cx, rval.handle_mut());
let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap();
assert_eq!(orig_vec, converted);
let orig_vec: Vec<i32> = vec![1, 2, 3];
orig_vec.to_jsval(cx, rval.handle_mut());
let converted = Vec::<i32>::from_jsval(cx... | {
unsafe {
assert!(JS_Init());
let rt = Runtime::new(ptr::null_mut());
let cx = rt.cx();
let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook;
let c_option = CompartmentOptions::default();
let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS,
... | identifier_body |
vec_conversion.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/. */
extern crate js;
use js::conversions::ConversionBehavior;
use js::conversions::FromJSValConvertible;
use js::conv... | () {
unsafe {
assert!(JS_Init());
let rt = Runtime::new(ptr::null_mut());
let cx = rt.cx();
let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook;
let c_option = CompartmentOptions::default();
let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS,
... | vec_conversion | identifier_name |
writer.rs | use schema::{Schema, Field, Document};
use fastfield::FastFieldSerializer;
use std::io;
use schema::Value;
use DocId;
use schema::FieldType;
use common;
use common::VInt;
use common::BinarySerializable;
/// The fastfieldswriter regroup all of the fast field writers.
pub struct FastFieldsWriter {
field_writers: Vec... | /// method.
///
/// We cannot serialize earlier as the values are
/// bitpacked and the number of bits required for bitpacking
/// can only been known once we have seen all of the values.
///
/// Both u64, and i64 use the same writer.
/// i64 are just remapped to the `0..2^64 - 1`
/// using `common::i64_to_u64`.
pub st... | /// The fast field writer just keeps the values in memory.
///
/// Only when the segment writer can be closed and
/// persisted on disc, the fast field writer is
/// sent to a `FastFieldSerializer` via the `.serialize(...)` | random_line_split |
writer.rs | use schema::{Schema, Field, Document};
use fastfield::FastFieldSerializer;
use std::io;
use schema::Value;
use DocId;
use schema::FieldType;
use common;
use common::VInt;
use common::BinarySerializable;
/// The fastfieldswriter regroup all of the fast field writers.
pub struct FastFieldsWriter {
field_writers: Vec... | (&mut self, doc: &Document) {
let val = self.extract_val(doc);
self.add_val(val);
}
/// Push the fast fields value to the `FastFieldWriter`.
pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> {
let (min, max) = if self.val_min > self.val_max {
... | add_document | identifier_name |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... |
pub fn can_reset(body: &Body) -> bool {
match body.reader {
Kind::Bytes(_) => true,
Kind::Reader(..) => false,
}
}
| {
match body.reader {
Kind::Bytes(ref bytes) => {
let len = bytes.len();
::hyper::client::Body::BufBody(bytes, len)
}
Kind::Reader(ref mut reader, len_opt) => {
match len_opt {
Some(len) => ::hyper::client::Body::SizedBody(reader, len),
... | identifier_body |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... |
Kind::Bytes(ref mut bytes) => {
(&**bytes).read_to_string(&mut s)
}
}.map(|_| s)
}
enum Kind {
Reader(Box<Read + Send>, Option<u64>),
Bytes(Vec<u8>),
}
impl From<Vec<u8>> for Body {
#[inline]
fn from(v: Vec<u8>) -> Body {
Body {
reader: Kind::Bytes(... | {
reader.read_to_string(&mut s)
} | conditional_block |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
&Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
}
}
}
// Wraps a `std::io::Write`.
//pub struct Pipe(... | fmt | identifier_name |
body.rs | use std::io::Read;
use std::fs::File;
use std::fmt;
/// Body type for a request.
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
/// Instantiate a `Body` from a reader.
///
/// # Note
///
/// While allowing for many types to be used, these bodies do not have
/// a way to res... | }
}
}
impl fmt::Debug for Kind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
&Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
}
... | #[inline]
fn from(f: File) -> Body {
let len = f.metadata().map(|m| m.len()).ok();
Body {
reader: Kind::Reader(Box::new(f), len), | random_line_split |
mod.rs | ::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::ServoParserBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js:... | }
/// Corresponds to the latter part of the "Otherwise" branch of the 'An end
/// tag whose tag name is "script"' of
/// https://html.spec.whatwg.org/multipage/#parsing-main-incdata
///
/// This first moves everything from the script input to the beginning of
/// the network input, effectiv... | pub fn script_nesting_level(&self) -> usize {
self.script_nesting_level.get() | random_line_split |
mod.rs | Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::ServoParserBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{... | {
Received,
NotReceived,
}
impl ServoParser {
pub fn parse_html_document(
document: &Document,
input: DOMString,
url: ServoUrl,
owner: Option<PipelineId>) {
let parser = ServoParser::new(
document,
owner,
Tokenizer... | LastChunkState | identifier_name |
handlers.rs | use x11::xlib;
use window_system::WindowSystem;
use libc::{c_ulong};
pub struct KeyPressedHandler;
pub struct MapRequestHandler;
fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong {
let border_width = 2;
unsafe {
let border = xlib::XWhitePixel... | border_width,
border,background);
xlib::XSelectInput(window_system.display,
window,
xlib::SubstructureNotifyMask | xlib::SubstructureRedirectMask);
return window;... | x,
y,
width,
height, | random_line_split |
handlers.rs | use x11::xlib;
use window_system::WindowSystem;
use libc::{c_ulong};
pub struct KeyPressedHandler;
pub struct MapRequestHandler;
fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong {
let border_width = 2;
unsafe {
let border = xlib::XWhitePixel... |
else {
width = (window_system.info.width / 2) as u32;
height = window_system.info.height as u32;
x = width as i32;
}
// create frame as a new parent for the window to be mapped
let frame = create_some_window(window_system, width, height, x, y);
... | {
width = window_system.info.width as u32;
height = window_system.info.height as u32;
} | conditional_block |
handlers.rs | use x11::xlib;
use window_system::WindowSystem;
use libc::{c_ulong};
pub struct KeyPressedHandler;
pub struct | ;
fn create_some_window(window_system: &WindowSystem, width: u32, height: u32, x: i32, y: i32) -> c_ulong {
let border_width = 2;
unsafe {
let border = xlib::XWhitePixel(window_system.display,
xlib::XDefaultScreen(window_system.display));
let backgro... | MapRequestHandler | identifier_name |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn main() | }
if!p.ends_with(".MP4") {
continue;
}
// 0123456789AB
// GX030293.MP4
if p.len()!= 0xc {
continue;
}
let s = match p.to_str() {
Some(s) => s,
None => contin... | {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get_matches();
if let Some(matches) = matches.subcomman... | identifier_body |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn main() {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get_mat... | let n = s[4..8];
bases.entry((k, n)).
}
}
println!("Hello, world!");
} | // note: we could probably mix these.
let k = s[1];
// GXaa1234 - aa - the index of clip
let i = s[2..4];
// GX01bbbb - bbbb - the number of the video (composed of clips) | random_line_split |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn | () {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get_matches();
if let Some(matches) = matches.subcommand... | main | identifier_name |
main.rs | #![macro_use]
extern crate clap;
use std::fs;
fn main() {
let matches = app_from_crate!()
.subcommand(SubCommand::with_name("create-combine-lists")
.arg(Arg::with_name("DIR")
.required(true)
.index(1)
)
).get_mat... |
let s = match p.to_str() {
Some(s) => s,
None => continue,
}
// P (x264) or X (x265)
// note: we could probably mix these.
let k = s[1];
// GXaa1234 - aa - the index of clip
let i = s[2..4];
... | {
continue;
} | conditional_block |
mod.rs | use crate::{
commands::CommandHelpers,
entity::{EntityRef, Realm},
player_output::PlayerOutput,
};
mod enter_room_command;
pub use enter_room_command::enter_room;
pub fn | <F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Realm, EntityRef, CommandHelpers) -> Result<Vec<PlayerOutput>, String> +'static,
{
Box::new(
move |realm, player_ref, helpers| match realm.player(player_ref) {
Some(player) if player.... | wrap_admin_command | identifier_name |
mod.rs | use crate::{
commands::CommandHelpers,
entity::{EntityRef, Realm},
player_output::PlayerOutput,
};
mod enter_room_command;
pub use enter_room_command::enter_room;
pub fn wrap_admin_command<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Real... | {
Box::new(
move |realm, player_ref, helpers| match realm.player(player_ref) {
Some(player) if player.is_admin() => match f(realm, player_ref, helpers) {
Ok(output) => output,
Err(mut message) => {
message.push('\n');
let mu... | identifier_body | |
mod.rs | use crate::{
commands::CommandHelpers,
entity::{EntityRef, Realm},
player_output::PlayerOutput,
};
mod enter_room_command;
pub use enter_room_command::enter_room;
pub fn wrap_admin_command<F>(
f: F,
) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>>
where
F: Fn(&mut Real... | push_output_string!(output, player_ref, message);
output
}
},
_ => {
let mut output: Vec<PlayerOutput> = Vec::new();
push_output_str!(output, player_ref, "You are not an admin.");
output
... | let mut output: Vec<PlayerOutput> = Vec::new(); | random_line_split |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (r : rand::rng, n : uint) -> bool { under(r, n) == 0u }
// shuffle a vec in place
fn shuffle<T>(r : rand::rng, &v : ~[T]) {
let i = vec::len(v);
while i >= 2u {
// Loop invariant: elements with index >= i have been locked in place.
i -= 1u;
vec::swap(v, i, under(r, i + 1u)); // Lock ele... | unlikely | identifier_name |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | );
let mut a = ~[1, 2, 3];
shuffle(r, a);
log(error, a);
let i = 0u;
let v = ~[
{weight:1u, item:"low"},
{weight:8u, item:"middle"},
{weight:1u, item:"high"}
];
let w = weighted_vec(v);
while i < 1000u {
log(error, "Immed: " + weighted_choice(r, v));
... | { "likely" } | conditional_block |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(vec::len(v)!= 0u);
let total = 0u;
for {weight: weight, item: _} in v {
total += weight;
}
assert!(total >= 0u);
let chosen = under(r, total);
let so_far = 0u;
for {weight: weight, item: item} in v {
so_far += weight;
if so_far > chosen {
retur... | // * weighted_vec is O(total weight) space
type weighted<T> = { weight: uint, item: T };
fn weighted_choice<T:copy>(r : rand::rng, v : ~[weighted<T>]) -> T { | random_line_split |
rand_util.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | log(error, "Immed: " + weighted_choice(r, v));
log(error, "Fast: " + choice(r, w));
i += 1u;
}
}
| {
let r = rand::mk_rng();
log(error, under(r, 5u));
log(error, choice(r, ~[10, 20, 30]));
log(error, if unlikely(r, 5u) { "unlikely" } else { "likely" });
let mut a = ~[1, 2, 3];
shuffle(r, a);
log(error, a);
let i = 0u;
let v = ~[
{weight:1u, item:"low"},
{weight:... | identifier_body |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct | {
pub key: u64,
pub disps: Vec<(u32, u32)>,
pub map: Vec<usize>,
}
pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState {
let mut rng = XorShiftRng::from_seed(FIXED_SEED);
loop {
if let Some(s) = try_generate_hash(entries, &mut rng) {
return s;
}
}
}
fn try... | HashState | identifier_name |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct HashState {
pub k... |
fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> {
struct Bucket {
idx: usize,
keys: Vec<usize>,
}
struct Hashes {
g: u32,
f1: u32,
f2: u32,
}
let key = rng.gen();
let hashes: Vec<_> = entries.iter()
... | {
let mut rng = XorShiftRng::from_seed(FIXED_SEED);
loop {
if let Some(s) = try_generate_hash(entries, &mut rng) {
return s;
}
}
} | identifier_body |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct HashState {
pub k... | }
// Sort descending
buckets.sort_by(|a, b| a.keys.len().cmp(&b.keys.len()).reverse());
let table_len = entries.len();
let mut map = vec![None; table_len];
let mut disps = vec![(0u32, 0u32); buckets_len];
// store whether an element from the bucket being placed is
// located at a cert... | })
.collect::<Vec<_>>();
for (i, hash) in hashes.iter().enumerate() {
buckets[(hash.g % (buckets_len as u32)) as usize].keys.push(i); | random_line_split |
lib.rs | #![doc(html_root_url="https://docs.rs/phf_generator/0.7.20")]
extern crate phf_shared;
extern crate rand;
use phf_shared::PhfHash;
use rand::{SeedableRng, XorShiftRng, Rng};
const DEFAULT_LAMBDA: usize = 5;
const FIXED_SEED: [u32; 4] = [3141592653, 589793238, 462643383, 2795028841];
pub struct HashState {
pub k... |
}
}
fn try_generate_hash<H: PhfHash>(entries: &[H], rng: &mut XorShiftRng) -> Option<HashState> {
struct Bucket {
idx: usize,
keys: Vec<usize>,
}
struct Hashes {
g: u32,
f1: u32,
f2: u32,
}
let key = rng.gen();
let hashes: Vec<_> = entries.iter()
... | {
return s;
} | conditional_block |
dropck_vec_cycle_checked.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 ... | }
#[derive(Debug)]
struct C<'a> {
id: Id,
v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
}
impl<'a> HasId for Cell<Option<&'a C<'a>>> {
fn count(&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
... | fn drop(&mut self) {
assert!(self.v.count() > 0);
} | random_line_split |
dropck_vec_cycle_checked.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 ... | () -> Id {
let c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop fo... | new | identifier_name |
html2html.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... | use html5ever::driver::ParseOpts;
use html5ever::tree_builder::TreeBuilderOpts;
use html5ever::{parse, one_input, serialize};
fn main() {
let input = io::stdin().read_to_string().unwrap();
let dom: RcDom = parse(one_input(input), ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: tru... | use std::default::Default;
use html5ever::sink::rcdom::RcDom; | random_line_split |
html2html.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... | {
let input = io::stdin().read_to_string().unwrap();
let dom: RcDom = parse(one_input(input), ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: true,
..Default::default()
},
..Default::default()
});
// The validator.nu HTML2HTML always prints a do... | identifier_body | |
html2html.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... | () {
let input = io::stdin().read_to_string().unwrap();
let dom: RcDom = parse(one_input(input), ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: true,
..Default::default()
},
..Default::default()
});
// The validator.nu HTML2HTML always prints a d... | main | identifier_name |
lib.rs | #![feature(no_std,core_intrinsics)]
#![no_std]
#[macro_export]
macro_rules! impl_fmt
{
(@as_item $($i:item)*) => {$($i)*};
($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t {
fn fmt(&$s... | $(impl_from!{ @as_item
impl$(<$($params)+>)* ::std::convert::From<$src> for $t {
fn from($v: $src) -> $t {
$($code)*
}
}
})+
};
(@match_ $( $(<($($params:tt)+)>)* Into<$dst:ty>($self_:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl$(<$($params)+>)* ::std::convert:... | (@as_item $($i:item)*) => {$($i)*};
(@match_ $( $(<($($params:tt)+)>)* From<$src:ty>($v:ident) for $t:ty { $($code:stmt)*} )+) => { | random_line_split |
lib.rs | #![feature(no_std,core_intrinsics)]
#![no_std]
#[macro_export]
macro_rules! impl_fmt
{
(@as_item $($i:item)*) => {$($i)*};
($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t {
fn fmt(&$s... |
#[macro_export]
macro_rules! type_name {
($t:ty) => ( $crate::type_name::<$t>() );
}
#[macro_export]
macro_rules! todo
{
( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) );
( $s:expr, $($v:tt)* ) => ( panic!( concat!("TODO: ",$s), $($v)* ) );
}
/// Override libcore's `try!` macro with one that backs onto `From`
#[... | {
// SAFE: Intrinsic with no sideeffect
unsafe { ::core::intrinsics::type_name::<T>() }
} | identifier_body |
lib.rs | #![feature(no_std,core_intrinsics)]
#![no_std]
#[macro_export]
macro_rules! impl_fmt
{
(@as_item $($i:item)*) => {$($i)*};
($( /*$(<($($params:tt)+)>)* */ $tr:ident($s:ident, $f:ident) for $t:ty { $($code:stmt)*} )+) => {
$(impl_from!{ @as_item
impl/*$(<$($params)+>)* */ ::std::fmt::$tr for $t {
fn fmt(&$s... | <T:?::core::marker::Sized>() -> &'static str {
// SAFE: Intrinsic with no sideeffect
unsafe { ::core::intrinsics::type_name::<T>() }
}
#[macro_export]
macro_rules! type_name {
($t:ty) => ( $crate::type_name::<$t>() );
}
#[macro_export]
macro_rules! todo
{
( $s:expr ) => ( panic!( concat!("TODO: ",$s) ) );
( $s:ex... | type_name | identifier_name |
msgsend-pipes.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = args[1].parse::<usize>().unwrap();
let workers = args[2].parse::<usize>().unwrap();
let num_bytes = 100;
let mut result = None;
let mut to_parent = Some(to_parent);
let dur = Duration::span(|| {
let to_p... | {
let mut count: usize = 0;
let mut done = false;
while !done {
match requests.recv() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
count += b;
}
Er... | identifier_body |
msgsend-pipes.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //
// I *think* it's the same, more or less.
#![feature(std_misc)]
use std::sync::mpsc::{channel, Sender, Receiver};
use std::env;
use std::thread;
use std::time::Duration;
enum request {
get_count,
bytes(usize),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<usize>) {
let mut cou... | //
// http://github.com/PaulKeeble/ScalaVErlangAgents | random_line_split |
msgsend-pipes.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (requests: &Receiver<request>, responses: &Sender<usize>) {
let mut count: usize = 0;
let mut done = false;
while!done {
match requests.recv() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} byt... | server | identifier_name |
mod.rs | // Copyright (c) 2019, Ben Boeckel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of cond... | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
... | // may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | random_line_split |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... |
/// close all file descriptors other than the base directory, and return the errno for
/// convenience with `return`
fn ret_error(
dir_stack: &mut Vec<RawFd>,
errno: host::__wasi_errno_t,
) -> Result<(RawFd, OsString), host::__wasi_errno_t> {
if let Some(dirfds) = dir_stack.get(... | {
use nix::errno::Errno;
use nix::fcntl::{openat, readlinkat, OFlag};
use nix::sys::stat::Mode;
const MAX_SYMLINK_EXPANSIONS: usize = 128;
/// close all the intermediate file descriptors, but make sure not to drop either the original
/// dirfd or the one we return (which may be the same dirfd)... | identifier_body |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... | () -> c_long {
-1
}
#[cfg(not(target_os = "macos"))]
pub fn utime_omit() -> c_long {
libc::UTIME_OMIT
}
#[cfg(target_os = "macos")]
pub fn utime_omit() -> c_long {
-2
}
| utime_now | identifier_name |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... |
// not a symlink, so we're done;
return Ok((
ret_dir_success(&mut dir_stack),
OsStr::from_bytes(component).to_os_string(),
));
}
}
if path_stack.is_empty() {
// no further components to proc... | random_line_split | |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... |
Err(e)
// Check to see if it was a symlink. Linux indicates
// this with ENOTDIR because of the O_DIRECTORY flag.
if e.as_errno() == Some(Errno::ELOOP)
|| e.as_errno() == Some(Errno::EMLINK)
... | {
dir_stack.push(new_dir);
continue;
} | conditional_block |
tydecode.rs | ://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to th... | (st: @mut PState, is_last: @fn(char) -> bool) ->
ast::ident {
let rslt = scan(st, is_last, str::from_bytes);
return st.tcx.sess.ident_of(rslt);
}
pub fn parse_state_from_data(data: @~[u8], crate_num: int,
pos: uint, tcx: ty::ctxt) -> @mut PState {
@mut PState {
data:... | parse_ident_ | identifier_name |
tydecode.rs | ://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to th... |
pub fn parse_arg_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt,
conv: conv_did) -> ty::arg {
let st = parse_state_from_data(data, crate_num, pos, tcx);
parse_arg(st, conv)
}
fn parse_path(st: @mut PState) -> @ast::path {
let mut idents: ~[ast::ident] = ~[];
fn is_l... | {
let st = parse_state_from_data(data, crate_num, pos, tcx);
parse_ty(st, conv)
} | identifier_body |
tydecode.rs | http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according ... | }
'T' => {
assert!((next(st) == '['));
let mut params = ~[];
while peek(st)!= ']' { params.push(parse_ty(st, conv)); }
st.pos = st.pos + 1u;
return ty::mk_tup(st.tcx, params);
}
'f' => {
return ty::mk_closure(st.tcx, parse_closure_ty(st, conv));
... | random_line_split | |
mock.rs | use std::{
io::{self, Cursor, Read, Write},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
written: Cursor<Vec<u8>>,
received: Cursor<Vec<u8>>,
}
impl ... | (&self) -> &[u8] {
self.received.get_ref()
}
}
impl AsyncRead for MockStream {
fn poll_read(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(self.as_mut().received.read(buf))
}
}
impl AsyncWrite for MockS... | received | identifier_name |
mock.rs | use std::{
io::{self, Cursor, Read, Write},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
written: Cursor<Vec<u8>>,
received: Cursor<Vec<u8>>,
}
impl ... | fn poll_read(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(self.as_mut().received.read(buf))
}
}
impl AsyncWrite for MockStream {
fn poll_write(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
... | }
impl AsyncRead for MockStream { | random_line_split |
mock.rs | use std::{
io::{self, Cursor, Read, Write},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
written: Cursor<Vec<u8>>,
received: Cursor<Vec<u8>>,
}
impl ... |
}
| {
Poll::Ready(Ok(()))
} | identifier_body |
sync-send-iterators-in-libcore.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 is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
)+
})
}
fn main() {
// for char.rs
all_sync_send!("Я"... | {} | identifier_body |
sync-send-iterators-in-libcore.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 ... | <T>(_: T) where T: Sync {}
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
)+
})
}
fn main() {
// for char... | is_sync | identifier_name |
sync-send-iterators-in-libcore.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 ... | // pretty-expanded FIXME #23616
#![feature(collections)]
fn is_sync<T>(_: T) where T: Sync {}
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
cipher.rs | //! Implements the basic XTEA cipher routines as described in the
//! paper (http://en.wikipedia.org/wiki/XTEA). These functions only
//! deal with a single 64-bit block of data at a time.
static NUM_ROUNDS: u32 = 32;
use super::{Key, Block};
/// Encrypts 64 bits of `input` using the `key`.
///
/// # Example:
/// `... | {
let key: Key = [10, 20, 30, 42];
let plaintext: Block = [300, 400];
let ciphertext = encipher(&key, &plaintext);
assert!(plaintext != ciphertext);
assert_eq!(plaintext, decipher(&key, &ciphertext));
} | identifier_body | |
cipher.rs | //! Implements the basic XTEA cipher routines as described in the
//! paper (http://en.wikipedia.org/wiki/XTEA). These functions only
//! deal with a single 64-bit block of data at a time.
static NUM_ROUNDS: u32 = 32;
use super::{Key, Block};
/// Encrypts 64 bits of `input` using the `key`.
///
/// # Example:
/// `... |
#[test]
fn it_works() {
let key: Key = [10, 20, 30, 42];
let plaintext: Block = [300, 400];
let ciphertext = encipher(&key, &plaintext);
assert!(plaintext!= ciphertext);
assert_eq!(plaintext, decipher(&key, &ciphertext));
} | }
[v0, v1]
} | random_line_split |
cipher.rs | //! Implements the basic XTEA cipher routines as described in the
//! paper (http://en.wikipedia.org/wiki/XTEA). These functions only
//! deal with a single 64-bit block of data at a time.
static NUM_ROUNDS: u32 = 32;
use super::{Key, Block};
/// Encrypts 64 bits of `input` using the `key`.
///
/// # Example:
/// `... | (key: &Key, input: &Block) -> Block {
let [mut v0, mut v1] = *input;
let delta = 0x9E3779B9;
let mut sum: u32 = 0;
for _ in 0..NUM_ROUNDS {
v0 = v0.wrapping_add((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize])));
sum = sum.wrapping_add(delta);
... | encipher | identifier_name |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... | &[]
};
Message::deserialize(&message[..3], text)
}
}
} | random_line_split | |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... | {
pub identity: String,
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub enum Message {
ADL { ops: Vec<String> },
AOP { character: String },
BRO { message: String },
CDS {
channel: String,
description: String,
},
CHA { channels: Vec<String> },
CIU {
sender:... | UserObject | identifier_name |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... |
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ParseError::*;
match *self {
Json(ref err) => err.fmt(f),
InvalidMessage => "Invalid F-Chat message received.".fmt(f),
}
}
}
impl ::std::error::Error for Parse... | {
ParseError::Json(error)
} | identifier_body |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... |
}
}
| {
let text = if message.len() >= 4 {
&message[4..]
} else {
&[]
};
Message::deserialize(&message[..3], text)
} | conditional_block |
text_info.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates};
use crate::tree::Count;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TextInfo {
pub(crate) bytes: Count,
pub(crate) chars: Count,
pub(crate) utf16_surrogates: Count,
p... | impl TextInfo {
#[inline]
pub fn new() -> TextInfo {
TextInfo {
bytes: 0,
chars: 0,
utf16_surrogates: 0,
line_breaks: 0,
}
}
#[inline]
pub fn from_str(text: &str) -> TextInfo {
TextInfo {
bytes: text.len() as Count,... | random_line_split | |
text_info.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates};
use crate::tree::Count;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TextInfo {
pub(crate) bytes: Count,
pub(crate) chars: Count,
pub(crate) utf16_surrogates: Count,
p... |
}
impl Add for TextInfo {
type Output = Self;
#[inline]
fn add(self, rhs: TextInfo) -> TextInfo {
TextInfo {
bytes: self.bytes + rhs.bytes,
chars: self.chars + rhs.chars,
utf16_surrogates: self.utf16_surrogates + rhs.utf16_surrogates,
line_breaks: se... | {
TextInfo {
bytes: text.len() as Count,
chars: count_chars(text) as Count,
utf16_surrogates: count_utf16_surrogates(text) as Count,
line_breaks: count_line_breaks(text) as Count,
}
} | identifier_body |
text_info.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates};
use crate::tree::Count;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TextInfo {
pub(crate) bytes: Count,
pub(crate) chars: Count,
pub(crate) utf16_surrogates: Count,
p... | (&mut self, other: TextInfo) {
*self = *self + other;
}
}
impl Sub for TextInfo {
type Output = Self;
#[inline]
fn sub(self, rhs: TextInfo) -> TextInfo {
TextInfo {
bytes: self.bytes - rhs.bytes,
chars: self.chars - rhs.chars,
utf16_surrogates: self.u... | add_assign | identifier_name |
issue-15381.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 values: Vec<u8> = vec![1,2,3,4,5,6,7,8];
for
[x,y,z]
//~^ ERROR refutable pattern in `for` loop binding: `[]` not covered
in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) {
println!("y={}", y);
}
} | identifier_body | |
issue-15381.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 values: Vec<u8> = vec![1,2,3,4,5,6,7,8];
for
[x,y,z]
//~^ ERROR refutable pattern in `for` loop binding: `[]` not covered
in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) {
println!("y={}", y);
}
}
| main | identifier_name |
issue-15381.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 ... | println!("y={}", y);
}
} |
for
[x,y,z]
//~^ ERROR refutable pattern in `for` loop binding: `[]` not covered
in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) { | random_line_split |
mod.rs | pub use self::manager::ContextManager;
pub use self::manager::ViewContext;
pub use self::manager::ViewContextMut;
mod manager;
//mod proxies;
//use mopa;
use std::collections::HashMap;
use store::StoreValueStatic;
use {
Store,
StoreValue,
AttributeGetResult,
AttributeMutResult,
AttributeSetResult
... | }
} |
fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store + 'static>> {
self.stores.get_mut(&key) | random_line_split |
mod.rs | pub use self::manager::ContextManager;
pub use self::manager::ViewContext;
pub use self::manager::ViewContextMut;
mod manager;
//mod proxies;
//use mopa;
use std::collections::HashMap;
use store::StoreValueStatic;
use {
Store,
StoreValue,
AttributeGetResult,
AttributeMutResult,
AttributeSetResult
... |
}
// Context implementation
impl Context for AmbientModel {
fn register_value<V: Into<StoreValueStatic>>(&mut self, key: String, value: V) {
self.values.insert(key, value.into());
}
fn register_store<S: Store +'static>(&mut self, key: String, store: S) {
self.stores.insert(key, Box::new(... | {
match self.stores.set_attribute(k.clone(), value) {
AttributeSetResult::NoSuchProperty(v) => {
self.values.set_attribute(k, v)
}
_ => AttributeSetResult::Stored
}
} | identifier_body |
mod.rs | pub use self::manager::ContextManager;
pub use self::manager::ViewContext;
pub use self::manager::ViewContextMut;
mod manager;
//mod proxies;
//use mopa;
use std::collections::HashMap;
use store::StoreValueStatic;
use {
Store,
StoreValue,
AttributeGetResult,
AttributeMutResult,
AttributeSetResult
... | <S: Store +'static>(&mut self, key: String, store: S) {
self.stores.insert(key, Box::new(store) as Box<Store>);
}
fn get_store_mut(&mut self, key: String) -> Option<&mut Box<Store +'static>> {
self.stores.get_mut(&key)
}
}
| register_store | identifier_name |
object.rs | use std::sync::Arc;
use ::types::{Vec3f, Mat4f};
use ::Material;
use ::ray::Ray;
pub struct | {
ray: Ray, // Ray that intersected
pub time: f64,
normal: Vec3f,
object: Arc<Object>
}
pub struct ObjectData {
// texture
transformation: Mat4f,
inv_trans: Mat4f
}
pub trait Object {
/// Return whether ray intersected object
fn intersection(&self, ray: &Ray) -> Opt... | Intersection | identifier_name |
object.rs | use std::sync::Arc;
use ::types::{Vec3f, Mat4f};
use ::Material;
use ::ray::Ray;
pub struct Intersection {
ray: Ray, // Ray that intersected
pub time: f64,
normal: Vec3f,
object: Arc<Object>
}
pub struct ObjectData {
// texture
transformation: Mat4f,
inv_trans: Mat4f
}
pub... | // fn children
// pre computed
// trans_inverse
// aabb
} | random_line_split | |
grabbing.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use glutin::{Event, ElementState};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn main() {
let window = glutin::WindowBuilder::new().build().unwrap();
window.set_title("glutin - Cursor grabbing t... | else {
grabbed = true;
window.set_cursor_state(glutin::CursorState::Grab)
.ok().expect("could not grab mouse cursor");
}
},
Event::Closed => break,
a @ Event::MouseMoved(_, _) => {
pri... | {
grabbed = false;
window.set_cursor_state(glutin::CursorState::Normal)
.ok().expect("could not ungrab mouse cursor");
} | conditional_block |
grabbing.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use glutin::{Event, ElementState};
mod support;
#[cfg(target_os = "android")] | window.set_title("glutin - Cursor grabbing test");
let _ = unsafe { window.make_current() };
let context = support::load(&window);
let mut grabbed = false;
for event in window.wait_events() {
match event {
Event::KeyboardInput(ElementState::Pressed, _, _) => {
i... | android_start!(main);
fn main() {
let window = glutin::WindowBuilder::new().build().unwrap(); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.