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 |
|---|---|---|---|---|
allow.rs | use method::Method;
header! {
#[doc="`Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)"]
#[doc=""]
#[doc="The `Allow` header field lists the set of methods advertised as"]
#[doc="supported by the target resource. The purpose of this field is"]
#[doc="strictly t... | bench_header!(bench,
Allow, { vec![b"OPTIONS,GET,PUT,POST,DELETE,HEAD,TRACE,CONNECT,PATCH,fOObAr".to_vec()] }); | random_line_split | |
test_shred.rs | use crate::common::util::*;
#[test]
fn | () {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let file_a = "test_shred_remove_a";
let file_b = "test_shred_remove_b";
// Create file_a and file_b.
at.touch(file_a);
at.touch(file_b);
// Shred file_a.
scene.ucmd().arg("-u").arg(file_a).run();
// f... | test_shred_remove | identifier_name |
test_shred.rs | use crate::common::util::*;
#[test]
fn test_shred_remove() {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let file_a = "test_shred_remove_a";
let file_b = "test_shred_remove_b";
// Create file_a and file_b.
at.touch(file_a);
at.touch(file_b);
// Shred file_a... | let file = "test_shred_force";
// Create file_a.
at.touch(file);
assert!(at.file_exists(file));
// Make file_a readonly.
at.set_readonly(file);
// Try shred -u.
scene.ucmd().arg("-u").arg(file).run();
// file_a was not deleted because it is readonly.
assert!(at.file_exists(fi... | fn test_shred_force() {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
| random_line_split |
test_shred.rs | use crate::common::util::*;
#[test]
fn test_shred_remove() |
#[cfg(not(target_os = "freebsd"))]
#[test]
fn test_shred_force() {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let file = "test_shred_force";
// Create file_a.
at.touch(file);
assert!(at.file_exists(file));
// Make file_a readonly.
at.set_readonly(file);
... | {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let file_a = "test_shred_remove_a";
let file_b = "test_shred_remove_b";
// Create file_a and file_b.
at.touch(file_a);
at.touch(file_b);
// Shred file_a.
scene.ucmd().arg("-u").arg(file_a).run();
// file... | identifier_body |
spinner.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use gobject_ffi;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
... | (&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
let mut value = Value::from(&false);
unsafe ... | start | identifier_name |
spinner.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use gobject_ffi;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
... |
}
pub trait SpinnerExt {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
}
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O {
fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.to_gli... | {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).downcast_unchecked()
}
} | identifier_body |
spinner.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use gobject_ffi;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
... | let mut value = Value::from(&false);
unsafe {
gobject_ffi::g_object_get_property(self.to_glib_none().0, "active".to_glib_none().0, value.to_glib_none_mut().0);
}
value.get().unwrap()
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject... | random_line_split | |
issue-2936.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 ... | {
let x: isize = foo::<isize, cbar>(cbar(5));
assert_eq!(x, 5);
} | identifier_body | |
issue-2936.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 ... | () {
let x: isize = foo::<isize, cbar>(cbar(5));
assert_eq!(x, 5);
}
| main | identifier_name |
issue-2936.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 ... | struct cbar {
x: isize,
}
impl bar<isize> for cbar {
fn get_bar(&self) -> isize {
self.x
}
}
fn cbar(x: isize) -> cbar {
cbar {
x: x
}
}
pub fn main() {
let x: isize = foo::<isize, cbar>(cbar(5));
assert_eq!(x, 5);
} | random_line_split | |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | Ok(())
}
| return Err(Error::from(
format!("can only read version 1 of input, got version {}", version),
));
}
| conditional_block |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | let input = config.get("input").ok_or(
Error::from("missing 'input' table")
)?;
let version = input.get("version").ok_or(
Error::from("missing 'version' key in 'input' table")
)?;
let version = version.as_integer().ok_or(
Error::from("'input.version' must be an integer")
... | identifier_body | |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | onfig: &Table) -> Result<(), Error> {
let input = config.get("input").ok_or(
Error::from("missing 'input' table")
)?;
let version = input.get("version").ok_or(
Error::from("missing'version' key in 'input' table")
)?;
let version = version.as_integer().ok_or(
Error::from("'i... | lidate(c | identifier_name |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | Error::from("missing'version' key in 'input' table")
)?;
let version = version.as_integer().ok_or(
Error::from("'input.version' must be an integer")
)?;
if version!= 1 {
return Err(Error::from(
format!("can only read version 1 of input, got version {}", version),
... | random_line_split | |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... |
}
/// Represents a descriptor
pub enum Descriptor {
UserSegment(u64),
SystemSegment(u64, u64),
}
impl Descriptor {
/// Creates a kernel mode segment
pub fn kernel_code_segment() -> Descriptor {
let flags = USER_SEGMENT | PRESENT | EXECUTABLE | LONG_MODE;
Descriptor::UserSegment(flags.... | {
use x86_64::instructions::tables::{DescriptorTablePointer, lgdt};
use core::mem::size_of;
let ptr = DescriptorTablePointer {
base: self.table.as_ptr() as u64,
limit: (self.table.len() * size_of::<u64>() - 1) as u16,
};
unsafe { lgdt(&ptr) };
} | identifier_body |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... | else {
panic!("GDT full");
}
}
/// Loads the GDT table into memory.
pub fn load(&'static self) {
use x86_64::instructions::tables::{DescriptorTablePointer, lgdt};
use core::mem::size_of;
let ptr = DescriptorTablePointer {
base: self.table.as_ptr() a... | {
let index = self.next_free;
self.table[index] = value;
self.next_free += 1;
index
} | conditional_block |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... | let off = offset as u64;
bits.set_bits(16..40, off.get_bits(0..24));
bits.set_bits(56..64, off.get_bits(24..32));
Descriptor::UserSegment(bits)
}
/// Create a new TSS segment
///
/// ## Parameters
///
/// * `tss` - Task state segment
pub fn tss_segment(tss: ... | let mut bits = flags.bits();
// set the offset | random_line_split |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... | {
UserSegment(u64),
SystemSegment(u64, u64),
}
impl Descriptor {
/// Creates a kernel mode segment
pub fn kernel_code_segment() -> Descriptor {
let flags = USER_SEGMENT | PRESENT | EXECUTABLE | LONG_MODE;
Descriptor::UserSegment(flags.bits())
}
pub fn kernel_data_segment() -> ... | Descriptor | identifier_name |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... | }
}
impl<B: IBackend + LayerOps<f32>> ComputeOutput<f32, B> for Linear {
fn compute_output(&self,
backend: &B,
weights: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
output_data: &mut [&mut SharedTensor<f32>]) ... | {
let input = input_data[0].read().unwrap();
// reshape top
let output_shape = self.calculate_output_shape(input.desc());
output_data[0].write().unwrap().resize(&output_shape).unwrap();
output_gradient[0].write().unwrap().resize(&output_shape).unwrap();
// reshape weight
... | identifier_body |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... |
if let Some(weight) = weights_gradient.get(0) {
weight.write().unwrap().resize(&weight_shape).unwrap();
}
}
}
impl<B: IBackend + LayerOps<f32>> ComputeOutput<f32, B> for Linear {
fn compute_output(&self,
backend: &B,
weights: &[&SharedTen... | {
weight.write().unwrap().resize(&weight_shape).unwrap();
let filler = FillerType::Glorot {
input_size: Self::calculate_input_size(input.desc()),
output_size: self.output_size,
};
filler.fill(&mut weight.write().unwrap());
} | conditional_block |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... | (&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
output_gradients: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
... | compute_input_gradient | identifier_name |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... | type Builder = capnp_config::Builder<'a>;
/// Write the LinearConfig into a capnp message.
fn write_capnp(&self, builder: &mut Self::Builder) {
builder.borrow().set_output_size(self.output_size as u64);
}
}
impl<'a> CapnpRead<'a> for LinearConfig {
type Reader = capnp_config::Reader<'a>;
... | pub output_size: usize,
}
impl<'a> CapnpWrite<'a> for LinearConfig { | random_line_split |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... | generationNo += 1;
}
} | random_line_split | |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... | {
/// Sets the amount of threads that should be used (to calculate fitness)
/// Defaults to the amount of cpu cores detected
pub threads: usize,
//pub hooks: Vec<EvolutionHooks>
}
impl EvolutionOptions {
pub fn defaults() -> Self {
// TODO: Detect cpu core amount
EvolutionOption... | EvolutionOptions | identifier_name |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... |
}
pub fn genetic_evolution<T: Evolvable + Clone + Sync + Send, Fnew, Frate>(population: usize, stop_rule: StopRule, new: Fnew, rate: &mut Frate, opt_options: Option<EvolutionOptions>) -> T
where Fnew: Fn() -> T, Frate: FnMut(&T) -> f64
{
// get options of grab defaults
let options = match opt_options {
... | {
// TODO: Detect cpu core amount
EvolutionOptions {
threads: 6
}
} | identifier_body |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... | ,
StopRule::HasNotImprovedSince(gen) => { },
StopRule::Never => { }
}
for i in (0..population).rev() {
if i!= bests[0].1 && i!= bests[1].1 {
generation.remove(i);
}
}
// Create next Generation (2 best will continue to live... | {
if generationNo >= gen {
return (*generation[bests[0].1]).clone();
}
} | conditional_block |
lib.rs | // bench command:
//
// ```
// $ rustup run nightly cargo bench
// ```
#![feature(test)]
extern crate rand;
extern crate test;
extern crate quicksort;
extern crate rust_quicksort;
#[cfg(test)]
mod benches {
use rand::{Rng, SeedableRng, StdRng};
use test;
use quicksort;
use rust_quicksort;
static ... | fn bench_quicksort(b: &mut test::Bencher) {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| quicksort::quicksort(&mut v))
}
#[bench]
fn bench_sort(b: &mut test::Bencher) {
let mu... | b.iter(|| rust_quicksort::quicksort(&mut v))
}
#[bench] | random_line_split |
lib.rs | // bench command:
//
// ```
// $ rustup run nightly cargo bench
// ```
#![feature(test)]
extern crate rand;
extern crate test;
extern crate quicksort;
extern crate rust_quicksort;
#[cfg(test)]
mod benches {
use rand::{Rng, SeedableRng, StdRng};
use test;
use quicksort;
use rust_quicksort;
static ... |
#[bench]
fn bench_sort(b: &mut test::Bencher) {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| v.sort())
}
} | {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| quicksort::quicksort(&mut v))
} | identifier_body |
lib.rs | // bench command:
//
// ```
// $ rustup run nightly cargo bench
// ```
#![feature(test)]
extern crate rand;
extern crate test;
extern crate quicksort;
extern crate rust_quicksort;
#[cfg(test)]
mod benches {
use rand::{Rng, SeedableRng, StdRng};
use test;
use quicksort;
use rust_quicksort;
static ... | (b: &mut test::Bencher) {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| rust_quicksort::quicksort(&mut v))
}
#[bench]
fn bench_quicksort(b: &mut test::Bencher) {
let mut rng: StdRn... | bench_rust_quicksort | identifier_name |
flex.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/. */
//! Computed types for CSS values related to flexbox.
use values::generics::flex::FlexBasis as GenericFlexBasis;
... | () -> Self {
GenericFlexBasis::Width(Width::auto())
}
}
| auto | identifier_name |
flex.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/. */ |
/// The `width` value type.
#[cfg(feature = "servo")]
pub type Width = ::values::computed::NonNegativeLengthOrPercentageOrAuto;
/// The `width` value type.
#[cfg(feature = "gecko")]
pub type Width = ::values::computed::MozLength;
/// A computed value for the `flex-basis` property.
pub type FlexBasis = GenericFlexBas... |
//! Computed types for CSS values related to flexbox.
use values::generics::flex::FlexBasis as GenericFlexBasis; | random_line_split |
flex.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/. */
//! Computed types for CSS values related to flexbox.
use values::generics::flex::FlexBasis as GenericFlexBasis;
... |
}
| {
GenericFlexBasis::Width(Width::auto())
} | identifier_body |
capture-analysis-2.rs | // edition:2021
#![feature(rustc_attrs)]
#[derive(Debug)] | x: String,
y: i32,
}
fn main() {
let mut p = Point { x: String::new(), y: 10 };
let c = #[rustc_capture_analysis]
//~^ ERROR: attributes on expressions are experimental
//~| NOTE: see issue #15701 <https://github.com/rust-lang/rust/issues/15701>
|| {
//~^ First Pass analysis includes:
... | struct Point { | random_line_split |
capture-analysis-2.rs | // edition:2021
#![feature(rustc_attrs)]
#[derive(Debug)]
struct | {
x: String,
y: i32,
}
fn main() {
let mut p = Point { x: String::new(), y: 10 };
let c = #[rustc_capture_analysis]
//~^ ERROR: attributes on expressions are experimental
//~| NOTE: see issue #15701 <https://github.com/rust-lang/rust/issues/15701>
|| {
//~^ First Pass analysis include... | Point | identifier_name |
shader.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | ShaderType::VertexShader => gl::VERTEX_SHADER,
ShaderType::FragmentShader => gl::FRAGMENT_SHADER
}
} |
fn shader_type_to_enum(shader_type: ShaderType) -> GLenum {
match shader_type { | random_line_split |
shader.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (&self) -> bool {
let mut compile_status = 0;
unsafe {
gl::GetShaderiv(self.id, gl::COMPILE_STATUS, &mut compile_status);
check_error!();
}
compile_status == (gl::TRUE as i32)
}
fn get_info_length(&self) -> GLsizei {
let mut info_length = 0;
... | get_compile_status | identifier_name |
shader.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
fn get_info_log(&self) -> String {
let info_length = self.get_info_length();
let mut actual_info_length = 0;
let mut info_vec: Vec<u8> = repeat(0u8).take(info_length as usize).collect();
unsafe {
let info_vec_ptr = info_vec.as_mut_ptr() as *mut i8;
gl::GetSh... | {
self.id
} | identifier_body |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use... |
input.expect_function_matching("symbols")?;
input.parse_nested_block(|input| {
let symbols_type = input
.try_parse(SymbolsType::parse)
.unwrap_or(SymbolsType::Symbolic);
let symbols = Symbols::parse(context, input)?;
// There must be at ... | {
return Ok(CounterStyle::Name(name));
} | conditional_block |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use... | (&self) -> bool {
matches!(*self, ClipRectOrAuto::Auto)
}
}
pub use page::PageSize;
| is_auto | identifier_name |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use... |
impl CounterStyle {
/// disc value
pub fn disc() -> Self {
CounterStyle::Name(CustomIdent(atom!("disc")))
}
/// decimal value
pub fn decimal() -> Self {
CounterStyle::Name(CustomIdent(atom!("decimal")))
}
}
impl Parse for CounterStyle {
fn parse<'i, 't>(
context: ... | {
*symbols_type == SymbolsType::Symbolic
} | identifier_body |
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use... | /// A wrapper of greater-than-or-equal-to-one values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
To... | NonNegative(T::zero())
}
}
| random_line_split |
lib.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (&mut self, bit_count: u64) -> Result<()> {
let end_position = self.position + bit_count;
if end_position > self.bytes.len() as u64 * 8 {
return Err(BitReaderError::NotEnoughData {
position: self.position,
length: (self.bytes.len() * 8) as u64,
... | skip | identifier_name |
lib.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | relative_offset: self.position,
}
}
/// Read at most 8 bits into a u8.
pub fn read_u8(&mut self, bit_count: u8) -> Result<u8> {
let value = try!(self.read_value(bit_count, 8));
Ok((value & 0xff) as u8)
}
/// Read at most 16 bits into a u16.
pub fn read_u16(&... | pub fn relative_reader(&self) -> BitReader<'a> {
BitReader {
bytes: self.bytes,
position: self.position, | random_line_split |
lib.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
| {
match try!(reader.read_u8(bits)) {
0 => Ok(false),
_ => Ok(true),
}
} | identifier_body |
lib.rs | // Copyright 2015 Ilkka Rauta
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
let start_position = self.position;
let end_position = self.position + bit_count as u64;
if end_position > self.bytes.len() as u64 * 8 {
return Err(BitReaderError::NotEnoughData {
position: self.position,
length: (self.bytes.len() * 8) as u64,
... | {
return Err(BitReaderError::TooManyBitsForType {
position: self.position,
requested: bit_count,
allowed: maximum_count,
});
} | conditional_block |
videotrack.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/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackBinding::Video... |
pub fn add_track_list(&self, track_list: &VideoTrackList) {
*self.track_list.borrow_mut() = Some(Dom::from_ref(track_list));
}
pub fn remove_track_list(&self) {
*self.track_list.borrow_mut() = None;
}
}
impl VideoTrackMethods for VideoTrack {
// https://html.spec.whatwg.org/multi... | {
self.selected.set(value);
} | identifier_body |
videotrack.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/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackBinding::Video... | }
pub fn id(&self) -> DOMString {
self.id.clone()
}
pub fn kind(&self) -> DOMString {
self.kind.clone()
}
pub fn selected(&self) -> bool {
self.selected.get().clone()
}
pub fn set_selected(&self, value: bool) {
self.selected.set(value);
}
pub ... | random_line_split | |
videotrack.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/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackBinding::Video... | (&self, value: bool) {
self.selected.set(value);
}
pub fn add_track_list(&self, track_list: &VideoTrackList) {
*self.track_list.borrow_mut() = Some(Dom::from_ref(track_list));
}
pub fn remove_track_list(&self) {
*self.track_list.borrow_mut() = None;
}
}
impl VideoTrackMeth... | set_selected | identifier_name |
videotrack.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/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::VideoTrackBinding::Video... |
}
self.set_selected(value);
}
}
| {
list.set_selected(idx, value);
} | conditional_block |
surface.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::vec;
use geom::size::Size2D;
#[deriving(Eq)]
pub enum | {
fo_rgba_8888
// TODO: RGB 565, others?
}
impl format {
fn bpp(self) -> uint {
match self {
fo_rgba_8888 => 32u
}
}
}
pub struct ImageSurface {
size: Size2D<int>,
format: format,
buffer: ~[u8]
}
impl ImageSurface {
pub fn new(size: Size2D<int>, format: f... | format | identifier_name |
surface.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::vec;
use geom::size::Size2D;
#[deriving(Eq)]
pub enum format {
fo_rgba_8888
// TODO: RGB 565, ot... |
}
pub struct ImageSurface {
size: Size2D<int>,
format: format,
buffer: ~[u8]
}
impl ImageSurface {
pub fn new(size: Size2D<int>, format: format) -> ImageSurface {
ImageSurface {
size: size.clone(),
format: format,
buffer: vec::from_elem((size.area() as uint... | {
match self {
fo_rgba_8888 => 32u
}
} | identifier_body |
surface.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::vec;
use geom::size::Size2D;
#[deriving(Eq)]
pub enum format {
fo_rgba_8888
// TODO: RGB 565, ot... |
pub struct ImageSurface {
size: Size2D<int>,
format: format,
buffer: ~[u8]
}
impl ImageSurface {
pub fn new(size: Size2D<int>, format: format) -> ImageSurface {
ImageSurface {
size: size.clone(),
format: format,
buffer: vec::from_elem((size.area() as uint) *... | }
}
} | random_line_split |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... |
/// Publish data for a topic
pub fn publish(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let topic = cx.argument::<JsString>(0)?.value(&mut cx);
let json = cx.argument::<JsString>(1)?.value(&mut cx);
bridging_subscriber(topic, from_json::<serde_json::Value>(&mut cx, &json)?);
Ok(cx.undefined(... | {
let topic = cx.argument::<JsString>(0)?.value(&mut cx);
let mut subscriptions = obtain(&mut cx)?;
subscriptions.retain(|subscription| subscription.topic != topic);
Ok(cx.undefined())
} | identifier_body |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... | "While attempting to initialize pubsub: {}",
error.to_string()
));
}
Ok(cx.undefined())
} | random_line_split | |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... | (cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Vec<JsSubscription>>> {
match SUBSCRIPTIONS.try_lock() {
Ok(guard) => Ok(guard),
Err(error) => cx.throw_error(format!(
"When attempting to obtain subscriptions: {}",
error.to_string()
)),
}
}
/// Subscr... | obtain | identifier_name |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... |
}
Ok(())
});
}
}
/// Initialize the pubsub module by registering the `bridging_subscriber`
/// as a subscriber to all topics.
pub fn init(mut cx: FunctionContext) -> JsResult<JsUndefined> {
if let Err(error) = events::subscribe("*", events::Subscriber::Function(bridging_subscri... | {
let callback = subscriber.to_inner(&mut cx);
let this = cx.undefined();
let json = serde_json::to_string(&data).expect("Unable to convert to JSON");
let args = vec![cx.string(&topic), cx.string(json)];
callback.call(&m... | conditional_block |
lib.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | #[macro_export]
macro_rules! expect_replayer_valid {
() => (
$crate::with_mut_replayer(|r| {
r.verify(expectest::core::SourceLocation::new(file!(), line!()));
})
);
}
#[macro_export]
macro_rules! init_replayer {
() => (
set_replayer(VolatileCellReplayer::new());
);
} | random_line_split | |
lib.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | (&self, actual: &A) -> bool {
*actual == self.expected
}
}
#[macro_export]
macro_rules! expect_volatile_read {
($addr: expr, $val: expr) => (
$crate::with_mut_replayer(|r| {
r.expect_read($addr, $val, expectest::core::SourceLocation::new(file!(), line!()));
})
);
}
#[macro_export]
macro_... | matches | identifier_name |
lib.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
pub fn verify(&self, loc: expectest::core::SourceLocation) {
expect(self.current_replay).location(loc).to(
be_equal_to_with_context(
self.replays.len(),
format!("expected {} replays, performed {}",
self.replays.len(), self.current_replay)));
for ref replay in &*self.... | {
self.replays.push(ReplayRecord {
is_read: false,
address: address,
value: value,
replayed: false,
did_read: false,
actual_address: 0,
actual_value: 0,
loc: loc,
});
} | identifier_body |
demo.rs | use euclid::default::Rect;
use euclid::point2;
use vitral::{
color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch,
};
struct World {
font: vitral::FontData,
image: vitral::ImageData,
fore_color: Rgba,
back_color: Rgba,
}
impl World {
pub fn new() -> World... | (&mut self, _ctx: &mut World) -> Option<SceneSwitch<World>> { None }
fn render(&mut self, ctx: &mut World, canvas: &mut Canvas) -> Option<SceneSwitch<World>> {
canvas.draw_image(&ctx.image, point2(20, 20), color::WHITE);
let bounds = canvas.bounds();
let (_, title_area) = bounds.horizontal... | update | identifier_name |
demo.rs | use euclid::default::Rect;
use euclid::point2;
use vitral::{
color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch,
};
struct World {
font: vitral::FontData,
image: vitral::ImageData,
fore_color: Rgba,
back_color: Rgba,
}
impl World {
pub fn new() -> World... |
fn render(&mut self, ctx: &mut World, canvas: &mut Canvas) -> Option<SceneSwitch<World>> {
canvas.draw_image(&ctx.image, point2(20, 20), color::WHITE);
let bounds = canvas.bounds();
let (_, title_area) = bounds.horizontal_split(12);
self.title_bar(ctx, canvas, &title_area, "Vitral... | { None } | identifier_body |
demo.rs | use euclid::default::Rect;
use euclid::point2;
use vitral::{
color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch,
};
struct World {
font: vitral::FontData,
image: vitral::ImageData,
fore_color: Rgba,
back_color: Rgba,
}
impl World {
pub fn new() -> World... | impl Scene<World> for DemoScene {
fn update(&mut self, _ctx: &mut World) -> Option<SceneSwitch<World>> { None }
fn render(&mut self, ctx: &mut World, canvas: &mut Canvas) -> Option<SceneSwitch<World>> {
canvas.draw_image(&ctx.image, point2(20, 20), color::WHITE);
let bounds = canvas.bounds();
... | random_line_split | |
demo.rs | use euclid::default::Rect;
use euclid::point2;
use vitral::{
color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch,
};
struct World {
font: vitral::FontData,
image: vitral::ImageData,
fore_color: Rgba,
back_color: Rgba,
}
impl World {
pub fn new() -> World... | else {
ctx.fore_color
};
canvas.fill_rect(bounds, color);
canvas.fill_rect(&bounds.inflate(-1, -1), ctx.back_color);
let inner = bounds.inflate(-3, -3).inclusivize();
canvas.draw_line(1.0, color, inner.bottom_right(), inner.origin);
canvas.draw_line(1.0, ... | {
self.bright_color()
} | conditional_block |
mod.rs | //! This module defines the trait necessary for a session storage struct.
use self::session::Session;
pub mod session;
/// A default implementation of `SessionStore`: `Session`.
pub mod hashsession;
/// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`.
pub trai... |
/// Set the value of the session belonging to `key`, replacing any previously set value.
fn insert(&self, key: &K, value: V);
/// Retrieve the value of this session.
///
/// Returns `None` if the session belonging to `key` has not been set.
fn find(&self, key: &K) -> Option<V>;
/// Swap the... | {
Session::new(key, box self.clone())
} | identifier_body |
mod.rs | //! This module defines the trait necessary for a session storage struct.
use self::session::Session;
pub mod session;
/// A default implementation of `SessionStore`: `Session`.
pub mod hashsession;
/// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`.
pub trai... | /// Swap the given value with the current value of the session belonging to `key`.
///
/// Returns the value being replaced, or `None` if this session was not yet set.
fn swap(&self, key: &K, value: V) -> Option<V>;
/// Insert value, if not yet set, or update the current value of the session belongi... | ///
/// Returns `None` if the session belonging to `key` has not been set.
fn find(&self, key: &K) -> Option<V>; | random_line_split |
mod.rs | //! This module defines the trait necessary for a session storage struct.
use self::session::Session;
pub mod session;
/// A default implementation of `SessionStore`: `Session`.
pub mod hashsession;
/// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`.
pub trai... | (&mut self, key: K) -> Session<K, V> {
Session::new(key, box self.clone())
}
/// Set the value of the session belonging to `key`, replacing any previously set value.
fn insert(&self, key: &K, value: V);
/// Retrieve the value of this session.
///
/// Returns `None` if the session belongi... | select_session | identifier_name |
timer.rs | use std::sync::atomic::{Ordering,AtomicBool};
use std::sync::Arc;
#[derive(Clone)]
pub struct Timer{
seconds:u64,
running:Arc<AtomicBool>,
}
impl Timer{
pub fn new(seconds:u64)->Timer{
let running = Arc::new(AtomicBool::new(false));
Timer{
seconds,
running
} | use std::thread;
use std::time::Duration;
if self.running.load(Ordering::Relaxed){
return Err("timer already running")
}
let running_clone = self.running.clone();
let sleep_time = self.seconds;
let thread_builder = thread::Builder::new();
matc... | }
pub fn start(&self)->Result<(),&str>{ | random_line_split |
timer.rs | use std::sync::atomic::{Ordering,AtomicBool};
use std::sync::Arc;
#[derive(Clone)]
pub struct Timer{
seconds:u64,
running:Arc<AtomicBool>,
}
impl Timer{
pub fn new(seconds:u64)->Timer{
let running = Arc::new(AtomicBool::new(false));
Timer{
seconds,
running
}... |
}
| {
let timer = Timer::new(30);
timer.start().unwrap();
std::thread::sleep(std::time::Duration::from_secs(5));
timer.start().unwrap();
} | identifier_body |
timer.rs | use std::sync::atomic::{Ordering,AtomicBool};
use std::sync::Arc;
#[derive(Clone)]
pub struct Timer{
seconds:u64,
running:Arc<AtomicBool>,
}
impl Timer{
pub fn new(seconds:u64)->Timer{
let running = Arc::new(AtomicBool::new(false));
Timer{
seconds,
running
}... | (){
let timer = Timer::new(30);
assert_eq!(timer.is_running(),false);
timer.start().unwrap();
}
#[test]
#[should_panic(expected = "timer already running")]
fn multiple_timer_test(){
let timer = Timer::new(30);
timer.start().unwrap();
std::thread::sleep(st... | timer_test | identifier_name |
timer.rs | use std::sync::atomic::{Ordering,AtomicBool};
use std::sync::Arc;
#[derive(Clone)]
pub struct Timer{
seconds:u64,
running:Arc<AtomicBool>,
}
impl Timer{
pub fn new(seconds:u64)->Timer{
let running = Arc::new(AtomicBool::new(false));
Timer{
seconds,
running
}... |
let running_clone = self.running.clone();
let sleep_time = self.seconds;
let thread_builder = thread::Builder::new();
match thread_builder.spawn(move ||{
running_clone.store(true,Ordering::Relaxed);
thread::sleep(Duration::from_secs(sleep_time));
runn... | {
return Err("timer already running")
} | conditional_block |
klog.rs | use core::fmt;
#[derive(PartialEq, PartialOrd)]
pub enum Level {
Debug,
Info,
Warning,
Error,
Fatal,
}
fn write_nothing(_: &str) {}
static mut WRITE: fn(&str) = write_nothing;
static mut LEVEL: Level = Level::Info;
pub fn init(write: fn(&str), level: Level) {
unsafe {
WRITE = write;
... | (level: Level, args: fmt::Arguments) {
unsafe {
if level < LEVEL {
return;
}
let writer: &mut fmt::Write = &mut Writer;
let prefix = match level {
Level::Debug => "d ",
Level::Info => "i ",
Level::Warning => "W ",
Level::Er... | log | identifier_name |
klog.rs | use core::fmt;
#[derive(PartialEq, PartialOrd)]
pub enum Level {
Debug,
Info,
Warning,
Error,
Fatal,
}
fn write_nothing(_: &str) {}
static mut WRITE: fn(&str) = write_nothing;
static mut LEVEL: Level = Level::Info;
pub fn init(write: fn(&str), level: Level) {
unsafe {
WRITE = write;
... | fn write_str(&mut self, s: &str) -> fmt::Result {
unsafe { WRITE(s); }
Ok(())
}
}
pub fn log(level: Level, args: fmt::Arguments) {
unsafe {
if level < LEVEL {
return;
}
let writer: &mut fmt::Write = &mut Writer;
let prefix = match level {
... |
struct Writer;
impl fmt::Write for Writer { | random_line_split |
mod.rs | // Copyright 2016 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 decode_error_kind(errno: i32) -> ErrorKind {
match errno {
syscall::ECONNREFUSED => ErrorKind::ConnectionRefused,
syscall::ECONNRESET => ErrorKind::ConnectionReset,
syscall::EPERM | syscall::EACCES => ErrorKind::PermissionDenied,
syscall::EPIPE => ErrorKind::BrokenPipe,
... | {} | identifier_body |
mod.rs | // Copyright 2016 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 mod thread_local;
pub mod time;
#[cfg(not(test))]
pub fn init() {}
pub fn decode_error_kind(errno: i32) -> ErrorKind {
match errno {
syscall::ECONNREFUSED => ErrorKind::ConnectionRefused,
syscall::ECONNRESET => ErrorKind::ConnectionReset,
syscall::EPERM | syscall::EACCES => ErrorKind::... | pub mod stack_overflow;
pub mod stdio;
pub mod syscall;
pub mod thread; | random_line_split |
mod.rs | // Copyright 2016 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 decode_error_kind(errno: i32) -> ErrorKind {
match errno {
syscall::ECONNREFUSED => ErrorKind::ConnectionRefused,
syscall::ECONNRESET => ErrorKind::ConnectionReset,
syscall::EPERM | syscall::EACCES => ErrorKind::PermissionDenied,
syscall::EPIPE => ErrorKind::BrokenPipe,... | init | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(fnbox)]
#![feature(fs_time)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![fe... | pub mod about_loader;
pub mod bluetooth_thread;
pub mod chrome_loader;
pub mod connector;
pub mod cookie;
pub mod cookie_storage;
pub mod data_loader;
pub mod file_loader;
pub mod filemanager_thread;
pub mod hsts;
pub mod http_loader;
pub mod image_cache_thread;
pub mod mime_classifier;
pub mod pub_domains;
pub mod res... | extern crate webrender_traits;
extern crate websocket;
| random_line_split |
trait-safety-ok.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. | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Simple smoke test that unsafe traits can be compiled etc.
unsafe trait Foo {
fn... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
trait-safety-ok.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x: isize = 22;
assert_eq!(22, take_foo(&x));
}
| main | identifier_name |
trait-safety-ok.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 take_foo<F:Foo>(f: &F) -> isize { f.foo() }
fn main() {
let x: isize = 22;
assert_eq!(22, take_foo(&x));
}
| { *self } | identifier_body |
limited_heap.rs | use min_max_heap::{IntoIter, MinMaxHeap};
use std::iter::IntoIterator;
use super::weighted::WeightedItem;
/// A heap that only allows a constant amount of items. It will keep the items
/// with the highest priority.
#[derive(Clone)]
pub struct LimitedHeap<I, W>
where
W: Ord,
{
heap: MinMaxHeap<WeightedItem<I,... |
pub fn pop(&mut self) -> Option<I> {
self.0.pop()
}
pub fn clear(&mut self) {
self.0.clear()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn peek(&self) -> Option<&I> {
self.0.peek()
}
}
im... | {
let priority = element.get_weight();
self.0.push(element, priority)
} | identifier_body |
limited_heap.rs | use min_max_heap::{IntoIter, MinMaxHeap};
use std::iter::IntoIterator;
use super::weighted::WeightedItem;
/// A heap that only allows a constant amount of items. It will keep the items
/// with the highest priority.
#[derive(Clone)]
pub struct LimitedHeap<I, W>
where
W: Ord,
{
heap: MinMaxHeap<WeightedItem<I,... | (self) -> Self::IntoIter {
self.heap.into_iter().into()
}
}
| into_iter | identifier_name |
limited_heap.rs | use min_max_heap::{IntoIter, MinMaxHeap};
use std::iter::IntoIterator;
use super::weighted::WeightedItem;
/// A heap that only allows a constant amount of items. It will keep the items
/// with the highest priority.
#[derive(Clone)]
pub struct LimitedHeap<I, W>
where
W: Ord,
{
heap: MinMaxHeap<WeightedItem<I,... | Some(self.heap.push_pop_min(WeightedItem(element, priority)).0)
}
}
pub fn pop(&mut self) -> Option<I> {
self.heap.pop_max().map(|wi| wi.0)
}
pub fn clear(&mut self) {
self.heap.clear();
}
pub fn len(&self) -> usize {
self.heap.len()
}
pub ... | pub fn push(&mut self, element: I, priority: W) -> Option<I> {
if self.capacity > self.heap.len() {
self.heap.push(WeightedItem(element, priority));
None
} else { | random_line_split |
limited_heap.rs | use min_max_heap::{IntoIter, MinMaxHeap};
use std::iter::IntoIterator;
use super::weighted::WeightedItem;
/// A heap that only allows a constant amount of items. It will keep the items
/// with the highest priority.
#[derive(Clone)]
pub struct LimitedHeap<I, W>
where
W: Ord,
{
heap: MinMaxHeap<WeightedItem<I,... | else {
Some(self.heap.push_pop_min(WeightedItem(element, priority)).0)
}
}
pub fn pop(&mut self) -> Option<I> {
self.heap.pop_max().map(|wi| wi.0)
}
pub fn clear(&mut self) {
self.heap.clear();
}
pub fn len(&self) -> usize {
self.heap.len()
}
... | {
self.heap.push(WeightedItem(element, priority));
None
} | conditional_block |
lookup.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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
// later version.
// Th... | (mut self, key: NodeKey) -> super::Result<Option<Q::Item>> {
let mut hash = self.hash;
// this loop iterates through non-inline nodes.
for depth in 0.. {
let node_data = match self.db.get(&hash) {
Some(value) => value,
None => {
re... | look_up | identifier_name |
lookup.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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
// later version.
// Th... | ;
node_data = children[idx as usize];
}
_ => return Ok(None),
}
// check if new node data is inline or hash.
let r = Rlp::new(node_data);
if r.is_data() && r.size() == 32 {
... | { 1 } | conditional_block |
lookup.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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
// later version.
// Th... | loop {
match Node::decoded(node_data) {
Node::Leaf(k, value) => {
return Ok(match k == key {
true => Some(self.query.decode(value)),
false => None,
... | {
let mut hash = self.hash;
// this loop iterates through non-inline nodes.
for depth in 0.. {
let node_data = match self.db.get(&hash) {
Some(value) => value,
None => {
return Err(Box::new(match depth {
... | identifier_body |
lookup.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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
// later version.
// Th... | _ => AVLError::IncompleteDatabase(hash),
}));
}
};
self.query.record(&hash, &node_data, depth);
// this loop iterates through all inline children (usually max 1)
// witho... | return Err(Box::new(match depth {
0 => AVLError::InvalidStateRoot(hash), | random_line_split |
lib.rs | extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use quote::ToTokens;
use syn;
//##########################################
// #[derive] mode macros
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as... | (_attr: TokenStream, item: TokenStream) -> TokenStream {
// syn::ItemStruct requires feature "full"
let input = syn::parse_macro_input!(item as syn::ItemStruct);
let name = &input.ident;
let result = match input.fields {
syn::Fields::Named(ref fields) => {
let fields = &fields.name... | struct_extension | identifier_name |
lib.rs | extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use quote::ToTokens;
use syn;
//##########################################
// #[derive] mode macros
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as... |
}
| {
assert_eq!(2 + 2, 4);
} | identifier_body |
lib.rs | extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use quote::ToTokens;
use syn;
//##########################################
// #[derive] mode macros
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as... | let r = quote! {
fn hello_macro() -> String {
#input.to_owned()
}
};
r.into()
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
} | random_line_split | |
main.rs | //! The top level executable
extern crate craft;
extern crate url;
extern crate env_logger;
extern crate git2_curl;
extern crate rustc_serialize;
extern crate term;
extern crate toml;
#[macro_use]
extern crate log;
use std::{env, fs, iter};
use std::path::{Path, PathBuf};
use std::collections::{BTreeSet, HashMap};
u... | flag_list: bool,
flag_version: bool,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
arg_command: String,
arg_args: Vec<String>,
flag_locked: bool,
flag_frozen: bool,
}
const USAGE: &'static str = "
Cargo inspired build system for C based projects
Usage:
... | random_line_split | |
main.rs | //! The top level executable
extern crate craft;
extern crate url;
extern crate env_logger;
extern crate git2_curl;
extern crate rustc_serialize;
extern crate term;
extern crate toml;
#[macro_use]
extern crate log;
use std::{env, fs, iter};
use std::path::{Path, PathBuf};
use std::collections::{BTreeSet, HashMap};
u... | (config: &Config, command: &String) -> CraftResult<Option<Vec<String>>> {
let alias_name = format!("alias.{}", command);
let mut result = Ok(None);
match config.get_string(&alias_name) {
Ok(value) => {
if let Some(record) = value {
let alias_commands = record.val
... | aliased_command | identifier_name |
main.rs | //! The top level executable
extern crate craft;
extern crate url;
extern crate env_logger;
extern crate git2_curl;
extern crate rustc_serialize;
extern crate term;
extern crate toml;
#[macro_use]
extern crate log;
use std::{env, fs, iter};
use std::path::{Path, PathBuf};
use std::collections::{BTreeSet, HashMap};
u... |
fn aliased_command(config: &Config, command: &String) -> CraftResult<Option<Vec<String>>> {
let alias_name = format!("alias.{}", command);
let mut result = Ok(None);
match config.get_string(&alias_name) {
Ok(value) => {
if let Some(record) = value {
let alias_commands =... | {
macro_rules! cmd {
($name:ident) => (if args[1] == stringify!($name).replace("_", "-") {
config.shell().set_verbosity(Verbosity::Verbose);
let r = craft::call_main_without_stdin($name::execute, config,
$name::USAGE,
... | identifier_body |
kzip_sys.rs | // Copyright 2020 The Kythe Authors. 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 appli... | #[doc = " \\brief Deallocates KzipWriter."]
#[doc = ""]
#[doc = " Must be called once KzipWriter is no longer needed."]
pub fn KzipWriter_Delete(writer: *mut KzipWriter);
}
extern "C" {
#[doc = " \\brief Closes the writer."]
#[doc = " Must be called before destroying the object."]
pub fn Kzi... | encoding: i32,
create_status: *mut i32,
) -> *mut KzipWriter;
}
extern "C" { | random_line_split |
kzip_sys.rs | // Copyright 2020 The Kythe Authors. 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 appli... | {
_unused: [u8; 0],
}
extern "C" {
#[doc = " \\brief Creates a new kzip writer."]
#[doc = " \\param path The path to the file to create."]
#[doc = " \\param path_len the string length of path, required due to the C API."]
#[doc = " \\param encoding The compilation unit encoding, either"]
#[doc ... | KzipWriter | identifier_name |
db.rs | panic!("Couldn't connect, sleep disabled!");
}
}
}
/// Set state of query
pub fn set_query_state(conn: &mut PooledConn, qid: &u64, state: &str) {
match conn.exec_drop(
"UPDATE querydetails SET status =?, progress =? WHERE qid =?",
(&state, &0, qid),
) {
Ok(_) => (),
... | fn get_db_create_sql<'a>() -> Vec<String> {
let raw_sql = include_str!("../../setup.sql");
let reg = regex::Regex::new(r"(/\*(.|\s)*?\*/)").unwrap(); // https://regex101.com/r/bG6aF2/6, replace `\/` with `/`
let raw_sql = reg.replace_all(raw_sql, "");
let raw_sql = raw_sql.replace("\n", "");
let r... | /// Returns a vector of table setup sql
#[cfg(test)] | random_line_split |
db.rs | > older then age
pub fn get_files_to_delete(
conn: &mut PooledConn,
del_type: DeleteRequestType,
) -> Result<(Vec<u64>, Vec<(u64, String)>)> {
let sql = String::from(
"SELECT `query_files`.`qid`,`files`.`fid`,`name` FROM files \
LEFT JOIN `query_files` ON files.fid = query_files.fid ",
... | {
let (conf, pool) = connect();
let mut conn = pool.get_conn().unwrap();
let request = create_request(false, &conf);
setup(&mut conn);
let id = insert_query_core(&request, &mut conn).unwrap();
let new_error = String::from("asd");
super::add_query_error(&mut conn... | identifier_body | |
db.rs | panic!("Couldn't connect, sleep disabled!");
}
}
}
/// Set state of query
pub fn set_query_state(conn: &mut PooledConn, qid: &u64, state: &str) {
match conn.exec_drop(
"UPDATE querydetails SET status =?, progress =? WHERE qid =?",
(&state, &0, qid),
) {
Ok(_) => (),
... | (conn: &mut PooledConn, qid: &u64) -> Option<String> {
let mut stmt = conn
.prep("SELECT `msg` FROM `queryerror` WHERE `qid`=?")
.unwrap();
let mut result = conn.exec_iter(&stmt, (qid,)).unwrap();
result.next().unwrap().unwrap().take("msg")
}
/// Test wrapper, acce... | get_error | identifier_name |
tests.rs | extern crate arrayvec;
use arrayvec::ArrayVec;
use std::mem;
#[test]
fn test_simple() {
use std::ops::Add;
let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new();
vec.push(vec![1, 2, 3, 4]);
vec.push(vec![10]);
vec.push(vec![-1, 13, -2]);
for elt in &vec {
assert_eq!(elt.iter().fol... | () {
const N: usize = 4096;
let mut vec: ArrayVec<[_; N]> = ArrayVec::new();
for _ in 0..N {
assert!(vec.push(1u8).is_none());
}
assert!(vec.push(0).is_some());
assert_eq!(vec.len(), N);
}
#[test]
fn test_iter() {
let mut iter = ArrayVec::from([1, 2, 3]).into_iter();
assert_eq!(... | test_u16_index | identifier_name |
tests.rs | extern crate arrayvec;
use arrayvec::ArrayVec;
use std::mem;
#[test]
fn test_simple() {
use std::ops::Add;
let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new();
vec.push(vec![1, 2, 3, 4]);
vec.push(vec![10]);
vec.push(vec![-1, 13, -2]);
for elt in &vec {
assert_eq!(elt.iter().fol... | fn test_is_send_sync() {
let data = ArrayVec::<[Vec<i32>; 5]>::new();
&data as &Send;
&data as &Sync;
}
#[test]
fn test_compact_size() {
// Future rust will kill these drop flags!
// 4 elements size + 1 len + 1 enum tag + [1 drop flag]
type ByteArray = ArrayVec<[u8; 4]>;
println!("{}", mem:... | assert_eq!(&array[..], &[0, 1, 2, 3, 4]);
}
#[test] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.