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 |
|---|---|---|---|---|
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! This module provides algorithms for accessing and updating a Merkle Accumulator structure
//! persisted in a key-value store. Note that this doesn't write to the storage directly, rather,
//! it reads from i... |
/// Get root hash at a specific version (hence num_leaves).
pub fn get_root_hash(reader: &R, num_leaves: LeafCount) -> Result<HashValue> {
MerkleAccumulatorView::<R, H>::new(reader, num_leaves).get_root_hash()
}
}
/// Actual implementation of Merkle Accumulator algorithms, which carries the `read... | {
MerkleAccumulatorView::<R, H>::new(reader, num_leaves).get_frozen_subtree_hashes()
} | identifier_body |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
//! This module provides algorithms for accessing and updating a Merkle Accumulator structure
//! persisted in a key-value store. Note that this doesn't write to the storage directly, rather,
//! it reads from i... | (
&self,
leaf_index: u64,
filter: impl Fn(Position) -> bool,
) -> Result<Vec<HashValue>> {
self.get_hashes(&self.get_sibling_positions(leaf_index, filter))
}
/// Helper function to get siblings on the path from the given leaf to the root. An additional
/// filter functio... | get_siblings | identifier_name |
instruction.rs | use core::convert::{TryFrom, TryInto};
use core::fmt::{self, Debug, Display, Error, Formatter};
use core::marker::PhantomData;
use core::ops::Deref;
use core::slice;
use core::str;
use capstone_sys::*;
use crate::arch::ArchDetail;
use crate::constants::Arch;
use crate::ffi::str_from_cstr_ptr;
/// Represents a slice ... |
Ok(())
}
}
/// Iterator over instruction group ids
#[derive(Debug, Clone)]
pub struct InsnGroupIter<'a>(slice::Iter<'a, InsnGroupIdInt>);
impl<'a> InsnDetail<'a> {
/// Returns the implicit read registers
pub fn regs_read(&self) -> &[RegId] {
unsafe {
&*(&self.0.regs_read[..sel... | {
write!(fmt, "{} ", mnemonic)?;
if let Some(op_str) = self.op_str() {
write!(fmt, "{}", op_str)?;
}
} | conditional_block |
instruction.rs | use core::convert::{TryFrom, TryInto};
use core::fmt::{self, Debug, Display, Error, Formatter};
use core::marker::PhantomData;
use core::ops::Deref;
use core::slice;
use core::str;
use capstone_sys::*;
use crate::arch::ArchDetail;
use crate::constants::Arch;
use crate::ffi::str_from_cstr_ptr;
/// Represents a slice ... | [ARM, ArmDetail, ArmInsnDetail, arm]
[ARM64, Arm64Detail, Arm64InsnDetail, arm64]
[EVM, EvmDetail, EvmInsnDetail, evm]
[M680X, M680xDetail, M680xInsnDetail, m680x]
[M68K, M68kDetail, M68kInsnDetail, m68k]
[MIPS, MipsDetail, MipsInsnDetail, mips]
... | {
macro_rules! def_arch_detail_match {
(
$( [ $ARCH:ident, $detail:ident, $insn_detail:ident, $arch:ident ] )*
) => {
use self::ArchDetail::*;
use crate::Arch::*;
$( use crate::arch::$arch::$insn_detail; )*
... | identifier_body |
instruction.rs | use core::convert::{TryFrom, TryInto};
use core::fmt::{self, Debug, Display, Error, Formatter};
use core::marker::PhantomData;
use core::ops::Deref;
use core::slice;
use core::str;
use capstone_sys::*;
use crate::arch::ArchDetail;
use crate::constants::Arch;
use crate::ffi::str_from_cstr_ptr;
/// Represents a slice ... | <'a>(pub(crate) &'a cs_detail, pub(crate) Arch);
impl<'a> Insn<'a> {
/// Create an `Insn` from a raw pointer to a [`capstone_sys::cs_insn`].
///
/// This function serves to allow integration with libraries which generate `capstone_sys::cs_insn`'s internally.
///
/// # Safety
///
/// Note th... | InsnDetail | identifier_name |
instruction.rs | use core::convert::{TryFrom, TryInto};
use core::fmt::{self, Debug, Display, Error, Formatter};
use core::marker::PhantomData;
use core::ops::Deref;
use core::slice;
use core::str;
use capstone_sys::*;
use crate::arch::ArchDetail;
use crate::constants::Arch;
use crate::ffi::str_from_cstr_ptr;
/// Represents a slice ... | ///
/// Note that an instruction may read and write to the register
/// simultaneously. In this case, the operand is also considered as
/// writable.
pub fn is_writable(self) -> bool {
self == RegAccessType::WriteOnly || self == RegAccessType::ReadWrite
}
}
impl TryFrom<cs_ac_type> for ... | random_line_split | |
leb128.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... | }
#[test]
fn test_signed_leb128() {
let mut values = Vec::new();
let mut i = -500;
while i < 500 {
values.push(i * 123457i64);
i += 1;
}
let mut stream = Vec::new();
for &x in &values {
let pos = stream.len();
let bytes_written = write_signed_leb128(&mut strea... | let (actual, bytes_read) = read_unsigned_leb128(&stream, position);
assert_eq!(expected, actual);
position += bytes_read;
}
assert_eq!(stream.len(), position); | random_line_split |
leb128.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... | (out: &mut Vec<u8>, start_position: usize, mut value: i64) -> usize {
let mut position = start_position;
loop {
let mut byte = (value as u8) & 0x7f;
value >>= 7;
let more =!((((value == 0) && ((byte & 0x40) == 0)) ||
((value == -1) && ((byte & 0x40)!= 0))));
... | write_signed_leb128 | identifier_name |
leb128.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... |
#[inline]
pub fn read_unsigned_leb128(data: &[u8], start_position: usize) -> (u64, usize) {
let mut result = 0;
let mut shift = 0;
let mut position = start_position;
loop {
let byte = data[position];
position += 1;
result |= ((byte & 0x7F) as u64) << shift;
if (byte & 0... | {
let mut position = start_position;
loop {
let mut byte = (value & 0x7F) as u8;
value >>= 7;
if value != 0 {
byte |= 0x80;
}
write_to_vec(out, &mut position, byte);
if value == 0 {
break;
}
}
return position - start_posi... | identifier_body |
leb128.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... |
}
return position - start_position;
}
#[inline]
pub fn read_signed_leb128(data: &[u8], start_position: usize) -> (i64, usize) {
let mut result = 0;
let mut shift = 0;
let mut position = start_position;
let mut byte;
loop {
byte = data[position];
position += 1;
res... | {
break;
} | conditional_block |
backup.rs | // Copyright 2016 Alex Regueiro
//
// 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 wr... | <P: AsRef<Path>>(opts: &BackupEngineOptions,
path: P)
-> Result<BackupEngine, Error> {
let path = path.as_ref();
let cpath = match CString::new(path.to_string_lossy().as_bytes()) {
Ok(c) => c,
Err(_) => {
... | open | identifier_name |
backup.rs | // Copyright 2016 Alex Regueiro
//
// 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 wr... |
}
impl Drop for RestoreOptions {
fn drop(&mut self) {
unsafe {
ffi::rocksdb_restore_options_destroy(self.inner);
}
}
}
| {
unsafe {
ffi::rocksdb_options_destroy(self.inner);
}
} | identifier_body |
backup.rs | // Copyright 2016 Alex Regueiro
//
// 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 wr... | impl Default for BackupEngineOptions {
fn default() -> BackupEngineOptions {
unsafe {
let opts = ffi::rocksdb_options_create();
if opts.is_null() {
panic!("Could not create RocksDB backup options".to_owned());
}
BackupEngineOptions { inner: opt... | ffi::rocksdb_restore_options_set_keep_log_files(self.inner, keep_log_files as c_int);
}
}
}
| random_line_split |
backup.rs | // Copyright 2016 Alex Regueiro
//
// 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 wr... |
Ok(BackupEngine { inner: be })
}
pub fn create_new_backup(&mut self, db: &DB) -> Result<(), Error> {
unsafe {
ffi_try!(ffi::rocksdb_backup_engine_create_new_backup(self.inner, db.inner));
Ok(())
}
}
pub fn purge_old_backups(&mut self, num_backups_to_ke... | {
return Err(Error::new("Could not initialize backup engine.".to_owned()));
} | conditional_block |
console.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::ConsoleBinding;
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Ref... | () -> Console {
Console {
reflector_: Reflector::new()
}
}
pub fn new(window: &JS<Window>) -> JS<Console> {
reflect_dom_object(~Console::new_inherited(), window, ConsoleBinding::Wrap)
}
pub fn Log(&self, message: DOMString) {
println!("{:s}", message);
}... | new_inherited | identifier_name |
console.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::ConsoleBinding;
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Ref... |
pub fn new(window: &JS<Window>) -> JS<Console> {
reflect_dom_object(~Console::new_inherited(), window, ConsoleBinding::Wrap)
}
pub fn Log(&self, message: DOMString) {
println!("{:s}", message);
}
pub fn Debug(&self, message: DOMString) {
println!("{:s}", message);
}
... | } | random_line_split |
lump.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: shared/obj/bsp/lump.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Lump definitions for Q3 BSP maps.
*/
use math;
pub enum Lump_Type
{
Entity_Type... | () -> Header
{ Header{ magic: [0,..4], version: 0, lumps: [Lump::new(),..17] } }
}
#[packed]
pub struct Entity
{
/* Size of the buffer. */
size: i32,
buffer: ~[i8] /* TODO: Read binary into this? */
}
impl Entity
{
pub fn new() -> Entity
{ Entity{ size: 0, buffer: ~[] } }
}
#[packed]
pub struct Texture
{
... | new | identifier_name |
lump.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: shared/obj/bsp/lump.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
Lump definitions for Q3 BSP maps.
*/
use math;
pub enum Lump_Type
{
Entity_Type... | normal: math::Vec3f::zero(),
patch_size: math::Vec2i::zero() }
}
}
#[packed]
pub struct Light_Map
{
data: [[[u8,..128],..128],..3]
}
#[packed]
pub struct Light_Vol
{
/* Ambient color compontn RGB. */
ambient: math::Vec3u8,
/* Directional color component RGB. */
directional: math::... | lightmap_size: math::Vec2i::zero(),
lightmap_origin: math::Vec3f::zero(),
lightmap_vecs: [math::Vec3f::zero(), ..2], | random_line_split |
TestLog1p.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 app... | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma version(1)
#pragma rs java_package_name(android.renderscr... | random_line_split | |
request_context.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use gotham::state::{FromState, State};
use gotham_derive::StateData;
use hyper::{Body, Response};
use rate_limiting::RateLimitEnvironment;
... | (
fb: FacebookInit,
logger: Logger,
scuba: MononokeScubaSampleBuilder,
rate_limiter: Option<RateLimitEnvironment>,
) -> Self {
Self {
fb,
logger,
scuba: Arc::new(scuba),
rate_limiter,
}
}
}
#[async_trait::async_trai... | new | identifier_name |
request_context.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the |
use gotham::state::{FromState, State};
use gotham_derive::StateData;
use hyper::{Body, Response};
use rate_limiting::RateLimitEnvironment;
use slog::{o, Logger};
use std::sync::Arc;
use context::{CoreContext, SessionContainer};
use fbinit::FacebookInit;
use gotham_ext::{
middleware::{ClientIdentity, Middleware},
... | * GNU General Public License version 2.
*/ | random_line_split |
request_context.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use gotham::state::{FromState, State};
use gotham_derive::StateData;
use hyper::{Body, Response};
use rate_limiting::RateLimitEnvironment;
... | }
}
| {
let identities = ClientIdentity::borrow_from(state)
.identities()
.clone()
.unwrap_or_default();
let metadata = Metadata::default().set_identities(identities);
let metadata = Arc::new(metadata);
let session = SessionContainer::builder(self.fb)
... | identifier_body |
schema.rs | table! {
attachments (id) {
id -> Integer,
message_id -> Integer,
file_name -> Text,
mime_type -> Text,
character_set -> Text,
content_id -> Text,
content_location -> Text,
part_id -> Text,
encoding -> Integer,
data -> Binary,
i... | in_reply_to -> Text,
uid -> BigInt,
modification_sequence -> BigInt,
seen -> Bool,
flagged -> Bool,
draft -> Bool,
deleted -> Bool,
}
}
allow_tables_to_appear_in_same_query!(attachments, folders, identities, messages,); | to -> Text,
cc -> Text,
bcc -> Text,
content -> Nullable<Text>,
references -> Text, | random_line_split |
body_sync.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | // http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language govern... | // You may obtain a copy of the License at
// | random_line_split |
body_sync.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... |
/// Return true if txhashset download is needed (when requested block is under the horizon).
/// Otherwise go request some missing blocks and return false.
fn body_sync(&mut self) -> Result<bool, chain::Error> {
let head = self.chain.head()?;
let header_head = self.chain.header_head()?;
let fork_point = self... | {
self.chain.archive_mode()
} | identifier_body |
body_sync.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | else {
self.blocks_requested += 1;
}
}
}
}
return Ok(false);
}
fn block_hashes_to_sync(
&self,
fork_point: &BlockHeader,
header_head: &Tip,
count: u64,
) -> Result<Vec<Hash>, chain::Error> {
let mut hashes = vec![];
let max_height = cmp::min(fork_point.height + count, header_head.... | {
debug!("Skipped request to {}: {:?}", peer.info.addr, e);
peer.stop();
} | conditional_block |
body_sync.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | (&mut self) -> Result<bool, chain::Error> {
let blocks_received = self.blocks_received()?;
// some blocks have been requested
if self.blocks_requested > 0 {
// but none received since timeout, ask again
let timeout = Utc::now() > self.receive_timeout;
if timeout && blocks_received <= self.prev_blocks_re... | body_sync_due | identifier_name |
local.rs | this `Key` is
// stored as a `static`, and it's not valid for a static to reference the
// address of another thread_local static. For this reason we kinda wonkily
// work around this by generating a shim function which will give us the
// address of the inner TLS key at runtime.
//
// This is ... | }
#[test]
fn circular() {
struct S1;
struct S2;
thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
static mut HITS: u32 = 0;
impl Drop for S1 {
fn dr... | random_line_split | |
local.rs | `Key` is
// stored as a `static`, and it's not valid for a static to reference the
// address of another thread_local static. For this reason we kinda wonkily
// work around this by generating a shim function which will give us the
// address of the inner TLS key at runtime.
//
// This is trivi... | (&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
if intrinsics::needs_drop::<T>() && self.dtor_running.get() {
return None
}
self.register_dtor();
Some(&self.inner)
}
unsafe fn register_dtor(&self) {
if!intrinsics::n... | get | identifier_name |
local.rs | __thread_local_inner!($t, $init,
#[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
not(target_arch = "aarch64")),
thread_local)]);
);
}
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_un... | {
K2.with(|s| *s.get() = Some(Foo(tx.clone())));
} | conditional_block | |
local.rs | `Key` is
// stored as a `static`, and it's not valid for a static to reference the
// address of another thread_local static. For this reason we kinda wonkily
// work around this by generating a shim function which will give us the
// address of the inner TLS key at runtime.
//
// This is trivi... | ptr::read((*ptr).inner.get());
} else {
intrinsics::drop_in_place((*ptr).inner.get());
}
}
}
#[cfg(any(not(any(target_os = "macos", target_os = "linux")),
target_arch = "aarch64",
no_elf_tls))]
#[doc(hidden)]
mod imp {
use prelude::v1::*;
use ce... | {
let ptr = ptr as *mut Key<T>;
// Right before we run the user destructor be sure to flag the
// destructor as running for this thread so calls to `get` will return
// `None`.
(*ptr).dtor_running.set(true);
// The OSX implementation of TLS apparently had an odd aspect t... | identifier_body |
addrinfo.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 ... | }
fn each_ai_flag(_f: |c_int, ai::Flag|) {
/* XXX: do we really want to support these?
unsafe {
f(uvll::rust_AI_ADDRCONFIG(), ai::AddrConfig);
f(uvll::rust_AI_ALL(), ai::All);
f(uvll::rust_AI_CANONNAME(), ai::CanonName);
f(uvll::rust_AI_NUMERICHOST(), ai::NumericHost);
f... | impl Drop for Addrinfo {
fn drop(&mut self) {
unsafe { uvll::uv_freeaddrinfo(self.handle) }
} | random_line_split |
addrinfo.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 ... | (req: *uvll::uv_getaddrinfo_t,
status: c_int,
res: *libc::addrinfo) {
let req = Request::wrap(req);
assert!(status!= uvll::ECANCELED);
let cx: &mut Ctx = unsafe { req.get_data() };
cx.status = status;
... | getaddrinfo_cb | identifier_name |
nfs2_records.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | }
named!(pub parse_nfs2_handle<Nfs2Handle>,
do_parse!(
handle: take!(32)
>> (
Nfs2Handle {
value:handle,
}
))
);
#[derive(Debug,PartialEq)]
pub struct Nfs2RequestLookup<'a> {
pub handle: Nfs2Handle<'a>,
pub name_vec: Vec<u8>,
}
named!(pub pa... |
#[derive(Debug,PartialEq)]
pub struct Nfs2Handle<'a> {
pub value: &'a[u8], | random_line_split |
nfs2_records.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | <'a> {
pub handle: Nfs2Handle<'a>,
pub offset: u32,
}
named!(pub parse_nfs2_request_read<Nfs2RequestRead>,
do_parse!(
handle: parse_nfs2_handle
>> offset: be_u32
>> count: be_u32
>> (
Nfs2RequestRead {
handle:handle,
offset:o... | Nfs2RequestRead | identifier_name |
lib.rs | extern crate urlencoding;
mod query;
pub use urlencoding::{encode, decode};
pub use query::{Query, QueryValue};
#[cfg(test)]
mod tests {
use super::{encode, decode};
use super::{Query, QueryValue};
const DECODED: &str = "title=Encode some URLs";
const ENCODED: &str = "title%3DEncode%20some%20URLs";... |
}
#[test]
fn parse_query_vector_test() {
let expected = vec![
"apple".to_string(),
"banana".to_string(),
"coconut".to_string(),
];
if let Ok(query) = "fruits=apple,banana,coconut".parse::<Query>() {
assert_eq!(Some(&expected), query.g... | {
assert!(false);
} | conditional_block |
lib.rs | extern crate urlencoding;
mod query;
pub use urlencoding::{encode, decode};
pub use query::{Query, QueryValue};
#[cfg(test)]
mod tests {
use super::{encode, decode};
use super::{Query, QueryValue};
const DECODED: &str = "title=Encode some URLs";
const ENCODED: &str = "title%3DEncode%20some%20URLs";... | () {
let expected = vec![
"apple".to_string(),
"banana".to_string(),
"coconut".to_string(),
];
if let Ok(query) = "fruits=apple,banana,coconut".parse::<Query>() {
assert_eq!(Some(&expected), query.get("fruits"));
} else {
assert... | parse_query_vector_test | identifier_name |
lib.rs | extern crate urlencoding;
mod query;
pub use urlencoding::{encode, decode};
pub use query::{Query, QueryValue};
#[cfg(test)]
mod tests {
use super::{encode, decode};
use super::{Query, QueryValue};
const DECODED: &str = "title=Encode some URLs";
const ENCODED: &str = "title%3DEncode%20some%20URLs";... |
#[test]
fn parse_query_vector_test() {
let expected = vec![
"apple".to_string(),
"banana".to_string(),
"coconut".to_string(),
];
if let Ok(query) = "fruits=apple,banana,coconut".parse::<Query>() {
assert_eq!(Some(&expected), query.get("fr... | {
if let Ok(query) = ENCODED.parse::<Query>() {
assert_eq!(Some(&"Encode some URLs".to_string()), query.get_first("title"));
} else {
assert!(false);
}
} | identifier_body |
lib.rs | extern crate urlencoding;
mod query;
pub use urlencoding::{encode, decode};
pub use query::{Query, QueryValue};
#[cfg(test)]
mod tests {
use super::{encode, decode};
use super::{Query, QueryValue};
const DECODED: &str = "title=Encode some URLs";
const ENCODED: &str = "title%3DEncode%20some%20URLs"; |
#[test]
fn parse_query_test() {
if let Ok(query) = ENCODED.parse::<Query>() {
assert_eq!(Some(&"Encode some URLs".to_string()), query.get_first("title"));
} else {
assert!(false);
}
}
#[test]
fn parse_query_vector_test() {
let expected = vec!... | random_line_split | |
tictactoe.rs | use crate::{game, statistics};
use r4::iterate;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Player {
X,
O,
}
impl statistics::two_player::PlayerMapping for Player {
fn player_one() -> Self {
Player::X
}
fn player_two() -> Self {
Player::O
}
fn resolve_player(&self) -> statistics:... | Tie,
}
impl Board {
pub fn new() -> Self {
Board {
cells: [[None, None, None], [None, None, None], [None, None, None]],
}
}
pub fn set(&mut self, row: usize, column: usize, value: Player) {
assert!(row < 3);
assert!(column < 3);
assert!(self.cells[row][column].is_none());
self.ce... | Winner(Player), | random_line_split |
tictactoe.rs | use crate::{game, statistics};
use r4::iterate;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum | {
X,
O,
}
impl statistics::two_player::PlayerMapping for Player {
fn player_one() -> Self {
Player::X
}
fn player_two() -> Self {
Player::O
}
fn resolve_player(&self) -> statistics::two_player::Player {
match *self {
Player::X => statistics::two_player::Player::One,
Player::O => ... | Player | identifier_name |
tictactoe.rs | use crate::{game, statistics};
use r4::iterate;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Player {
X,
O,
}
impl statistics::two_player::PlayerMapping for Player {
fn player_one() -> Self {
Player::X
}
fn player_two() -> Self {
Player::O
}
fn resolve_player(&self) -> statistics:... |
pub fn get(&self, row: usize, column: usize) -> Option<Player> {
assert!(row < 3);
assert!(column < 3);
self.cells[row][column]
}
pub fn outcome(&self) -> Option<Outcome> {
for n in 0..3 {
let mut p = winning_player(self.cells[n][0], self.cells[n][1], self.cells[n][2]);
if p.is_some... | {
assert!(row < 3);
assert!(column < 3);
assert!(self.cells[row][column].is_none());
self.cells[row][column] = Some(value);
} | identifier_body |
p_4_3_1_01.rs | // P_4_3_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | draw.line()
.start(pt2(pos_x, pos_y))
.end(pt2(pos_x + 5.0, pos_y + 5.0))
.weight(w1 * mouse_x_factor)
.caps_round()
.color(BLACK);
}
2 => {
... | match model.draw_mode {
1 => {
// greyscale to stroke weight
let w1 = map_range(greyscale, 0.0, 1.0, 15.0, 0.1); | random_line_split |
p_4_3_1_01.rs | // P_4_3_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | let tile_width = win.w() / w as f32;
let tile_height = win.h() / h as f32;
let pos_x = win.left() + tile_width * grid_x as f32 + (tile_width / 2.0);
let pos_y = win.top() - tile_height * grid_y as f32 - (tile_height / 2.0);
match model.draw_mode {
... | frame.clear(WHITE);
let draw = app.draw();
let win = app.window_rect();
let mouse_x_factor = map_range(app.mouse.x, win.left(), win.right(), 0.01, 1.0);
let mouse_y_factor = map_range(app.mouse.y, win.bottom(), win.top(), 0.01, 1.0);
let (w, h) = model.image.dimensions();
for grid_x in 0..... | identifier_body |
p_4_3_1_01.rs | // P_4_3_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | _ => (),
}
}
}
draw.to_frame(app, &frame).unwrap();
}
fn key_released(app: &App, model: &mut Model, key: Key) {
match key {
Key::Key1 => {
model.draw_mode = 1;
}
Key::Key2 => {
model.draw_mode = 2;
}
Key::Key3... | let draw = draw.x_y(pos_x, pos_y).rotate(greyscale * PI);
draw.rect()
.x_y(0.0, 0.0)
.w_h(15.0 * mouse_x_factor, 15.0 * mouse_y_factor)
.stroke_weight(1.0)
.stroke(rgb(1.0, greyscale, 0... | conditional_block |
p_4_3_1_01.rs | // P_4_3_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | p: &App, model: &mut Model, key: Key) {
match key {
Key::Key1 => {
model.draw_mode = 1;
}
Key::Key2 => {
model.draw_mode = 2;
}
Key::Key3 => {
model.draw_mode = 3;
}
Key::Key4 => {
model.draw_mode = 4;
}
... | _released(ap | identifier_name |
rotational-cipher.rs | extern crate rotational_cipher as cipher;
#[test]
fn rotate_a_1() {
assert_eq!("b", cipher::rotate("a", 1));
}
#[test]
#[ignore]
fn rotate_a_26() {
assert_eq!("a", cipher::rotate("a", 26));
}
#[test]
#[ignore]
fn rotate_a_0() {
assert_eq!("a", cipher::rotate("a", 0));
}
#[test] | #[test]
#[ignore]
fn rotate_n_13_with_wrap() {
assert_eq!("a", cipher::rotate("n", 13));
}
#[test]
#[ignore]
fn rotate_caps() {
assert_eq!("TRL", cipher::rotate("OMG", 5));
}
#[test]
#[ignore]
fn rotate_spaces() {
assert_eq!("T R L", cipher::rotate("O M G", 5));
}
#[test]
#[ignore]
fn rotate_numbers() {
... | #[ignore]
fn rotate_m_13() {
assert_eq!("z", cipher::rotate("m", 13));
}
| random_line_split |
rotational-cipher.rs | extern crate rotational_cipher as cipher;
#[test]
fn rotate_a_1() {
assert_eq!("b", cipher::rotate("a", 1));
}
#[test]
#[ignore]
fn rotate_a_26() {
assert_eq!("a", cipher::rotate("a", 26));
}
#[test]
#[ignore]
fn rotate_a_0() {
assert_eq!("a", cipher::rotate("a", 0));
}
#[test]
#[ignore]
fn rotate_m_13(... |
#[test]
#[ignore]
fn rotate_caps() {
assert_eq!("TRL", cipher::rotate("OMG", 5));
}
#[test]
#[ignore]
fn rotate_spaces() {
assert_eq!("T R L", cipher::rotate("O M G", 5));
}
#[test]
#[ignore]
fn rotate_numbers() {
assert_eq!("Xiwxmrk 1 2 3 xiwxmrk", cipher::rotate("Testing 1 2 3 testing", 4));
}
#[test... | {
assert_eq!("a", cipher::rotate("n", 13));
} | identifier_body |
rotational-cipher.rs | extern crate rotational_cipher as cipher;
#[test]
fn rotate_a_1() {
assert_eq!("b", cipher::rotate("a", 1));
}
#[test]
#[ignore]
fn rotate_a_26() {
assert_eq!("a", cipher::rotate("a", 26));
}
#[test]
#[ignore]
fn rotate_a_0() {
assert_eq!("a", cipher::rotate("a", 0));
}
#[test]
#[ignore]
fn rotate_m_13(... | () {
assert_eq!("a", cipher::rotate("n", 13));
}
#[test]
#[ignore]
fn rotate_caps() {
assert_eq!("TRL", cipher::rotate("OMG", 5));
}
#[test]
#[ignore]
fn rotate_spaces() {
assert_eq!("T R L", cipher::rotate("O M G", 5));
}
#[test]
#[ignore]
fn rotate_numbers() {
assert_eq!("Xiwxmrk 1 2 3 xiwxmrk", ci... | rotate_n_13_with_wrap | identifier_name |
trait-generic.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... | {
assert_eq!(foo(vec!(1)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
vec!("x".to_string(), "y".to_string()));
assert_eq!(bar::<(), Vec<()>>... | identifier_body | |
trait-generic.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... | (&self) -> String { "()".to_string() }
}
trait map<T> {
fn map<U, F>(&self, f: F) -> Vec<U> where F: FnMut(&T) -> U;
}
impl<T> map<T> for Vec<T> {
fn map<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
for i in self {
r.push(f(i));
}
... | to_string_ | identifier_name |
trait-generic.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... | }
r
}
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string_() )
}
pub fn main() {
assert_eq!(foo(vec!(1)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("... | impl<T> map<T> for Vec<T> {
fn map<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
for i in self {
r.push(f(i)); | random_line_split |
030.rs | use std::io::{self, BufRead};
use std::str::FromStr;
fn read_line<F>() -> Result<F, F::Err> where F: FromStr {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Could not read stdin!");
input.trim().parse()
}
fn is_writable(number: u32, power: u32) -> bool {
let mut sum = 0;
let mut n... | let power = read_line::<u32>().unwrap_or(0);
let sum = (10.. 10u32.pow(6)).filter(|&k| is_writable(k, power))
.fold(0, |sum, k| sum + k);
println!("{}", sum);
} | random_line_split | |
030.rs | use std::io::{self, BufRead};
use std::str::FromStr;
fn read_line<F>() -> Result<F, F::Err> where F: FromStr {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Could not read stdin!");
input.trim().parse()
}
fn | (number: u32, power: u32) -> bool {
let mut sum = 0;
let mut n = number;
while n > 0 {
sum += (n % 10).pow(power);
n /= 10;
}
sum == number
}
fn main() {
let power = read_line::<u32>().unwrap_or(0);
let sum = (10.. 10u32.pow(6)).filter(|&k| is_writable(k, power))
... | is_writable | identifier_name |
030.rs | use std::io::{self, BufRead};
use std::str::FromStr;
fn read_line<F>() -> Result<F, F::Err> where F: FromStr {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Could not read stdin!");
input.trim().parse()
}
fn is_writable(number: u32, power: u32) -> bool {
let mut sum = 0;
let mut n... | {
let power = read_line::<u32>().unwrap_or(0);
let sum = (10 .. 10u32.pow(6)).filter(|&k| is_writable(k, power))
.fold(0, |sum, k| sum + k);
println!("{}", sum);
} | identifier_body | |
vector.rs | #[derive(Debug, Copy, Clone)]
pub struct Vector2d {
x: f32,
y: f32,
}
impl Vector2d {
pub fn new(x: f32, y: f32) -> Vector2d {
Vector2d {
x: x,
y: y,
}
}
pub fn get_pos(&self) -> (f32, f32) {
(self.x, self.y)
}
}
#[derive(Debug, Copy, Clone)]
pu... | (self.x, self.y, self.z)
}
} | z: z,
}
}
pub fn get_pos(&self) -> (f32, f32, f32) { | random_line_split |
vector.rs | #[derive(Debug, Copy, Clone)]
pub struct Vector2d {
x: f32,
y: f32,
}
impl Vector2d {
pub fn new(x: f32, y: f32) -> Vector2d {
Vector2d {
x: x,
y: y,
}
}
pub fn get_pos(&self) -> (f32, f32) {
(self.x, self.y)
}
}
#[derive(Debug, Copy, Clone)]
pu... | (x: f32, y: f32, z: f32) -> Vector3d {
Vector3d {
x: x,
y: y,
z: z,
}
}
pub fn get_pos(&self) -> (f32, f32, f32) {
(self.x, self.y, self.z)
}
}
| new | identifier_name |
read_method.rs | use super::branchify::generate_branchified_method;
use super::get_writer;
use std::io::IoResult;
pub fn generate(output_dir: Path) -> IoResult<()> {
let mut writer = get_writer(output_dir, "read_method.rs");
try!(writer.write(b"\
// This automatically generated file is included in request.rs.
pub mod dummy {
u... | use server::request::MAX_METHOD_LEN;
use rfc2616::{SP, is_token_item};
use buffer::BufferedStream;
#[inline]
pub fn read_method<S: Stream>(stream: &mut BufferedStream<S>) -> IoResult<Method> {
"));
try!(generate_branchified_method(
&mut *writer,
branchify!(case sensitive,
"CONNECT" => ... | use method::Method::{Connect, Delete, Get, Head, Options, Patch, Post, Put, Trace, ExtensionMethod}; | random_line_split |
read_method.rs | use super::branchify::generate_branchified_method;
use super::get_writer;
use std::io::IoResult;
pub fn | (output_dir: Path) -> IoResult<()> {
let mut writer = get_writer(output_dir, "read_method.rs");
try!(writer.write(b"\
// This automatically generated file is included in request.rs.
pub mod dummy {
use std::io::{Stream, IoResult};
use method::Method;
use method::Method::{Connect, Delete, Get, Head, Options, Pat... | generate | identifier_name |
read_method.rs | use super::branchify::generate_branchified_method;
use super::get_writer;
use std::io::IoResult;
pub fn generate(output_dir: Path) -> IoResult<()> | "DELETE" => Delete,
"GET" => Get,
"HEAD" => Head,
"OPTIONS" => Options,
"PATCH" => Patch,
"POST" => Post,
"PUT" => Put,
"TRACE" => Trace
),
1,
"stream.read_byte()",
"SP",
... | {
let mut writer = get_writer(output_dir, "read_method.rs");
try!(writer.write(b"\
// This automatically generated file is included in request.rs.
pub mod dummy {
use std::io::{Stream, IoResult};
use method::Method;
use method::Method::{Connect, Delete, Get, Head, Options, Patch, Post, Put, Trace, ExtensionMeth... | identifier_body |
dispatcher.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::io::{self, Cursor};
use std::net::SocketAddr;
use std::thread;
use bip_handshake::{DiscoveryInfo, InitiateMessage, Protocol};
use bip_util::bt::PeerId;
use chrono::{DateTime, Duration};
use chrono::offset::Utc;
use futures::future::Either;
... | {
addr: SocketAddr,
attempt: u64,
request: ClientRequest,
timeout_id: Option<Timeout>,
}
impl ConnectTimer {
/// Create a new ConnectTimer.
pub fn new(addr: SocketAddr, request: ClientRequest) -> ConnectTimer {
ConnectTimer {
addr: addr,
attempt: 0,
... | ConnectTimer | identifier_name |
dispatcher.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::io::{self, Cursor};
use std::net::SocketAddr;
use std::thread;
use bip_handshake::{DiscoveryInfo, InitiateMessage, Protocol};
use bip_util::bt::PeerId;
use chrono::{DateTime, Duration};
use chrono::offset::Utc;
use futures::future::Either;
... |
/// Process a request to be sent to the given address and associated with the given token.
pub fn send_request<'a>(&mut self,
provider: &mut Provider<'a, ClientDispatcher<H>>,
addr: SocketAddr,
token: ClientToken,
... | {
self.handshaker.send(Either::B(ClientMetadata::new(token, result)).into())
.unwrap_or_else(|_| panic!("NEED TO FIX"));
self.limiter.acknowledge();
} | identifier_body |
dispatcher.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::io::{self, Cursor};
use std::net::SocketAddr;
use std::thread;
use bip_handshake::{DiscoveryInfo, InitiateMessage, Protocol};
use bip_util::bt::PeerId;
use chrono::{DateTime, Duration};
use chrono::offset::Utc;
use futures::future::Either;
... |
Some(calculate_message_timeout_millis(self.attempt))
}
}
/// Yields the current timeout id if one is set.
pub fn timeout_id(&self) -> Option<Timeout> {
self.timeout_id
}
/// Sets a new timeout id.
pub fn set_timeout_id(&mut self, id: Timeout) {
self.timeout... | } else {
if timed_out {
self.attempt += 1;
} | random_line_split |
os.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 ... | }
impl Drop for Env {
fn drop(&mut self) {
unsafe { FreeEnvironmentStringsW(self.base); }
}
}
pub fn env() -> Env {
unsafe {
let ch = GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
IoError::last_error(... | } | random_line_split |
os.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 ... | (&mut self) {
unsafe { FreeEnvironmentStringsW(self.base); }
}
}
pub fn env() -> Env {
unsafe {
let ch = GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
IoError::last_error());
}
Env { base: ... | drop | identifier_name |
os.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let v = path.encode_wide().collect::<Vec<u16>>();
if v.contains(&(b'"' as u16)) {
return Err(JoinPathsError)
} else if v.contains(&sep) {
joined.push(b'"' as u16);
joined.push_all(&v[]);
joined.push(b'"' as u16);
} else {
joine... | { joined.push(sep) } | conditional_block |
os.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub struct SplitPaths<'a> {
data: EncodeWide<'a>,
must_yield: bool,
}
pub fn split_paths(unparsed: &OsStr) -> SplitPaths {
SplitPaths {
data: unparsed.encode_wide(),
must_yield: true,
}
}
impl<'a> Iterator for SplitPaths<'a> {
type Item = Path;
fn next(&mut self) -> Option<Pa... | {
unsafe {
let ch = GetEnvironmentStringsW();
if ch as usize == 0 {
panic!("failure getting env string from OS: {}",
IoError::last_error());
}
Env { base: ch, cur: ch }
}
} | identifier_body |
entry.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... |
/// Autolink entry to entries linked in content with the passed `LinkProcessor` instance.
///
/// See the documentation of `::libimagentrymarkdown::processor::LinkProcessor`.
fn autolink_with_processor(&mut self, store: &Store, processor: LinkProcessor) -> Result<()> {
processor.process(self, ... | {
let processor = LinkProcessor::default()
.process_links(true)
.create_targets(true)
.process_urls(true)
.process_refs(true);
self.autolink_with_processor(store, processor)
} | identifier_body |
entry.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... | /// * Processing of Refs = true
///
/// This is a convenience function for `WikiEntry::autolink_with_processor()`.
///
/// # Warning
///
/// With this function, the `LinkProcessor` automatically creates entries in the store if they
/// are linked from the current entry but do not ... | /// Uses `libimagentrymarkdown::processor::LinkProcessor` for this, with the following settings:
///
/// * Interal link processing = true
/// * Internal targets creating = true
/// * External link processing = true | random_line_split |
entry.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... | (&mut self, store: &Store) -> Result<()> {
let processor = LinkProcessor::default()
.process_links(true)
.create_targets(true)
.process_urls(true)
.process_refs(true);
self.autolink_with_processor(store, processor)
}
/// Autolink entry to entries lin... | autolink | identifier_name |
xul.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
// Non-standard properties th... |
${helpers.predefined_type(
"-moz-box-ordinal-group",
"Integer",
"0",
parse_method="parse_non_negative",
products="gecko",
alias="-webkit-box-ordinal-group",
gecko_ffi_name="mBoxOrdinal",
animation_value_type="discrete",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web... | gecko_enum_prefix="StyleStackSizing",
animation_value_type="discrete",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-stack-sizing)",
)} | random_line_split |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... | <Handle> {
AppendNode(Handle),
AppendText(String),
}
/// Types which can process tree modifications from the tree builder.
pub trait TreeSink {
/// `Handle` is a reference to a DOM node. The tree builder requires
/// that a `Handle` implements `Clone` to get another reference to
/// the same node.... | NodeOrText | identifier_name |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... |
}
/// Trace hooks for a garbage-collected DOM.
pub trait Tracer {
type Handle;
/// Upon a call to `trace_handles`, the tree builder will call this method
/// for each handle in its internal state.
fn trace_handle(&self, node: Self::Handle);
}
| { } | identifier_body |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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>,... |
/// Do two handles refer to the same node?
fn same_node(&self, x: Self::Handle, y: Self::Handle) -> bool;
/// What is the name of this element?
///
/// Should never be called on a non-element node;
/// feel free to `panic!`.
fn elem_name(&self, target: Self::Handle) -> QualName;
/// S... | random_line_split | |
command.rs | use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, Write, BufRead, BufReader, Seek, SeekFrom};
use std::process::{self, Command, Stdio};
use std::time::Instant;
use regex::Regex;
use tempfile::tempfile;
use Cfg;
use errors::*;
use notifications::*;
use rustup_utils;
use telemetry::{Telemetry, TelemetryEvent};... | else { Some(errors) };
let te = TelemetryEvent::RustcRun { duration_ms: ms,
exit_code: exit_code,
errors: e };
let _ = t.log_telemetry(te).map_err(|xe| {
(cfg.notify_handler)(Notifi... | { None } | conditional_block |
command.rs | use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, Write, BufRead, BufReader, Seek, SeekFrom};
use std::process::{self, Command, Stdio};
use std::time::Instant;
use regex::Regex;
use tempfile::tempfile;
use Cfg;
use errors::*;
use notifications::*;
use rustup_utils;
use telemetry::{Telemetry, TelemetryEvent};... | (file: &File) -> Stdio {
use std::os::unix::io::{AsRawFd, FromRawFd};
unsafe { Stdio::from_raw_fd(file.as_raw_fd()) }
}
#[cfg(windows)]
fn file_as_stdio(file: &File) -> Stdio {
use std::os::windows::io::{AsRawHandle, FromRawHandle};
unsafe { Stdio::from_raw_handle(file.as_ra... | file_as_stdio | identifier_name |
command.rs | use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, Write, BufRead, BufReader, Seek, SeekFrom};
use std::process::{self, Command, Stdio};
use std::time::Instant;
use regex::Regex;
use tempfile::tempfile;
use Cfg;
use errors::*;
use notifications::*;
use rustup_utils;
use telemetry::{Telemetry, TelemetryEvent};... | };
}
let e = if errors.is_empty() { None } else { Some(errors) };
let te = TelemetryEvent::RustcRun { duration_ms: ms,
exit_code: exit_code,
errors: e };
let... |
if let Some(caps) = re.captures(&b) {
if !caps.is_empty() {
errors.push(caps.name("error").unwrap_or("").to_owned());
} | random_line_split |
command.rs | use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, Write, BufRead, BufReader, Seek, SeekFrom};
use std::process::{self, Command, Stdio};
use std::time::Instant;
use regex::Regex;
use tempfile::tempfile;
use Cfg;
use errors::*;
use notifications::*;
use rustup_utils;
use telemetry::{Telemetry, TelemetryEvent};... | {
type DWORD = u32;
type BOOL = i32;
type HANDLE = *mut u8;
const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
extern "system" {
fn GetStdHandle(which: DWORD) -> HANDLE;
fn GetConsoleMode(hConsoleHandle: HANDLE,
lpMode: *mut DWORD) -> BOOL;
}
unsafe {
... | identifier_body | |
method-self-arg.rs | // run-pass
// Test method calls with self as an argument
static mut COUNT: usize = 1;
#[derive(Copy, Clone)]
struct Foo;
impl Foo {
fn foo(self, x: &Foo) {
unsafe { COUNT *= 2; }
// Test internal call.
Foo::bar(&self);
Foo::bar(x);
Foo::baz(self);
Foo::baz(*x);
... |
x.foo(&x);
unsafe { assert_eq!(COUNT, 2*3*3*3*5*5*5*7*7*7); }
} | let x = Foo;
// Test external call.
Foo::bar(&x);
Foo::baz(x);
Foo::qux(Box::new(x)); | random_line_split |
method-self-arg.rs | // run-pass
// Test method calls with self as an argument
static mut COUNT: usize = 1;
#[derive(Copy, Clone)]
struct Foo;
impl Foo {
fn foo(self, x: &Foo) |
fn bar(&self) {
unsafe { COUNT *= 3; }
}
fn baz(self) {
unsafe { COUNT *= 5; }
}
fn qux(self: Box<Foo>) {
unsafe { COUNT *= 7; }
}
}
fn main() {
let x = Foo;
// Test external call.
Foo::bar(&x);
Foo::baz(x);
Foo::qux(Box::new(x));
x.foo(&x);
... | {
unsafe { COUNT *= 2; }
// Test internal call.
Foo::bar(&self);
Foo::bar(x);
Foo::baz(self);
Foo::baz(*x);
Foo::qux(Box::new(self));
Foo::qux(Box::new(*x));
} | identifier_body |
method-self-arg.rs | // run-pass
// Test method calls with self as an argument
static mut COUNT: usize = 1;
#[derive(Copy, Clone)]
struct Foo;
impl Foo {
fn foo(self, x: &Foo) {
unsafe { COUNT *= 2; }
// Test internal call.
Foo::bar(&self);
Foo::bar(x);
Foo::baz(self);
Foo::baz(*x);
... | () {
let x = Foo;
// Test external call.
Foo::bar(&x);
Foo::baz(x);
Foo::qux(Box::new(x));
x.foo(&x);
unsafe { assert_eq!(COUNT, 2*3*3*3*5*5*5*7*7*7); }
}
| main | identifier_name |
adt-brace-structs.rs | // Unit test for the "user substitutions" that are annotated on each
// node.
struct SomeStruct<T> { t: T }
fn no_annot() {
let c = 66;
SomeStruct { t: &c };
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_> { t: &c };
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32> ... | <'a>(_: &'a u32) {
let _closure = || {
let c = 66;
SomeStruct::<&'a u32> { t: &c }; //~ ERROR
};
}
fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) {
let _closure = || {
SomeStruct::<&'a u32> { t: c };
};
}
fn main() { }
| annot_reference_named_lifetime_in_closure | identifier_name |
adt-brace-structs.rs | fn no_annot() {
let c = 66;
SomeStruct { t: &c };
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_> { t: &c };
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32> { t: &c };
}
fn annot_reference_static_lifetime() {
let c = 66;
SomeStruct::<&'static u32> { t: &c };... | // Unit test for the "user substitutions" that are annotated on each
// node.
struct SomeStruct<T> { t: T }
| random_line_split | |
adt-brace-structs.rs | // Unit test for the "user substitutions" that are annotated on each
// node.
struct SomeStruct<T> { t: T }
fn no_annot() {
let c = 66;
SomeStruct { t: &c };
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_> { t: &c };
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32> ... |
fn main() { }
| {
let _closure = || {
SomeStruct::<&'a u32> { t: c };
};
} | identifier_body |
transaction.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 bytes::Bytes;
use hash::{Address, H256};
use maybe::MaybeEmpty;
/// State test transaction deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Transaction {
/// Transaction data.
pub data: Bytes,
/// Gas limit.
#[serde(rename="gasLimit")]
pub gas_limit: Uint,
/// Gas price.
#[serde(rename="... | random_line_split | |
transaction.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... |
}
| {
let s = r#"{
"data" : "",
"gasLimit" : "0x2dc6c0",
"gasPrice" : "0x01",
"nonce" : "0x00",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "1000000000000000000000000000000000000000",
"value" : "0x00"
}"#;
let _deserialized: Transaction = serde_json::f... | identifier_body |
transaction.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... | () {
let s = r#"{
"data" : "",
"gasLimit" : "0x2dc6c0",
"gasPrice" : "0x01",
"nonce" : "0x00",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "1000000000000000000000000000000000000000",
"value" : "0x00"
}"#;
let _deserialized: Transaction = serde_json... | transaction_deserialization | identifier_name |
overflowing_pow.rs | use num::arithmetic::traits::{OverflowingPow, OverflowingPowAssign};
use num::conversion::traits::ExactFrom;
macro_rules! impl_overflowing_pow {
($t:ident) => {
impl OverflowingPow<u64> for $t {
type Output = $t;
#[inline]
fn overflowing_pow(self, exp: u64) -> ($t, bool... | impl OverflowingPowAssign<u64> for $t {
/// Replaces `self` with `self ^ exp`.
///
/// Returns a boolean indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred, then the wrapped value is assigned.
///
... | }
| random_line_split |
instant_seal.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... | (&self) -> &M { &self.machine }
fn seals_internally(&self) -> Option<bool> { Some(true) }
fn generate_seal(&self, block: &M::LiveBlock) -> Seal {
if block.transactions().is_empty() { Seal::None } else { Seal::Regular(Vec::new()) }
}
fn verify_local_seal(&self, _header: &M::Header) -> Result<(), M::Error> {
O... | machine | identifier_name |
instant_seal.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... |
fn machine(&self) -> &M { &self.machine }
fn seals_internally(&self) -> Option<bool> { Some(true) }
fn generate_seal(&self, block: &M::LiveBlock) -> Seal {
if block.transactions().is_empty() { Seal::None } else { Seal::Regular(Vec::new()) }
}
fn verify_local_seal(&self, _header: &M::Header) -> Result<(), M:... | {
"InstantSeal"
} | identifier_body |
instant_seal.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... | else { Seal::Regular(Vec::new()) }
}
fn verify_local_seal(&self, _header: &M::Header) -> Result<(), M::Error> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use bigint::hash::H520;
use util::*;
use tests::helpers::*;
use spec::Spec;
use header::Header;
use block::*;
use engines::Seal;
#[tes... | { Seal::None } | conditional_block |
instant_seal.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... | let last_hashes = Arc::new(vec![genesis_header.hash()]);
let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::default(), (3141562.into(), 31415620.into()), vec![], false).unwrap();
let b = b.close_and_lock();
if let Seal::Regular(seal) = engine.generate_seal(b.blo... | random_line_split | |
main.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
fn get_input() -> i32 {
let mut file = File::open("input.txt").unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
content.parse().unwrap()
}
#[derive(Copy, Clone, Debug)]
enum Direction {
... | {
stride: i32,
left: i32,
x: i32,
y: i32,
dir: Direction
}
impl State {
fn move_next(self: &mut State) {
if self.left > 0 {
match self.dir {
Direction::XPos => self.x += 1,
Direction::XNeg => self.x -= 1,
Direction::YPos => se... | State | identifier_name |
main.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
fn get_input() -> i32 {
let mut file = File::open("input.txt").unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
content.parse().unwrap()
}
#[derive(Copy, Clone, Debug)]
enum Direction {
... | Direction::XNeg => self.x -= 1,
Direction::YPos => self.y += 1,
Direction::YNeg => self.y -= 1
}
self.left -= 1;
} else {
match self.dir {
Direction::XPos => {
self.dir = Direction::YPos;
... | match self.dir {
Direction::XPos => self.x += 1, | random_line_split |
main.rs | #[cfg(debug_assertions)]
#[macro_use] extern crate log;
extern crate crypto;
#[cfg(debug_assertions)]
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate hyper;
extern crate librespot;
extern crate rpassword;
#[macro_use]
extern crate serde_json;
extern crate tokio_core;
extern crate tokio... | .optopt("T", "save-token", "Get oauth token to be used with the web API etc. and store it in the given file.", "TOKENFILE")
.optopt("i", "client-id", "A Spotify client_id to be used to get the oauth token. Required with the --get-token request.", "CLIENT_ID")
.optopt("", "scope", "The scopes you want to have acce... | {
let mut opts = getopts::Options::new();
opts.optopt("c", "cache", "Path to a directory where files will be cached.", "CACHE")
.optflag("", "enable-audio-cache", "Enable caching of the audio data.")
.optflag("", "disable-audio-cache", "(Only here fore compatibility with librespot - audio cache is disabled by def... | identifier_body |
main.rs | #[cfg(debug_assertions)]
#[macro_use] extern crate log;
extern crate crypto;
#[cfg(debug_assertions)]
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate hyper;
extern crate librespot;
extern crate rpassword;
#[macro_use]
extern crate serde_json;
extern crate tokio_core;
extern crate tokio... | if!progress {
return Ok(Async::NotReady);
}
}
}
}
fn main() {
let mut core = Core::new().unwrap();
let handle = core.handle();
let args: Vec<String> = std::env::args().collect();
let Setup {
cache,
session_config,
player_config,
connect_config,
credentials,
authenticate,
enable_discover... | random_line_split | |
main.rs | #[cfg(debug_assertions)]
#[macro_use] extern crate log;
extern crate crypto;
#[cfg(debug_assertions)]
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate hyper;
extern crate librespot;
extern crate rpassword;
#[macro_use]
extern crate serde_json;
extern crate tokio_core;
extern crate tokio... | ,
client_id: if client_id.as_str().len() == 0 { None } else { Some(client_id) },
scope: matches.opt_str("scope"),
single_track: matches.opt_str("single-track"),
start_position: (start_position * 1000.0) as u32,
lms: lms
}
}
struct Main {
cache: Option<Cache>,
player_config: PlayerConfig,
session_confi... | { Some(save_token) } | conditional_block |
main.rs | #[cfg(debug_assertions)]
#[macro_use] extern crate log;
extern crate crypto;
#[cfg(debug_assertions)]
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate hyper;
extern crate librespot;
extern crate rpassword;
#[macro_use]
extern crate serde_json;
extern crate tokio_core;
extern crate tokio... | (handle: Handle, setup: Setup) -> Main {
let mut task = Main {
handle: handle.clone(),
cache: setup.cache,
session_config: setup.session_config,
player_config: setup.player_config,
connect_config: setup.connect_config,
connect: Box::new(futures::future::empty()),
discovery: None,
spirc: None,... | new | identifier_name |
color.rs | use crate::rank::Rank;
use std::ops::Not;
/// Represent a color.
#[derive(PartialOrd, PartialEq, Eq, Copy, Clone, Debug, Hash)]
pub enum Color {
White,
Black,
}
/// How many colors are there?
pub const NUM_COLORS: usize = 2;
/// List all colors
pub const ALL_COLORS: [Color; NUM_COLORS] = [Color::White, Color:... |
/// Convert a `Color` to my opponents backrank, which represents the starting rank for the
/// opponents pieces.
#[inline]
pub fn to_their_backrank(&self) -> Rank {
match *self {
Color::White => Rank::Eighth,
Color::Black => Rank::First,
}
}
/// Convert... | {
match *self {
Color::White => Rank::First,
Color::Black => Rank::Eighth,
}
} | identifier_body |
color.rs | use crate::rank::Rank;
use std::ops::Not;
/// Represent a color.
#[derive(PartialOrd, PartialEq, Eq, Copy, Clone, Debug, Hash)]
pub enum Color {
White,
Black,
}
/// How many colors are there?
pub const NUM_COLORS: usize = 2;
/// List all colors
pub const ALL_COLORS: [Color; NUM_COLORS] = [Color::White, Color:... | match *self {
Color::White => Rank::Fourth,
Color::Black => Rank::Fifth,
}
}
/// Convert a `Color` to my seventh rank, which represents the rank before pawn promotion.
#[inline]
pub fn to_seventh_rank(&self) -> Rank {
match *self {
Color::Whit... | #[inline]
pub fn to_fourth_rank(&self) -> Rank { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.