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 |
|---|---|---|---|---|
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(se... | {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect()
} | identifier_body |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
... | () {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));... | line_through | identifier_name |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
... | #[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.co... | }
}
| random_line_split |
classes-cross-crate.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 nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | identifier_body | |
classes-cross-crate.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 | // <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.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn main() {
let mut nyan = cat(0u, 2, ~"nyan");
... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
classes-cross-crate.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 nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
}
| main | identifier_name |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
//... | (stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
... | read_and_decode | identifier_name |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result; | // Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_... | random_line_split | |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
//... | }
Ok(results)
}
}
| {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
... | identifier_body |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum HttpMethod {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlo... | HttpMethod::Checkout => "CHECKOUT".to_string(),
HttpMethod::Merge => "MERGE".to_string(),
HttpMethod::MSearch => "M-SEARCH".to_string(),
HttpMethod::Notify => "NOTIFY".to_string(),
HttpMethod::Subscribe => "SUBSCRIBE".to_string(),
... | {
match *self {
HttpMethod::Delete => "DELETE".to_string(),
HttpMethod::Get => "GET".to_string(),
HttpMethod::Head => "HEAD".to_string(),
HttpMethod::Post => "POST".to_string(),
HttpMethod::Put => "Put".to_string(),
... | identifier_body |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum | {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlock,
// subversion
Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
No... | HttpMethod | identifier_name |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum HttpMethod {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlo... | Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
Notify,
Subscribe,
Unsubscribe,
// RFC-5789
Patch,
Purge,
// CalDAV
MKCalendar,
}
impl ToString for HttpMethod {
fn to_string(&self) -> String {
match *self {
HttpMethod::Delete =>... | random_line_split | |
lib.rs | //! `bincode` is a crate for encoding and decoding using a tiny binary
//! serialization strategy.
//!
//! There are simple functions for encoding to `Vec<u8>` and decoding from
//! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from`
//! functions which respectively allow encoding into a `std::i... | {
Infinite,
Bounded(u64)
}
| SizeLimit | identifier_name |
lib.rs | //! `bincode` is a crate for encoding and decoding using a tiny binary
//! serialization strategy.
//!
//! There are simple functions for encoding to `Vec<u8>` and decoding from
//! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from`
//! functions which respectively allow encoding into a `std::i... | pub use refbox::{RefBox, StrBox, SliceBox};
mod refbox;
pub mod rustc_serialize;
pub mod serde;
/// A limit on the amount of bytes that can be read or written.
///
/// Size limits are an incredibly important part of both encoding and decoding.
///
/// In order to prevent DOS attacks on a decoder, it is important to l... | random_line_split | |
trait-attributes.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT | // 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 accordin... | // file at the top-level directory of this distribution and at | random_line_split |
trait-attributes.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| {} | identifier_body |
trait-attributes.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
impl Bar {
// @has foo/struct.Bar.html '//h4[@id="method.bar"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar() {}
// @has foo/struct.Bar.html '//h4[@id="method.bar2"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar2() {}
}
| Bar | identifier_name |
attributes.rs | #!/she-bang line
//inner attributes
#![crate_type = "lib"]
#![crate_name = "rary"]
mod empty {}
fn main() {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() |
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_export]
macro_rules! give_me_struct {
($name:ident) => {
#[allow(non_camel_case_types)]
struct $name;
}
}
#[cfg(not(test))]
give_me_struct! {
hello_world
}
#[post("/", data = "<todo_form>")]
fn string_value() {}
| {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
} | identifier_body |
attributes.rs | #!/she-bang line
//inner attributes | #![crate_name = "rary"]
mod empty {}
fn main() {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
}
stru... | #![crate_type = "lib"] | random_line_split |
attributes.rs | #!/she-bang line
//inner attributes
#![crate_type = "lib"]
#![crate_name = "rary"]
mod empty {}
fn | () {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
}
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_exp... | main | identifier_name |
lib.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... | #![crate_type = "dylib"]
#![allow(dead_code, non_camel_case_types, missing_doc)]
#![feature(struct_variant)]
#![feature(globs)]
#![unstable]
extern crate libc;
pub use self::window::Window;
pub use self::video_mode::VideoMode;
pub use self::window_builder::WindowBuilder;
pub use self::context_settings::ContextSetting... |
#![crate_name = "verdigris"]
#![desc = "Multi plateform opengl windowing for Rust"]
#![license = "MIT"]
#![crate_type = "rlib"] | random_line_split |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf... | (
&mut self,
id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
{
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { g... | confirm_request | identifier_name |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf... |
pub fn reject_request(&mut self, id: U256) ->
BoxFuture<Result<bool, RpcError>, Canceled>
{
self.rpc.request("signer_rejectRequest", vec![
JsonValue::String(format!("{:#x}", id))
])
}
}
| {
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_gas_price, gas: new_gas, min_block: new_min_block }),
to_value(&pwd),
])
} | identifier_body |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf... | id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
{
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_g... | }
pub fn confirm_request(
&mut self, | random_line_split |
feature-gate-unboxed-closures.rs | // Copyright 2016 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 ... |
//~^^^ ERROR rust-call ABI is subject to change (see issue #29625)
}
fn main() {
assert_eq!(Test(1u32, 2u32), 3u32);
}
| {
a + b
} | identifier_body |
feature-gate-unboxed-closures.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(Test(1u32, 2u32), 3u32);
}
| main | identifier_name |
feature-gate-unboxed-closures.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <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.
struct Test;
impl FnOnce<(u32, u32)> for Test {
type Output = u32;
extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 {
a ... | // 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 | random_line_split |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn | () {
let conn = rocket().1;
let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
assert_eq!(expected_keys, actual_keys);
}
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
le... | db_connection | identifier_name |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn db_connection() {
let conn = rocket().1;
| assert_eq!(expected_keys, actual_keys);
}
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispa... | let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
| random_line_split |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn db_connection() |
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispatch();
let session_key: Vec<String> = pr... | {
let conn = rocket().1;
let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
assert_eq!(expected_keys, actual_keys);
} | identifier_body |
borrowck-let-suggestion-suffixes.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 ... | () {
f();
}
| main | identifier_name |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let young = ['y']; // statement 3
//~^ NOTE...but borrowed value is only valid for the block suffix following statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[..]` does not live long enough
let mut v3 = Vec::new(); // statement 5
//~^ NOTE reference must be valid for... | //~^ NOTE reference must be valid for the block suffix following statement 2
| random_line_split |
borrowck-let-suggestion-suffixes.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 ... | {
f();
} | identifier_body | |
TestNativeRsqrt.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... | * See the License for the specific language governing permissions and
* limitations under the License.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
float __attribute__((kernel)) testNativeRsqrtFloatFl... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... |
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
... | {
lt as *mut Vec<*mut cef_string_t>
} | identifier_body |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... | (lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len()!= 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
... | cef_string_list_clear | identifier_name |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... | use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_s... | random_line_split | |
string_list.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 eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... |
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_str... | { return; } | conditional_block |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bind... | format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if!is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase t... | random_line_split | |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bind... |
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
... | {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::n... | identifier_body |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bind... | (&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_stat... | get_mime_type | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | () {
let s = r#"{
"params": {
"blockReward": "0x0d"
}
}"#;
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
}
| null_engine_deserialization | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
} | "params": {
"blockReward": "0x0d"
}
}"#; | random_line_split |
fs.rs | fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
O... | (root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf)... | create_ignore | identifier_name |
fs.rs | FS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
... | let mut entry = entry_res?;
if entry.header().entry_type() == tar::EntryType::file() {
let path = | random_line_split | |
fs.rs | fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
O... |
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path... | {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i| !exclude_set.contains(i)).collect()
})
.boxe... | identifier_body |
borrowck-borrowed-uniq-rvalue-2.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 ... | unsafe {
error!("%?", self.x);
}
}
}
fn defer<'r>(x: &'r [&'r str]) -> defer<'r> {
defer {
x: x
}
}
fn main() {
let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough
x.x[0];
} | #[unsafe_destructor]
impl<'self> Drop for defer<'self> {
fn drop(&self) { | random_line_split |
borrowck-borrowed-uniq-rvalue-2.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>(x: &'r [&'r str]) -> defer<'r> {
defer {
x: x
}
}
fn main() {
let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough
x.x[0];
}
| defer | identifier_name |
borrowck-borrowed-uniq-rvalue-2.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 defer<'r>(x: &'r [&'r str]) -> defer<'r> {
defer {
x: x
}
}
fn main() {
let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough
x.x[0];
}
| {
unsafe {
error!("%?", self.x);
}
} | identifier_body |
gzip.rs | extern crate extra;
extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn | () {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
keep = true;
} else {
files.push(arg)
}
}
if files.is_empty() {
eprintln!("gzip: no files provided");
... | main | identifier_name |
gzip.rs | extern crate extra;
extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn main() {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == ... |
}
if files.is_empty() {
eprintln!("gzip: no files provided");
process::exit(1);
}
for arg in files {
{
let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr);
let mut encoder = Encoder::new(output).try(&mut stderr);
let mut... | {
files.push(arg)
} | conditional_block |
gzip.rs | extern crate extra; | extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn main() {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
k... | random_line_split | |
gzip.rs | extern crate extra;
extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn main() | let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr);
let mut encoder = Encoder::new(output).try(&mut stderr);
let mut input = fs::File::open(&arg).try(&mut stderr);
io::copy(&mut input, &mut encoder).try(&mut stderr);
let mut encoded = en... | {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
keep = true;
} else {
files.push(arg)
}
}
if files.is_empty() {
eprintln!("gzip: no files provided");
... | identifier_body |
meg.rs |
extern crate env_logger;
extern crate rustc_serialize;
extern crate toml;
extern crate turbo;
extern crate meg;
extern crate term_painter;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
use std::path::{PathBuf, Path};
use std::process::Command;
use turbo::turb... | (cmd: &str) -> Option<String> {
let cmds = list_commands();
// Only consider candidates with a lev_distance of 3 or less so we don't
// suggest out-of-the-blue options.
let mut filtered = cmds.iter().map(|c| (lev_distance(&c, cmd), c))
.filter(|&(d, _)| d < 4)
... | find_closest | identifier_name |
meg.rs | extern crate env_logger;
extern crate rustc_serialize;
extern crate toml;
extern crate turbo;
extern crate meg;
extern crate term_painter;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
use std::path::{PathBuf, Path};
use std::process::Command;
use turbo::turbo... | dirs
} | if let Some(val) = env::var_os("PATH") {
dirs.extend(env::split_paths(&val));
} | random_line_split |
meg.rs |
extern crate env_logger;
extern crate rustc_serialize;
extern crate toml;
extern crate turbo;
extern crate meg;
extern crate term_painter;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
use std::path::{PathBuf, Path};
use std::process::Command;
use turbo::turb... | }
}
}
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
handle_error(CliError::new("No such subcommand", 127), shell)
}
Err(err) => {
let msg = format!("Subcommand failed to run: {}", err);
handle_error(CliError::new(&m... | {
let command = match find_command(cmd) {
Some(command) => command,
None => {
let msg = match find_closest(cmd) {
Some(closest) => format!("No such subcommand\n\n\t\
Did you mean `{}`?\n", closest),
None => "No suc... | identifier_body |
spinner.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::s... | fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
unsafe {
let mut value = Val... | }
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O { | random_line_split |
spinner.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::s... | (&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
unsafe {
let mut value = Value::from_typ... | start | identifier_name |
spinner.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::s... |
}
unsafe extern "C" fn notify_active_trampoline<P>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Spinner> {
let f: &&(Fn(&P) +'static) = transmute(f);
f(&Spinner::from_glib_borrow(this).downcast_unchecked())
}
| {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::active",
transmute(notify_active_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
} | identifier_body |
media_rule.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/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cs... | (
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard
) -> Self {
let media_queries = self.media_queries.read_with(guard);
let rules = self.rules.read_with(guard);
MediaRule {
media_queries: Arc::new(lock.wrap(media_queries.clone())),
rul... | deep_clone_with_lock | identifier_name |
media_rule.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/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cs... | MediaRule {
media_queries: Arc::new(lock.wrap(media_queries.clone())),
rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
source_location: self.source_location.clone(),
}
}
} | lock: &SharedRwLock,
guard: &SharedRwLockReadGuard
) -> Self {
let media_queries = self.media_queries.read_with(guard);
let rules = self.rules.read_with(guard); | random_line_split |
media_rule.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/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cs... |
}
| {
let media_queries = self.media_queries.read_with(guard);
let rules = self.rules.read_with(guard);
MediaRule {
media_queries: Arc::new(lock.wrap(media_queries.clone())),
rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
source_location: sel... | identifier_body |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWr... |
let a = f32::min(a, 1.);
let inverse_a = 1. / a;
let r = (p1 * r1 + p2 * r2) * inverse_a;
let g = (p1 * g1 + p2 * g2) * inverse_a;
let b = (p1 * b1 + p2 * b2) * inverse_a;
return RGBA::from_floats(r, g, b, a);
}
}
impl ToCss for Color {
fn to_css<W>(&self, dest... | {
return RGBA::transparent();
} | conditional_block |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWr... |
let p1 = ratios.bg;
let a1 = color.alpha_f32();
let r1 = a1 * color.red_f32();
let g1 = a1 * color.green_f32();
let b1 = a1 * color.blue_f32();
let p2 = ratios.fg;
let a2 = fg_color.alpha_f32();
let r2 = a2 * fg_color.red_f32();
let g2 = a2 * fg_... | // color = (self_color * self_alpha * bg_ratio +
// fg_color * fg_alpha * fg_ratio) / alpha | random_line_split |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWr... |
let p2 = ratios.fg;
let a2 = fg_color.alpha_f32();
let r2 = a2 * fg_color.red_f32();
let g2 = a2 * fg_color.green_f32();
let b2 = a2 * fg_color.blue_f32();
let a = p1 * a1 + p2 * a2;
if a <= 0. {
return RGBA::transparent();
}
let a = ... | {
let (color, ratios) = match *self {
// Common cases that the complex color is either pure numeric
// color or pure currentcolor.
GenericColor::Numeric(color) => return color,
GenericColor::Foreground => return fg_color,
GenericColor::Complex(color, r... | identifier_body |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWr... | (&self, fg_color: RGBA) -> RGBA {
let (color, ratios) = match *self {
// Common cases that the complex color is either pure numeric
// color or pure currentcolor.
GenericColor::Numeric(color) => return color,
GenericColor::Foreground => return fg_color,
... | to_rgba | identifier_name |
main.rs | #![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use commands::*;
use serde::Deserialize;
use serenity::async_trait;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::macros::*;
u... | ;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, _: Ready) {
ctx.set_activity(Activity::playing("charades")).await;
}
}
#[group("General")]
#[commands(ping, avatar_url)]
struct General;
#[help]
async fn my_help(
ctx: &Context,
msg: &Message,
args: Args,... | Handler | identifier_name |
main.rs | #![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use commands::*;
use serde::Deserialize;
use serenity::async_trait;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::macros::*;
u... |
}
}
#[derive(Deserialize)]
struct Config {
token: String,
prefix: String,
}
fn read_config() -> Result<Config, Box<dyn std::error::Error>> {
let path = std::env::var("KITTY_CONFIG").unwrap_or_else(|_| "config.json".to_string());
let content = std::fs::read_to_string(path)?;
Ok(serde_json::fro... | {
error!("`{:?}`", err);
} | conditional_block |
main.rs | #![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use commands::*;
use serde::Deserialize;
use serenity::async_trait;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::macros::*;
u... | let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
shard_manager.lock().await.shutdown_all().await;
});
client.start_autosharded().await?;
Ok(())
} | random_line_split | |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if i... | () -> LightUniform
{
LightUniform
{
sphere_light_count: 0,
sphere_lights: [SphericalLight::new(); MAX_SPHERICAL_LIGHTS as usize],
padding: [0.0; 3]
}
}
pub fn add_light(&mut self, light: SphericalLight)
{
if self.sphere_lights.len() < ... | new | identifier_name |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if i... |
}
| {
if self.sphere_lights.len() < MAX_SPHERICAL_LIGHTS as usize
{
self.sphere_lights[self.sphere_light_count as usize] = light;
self.sphere_light_count += 1;
}
else
{
panic!("Too many lights have been added");
}
} | identifier_body |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if i... | }
impl SphericalLight
{
pub fn new() -> SphericalLight
{
SphericalLight
{
position: [0.0; 3],
color: [0.0; 3],
range: 0.0,
}
}
pub fn set_position(mut self, position: [f32; 3])
{
self.position = position;
}
}
#[derive(Copy, C... | fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("position", UniformValue::Vec3(self.position.clone()));
f("position", UniformValue::Vec3(self.color.clone()));
f("color", UniformValue::Float(self.range.clone()));
} | random_line_split |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if i... |
else
{
panic!("Too many lights have been added");
}
}
}
| {
self.sphere_lights[self.sphere_light_count as usize] = light;
self.sphere_light_count += 1;
} | conditional_block |
reverse-string.rs | //! Tests for reverse-string
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_... |
#[test]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
process_reverse_case("I'm hungry!", "!yrgnuh m'I");
}
#[test]
/// a palindrome
fn test_a_palindrome() {
process_reverse_case("racecar", "racecar");
}
| {
process_reverse_case("Ramen", "nemaR");
} | identifier_body |
reverse-string.rs | //! Tests for reverse-string
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_... | () {
process_reverse_case("", "");
}
#[test]
/// a word
fn test_a_word() {
process_reverse_case("robot", "tobor");
}
#[test]
/// a capitalized word
fn test_a_capitalized_word() {
process_reverse_case("Ramen", "nemaR");
}
#[test]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
... | test_empty_string | identifier_name |
reverse-string.rs | //! Tests for reverse-string
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_... | fn test_a_word() {
process_reverse_case("robot", "tobor");
}
#[test]
/// a capitalized word
fn test_a_capitalized_word() {
process_reverse_case("Ramen", "nemaR");
}
#[test]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
process_reverse_case("I'm hungry!", "!yrgnuh m'I");
}
#[t... |
#[test]
/// a word | random_line_split |
simple_receiver.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | match event {
crust::Event::NewMessage(endpoint, bytes) => {
// For this example, we only expect to receive encoded `u8`s
let requested_value = match String::from_utf8(bytes) {
Ok(message) => {
match u8::from_str(message.as_... | println!("Run the simple_sender example in another terminal to send messages to this node.");
// Receive the next event
while let Ok(event) = channel_receiver.recv() {
// Handle the event | random_line_split |
simple_receiver.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
print!("Listening for new connections on ");
for endpoint in &listening_endpoints {
print!("{:?}, ", *endpoint);
};
println!("Run the simple_sender example in another terminal to send messages to this node.");
// Receive the next event
while let Ok(event) = channel_receiver.recv() {
... | {
match env_logger::init() {
Ok(()) => {},
Err(e) => debug!("Error initialising logger; continuing without: {:?}", e)
}
let _ = write_config_file(None, None,Some(9999)).unwrap();
// We receive events (e.g. new connection, message received) from the ConnectionManager via an
// asynch... | identifier_body |
simple_receiver.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | () {
match env_logger::init() {
Ok(()) => {},
Err(e) => debug!("Error initialising logger; continuing without: {:?}", e)
}
let _ = write_config_file(None, None,Some(9999)).unwrap();
// We receive events (e.g. new connection, message received) from the ConnectionManager via an
// asy... | main | identifier_name |
keyfsm.rs | use bitflags::bitflags;
mod keymap {
static KEYCODE_LUT: [u8; 132] =
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
[
0x00, 0x43, 0x00, 0x3F, 0x3D, 0x3B, 0x3C, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3E, 0x0F,
0x29, 0x00, 0x00, 0x38, 0x2A, 0x00, 0x1D... | () -> ProcReply {
ProcReply::NothingToDo
}
}
enum State {
NotInKey,
SimpleKey(u8),
PossibleBreakCode,
KnownBreakCode(u8),
UnmodifiedKey(u8),
ToggleLedFirst(u8),
// InPause(u8), // Number of keycodes in pause left to handle- alternate impl.
Inconsistent,
ExpectingBufferCl... | init | identifier_name |
keyfsm.rs | use bitflags::bitflags;
mod keymap {
static KEYCODE_LUT: [u8; 132] =
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
[
0x00, 0x43, 0x00, 0x3F, 0x3D, 0x3B, 0x3C, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3E, 0x0F,
0x29, 0x00, 0x00, 0x38, 0x2A, 0x00, 0x1D... | | (&State::SimpleKey(_), &ProcReply::SentKey(_))
| (&State::KnownBreakCode(_), &ProcReply::SentKey(_))
| (&State::UnmodifiedKey(_), &ProcReply::SentKey(_))
| (&State::ExpectingBufferClear, &ProcReply::ClearedBuffer) => State::NotInKey,
(&State::NotInKey, &Proc... |
fn next_state(&mut self, curr_reply: &ProcReply) -> State {
match (&self.curr_state, curr_reply) {
(_, &ProcReply::KeyboardReset) => State::ExpectingBufferClear,
(&State::NotInKey, &ProcReply::NothingToDo) | random_line_split |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since ... | {
(**self).clone_from(&(**source));
} | identifier_body |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
... | }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> { | random_line_split |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { Partial... | lt | identifier_name |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
... | {
Err(self)
} | conditional_block |
ast_util.rs | &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_l... |
fn visit_block(&mut self, block: &Block) {
self.operation.visit_id(block.id);
visit::walk_block(self, block)
}
fn visit_stmt(&mut self, statement: &Stmt) {
self.operation.visit_id(ast_util::stmt_id(statement));
visit::walk_stmt(self, statement)
}
fn visit_pat(&mut... | {
self.operation.visit_id(local.id);
visit::walk_local(self, local)
} | identifier_body |
ast_util.rs | &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_l... |
}
}
self.operation.visit_id(node_id);
match function_kind {
visit::FkItemFn(_, generics, _, _, _) => {
self.visit_generics_helper(generics)
}
visit::FkMethod(_, sig, _) => {
self.visit_generics_helper(&sig.generic... | {} | conditional_block |
ast_util.rs | : &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_... | }
fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
self.operation.visit_id(foreign_item.id);
visit::walk_foreign_item(self, foreign_item)
}
fn visit_item(&mut self, item: &Item) {
if!self.pass_through_items {
if self.visited_outermost {
... | random_line_split | |
ast_util.rs | &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_l... | (&mut self, id: NodeId) {
self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, id + 1);
}
}
pub trait IdVisitingOperation {
fn visit_id(&mut self, node_id: NodeId);
}
/// A visitor that applies its operation to all of the node IDs
/// in a visitable thing.
pub struct IdVisitor<'a,... | add | identifier_name |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... | (&self) -> &str { self.package_id().name() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn source_id(&self) -> &SourceId { self.package_id().source_id() }
pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies }
pub fn features(&self) -> &HashMap<String, Vec<St... | name | identifier_name |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... |
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
}
| {
let me = if self.package_id().source_id() == to_replace {
let new_id = self.package_id().with_source_id(replace_with);
self.override_id(new_id)
} else {
self
};
me.map_dependencies(|dep| {
dep.map_source(to_replace, replace_with)
... | identifier_body |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... | }
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
} | dep.map_source(to_replace, replace_with)
}) | random_line_split |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
... |
None if is_reexport => {
bail!("Feature `{}` requires `{}` which is not an \
optional dependency", feature, dep)
}
None => {
bail!("Feature `{}` includes `{}` which is neither \
... | {
if d.is_optional() || is_reexport { continue }
bail!("Feature `{}` depends on `{}` which is not an \
optional dependency.\nConsider adding \
`optional = true` to the dependency",
... | conditional_block |
error.rs | env};
use hir::map::definitions::DefPathData;
use mir;
use ty::{self, Ty, layout};
use ty::layout::{Size, Align, LayoutError};
use rustc_target::spec::abi::Abi;
use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef};
use backtrace::Backtrace;
use ty::query::TyCtxtAt;
use errors::DiagnosticBuilder;
use sy... | "pointer offset outside bounds of allocation",
InvalidNullPointerUsage =>
"invalid use of NULL pointer",
ValidationFailure(..) =>
"type validation failed",
ReadPointerAsBytes =>
"a raw memory access tried to access part ... | {
use self::EvalErrorKind::*;
match *self {
MachineError(ref inner) => inner,
FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
| FunctionArgCountMismatch =>
"tried to call a function through a function pointer of incompatible... | identifier_body |
error.rs | env};
use hir::map::definitions::DefPathData;
use mir;
use ty::{self, Ty, layout};
use ty::layout::{Size, Align, LayoutError};
use rustc_target::spec::abi::Abi;
use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef};
use backtrace::Backtrace;
use ty::query::TyCtxtAt;
use errors::DiagnosticBuilder;
use sy... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::EvalErrorKind::*;
match *self {
PointerOutOfBounds { ptr, check, allocation_size } => {
write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \
allocation {} whic... | fmt | identifier_name |
error.rs | , env};
use hir::map::definitions::DefPathData;
use mir;
use ty::{self, Ty, layout};
use ty::layout::{Size, Align, LayoutError};
use rustc_target::spec::abi::Abi;
use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef};
use backtrace::Backtrace;
use ty::query::TyCtxtAt;
use errors::DiagnosticBuilder;
use s... | "tried to read from foreign (extern) static",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, \
e.g., comparing pointers into different allocations",
ReadUndefBytes(_) =>
"attemp... | ReadBytesAsPointer =>
"a memory access tried to interpret some bytes as a pointer",
ReadForeignStatic => | random_line_split |
item-attributes.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 ... |
#[attr1 = "val"]
#[attr2 = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {}
}
#[attr1 = "val"]
#[attr2 = "val"]
struct t {x: int}
}
mod test_stmt_single_attr_outer {
pub fn f() {
#[attr = "val"]
static x:... | { } | identifier_body |
item-attributes.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 ... |
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_int = 100u32];
#[float = 1.0];
#[mach_float = 1.0f32];
#[nil = ()];
... | random_line_split | |
item-attributes.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 ... | () { }
}
mod test_foreign_items {
pub mod rustrt {
use std::libc;
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_in... | f | identifier_name |
lib.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... | #![cfg_attr(rust_build,
unstable(feature = "rustc_private",
reason = "use the crates.io `rustc-serialize` library instead"))]
#[cfg(test)] extern crate rand;
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};
m... | #![cfg_attr(rust_build, staged_api)] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.