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 |
|---|---|---|---|---|
day25.rs | use std::collections::HashMap;
use std::io::Read;
use crate::common::from_lines;
use crate::Solution;
const MOD_BASE: u32 = 20201227;
const SUBJECT_NUMBER: u32 = 7;
fn loop_count(public_key: u32) -> u64 {
discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64
}
// Implementation of the baby-step gia... | fn test_loop_count() {
assert_eq!(8, loop_count(5764801));
assert_eq!(11, loop_count(17807724));
}
#[test]
fn sample_part1() {
test_implementation(Day25, 1, SAMPLE, 14897079);
}
} |
#[test] | random_line_split |
aes_gcm_hkdf.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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 applicable law or ag... |
/// A [`noncebased::SegmentEncrypter`] based on AES-GCM-HKDF.
struct AesGcmHkdfSegmentEncrypter {
cipher_key: AesGcmKeyVariant,
}
impl noncebased::SegmentEncrypter for AesGcmHkdfSegmentEncrypter {
fn encrypt_segment(&self, segment: &[u8], nonce: &[u8]) -> Result<Vec<u8>, TinkError> {
let iv = Generic... | {
match aes_variant {
AesVariant::Aes128 => Ok(AesGcmKeyVariant::Aes128(Box::new(aes_gcm::Aes128Gcm::new(
GenericArray::from_slice(key),
)))),
AesVariant::Aes256 => Ok(AesGcmKeyVariant::Aes256(Box::new(aes_gcm::Aes256Gcm::new(
GenericArray::from_slice(key),
))... | identifier_body |
aes_gcm_hkdf.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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 applicable law or ag... | }
/// A [`noncebased::SegmentDecrypter`] based on AES-GCM-HKDF.
struct AesGcmHkdfSegmentDecrypter {
cipher_key: AesGcmKeyVariant,
}
impl noncebased::SegmentDecrypter for AesGcmHkdfSegmentDecrypter {
fn decrypt_segment(&self, segment: &[u8], nonce: &[u8]) -> Result<Vec<u8>, TinkError> {
let iv = Generi... | AesGcmKeyVariant::Aes128(key) => key.encrypt(iv, segment),
AesGcmKeyVariant::Aes256(key) => key.encrypt(iv, segment),
}
.map_err(|e| wrap_err("AesGcmHkdf: encryption failed", e))
} | random_line_split |
aes_gcm_hkdf.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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 applicable law or ag... | {
Aes128(Box<aes_gcm::Aes128Gcm>),
Aes256(Box<aes_gcm::Aes256Gcm>),
}
/// Calculate the header length for a given key size. The header includes
/// space for:
/// - a single byte indicating header length
/// - a salt that is the same size as the sub key
/// - a nonce prefix.
fn header_length_for(key_size_in_... | AesGcmKeyVariant | identifier_name |
aes_gcm_hkdf.rs | // Copyright 2020 The Tink-Rust Authors
//
// 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 applicable law or ag... |
let mut salt = vec![0; self.aes_variant.key_size()];
r.read_exact(&mut salt)
.map_err(|e| wrap_err("cannot read salt", e))?;
let mut nonce_prefix = vec![0; AES_GCM_HKDF_NONCE_PREFIX_SIZE_IN_BYTES];
r.read_exact(&mut nonce_prefix)
.map_err(|e| wrap_err("cannot rea... | {
return Err("invalid header length".into());
} | conditional_block |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLOptionElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLOptionElementD... |
pub fn DefaultSelected(&self) -> bool {
false
}
pub fn SetDefaultSelected(&mut self, _default_selected: bool) -> ErrorResult {
Ok(())
}
pub fn Selected(&self) -> bool {
false
}
pub fn SetSelected(&mut self, _selected: bool) -> ErrorResult {
Ok(())
}
... | {
Ok(())
} | identifier_body |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLOptionElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLOptionElementD... | (&mut self, _value: DOMString) -> ErrorResult {
Ok(())
}
pub fn Text(&self) -> DOMString {
~""
}
pub fn SetText(&mut self, _text: DOMString) -> ErrorResult {
Ok(())
}
pub fn Index(&self) -> i32 {
0
}
}
| SetValue | identifier_name |
htmloptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLOptionElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLOptionElementD... | pub fn Value(&self) -> DOMString {
~""
}
pub fn SetValue(&mut self, _value: DOMString) -> ErrorResult {
Ok(())
}
pub fn Text(&self) -> DOMString {
~""
}
pub fn SetText(&mut self, _text: DOMString) -> ErrorResult {
Ok(())
}
pub fn Index(&self) -> i3... |
pub fn SetSelected(&mut self, _selected: bool) -> ErrorResult {
Ok(())
}
| random_line_split |
proximity_ball_ball.rs | use crate::math::Point;
use crate::query::Proximity;
use crate::shape::Ball;
use na::{self, RealField};
/// Proximity between balls.
#[inline]
pub fn proximity_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
margin: N,
) -> Proximity {
assert!(
... | else {
Proximity::Disjoint
}
}
| {
if distance_squared <= sum_radius * sum_radius {
Proximity::Intersecting
} else {
Proximity::WithinMargin
}
} | conditional_block |
proximity_ball_ball.rs | use crate::math::Point;
use crate::query::Proximity;
use crate::shape::Ball;
use na::{self, RealField};
/// Proximity between balls.
#[inline]
pub fn proximity_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
margin: N,
) -> Proximity | Proximity::Disjoint
}
}
| {
assert!(
margin >= na::zero(),
"The proximity margin must be positive or null."
);
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_ra... | identifier_body |
proximity_ball_ball.rs | use crate::math::Point;
use crate::query::Proximity;
use crate::shape::Ball;
use na::{self, RealField};
/// Proximity between balls.
#[inline]
pub fn | <N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
margin: N,
) -> Proximity {
assert!(
margin >= na::zero(),
"The proximity margin must be positive or null."
);
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *... | proximity_ball_ball | identifier_name |
proximity_ball_ball.rs | use crate::math::Point;
use crate::query::Proximity;
use crate::shape::Ball;
use na::{self, RealField};
/// Proximity between balls.
#[inline]
pub fn proximity_ball_ball<N: RealField>(
center1: &Point<N>,
b1: &Ball<N>,
center2: &Point<N>,
b2: &Ball<N>,
margin: N, |
let r1 = b1.radius;
let r2 = b2.radius;
let delta_pos = *center2 - *center1;
let distance_squared = delta_pos.norm_squared();
let sum_radius = r1 + r2;
let sum_radius_with_error = sum_radius + margin;
if distance_squared <= sum_radius_with_error * sum_radius_with_error {
if distanc... | ) -> Proximity {
assert!(
margin >= na::zero(),
"The proximity margin must be positive or null."
); | random_line_split |
derive_object_with_raw_idents.rs | use juniper::{
execute, graphql_object, graphql_value, EmptyMutation, EmptySubscription, GraphQLInputObject,
RootNode, Value, Variables,
};
pub struct Query;
#[graphql_object]
impl Query {
fn r#type(r#fn: MyInputType) -> Vec<String> {
let _ = r#fn;
unimplemented!()
}
}
#[derive(GraphQ... | }
]
}
}
),
);
}
#[tokio::test]
async fn supports_raw_idents_in_fields_of_input_types() {
let doc = r#"
{
__type(name: "MyInputType") {
inputFields {
name
}
}
}
"#;
... | random_line_split | |
derive_object_with_raw_idents.rs | use juniper::{
execute, graphql_object, graphql_value, EmptyMutation, EmptySubscription, GraphQLInputObject,
RootNode, Value, Variables,
};
pub struct Query;
#[graphql_object]
impl Query {
fn r#type(r#fn: MyInputType) -> Vec<String> {
let _ = r#fn;
unimplemented!()
}
}
#[derive(GraphQ... | "name": "trait",
}
]
}
}
),
);
}
async fn run_type_info_query(doc: &str) -> Value {
let schema = RootNode::new(
Query,
EmptyMutation::<()>::new(),
EmptySubscription::<()>::new(),... | {
let doc = r#"
{
__type(name: "MyInputType") {
inputFields {
name
}
}
}
"#;
let value = run_type_info_query(&doc).await;
assert_eq!(
value,
graphql_value!(
{
"__type": {
"inpu... | identifier_body |
derive_object_with_raw_idents.rs | use juniper::{
execute, graphql_object, graphql_value, EmptyMutation, EmptySubscription, GraphQLInputObject,
RootNode, Value, Variables,
};
pub struct Query;
#[graphql_object]
impl Query {
fn r#type(r#fn: MyInputType) -> Vec<String> {
let _ = r#fn;
unimplemented!()
}
}
#[derive(GraphQ... | () {
let doc = r#"
{
__type(name: "MyInputType") {
inputFields {
name
}
}
}
"#;
let value = run_type_info_query(&doc).await;
assert_eq!(
value,
graphql_value!(
{
"__type": {
"i... | supports_raw_idents_in_fields_of_input_types | identifier_name |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... | pub mod console;
pub mod engine;
pub mod host;
pub mod math;
pub mod mdl;
pub mod model;
pub mod net;
pub mod pak;
pub mod parse;
pub mod sprite;
pub mod util;
pub mod vfs;
pub mod wad;
use std::path::PathBuf;
pub fn default_base_dir() -> std::path::PathBuf {
match std::env::current_dir() {
Ok(cwd) => cwd... | pub mod alloc;
pub mod bitset;
pub mod bsp; | random_line_split |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... |
pub const MAX_LIGHTSTYLES: usize = 64;
/// The maximum number of `.pak` files that should be loaded at runtime.
///
/// The original engine does not make this restriction, and this limit can be increased if need be.
pub const MAX_PAKFILES: usize = 32;
|
match std::env::current_dir() {
Ok(cwd) => cwd,
Err(e) => {
log::error!("cannot access current directory: {}", e);
std::process::exit(1);
}
}
}
| identifier_body |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... | ) -> std::path::PathBuf {
match std::env::current_dir() {
Ok(cwd) => cwd,
Err(e) => {
log::error!("cannot access current directory: {}", e);
std::process::exit(1);
}
}
}
pub const MAX_LIGHTSTYLES: usize = 64;
/// The maximum number of `.pak` files that should be... | efault_base_dir( | identifier_name |
lib.rs | #![no_std]
#![warn(missing_docs)]
//! A logging facade for writing logging information to the Linux Kernel System
//! Log.
use log;
use core::fmt;
use core::fmt::Write;
extern "C" {
fn printk(fmt: *const u8,...) -> i32;
}
/// A logger which writes to the Linux Kernel System Log.
pub struct DMesgLogger {}
stru... |
}
| {} | identifier_body |
lib.rs | #![no_std]
#![warn(missing_docs)]
//! A logging facade for writing logging information to the Linux Kernel System
//! Log.
use log;
use core::fmt;
use core::fmt::Write;
extern "C" {
fn printk(fmt: *const u8,...) -> i32;
}
/// A logger which writes to the Linux Kernel System Log.
pub struct DMesgLogger {}
stru... | {}
const KERN_INFO: &[u8; 2] = b"6\0";
// https://www.kernel.org/doc/html/latest/core-api/printk-basics.html
impl fmt::Write for PrintK {
fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
unsafe {
printk(KERN_INFO.as_ptr());
}
for c in s.bytes() {
unsaf... | PrintK | identifier_name |
lib.rs | #![no_std]
#![warn(missing_docs)]
//! A logging facade for writing logging information to the Linux Kernel System
//! Log.
use log;
use core::fmt;
use core::fmt::Write;
extern "C" {
fn printk(fmt: *const u8,...) -> i32;
}
/// A logger which writes to the Linux Kernel System Log.
pub struct DMesgLogger {}
stru... |
}
fn flush(&self) {}
}
| {
self.write_fmt(*record.args());
} | conditional_block |
lib.rs | #![no_std]
#![warn(missing_docs)]
//! A logging facade for writing logging information to the Linux Kernel System
//! Log.
use log;
use core::fmt;
use core::fmt::Write;
extern "C" {
fn printk(fmt: *const u8,...) -> i32;
}
/// A logger which writes to the Linux Kernel System Log.
pub struct DMesgLogger {}
stru... | fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
self.write_fmt(*record.args());
}
}
fn flush(&self) {}
} | random_line_split | |
add.rs | use std::error;
use std::fs;
use std::path;
use std::io::Read;
use itertools::Itertools;
use fat;
pub fn add_file(args: &[String])
-> Result<(), Box<error::Error>>
|
// Ensure input file exists.
let file = fs::File::open(file_name)?;
let metadata = file.metadata()?;
// Create a root dir entry.
let (entry, index) =
image.create_file_entry(fat_file_name, metadata.len() as u32)?;
// Get free FAT entries, fill sectors with file data.
for chunk in ... | {
expect_args!(args, 2);
let file_name = args[0].clone();
let image_name = args[1].clone();
let fat_file_name = if args.len() > 2 {
args[2].clone()
} else {
match path::Path::new(&file_name).file_name() {
Some(n) => n.to_string_lossy().into_owned(),
None => ... | identifier_body |
add.rs | use std::error;
use std::fs;
use std::path;
use std::io::Read;
use itertools::Itertools;
use fat;
pub fn | (args: &[String])
-> Result<(), Box<error::Error>>
{
expect_args!(args, 2);
let file_name = args[0].clone();
let image_name = args[1].clone();
let fat_file_name = if args.len() > 2 {
args[2].clone()
} else {
match path::Path::new(&file_name).file_name() {
Some(n) =>... | add_file | identifier_name |
add.rs | use std::error;
use std::fs;
use std::path;
use std::io::Read;
use itertools::Itertools;
use fat;
pub fn add_file(args: &[String])
-> Result<(), Box<error::Error>>
{
expect_args!(args, 2);
let file_name = args[0].clone();
let image_name = args[1].clone();
let fat_file_name = if args.len() > 2 {... | // Get free sector.
let entry_index: usize;
match image.get_free_fat_entry() {
Some(i) => entry_index = i,
None => {
// TODO: Remove entries written so far.
panic!("image ran out of space while writing file")
},
}
... | random_line_split | |
error.rs | use image::ImageError;
use std::{io, fmt};
use std::error::Error;
#[derive(Debug)]
pub enum ShadowError {
Configuration(String),
ImageLibrary(ImageError),
Image(String),
Io(io::Error),
NotImplemented,
}
impl Error for ShadowError {
fn description(&self) -> &str {
match *self {
... |
}
impl fmt::Display for ShadowError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ShadowError::Configuration(ref msg) => write!(f, "Configuration error: {}", msg),
ShadowError::ImageLibrary(ref err) => err.fmt(f),
ShadowError::Image(ref msg) => ... | {
match *self {
ShadowError::ImageLibrary(ref err) => err.cause(),
ShadowError::Io(ref err) => err.cause(),
_ => None,
}
} | identifier_body |
error.rs | use image::ImageError;
use std::{io, fmt};
use std::error::Error;
#[derive(Debug)]
pub enum ShadowError {
Configuration(String),
ImageLibrary(ImageError),
Image(String),
Io(io::Error),
NotImplemented,
}
impl Error for ShadowError {
fn description(&self) -> &str {
match *self {
... | (err: io::Error) -> ShadowError {
ShadowError::Io(err)
}
}
impl From<ImageError> for ShadowError {
fn from(err: ImageError) -> ShadowError {
ShadowError::ImageLibrary(err)
}
}
| from | identifier_name |
error.rs | use image::ImageError;
use std::{io, fmt};
use std::error::Error;
#[derive(Debug)]
pub enum ShadowError {
Configuration(String), | ImageLibrary(ImageError),
Image(String),
Io(io::Error),
NotImplemented,
}
impl Error for ShadowError {
fn description(&self) -> &str {
match *self {
ShadowError::Configuration(_) => "configuration error",
ShadowError::ImageLibrary(ref err) => err.description(),
... | random_line_split | |
mod.rs | #[macro_use]
// has macros, must go first
mod utils;
pub mod annotation;
pub mod attribute;
pub mod attribute_group;
pub mod attributes;
pub mod choice;
pub mod common;
pub mod complex_content;
pub mod complex_type;
pub mod constants;
pub mod element;
pub mod extension;
pub mod group;
pub mod id;
pub mod import;
pub m... |
pub(crate) fn type_attribute(node: &exile::Element) -> Result<String> {
get_attribute(node, TYPE)
}
pub(crate) fn use_required(node: &exile::Element) -> bool {
match get_attribute(node, USE) {
Ok(val) => val.as_str() == REQUIRED,
Err(_) => false,
}
}
pub(crate) fn default_attribute(node:... | {
get_attribute(node, REF)
} | identifier_body |
mod.rs | #[macro_use]
// has macros, must go first
mod utils;
pub mod annotation;
pub mod attribute;
pub mod attribute_group;
pub mod attributes;
pub mod choice;
pub mod common;
pub mod complex_content;
pub mod complex_type;
pub mod constants;
pub mod element;
pub mod extension;
pub mod group;
pub mod id;
pub mod import;
pub m... | (node: &exile::Element) -> Result<String> {
get_attribute(node, TYPE)
}
pub(crate) fn use_required(node: &exile::Element) -> bool {
match get_attribute(node, USE) {
Ok(val) => val.as_str() == REQUIRED,
Err(_) => false,
}
}
pub(crate) fn default_attribute(node: &exile::Element) -> Option<St... | type_attribute | identifier_name |
mod.rs | #[macro_use]
// has macros, must go first
mod utils;
pub mod annotation;
pub mod attribute;
pub mod attribute_group;
pub mod attributes;
pub mod choice;
pub mod common;
pub mod complex_content;
pub mod complex_type;
pub mod constants;
pub mod element;
pub mod extension;
pub mod group;
pub mod id;
pub mod import;
pub m... | ];
for (xml, want) in test_cases {
let doc = exile::parse(xml).unwrap();
let got = Occurs::from_xml(doc.root()).unwrap();
assert_eq!(got, want)
}
}
#[test]
fn parse_occurs_err() {
let test_cases = vec for more
//! information.
//!
//! # Safety
//!
//! Obviously unsafe.
//!
//! Every `handle` shall be initialied first with `cs_open`.
//!
//! # Examples
//!
//! TODO
# for more
//! information.
//!
//! # Safety
//!
//! Obviously unsafe.
//!
//! Every `handle` shall be initialied first with `cs_open`.
//!
//! # Examples
//!
//! TODO
#![allow(non_camel... | (&self) -> &sparc::cs_sparc {
::std::mem::transmute(&self.data)
}
pub unsafe fn sysz(&self) -> &sysz::cs_sysz {
::std::mem::transmute(&self.data)
}
pub unsafe fn xcore(&self) -> &xcore::cs_xcore {
::std::mem::transmute(&self.data)
}
}
/// Information on a disassembled instru... | sparc | identifier_name |
seq.rs | extern crate libc;
use std::fmt;
use std::default::Default;
use self::libc::{c_double};
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Seq {
begin: c_double,
end: c_double,
step: c_double,
}
/// Default `Seq` spans all the elements along a dimension
impl Default f... |
}
/// Enables use of `Seq` with `{}` format in print statements
impl fmt::Display for Seq {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[begin: {}, end: {}, step: {}]", self.begin, self.end, self.step)
}
}
impl Seq {
/// Create a `Seq` that goes from `begin` to `end` at a st... | {
Seq { begin: 1.0, end: 1.0, step: 0.0, }
} | identifier_body |
seq.rs | extern crate libc;
use std::fmt;
use std::default::Default;
use self::libc::{c_double};
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone)]
#[repr(C)]
pub struct | {
begin: c_double,
end: c_double,
step: c_double,
}
/// Default `Seq` spans all the elements along a dimension
impl Default for Seq {
fn default() -> Seq {
Seq { begin: 1.0, end: 1.0, step: 0.0, }
}
}
/// Enables use of `Seq` with `{}` format in print statements
impl fmt::Display for Seq ... | Seq | identifier_name |
seq.rs | extern crate libc;
use std::fmt;
use std::default::Default;
use self::libc::{c_double};
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Seq {
begin: c_double,
end: c_double, | step: c_double,
}
/// Default `Seq` spans all the elements along a dimension
impl Default for Seq {
fn default() -> Seq {
Seq { begin: 1.0, end: 1.0, step: 0.0, }
}
}
/// Enables use of `Seq` with `{}` format in print statements
impl fmt::Display for Seq {
fn fmt(&self, f: &mut fmt::Formatter)... | random_line_split | |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use std::io;
use rocket::request::{Form, FromFormValue};
use rocket::response::NamedFile;
use rocket::http::RawStr;
// TODO: Make deriving `FromForm` for this enum possible.
#[derive(Debug)]
enum FormOption {
A, B, C
}
impl<'v> F... | }
}
#[derive(Debug, FromForm)]
struct FormInput {
checkbox: bool,
number: usize,
#[form(field = "type")]
radio: FormOption,
password: String,
#[form(field = "textarea")]
text_area: String,
select: FormOption,
}
#[post("/", data = "<sink>")]
fn sink(sink: Result<Form<FormInput>, Opt... | Ok(variant) | random_line_split |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use std::io;
use rocket::request::{Form, FromFormValue};
use rocket::response::NamedFile;
use rocket::http::RawStr;
// TODO: Make deriving `FromForm` for this enum possible.
#[derive(Debug)]
enum FormOption {
A, B, C
}
impl<'v> F... | () {
rocket::ignite()
.mount("/", routes![index, sink])
.launch();
}
| main | identifier_name |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use std::io;
use rocket::request::{Form, FromFormValue};
use rocket::response::NamedFile;
use rocket::http::RawStr;
// TODO: Make deriving `FromForm` for this enum possible.
#[derive(Debug)]
enum FormOption {
A, B, C
}
impl<'v> F... |
#[get("/")]
fn index() -> io::Result<NamedFile> {
NamedFile::open("static/index.html")
}
fn main() {
rocket::ignite()
.mount("/", routes![index, sink])
.launch();
}
| {
match sink {
Ok(form) => format!("{:?}", form.get()),
Err(Some(f)) => format!("Invalid form input: {}", f),
Err(None) => format!("Form input was invalid UTF8."),
}
} | identifier_body |
mod.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
/// Helper type for futures that can result in `NfsError`.
pub type NfsFuture<T> = Future<Item = T, Error = NfsError>; | random_line_split | |
api_agent.rs | use actix::prelude::*;
use actix_web::*;
use bytes::Bytes;
use crate::actors::{ForwardA2AMsg, GetEndpoint};
use crate::app::AppData;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub fn generate_api_agent_configuration(api_prefix: &String) -> Box<dyn FnOnce(&mut web::ServiceConfig)>{
let prefix = api_prefix.clone... | (state: web::Data<AppData>) -> Box<dyn Future<Item=HttpResponse, Error=Error>> {
let f = state.forward_agent
.send(GetEndpoint {})
.from_err()
.map(|res| match res {
Ok(endpoint) => HttpResponse::Ok().json(&endpoint),
Err(err) => HttpResponse::InternalServerError().body(... | _get_endpoint_details | identifier_name |
api_agent.rs | use actix::prelude::*;
use actix_web::*;
use bytes::Bytes;
use crate::actors::{ForwardA2AMsg, GetEndpoint};
use crate::app::AppData;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub fn generate_api_agent_configuration(api_prefix: &String) -> Box<dyn FnOnce(&mut web::ServiceConfig)>{
let prefix = api_prefix.clone... | .and_then(|res| match res {
Ok(msg) => Ok(Bytes::from(msg).into()),
Err(err) => Ok(HttpResponse::InternalServerError().body(format!("{:?}", err)).into()), // FIXME: Better error
})
});
Box::new(f)
} | random_line_split | |
api_agent.rs | use actix::prelude::*;
use actix_web::*;
use bytes::Bytes;
use crate::actors::{ForwardA2AMsg, GetEndpoint};
use crate::app::AppData;
const MAX_PAYLOAD_SIZE: usize = 105_906_176;
pub fn generate_api_agent_configuration(api_prefix: &String) -> Box<dyn FnOnce(&mut web::ServiceConfig)> |
fn _get_endpoint_details(state: web::Data<AppData>) -> Box<dyn Future<Item=HttpResponse, Error=Error>> {
let f = state.forward_agent
.send(GetEndpoint {})
.from_err()
.map(|res| match res {
Ok(endpoint) => HttpResponse::Ok().json(&endpoint),
Err(err) => HttpResponse::I... | {
let prefix = api_prefix.clone();
Box::new( move |cfg: &mut web::ServiceConfig| {
cfg.service(
web::scope(&prefix)
.route("", web::get().to(_get_endpoint_details))
.route("/msg", web::post().to(_forward_message)));
})
} | identifier_body |
jstraceable.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 syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem, E... | fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let state_expr = match substr.nonself_args {
[ref state_expr] => state_expr,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `jstraceable`")
};
let trace_ident = substr.method_i... | // Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated | random_line_split |
jstraceable.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 syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem, E... | associated_types: vec![],
};
trait_def.expand(cx, mitem, item, |a| push(a))
}
// Mostly copied from syntax::ext::deriving::hash
/// Defines how the implementation for `trace()` is to be generated
fn jstraceable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
le... | {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: ty::Path::new(vec!("dom","bindings","trace","JSTraceable")),
additional_bounds: Vec::new(),
generics: ty::LifetimeBounds::empty(),
methods: vec![
MethodDef {
name: "trac... | identifier_body |
jstraceable.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 syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem, E... | (_: &mut ExtCtxt, _: Span, _: &MetaItem, item: P<Item>) -> P<Item> {
let mut item2 = (*item).clone();
{
let mut add_attr = |s| {
item2.attrs.push(attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_word_item(InternedString::new(s))));
};
add_attr("must_root");
add_attr("... | expand_dom_struct | identifier_name |
request.rs | use std::io::Read;
use std::net::{SocketAddr, TcpStream};
use super::headers::Headers;
use super::query::Query;
#[allow(dead_code)]
pub struct Request {
http_version: (u16, u16),
method: String,
scheme: String,
path: Vec<String>,
path_str: String,
query: Option<Query>,
headers: Headers,
... | }
pub fn content_length(&self) -> Option<u64> {
self.content_length
}
pub fn headers(&self) -> &Headers {
&self.headers
}
pub fn body<'a>(&'a mut self) -> &'a mut Read {
&mut self.stream
}
} | pub fn remote_addr(&self) -> SocketAddr {
self.stream.peer_addr().unwrap() | random_line_split |
request.rs | use std::io::Read;
use std::net::{SocketAddr, TcpStream};
use super::headers::Headers;
use super::query::Query;
#[allow(dead_code)]
pub struct Request {
http_version: (u16, u16),
method: String,
scheme: String,
path: Vec<String>,
path_str: String,
query: Option<Query>,
headers: Headers,
... |
pub fn remote_addr(&self) -> SocketAddr {
self.stream.peer_addr().unwrap()
}
pub fn content_length(&self) -> Option<u64> {
self.content_length
}
pub fn headers(&self) -> &Headers {
&self.headers
}
pub fn body<'a>(&'a mut self) -> &'a mut Read {
&mut self.... | {
&self.query
} | identifier_body |
request.rs | use std::io::Read;
use std::net::{SocketAddr, TcpStream};
use super::headers::Headers;
use super::query::Query;
#[allow(dead_code)]
pub struct Request {
http_version: (u16, u16),
method: String,
scheme: String,
path: Vec<String>,
path_str: String,
query: Option<Query>,
headers: Headers,
... | (&self) -> Option<u64> {
self.content_length
}
pub fn headers(&self) -> &Headers {
&self.headers
}
pub fn body<'a>(&'a mut self) -> &'a mut Read {
&mut self.stream
}
}
| content_length | identifier_name |
etcd.rs | extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate openssl;
use std::time::Duration;
use std::thread;
use hyper::Error;
use hyper::status::StatusCode;
use serde_json::Value;
pub use common::etcd::SSLOptions;
use common::etcd::etcd_https_client;
/// Polls the etcd health endpoint until it... | if health == "true" {
return Ok(());
} else {
println!("Health is {}", health);
}
} else {
println!("Etcd not responding. Will try again");
}
}
}
| {
let client = try!(etcd_https_client(options));
let health_url = server_url + "/health";
loop {
thread::sleep(Duration::from_millis(1000));
println!("Checking etcd status...");
if let Ok(response) = client.get(&health_url).send() {
if response.status != StatusCode::Ok ... | identifier_body |
etcd.rs | extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate openssl;
use std::time::Duration;
use std::thread;
use hyper::Error;
use hyper::status::StatusCode;
use serde_json::Value;
pub use common::etcd::SSLOptions;
use common::etcd::etcd_https_client;
/// Polls the etcd health endpoint until it... | }
} else {
println!("Etcd not responding. Will try again");
}
}
} | random_line_split | |
etcd.rs | extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate openssl;
use std::time::Duration;
use std::thread;
use hyper::Error;
use hyper::status::StatusCode;
use serde_json::Value;
pub use common::etcd::SSLOptions;
use common::etcd::etcd_https_client;
/// Polls the etcd health endpoint until it... | (server_url: String, options: SSLOptions)
-> Result<(), Error> {
let client = try!(etcd_https_client(options));
let health_url = server_url + "/health";
loop {
thread::sleep(Duration::from_millis(1000));
println!("Checking etcd status...");
if let Ok(respon... | wait_till_healthy | identifier_name |
etcd.rs | extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate openssl;
use std::time::Duration;
use std::thread;
use hyper::Error;
use hyper::status::StatusCode;
use serde_json::Value;
pub use common::etcd::SSLOptions;
use common::etcd::etcd_https_client;
/// Polls the etcd health endpoint until it... |
}
}
| {
println!("Etcd not responding. Will try again");
} | conditional_block |
linearinterpol.rs | use crate::FastFieldCodecReader;
use crate::FastFieldCodecSerializer;
use crate::FastFieldDataAccess;
use crate::FastFieldStats;
use std::io::{self, Read, Write};
use std::ops::Sub;
use tantivy_bitpacker::compute_num_bits;
use tantivy_bitpacker::BitPacker;
use common::BinarySerializable;
use common::FixedSize;
use tan... | return false;
}
true
}
/// estimation for linear interpolation is hard because, you don't know
/// where the local maxima for the deviation of the calculated value are and
/// the offset to shift all values to >=0 is also unknown.
fn estimate(fastfield_accessor: &impl Fas... | { | random_line_split |
linearinterpol.rs | use crate::FastFieldCodecReader;
use crate::FastFieldCodecSerializer;
use crate::FastFieldDataAccess;
use crate::FastFieldStats;
use std::io::{self, Read, Write};
use std::ops::Sub;
use tantivy_bitpacker::compute_num_bits;
use tantivy_bitpacker::BitPacker;
use common::BinarySerializable;
use common::FixedSize;
use tan... |
}
// rel_positive_max will be adjusted by offset
let relative_max_value = rel_positive_max + offset;
let num_bits = compute_num_bits(relative_max_value);
let mut bit_packer = BitPacker::new();
for (pos, val) in data_iter.enumerate() {
let calculated_value =... | {
//positive value no offset reuqired
rel_positive_max = rel_positive_max.max(actual_value - calculated_value);
} | conditional_block |
linearinterpol.rs | use crate::FastFieldCodecReader;
use crate::FastFieldCodecSerializer;
use crate::FastFieldDataAccess;
use crate::FastFieldStats;
use std::io::{self, Read, Write};
use std::ops::Sub;
use tantivy_bitpacker::compute_num_bits;
use tantivy_bitpacker::BitPacker;
use common::BinarySerializable;
use common::FixedSize;
use tan... |
}
| {
for _ in 0..5000 {
let mut data = (0..50).map(|_| rand::random::<u64>()).collect::<Vec<_>>();
create_and_validate(&data, "random");
data.reverse();
create_and_validate(&data, "random");
}
} | identifier_body |
linearinterpol.rs | use crate::FastFieldCodecReader;
use crate::FastFieldCodecSerializer;
use crate::FastFieldDataAccess;
use crate::FastFieldStats;
use std::io::{self, Read, Write};
use std::ops::Sub;
use tantivy_bitpacker::compute_num_bits;
use tantivy_bitpacker::BitPacker;
use common::BinarySerializable;
use common::FixedSize;
use tan... | () {
let data = (10..=20_u64).collect::<Vec<_>>();
create_and_validate(&data, "simple monotonically");
}
#[test]
fn linear_interpol_fast_field_rand() {
for _ in 0..5000 {
let mut data = (0..50).map(|_| rand::random::<u64>()).collect::<Vec<_>>();
create_and_v... | linear_interpol_fast_field_test_simple | identifier_name |
lib.rs | #![no_std]
#![allow(non_upper_case_globals)]
use libtww::{game::Console, system::custom_game_loop};
use gcn_fonts::prelude::*;
pub mod cheat_menu;
pub mod controller;
pub mod flag_menu;
pub mod inventory_menu;
pub mod main_menu;
pub mod memory;
pub mod popups;
pub mod print;
pub mod settings;
pub mod spawn_menu;
pub... | {
print::setup_draw();
memory::render_watches();
} | identifier_body | |
lib.rs | #![no_std]
#![allow(non_upper_case_globals)]
use libtww::{game::Console, system::custom_game_loop};
use gcn_fonts::prelude::*;
pub mod cheat_menu;
pub mod controller;
pub mod flag_menu;
pub mod inventory_menu;
pub mod main_menu;
pub mod memory;
pub mod popups;
pub mod print;
pub mod settings;
pub mod spawn_menu;
pub... | () {
print::setup_draw();
memory::render_watches();
}
| draw | identifier_name |
lib.rs |
use gcn_fonts::prelude::*;
pub mod cheat_menu;
pub mod controller;
pub mod flag_menu;
pub mod inventory_menu;
pub mod main_menu;
pub mod memory;
pub mod popups;
pub mod print;
pub mod settings;
pub mod spawn_menu;
pub mod utils;
pub mod warp_menu;
pub static mut visible: bool = false;
struct State {
font: Uploa... | #![no_std]
#![allow(non_upper_case_globals)]
use libtww::{game::Console, system::custom_game_loop}; | random_line_split | |
issue-13853.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 iterate<N: Node, G: Graph<N>>(graph: &G) {
for node in graph.iter() { //~ ERROR does not implement any method in scope named
node.zomg(); //~ error: the type of this value must be known in this context
}
}
pub fn main() {
let graph = Vec::new();
graph.push(Stuff);
iterate(graph); ... | {
println!("zomg");
} | identifier_body |
issue-13853.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 zomg();
}
trait Graph<N: Node> {
fn nodes<'a, I: Iterator<Item=&'a N>>(&'a self) -> I;
}
impl<N: Node> Graph<N> for Vec<N> {
fn nodes<'a, I: Iterator<Item=&'a N>>(&self) -> I {
self.iter() //~ ERROR mismatched types
}
}
struct Stuff;
impl Node for Stuff {
fn zomg() {
println!(... | use std::marker::MarkerTrait;
trait Node : MarkerTrait { | random_line_split |
issue-13853.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let graph = Vec::new();
graph.push(Stuff);
iterate(graph); //~ ERROR mismatched types
}
| main | identifier_name |
effects.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/. */
//! Generic types for CSS values related to effects.
/// A generic value for a single `box-shadow`.
#[derive(
... | <Color, SizeLength, ShapeLength> {
/// Color.
pub color: Color,
/// Horizontal radius.
pub horizontal: SizeLength,
/// Vertical radius.
pub vertical: SizeLength,
/// Blur radius.
pub blur: ShapeLength,
}
pub use self::GenericSimpleShadow as SimpleShadow;
| GenericSimpleShadow | identifier_name |
effects.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/. */
//! Generic types for CSS values related to effects.
/// A generic value for a single `box-shadow`.
#[derive(
... | pub color: Color,
/// Horizontal radius.
pub horizontal: SizeLength,
/// Vertical radius.
pub vertical: SizeLength,
/// Blur radius.
pub blur: ShapeLength,
}
pub use self::GenericSimpleShadow as SimpleShadow; | #[repr(C)]
pub struct GenericSimpleShadow<Color, SizeLength, ShapeLength> {
/// Color. | random_line_split |
lib.rs | //! The `check` crate is responsible for ensuring that an AST expression is actually a valid
//! program. This currently consits of three larger parts, typechecking, kindchecking and renaming.
//! If an AST passes the checks in `Typecheck::typecheck_expr` (which runs all of theses checks
//! the expression is expected ... |
fn find_type_info(&self, _id: &SymbolRef) -> Option<Alias<Symbol, RcType>> {
None
}
}
/// Returns a reference to the interner stored in TLD
pub fn get_local_interner() -> Rc<RefCell<Symbols>> {
thread_local!(static INTERNER: Rc<RefCell<Symbols>>
= Rc::new(RefCel... | {
None
} | identifier_body |
lib.rs | //! The `check` crate is responsible for ensuring that an AST expression is actually a valid
//! program. This currently consits of three larger parts, typechecking, kindchecking and renaming.
//! If an AST passes the checks in `Typecheck::typecheck_expr` (which runs all of theses checks
//! the expression is expected ... | () -> Rc<RefCell<Symbols>> {
thread_local!(static INTERNER: Rc<RefCell<Symbols>>
= Rc::new(RefCell::new(Symbols::new())));
INTERNER.with(|interner| interner.clone())
}
pub fn intern(s: &str) -> Symbol {
let interner = get_local_interner();
let mut interner = interner.bor... | get_local_interner | identifier_name |
lib.rs | //! The `check` crate is responsible for ensuring that an AST expression is actually a valid
//! program. This currently consits of three larger parts, typechecking, kindchecking and renaming.
//! If an AST passes the checks in `Typecheck::typecheck_expr` (which runs all of theses checks
//! the expression is expected ... |
result.is_ok()
}
pub trait TypecheckEnv: PrimitiveEnv + MetadataEnv {}
impl<T> TypecheckEnv for T where T: PrimitiveEnv + MetadataEnv {}
#[cfg(test)]
mod tests {
use super::*;
use std::{cell::RefCell, rc::Rc};
use crate::base::{
kind::{ArcKind, KindEnv},
symbol::{Symbol, SymbolModu... | {
warn!("Check signature error: {}", err);
} | conditional_block |
lib.rs | //! The `check` crate is responsible for ensuring that an AST expression is actually a valid
//! program. This currently consits of three larger parts, typechecking, kindchecking and renaming.
//! If an AST passes the checks in `Typecheck::typecheck_expr` (which runs all of theses checks
//! the expression is expected ... | types::{translate_type, ArcType, PrimitiveEnv, SharedInterner, TypeEnv, TypeExt},
};
use crate::{substitution::Substitution, typ::RcType};
/// Checks if `actual` can be assigned to a binding with the type signature `signature`
pub fn check_signature(
env: &dyn TypecheckEnv<Type = ArcType>,
signature: &Arc... | random_line_split | |
window.rs | use ::game::*;
use ::ncurses::*;
use std::ascii::AsciiExt;
use std::char;
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::mem;
use std::iter::repeat;
use ::itertools::Itertools;
use ::consts::*;
pub struct NCursesWindow;
pub fn create() -> Box<Window> {
Box::new(NCurs... | Entry::Correct { ref word } => {
mvprintw_checked(entries_row,
col,
&[&format!(">{}", word.to_ascii_uppercase()),
">Exact match!",
">... | mvprintw_checked(entries_row,
col,
&[&format!(">{}", word.to_ascii_uppercase()),
">Entry denied",
&format!(">{}/{} correct.", num_correct, 7)]);
... | conditional_block |
window.rs | use ::game::*;
use ::ncurses::*;
use std::ascii::AsciiExt;
use std::char;
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::mem;
use std::iter::repeat;
use ::itertools::Itertools;
use ::consts::*;
pub struct | ;
pub fn create() -> Box<Window> {
Box::new(NCursesWindow::new())
}
pub trait Window {
fn render(&self, &GameState);
fn handle_input(&self, &mut GameState) -> Option<InputEvent>;
}
impl NCursesWindow {
fn new() -> NCursesWindow {
// Enable all mouse events for the current terminal.
en... | NCursesWindow | identifier_name |
window.rs | use ::game::*;
use ::ncurses::*;
use std::ascii::AsciiExt;
use std::char;
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::mem;
use std::iter::repeat;
use ::itertools::Itertools;
use ::consts::*;
pub struct NCursesWindow;
pub fn create() -> Box<Window> {
Box::new(NCurs... | KEY_DOWN | KEY_S | KEY_J => Some(InputEvent::Down),
KEY_MOUSE => {
let mut event: MEVENT = unsafe { mem::uninitialized() };
assert!(getmouse(&mut event) == OK);
game_state.cursor_position = (event.x, event.y);
if event.bstate & (BU... | {
let ch: i32 = getch();
// Allow WASD and HJKL controls
const KEY_W: i32 = 'w' as i32;
const KEY_A: i32 = 'a' as i32;
const KEY_S: i32 = 's' as i32;
const KEY_D: i32 = 'd' as i32;
const KEY_H: i32 = 'h' as i32;
const KEY_J: i32 = 'j' as i32;
con... | identifier_body |
window.rs | use ::game::*;
use ::ncurses::*;
use std::ascii::AsciiExt;
use std::char;
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::mem;
use std::iter::repeat;
use ::itertools::Itertools;
use ::consts::*;
pub struct NCursesWindow;
pub fn create() -> Box<Window> {
Box::new(NCurs... | mvprintw((starting_line + ROWS) / 2,
0,
&format!("{:^1$}", "TERMINAL LOCKED", WINDOW_WIDTH as usize));
mvprintw((starting_line + ROWS + 1) / 2,
0,
&format!("{:^1$}"... | }
GameEnding::Lost => {
curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE); | random_line_split |
u32x4.rs | // Copyright 2015 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according... | (vec: u32x4, n: u32) -> u32x4 {
match n {
16 => rotate_right_16(vec),
8 => rotate_right_8(vec),
_ => rotate_right_any(vec, n),
}
}
#[cfg(not(feature = "simd_opt"))]
#[inline(always)]
pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
rotate_right_any(vec, n)
}
#[inline(alwa... | rotate_right_const | identifier_name |
u32x4.rs | // Copyright 2015 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according... |
#[inline(always)]
fn rotate_right_any(vec: u32x4, n: u32) -> u32x4 {
let r = n as u32;
let l = 32 - r;
(vec >> u32x4::new(r, r, r, r)) ^ (vec << u32x4::new(l, l, l, l))
}
#[cfg(feature = "simd_opt")]
#[inline(always)]
fn rotate_right_16(vec: u32x4) -> u32x4 {
if cfg!(target_feature = "ssse3") {
... | {
rotate_right_any(vec, n)
} | identifier_body |
u32x4.rs | // Copyright 2015 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according... | pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
match n {
16 => rotate_right_16(vec),
8 => rotate_right_8(vec),
_ => rotate_right_any(vec, n),
}
}
#[cfg(not(feature = "simd_opt"))]
#[inline(always)]
pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
rotate_right_any... | #[cfg(feature = "simd_opt")]
#[inline(always)] | random_line_split |
u32x4.rs | // Copyright 2015 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according... | else {
rotate_right_any(vec, 16)
}
}
#[cfg(feature = "simd_opt")]
#[inline(always)]
fn rotate_right_8(vec: u32x4) -> u32x4 {
if cfg!(target_feature = "ssse3") {
// pshufb (SSSE3) / vpshufb (AVX2)
transmute_shuffle!(u8x16, simd_shuffle16, vec,
[ 1, 2, 3, 0,... | {
// pshuflw+pshufhw (SSE2) / vrev (NEON)
transmute_shuffle!(u16x8, simd_shuffle8, vec,
[1, 0,
3, 2,
5, 4,
7, 6])
} | conditional_block |
source_util.rs | // Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
let s = pprust::tts_to_str(tts, cx.parse_sess().interner);
base::MRExpr(mk_base_str(cx, sp, s))
}
pub fn expand_mod(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
base::check_zero_tts(cx, sp, tts, "modul... | expand_stringify | identifier_name |
source_util.rs | // Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | if *name == ~"include" {
expn_info
} else {
topmost_expn_info(next_expn_info)
}
}
}
},
None => e... | // Don't recurse into file using "include!" | random_line_split |
source_util.rs | // Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
// NB: relative paths are resolved relative to the compilation unit
if !arg.is_absolute {
let cu = Path(cx.codemap().span_to_filename(sp));
cu.dir_path().push_many(arg.components)
} else {
copy *arg
}
} | identifier_body | |
source_util.rs | // Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
result::Err(ref e) => {
cx.parse_sess().span_diagnostic.handler().fatal((*e))
}
}
}
// recur along an ExpnInfo chain to find the original expression
fn topmost_expn_info(expn_info: @codemap::ExpnInfo) -> @codemap::ExpnInfo {
match *expn_info {
ExpandedFrom(CallInfo { call_site: ref... | {
let u8_exprs = vec::map(src, |char| {
mk_u8(cx, sp, *char)
});
base::MRExpr(mk_base_vec_e(cx, sp, u8_exprs))
} | conditional_block |
either.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 f_right(_x: &uint) -> bool { false }
assert!((either(f_left, f_right, &val)));
}
#[test]
fn test_either_right() {
let val = Right(10u);
fn f_left(_x: &int) -> bool { false }
fn f_right(x: &uint) -> bool { *x == 10u }
assert!((either(f_left, f_right, &val)));
}
#[test]
fn test_lefts() {
... | { *x == 10 } | identifier_body |
either.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 ... | <T:Copy,U>(eithers: &[Either<T, U>]) -> ~[T] {
//! Extracts from a vector of either all the left values
do vec::build_sized(eithers.len()) |push| {
for vec::each(eithers) |elt| {
match *elt {
Left(ref l) => { push(*l); }
_ => { /* fallthrough */ }
... | lefts | identifier_name |
either.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 f_left(_x: &int) -> bool { false }
fn f_right(x: &uint) -> bool { *x == 10u }
assert!((either(f_left, f_right, &val)));
}
#[test]
fn test_lefts() {
let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
let result = lefts(input);
assert_eq!(result, ~[10, 12, 14]);
}
#[test]
fn t... |
#[test]
fn test_either_right() {
let val = Right(10u); | random_line_split |
dns_2.rs | extern crate martin;
use martin::*;
#[test]
fn parse_query() {
let data = include_bytes!("../assets/captures/dns_2_query.bin");
let question = Question::new("google.com.", QType::ByType(Type::AAAA), Class::Internet) | let msg = Message::parse(&data[..]).unwrap();
assert!(msg.is_query());
assert_eq!(msg.id(), 3);
assert_eq!(msg.opcode(), Opcode::Query);
assert_eq!(msg.questions, vec![question]);
}
#[test]
fn parse_response() {
let data = include_bytes!("../assets/captures/dns_2_response.bin");
let questio... | .unwrap(); | random_line_split |
dns_2.rs | extern crate martin;
use martin::*;
#[test]
fn parse_query() |
#[test]
fn parse_response() {
let data = include_bytes!("../assets/captures/dns_2_response.bin");
let question = Question::new("google.com.", QType::ByType(Type::AAAA), Class::Internet)
.unwrap();
let rr = ResourceRecord::AAAA {
name: "google.com.".parse().unwrap(),
class: Class::In... | {
let data = include_bytes!("../assets/captures/dns_2_query.bin");
let question = Question::new("google.com.", QType::ByType(Type::AAAA), Class::Internet)
.unwrap();
let msg = Message::parse(&data[..]).unwrap();
assert!(msg.is_query());
assert_eq!(msg.id(), 3);
assert_eq!(msg.opcode(), O... | identifier_body |
dns_2.rs | extern crate martin;
use martin::*;
#[test]
fn | () {
let data = include_bytes!("../assets/captures/dns_2_query.bin");
let question = Question::new("google.com.", QType::ByType(Type::AAAA), Class::Internet)
.unwrap();
let msg = Message::parse(&data[..]).unwrap();
assert!(msg.is_query());
assert_eq!(msg.id(), 3);
assert_eq!(msg.opcode(),... | parse_query | identifier_name |
day02.rs | use std::io::Read;
use crate::common::LineIter;
enum Dir {
Up,
Down,
Forward,
}
fn parse_input(input: &mut dyn Read) -> Vec<(Dir, i32)> {
let mut reader = LineIter::new(input);
let mut moves = Vec::new();
while let Some(line) = reader.next() {
let (dir, amount) = line.split_once(' ')... | () {
test_implementation(part1, SAMPLE, 150);
}
#[test]
fn sample_part2() {
test_implementation(part1, SAMPLE, 150);
}
}
| sample_part1 | identifier_name |
day02.rs | use std::io::Read;
use crate::common::LineIter;
enum Dir {
Up,
Down,
Forward,
}
fn parse_input(input: &mut dyn Read) -> Vec<(Dir, i32)> {
let mut reader = LineIter::new(input);
let mut moves = Vec::new();
while let Some(line) = reader.next() {
let (dir, amount) = line.split_once(' ')... |
pub fn part2(input: &mut dyn Read) -> String {
let moves = parse_input(input);
let mut x = 0;
let mut depth = 0;
let mut aim = 0;
for (dir, amount) in moves {
match dir {
Dir::Up => aim -= amount,
Dir::Down => aim += amount,
Dir::Forward => {
... | {
let moves = parse_input(input);
let mut x = 0;
let mut depth = 0;
for (dir, amount) in moves {
match dir {
Dir::Up => depth -= amount,
Dir::Down => depth += amount,
Dir::Forward => x += amount,
}
}
(x * depth).to_string()
} | identifier_body |
day02.rs | use std::io::Read;
use crate::common::LineIter;
enum Dir {
Up,
Down,
Forward,
}
fn parse_input(input: &mut dyn Read) -> Vec<(Dir, i32)> {
let mut reader = LineIter::new(input);
let mut moves = Vec::new();
while let Some(line) = reader.next() {
let (dir, amount) = line.split_once(' ')... |
pub fn part1(input: &mut dyn Read) -> String {
let moves = parse_input(input);
let mut x = 0;
let mut depth = 0;
for (dir, amount) in moves {
match dir {
Dir::Up => depth -= amount,
Dir::Down => depth += amount,
Dir::Forward => x += amount,
}
}
... |
moves
} | random_line_split |
htmltitleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
fn bind_to_tree(&self, is_in_doc: bool) {
let node = self.upcast::<Node>();
if is_in_doc {
node.owner_doc().title_changed();
}
}
}
| {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
let node = self.upcast::<Node>();
if node.is_in_doc() {
node.owner_doc().title_changed();
}
} | identifier_body |
htmltitleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
}
DOMString::from(content)
}
// https://html.spec.whatwg.org/multipage/#dom-title-text
fn SetText(&self, value: DOMString) {
self.upcast::<Node>().SetTextContent(Some(value))
}
}
impl VirtualMethods for HTMLTitleElement {
fn super_type(&self) -> Option<&VirtualMethods> {
... | {
content.push_str(&text.upcast::<CharacterData>().data());
} | conditional_block |
htmltitleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | {
htmlelement: HTMLElement,
}
impl HTMLTitleElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTitleElement {
HTMLTitleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted... | HTMLTitleElement | identifier_name |
htmltitleelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | use dom::text::Text;
use dom::virtualmethods::VirtualMethods;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLTitleElement {
htmlelement: HTMLElement,
}
impl HTMLTitleElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTitleElement {
HT... | use dom::bindings::str::DOMString;
use dom::characterdata::CharacterData;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::{ChildrenMutation, Node}; | random_line_split |
sync.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 ... | // only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.f... | {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 && !w... | identifier_body |
sync.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 ... | <T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T: Send> Send for Packet<T> { }
unsafe impl<T: Send> Sync for Packet<T> { }
struct State<T> {
... | Packet | identifier_name |
sync.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 ... | pub fn new(cap: usize) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
... | drop(guard);
token.signal();
}
impl<T> Packet<T> { | random_line_split |
sync.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 ... |
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting ... | {} | conditional_block |
crt-static.rs | // Test proc-macro crate can be built without additional RUSTFLAGS
// on musl target
// override -Ctarget-feature=-crt-static from compiletest
// compile-flags: --crate-type proc-macro -Ctarget-feature=
// ignore-wasm32
// ignore-sgx no support for proc-macro crate type
// build-pass
#![crate_type = "proc-macro"]
// F... | (input: TokenStream) -> TokenStream {
input
}
| derive_foo | identifier_name |
crt-static.rs | // Test proc-macro crate can be built without additional RUSTFLAGS
// on musl target
// override -Ctarget-feature=-crt-static from compiletest
// compile-flags: --crate-type proc-macro -Ctarget-feature=
// ignore-wasm32
// ignore-sgx no support for proc-macro crate type
// build-pass
#![crate_type = "proc-macro"]
// F... | {
input
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.