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
exp2f64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::exp2f64;
// pub fn exp2f64(x: f64) -> f64; #[test] fn expf64_test1() { let x: f64 = f64::nan(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result.is_nan(), true); } #[test] fn expf64_test2() { let x: f64 = f64::infinity(); let result: f64 = unsafe { exp2f64(x) }; assert_eq!(result, f64...
use core::num::Float; use core::f64;
random_line_split
lib.rs
#![deny(unsafe_code)] extern crate app_units; extern crate atomic_refcell; #[macro_use] extern crate bitflags; extern crate canvas_traits; extern crate euclid; extern crate fnv; extern crate fxhash; extern crate gfx; extern crate gfx_traits; #[macro_use] extern crate html5ever; extern crate ipc_channel; extern crate ...
/* 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/. */
random_line_split
mma8652fc.rs
use blue_pill::stm32f103xx::I2C1; use cast::u16; use cortex_m; use i2c; const I2C_ADDRESS: u8 = 0x1D; /// MMA8652FC Register Addresses #[allow(dead_code)] #[allow(non_camel_case_types)] #[derive(Clone, Copy)] pub enum Register { /// Status Register (R) STATUS = 0x00, /// [7:0] are 8 MSBs of the 14-bit X-...
(&self, threshold: u8, filter_time: u8) -> &Self { let sens = 9 * 2 + 17 - 2 * threshold; self // sleep mode .set_register(Register::CTRL_REG1, 0); // set accumulation threshold self.set_register(Register::FF_MT_THS, (sens & 0x7F)); // set debounce threshold ...
set_sensitivity
identifier_name
mma8652fc.rs
use blue_pill::stm32f103xx::I2C1; use cast::u16; use cortex_m; use i2c; const I2C_ADDRESS: u8 = 0x1D; /// MMA8652FC Register Addresses #[allow(dead_code)] #[allow(non_camel_case_types)] #[derive(Clone, Copy)] pub enum Register { /// Status Register (R) STATUS = 0x00, /// [7:0] are 8 MSBs of the 14-bit X-...
} #[derive(Clone, Copy)] pub struct Accel { /// X component pub x: i16, /// Y component pub y: i16, /// Z component pub z: i16, } pub struct MMA8652FC<'a>(pub &'a I2C1); impl<'a> MMA8652FC<'a> { pub fn init(&self) { self // Normal Mode .set_register(Register::C...
{ *self as u8 }
identifier_body
mma8652fc.rs
use blue_pill::stm32f103xx::I2C1; use cast::u16; use cortex_m; use i2c;
#[derive(Clone, Copy)] pub enum Register { /// Status Register (R) STATUS = 0x00, /// [7:0] are 8 MSBs of the 14-bit X-axis sample (R) OUT_X_MSB = 0x01, /// [7:2] are 6 LSBs of the 14-bit X-axis sample (R) OUT_X_LSB = 0x02, /// [7:0] are 8 MSBs of the 14-bit Y-axis sample (R) OUT_Y_MSB ...
const I2C_ADDRESS: u8 = 0x1D; /// MMA8652FC Register Addresses #[allow(dead_code)] #[allow(non_camel_case_types)]
random_line_split
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that ...
fn default() -> Self { FillRule::NonZero } }
#[inline]
random_line_split
basic_shape.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/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that ...
() -> Self { ShapeRadius::ClosestSide } } impl<L: ToCss> ToCss for ShapeRadius<L> { #[inline] fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { ShapeRadius::Length(ref lop) => lop.to_css(dest), ShapeRadius::ClosestSide => dest.write_str("closes...
default
identifier_name
access.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 ...
<'a>(&'a mut self, _missile: &HomingMissile) -> &'a mut T { unsafe { &mut *self.unsafe_get() } } pub fn close(&self, _missile: &HomingMissile) { // This unsafety is OK because with a homing missile we're guaranteed to // be the only task looking at the `closed` flag (and are therefore ...
get_mut
identifier_name
access.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 ...
} } pub fn grant<'a>(&'a mut self, token: uint, missile: HomingMissile) -> Guard<'a, T> { // This unsafety is actually OK because the homing missile argument // guarantees that we're on the same event loop as all the other objects // attempting to get access...
queue: vec![], held: false, closed: false, data: data, }))
random_line_split
access.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 ...
} #[unsafe_destructor] impl<'a, T> Drop for Guard<'a, T> { fn drop(&mut self) { // This guard's homing missile is still armed, so we're guaranteed to be // on the same I/O event loop, so this unsafety should be ok. assert!(self.missile.is_some()); let inner: &mut Inner<T> = unsafe ...
{ unsafe { &mut (*self.access.inner.get()).data } }
identifier_body
path_utils.rs
use crate::borrow_check::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; use crate::borrow_check::places_conflict; use crate::borrow_check::AccessDepth; use crate::borrow_check::Upvar; use crate::dataflow::indexes::BorrowIndex; use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::Bo...
(place: Place<'_>) -> bool { // Reborrow of already borrowed data is ignored // Any errors will be caught on the initial borrow !place.is_indirect() } /// If `place` is a field projection, and the field is being projected from a closure type, /// then returns the index of the field being projected. Note tha...
borrow_of_local_data
identifier_name
path_utils.rs
use crate::borrow_check::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; use crate::borrow_check::places_conflict; use crate::borrow_check::AccessDepth; use crate::borrow_check::Upvar; use crate::dataflow::indexes::BorrowIndex; use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::Bo...
// // X // / // R <--+ Except for this // / \ | diamond // \ / | // A <------+ // | // Z // // Note that we assume that: // - the reservation R dominates the activation A // - the activation A post-dominates the res...
// Otherwise, it is active for every location *except* in between // the reservation and the activation:
random_line_split
path_utils.rs
use crate::borrow_check::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; use crate::borrow_check::places_conflict; use crate::borrow_check::AccessDepth; use crate::borrow_check::Upvar; use crate::dataflow::indexes::BorrowIndex; use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::Bo...
else { // Otherwise, this point is outside the diamond, so // consider the borrow active. This could happen for // example if the borrow remains active around a loop (in // which case it would be active also for the point R, // which would generate an error). true } ...
{ false }
conditional_block
cfg-macros-notfoo.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { assert!(!bar!()) }
main
identifier_name
cfg-macros-notfoo.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}
} } pub fn main() { assert!(!bar!())
random_line_split
cfg-macros-notfoo.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ assert!(!bar!()) }
identifier_body
domrectlist.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::DOMRectListBinding; use dom::bindings::codegen::Bindings::DOMRectListBinding...
} impl Reflectable for DOMRectList { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<DOMRect>> { *found = index < self.rects.len() as u32; self.Item(index) }
random_line_split
domrectlist.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::DOMRectListBinding; use dom::bindings::codegen::Bindings::DOMRectListBinding...
} impl Reflectable for DOMRectList { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
{ *found = index < self.rects.len() as u32; self.Item(index) }
identifier_body
domrectlist.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::DOMRectListBinding; use dom::bindings::codegen::Bindings::DOMRectListBinding...
(window: JSRef<Window>, rects: Vec<JSRef<DOMRect>>) -> DOMRectList { let rects = rects.iter().map(|rect| JS::from_rooted(*rect)).collect(); DOMRectList { reflector_: Reflector::new(), rects: rects, window: JS::from_rooted(window), } ...
new_inherited
identifier_name
domrectlist.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::DOMRectListBinding; use dom::bindings::codegen::Bindings::DOMRectListBinding...
else { None } } fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<DOMRect>> { *found = index < self.rects.len() as u32; self.Item(index) } } impl Reflectable for DOMRectList { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflec...
{ Some(Temporary::new(rects[index as uint].clone())) }
conditional_block
normalized.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ access::ModuleAccess, file_format::{ AbilitySet, CompiledModule, FieldDefinition, FunctionHandle, SignatureToken, StructDefinition, StructFieldInformation, TypeParameterIndex, Visibility, }, }; u...
use Type::*; match self { TypeParameter(_) => false, Bool => true, U8 => true, U64 => true, U128 => true, Address => true, Signer => true, Struct { type_arguments,.. } => type_arguments.iter().all(|t| t.is_cl...
} /// Return true if `self` is a closed type with no free type variables pub fn is_closed(&self) -> bool {
random_line_split
normalized.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ access::ModuleAccess, file_format::{ AbilitySet, CompiledModule, FieldDefinition, FunctionHandle, SignatureToken, StructDefinition, StructFieldInformation, TypeParameterIndex, Visibility, }, }; u...
{ pub address: AccountAddress, pub name: Identifier, pub friends: Vec<ModuleId>, pub structs: Vec<Struct>, pub exposed_functions: BTreeMap<FunctionSignature, Visibility>, } impl Module { /// Extract a normalized module from a `CompiledModule`. The module `m` should be verified. /// Nothing...
Module
identifier_name
normalized.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ access::ModuleAccess, file_format::{ AbilitySet, CompiledModule, FieldDefinition, FunctionHandle, SignatureToken, StructDefinition, StructFieldInformation, TypeParameterIndex, Visibility, }, }; u...
} impl Type { /// Create a normalized `Type` for `SignatureToken` `s` in module `m`. pub fn new(m: &CompiledModule, s: &SignatureToken) -> Self { use SignatureToken::*; match s { Struct(shi) => { let s_handle = m.struct_handle_at(*shi); assert!(s_han...
{ ModuleId::new(self.address, self.name.clone()) }
identifier_body
shared_lock.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/. */ //! Different objects protected by the same lock #[cfg(feature = "gecko")] use atomic_refcell::{AtomicRefCell, At...
(&self) -> SharedRwLockWriteGuard { SharedRwLockWriteGuard(self.cell.borrow_mut()) } } /// Proof that a shared lock was obtained for reading (servo). #[cfg(feature = "servo")] pub struct SharedRwLockReadGuard<'a>(&'a SharedRwLock); /// Proof that a shared lock was obtained for writing (gecko). #[cfg(featur...
write
identifier_name
shared_lock.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/. */ //! Different objects protected by the same lock #[cfg(feature = "gecko")] use atomic_refcell::{AtomicRefCell, At...
unsafe impl<T: Send + Sync> Sync for Locked<T> {} impl<T: fmt::Debug> fmt::Debug for Locked<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let guard = self.shared_lock.read(); self.read_with(&guard).fmt(f) } } impl<T> Locked<T> { #[cfg(feature = "servo")] fn same_lock_as(&...
unsafe impl<T: Send> Send for Locked<T> {}
random_line_split
commands.rs
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
#[completion(hidden)] UrlIncrement, #[completion(hidden)] UrlDecrement, #[completion(hidden)] WinFollow, #[help(text="Open an URL in a new window")] WinOpen(String), #[completion(hidden)] WinPasteUrl, #[help(text="Zoom the current page in")] ZoomIn, #[help(text="Zoom ...
#[help(text="Stop loading the current page")] Stop,
random_line_split
commands.rs
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
{ #[completion(hidden)] ActivateSelection, #[help(text="Update the host file used by the adblocker")] AdblockUpdate, #[help(text="Add a new user agent")] AddUserAgent(String), #[help(text="Go back in the history")] Back, #[special_command(incremental, identifier="?")] BackwardSe...
AppCommand
identifier_name
incremental_get.rs
use test::{black_box, Bencher}; use engine_rocks::RocksSnapshot; use kvproto::kvrpcpb::{Context, IsolationLevel}; use std::sync::Arc; use test_storage::SyncTestStorageBuilder; use tidb_query_datatype::codec::table; use tikv::storage::{Engine, SnapshotStore, Statistics, Store}; use txn_types::{Key, Mutation}; fn table...
let mutation = Mutation::Put((key.clone(), user_value)); mutations.push(mutation); keys.push(key); } let pk = table::encode_row_key(5, 0); store .prewrite(Context::default(), mutations, pk, 1) .unwrap(); store.commit(Context::default(), keys, 1, 2).unwrap(); ...
let user_value = vec![b'x'; 60]; let key = Key::from_raw(&user_key);
random_line_split
incremental_get.rs
use test::{black_box, Bencher}; use engine_rocks::RocksSnapshot; use kvproto::kvrpcpb::{Context, IsolationLevel}; use std::sync::Arc; use test_storage::SyncTestStorageBuilder; use tidb_query_datatype::codec::table; use tikv::storage::{Engine, SnapshotStore, Statistics, Store}; use txn_types::{Key, Mutation}; fn table...
#[bench] fn bench_table_lookup_mvcc_incremental_get(b: &mut Bencher) { let (mut store, keys) = table_lookup_gen_data(); b.iter(|| { for key in &keys { black_box(store.incremental_get(key).unwrap()); } }) }
{ let (store, keys) = table_lookup_gen_data(); b.iter(|| { let mut stats = Statistics::default(); for key in &keys { black_box(store.get(key, &mut stats).unwrap()); } }); }
identifier_body
incremental_get.rs
use test::{black_box, Bencher}; use engine_rocks::RocksSnapshot; use kvproto::kvrpcpb::{Context, IsolationLevel}; use std::sync::Arc; use test_storage::SyncTestStorageBuilder; use tidb_query_datatype::codec::table; use tikv::storage::{Engine, SnapshotStore, Statistics, Store}; use txn_types::{Key, Mutation}; fn table...
(b: &mut Bencher) { let (store, keys) = table_lookup_gen_data(); b.iter(|| { let mut stats = Statistics::default(); for key in &keys { black_box(store.get(key, &mut stats).unwrap()); } }); } #[bench] fn bench_table_lookup_mvcc_incremental_get(b: &mut Bencher) { let (...
bench_table_lookup_mvcc_get
identifier_name
buffer_map.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::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
} impl PartialEq for BufferKey { fn eq(&self, other: &BufferKey) -> bool { let BufferKey(s) = *self; let BufferKey(o) = *other; s[0] == o[0] && s[1] == o[1] } } /// Create a key from a given size impl BufferKey { fn get(input: Size2D<uint>) -> BufferKey { BufferKey([input....
{ let BufferKey(ref bytes) = *self; bytes.as_slice().hash(state); }
identifier_body
buffer_map.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::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
(&mut self, size: Size2D<uint>) -> Option<Box<LayerBuffer>> { let mut flag = false; // True if key needs to be popped after retrieval. let key = BufferKey::get(size); let ret = match self.map.get_mut(&key) { Some(ref mut buffer_val) => { buffer_val.last_action = self....
find
identifier_name
buffer_map.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::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; use geom::size::Size2D; ...
mem: uint, /// The maximum allowed memory. Unused buffers will be deleted /// when this threshold is exceeded. max_mem: uint, /// A monotonically increasing counter to track how recently tile sizes were used. counter: uint, } /// A key with which to store buffers. It is based on the size of the...
pub struct BufferMap { /// A HashMap that stores the Buffers. map: HashMap<BufferKey, BufferValue>, /// The current amount of memory stored by the BufferMap's buffers.
random_line_split
inflightmap.rs
use std::cmp::Ordering; use std::collections::hash_map::{Entry, RandomState}; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::Deref; // TODO: need a more efficient implementation and possibly more flexibility #[derive(Debug)] pub struct InFlightMap<K: Hash ...
} impl<T: Eq, V> Eq for Pair<T, V> {} impl<T: PartialOrd, V> PartialOrd<Pair<T, V>> for Pair<T, V> { fn partial_cmp(&self, other: &Pair<T, V>) -> Option<Ordering> { other.0.partial_cmp(&self.0) } } impl<T: Ord, V> Ord for Pair<T, V> { fn cmp(&self, other: &Pair<T, V>) -> Ordering { other...
{ other.0.eq(&self.0) }
identifier_body
inflightmap.rs
use std::cmp::Ordering; use std::collections::hash_map::{Entry, RandomState}; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::Deref; // TODO: need a more efficient implementation and possibly more flexibility #[derive(Debug)] pub struct InFlightMap<K: Hash ...
(&mut self, key: &K) -> Option<V> { self.map.remove(key) } pub fn entry_with_timeout(&mut self, key: K, expire: T) -> Entry<K, V> { self.heap.push(Pair(expire, key)); self.map.entry(key) } pub fn entry(&mut self, key: K) -> Entry<K, V> { self.map.entry(key) } p...
remove
identifier_name
inflightmap.rs
use std::cmp::Ordering; use std::collections::hash_map::{Entry, RandomState}; use std::collections::{BinaryHeap, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::Deref; // TODO: need a more efficient implementation and possibly more flexibility #[derive(Debug)] pub struct InFlightMap<K: Hash ...
} pub fn entry_with_timeout(&mut self, key: K, expire: T) -> Entry<K, V> { self.heap.push(Pair(expire, key)); self.map.entry(key) } pub fn entry(&mut self, key: K) -> Entry<K, V> { self.map.entry(key) } pub fn insert(&mut self, key: K, value: V, expire: T) -> &mut V { ...
pub fn remove(&mut self, key: &K) -> Option<V> { self.map.remove(key)
random_line_split
list_documents.rs
use crate::domain::model::error::Error as ModelError; use crate::domain::ports::secondary::list::{List, Parameters}; use async_trait::async_trait; use common::document::ContainerDocument; use futures::stream::{Stream, StreamExt}; use std::pin::Pin; use tracing::info_span; use tracing_futures::Instrument; type PinnedSt...
(&self) -> Result<PinnedStream<Result<D, ModelError>>, ModelError> { let doc_type = D::static_doc_type().to_string(); let documents = self .list_documents(Parameters { doc_type }) .await? .map(|raw| raw.map_err(|err| ModelError::DocumentRetrievalError { source: err.into...
list_documents
identifier_name
list_documents.rs
use crate::domain::model::error::Error as ModelError; use crate::domain::ports::secondary::list::{List, Parameters}; use async_trait::async_trait; use common::document::ContainerDocument;
use tracing_futures::Instrument; type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send +'static>>; #[async_trait] pub trait ListDocuments<D> { async fn list_documents(&self) -> Result<PinnedStream<Result<D, ModelError>>, ModelError>; } #[async_trait] impl<D, T> ListDocuments<D> for T where D: ContainerD...
use futures::stream::{Stream, StreamExt}; use std::pin::Pin; use tracing::info_span;
random_line_split
list_documents.rs
use crate::domain::model::error::Error as ModelError; use crate::domain::ports::secondary::list::{List, Parameters}; use async_trait::async_trait; use common::document::ContainerDocument; use futures::stream::{Stream, StreamExt}; use std::pin::Pin; use tracing::info_span; use tracing_futures::Instrument; type PinnedSt...
}
{ let doc_type = D::static_doc_type().to_string(); let documents = self .list_documents(Parameters { doc_type }) .await? .map(|raw| raw.map_err(|err| ModelError::DocumentRetrievalError { source: err.into() })) .instrument(info_span!( "List...
identifier_body
equals.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator;
use core::cmp::Eq; struct A<T: Eq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); ...
use core::iter::order::equals;
random_line_split
equals.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::equals; use core::cmp::Eq; struct A<T: Eq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -...
() { let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 0, end: 10 }; let result: bool = equals::<AA, L, R>(a, b); assert_eq!(result, true); } #[test] fn equals_test2() { let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 0, end: 11 }; let result: bool = equals::<AA, L, R>(a, b); as...
equals_test1
identifier_name
issue-13808.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 ...
} impl<'a> Foo<'a> { fn new<F>(listener: F) -> Foo<'a> where F: FnMut() + 'a { Foo { listener: box listener } } } fn main() { let a = Foo::new(|| {}); }
#![feature(box_syntax)] struct Foo<'a> { listener: Box<FnMut() + 'a>,
random_line_split
issue-13808.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 a = Foo::new(|| {}); }
identifier_body
issue-13808.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 ...
<'a> { listener: Box<FnMut() + 'a>, } impl<'a> Foo<'a> { fn new<F>(listener: F) -> Foo<'a> where F: FnMut() + 'a { Foo { listener: box listener } } } fn main() { let a = Foo::new(|| {}); }
Foo
identifier_name
workspace.rs
use crate::config::GeneralConfig; use crate::core::stack::Stack; use crate::layout::{Layout, LayoutMessage}; use crate::window_system::{Window, WindowSystem}; /// Represents a single workspace with a `tag` (name), /// `id`, a `layout` and a `stack` for all windows pub struct Workspace { pub id: u32, pub tag: S...
(&self) -> usize { self.stack.clone().map_or(0usize, |x| x.len()) } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Checks if the workspace contains the given window pub fn contains(&self, window: Window) -> bool { self.stack.clone().map_or(false, |x| x.contains(wind...
len
identifier_name
workspace.rs
use crate::config::GeneralConfig; use crate::core::stack::Stack; use crate::layout::{Layout, LayoutMessage}; use crate::window_system::{Window, WindowSystem}; /// Represents a single workspace with a `tag` (name), /// `id`, a `layout` and a `stack` for all windows pub struct Workspace { pub id: u32, pub tag: S...
pub fn map_or<F>(&self, default: Stack<Window>, f: F) -> Workspace where F: Fn(Stack<Window>) -> Stack<Window>, { Workspace::new( self.id, self.tag.clone(), self.layout.copy(), Some(self.stack.clone().map_or(default, |x| f(x))), ) ...
random_line_split
workspace.rs
use crate::config::GeneralConfig; use crate::core::stack::Stack; use crate::layout::{Layout, LayoutMessage}; use crate::window_system::{Window, WindowSystem}; /// Represents a single workspace with a `tag` (name), /// `id`, a `layout` and a `stack` for all windows pub struct Workspace { pub id: u32, pub tag: S...
/// Returns the number of windows contained in this workspace pub fn len(&self) -> usize { self.stack.clone().map_or(0usize, |x| x.len()) } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Checks if the workspace contains the given window pub fn contains(&self, wind...
{ Workspace::new( self.id, self.tag.clone(), self.layout.copy(), Some( self.stack .clone() .map_or(Stack::from_element(window), |s| s.add(window)), ), ) }
identifier_body
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
<'a, T: Encodable>(&mut self, obj: &T) { let s = json::encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); } fn read...
write_json_packet
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
let packet_len = match u64::from_str_radix(&packet_len_str, 10) { Ok(packet_len) => packet_len, Err(_) => return Err("packet length missing / not parsable".to_string()), }; let mut packet = String::new(); ...
let packet_len_str = match String::from_utf8(buffer) { Ok(packet_len) => packet_len, Err(_) => return Err("nonvalid UTF8 in packet length".to_string()), };
random_line_split
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
Err(_) => return Err("packet length missing / not parsable".to_string()), }; let mut packet = String::new(); self.take(packet_len).read_to_string(&mut packet).unwrap(); println!("{}", packet); ret...
{ // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match self.read(&mut buf) { Ok(0) => ...
identifier_body
cannot-mutate-captured-non-mut-var.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 = 1; to_fn_once(move|| { x = 2; }); //[ast]~^ ERROR: cannot assign to immutable captured outer variable //[mir]~^^ ERROR: cannot assign to `x`, as it is not declared as mutable let s = std::io::stdin(); to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); //[ast]~^ ERROR: cann...
main
identifier_name
cannot-mutate-captured-non-mut-var.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 ...
//[ast]~^ ERROR: cannot assign to immutable captured outer variable //[mir]~^^ ERROR: cannot assign to `x`, as it is not declared as mutable let s = std::io::stdin(); to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); //[ast]~^ ERROR: cannot borrow immutable captured outer variable //[mir]...
let x = 1; to_fn_once(move|| { x = 2; });
random_line_split
cannot-mutate-captured-non-mut-var.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 main() { let x = 1; to_fn_once(move|| { x = 2; }); //[ast]~^ ERROR: cannot assign to immutable captured outer variable //[mir]~^^ ERROR: cannot assign to `x`, as it is not declared as mutable let s = std::io::stdin(); to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); //[ast]~^ ER...
{ f }
identifier_body
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Modules Struct Visibility in Rust mod my { // A public struct with a public field of generic type `T` pub struct WhiteBox<T> { pub contents: T, } // A public struct with a private field o...
> { contents: T, } impl<T> BlackBox<T> { // A public constructor method pub fn new(contents: T) -> BlackBox<T> { BlackBox { contents: contents, } } } } fn main() { // Public structs with public fields can be constructed as usual ...
ackBox<T
identifier_name
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Modules Struct Visibility in Rust mod my { // A public struct with a public field of generic type `T` pub struct WhiteBox<T> { pub contents: T, } // A public struct with a private field o...
impl<T> BlackBox<T> { // A public constructor method pub fn new(contents: T) -> BlackBox<T> { BlackBox { contents: contents, } } } } fn main() { // Public structs with public fields can be constructed as usual let white_box = my::WhiteBox...
random_line_split
radio_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use RadioButton; use ToggleToolButton; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::obj...
} pub const NONE_RADIO_TOOL_BUTTON: Option<&RadioToolButton> = None; pub trait RadioToolButtonExt:'static { fn get_group(&self) -> Vec<RadioButton>; } impl<O: IsA<RadioToolButton>> RadioToolButtonExt for O { fn get_group(&self) -> Vec<RadioButton> { unsafe { FromGlibPtrContainer::from_gl...
{ skip_assert_initialized!(); unsafe { ToolItem::from_glib_none(ffi::gtk_radio_tool_button_new_from_widget(group.as_ref().to_glib_none().0)).unsafe_cast() } }
identifier_body
radio_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use RadioButton; use ToggleToolButton; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::obj...
pub const NONE_RADIO_TOOL_BUTTON: Option<&RadioToolButton> = None; pub trait RadioToolButtonExt:'static { fn get_group(&self) -> Vec<RadioButton>; } impl<O: IsA<RadioToolButton>> RadioToolButtonExt for O { fn get_group(&self) -> Vec<RadioButton> { unsafe { FromGlibPtrContainer::from_glib_...
ToolItem::from_glib_none(ffi::gtk_radio_tool_button_new_from_widget(group.as_ref().to_glib_none().0)).unsafe_cast() } } }
random_line_split
radio_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use RadioButton; use ToggleToolButton; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::obj...
(&self) -> Vec<RadioButton> { unsafe { FromGlibPtrContainer::from_glib_none(ffi::gtk_radio_tool_button_get_group(self.as_ref().to_glib_none().0)) } } } impl fmt::Display for RadioToolButton { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "RadioToolButton")...
get_group
identifier_name
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn main() { let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Ve...
} if good { break; } input += 1; } println!("1: {:?}", input); }
{ good = good && o == 1; }
conditional_block
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn main()
let mut good = output.len() % 2 == 0; for (i, &o) in output.iter().enumerate() { if i % 2 == 0 { good = good && o == 0; } else { good = good && o == 1; } } if good { break; } input += 1; ...
{ let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Vec::new(); for line in reader.lines() { let line = line.unwrap(); program.push(line.parse().unwrap()); } let mut cpu = Cpu::new(); let mut inpu...
identifier_body
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn
() { let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Vec::new(); for line in reader.lines() { let line = line.unwrap(); program.push(line.parse().unwrap()); } let mut cpu = Cpu::new(); let mut i...
main
identifier_name
day25.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate aoc2016; use std::io::{BufReader, BufRead}; use std::fs::File; use aoc2016::assembunny::Cpu; fn main() { let file = File::open("input/day25.in").expect("Failed to open input"); let reader = BufReader::new(&file); let mut program = Ve...
loop { cpu.reset(); cpu.registers[0] = input; let output = cpu.run(&program); let mut good = output.len() % 2 == 0; for (i, &o) in output.iter().enumerate() { if i % 2 == 0 { good = good && o == 0; } else { good = good ...
random_line_split
docker.rs
use std::io; use std::io::prelude::*; use std::mem; use std::process::{Output, Command, Stdio, ExitStatus}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use wait_timeout::ChildExt; pub struct Container { id: String, } impl Container { pub fn new(cmd: &str, ...
else { let s = output_lossy.chars().take(1024).collect::<String>(); debug!("output (truncated): {}...", s); } } Ok((status, output, timeout)) } } fn append(into: &Mutex<Vec<u8>>, from: &mut Read) { let mut buf = [0; 1024]; while let Ok(amt) = fro...
{ debug!("output: {}", output_lossy); }
conditional_block
docker.rs
use std::io; use std::io::prelude::*; use std::mem; use std::process::{Output, Command, Stdio, ExitStatus}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use wait_timeout::ChildExt; pub struct
{ id: String, } impl Container { pub fn new(cmd: &str, args: &[String], env: &[(String, String)], name: &str) -> io::Result<Container> { let out = try!(run(Command::new("docker") .arg("create") ...
Container
identifier_name
docker.rs
use std::io; use std::io::prelude::*; use std::mem; use std::process::{Output, Command, Stdio, ExitStatus}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use wait_timeout::ChildExt; pub struct Container { id: String, } impl Container { pub fn new(cmd: &str, ...
} into.lock().unwrap().extend_from_slice(&buf[..amt]); } } impl Drop for Container { fn drop(&mut self) { run(Command::new("docker") .arg("rm") .arg("--force") .arg(&self.id)).unwrap(); } } fn run(cmd: &mut Command) -> io::Re...
if amt == 0 { break
random_line_split
docker.rs
use std::io; use std::io::prelude::*; use std::mem; use std::process::{Output, Command, Stdio, ExitStatus}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use wait_timeout::ChildExt; pub struct Container { id: String, } impl Container { pub fn new(cmd: &str, ...
let sink2 = sink.clone(); let stderr = thread::spawn(move || append(&sink2, &mut stderr)); let (status, timeout) = match try!(cmd.wait_timeout(timeout)) { Some(status) => { debug!("finished before timeout"); // TODO: document this (uns...
{ let mut cmd = Command::new("docker"); cmd.arg("start") .arg("--attach") .arg("--interactive") .arg(&self.id) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); debug!("attaching with {:?}", cmd); let...
identifier_body
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Generics bounds in Rust // A trait which implements the print marker: `{:?}`. use std::fmt::Debug; trait HasArea { fn area(&self) -> f64; } impl HasArea for Rectangle { fn area(&self) -> f64 { self.lengt...
let rectangle = Rectangle { length: 3.0, height: 4.0 }; let _triangle = Triangle { length: 3.0, height: 4.0 }; print_debug(&rectangle); println!("Area: {}", area(&rectangle)); //print_debug(&_triangle); //println!("Area: {}", area(&_triangle)); // ^ TODO: Try uncommenting these. // | ...
identifier_body
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Generics bounds in Rust // A trait which implements the print marker: `{:?}`. use std::fmt::Debug; trait HasArea { fn area(&self) -> f64; } impl HasArea for Rectangle { fn ar
self) -> f64 { self.length * self.height } } #[derive(Debug)] struct Rectangle { length: f64, height: f64 } #[allow(dead_code)] struct Triangle { length: f64, height: f64 } // The generic `T` must implement `Debug`. Regardless // of type, this will work properly. fn print_debug<T: Debug>(t: &T) { println!("{:?}"...
ea(&
identifier_name
main.rs
/* Aurélien DESBRIÈRES aurelien(at)hackers(dot)camp License GNU GPL latest */ // Rust experimentations // Generics bounds in Rust // A trait which implements the print marker: `{:?}`. use std::fmt::Debug; trait HasArea { fn area(&self) -> f64;
} #[derive(Debug)] struct Rectangle { length: f64, height: f64 } #[allow(dead_code)] struct Triangle { length: f64, height: f64 } // The generic `T` must implement `Debug`. Regardless // of type, this will work properly. fn print_debug<T: Debug>(t: &T) { println!("{:?}", t); } // `T` must implement `HasArea`. A...
} impl HasArea for Rectangle { fn area(&self) -> f64 { self.length * self.height }
random_line_split
gpu_types.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 api::{DevicePoint, LayoutToWorldTransform, WorldToLayoutTransform}; use gpu_cache::{GpuCacheAddress, GpuDataRe...
pub uv_rect_kind: UvRectKind, } impl ImageSource { pub fn write_gpu_blocks(&self, request: &mut GpuDataRequest) { request.push([ self.p0.x, self.p0.y, self.p1.x, self.p1.y, ]); request.push([ self.texture_layer, sel...
pub texture_layer: f32, pub user_data: [f32; 3],
random_line_split
gpu_types.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 api::{DevicePoint, LayoutToWorldTransform, WorldToLayoutTransform}; use gpu_cache::{GpuCacheAddress, GpuDataRe...
} }
{ request.push([ top_left.x, top_left.y, top_right.x, top_right.y, ]); request.push([ bottom_left.x, bottom_left.y, bottom_right.x, bottom_right.y, ...
conditional_block
gpu_types.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 api::{DevicePoint, LayoutToWorldTransform, WorldToLayoutTransform}; use gpu_cache::{GpuCacheAddress, GpuDataRe...
{ next: i32, } impl ZBufferIdGenerator { pub fn new() -> Self { ZBufferIdGenerator { next: 0 } } pub fn next(&mut self) -> ZBufferId { let id = ZBufferId(self.next); self.next += 1; id } } #[derive(Debug, Copy, Clone)] #[cfg_attr(feature = "cap...
ZBufferIdGenerator
identifier_name
main.rs
extern crate config; extern crate rand; extern crate clap; extern crate nix; extern crate sys_info; extern crate anyhow; extern crate flate2; extern crate tar; #[macro_use] extern crate lazy_static; #[cfg(target_os = "linux")] extern crate gtk; #[cfg(target_os = "linux")] extern crate libappindicator; #[cfg(target_os...
else { handle_file_upload(config, &path); } } } fn handle_file_upload(config: DropConfig, file: &Path) { if!file.exists() { println!("File does not exist! ({:?})", file); std::process::exit(1); } else { let filename = util::generate_filename(&config, file.file_name().map(|s| util::from_os_...
{ let archive = archive_directory(&path); handle_file_upload(config, &archive.as_path()) }
conditional_block
main.rs
extern crate config; extern crate rand; extern crate clap; extern crate nix; extern crate sys_info; extern crate anyhow; extern crate flate2; extern crate tar; #[macro_use] extern crate lazy_static; #[cfg(target_os = "linux")] extern crate gtk; #[cfg(target_os = "linux")] extern crate libappindicator; #[cfg(target_os...
fn capture_screencast(config: &DropConfig) -> PathBuf { let out_file_name = util::generate_filename(config, None, Some(config.video_format.clone())); let out_file = Path::new(&config.dir).join(out_file_name); capture::screencast(out_file.as_path(), config); out_file } fn handle_file(config: DropConfig, match...
{ let out_file_name = util::generate_filename(config, None, Some("png".to_string())); let out_file = Path::new(&config.dir).join(out_file_name); capture::screenshot(out_file.as_path(), config); out_file }
identifier_body
main.rs
extern crate config; extern crate rand; extern crate clap; extern crate nix; extern crate sys_info; extern crate anyhow; extern crate flate2; extern crate tar; #[macro_use] extern crate lazy_static; #[cfg(target_os = "linux")] extern crate gtk; #[cfg(target_os = "linux")] extern crate libappindicator; #[cfg(target_os...
(config: &DropConfig, file: &Path, filename: Option<String>) -> String { if config.local || config.aws_bucket.is_none() || config.aws_key.is_none() || config.aws_secret.is_none() { format!("file://{}", util::path_to_str(file.canonicalize().unwrap().as_path())) } else { aws::upload_file_to_s3(&config, &file,...
handle_upload_and_produce_url
identifier_name
main.rs
extern crate config; extern crate rand; extern crate clap; extern crate nix; extern crate sys_info; extern crate anyhow; extern crate flate2; extern crate tar; #[macro_use] extern crate lazy_static; #[cfg(target_os = "linux")] extern crate gtk; #[cfg(target_os = "linux")] extern crate libappindicator; #[cfg(target_os...
let url = handle_upload_and_produce_url(&config, &file, Some(filename.clone())); clip::copy_to_clipboard(url.clone()); if config.notifications { notify::send_upload_notification(filename, &config); } println!("{}", url); } } fn archive_directory(file: &Path) -> PathBuf { let archive_path ...
} else { let filename = util::generate_filename(&config, file.file_name().map(|s| util::from_os_str(s)), None);
random_line_split
mod.rs
pub mod g2d; pub mod g3d; use time; pub trait Drawable { fn draw(&self); } pub struct
{ pub width: u32, pub height: u32, pub refresh_rate: u16, pub bits_per_pixel: u16 } pub struct Monitor { pub virtual_y: u32, pub virtual_x: u32, pub name: String, pub display_modes: Vec<DisplayMode> } pub struct Graphics { pub display_mode: DisplayMode, pub frame_id: u32, ...
DisplayMode
identifier_name
mod.rs
pub mod g2d; pub mod g3d; use time; pub trait Drawable { fn draw(&self); } pub struct DisplayMode { pub width: u32, pub height: u32, pub refresh_rate: u16, pub bits_per_pixel: u16 } pub struct Monitor { pub virtual_y: u32, pub virtual_x: u32,
} pub struct Graphics { pub display_mode: DisplayMode, pub frame_id: u32, pub delta_time: time::Duration, pub fps: u16, pub monitors: Vec<Monitor>, pub should_close: bool } impl Graphics { pub fn new(width: u32, height: u32, title: &str) -> Self { Graphics { display_mod...
pub name: String, pub display_modes: Vec<DisplayMode>
random_line_split
enum-null-pointer-opt.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(size_of::<Foo>(), size_of::<Option<Foo>>()); assert_eq!(size_of::<Bar>(), size_of::<Option<Bar>>()); // and tuples assert_eq!(size_of::<(u8, Box<isize>)>(), size_of::<Option<(u8, Box<isize>)>>()); // and fixed-size arrays assert_eq!(size_of::<[Box<isize>; 1]>(), size_of::<Option<[Box<...
struct Bar(Box<isize>); // Should apply through structs
random_line_split
enum-null-pointer-opt.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 ...
{ _a: Box<isize> } struct Bar(Box<isize>); // Should apply through structs assert_eq!(size_of::<Foo>(), size_of::<Option<Foo>>()); assert_eq!(size_of::<Bar>(), size_of::<Option<Bar>>()); // and tuples assert_eq!(size_of::<(u8, Box<isize>)>(), size_of::<Option<(u8, Box<isize>)>>());...
Foo
identifier_name
optimizer.rs
use std::collections::BTreeMap; use crate::structs::Op::*; use crate::structs::{Op, OpStream}; impl OpStream { pub fn optimize(&mut self) { let mut i = 0; while i < self.ops.len() { match self.ops[i..] { [Add(a), Add(b),..] => { self.ops[i] = Add(a.w...
map.remove(&0).unwrap_or(0), map.into_iter().collect(), )) } else { None } } } #[cfg(test)] mod tests { use crate::structs::Op::*; use crate::structs::OpStream; #[test] fn test_opstream_optimize() { let mut opstream =...
{ let mut map = BTreeMap::<isize, u8>::new(); let mut rel_index = 0; for op in &self.ops { match *op { Add(x) => { map.insert(rel_index, map.get(&rel_index).unwrap_or(&0).wrapping_add(x)); } Mov(x) => { ...
identifier_body
optimizer.rs
use std::collections::BTreeMap; use crate::structs::Op::*; use crate::structs::{Op, OpStream}; impl OpStream { pub fn optimize(&mut self) { let mut i = 0; while i < self.ops.len() { match self.ops[i..] { [Add(a), Add(b),..] => { self.ops[i] = Add(a.w...
() { let mut opstream = OpStream { ops: vec![Loop(OpStream { ops: vec![Add(0x01), Mov(3), Add(0xff), Mov(-3)], })], }; opstream.optimize(); assert_eq!( opstream, OpStream { ops: vec![Transfer(1, vec![(3, 255...
test_opstream_optimize_transfer
identifier_name
optimizer.rs
use std::collections::BTreeMap; use crate::structs::Op::*; use crate::structs::{Op, OpStream}; impl OpStream { pub fn optimize(&mut self) { let mut i = 0; while i < self.ops.len() { match self.ops[i..] { [Add(a), Add(b),..] => { self.ops[i] = Add(a.w...
#[test] fn test_opstream_optimize() { let mut opstream = OpStream { ops: vec![ Mov(1), Mov(1), Add(0x01), Add(0xff), Add(0xff), Mov(1), Mov(-1), Loop(OpStream { ...
#[cfg(test)] mod tests { use crate::structs::Op::*; use crate::structs::OpStream;
random_line_split
http_server.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 foxbox_taxonomy::manager::*; use hyper::net::{ NetworkListener }; use iron::{ AfterMiddleware, Chain, Handler, HttpServerFactory, Iron, IronResult, Request, Response, ServerFactory }; use iron_cors::CORS; use iron::error::{ IronError }; use iron::method::Method; use iron::status::Status; us...
random_line_split
http_server.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 foxbox_taxonomy::manager::*; use hyper::net::{ NetworkListener }; use iron::{ AfterMiddleware, Chain, Handler,...
// Taxonomy router paths. Keep in sync with taxonomy_router.rs (vec![Method::Get, Method::Post], "api/v1/services".to_owned()), (vec![Method::Post, Method::Delete], "api/v1/services/tags".to_owned()), (vec![Method::Get, Method::Post], "api/v1/channels".to_owned()), ...
{ let taxonomy_chain = taxonomy_router::create(self.controller.clone(), adapter_api); let users_manager = self.controller.get_users_manager(); let mut mount = Mount::new(); mount.mount("/", static_router::create(users_manager.clone()...
identifier_body
http_server.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 foxbox_taxonomy::manager::*; use hyper::net::{ NetworkListener }; use iron::{ AfterMiddleware, Chain, Handler,...
} } fn start_server<TListener, T>(addrs: Vec<SocketAddr>, chain: Chain, factory: T) where TListener: NetworkListener + Send +'static, T: ServerFactory<TListener> + Send +'static { thread::Builder::new().name("HttpServer".to_owned()) .spawn(move || { Iron::new(ch...
{ start_server(addrs, chain, HttpServerFactory {}); }
conditional_block
http_server.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 foxbox_taxonomy::manager::*; use hyper::net::{ NetworkListener }; use iron::{ AfterMiddleware, Chain, Handler,...
(&mut self, adapter_api: &Arc<AdapterManager>) { let taxonomy_chain = taxonomy_router::create(self.controller.clone(), adapter_api); let users_manager = self.controller.get_users_manager(); let mut mount = Mount::new(); mount.mount("...
start
identifier_name
raii_mutex_table.rs
use parking_lot::Mutex; use std::cmp::Eq; use std::collections::HashSet; use std::hash::Hash; pub struct
<K> { map: Mutex<HashSet<K>>, } pub struct RAIIMutexGuard<'a, K> where K: Eq + Clone + Hash, { parent: &'a RAIIMutexTable<K>, key: K, } impl<K> RAIIMutexTable<K> where K: Eq + Clone + Hash, { pub fn new() -> RAIIMutexTable<K> { RAIIMutexTable { map: Mutex::new(HashSet::new(...
RAIIMutexTable
identifier_name
raii_mutex_table.rs
use parking_lot::Mutex; use std::cmp::Eq; use std::collections::HashSet; use std::hash::Hash; pub struct RAIIMutexTable<K> { map: Mutex<HashSet<K>>, } pub struct RAIIMutexGuard<'a, K> where K: Eq + Clone + Hash, { parent: &'a RAIIMutexTable<K>, key: K, } impl<K> RAIIMutexTable<K> where K: Eq + Cl...
} } pub fn unlock(&self, key: &K) { let mut map_guard = self.map.lock(); debug_assert!(map_guard.contains(key)); map_guard.remove(key); } } impl<'a, K> Drop for RAIIMutexGuard<'a, K> where K: Eq + Clone + Hash, { fn drop(&mut self) { self.parent.unlock(&sel...
{ map_guard.insert(k.clone()); return RAIIMutexGuard { parent: self, key: k, }; }
conditional_block
raii_mutex_table.rs
use parking_lot::Mutex; use std::cmp::Eq; use std::collections::HashSet; use std::hash::Hash; pub struct RAIIMutexTable<K> { map: Mutex<HashSet<K>>, } pub struct RAIIMutexGuard<'a, K> where K: Eq + Clone + Hash, { parent: &'a RAIIMutexTable<K>, key: K, } impl<K> RAIIMutexTable<K> where K: Eq + Cl...
where K: Eq + Clone + Hash, { fn drop(&mut self) { self.parent.unlock(&self.key) } }
} impl<'a, K> Drop for RAIIMutexGuard<'a, K>
random_line_split
raii_mutex_table.rs
use parking_lot::Mutex; use std::cmp::Eq; use std::collections::HashSet; use std::hash::Hash; pub struct RAIIMutexTable<K> { map: Mutex<HashSet<K>>, } pub struct RAIIMutexGuard<'a, K> where K: Eq + Clone + Hash, { parent: &'a RAIIMutexTable<K>, key: K, } impl<K> RAIIMutexTable<K> where K: Eq + Cl...
}
{ self.parent.unlock(&self.key) }
identifier_body
mod.rs
use crate::traits::*; use rustc_errors::ErrorReported; use rustc_middle::mir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TypeFoldable}; use rustc_symbol_mangling::typeid_for_fnabi; use rustc_target::abi::cal...
else { let tmp = PlaceRef::alloca(bx, arg.layout); bx.store_fn_arg(arg, &mut llarg_idx, tmp); LocalRef::Place(tmp) } }) .collect::<Vec<_>>(); if fx.instance.def.requires_caller_location(bx.tcx()) { let mir_args = if let Some(num_un...
{ // As the storage for the indirect argument lives during // the whole function call, we just copy the fat pointer. let llarg = bx.get_param(llarg_idx); llarg_idx += 1; let llextra = bx.get_param(llarg_idx); llarg_idx += 1;...
conditional_block
mod.rs
use crate::traits::*; use rustc_errors::ErrorReported; use rustc_middle::mir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TypeFoldable}; use rustc_symbol_mangling::typeid_for_fnabi; use rustc_target::abi::cal...
use self::operand::{OperandRef, OperandValue}; /// Master context for codegenning from MIR. pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> { instance: Instance<'tcx>, mir: &'tcx mir::Body<'tcx>, debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>, llfn: Bx::Funct...
use rustc_middle::mir::traversal;
random_line_split
mod.rs
use crate::traits::*; use rustc_errors::ErrorReported; use rustc_middle::mir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TypeFoldable}; use rustc_symbol_mangling::typeid_for_fnabi; use rustc_target::abi::cal...
<'tcx, V> { Place(PlaceRef<'tcx, V>), /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place). /// `*p` is the fat pointer that references the actual unsized place. /// Every time it is initialized, we have to reallocate the place /// and update the fat pointer. That's the reason why it...
LocalRef
identifier_name
local_data.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert!(*(local_data_get(my_key).get()) == ~"parent data"); assert!(*(local_data_get(my_key).get()) == ~"parent data"); } } #[test] fn test_tls_overwrite() { unsafe { fn my_key(_x: @~str) { } local_data_set(my_key, @~"first data"); local_data_set(my_key, @~"next data"); ...
} } // Must work multiple times assert!(*(local_data_get(my_key).get()) == ~"parent data");
random_line_split
local_data.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 ...
() { unsafe { fn my_key(_x: @~str) { } local_data_set(my_key, @~"weasel"); assert!(*(local_data_pop(my_key).get()) == ~"weasel"); // Pop must remove the data from the map. assert!(local_data_pop(my_key).is_none()); } } #[test] fn test_tls_modify() { unsafe { ...
test_tls_pop
identifier_name
local_data.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 ...
/** * Modify a task-local data value. If the function returns 'None', the * data is removed (and its reference dropped). */ pub unsafe fn local_data_modify<T:'static>( key: LocalDataKey<T>, modify_fn: &fn(Option<@T>) -> Option<@T>) { local_modify(Handle::new(), key, modify_fn) } #[test] fn test_tls_mu...
{ local_set(Handle::new(), key, data) }
identifier_body
csssupportsrule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule .read_with(&guard) .to_css_string(&guard) .into() } }
get_css
identifier_name
csssupportsrule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
} } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.s...
}
random_line_split
csssupportsrule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
.namespaces .read(); cond.eval(&context, &namespaces) }; let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule...
{ let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom( &url, Some(CssRuleType::Supports), ...
conditional_block