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 | // Copyright 2014 The rust-pcre authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except ac... | else if curr_refcount + adjust > 65535 {
panic!("refcount overflow");
}
native::pcre_refcount(code, adjust)
}
pub unsafe fn pcre_study(code: *const ::detail::pcre,
options: &EnumSet<::StudyOption>) -> *mut ::PcreExtra {
assert!(!code.is_null());
let converted_options =... | {
panic!("refcount underflow");
} | conditional_block |
cli.rs | // Copyright 2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_snake_case)]
use std;
use std::collections;
use std::io::prelude::*;
use bio::stats::{LogProb, Prob};
use... | {
p0: Vec<Prob>,
p1: Vec<Prob>,
codebook_path: String,
estimate_path: Option<String>,
stats_path: Option<String>,
threads: usize,
cells: Regex,
window_width: u32,
seed: u64,
#[builder(setter(skip))]
counts: collections::HashMap<String, collections::HashMap<String, Counts>>,
}... | xpression | identifier_name |
cli.rs | // Copyright 2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_snake_case)]
use std;
use std::collections;
use std::io::prelude::*;
use bio::stats::{LogProb, Prob};
use... | let mut total_counts = collections::HashMap::new();
for res in reader.records() {
let record = res.unwrap();
let total_count = total_counts.entry(record.cell_id).or_insert(0);
*total_count += 1;
}
let mut writer = csv::Writer::from_writer(std::io::stdout()).delimiter(b'\t');
... | /*pub fn stats(N: u8, m: u8, p0: Prob, p1: Prob, dist: u8, codebook_path: &str) {
let codebook = io::codebook::Reader::from_file(codebook_path, dist).unwrap().codebook();
let model = model::readout::new_model(N, m, p0, p1, dist, codebook);
let mut reader = io::merfishdata::Reader::from_reader(std::io::stdin... | random_line_split |
lib.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may no... |
}
}
}
#[test]
fn test_arena_destructors() {
let arena = Arena::new();
for i in range(0u, 10) {
// Arena allocate something with drop glue to make sure it
// doesn't leak.
arena.alloc(|| Rc::new(i));
// Allocate something with funny size and alignment, to keep
... | {
self.alloc_copy(op)
} | conditional_block |
lib.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file m... | pub fn test_copy() {
let arena = TypedArena::new();
for _ in range(0u, 100000) {
arena.alloc(Point {
x: 1,
y: 2,
z: 3,
});
}
}
#[bench]
pub fn bench_copy(b: &mut Bencher) {
let arena = TypedArena::ne... | y: int,
z: int,
}
#[test] | random_line_split |
lib.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may no... | (b: &mut Bencher) {
let arena = Arena::new();
b.iter(|| {
arena.alloc(|| Noncopy {
string: "hello world".to_string(),
array: vec!( | bench_noncopy_old_arena | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of_derive;
use gfx_traits::{DisplayList, Ep... |
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
// https://w3c.github.io/paint-timing/
pub struct PaintTimeMetrics {
pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>,
navigati... | {} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of_derive;
use gfx_traits::{DisplayList, Ep... | (
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
) -> PaintTimeMetrics {
PaintTimeMetrics {
pending_metrics: RefCell::new(HashMap::new()),... | new | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of_derive;
use gfx_traits::{DisplayList, Ep... | println!(
"Navigation start: {}",
pwm.get_navigation_start().unwrap().to_ms()
);
println!("{:?} {:?} {:?}", url, metric_type, time.to_ms());
}
}
// spec: https://github.com/WICG/time-to-interactive
// https://github.com/GoogleChrome/lighthouse/issues/27
// we can loo... | if opts::get().print_pwm { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of_derive;
use gfx_traits::{DisplayList, Ep... |
}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
| {
warn!("Sending metric to script thread failed ({}).", e);
} | conditional_block |
size_of.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 script::dom::characterdata::CharacterData;
use script::dom::element::Element;
use script::dom::eventtarget::Ev... | sizeof_checker!(size_span, HTMLSpanElement, 328);
sizeof_checker!(size_text, Text, 192);
sizeof_checker!(size_characterdata, CharacterData, 192); | sizeof_checker!(size_element, Element, 312);
sizeof_checker!(size_htmlelement, HTMLElement, 328);
sizeof_checker!(size_div, HTMLDivElement, 328); | random_line_split |
file_system.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::raw::Env;
use engine_traits::{EngineFileSystemInspector, FileSystemInspector};
use rocksdb::FileSystemInspector as DBFileSystemInspector;
use std::sync::Arc;
// Use engine::Env directly since Env is not abstracted.
pub(crate) fn get_env(
... |
fn write(&self, len: usize) -> Result<usize, String> {
self.inspector.write(len)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compat::Compat;
use crate::event_listener::RocksEventListener;
use crate::raw::{ColumnFamilyOptions, DBCompressionType};
use crate::raw_util::{new... | {
self.inspector.read(len)
} | identifier_body |
file_system.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::raw::Env;
use engine_traits::{EngineFileSystemInspector, FileSystemInspector};
use rocksdb::FileSystemInspector as DBFileSystemInspector;
use std::sync::Arc;
// Use engine::Env directly since Env is not abstracted.
pub(crate) fn get_env(
... | () {
let value_size = 1024;
let temp_dir = Builder::new()
.prefix("test_inspected_compact")
.tempdir()
.unwrap();
let (db, stats) = new_test_db(temp_dir.path().to_str().unwrap());
let value = vec![b'v'; value_size];
db.put(&data_key(b"a1"), &val... | test_inspected_compact | identifier_name |
error.rs | // Copyright 2016 Claus Matzinger
//
// 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 ... |
}
impl Error for BackendError {
fn description(&self) -> &str {
&self.description
}
}
impl fmt::Display for BackendError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.description, f)
}
}
#[derive(Debug, Clone)]
pub enum BlobError {
Action(CrateDBError)... | {
BackendError { description: error }
} | identifier_body |
error.rs | // Copyright 2016 Claus Matzinger
//
// 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 ... | Debug::fmt(self, f)
}
}
impl Error for CrateDBError {
fn description(&self) -> &str {
&self.description
}
}
#[derive(Debug)]
pub struct CrateDBConfigurationError {
pub description: String,
}
impl Error for CrateDBConfigurationError {
fn description(&self) -> &str {
&self.... | }
impl fmt::Display for CrateDBError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | random_line_split |
error.rs | // Copyright 2016 Claus Matzinger
//
// 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 ... | (error: io::Error) -> BackendError {
BackendError { description: format!("Error on I/O: {:?}", error) }
}
pub fn new(error: String) -> BackendError {
BackendError { description: error }
}
}
impl Error for BackendError {
fn description(&self) -> &str {
&self.description
}
}... | from_io | 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... |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T:?Sized> Clone for &'a T {
/// Return a shallow copy of the reference.
#[inline]
fn clone(&self) -> &'a T { *self }
}
macro_rules! clone_impl {
($t:ty) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for $t {
... | {
*self = source.clone()
} | 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()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T:?Sized> Clone for &'a T {
/// Return a shallow copy of the reference.
#[inline]
fn clone(&self) -> &'a T { *self }
}
macro_rules! clone_impl {
($t:ty) => {
#[stable(feat... | clone_from | 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... |
macro_rules! extern_fn_clone {
($($A:ident),*) => (
#[unstable(feature = "core",
reason = "this may not be sufficient for fns with region parameters")]
impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType {
/// Return a copy of a function pointer... | clone_impl! { f64 }
clone_impl! { () }
clone_impl! { bool }
clone_impl! { char } | random_line_split |
class-attributes-1.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 ... | (&mut self) { println!("{} landed on hir feet", self. name); }
}
#[cat_maker]
fn cat(name: String) -> cat { cat{name: name,} }
pub fn main() { let _kitty = cat("Spotty".to_string()); }
| drop | identifier_name |
class-attributes-1.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 ... |
#[cat_maker]
fn cat(name: String) -> cat { cat{name: name,} }
pub fn main() { let _kitty = cat("Spotty".to_string()); } |
impl Drop for cat {
#[cat_dropper]
fn drop(&mut self) { println!("{} landed on hir feet" , self . name); }
} | random_line_split |
test_modbus_tcp_pi.rs | use libmodbus::{Modbus, ModbusTCPPI};
#[test]
fn new_tcp_pi() |
#[test]
#[ignore]
fn tcp_pi_accept() {
let mut server = Modbus::new_tcp_pi("::1", "1502").unwrap();
match server.tcp_pi_listen(1) {
Ok(mut socket) => assert_eq!(server.tcp_pi_accept(&mut socket).unwrap(), 1),
_ => panic!("could not listen to socket"),
}
}
#[test]
#[ignore]
fn tcp_pi_liste... | {
assert!(Modbus::new_tcp_pi("::1", "1502").is_ok());
} | identifier_body |
test_modbus_tcp_pi.rs | use libmodbus::{Modbus, ModbusTCPPI};
#[test]
fn new_tcp_pi() {
assert!(Modbus::new_tcp_pi("::1", "1502").is_ok());
}
#[test]
#[ignore]
fn tcp_pi_accept() {
let mut server = Modbus::new_tcp_pi("::1", "1502").unwrap();
match server.tcp_pi_listen(1) {
Ok(mut socket) => assert_eq!(server.tcp_pi_accep... | () {
let mut server = Modbus::new_tcp_pi("::1", "1502").unwrap();
let client = Modbus::new_tcp_pi("::1", "1502").unwrap();
match server.tcp_pi_listen(1) {
Ok(mut _socket) => assert!(client.connect().is_ok()),
_ => panic!("could not listen to socket"),
}
}
| tcp_pi_listen | identifier_name |
test_modbus_tcp_pi.rs | use libmodbus::{Modbus, ModbusTCPPI};
#[test]
fn new_tcp_pi() {
assert!(Modbus::new_tcp_pi("::1", "1502").is_ok());
}
#[test]
#[ignore]
fn tcp_pi_accept() { | match server.tcp_pi_listen(1) {
Ok(mut socket) => assert_eq!(server.tcp_pi_accept(&mut socket).unwrap(), 1),
_ => panic!("could not listen to socket"),
}
}
#[test]
#[ignore]
fn tcp_pi_listen() {
let mut server = Modbus::new_tcp_pi("::1", "1502").unwrap();
let client = Modbus::new_tcp_pi... | let mut server = Modbus::new_tcp_pi("::1", "1502").unwrap(); | random_line_split |
broker.rs | //! Represents a broker - the endpoint for all trading activity on the platform.
//! Also contains helper functions for managing accounts.
use std::collections::HashMap;
use futures::sync::oneshot::Receiver;
use futures::stream::Stream;
use trading::tick::Tick;
pub use trading::objects::*;
/// A broker is the endpo... | /// orders being filled, etc.
fn get_stream(&mut self) -> Result<Box<Stream<Item=(u64, BrokerResult), Error=()> + Send>, BrokerError>;
/// Returns a stream of live ticks for a symbol.
fn sub_ticks(&mut self, symbol: String) -> Result<Box<Stream<Item=Tick, Error=()> + Send>, BrokerError>;
}
/// Utility... | /// Executes a BrokerAction on the broker, returning its response.
fn execute(&mut self, action: BrokerAction) -> PendingResult;
/// Returns a stream of messages pushed from the broker that do not originate from an
/// action sent to the broker. These can be things like notifications of closed positio... | random_line_split |
mod.rs | /*! Provides packet encoding and decoding functionality, as well as the packet enum.
This module does not handle the checksum. If it did, it would be incredibly difficult to write Fastnet tests.*/
pub use self::encoder::*;
pub use self::decoder::*;
use uuid;
use std::cmp;
mod encoder;
mod encoder_tests;
mod decoder;... | pub const DATA_PACKET_SPECIFIER: u8 = 0;
pub const ACK_PACKET_SPECIFIER: u8 = 1;
pub const FRAME_HEADER_SIZE: usize = 12; //64-bit sequence number and 32-bit length.
/**Represents the part of a data packet that a channel must use to assemble packets.
The actual channel itself is stored in the enum variant.
These ar... | pub const DATA_FRAME_START_BIT: u8 = 0;
pub const DATA_FRAME_END_BIT: u8 = 1;
pub const DATA_RELIABLE_BIT: u8 = 2;
| random_line_split |
mod.rs | /*! Provides packet encoding and decoding functionality, as well as the packet enum.
This module does not handle the checksum. If it did, it would be incredibly difficult to write Fastnet tests.*/
pub use self::encoder::*;
pub use self::decoder::*;
use uuid;
use std::cmp;
mod encoder;
mod encoder_tests;
mod decoder;... | (&self)->bool {
(self.flags & DATA_FRAME_END_BIT) > 0
}
pub fn sequence_number(&self)->u64 {
self.sequence_number
}
pub fn borrow_header(&self)->Option<&FrameHeader> {
self.header.as_ref()
}
pub fn get_header(&self)->Option<FrameHeader> {
self.header
}
... | is_frame_end | identifier_name |
mod.rs | /*! Provides packet encoding and decoding functionality, as well as the packet enum.
This module does not handle the checksum. If it did, it would be incredibly difficult to write Fastnet tests.*/
pub use self::encoder::*;
pub use self::decoder::*;
use uuid;
use std::cmp;
mod encoder;
mod encoder_tests;
mod decoder;... |
let start_flag = (self.is_frame_start as u8) << DATA_FRAME_START_BIT;
let end_flag = (self.is_frame_end as u8) << DATA_FRAME_END_BIT;
let reliable_flag = (self.is_reliable as u8) << DATA_RELIABLE_BIT;
let flags = start_flag | end_flag | reliable_flag;
DataPacket {
s... | {
panic!("Header and start flag mismatch. Start flag = {:?}, header = {:?}", self.is_frame_start, self.header);
} | conditional_block |
test.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/. */
pub use dom::bindings::str::{ByteString, DOMString};
pub use dom::headers::normalize_value;
// For compile-fail t... | () -> usize {
size_of::<Element>()
}
pub fn EventTarget() -> usize {
size_of::<EventTarget>()
}
pub fn HTMLDivElement() -> usize {
size_of::<HTMLDivElement>()
}
pub fn HTMLElement() -> usize {
size_of::<HTMLElement>()
}
pub fn HTMLSpanElement() -> usiz... | Element | identifier_name |
test.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/. */
pub use dom::bindings::str::{ByteString, DOMString};
pub use dom::headers::normalize_value;
// For compile-fail t... | }
pub fn Text() -> usize {
size_of::<Text>()
}
} | random_line_split | |
test.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/. */
pub use dom::bindings::str::{ByteString, DOMString};
pub use dom::headers::normalize_value;
// For compile-fail t... |
pub fn HTMLSpanElement() -> usize {
size_of::<HTMLSpanElement>()
}
pub fn Node() -> usize {
size_of::<Node>()
}
pub fn Text() -> usize {
size_of::<Text>()
}
}
| {
size_of::<HTMLElement>()
} | identifier_body |
memorysink.rs | //! Code sink that writes binary machine code into contiguous memory.
//!
//! The `CodeSink` trait is the most general way of extracting binary machine code from Cretonne,
//! and it is implemented by things like the `test binemit` file test driver to generate
//! hexadecimal machine code. The `CodeSink` has some undes... | offset: isize,
relocs: &'a mut RelocSink,
}
impl<'a> MemoryCodeSink<'a> {
/// Create a new memory code sink that writes a function to the memory pointed to by `data`.
pub fn new(data: *mut u8, relocs: &mut RelocSink) -> MemoryCodeSink {
MemoryCodeSink {
data,
offset: 0,
... | /// Note that `MemoryCodeSink` writes multi-byte values in the native byte order of the host. This
/// is not the right thing to do for cross compilation.
pub struct MemoryCodeSink<'a> {
data: *mut u8, | random_line_split |
memorysink.rs | //! Code sink that writes binary machine code into contiguous memory.
//!
//! The `CodeSink` trait is the most general way of extracting binary machine code from Cretonne,
//! and it is implemented by things like the `test binemit` file test driver to generate
//! hexadecimal machine code. The `CodeSink` has some undes... | (&mut self, x: u32) {
unsafe {
write_unaligned(self.data.offset(self.offset) as *mut u32, x);
}
self.offset += 4;
}
fn put8(&mut self, x: u64) {
unsafe {
write_unaligned(self.data.offset(self.offset) as *mut u64, x);
}
self.offset += 8;
... | put4 | identifier_name |
memorysink.rs | //! Code sink that writes binary machine code into contiguous memory.
//!
//! The `CodeSink` trait is the most general way of extracting binary machine code from Cretonne,
//! and it is implemented by things like the `test binemit` file test driver to generate
//! hexadecimal machine code. The `CodeSink` has some undes... |
fn reloc_jt(&mut self, rel: Reloc, jt: JumpTable) {
let ofs = self.offset();
self.relocs.reloc_jt(ofs, rel, jt);
}
}
| {
let ofs = self.offset();
self.relocs.reloc_external(ofs, rel, name, addend);
} | identifier_body |
http.rs | the size of the next chunk
None => try!(read_chunk_size(body))
};
debug!("Chunked read, remaining={}", rem);
if rem == 0 {
*opt_remaining = Some(0);
// chunk of size 0 signals the end of the chunked stream
... |
/// Ends the HttpWriter, and returns the underlying Writer.
///
/// A final `write()` is called with an empty message, and then flushed.
/// The ChunkedWriter variant will use this to write the 0-sized last-chunk.
#[inline]
pub fn end(mut self) -> IoResult<W> {
try!(self.write(&[]));
... | {
match *self {
ThroughWriter(ref mut w) => w,
ChunkedWriter(ref mut w) => w,
SizedWriter(ref mut w, _) => w,
EmptyWriter(ref mut w) => w,
}
} | identifier_body |
http.rs | know the size of the next chunk
None => try!(read_chunk_size(body))
};
debug!("Chunked read, remaining={}", rem);
if rem == 0 {
*opt_remaining = Some(0);
// chunk of size 0 signals the end of the chunked strea... | /// Access the inner Writer mutably.
///
/// Warning: You should not write to this directly, as you can corrupt
/// the state.
#[inline]
pub fn get_mut<'a>(&'a mut self) -> &'a mut W {
match *self {
ThroughWriter(ref mut w) => w,
ChunkedWriter(ref mut w) => w,
... | EmptyWriter(ref w) => w,
}
}
| random_line_split |
http.rs | the size of the next chunk
None => try!(read_chunk_size(body))
};
debug!("Chunked read, remaining={}", rem);
if rem == 0 {
*opt_remaining = Some(0);
// chunk of size 0 signals the end of the chunked stream
... | <'a>(&'a self) -> &'a W {
match *self {
ThroughWriter(ref w) => w,
ChunkedWriter(ref w) => w,
SizedWriter(ref w, _) => w,
EmptyWriter(ref w) => w,
}
}
/// Access the inner Writer mutably.
///
/// Warning: You should not write to this direc... | get_ref | identifier_name |
match-pattern-lit.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
assert_eq!(altlit(10), 20);
assert_eq!(altlit(11), 22);
}
| {
match f {
10 => { println!("case 10"); return 20; }
11 => { println!("case 11"); return 22; }
_ => panic!("the impossible happened")
}
} | identifier_body |
match-pattern-lit.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 ... | match f {
10 => { println!("case 10"); return 20; }
11 => { println!("case 11"); return 22; }
_ => panic!("the impossible happened")
}
}
pub fn main() {
assert_eq!(altlit(10), 20);
assert_eq!(altlit(11), 22);
} | fn altlit(f: isize) -> isize { | random_line_split |
match-pattern-lit.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 ... | (f: isize) -> isize {
match f {
10 => { println!("case 10"); return 20; }
11 => { println!("case 11"); return 22; }
_ => panic!("the impossible happened")
}
}
pub fn main() {
assert_eq!(altlit(10), 20);
assert_eq!(altlit(11), 22);
}
| altlit | identifier_name |
match-pattern-lit.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 ... |
_ => panic!("the impossible happened")
}
}
pub fn main() {
assert_eq!(altlit(10), 20);
assert_eq!(altlit(11), 22);
}
| { println!("case 11"); return 22; } | conditional_block |
estr-slice.rs | // run-pass
pub fn main() |
println!("{}", a);
assert!(a < b);
assert!(a <= b);
assert_ne!(a, b);
assert!(b >= a);
assert!(b > a);
println!("{}", b);
assert!(a < c);
assert!(a <= c);
assert_ne!(a, c);
assert!(c >= a);
assert!(c > a);
println!("{}", c);
assert!(c < cc);
assert!(c <=... | {
let x = "hello";
let v = "hello";
let y : &str = "there";
println!("{}", x);
println!("{}", y);
assert_eq!(x.as_bytes()[0], 'h' as u8);
assert_eq!(x.as_bytes()[4], 'o' as u8);
let z : &str = "thing";
assert_eq!(v, x);
assert_ne!(x, z);
let a = "aaaa";
let b = "bbbb"... | identifier_body |
estr-slice.rs | // run-pass
pub fn | () {
let x = "hello";
let v = "hello";
let y : &str = "there";
println!("{}", x);
println!("{}", y);
assert_eq!(x.as_bytes()[0], 'h' as u8);
assert_eq!(x.as_bytes()[4], 'o' as u8);
let z : &str = "thing";
assert_eq!(v, x);
assert_ne!(x, z);
let a = "aaaa";
let b = "bb... | main | identifier_name |
estr-slice.rs | // run-pass
pub fn main() {
let x = "hello";
let v = "hello";
let y : &str = "there";
println!("{}", x);
println!("{}", y);
assert_eq!(x.as_bytes()[0], 'h' as u8);
assert_eq!(x.as_bytes()[4], 'o' as u8);
let z : &str = "thing";
assert_eq!(v, x);
assert_ne!(x, z);
let a ... | } | random_line_split | |
TestDegrees.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... | half3 __attribute__((kernel)) testDegreesHalf3Half3(half3 inV) {
return degrees(inV);
}
half4 __attribute__((kernel)) testDegreesHalf4Half4(half4 inV) {
return degrees(inV);
} | return degrees(inV);
}
| random_line_split |
canvaspattern.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 canvas_traits::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle};
use dom::bindings::codegen::Bindings::Canva... | (surface_data: Vec<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle) -> CanvasPattern {
let (x, y) = match repeat {
RepetitionStyle::Repeat => (true, true),
RepetitionStyle::RepeatX => (true, false),
RepetitionStyle::RepeatY => (false, true),
RepetitionStyl... | new_inherited | identifier_name |
canvaspattern.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 canvas_traits::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle};
use dom::bindings::codegen::Bindings::Canva... | -> Root<CanvasPattern> {
reflect_dom_object(box CanvasPattern::new_inherited(surface_data, surface_size, repeat),
global, CanvasPatternBinding::Wrap)
}
}
impl<'a> ToFillOrStrokeStyle for &'a CanvasPattern {
fn to_fill_or_stroke_style(self) -> FillOrStrokeStyle ... | pub fn new(global: GlobalRef,
surface_data: Vec<u8>,
surface_size: Size2D<i32>,
repeat: RepetitionStyle) | random_line_split |
appcenter.rs | use std::env;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::{Command, Output};
use std::str;
use console::strip_ansi_codes;
use failure::{bail, err_msg, Error};
use glob::{glob_with, MatchOptions};
// use serde::de::{Deserialize, Deserializer, Error as DeError};
use if_chain::if_chain;
use serde::d... |
pub fn get_appcenter_deployment_history(
app: &str,
deployment: &str,
) -> Result<Vec<AppCenterPackage>, Error> {
let appcenter_bin = if Path::new(APPCENTER_NPM_PATH).exists() {
APPCENTER_NPM_PATH
} else {
APPCENTER_BIN_PATH
};
let output = Command::new(appcenter_bin)
.... | {
let message = str::from_utf8(&output.stdout).unwrap_or("Unknown AppCenter error");
let stripped = strip_ansi_codes(message);
let cause = if let Some(rest) = stripped.strip_prefix("Error: ") {
rest
} else {
&stripped
}
.to_string();
err_msg(cause)
} | identifier_body |
appcenter.rs | use std::env;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::{Command, Output};
use std::str;
use console::strip_ansi_codes;
use failure::{bail, err_msg, Error};
use glob::{glob_with, MatchOptions};
// use serde::de::{Deserialize, Deserializer, Error as DeError};
use if_chain::if_chain;
use serde::d... | .next_element()?
.ok_or_else(|| de::Error::custom("missing package label"))?;
// Drain the sequence, ignoring all other values.
while seq.next_element::<de::IgnoredAny>()?.is_some() {}
Ok(AppCenterPackage { label })
}
... | ) -> Result<AppCenterPackage, S::Error> {
// Since we only need the package label, we can deserialize the JSON string very
// efficiently by only looking at the first element.
let label = seq | random_line_split |
appcenter.rs | use std::env;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::{Command, Output};
use std::str;
use console::strip_ansi_codes;
use failure::{bail, err_msg, Error};
use glob::{glob_with, MatchOptions};
// use serde::de::{Deserialize, Deserializer, Error as DeError};
use if_chain::if_chain;
use serde::d... | (
package: &AppCenterPackage,
platform: &str,
bundle_id_override: Option<&str>,
version_name_override: Option<&str>,
release_name_override: Option<&str>,
) -> Result<String, Error> {
let bundle_id_ovrr = bundle_id_override.unwrap_or("");
let version_name_ovrr = version_name_override.unwrap_o... | get_react_native_appcenter_release | identifier_name |
main.rs | extern crate rustc_serialize;
| None
} else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
let bytes2 = str2.from_hex().expect("could not parse hex string");
let mut vec = Vec::new();
for (a, b) in bytes1.iter().zip(bytes2.iter()) {
vec.push(a ^ b);
}
Some... | use rustc_serialize::hex::{FromHex, ToHex};
fn xor_hex_strings(str1: &str, str2: &str) -> Option<String> {
if str1.len() != str2.len() { | random_line_split |
main.rs | extern crate rustc_serialize;
use rustc_serialize::hex::{FromHex, ToHex};
fn xor_hex_strings(str1: &str, str2: &str) -> Option<String> {
if str1.len()!= str2.len() {
None
} else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
let bytes2 = str2.from_hex().expect("co... | {
match xor_hex_strings("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") {
Some(x) => println!("{}", x),
None => println!("nope"),
}
} | identifier_body | |
main.rs | extern crate rustc_serialize;
use rustc_serialize::hex::{FromHex, ToHex};
fn xor_hex_strings(str1: &str, str2: &str) -> Option<String> {
if str1.len()!= str2.len() | else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
let bytes2 = str2.from_hex().expect("could not parse hex string");
let mut vec = Vec::new();
for (a, b) in bytes1.iter().zip(bytes2.iter()) {
vec.push(a ^ b);
}
Some(vec.to_hex())
... | {
None
} | conditional_block |
main.rs | extern crate rustc_serialize;
use rustc_serialize::hex::{FromHex, ToHex};
fn xor_hex_strings(str1: &str, str2: &str) -> Option<String> {
if str1.len()!= str2.len() {
None
} else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
let bytes2 = str2.from_hex().expect("co... | () {
match xor_hex_strings("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") {
Some(x) => println!("{}", x),
None => println!("nope"),
}
}
| main | identifier_name |
request_set.rs | // Copyright 2015, 2016 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 la... | (&mut self, req_id: &ReqId, now: SteadyTime) -> Option<Request> {
let id = match self.ids.remove(&req_id) {
Some(id) => id,
None => return None,
};
let req = self.reqs.remove(&id).expect("entry in `ids` implies entry in `reqs`; qed");
match self.reqs.keys().next() {
Some(k) if *k > id => self.base = ... | remove | identifier_name |
request_set.rs | // Copyright 2015, 2016 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 la... | base + Duration::milliseconds(kind_timeout) <= now
}
/// Collect all pending request ids.
pub fn collect_ids<F>(&self) -> F where F: FromIterator<ReqId> {
self.ids.keys().cloned().collect()
}
}
#[cfg(test)]
mod tests {
use net::{timeout, ReqId};
use request::{Request, Receipts};
use time::{SteadyTime, Dur... | {
let base = match self.base.as_ref().cloned() {
Some(base) => base,
None => return false,
};
let kind = self.reqs.values()
.next()
.map(|r| r.kind())
.expect("base time implies `reqs` non-empty; qed");
let kind_timeout = match kind {
request::Kind::Headers => timeout::HEADERS,
request::K... | identifier_body |
request_set.rs | // Copyright 2015, 2016 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 la... | }
self.counter += 1;
}
/// Remove a request from the stack.
pub fn remove(&mut self, req_id: &ReqId, now: SteadyTime) -> Option<Request> {
let id = match self.ids.remove(&req_id) {
Some(id) => id,
None => return None,
};
let req = self.reqs.remove(&id).expect("entry in `ids` implies entry in `reqs... | random_line_split | |
msgs.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::sync::mpsc;
pub fn make_idle_task<S, M, FI>(client: Client<M>, state: S, idle_handler: FI) -> thread::JoinHandle<()>
where M: Ident + Send + Clone +'static, S: Send +'static, FI: Fn(M, &mut S) -> bool + Send +'static {
thread::sp... | <M: Ident + Clone> {
tx: HashMap<<M as Ident>::Identifier, Vec<Route<M>>>,
rx: RouteSink<M>
}
impl<M: Ident + Clone> Client<M> {
pub fn send(&self, msg: M) {
let vec = self.tx.get(&msg.ident())
.expect("Attempted to send unauthorized message!");
for dst in vec {
... | Client | identifier_name |
msgs.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::sync::mpsc;
pub fn make_idle_task<S, M, FI>(client: Client<M>, state: S, idle_handler: FI) -> thread::JoinHandle<()>
where M: Ident + Send + Clone +'static, S: Send +'static, FI: Fn(M, &mut S) -> bool + Send +'static {
thread::sp... |
}
}
MsgGraph {
client_routes,
clients
}
}
pub fn client(&mut self, client: ClientId) -> Option<Client<M>> {
let mut tx_map = HashMap::new();
for (msg, tx_routes) in self.client_routes.remove(client)? {
... | {
for dst_client in dst_clients {
let route = clients[dst_client].0.clone();
routes.push(route);
}
} | conditional_block |
msgs.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::sync::mpsc;
pub fn make_idle_task<S, M, FI>(client: Client<M>, state: S, idle_handler: FI) -> thread::JoinHandle<()>
where M: Ident + Send + Clone +'static, S: Send +'static, FI: Fn(M, &mut S) -> bool + Send +'static {
thread::sp... | for dst_client in dst_clients {
let route = clients[dst_client].0.clone();
routes.push(route);
}
}
}
}
MsgGraph {
client_routes,
clients
}
}
... | {
let mut client_routes: ClientRoutes<M> = HashMap::new();
let mut clients: ClientMap<M> = HashMap::new();
let mut msg_dests: MsgDests<M> = HashMap::new();
for (client, _, rx_msgs) in graph_spec {
clients.insert(*client, mpsc::channel());
for rx_msg in rx... | identifier_body |
msgs.rs | use std::collections::HashMap;
use std::hash::Hash;
use std::thread;
use std::sync::mpsc;
pub fn make_idle_task<S, M, FI>(client: Client<M>, state: S, idle_handler: FI) -> thread::JoinHandle<()>
where M: Ident + Send + Clone +'static, S: Send +'static, FI: Fn(M, &mut S) -> bool + Send +'static {
thread::sp... | type ClientMap<M> = HashMap<ClientId, (Route<M>, RouteSink<M>)>;
type MsgDests<M> = HashMap<<M as Ident>::Identifier, Vec<ClientId>>;
pub struct MsgGraph<M: Ident + Clone + Send +'static> {
client_routes: ClientRoutes<M>,
clients: ClientMap<M>
}
impl<M: Ident + Clone + Send> MsgGraph<M> {
pub fn new(graph... | random_line_split | |
version.rs | extern crate diesel;
extern crate serde_json;
use serde_json::Value;
use conduit::{Handler, Method};
use self::diesel::prelude::*;
use cargo_registry::version::EncodableVersion;
use cargo_registry::schema::versions;
#[derive(Deserialize)]
struct VersionList {
versions: Vec<EncodableVersion>,
}
#[derive(Deserial... | () {
let (_b, app, middle) = ::app();
let mut req = ::req(
app.clone(),
Method::Get,
"/api/v1/crates/foo_authors/1.0.0/authors",
);
{
let conn = app.diesel_database.get().unwrap();
let u = ::new_user("foo").create_or_update(&conn).unwrap();
let c = ::Crate... | authors | identifier_name |
certificate_record.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 std::io;
use std::io::{ Error, ErrorKind };
use std::fs::File;
use std::path::PathBuf;
use openssl::x509::X50... | ,
Err(error) => {
Err(Error::new(
ErrorKind::InvalidData,
format!("Could not load PEM file '{:?}': {}", pem_file, error))
)
}
}
}
impl CertificateRecord {
pub fn new(hostname: String,
certificate_file: PathBuf,
... | {
pem_file_x509.fingerprint(FINGERPRINT_DIGEST)
.map(| fingerprint | {
vec_to_str(fingerprint)
})
.ok_or_else(|| { Error::new(
ErrorKind::InvalidData,
... | conditional_block |
certificate_record.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 std::io;
use std::io::{ Error, ErrorKind };
use std::fs::File;
use std::path::PathBuf;
use openssl::x509::X50... |
}
| {
let certificate_record = CertificateRecord {
cert_file: PathBuf::from("/test/crt.pem"),
private_key_file: PathBuf::from("/test/pkf.pem"),
hostname: "test.example.com".to_owned(),
cert_fingerprint: "1234567890abcdef".to_owned()
};
assert_eq!(... | identifier_body |
certificate_record.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 std::io;
use std::io::{ Error, ErrorKind };
use std::fs::File;
use std::path::PathBuf;
use openssl::x509::X50... | cert_fingerprint: "1234567890abcdef".to_owned()
};
assert_eq!(certificate_record.get_certificate_fingerprint(), "1234567890abcdef");
}
} | private_key_file: PathBuf::from("/test/pkf.pem"),
hostname: "test.example.com".to_owned(), | random_line_split |
certificate_record.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 std::io;
use std::io::{ Error, ErrorKind };
use std::fs::File;
use std::path::PathBuf;
use openssl::x509::X50... | (pem_file: PathBuf) -> io::Result<String> {
let mut file = try!(File::open(pem_file.clone()));
match X509::from_pem(&mut file) {
Ok(pem_file_x509) => {
pem_file_x509.fingerprint(FINGERPRINT_DIGEST)
.map(| fingerprint | {
vec_to_str(fingerp... | get_x509_sha1_fingerprint_from_pem | identifier_name |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions, remove_file};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: String = threa... | ;
let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect();
storage.push(v);
allocated += vec_len;
}
let mut iovecs = Vec::with_capacity(storage.len());
for v in storage.iter_mut() {
iovecs.push(IoVec::from_mut_slice(&mut v[..]));
}
let pipe_res = pipe();
assert... | { thread_rng().gen_range(64, cmp::min(256, left)) } | conditional_block |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions, remove_file};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: String = threa... |
#[test]
#[cfg(feature = "preadv_pwritev")]
fn test_pwritev() {
use std::io::Read;
let to_write: Vec<u8> = (0..128).collect();
let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat();
let iovecs = [
IoVec::from_slice(&to_write[0..17]),
IoVec::from_slice(&to_write[17..64]),
... | {
use std::io::Write;
let tempdir = TempDir::new("nix-test_pread").unwrap();
let path = tempdir.path().join("pread_test_file");
let mut file = OpenOptions::new().write(true).read(true).create(true)
.truncate(true).open(path).unwrap();
let file_content: Vec<u8> =... | identifier_body |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions, remove_file};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: String = threa... | }
// Check whether iovecs contain all written data
assert_eq!(read_buf.len(), to_write.len());
// Check equality of written and read data
assert_eq!(&read_buf, &to_write);
let close_res = close(reader);
assert!(close_res.is_ok());
let close_res = close(writer);
assert!(close_res.is_o... | // Cccumulate data from iovecs
let mut read_buf = Vec::with_capacity(to_write.len());
for iovec in iovecs.iter() {
read_buf.extend(iovec.as_slice().iter().map(|x| x.clone())); | random_line_split |
test_uio.rs | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use std::{cmp, iter};
use std::fs::{OpenOptions, remove_file};
use std::os::unix::io::AsRawFd;
use tempdir::TempDir;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: String = threa... | () {
let s:String = thread_rng().gen_ascii_chars().take(128).collect();
let to_write = s.as_bytes().to_vec();
let mut storage = Vec::new();
let mut allocated = 0;
while allocated < to_write.len() {
let left = to_write.len() - allocated;
let vec_len = if left <= 64 { left } else { thr... | test_readv | identifier_name |
mock_engine.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use super::Result;
use crate::{Callback, ExtCallback, Modify, SnapContext, WriteData};
use crate::{Engine, RocksEngine};
use kvproto::kvrpcpb::Context;
use std::collections::LinkedList;
use std::sync::{Arc, Mutex};
/// A mock engine is a simple wrappe... | (&self, ctx: SnapContext<'_>, cb: Callback<Self::Snap>) -> Result<()> {
self.base.async_snapshot(ctx, cb)
}
fn async_write(&self, ctx: &Context, batch: WriteData, write_cb: Callback<()>) -> Result<()> {
self.async_write_ext(ctx, batch, write_cb, None, None)
}
fn async_write_ext(
... | async_snapshot | identifier_name |
mock_engine.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use super::Result;
use crate::{Callback, ExtCallback, Modify, SnapContext, WriteData};
use crate::{Engine, RocksEngine};
use kvproto::kvrpcpb::Context;
use std::collections::LinkedList;
use std::sync::{Arc, Mutex};
/// A mock engine is a simple wrappe... |
fn async_write(&self, ctx: &Context, batch: WriteData, write_cb: Callback<()>) -> Result<()> {
self.async_write_ext(ctx, batch, write_cb, None, None)
}
fn async_write_ext(
&self,
ctx: &Context,
batch: WriteData,
write_cb: Callback<()>,
proposed_cb: Option<E... | {
self.base.async_snapshot(ctx, cb)
} | identifier_body |
mock_engine.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use super::Result;
use crate::{Callback, ExtCallback, Modify, SnapContext, WriteData};
use crate::{Engine, RocksEngine};
use kvproto::kvrpcpb::Context;
use std::collections::LinkedList;
use std::sync::{Arc, Mutex};
/// A mock engine is a simple wrappe... | }
}
self
}
pub fn build(self) -> MockEngine {
MockEngine {
base: self.base,
expected_modifies: self
.expected_modifies
.map(|m| Arc::new(ExpectedWriteList(Mutex::new(m)))),
last_modifies: Arc::new(Mutex::new(V... | random_line_split | |
iter-sum-overflow-debug.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// compile-flags: -C debug_assertions=yes
use std::panic;
fn | () {
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().sum::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[2, i32::MAX].iter().product::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().cloned().sum::<i3... | main | identifier_name |
iter-sum-overflow-debug.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// compile-flags: -C debug_assertions=yes
use std::panic;
fn main() | }
| {
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().sum::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[2, i32::MAX].iter().product::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().cloned().sum::<i32>(... | identifier_body |
iter-sum-overflow-debug.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// compile-flags: -C debug_assertions=yes
|
fn main() {
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().sum::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[2, i32::MAX].iter().product::<i32>();
});
assert!(r.is_err());
let r = panic::catch_unwind(|| {
[1, i32::MAX].iter().cloned().... | use std::panic; | random_line_split |
slice.rs | use std::fs;
use CliResult;
use config::{Config, Delimiter};
use index::Indexed;
use util;
static USAGE: &'static str = "
Returns the rows in the range specified (starting at 0, half-open interval).
The range does not include headers.
If the start of the range isn't specified, then the slice starts from the first
r... |
fn rconfig(&self) -> Config {
Config::new(&self.arg_input)
.delimiter(self.flag_delimiter)
.no_headers(self.flag_no_headers)
}
fn wconfig(&self) -> Config {
Config::new(&self.flag_output)
}
}
| {
util::range(
self.flag_start, self.flag_end, self.flag_len, self.flag_index)
} | identifier_body |
slice.rs | use std::fs;
use CliResult;
use config::{Config, Delimiter};
use index::Indexed;
use util;
static USAGE: &'static str = "
Returns the rows in the range specified (starting at 0, half-open interval).
The range does not include headers.
If the start of the range isn't specified, then the slice starts from the first
r... | (&self) -> Result<(usize, usize), String> {
util::range(
self.flag_start, self.flag_end, self.flag_len, self.flag_index)
}
fn rconfig(&self) -> Config {
Config::new(&self.arg_input)
.delimiter(self.flag_delimiter)
.no_headers(self.flag_no_headers)
}
fn... | range | identifier_name |
slice.rs | use std::fs;
use CliResult;
use config::{Config, Delimiter};
use index::Indexed;
use util;
static USAGE: &'static str = "
Returns the rows in the range specified (starting at 0, half-open interval).
The range does not include headers.
If the start of the range isn't specified, then the slice starts from the first
r... | match args.rconfig().indexed()? {
None => args.no_index(),
Some(idxed) => args.with_index(idxed),
}
}
impl Args {
fn no_index(&self) -> CliResult<()> {
let mut rdr = self.rconfig().reader()?;
let mut wtr = self.wconfig().writer()?;
self.rconfig().write_headers(&mut r... | }
pub fn run(argv: &[&str]) -> CliResult<()> {
let args: Args = util::get_args(USAGE, argv)?; | random_line_split |
slice.rs | use std::fs;
use CliResult;
use config::{Config, Delimiter};
use index::Indexed;
use util;
static USAGE: &'static str = "
Returns the rows in the range specified (starting at 0, half-open interval).
The range does not include headers.
If the start of the range isn't specified, then the slice starts from the first
r... |
idx.seek(start as u64)?;
for r in idx.byte_records().take(end - start) {
wtr.write_byte_record(&r?)?;
}
wtr.flush()?;
Ok(())
}
fn range(&self) -> Result<(usize, usize), String> {
util::range(
self.flag_start, self.flag_end, self.flag_len,... | {
return Ok(());
} | conditional_block |
browsingcontext.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::DocumentBinding::DocumentMethods;
use d... | (&self, document: &Document) {
assert!(self.history.borrow().is_empty());
assert_eq!(self.active_index.get(), 0);
self.history.borrow_mut().push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
}
pub fn push_history(&self, document: &Document) {
let... | init | identifier_name |
browsingcontext.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::DocumentBinding::DocumentMethods;
use d... | {
unsafe {
WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER))
}
} | identifier_body | |
browsingcontext.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::DocumentBinding::DocumentMethods;
use d... |
*bp = found;
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn get(cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleValue,
id: HandleId,
vp: MutableHandleValue)
-> bool {
l... | {
return false;
} | conditional_block |
browsingcontext.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::DocumentBinding::DocumentMethods;
use d... | unsafe {
let WindowProxyHandler(handler) = window.windowproxy_handler();
assert!(!handler.is_null());
let cx = window.get_cx();
let parent = window.reflector().get_jsobject();
assert!(!parent.get().is_null());
assert!(((*JS_GetClass(parent... |
#[allow(unsafe_code)]
pub fn new(window: &Window, frame_element: Option<&Element>, id: PipelineId) -> Root<BrowsingContext> { | random_line_split |
threads.rs | // Copyright 2020 Google Inc. All Rights Reserved.
//
// 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... | {
Wake(MemArg32) = 0x00,
I32Wait(MemArg32) = 0x01,
I64Wait(MemArg64) = 0x02,
I32Load(MemArg32) = 0x10,
I64Load(MemArg64) = 0x11,
I32Load8U(MemArg8) = 0x12,
I32Load16U(MemArg16) = 0x13,
I64Load8U(MemArg8) = 0x14,
I64Load16U(MemArg16) = 0x15,
I64Load32U(MemArg32) = 0x16,
I32St... | Atomic | identifier_name |
threads.rs | // Copyright 2020 Google Inc. All Rights Reserved. | // 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 writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// Se... | //
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | random_line_split |
pipe.rs | extern crate desync;
extern crate futures;
use desync::*;
use futures::stream;
use futures::future;
use futures::executor;
use futures::sink::{SinkExt};
use futures::stream::{StreamExt};
use futures::channel::mpsc;
use futures::prelude::*;
use std::sync::*;
use std::thread;
use std::time::Duration;
#[test]
fn pipe_i... | thread::sleep(Duration::from_millis(5));
}
// This will stick in the channel (pipe should not be accepting more input)
assert!(sender.try_send(2) == Ok(()));
thread::sleep(Duration::from_millis(5));
// Channel will push back on this one
let channel_full = se... | {
// Create a channel we'll use to send data to the pipe
let (mut sender, receiver) = mpsc::channel(0);
// Create an object to pipe through
let obj = Arc::new(Desync::new(1));
// Create a pipe that adds values from the stream to the value in the object
let mut pipe_out = pipe(Arc::clone(&ob... | identifier_body |
pipe.rs | extern crate desync;
extern crate futures;
use desync::*;
use futures::stream;
use futures::future;
use futures::executor;
use futures::sink::{SinkExt};
use futures::stream::{StreamExt};
use futures::channel::mpsc;
use futures::prelude::*;
use std::sync::*;
use std::thread;
use std::time::Duration;
#[test]
fn pipe_i... |
// Create an object
let obj = Arc::new(Desync::new(vec![]));
// Add anything received to the vector via a pipe
pipe_in(Arc::clone(&obj), receiver, |core, item| { core.push(item); Box::pin(future::ready(())) });
// Initially empty
assert!(obj.sync(|core| core.clone()) == vec![]);
// Send ... | let (mut sender, receiver) = mpsc::channel(0); | random_line_split |
pipe.rs | extern crate desync;
extern crate futures;
use desync::*;
use futures::stream;
use futures::future;
use futures::executor;
use futures::sink::{SinkExt};
use futures::stream::{StreamExt};
use futures::channel::mpsc;
use futures::prelude::*;
use std::sync::*;
use std::thread;
use std::time::Duration;
#[test]
fn pipe_i... | () {
// Create a channel we'll use to send data to the pipe
let (mut sender, receiver) = mpsc::channel(0);
// Create an object to pipe through
let obj = Arc::new(Desync::new(1));
// Create a pipe that adds values from the stream to the value in the object
let mut pipe_out = pipe(Arc::clone(... | pipe_through_produces_backpressure | identifier_name |
reachable.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... | (&self, def_id: ast::DefId) -> bool {
if def_id.krate!= ast::LOCAL_CRATE {
return false
}
let node_id = def_id.node;
match self.tcx.map.find(node_id) {
Some(ast_map::NodeItem(item)) => {
match item.node {
ast::ItemFn(..) => ite... | def_id_represents_local_inlined_item | identifier_name |
reachable.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... | ast::ItemStruct(..) | ast::ItemEnum(..) |
ast::ItemDefaultImpl(..) => {}
_ => {
self.tcx.sess.span_bug(item.span,
"found non-function item \
... | // worklist, as determined by the privacy pass
ast::ItemExternCrate(_) | ast::ItemUse(_) |
ast::ItemTy(..) | ast::ItemStatic(_, _, _) |
ast::ItemMod(..) | ast::ItemForeignMod(..) |
ast::ItemImpl(..) | ast::ItemTrait(..) ... | random_line_split |
reachable.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... | }
// Information needed while computing reachability.
struct ReachableContext<'a, 'tcx: 'a> {
// The type context.
tcx: &'a ty::ctxt<'tcx>,
// The set of items which must be exported in the linkage sense.
reachable_symbols: NodeSet,
// A worklist of item IDs. Each item ID in this worklist will be ... | {
if attr::requests_inline(&impl_item.attrs) ||
generics_require_inlining(&sig.generics) {
return true
}
if is_local(impl_src) {
{
match tcx.map.find(impl_src.node) {
Some(ast_map::NodeItem(item)) => {
item_might_be_inlined(&*item)
... | identifier_body |
performanceobserverentrylist.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::PerformanceObserverEntryListBinding;
us... | (global: &GlobalScope, entries: PerformanceEntryList)
-> Root<PerformanceObserverEntryList> {
let observer_entry_list = PerformanceObserverEntryList::new_inherited(entries);
reflect_dom_object(box observer_entry_list, global, PerformanceObserverEntryListBinding::Wrap)
}
}
impl PerformanceOb... | new | identifier_name |
performanceobserverentrylist.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::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope;
use dom::performance::PerformanceEntryList;
use dom::performanceentry::PerformanceEntry;
use dom_struct::dom_struct;
#[dom_struct]
pub struct PerformanceObse... |
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::PerformanceObserverEntryListBinding;
use dom::bindings::codegen::Bindings::PerformanceObserverEntryListBinding::PerformanceObserverEntryListMethods; | random_line_split |
performanceobserverentrylist.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::PerformanceObserverEntryListBinding;
us... |
}
| {
self.entries.borrow().get_entries_by_name_and_type(Some(name), entry_type)
} | identifier_body |
point.rs | extern crate rand;
extern crate calco;
use rand::{Rng, SeedableRng, StdRng};
use rand::distributions::{IndependentSample, Range};
use calco::{Calco, Parameters};
use calco::traits::{Evaluate, Mutate, Reproduce};
const SEED: [usize; 4] = [4, 2, 42, 4242];
const GLOBAL_MINIMUM: (f32, f32) = (15.0, -15.0);
#[derive(Deb... |
}
impl Reproduce for SimpleIndividual {
fn reproduce<'a, R: Rng>(&self, father: &Self, mut rng: R) -> Self {
match rng.gen_range(0, 6u8) {
0 => SimpleIndividual { x: self.x, y: father.y },
1 => SimpleIndividual { x: father.x, y: self.y },
2 => SimpleIndividual {
... | {
if rng.gen() {
self.x = rng.gen_range(-10000.0, 10000.0)
}
else {
self.y = rng.gen_range(-10000.0, 10000.0)
}
} | identifier_body |
point.rs | extern crate rand;
extern crate calco;
use rand::{Rng, SeedableRng, StdRng};
use rand::distributions::{IndependentSample, Range};
use calco::{Calco, Parameters};
use calco::traits::{Evaluate, Mutate, Reproduce};
const SEED: [usize; 4] = [4, 2, 42, 4242];
const GLOBAL_MINIMUM: (f32, f32) = (15.0, -15.0);
#[derive(Deb... | <'a, R: Rng>(&self, father: &Self, mut rng: R) -> Self {
match rng.gen_range(0, 6u8) {
0 => SimpleIndividual { x: self.x, y: father.y },
1 => SimpleIndividual { x: father.x, y: self.y },
2 => SimpleIndividual {
x: (self.x + father.x) / 2.0,
y: ... | reproduce | identifier_name |
point.rs | extern crate rand;
extern crate calco;
use rand::{Rng, SeedableRng, StdRng};
use rand::distributions::{IndependentSample, Range};
use calco::{Calco, Parameters};
use calco::traits::{Evaluate, Mutate, Reproduce};
const SEED: [usize; 4] = [4, 2, 42, 4242];
const GLOBAL_MINIMUM: (f32, f32) = (15.0, -15.0);
#[derive(Deb... | let parameters = Parameters {
mutation_rate: 0.2,
population_limit: Some(100),
elite_threshold: 0.9,
deletion_threshold: 0.5,
};
let population = (0..100).into_iter()
.map(move |_| SimpleIndividual {
x: dist.ind_sample(&mut ... | let dist = Range::new(-1000.0, 1000.0);
| random_line_split |
build.rs | #[cfg(target_os="macos")]
fn build_flags(){
println!("cargo:rustc-flags= -L framework=/Library/Frameworks");
}
#[cfg(target_os="linux")]
fn build_flags(){
}
| extern crate libc;
#[cfg(target_os="windows")]
use std::env;
#[cfg(target_os="windows")]
use std::mem;
#[cfg(target_os="windows")]
fn build_flags(){
let key = if cfg!(target_pointer_width = "32") {
"GSTREAMER_1_0_ROOT_X86"
}else{
"GSTREAMER_1_0_ROOT_X86_64"
};
if let Ok(gst_root) = env::var(key){
println!("ca... |
#[cfg(target_os="windows")] | random_line_split |
build.rs | #[cfg(target_os="macos")]
fn | (){
println!("cargo:rustc-flags= -L framework=/Library/Frameworks");
}
#[cfg(target_os="linux")]
fn build_flags(){
}
#[cfg(target_os="windows")]
extern crate libc;
#[cfg(target_os="windows")]
use std::env;
#[cfg(target_os="windows")]
use std::mem;
#[cfg(target_os="windows")]
fn build_flags(){
let key = if cfg!(ta... | build_flags | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.