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 |
|---|---|---|---|---|
compare.rs | #![crate_id="compare#0.1"]
#![crate_type="bin"]
extern crate bancnova;
use std::os;
use bancnova::syntax::bscode;
use bancnova::syntax::tokenize;
use bancnova::syntax::tokenize::Tokenizer;
use bancnova::syntax::tree::Tree;
use std::io::IoResult;
use std::cmp::min;
mod util;
fn main() |
fn read_tree<R: Reader>(tokenizer: &mut Tokenizer<R>) -> IoResult<Tree<bscode::Instruction>> {
match Tree::parse(tokenizer) {
Ok(tree) => Ok(tree),
Err(s) => util::make_ioerr(s, tokenizer),
}
}
struct ComparisonReporter<'a> {
filename1: &'a str,
filename2: &'a str,
count: uint,
}
... | {
let args = os::args();
match compare_files(args.get(1).as_slice(), args.get(2).as_slice()) {
Err(err) => {
println!("error: [{}] {}", err.kind, err.desc);
if err.detail.is_some() {
println!("\t{}", err.detail.unwrap());
}
os::set_exit_sta... | identifier_body |
lib.rs | #![cfg_attr(test, deny(warnings))]
#![warn(trivial_casts)]
#![forbid(unused, unused_extern_crates, unused_import_braces, unused_qualifications)]
pub fn nav(subdomain: &str, page: &str, is_admin: bool) -> String | <li{active_kontakt}><a href="{wiw}/kontakt"><span class="fa fa-envelope"></span>Kontakt</a></li>
<li{active_boerse}><a href="{boerse}/"><span class="fa fa-exchange"></span>Börse</a></li>
</ul>
{right}
</div>
</nav>
"#,
wiw=if subdomain == "boerse" { "//willkom... | {
format!(
r#"
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span cl... | identifier_body |
lib.rs | #![cfg_attr(test, deny(warnings))]
#![warn(trivial_casts)]
#![forbid(unused, unused_extern_crates, unused_import_braces, unused_qualifications)]
pub fn | (subdomain: &str, page: &str, is_admin: bool) -> String {
format!(
r#"
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class... | nav | identifier_name |
lib.rs | #![cfg_attr(test, deny(warnings))]
#![warn(trivial_casts)]
#![forbid(unused, unused_extern_crates, unused_import_braces, unused_qualifications)]
pub fn nav(subdomain: &str, page: &str, is_admin: bool) -> String {
format!(
r#"
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div c... | <ul id="navbar-list" class="nav navbar-nav">
<li{active_home}><a href="{wiw}/"><span class="fa fa-home"></span>Home</a></li>
<li{active_angebote}><a href="{wiw}/angebote"><span class="fa fa-smile-o"></span>Unsere Angebote</a></li>
<li{active_veranstaltungen}><a href="{wiw}/ve... | <span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{wiw}/">Willkommen in Wöllstein</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse"> | random_line_split |
list.rs | // Copyright 2016 Jeremy Letang.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to ... | Ok(l) => responses::ok(serde_json::to_string(&l).unwrap()),
Err(e) => responses::internal_error(e.description()),
}
} | // get /api/v1/tags
pub fn list(ctx: Context, _: &mut Request) -> IronResult<Response> {
let db = &mut *ctx.db.get().expect("cannot get sqlite connection from the context");
match repo_repo::list_for_user_id(db, &*ctx.user.id) { | random_line_split |
list.rs | // Copyright 2016 Jeremy Letang.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to ... | {
let db = &mut *ctx.db.get().expect("cannot get sqlite connection from the context");
match repo_repo::list_for_user_id(db, &*ctx.user.id) {
Ok(l) => responses::ok(serde_json::to_string(&l).unwrap()),
Err(e) => responses::internal_error(e.description()),
}
} | identifier_body | |
list.rs | // Copyright 2016 Jeremy Letang.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to ... | (ctx: Context, _: &mut Request) -> IronResult<Response> {
let db = &mut *ctx.db.get().expect("cannot get sqlite connection from the context");
match repo_repo::list_for_user_id(db, &*ctx.user.id) {
Ok(l) => responses::ok(serde_json::to_string(&l).unwrap()),
Err(e) => responses::internal_error(e.... | list | identifier_name |
network.rs | use std::ptr::{null, copy};
use std::ffi::{CString};
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::net::Ipv4Addr;
use libc::{c_int, size_t, c_char, EINVAL};
#[repr(C)]
struct hostent {
h_name: *const c_char, /* official name of host */
h_aliases: *const *const c_char, ... |
if (*hostent).h_length == 0 {
return Err(IoError::from_raw_os_error(EINVAL));
}
let mut addr = [0u8; 4];
copy(*(*hostent).h_addr_list, addr.as_mut_ptr() as *mut i8, 4);
return Ok(format!("{}",
Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3])));
... | {
return Err(IoError::last_os_error());
} | conditional_block |
network.rs | use std::ptr::{null, copy};
use std::ffi::{CString};
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::net::Ipv4Addr;
use libc::{c_int, size_t, c_char, EINVAL};
#[repr(C)]
struct hostent {
h_name: *const c_char, /* official name of host */
h_aliases: *const *const c_char, ... | () -> IoResult<String> {
let host = try!(get_host_name());
let addr = try!(get_host_address(&host[..]));
return Ok(addr);
}
pub fn get_host_name() -> IoResult<String> {
let mut buf: Vec<u8> = Vec::with_capacity(256);
let nbytes = unsafe {
buf.set_len(256);
gethostname(
(... | get_host_ip | identifier_name |
network.rs | use std::ptr::{null, copy};
use std::ffi::{CString};
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::net::Ipv4Addr;
use libc::{c_int, size_t, c_char, EINVAL};
#[repr(C)]
struct hostent {
h_name: *const c_char, /* official name of host */
h_aliases: *const *const c_char, ... | }
let mut addr = [0u8; 4];
copy(*(*hostent).h_addr_list, addr.as_mut_ptr() as *mut i8, 4);
return Ok(format!("{}",
Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3])));
}
} | if hostent == null() {
return Err(IoError::last_os_error());
}
if (*hostent).h_length == 0 {
return Err(IoError::from_raw_os_error(EINVAL)); | random_line_split |
htmltablesectionelement.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::HTMLTableSectionElementBinding::{
self, HTMLTableSectionElementM... | (
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLTableSectionElement> {
Node::reflect_node(
Box::new(HTMLTableSectionElement::new_inherited(
local_name, prefix, document,
)),
document,
... | new | identifier_name |
htmltablesectionelement.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 | use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{
self, HTMLTableSectionElementMethods,
};
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::error::{ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bi... | * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
| random_line_split |
htmltablesectionelement.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::HTMLTableSectionElementBinding::{
self, HTMLTableSectionElementM... |
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLTableSectionElement> {
Node::reflect_node(
Box::new(HTMLTableSectionElement::new_inherited(
local_name, prefix, document... | {
HTMLTableSectionElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
} | identifier_body |
mod.rs | #![allow(dead_code)]
use std::rc::Rc;
use std::ops::{
Add,
Sub,
};
use chunk::{ChunkOption};
pub struct | {
x: f64,
y: f64,
z: f64,
}
pub struct Entity {
mass: Rc<ChunkOption>,
velocity: Vec3f64,
location: Vec3f64,
rotation: Vec3f64,
}
impl Add<Vec3f64> for Vec3f64 {
type Output = Vec3f64;
fn add(self, _rhs: Vec3f64) -> Vec3f64 {
Vec3f64 {
x: self.x + _rhs.x,
... | Vec3f64 | identifier_name |
mod.rs | #![allow(dead_code)]
use std::rc::Rc;
use std::ops::{
Add,
Sub,
};
use chunk::{ChunkOption};
pub struct Vec3f64 {
x: f64,
y: f64,
z: f64,
}
pub struct Entity {
mass: Rc<ChunkOption>,
velocity: Vec3f64, | location: Vec3f64,
rotation: Vec3f64,
}
impl Add<Vec3f64> for Vec3f64 {
type Output = Vec3f64;
fn add(self, _rhs: Vec3f64) -> Vec3f64 {
Vec3f64 {
x: self.x + _rhs.x,
y: self.y + _rhs.y,
z: self.z + _rhs.z
}
}
}
impl Sub<Vec3f64> for Vec3f64 {
... | random_line_split | |
mod.rs | #![allow(dead_code)]
use std::rc::Rc;
use std::ops::{
Add,
Sub,
};
use chunk::{ChunkOption};
pub struct Vec3f64 {
x: f64,
y: f64,
z: f64,
}
pub struct Entity {
mass: Rc<ChunkOption>,
velocity: Vec3f64,
location: Vec3f64,
rotation: Vec3f64,
}
impl Add<Vec3f64> for Vec3f64 {
typ... |
}
impl Sub<Vec3f64> for Vec3f64 {
type Output = Vec3f64;
fn sub(self, _rhs: Vec3f64) -> Vec3f64 {
Vec3f64 {
x: self.x + _rhs.x,
y: self.y + _rhs.y,
z: self.z + _rhs.z
}
}
}
| {
Vec3f64 {
x: self.x + _rhs.x,
y: self.y + _rhs.y,
z: self.z + _rhs.z
}
} | identifier_body |
case.rs | use super::super::ArgumentSplitter;
use std::fmt::{self, Display, Formatter};
#[derive(Debug, PartialEq)] | }
impl<'a> Display for CaseError<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
CaseError::NoBindVariable => write!(f, "no bind variable was supplied"),
CaseError::NoConditional => write!(f, "no conditional statement was given"),
CaseError::ExtraBi... | pub(crate) enum CaseError<'a> {
NoBindVariable,
NoConditional,
ExtraBind(&'a str),
ExtraVar(&'a str), | random_line_split |
case.rs | use super::super::ArgumentSplitter;
use std::fmt::{self, Display, Formatter};
#[derive(Debug, PartialEq)]
pub(crate) enum CaseError<'a> {
NoBindVariable,
NoConditional,
ExtraBind(&'a str),
ExtraVar(&'a str),
}
impl<'a> Display for CaseError<'a> {
fn | (&self, f: &mut Formatter) -> fmt::Result {
match *self {
CaseError::NoBindVariable => write!(f, "no bind variable was supplied"),
CaseError::NoConditional => write!(f, "no conditional statement was given"),
CaseError::ExtraBind(value) => write!(f, "extra value, '{}', was giv... | fmt | identifier_name |
case.rs | use super::super::ArgumentSplitter;
use std::fmt::{self, Display, Formatter};
#[derive(Debug, PartialEq)]
pub(crate) enum CaseError<'a> {
NoBindVariable,
NoConditional,
ExtraBind(&'a str),
ExtraVar(&'a str),
}
impl<'a> Display for CaseError<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
... |
}
| {
assert_eq!(
Ok((Some("test"), Some("test"), Some("exists".into()))),
parse_case("test @ test if exists")
);
assert_eq!(
Ok((Some("test"), Some("test"), None)),
parse_case("test @ test")
);
assert_eq!(Ok((Some("test"), None, None))... | identifier_body |
errors.rs | use actix_web::{error, http, HttpResponse};
use diesel;
use failure::Fail;
use r2d2;
use std::convert::From;
#[derive(Fail, Debug)]
pub enum MailboxerError {
#[fail(display = "Mailbox already exists")]
MailboxAlreadyExists,
#[fail(display = "Mailbox not found")]
MailboxNotFound,
#[fail(display = "I... |
}
| {
match *self {
MailboxerError::MailboxAlreadyExists => HttpResponse::new(http::StatusCode::CONFLICT),
MailboxerError::InternalServerError => {
HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR)
}
ref e @ MailboxerError::MailboxNotFound => ... | identifier_body |
errors.rs | use actix_web::{error, http, HttpResponse};
use diesel; | pub enum MailboxerError {
#[fail(display = "Mailbox already exists")]
MailboxAlreadyExists,
#[fail(display = "Mailbox not found")]
MailboxNotFound,
#[fail(display = "Internal error")]
InternalServerError,
}
impl From<diesel::result::Error> for MailboxerError {
fn from(_err: diesel::result::... | use failure::Fail;
use r2d2;
use std::convert::From;
#[derive(Fail, Debug)] | random_line_split |
errors.rs | use actix_web::{error, http, HttpResponse};
use diesel;
use failure::Fail;
use r2d2;
use std::convert::From;
#[derive(Fail, Debug)]
pub enum MailboxerError {
#[fail(display = "Mailbox already exists")]
MailboxAlreadyExists,
#[fail(display = "Mailbox not found")]
MailboxNotFound,
#[fail(display = "I... |
}
}
}
| {
HttpResponse::with_body(http::StatusCode::NOT_FOUND, e.to_string())
} | conditional_block |
errors.rs | use actix_web::{error, http, HttpResponse};
use diesel;
use failure::Fail;
use r2d2;
use std::convert::From;
#[derive(Fail, Debug)]
pub enum MailboxerError {
#[fail(display = "Mailbox already exists")]
MailboxAlreadyExists,
#[fail(display = "Mailbox not found")]
MailboxNotFound,
#[fail(display = "I... | (_err: diesel::result::Error) -> Self {
MailboxerError::InternalServerError
}
}
impl From<r2d2::Error> for MailboxerError {
fn from(_err: r2d2::Error) -> Self {
MailboxerError::InternalServerError
}
}
impl error::ResponseError for MailboxerError {
fn error_response(&self) -> HttpRespon... | from | identifier_name |
util.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
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, di... |
/**
Evaluates a polynomial using Horner's algorithm
# Arguments
* `$x` : The value of the independent variable `f32 or f64`
* `$c` : The constant term `f32 or f64`
* `$($a),*`: Sequence of coefficient terms for `$x`, in ascending
powers of `$x`
**/
#[macro_export]
macro_rules! Horner_eval
{
... | {
let mut d = 1.0;
for _ in 1..(decimal_digits + 1) {
d *= 10.0;
}
(float * d).round() / d
} | identifier_body |
util.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
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, di... | */
//! Some programming utilities
/// Returns a float rounded upto a certain number of decimal digits
#[inline]
pub fn round_upto_digits(float: f64, decimal_digits: u32) -> f64
{
let mut d = 1.0;
for _ in 1..(decimal_digits + 1) {
d *= 10.0;
}
(float * d).round() / d
}
/**
Evaluates a polyn... | random_line_split | |
util.rs | /*
Copyright (c) 2015, 2016 Saurav Sachidanand
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, di... | (float: f64, decimal_digits: u32) -> f64
{
let mut d = 1.0;
for _ in 1..(decimal_digits + 1) {
d *= 10.0;
}
(float * d).round() / d
}
/**
Evaluates a polynomial using Horner's algorithm
# Arguments
* `$x` : The value of the independent variable `f32 or f64`
* `$c` : The constant ter... | round_upto_digits | identifier_name |
build.rs | // Copyright (C) 2017-2022 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// 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... |
previous = s;
}
}
attack
}
fn sliding_bishop_attacks(sq: Square, occupied: Bitboard) -> Bitboard {
sliding_attacks(sq, occupied, &BISHOP_DELTAS)
}
fn sliding_rook_attacks(sq: Square, occupied: Bitboard) -> Bitboard {
sliding_attacks(sq, occupied, &ROOK_DELTAS)
}
fn step_attacks... | {
break;
} | conditional_block |
build.rs | // Copyright (C) 2017-2022 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// 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... | .with(a)
.with(b);
}
for b in sliding_rook_attacks(a, Bitboard(0)) {
bb_rays[usize::from(a)][usize::from(b)] = (sliding_rook_attacks(a, Bitboard(0))
& sliding_rook_attacks(b, Bitboard(0)))
.with(a)
.with(b);
}
}
dum... |
for a in Square::ALL {
for b in sliding_bishop_attacks(a, Bitboard(0)) {
bb_rays[usize::from(a)][usize::from(b)] = (sliding_bishop_attacks(a, Bitboard(0))
& sliding_bishop_attacks(b, Bitboard(0))) | random_line_split |
build.rs | // Copyright (C) 2017-2022 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// 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... | <W: Write>(f: &mut W) -> io::Result<()> {
let mut knight_attacks = [Bitboard(0); 64];
let mut king_attacks = [Bitboard(0); 64];
let mut white_pawn_attacks = [Bitboard(0); 64];
let mut black_pawn_attacks = [Bitboard(0); 64];
let mut bb_rays = [[Bitboard(0); 64]; 64];
for sq in Square::ALL {
... | generate_basics | identifier_name |
build.rs | // Copyright (C) 2017-2022 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// 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... |
fn step_attacks(sq: Square, deltas: &[i32]) -> Bitboard {
sliding_attacks(sq, Bitboard::FULL, deltas)
}
fn init_magics(sq: Square, magic: &Magic, shift: u32, attacks: &mut [Bitboard], deltas: &[i32]) {
for subset in Bitboard(magic.mask).carry_rippler() {
let attack = sliding_attacks(sq, subset, delta... | {
sliding_attacks(sq, occupied, &ROOK_DELTAS)
} | identifier_body |
menu.rs | // Copyright 2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::object::Cast;
use glib::translate::*;
use Menu;
use IsA;
use Widg... | button, activate_time)
}
}
}
unsafe extern "C" fn position_callback<T, F: FnOnce(&T, &mut i32, &mut i32) -> bool +'static>(this: *mut ffi::GtkMenu,
x: *mut c_int,
... |
fn popup_easy(&self, button: u32, activate_time: u32) {
unsafe {
ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, ptr::null_mut(),
ptr::null_mut(), None, ptr::null_mut(), | random_line_split |
menu.rs | // Copyright 2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::object::Cast;
use glib::translate::*;
use Menu;
use IsA;
use Widg... | (&self, button: u32, activate_time: u32) {
unsafe {
ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, ptr::null_mut(),
ptr::null_mut(), None, ptr::null_mut(),
button, activate_time)
}
}
}
unsafe extern "C" fn position_cal... | popup_easy | identifier_name |
menu.rs | // Copyright 2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::object::Cast;
use glib::translate::*;
use Menu;
use IsA;
use Widg... |
fn popup_easy(&self, button: u32, activate_time: u32) {
unsafe {
ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, ptr::null_mut(),
ptr::null_mut(), None, ptr::null_mut(),
button, activate_time)
}
}
}
unsafe extern ... | {
unsafe {
let f: Box_<Option<F>> = Box_::new(Some(f));
ffi::gtk_menu_popup(self.as_ref().to_glib_none().0, parent_menu_shell.map(|p| p.as_ref()).to_glib_none().0,
parent_menu_item.map(|p| p.as_ref()).to_glib_none().0,
Some(... | identifier_body |
all.rs | use crate::rutil::fix_new_line::fix_new_line;
use crate::rutil::print_tty::{print_tty, print_writer};
use crate::rutil::safe_string::SafeString;
use std::io::{BufRead, Write};
#[cfg(target_family = "wasm")]
mod wasm {
use std::io::{self, BufRead};
/// Reads a password from the TTY
pub fn read_password() -... |
fn safe_tcgetattr(fd: c_int) -> std::io::Result<termios> {
let mut term = mem::MaybeUninit::<termios>::uninit();
io_result(unsafe { ::libc::tcgetattr(fd, term.as_mut_ptr()) })?;
Ok(unsafe { term.assume_init() })
}
/// Reads a password from the TTY
pub fn read_password() -> std... | {
match ret {
0 => Ok(()),
_ => Err(std::io::Error::last_os_error()),
}
} | identifier_body |
all.rs | use crate::rutil::fix_new_line::fix_new_line;
use crate::rutil::print_tty::{print_tty, print_writer};
use crate::rutil::safe_string::SafeString;
use std::io::{BufRead, Write};
#[cfg(target_family = "wasm")]
mod wasm {
use std::io::{self, BufRead};
/// Reads a password from the TTY
pub fn read_password() -... | (
reader: &mut impl BufRead,
writer: &mut impl Write,
prompt: impl ToString,
) -> std::io::Result<String> {
print_writer(writer, prompt.to_string().as_str())
.and_then(|_| read_password_from_bufread(reader))
}
/// Prompts on the TTY and then reads a password from stdin
pub fn prompt_password(pro... | prompt_password_from_bufread | identifier_name |
all.rs | use crate::rutil::fix_new_line::fix_new_line;
use crate::rutil::print_tty::{print_tty, print_writer};
use crate::rutil::safe_string::SafeString;
use std::io::{BufRead, Write};
#[cfg(target_family = "wasm")]
mod wasm {
use std::io::{self, BufRead};
/// Reads a password from the TTY
pub fn read_password() -... |
reader.read_line(&mut password)?;
std::mem::drop(hidden_input);
super::fix_new_line(password.into_inner())
}
}
#[cfg(target_family = "windows")]
mod windows {
use std::io::{self, BufReader};
use std::io::{BufRead, StdinLock};
use std::os::windows::io::FromRawHandle;
use w... | random_line_split | |
htmlareaelement.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::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen... | use dom::virtualmethods::VirtualMethods;
use std::default::Default;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLAreaElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
}
impl HTMLAreaElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Doc... | random_line_split | |
htmlareaelement.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::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen... |
}
impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast(), &atom!("rel"))
})
}
}
| {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
} | identifier_body |
htmlareaelement.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::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen... | (localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
rel_list: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
... | new_inherited | identifier_name |
mod.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | pub mod tests;
pub mod types;
pub use self::traits::{Web3, Eth, EthFilter, EthSigning, Net, Parity, ParityAccounts, ParitySet, ParitySigning, Signer, Personal, Traces, Rpc};
pub use self::impls::*;
pub use self::helpers::{SigningQueue, SignerService, ConfirmationsQueue, NetworkSettings, block_import}; |
pub mod traits; | random_line_split |
range.rs | // Copyright 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-MIT or ... | () {
Range::new(10i, 10i);
}
#[should_fail]
#[test]
fn test_range_bad_limits_flipped() {
Range::new(10i, 5i);
}
#[test]
fn test_integers() {
let mut rng = ::test::rng();
macro_rules! t (
($($ty:ty),*) => {{
$(
le... | test_range_bad_limits_equal | identifier_name |
range.rs | // Copyright 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-MIT or ... | /// `high = 170u8`, for which a naive modulo operation would return
/// numbers less than 85 with double the probability to those greater
/// than 85.
///
/// Types should attempt to sample in `[low, high)`, i.e., not
/// including `high`, but this may be very difficult. All the
/// primitive integer types satisfy this... | ///
/// This gives a uniform distribution (assuming the RNG used to sample
/// it is itself uniform & the `SampleRange` implementation for the
/// given type is correct), even for edge cases like `low = 0u8`, | random_line_split |
hyper_server.rs | use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use futures::prelude::*;
use futures::StreamExt;
use futures::task::{Context, Poll};
use hyper::{Body, Error, Response, Server};
use hyper::http::header::{HeaderName, HeaderValue};
use hyper::http::res... | let ms = mock_server.lock().unwrap();
let context = hashmap!{
"mockServer" => json!({
"href": ms.url(),
"port": ms.port
})
};
debug!("Test context = {:?}", context);
let response = pact_matching::generate_response(&interaction.response, &GeneratorTestMod... | random_line_split | |
hyper_server.rs | use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use futures::prelude::*;
use futures::StreamExt;
use futures::task::{Context, Poll};
use hyper::{Body, Error, Response, Server};
use hyper::http::header::{HeaderName, HeaderValue};
use hyper::http::res... | (
request: &Request,
match_result: MatchResult,
mock_server: Arc<Mutex<MockServer>>
) -> Result<Response<Body>, InteractionError> {
let cors_preflight = {
let ms = mock_server.lock().unwrap();
ms.config.cors_preflight
};
match match_result {
MatchResult::RequestMatch(ref interaction) => {
... | match_result_to_hyper_response | identifier_name |
hyper_server.rs | use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use futures::prelude::*;
use futures::StreamExt;
use futures::task::{Context, Poll};
use hyper::{Body, Error, Response, Server};
use hyper::http::header::{HeaderName, HeaderValue};
use hyper::http::res... | .collect()))
}
})
.collect();
result.map(|map| Some(map))
} else {
Ok(None)
}
}
fn extract_body(bytes: bytes::Bytes, request: &Request) -> OptionalBody {
if bytes.len() > 0 {
OptionalBody::Present(bytes, request.content_type())
} else {
OptionalBody::Empt... | {
if !headers.is_empty() {
let result: Result<HashMap<String, Vec<String>>, InteractionError> = headers.keys()
.map(|name| -> Result<(String, Vec<String>), InteractionError> {
let values = headers.get_all(name);
let parsed_vals: Vec<Result<String, InteractionError>> = values.iter()
... | identifier_body |
f64.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... |
/// Rounds towards plus infinity.
#[inline]
fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Rounds to nearest integer. Rounds half-way cases away from zero.
#[inline]
fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the ... | #[inline]
fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
} | random_line_split |
f64.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... |
#[inline]
fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP }
#[inline]
fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE }
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
... | { MIN_10_EXP } | identifier_body |
f64.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 mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
(manti... | { -1 } | conditional_block |
f64.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... | () -> f64 { consts::LOG10_E }
/// ln(2.0)
#[inline]
fn ln_2() -> f64 { consts::LN_2 }
/// ln(10.0)
#[inline]
fn ln_10() -> f64 { consts::LN_10 }
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Re... | log10_e | identifier_name |
mod.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
//#[cfg(feature = "lua")]
//pub mod lua; | random_line_split | |
mod.rs | //! The SpaceAPI server struct.
use std::net::ToSocketAddrs;
use std::sync::Arc;
use std::time::Duration;
use iron::Iron;
use log::debug;
use r2d2;
use r2d2_redis::RedisConnectionManager;
use redis::{ConnectionInfo, IntoConnectionInfo};
use router::Router;
use serde_json::map::Map;
use serde_json::Value;
mod handle... | Ok(redis_pool)
}
};
Ok(SpaceapiServer {
status: self.status,
redis_pool: pool?,
sensor_specs: Arc::new(self.sensor_specs),
status_modifiers: self.status_modifiers,
})
}
}
/// A SpaceAPI server instance.
///
/// You... | // server to work even without a database connection.
.build_unchecked(redis_manager); | random_line_split |
mod.rs | //! The SpaceAPI server struct.
use std::net::ToSocketAddrs;
use std::sync::Arc;
use std::time::Duration;
use iron::Iron;
use log::debug;
use r2d2;
use r2d2_redis::RedisConnectionManager;
use redis::{ConnectionInfo, IntoConnectionInfo};
use router::Router;
use serde_json::map::Map;
use serde_json::Value;
mod handle... | (self) -> Result<SpaceapiServer, SpaceapiServerError> {
let pool = match self.redis_info {
RedisInfo::None => Err("No redis connection defined".into()),
RedisInfo::Err(e) => Err(e),
RedisInfo::Pool(p) => Ok(p),
RedisInfo::ConnectionInfo(ci) => {
//... | build | identifier_name |
mod.rs | //! The SpaceAPI server struct.
use std::net::ToSocketAddrs;
use std::sync::Arc;
use std::time::Duration;
use iron::Iron;
use log::debug;
use r2d2;
use r2d2_redis::RedisConnectionManager;
use redis::{ConnectionInfo, IntoConnectionInfo};
use router::Router;
use serde_json::map::Map;
use serde_json::Value;
mod handle... | router
}
/// Start a HTTP server listening on ``self.host:self.port``.
///
/// The call returns an `HttpResult<Listening>` object, see
/// http://ironframework.io/doc/hyper/server/struct.Listening.html
/// for more information.
pub fn serve<S: ToSocketAddrs>(self, socket_addr: S) -... | {
let mut router = Router::new();
router.get(
"/",
handlers::ReadHandler::new(
self.status.clone(),
self.redis_pool.clone(),
self.sensor_specs.clone(),
self.status_modifiers,
),
"root",
... | identifier_body |
build.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate cc;
extern crate gl_generator;
use gl_generator::{Api, Fallbacks, Profile, Registry};
use std::env;
... |
println!("cargo:rustc-link-lib=static=android_native_app_glue");
println!("cargo:rustc-link-search=native={}", out_dir);
println!("cargo:rustc-link-lib=log");
println!("cargo:rustc-link-lib=android");
}
fn generate_gl_bindings(target: &str) {
// For now, we only support EGL, and only on Windows a... | {
// Get the NDK path from NDK_HOME env.
let ndk_path =
env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable");
let ndk_path = Path::new(&ndk_path);
// compiling android_native_app_glue.c
let c_file = ndk_path
.join("sources")
.join("android")
... | identifier_body |
build.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate cc;
extern crate gl_generator;
use gl_generator::{Api, Fallbacks, Profile, Registry};
use std::env;
... | (target: &str) {
// For now, we only support EGL, and only on Windows and Android.
if target.contains("android") || target.contains("windows") {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("egl_bindings.rs")).unwrap();
if target.contains("a... | generate_gl_bindings | identifier_name |
build.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate cc;
extern crate gl_generator;
use gl_generator::{Api, Fallbacks, Profile, Registry};
use std::env;
... |
// compiling android_native_app_glue.c
let c_file = ndk_path
.join("sources")
.join("android")
.join("native_app_glue")
.join("android_native_app_glue.c");
cc::Build::new()
.file(c_file)
.warnings(false)
.compile("android_native_app_glue");
// Get the o... | env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable");
let ndk_path = Path::new(&ndk_path); | random_line_split |
build.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate cc;
extern crate gl_generator;
use gl_generator::{Api, Fallbacks, Profile, Registry};
use std::env;
... |
generate_gl_bindings(&target);
}
fn android_main() {
// Get the NDK path from NDK_HOME env.
let ndk_path =
env::var_os("ANDROID_NDK").expect("Please set the ANDROID_NDK environment variable");
let ndk_path = Path::new(&ndk_path);
// compiling android_native_app_glue.c
let c_file = ndk... | {
android_main()
} | conditional_block |
unary-minus-suffix-inference.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 ... | println!("{}", a_neg);
let b = 1;
let b_neg: i16 = -b;
println!("{}", b_neg);
let c = 1;
let c_neg: i32 = -c;
println!("{}", c_neg);
let d = 1;
let d_neg: i64 = -d;
println!("{}", d_neg);
let e = 1;
let e_neg: int = -e;
println!("{}", e_neg);
// intentional o... | let a = 1;
let a_neg: i8 = -a; | random_line_split |
unary-minus-suffix-inference.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = 1;
let a_neg: i8 = -a;
println!("{}", a_neg);
let b = 1;
let b_neg: i16 = -b;
println!("{}", b_neg);
let c = 1;
let c_neg: i32 = -c;
println!("{}", c_neg);
let d = 1;
let d_neg: i64 = -d;
println!("{}", d_neg);
let e = 1;
let e_neg: int = -e;
... | main | identifier_name |
unary-minus-suffix-inference.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 ... |
// intentional overflows
let f = 1;
let f_neg: u8 = -f;
println!("{}", f_neg);
let g = 1;
let g_neg: u16 = -g;
println!("{}", g_neg);
let h = 1;
let h_neg: u32 = -h;
println!("{}", h_neg);
let i = 1;
let i_neg: u64 = -i;
println!("{}", i_neg);
let j = 1;
... | {
let a = 1;
let a_neg: i8 = -a;
println!("{}", a_neg);
let b = 1;
let b_neg: i16 = -b;
println!("{}", b_neg);
let c = 1;
let c_neg: i32 = -c;
println!("{}", c_neg);
let d = 1;
let d_neg: i64 = -d;
println!("{}", d_neg);
let e = 1;
let e_neg: int = -e;
pri... | identifier_body |
pipe_windows.rs | atomic::AtomicBool,
}
impl Inner {
fn new(handle: libc::HANDLE) -> Inner {
Inner {
handle: handle,
lock: unsafe { mutex::NativeMutex::new() },
read_closed: atomic::AtomicBool::new(false),
write_closed: atomic::AtomicBool::new(false),
}
}
}
impl ... | read_deadline: u64,
write_deadline: u64,
}
impl UnixStream {
fn try_connect(p: *const u16) -> Option<libc::HANDLE> {
// Note that most of this is lifted from the libuv implementation.
// The idea is that if we fail to open a pipe in read/write mode
// that we try afterwards in just ... | random_line_split | |
pipe_windows.rs | }
}
}
}
}
fn handle(&self) -> libc::HANDLE { self.inner.handle }
fn read_closed(&self) -> bool {
self.inner.read_closed.load(atomic::SeqCst)
}
fn write_closed(&self) -> bool {
self.inner.write_closed.load(atomic::SeqCst)
}
fn cancel_io... | {
Err(super::last_error())
} | conditional_block | |
pipe_windows.rs | WaitForSingleObject in tandem with CancelIo
// to figure out if we should indeed get the result.
let ms = if deadline == 0 {
libc::INFINITE as u64
} else {
let now = ::io::timer::now();
if deadline < now {0} else {deadline - now}
};
let ret = unsafe {
c::WaitForMulti... | {
unsafe { let _ = libc::CloseHandle(self.handle); }
} | identifier_body | |
pipe_windows.rs | ::AtomicBool,
}
impl Inner {
fn new(handle: libc::HANDLE) -> Inner {
Inner {
handle: handle,
lock: unsafe { mutex::NativeMutex::new() },
read_closed: atomic::AtomicBool::new(false),
write_closed: atomic::AtomicBool::new(false),
}
}
}
impl Drop fo... | (handle: libc::HANDLE, deadline: u64,
events: &[libc::HANDLE]) -> IoResult<uint> {
use libc::consts::os::extra::{WAIT_FAILED, WAIT_TIMEOUT, WAIT_OBJECT_0};
// If we've got a timeout, use WaitForSingleObject in tandem with CancelIo
// to figure out if we should indeed get the result.
let ms... | await | identifier_name |
read_to_string.rs | use super::read_to_end::read_to_end_internal;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncRead;
use std::pin::Pin;
use std::vec::Vec;
use std::{io, mem, str};
/// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method.
... | <R: AsyncRead +?Sized>(
reader: Pin<&mut R>,
cx: &mut Context<'_>,
buf: &mut String,
bytes: &mut Vec<u8>,
start_len: usize,
) -> Poll<io::Result<usize>> {
let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len));
if str::from_utf8(bytes).is_err() {
Poll::Ready(ret.and_the... | read_to_string_internal | identifier_name |
read_to_string.rs | use super::read_to_end::read_to_end_internal;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncRead;
use std::pin::Pin;
use std::vec::Vec;
use std::{io, mem, str};
/// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method.
... | else {
debug_assert!(buf.is_empty());
// Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`.
mem::swap(unsafe { buf.as_mut_vec() }, bytes);
Poll::Ready(ret)
}
}
impl<A> Future for ReadToString<'_, A>
where
A: AsyncRead +?Sized + Unpin,
{
type Output = i... | {
Poll::Ready(ret.and_then(|_| {
Err(io::Error::new(io::ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
}))
} | conditional_block |
read_to_string.rs | use super::read_to_end::read_to_end_internal;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::AsyncRead;
use std::pin::Pin;
use std::vec::Vec;
use std::{io, mem, str};
/// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method.
... |
impl<R:?Sized + Unpin> Unpin for ReadToString<'_, R> {}
impl<'a, R: AsyncRead +?Sized + Unpin> ReadToString<'a, R> {
pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self {
let start_len = buf.len();
Self { reader, bytes: mem::replace(buf, String::new()).into_bytes(), buf, start_len }
... | buf: &'a mut String,
bytes: Vec<u8>,
start_len: usize,
} | random_line_split |
hmac.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* This module ... |
}
| {
let tests = tests();
for t in tests.iter() {
let mut hmac = Hmac::new(Md5::new(), t.key[]);
for i in range(0, t.data.len()) {
hmac.input(t.data.slice(i, i + 1));
}
let result = hmac.result();
let expected = MacResult::new(t.ex... | identifier_body |
hmac.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* This module ... |
expanded_key
}
// Hmac uses two keys derived from the provided key - one by xoring every byte with 0x36 and another
// with 0x5c.
fn create_keys<D: Digest>(digest: &mut D, key: &[u8]) -> (Vec<u8>, Vec<u8>) {
let mut i_key = expand_key(digest, key);
let mut o_key = i_key.clone();
derive_key(i_key.as_mu... | {
let output_size = digest.output_bytes();
digest.input(key);
digest.result(expanded_key.slice_to_mut(output_size));
digest.reset();
} | conditional_block |
hmac.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* This module ... | <D: Digest>(digest: &mut D, key: &[u8]) -> Vec<u8> {
let bs = digest.block_size();
let mut expanded_key = Vec::from_elem(bs, 0u8);
if key.len() <= bs {
slice::bytes::copy_memory(expanded_key.as_mut_slice(), key);
} else {
let output_size = digest.output_bytes();
digest.input(key... | expand_key | identifier_name |
hmac.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* This module ... | fn test_hmac_md5_incremental() {
let tests = tests();
for t in tests.iter() {
let mut hmac = Hmac::new(Md5::new(), t.key[]);
for i in range(0, t.data.len()) {
hmac.input(t.data.slice(i, i + 1));
}
let result = hmac.result();
... | random_line_split | |
tls-try-with.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
thread::spawn(|| {
assert_eq!(FOO.try_with(|_| {
132
}).expect("`try_with` failed"), 132);
}).join().unwrap();
assert!(unsafe { DROP_RUN });
} | identifier_body | |
tls-try-with.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
static mut DROP_RUN: bool = false;
struct Foo;
thread_local!(static FOO: Foo = Foo {});
impl Drop for Foo {
fn drop(&mut self) {
assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err());
unsafe { DROP_RUN = true; }
}
}
fn main() {
thread::spawn(|| {
assert_eq!(FOO.tr... |
#![feature(thread_local_try_with)]
use std::thread; | random_line_split |
tls-try-with.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) {
assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err());
unsafe { DROP_RUN = true; }
}
}
fn main() {
thread::spawn(|| {
assert_eq!(FOO.try_with(|_| {
132
}).expect("`try_with` failed"), 132);
}).join().unwrap();
assert!(unsafe { DRO... | drop | identifier_name |
metrics_flusher.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::result::Result;
use std::sync::mpsc::{self, Sender};
use std::thread::{Builder as ThreadBuilder, JoinHandle};
use std::time::{Duration, Instant};
use file_system::flush_io_metrics;
use crate::engine::KvEngine;
use crate::engines... |
}
}
| {
error!("join metrics flusher failed"; "err" => ?e);
return;
} | conditional_block |
metrics_flusher.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::result::Result;
use std::sync::mpsc::{self, Sender};
use std::thread::{Builder as ThreadBuilder, JoinHandle};
use std::time::{Duration, Instant};
use file_system::flush_io_metrics;
use crate::engine::KvEngine;
use crate::engines... | <K: KvEngine, R: RaftEngine> {
pub engines: Engines<K, R>,
interval: Duration,
handle: Option<JoinHandle<()>>,
sender: Option<Sender<bool>>,
}
impl<K: KvEngine, R: RaftEngine> MetricsFlusher<K, R> {
pub fn new(engines: Engines<K, R>) -> Self {
MetricsFlusher {
engines,
... | MetricsFlusher | identifier_name |
metrics_flusher.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use std::io;
use std::result::Result;
use std::sync::mpsc::{self, Sender};
use std::thread::{Builder as ThreadBuilder, JoinHandle};
use std::time::{Duration, Instant};
use file_system::flush_io_metrics;
use crate::engine::KvEngine;
use crate::engines... | return;
}
drop(self.sender.take().unwrap());
if let Err(e) = h.unwrap().join() {
error!("join metrics flusher failed"; "err" =>?e);
return;
}
}
} | if h.is_none() { | random_line_split |
chacha.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.state[13] += 1;
if self.state[13]!= 0 { return };
self.state[14] += 1;
if self.state[14]!= 0 { return };
self.state[15] += 1;
}
}
impl Rng for ChaChaRng {
#[inline]
fn next_u32(&mut self) -> u32 {
if self.index == STATE_WORDS {
self.update(... | { return } | conditional_block |
chacha.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 ... | () -> ChaChaRng {
let mut rng = EMPTY;
rng.init(&[0; KEY_WORDS]);
rng
}
/// Sets the internal 128-bit ChaCha counter to
/// a user-provided value. This permits jumping
/// arbitrarily ahead (or backwards) in the pseudorandom stream.
///
/// Since the nonce words are used... | new_unseeded | identifier_name |
chacha.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 seed : &[_] = &[0u32; 8];
let mut rng: ChaChaRng = SeedableRng::from_seed(seed);
let mut clone = rng.clone();
for _ in 0..16 {
assert_eq!(rng.next_u64(), clone.next_u64());
}
} | identifier_body |
chacha.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 next_u32(&mut self) -> u32 {
if self.index == STATE_WORDS {
self.update();
}
let value = self.buffer[self.index % STATE_WORDS];
self.index += 1;
value
}
}
impl<'a> SeedableRng<&'a [u32]> for ChaChaRng {
fn reseed(&mut self, seed: &'a [u32]) {
... | #[inline] | random_line_split |
mod.rs | // Copyright (C) 2020 Mathieu Duponchelle <mathieu@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any late... | (plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"textwrap",
gst::Rank::None,
TextWrap::static_type(),
)
}
| register | identifier_name |
mod.rs | // Copyright (C) 2020 Mathieu Duponchelle <mathieu@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any late... | unsafe impl Send for TextWrap {}
unsafe impl Sync for TextWrap {}
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"textwrap",
gst::Rank::None,
TextWrap::static_type(),
)
} | random_line_split | |
mod.rs | // Copyright (C) 2020 Mathieu Duponchelle <mathieu@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any late... | {
gst::Element::register(
Some(plugin),
"textwrap",
gst::Rank::None,
TextWrap::static_type(),
)
} | identifier_body | |
system.rs | use std::fmt;
use std::process;
use std::time;
#[cfg(debug_assertions)]
pub fn pdbg(args: fmt::Arguments) {
eprintln!("[DBG ] {}", args);
}
#[cfg(not(debug_assertions))]
pub fn | (_: fmt::Arguments) {}
pub fn pdie(args: fmt::Arguments) ->! {
perr(args);
process::exit(1)
}
pub fn perr(args: fmt::Arguments) {
eprintln!("[ERR ] {}", args);
}
pub fn pwarn(args: fmt::Arguments) {
eprintln!("[WARN] {}", args);
}
pub fn pinfo(args: fmt::Arguments) {
println!("[INFO] {}", args);
}
pub fn... | pdbg | identifier_name |
system.rs | use std::fmt;
use std::process;
use std::time;
#[cfg(debug_assertions)]
pub fn pdbg(args: fmt::Arguments) {
eprintln!("[DBG ] {}", args);
}
#[cfg(not(debug_assertions))]
pub fn pdbg(_: fmt::Arguments) {}
pub fn pdie(args: fmt::Arguments) ->! |
pub fn perr(args: fmt::Arguments) {
eprintln!("[ERR ] {}", args);
}
pub fn pwarn(args: fmt::Arguments) {
eprintln!("[WARN] {}", args);
}
pub fn pinfo(args: fmt::Arguments) {
println!("[INFO] {}", args);
}
pub fn pts(t1: &time::Instant, t2: &time::Instant) {
let d = t2.duration_since(*t1);
let d_seconds =... | {
perr(args);
process::exit(1)
} | identifier_body |
system.rs | use std::fmt;
use std::process;
use std::time;
#[cfg(debug_assertions)]
pub fn pdbg(args: fmt::Arguments) { |
pub fn pdie(args: fmt::Arguments) ->! {
perr(args);
process::exit(1)
}
pub fn perr(args: fmt::Arguments) {
eprintln!("[ERR ] {}", args);
}
pub fn pwarn(args: fmt::Arguments) {
eprintln!("[WARN] {}", args);
}
pub fn pinfo(args: fmt::Arguments) {
println!("[INFO] {}", args);
}
pub fn pts(t1: &time::Instant... | eprintln!("[DBG ] {}", args);
}
#[cfg(not(debug_assertions))]
pub fn pdbg(_: fmt::Arguments) {} | random_line_split |
context.rs | use machine_message::TaskStatus;
use super::Task;
use std::collections::vec_deque::VecDeque;
use printspool_protobufs::MachineFlags;
use crate::protos::{
machine_message::{
self,
},
// MachineMessage,
};
use crate::state_machine;
use printspool_machine::{
config::MachineConfig,
components::C... |
fn push_gcode_history_entry(&mut self, content: String, direction: i32) {
let entry = machine_message::GCodeHistoryEntry {
content,
direction,
};
if self.gcode_history_buffer.len() >= self.controller.model.gcode_history_buffer_size {
let _ = self.gcode_... | {
// Placeholder: Some day we might allow a toggle to display polling gcodes
if is_polling {
return
}
let direction = machine_message::GCodeHistoryDirection::Tx as i32;
self.push_gcode_history_entry(raw_src, direction)
} | identifier_body |
context.rs | use machine_message::TaskStatus;
use super::Task;
use std::collections::vec_deque::VecDeque;
use printspool_protobufs::MachineFlags;
use crate::protos::{
machine_message::{
self,
},
// MachineMessage,
};
use crate::state_machine;
use printspool_machine::{
config::MachineConfig,
components::C... | (&mut self) -> () {
// println!("History Buffer: {:?}", self.gcode_history_buffer);
self.feedback.gcode_history = self.gcode_history_buffer.drain(..).collect();
}
pub fn handle_state_change(&mut self, state: &state_machine::State) {
use state_machine::State::*;
let status = mat... | add_gcode_history_to_feedback | identifier_name |
context.rs | use machine_message::TaskStatus;
use super::Task;
use std::collections::vec_deque::VecDeque;
use printspool_protobufs::MachineFlags;
use crate::protos::{
machine_message::{
self,
},
// MachineMessage,
};
use crate::state_machine;
use printspool_machine::{
config::MachineConfig,
components::C... | .find(|p| p.task_id == task.id);
if let Some(mut progress) = progress {
// Optimized by re-using existing progress structs if they exist
progress.despooled_line_number = despooled_line_number;
progress.status = status as i32;
} else {
// If a p... |
let progress = self.feedback.task_progress
.iter_mut() | random_line_split |
main.rs | extern crate ncurses;
mod podcast;
use ncurses::*;
use self::podcast::*;
const KEY_A: i32 = 97;
const KEY_Q: i32 = 113;
fn main() {
let locale_conf = LcCategory::all;
setlocale(locale_conf, "en_US.UTF-8");
/* Initialization */
initscr(); // Start ncurses
raw(); // Line buffering disabled
noecho(); // D... | echo();
let mut feed: String = String::new();
getstr(&mut feed);
noecho();
podcasts.push(Podcast::new(feed));
destroy_window(pw);
menu();
pw = podcasts_window(&podcasts);
},
_ => {}
}
ch = getch();
}
endwin(); // Terminate ncurse... | random_line_split | |
main.rs | extern crate ncurses;
mod podcast;
use ncurses::*;
use self::podcast::*;
const KEY_A: i32 = 97;
const KEY_Q: i32 = 113;
fn main() {
let locale_conf = LcCategory::all;
setlocale(locale_conf, "en_US.UTF-8");
/* Initialization */
initscr(); // Start ncurses
raw(); // Line buffering disabled
noecho(); // D... | }
wrefresh(win);
return win;
}
| {
let lines: i32 = LINES-1;
let cols: i32 = 30;
let x: i32 = 0;
let y: i32 = 0;
let win = newwin(lines, cols, y, x);
// Draw a vertical line on the right side
for i in 0..lines {
mvwprintw(win, i, cols - 1, "|");
}
// Print podcasts names
for i in 0..podcasts.len() {
let title: &str = &pod... | identifier_body |
main.rs | extern crate ncurses;
mod podcast;
use ncurses::*;
use self::podcast::*;
const KEY_A: i32 = 97;
const KEY_Q: i32 = 113;
fn main() {
let locale_conf = LcCategory::all;
setlocale(locale_conf, "en_US.UTF-8");
/* Initialization */
initscr(); // Start ncurses
raw(); // Line buffering disabled
noecho(); // D... | (podcasts: &Vec<Podcast>) -> WINDOW {
let lines: i32 = LINES-1;
let cols: i32 = 30;
let x: i32 = 0;
let y: i32 = 0;
let win = newwin(lines, cols, y, x);
// Draw a vertical line on the right side
for i in 0..lines {
mvwprintw(win, i, cols - 1, "|");
}
// Print podcasts names
for i in 0..podcast... | podcasts_window | identifier_name |
about_loader.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 file_loader;
use hyper::header::ContentType;
use hyper::http::RawStatus;
use hyper::mime::{Mime, SubLevel, Top... | (mut load_data: LoadData,
start_chan: LoadConsumer,
classifier: Arc<MIMEClassifier>,
cancel_listener: CancellationListener) {
let url = load_data.url.clone();
let non_relative_scheme_data = url.non_relative_scheme_data().unwrap();
match non_relative_scheme_data {... | factory | identifier_name |
about_loader.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 file_loader;
use hyper::header::ContentType;
use hyper::http::RawStatus;
use hyper::mime::{Mime, SubLevel, Top... | }
"crash" => panic!("Loading the about:crash URL."),
"failure" | "not-found" => {
let mut path = resources_dir_path();
let file_name = non_relative_scheme_data.to_owned() + ".html";
path.push(&file_name);
assert!(path.exists());
load_da... | {
let url = load_data.url.clone();
let non_relative_scheme_data = url.non_relative_scheme_data().unwrap();
match non_relative_scheme_data {
"blank" => {
let metadata = Metadata {
final_url: load_data.url,
content_type: Some(ContentType(Mime(TopLevel::Text,... | identifier_body |
about_loader.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 file_loader;
use hyper::header::ContentType;
use hyper::http::RawStatus;
use hyper::mime::{Mime, SubLevel, Top... | load_data.context) {
let _ = chan.send(Done(Ok(())));
}
return
}
"crash" => panic!("Loading the about:crash URL."),
"failure" | "not-found" => {
let mut path = resources_dir_path();
... | };
if let Ok(chan) = start_sending_sniffed_opt(start_chan,
metadata,
classifier,
&[], | random_line_split |
about_loader.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 file_loader;
use hyper::header::ContentType;
use hyper::http::RawStatus;
use hyper::mime::{Mime, SubLevel, Top... |
"crash" => panic!("Loading the about:crash URL."),
"failure" | "not-found" => {
let mut path = resources_dir_path();
let file_name = non_relative_scheme_data.to_owned() + ".html";
path.push(&file_name);
assert!(path.exists());
load_data.url = ... | {
let metadata = Metadata {
final_url: load_data.url,
content_type: Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))),
charset: Some("utf-8".to_owned()),
headers: None,
status: Some(RawStatus(200, "OK".into())),
... | conditional_block |
convert.rs | #include "shared.rsh"
float4 f4 = { 2.0f, 4.0f, 6.0f, 8.0f };
char4 i8_4 = { -1, -2, -3, 4 };
static bool test_convert() {
bool failed = false;
f4 = convert_float4(i8_4);
_RS_ASSERT(f4.x == -1.0f);
_RS_ASSERT(f4.y == -2.0f);
_RS_ASSERT(f4.z == -3.0f);
_RS_ASSERT(f4.w == 4.0f);
if (faile... |
else {
rsSendToClientBlocking(RS_MSG_TEST_PASSED);
}
}
| {
rsSendToClientBlocking(RS_MSG_TEST_FAILED);
} | conditional_block |
convert.rs | #include "shared.rsh"
float4 f4 = { 2.0f, 4.0f, 6.0f, 8.0f };
| static bool test_convert() {
bool failed = false;
f4 = convert_float4(i8_4);
_RS_ASSERT(f4.x == -1.0f);
_RS_ASSERT(f4.y == -2.0f);
_RS_ASSERT(f4.z == -3.0f);
_RS_ASSERT(f4.w == 4.0f);
if (failed) {
rsDebug("test_convert FAILED", 0);
}
else {
rsDebug("test_convert PA... | char4 i8_4 = { -1, -2, -3, 4 };
| random_line_split |
advapi32.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
#![feature(test)]
#![cfg(windows)]
extern crate advapi32;
extern crate test;
use advapi32::*;
use test::black_box as bb;
#[test]
fn f | ) {
bb(AdjustTokenPrivileges);
bb(CloseServiceHandle);
bb(ControlService);
bb(CreateServiceA);
bb(CreateServiceW);
bb(CryptAcquireContextA);
bb(CryptAcquireContextW);
bb(CryptCreateHash);
bb(CryptDestroyHash);
bb(CryptGetHashParam);
bb(CryptHashData);
bb(CryptReleaseConte... | unctions( | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.