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 |
|---|---|---|---|---|
monad.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn main() {
assert_eq!(transform(Some(10)), Some("11".to_string()));
assert_eq!(transform(None), None);
assert!((vec!("hi".to_string()))
.bind(|x| vec!(x.clone(), format!("{}!", x)) )
.bind(|x| vec!(x.clone(), format!("{}?", x)) ) ==
vec!("hi".to_string(),
"hi?".to_s... | {
x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) )
} | identifier_body |
monad.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> {
let mut r = Vec::new();
for elt in self.iter() {
r.extend(f(elt).into_iter());
}
r
}
}
trait option_monad<A> {
fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>;
}
imp... | }
impl<A> vec_monad<A> for Vec<A> { | random_line_split |
monad.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
}
}
fn transform(x: Option<int>) -> Option<String> {
x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) )
}
pub fn main() {
assert_eq!(transform(Some(10)), Some("11".to_string()));
assert_eq!(transform(None), None);
assert!((vec!("hi".to_string()))
.bind(|x| vec!(x.clone(), f... | { None } | conditional_block |
gecko_selector_impl.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::ToCss;
use element_state::ElementState;
use selector_impl::{attr_equals_selector_is_shareable, attr... | (pseudo: &PseudoElement) -> bool {
*pseudo.as_atom() == atom!(":before") ||
*pseudo.as_atom() == atom!(":after")
}
#[inline]
pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState {
pc.state_flag()
}
}
| pseudo_is_before_or_after | identifier_name |
gecko_selector_impl.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::ToCss;
use element_state::ElementState;
use selector_impl::{attr_equals_selector_is_shareable, attr... |
fn parse_pseudo_element(context: &ParserContext<Self>,
name: &str) -> Result<PseudoElement, ()> {
match PseudoElement::from_slice(name, context.in_user_agent_stylesheet) {
Some(pseudo) => Ok(pseudo),
None => Err(()),
}
}
}
impl GeckoSelectorI... |
Ok(pseudo_class)
} | random_line_split |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (cache: Arc<Mutex<Cache>>) -> Self {
let mut me = OnDemand::new(cache);
me.no_immediate_dispatch = true;
me
}
/// Submit a vector of requests to be processed together.
///
/// Fails if back-references are not coherent.
/// The returned vector of responses will correspond to the requests exactly.
pub fn re... | new_test | identifier_name |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | ,
CheckedRequest::Execution(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() {
update_since(&mut caps.serve_state_since, hdr.number());
},
}
}
caps
}
/// A future extracting the concrete output type of the generic adapter
/// from a vector of responses.
pub struct OnResponses<T: request::RequestA... | {
update_since(&mut caps.serve_state_since, hdr.number());
} | conditional_block |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | use net::{
self, Handler, PeerStatus, Status, Capabilities,
Announcement, EventContext, BasicContext, ReqId,
};
use cache::Cache;
use request::{self as basic_request, Request as NetworkRequest};
use self::request::CheckedRequest;
pub use self::request::{Request, Response, HeaderRef};
#[cfg(test)]
mod tests;
pub mo... | use futures::sync::oneshot::{self, Sender, Receiver, Canceled};
use network::PeerId;
use parking_lot::{RwLock, Mutex};
| random_line_split |
extdeps.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 ... | println!("invalid source: {}", source);
*bad = true;
}
}
}
| {
// Cargo.lock of rust (tidy runs inside src/)
let path = path.join("../Cargo.lock");
// open and read the whole file
let cargo_lock = t!(fs::read_to_string(&path));
// process each line
for line in cargo_lock.lines() {
// consider only source entries
if ! line.starts_with("s... | identifier_body |
extdeps.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 ... | (path: &Path, bad: &mut bool) {
// Cargo.lock of rust (tidy runs inside src/)
let path = path.join("../Cargo.lock");
// open and read the whole file
let cargo_lock = t!(fs::read_to_string(&path));
// process each line
for line in cargo_lock.lines() {
// consider only source entries
... | check | identifier_name |
extdeps.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 ... | } | } | random_line_split |
extdeps.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 ... |
}
}
| {
println!("invalid source: {}", source);
*bad = true;
} | conditional_block |
jack_utils.rs | use jack_sys as j;
use std::ffi;
/// Collects strings from an array of c-strings into a Rust vector of strings
/// and frees the memory pointed to by `ptr`. The end of the array is marked by
/// the value of the c-string being the null pointer. `ptr` may be `null`, in
/// which case nothing (deallocating) is done and ... | (ptr: *const *const libc::c_char) -> Vec<String> {
if ptr.is_null() {
return Vec::new();
};
let len = {
let mut len = 0;
while!(*ptr.offset(len)).is_null() {
len += 1;
}
len
};
let mut strs = Vec::with_capacity(len as usize);
for i in 0..len {
... | collect_strs | identifier_name |
jack_utils.rs | use jack_sys as j;
use std::ffi;
/// Collects strings from an array of c-strings into a Rust vector of strings
/// and frees the memory pointed to by `ptr`. The end of the array is marked by
/// the value of the c-string being the null pointer. `ptr` may be `null`, in
/// which case nothing (deallocating) is done and ... | {
if ptr.is_null() {
return Vec::new();
};
let len = {
let mut len = 0;
while !(*ptr.offset(len)).is_null() {
len += 1;
}
len
};
let mut strs = Vec::with_capacity(len as usize);
for i in 0..len {
let cstr_ptr = *ptr.offset(i);
l... | identifier_body | |
jack_utils.rs | use jack_sys as j;
use std::ffi;
/// Collects strings from an array of c-strings into a Rust vector of strings
/// and frees the memory pointed to by `ptr`. The end of the array is marked by
/// the value of the c-string being the null pointer. `ptr` may be `null`, in
/// which case nothing (deallocating) is done and ... | ;
let len = {
let mut len = 0;
while!(*ptr.offset(len)).is_null() {
len += 1;
}
len
};
let mut strs = Vec::with_capacity(len as usize);
for i in 0..len {
let cstr_ptr = *ptr.offset(i);
let s = ffi::CStr::from_ptr(cstr_ptr).to_string_lossy().int... | {
return Vec::new();
} | conditional_block |
jack_utils.rs | use jack_sys as j;
use std::ffi;
/// Collects strings from an array of c-strings into a Rust vector of strings
/// and frees the memory pointed to by `ptr`. The end of the array is marked by
/// the value of the c-string being the null pointer. `ptr` may be `null`, in
/// which case nothing (deallocating) is done and ... | j::jack_free(ptr as *mut ::libc::c_void);
strs
} | let cstr_ptr = *ptr.offset(i);
let s = ffi::CStr::from_ptr(cstr_ptr).to_string_lossy().into_owned();
strs.push(s);
} | random_line_split |
leader.rs | use chrono::{DateTime, FixedOffset, ParseError, Local};
use self::super::{read_toml_file, write_toml_file};
use self::super::super::Error;
use std::iter::FromIterator;
use std::cmp::Ordering;
use std::path::Path;
/// A leaderboard entry.
///
/// # Examples
///
/// Reading a leaderboard, adding an entry to it, then wr... | else {
Ok(vec![])
}
}
/// Save leaderboard to the specified file.
///
/// # Examples
///
/// ```
/// # extern crate poke_a_mango;
/// # extern crate chrono;
/// # use std::fs::{File, create_dir_all};
/// # use self::chrono::{Duration, Local};
/// # use s... | {
let queued_leaders: Leaders = try!(read_toml_file(p, "leaderboard"));
Ok(Result::from_iter(queued_leaders.leader.into_iter().map(|qts| qts.into()).collect::<Vec<_>>()).unwrap())
} | conditional_block |
leader.rs | use chrono::{DateTime, FixedOffset, ParseError, Local};
use self::super::{read_toml_file, write_toml_file};
use self::super::super::Error;
use std::iter::FromIterator;
use std::cmp::Ordering;
use std::path::Path;
/// A leaderboard entry.
///
/// # Examples
///
/// Reading a leaderboard, adding an entry to it, then wr... | {
leader: Vec<LeaderForSerialisation>,
}
impl Leader {
/// Create a new leaderboard entry with `time` set to now.
///
/// # Examples
///
/// ```
/// # use poke_a_mango::ops::Leader;
/// let ldr = Leader::now("nabijaczleweli".to_string(), 36);
/// assert_eq!(ldr.name, "nabijaczlewe... | Leaders | identifier_name |
leader.rs | use chrono::{DateTime, FixedOffset, ParseError, Local};
use self::super::{read_toml_file, write_toml_file};
use self::super::super::Error;
use std::iter::FromIterator;
use std::cmp::Ordering;
use std::path::Path;
/// A leaderboard entry.
///
/// # Examples
///
/// Reading a leaderboard, adding an entry to it, then wr... |
}
| {
Ok(Leader {
name: self.name,
time: try!(DateTime::parse_from_rfc3339(&self.time)),
score: self.score,
})
} | identifier_body |
leader.rs | use chrono::{DateTime, FixedOffset, ParseError, Local};
use self::super::{read_toml_file, write_toml_file};
use self::super::super::Error;
use std::iter::FromIterator;
use std::cmp::Ordering;
use std::path::Path;
/// A leaderboard entry.
///
/// # Examples
///
/// Reading a leaderboard, adding an entry to it, then wr... | /// Create a new leaderboard entry with `time` set to now.
///
/// # Examples
///
/// ```
/// # use poke_a_mango::ops::Leader;
/// let ldr = Leader::now("nabijaczleweli".to_string(), 36);
/// assert_eq!(ldr.name, "nabijaczleweli");
/// assert_eq!(ldr.score, 36);
/// ```
pub f... | random_line_split | |
multi.rs | use wlroots_sys::{
wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove,
wlr_multi_is_empty
};
use crate::backend::UnsafeRenderSetupFunction;
/// When multiple backends are running or when the compositor writer doesn't
/// care and just used the auto create option i... |
pub fn is_empty(&self) -> bool {
unsafe { wlr_multi_is_empty(self.backend) }
}
}
| {
wlr_multi_backend_remove(self.backend, backend)
} | identifier_body |
multi.rs | use wlroots_sys::{
wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove,
wlr_multi_is_empty
};
use crate::backend::UnsafeRenderSetupFunction;
/// When multiple backends are running or when the compositor writer doesn't
/// care and just used the auto create option i... |
Multi { backend }
}
/// Adds the given backend to the multi backend.
///
/// # Safety
///
/// This should be done before the new backend is started.
pub unsafe fn add_backend(&self, new_backend: *mut wlr_backend) -> bool {
wlr_multi_backend_add(self.backend, new_backend)
... | {
panic!("Could not auto construct backend");
} | conditional_block |
multi.rs | use wlroots_sys::{
wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove,
wlr_multi_is_empty
};
use crate::backend::UnsafeRenderSetupFunction;
/// When multiple backends are running or when the compositor writer doesn't
/// care and just used the auto create option i... | (&self, new_backend: *mut wlr_backend) -> bool {
wlr_multi_backend_add(self.backend, new_backend)
}
/// Removes the backend.
///
/// # Safety
///
/// Doesn't check if that backend is valid.
pub unsafe fn remove_backend(&self, backend: *mut wlr_backend) {
wlr_multi_backend_re... | add_backend | identifier_name |
multi.rs | use wlroots_sys::{
wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove,
wlr_multi_is_empty
};
use crate::backend::UnsafeRenderSetupFunction;
/// When multiple backends are running or when the compositor writer doesn't
/// care and just used the auto create option i... | display: *mut wl_display,
render_setup_func: Option<UnsafeRenderSetupFunction>
) -> Self {
let backend = wlr_backend_autocreate(display, render_setup_func);
if backend.is_null() {
panic!("Could not auto construct backend");
}
Multi { backend }
}
/... | impl Multi {
/// Auto create a backend based on the environment.
pub unsafe fn auto_create( | random_line_split |
classify.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 ... | (e: @ast::expr) -> bool {
match e.node {
ast::expr_if(*)
| ast::expr_match(*)
| ast::expr_block(_)
| ast::expr_while(*)
| ast::expr_loop(*)
| ast::expr_call(_, _, ast::DoSugar)
| ast::expr_call(_, _, ast::ForSugar)
| ast::expr_method_call(_, _, _, _, _, ast::DoSugar)
... | expr_requires_semi_to_be_stmt | identifier_name |
classify.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 ... | {
return match stmt.node {
ast::stmt_decl(d, _) => {
match d.node {
ast::decl_local(_) => true,
ast::decl_item(_) => false
}
}
ast::stmt_expr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::stmt_semi(*) => { false }
a... | identifier_body | |
classify.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 ... | return match stmt.node {
ast::stmt_decl(d, _) => {
match d.node {
ast::decl_local(_) => true,
ast::decl_item(_) => false
}
}
ast::stmt_expr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::stmt_semi(*) => { false }
ast... | // note that in one case (stmt_semi), we've already
// seen the semicolon, and thus don't need another.
pub fn stmt_ends_with_semi(stmt: &ast::stmt) -> bool { | random_line_split |
llrepr.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 ... | (&self, ccx: &CrateContext) -> String {
ccx.tn.type_to_string(*self)
}
}
impl LlvmRepr for ValueRef {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn.val_to_string(*self)
}
}
| llrepr | identifier_name |
llrepr.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 ... |
}
impl LlvmRepr for ValueRef {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn.val_to_string(*self)
}
}
| {
ccx.tn.type_to_string(*self)
} | identifier_body |
llrepr.rs | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::tran... | // 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. | random_line_split | |
mod.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module defines physical storage schema for a transaction index via which the version of a
//! transaction sent by `account_address` with `sequence_number` can be found. With the version one
//! can resort to `TransactionSchema`... | (data: &[u8]) -> Result<Self> {
ensure_slice_len_eq(data, size_of::<Self>())?;
let address = AccountAddress::try_from(&data[..AccountAddress::LENGTH])?;
let seq_num = (&data[AccountAddress::LENGTH..]).read_u64::<BigEndian>()?;
Ok((address, seq_num))
}
}
impl ValueCodec<Transaction... | decode_key | identifier_name |
mod.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module defines physical storage schema for a transaction index via which the version of a
//! transaction sent by `account_address` with `sequence_number` can be found. With the version one
//! can resort to `TransactionSchema`... | );
type SeqNum = u64;
type Key = (AccountAddress, SeqNum);
impl KeyCodec<TransactionByAccountSchema> for Key {
fn encode_key(&self) -> Result<Vec<u8>> {
let (ref account_address, seq_num) = *self;
let mut encoded = account_address.to_vec();
encoded.write_u64::<BigEndian>(seq_num)?;
... | define_schema!(
TransactionByAccountSchema,
Key,
Version,
TRANSACTION_BY_ACCOUNT_CF_NAME | random_line_split |
mod.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module defines physical storage schema for a transaction index via which the version of a
//! transaction sent by `account_address` with `sequence_number` can be found. With the version one
//! can resort to `TransactionSchema`... |
fn decode_key(data: &[u8]) -> Result<Self> {
ensure_slice_len_eq(data, size_of::<Self>())?;
let address = AccountAddress::try_from(&data[..AccountAddress::LENGTH])?;
let seq_num = (&data[AccountAddress::LENGTH..]).read_u64::<BigEndian>()?;
Ok((address, seq_num))
}
}
impl Val... | {
let (ref account_address, seq_num) = *self;
let mut encoded = account_address.to_vec();
encoded.write_u64::<BigEndian>(seq_num)?;
Ok(encoded)
} | identifier_body |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... |
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial.
fn crc32c_slice16(mut buf: &[u8]) -> u32 {
let tab = &*TABLE;
let tab16 = &*TABLE16;
let mut crc: u32 =!0;
while buf.len() >= 16 {
crc ^= LE::read_u32(&buf[0..4]);
crc = tab16[0][buf[15] as usize]
^ ta... | {
// I can't measure any difference between slice8 and slice16.
crc32c_slice8(buf)
} | identifier_body |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... | let mut crc = tab[0][i];
for j in 1..16 {
crc = (crc >> 8) ^ tab[0][crc as u8 as usize];
tab[j][i] = crc;
}
}
tab
};
}
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial.
pub fn crc32c(buf: &[u8]) -> u32 {
... | for i in 0..256 { | random_line_split |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... | (buf: &[u8]) -> u32 {
let tab = &*TABLE;
let mut crc: u32 =!0;
for &b in buf {
crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8);
}
!crc
}
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial.
fn crc32c_bitwise(buf: &[u8]) -> u32 {
let mut crc: u32 =!0;
for &b in ... | crc32c_multiple | identifier_name |
crc32.rs | // Sadly, all of the crc crates in Rust appear to be insufficient for high
// performance algorithms. In fact, the implementation here is insufficient!
// The best implementation uses the CRC32 instruction from SSE 4.2, but using
// specialty instructions on stable Rust is an absolute nightmare at the
// moment. The on... |
}
tab[i as usize] = crc;
}
tab
}
| {
crc >>= 1;
} | conditional_block |
hmac_prf_key_manager.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | /// Validates the given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat).
fn validate_key_format(format: &tink_proto::HmacPrfKeyFormat) -> Result<(), TinkError> {
let params = format
.params
.as_ref()
.ok_or_else(|| TinkError::new("no params"))?;
let hash = HashType::from_i32(params.hash)... | }
| random_line_split |
hmac_prf_key_manager.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
/// Validate the given [`HmacPrfKey`](tink_proto::HmacPrfKey). It only validates the version of the
/// key because other parameters will be validated in primitive construction.
fn validate_key(
key: &tink_proto::HmacPrfKey,
) -> Result<(tink_proto::HmacPrfParams, HashType), TinkError> {
tink_core::keyset::... | {
tink_proto::key_data::KeyMaterialType::Symmetric
} | identifier_body |
hmac_prf_key_manager.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> {
if serialized_key.is_empty() {
return Err("HmacPrfKeyManager: invalid key".into());
}
let key = tink_proto::HmacPrfKey::decode(serialized_key)
.map_err(|_| TinkError::new("HmacPrfKeyManager: invali... | primitive | identifier_name |
cp437.rs | //! Convert a string in IBM codepage 437 to UTF-8
/// Trait to convert IBM codepage 437 to the target type
pub trait FromCp437 {
/// Target type
type Target;
/// Function that does the conversion from cp437.
/// Generally allocations will be avoided if all data falls into the ASCII range.
#[allow(... |
#[test]
fn example_slice() {
use super::FromCp437;
let data = b"Cura\x87ao";
assert!(::std::str::from_utf8(data).is_err());
assert_eq!(data.from_cp437(), "Curaçao");
}
#[test]
fn example_vec() {
use super::FromCp437;
let data = vec![0xCC, 0xCD, 0xCD... | {
for i in 0x00..0x80 {
assert_eq!(super::to_char(i), i as char);
}
} | identifier_body |
cp437.rs | //! Convert a string in IBM codepage 437 to UTF-8
/// Trait to convert IBM codepage 437 to the target type
pub trait FromCp437 {
/// Target type
type Target;
/// Function that does the conversion from cp437.
/// Generally allocations will be avoided if all data falls into the ASCII range.
#[allow(... | () {
for i in 0x00..0x80 {
assert_eq!(super::to_char(i), i as char);
}
}
#[test]
fn example_slice() {
use super::FromCp437;
let data = b"Cura\x87ao";
assert!(::std::str::from_utf8(data).is_err());
assert_eq!(data.from_cp437(), "Curaçao");
}
... | ascii | identifier_name |
cp437.rs | //! Convert a string in IBM codepage 437 to UTF-8
/// Trait to convert IBM codepage 437 to the target type
pub trait FromCp437 {
/// Target type
type Target;
/// Function that does the conversion from cp437.
/// Generally allocations will be avoided if all data falls into the ASCII range.
#[allow(... |
impl FromCp437 for Vec<u8> {
type Target = String;
fn from_cp437(self) -> Self::Target {
if self.iter().all(|c| *c < 0x80) {
String::from_utf8(self).unwrap()
} else {
self.into_iter().map(to_char).collect()
}
}
}
fn to_char(input: u8) -> char {
let outp... | self.iter().map(|c| to_char(*c)).collect::<String>().into()
}
}
} | random_line_split |
callback.rs | use std::mem;
use std::ptr;
use std::cell::RefCell;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use CursorState;
use Event;
use super::event;
use user32;
use shell32;
use winapi;
/// There's no parameters passed to the callback function, s... | ,
winapi::WM_SIZE => {
use events::Event::Resized;
let w = winapi::LOWORD(lparam as winapi::DWORD) as u32;
let h = winapi::HIWORD(lparam as winapi::DWORD) as u32;
send_event(window, Resized(w, h));
0
},
winapi::WM_MOVE => {
... | {
1
} | conditional_block |
callback.rs | use std::mem;
use std::ptr;
use std::cell::RefCell;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use CursorState;
use Event;
use super::event;
use user32;
use shell32;
use winapi;
/// There's no parameters passed to the callback function, s... | (window: winapi::HWND, msg: winapi::UINT,
wparam: winapi::WPARAM, lparam: winapi::LPARAM)
-> winapi::LRESULT
{
match msg {
winapi::WM_DESTROY => {
use events::Event::Closed;
CONTEXT_STASH.with(|context_sta... | callback | identifier_name |
callback.rs | use std::mem;
use std::ptr;
use std::cell::RefCell;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use CursorState;
use Event;
use super::event;
use user32;
use shell32;
use winapi;
/// There's no parameters passed to the callback function, s... |
winapi::WM_RBUTTONUP => {
use events::Event::MouseInput;
use events::MouseButton::Right;
use events::ElementState::Released;
send_event(window, MouseInput(Released, Right));
0
},
winapi::WM_MBUTTONDOWN => {
use events::Eve... | send_event(window, MouseInput(Pressed, Right));
0
}, | random_line_split |
index.rs | //! Index for finding Project Gutenberg texts by subject, author, or title.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as... | (&self, s: &str) -> Vec<ScoredResult> {
let mut results = Vec::new();
for key in s.split(' ').map( encode_strict ) {
self.accept_or_merge_postings(&mut results, &key);
}
// Sort results by score, decreasing.
results.sort_by( |l,r| {
match l.1.partial_cmp(&... | get_entries | identifier_name |
index.rs | //! Index for finding Project Gutenberg texts by subject, author, or title.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as... |
fn accept_or_merge_postings(&self, results: &mut Vec<ScoredResult>, key: &String) {
match self.index.get(key) {
Some(postings) => {
if results.len() == 0 {
for posting in postings.iter() {
results.push(posting.clone());
... | {
let mut results = Vec::new();
for key in s.split(' ').map( encode_strict ) {
self.accept_or_merge_postings(&mut results, &key);
}
// Sort results by score, decreasing.
results.sort_by( |l,r| {
match l.1.partial_cmp(&r.1) {
Some(o) => o.re... | identifier_body |
index.rs | //! Index for finding Project Gutenberg texts by subject, author, or title.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as... | * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
use std::cmp::{Ord,Ordering};
use std::collections::HashMap;
use iterator_utilities::equivalence_class::equivalence_classes;
use metadata::Metadata;
use nysiis::encod... | * You should have received a copy of the GNU General Public License | random_line_split |
boss.rs | // Copyright 2015 SiegeLord
//
// See LICENSE for terms.
use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE};
use dollar::new_dollar;
use std::f32::consts::PI;
use rand::{self, Rng};
use allegro::*;
pub fn new_boss(parent: usize, dollar_spawn_color: Color, state: &mut GameState) ... | {
let n = 13;
for i in 0..n
{
let theta = 2.0 * PI * (i as f32) / (n as f32);
let dollar = new_dollar(obj.parent, obj.dollar_spawn_color, obj.x, obj.y, theta.cos() * 256.0, theta.sin() * 256.0, state);
state.add_object(dollar);
}
}
}
} | if rng.gen::<f32>() < 0.2 * DT | random_line_split |
boss.rs | // Copyright 2015 SiegeLord
//
// See LICENSE for terms.
use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE};
use dollar::new_dollar;
use std::f32::consts::PI;
use rand::{self, Rng};
use allegro::*;
pub fn | (parent: usize, dollar_spawn_color: Color, state: &mut GameState) -> Object
{
let mut obj = Object::new(state.new_id());
obj.is_boss = true;
obj.has_pos = true;
obj.x = BOSS_RX;
obj.y = -DEATH;
obj.parent = parent;
obj.start_time = state.time;
obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.... | new_boss | identifier_name |
boss.rs | // Copyright 2015 SiegeLord
//
// See LICENSE for terms.
use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE};
use dollar::new_dollar;
use std::f32::consts::PI;
use rand::{self, Rng};
use allegro::*;
pub fn new_boss(parent: usize, dollar_spawn_color: Color, state: &mut GameState) ... |
simple_behavior!
{
BossLogic[obj.is_boss] |obj, state|
{
let theta = 2.0 * PI * (state.time - obj.start_time) / BOSS_RATE;
obj.x = BOSS_RX * theta.cos();
obj.y = BOSS_RY * theta.sin() - DEATH;
let mut rng = rand::thread_rng();
if rng.gen::<f32>() < 0.2 * DT
{
let n = 13;
for i in 0..n
{
... | {
let mut obj = Object::new(state.new_id());
obj.is_boss = true;
obj.has_pos = true;
obj.x = BOSS_RX;
obj.y = -DEATH;
obj.parent = parent;
obj.start_time = state.time;
obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.png").unwrap());
obj.color = random_color();
obj.size = 32.0;
obj.dollar_... | identifier_body |
utils.rs | val::JSVal;
use js::jsval::{PrivateValue, ObjectValue, NullValue};
use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue};
use js::rust::with_compartment;
use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT};
use js::JSFUN_CONSTRUCTOR;
use js;
/// Proxy handler for a WindowProxy.
... | }
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0;
/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals ... | pub fn new() -> GlobalStaticData {
GlobalStaticData {
windowproxy_handler: browsercontext::new_window_proxy_handler(),
}
} | random_line_split |
utils.rs | ::JSVal;
use js::jsval::{PrivateValue, ObjectValue, NullValue};
use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue};
use js::rust::with_compartment;
use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT};
use js::JSFUN_CONSTRUCTOR;
use js;
/// Proxy handler for a WindowProxy.
pub... | (cx: *mut JSContext, object: *mut JSObject,
id: jsid, bp: &mut bool) -> bool {
let mut value = UndefinedValue(); | delete_property_by_id | identifier_name |
utils.rs | ::JSVal;
use js::jsval::{PrivateValue, ObjectValue, NullValue};
use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue};
use js::rust::with_compartment;
use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT};
use js::JSFUN_CONSTRUCTOR;
use js;
/// Proxy handler for a WindowProxy.
pub... |
/// Callback to outerize windows.
pub extern fn outerize_global(_cx: *mut JSContext, obj: JSHandleObject) -> *mut JSObject {
unsafe {
debug!("outerizing");
let obj = *obj.unnamed_field1;
let win: Root<window::Window> = native_from_reflector_jsmanaged(obj).unwrap().root();
// FIXME(... | {
JS_ObjectToOuterObject(cx, obj)
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... | (opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>,
... | create_constellation | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... |
pub fn request_title_for_main_frame(&self) {
self.compositor.title_for_main_frame()
}
}
fn create_constellation(opts: opts::Opts,
compositor_proxy: Box<CompositorProxy + Send>,
time_profiler_chan: time::ProfilerChan,
mem_profiler... | {
self.compositor.pinch_zoom_level()
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... |
}
// The compositor coordinates with the client window to create the final
// rendered page and display it somewhere.
let compositor = CompositorTask::create(window, InitialCompositorState {
sender: compositor_proxy,
receiver: compositor_receiver,
co... | {
webdriver(port, constellation_chan.clone());
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Servo, the mighty web browser engine from the future.
//
// This is a very simple library that wires all of Ser... |
pub use _util as util;
pub use export::canvas;
pub use export::canvas_traits;
pub use export::compositing;
pub use export::devtools;
pub use export::devtools_traits;
pub use export::euclid;
pub use export::gfx;
pub use export::gleam::gl;
pub use export::layers;
pub use export::layout;
pub use export::msg;
pub use expo... | use std::rc::Rc;
use std::sync::mpsc::Sender;
use util::opts; | random_line_split |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct Cpu {
pub registers: Reg,
rng: ThreadRng,
}
impl Cpu {
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub f... | ,
0x3 => {self.v3 = value},
0x4 => {self.v4 = value},
0x5 => {self.v5 = value},
0x6 => {self.v6 = value},
0x7 => {self.v7 = value},
0x8 => {self.v8 = value},
0x9 => {self.v9 = value},
0xa => {self.va = value},
... | {self.v2 = value} | conditional_block |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct Cpu {
pub registers: Reg,
rng: ThreadRng,
} |
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub fn random_byte(&mut self) -> u8 {
self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX)
}
}
#[derive(Default)]
pub struct Reg {
pub... |
impl Cpu { | random_line_split |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct | {
pub registers: Reg,
rng: ThreadRng,
}
impl Cpu {
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub fn random_byte(&mut self) -> u8 {
self.rng.gen_range(::std::u8::MIN, ::std::... | Cpu | identifier_name |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct Cpu {
pub registers: Reg,
rng: ThreadRng,
}
impl Cpu {
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub f... |
}
#[derive(Default)]
pub struct Reg {
pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8,
pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8,
pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8,
pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8,
pub i: u16, pub pc: u16, pub sp: u8,
}
impl Reg {
#[inline]
... | {
self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX)
} | identifier_body |
implicit_infer.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
use super::explicit::ExplicitPredicatesMap;
use ... | }
let predicate = outlives_predicate.subst(tcx, substs);
debug!("predicate = {:?}", &predicate);
insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);
}
} | debug!("skipping self ty = {:?}", &ty);
continue;
}
} | random_line_split |
implicit_infer.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
use super::explicit::ExplicitPredicatesMap;
use ... |
match *ty.kind() {
// The field is of type &'a T which means that we will have
// a predicate requirement of T: 'a (T outlives 'a).
//
// We also want to calculate potential predicates for the T
ty::Ref(region, rty, _) => {
debug!("Ref... | {
// We must not look into the default substs of consts
// as computing those depends on the results of `predicates_of`.
//
// Luckily the only types contained in default substs are type
// parameters which don't matter here.
//
// FIXME(adt_const_params): Once complex const parameter types
... | identifier_body |
implicit_infer.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
use super::explicit::ExplicitPredicatesMap;
use ... | (&mut self, _trait_item: &'tcx hir::TraitItem<'tcx>) {}
fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem<'tcx>) {}
fn visit_foreign_item(&mut self, _foreign_item: &'tcx hir::ForeignItem<'tcx>) {}
}
fn insert_required_predicates_to_be_wf<'tcx>(
tcx: TyCtxt<'tcx>,
field_ty: Ty<'tcx>,
f... | visit_trait_item | identifier_name |
compiletest.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 ... | (config: &config) -> ~[test::TestDescAndFn] {
debug!("making tests from {}",
config.src_base.display());
let mut tests = ~[];
let dirs = fs::readdir(&config.src_base);
for file in dirs.iter() {
let file = file.clone();
debug!("inspecting file {}", file.display());
if i... | make_tests | identifier_name |
compiletest.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 ... |
pub fn str_mode(s: ~str) -> mode {
match s {
~"compile-fail" => mode_compile_fail,
~"run-fail" => mode_run_fail,
~"run-pass" => mode_run_pass,
~"pretty" => mode_pretty,
~"debug-info" => mode_debug_info,
~"codegen" => mode_codegen,
_ => fail!("invalid mode")
}
}
pub f... | {
match maybestr { None => ~"(none)", Some(s) => { s } }
} | identifier_body |
compiletest.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 ... | mode_run_pass => ~"run-pass",
mode_pretty => ~"pretty",
mode_debug_info => ~"debug-info",
mode_codegen => ~"codegen",
}
}
pub fn run_tests(config: &config) {
if config.target == ~"arm-linux-androideabi" {
match config.mode{
mode_debug_info => {
printl... | random_line_split | |
main.rs | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | {
// Note: This will need to change if the dependency version changes
let texture_synthesis_path =
Path::new("./external/remote_binary_dependencies__texture_synthesis_cli__0_8_0/cargo_bin_texture_synthesis");
// Run the command
let texture_synthesis_output = Command::new(texture_synthesis_path)
.... | identifier_body | |
main.rs | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | Path::new("./external/remote_binary_dependencies__texture_synthesis_cli__0_8_0/cargo_bin_texture_synthesis");
// Run the command
let texture_synthesis_output = Command::new(texture_synthesis_path)
.arg("--help")
.output()
.unwrap();
// Print the results
let mut writer = BufWriter::new(stdout... | // Note: This will need to change if the dependency version changes
let texture_synthesis_path = | random_line_split |
main.rs | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | () {
// Note: This will need to change if the dependency version changes
let texture_synthesis_path =
Path::new("./external/remote_binary_dependencies__texture_synthesis_cli__0_8_0/cargo_bin_texture_synthesis");
// Run the command
let texture_synthesis_output = Command::new(texture_synthesis_path)
... | main | identifier_name |
utils.rs | use byteorder::BigEndian;
use byteorder::ByteOrder;
use fcp_cryptoauth::CAWrapper;
use operation::{BackwardPath, ForwardPath};
use packets::switch::Payload as SwitchPayload;
use packets::switch::SwitchPacket;
use session_manager::{SessionHandle, TheirSessionHandle};
/// Creates a switch packet from a raw payload.
///... |
}
}
/// Creates a reply switch packet to an other switch packet.
/// The content of the reply is given as a byte array (returned by CryptoAuth's
/// `wrap_messages`).
pub fn make_reply<PeerId: Clone>(
replied_to_packet: &SwitchPacket,
reply_content: Vec<u8>,
inner_conn: &CAWrapper<PeerId>,
) -> Switch... | {
// Otherwise, it is a CryptoAuth data packet. We have to prepend
// the session handle to the reply.
// This handle is used by the peer to know this packet is coming
// from us.
let peer_handle = handle.unwrap().0;
SwitchPacket::new(path, SwitchP... | conditional_block |
utils.rs | use byteorder::BigEndian;
use byteorder::ByteOrder;
use fcp_cryptoauth::CAWrapper;
use operation::{BackwardPath, ForwardPath};
use packets::switch::Payload as SwitchPayload;
use packets::switch::SwitchPacket;
use session_manager::{SessionHandle, TheirSessionHandle};
/// Creates a switch packet from a raw payload.
///... | // from us.
let peer_handle = handle.unwrap().0;
SwitchPacket::new(path, SwitchPayload::CryptoAuthData(peer_handle, content))
}
}
}
/// Creates a reply switch packet to an other switch packet.
/// The content of the reply is given as a byte array (returned by CryptoAuth... | {
let first_four_bytes = BigEndian::read_u32(&content[0..4]);
match first_four_bytes {
0 | 1 => {
// If it is a CryptoAuth handshake Hello packet, send it as is.
let payload = SwitchPayload::CryptoAuthHello(content);
SwitchPacket::new(path, payload)
}
... | identifier_body |
utils.rs | use byteorder::BigEndian;
use byteorder::ByteOrder;
use fcp_cryptoauth::CAWrapper;
use operation::{BackwardPath, ForwardPath};
use packets::switch::Payload as SwitchPayload;
use packets::switch::SwitchPacket;
use session_manager::{SessionHandle, TheirSessionHandle};
/// Creates a switch packet from a raw payload.
///... | <PeerId: Clone>(
replied_to_packet: &SwitchPacket,
reply_content: Vec<u8>,
inner_conn: &CAWrapper<PeerId>,
) -> SwitchPacket {
let path = BackwardPath::from(replied_to_packet.label()).reverse();
new_from_raw_content(
path,
reply_content,
inner_conn
.peer_session_ha... | make_reply | identifier_name |
utils.rs | use byteorder::BigEndian;
use byteorder::ByteOrder;
use fcp_cryptoauth::CAWrapper;
use operation::{BackwardPath, ForwardPath};
use packets::switch::Payload as SwitchPayload;
use packets::switch::SwitchPacket;
use session_manager::{SessionHandle, TheirSessionHandle};
/// Creates a switch packet from a raw payload.
///... | // This handle is used by the peer to know this packet is coming
// from us.
let peer_handle = handle.unwrap().0;
SwitchPacket::new(path, SwitchPayload::CryptoAuthData(peer_handle, content))
}
}
}
/// Creates a reply switch packet to an other switch packet.
/... | unimplemented!()
}
_ => {
// Otherwise, it is a CryptoAuth data packet. We have to prepend
// the session handle to the reply. | random_line_split |
tcp.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 ... | {
inner: Arc<AcceptorInner>,
deadline: u64,
}
struct AcceptorInner {
listener: TcpListener,
abort: Event,
accept: Event,
closed: AtomicBool,
}
unsafe impl Sync for AcceptorInner {}
impl TcpAcceptor {
pub fn socket(&self) -> sock_t { self.inner.listener.socket() }
pub fn accept(&mut ... | TcpAcceptor | identifier_name |
tcp.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 ... | c::WSAEventSelect(socket, events[1], 0)
};
if ret!= 0 { return Err(last_net_error()) }
set_nonblocking(socket, false);
return Ok(stream)
}
}
}
Err(eof())
}
pub fn... | // to blocking mode
socket => {
let stream = TcpStream::new(socket);
let ret = unsafe { | random_line_split |
github_repositorypermissions.rs | /* | * 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 GithubRepositorypermissions {... | * Swaggy Jenkins
* | random_line_split |
github_repositorypermissions.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 Githu... |
}
| {
GithubRepositorypermissions {
admin: None,
push: None,
pull: None,
_class: None,
}
} | identifier_body |
github_repositorypermissions.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 | {
#[serde(rename = "admin", skip_serializing_if = "Option::is_none")]
pub admin: Option<bool>,
#[serde(rename = "push", skip_serializing_if = "Option::is_none")]
pub push: Option<bool>,
#[serde(rename = "pull", skip_serializing_if = "Option::is_none")]
pub pull: Option<bool>,
#[serde(rename... | GithubRepositorypermissions | identifier_name |
dynamodb.rs | #![cfg(feature = "dynamodb")]
extern crate rusoto;
use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn | () {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
// limit of -1 should generate a validation error
let request = ListTablesInput { limit: Some(-1),..Default::default() };
let response =... | should_parse_error_type | identifier_name |
dynamodb.rs | #![cfg(feature = "dynamodb")]
extern crate rusoto;
use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_parse_error_type() {
let credentials = DefaultCredentialsProvider::new().unwra... |
_ => panic!("Should have been a Validation error"),
};
}
#[test]
fn should_list_tables() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = ListTablesInput::default();
... | {
assert!(msg.contains("Member must have value greater than or equal to 1"))
} | conditional_block |
dynamodb.rs | #![cfg(feature = "dynamodb")]
extern crate rusoto;
use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_parse_error_type() {
let credentials = DefaultCredentialsProvider::new().unwra... | fn should_list_tables() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = ListTablesInput::default();
client.list_tables(&request).unwrap();
} | random_line_split | |
dynamodb.rs | #![cfg(feature = "dynamodb")]
extern crate rusoto;
use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_parse_error_type() {
let credentials = DefaultCredentialsProvider::new().unwra... | {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = ListTablesInput::default();
client.list_tables(&request).unwrap();
} | identifier_body | |
error.rs | //! # Keystore files (UTC / JSON) module errors
use super::core;
use std::{error, fmt};
/// Keystore file errors
#[derive(Debug)]
pub enum Error {
/// An unsupported cipher
UnsupportedCipher(String),
/// An unsupported key derivation function
UnsupportedKdf(String),
/// An unsupported pseudo-ran... |
}
| {
match *self {
Error::CoreFault(ref err) => Some(err),
_ => None,
}
} | identifier_body |
error.rs | //! # Keystore files (UTC / JSON) module errors
use super::core;
use std::{error, fmt};
/// Keystore file errors
#[derive(Debug)]
pub enum | {
/// An unsupported cipher
UnsupportedCipher(String),
/// An unsupported key derivation function
UnsupportedKdf(String),
/// An unsupported pseudo-random function
UnsupportedPrf(String),
/// `keccak256_mac` field validation failed
FailedMacValidation,
/// Core module error wrap... | Error | identifier_name |
error.rs | //! # Keystore files (UTC / JSON) module errors
use super::core;
use std::{error, fmt};
/// Keystore file errors
#[derive(Debug)]
pub enum Error {
/// An unsupported cipher
UnsupportedCipher(String),
/// An unsupported key derivation function
UnsupportedKdf(String),
/// An unsupported pseudo-ran... |
impl From<core::Error> for Error {
fn from(err: core::Error) -> Self {
Error::CoreFault(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::UnsupportedCipher(ref str) => write!(f, "Unsupported cipher: {}", str),
... | random_line_split | |
free.rs | //! Free functions that create iterator adaptors or call iterator methods.
//!
//! The benefit of free functions is that they accept any `IntoIterator` as
//! argument, so the resulting code may be easier to read.
use std::fmt::Display;
use std::iter::{self, Zip};
use Itertools;
pub use adaptors::{
interleave,
... | <I, J>(i: I, j: J) -> Zip<I::IntoIter, J::IntoIter>
where I: IntoIterator,
J: IntoIterator
{
i.into_iter().zip(j)
}
/// Create an iterator that first iterates `i` and then `j`.
///
/// `IntoIterator` enabled version of `i.chain(j)`.
///
/// ```
/// use itertools::chain;
///
/// for elt in chain(&[1, ... | zip | identifier_name |
free.rs | //! Free functions that create iterator adaptors or call iterator methods.
//!
//! The benefit of free functions is that they accept any `IntoIterator` as
//! argument, so the resulting code may be easier to read.
use std::fmt::Display;
use std::iter::{self, Zip};
use Itertools;
pub use adaptors::{
interleave,
... | /// `IntoIterator` enabled version of `.enumerate()`.
///
/// ```
/// use itertools::enumerate;
///
/// for (i, elt) in enumerate(&[1, 2, 3]) {
/// /* loop body */
/// }
/// ```
pub fn enumerate<I>(iterable: I) -> iter::Enumerate<I::IntoIter>
where I: IntoIterator
{
iterable.into_iter().enumerate()
}
/// I... |
/// Iterate `iterable` with a running index.
/// | random_line_split |
free.rs | //! Free functions that create iterator adaptors or call iterator methods.
//!
//! The benefit of free functions is that they accept any `IntoIterator` as
//! argument, so the resulting code may be easier to read.
use std::fmt::Display;
use std::iter::{self, Zip};
use Itertools;
pub use adaptors::{
interleave,
... |
/// Create an iterator that clones each element from &T to T
///
/// `IntoIterator` enabled version of `i.cloned()`.
///
/// ```
/// use itertools::cloned;
///
/// assert_eq!(cloned(b"abc").next(), Some(b'a'));
/// ```
pub fn cloned<'a, I, T: 'a>(iterable: I) -> iter::Cloned<I::IntoIter>
where I: IntoIterator<Ite... | {
i.into_iter().chain(j)
} | identifier_body |
dbscan.rs | use rm::linalg::Matrix; | #[test]
fn test_basic_clusters() {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
... |
use rm::learning::dbscan::DBSCAN;
use rm::learning::UnSupModel;
| random_line_split |
dbscan.rs | use rm::linalg::Matrix;
use rm::learning::dbscan::DBSCAN;
use rm::learning::UnSupModel;
#[test]
fn test_basic_clusters() |
#[test]
fn test_basic_prediction() {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
... | {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
-2.2, 3.1]);
let mut m... | identifier_body |
dbscan.rs | use rm::linalg::Matrix;
use rm::learning::dbscan::DBSCAN;
use rm::learning::UnSupModel;
#[test]
fn | () {
let inputs = Matrix::new(6, 2, vec![1.0, 2.0,
1.1, 2.2,
0.9, 1.9,
1.0, 2.1,
-2.0, 3.0,
-2.2, 3.1]);
let mu... | test_basic_clusters | identifier_name |
mod.rs | // that the user can type
inference_context.tcx.sess.span_bug(
span,
&format!("coherence encountered unexpected type searching for base type: {}",
ty.repr(inference_context.tcx))[]);
}
}
}
struct CoherenceChecker<'a, 'tcx: 'a> {
crate... |
fn get_self_type_for_implementation(&self, impl_did: DefId)
-> TypeScheme<'tcx> {
self.crate_context.tcx.tcache.borrow()[impl_did].clone()
}
// Converts an implementation in the AST to a vector of items.
fn create_impl_from_item(&self, item: &Item) -> V... | {
debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}",
base_def_id, impl_def_id);
ty::record_trait_implementation(self.crate_context.tcx,
base_def_id,
impl_def_id);
} | identifier_body |
mod.rs | // that the user can type
inference_context.tcx.sess.span_bug(
span,
&format!("coherence encountered unexpected type searching for base type: {}",
ty.repr(inference_context.tcx))[]);
}
}
}
struct | <'a, 'tcx: 'a> {
crate_context: &'a CrateCtxt<'a, 'tcx>,
inference_context: InferCtxt<'a, 'tcx>,
inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
}
struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
cc: &'a CoherenceChecker<'a, 'tcx>
}
impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheck... | CoherenceChecker | identifier_name |
mod.rs |
ty_infer(..) | ty_closure(..) => {
// `ty` comes from a user declaration so we should only expect types
// that the user can type
inference_context.tcx.sess.span_bug(
span,
&format!("coherence encountered unexpected type searching for base ty... | {
None
} | conditional_block | |
mod.rs | match ty.sty {
ty_enum(def_id, _) |
ty_struct(def_id, _) => {
Some(def_id)
}
ty_trait(ref t) => {
Some(t.principal_def_id())
}
ty_uniq(_) => {
inference_context.tcx.lang_items.owned_box()
}
ty_bool | ty_char | ty_... | // Returns the def ID of the base type, if there is one.
fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>,
span: Span,
ty: Ty<'tcx>)
-> Option<DefId> { | random_line_split | |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 F... | (rt: &Runtime, app_name: &'static str) -> Result<RefConfig> {
use toml_query::read::TomlValueReadExt;
let setting_name = "ref.basepathes";
rt.config()
.ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))?
.read_deserialized::<RefConfig>(setting_name)?
... | get_ref_config | identifier_name |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library 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 F... | .ok_or_else(|| anyhow!("Setting missing: {}", setting_name))
} | rt.config()
.ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))?
.read_deserialized::<RefConfig>(setting_name)? | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.