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 |
|---|---|---|---|---|
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::TXCRCR {
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = r" Value of the field"]
pub struct TXCRCR {
... |
#[doc = "Bits 0:15 - Tx CRC register"]
#[inline(always)]
pub fn tx_crc(&self) -> TXCRCR {
let bits = {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
};
TXCRCR { bits }
}
}
| {
self.bits
} | identifier_body |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::TXCRCR {
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = r" Value of the field"]
pub struct TXCRCR {
... | self.bits
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:15 - Tx CRC register"]
#[inline(always)]
pub fn tx_crc(&self) -> TXCRCR {
let bits = {
const MASK: u16 = 655... | pub fn bits(&self) -> u16 { | random_line_split |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::TXCRCR {
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn | (&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = r" Value of the field"]
pub struct TXCRCR {
bits: u16,
}
impl TXCRCR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
}
impl R {
#[doc = r" V... | read | identifier_name |
card.rs | // Copyright 2016-2018 Matthew D. Michelotti
//
// 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 ... | pub fn empty() -> CardMask {
CardMask { flags: [false; 4] }
}
/// Creates a `CardMask` with all values set to `true`.
#[inline]
pub fn full() -> CardMask {
CardMask { flags: [true; 4] }
}
pub(crate) fn flip(self) -> CardMask {
let mut result = CardMask::empty();
... | impl CardMask {
/// Creates a `CardMask` with all values set to `false`.
#[inline] | random_line_split |
card.rs | // Copyright 2016-2018 Matthew D. Michelotti
//
// 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 ... | () -> CardMask {
CardMask { flags: [true; 4] }
}
pub(crate) fn flip(self) -> CardMask {
let mut result = CardMask::empty();
result[Card::PlusX] = self[Card::MinusX];
result[Card::MinusX] = self[Card::PlusX];
result[Card::PlusY] = self[Card::MinusY];
result[Card::... | full | identifier_name |
arith-unsigned.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 ... |
}
| {
assert!((0u8 < 255u8));
assert!((0u8 <= 255u8));
assert!((255u8 > 0u8));
assert!((255u8 >= 0u8));
assert!((250u8 / 10u8 == 25u8));
assert!((255u8 % 10u8 == 5u8));
assert!((0u16 < 60000u16));
assert!((0u16 <= 60000u16));
assert!((60000u16 > 0u16));
assert!((60000u16 >= 0u16));
... | identifier_body |
arith-unsigned.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 ... | () {
assert!((0u8 < 255u8));
assert!((0u8 <= 255u8));
assert!((255u8 > 0u8));
assert!((255u8 >= 0u8));
assert!((250u8 / 10u8 == 25u8));
assert!((255u8 % 10u8 == 5u8));
assert!((0u16 < 60000u16));
assert!((0u16 <= 60000u16));
assert!((60000u16 > 0u16));
assert!((60000u16 >= 0u16))... | main | identifier_name |
arith-unsigned.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 ... | assert!((250u8 / 10u8 == 25u8));
assert!((255u8 % 10u8 == 5u8));
assert!((0u16 < 60000u16));
assert!((0u16 <= 60000u16));
assert!((60000u16 > 0u16));
assert!((60000u16 >= 0u16));
assert!((60000u16 / 10u16 == 6000u16));
assert!((60005u16 % 10u16 == 5u16));
assert!((0u32 < 4000000000u3... | random_line_split | |
ffi.rs | // The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitati... | {
pub format : i32,
pub name : *const c_char,
pub extension : *const c_char
}
extern "C" {
pub fn sf_open(path : *const c_char, mode : SF_MODE, info : *const SndInfo) -> *mut SNDFILE;
pub fn sf_open_fd(fd : i32, mode : SF_MODE, info : *const SndInfo, close_desc : SF_BOOL) -> *mut SNDFILE;
pub ... | FormatInfo | identifier_name |
ffi.rs | // The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitati... | pub fn sf_write_double(sndfile : *mut SNDFILE, ptr : *mut f64, items : i64) -> i64;
pub fn sf_writef_short(sndfile : *mut SNDFILE, ptr : *mut i16, frames : i64) -> i64;
pub fn sf_writef_int(sndfile : *mut SNDFILE, ptr : *mut i32, frames : i64) -> i64;
pub fn sf_writef_float(sndfile : *mut SNDFILE, ptr ... | pub fn sf_readf_double(sndfile : *mut SNDFILE, ptr : *mut f64, frames : i64) -> i64;
pub fn sf_write_short(sndfile : *mut SNDFILE, ptr : *mut i16, items : i64) -> i64;
pub fn sf_write_int(sndfile : *mut SNDFILE, ptr : *mut i32, items : i64) -> i64;
pub fn sf_write_float(sndfile : *mut SNDFILE, ptr : *m... | random_line_split |
peers_api.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... | let peers = w(&self.peers)?
.iter()
.connected()
.into_iter()
.map(|p| p.info.clone().into())
.collect::<Vec<PeerInfoDisplay>>();
Ok(peers)
}
}
impl Handler for PeersConnectedHandler {
fn get(&self, _req: Request<Body>) -> ResponseFuture {
let peers: Vec<PeerInfoDisplay> = w_fut!(&self.peers)
... | impl PeersConnectedHandler {
pub fn get_connected_peers(&self) -> Result<Vec<PeerInfoDisplay>, Error> { | random_line_split |
peers_api.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... | (&self, addr: Option<SocketAddr>) -> Result<Vec<PeerData>, Error> {
if let Some(addr) = addr {
let peer_addr = PeerAddr(addr);
let peer_data: PeerData = w(&self.peers)?.get_peer(peer_addr).map_err(|e| {
let e: Error = ErrorKind::Internal(format!("get peer error: {:?}", e)).into();
e
})?;
return Ok... | get_peers | identifier_name |
peers_api.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... |
};
match command {
"ban" => match w_fut!(&self.peers).ban_peer(addr, ReasonForBan::ManualBan) {
Ok(_) => response(StatusCode::OK, "{}"),
Err(e) => response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("ban failed: {:?}", e),
),
},
"unban" => match w_fut!(&self.peers).unban_peer(addr)... | {
if let Ok(ip_addr) = a.parse() {
PeerAddr::from_ip(ip_addr)
} else if let Ok(addr) = a.parse() {
PeerAddr(addr)
} else {
return response(
StatusCode::BAD_REQUEST,
format!("invalid peer address: {}", req.uri().path()),
);
}
} | conditional_block |
peers_api.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... |
pub fn ban_peer(&self, addr: SocketAddr) -> Result<(), Error> {
let peer_addr = PeerAddr(addr);
w(&self.peers)?
.ban_peer(peer_addr, ReasonForBan::ManualBan)
.map_err(|e| ErrorKind::Internal(format!("ban peer error: {:?}", e)).into())
}
pub fn unban_peer(&self, addr: SocketAddr) -> Result<(), Error> {
... | {
if let Some(addr) = addr {
let peer_addr = PeerAddr(addr);
let peer_data: PeerData = w(&self.peers)?.get_peer(peer_addr).map_err(|e| {
let e: Error = ErrorKind::Internal(format!("get peer error: {:?}", e)).into();
e
})?;
return Ok(vec![peer_data]);
}
let peers = w(&self.peers)?.all_peer_data... | identifier_body |
lib.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... | (bh: &mut BenchHarness) {
bh.iter(|| {
~Point {
x: 1,
y: 2,
z: 3,
}
})
}
#[bench]
pub fn bench_copy_old_arena(bh: &mut BenchHarness) {
let arena = Arena::new();
bh.iter(|| {
arena.alloc(|| {
... | bench_copy_nonarena | identifier_name |
lib.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... | let start = self.first.get_ref().start() as uint;
let end = self.ptr as uint;
let diff = (end - start) / mem::size_of::<T>();
// Pass that to the `destroy` method.
unsafe {
self.first.get_mut_ref().destroy(diff)
}
}
}
#[cfg(test)]
mod tests {
extern ... | fn drop(&mut self) {
// Determine how much was filled. | random_line_split |
lib.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... |
}
}
}
}
#[inline]
fn round_up(base: uint, align: uint) -> uint {
(base.checked_add(&(align - 1))).unwrap() &!(&(align - 1))
}
// Walk down a chunk, running the destructors for any objects stored
// in it.
unsafe fn destroy_chunk(chunk: &Chunk) {
let mut idx = 0;
let buf = chunk.as... | {
destroy_chunk(chunk);
} | conditional_block |
79.rs | /* Problem 79: Passcode derivation
*
* A common security method used for online banking is to ask the user for three random characters
* from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th
* characters; the expected reply would be: 317.
*
* The text file, keylog.txt, c... | {
let mut remaining = hyp;
for &follower in followers {
let index = memchr(follower, remaining);
match index {
Some(index) => remaining = &hyp[index + 1..],
None => return false,
}
}
return true;
} | identifier_body | |
79.rs | /* Problem 79: Passcode derivation | * from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th
* characters; the expected reply would be: 317.
*
* The text file, keylog.txt, contains fifty successful login attempts.
*
* Given that the three characters are always asked for in order, analyse the file so as to
... | *
* A common security method used for online banking is to ask the user for three random characters | random_line_split |
79.rs | /* Problem 79: Passcode derivation
*
* A common security method used for online banking is to ask the user for three random characters
* from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th
* characters; the expected reply would be: 317.
*
* The text file, keylog.txt, c... | (min_size: u8, f: impl Fn(&[u8]) -> bool) -> Vec<u8> {
let mut current = vec![0; min_size as usize];
loop {
let maxed_count = current.iter().rev().take_while(|i| **i == 9).count();
let first_to_turn = current.len() - maxed_count;
for num in &mut current[first_to_turn..] {
*... | find_hypothesis | identifier_name |
sha2.rs | bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits(bits: u64, bytes: u64) -> u64 {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > 0 ... | {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests {
sh.reset();
sh.input_str(&t.input);
let out_str = sh.result_str();
... | Test | identifier_name |
sha2.rs | bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits(bits: u64, bytes: u64) -> u64 {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > 0 ... |
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..i + size]);
i += size;
}
// Copy any input data into the buffer. At this point in ... | {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
&input[..buffer_remaining],
&mut self.buffer[self.buffer_idx..size]);
self.buffer_idx = 0;
func(&... | conditional_block |
sha2.rs | _bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits(bits: u64, bytes: u64) -> u64 {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > 0... | &mut self.buffer[self.buffer_idx..size]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
input,
&mut self.buffer[self.buffer_idx..self.buffer... | random_line_split | |
sha2.rs | };
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if t... | {
let total_size = 1000000;
let buffer: Vec<u8> = repeat('a' as u8).take(blocksize * 2).collect();
let mut rng = IsaacRng::new_unseeded();
let mut count = 0;
digest.reset();
while count < total_size {
let next: usize = rng.gen_range(0, 2 * blocksize + 1);
... | identifier_body | |
transport.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::raft_serverpb::RaftMessage;
use crate::server::raft_client::RaftClient;
use crate::server::resolve::StoreAddrResolver;
use engine_traits::KvEngine;
use raftstore::router::RaftStoreRouter;
use raftstore::store::Transport;
use raftstore::Re... | (&mut self) {
self.raft_client.flush();
}
}
| flush | identifier_name |
transport.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::raft_serverpb::RaftMessage;
use crate::server::raft_client::RaftClient;
use crate::server::resolve::StoreAddrResolver;
use engine_traits::KvEngine;
use raftstore::router::RaftStoreRouter;
use raftstore::store::Transport;
use raftstore::Re... | {
fn clone(&self) -> Self {
ServerTransport {
raft_client: self.raft_client.clone(),
engine: PhantomData,
}
}
}
impl<T, S, E> ServerTransport<T, S, E>
where
E: KvEngine,
T: RaftStoreRouter<E> +'static,
S: StoreAddrResolver +'static,
{
pub fn new(raft_clie... | random_line_split | |
transport.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::raft_serverpb::RaftMessage;
use crate::server::raft_client::RaftClient;
use crate::server::resolve::StoreAddrResolver;
use engine_traits::KvEngine;
use raftstore::router::RaftStoreRouter;
use raftstore::store::Transport;
use raftstore::Re... |
fn flush(&mut self) {
self.raft_client.flush();
}
}
| {
self.raft_client.need_flush()
} | identifier_body |
vocab.rs |
use std::collections::hashmap::{Occupied, Vacant, HashMap};
use std::io::BufferedReader;
use std::io::File;
use std::os;
use std::str::StrSlice;
fn | ()
{
let args = os::args();
let path = Path::new(args[1].as_slice());
let mut file = BufferedReader::new(File::open(&path));
let mut counter: HashMap<String, uint> = HashMap::new();
for line_opt in file.lines()
{
let line = line_opt.ok().expect("Could not read line");
for word i... | main | identifier_name |
vocab.rs |
use std::collections::hashmap::{Occupied, Vacant, HashMap};
use std::io::BufferedReader;
use std::io::File;
use std::os;
use std::str::StrSlice;
fn main()
| }
println!("{}", counter.len());
}
| {
let args = os::args();
let path = Path::new(args[1].as_slice());
let mut file = BufferedReader::new(File::open(&path));
let mut counter: HashMap<String, uint> = HashMap::new();
for line_opt in file.lines()
{
let line = line_opt.ok().expect("Could not read line");
for word in l... | identifier_body |
vocab.rs | use std::collections::hashmap::{Occupied, Vacant, HashMap};
use std::io::BufferedReader;
use std::io::File;
use std::os;
use std::str::StrSlice;
fn main()
{
let args = os::args();
let path = Path::new(args[1].as_slice());
let mut file = BufferedReader::new(File::open(&path));
let mut counter: HashMap<S... | }
};
}
}
println!("{}", counter.len());
} | random_line_split | |
vocab.rs |
use std::collections::hashmap::{Occupied, Vacant, HashMap};
use std::io::BufferedReader;
use std::io::File;
use std::os;
use std::str::StrSlice;
fn main()
{
let args = os::args();
let path = Path::new(args[1].as_slice());
let mut file = BufferedReader::new(File::open(&path));
let mut counter: HashMap<... | ,
Occupied(mut entry) => {
*entry.get_mut() += 1;
}
};
}
}
println!("{}", counter.len());
}
| { let _ = entry.set(1u); } | conditional_block |
def_id_forest.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... |
/// Create a forest containing a DefId and all its descendants.
pub fn from_id(id: DefId) -> DefIdForest {
let mut root_ids = SmallVec::new();
root_ids.push(id);
DefIdForest {
root_ids,
}
}
/// Test whether the forest is empty.
pub fn is_empty(&self) ->... | {
let crate_id = tcx.hir().local_def_id(CRATE_NODE_ID);
DefIdForest::from_id(crate_id)
} | identifier_body |
def_id_forest.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... |
}
ret.root_ids.extend(old_ret.drain());
next_ret.extend(next_forest.root_ids.into_iter().filter(|&id| ret.contains(tcx, id)));
mem::swap(&mut next_ret, &mut ret.root_ids);
next_ret.drain();
}
ret
}
/// Calculate the union of a colle... | {
old_ret.push(id);
} | conditional_block |
def_id_forest.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... | pub fn contains(&self,
tcx: TyCtxt<'a, 'gcx, 'tcx>,
id: DefId) -> bool
{
self.root_ids.iter().any(|root_id| tcx.is_descendant_of(id, *root_id))
}
/// Calculate the intersection of a collection of forests.
pub fn intersection<I>(tcx: TyCtxt<'a, 'gcx, '... | pub fn is_empty(&self) -> bool {
self.root_ids.is_empty()
}
/// Test whether the forest contains a given DefId. | random_line_split |
def_id_forest.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... | (id: DefId) -> DefIdForest {
let mut root_ids = SmallVec::new();
root_ids.push(id);
DefIdForest {
root_ids,
}
}
/// Test whether the forest is empty.
pub fn is_empty(&self) -> bool {
self.root_ids.is_empty()
}
/// Test whether the forest contains... | from_id | identifier_name |
session.rs | use elasticsearch::Client;
use model::{Model, Error};
pub struct Session {
model: Model,
}
impl Session {
fn id(&self) -> &self/~str { &self.model._id }
fn user_id(&self) -> ~str { self.model.get_str(&~"user_id") }
fn set_user_id(&mut self, user_id: ~str) -> bool {
self.model.set_str(~"user_... |
fn save(&self) -> Result<(~str, uint), Error> {
self.model.save()
}
fn delete(&self) {
self.model.delete()
}
}
pub fn Session(es: Client, index: ~str, user_id: ~str) -> Session {
let id = crypto::rand::rand_bytes(32u).to_base64();
let mut session = Session { model: Model(es, ... | {
self.model.create()
} | identifier_body |
session.rs | use elasticsearch::Client;
use model::{Model, Error};
pub struct Session {
model: Model,
}
impl Session {
fn id(&self) -> &self/~str { &self.model._id }
fn | (&self) -> ~str { self.model.get_str(&~"user_id") }
fn set_user_id(&mut self, user_id: ~str) -> bool {
self.model.set_str(~"user_id", user_id)
}
fn create(&self) -> Result<(~str, uint), Error> {
self.model.create()
}
fn save(&self) -> Result<(~str, uint), Error> {
self.mod... | user_id | identifier_name |
session.rs | use elasticsearch::Client; | use model::{Model, Error};
pub struct Session {
model: Model,
}
impl Session {
fn id(&self) -> &self/~str { &self.model._id }
fn user_id(&self) -> ~str { self.model.get_str(&~"user_id") }
fn set_user_id(&mut self, user_id: ~str) -> bool {
self.model.set_str(~"user_id", user_id)
}
fn... | random_line_split | |
wait_queue.rs | use alloc::boxed::Box;
use intrusive::queue::Queue;
use hal::local_irq_disable;
use sync::spin::{InterruptSpinLock, InterruptSpinGuard};
use super::{Thread, ThreadImpl, Scheduler};
pub type InternalQueue = Queue<Box<ThreadImpl>, ThreadImpl>;
pub struct WaitQueue {
queue: InterruptSpinLock<InternalQueue>,
}
i... |
}
unsafe impl Send for WaitQueue {}
unsafe impl Sync for WaitQueue {}
| {
let mut queue = self.queue.lock();
while let Some(t) = queue.dequeue() {
WaitQueue::unblock_thread(t);
}
} | identifier_body |
wait_queue.rs | use alloc::boxed::Box;
use intrusive::queue::Queue;
use hal::local_irq_disable;
use sync::spin::{InterruptSpinLock, InterruptSpinGuard};
use super::{Thread, ThreadImpl, Scheduler};
pub type InternalQueue = Queue<Box<ThreadImpl>, ThreadImpl>;
pub struct WaitQueue {
queue: InterruptSpinLock<InternalQueue>,
}
i... | () -> Self {
WaitQueue {
queue: InterruptSpinLock::new(Queue::new()),
}
}
#[doc(hidden)]
pub fn lock(&self) -> InterruptSpinGuard<InternalQueue> {
self.queue.lock()
}
#[inline]
/// Block the current thread
pub fn block(&self) {
local_irq_disable(... | new | identifier_name |
wait_queue.rs | use alloc::boxed::Box;
use intrusive::queue::Queue;
use hal::local_irq_disable;
use sync::spin::{InterruptSpinLock, InterruptSpinGuard};
use super::{Thread, ThreadImpl, Scheduler};
pub type InternalQueue = Queue<Box<ThreadImpl>, ThreadImpl>;
pub struct WaitQueue {
queue: InterruptSpinLock<InternalQueue>,
}
i... |
}
/// Unblock all threads in the queue
pub fn unblock_all(&self) {
let mut queue = self.queue.lock();
while let Some(t) = queue.dequeue() {
WaitQueue::unblock_thread(t);
}
}
}
unsafe impl Send for WaitQueue {}
unsafe impl Sync for WaitQueue {}
| {
WaitQueue::unblock_thread(t);
} | conditional_block |
wait_queue.rs | use alloc::boxed::Box;
use intrusive::queue::Queue;
use hal::local_irq_disable;
use sync::spin::{InterruptSpinLock, InterruptSpinGuard};
use super::{Thread, ThreadImpl, Scheduler};
pub type InternalQueue = Queue<Box<ThreadImpl>, ThreadImpl>;
pub struct WaitQueue {
queue: InterruptSpinLock<InternalQueue>,
}
i... | /// Returns true if a thread was unblocked, false otherwise
pub fn unblock(&self) {
if let Some(t) = self.queue.lock().dequeue() {
WaitQueue::unblock_thread(t);
}
}
/// Unblock all threads in the queue
pub fn unblock_all(&self) {
let mut queue = self.queue.lock()... | random_line_split | |
shader.rs | use std::ffi::CStr;
use std::fmt;
use crate::gl;
use crate::gl::types::*;
/// A wrapper for a shader program id, with automatic lifetime management.
#[derive(Debug)]
pub struct ShaderProgram(GLuint);
#[derive(Copy, Clone, Debug)]
pub enum ShaderVersion {
/// OpenGL 3.3 core shaders.
Glsl3,
/// OpenGL ES... | fn new(
shader_version: ShaderVersion,
kind: GLenum,
source: &'static str,
) -> Result<Self, ShaderError> {
let header = shader_version.shader_header();
let len: [GLint; 2] = [header.len() as GLint, source.len() as GLint];
let source = [header.as_ptr() as *const _... |
impl Shader { | random_line_split |
shader.rs | use std::ffi::CStr;
use std::fmt;
use crate::gl;
use crate::gl::types::*;
/// A wrapper for a shader program id, with automatic lifetime management.
#[derive(Debug)]
pub struct ShaderProgram(GLuint);
#[derive(Copy, Clone, Debug)]
pub enum ShaderVersion {
/// OpenGL 3.3 core shaders.
Glsl3,
/// OpenGL ES... |
}
/// A wrapper for a shader id, with automatic lifetime management.
#[derive(Debug)]
struct Shader(GLuint);
impl Shader {
fn new(
shader_version: ShaderVersion,
kind: GLenum,
source: &'static str,
) -> Result<Self, ShaderError> {
let header = shader_version.shader_header();
... | {
unsafe { gl::DeleteProgram(self.0) }
} | identifier_body |
shader.rs | use std::ffi::CStr;
use std::fmt;
use crate::gl;
use crate::gl::types::*;
/// A wrapper for a shader program id, with automatic lifetime management.
#[derive(Debug)]
pub struct ShaderProgram(GLuint);
#[derive(Copy, Clone, Debug)]
pub enum ShaderVersion {
/// OpenGL 3.3 core shaders.
Glsl3,
/// OpenGL ES... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Compile(reason) => write!(f, "Failed compiling shader: {}", reason),
Self::Link(reason) => write!(f, "Failed linking shader: {}", reason),
Self::Uniform(name) => write!(f, "Failed to get uniform location ... | fmt | identifier_name |
string.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
// ensure our operation produces an exact-size string before we benchmark it
let mut r = String::with_capacity(s.len());
r.push_str(s);
assert_eq!(r.len(), r.capacity());
b.iter(|| {
... | let _ = String::from_utf8_lossy(&s);
});
}
#[bench]
fn bench_exact_size_shrink_to_fit(b: &mut Bencher) {
let s = "Hello | identifier_body |
string.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (b: &mut Bencher) {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
b.iter(|| {
let mut r = String::new();
r.push_str(s);
});
}
const REPETITIONS: u64 = 10_000;
#[bench]
fn bench_push_str_one_byte(b: &mut Bencher) {
b.bytes = REPETITIONS;
b.iter(|| {
let mut ... | bench_push_str | identifier_name |
string.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | for _ in 0..REPETITIONS {
r.push('â')
}
});
}
#[bench]
fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
assert_eq!(100, s.len());
b.iter(|| {
... | b.iter(|| {
let mut r = String::new(); | random_line_split |
disk.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::borrow::ToOwned;
use collections::String;
use core::cell::UnsafeCell;
use core::cmp;
use disk::Disk;
use fs::{KScheme, Resource, ResourceSeek, VecResource};
use syscall::{MODE_DIR, MODE_FILE, Stat};
use system::error::{Error, Result, ENOENT};
/// A disk ... | }
impl Drop for DiskResource {
fn drop(&mut self) {
let _ = self.sync();
}
}
/// A disk scheme
pub struct DiskScheme;
impl KScheme for DiskScheme {
fn scheme(&self) -> &str {
"disk"
}
fn on_irq(&mut self, irq: u8) {
for disk in unsafe { &mut *::env().disks.get() }.iter_mu... | random_line_split | |
disk.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::borrow::ToOwned;
use collections::String;
use core::cell::UnsafeCell;
use core::cmp;
use disk::Disk;
use fs::{KScheme, Resource, ResourceSeek, VecResource};
use syscall::{MODE_DIR, MODE_FILE, Stat};
use system::error::{Error, Result, ENOENT};
/// A disk ... | });
}
}
}
Err(Error::new(ENOENT))
}
}
| {
let path = url.splitn(2, ":").nth(1).unwrap_or("").trim_matches('/');
if path.is_empty() {
let mut list = String::new();
for i in 0..unsafe { & *::env().disks.get() }.len() {
if ! list.is_empty() {
list.push('\n');
}
... | identifier_body |
disk.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use collections::borrow::ToOwned;
use collections::String;
use core::cell::UnsafeCell;
use core::cmp;
use disk::Disk;
use fs::{KScheme, Resource, ResourceSeek, VecResource};
use syscall::{MODE_DIR, MODE_FILE, Stat};
use system::error::{Error, Result, ENOENT};
/// A disk ... | (&mut self, buf: &[u8]) -> Result<usize> {
let count = try!(unsafe { &mut *self.disk.get() }.write(self.seek/512, buf));
self.seek += count as u64;
Ok(count)
}
fn seek(&mut self, pos: ResourceSeek) -> Result<usize> {
let size = unsafe { & *self.disk.get() }.size();
match... | write | identifier_name |
clone_on_copy.rs | use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::get_parent_node;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sugg;
use clippy_utils::ty::is_copy;
use rustc_errors::Applicability;
use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKin... | if is_copy(cx, ty) {
let parent_is_suffix_expr = match get_parent_node(cx.tcx, expr.hir_id) {
Some(Node::Expr(parent)) => match parent.kind {
// &*x is a nop, &x.clone() is not
ExprKind::AddrOf(..) => return,
// (*x).func() is useless, x.clone().fu... | random_line_split | |
clone_on_copy.rs | use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::get_parent_node;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sugg;
use clippy_utils::ty::is_copy;
use rustc_errors::Applicability;
use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKin... | if let ty::Ref(_, inner, _) = arg_ty.kind() {
if let ty::Ref(_, innermost, _) = inner.kind() {
span_lint_and_then(
cx,
CLONE_DOUBLE_REF,
expr.span,
&format!(
"using `clone` on a double-reference; \
... | {
let arg = match args {
[arg] if method_name == sym::clone => arg,
_ => return,
};
if cx
.typeck_results()
.type_dependent_def_id(expr.hir_id)
.and_then(|id| cx.tcx.trait_of_item(id))
.zip(cx.tcx.lang_items().clone_trait())
.map_or(true, |(x, y)| x !=... | identifier_body |
clone_on_copy.rs | use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::get_parent_node;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sugg;
use clippy_utils::ty::is_copy;
use rustc_errors::Applicability;
use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKin... | (cx: &LateContext<'_>, expr: &Expr<'_>, method_name: Symbol, args: &[Expr<'_>]) {
let arg = match args {
[arg] if method_name == sym::clone => arg,
_ => return,
};
if cx
.typeck_results()
.type_dependent_def_id(expr.hir_id)
.and_then(|id| cx.tcx.trait_of_item(id))
... | check | identifier_name |
mod.rs | extern crate regex;
pub struct Prefix {
pub nick: String,
pub user: String,
pub host: String
}
impl Prefix {
/// Attempts to parse a prefix, e.g. ":aleph!user@example.com"
pub fn parse(prefix: &str) -> Option<Prefix> {
let re = match regex::Regex::new(r"^:(.+)!(.+)@(.+)$") {
Ok... |
}
| {
Message{
prefix: Prefix::parse(prefix),
command: command.to_string(),
trailing: trailing.to_string()
}
} | identifier_body |
mod.rs | extern crate regex;
pub struct Prefix {
pub nick: String,
pub user: String,
pub host: String
}
impl Prefix {
/// Attempts to parse a prefix, e.g. ":aleph!user@example.com"
pub fn parse(prefix: &str) -> Option<Prefix> {
let re = match regex::Regex::new(r"^:(.+)!(.+)@(.+)$") {
Ok... | {
pub prefix: Option<Prefix>,
pub command: String,
pub trailing: String
}
impl Message {
// Returns a single token from a line
pub fn parse_token(line: &str) -> (&str, &str) {
let tokens: Vec<&str> = line.splitn(1,'').collect();
return (tokens[0], tokens[1]);
}
/// Parses ... | Message | identifier_name |
mod.rs | extern crate regex;
pub struct Prefix {
pub nick: String, | }
impl Prefix {
/// Attempts to parse a prefix, e.g. ":aleph!user@example.com"
pub fn parse(prefix: &str) -> Option<Prefix> {
let re = match regex::Regex::new(r"^:(.+)!(.+)@(.+)$") {
Ok(re) => re,
Err(err) => panic!("{}", err),
};
match re.captures(prefix) {
... | pub user: String,
pub host: String | random_line_split |
event.rs | use std::ops::Deref;
use std::any::Any;
use glium::Display;
use timer::Ms;
use render::Renderer;
pub use glium::glutin::Event as WindowEvent;
pub enum Event {
Window (WindowEvent),
Message (String),
Something (String, Box<Any>),
}
pub struct EventStream (Vec<Event>);
impl EventStream {
pub fn new... | for item in self {
stream = item.update(renderer, delta, stream);
}
return stream;
}
} | fn update(&mut self, renderer: &Renderer, delta: Ms, mut stream: EventStream)
-> EventStream
{ | random_line_split |
event.rs | use std::ops::Deref;
use std::any::Any;
use glium::Display;
use timer::Ms;
use render::Renderer;
pub use glium::glutin::Event as WindowEvent;
pub enum Event {
Window (WindowEvent),
Message (String),
Something (String, Box<Any>),
}
pub struct EventStream (Vec<Event>);
impl EventStream {
pub fn new... |
}
pub trait Update {
fn update(&mut self, renderer: &Renderer, delta: Ms, stream: EventStream) -> EventStream;
}
impl<'a> Update for Vec<&'a mut Update> {
fn update(&mut self, renderer: &Renderer, delta: Ms, mut stream: EventStream)
-> EventStream
{
for item in self {
strea... | {
let &EventStream (ref x) = self;
return x;
} | identifier_body |
event.rs | use std::ops::Deref;
use std::any::Any;
use glium::Display;
use timer::Ms;
use render::Renderer;
pub use glium::glutin::Event as WindowEvent;
pub enum | {
Window (WindowEvent),
Message (String),
Something (String, Box<Any>),
}
pub struct EventStream (Vec<Event>);
impl EventStream {
pub fn new(display: &Display) -> EventStream {
use glium::glutin::Event::MouseMoved;
let f = display.get_window().unwrap().hidpi_factor();
let (w... | Event | identifier_name |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::errors::corruption;
use crate::Result;
use crate::RevlogEntry;
use radixbuf::key::KeyId;
use radixbuf::radix::{
radix_insert, ... | index.reserve(7 * (end_rev - start_rev) as usize);
for i in start_rev..end_rev {
let _ = radix_insert(index, radix_offset, i.into(), rev_to_node, changelogi)?;
}
Ok(())
}
/// Helper method similar to `radixbuf::key::FixedKey::read`, but takes a revision number instead.
fn rev_to_node<K: AsRef<[... | random_line_split | |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::errors::corruption;
use crate::Result;
use crate::RevlogEntry;
use radixbuf::key::KeyId;
use radixbuf::radix::{
radix_insert, ... | <K: AsRef<[RevlogEntry]>>(changelogi: &K, rev: KeyId) -> radixbuf::Result<&[u8]> {
let buf = changelogi.as_ref();
let rev_usize: usize = rev.into();
let entry = &buf[rev_usize];
Ok(&entry.node[..])
}
/// Convert hex base16 sequence to binary base16 sequence.
fn hex_to_bin_base16<T: AsRef<[u8]>>(base16:... | rev_to_node | identifier_name |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::errors::corruption;
use crate::Result;
use crate::RevlogEntry;
use radixbuf::key::KeyId;
use radixbuf::radix::{
radix_insert, ... |
// Check if the index is behind and build incrementally
let next_rev = u32::from_be(main_index.as_ref()[RADIX_NEXT_REV_OFFSET]);
let end_rev = changelog_end_rev(&changelogi);
if next_rev > end_rev {
// next_rev cannot be larger than what changelogi has.
return ... | {
return corruption("revlog radix index corrupted (main index too small)");
} | conditional_block |
zero.rs | // Copyright (c) 2006-2009 Graydon Hoare
// Copyright (c) 2009-2013 Mozilla Foundation
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitat... | let alloc: *mut Header = transmute(malloc(size_of::<Header>() + size));
(*alloc).minus_one = -1;
(*alloc).type_desc = type_desc;
(*alloc).null_0 = 0;
(*alloc).null_1 = 0;
transmute(alloc)
}
#[lang="exchange_free"]
#[fixed_stack_segment]
pub unsafe fn exchange_free(alloc: *i8) {
free(transmu... |
// FIXME: This is horrendously inefficient.
#[lang="exchange_malloc"]
#[fixed_stack_segment]
pub unsafe fn exchange_malloc(type_desc: *i8, size: uint) -> *i8 { | random_line_split |
zero.rs | // Copyright (c) 2006-2009 Graydon Hoare
// Copyright (c) 2009-2013 Mozilla Foundation
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitat... |
memcmp(aptr, bptr, alen - 1) == 0
}
}
// FIXME(pcwalton): This function is legacy junk.
#[lang="uniq_str_eq"]
pub fn uniq_str_eq(a: &~str, b: &~str) -> bool {
str_eq(*a, *b)
}
struct StringRepr {
fill: uint,
alloc: uint,
}
// FIXME(pcwalton): This function should not be necessary, I don't th... | {
return false
} | conditional_block |
zero.rs | // Copyright (c) 2006-2009 Graydon Hoare
// Copyright (c) 2009-2013 Mozilla Foundation
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitat... |
// Legacy junk
#[lang="log_type"]
pub fn log_type<T>(_: u32, _: &T) {
// FIXME: This function should not be a lang item.
}
#[lang="annihilate"]
pub unsafe fn annihilate() {}
// Failure
#[lang="fail_"]
#[fixed_stack_segment]
pub fn fail(_: *i8, _: *i8, _: uint) ->! {
unsafe {
abort()
}
}
#[lan... | {
let size = size_of::<StringRepr>() + len + 1;
let string: *mut StringRepr = transmute(exchange_malloc(transmute(0),
size));
(*string).fill = len + 1;
(*string).alloc = len + 1;
let mut data_ptr: uint = transmute(string);
data_ptr += ... | identifier_body |
zero.rs | // Copyright (c) 2006-2009 Graydon Hoare
// Copyright (c) 2009-2013 Mozilla Foundation
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitat... | (type_desc: *i8, size: uint) -> *i8 {
let alloc: *mut Header = transmute(malloc(size_of::<Header>() + size));
(*alloc).minus_one = -1;
(*alloc).type_desc = type_desc;
(*alloc).null_0 = 0;
(*alloc).null_1 = 0;
transmute(alloc)
}
#[lang="exchange_free"]
#[fixed_stack_segment]
pub unsafe fn exchan... | exchange_malloc | identifier_name |
check_button.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Actionable;
use Bin;
use Buildable;
use Button;
use Container;
use ToggleButton;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct CheckButton(Object<ffi... | (label: &str) -> CheckButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_check_button_new_with_mnemonic(label.to_glib_none().0)).downcast_unchecked()
}
}
}
pub trait CheckButtonExt {}
impl<O: IsA<CheckButton>> CheckButtonExt for O {}
| new_with_mnemonic | identifier_name |
check_button.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Actionable;
use Bin;
use Buildable;
use Button;
use Container;
use ToggleButton;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct CheckButton(Object<ffi... | pub fn new_with_mnemonic(label: &str) -> CheckButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_check_button_new_with_mnemonic(label.to_glib_none().0)).downcast_unchecked()
}
}
}
pub trait CheckButtonExt {}
impl<O: IsA<CheckButton>> CheckB... | }
| random_line_split |
check_button.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Actionable;
use Bin;
use Buildable;
use Button;
use Container;
use ToggleButton;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct CheckButton(Object<ffi... |
pub fn new_with_label(label: &str) -> CheckButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_check_button_new_with_label(label.to_glib_none().0)).downcast_unchecked()
}
}
pub fn new_with_mnemonic(label: &str) -> CheckButton {
... | {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_check_button_new()).downcast_unchecked()
}
} | identifier_body |
lib.rs | //! Linear Algebra eXtension (LAX)
//! ===============================
//!
//! ndarray-free safe Rust wrapper for LAPACK FFI
//!
//! Linear equation, Inverse matrix, Condition number
//! --------------------------------------------------
//!
//! As the property of $A$, several types of triangular factorization are used... | (self) -> Self {
match self {
NormType::One => NormType::Infinity,
NormType::Infinity => NormType::One,
NormType::Frobenius => NormType::Frobenius,
}
}
}
/// Create a vector without initialization
///
/// Safety
/// ------
/// - Memory is not initialized. Do not ... | transpose | identifier_name |
lib.rs | //! Linear Algebra eXtension (LAX)
//! ===============================
//!
//! ndarray-free safe Rust wrapper for LAPACK FFI
//!
//! Linear equation, Inverse matrix, Condition number
//! --------------------------------------------------
//!
//! As the property of $A$, several types of triangular factorization are used... | {
let mut v = Vec::with_capacity(n);
v.set_len(n);
v
} | identifier_body | |
lib.rs | //! Linear Algebra eXtension (LAX)
//! ===============================
//!
//! ndarray-free safe Rust wrapper for LAPACK FFI
//!
//! Linear equation, Inverse matrix, Condition number
//! --------------------------------------------------
//!
//! As the property of $A$, several types of triangular factorization are used... |
impl NormType {
pub fn transpose(self) -> Self {
match self {
NormType::One => NormType::Infinity,
NormType::Infinity => NormType::One,
NormType::Frobenius => NormType::Frobenius,
}
}
}
/// Create a vector without initialization
///
/// Safety
/// ------
///... | Infinity = b'I',
Frobenius = b'F',
} | random_line_split |
mem.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... | /// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without deinitializing or copying
/// either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x = &mut 5;
//... | /// allocation:
///
/// ```
/// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
/// println!("{:?}", &data[0]); | random_line_split |
mem.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... | <T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")... | align_of | identifier_name |
mem.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... |
/// Returns the size of the type that `val` points to in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::size_of_val(val) }
... | {
unsafe { intrinsics::size_of::<T>() }
} | identifier_body |
function.rs | use syntax::ast::*;
use syntax::codemap::{Span, Spanned};
use syntax::ext::base::Annotatable;
use utils::{ArgExt, span};
#[derive(Debug)]
pub struct Function(Spanned<(Ident, FnDecl)>);
impl Function {
pub fn from(annotated: &Annotatable) -> Result<Function, Span> {
let inner = match *annotated {
... |
_ => return Err(item.span)
},
Annotatable::TraitItem(ref item) => return Err(item.span),
Annotatable::ImplItem(ref item) => return Err(item.span),
};
Ok(Function(inner))
}
pub fn ident(&self) -> &Ident {
&self.0.node.0
}
pub... | {
span((item.ident, decl.clone().unwrap()), item.span)
} | conditional_block |
function.rs | use syntax::ast::*;
use syntax::codemap::{Span, Spanned};
use syntax::ext::base::Annotatable;
use utils::{ArgExt, span};
#[derive(Debug)]
pub struct | (Spanned<(Ident, FnDecl)>);
impl Function {
pub fn from(annotated: &Annotatable) -> Result<Function, Span> {
let inner = match *annotated {
Annotatable::Item(ref item) => match item.node {
ItemKind::Fn(ref decl,..) => {
span((item.ident, decl.clone().unwrap()... | Function | identifier_name |
function.rs | use syntax::codemap::{Span, Spanned};
use syntax::ext::base::Annotatable;
use utils::{ArgExt, span};
#[derive(Debug)]
pub struct Function(Spanned<(Ident, FnDecl)>);
impl Function {
pub fn from(annotated: &Annotatable) -> Result<Function, Span> {
let inner = match *annotated {
Annotatable::Item... | use syntax::ast::*; | random_line_split | |
function.rs | use syntax::ast::*;
use syntax::codemap::{Span, Spanned};
use syntax::ext::base::Annotatable;
use utils::{ArgExt, span};
#[derive(Debug)]
pub struct Function(Spanned<(Ident, FnDecl)>);
impl Function {
pub fn from(annotated: &Annotatable) -> Result<Function, Span> {
let inner = match *annotated {
... |
pub fn find_input<'a>(&'a self, name: &Name) -> Option<&'a Arg> {
self.decl().inputs.iter().find(|arg| arg.named(name))
}
}
| {
self.0.span
} | identifier_body |
lz4.rs | extern crate lz4;
use std::env; | use std::io::Write;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
println!("LZ4 version: {}", lz4::version());
let suffix = ".lz4";
for arg in Vec::from_iter(env::args())[1..].iter() {
if arg.ends_with(suffix) {
decompress(
&Path::new(arg),
... | use std::fs::File;
use std::io::Read;
use std::io::Result; | random_line_split |
lz4.rs | extern crate lz4;
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
println!("LZ4 version: {}", lz4::version());
let suffix = ".lz4";
for arg in Vec::from_iter(env::args())[1..].iter() {
if arg... | (src: &Path, dst: &Path) -> Result<()> {
println!("Decompressing: {:?} -> {:?}", src, dst);
let mut fi = try!(lz4::Decoder::new(try!(File::open(src))));
let mut fo = try!(File::create(dst));
copy(&mut fi, &mut fo)
}
fn copy(src: &mut Read, dst: &mut Write) -> Result<()> {
let mut buffer: [u8; 1024]... | decompress | identifier_name |
lz4.rs | extern crate lz4;
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
println!("LZ4 version: {}", lz4::version());
let suffix = ".lz4";
for arg in Vec::from_iter(env::args())[1..].iter() {
if arg... |
fn copy(src: &mut Read, dst: &mut Write) -> Result<()> {
let mut buffer: [u8; 1024] = [0; 1024];
loop {
let len = try!(src.read(&mut buffer));
if len == 0 {
break;
}
try!(dst.write_all(&buffer[0..len]));
}
Ok(())
}
| {
println!("Decompressing: {:?} -> {:?}", src, dst);
let mut fi = try!(lz4::Decoder::new(try!(File::open(src))));
let mut fo = try!(File::create(dst));
copy(&mut fi, &mut fo)
} | identifier_body |
lz4.rs | extern crate lz4;
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::iter::FromIterator;
use std::path::Path;
fn main() {
println!("LZ4 version: {}", lz4::version());
let suffix = ".lz4";
for arg in Vec::from_iter(env::args())[1..].iter() {
if arg... |
}
}
fn compress(src: &Path, dst: &Path) -> Result<()> {
println!("Compressing: {:?} -> {:?}", src, dst);
let mut fi = try!(File::open(src));
let mut fo = try!(lz4::EncoderBuilder::new().build(try!(File::create(dst))));
try!(copy(&mut fi, &mut fo));
match fo.finish() {
(_, result) => re... | {
compress(&Path::new(arg), &Path::new(&(arg.to_string() + suffix))).unwrap();
} | conditional_block |
dbvt_broad_phase3d.rs | extern crate nalgebra as na;
use na::{Isometry3, Vector3};
use ncollide3d::bounding_volume;
use ncollide3d::broad_phase::{BroadPhase, BroadPhaseInterferenceHandler, DBVTBroadPhase};
use ncollide3d::shape::Ball;
struct InterferenceHandler;
impl BroadPhaseInterferenceHandler<i32> for InterferenceHandler {
fn is_in... |
fn interference_started(&mut self, _: &i32, _: &i32) {}
fn interference_stopped(&mut self, _: &i32, _: &i32) {}
}
fn main() {
/*
* Create the objects.
*/
let poss = [
Isometry3::new(Vector3::new(0.0, 0.0, 0.0), na::zero()),
Isometry3::new(Vector3::new(0.0, 0.5, 0.0), na::ze... | {
// Prevent self-collision.
*a != *b
} | identifier_body |
dbvt_broad_phase3d.rs | extern crate nalgebra as na;
use na::{Isometry3, Vector3};
use ncollide3d::bounding_volume;
use ncollide3d::broad_phase::{BroadPhase, BroadPhaseInterferenceHandler, DBVTBroadPhase};
use ncollide3d::shape::Ball;
struct | ;
impl BroadPhaseInterferenceHandler<i32> for InterferenceHandler {
fn is_interference_allowed(&mut self, a: &i32, b: &i32) -> bool {
// Prevent self-collision.
*a!= *b
}
fn interference_started(&mut self, _: &i32, _: &i32) {}
fn interference_stopped(&mut self, _: &i32, _: &i32) {}
}
... | InterferenceHandler | identifier_name |
dbvt_broad_phase3d.rs | extern crate nalgebra as na;
use na::{Isometry3, Vector3};
use ncollide3d::bounding_volume;
use ncollide3d::broad_phase::{BroadPhase, BroadPhaseInterferenceHandler, DBVTBroadPhase};
use ncollide3d::shape::Ball;
struct InterferenceHandler;
impl BroadPhaseInterferenceHandler<i32> for InterferenceHandler {
fn is_in... |
fn interference_stopped(&mut self, _: &i32, _: &i32) {}
}
fn main() {
/*
* Create the objects.
*/
let poss = [
Isometry3::new(Vector3::new(0.0, 0.0, 0.0), na::zero()),
Isometry3::new(Vector3::new(0.0, 0.5, 0.0), na::zero()),
Isometry3::new(Vector3::new(0.5, 0.0, 0.0), na:... | // Prevent self-collision.
*a != *b
}
fn interference_started(&mut self, _: &i32, _: &i32) {} | random_line_split |
knm_kernel.rs | use matrix::{Scalar,Mat,RoCM,Matrix};
use core::{ptr, marker::PhantomData};
use composables::{GemmNode,AlgorithmStep};
use thread_comm::{ThreadInfo};
use typenum::Unsigned;
use super::knm_kernel_wrapper::{KnmKernelWrapper,GenericKnmKernelWrapper};
pub struct KnmKernel<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Mr:... | ptr::write(cp.offset(ii * c_leaf_rs + jj * c_leaf_cs), tau+beta*chi);
}
}
}
}
} | for jj in 0..c.width() as isize {
let tau = ptr::read(tp.offset(ii * t_rs + jj * t_cs));
let chi = ptr::read(cp.offset(ii * c_leaf_rs + jj * c_leaf_cs)); | random_line_split |
knm_kernel.rs | use matrix::{Scalar,Mat,RoCM,Matrix};
use core::{ptr, marker::PhantomData};
use composables::{GemmNode,AlgorithmStep};
use thread_comm::{ThreadInfo};
use typenum::Unsigned;
use super::knm_kernel_wrapper::{KnmKernelWrapper,GenericKnmKernelWrapper};
pub struct KnmKernel<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Mr:... |
}
}
| {
let tp = self.tmp.get_mut_buffer();
let t_rs = self.tmp.get_row_stride() as isize;
let t_cs = self.tmp.get_column_stride() as isize;
let mut zero = T::zero();
<KnmKernelWrapper<Mr,Nr,T>>::run(k, &mut alpha, ap, bp, &mut zero, tp, t_rs, t_cs);
/... | conditional_block |
knm_kernel.rs | use matrix::{Scalar,Mat,RoCM,Matrix};
use core::{ptr, marker::PhantomData};
use composables::{GemmNode,AlgorithmStep};
use thread_comm::{ThreadInfo};
use typenum::Unsigned;
use super::knm_kernel_wrapper::{KnmKernelWrapper,GenericKnmKernelWrapper};
pub struct KnmKernel<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Mr:... | (&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) -> () {
for z in 0..a.width() {
for y in 0..c.height() {
for x in 0..c.width() {
let t = a.get(y,z) * b.get(z,x) + c.get(y,x);
c.set(y, x, t);
}
... | run | identifier_name |
knm_kernel.rs | use matrix::{Scalar,Mat,RoCM,Matrix};
use core::{ptr, marker::PhantomData};
use composables::{GemmNode,AlgorithmStep};
use thread_comm::{ThreadInfo};
use typenum::Unsigned;
use super::knm_kernel_wrapper::{KnmKernelWrapper,GenericKnmKernelWrapper};
pub struct KnmKernel<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Mr:... |
}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, Mr: Unsigned, Nr: Unsigned>
GemmNode<T, At, Bt, Ct> for KnmKernel<T, At, Bt, Ct, Mr, Nr>
where At: RoCM<T>, Bt: RoCM<T>, Ct: RoCM<T>
{
#[inline(always)]
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) -> () {
... | {
let mut desc = Vec::new();
desc.push(AlgorithmStep::K{bsz: 4});
desc
} | identifier_body |
sha2.rs |
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8,..64],
buffer_idx: uint,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8,..64],
... | {
let total_size = 1000000;
let buffer = Vec::from_elem(blocksize * 2, 'a' as u8);
let mut rng = IsaacRng::new_unseeded();
let mut count = 0;
digest.reset();
while count < total_size {
let next: uint = rng.gen_range(0, 2 * blocksize + 1);
let rem... | identifier_body | |
sha2.rs | the
/// high-order value and the 2nd item is the low order value.
fn to_bits(self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// ov... |
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
}
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing... | {
panic!("numeric overflow occurred.")
} | conditional_block |
sha2.rs | is the
/// high-order value and the 2nd item is the low order value.
fn to_bits(self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
///... | // A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32,..8]) -> Engine256State {
... | }
}
| random_line_split |
sha2.rs | the
/// high-order value and the 2nd item is the low order value.
fn to_bits(self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// ov... | (&mut self) -> Vec<u8> {
let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8);
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.re... | result_bytes | identifier_name |
unboxed-closures-drop.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 ... | assert_eq!(drop_count(), 1);
}
assert_eq!(drop_count(), 3);
}
fn test_fn_mut() {
{
b(move |a: isize, b| { a + b });
}
assert_eq!(drop_count(), 3);
{
let z = &Droppable::new();
b(move |a: isize, b| { z; a + b });
assert_eq!(drop_count(), 3);
}
ass... | a(move |a: isize, b| { z; zz; a + b }); | random_line_split |
unboxed-closures-drop.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 b<F:FnMut(isize, isize) -> isize>(mut f: F) -> isize {
f(3, 4)
}
fn c<F:FnOnce(isize, isize) -> isize>(f: F) -> isize {
f(5, 6)
}
fn test_fn() {
{
a(move |a: isize, b| { a + b });
}
assert_eq!(drop_count(), 0);
{
let z = &Droppable::new();
a(move |a: isize, b| { z... | {
f(1, 2)
} | identifier_body |
unboxed-closures-drop.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:Fn(isize, isize) -> isize>(f: F) -> isize {
f(1, 2)
}
fn b<F:FnMut(isize, isize) -> isize>(mut f: F) -> isize {
f(3, 4)
}
fn c<F:FnOnce(isize, isize) -> isize>(f: F) -> isize {
f(5, 6)
}
fn test_fn() {
{
a(move |a: isize, b| { a + b });
}
assert_eq!(drop_count(), 0);
{
... | a | identifier_name |
tree.rs | #![cfg_attr(feature = "unstable", feature(test))]
extern crate rand;
extern crate rdxsort;
#[cfg(feature = "unstable")]
mod unstable {
extern crate test;
use self::test::Bencher;
use rand::{Rng, XorShiftRng};
use rdxsort::*;
use std::collections::BTreeSet;
use std::collections::HashSet;
... | <F>(b: &mut Bencher, f: F) where F: Fn(Vec<u32>) {
let mut set = HashSet::new();
let mut rng = XorShiftRng::new_unseeded();
while set.len() < N_MEDIUM {
set.insert(rng.gen::<u32>());
}
let mut vec: Vec<u32> = set.into_iter().collect();
rng.shuffle(&mut vec[..]... | bench_generic | identifier_name |
tree.rs | #![cfg_attr(feature = "unstable", feature(test))]
extern crate rand;
extern crate rdxsort;
#[cfg(feature = "unstable")]
mod unstable {
extern crate test;
use self::test::Bencher;
use rand::{Rng, XorShiftRng};
use rdxsort::*;
use std::collections::BTreeSet;
use std::collections::HashSet;
... |
#[bench]
fn bench_set_rdx(b: &mut Bencher) {
bench_generic(b, |vec| {
let mut set = RdxTree::new();
for x in vec {
set.insert(x);
}
});
}
#[bench]
fn bench_set_std(b: &mut Bencher) {
bench_generic(b, |vec| {
l... | {
let mut set = HashSet::new();
let mut rng = XorShiftRng::new_unseeded();
while set.len() < N_MEDIUM {
set.insert(rng.gen::<u32>());
}
let mut vec: Vec<u32> = set.into_iter().collect();
rng.shuffle(&mut vec[..]);
let _ = b.iter(|| {
let ve... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.