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 |
|---|---|---|---|---|
easy.rs | use std::sync::{Once, ONCE_INIT};
use std::c_vec::CVec;
use std::{io,mem};
use std::collections::HashMap;
use libc::{c_void,c_int,c_long,c_double,size_t};
use super::{consts,err,info,opt};
use super::err::ErrCode;
use http::body::Body;
use http::{header,Response};
type CURL = c_void;
pub type ProgressCb<'a> = |uint, u... | return Err(res);
}
Ok(v)
}
}
#[inline]
fn global_init() {
// Schedule curl to be cleaned up after we're done with this whole process
static mut INIT: Once = ONCE_INIT;
unsafe {
INIT.doit(|| ::std::rt::at_exit(proc() curl_global_cleanup()))
}
}
impl Drop for Eas... |
if !res.is_success() { | random_line_split |
term.rs | use std::fmt;
use super::Field;
use byteorder::{BigEndian, ByteOrder};
use common;
use schema::Facet;
use std::str;
use DateTime;
/// Size (in bytes) of the buffer of a int field.
const INT_TERM_LEN: usize = 4 + 8;
/// Term represents the value that the token can take.
///
/// It actually wraps a `Vec<u8>`.
#[derive... |
/// Builds a term given a field, and a string value
///
/// Assuming the term has a field id of 2, and a text value of "abc",
/// the Term will have 4 bytes.
/// The first byte is 2, and the three following bytes are the utf-8
/// representation of "abc".
pub fn from_field_text(field: Fiel... | {
let bytes = facet.encoded_str().as_bytes();
let buffer = Vec::with_capacity(4 + bytes.len());
let mut term = Term(buffer);
term.set_field(field);
term.set_bytes(bytes);
term
} | identifier_body |
term.rs | use std::fmt;
use super::Field;
use byteorder::{BigEndian, ByteOrder};
use common;
use schema::Facet;
use std::str;
use DateTime;
/// Size (in bytes) of the buffer of a int field.
const INT_TERM_LEN: usize = 4 + 8;
/// Term represents the value that the token can take.
///
/// It actually wraps a `Vec<u8>`.
#[derive... | }
/// Returns the `u64` value stored in a term.
///
/// # Panics
///... or returns an invalid value
/// if the term is not a `u64` field.
pub fn get_u64(&self) -> u64 {
BigEndian::read_u64(&self.0.as_ref()[4..])
}
/// Returns the `i64` value stored in a term.
///
//... | random_line_split | |
term.rs | use std::fmt;
use super::Field;
use byteorder::{BigEndian, ByteOrder};
use common;
use schema::Facet;
use std::str;
use DateTime;
/// Size (in bytes) of the buffer of a int field.
const INT_TERM_LEN: usize = 4 + 8;
/// Term represents the value that the token can take.
///
/// It actually wraps a `Vec<u8>`.
#[derive... |
BigEndian::write_u32(&mut self.0[0..4], field.0);
}
/// Sets a u64 value in the term.
///
/// U64 are serialized using (8-byte) BigEndian
/// representation.
/// The use of BigEndian has the benefit of preserving
/// the natural order of the values.
pub fn set_u64(&mut self, va... | {
self.0.resize(4, 0u8);
} | conditional_block |
term.rs | use std::fmt;
use super::Field;
use byteorder::{BigEndian, ByteOrder};
use common;
use schema::Facet;
use std::str;
use DateTime;
/// Size (in bytes) of the buffer of a int field.
const INT_TERM_LEN: usize = 4 + 8;
/// Term represents the value that the token can take.
///
/// It actually wraps a `Vec<u8>`.
#[derive... | (&mut self, val: i64) {
self.set_u64(common::i64_to_u64(val));
}
fn set_bytes(&mut self, bytes: &[u8]) {
self.0.resize(4, 0u8);
self.0.extend(bytes);
}
pub(crate) fn from_field_bytes(field: Field, bytes: &[u8]) -> Term {
let mut term = Term::for_field(field);
te... | set_i64 | identifier_name |
freqs.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | 235, // 'u'
201, // 'v'
196, // 'w'
240, // 'x'
214, // 'y'
152, // 'z'
182, // '{'
205, // '|'
181, // '}'
127, // '~'
27, // '\x7f'
212, // '\x80'
211, // '\x81'
210, // '\x82'
213, // '\x83'
228, // '\x84'
197, // '\x85'
169, // '\x86'
159,... | 231, // 'p'
139, // 'q'
245, // 'r'
243, // 's'
251, // 't' | random_line_split |
select.rs | use super::{parse_index_range, Index, Range};
use std::{
iter::{empty, FromIterator},
str::FromStr,
};
/// Represents a filter on a vector-like object
#[derive(Debug, PartialEq, Clone)]
pub enum Select<K> {
/// Select all elements
All,
/// Select a single element based on its index | /// Select an element by mapped key
Key(K),
}
pub trait SelectWithSize {
type Item;
fn select<O, K>(&mut self, selection: &Select<K>, len: usize) -> O
where
O: FromIterator<Self::Item>;
}
impl<I, T> SelectWithSize for I
where
I: DoubleEndedIterator<Item = T>,
{
type Item = T;
... | Index(Index),
/// Select a range of elements
Range(Range), | random_line_split |
select.rs | use super::{parse_index_range, Index, Range};
use std::{
iter::{empty, FromIterator},
str::FromStr,
};
/// Represents a filter on a vector-like object
#[derive(Debug, PartialEq, Clone)]
pub enum Select<K> {
/// Select all elements
All,
/// Select a single element based on its index
Index(Index)... | <O, K>(&mut self, s: &Select<K>, size: usize) -> O
where
O: FromIterator<Self::Item>,
{
match s {
Select::Key(_) => empty().collect(),
Select::All => self.collect(),
Select::Index(Index::Forward(idx)) => self.nth(*idx).into_iter().collect(),
Select... | select | identifier_name |
select.rs | use super::{parse_index_range, Index, Range};
use std::{
iter::{empty, FromIterator},
str::FromStr,
};
/// Represents a filter on a vector-like object
#[derive(Debug, PartialEq, Clone)]
pub enum Select<K> {
/// Select all elements
All,
/// Select a single element based on its index
Index(Index)... |
}
impl<K: FromStr> FromStr for Select<K> {
type Err = ();
fn from_str(data: &str) -> Result<Self, ()> {
if data == ".." {
Ok(Select::All)
} else if let Ok(index) = data.parse::<isize>() {
Ok(Select::Index(Index::new(index)))
} else if let Some(range) = parse_in... | {
match s {
Select::Key(_) => empty().collect(),
Select::All => self.collect(),
Select::Index(Index::Forward(idx)) => self.nth(*idx).into_iter().collect(),
Select::Index(Index::Backward(idx)) => self.rev().nth(*idx).into_iter().collect(),
Select::Range... | identifier_body |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... | _ => {
return Err(ActionRunnerError::RequiredError(error::RequiredError(
format!("Could not find action {} in local registry", action),
)))
}
};
run_plugin(id, in_flight, plugin).await
}
... | {
match action {
Action::ActionCancel { id } => {
let _ = remove_in_flight(in_flight, &id)
.await
.map(|tx| tx.send(Ok(serde_json::Value::Null)));
Ok(Ok(serde_json::Value::Null))
}
Action::ActionStart { id, action, args } => {
... | identifier_body |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... | (
id: ActionId,
in_flight: SharedLocalActionsInFlight,
fut: impl Future<Output = Result<Value, String>> + Send +'static,
) -> Result<Result<serde_json::value::Value, String>, ActionRunnerError> {
let rx = add_in_flight(Arc::clone(&in_flight), id.clone()).await;
spawn_plugin(fut, in_flight, id);
... | run_plugin | identifier_name |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... | /// Removes an action id from the in-flight list.
///
/// Returns the tx handle which can then be used to cancel the action if needed.
async fn remove_in_flight(
in_flight: SharedLocalActionsInFlight,
id: &ActionId,
) -> Option<oneshot::Sender<Result<Value, String>>> {
let mut in_flight = in_flight.lock().a... | }
| random_line_split |
local_actions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
data::{await_next_session, get_session},
db,
error::{self, ActionRunnerError},
Sender, Sessions, Shared,
};
use futures::{channel::oneshot... |
};
run_plugin(id, in_flight, plugin).await
}
}
}
| {
return Err(ActionRunnerError::RequiredError(error::RequiredError(
format!("Could not find action {} in local registry", action),
)))
} | conditional_block |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... | // a match is impossible.
let aligned_rare2i = i - rare1i + rare2i;
if haystack.get(aligned_rare2i)!= Some(&rare2) {
i += 1;
continue;
}
// We've done what we can. There might be a match here.
return Some(i - rare1i);
}
// The only way we ... | {
let mut i = 0;
let (rare1i, rare2i) = ninfo.rarebytes.as_rare_usize();
let (rare1, rare2) = ninfo.rarebytes.as_rare_bytes(needle);
while prestate.is_effective() {
// Use a fast vectorized implementation to skip to the next
// occurrence of the rarest byte (heuristically chosen) in the
... | identifier_body |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... |
// We've done what we can. There might be a match here.
return Some(i - rare1i);
}
// The only way we get here is if we believe our skipping heuristic
// has become ineffective. We're allowed to return false positives,
// so return the position at which we advanced to, aligned to the
... | {
i += 1;
continue;
} | conditional_block |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... |
// Check that the functions below satisfy the Prefilter function type.
const _: PrefilterFnTy = find;
/// Look for a possible occurrence of needle. The position returned
/// corresponds to the beginning of the occurrence, if one exists.
///
/// Callers may assume that this never returns false negatives (i.e., it
/// ... |
use crate::memmem::{
prefilter::{PrefilterFnTy, PrefilterState},
NeedleInfo,
}; | random_line_split |
fallback.rs | /*
This module implements a "fallback" prefilter that only relies on memchr to
function. While memchr works best when it's explicitly vectorized, its
fallback implementations are fast enough to make a prefilter like this
worthwhile.
The essence of this implementation is to identify two rare bytes in a needle
based on ... | (
prestate: &mut PrefilterState,
ninfo: &NeedleInfo,
haystack: &[u8],
needle: &[u8],
) -> Option<usize> {
let mut i = 0;
let (rare1i, rare2i) = ninfo.rarebytes.as_rare_usize();
let (rare1, rare2) = ninfo.rarebytes.as_rare_bytes(needle);
while prestate.is_effective() {
// Use a fa... | find | identifier_name |
branch_implpermissions.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct Branc... | () -> BranchImplpermissions {
BranchImplpermissions {
create: None,
read: None,
start: None,
stop: None,
_class: None,
}
}
}
| new | identifier_name |
branch_implpermissions.rs | /*
* Swaggy Jenkins | * Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct BranchImplpermissions {
#... | * | random_line_split |
log.rs | /* Copyright (C) 2018 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... |
js.set_integer("errors", tx.errors as u64);
let jsa = Json::array();
for payload in tx.payload_types.iter() {
jsa.array_append_string(&format!("{:?}", payload));
}
js.set("payload", jsa);
let jsa = Json::array();
for notify in tx.notify_types.iter() {
jsa.array_append_string... | {
js.set_string("role", &"responder");
js.set_string("alg_enc", &format!("{:?}", state.alg_enc));
js.set_string("alg_auth", &format!("{:?}", state.alg_auth));
js.set_string("alg_prf", &format!("{:?}", state.alg_prf));
js.set_string("alg_dh", &format!("{:?}", state.alg_dh));
... | conditional_block |
log.rs | /* Copyright (C) 2018 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... | } | return js.unwrap(); | random_line_split |
log.rs | /* Copyright (C) 2018 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... | for payload in tx.payload_types.iter() {
jsa.array_append_string(&format!("{:?}", payload));
}
js.set("payload", jsa);
let jsa = Json::array();
for notify in tx.notify_types.iter() {
jsa.array_append_string(&format!("{:?}", notify));
}
js.set("notify", jsa);
return js.unw... | {
let js = Json::object();
js.set_integer("version_major", tx.hdr.maj_ver as u64);
js.set_integer("version_minor", tx.hdr.min_ver as u64);
js.set_integer("exchange_type", tx.hdr.exch_type.0 as u64);
js.set_integer("message_id", tx.hdr.msg_id as u64);
js.set_string("init_spi", &format!("{:016x}",... | identifier_body |
log.rs | /* Copyright (C) 2018 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... | (state: &mut IKEV2State, tx: &mut IKEV2Transaction) -> *mut JsonT
{
let js = Json::object();
js.set_integer("version_major", tx.hdr.maj_ver as u64);
js.set_integer("version_minor", tx.hdr.min_ver as u64);
js.set_integer("exchange_type", tx.hdr.exch_type.0 as u64);
js.set_integer("message_id", tx.hdr... | rs_ikev2_log_json_response | identifier_name |
lib.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Types for loading and managing AWS access credentials for API requests.
extern crate chrono;
extern crate reqwest;
extern crate regex;
extern... | (provider: P) -> Result<AutoRefreshingProviderSync<P>, CredentialsError> {
let creds = try!(provider.credentials());
Ok(BaseAutoRefreshingProvider {
credentials_provider: provider,
cached_credentials: Mutex::new(creds)
})
}
}
impl <P: ProvideAwsCredentials> ProvideAw... | with_mutex | identifier_name |
lib.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Types for loading and managing AWS access credentials for API requests.
extern crate chrono;
extern crate reqwest;
extern crate regex;
extern... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credential_chain_explicit_profile_provider() {
let profile_provider = ProfileProvider::with_configuration(
"tests/sample-data/multiple_profile_credentials",
"foo",
);
let chain = ChainProvider::with_profile... | {
match json_object.get(key) {
Some(v) => Ok(v.as_str().expect(&format!("{} value was not a string", key)).to_owned()),
None => Err(CredentialsError::new(format!("Couldn't find {} in response.", key))),
}
} | identifier_body |
lib.rs | #![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(not(feature = "unstable"), deny(warnings))]
//! Types for loading and managing AWS access credentials for API requests.
extern crate chrono;
extern crate reqwest;
extern crate regex;
extern... | &self.token
}
/// Determine whether or not the credentials are expired.
fn credentials_are_expired(&self) -> bool {
// This is a rough hack to hopefully avoid someone requesting creds then sitting on them
// before issuing the request:
self.expires_at < UTC::now() + Duration... |
/// Get a reference to the access token.
pub fn token(&self) -> &Option<String> { | random_line_split |
cache_repair.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::input_arg::*;
use common::output_option::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: &str = concat!(
"cache_repair ",
include... |
}
impl<'a> OutputProgram<'a> for CacheRepair {
fn missing_output_arg() -> &'a str {
msg::MISSING_OUTPUT_ARG
}
}
impl<'a> MetadataWriter<'a> for CacheRepair {
fn file_not_found() -> &'a str {
msg::FILE_NOT_FOUND
}
}
//-----------------------------------------
test_accepts_help!(Cache... | {
"bad checksum in superblock"
} | identifier_body |
cache_repair.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::input_arg::*;
use common::output_option::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: &str = concat!(
"cache_repair ",
include... | impl<'a> OutputProgram<'a> for CacheRepair {
fn missing_output_arg() -> &'a str {
msg::MISSING_OUTPUT_ARG
}
}
impl<'a> MetadataWriter<'a> for CacheRepair {
fn file_not_found() -> &'a str {
msg::FILE_NOT_FOUND
}
}
//-----------------------------------------
test_accepts_help!(CacheRepa... | "bad checksum in superblock"
}
}
| random_line_split |
cache_repair.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::input_arg::*;
use common::output_option::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: &str = concat!(
"cache_repair ",
include... | () -> &'a str {
msg::FILE_NOT_FOUND
}
fn missing_input_arg() -> &'a str {
msg::MISSING_INPUT_ARG
}
fn corrupted_input() -> &'a str {
"bad checksum in superblock"
}
}
impl<'a> OutputProgram<'a> for CacheRepair {
fn missing_output_arg() -> &'a str {
msg::MISSING_... | file_not_found | identifier_name |
arena.rs |
// 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 accordi... |
}
#[cfg(test)]
mod test {
use super::{Arena, TypedArena};
use test::BenchHarness;
struct Point {
x: int,
y: int,
z: int,
}
#[test]
pub fn test_pod() {
let arena = TypedArena::new();
for _ in range(0, 1000000) {
arena.alloc(Point {
... | {
// Determine how much was filled.
let start = self.first.get_ref().start(self.tydesc) as uint;
let end = self.ptr as uint;
let diff = (end - start) / mem::size_of::<T>();
// Pass that to the `destroy` method.
unsafe {
let opt_tydesc = if intrinsics::needs_d... | identifier_body |
arena.rs | 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 acco... |
// Walk down a chunk, running the destructors for any objects stored
// in it.
unsafe fn destroy_chunk(chunk: &Chunk) {
let mut idx = 0;
let buf = {
let data = chunk.data.borrow();
data.get().as_ptr()
};
let fill = chunk.fill.get();
while idx < fill {
let tydesc_data: *uint... | } | random_line_split |
arena.rs |
// 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 accordi... | () {
let arena = TypedArena::new();
for _ in range(0, 1000000) {
arena.alloc(Point {
x: 1,
y: 2,
z: 3,
});
}
}
#[bench]
pub fn bench_pod(bh: &mut BenchHarness) {
let arena = TypedArena::new();
bh... | test_pod | identifier_name |
arena.rs |
// 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 accordi... |
this.pod_head.fill.set(end);
//debug!("idx = {}, size = {}, align = {}, fill = {}",
// start, n_bytes, align, head.fill.get());
ptr::offset(this.pod_head.data.get().as_ptr(), start as int)
}
}
#[inline]
fn alloc_pod<'a, T>(&'a mut self, op: |... | {
return this.alloc_pod_grow(n_bytes, align);
} | conditional_block |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... | cluster.must_split(&r3, b"k2");
let r4 = cluster.get_region(b"k3");
cluster.must_split(&r4, b"k3");
}
let split_regions = dump(c);
check_region_ranges(
&split_regions,
&[
(&b""[..], &b"k1"[..]),
(b"k1", b"k2"),
(b"k2", b"k3"),
... | {
for i in 0..9 {
let k = format!("k{}", i).into_bytes();
let v = format!("v{}", i).into_bytes();
cluster.must_put(&k, &v);
}
let pd_client = Arc::clone(&cluster.pd_client);
let init_regions = dump(c);
check_region_ranges(&init_regions, &[(&b""[..], &b""[..])]);
assert_... | identifier_body |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... | (regions: &[(Region, StateRole)], ranges: &[(&[u8], &[u8])]) {
assert_eq!(regions.len(), ranges.len());
regions
.iter()
.zip(ranges.iter())
.for_each(|((r, _), (start_key, end_key))| {
assert_eq!(r.get_start_key(), *start_key);
assert_eq!(r.get_end_key(), *end_key);
... | check_region_ranges | identifier_name |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... |
thread::sleep(Duration::from_millis(20));
}
check_region_ranges(
®ions_after_removing,
&[(&b""[..], &b"k1"[..]), (b"k4", b"")],
);
}
#[test]
fn test_node_cluster_region_info_accessor() {
let mut cluster = new_node_cluster(1, 3);
configure_for_merge(&mut cluster);
le... | {
break;
} | conditional_block |
test_region_info_accessor.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use keys::data_end_key;
use kvproto::metapb::Region;
use raft::StateRole;
use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor};
use raftstore::store::util::{find_peer, new_peer};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread... | drop(cluster);
c.stop();
} | random_line_split | |
codemap.rs | EXPANSION };
// Generic span to be used for code originating from the command line
pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
hi: BytePos(0),
expn_id: COMMAND_LINE_EXPN };
#[derive(Clone, PartialEq, Eq, RustcEncodable, Rus... |
pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
let idx = self.lookup_filemap_idx(bpos);
let fm = (*self.files.borrow())[idx].clone();
let offset = bpos - fm.start_pos;
FileMapAndBytePos {fm: fm, pos: offset}
}
/// Converts an absolute BytePos to a C... | {
for fm in self.files.borrow().iter() {
if filename == fm.name {
return fm.clone();
}
}
panic!("asking for {} which we don't know about", filename);
} | identifier_body |
codemap.rs | EXPANSION };
// Generic span to be used for code originating from the command line
pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
hi: BytePos(0),
expn_id: COMMAND_LINE_EXPN };
#[derive(Clone, PartialEq, Eq, RustcEncodable, Rus... | <D: Decoder>(_d: &mut D) -> Result<Span, D::Error> {
Ok(DUMMY_SP)
}
}
pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
respan(mk_sp(lo, hi), t)
}
pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
Spanned {node: t, span: sp}
}
pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
respa... | decode | identifier_name |
codemap.rs | /// with this Span.
pub name: String,
/// The format with which the macro was invoked.
pub format: MacroFormat,
/// The span of the macro definition itself. The macro may not
/// have a sensible definition span (e.g. something defined
/// completely inside libsyntax) in which case this is No... |
let loc2 = cm.lookup_char_pos(BytePos(24));
assert_eq!(loc2.file.name, "blork2.rs"); | random_line_split | |
test_nmount.rs | use crate::*;
use nix::{
errno::Errno,
mount::{MntFlags, Nmount, unmount}
};
use std::{
ffi::CString, | path::Path
};
use tempfile::tempdir;
#[test]
fn ok() {
require_mount!("nullfs");
let mountpoint = tempdir().unwrap();
let target = tempdir().unwrap();
let _sentry = File::create(target.path().join("sentry")).unwrap();
let fstype = CString::new("fstype").unwrap();
let nullfs = CString::new... | fs::File, | random_line_split |
test_nmount.rs | use crate::*;
use nix::{
errno::Errno,
mount::{MntFlags, Nmount, unmount}
};
use std::{
ffi::CString,
fs::File,
path::Path
};
use tempfile::tempdir;
#[test]
fn | () {
require_mount!("nullfs");
let mountpoint = tempdir().unwrap();
let target = tempdir().unwrap();
let _sentry = File::create(target.path().join("sentry")).unwrap();
let fstype = CString::new("fstype").unwrap();
let nullfs = CString::new("nullfs").unwrap();
Nmount::new()
.str_opt(... | ok | identifier_name |
test_nmount.rs | use crate::*;
use nix::{
errno::Errno,
mount::{MntFlags, Nmount, unmount}
};
use std::{
ffi::CString,
fs::File,
path::Path
};
use tempfile::tempdir;
#[test]
fn ok() {
require_mount!("nullfs");
let mountpoint = tempdir().unwrap();
let target = tempdir().unwrap();
let _sentry = File:... | {
let mountpoint = tempdir().unwrap();
let target = tempdir().unwrap();
let _sentry = File::create(target.path().join("sentry")).unwrap();
let e = Nmount::new()
.str_opt_owned("fspath", mountpoint.path().to_str().unwrap())
.str_opt_owned("target", target.path().to_str().unwrap())
... | identifier_body | |
x86_64.rs | #![allow(unused_imports)]
use core::intrinsics;
// NOTE These functions are implemented using assembly because they using a custom
// calling convention which can't be implemented using a normal Rust function
| // NOTE These functions are never mangled as they are not tested against compiler-rt
// and mangling ___chkstk would break the `jmp ___chkstk` instruction in __alloca
#[cfg(all(windows, target_env = "gnu", not(feature = "mangled-names")))]
#[naked]
#[no_mangle]
pub unsafe fn ___chkstk_ms() {
asm!("
push ... | random_line_split | |
x86_64.rs | #![allow(unused_imports)]
use core::intrinsics;
// NOTE These functions are implemented using assembly because they using a custom
// calling convention which can't be implemented using a normal Rust function
// NOTE These functions are never mangled as they are not tested against compiler-rt
// and mangling ___chks... | }
#[cfg(all(windows, target_env = "gnu", not(feature = "mangled-names")))]
#[naked]
#[no_mangle]
pub unsafe fn __alloca() {
asm!("mov %rcx,%rax // x64 _alloca is a normal function with parameter in rcx
jmp ___chkstk // Jump to ___chkstk since fallthrough may be unreliable"
::: "memory" ... | {
asm!("
push %rcx
push %rax
cmp $$0x1000,%rax
lea 24(%rsp),%rcx
jb 1f
2:
sub $$0x1000,%rcx
test %rcx,(%rcx)
sub $$0x1000,%rax
cmp $$0x1000,%rax
ja 2b
1:
sub %rax,%rcx
test %rcx,... | identifier_body |
x86_64.rs | #![allow(unused_imports)]
use core::intrinsics;
// NOTE These functions are implemented using assembly because they using a custom
// calling convention which can't be implemented using a normal Rust function
// NOTE These functions are never mangled as they are not tested against compiler-rt
// and mangling ___chks... | () {
asm!("mov %rcx,%rax // x64 _alloca is a normal function with parameter in rcx
jmp ___chkstk // Jump to ___chkstk since fallthrough may be unreliable"
::: "memory" : "volatile");
intrinsics::unreachable();
}
#[cfg(all(windows, target_env = "gnu", not(feature = "mangled-names")))]... | __alloca | identifier_name |
Slice.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::raw::Slice;
use core::raw::Repr;
// pub unsafe trait Repr<T> {
// /// This function "unwraps" a rust value (without consuming it) into its raw
// /// struct representation. This can be used to read/write different valu... | () {
let slice: &[T] = &[1, 2, 3, 4];
let repr: Slice<T> = slice.repr();
assert_eq!(repr.len, 4);
}
#[test]
fn slice_test2 () {
let slice: &[T] = &[1, 2, 3, 4];
let repr: Slice<T> = slice.repr();
let copy: &[T] = slice;
let copy_repr: Slice<T> = copy.repr();
assert_eq!(copy_repr.data, repr.data... | slice_test1 | identifier_name |
Slice.rs | #[cfg(test)]
mod tests {
use core::raw::Slice;
use core::raw::Repr;
// pub unsafe trait Repr<T> {
// /// This function "unwraps" a rust value (without consuming it) into its raw
// /// struct representation. This can be used to read/write different values
// /// for the struct. This... | #![feature(core)]
extern crate core;
| random_line_split | |
Slice.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::raw::Slice;
use core::raw::Repr;
// pub unsafe trait Repr<T> {
// /// This function "unwraps" a rust value (without consuming it) into its raw
// /// struct representation. This can be used to read/write different valu... |
}
| {
let slice: &[T] = &[1, 2, 3, 4];
let repr: Slice<T> = slice.repr();
let copy: &[T] = slice;
let copy_repr: Slice<T> = copy.repr();
assert_eq!(copy_repr.data, repr.data);
assert_eq!(copy_repr.len, repr.len);
} | identifier_body |
test_socket.rs | use nix::sys::socket::{InetAddr, UnixAddr, getsockname};
use std::{mem, net};
use std::path::Path;
use std::str::FromStr;
use std::os::unix::io::AsRawFd;
use ports::localhost;
#[test]
pub fn test_inetv4_addr_to_sock_addr() {
let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap();
let addr =... | }
_ => panic!("nope"),
}
assert_eq!(addr.to_str(), "127.0.0.1:3000");
let inet = addr.to_std();
assert_eq!(actual, inet);
}
#[test]
pub fn test_path_to_sock_addr() {
let actual = Path::new("/foo/bar");
let addr = UnixAddr::new(actual).unwrap();
let expect: &'static [i8] =... |
assert_eq!(addr.sin_addr.s_addr, ip.to_be());
assert_eq!(addr.sin_port, port.to_be()); | random_line_split |
test_socket.rs | use nix::sys::socket::{InetAddr, UnixAddr, getsockname};
use std::{mem, net};
use std::path::Path;
use std::str::FromStr;
use std::os::unix::io::AsRawFd;
use ports::localhost;
#[test]
pub fn test_inetv4_addr_to_sock_addr() {
let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap();
let addr =... | () {
use std::net::TcpListener;
let addr = localhost();
let sock = TcpListener::bind(&*addr).unwrap();
let res = getsockname(sock.as_raw_fd()).unwrap();
assert_eq!(addr, res.to_str());
}
| test_getsockname | identifier_name |
test_socket.rs | use nix::sys::socket::{InetAddr, UnixAddr, getsockname};
use std::{mem, net};
use std::path::Path;
use std::str::FromStr;
use std::os::unix::io::AsRawFd;
use ports::localhost;
#[test]
pub fn test_inetv4_addr_to_sock_addr() {
let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap();
let addr =... | {
use std::net::TcpListener;
let addr = localhost();
let sock = TcpListener::bind(&*addr).unwrap();
let res = getsockname(sock.as_raw_fd()).unwrap();
assert_eq!(addr, res.to_str());
} | identifier_body | |
weight.rs | //! Provides configuration of weights and their initialization.
use capnp_util::*;
use co::{ITensorDesc, SharedTensor};
use juice_capnp::weight_config as capnp_config;
use rand;
use rand::distributions::{IndependentSample, Range};
use util::native_backend;
#[derive(Debug, Clone)]
/// Specifies training configuration ... | (&self) -> f32 {
match self.lr_mult {
Some(val) => val,
None => 1.0f32,
}
}
/// The multiplier on the global weight decay for this weight blob.
pub fn decay_mult(&self) -> f32 {
match self.decay_mult {
Some(val) => val,
None => 1.0f32,... | lr_mult | identifier_name |
weight.rs | //! Provides configuration of weights and their initialization.
use capnp_util::*;
use co::{ITensorDesc, SharedTensor};
use juice_capnp::weight_config as capnp_config;
use rand;
use rand::distributions::{IndependentSample, Range}; | /// The name of the weight blob -- useful for sharing weights among
/// layers, but never required otherwise. To share a weight between two
/// layers, give it a (non-empty) name.
///
/// Default: ""
pub name: String,
/// Whether to require shared weights to have the same shape, or just the ... | use util::native_backend;
#[derive(Debug, Clone)]
/// Specifies training configuration for a weight blob.
pub struct WeightConfig { | random_line_split |
weight.rs | //! Provides configuration of weights and their initialization.
use capnp_util::*;
use co::{ITensorDesc, SharedTensor};
use juice_capnp::weight_config as capnp_config;
use rand;
use rand::distributions::{IndependentSample, Range};
use util::native_backend;
#[derive(Debug, Clone)]
/// Specifies training configuration ... |
}
impl<'a> CapnpWrite<'a> for WeightConfig {
type Builder = capnp_config::Builder<'a>;
/// Write the WeightConfig into a capnp message.
fn write_capnp(&self, builder: &mut Self::Builder) {
// TODO: incomplete since WeightConfig isn't really used internally in Juice at the moment.
builder.... | {
match self.decay_mult {
Some(val) => val,
None => 1.0f32,
}
} | identifier_body |
keyboard.rs | use libc::{c_int, c_char, uint8_t, uint16_t, | use keycode::{SDL_Keycode, SDL_Keymod};
pub type SDL_bool = c_int;
// SDL_keyboard.h
#[derive(Copy, Clone)]
pub struct SDL_Keysym {
pub scancode: SDL_Scancode,
pub sym: SDL_Keycode,
pub _mod: uint16_t,
pub unused: uint32_t,
}
extern "C" {
pub fn SDL_GetKeyboardFocus() -> *mut SDL_Window;
pub ... | uint32_t};
use rect::SDL_Rect;
use video::SDL_Window;
use scancode::SDL_Scancode; | random_line_split |
keyboard.rs | use libc::{c_int, c_char, uint8_t, uint16_t,
uint32_t};
use rect::SDL_Rect;
use video::SDL_Window;
use scancode::SDL_Scancode;
use keycode::{SDL_Keycode, SDL_Keymod};
pub type SDL_bool = c_int;
// SDL_keyboard.h
#[derive(Copy, Clone)]
pub struct | {
pub scancode: SDL_Scancode,
pub sym: SDL_Keycode,
pub _mod: uint16_t,
pub unused: uint32_t,
}
extern "C" {
pub fn SDL_GetKeyboardFocus() -> *mut SDL_Window;
pub fn SDL_GetKeyboardState(numkeys: *mut c_int) -> *const uint8_t;
pub fn SDL_GetModState() -> SDL_Keymod;
pub fn SDL_SetModSt... | SDL_Keysym | identifier_name |
tag-align-shape.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 x = t_rec {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
debug!("y = %s", y);
assert_eq!(y, ~"{c8: 22, t: a_tag(44)}");
} | identifier_body | |
tag-align-shape.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_tag(u64)
}
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
debug!("y = %s", y);
assert_eq!(y, ~"{c8: 22, t: a_tag(44)}");
} |
enum a_tag { | random_line_split |
tag-align-shape.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_tag(u64)
}
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
debug!("y = %s", y);
assert_eq!(y, ~"{c8: 22, t: a_tag(44)}");
}
| a_tag | identifier_name |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// ANCHOR: here
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool |
}
// ANCHOR_END: here
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect... | {
self.width > other.width && self.height > other.height
} | identifier_body |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32, | impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
// ANCHOR_END: here
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
l... | }
// ANCHOR: here | random_line_split |
main.rs | #[derive(Debug)]
struct | {
width: u32,
height: u32,
}
// ANCHOR: here
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
// ANCHOR_END: here
fn main() {
let rect1 = Rectangl... | Rectangle | identifier_name |
builtin-superkinds-capabilities.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 | // except according to those terms.
// Tests "capabilities" granted by traits that inherit from super-
// builtin-kinds, e.g., if a trait requires Send to implement, then
// at usage site of that trait, we know we have the Send capability.
trait Foo : Send { }
impl <T: Send> Foo for T { }
fn foo<T: Foo>(val: T, cha... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
builtin-superkinds-capabilities.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 (tx, rx): (Sender<int>, Receiver<int>) = channel();
foo(31337i, tx);
assert!(rx.recv() == 31337i);
}
| main | identifier_name |
builtin-superkinds-capabilities.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 (tx, rx): (Sender<int>, Receiver<int>) = channel();
foo(31337i, tx);
assert!(rx.recv() == 31337i);
} | identifier_body | |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... |
hbse.handlebars_mut().register_helper(
"some_helper",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
let mut ro... | {
panic!("{}", r);
} | conditional_block |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... | pts: 12u16,
},
];
data.insert("teams".to_string(), to_json(&teams));
data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
data
}
}
use data::*;
/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
let mut resp = Res... | {
let mut data = Map::new();
data.insert("year".to_string(), to_json(&"2015".to_owned()));
let teams = vec![
Team {
name: "Jiangsu Sainty".to_string(),
pts: 43u16,
},
Team {
name: "Beijing Guoan".to_string(),
... | identifier_body |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... | // an example compression middleware
pub struct GzMiddleware;
impl AfterMiddleware for GzMiddleware {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let compressed_bytes = resp.body.as_mut().map(|b| {
let mut encoder = GzEncoder::new(Vec::new(), Compression::Best... | random_line_split | |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... | (_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::with(
include_str!("templates/some/path/hello.hbs"),
data,
))
.set_mut(status::Ok);
Ok(resp)
}
fn plain(_: &mut Request) -> IronResult<Response> {
Ok(Res... | temp | identifier_name |
mips.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
abi::OsWindows => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"E-p:32:32:32\
... | {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:... | identifier_body |
mips.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
... | {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
} | conditional_block |
mips.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | },
target_triple: target_triple,
cc_args: Vec::new(),
};
} | -f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
} | random_line_split |
mips.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:6... | get_target_strs | identifier_name |
handlers.rs | //! Handlers for the server.
use std::collections::BTreeMap;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use iron::{status, headers, middleware};
use iron::modifiers::Header;
use router::Router;
use redis::ConnectionInfo;
use urlencoded;
use ::api;
use ::api::optional::Optional;
use ::sensors;
... | // Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any))
}
}
impl middleware::Handler for Updat... | /// Build an error response with the specified `error_code` and the specified `reason` text.
fn err_response(&self, error_code: status::Status, reason: &str) -> Response {
let error = ErrorResponse { reason: reason.to_string() };
Response::with((error_code, error.to_json().to_string())) | random_line_split |
handlers.rs | //! Handlers for the server.
use std::collections::BTreeMap;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use iron::{status, headers, middleware};
use iron::modifiers::Header;
use router::Router;
use redis::ConnectionInfo;
use urlencoded;
use ::api;
use ::api::optional::Optional;
use ::sensors;
... | (&self, error_code: status::Status, reason: &str) -> Response {
let error = ErrorResponse { reason: reason.to_string() };
Response::with((error_code, error.to_json().to_string()))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))... | err_response | identifier_name |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
| // 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.
// STD Dependencies... | random_line_split | |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 accordi... | (&mut self) {
// Actual time taken by the tick
let time_taken = nanos_from_duration(self.tick_start.elapsed());
// Required delay reduction to keep tick rate
let mut reduction = cmp::min(time_taken, self.tick_delay);
if self.tick_overflow_recovery {
// Keep track ... | end_tick | identifier_name |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 accordi... |
pub fn set_config(&mut self, config: Config) {
self.tick_overflow_recovery = config.tick_overflow_recovery;
self.tick_overflow_recovery_rate = config.tick_overflow_recovery_rate;
self.tick_delay = 1000000000 / config.send_rate
}
pub fn begin_tick(&mut self) {
self.tick_sta... | {
Ticker {
tick_start: Instant::now(),
tick_overflow: 0,
tick_overflow_recovery: config.tick_overflow_recovery,
tick_overflow_recovery_rate: config.tick_overflow_recovery_rate,
tick_delay: 1000000000 / config.send_rate
}
} | identifier_body |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 accordi... | // Update remaining overflow
self.tick_overflow = reduced_overflow;
}
thread::sleep(Duration::new(0, (self.tick_delay - reduction) as u32));
}
}
// Helpers ---------------------------------------------------------------------
fn nanos_from_duration(d: Duration) -> u64 {... | {
// Keep track of how much additional time the current tick required
self.tick_overflow += time_taken - reduction;
// Try to reduce the existing overflow by reducing the reduction time
// for the current frame.
let max_correction = (self.tick_delay - reduct... | conditional_block |
cpuid.rs |
use std::str;
use std::slice;
use std::mem;
use byteorder::{LittleEndian, WriteBytesExt};
const VENDOR_INFO: u32 = 0x0;
const FEATURE_INFO: u32 = 0x1;
const EXT_FEATURE_INFO: u32 = 0x7;
const EXT_PROCESSOR_INFO: u32 = 0x80000001;
#[cfg(target_arch = "x86_64")]
pub fn cpuid(func: u32) -> CpuIdInfo {
let (rax, rb... | {
pub highest_func_param: u32,
pub vendor_info: CpuIdInfo,
pub feature_info: CpuIdInfo,
pub ext_feature_info: CpuIdInfo,
pub ext_processor_info: CpuIdInfo
}
impl CpuId {
pub fn detect() -> CpuId {
CpuId {
highest_func_param: cpuid(VENDOR_INFO).rax,
vendor_info:... | CpuId | identifier_name |
cpuid.rs | use std::str;
use std::slice;
use std::mem;
use byteorder::{LittleEndian, WriteBytesExt};
const VENDOR_INFO: u32 = 0x0;
const FEATURE_INFO: u32 = 0x1;
const EXT_FEATURE_INFO: u32 = 0x7;
const EXT_PROCESSOR_INFO: u32 = 0x80000001;
#[cfg(target_arch = "x86_64")]
pub fn cpuid(func: u32) -> CpuIdInfo {
let (rax, rbx... | pub rcx: u32,
pub rdx: u32,
}
pub struct CpuId {
pub highest_func_param: u32,
pub vendor_info: CpuIdInfo,
pub feature_info: CpuIdInfo,
pub ext_feature_info: CpuIdInfo,
pub ext_processor_info: CpuIdInfo
}
impl CpuId {
pub fn detect() -> CpuId {
CpuId {
highest_func_... | random_line_split | |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
... |
}
Ok((pos, completions))
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
line.update(elected, start);
}
}
impl rustyline::hint::Hinter for CustomCompletion {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline... | {
completions.push(command.to_string());
} | conditional_block |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
| hinter: rustyline::hint::HistoryHinter {},
}
}
}
impl rustyline::completion::Completer for CustomCompletion {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usi... | let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
commands,
| random_line_split |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
... | () {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
}
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "pro... | completion_test_help | identifier_name |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
... |
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "projs");
}
| {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
} | identifier_body |
windows.rs |
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ... | (&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for FileMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
| as_ref | identifier_name |
windows.rs |
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ... |
// Create the memory file mapping
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY, 0, 0, ptr::null());
CloseHandle(file);
if map == NULL {
return Err(io::Error::last_os_error());
}
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if view == ptr::null_m... | {
return Err(io::Error::last_os_error());
} | conditional_block |
windows.rs | use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ,... | CloseHandle(self.handle);
}
}
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> +?Sized>(path: &P) -> io::Result<FileMap> {
uns... | }
impl Drop for ImageMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID); | random_line_split |
windows.rs |
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ... |
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> +?Sized>(path: &P) -> io::Result<FileMap> {
unsafe { Self::_open(path.as_ref()) }
... | {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
} | identifier_body |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... | (&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.current_battle = Some(Bat... | accept_quest | identifier_name |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... | return &self.username;
}
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: E... | PlayerState { username: username, accepted_quests: vec![], current_battle: None }
}
pub fn username(&self) -> &String { | random_line_split |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... |
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.cu... | {
return &self.username;
} | identifier_body |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... | else {
BattleState::Fight(self.current_battle.as_ref().unwrap())
}
}
}
pub type TsPlayerState = Ts<PlayerState>;
impl<'a, 'r> FromRequest<'a, 'r> for TsPlayerState {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<TsPlayerState, ()> {
let cookies = request.... | {
let enemy_id = self.current_battle.as_mut().unwrap().enemy.id;
self.on_enemy_killed(enemy_id);
self.current_battle = None;
BattleState::End(BattleReward{})
} | conditional_block |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | (pizza_order_form: Form<PizzaOrder>, database: State<PizzaOrderDatabase>) -> Result<Redirect, Failure> {
let pizza_order = pizza_order_form.get();
let pizza_name = &pizza_order.name;
let pizzas: Vec<String> = PIZZAS.iter().map(|p| p.to_string().to_lowercase()).collect();
if pizzas.contains(&pizza_name.to_lo... | order_pizza | identifier_name |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | fn show_pizza_ordered(order_id: String, database: State<PizzaOrderDatabase>) -> Result<Template, Failure> {
match Uuid::parse_str(order_id.as_str()) {
Ok(order_id) => {
match database.lock().unwrap().get(&order_id) {
Some(..) => {
let mut context = HashMap::new();
... | Template::render("pizza_menu", &context)
}
#[get("/pizza/order/<order_id>")] | random_line_split |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | ,
None => {
println!("Pizza order id not found: {}", &order_id);
Err(Failure(Status::NotFound))
}
}
},
Err(..) => {
println!("Pizza order id not valid: {}", &order_id);
Err(Failure(Status::NotFound))
},
}
}
#[derive(... | {
let mut context = HashMap::new();
context.insert("order_id", order_id);
Ok(Template::render("pizza_ordered", &context))
} | conditional_block |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | {
mount_rocket().launch();
} | identifier_body | |
udp-multicast.rs | use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr};
fn | () {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000;
let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_... | main | identifier_name |
udp-multicast.rs | use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr}; | let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group");
socket... |
fn main() {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.