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 |
|---|---|---|---|---|
unboxed-closures-extern-fn.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 z = call_it_once(square, 22);
assert_eq!(x, square(22));
assert_eq!(y, square(22));
assert_eq!(z, square(22));
} |
fn main() {
let x = call_it(&square, 22);
let y = call_it_mut(&mut square, 22); | random_line_split |
unboxed-closures-extern-fn.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <F:Fn(isize)->isize>(f: &F, x: isize) -> isize {
f(x)
}
fn call_it_mut<F:FnMut(isize)->isize>(f: &mut F, x: isize) -> isize {
f(x)
}
fn call_it_once<F:FnOnce(isize)->isize>(f: F, x: isize) -> isize {
f(x)
}
fn main() {
let x = call_it(&square, 22);
let y = call_it_mut(&mut square, 22);
let z ... | call_it | identifier_name |
unboxed-closures-extern-fn.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 = call_it(&square, 22);
let y = call_it_mut(&mut square, 22);
let z = call_it_once(square, 22);
assert_eq!(x, square(22));
assert_eq!(y, square(22));
assert_eq!(z, square(22));
} | identifier_body | |
_marker.rs | pub fn _marker() {
phantom_data_struct();
copy_trait();
// send_trait
// sync_trait
// unsize_trait
}
fn phantom_data_struct() {
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
fn | <'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
let ptr = vec.as_ptr();
Slice {
start: ptr,
end: unsafe { ptr.offset(vec.len() as isize) },
phantom: PhantomData,
}
}
}
fn copy_trait() {
#[derive(Copy, Clone)]
struct MyStructOne;
struct MyStructTwo... | borrow_vec | identifier_name |
_marker.rs | // sync_trait
// unsize_trait
}
fn phantom_data_struct() {
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
let ptr = vec.as_ptr();
... | pub fn _marker() {
phantom_data_struct();
copy_trait();
// send_trait | random_line_split | |
_marker.rs | pub fn _marker() |
fn phantom_data_struct() {
use std::marker::PhantomData;
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
fn borrow_vec<'a, T>(vec: &'a Vec<T>) -> Slice<'a, T> {
let ptr = vec.as_ptr();
Slice {
start: ptr,
... | {
phantom_data_struct();
copy_trait();
// send_trait
// sync_trait
// unsize_trait
} | identifier_body |
font_face.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 [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(m... |
}
}
rule
}
/// A @font-face rule that is known to have font-family and src declarations.
#[cfg(feature = "servo")]
pub struct FontFace<'a>(&'a FontFaceRuleData);
/// A list of effective sources that we send over through IPC to the font cache.
#[cfg(feature = "servo")]
#[derive(Clone, Debug)]
#[cfg_at... | {
let location = error.location;
let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error);
context.log_css_error(error_context, location, error)
} | conditional_block |
font_face.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 [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(m... | <W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
self.url.to_css(dest)
}
}
/// A font-display value for a @font-face rule.
/// The font-display descriptor determines how a font face is displayed based
/// on whether and when it is downloaded and ready to use.
define_css_keyword_en... | to_css | identifier_name |
font_face.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 [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(m... | use selectors::parser::SelectorParseErrorKind;
use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt;
use style_traits::{Comma, OneOrMoreSeparated, ParseError, StyleParseErrorKind, ToCss};
use values::computed::font::FamilyName;
use values::specified::url::SpecifiedUrl;
/// A source for a font-face ru... | use properties::longhands::font_language_override; | random_line_split |
cardgen.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::NoteType;
use crate::{
card::{Card, CardID},
cloze::add_cloze_numbers_in_string,
collection::Collection,
deckconf::{DeckConf, DeckConfID},
decks::DeckID,
e... | return Ok(deck);
}
}
self.default_deck_conf()
}
fn default_deck_conf(&mut self) -> Result<(DeckID, DeckConfID)> {
// currently hard-coded to 1, we could create this as needed in the future
Ok(self
.deck_conf_if_normal(DeckID(1))?
... | fn deck_for_adding(&mut self, did: Option<DeckID>) -> Result<(DeckID, DeckConfID)> {
if let Some(did) = did {
if let Some(deck) = self.deck_conf_if_normal(did)? { | random_line_split |
cardgen.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::NoteType;
use crate::{
card::{Card, CardID},
cloze::add_cloze_numbers_in_string,
collection::Collection,
deckconf::{DeckConf, DeckConfID},
decks::DeckID,
e... |
impl Collection {
pub(crate) fn generate_cards_for_new_note(
&mut self,
ctx: &CardGenContext,
note: &Note,
target_deck_id: DeckID,
) -> Result<()> {
self.generate_cards_for_note(
ctx,
note,
&[],
Some(target_deck_id),
... | {
let mut due = None;
let mut deck_ids = HashSet::new();
for card in cards {
if due.is_none() && card.position_if_new.is_some() {
due = card.position_if_new;
}
deck_ids.insert(card.original_deck_id);
}
let existing_ords: HashSet<_> = cards.iter().map(|c| c.ord).co... | identifier_body |
cardgen.rs | // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use super::NoteType;
use crate::{
card::{Card, CardID},
cloze::add_cloze_numbers_in_string,
collection::Collection,
deckconf::{DeckConf, DeckConfID},
decks::DeckID,
e... | (
items: Vec<AlreadyGeneratedCardInfo>,
) -> Vec<(NoteID, Vec<AlreadyGeneratedCardInfo>)> {
let mut out = vec![];
for (key, group) in &items.into_iter().group_by(|c| c.nid) {
out.push((key, group.collect()));
}
out
}
#[derive(Debug, PartialEq, Default)]
pub(crate) struct ExtractedCardInfo {... | group_generated_cards_by_note | identifier_name |
concurrent_hash_map.rs | use std::ptr;
use std::marker::Copy;
use std::clone::Clone;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::{RwLock, RwLockWriteGuard};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fmt::{Debug, Formatter, Result};
use super::super::round_up_to_next_highest_power_of_two;
struct Bucket {
... |
}
impl Debug for Bucket {
fn fmt(&self, fmt: &mut Formatter) -> Result {
write!(fmt, "[ Key = {:?} Value = {:?} ]", self.key, self.value)
}
}
struct Link {
ptr: *mut Bucket
}
impl Link {
fn new(bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
... | {
Bucket {
key: Some(key),
value: Some(value),
next: None
}
} | identifier_body |
concurrent_hash_map.rs | use std::ptr;
use std::marker::Copy;
use std::clone::Clone;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::{RwLock, RwLockWriteGuard};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fmt::{Debug, Formatter, Result};
use super::super::round_up_to_next_highest_power_of_two;
struct Bucket {
... |
else {
None
}
}
fn iterate(key: i32, guard: &RwLockWriteGuard<Link>) -> Link {
let mut link = **guard;
while (*link).key!= Some(key) && (*link).next.is_some() {
link = (*link).next.unwrap();
}
link
}
| {
let mut link = iterate(key, guard);
match (*link).next {
Some(next) => link.next = next.next,
None => link.ptr = ptr::null_mut(),
}
(*link).value
} | conditional_block |
concurrent_hash_map.rs | use std::ptr;
use std::marker::Copy;
use std::clone::Clone;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::{RwLock, RwLockWriteGuard};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fmt::{Debug, Formatter, Result};
use super::super::round_up_to_next_highest_power_of_two;
struct Bucket {
... | (bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
}
}
}
impl Deref for Link {
type Target = Bucket;
fn deref(&self) -> &Bucket {
unsafe { &*self.ptr }
}
}
impl DerefMut for Link {
fn deref_mut(&mut self) -> &mut Bucket {
unsafe { &... | new | identifier_name |
concurrent_hash_map.rs | use std::ptr;
use std::marker::Copy;
use std::clone::Clone;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::{RwLock, RwLockWriteGuard};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fmt::{Debug, Formatter, Result};
use super::super::round_up_to_next_highest_power_of_two;
struct Bucket {
... | table: Vec<RwLock<Link>>,
size: AtomicUsize
}
impl Default for ConcurrentHashMap {
fn default() -> ConcurrentHashMap {
ConcurrentHashMap::new()
}
}
impl ConcurrentHashMap {
/// Create hash table with vector of locks-buckets with default size which is 16
pub fn new() -> Concurrent... | /// Currnet implementation is non resizeble vector of Read-Write locks-buckets
/// which resolve hash collisions with link to the next key value pair
pub struct ConcurrentHashMap { | random_line_split |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::Na... |
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://h... | {
navigatorinfo::Product()
} | identifier_body |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::Na... |
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://... | navigatorinfo::TaintEnabled()
} | random_line_split |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::Na... | (&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMS... | Platform | identifier_name |
regions-early-bound-used-in-bound.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 b1 = Box { t: &3i };
assert_eq!(add(b1, b1), 6i);
}
| main | identifier_name |
regions-early-bound-used-in-bound.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() {
let b1 = Box { t: &3i };
assert_eq!(add(b1, b1), 6i);
}
| {
*g1.get() + *g2.get()
} | identifier_body |
regions-early-bound-used-in-bound.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 ... | *g1.get() + *g2.get()
}
pub fn main() {
let b1 = Box { t: &3i };
assert_eq!(add(b1, b1), 6i);
} | fn add<'a,G:GetRef<'a, int>>(g1: G, g2: G) -> int { | random_line_split |
newtype-struct-drop-run.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) {
***self = 23;
}
}
fn main() {
let y = @mut 32;
{
let _x = Foo(y);
}
assert_eq!(*y, 23);
}
| drop | identifier_name |
tuple-struct-constructor-pointer.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 ... | (int);
#[derive(PartialEq, Debug)]
struct Bar(int, int);
pub fn main() {
let f: fn(int) -> Foo = Foo;
let g: fn(int, int) -> Bar = Bar;
assert_eq!(f(42), Foo(42));
assert_eq!(g(4, 7), Bar(4, 7));
}
| Foo | identifier_name |
tuple-struct-constructor-pointer.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() {
let f: fn(int) -> Foo = Foo;
let g: fn(int, int) -> Bar = Bar;
assert_eq!(f(42), Foo(42));
assert_eq!(g(4, 7), Bar(4, 7));
} | #[derive(PartialEq, Debug)]
struct Foo(int);
#[derive(PartialEq, Debug)]
struct Bar(int, int);
| random_line_split |
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::CssStringWriter;
use gecko_bindings:... | (&self) -> ServoBundledURI {
let (ptr, len) = self.as_slice_components();
ServoBundledURI {
mURLString: ptr,
mURLStringLength: len as u32,
mExtraData: self.extra_data.get(),
}
}
}
impl ToCss for SpecifiedUrl {
fn to_css<W>(&self, dest: &mut W) -> fmt:... | for_ffi | identifier_name |
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::CssStringWriter;
use gecko_bindings:... | }
/// Little helper for Gecko's ffi.
pub fn as_slice_components(&self) -> (*const u8, usize) {
(self.serialization.as_str().as_ptr(), self.serialization.as_str().len())
}
/// Create a bundled URI suitable for sending to Gecko
/// to be constructed into a css::URLValue
pub fn for_ff... | pub fn as_str(&self) -> &str {
&*self.serialization | random_line_split |
url.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/. */
//! Common handling for the specified value CSS url() values.
use cssparser::CssStringWriter;
use gecko_bindings:... |
/// Returns true if the URL is definitely invalid. We don't eagerly resolve
/// URLs in gecko, so we just return false here.
/// use its |resolved| status.
pub fn is_invalid(&self) -> bool {
false
}
/// Returns true if this URL looks like a fragment.
/// See https://drafts.csswg.o... | {
Ok(SpecifiedUrl {
serialization: Arc::new(url.into_owned()),
extra_data: context.url_data.clone(),
})
} | identifier_body |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | assert!(non_intersection.is_none());
non_intersecting_ray = Ray::new(Vec3 { x: 0.0, y: 0.0, z: -2.0 }, Vec3 { x: -100.0, y: -100.0, z: 0.1 });
non_intersection = sphere.intersects(&non_intersecting_ray, 0.0, 10.0);
assert!(non_intersection.is_none());
// Ray in opposite direction
non_intersect... | {
let sphere = Sphere {
center: Vec3::zero(),
radius: 1.0,
material: Box::new(FlatMaterial { color: Vec3::one() })
};
// Tests actual intersection
let intersecting_ray = Ray::new(Vec3 { x: 0.0, y: 0.0, z: -2.0 }, Vec3 { x: 0.0, y: 0.0, z: 1.0 });
let intersection = sphere.in... | identifier_body |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | ;
let intersection_point = ray.origin + ray.direction.scale(t);
let n = (intersection_point - self.center).unit();
let u = 0.5 + n.z.atan2(n.x) / (::std::f64::consts::PI * 2.0);
let v = 0.5 - n.y.asin() / ::std::f64::consts::PI;
Some(Inte... | { t2 } | conditional_block |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | })
} else {
None
}
}
}
fn mut_transform(&mut self, transform: &Transform) {
let new_center = Mat4::mult_p(&transform.m, &self.center);
let new_radius = if transform.m.has_scale() {
self.radius * transform.m.scale()
... | u: u,
v: v,
position: intersection_point,
material: &self.material | random_line_split |
sphere.rs | use geometry::bbox::{BBox, PartialBoundingBox};
use geometry::prim::Prim;
use material::Material;
use mat4::{Mat4, Transform};
use raytracer::{Ray, Intersection};
use vec3::Vec3;
#[cfg(test)]
use material::materials::FlatMaterial;
#[allow(dead_code)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
... | (&self) -> Option<BBox> {
Some(BBox {
min: Vec3 {
x: self.center.x - self.radius,
y: self.center.y - self.radius,
z: self.center.z - self.radius
},
max: Vec3 {
x: self.center.x + self.radius,
y: s... | partial_bounding_box | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
mod errors;
use std::collections::HashSet;
use std::fmt;
use abomonation_derive::Abomonation;
use anyhow::Result;
use async_trait::async_... | {
Draft,
Public,
}
impl fmt::Display for Phase {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Phase::Draft => write!(f, "Draft"),
Phase::Public => write!(f, "Public"),
}
}
}
impl From<Phase> for u32 {
fn from(phase: Phase) -> u32 {
... | Phase | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
mod errors;
use std::collections::HashSet;
use std::fmt;
use abomonation_derive::Abomonation;
use anyhow::Result;
use async_trait::async_... | }
/// Phases tracks which commits are public, and which commits are draft.
///
/// A commit ordinarily becomes public when it is reachable from any
/// publishing bookmark. Once public, it never becomes draft again, even
/// if the public bookmark is deleted or moved elsewhere.
#[facet::facet]
#[async_trait]
pub trai... | 1 => Ok(Phase::Draft),
_ => Err(PhasesError::EnumError(phase_as_int)),
}
} | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
mod errors;
use std::collections::HashSet;
use std::fmt;
use abomonation_derive::Abomonation;
use anyhow::Result;
use async_trait::async_... |
}
impl From<Phase> for u32 {
fn from(phase: Phase) -> u32 {
match phase {
Phase::Public => 0,
Phase::Draft => 1,
}
}
}
impl TryFrom<u32> for Phase {
type Error = PhasesError;
fn try_from(phase_as_int: u32) -> Result<Phase, Self::Error> {
match phase_as... | {
match self {
Phase::Draft => write!(f, "Draft"),
Phase::Public => write!(f, "Public"),
}
} | identifier_body |
lib.rs | use std::cmp::PartialEq;
#[derive(Debug, Clone)]
pub struct CustomSet<T> {
elems: Vec<T>,
}
impl<T> PartialEq for CustomSet<T>
where T: PartialEq + Clone + Copy
{
fn eq(&self, other: &CustomSet<T>) -> bool {
self.elems.len() == other.elems.len() &&
self.elems.iter().map(|e| other.contains(... |
pub fn is_disjoint(&self, set: &CustomSet<T>) -> bool {
if self.elems.is_empty() {
true
} else {
self.elems.iter().map(|e|!set.contains(e)).all(|x| x)
}
}
pub fn add(&mut self, elem: T) {
if!self.elems.contains(&elem) {
self.elems.push(e... |
} | random_line_split |
lib.rs |
use std::cmp::PartialEq;
#[derive(Debug, Clone)]
pub struct CustomSet<T> {
elems: Vec<T>,
}
impl<T> PartialEq for CustomSet<T>
where T: PartialEq + Clone + Copy
{
fn eq(&self, other: &CustomSet<T>) -> bool {
self.elems.len() == other.elems.len() &&
self.elems.iter().map(|e| other.contains... |
}
pub fn is_disjoint(&self, set: &CustomSet<T>) -> bool {
if self.elems.is_empty() {
true
} else {
self.elems.iter().map(|e|!set.contains(e)).all(|x| x)
}
}
pub fn add(&mut self, elem: T) {
if!self.elems.contains(&elem) {
self.elem... | {
self.elems.iter().map(|e| set.contains(e)).all(|x| x)
} | conditional_block |
lib.rs |
use std::cmp::PartialEq;
#[derive(Debug, Clone)]
pub struct CustomSet<T> {
elems: Vec<T>,
}
impl<T> PartialEq for CustomSet<T>
where T: PartialEq + Clone + Copy
{
fn eq(&self, other: &CustomSet<T>) -> bool {
self.elems.len() == other.elems.len() &&
self.elems.iter().map(|e| other.contains... | (&self, other: &CustomSet<T>) -> Self {
self.elems.iter().chain(other.elems.iter()).fold(CustomSet::new(vec![]), |mut acc, val| {
acc.add(*val);
acc
})
}
}
| union | identifier_name |
issue-31424.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 ... | () {}
| main | identifier_name |
issue-31424.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 ... | {} | identifier_body | |
issue-31424.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 ... | (&mut self).bar(); //~ ERROR cannot borrow
}
}
fn main () {} | // In this case we could keep the suggestion, but to distinguish the
// two cases is pretty hard. It's an obscure case anyway.
fn bar(self: &mut Self) {
//~^ WARN function cannot return without recursing | random_line_split |
truncate_images.rs | //! Ensure truncated images are read without panics.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
extern crate glob;
extern crate image;
const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
whe... |
#[test]
#[ignore]
fn truncate_jpg() {
truncate_images("jpg")
}
#[test]
#[ignore]
fn truncate_hdr() {
truncate_images("hdr");
}
| {
truncate_images("ico")
} | identifier_body |
truncate_images.rs | //! Ensure truncated images are read without panics.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
extern crate glob;
extern crate image;
const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
whe... | () {
truncate_images("bmp")
}
#[test]
#[ignore]
fn truncate_ico() {
truncate_images("ico")
}
#[test]
#[ignore]
fn truncate_jpg() {
truncate_images("jpg")
}
#[test]
#[ignore]
fn truncate_hdr() {
truncate_images("hdr");
}
| truncate_bmp | identifier_name |
truncate_images.rs | //! Ensure truncated images are read without panics.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
extern crate glob;
extern crate image;
const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";
fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
whe... | None => decoder,
},
);
let pattern = &*format!("{}", path.display());
for path in glob::glob(pattern).unwrap().filter_map(Result::ok) {
func(path)
}
}
}
fn truncate_images(decoder: &str) {
process_images(IMAGE_DIR, Some(decoder), |path| {
... | path.push(
"*.".to_string() + match input_decoder {
Some(val) => val, | random_line_split |
multiple_rules.rs | /*
Copyright ⓒ 2016 Daniel Keep.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distribu... | fn parse(s: &str) -> Result<Parsed, SE> {
scan! { s;
("line:",..v) => Parsed::Line(v),
("word:", let v: Word) => Parsed::Word(v),
("i32:", let v) => Parsed::I32(v),
}
} | }
| random_line_split |
multiple_rules.rs | /*
Copyright ⓒ 2016 Daniel Keep.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distribu... | : &str) -> Result<Parsed, SE> {
scan! { s;
("line:",..v) => Parsed::Line(v),
("word:", let v: Word) => Parsed::Word(v),
("i32:", let v) => Parsed::I32(v),
}
}
| rse(s | identifier_name |
multiple_rules.rs | /*
Copyright ⓒ 2016 Daniel Keep.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distribu... | scan! { s;
("line:", ..v) => Parsed::Line(v),
("word:", let v: Word) => Parsed::Word(v),
("i32:", let v) => Parsed::I32(v),
}
}
| identifier_body | |
extern-call-scrub.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 ... | (n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
println!(... | count | identifier_name |
extern-call-scrub.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn count(n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
... | {
count(data - 1) + count(data - 1)
} | conditional_block |
extern-call-scrub.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 ... | {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
println!("result = {}", result);
assert_eq!(result, 2048);
});
} | identifier_body | |
extern-call-scrub.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 ... | println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
task::spawn(proc() {
let result = count(12);
println!("result = {}", result);
assert_eq!(result, 2048... | unsafe { | random_line_split |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... | () {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let filename = args.arg_input;
let source = read_file(&filename).unwrap();
let ctxt = Context::new(filename, source);
let mut compiler = Compiler::new(&ctxt);
compiler.define_entrypoint("main", make_fn_ty!(&ctxt, fn(time... | main | identifier_name |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... | {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let filename = args.arg_input;
let source = read_file(&filename).unwrap();
let ctxt = Context::new(filename, source);
let mut compiler = Compiler::new(&ctxt);
compiler.define_entrypoint("main", make_fn_ty!(&ctxt, fn(time: N... | identifier_body | |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... | else if args.cmd_stream {
play_stream(&compiler);
}
},
Err(issues) => println!("Compile Error!\n{}", issues),
}
}
| {
write_wav(&compiler, args.arg_output, args.flag_length);
} | conditional_block |
main.rs | #![feature(plugin, optin_builtin_traits)]
#![plugin(regex_macros, docopt_macros)]
extern crate docopt;
extern crate rustc_serialize;
extern crate vec_map;
#[macro_use]
extern crate interpreter;
docopt!(Args, "
Usage:
synthizer stream <input>
synthizer write <input> <output> [--length=<sec>]
synthizer --help
Op... |
#[allow(dead_code)]
fn main() {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
let filename = args.arg_input;
let source = read_file(&filename).unwrap();
let ctxt = Context::new(filename, source);
let mut compiler = Compiler::new(&ctxt);
compiler.define_entrypoint("main"... | use interpreter::common::{Context, read_file};
use interpreter::compiler::Compiler;
use interpreter::audio::{write_wav, play_stream}; | random_line_split |
mem.rs | memory reporters.
//
// This serializes the report-gathering. It might be worth creating a new scoped thread for
// each reporter once we have enough of them.
//
// If anything goes wrong with a reporter, we just skip it.
//
// We also track the total memory repo... |
// We record each segment's resident size.
let mut seg_map: HashMap<String, usize> = HashMap::new();
| random_line_split | |
mem.rs | (ProfilerMsg::RegisterReporter(
"system".to_owned(),
Reporter(system_reporter_sender),
));
mem_profiler_chan
}
pub fn new(port: IpcReceiver<ProfilerMsg>) -> Profiler {
Profiler {
port: port,
reporters: HashMap::new(),
created:... | (&self) {
let elapsed = self.created.elapsed();
println!("Begin memory reports {}", elapsed.as_secs());
println!("|");
// Collect reports from memory reporters.
//
// This serializes the report-gathering. It might be worth creating a new scoped thread for
// each... | handle_print_msg | identifier_name |
mem.rs | (ProfilerMsg::RegisterReporter(
"system".to_owned(),
Reporter(system_reporter_sender),
));
mem_profiler_chan
}
pub fn new(port: IpcReceiver<ProfilerMsg>) -> Profiler {
Profiler {
port: port,
reporters: HashMap::new(),
created:... | self.path_seg,
count_str
);
for child in &self.children {
child.print(depth + 1);
}
}
}
/// A collection of ReportsTrees. It represents the data from multiple memory reports in a form
/// that's good to print.
struct ReportsForest {
trees: HashMap<S... | {
if !self.children.is_empty() {
assert_eq!(self.count, 0);
}
let mut indent_str = String::new();
for _ in 0..depth {
indent_str.push_str(" ");
}
let mebi = 1024f64 * 1024f64;
let count_str = if self.count > 1 {
format!(" [{... | identifier_body |
stdbuf.rs | #![crate_name = "uu_stdbuf"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Dorota Kapturkiewicz <dokaptur@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uuco... |
fn print_usage(opts: &Options) {
let brief =
"Run COMMAND, with modified buffering operations for its standard streams\n \
Mandatory arguments to long options are mandatory for short options too.";
let explanation =
"If MODE is 'L' the corresponding stream will be line buffered.\n \
... | {
println!("{} {}", NAME, VERSION);
} | identifier_body |
stdbuf.rs | #![crate_name = "uu_stdbuf"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Dorota Kapturkiewicz <dokaptur@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uuco... | () -> (&'static str, &'static str) {
("DYLD_LIBRARY_PATH", ".dylib")
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn preload_strings() -> (&'static str, &'static str) {
crash!(1, "Command not supported for this operating system!")
}
fn print_version() {
println!("{} {}", NAME, VERSION);
... | preload_strings | identifier_name |
stdbuf.rs | #![crate_name = "uu_stdbuf"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Dorota Kapturkiewicz <dokaptur@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
#[macro_use]
extern crate uuco... | None => absolute_path.clone()
})
}
fn get_preload_env() -> (String, String) {
let (preload, extension) = preload_strings();
let mut libstdbuf = LIBSTDBUF.to_owned();
libstdbuf.push_str(extension);
// First search for library in directory of executable.
let mut path = exe_path().unwrap_o... | let exe_path = try!(std::env::current_exe());
let absolute_path = try!(canonicalize(exe_path, CanonicalizeMode::Normal));
Ok(match absolute_path.parent() {
Some(p) => p.to_path_buf(), | random_line_split |
lib.rs | //! Immutable binary search tree.
//!
//! This crate provides functional programming style binary search trees which returns modified
//! copy of original map or set with the new data, and preserves the original. Many features and
//! algorithms are borrowed from `Data.Map` of Haskell's standard library.
//!
//! See ht... | pub use map::TreeMap;
/// An endpoint of a range of keys.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Bound<T> {
/// An infinite endpoint. Indicates that there is no bound in this direction.
Unbounded,
/// An inclusive bound.
Included(T),
/// An exclusive bound.
Excluded(T)
}
#... | random_line_split | |
lib.rs | //! Immutable binary search tree.
//!
//! This crate provides functional programming style binary search trees which returns modified
//! copy of original map or set with the new data, and preserves the original. Many features and
//! algorithms are borrowed from `Data.Map` of Haskell's standard library.
//!
//! See ht... | <T> {
/// An infinite endpoint. Indicates that there is no bound in this direction.
Unbounded,
/// An inclusive bound.
Included(T),
/// An exclusive bound.
Excluded(T)
}
#[cfg(test)]
impl<T: Arbitrary> Arbitrary for Bound<T> {
fn arbitrary<G: Gen>(g: &mut G) -> Bound<T> {
match g.si... | Bound | identifier_name |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | () {
let args = ::std::env::args().collect::<Vec<_>>();
if args.len()!= 2 {
println!("Usage: {} <device>-<speed>-<package>", args[0]);
::std::process::exit(1);
}
let device_combination = &args[1];
let XC2DeviceSpeedPackage {
dev: device, spd: _, pkg: _
} = XC2DeviceSpee... | main | identifier_name |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | dev: device, spd: _, pkg: _
} = XC2DeviceSpeedPackage::from_str(device_combination).expect("invalid device name");
let node_vec = RefCell::new(Vec::new());
let wire_vec = RefCell::new(Vec::new());
get_device_structure(device,
|node_name: &str, node_type: &str, fb: u32, idx: u32| {
... | let XC2DeviceSpeedPackage { | random_line_split |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... | println!("Node: {} {} {} {}", node_name, node_type, fb, idx);
let i = node_vec.len();
node_vec.push((node_name.to_owned(), node_type.to_owned(), fb, idx));
i
},
|wire_name: &str| {
let mut wire_vec = wire_vec.borrow_mut();
println!... | {
let args = ::std::env::args().collect::<Vec<_>>();
if args.len() != 2 {
println!("Usage: {} <device>-<speed>-<package>", args[0]);
::std::process::exit(1);
}
let device_combination = &args[1];
let XC2DeviceSpeedPackage {
dev: device, spd: _, pkg: _
} = XC2DeviceSpeedP... | identifier_body |
xc2structuretest.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... |
let wire_ref = wire_ref - 1000000;
let node_vec = node_vec.borrow();
let wire_vec = wire_vec.borrow();
println!("Node connection: {} {} {} {} {} {} {} {} {}",
node_vec[node_ref].0, node_vec[node_ref].1, node_vec[node_ref].2, node_vec[node_ref].3,
... | {
panic!("node instead of wire");
} | conditional_block |
inverse.rs | use num::{Zero, One, Signed};
use bigint::{BigUint, BigInt, Sign};
pub trait Inverse {
type Output;
fn inverse(self, modulo: Self) -> Option<Self::Output>;
}
impl<'a> Inverse for &'a BigUint {
type Output = BigUint;
fn inverse(self, modulo: Self) -> Option<Self::Output> {
BigInt::from_biguin... | (self, modulo: Self) -> Option<Self::Output> {
let (mut t, mut new_t): (BigInt, BigInt) = (Zero::zero(), One::one());
let (mut r, mut new_r): (BigInt, BigInt) = (modulo.clone(), self.clone());
while!new_r.is_zero() {
let quo = &r / &new_r;
let tmp = &r - &quo * &new_r;
... | inverse | identifier_name |
inverse.rs | use num::{Zero, One, Signed};
use bigint::{BigUint, BigInt, Sign};
pub trait Inverse {
type Output;
fn inverse(self, modulo: Self) -> Option<Self::Output>;
}
impl<'a> Inverse for &'a BigUint {
type Output = BigUint;
fn inverse(self, modulo: Self) -> Option<Self::Output> {
BigInt::from_biguin... | impl<'a> Inverse for &'a BigInt {
type Output = BigInt;
fn inverse(self, modulo: Self) -> Option<Self::Output> {
let (mut t, mut new_t): (BigInt, BigInt) = (Zero::zero(), One::one());
let (mut r, mut new_r): (BigInt, BigInt) = (modulo.clone(), self.clone());
while!new_r.is_zero() {
... | }
| random_line_split |
inverse.rs | use num::{Zero, One, Signed};
use bigint::{BigUint, BigInt, Sign};
pub trait Inverse {
type Output;
fn inverse(self, modulo: Self) -> Option<Self::Output>;
}
impl<'a> Inverse for &'a BigUint {
type Output = BigUint;
fn inverse(self, modulo: Self) -> Option<Self::Output> {
BigInt::from_biguin... |
}
}
| {
Some(t)
} | conditional_block |
inverse.rs | use num::{Zero, One, Signed};
use bigint::{BigUint, BigInt, Sign};
pub trait Inverse {
type Output;
fn inverse(self, modulo: Self) -> Option<Self::Output>;
}
impl<'a> Inverse for &'a BigUint {
type Output = BigUint;
fn inverse(self, modulo: Self) -> Option<Self::Output> {
BigInt::from_biguin... | Some(t)
}
}
}
| {
let (mut t, mut new_t): (BigInt, BigInt) = (Zero::zero(), One::one());
let (mut r, mut new_r): (BigInt, BigInt) = (modulo.clone(), self.clone());
while !new_r.is_zero() {
let quo = &r / &new_r;
let tmp = &r - &quo * &new_r;
r = new_r;
new_r = tm... | identifier_body |
i686_unknown_linux_gnu.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 mut base = super::linux_base::opts();
base.pre_link_args.push("-m32".to_string());
Target {
data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(),
llvm_target: "i686-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
target_word_... | identifier_body | |
i686_unknown_linux_gnu.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 ... | () -> Target {
let mut base = super::linux_base::opts();
base.pre_link_args.push("-m32".to_string());
Target {
data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(),
llvm_target: "i686-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
... | target | identifier_name |
i686_unknown_linux_gnu.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target;... | random_line_split | |
from_list.rs | use crate::*;
// List used for calling from_list tests.
fn get_list<'a>() -> &'a [(i16, i16); 8] {
&[
(0, 0), // Default test,
(100, 100), // Two positive values test,
(50, -50), // One positive one negative test.
(-9999, 9999), // Larger values test.
(0, 1... |
#[test]
fn node() {
let result = Node::from_list(get_list());
assert_eq!(result.len(), 8);
}
#[test]
fn group() {
let result = Group::from_list(get_list());
assert_eq!(result.len(), 8);
}
| {
let result = Coordinate::from_list(get_list());
assert_eq!(result.len(), 8);
} | identifier_body |
from_list.rs | use crate::*;
// List used for calling from_list tests.
fn get_list<'a>() -> &'a [(i16, i16); 8] {
&[
(0, 0), // Default test,
(100, 100), // Two positive values test,
(50, -50), // One positive one negative test.
(-9999, 9999), // Larger values test.
(0, 1... | () {
let result = Group::from_list(get_list());
assert_eq!(result.len(), 8);
}
| group | identifier_name |
from_list.rs | use crate::*;
// List used for calling from_list tests.
fn get_list<'a>() -> &'a [(i16, i16); 8] {
&[
(0, 0), // Default test,
(100, 100), // Two positive values test,
(50, -50), // One positive one negative test.
(-9999, 9999), // Larger values test.
(0, 1... |
#[test]
fn group() {
let result = Group::from_list(get_list());
assert_eq!(result.len(), 8);
} | #[test]
fn node() {
let result = Node::from_list(get_list());
assert_eq!(result.len(), 8);
} | random_line_split |
mod.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | let vec0 = unwrap!(generate_random_vector::<u8>(SIZE));
let vec1 = unwrap!(generate_random_vector::<u8>(SIZE));
let vec2 = unwrap!(generate_random_vector::<u8>(SIZE));
assert_ne!(vec0, vec1);
assert_ne!(vec0, vec2);
assert_ne!(vec1, vec2);
assert_eq!(vec0.len(),... |
// Test `generate_random_vector` and that the results are not repeated.
#[test]
fn random_vector() { | random_line_split |
mod.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (length: usize) -> Result<String, CoreError> {
let mut os_rng = OsRng::new().map_err(|error| {
error!("{:?}", error);
CoreError::RandomDataGenerationFailure
})?;
Ok(generate_readable_string_rng(&mut os_rng, length))
}
/// Generates a readable `String` using provided `length` and `rng.
pub ... | generate_readable_string | identifier_name |
mod.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
/// Generate a random vector of given length.
pub fn generate_random_vector<T>(length: usize) -> Result<Vec<T>, CoreError>
where
Standard: Distribution<T>,
{
let mut os_rng = OsRng::new().map_err(|error| {
error!("{:?}", error);
CoreError::RandomDataGenerationFailure
})?;
Ok(generate_... | {
::std::iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(length)
.collect()
} | identifier_body |
pointer_constants.rs | // Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// ... | else { "" };
Ok(Branch(vec![
Line(format!("{}static {}: [capnp::Word; {}] = [", vis, name, words.len() / 8)),
Indent(Box::new(Branch(words_lines))),
Line("];".to_string())
]))
}
pub fn generate_pointer_constant(
gen: &GeneratorContext,
styled_name: &str,
typ: type_::Reader,... | { "pub " } | conditional_block |
pointer_constants.rs | // Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy | // furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO TH... | // of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is | random_line_split |
pointer_constants.rs | // Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// ... | {
pub public: bool,
pub omit_first_word: bool,
}
pub fn word_array_declaration(name: &str,
value: any_pointer::Reader,
options: WordArrayDeclarationOptions) -> ::capnp::Result<FormattedText> {
let allocator = message::HeapAllocator::new()
... | WordArrayDeclarationOptions | identifier_name |
pointer_constants.rs | // Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// ... | {
Ok(Branch(vec![
Line(format!("pub static {}: ::capnp::constant::Reader<{}> = {{",
styled_name, typ.type_string(gen, Leaf::Owned)?)),
Indent(Box::new(Branch(vec![
word_array_declaration("WORDS", value, WordArrayDeclarationOptions { public: false, omit_first_word: fa... | identifier_body | |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
use sdl2::rect::Point;
use std::time::Duration;
fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("... | renderer.set_draw_color(sdl2::pixels::Color::RGBA(0,0,0,255));
let mut timer = sdl_context.timer().unwrap();
let mut event_pump = sdl_context.event_pump().unwrap();
let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/animate.bmp")).unwrap();
let texture = renderer.create_texture... | let mut renderer = window.renderer()
.accelerated().build().unwrap();
| random_line_split |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
use sdl2::rect::Point;
use std::time::Duration;
fn main() | let mut source_rect = Rect::new(0, 0, 128, 82);
let mut dest_rect = Rect::new(0,0, 128, 82);
dest_rect.center_on(center);
let mut running = true;
while running {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: Some(... | {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("SDL2", 640, 480)
.position_centered().build().unwrap();
let mut renderer = window.renderer()
.accelerated().build().unwrap();
renderer.set_draw_color... | identifier_body |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
use sdl2::rect::Point;
use std::time::Duration;
fn | () {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("SDL2", 640, 480)
.position_centered().build().unwrap();
let mut renderer = window.renderer()
.accelerated().build().unwrap();
renderer.set_draw_colo... | main | identifier_name |
animation.rs | extern crate sdl2;
use std::path::Path;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
use sdl2::rect::Point;
use std::time::Duration;
fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("... |
}
}
let ticks = timer.ticks();
source_rect.set_x((128 * ((ticks / 100) % 6) ) as i32);
renderer.clear();
renderer.copy_ex(&texture, Some(source_rect), Some(dest_rect), 10.0, None, true, false).unwrap();
renderer.present();
std::thread::sleep(Durati... | {} | conditional_block |
pair_slices.rs | use core::cmp::{self};
use core::mem::replace;
use crate::alloc::Allocator;
use super::VecDeque;
/// PairSlices pairs up equal length slice parts of two deques
///
/// For example, given deques "A" and "B" with the following division into slices:
///
/// A: [0 1 2] [3 4 5]
/// B: [a b] [c d e]
///
/// It produces th... | (&mut self) -> Option<Self::Item> {
// Get next part length
let part = cmp::min(self.a0.len(), self.b0.len());
if part == 0 {
return None;
}
let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part);
let (q0, q1) = self.b0.split_at(part);
// Mo... | next | identifier_name |
pair_slices.rs | use core::cmp::{self};
use core::mem::replace;
use crate::alloc::Allocator;
use super::VecDeque;
/// PairSlices pairs up equal length slice parts of two deques
///
/// For example, given deques "A" and "B" with the following division into slices:
///
/// A: [0 1 2] [3 4 5]
/// B: [a b] [c d e]
///
/// It produces th... |
pub fn has_remainder(&self) -> bool {
!self.b0.is_empty()
}
pub fn remainder(self) -> impl Iterator<Item = &'b [T]> {
IntoIterator::into_iter([self.b0, self.b1])
}
}
impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> {
type Item = (&'a mut [T], &'b [T]);
fn next(&mut self) -> ... | {
let (a0, a1) = to.as_mut_slices();
let (b0, b1) = from.as_slices();
PairSlices { a0, a1, b0, b1 }
} | identifier_body |
pair_slices.rs | use core::cmp::{self};
use core::mem::replace;
use crate::alloc::Allocator;
use super::VecDeque;
/// PairSlices pairs up equal length slice parts of two deques
///
/// For example, given deques "A" and "B" with the following division into slices:
///
/// A: [0 1 2] [3 4 5]
/// B: [a b] [c d e]
///
/// It produces th... | }
pub fn remainder(self) -> impl Iterator<Item = &'b [T]> {
IntoIterator::into_iter([self.b0, self.b1])
}
}
impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> {
type Item = (&'a mut [T], &'b [T]);
fn next(&mut self) -> Option<Self::Item> {
// Get next part length
let part =... | random_line_split | |
pair_slices.rs | use core::cmp::{self};
use core::mem::replace;
use crate::alloc::Allocator;
use super::VecDeque;
/// PairSlices pairs up equal length slice parts of two deques
///
/// For example, given deques "A" and "B" with the following division into slices:
///
/// A: [0 1 2] [3 4 5]
/// B: [a b] [c d e]
///
/// It produces th... |
let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part);
let (q0, q1) = self.b0.split_at(part);
// Move a1 into a0, if it's empty (and b1, b0 the same way).
self.a0 = p1;
self.b0 = q1;
if self.a0.is_empty() {
self.a0 = replace(&mut self.a1, &mut [])... | {
return None;
} | conditional_block |
uuids.rs | extern crate cassandra;
use cassandra::CassSession;
use cassandra::CassUuid;
use cassandra::CassStatement;
use cassandra::CassResult;
use cassandra::CassError;
use cassandra::CassUuidGen;
use cassandra::CassCluster;
static INSERT_QUERY:&'static str = "INSERT INTO examples.log (key, time, entry) VALUES (?,?,?);";
stat... | (session: &mut CassSession, key: &str) -> Result<CassResult, CassError> {
let mut statement = CassStatement::new(SELECT_QUERY, 1);
statement.bind_string(0, &key).unwrap();
let mut future = session.execute_statement(&statement);
let results = try!(future.wait());
Ok(results)
}
fn main() {
let uu... | select_from_log | identifier_name |
uuids.rs | extern crate cassandra;
use cassandra::CassSession;
use cassandra::CassUuid;
use cassandra::CassStatement;
use cassandra::CassResult;
use cassandra::CassError;
use cassandra::CassUuidGen;
use cassandra::CassCluster;
static INSERT_QUERY:&'static str = "INSERT INTO examples.log (key, time, entry) VALUES (?,?,?);";
stat... |
fn select_from_log(session: &mut CassSession, key: &str) -> Result<CassResult, CassError> {
let mut statement = CassStatement::new(SELECT_QUERY, 1);
statement.bind_string(0, &key).unwrap();
let mut future = session.execute_statement(&statement);
let results = try!(future.wait());
Ok(results)
}
fn... | {
let mut statement = CassStatement::new(INSERT_QUERY, 3);
statement.bind_string(0, key).unwrap();
statement.bind_uuid(1, time).unwrap();
statement.bind_string(2, &entry).unwrap();
let mut future = session.execute_statement(&statement);
future.wait()
} | identifier_body |
uuids.rs | extern crate cassandra;
use cassandra::CassSession;
use cassandra::CassUuid;
use cassandra::CassStatement;
use cassandra::CassResult;
use cassandra::CassError;
use cassandra::CassUuidGen;
use cassandra::CassCluster;
static INSERT_QUERY:&'static str = "INSERT INTO examples.log (key, time, entry) VALUES (?,?,?);";
stat... | insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #3").unwrap();
insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #4").unwrap();
let results = select_from_log(session, "test").unwrap();
// for row in results.iter() {
// let time = row.get_column(1).unwrap();
// let entry = ... | insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #1").unwrap();
insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #2").unwrap(); | random_line_split |
mod.rs | use primal_estimate;
use primal_bit::{BitVec};
use std::{cmp};
use hamming;
use wheel;
pub mod primes; | /// This is a streaming segmented sieve, meaning it sieves numbers in
/// intervals, extracting whatever it needs and discarding it. See
/// `Sieve` for a wrapper that caches the information to allow for
/// repeated queries, at the cost of *O(limit)* memory use.
///
/// This uses *O(sqrt(limit))* memory, and is design... | mod presieve;
/// A heavily optimised prime sieve.
/// | random_line_split |
mod.rs | use primal_estimate;
use primal_bit::{BitVec};
use std::{cmp};
use hamming;
use wheel;
pub mod primes;
mod presieve;
/// A heavily optimised prime sieve.
///
/// This is a streaming segmented sieve, meaning it sieves numbers in
/// intervals, extracting whatever it needs and discarding it. See
/// `Sieve` for a wrap... | ut Bencher, n: usize) {
b.iter(|| {
let mut sieve = StreamingSieve::new(n);
while sieve.next().is_some() {}
})
}
#[bench]
fn sieve_small(b: &mut Bencher) {
run(b, 100)
}
#[bench]
fn sieve_medium(b: &mut Bencher) {
run(b, 10_000)
}
... | &m | identifier_name |
mod.rs | use primal_estimate;
use primal_bit::{BitVec};
use std::{cmp};
use hamming;
use wheel;
pub mod primes;
mod presieve;
/// A heavily optimised prime sieve.
///
/// This is a streaming segmented sieve, meaning it sieves numbers in
/// intervals, extracting whatever it needs and discarding it. See
/// `Sieve` for a wrap... | run(b, 10_000_000)
}
}
| identifier_body | |
socket.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi;
use glib::object::Downcast;
use Widget;
glib_wrapper! {
... |
/*pub fn add_id(&self, window: Window) {
unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) };
}
pub fn get_id(&self) -> Window {
unsafe { ffi::gtk_socket_get_id(self.to_glib_none().0) };
}
pub fn get_plug_window(&self) -> GdkWindow {
let tmp_pointer = unsafe ... | {
assert_initialized_main_thread!();
unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() }
} | identifier_body |
socket.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi;
use glib::object::Downcast;
use Widget;
glib_wrapper! {
... | pub fn new() -> Socket {
assert_initialized_main_thread!();
unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() }
}
/*pub fn add_id(&self, window: Window) {
unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) };
}
pub fn get_id(&self) -> W... |
impl Socket { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.