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 |
|---|---|---|---|---|
raw.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 crate::common::*;
use crate::user;
use chrono;
use serde::Deserialize;
use super::DMEntities;
#[derive(Debug, ... | {
///Numeric ID for this DM.
pub id: u64,
///UTC timestamp from when this DM was created.
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: chrono::DateTime<chrono::Utc>,
///The text of the DM.
pub text: String,
///Link, hashtag, and user mention information parsed out... | RawDirectMessage | identifier_name |
mod.rs | pub type Tag = u32;
pub type Vec2 = (f64, f64);
pub type Vec3 = (f64, f64, f64);
pub type Vec4 = (f64, f64, f64, f64);
pub type Box2 = (Vec2, Vec2);
#[derive(PartialEq, Debug)]
pub enum | {
Tag(Tag),
Bool(bool),
BoolArray(Box<[bool]>),
Int(i32),
IntArray(Box<[i32]>),
Double(f64),
DoubleArray(Box<[f64]>),
Vec2(Vec2),
Vec2Array(Box<[Vec2]>),
Vec3(Vec3),
Vec3Array(Box<[Vec3]>),
Vec4(Vec4),
Vec4Array(Box<[Vec4]>),
Box2(Box2),
Box2Array(Box<[Box2]>... | Value | identifier_name |
mod.rs | pub type Tag = u32;
pub type Vec2 = (f64, f64);
pub type Vec3 = (f64, f64, f64);
pub type Vec4 = (f64, f64, f64, f64);
pub type Box2 = (Vec2, Vec2);
#[derive(PartialEq, Debug)]
pub enum Value {
Tag(Tag),
Bool(bool),
BoolArray(Box<[bool]>),
Int(i32),
IntArray(Box<[i32]>),
Double(f64),
Double... | Box2Array(Box<[Box2]>),
String(Box<str>),
Blob(Box<[u8]>)
}
#[macro_use]
pub mod macros;
pub mod reader;
mod binary_reader;
mod text_reader;
pub mod writer;
mod binary_writer;
mod text_writer;
pub use self::reader::{Token, Reader};
pub use self::binary_reader::BinaryReader;
pub use self::text_reader::Te... | Vec4Array(Box<[Vec4]>),
Box2(Box2), | random_line_split |
pinger.rs | extern crate byteorder;
extern crate fcp;
extern crate fcp_cryptoauth;
extern crate hex;
extern crate rand;
use std::collections::{HashMap, VecDeque};
use std::iter::FromIterator;
use std::net::{IpAddr, Ipv6Addr, SocketAddr, UdpSocket};
use std::str::FromStr;
use fcp_cryptoauth::keys::ToBase32;
use fcp_cryptoauth::*;... | (&mut self, node: &Node, message: DataPacket) {
let node_pk = PublicKey::from_slice(node.public_key()).unwrap();
let addr = publickey_to_ipv6addr(&node_pk).into();
let my_handle_opt = self.address_to_my_handle.get(&addr).map(|h| *h);
match my_handle_opt {
Some(my_handle) => s... | send_message_to_node | identifier_name |
pinger.rs | extern crate byteorder;
extern crate fcp;
extern crate fcp_cryptoauth;
extern crate hex;
extern crate rand;
use std::collections::{HashMap, VecDeque};
use std::iter::FromIterator;
use std::net::{IpAddr, Ipv6Addr, SocketAddr, UdpSocket};
use std::str::FromStr;
use fcp_cryptoauth::keys::ToBase32;
use fcp_cryptoauth::*;... |
}
fn dispatch(&mut self, packet: SwitchPacket, from_interface: Director) {
self.plumbing.dispatch(packet, from_interface);
}
fn loop_(&mut self) {
loop {
let packets = self.plumbing.session_manager.upkeep();
for packet in packets {
self.plumbing... | {
println!("Pinging nodes.");
for address in self.ping_targets.clone() {
if !self.address_to_my_handle.contains_key(&address) {
self.try_connect_ping_target(&address)
}
}
for node in self.ping_nodes.clone() {
... | conditional_block |
pinger.rs | extern crate byteorder;
extern crate fcp;
extern crate fcp_cryptoauth;
extern crate hex;
extern crate rand;
use std::collections::{HashMap, VecDeque};
use std::iter::FromIterator;
use std::net::{IpAddr, Ipv6Addr, SocketAddr, UdpSocket};
use std::str::FromStr;
use fcp_cryptoauth::keys::ToBase32;
use fcp_cryptoauth::*;... |
fn loop_(&mut self) {
loop {
let packets = self.plumbing.session_manager.upkeep();
for packet in packets {
self.plumbing.dispatch(packet, 0b001);
}
let mut targets = Vec::new();
for (my_handle, ref mut session) in self.plumbing.s... | {
self.plumbing.dispatch(packet, from_interface);
} | identifier_body |
pinger.rs | extern crate byteorder;
extern crate fcp;
extern crate fcp_cryptoauth;
extern crate hex;
extern crate rand;
use std::collections::{HashMap, VecDeque};
use std::iter::FromIterator;
use std::net::{IpAddr, Ipv6Addr, SocketAddr, UdpSocket};
use std::str::FromStr;
use fcp_cryptoauth::keys::ToBase32;
use fcp_cryptoauth::*;... | allowed_peers: HashMap<Credentials, String>,
ping_targets: Vec<Address>,
) -> Pinger {
let udp_adapter = UdpAdapter::new(
sock,
my_pk.clone(),
my_sk.clone(),
allowed_peers.clone(),
peers,
);
let session_manager = Ses... | my_sk: SecretKey, | random_line_split |
module.rs | use std::ffi::CStr;
use std::marker::PhantomData;
use llvm_sys::prelude::*;
use llvm_sys::core::*;
use llvm_sys::target::LLVMSetModuleDataLayout;
use id::{Id, IdRef};
use inheritance::{upcast, DerivesFrom};
use opaque::Opaque;
use owned::{Owned, DropInPlace};
use llvm::{Context, FunctionType, Type, Global, Function,... |
}
| {
self as *const ModuleBuilder as *mut ModuleBuilder as LLVMModuleRef
} | identifier_body |
module.rs | use std::ffi::CStr;
use std::marker::PhantomData;
use llvm_sys::prelude::*;
use llvm_sys::core::*;
use llvm_sys::target::LLVMSetModuleDataLayout;
use id::{Id, IdRef};
use inheritance::{upcast, DerivesFrom};
use opaque::Opaque;
use owned::{Owned, DropInPlace};
use llvm::{Context, FunctionType, Type, Global, Function,... | LLVMModuleCreateWithNameInContext(name.as_ptr(), context.as_raw()) as *mut Module
)
}
}
pub fn set_data_layout(&mut self, layout: &DataLayout) {
unsafe {
LLVMSetModuleDataLayout(self.as_raw(), layout.as_raw());
}
}
pub fn set_target_tripl... | Owned::from_raw( | random_line_split |
module.rs | use std::ffi::CStr;
use std::marker::PhantomData;
use llvm_sys::prelude::*;
use llvm_sys::core::*;
use llvm_sys::target::LLVMSetModuleDataLayout;
use id::{Id, IdRef};
use inheritance::{upcast, DerivesFrom};
use opaque::Opaque;
use owned::{Owned, DropInPlace};
use llvm::{Context, FunctionType, Type, Global, Function,... | <'cid: 'context, 'context,'mid> {
_id: Id<'mid>,
_context: PhantomData<&'context Context<'cid>>,
_opaque: Opaque
}
impl<'cid, 'context,'mid> DropInPlace for Module<'cid, 'context,'mid> {
unsafe fn drop_in_place(&mut self) {
LLVMDisposeModule(self.as_raw());
}
}
impl<'cid, 'context,'mid> Mo... | Module | identifier_name |
module.rs | use std::ffi::CStr;
use std::marker::PhantomData;
use llvm_sys::prelude::*;
use llvm_sys::core::*;
use llvm_sys::target::LLVMSetModuleDataLayout;
use id::{Id, IdRef};
use inheritance::{upcast, DerivesFrom};
use opaque::Opaque;
use owned::{Owned, DropInPlace};
use llvm::{Context, FunctionType, Type, Global, Function,... |
}
}
pub fn reborrow<'a>(&'a mut self) -> &'a mut ModuleBuilder<'cid,'mid, 'a> {
unsafe {
&mut *(self.as_raw() as *mut ModuleBuilder)
}
}
pub fn as_raw(&self) -> LLVMModuleRef {
self as *const ModuleBuilder as *mut ModuleBuilder as LLVMModuleRef
}
}
| {
Some(&*(old as *mut FunctionLabel))
} | conditional_block |
template.rs | use std::fs::{self, File};
use std::io::{self, Error, ErrorKind, Read};
use std::path::{Path, PathBuf};
use super::{Name, Statement};
// A binding of template source file information and the parsed AST.
#[derive(Debug)]
pub struct Template {
pub tree: Statement,
pub path: PathBuf,
pub name: String,
id... | (base: &Path, path: &Path) -> String {
let base = path.strip_prefix(base).unwrap();
let stem = base.file_stem().unwrap();
let name = base.with_file_name(stem);
String::from(name.to_str().unwrap())
}
fn parse_dir(base: &Path, dir: &Path) -> io::Result<Vec<Template>> {
let mut templates = Vec::new();... | name | identifier_name |
template.rs | use std::fs::{self, File};
use std::io::{self, Error, ErrorKind, Read};
use std::path::{Path, PathBuf};
use super::{Name, Statement};
// A binding of template source file information and the parsed AST.
#[derive(Debug)]
pub struct Template {
pub tree: Statement,
pub path: PathBuf,
pub name: String,
id... | }
/// Creates a shortened path name for a template file name. The base directory
/// being compiled and the file extension is stripped off to create the short
/// name: `app/templates/include/header.mustache -> include/header`.
fn name(base: &Path, path: &Path) -> String {
let base = path.strip_prefix(base).unwrap... | random_line_split | |
template.rs | use std::fs::{self, File};
use std::io::{self, Error, ErrorKind, Read};
use std::path::{Path, PathBuf};
use super::{Name, Statement};
// A binding of template source file information and the parsed AST.
#[derive(Debug)]
pub struct Template {
pub tree: Statement,
pub path: PathBuf,
pub name: String,
id... |
}
/// Creates a shortened path name for a template file name. The base directory
/// being compiled and the file extension is stripped off to create the short
/// name: `app/templates/include/header.mustache -> include/header`.
fn name(base: &Path, path: &Path) -> String {
let base = path.strip_prefix(base).unwra... | {
Name::new(&self.name)
} | identifier_body |
lib.rs | #![allow(dead_code)]
use std::collections::{BTreeMap, HashMap};
use std::iter::FromIterator;
type DocId = i32;
const MIN_DOC_ID: DocId = std::i32::MIN;
const MAX_DOC_ID: DocId = std::i32::MAX;
#[derive(Clone, Debug, PartialEq)]
struct ScoredDoc {
id: DocId,
score: f32,
}
struct Term<'a> {
field: &'a str,... |
}
if matched_doc_count == frontier_length - 1 {
return Some(ScoredDoc {
id: last_viable_id,
score,
});
}
self.last_viable_id = last_viable_id;
self.sta... | {
let score_contribution = *weight * doc.score;
if doc.id == last_viable_id {
score += score_contribution;
matched_doc_count += 1;
} else {
score = score_contributi... | conditional_block |
lib.rs | #![allow(dead_code)]
use std::collections::{BTreeMap, HashMap};
use std::iter::FromIterator;
type DocId = i32;
const MIN_DOC_ID: DocId = std::i32::MIN;
const MAX_DOC_ID: DocId = std::i32::MAX;
#[derive(Clone, Debug, PartialEq)]
struct ScoredDoc {
id: DocId,
score: f32, |
struct Term<'a> {
field: &'a str,
token: &'a str,
weight: f32,
}
// used to populate an index in a simple way
type IndexEntry<'a> = (&'a str, &'a str, DocId, f32);
type DensePostingList = Vec<ScoredDoc>;
type WeightedPostingListIterator<'a> = (f32, std::slice::Iter<'a, ScoredDoc>);
#[derive(Debug)]
str... | } | random_line_split |
lib.rs | #![allow(dead_code)]
use std::collections::{BTreeMap, HashMap};
use std::iter::FromIterator;
type DocId = i32;
const MIN_DOC_ID: DocId = std::i32::MIN;
const MAX_DOC_ID: DocId = std::i32::MAX;
#[derive(Clone, Debug, PartialEq)]
struct ScoredDoc {
id: DocId,
score: f32,
}
struct Term<'a> {
field: &'a str,... | <'a> {
state: AndState,
frontier: Vec<WeightedPostingListIterator<'a>>,
last_viable_id: i32,
}
// TODO: ctor that takes in existing iterators
impl<'a> And<'a> {
fn new(index: &'a InvertedIndexNaive, terms: &[Term<'a>]) -> Self {
let mut frontier = Vec::with_capacity(terms.len());
for lo... | And | identifier_name |
stop_signs.rs | // Copyright 2018 Google LLC
//
// 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 ... |
}
true
}
pub fn changed(&self) -> bool {
// TODO detect edits that've been undone, equivalent to original
self.changed
}
pub fn get_savestate(&self) -> Option<ModifiedStopSign> {
if!self.changed() {
return None;
}
Some(ModifiedStopS... | {
return false;
} | conditional_block |
stop_signs.rs | // Copyright 2018 Google LLC
//
// 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 ... | for (t, pri) in &self.turns {
if *pri == TurnPriority::Priority
&& geom_map.get_t(id).conflicts_with(geom_map.get_t(*t))
{
return false;
}
}
true
}
pub fn changed(&self) -> bool {
// TODO detect edits that've be... | self.turns.insert(turn, priority);
self.changed = true;
}
pub fn could_be_priority_turn(&self, id: TurnID, geom_map: &GeomMap) -> bool { | random_line_split |
stop_signs.rs | // Copyright 2018 Google LLC
//
// 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 ... |
pub fn get_savestate(&self) -> Option<ModifiedStopSign> {
if!self.changed() {
return None;
}
Some(ModifiedStopSign {
turns: self.turns.clone(),
})
}
pub fn load_savestate(&mut self, state: &ModifiedStopSign) {
self.changed = true;
s... | {
// TODO detect edits that've been undone, equivalent to original
self.changed
} | identifier_body |
stop_signs.rs | // Copyright 2018 Google LLC
//
// 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 ... | (map: &Map, intersection: IntersectionID) -> ControlStopSign {
assert!(!map.get_i(intersection).has_traffic_signal);
ControlStopSign::all_way_stop(map, intersection)
}
fn all_way_stop(map: &Map, intersection: IntersectionID) -> ControlStopSign {
let mut ss = ControlStopSign {
... | new | identifier_name |
cast_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | });
c.bench_function("cast int32 to float64 512", |b| {
b.iter(|| cast_array(&i32_array, DataType::Float64))
});
c.bench_function("cast int32 to int64 512", |b| {
b.iter(|| cast_array(&i32_array, DataType::Int64))
});
c.bench_function("cast float32 to int32 512", |b| {
b.... | {
let i32_array = build_array::<Int32Type>(512);
let i64_array = build_array::<Int64Type>(512);
let f32_array = build_array::<Float32Type>(512);
let f64_array = build_array::<Float64Type>(512);
let date64_array = build_array::<Date64Type>(512);
let date32_array = build_array::<Date32Type>(512);
... | identifier_body |
cast_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | <FROM>(size: usize) -> ArrayRef
where
FROM: ArrowNumericType,
Standard: Distribution<FROM::Native>,
PrimitiveArray<FROM>: std::convert::From<Vec<Option<FROM::Native>>>,
{
let values = (0..size)
.map(|_| {
// 10% nulls, i.e. dense.
if random::<f64>() < 0.1 {
... | build_array | identifier_name |
cast_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | else {
Some(random::<FROM::Native>())
}
})
.collect();
Arc::new(PrimitiveArray::<FROM>::from(values))
}
fn build_timestamp_array<FROM>(size: usize) -> ArrayRef
where
FROM: ArrowTimestampType,
Standard: Distribution<FROM::Native>,
{
let values = (0..size)
... | {
None
} | conditional_block |
cast_kernels.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | c.bench_function("cast float64 to uint64 512", |b| {
b.iter(|| cast_array(&f64_array, DataType::UInt64))
});
c.bench_function("cast int64 to int32 512", |b| {
b.iter(|| cast_array(&i64_array, DataType::Int32))
});
c.bench_function("cast date64 to date32 512", |b| {
b.iter(|| ... | b.iter(|| cast_array(&f64_array, DataType::Float32))
}); | random_line_split |
mod.rs | pub mod brainfuck; |
#[derive(Clone, PartialEq, Debug)]
pub enum BasicCmd {
Skip,
Rewind,
Add,
Sub,
}
impl Display for BasicCmd {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:?}", self)
}
}
// workaround because FaustCmd::Repeatable is 'not a valid type'
#[derive(Clone, PartialEq, Debug)]
pub struct Repeata... | mod optimizer;
use std::fmt::{Display, Formatter, Result}; | random_line_split |
mod.rs | pub mod brainfuck;
mod optimizer;
use std::fmt::{Display, Formatter, Result};
#[derive(Clone, PartialEq, Debug)]
pub enum BasicCmd {
Skip,
Rewind,
Add,
Sub,
}
impl Display for BasicCmd {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:?}", self)
}
}
// workaround because FaustCmd::Repeata... | (&self, code: &String) -> Vec<FaustCmd> {
optimizer::full_optimize(self.basic(code))
}
}
| optimize | identifier_name |
mod.rs | pub mod brainfuck;
mod optimizer;
use std::fmt::{Display, Formatter, Result};
#[derive(Clone, PartialEq, Debug)]
pub enum BasicCmd {
Skip,
Rewind,
Add,
Sub,
}
impl Display for BasicCmd {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:?}", self)
}
}
// workaround because FaustCmd::Repeata... |
}
| {
optimizer::full_optimize(self.basic(code))
} | identifier_body |
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... |
/// Webapps HTTP+RPC server build.
pub struct ServerBuilder<T: Fetch = FetchClient> {
dapps_path: PathBuf,
registrar: Arc<ContractClient>,
sync_status: Arc<SyncStatus>,
web_proxy_tokens: Arc<WebProxyTokens>,
signer_address: Option<(String, u16)>,
allowed_hosts: DomainsValidation<Host>,
remote: Remote,
fetch:... | {
http_client::assert_security_headers_present(headers, Some(SIGNER_PORT))
} | identifier_body |
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... |
}
pub fn init_server<F, B>(process: F, io: IoHandler, remote: Remote) -> (Server, Arc<FakeRegistrar>) where
F: FnOnce(ServerBuilder) -> ServerBuilder<B>,
B: Fetch,
{
init_logger();
let registrar = Arc::new(FakeRegistrar::new());
let mut dapps_path = env::temp_dir();
dapps_path.push("non-existent-dir-to-prevent-... | {
let mut builder = LogBuilder::new();
builder.parse(&log);
let _ = builder.init(); // ignore errors since ./test.sh will call this multiple times.
} | 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... | dapps_path: PathBuf,
registrar: Arc<ContractClient>,
sync_status: Arc<SyncStatus>,
web_proxy_tokens: Arc<WebProxyTokens>,
signer_address: Option<(String, u16)>,
allowed_hosts: DomainsValidation<Host>,
remote: Remote,
fetch: Option<T>,
}
impl ServerBuilder {
/// Construct new dapps server
pub fn new<P: AsRef<... | /// Webapps HTTP+RPC server build.
pub struct ServerBuilder<T: Fetch = FetchClient> { | 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... | (web_token: &'static str, domain: &'static str) -> (Server, FakeFetch) {
let fetch = FakeFetch::default();
let f = fetch.clone();
let (server, _) = init_server(move |builder| {
builder
.fetch(f.clone())
.web_proxy_tokens(Arc::new(move |token| {
if &token == web_token { Some(domain.into()) } else { None }... | serve_with_fetch | identifier_name |
packet_identifier.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct PacketIdentifier(pub u16);
impl<'a> Encodable<'a> for PacketIdentifier {... | (&self) -> u32 {
2
}
}
impl<'a> Decodable<'a> for PacketIdentifier {
type Err = VariableHeaderError;
type Cond = ();
fn decode_with<R: Read>(reader: &mut R, _rest: Option<()>) -> Result<PacketIdentifier, VariableHeaderError> {
reader.read_u16::<BigEndian>()
.map(PacketIdenti... | encoded_length | identifier_name |
packet_identifier.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct PacketIdentifier(pub u16);
impl<'a> Encodable<'a> for PacketIdentifier {... | } | random_line_split | |
packet_identifier.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct PacketIdentifier(pub u16);
impl<'a> Encodable<'a> for PacketIdentifier {... |
}
impl<'a> Decodable<'a> for PacketIdentifier {
type Err = VariableHeaderError;
type Cond = ();
fn decode_with<R: Read>(reader: &mut R, _rest: Option<()>) -> Result<PacketIdentifier, VariableHeaderError> {
reader.read_u16::<BigEndian>()
.map(PacketIdentifier)
.map_err(From::... | {
2
} | identifier_body |
tac.rs | use std::process::Command;
use util::*;
static PROGNAME: &'static str = "./tac";
#[path = "common/util.rs"]
#[macro_use]
mod util;
#[test]
fn test_stdin_default() {
let mut cmd = Command::new(PROGNAME);
let result = run_piped_stdin(&mut cmd, "100\n200\n300\n400\n500");
assert_eq!(result.stdout, "500400\n... | {
let mut cmd = Command::new(PROGNAME);
let result = run(&mut cmd.args(&["-b", "-s", ":", "delimited_primes.txt"]));
assert_eq!(result.stdout, get_file_contents("delimited_primes_before.expected"));
} | identifier_body | |
tac.rs | use std::process::Command;
use util::*;
static PROGNAME: &'static str = "./tac";
#[path = "common/util.rs"]
#[macro_use]
mod util;
#[test]
fn test_stdin_default() {
let mut cmd = Command::new(PROGNAME);
let result = run_piped_stdin(&mut cmd, "100\n200\n300\n400\n500");
assert_eq!(result.stdout, "500400\n... | fn test_single_non_newline_separator() {
let mut cmd = Command::new(PROGNAME);
let result = run(&mut cmd.args(&["-s", ":", "delimited_primes.txt"]));
assert_eq!(result.stdout, get_file_contents("delimited_primes.expected"));
}
#[test]
fn test_single_non_newline_separator_before() {
let mut cmd = Comman... | }
#[test] | random_line_split |
tac.rs | use std::process::Command;
use util::*;
static PROGNAME: &'static str = "./tac";
#[path = "common/util.rs"]
#[macro_use]
mod util;
#[test]
fn test_stdin_default() {
let mut cmd = Command::new(PROGNAME);
let result = run_piped_stdin(&mut cmd, "100\n200\n300\n400\n500");
assert_eq!(result.stdout, "500400\n... | () {
let mut cmd = Command::new(PROGNAME);
let result = run_piped_stdin(&mut cmd.args(&["-b", "-s", ":"]), "100:200:300:400:500");
assert_eq!(result.stdout, "500:400:300:200:100");
}
#[test]
fn test_single_default() {
let mut cmd = Command::new(PROGNAME);
let result = run(&mut cmd.arg("prime_per_li... | test_stdin_non_newline_separator_before | identifier_name |
bench.rs | #![feature(test)]
extern crate chaskey;
extern crate rand;
extern crate test;
use chaskey::{Digester, Chaskey};
use rand::{Rng, ThreadRng, thread_rng};
use std::hash::{SipHasher, Hasher};
use test::{black_box, Bencher};
const SIZE: usize = 57;
#[bench]
fn sip_hasher(b: &mut Bencher) {
let mut rng: ThreadRng = ... | {
let data: Vec<u8> = {
let mut r = vec![0; size];
let mut rng: ThreadRng = thread_rng();
rng.fill_bytes(&mut r);
r
};
b.iter(|| {
hasher.write(&data);
let r = hasher.finish();
});
} | identifier_body | |
bench.rs | #![feature(test)] |
use chaskey::{Digester, Chaskey};
use rand::{Rng, ThreadRng, thread_rng};
use std::hash::{SipHasher, Hasher};
use test::{black_box, Bencher};
const SIZE: usize = 57;
#[bench]
fn sip_hasher(b: &mut Bencher) {
let mut rng: ThreadRng = thread_rng();
let (k0, k1) = rng.gen();
let mut hasher = SipHasher::new... |
extern crate chaskey;
extern crate rand;
extern crate test; | random_line_split |
bench.rs | #![feature(test)]
extern crate chaskey;
extern crate rand;
extern crate test;
use chaskey::{Digester, Chaskey};
use rand::{Rng, ThreadRng, thread_rng};
use std::hash::{SipHasher, Hasher};
use test::{black_box, Bencher};
const SIZE: usize = 57;
#[bench]
fn sip_hasher(b: &mut Bencher) {
let mut rng: ThreadRng = ... | <H: Hasher>(b: &mut Bencher, hasher: &mut H, size: usize) {
let data: Vec<u8> = {
let mut r = vec![0; size];
let mut rng: ThreadRng = thread_rng();
rng.fill_bytes(&mut r);
r
};
b.iter(|| {
hasher.write(&data);
let r = hasher.finish();
});
}
| bench_hasher | identifier_name |
build_gecko.rs |
path
};
static ref SEARCH_PATHS: Vec<PathBuf> = vec![
DISTDIR_PATH.join("include"),
DISTDIR_PATH.join("include/nspr"),
];
static ref ADDED_PATHS: Mutex<HashSet<PathBuf>> = Mutex::new(HashSet::new());
static ref LAST_MODIFIED: Mutex<SystemTime>... |
}
}
if let Some(path) = env::var_os("STYLO_BUILD_LOG") {
log::set_max_level(log::LevelFilter::Debug);
log::set_boxed_logger(Box::new(BuildLogger {
file: fs::File::create(path).ok().map(Mutex::new),
filter: env::var("STYLO_BUILD_FILTER... | {
file.lock().unwrap().flush().unwrap();
} | conditional_block |
build_gecko.rs | fn include<T: Into<String>>(self, file: T) -> Builder {
self.clang_arg("-include").clang_arg(file)
}
// This makes an FFI-safe void type that can't be matched on
// &VoidType is UB to have, because you can match on it
// to produce a reachable unreachable. If it's wrapped i... | copy_dir | identifier_name | |
build_gecko.rs |
lazy_static! {
static ref CONFIG: Table = {
// Load Gecko's binding generator config from the source tree.
let path = PathBuf::from(env::var_os("MOZ_SRC").unwrap())
.join("layout/style/ServoBindings.toml");
read_config(&path)
};
static ref... | {
println!("cargo:rerun-if-changed={}", path.to_str().unwrap());
update_last_modified(&path);
let mut contents = String::new();
File::open(path)
.expect("Failed to open config file")
.read_to_string(&mut contents)
.expect("Failed to read config file")... | identifier_body | |
build_gecko.rs | }
path
};
static ref SEARCH_PATHS: Vec<PathBuf> = vec![
DISTDIR_PATH.join("include"),
DISTDIR_PATH.join("include/nspr"),
];
static ref ADDED_PATHS: Mutex<HashSet<PathBuf>> = Mutex::new(HashSet::new());
static ref LAST_MODIFIED: Mutex<SystemTim... | for fixup in fixups.iter() {
result = Regex::new(&fixup.pat)
.unwrap()
.replace_all(&result, &*fixup.rep)
.into_owned()
.into();
}
let bytes = result.into_bytes();
File::create(&out_file)
.unwrap()
... | );
},
}; | random_line_split |
actor.rs | }
actors! {
breakable {
SIGN: Kanban
BREAKABLE_CUP: MKoppu
BREAKABLE_PLATE: MOsara
BREAKABLE_JUG: MPot
SKULL: Odokuro
NUT: VigaH
PILE_OF_LEAVES: Vochi
SMALL_POT: kotubo
LARGE_POT: ootubo1
}
door {
KNOB00D: KNOB00D
KNOB... | } | random_line_split | |
actor.rs | BARRED_EARTH_AND_WIND_TEMPLE_DOOR: doorSH
LOCKED_EARTH_AND_WIND_TEMPLE_DOOR: keyS12
DUNGEON_LOCKED_DOOR: keyshut
}
treasure_chest {
TREASURE_CHEST: takara
TREASURE_CHEST_2: takara2
TAKARA3: takara3
TREASURE_CHEST_3: takara3
TREASURE_CHEST_4: takara4
... | with_params | identifier_name | |
actor.rs | AGc
TREASURE_AIK: tkrAIk
TREASURE_AKD: tkrAKd
TREASURE_AOC: tkrAOc
TREASURE_AOS: tkrAOs
TREASURE_A_SWITCH: tkrASw
TREASURE_CHEST_UNLOCKED_BY_LIGHT_BEAM: tkrBMs
TREASURE_CTF: tkrCTf
}
trigger {
EVENT_TRIGGER: TagEv
HINT_TRIGGER: TagHt
... | {
let memory = ActorMemory::new();
memory.write_actor(self);
memory.room_id = Link::room();
layer::switch_to_safe_layer();
system::dstage_actor_create(self, memory);
memory
} | identifier_body | |
smb3.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | use nom7::number::streaming::{le_u16, le_u32, le_u64};
use nom7::IResult;
#[derive(Debug,PartialEq)]
pub struct Smb3TransformRecord<'a> {
pub session_id: u64,
pub enc_algo: u16,
pub enc_data: &'a[u8],
}
pub fn parse_smb3_transform_record(i: &[u8]) -> IResult<&[u8], Smb3TransformRecord> {
let (i, _) = ... |
use nom7::bytes::streaming::{tag, take}; | random_line_split |
smb3.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
let (i, _) = tag(b"\xfdSMB")(i)?;
let (i, _signature) = take(16_usize)(i)?;
let (i, _nonce) = take(16_usize)(i)?;
let (i, msg_size) = le_u32(i)?;
let (i, _reserved) = le_u16(i)?;
let (i, enc_algo) = le_u16(i)?;
let (i, session_id) = le_u64(i)?;
let (i, enc_data) = take(msg_size)(i)?;
... | identifier_body | |
smb3.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | (i: &[u8]) -> IResult<&[u8], Smb3TransformRecord> {
let (i, _) = tag(b"\xfdSMB")(i)?;
let (i, _signature) = take(16_usize)(i)?;
let (i, _nonce) = take(16_usize)(i)?;
let (i, msg_size) = le_u32(i)?;
let (i, _reserved) = le_u16(i)?;
let (i, enc_algo) = le_u16(i)?;
let (i, session_id) = le_u64(... | parse_smb3_transform_record | identifier_name |
inline.rs | // compile-flags: -Zinline-mir
use std::fmt::Display;
fn main() {
permutations(&['a', 'b', 'c']);
}
#[inline(always)]
fn | <T: Copy + Display>(xs: &[T]) {
let mut ys = xs.to_owned();
permutate(&mut ys, 0);
}
fn permutate<T: Copy + Display>(xs: &mut [T], k: usize) {
let n = length(xs);
if k == n {
display(xs);
} else if k < n {
for i in k..n {
swap(xs, i, k);
permutate(xs, k + 1);... | permutations | identifier_name |
inline.rs | // compile-flags: -Zinline-mir
use std::fmt::Display;
fn main() {
permutations(&['a', 'b', 'c']);
}
#[inline(always)]
fn permutations<T: Copy + Display>(xs: &[T]) {
let mut ys = xs.to_owned();
permutate(&mut ys, 0);
}
fn permutate<T: Copy + Display>(xs: &mut [T], k: usize) {
let n = length(xs);
... |
}
fn length<T>(xs: &[T]) -> usize {
xs.len()
}
#[inline]
fn swap<T: Copy>(xs: &mut [T], i: usize, j: usize) {
let t = xs[i];
xs[i] = xs[j];
xs[j] = t;
}
fn display<T: Display>(xs: &[T]) {
for x in xs {
print!("{}", x);
}
println!();
}
#[inline(always)]
fn error() {
panic!("e... | {
error();
} | conditional_block |
inline.rs | // compile-flags: -Zinline-mir
use std::fmt::Display;
fn main() {
permutations(&['a', 'b', 'c']);
} | #[inline(always)]
fn permutations<T: Copy + Display>(xs: &[T]) {
let mut ys = xs.to_owned();
permutate(&mut ys, 0);
}
fn permutate<T: Copy + Display>(xs: &mut [T], k: usize) {
let n = length(xs);
if k == n {
display(xs);
} else if k < n {
for i in k..n {
swap(xs, i, k);
... | random_line_split | |
inline.rs | // compile-flags: -Zinline-mir
use std::fmt::Display;
fn main() {
permutations(&['a', 'b', 'c']);
}
#[inline(always)]
fn permutations<T: Copy + Display>(xs: &[T]) {
let mut ys = xs.to_owned();
permutate(&mut ys, 0);
}
fn permutate<T: Copy + Display>(xs: &mut [T], k: usize) |
fn length<T>(xs: &[T]) -> usize {
xs.len()
}
#[inline]
fn swap<T: Copy>(xs: &mut [T], i: usize, j: usize) {
let t = xs[i];
xs[i] = xs[j];
xs[j] = t;
}
fn display<T: Display>(xs: &[T]) {
for x in xs {
print!("{}", x);
}
println!();
}
#[inline(always)]
fn error() {
panic!("err... | {
let n = length(xs);
if k == n {
display(xs);
} else if k < n {
for i in k..n {
swap(xs, i, k);
permutate(xs, k + 1);
swap(xs, i, k);
}
} else {
error();
}
} | identifier_body |
commands.rs | use std::process::exit;
use std::fs::File;
use std::io::Write;
use libllama::dbgcore::{self, ActiveCpu};
use libllama::utils::from_hex;
/// Prints disassembly for the next instruction
/// Command format: "asm [address hex]"
///
/// `args`: Iterator over &str items
fn cmd_asm<'a, It>(active_cpu: ActiveCpu, debugger: &... |
if let Ok(mut cs) = cs {
let mut inst_bytes = [0u8; 4];
if let Err(e) = hw.read_mem(pause_addr, &mut inst_bytes) {
error!("{}", e);
return;
}
match cs.disasm_count(&inst_bytes, pause_addr as u64, 1) {
Ok(insts) => {
let inst = ins... | random_line_split | |
commands.rs | use std::process::exit;
use std::fs::File;
use std::io::Write;
use libllama::dbgcore::{self, ActiveCpu};
use libllama::utils::from_hex;
/// Prints disassembly for the next instruction
/// Command format: "asm [address hex]"
///
/// `args`: Iterator over &str items
fn cmd_asm<'a, It>(active_cpu: ActiveCpu, debugger: &... | ];
let mut btn_map = btn_map.iter();
if let Some(button) = args.next() {
let press = match args.next() {
Some("up") => hid::ButtonState::Released,
Some("down") => hid::ButtonState::Pressed,
_ => {
error!("Specify whether button `{}` should be `up`... | {
use libllama::io::hid;
let mut ctx = debugger.ctx(ActiveCpu::Arm11);
let hw = ctx.hw11();
let io_shared = &hw.io_shared_devices().hid;
let btn_map = [
("a", hid::Button::A),
("b", hid::Button::B),
("x", hid::Button::X),
("y", hid::Button::Y),
("l", hid::Bu... | identifier_body |
commands.rs | use std::process::exit;
use std::fs::File;
use std::io::Write;
use libllama::dbgcore::{self, ActiveCpu};
use libllama::utils::from_hex;
/// Prints disassembly for the next instruction
/// Command format: "asm [address hex]"
///
/// `args`: Iterator over &str items
fn cmd_asm<'a, It>(active_cpu: ActiveCpu, debugger: &... | ;
let cs = Capstone::new()
.arm()
.mode(cpu_mode)
.build();
if let Ok(mut cs) = cs {
let mut inst_bytes = [0u8; 4];
if let Err(e) = hw.read_mem(pause_addr, &mut inst_bytes) {
error!("{}", e);
return;
}
match cs.disasm_count(&inst_by... | {
ArchMode::Arm
} | conditional_block |
commands.rs | use std::process::exit;
use std::fs::File;
use std::io::Write;
use libllama::dbgcore::{self, ActiveCpu};
use libllama::utils::from_hex;
/// Prints disassembly for the next instruction
/// Command format: "asm [address hex]"
///
/// `args`: Iterator over &str items
fn cmd_asm<'a, It>(active_cpu: ActiveCpu, debugger: &... | <'a, It>(active_cpu: ActiveCpu, debugger: &mut dbgcore::DbgCore, mut args: It)
where It: Iterator<Item=&'a str> {
let mut ctx = debugger.ctx(active_cpu);
let hw = ctx.hw();
let print_reg = |reg_num| info!("R{} = 0x{:08X}", reg_num, hw.read_reg(reg_num));
let print_cpsr = || info!("CPSR = 0x{:08X}",... | cmd_reg | identifier_name |
attr.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding;
use dom::bindings::codegen... |
fn GetPrefix(self) -> Option<DOMString> {
self.prefix.clone()
}
fn GetOwnerElement(self) -> Option<Temporary<Element>> {
self.owner.map(|o| Temporary::new(o))
}
fn Specified(self) -> bool {
true // Always returns true
}
}
pub trait AttrHelpers<'a> {
fn set_value(... | {
let Namespace(ref atom) = self.namespace;
match atom.as_slice() {
"" => None,
url => Some(url.to_string()),
}
} | identifier_body |
attr.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding;
use dom::bindings::codegen... | <'a>(&'a self) -> &'a Atom {
&self.name
}
#[inline]
pub fn namespace<'a>(&'a self) -> &'a Namespace {
&self.namespace
}
#[inline]
pub fn prefix<'a>(&'a self) -> &'a Option<DOMString> {
&self.prefix
}
}
impl<'a> AttrMethods for JSRef<'a, Attr> {
fn LocalName(sel... | name | identifier_name |
attr.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding;
use dom::bindings::codegen... | TokenListAttrValue(_, ref tokens) => Some(tokens.as_slice()),
_ => None
}
}
}
impl Str for AttrValue {
fn as_slice<'a>(&'a self) -> &'a str {
match *self {
StringAttrValue(ref value) |
TokenListAttrValue(ref value, _) |
UIntAttrValue(r... | AtomAttrValue(value)
}
pub fn tokens<'a>(&'a self) -> Option<&'a [Atom]> {
match *self { | random_line_split |
namespaced-enum-glob-import.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn _f2(f: m2::Foo) {
match f {
m::A | m::B(_) | m::C {.. } => {}
}
}
pub fn main() {} | }
} | random_line_split |
namespaced-enum-glob-import.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
fn _f2(f: m2::Foo) {
match f {
m::A | m::B(_) | m::C {.. } => {}
}
}
pub fn main() {}
| {} | conditional_block |
namespaced-enum-glob-import.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 ... | (f: m2::Foo) {
use m2::Foo::*;
match f {
A | B(_) | C {.. } => {}
}
}
fn _f2(f: m2::Foo) {
match f {
m::A | m::B(_) | m::C {.. } => {}
}
}
pub fn main() {}
| _f | identifier_name |
clone.rs | // Copyright 2012-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-MI... | /// Return a shallow copy of the slice.
#[inline]
fn clone(&self) -> &'a [T] { *self }
}
impl<'a> Clone for &'a str {
/// Return a shallow copy of the slice.
#[inline]
fn clone(&self) -> &'a str { *self }
}
macro_rules! clone_impl(
($t:ty) => {
impl Clone for $t {
/// R... |
impl<'a, T> Clone for &'a [T] { | random_line_split |
clone.rs | // Copyright 2012-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-MI... |
}
impl<'a> Clone for &'a str {
/// Return a shallow copy of the slice.
#[inline]
fn clone(&self) -> &'a str { *self }
}
macro_rules! clone_impl(
($t:ty) => {
impl Clone for $t {
/// Return a deep copy of the value.
#[inline]
fn clone(&self) -> $t { *self }
... | { *self } | identifier_body |
clone.rs | // Copyright 2012-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-MI... | (&mut self, source: &Self) {
*self = source.clone()
}
}
impl<'a, T> Clone for &'a T {
/// Return a shallow copy of the reference.
#[inline]
fn clone(&self) -> &'a T { *self }
}
impl<'a, T> Clone for &'a [T] {
/// Return a shallow copy of the slice.
#[inline]
fn clone(&self) -> &'a ... | clone_from | identifier_name |
flexible_array.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! A wrapper for structures that contain flexible arrays.
use std::marker::PhantomData;
use std::mem::size_of;
// Returns a `Vec<T>` with a size in ... |
}
/// Returns a slice of the flexible array member, for inspecting. To modify, use
/// mut_entries_slice instead.
pub fn entries_slice(&self) -> &[S] {
let valid_length = self.get_valid_len();
// Safe because the length has been validated.
unsafe { self.entries[0].get_slice(val... | {
self.entries[0].get_len()
} | conditional_block |
flexible_array.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! A wrapper for structures that contain flexible arrays.
use std::marker::PhantomData;
use std::mem::size_of;
// Returns a `Vec<T>` with a size in ... |
/// Get a pointer so it can be passed to the kernel. Callers must not access the flexible
/// array member. Using this pointer is unsafe.
pub fn as_ptr(&self) -> *const T {
&self.entries[0]
}
/// Get a mutable pointer so it can be passed to the kernel. Callers must not access the
///... | {
let valid_length = self.get_valid_len();
self.entries[0].set_len(valid_length);
// Safe because the length has been validated.
unsafe { self.entries[0].get_mut_slice(valid_length) }
} | identifier_body |
flexible_array.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! A wrapper for structures that contain flexible arrays.
use std::marker::PhantomData;
use std::mem::size_of;
// Returns a `Vec<T>` with a size in ... | (&self) -> *const T {
&self.entries[0]
}
/// Get a mutable pointer so it can be passed to the kernel. Callers must not access the
/// flexible array member. Using this pointer is unsafe.
pub fn as_mut_ptr(&mut self) -> *mut T {
&mut self.entries[0]
}
}
| as_ptr | identifier_name |
flexible_array.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! A wrapper for structures that contain flexible arrays.
use std::marker::PhantomData;
use std::mem::size_of;
// Returns a `Vec<T>` with a size in ... |
FlexibleArrayWrapper {
entries,
phantom: PhantomData,
allocated_len: array_len,
}
}
/// Mapping the unsized array to a slice is unsafe because the length isn't known. Using
/// the length we originally allocated with eliminates the possibility of overfl... | entries[0].set_len(array_len); | random_line_split |
borrowck-object-mutability.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn borrowed_mut_receiver(x: &mut Foo) {
x.borrowed();
x.borrowed_mut();
}
fn owned_receiver(x: Box<Foo>) {
x.borrowed();
x.borrowed_mut(); //~ ERROR cannot borrow
}
fn mut_owned_receiver(mut x: Box<Foo>) {
x.borrowed();
x.borrowed_mut();
}
fn main() {} | x.borrowed();
x.borrowed_mut(); //~ ERROR cannot borrow
} | random_line_split |
borrowck-object-mutability.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn borrowed_mut_receiver(x: &mut Foo) {
x.borrowed();
x.borrowed_mut();
}
fn owned_receiver(x: Box<Foo>) {
x.borrowed();
x.borrowed_mut(); //~ ERROR cannot borrow
}
fn mut_owned_receiver(mut x: Box<Foo>) {
x.borrowed();
x.borrowed_mut();
}
fn main() {}
| {
x.borrowed();
x.borrowed_mut(); //~ ERROR cannot borrow
} | identifier_body |
borrowck-object-mutability.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 ... | (x: &mut Foo) {
x.borrowed();
x.borrowed_mut();
}
fn owned_receiver(x: Box<Foo>) {
x.borrowed();
x.borrowed_mut(); //~ ERROR cannot borrow
}
fn mut_owned_receiver(mut x: Box<Foo>) {
x.borrowed();
x.borrowed_mut();
}
fn main() {}
| borrowed_mut_receiver | identifier_name |
kitchen_sink.rs | #![feature(plugin)]
#![plugin(json_macros)]
#[cfg(feature="with-rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="with-serde")]
extern crate serde_json;
#[cfg(feature="with-rustc-serialize")]
fn make_pretty_json(x: i32) -> String {
json!({ // object literal
"foo": "foooooo", // string liter... | "bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals
"quux": { // nest as deeply as you like
"a": [1, 2, 3, 4],
"b": { "a": null },
"c": false
},
"waldo": (192 - x) // wrap in parens to splice ToJson expressions directly
})).u... | #[cfg(feature="with-serde")]
fn make_pretty_json(x: i32) -> String {
serde_json::to_string_pretty(&json!({ // object literal
"foo": "foooooo", // string literal keys and values | random_line_split |
kitchen_sink.rs | #![feature(plugin)]
#![plugin(json_macros)]
#[cfg(feature="with-rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="with-serde")]
extern crate serde_json;
#[cfg(feature="with-rustc-serialize")]
fn | (x: i32) -> String {
json!({ // object literal
"foo": "foooooo", // string literal keys and values
"bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals
"quux": { // nest as deeply as you like
"a": [1, 2, 3, 4],
"b": { "a": null },
"c"... | make_pretty_json | identifier_name |
kitchen_sink.rs | #![feature(plugin)]
#![plugin(json_macros)]
#[cfg(feature="with-rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="with-serde")]
extern crate serde_json;
#[cfg(feature="with-rustc-serialize")]
fn make_pretty_json(x: i32) -> String |
#[cfg(feature="with-serde")]
fn make_pretty_json(x: i32) -> String {
serde_json::to_string_pretty(&json!({ // object literal
"foo": "foooooo", // string literal keys and values
"bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals
"quux": { // nest as deeply as you lik... | {
json!({ // object literal
"foo": "foooooo", // string literal keys and values
"bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals
"quux": { // nest as deeply as you like
"a": [1, 2, 3, 4],
"b": { "a": null },
"c": false
},
... | identifier_body |
search.rs | use bytes::Bytes;
use std::io::Cursor;
use rocket::response::{self, Response, Responder};
use rocket::request::Request;
use rocket::http::ContentType;
use crate::web::config::{Config, ServerConfig};
use crate::data_types::{SolrTermSummary, SolrReferenceSummary};
use crate::api::term_search::{search_terms, term_com... | ;
let doc_matches =
if scope.is_documentation() {
search_docs(&self.config, trimmed_query)?
} else {
vec![]
};
Ok(SolrSearchResult {
term_matches,
ref_matches,
doc_matches,
})
}
}
| {
vec![]
} | conditional_block |
search.rs | use bytes::Bytes;
use std::io::Cursor;
use rocket::response::{self, Response, Responder};
use rocket::request::Request;
use rocket::http::ContentType;
use crate::web::config::{Config, ServerConfig};
use crate::data_types::{SolrTermSummary, SolrReferenceSummary};
use crate::api::term_search::{search_terms, term_com... | {
pub bytes: Bytes
}
impl<'a> Responder<'a, 'a> for PNGPlot {
fn respond_to(self, _: &Request) -> response::Result<'a> {
Response::build()
.sized_body(self.bytes.len(), Cursor::new(self.bytes))
.header(ContentType::new("image", "png"))
.ok()
}
}
#[derive(Deserial... | PNGPlot | identifier_name |
search.rs | use bytes::Bytes;
use std::io::Cursor;
use rocket::response::{self, Response, Responder};
use rocket::request::Request;
use rocket::http::ContentType;
use crate::web::config::{Config, ServerConfig};
use crate::data_types::{SolrTermSummary, SolrReferenceSummary};
use crate::api::term_search::{search_terms, term_com... |
pub fn is_term(&self) -> bool {
matches!(self, SolrSearchScope::Term)
}
pub fn is_reference(&self) -> bool {
matches!(self, SolrSearchScope::Reference)
}
pub fn is_documentation(&self) -> bool {
matches!(self, SolrSearchScope::Documentation)
}
}
#[derive(Serialize, D... | } | random_line_split |
asm_ext.rs | // #![crate_type="dylib"]
// #![feature(plugin_registrar, rustc_private)]
//
// extern crate syntax;
// extern crate rustc;
// extern crate rustc_plugin;
//
// use syntax::parse::token;
// use syntax::tokenstream::TokenTree;
// use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
// use syntax::ext::buil... | //
// asm::parseInput();
//
// }
//
//
// #[plugin_registrar]
// pub fn plugin_registrar(reg: &mut Registry) {
// reg.register_macro("z80asm", expand_asm);
// }
// | //
// fn expand_asm(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult + 'static> {
// use rusty_boy::assembler::asm;
// use rusty_boy::assembler::language; | random_line_split |
13b_enum_values_manual.rs | // If you require more complex configuration than simple_enum! provides, you can implement the
// trait manually, as in the following example.
//
// In the following example we will create an enum with 4 values, assign a positional argument
// that accepts only one of those values, and use clap to parse the argument.
/... | {
// Create the application like normal
let enum_vals = ["Foo", "Bar", "Baz", "Qux"];
let m = App::new("myapp")
// Use a single positional argument that is required
.arg(Arg::from_usage("<type> 'The type to use'")
// Define the list of poss... | identifier_body | |
13b_enum_values_manual.rs | // If you require more complex configuration than simple_enum! provides, you can implement the
// trait manually, as in the following example.
//
// In the following example we will create an enum with 4 values, assign a positional argument
// that accepts only one of those values, and use clap to parse the argument.
/... | () {
// Create the application like normal
let enum_vals = ["Foo", "Bar", "Baz", "Qux"];
let m = App::new("myapp")
// Use a single positional argument that is required
.arg(Arg::from_usage("<type> 'The type to use'")
// Define the list of po... | main | identifier_name |
13b_enum_values_manual.rs | // If you require more complex configuration than simple_enum! provides, you can implement the
// trait manually, as in the following example.
//
// In the following example we will create an enum with 4 values, assign a positional argument
// that accepts only one of those values, and use clap to parse the argument.
/... | }
// Implement the trait
impl FromStr for Vals {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Foo" => Ok(Vals::Foo),
"Bar" => Ok(Vals::Bar),
"Baz" => Ok(Vals::Baz),
"Qux" => Ok(Vals::Qux),
_ =>... | Qux | random_line_split |
alert.rs | use util::{ReadExt, WriteExt};
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_item::TlsItem;
// we treat every alert as fatal.
tls_enum!(u8, enum AlertLevel {
warning(1),
fatal(2)
});
// A.3. Alert Messages
// http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml
tls_enum!(u8, #[de... | insufficient_security(71),
internal_error(80),
user_canceled(90),
no_renegotiation(100),
unsupported_extension(110)
// RFC 6066
// certificate_unobtainable(111),
// unrecognized_name(112),
// bad_certificate_status_response(113),
// bad_certificate_hash_value(114),
});
impl Ale... | protocol_version(70), | random_line_split |
alert.rs | use util::{ReadExt, WriteExt};
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_item::TlsItem;
// we treat every alert as fatal.
tls_enum!(u8, enum AlertLevel {
warning(1),
fatal(2)
});
// A.3. Alert Messages
// http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml
tls_enum!(u8, #[de... |
}
| {
Alert {
level: AlertLevel::fatal,
description: AlertDescription::from_err(err.kind),
}
} | identifier_body |
alert.rs | use util::{ReadExt, WriteExt};
use tls_result::{TlsResult, TlsError, TlsErrorKind};
use tls_item::TlsItem;
// we treat every alert as fatal.
tls_enum!(u8, enum AlertLevel {
warning(1),
fatal(2)
});
// A.3. Alert Messages
// http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml
tls_enum!(u8, #[de... | (level: AlertLevel, desc: AlertDescription) -> TlsResult<Alert> {
// TODO filter out some rfc-invalid alerts
Ok(Alert {
level: level,
description: desc,
})
}
pub fn from_tls_err(err: &TlsError) -> Alert {
Alert {
level: AlertLevel::fatal,
... | new | identifier_name |
c-style-enum.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 ... | () {()}
| zzz | identifier_name |
c-style-enum.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 ... |
#[allow(unused_variable)];
enum AutoDiscriminant {
One,
Two,
Three
}
enum ManualDiscriminant {
OneHundred = 100,
OneThousand = 1000,
OneMillion = 1000000
}
enum SingleVariant {
TheOnlyVariant
}
fn main() {
let auto_one = One;
let auto_two = Two;
let auto_three = Three;
... | random_line_split | |
main.rs | mod game;
use game::*;
use std::time::Instant;
use std::env;
#[allow(unreachable_code)]
fn main()
{
match 55
{
0 => general_play(PlayerType::IO, PlayerType::AIValue, 2, 1, true), //play against IO + learn
1 => general_play(PlayerType::IO, PlayerType::AIValueFixed, 2, 1, true), //test with IO
2 => general_pla... | (p1:PlayerType, p2:PlayerType, num:u32, gps:u32, player1starts:bool)
{
println!("Player X: {:?}", p1);
println!("Player O: {:?}", p2);
println!("Playing {} games..", num);
//prepare
let mut game = Game::new();
game.set_start_player(if player1starts {1} else {2});
game.set_player1(p1);
game.set_player2(p2);
... | general_play | identifier_name |
main.rs | mod game;
use game::*;
use std::time::Instant;
use std::env;
#[allow(unreachable_code)]
fn main()
| },
_ => {
//general playing with command line arguments
play_from_args();
}
}
}
#[allow(dead_code)]
fn play_from_args()
{
let args = env::args();
//general playing with command line arguments
let mut p1 = PlayerType::IO;
let mut p2 = PlayerType::AIValue;
let mut num = 2;
let mut player1starts ... | {
match 55
{
0 => general_play(PlayerType::IO, PlayerType::AIValue, 2, 1, true), //play against IO + learn
1 => general_play(PlayerType::IO, PlayerType::AIValueFixed, 2, 1, true), //test with IO
2 => general_play(PlayerType::Minimax, PlayerType::AIValueFixed, 100, 1, true), //test with minimax
3 => general_pl... | identifier_body |
main.rs | mod game;
use game::*;
use std::time::Instant;
use std::env;
#[allow(unreachable_code)]
fn main()
{
match 55 | 4 => general_play(PlayerType::AIValueFixed, PlayerType::AIValue, 1_000, 10, true), //training
5 => { //continuous training and testing
println!("Training:");
for i in 0..100
{
println!("Training {}:", i+1);
general_play(PlayerType::AIValueFixed, PlayerType::AIValue, 100, 10, true); //train, le... | {
0 => general_play(PlayerType::IO, PlayerType::AIValue, 2, 1, true), //play against IO + learn
1 => general_play(PlayerType::IO, PlayerType::AIValueFixed, 2, 1, true), //test with IO
2 => general_play(PlayerType::Minimax, PlayerType::AIValueFixed, 100, 1, true), //test with minimax
3 => general_play(PlayerTyp... | random_line_split |
filter-on-struct-member.rs | // edition:2021
#![feature(rustc_attrs)]
struct Filter {
div: i32,
}
impl Filter {
fn | (&self, x: i32) -> bool {
x % self.div == 1
}
}
struct Data {
filter: Filter,
list: Vec<i32>,
}
impl Data {
fn update(&mut self) {
// The closure passed to filter only captures self.filter,
// therefore mutating self.list is allowed.
self.list.retain(
#[rustc... | allowed | identifier_name |
filter-on-struct-member.rs | // edition:2021
#![feature(rustc_attrs)]
struct Filter {
div: i32,
}
impl Filter {
fn allowed(&self, x: i32) -> bool {
x % self.div == 1
}
}
struct Data {
filter: Filter,
list: Vec<i32>,
}
impl Data {
fn update(&mut self) {
// The closure passed to filter only captures self.fi... | //~| NOTE: Min Capture self[Deref,(0, 0)] -> ImmBorrow
);
}
}
fn main() {
let mut d = Data { filter: Filter { div: 3 }, list: Vec::new() };
for i in 1..10 {
d.list.push(i);
}
d.update();
} | #[rustc_capture_analysis]
|v| self.filter.allowed(*v),
//~^ ERROR: First Pass analysis includes:
//~| ERROR: Min Capture analysis includes:
//~| NOTE: Capturing self[Deref,(0, 0)] -> ImmBorrow | random_line_split |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::syscall::sys_yield;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the wind... | }
/// Return a iterator over events
pub fn event_iter<'a>(&'a mut self) -> EventIter<'a> {
EventIter {
window: self,
}
}
}
/// Event iterator
pub struct EventIter<'a> {
window: &'a mut Window,
}
impl<'a> Iterator for EventIter<'a> {
type Item = Event;
fn next(&... | self.file.seek(SeekFrom::Start(0));
self.file.write(& unsafe {
slice::from_raw_parts(self.data.as_ptr() as *const u8, self.data.len() * mem::size_of::<u32>())
});
return self.file.sync_all().is_ok(); | random_line_split |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::syscall::sys_yield;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the wind... |
}
}
/// Get x
//TODO: Sync with window movements
pub fn x(&self) -> i32 {
self.x
}
/// Get y
//TODO: Sync with window movements
pub fn y(&self) -> i32 {
self.y
}
/// Get width
pub fn width(&self) -> u32 {
self.w
}
/// Get height
... | {
let parts: Vec<&str> = path_str.split('/').collect();
if let Some(x) = parts.get(3) {
self.x = x.to_num_signed();
}
if let Some(y) = parts.get(4) {
self.y = y.to_num_signed();
}
if l... | conditional_block |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::syscall::sys_yield;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the wind... |
/// Get y
//TODO: Sync with window movements
pub fn y(&self) -> i32 {
self.y
}
/// Get width
pub fn width(&self) -> u32 {
self.w
}
/// Get height
pub fn height(&self) -> u32 {
self.h
}
/// Get title
pub fn title(&self) -> String {
self... | {
self.x
} | identifier_body |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::syscall::sys_yield;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the wind... | (&mut self, color: Color) {
let w = self.w;
let h = self.h;
self.rect(0, 0, w, h, color);
}
/// Draw rectangle
// TODO: Improve speed
#[allow(unused_variables)]
pub fn rect(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, color: Color) {
for y in start_y..start... | set | identifier_name |
lint-dead-code-5.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 ... | Enum1::Variant1(_) => (),
Enum1::Variant2 => ()
}
let x = Enum2::Variant3(true);
} | let v = Enum1::Variant1(1);
match v { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.