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 |
|---|---|---|---|---|
implied-bounds-closure-arg-outlives.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 ... | ;
cx.set_short(l);
});
}
| { cx.short() } | conditional_block |
implied-bounds-closure-arg-outlives.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 ... | (self) -> &'short u32 { self.short }
fn long(self) -> &'long u32 { self.long }
fn set_short(&mut self, v: &'short u32) { self.short = v; }
}
fn with<F, R>(op: F) -> R
where
F: for<'short, 'long> FnOnce(MyCx<'short, 'long>) -> R,
{
op(MyCx {
short: &22,
long: &22,
})
}
fn main() {
... | short | identifier_name |
implied-bounds-closure-arg-outlives.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 ... | } | random_line_split | |
match-value-binding-in-guard-3291.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 | fn foo(x: Option<~int>, b: bool) -> int {
match x {
None => { 1 }
Some(ref x) if b => { *x.clone() }
Some(_) => { 0 }
}
}
pub fn main() {
foo(Some(~22), true);
foo(Some(~22), false);
foo(None, true);
foo(None, false);
} | // <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 |
match-value-binding-in-guard-3291.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 ... | {
foo(Some(~22), true);
foo(Some(~22), false);
foo(None, true);
foo(None, false);
} | identifier_body | |
match-value-binding-in-guard-3291.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 ... | (x: Option<~int>, b: bool) -> int {
match x {
None => { 1 }
Some(ref x) if b => { *x.clone() }
Some(_) => { 0 }
}
}
pub fn main() {
foo(Some(~22), true);
foo(Some(~22), false);
foo(None, true);
foo(None, false);
}
| foo | identifier_name |
match-value-binding-in-guard-3291.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 ... |
Some(ref x) if b => { *x.clone() }
Some(_) => { 0 }
}
}
pub fn main() {
foo(Some(~22), true);
foo(Some(~22), false);
foo(None, true);
foo(None, false);
}
| { 1 } | conditional_block |
bluetooth.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 bluetooth_traits::{BluetoothError, BluetoothRequest};
use bluetooth_traits::{BluetoothResponse, BluetoothRespo... | (&self)
-> &DOMRefCell<HashMap<String, MutHeap<JS<BluetoothRemoteGATTCharacteristic>>>> {
&self.characteristic_instance_map
}
pub fn get_descriptor_map(&self) -> &DOMRefCell<HashMap<String, MutHeap<JS<BluetoothRemoteGATTDescriptor>>>> {
&self.descriptor_instance_map
}
fn ge... | get_characteristic_map | identifier_name |
bluetooth.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 bluetooth_traits::{BluetoothError, BluetoothRequest};
use bluetooth_traits::{BluetoothResponse, BluetoothRespo... | const SERVICE_ERROR: &'static str = "'services', if present, must contain at least one service.";
const OPTIONS_ERROR: &'static str = "Fields of 'options' conflict with each other.
Either 'acceptAllDevices' member must be true, or 'filters' member must be set to a value.";
struct BluetoothContext<T: AsyncBluetoothLis... | const NAME_PREFIX_ERROR: &'static str = "'namePrefix', if present, must be nonempty.";
const NAME_TOO_LONG_ERROR: &'static str = "A device name can't be longer than 248 bytes."; | random_line_split |
bluetooth.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 bluetooth_traits::{BluetoothError, BluetoothRequest};
use bluetooth_traits::{BluetoothResponse, BluetoothRespo... |
}
impl AsyncBluetoothListener for Bluetooth {
fn handle_response(&self, response: BluetoothResponse, promise_cx: *mut JSContext, promise: &Rc<Promise>) {
match response {
BluetoothResponse::RequestDevice(device) => {
let mut device_instance_map = self.device_instance_map.borrow... | {
let p = Promise::new(&self.global());
// Step 1.
if (option.filters.is_some() && option.acceptAllDevices) ||
(option.filters.is_none() && !option.acceptAllDevices) {
p.reject_error(p.global().get_cx(), Error::Type(OPTIONS_ERROR.to_owned()));
return p;
... | identifier_body |
response.rs | use super::error::InvalidJsonError;
use serde_json::Map;
use serde_json::Value as JsonValue;
/// The response from a command send to the DaZeus server.
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
data: JsonValue,
}
impl Response {
/// Create a new response based upon a failure message.
///
... |
}
| {
match self.get("success") {
Some(&JsonValue::Bool(true)) => true,
_ => false,
}
} | identifier_body |
response.rs | use super::error::InvalidJsonError;
use serde_json::Map;
use serde_json::Value as JsonValue;
/// The response from a command send to the DaZeus server.
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
data: JsonValue,
}
impl Response {
/// Create a new response based upon a failure message.
///
... | ///
/// Returns `Some(data)` if the property exists, or `None` if the property doesn't exist.
pub fn get<'a>(&'a self, prop: &'a str) -> Option<&'a JsonValue> {
match self.data {
JsonValue::Object(ref obj) => obj.get(prop),
_ => None,
}
}
/// Retrieve a strin... | }
/// Retrieve a property from the data object. | random_line_split |
response.rs | use super::error::InvalidJsonError;
use serde_json::Map;
use serde_json::Value as JsonValue;
/// The response from a command send to the DaZeus server.
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
data: JsonValue,
}
impl Response {
/// Create a new response based upon a failure message.
///
... | (&self) -> bool {
match self.get("success") {
Some(&JsonValue::Bool(true)) => true,
_ => false,
}
}
}
| has_success | identifier_name |
write_dir.rs | use std::io::prelude::*;
use std::io::{Seek, Write};
use std::iter::Iterator;
use zip::result::ZipError;
use zip::write::FileOptions;
use std::fs::File;
use std::path::Path;
use walkdir::{DirEntry, WalkDir};
fn main() |
const METHOD_STORED: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Stored);
#[cfg(any(
feature = "deflate",
feature = "deflate-miniz",
feature = "deflate-zlib"
))]
const METHOD_DEFLATED: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Deflated);
#[cfg(not(any(
feature = ... | {
std::process::exit(real_main());
} | identifier_body |
write_dir.rs | use std::io::prelude::*;
use std::io::{Seek, Write};
use std::iter::Iterator;
use zip::result::ZipError;
use zip::write::FileOptions;
use std::fs::File;
use std::path::Path;
use walkdir::{DirEntry, WalkDir};
fn main() {
std::process::exit(real_main());
}
const METHOD_STORED: Option<zip::CompressionMethod> = Some... |
let path = Path::new(dst_file);
let file = File::create(&path).unwrap();
let walkdir = WalkDir::new(src_dir);
let it = walkdir.into_iter();
zip_dir(&mut it.filter_map(|e| e.ok()), src_dir, file, method)?;
Ok(())
}
| {
return Err(ZipError::FileNotFound);
} | conditional_block |
write_dir.rs | use std::io::prelude::*;
use std::io::{Seek, Write};
use std::iter::Iterator;
use zip::result::ZipError;
use zip::write::FileOptions;
use std::fs::File;
use std::path::Path;
use walkdir::{DirEntry, WalkDir};
fn main() {
std::process::exit(real_main());
}
const METHOD_STORED: Option<zip::CompressionMethod> = Some... | (
src_dir: &str,
dst_file: &str,
method: zip::CompressionMethod,
) -> zip::result::ZipResult<()> {
if!Path::new(src_dir).is_dir() {
return Err(ZipError::FileNotFound);
}
let path = Path::new(dst_file);
let file = File::create(&path).unwrap();
let walkdir = WalkDir::new(src_dir)... | doit | identifier_name |
write_dir.rs | use std::io::prelude::*;
use std::io::{Seek, Write};
use std::iter::Iterator;
use zip::result::ZipError;
use zip::write::FileOptions;
use std::fs::File;
use std::path::Path;
use walkdir::{DirEntry, WalkDir};
fn main() {
std::process::exit(real_main());
}
const METHOD_STORED: Option<zip::CompressionMethod> = Some... | feature = "deflate-zlib"
))]
const METHOD_DEFLATED: Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Deflated);
#[cfg(not(any(
feature = "deflate",
feature = "deflate-miniz",
feature = "deflate-zlib"
)))]
const METHOD_DEFLATED: Option<zip::CompressionMethod> = None;
#[cfg(feature = "bzip2"... | random_line_split | |
main.rs | #[macro_use]
extern crate clap;
use clap::Arg;
use failure::Fail;
use lucet_validate::{self, Validator};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process;
use witx;
pub fn main() {
// rebuild if env vars used by app_from_crate! change:
let _ = include_str!("../Carg... |
Err(e) => {
if matches.is_present("verbose") {
match e {
Error::Witx(e) => {
println!("{}", e.report());
}
_ => {
println!("{:?}", e);
}
}
... | {
if matches.is_present("verbose") {
println!("validated successfully")
}
} | conditional_block |
main.rs | #[macro_use]
extern crate clap;
use clap::Arg;
use failure::Fail;
use lucet_validate::{self, Validator};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process;
use witx;
pub fn main() {
// rebuild if env vars used by app_from_crate! change:
let _ = include_str!("../Carg... | impl From<witx::WitxError> for Error {
fn from(e: witx::WitxError) -> Error {
Error::Witx(e)
}
}
impl From<lucet_validate::Error> for Error {
fn from(e: lucet_validate::Error) -> Error {
Error::Validate(e)
}
} | random_line_split | |
main.rs | #[macro_use]
extern crate clap;
use clap::Arg;
use failure::Fail;
use lucet_validate::{self, Validator};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process;
use witx;
pub fn main() {
// rebuild if env vars used by app_from_crate! change:
let _ = include_str!("../Carg... |
}
| {
Error::Validate(e)
} | identifier_body |
main.rs | #[macro_use]
extern crate clap;
use clap::Arg;
use failure::Fail;
use lucet_validate::{self, Validator};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process;
use witx;
pub fn main() {
// rebuild if env vars used by app_from_crate! change:
let _ = include_str!("../Carg... | (e: witx::WitxError) -> Error {
Error::Witx(e)
}
}
impl From<lucet_validate::Error> for Error {
fn from(e: lucet_validate::Error) -> Error {
Error::Validate(e)
}
}
| from | identifier_name |
blocks.rs | //
// Stachanov
// Copyright (C) 2017 Stachanov Developer Collective
//
// This file is part of Stachanov.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License, version 3, as published by the Free Software Foundati... | let mut blocks = vec![];
let chain_len = 10;
// we create a list of blocks, that all have a time difference
// of 2 seconds, starting at 1, so we have an order of timestamps
// like 1, 3, 5, 7,... get_from_timestamp should work when we
// provide a timestamp that hits a block as well as when i... | random_line_split | |
blocks.rs | //
// Stachanov
// Copyright (C) 2017 Stachanov Developer Collective
//
// This file is part of Stachanov.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License, version 3, as published by the Free Software Foundati... | }
let cloned = block.clone();
let result = storage.append_verified_block(cloned);
assert!(result.is_ok(), "Could not append block");
blocks.push(block);
}
// test timestamps that hit blocks exactly (get_after_timestamp
// then behaves similar to get_after, getting... | {
let mut blocks = vec![];
let chain_len = 10;
// we create a list of blocks, that all have a time difference
// of 2 seconds, starting at 1, so we have an order of timestamps
// like 1, 3, 5, 7, ... get_from_timestamp should work when we
// provide a timestamp that hits a block as well as wh... | identifier_body |
blocks.rs | //
// Stachanov
// Copyright (C) 2017 Stachanov Developer Collective
//
// This file is part of Stachanov.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License, version 3, as published by the Free Software Foundati... | else{
assert!(i == (chain_len - 1),
"get_after_timestamp returned a None \
value in a case where a block should \
be returned");
}
}
// test timestamps that hit the gaps between the blocks
for i in 0..chain_len {
... | {
assert!(i < (chain_len - 1),
"get_after_timestamp returned a block \
for the timestamp of the tail block");
let fetched_id = block.get_id();
let block_index = i as usize + 1;
let assumed_id = blocks[block_index].get_id();
... | conditional_block |
blocks.rs | //
// Stachanov
// Copyright (C) 2017 Stachanov Developer Collective
//
// This file is part of Stachanov.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License, version 3, as published by the Free Software Foundati... | <T>(storage: &mut T) where T: ChainStorage{
// append a chain of different blocks (all unverified)
let mut blocks = vec![];
let chain_len = 10;
for _i in 0..chain_len {
let block;
if let Some(previous_block) = blocks.last(){
block = Block::new([0; 32], Some(&previous_blo... | test_get_after | identifier_name |
test_broken_pipe.rs | #![cfg(unix)]
use mio::{Token, Ready, PollOpt};
use mio::deprecated::{unix, EventLoop, Handler};
use std::time::Duration;
pub struct BrokenPipeHandler;
impl Handler for BrokenPipeHandler {
type Timeout = ();
type Message = ();
fn ready(&mut self, _: &mut EventLoop<Self>, token: Token, _: Ready) {
... |
}
}
#[test]
pub fn broken_pipe() {
let mut event_loop: EventLoop<BrokenPipeHandler> = EventLoop::new().unwrap();
let (reader, _) = unix::pipe().unwrap();
// On Darwin this returns a "broken pipe" error.
let _ = event_loop.register(&reader, Token(1), Ready::all(), PollOpt::edge());
let mut ha... | {
panic!("Received ready() on a closed pipe.");
} | conditional_block |
test_broken_pipe.rs | #![cfg(unix)]
use mio::{Token, Ready, PollOpt};
use mio::deprecated::{unix, EventLoop, Handler};
use std::time::Duration;
pub struct BrokenPipeHandler;
impl Handler for BrokenPipeHandler {
type Timeout = ();
type Message = ();
fn ready(&mut self, _: &mut EventLoop<Self>, token: Token, _: Ready) |
}
#[test]
pub fn broken_pipe() {
let mut event_loop: EventLoop<BrokenPipeHandler> = EventLoop::new().unwrap();
let (reader, _) = unix::pipe().unwrap();
// On Darwin this returns a "broken pipe" error.
let _ = event_loop.register(&reader, Token(1), Ready::all(), PollOpt::edge());
let mut handler ... | {
if token == Token(1) {
panic!("Received ready() on a closed pipe.");
}
} | identifier_body |
test_broken_pipe.rs | #![cfg(unix)]
use mio::{Token, Ready, PollOpt};
use mio::deprecated::{unix, EventLoop, Handler};
use std::time::Duration;
pub struct | ;
impl Handler for BrokenPipeHandler {
type Timeout = ();
type Message = ();
fn ready(&mut self, _: &mut EventLoop<Self>, token: Token, _: Ready) {
if token == Token(1) {
panic!("Received ready() on a closed pipe.");
}
}
}
#[test]
pub fn broken_pipe() {
let mut event_lo... | BrokenPipeHandler | identifier_name |
test_broken_pipe.rs | #![cfg(unix)]
use mio::{Token, Ready, PollOpt};
use mio::deprecated::{unix, EventLoop, Handler};
use std::time::Duration;
pub struct BrokenPipeHandler;
impl Handler for BrokenPipeHandler {
type Timeout = (); | if token == Token(1) {
panic!("Received ready() on a closed pipe.");
}
}
}
#[test]
pub fn broken_pipe() {
let mut event_loop: EventLoop<BrokenPipeHandler> = EventLoop::new().unwrap();
let (reader, _) = unix::pipe().unwrap();
// On Darwin this returns a "broken pipe" error.
... | type Message = ();
fn ready(&mut self, _: &mut EventLoop<Self>, token: Token, _: Ready) { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
#![cfg_attr(feature = "unstable", feature(conservative_impl_trait))]
extern crate backtrace... | #[cfg(not(target_os = "ios"))]
extern crate embedder_traits;
extern crate euclid;
#[cfg(all(not(target_os = "windows"), not(target_os = "ios")))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate hyper;
extern crate ipc_channel;
extern crate keyboard_types;
extern crate layout_traits;
#[macro_u... | extern crate devtools_traits; | random_line_split |
extern-pass-TwoU64s.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... | () {
unsafe {
let x = TwoU64s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU64s(x);
assert_eq!(x, y);
}
}
| main | identifier_name |
extern-pass-TwoU64s.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... |
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_identity_TwoU64s(v: TwoU64s) -> TwoU64s;
}
pub fn main() {
unsafe {
let x = TwoU64s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU64s(x);
assert_eq!(x, y);
}
} | random_line_split | |
extern-pass-TwoU64s.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... | {
unsafe {
let x = TwoU64s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU64s(x);
assert_eq!(x, y);
}
} | identifier_body | |
const-block.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 ... |
static BLOCK_INTEGRAL: usize = { 1 };
static BLOCK_EXPLICIT_UNIT: () = { () };
static BLOCK_IMPLICIT_UNIT: () = { };
static BLOCK_FLOAT: f64 = { 1.0 };
static BLOCK_ENUM: Option<usize> = { Some(100) };
static BLOCK_STRUCT: Foo = { Foo { a: 12, b: 0 as *const () } };
static BLOCK_UNSAFE: usize = unsafe { 1000 };
stati... | fn foo<T>(a: T) -> T {
a
} | random_line_split |
const-block.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 ... | {
assert_eq!(BLOCK_INTEGRAL, 1);
assert_eq!(BLOCK_EXPLICIT_UNIT, ());
assert_eq!(BLOCK_IMPLICIT_UNIT, ());
assert_eq!(BLOCK_FLOAT, 1.0_f64);
assert_eq!(BLOCK_STRUCT.a, 12);
assert_eq!(BLOCK_STRUCT.b, 0 as *const ());
assert_eq!(BLOCK_ENUM, Some(100));
assert_eq!(BLOCK_UNSAFE, 1000);
... | identifier_body | |
const-block.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 ... | () {
assert_eq!(BLOCK_INTEGRAL, 1);
assert_eq!(BLOCK_EXPLICIT_UNIT, ());
assert_eq!(BLOCK_IMPLICIT_UNIT, ());
assert_eq!(BLOCK_FLOAT, 1.0_f64);
assert_eq!(BLOCK_STRUCT.a, 12);
assert_eq!(BLOCK_STRUCT.b, 0 as *const ());
assert_eq!(BLOCK_ENUM, Some(100));
assert_eq!(BLOCK_UNSAFE, 1000);
... | main | identifier_name |
frustum.rs | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a ... |
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
pub struct FrustumPoints<S> {
pub near_top_left: Point3<S>,
pub near_top_right: Point3<S>,
pub near_bottom_left: Point3<S>,
pub near_bottom_right: Point3<S>,
pub far_top_left: Point3<S>,
pub far_top_right: Poi... | {
[&self.left, &self.right, &self.top, &self.bottom, &self.near, &self.far]
.iter().fold(Relation::In, |cur, p| {
use std::cmp::max;
let r = bound.relate_plane(p);
// If any of the planes are `Out`, the bound is outside.
// Otherwise, if any are `Cross... | identifier_body |
frustum.rs | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a ... | use vector::{Vector, EuclideanVector};
#[derive(Copy, Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
pub struct Frustum<S: BaseFloat> {
pub left: Plane<S>,
pub right: Plane<S>,
pub bottom: Plane<S>,
pub top: Plane<S>,
pub near: Plane<S>,
pub far: Plane<S>,
}
impl<S: BaseF... | use num::BaseFloat;
use plane::Plane;
use point::Point3; | random_line_split |
frustum.rs | // Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a ... | <S> {
pub near_top_left: Point3<S>,
pub near_top_right: Point3<S>,
pub near_bottom_left: Point3<S>,
pub near_bottom_right: Point3<S>,
pub far_top_left: Point3<S>,
pub far_top_right: Point3<S>,
pub far_bottom_left: Point3<S>,
pub far_bottom_right: Point3<S>,
}
| FrustumPoints | identifier_name |
pcg128.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2017 Paul Dicker.
// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opens... |
cur_plus = cur_mult.wrapping_add(1).wrapping_mul(cur_plus);
cur_mult = cur_mult.wrapping_mul(cur_mult);
mdelta /= 2;
}
self.state = acc_mult.wrapping_mul(self.state).wrapping_add(acc_plus);
}
/// Construct an instance compatible with PCG seed.
///
//... | {
acc_mult = acc_mult.wrapping_mul(cur_mult);
acc_plus = acc_plus.wrapping_mul(cur_mult).wrapping_add(cur_plus);
} | conditional_block |
pcg128.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2017 Paul Dicker.
// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opens... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Lcg128Xsl64 {{}}")
}
}
/// We use a single 255-bit seed to initialise the state and select a stream.
/// One `seed` bit (lowest bit of `seed[8]`) is ignored.
impl SeedableRng for Lcg128Xsl64 {
type Seed = [u8; 32];
fn from_seed(seed: Self... | fmt | identifier_name |
pcg128.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2017 Paul Dicker.
// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opens... | }
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
/// A PCG random number generator (XSL 128/64 (MCG) variant).
///
/// Permuted Congruential Generator with 128-bit state, internal Multiplicative
/// Congruential Generat... | random_line_split | |
pcg128.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2017 Paul Dicker.
// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opens... |
/// Construct an instance compatible with PCG seed and stream.
///
/// Note that two generators with different stream parameters may be closely
/// correlated.
///
/// PCG specifies the following default values for both parameters:
///
/// - `state = 0xcafef00dd15ea5e5`
/// - `stre... | {
let mut acc_mult: u128 = 1;
let mut acc_plus: u128 = 0;
let mut cur_mult = MULTIPLIER;
let mut cur_plus = self.increment;
let mut mdelta = delta;
while mdelta > 0 {
if (mdelta & 1) != 0 {
acc_mult = acc_mult.wrapping_mul(cur_mult);
... | identifier_body |
mod.rs | mod deck;
mod parts;
pub use self::deck::*;
pub use self::parts::*;
use players::HasHand;
use rand::{Rng, thread_rng};
/// A playing card
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Card {
/// A normal card
Normal {
/// The suit of the card
suit: CardSuit,
/// The value of the card
... | if self.len() < players.len() * n {
return false;
}
for player in players {
player.hand_mut().append(&mut self.draw_many(n).unwrap());
}
true
}
} | identifier_body | |
mod.rs | mod deck;
mod parts;
pub use self::deck::*;
pub use self::parts::*;
use players::HasHand;
use rand::{Rng, thread_rng};
/// A playing card
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Card {
/// A normal card
Normal {
/// The suit of the card
suit: CardSuit,
/// The value of the card
... | Some(self.remove(0))
}
fn draw_many(&mut self, n: usize) -> Option<Vec<Card>> {
if self.len() < n {
return None;
}
Some((0..n).map(|_| self.draw().unwrap()).collect())
}
fn peek(&self) -> Option<&Card> {
self.get(0)
}
fn peek_many(&self, n: usize) -> Option<Vec<&Card>> {
(0..... | return None;
}
| conditional_block |
mod.rs | mod deck;
mod parts;
pub use self::deck::*;
pub use self::parts::*;
use players::HasHand;
use rand::{Rng, thread_rng};
/// A playing card
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Card {
/// A normal card
Normal {
/// The suit of the card
suit: CardSuit,
/// The value of the card
... |
fn draw_many(&mut self, n: usize) -> Option<Vec<Card>> {
if self.len() < n {
return None;
}
Some((0..n).map(|_| self.draw().unwrap()).collect())
}
fn peek(&self) -> Option<&Card> {
self.get(0)
}
fn peek_many(&self, n: usize) -> Option<Vec<&Card>> {
(0..n).map(|i| self.get(i)).coll... | }
Some(self.remove(0))
} | random_line_split |
mod.rs | mod deck;
mod parts;
pub use self::deck::*;
pub use self::parts::*;
use players::HasHand;
use rand::{Rng, thread_rng};
/// A playing card
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Card {
/// A normal card
Normal {
/// The suit of the card
suit: CardSuit,
/// The value of the card
... | self) -> String {
match *self {
Card::Normal { ref suit, ref value } => format!("{}{}", value, suit),
Card::Joker(ref color) => format!("Jo{}", color)
}
}
}
/// Methods for working with collections of cards
pub trait Cards {
/// Draws a card from the deck, removing it from the deck.
///
///... | _string(& | identifier_name |
xrray.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::DOMPointBinding::DOMPointInit;
use crate::dom::bindings::codegen::Bi... | } else {
Rotation3D::identity()
};
// Step 6
let translation = self.ray.origin;
// Step 7
// According to the spec all matrices are column-major,
// however euclid uses row vectors so we use.to_row_major_array()
... | Rotation3D::around_axis(axis, Angle::radians(cos_angle.acos()))
} else if cos_angle == -1. {
let axis = Vector3D::new(1., 0., 0.);
Rotation3D::around_axis(axis, Angle::radians(cos_angle.acos())) | random_line_split |
xrray.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::DOMPointBinding::DOMPointInit;
use crate::dom::bindings::codegen::Bi... |
/// https://immersive-web.github.io/hit-test/#dom-xrray-direction
fn Direction(&self) -> DomRoot<DOMPointReadOnly> {
DOMPointReadOnly::new(
&self.global(),
self.ray.direction.x as f64,
self.ray.direction.y as f64,
self.ray.direction.z as f64,
... | {
DOMPointReadOnly::new(
&self.global(),
self.ray.origin.x as f64,
self.ray.origin.y as f64,
self.ray.origin.z as f64,
1.,
)
} | identifier_body |
xrray.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::DOMPointBinding::DOMPointInit;
use crate::dom::bindings::codegen::Bi... | (&self) -> DomRoot<DOMPointReadOnly> {
DOMPointReadOnly::new(
&self.global(),
self.ray.direction.x as f64,
self.ray.direction.y as f64,
self.ray.direction.z as f64,
0.,
)
}
/// https://immersive-web.github.io/hit-test/#dom-xrray-matrix... | Direction | identifier_name |
xrray.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::DOMPointBinding::DOMPointInit;
use crate::dom::bindings::codegen::Bi... | // According to the spec all matrices are column-major,
// however euclid uses row vectors so we use.to_row_major_array()
let arr = RigidTransform3D::new(rotation, translation)
.to_transform()
.to_row_major_array();
create_typed_array(cx, &ar... | {
let cx = self.global().get_cx();
// Step 2
let z = Vector3D::new(0., 0., -1.);
// Step 3
let axis = z.cross(self.ray.direction);
// Step 4
let cos_angle = z.dot(self.ray.direction);
// Step 5
let rotation = if ... | conditional_block |
tee.rs | //#![deny(warnings)]
extern crate coreutils;
use coreutils::ArgParser;
use std::{process, env};
use std::io::{self, Read, Write};
const MAN_PAGE: &'static str = /* @MANSTART{tee} */ r#"
NAME
tee - read from standard input and write to standard output and files
SYNOPSIS
tee [OPTION]... [FILE]...
DESCRIPTION... | ) {
let mut parser = ArgParser::new(2).
add_flag(&["a", "append"]).
add_flag(&["h", "help"]);
parser.parse(env::args());
let mut stdout = io::stdout();
if parser.found("help") {
stdout.write_all(MAN_PAGE.as_bytes()).unwrap();
stdout.flush().unwrap();
process::ex... | ain( | identifier_name |
tee.rs | //#![deny(warnings)]
extern crate coreutils;
use coreutils::ArgParser;
use std::{process, env};
use std::io::{self, Read, Write};
const MAN_PAGE: &'static str = /* @MANSTART{tee} */ r#"
NAME
tee - read from standard input and write to standard output and files
SYNOPSIS
tee [OPTION]... [FILE]...
DESCRIPTION... |
};
}
},
Err(e) => {
println!("Err(e): {}", e);
break;
},
};
}
stdout.flush().unwrap();
process::exit(0);
}
|
println!("Err(e): {}", e);
break 'programmloop;
}, | conditional_block |
tee.rs | //#![deny(warnings)]
extern crate coreutils;
use coreutils::ArgParser;
use std::{process, env};
use std::io::{self, Read, Write};
const MAN_PAGE: &'static str = /* @MANSTART{tee} */ r#"
NAME
tee - read from standard input and write to standard output and files
SYNOPSIS
tee [OPTION]... [FILE]...
DESCRIPTION... | let fd = std::fs::OpenOptions::new().append(true).open(arg);
match fd {
Ok(f) => fds.push(f),
Err(e) => println!("Err(e): {}", e),
}
}
}
} else {
let args = env::args().skip(1);
if args.len() > 0 {... |
let mut parser = ArgParser::new(2).
add_flag(&["a", "append"]).
add_flag(&["h", "help"]);
parser.parse(env::args());
let mut stdout = io::stdout();
if parser.found("help") {
stdout.write_all(MAN_PAGE.as_bytes()).unwrap();
stdout.flush().unwrap();
process::exit(... | identifier_body |
tee.rs | //#![deny(warnings)]
extern crate coreutils;
use coreutils::ArgParser;
use std::{process, env};
use std::io::{self, Read, Write};
const MAN_PAGE: &'static str = /* @MANSTART{tee} */ r#"
NAME
tee - read from standard input and write to standard output and files
SYNOPSIS
tee [OPTION]... [FILE]...
DESCRIPTION... | let mut stdout = io::stdout();
if parser.found("help") {
stdout.write_all(MAN_PAGE.as_bytes()).unwrap();
stdout.flush().unwrap();
process::exit(0);
}
let mut fds: Vec<std::fs::File> = Vec::with_capacity(env::args().len());
if parser.found("append") {
let args = env... | random_line_split | |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
closure_did: DefId,
substs: ty::ClosureSubsts<'tcx>,
) -> Instance<'tcx> {
debug!("fn_once_adapter_shim({:?}, {:?})",
closure_did,
substs);
let fn_once = tcx.lang_items().fn_once_trait().unwrap();
let call_once = tcx.associated_i... | fn_once_adapter_instance | identifier_name |
mod.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... | // fn call_once(self,...) { call_mut(&self,...) }
// fn call_once(mut self,...) { call_mut(&mut self,...) }
//
// These are both the same at codegen time.
Ok(true)
}
_ => Err(()),
}
}
pub fn resolve_closure<'a, 'tcx> (
tcx: Ty... | {
match (actual_closure_kind, trait_closure_kind) {
(ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
(ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
(ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
// No adapter needed.
Ok(false)
}
(ty::ClosureKin... | identifier_body |
mod.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... |
(ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
(ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
// The closure fn `llfn` is a `fn(&self,...)` or `fn(&mut
// self,...)`. We want a `fn(self,...)`. We can produce
// this by doing something like:
//
... | {
// The closure fn `llfn` is a `fn(&self, ...)`. We want a
// `fn(&mut self, ...)`. In fact, at codegen time, these are
// basically the same thing, so we can just return llfn.
Ok(false)
} | conditional_block |
mod.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let def = ty::InstanceDef::ClosureOnceShim { call_once };
let self_ty = tcx.mk_closure(closure_did, substs);
let sig = substs.closure_sig(closure_did, tcx);
let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
assert_eq!(sig.inputs().len(), 1);
let substs = tcx... | .unwrap().def_id; | random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::pin::Pin;
use anyhow::{Context, Error};
use edenapi_types::ToWire;
use futures::{stream::TryStreamExt, FutureExt, S... | <S, T>(stream: S, encoding: ContentEncoding) -> impl TryIntoResponse
where
S: Stream<Item = Result<T, Error>> + Send +'static,
T: ToWire + Send +'static,
{
let stream = stream.and_then(|item| async move { to_cbor_bytes(&item.to_wire()) });
let stream = encode_stream(stream, encoding, None).capture_first... | encode_response_stream | identifier_name |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::pin::Pin;
use anyhow::{Context, Error};
use edenapi_types::ToWire;
use futures::{stream::TryStreamExt, FutureExt, S... |
}
/// JSON representation of an error to send to the client.
#[derive(Clone, Serialize, Debug, Deserialize)]
struct JsonError {
message: String,
request_id: String,
}
struct JsonErrorFomatter;
impl ErrorFormatter for JsonErrorFomatter {
type Body = Vec<u8>;
fn format(&self, error: &Error, state: &S... | {
Self {
repo: Some(repo.to_string()),
method: Some(method),
}
} | identifier_body |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::pin::Pin;
use anyhow::{Context, Error};
use edenapi_types::ToWire;
use futures::{stream::TryStreamExt, FutureExt, S... | }
}
.await;
build_response(res, state, &JsonErrorFomatter)
}
/// Encode a stream of EdenAPI responses into its final on-wire representation.
///
/// This involves converting each item to its wire format, CBOR serializing them, and then
/// optionally compressing the resulting byte stream based on t... | }
match Handler::handler(repo, path, query_string, request).await {
Ok(responses) => Ok(encode_response_stream(responses, content_encoding)),
Err(HandlerError::E500(err)) => Err(HttpError::e500(err)), | random_line_split |
objects.rs | //! Various functions operating on any object.
use remacs_macros::lisp_fn;
use remacs_sys::{EqualKind, Qnil};
use remacs_sys::internal_equal;
use lisp::LispObject;
use lisp::defsubr;
/// Return t if OBJECT is nil, and return nil otherwise.
#[lisp_fn]
fn null(object: LispObject) -> LispObject {
LispObject::from_b... |
/// Return the argument unchanged.
#[lisp_fn]
fn identity(arg: LispObject) -> LispObject {
arg
}
include!(concat!(env!("OUT_DIR"), "/objects_exports.rs"));
| {
let res = unsafe {
internal_equal(
o1.to_raw(),
o2.to_raw(),
EqualKind::IncludingProperties,
0,
Qnil,
)
};
LispObject::from_bool(res)
} | identifier_body |
objects.rs | //! Various functions operating on any object.
use remacs_macros::lisp_fn;
use remacs_sys::{EqualKind, Qnil};
use remacs_sys::internal_equal;
use lisp::LispObject;
use lisp::defsubr;
/// Return t if OBJECT is nil, and return nil otherwise.
#[lisp_fn]
fn null(object: LispObject) -> LispObject { | #[lisp_fn]
fn eq(obj1: LispObject, obj2: LispObject) -> LispObject {
LispObject::from_bool(obj1.eq(obj2))
}
/// Return t if the two args are the same Lisp object.
/// Floating-point numbers of equal value are `eql', but they may not be `eq'.
#[lisp_fn]
fn eql(obj1: LispObject, obj2: LispObject) -> LispObject {
... | LispObject::from_bool(object.is_nil())
}
/// Return t if the two args are the same Lisp object. | random_line_split |
objects.rs | //! Various functions operating on any object.
use remacs_macros::lisp_fn;
use remacs_sys::{EqualKind, Qnil};
use remacs_sys::internal_equal;
use lisp::LispObject;
use lisp::defsubr;
/// Return t if OBJECT is nil, and return nil otherwise.
#[lisp_fn]
fn null(object: LispObject) -> LispObject {
LispObject::from_b... | (obj1: LispObject, obj2: LispObject) -> LispObject {
LispObject::from_bool(obj1.eq(obj2))
}
/// Return t if the two args are the same Lisp object.
/// Floating-point numbers of equal value are `eql', but they may not be `eq'.
#[lisp_fn]
fn eql(obj1: LispObject, obj2: LispObject) -> LispObject {
LispObject::fro... | eq | identifier_name |
zhtta.rs | .1";
static PORT : usize = 4414;
static WWW_DIR : &'static str = "./www";
static HTTP_OK : &'static str = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n";
static HTTP_BAD : &'static str = "HTTP/1.1 404 Not Found\r\n\r\n";
static COUNTER_STYLE : &'static str = "<doctype!html><html><head><title>Hell... | let (req_tx, req_rx) = channel();
req_tx.send(req);
debug!("Waiting for queue mutex lock.");
let local_req_queue = req_queue_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
... | random_line_split | |
zhtta.rs | 1";
static PORT : usize = 4414;
static WWW_DIR : &'static str = "./www";
static HTTP_OK : &'static str = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n";
static HTTP_BAD : &'static str = "HTTP/1.1 404 Not Found\r\n\r\n";
static COUNTER_STYLE : &'static str = "<doctype!html><html><head><title>Hello... | println!("NOT in cache");
file_reader = File::open(path).unwrap();
let mut reader = BufferedReader::new(file_reader);
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
let mut contents: Vec<u8>=Vec::new();
//for ea... | {
//boolean saying whether file in cache or not
let mut was_cached = 0;
let mut file_reader: File;
//first, get the map that stores all the files in cache, acquire lock, and set boolean indicating whether or not it was in cache
{
let mut cache_map = cache.lock().unwra... | identifier_body |
zhtta.rs | 1";
static PORT : usize = 4414;
static WWW_DIR : &'static str = "./www";
static HTTP_OK : &'static str = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n";
static HTTP_BAD : &'static str = "HTTP/1.1 404 Not Found\r\n\r\n";
static COUNTER_STYLE : &'static str = "<doctype!html><html><head><title>Hello... | (&mut self) {
let addr = String::from_str(format!("{}:{}", self.ip, self.port).as_slice());
let www_dir_path_str = self.www_dir_path.clone();
let request_queue_arc = self.request_queue_arc.clone(); //tasks to schedule- want it to be a priority queue if static file, put in request queue and ... | listen | identifier_name |
mutex.rs | use core::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT, spin_loop_hint as cpu_relax};
use core::cell::UnsafeCell;
use core::marker::Sync;
use core::ops::{Drop, Deref, DerefMut};
use core::fmt;
use core::option::Option::{self, None, Some};
use core::default::Default;
/// This type provides MUTual EXclusion bas... | // `self` so there's no need to lock.
let Mutex { data,.. } = self;
data.into_inner()
}
}
impl<T:?Sized> Mutex<T>
{
fn obtain_lock(&self)
{
while self.lock.compare_and_swap(false, true, Ordering::Acquire)!= false
{
// Wait until the lock looks unlocked be... | random_line_split | |
mutex.rs | use core::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT, spin_loop_hint as cpu_relax};
use core::cell::UnsafeCell;
use core::marker::Sync;
use core::ops::{Drop, Deref, DerefMut};
use core::fmt;
use core::option::Option::{self, None, Some};
use core::default::Default;
/// This type provides MUTual EXclusion bas... | (i32);
#[test]
fn smoke() {
let m = Mutex::new(());
drop(m.lock());
drop(m.lock());
}
#[test]
fn lots_and_lots() {
static M: Mutex<()> = Mutex::new(());
static mut CNT: u32 = 0;
const J: u32 = 1000;
const K: u32 = 3;
fn inc() {
... | NonCopy | identifier_name |
mutex.rs | use core::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT, spin_loop_hint as cpu_relax};
use core::cell::UnsafeCell;
use core::marker::Sync;
use core::ops::{Drop, Deref, DerefMut};
use core::fmt;
use core::option::Option::{self, None, Some};
use core::default::Default;
/// This type provides MUTual EXclusion bas... |
#[test]
fn test_into_inner_drop() {
struct Foo(Arc<AtomicUsize>);
impl Drop for Foo {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let num_drops = Arc::new(AtomicUsize::new(0));
let m = Mutex::new(Foo(num_drops.... | {
let m = Mutex::new(NonCopy(10));
assert_eq!(m.into_inner(), NonCopy(10));
} | identifier_body |
mutex.rs | use core::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT, spin_loop_hint as cpu_relax};
use core::cell::UnsafeCell;
use core::marker::Sync;
use core::ops::{Drop, Deref, DerefMut};
use core::fmt;
use core::option::Option::{self, None, Some};
use core::default::Default;
/// This type provides MUTual EXclusion bas... |
else
{
None
}
}
}
impl<T:?Sized + fmt::Debug> fmt::Debug for Mutex<T>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
match self.try_lock()
{
Some(guard) => write!(f, "Mutex {{ data: ")
.and_then(|()| (&*guard).fmt(f))
.and_t... | {
Some(
MutexGuard {
lock: &self.lock,
data: unsafe { &mut *self.data.get() },
}
)
} | conditional_block |
where-clauses-method.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn main() {
let x = Foo { value: 1i };
let y = Foo { value: 2i };
println!("{}", x.equals(&x));
println!("{}", x.equals(&y));
}
| {
self.value == u.value
} | identifier_body |
where-clauses-method.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 ... | // additional constraints to a parameter out of scope.
struct Foo<T> {
value: T
}
impl<T> Foo<T> {
fn equals(&self, u: &Foo<T>) -> bool where T : Eq {
self.value == u.value
}
}
fn main() {
let x = Foo { value: 1i };
let y = Foo { value: 2i };
println!("{}", x.equals(&x));
println!... | random_line_split | |
where-clauses-method.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, u: &Foo<T>) -> bool where T : Eq {
self.value == u.value
}
}
fn main() {
let x = Foo { value: 1i };
let y = Foo { value: 2i };
println!("{}", x.equals(&x));
println!("{}", x.equals(&y));
}
| equals | identifier_name |
extract.rs | //! Extract dependency information from extract info.
use piston_meta::MetaData;
use dependencies::{ self, Package };
use range::Range;
use std::rc::Rc;
/// Stores extract information.
pub struct Extract {
/// The package name.
pub package: Rc<String>,
/// The url of the Cargo.toml.
pub url: Rc<String... | Ok(val) => val,
Err((range, err)) => {
let mut w: Vec<u8> = vec![];
ParseErrorHandler::new(&config).write(&mut w, range, err);
return Err(format!("{}: Syntax error in Cargo.toml for url `{}`\n{}",
&extract.package, &extract.url,... | for extract in &list {
let config = try!(load_text_file_from_url(&extract.url));
let cargo_toml_data = match parse(&cargo_toml_rules, &config) { | random_line_split |
extract.rs | //! Extract dependency information from extract info.
use piston_meta::MetaData;
use dependencies::{ self, Package };
use range::Range;
use std::rc::Rc;
/// Stores extract information.
pub struct Extract {
/// The package name.
pub package: Rc<String>,
/// The url of the Cargo.toml.
pub url: Rc<String... | (
mut data: &[(Range, MetaData)],
ignored: &mut Vec<Range>
) -> Result<Vec<Extract>, ()> {
use piston_meta::bootstrap::*;
let mut list = vec![];
let mut offset = 0;
loop {
if let Ok((range, extract)) = Extract::from_meta_data(data, offset, ignored) {
update(range, &mut data,... | convert_extract_info | identifier_name |
extract.rs | //! Extract dependency information from extract info.
use piston_meta::MetaData;
use dependencies::{ self, Package };
use range::Range;
use std::rc::Rc;
/// Stores extract information.
pub struct Extract {
/// The package name.
pub package: Rc<String>,
/// The url of the Cargo.toml.
pub url: Rc<String... | url = Some(val);
} else if let Ok((range, val)) = meta_string("ignore_version", data, offset) {
update(range, &mut data, &mut offset);
ignore_version = Some(val);
} else {
let range = ignore(data, offset);
update(ran... | {
use piston_meta::bootstrap::*;
let start_offset = offset;
let node = "library";
let start_range = try!(start_node(node, data, offset));
update(start_range, &mut data, &mut offset);
let mut package: Option<Rc<String>> = None;
let mut url: Option<Rc<String>> = N... | identifier_body |
extract.rs | //! Extract dependency information from extract info.
use piston_meta::MetaData;
use dependencies::{ self, Package };
use range::Range;
use std::rc::Rc;
/// Stores extract information.
pub struct Extract {
/// The package name.
pub package: Rc<String>,
/// The url of the Cargo.toml.
pub url: Rc<String... | else {
let range = ignore(data, offset);
update(range, &mut data, &mut offset);
ignored.push(range);
}
}
let package = try!(package.ok_or(()));
let url = try!(url.ok_or(()));
Ok((Range::new(start_offset, offset - start_offset)... | {
update(range, &mut data, &mut offset);
ignore_version = Some(val);
} | conditional_block |
unify.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 ... | (err: expected_found<ast::float_ty>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
| to_type_err | identifier_name |
unify.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 ... | Redirect(vid) => {
let node: Node<V,T> = helper(tcx, vb, vid.clone());
if node.root!= vid {
// Path compression
vb.vals.insert(vid.to_uint(),
Redirect(node.root.clone()));
... | match var_val { | random_line_split |
point_construction.rs | #[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::{Bounded, One, Zero};
use rand::distributions::{Distribution, Standard};
use rand::Rng;
use crate::base::allocator::Allocator;
use crate::base::dimension::{DimName, DimNameAdd, DimNameSum, U1, U2, U3, U4, U5, U6};
use crate::base::{DefaultAlloca... | }
}
/*
*
* Traits that build points.
*
*/
impl<N: Scalar + Bounded, D: DimName> Bounded for Point<N, D>
where
DefaultAllocator: Allocator<N, D>,
{
#[inline]
fn max_value() -> Self {
Self::from(VectorN::max_value())
}
#[inline]
fn min_value() -> Self {
Self::from(VectorN... |
None
}
| conditional_block |
point_construction.rs | #[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::{Bounded, One, Zero};
use rand::distributions::{Distribution, Standard};
use rand::Rng;
use crate::base::allocator::Allocator;
use crate::base::dimension::{DimName, DimNameAdd, DimNameSum, U1, U2, U3, U4, U5, U6};
use crate::base::{DefaultAlloca... | G: Gen>(g: &mut G) -> Self {
Self::from(VectorN::arbitrary(g))
}
}
/*
*
* Small points construction from components.
*
*/
macro_rules! componentwise_constructors_impl(
($($doc: expr; $D: ty, $($args: ident:$irow: expr),*);* $(;)*) => {$(
impl<N: Scalar> Point<N, $D>
where Defaul... | rbitrary< | identifier_name |
point_construction.rs | #[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::{Bounded, One, Zero};
use rand::distributions::{Distribution, Standard};
use rand::Rng;
use crate::base::allocator::Allocator;
use crate::base::dimension::{DimName, DimNameAdd, DimNameSum, U1, U2, U3, U4, U5, U6};
use crate::base::{DefaultAlloca... |
/// Creates a new point with all coordinates equal to zero.
///
/// # Example
///
/// ```
/// # use nalgebra::{Point2, Point3};
/// // This works in any dimension.
/// // The explicit crate::<f32> type annotation may not always be needed,
/// // depending on the context of type inf... | {
Self::from(VectorN::new_uninitialized())
} | identifier_body |
point_construction.rs | #[cfg(feature = "arbitrary")]
use quickcheck::{Arbitrary, Gen};
use num::{Bounded, One, Zero};
use rand::distributions::{Distribution, Standard};
use rand::Rng;
use crate::base::allocator::Allocator;
use crate::base::dimension::{DimName, DimNameAdd, DimNameSum, U1, U2, U3, U4, U5, U6};
use crate::base::{DefaultAlloca... | {
/// Creates a new point with uninitialized coordinates.
#[inline]
pub unsafe fn new_uninitialized() -> Self {
Self::from(VectorN::new_uninitialized())
}
/// Creates a new point with all coordinates equal to zero.
///
/// # Example
///
/// ```
/// # use nalgebra::{Point... | random_line_split | |
error_combinators.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use rayon::prelude::*;
// Helpers for unwrapping multiple Results to aggregate all success values or all error values.
pub fn try... |
#[macro_export]
macro_rules! validate {
($($args:expr),*) => {{
let mut errors = Vec::new();
$(
match $args {
Ok(_) => {},
Err(e) => {
errors.extend(e);
}
}
)*
if errors.is_empty() {
... | {
let results: Vec<Result<T, Vec<E>>> = items.into_par_iter().map(f).collect();
let mut errors = Vec::new();
let mut values = Vec::with_capacity(results.len());
for result in results {
match result {
Ok(item_value) => values.push(item_value),
Err(item_errors) => errors.ex... | identifier_body |
error_combinators.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use rayon::prelude::*;
// Helpers for unwrapping multiple Results to aggregate all success values or all error values.
pub fn try... | None
}
};
let t4 = match t4 {
Ok(t4) => Some(t4),
Err(e) => {
errors.extend(e);
None
}
};
if!errors.is_empty() {
Err(errors)
} else {
Ok((t1.unwrap(), t2.unwrap(), t3.unwrap(), t4.unwrap()))
}
}
/// Given an ite... | Err(e) => {
errors.extend(e); | random_line_split |
error_combinators.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use rayon::prelude::*;
// Helpers for unwrapping multiple Results to aggregate all success values or all error values.
pub fn try... | <T, E, I>(items: I) -> Result<Vec<T>, Vec<E>>
where
I: IntoIterator<Item = Result<T, Vec<E>>>,
{
try_map(items, |x| x)
}
/// Transforms the items of a list with a fallible transform function, returning either
/// all the transformed values if all items succeeded or a list of all errors if one or
/// more items... | try_all | identifier_name |
stream.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn connect(path: &Path) -> io::Result<net::UnixStream> { | Ok(_) => {}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
Err(e) => {
// Close the socket if we hit an error, ignoring the error
// from closing since we can't pass back two errors.
let _ = unsafe { libc::close(socket) };
return Err(e)... | let socket = new_socket(libc::AF_UNIX, libc::SOCK_STREAM)?;
let (sockaddr, socklen) = socket_addr(path)?;
let sockaddr = &sockaddr as *const libc::sockaddr_un as *const libc::sockaddr;
match syscall!(connect(socket, sockaddr, socklen)) { | random_line_split |
stream.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn connect(path: &Path) -> io::Result<net::UnixStream> {
let socket = new_socket(libc::AF_UNIX, libc::SOCK_STREAM)?;
le... | {
super::peer_addr(socket.as_raw_fd())
} | identifier_body | |
stream.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn connect(path: &Path) -> io::Result<net::UnixStream> {
let socket = new_socket(libc::AF_UNIX, libc::SOCK_STREAM)?;
le... |
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
Err(e) => {
// Close the socket if we hit an error, ignoring the error
// from closing since we can't pass back two errors.
let _ = unsafe { libc::close(socket) };
return Err(e);
}
}
... | {} | conditional_block |
stream.rs | use super::{socket_addr, SocketAddr};
use crate::sys::unix::net::new_socket;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net;
use std::path::Path;
pub(crate) fn connect(path: &Path) -> io::Result<net::UnixStream> {
let socket = new_socket(libc::AF_UNIX, libc::SOCK_STREAM)?;
le... | (socket: &net::UnixStream) -> io::Result<SocketAddr> {
super::local_addr(socket.as_raw_fd())
}
pub(crate) fn peer_addr(socket: &net::UnixStream) -> io::Result<SocketAddr> {
super::peer_addr(socket.as_raw_fd())
}
| local_addr | identifier_name |
db_job_depend.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct JobDepend {
pub id: i32,
pub fk_job: i32,
pub fk_variable: i32,
pub sq_order: i32,
}
pub fn table_create_job_depend(conn: &Connection) -> &Connection {
conn.execute(
"CREATE TABLE JOBDEPEND (
id INTEGER ... | }
job_depend_instance.unwrap();
return Ok(0);
}
pub fn list_job_depend(conn: &Connection) -> Vec<JobDepend> {
let mut stmt = conn
.prepare("SELECT id, fk_job, fk_variable, sq_order FROM JOBDEPEND")
.unwrap();
let wraped_fs_file_iter = stmt.query_map(&[], |row| JobDepend {
id:... | );
if job_depend_instance.is_err() {
return Err("Failed trying to INSERT INTO JOBDEPEND"); | random_line_split |
db_job_depend.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct JobDepend {
pub id: i32,
pub fk_job: i32,
pub fk_variable: i32,
pub sq_order: i32,
}
pub fn table_create_job_depend(conn: &Connection) -> &Connection {
conn.execute(
"CREATE TABLE JOBDEPEND (
id INTEGER ... | {
let count_prep_rc =
conn.prepare("SELECT JOBDEPEND.id FROM JOBDEPEND WHERE JOBDEPEND.fk_job = ?1");
match count_prep_rc {
Ok(mut result) => {
let result_row = result.query(&[fk_job]);
let mut rox = result_row.unwrap();
let mut counter = 0;
while ... | identifier_body | |
db_job_depend.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct JobDepend {
pub id: i32,
pub fk_job: i32,
pub fk_variable: i32,
pub sq_order: i32,
}
pub fn table_create_job_depend(conn: &Connection) -> &Connection {
conn.execute(
"CREATE TABLE JOBDEPEND (
id INTEGER ... |
let result = job_depend_iter.unwrap();
let mut found = 0;
for person in result {
let bill = person.unwrap();
output = bill.id;
found = 1;
}
if found!= 0 {
return Ok(output);
}
return Err("None found");
}
pub fn job_depend_count(conn: &Connection, fk_job: &i3... | {
return Err("Insert failed");
} | conditional_block |
db_job_depend.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct | {
pub id: i32,
pub fk_job: i32,
pub fk_variable: i32,
pub sq_order: i32,
}
pub fn table_create_job_depend(conn: &Connection) -> &Connection {
conn.execute(
"CREATE TABLE JOBDEPEND (
id INTEGER PRIMARY KEY ASC,
fk_job INTEGER NOT... | JobDepend | identifier_name |
core-traits-impls-length-33.rs | // check-pass
pub fn yes_as_ref() -> impl AsRef<[u8]> {
[0; 33]
} | }
pub fn yes_borrow() -> impl std::borrow::Borrow<[u8]> {
[0; 33]
}
pub fn yes_borrow_mut() -> impl std::borrow::BorrowMut<[u8]> {
[0; 33]
}
pub fn yes_try_from_slice() -> impl std::convert::TryFrom<&'static [u8]> {
[0; 33]
}
pub fn yes_ref_try_from_slice() -> impl std::convert::TryFrom<&'static [u8]> {... |
pub fn yes_as_mut() -> impl AsMut<[u8]> {
[0; 33] | random_line_split |
core-traits-impls-length-33.rs | // check-pass
pub fn yes_as_ref() -> impl AsRef<[u8]> {
[0; 33]
}
pub fn yes_as_mut() -> impl AsMut<[u8]> {
[0; 33]
}
pub fn yes_borrow() -> impl std::borrow::Borrow<[u8]> {
[0; 33]
}
pub fn yes_borrow_mut() -> impl std::borrow::BorrowMut<[u8]> {
[0; 33]
}
pub fn yes_try_from_slice() -> impl std::c... | () -> impl PartialEq<[u8; 33]> {
[0; 33]
}
pub fn yes_partial_eq_slice() -> impl PartialEq<[u8]> {
[0; 33]
}
pub fn yes_slice_partial_eq() -> impl PartialEq<[u8; 33]> {
let a: &'static _ = &[0; 33];
&a[..]
}
pub fn yes_eq() -> impl Eq {
[0; 33]
}
pub fn yes_partial_ord() -> impl PartialOrd<[u8; ... | yes_partial_eq | identifier_name |
core-traits-impls-length-33.rs | // check-pass
pub fn yes_as_ref() -> impl AsRef<[u8]> {
[0; 33]
}
pub fn yes_as_mut() -> impl AsMut<[u8]> {
[0; 33]
}
pub fn yes_borrow() -> impl std::borrow::Borrow<[u8]> {
[0; 33]
}
pub fn yes_borrow_mut() -> impl std::borrow::BorrowMut<[u8]> |
pub fn yes_try_from_slice() -> impl std::convert::TryFrom<&'static [u8]> {
[0; 33]
}
pub fn yes_ref_try_from_slice() -> impl std::convert::TryFrom<&'static [u8]> {
let a: &'static _ = &[0; 33];
a
}
pub fn yes_hash() -> impl std::hash::Hash {
[0; 33]
}
pub fn yes_debug() -> impl std::fmt::Debug {
... | {
[0; 33]
} | identifier_body |
main.rs | // Copyright (C) 2015 Sam Henson
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distribute... | println!("calling sync() and reboot()");
sync();
thread::sleep( Duration::new(3, 0) );
reboot();
} | println!("remounting root read-only");
remount_root(MS_RDONLY);
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.