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 |
|---|---|---|---|---|
tweet.rs | #![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use color_eyre::{
eyre::{bail, eyre, Error, Result, WrapErr as _},
owo_colors::OwoColorize as _,
};
use oauth_client::Token;
use serde::{Deserialize, Serialize};
use std::pat... | match twitter::get_access_token(&consumer_token, &request_token, &pin) {
Ok(token) => token,
Err(err) => {
error!("Failed to get `access token`: {:?}", err);
continue;
}
};
... | random_line_split | |
tweet.rs | #![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use color_eyre::{
eyre::{bail, eyre, Error, Result, WrapErr as _},
owo_colors::OwoColorize as _,
};
use oauth_client::Token;
use serde::{Deserialize, Serialize};
use std::pat... | {
consumer_key: String,
consumer_secret: String,
access_key: String,
access_secret: String,
}
impl Config {
fn from_user_input(old_value: Option<&Self>) -> Result<Self> {
let input = |prompt, old_value| {
match old_value {
Some(value) => console::input_with_defa... | Config | identifier_name |
extern-return-TwoU8s.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 ... | }
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s;
}
pub fn main() {
unsafe {
let y = rust_dbg_extern_return_TwoU8s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
} | // except according to those terms.
pub struct TwoU8s {
one: u8, two: u8 | random_line_split |
extern-return-TwoU8s.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 ... | {
one: u8, two: u8
}
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_return_TwoU8s() -> TwoU8s;
}
pub fn main() {
unsafe {
let y = rust_dbg_extern_return_TwoU8s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
}
| TwoU8s | identifier_name |
extern-return-TwoU8s.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
unsafe {
let y = rust_dbg_extern_return_TwoU8s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
} | identifier_body | |
date.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/.
//
//! Module for wrapping chrono::naive::datetime::NaiveDateTime
use std::ops::{Deref, DerefMut};
use serde::Se... | (&self) -> &NaiveDateTime {
&self.0
}
}
impl DerefMut for Date {
fn deref_mut(&mut self) -> &mut NaiveDateTime {
&mut self.0
}
}
impl From<NaiveDateTime> for Date {
fn from(ndt: NaiveDateTime) -> Date {
Date(ndt)
}
}
/// The date-time parsing template used to parse the dat... | deref | identifier_name |
date.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/.
//
//! Module for wrapping chrono::naive::datetime::NaiveDateTime
use std::ops::{Deref, DerefMut};
use serde::Se... | use chrono::NaiveDateTime;
/// Date is a NaiveDateTime-Wrapper object to be able to implement foreign traits on it
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct Date(NaiveDateTime);
impl Deref for Date {
type Target = NaiveDateTime;
fn deref(&self) -> &NaiveDateTime {
&self.0
}
}
impl ... | use serde::Deserializer;
use serde::de::Visitor;
use serde::de::Error as SerdeError; | random_line_split |
date.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/.
//
//! Module for wrapping chrono::naive::datetime::NaiveDateTime
use std::ops::{Deref, DerefMut};
use serde::Se... |
}
deserializer.deserialize_str(DateVisitor)
}
}
| {
NaiveDateTime::parse_from_str(value, TASKWARRIOR_DATETIME_TEMPLATE)
.map(|d| Date(d))
.map_err(|e| SerdeError::custom(e.to_string()))
} | identifier_body |
issue-10228.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(dead_code)]
#![allow(unused_variables)]
// pretty-expanded FIXME #23616
enum StdioContainer {
CreatePipe(bool)
}
struct Test<'a> {
args: &'a [String],
io: &'a [StdioContainer]
}
pub ... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
issue-10228.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 test = Test {
args: &[],
io: &[StdioContainer::CreatePipe(true)]
};
}
| main | identifier_name |
classfile.rs | use std::fmt;
use std::vec::Vec;
use super::{Attributes, ConstantPool, FieldInfo, MethodInfo};
#[derive(Debug)]
pub struct ClassFile {
/// Java classfile magic number. `0xcafebabe` is the only valid value for
/// this field.
pub magic: u32,
/// The minor version of this classfile.
pub minor_versio... | (&self, method_name: &str) -> Option<&MethodInfo> {
for method in self.methods.iter() {
let name = self.constants[method.name_index].as_utf8();
if name == method_name {
return Some(method);
}
}
None
}
pub fn find_field(&self, field_nam... | find_method | identifier_name |
classfile.rs | use std::fmt;
use std::vec::Vec;
use super::{Attributes, ConstantPool, FieldInfo, MethodInfo};
#[derive(Debug)]
pub struct ClassFile {
/// Java classfile magic number. `0xcafebabe` is the only valid value for
/// this field.
pub magic: u32,
/// The minor version of this classfile.
pub minor_versio... | if self.is_annotation() {
v.push("ACC_ANNOTATION");
}
if self.is_enum() {
v.push("ACC_ENUM");
}
write!(f, "{}", v.join(", "))
}
}
| {
let mut v = Vec::new();
if self.is_public() {
v.push("ACC_PUBLIC");
}
if self.is_final() {
v.push("ACC_FINAL");
}
if self.is_super() {
v.push("ACC_SUPER");
}
if self.is_interface() {
v.push("ACC_INTERFACE")... | identifier_body |
classfile.rs | use std::fmt;
use std::vec::Vec;
use super::{Attributes, ConstantPool, FieldInfo, MethodInfo};
#[derive(Debug)]
pub struct ClassFile {
/// Java classfile magic number. `0xcafebabe` is the only valid value for
/// this field.
pub magic: u32,
/// The minor version of this classfile.
pub minor_versio... | }
let name_index = self.constants[self.super_class].as_class();
Some(self.constants[name_index].as_utf8())
}
pub fn find_method(&self, method_name: &str) -> Option<&MethodInfo> {
for method in self.methods.iter() {
let name = self.constants[method.name_index].as_utf8... | /// that holds the super class name. If `super_class == 0` then `None` is
/// returned.
pub fn super_class_name(&self) -> Option<&String> {
if self.super_class == 0 {
return None; | random_line_split |
classfile.rs | use std::fmt;
use std::vec::Vec;
use super::{Attributes, ConstantPool, FieldInfo, MethodInfo};
#[derive(Debug)]
pub struct ClassFile {
/// Java classfile magic number. `0xcafebabe` is the only valid value for
/// this field.
pub magic: u32,
/// The minor version of this classfile.
pub minor_versio... |
}
None
}
}
bitflags! {
pub flags ClassAccessFlags: u16 {
const CLASS_ACC_PUBLIC = 0x0001,
const CLASS_ACC_FINAL = 0x0010,
const CLASS_ACC_SUPER = 0x0020,
const CLASS_ACC_INTERFACE = 0x0200,
const CLASS_ACC_ABSTRACT = 0x040... | {
return Some(field);
} | conditional_block |
unsupported.rs | use std::ffi::{OsStr, OsString};
use std::os::unix::io::RawFd;
use std::path::Path;
use std::io;
use ::UnsupportedPlatformError;
#[derive(Clone, Debug)]
pub struct XAttrs;
impl Iterator for XAttrs {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
unreachable!("this should never exist")... | (_: &Path, _: &OsStr) -> io::Result<Vec<u8>> {
Err(io::Error::new(io::ErrorKind::Other, UnsupportedPlatformError))
}
pub fn set_path(_: &Path, _: &OsStr, _: &[u8]) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Other, UnsupportedPlatformError))
}
pub fn remove_path(_: &Path, _: &OsStr) -> io::Result<()... | get_path | identifier_name |
unsupported.rs | use std::ffi::{OsStr, OsString};
use std::os::unix::io::RawFd;
use std::path::Path;
use std::io;
use ::UnsupportedPlatformError;
#[derive(Clone, Debug)]
pub struct XAttrs;
impl Iterator for XAttrs {
type Item = OsString;
fn next(&mut self) -> Option<OsString> { | }
fn size_hint(&self) -> (usize, Option<usize>) {
unreachable!("this should never exist")
}
}
pub fn get_fd(_: RawFd, _: &OsStr) -> io::Result<Vec<u8>> {
Err(io::Error::new(io::ErrorKind::Other, UnsupportedPlatformError))
}
pub fn set_fd(_: RawFd, _: &OsStr, _: &[u8]) -> io::Result<()> {
... | unreachable!("this should never exist") | random_line_split |
unsupported.rs | use std::ffi::{OsStr, OsString};
use std::os::unix::io::RawFd;
use std::path::Path;
use std::io;
use ::UnsupportedPlatformError;
#[derive(Clone, Debug)]
pub struct XAttrs;
impl Iterator for XAttrs {
type Item = OsString;
fn next(&mut self) -> Option<OsString> |
fn size_hint(&self) -> (usize, Option<usize>) {
unreachable!("this should never exist")
}
}
pub fn get_fd(_: RawFd, _: &OsStr) -> io::Result<Vec<u8>> {
Err(io::Error::new(io::ErrorKind::Other, UnsupportedPlatformError))
}
pub fn set_fd(_: RawFd, _: &OsStr, _: &[u8]) -> io::Result<()> {
Err(i... | {
unreachable!("this should never exist")
} | identifier_body |
path.rs | //! Items related to working with paths for 2D geometry and vector graphics.
//!
//! This module attempts to provide abstractions around the various `Path` and `Builder` types
//! offerred by `lyon` in a way that interoperates a little more fluidly and consistently with the
//! rest of nannou's API.
use crate::geom::{... |
}
// Simplified constructors
/// Begin building a path.
pub fn path() -> Builder {
Builder::new()
}
/// Build a path with the given capacity for the inner path event storage.
pub fn path_with_capacity(points: usize, edges: usize) -> Builder {
Builder::with_capacity(points, edges)
}
// Conversions between s... | {
self.as_slice()
} | identifier_body |
path.rs | //! Items related to working with paths for 2D geometry and vector graphics.
//!
//! This module attempts to provide abstractions around the various `Path` and `Builder` types
//! offerred by `lyon` in a way that interoperates a little more fluidly and consistently with the
//! rest of nannou's API.
use crate::geom::{... | (mut self, to: Point2) -> Self {
self.builder.line_to(to.into());
self
}
/// Closes the current sub path and sets the current position to the first position of the
/// current sub-path.
pub fn close(mut self) -> Self {
self.builder.close();
self
}
/// Add a quad... | line_to | identifier_name |
path.rs | //! Items related to working with paths for 2D geometry and vector graphics.
//!
//! This module attempts to provide abstractions around the various `Path` and `Builder` types
//! offerred by `lyon` in a way that interoperates a little more fluidly and consistently with the
//! rest of nannou's API.
use crate::geom::{... | /// Returns a lyon view on this **Path**.
pub fn as_slice(&self) -> lyon::path::PathSlice {
self.path.as_slice()
}
/// Returns a slice over an endpoint's custom attributes.
pub fn attributes(&self, endpoint: lyon::path::EndpointId) -> &[f32] {
self.path.attributes(endpoint)
}
... | pub fn new() -> Self {
lyon::path::Path::new().into()
}
| random_line_split |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... | underline: false, overline: false, line_through: false,
};
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result)
}
let mut blink = false;
let mut empty = true;
while input.try(|input| {
if let Ok(ide... | }
/// none | [ underline || overline || line-through || blink ]
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut result = SpecifiedValue { | random_line_split |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... | else {
return Err(());
}
Ok(())
}).is_ok() {
}
if!empty { Ok(result) } else { Err(()) }
}
% if product == "servo":
fn cascade_property_custom<C: ComputedValues>(
_declaration: &PropertyD... | {
match_ignore_ascii_case! { ident,
"underline" => if result.underline { return Err(()) }
else { empty = false; result.underline = true },
"overline" => if result.overline { return Err(()) }
... | conditional_block |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... | () -> computed_value::T {
computed_value::none
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut result = SpecifiedValue {
underline: false, overline: false, line_thro... | get_initial_value | identifier_name |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... | else { empty = false; blink = true },
_ => return Err(())
}
} else {
return Err(());
}
Ok(())
}).is_ok() {
}
if!empty { Ok(result) } else { Err(... | {
let mut result = SpecifiedValue {
underline: false, overline: false, line_through: false,
};
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result)
}
let mut blink = false;
let mut empty = true;
while input... | identifier_body |
toolbutton.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
pub fn new_from_stock(stock_id: &str) -> Option<ToolButton> {
let tmp_pointer = stock_id.with_c_str(|c_str| {
unsafe { ffi::gtk_tool_button_new_from_stock(c_str) }
});
check_pointer!(tmp_pointer, ToolButton)
}
}
impl_drop!(ToolButton)
impl_TraitWidget!(ToolButton)
impl gtk... | let tmp_pointer = unsafe {
match label {
Some(l) => {
l.with_c_str(|c_str| {
match icon_widget {
Some(i) => ffi::gtk_tool_button_new(i.get_widget(), c_str),
None => ffi::gtk_tool_bu... | identifier_body |
toolbutton.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | : gtk::WidgetTrait>(icon_widget: Option<&T>, label: Option<&str>) -> Option<ToolButton> {
let tmp_pointer = unsafe {
match label {
Some(l) => {
l.with_c_str(|c_str| {
match icon_widget {
Some(i) => ffi::gtk_tool_... | w<T | identifier_name |
toolbutton.rs | // rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but ... | // This file is part of rgtk.
// | random_line_split | |
mod.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <bgamari@gmail.com>
//
// 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... |
This module also provides `isr.rs`, that is not compiled as a part of this
crate. `isr.rs` provides ISR vector table.
*/
pub use super::cortex_common::systick;
pub use super::cortex_common::scb;
pub use super::cortex_common::nvic;
pub use super::cortex_common::irq;
pub mod lock; | // See the License for the specific language governing permissions and
// limitations under the License.
/*!
Generic routines for ARM Cortex-M3 cores. | random_line_split |
licenses.rs | use std::fs::File;
use proc_macro::TokenStream;
use quote;
use serde_json;
use serde::de::IgnoredAny;
const SOURCES: &[&str] = &[
"src/licenses/license-hound.json",
"src/licenses/other.json",
];
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum LicenseId {
Bsd3Clause,
Mit,
Mpl2,
Ofl11,
}
i... | (&self, tokens: &mut quote::Tokens) {
let c: &LicenseDescription = self.conclusion.as_ref().unwrap();
let (name, link, copyright, license) =
(&self.package_name, &c.link, &c.copyright_notice, &c.chosen_license);
let link = match link {
&Some(ref link) => quote! { Some(#l... | to_tokens | identifier_name |
licenses.rs | use std::fs::File;
use proc_macro::TokenStream;
use quote;
use serde_json;
use serde::de::IgnoredAny;
const SOURCES: &[&str] = &[
"src/licenses/license-hound.json",
"src/licenses/other.json",
];
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum LicenseId {
Bsd3Clause,
Mit,
Mpl2,
Ofl11,
}
i... |
let copyright = match license.include_notice() {
true => copyright,
false => "",
};
tokens.append(quote! {
LicenseInfo {
name: #name,
link: #link,
copyright: #copyright,
license: License::#licen... | &Some(ref link) => quote! { Some(#link) },
&None => quote! { None },
}; | random_line_split |
four_bit_adder.rs | // http://rosettacode.org/wiki/Four_bit_adder
use std::ops::Deref;
use std::fmt;
// primitive gates
fn not(a: bool) -> bool {
!a
}
fn or(a: bool, b: bool) -> bool {
a || b
}
fn and(a: bool, b: bool) -> bool {
a && b
}
/// xor gate [2x not, 2x and, 1x or]
/// (A &!B) | (B &!A)
fn xor(a: bool, b: bool) -> bo... |
#[test]
fn test_not() {
assert_eq!(true, not(false));
assert_eq!(false, not(true));
}
#[test]
fn test_or() {
assert_eq!(false, or(false, false));
assert_eq!(true, or(true, false));
assert_eq!(true, or(false, true));
assert_eq!(true, or(true, true));
}
#[test]
fn test_and() {
assert_eq!(fa... | nib_b,
result,
carry)
} | random_line_split |
four_bit_adder.rs | // http://rosettacode.org/wiki/Four_bit_adder
use std::ops::Deref;
use std::fmt;
// primitive gates
fn not(a: bool) -> bool {
!a
}
fn or(a: bool, b: bool) -> bool {
a || b
}
fn and(a: bool, b: bool) -> bool {
a && b
}
/// xor gate [2x not, 2x and, 1x or]
/// (A &!B) | (B &!A)
fn xor(a: bool, b: bool) -> bo... | ([bool; 4]);
impl Nibble {
fn new(arr: [u8; 4]) -> Nibble {
Nibble([arr[0]!= 0, arr[1]!= 0, arr[2]!= 0, arr[3]!= 0])
}
fn from_u8(n: u8) -> Nibble {
Nibble::new([n & 8, n & 4, n & 2, n & 1])
}
fn to_u8(&self, carry: bool) -> u8 {
match u8::from_str_radix(&(format!("{}", sel... | Nibble | identifier_name |
four_bit_adder.rs | // http://rosettacode.org/wiki/Four_bit_adder
use std::ops::Deref;
use std::fmt;
// primitive gates
fn not(a: bool) -> bool {
!a
}
fn or(a: bool, b: bool) -> bool {
a || b
}
fn and(a: bool, b: bool) -> bool {
a && b
}
/// xor gate [2x not, 2x and, 1x or]
/// (A &!B) | (B &!A)
fn xor(a: bool, b: bool) -> bo... |
#[test]
fn test_four_bit_adder() {
for (a, b) in (0..std::u8::MAX).map(|n| (n >> 4, n & 15)) {
let nib_a = Nibble::from_u8(a);
let nib_b = Nibble::from_u8(b);
let (result, carry) = four_bit_adder(nib_a, nib_b, false);
assert_eq!(a + b, result.to_u8(carry));
let (result, ca... | {
assert_eq!((false, false), full_adder(false, false, false));
assert_eq!((true, false), full_adder(false, false, true));
assert_eq!((true, false), full_adder(false, true, false));
assert_eq!((true, false), full_adder(true, false, false));
assert_eq!((false, true), full_adder(false, true, true));
... | identifier_body |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... |
#[macro_export]
macro_rules! try_log {
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {
error!("try_log! | {}", err);
return Err(From::from(err))
}
})
}
macro_rules! _map_err {
($lvl:expr, $expr:expr) => (
|err| {
log!($lvl, ... | {
match level {
1 => Level::Error,
2 => Level::Warn,
3 => Level::Info,
4 => Level::Debug,
5 => Level::Trace,
_ => unreachable!(),
}
} | identifier_body |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... | static mut LOG_CB: Option<LogCB> = None;
static mut FLUSH_CB: Option<FlushCB> = None;
pub struct LibindyLogger {
context: *const c_void,
enabled: Option<EnabledCB>,
log: LogCB,
flush: Option<FlushCB>,
}
impl LibindyLogger {
fn new(context: *const c_void, enabled: Option<EnabledCB>, log: LogCB, flu... | static mut CONTEXT: *const c_void = ptr::null();
static mut ENABLED_CB: Option<EnabledCB> = None; | random_line_split |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... | (&self) -> (*const c_void, Option<EnabledCB>, Option<LogCB>, Option<FlushCB>) {
match self {
LoggerState::Default => (ptr::null(), Some(LibindyDefaultLogger::enabled), Some(LibindyDefaultLogger::log), Some(LibindyDefaultLogger::flush)),
LoggerState::Custom => unsafe { (CONTEXT, ENABLED_C... | get | identifier_name |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... |
}
fn log(&self, record: &Record) {
let log_cb = self.log;
let level = record.level() as u32;
let target = CString::new(record.target()).unwrap();
let message = CString::new(record.args().to_string()).unwrap();
let module_path = record.module_path().map(|a| CString::ne... | { true } | conditional_block |
union-const-eval-field.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Field1 {
const FIELD1: Field1 = unsafe { UNION.field1 };
FIELD1
}
const fn read_field2() -> Field2 {
const FIELD2: Field2 = unsafe { UNION.field2 };
FIELD2
}
const fn read_field3() -> Field3 {
const FIELD3: Field3 = unsafe { UNION.field3 };
//~^ ERROR it is undefined behavior to use this... | read_field1 | identifier_name |
union-const-eval-field.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
const fn read_field2() -> Field2 {
const FIELD2: Field2 = unsafe { UNION.field2 };
FIELD2
}
const fn read_field3() -> Field3 {
const FIELD3: Field3 = unsafe { UNION.field3 };
//~^ ERROR it is undefined behavior to use this value
FIELD3
}
fn main() {
assert_eq!(read_field1(), FLOAT1_AS_I32);
... | {
const FIELD1: Field1 = unsafe { UNION.field1 };
FIELD1
} | identifier_body |
union-const-eval-field.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
const fn read_field2() -> Field2 {
const FIELD2: Field2 = unsafe { UNION.field2 };
FIELD2
}
const fn read_field3() -> Field3 {
const FIELD3: Field3 = unsafe { UNION.field3 };
//~^ ERROR it is undefined behavior to use this value
FIELD3
}
fn main() {
assert_eq!(read_field1(), FLOAT1_AS_I32);
... | const fn read_field1() -> Field1 {
const FIELD1: Field1 = unsafe { UNION.field1 };
FIELD1
} | random_line_split |
class_method.rs | // Copyright 2016-17 Alexander Reece
//
// 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 accord... | (&self) -> &Self::Target {
self.method
}
} | deref | identifier_name |
class_method.rs | // Copyright 2016-17 Alexander Reece
//
// 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 accord... | &self.pascal_case
}
pub fn has_lifetimes(&self) -> bool {
self.has_lifetimes
}
pub fn has_usable_fields(&self) -> bool {
self.has_usable_fields
}
}
impl Deref for ClassMethod {
type Target = specs::ClassMethod;
fn deref(&self) -> &Self::Target {
self.metho... | pub fn pascal_case(&self) -> &str { | random_line_split |
class_method.rs | // Copyright 2016-17 Alexander Reece
//
// 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 accord... |
}
impl Deref for ClassMethod {
type Target = specs::ClassMethod;
fn deref(&self) -> &Self::Target {
self.method
}
} | {
self.has_usable_fields
} | identifier_body |
os_str.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 ... |
pub fn push_slice(&mut self, s: &Slice) {
self.inner.push_wtf8(&s.inner)
}
}
impl Slice {
pub fn from_str(s: &str) -> &Slice {
unsafe { mem::transmute(Wtf8::from_str(s)) }
}
pub fn to_str(&self) -> Option<&str> {
self.inner.as_str()
}
pub fn to_string_lossy(&self... | {
self.inner.into_string().map_err(|buf| Buf { inner: buf })
} | identifier_body |
os_str.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 ... | pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(self.inner.as_slice()) }
}
pub fn into_string(self) -> Result<String, Buf> {
self.inner.into_string().map_err(|buf| Buf { inner: buf })
}
pub fn push_slice(&mut self, s: &Slice) {
self.inner.push_wtf8(&s.inner)
... | Buf { inner: Wtf8Buf::from_string(s) }
}
| random_line_split |
os_str.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 ... | (&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.inner.fmt(formatter)
}
}
impl Buf {
pub fn from_string(s: String) -> Buf {
Buf { inner: Wtf8Buf::from_string(s) }
}
pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(self.inner.as_slice()) }
}... | fmt | identifier_name |
transport.rs | use std::convert::From;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
BadInput(&'static str),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
const LENGTH_HEADER: &'static str = "Content-Length:";
#[derive(Debug... |
}
let content_length = content_length.ok_or(Error::BadInput("no content length"))?;
self.read_buffer.clear();
(&mut self.reader)
.take(content_length)
.read_line(&mut self.read_buffer)?;
Ok(self.read_buffer.clone())
}
pub fn send_message(&mut self,... | {
return Err(Error::BadInput("unexpected eof"));
} | conditional_block |
transport.rs | use std::convert::From;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
BadInput(&'static str),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
const LENGTH_HEADER: &'static str = "Content-Length:";
#[derive(Debug... | } else if self.read_buffer == "\r\n" {
break;
} else if self.read_buffer.is_empty() {
return Err(Error::BadInput("unexpected eof"));
}
}
let content_length = content_length.ok_or(Error::BadInput("no content length"))?;
self.read... | random_line_split | |
transport.rs | use std::convert::From;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
BadInput(&'static str),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
const LENGTH_HEADER: &'static str = "Content-Length:";
#[derive(Debug... | (reader: R, writer: W) -> Self {
Transport {
read_buffer: String::new(),
reader,
writer,
}
}
pub fn read_message(&mut self) -> Result<String, Error> {
let mut content_length = None;
loop {
self.read_buffer.clear();
self... | new | identifier_name |
struct-base-wrong-type.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo { a: isi... | random_line_split | |
struct-base-wrong-type.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 ... | {
let b = Bar { x: 5 };
let f = Foo { a: 2, ..b }; //~ ERROR mismatched types
//~| expected `Foo`
//~| found `Bar`
//~| expected struct `Foo`
//~| found struct `Bar`
let f__isize = Fo... | identifier_body | |
struct-base-wrong-type.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 ... | { x: isize }
static bar: Bar = Bar { x: 5 };
static foo: Foo = Foo { a: 2,..bar }; //~ ERROR mismatched types
//~| expected `Foo`
//~| found `Bar`
//~| expected struct `Foo`
... | Bar | identifier_name |
macro_rules.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ], Some(SEMI), false, 0u, 2u)),
//to phase into semicolon-termination instead of
//semicolon-separation
ms(match_seq(~[ms(match_tok(SEMI))], None, true, 2u, 2u))];
// Parse the macro_rules! invocation (`none` is for no interpolations):
let arg_reader = new_tt_reader(copy cx.par... | ms(match_tok(FAT_ARROW)),
ms(match_nonterminal(rhs_nm, special_idents::tt, 1u)), | random_line_split |
macro_rules.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 lhs_nm = cx.parse_sess().interner.gensym("lhs");
let rhs_nm = cx.parse_sess().interner.gensym("rhs");
// The grammar for macro_rules! is:
// $( $lhs:mtcs => $rhs:tt );+
//...quasiquoting this would be nice.
let argument_gram = ~[
ms(match_seq(~[
ms(match_nonterminal(... | {
spanned { node: copy m, span: dummy_sp() }
} | identifier_body |
macro_rules.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 ... | (m: matcher_) -> matcher {
spanned { node: copy m, span: dummy_sp() }
}
let lhs_nm = cx.parse_sess().interner.gensym("lhs");
let rhs_nm = cx.parse_sess().interner.gensym("rhs");
// The grammar for macro_rules! is:
// $( $lhs:mtcs => $rhs:tt );+
//...quasiquoting this would be nice.
... | ms | identifier_name |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
us... |
if members.len() <= MAX_CHOP {
vec![Chop { members: members } ]
} else {
Vec::new()
}
}
}
#[derive(Debug, Clone, Hash, PartialEq)]
pub struct ChopType;
impl TypeT for ChopType {
fn name(&self) -> Option<&'static str> {
Some("chop")
}
fn extract(&... | {
members.push(func.clone());
members.sort();
} | conditional_block |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
us... |
typet_boiler!();
}
impl ValueT for Chop {
fn type_(&self) -> Type {
Arc::new(ChopType)
}
fn get(&self) -> &Any {
self as &Any
}
fn to_sql(&self) -> Vec<&ToSql> {
vec![self]
}
valuet_boiler!();
}
impl ToSql for Chop {
accepts!(::postgres::types::JSONB, ::pos... | {
"jsonb"
} | identifier_body |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
us... | (
&self,
ty: &::postgres::types::Type,
out: &mut Vec<u8>,
) -> ::std::result::Result<IsNull, Box<::std::error::Error + Send + Sync>> {
self.to_json().to_sql(ty, out)
}
}
impl ToValue for Chop {
fn to_value(self) -> Value {
Arc::new(self)
}
}
// TODO placeholder
... | to_sql | identifier_name |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter; | use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
use rustc_serialize::Decodable;
#[derive(Debug, Clone, Hash, PartialOrd, PartialEq, RustcDecodable, RustcEncodable, Eq)]
pub struct Chop {
members: Vec<BitVector>,
}
impl ToJson for Chop {
fn to_json(&self) -> J... | use holmes::pg::dyn::{Type, Value}; | random_line_split |
timer.rs | extern crate coio;
use std::sync::Arc;
fn invoke_every_ms<F>(ms: u64, f: F)
where F: Fn() + Sync + Send +'static
{
let f = Arc::new(f);
coio::spawn(move|| {
loop {
coio::sleep_ms(ms);
let f = f.clone();
coio::spawn(move|| (*f)());
}
});
}
fn invoke_... | {
coio::spawn(|| {
for i in 0..10 {
println!("Qua {}", i);
coio::sleep_ms(2000);
}
});
invoke_every_ms(1000, || println!("Purr :P"));
invoke_after_ms(10000, || println!("Tadaaaaaaa"));
coio::run(2);
} | identifier_body | |
timer.rs | extern crate coio;
use std::sync::Arc;
fn invoke_every_ms<F>(ms: u64, f: F)
where F: Fn() + Sync + Send +'static
{
let f = Arc::new(f); | let f = f.clone();
coio::spawn(move|| (*f)());
}
});
}
fn invoke_after_ms<F>(ms: u64, f: F)
where F: FnOnce() + Send +'static
{
coio::spawn(move|| {
coio::sleep_ms(ms);
f();
});
}
fn main() {
coio::spawn(|| {
for i in 0..10 {
prin... | coio::spawn(move|| {
loop {
coio::sleep_ms(ms); | random_line_split |
timer.rs | extern crate coio;
use std::sync::Arc;
fn | <F>(ms: u64, f: F)
where F: Fn() + Sync + Send +'static
{
let f = Arc::new(f);
coio::spawn(move|| {
loop {
coio::sleep_ms(ms);
let f = f.clone();
coio::spawn(move|| (*f)());
}
});
}
fn invoke_after_ms<F>(ms: u64, f: F)
where F: FnOnce() + Send +'s... | invoke_every_ms | identifier_name |
database.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
}
pub fn get_available_space(&self) -> u64 {
self.space_available.clone()
}
pub fn get_data_stored(&self) -> u64 {
self.data_stored.clone()
}
}
pub struct MaidManagerDatabase {
storage: collections::HashMap<Identity, MaidManagerAccount>,
}
impl MaidManagerDatabase {
pub fn ... | {
self.data_stored -= size;
self.space_available += size;
} | conditional_block |
database.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | () -> MaidManagerDatabase {
MaidManagerDatabase { storage: collections::HashMap::with_capacity(10000), }
}
pub fn exist(&mut self, name : &Identity) -> bool {
self.storage.contains_key(name)
}
pub fn put_data(&mut self, name: &Identity, size: u64) -> bool {
let entry = self.storage.entry(na... | new | identifier_name |
database.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
fn serialised_contents(&self) -> Vec<u8> {
let mut e = cbor::Encoder::from_memory();
e.encode(&[&self]).unwrap();
e.into_bytes()
}
fn refresh(&self)->bool {
true
}
fn merge(&self, responses: Vec<Box<Sendable>>) -> Option<Box<Sendable>> {
let mut tmp_wrappe... | {
MAID_MANAGER_ACCOUNT_TAG
} | identifier_body |
database.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | let name = routing::test_utils::Random::generate_random();
db.delete_data(&name, 0);
assert_eq!(db.exist(&name), false);
assert_eq!(db.put_data(&name, 0), true);
assert_eq!(db.exist(&name), true);
db.delete_data(&name, 1);
assert_eq!(db.exist(&name), true);
... | }
#[test]
fn delete_data() {
let mut db = MaidManagerDatabase::new(); | random_line_split |
main.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a> {
inner: &'a Path,
}
impl<'a> Drop for RemoveOnDrop<'a> {
fn drop(&mut self) {
t!(fs::remove_dir_all(self.inner));
}
}
fn handle_run(socket: TcpStream, work: &Path, lock: &Mutex<()>) {
let mut arg = Vec::new();
let mut reader = BufReader::new(socket);
// Allocate ourselves a dire... | RemoveOnDrop | identifier_name |
main.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut len = [0; 4];
t!(r.read_exact(&mut len));
((len[0] as u32) << 24) |
((len[1] as u32) << 16) |
((len[2] as u32) << 8) |
((len[3] as u32) << 0)
} | identifier_body | |
main.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else if &buf[..] == b"run " {
let lock = lock.clone();
thread::spawn(move || handle_run(socket, work, &lock));
} else {
panic!("unknown command {:?}", buf);
}
}
}
fn handle_push(socket: TcpStream, work: &Path) {
let mut reader = BufReader::new(socket);
r... | {
handle_push(socket, work);
} | conditional_block |
main.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let mut env = Vec::new();
arg.truncate(0);
while t!(reader.read_until(0, &mut arg)) > 1 {
let key_len = arg.len() - 1;
let val_len = t!(reader.read_until(0, &mut arg)) - 1;
{
let key = &arg[..key_len];
let val = &arg[key_len + 1..][..val_len];
let ... | arg.truncate(0);
}
// Next we'll get a bunch of env vars in pairs delimited by 0s as well | random_line_split |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn read_grid_from_file(input_file_path: &String) -> Result<Grid, io::Error> | Ok(grid)
}
| {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines().next().unwrap().unwrap().chars().count();
reader.seek(SeekFrom::Start(0)).unwrap();
let y = reader.by_ref().lines().count();
reader.seek(SeekFrom::Start(0)).unwrap();
let... | identifier_body |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn | (input_file_path: &String) -> Result<Grid, io::Error> {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines().next().unwrap().unwrap().chars().count();
reader.seek(SeekFrom::Start(0)).unwrap();
let y = reader.by_ref().lines().count();
... | read_grid_from_file | identifier_name |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn read_grid_from_file(input_file_path: &String) -> Result<Grid, io::Error> {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines... | } | random_line_split | |
file.rs | use std::io;
use std::io::{ BufRead, BufReader, Read, Seek, SeekFrom };
use std::fs::File;
use models::Grid;
pub fn read_grid_from_file(input_file_path: &String) -> Result<Grid, io::Error> {
let file = try!(File::open(input_file_path));
let mut reader = BufReader::new(file);
let x = reader.by_ref().lines... | ,
_ => { grid[y][x].die() }
}
}
}
Ok(grid)
}
| { grid[y][x].arise() } | conditional_block |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... | <V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
So... | set | identifier_name |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... | /// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
... | impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but | random_line_split |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// 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,
// pu... |
}
}
return request_header;
}
// TODO - Create real logic that will actually verifiy this
pub fn is_valid(&self) -> bool {
if self.sec_websocket_key.as_slice()!= "" {
return true;
}
return false;
}
}
impl ReturnHeader {
/*
* Re... | { /* Do nothing */ } | conditional_block |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// 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,
// pu... |
/*
* SHA-1 Hash performed on passed value
* Bytes placed in passed out buffer
*/
fn sha1_hash(value: &str, out: &mut [u8]) {
let mut sha = box Sha1::new();
(*sha).input_str(value);
sha.result(out);
}
}
| {
let mut stringified = String::new();
stringified.push_str(self.heading.as_slice());
stringified.push_str(self.upgrade.as_slice());
stringified.push_str(self.connection.as_slice());
stringified.push_str("Sec-Websocket-Accept: ");
stringified.push_str(self.sec_websocket_a... | identifier_body |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// 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,
// pu... | (value: &str, out: &mut [u8]) {
let mut sha = box Sha1::new();
(*sha).input_str(value);
sha.result(out);
}
}
| sha1_hash | identifier_name |
httpheader.rs | // Copyright (c) 2014 Nathan Sizemore
// 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,
// pu... |
// Get the SHA-1 Hash as bytes
let mut out = [0u8; 20];
ReturnHeader::sha1_hash(pre_hash.as_slice(), &mut out);
// Base64 encode the buffer
let config = STANDARD;
let encoded = out.to_base64(config);
ReturnHeader {
heading: String::from_str("HTTP/1.... | let mut pre_hash = String::from_str(key);
pre_hash.push_str("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); | random_line_split |
mediastream.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::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... | (&self) -> Vec<DomRoot<MediaStreamTrack>> {
self.tracks
.borrow()
.iter()
.filter(|x| x.ty() == MediaStreamType::Video)
.map(|x| DomRoot::from_ref(&**x))
.collect()
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-gettrackbyid
fn ... | GetVideoTracks | identifier_name |
mediastream.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::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... |
self.add_track(track)
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-removetrack
fn RemoveTrack(&self, track: &MediaStreamTrack) {
self.tracks.borrow_mut().retain(|x| *x!= track);
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-clone
fn Clone(&se... | {
return;
} | conditional_block |
mediastream.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::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... | self.tracks
.borrow()
.iter()
.filter(|x| x.ty() == MediaStreamType::Video)
.map(|x| DomRoot::from_ref(&**x))
.collect()
}
/// https://w3c.github.io/mediacapture-main/#dom-mediastream-gettrackbyid
fn GetTrackById(&self, id: DOMString) -> Option... | /// https://w3c.github.io/mediacapture-main/#dom-mediastream-getvideotracks
fn GetVideoTracks(&self) -> Vec<DomRoot<MediaStreamTrack>> { | random_line_split |
mediastream.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::cell::{DomRefCell, Ref};
use crate::dom::bindings::codegen::Bindings::MediaStreamBindin... |
pub fn Constructor__(
global: &Window,
tracks: Vec<DomRoot<MediaStreamTrack>>,
) -> Fallible<DomRoot<MediaStream>> {
let new = MediaStream::new(&global.global());
for track in tracks {
// this is quadratic, but shouldn't matter much
// if this becomes a ... | {
Ok(stream.Clone())
} | identifier_body |
mod.rs | use iron::prelude::*;
use mount::Mount;
use config::CONFIG;
mod handlers;
pub fn | () {
let mut mount = Mount::new();
mount.mount("/pullrequests/",
router!(get "/" => handlers::pull_requests));
mount.mount("/issues/", router!(get "/" => handlers::issues));
mount.mount("/buildbots/", router!(get "/" => handlers::buildbots));
mount.mount("/releases/", router!(get "/... | serve | identifier_name |
mod.rs | use iron::prelude::*;
use mount::Mount;
use config::CONFIG;
mod handlers;
pub fn serve() | let server_addr = format!("0.0.0.0:{}", CONFIG.server_port);
info!("Starting API server running at {}", &server_addr);
Iron::new(chain).http(&*server_addr).unwrap();
}
| {
let mut mount = Mount::new();
mount.mount("/pullrequests/",
router!(get "/" => handlers::pull_requests));
mount.mount("/issues/", router!(get "/" => handlers::issues));
mount.mount("/buildbots/", router!(get "/" => handlers::buildbots));
mount.mount("/releases/", router!(get "/" =... | identifier_body |
mod.rs | use iron::prelude::*;
use mount::Mount;
use config::CONFIG;
mod handlers;
pub fn serve() {
let mut mount = Mount::new();
mount.mount("/pullrequests/",
router!(get "/" => handlers::pull_requests));
mount.mount("/issues/", router!(get "/" => handlers::issues));
mount.mount("/buildbots/... | } | info!("Starting API server running at {}", &server_addr);
Iron::new(chain).http(&*server_addr).unwrap(); | random_line_split |
state_set.rs | use ena::unify::{UnifyKey, UnifyValue};
use lr1::lane_table::table::context_set::{ContextSet, OverlappingLookahead};
/// The unification key for a set of states in the lane table
/// algorithm. Each set of states is associated with a
/// `ContextSet`. When two sets of states are merged, their conflict
/// sets are me... | // (for example, we could have each state set be associated with an
// index that maps to a `ContextSet`), and do the merging ourselves.
// But this is easier for now, and cloning a `ContextSet` isn't THAT
// expensive, right? :)
impl UnifyValue for ContextSet {
type Error = (Self, Self);
fn unify_values(value... | // FIXME: The `ena` interface is really designed around `UnifyValue`
// being cheaply cloneable; we should either refactor `ena` a bit or
// find some other way to associate a `ContextSet` with a state set | random_line_split |
state_set.rs | use ena::unify::{UnifyKey, UnifyValue};
use lr1::lane_table::table::context_set::{ContextSet, OverlappingLookahead};
/// The unification key for a set of states in the lane table
/// algorithm. Each set of states is associated with a
/// `ContextSet`. When two sets of states are merged, their conflict
/// sets are me... | {
index: u32,
}
impl UnifyKey for StateSet {
type Value = ContextSet;
fn index(&self) -> u32 {
self.index
}
fn from_index(u: u32) -> Self {
StateSet { index: u }
}
fn tag() -> &'static str {
"StateSet"
}
}
// FIXME: The `ena` interface is really designed aro... | StateSet | identifier_name |
state_set.rs | use ena::unify::{UnifyKey, UnifyValue};
use lr1::lane_table::table::context_set::{ContextSet, OverlappingLookahead};
/// The unification key for a set of states in the lane table
/// algorithm. Each set of states is associated with a
/// `ContextSet`. When two sets of states are merged, their conflict
/// sets are me... |
fn from_index(u: u32) -> Self {
StateSet { index: u }
}
fn tag() -> &'static str {
"StateSet"
}
}
// FIXME: The `ena` interface is really designed around `UnifyValue`
// being cheaply cloneable; we should either refactor `ena` a bit or
// find some other way to associate a `ContextSe... | {
self.index
} | identifier_body |
regions-ret-borrowed.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 main() {
let x = return_it();
println!("foo={}", *x);
}
| {
with(|o| o) //~ ERROR mismatched types
//~^ ERROR lifetime of return value does not outlive the function call
//~^^ ERROR cannot infer
} | identifier_body |
regions-ret-borrowed.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 with<R>(f: |x: &int| -> R) -> R {
f(&3)
}
fn return_it<'a>() -> &'a int {
with(|o| o) //~ ERROR mismatched types
//~^ ERROR lifetime of return value does not outlive the function call
//~^^ ERROR cannot infer
}
fn main() {
let x = return_it();
println!("foo={}", *x);
} | // provides a value that is only good within its own stack frame. This
// used to successfully compile because we failed to account for the
// fact that fn(x: &int) rebound the region &.
| random_line_split |
regions-ret-borrowed.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 ... | <'a>() -> &'a int {
with(|o| o) //~ ERROR mismatched types
//~^ ERROR lifetime of return value does not outlive the function call
//~^^ ERROR cannot infer
}
fn main() {
let x = return_it();
println!("foo={}", *x);
}
| return_it | identifier_name |
config.rs | strips out items that do not belong in the current configuration.
pub struct StripUnconfigured<'a> {
pub sess: &'a Session,
pub features: Option<&'a Features>,
/// If `true`, perform cfg-stripping on attached tokens.
/// This is only used for the input to derive macros,
/// which needs eager expans... | data.attrs = attrs.into();
if self.in_cfg(&data.attrs) {
data.tokens = LazyTokenStream::new(
self.configure_tokens(&data.tokens.create_token_stream()),
);
Some((AttrAnnotatedToken... | .iter()
.flat_map(|(tree, spacing)| match tree.clone() {
AttrAnnotatedTokenTree::Attributes(mut data) => {
let mut attrs: Vec<_> = std::mem::take(&mut data.attrs).into();
attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); | random_line_split |
config.rs | {
let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
err.span_label(span, "feature has been removed");
if let Some(reason) = reason {
err.note(reason);
}
err.emit();
}
fn active_features_up_to(edition: Edition) -> impl Ite... | {
for attr in expr.attrs.iter() {
self.maybe_emit_expr_attr_err(attr);
}
// If an expr is valid to cfg away it will have been removed by the
// outer stmt or expression folder before descending in here.
// Anything else is always required, and thus has to error out
... | identifier_body | |
config.rs | out items that do not belong in the current configuration.
pub struct StripUnconfigured<'a> {
pub sess: &'a Session,
pub features: Option<&'a Features>,
/// If `true`, perform cfg-stripping on attached tokens.
/// This is only used for the input to derive macros,
/// which needs eager expansion of ... |
let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
if let Some(Feature { state,.. }) = removed.or(stable_removed) {
if let FeatureState::Removed { reason } | FeatureState::Sta... | {
// Handled in the separate loop above.
continue;
} | conditional_block |
config.rs | let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
err.span_label(span, "feature has been removed");
if let Some(reason) = reason {
err.note(reason);
}
err.emit();
}
fn active_features_up_to(edition: Edition) -> impl Iterator<Item... | parse_cfg | identifier_name | |
resource_thread.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/. */
//! A thread that takes a URL and streams back the binary data.
use connector::{Connector, create_http_connector};... | }
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCache {
pub version: u32,
pub entries: HashMap<String, AuthCacheEntry>,
}
pub struct CoreResourceManager {
user_agent: Cow<'static, str>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
swmanager_chan: Option<IpcSender<Cust... | AuthCache {
version: 1,
entries: HashMap::new()
} | random_line_split |
resource_thread.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/. */
//! A thread that takes a URL and streams back the binary data.
use connector::{Connector, create_http_connector};... | (user_agent: Cow<'static, str>,
devtools_channel: Option<Sender<DevtoolsControlMsg>>,
_profiler_chan: ProfilerChan) -> CoreResourceManager {
CoreResourceManager {
user_agent: user_agent,
devtools_chan: devtools_channel,
swmanager_chan: None,
... | new | identifier_name |
resource_thread.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/. */
//! A thread that takes a URL and streams back the binary data.
use connector::{Connector, create_http_connector};... | });
let (toplevel, sublevel) = classifier.classify(context,
no_sniff,
check_for_apache_bug,
&supplied_type,
... | {
if PREFS.get("network.mime.sniff").as_boolean().unwrap_or(false) {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut no_sniff = NoSniffFlag::Off;
let mut check_for_apache_bug = ApacheBugFlag::Off;
if let Some(ref headers) = metadata.headers {
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.