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 |
|---|---|---|---|---|
media_queries.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 app_units::Au;
use cssparser::{Delimiter, Parser, Token};
use euclid::size::{Size2D, TypedSize2D};
use propert... | // Media type is only optional if qualifier is not specified.
if qualifier.is_some() {
return Err(())
}
media_type = MediaQueryType::All;
// Without a media type, require at least one expression
expressions.push(try!(Expression::par... | {
let mut expressions = vec![];
let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() {
Some(Qualifier::Only)
} else if input.try(|input| input.expect_ident_matching("not")).is_ok() {
Some(Qualifier::Not)
} else {
None
... | identifier_body |
media_queries.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 app_units::Au;
use cssparser::{Delimiter, Parser, Token};
use euclid::size::{Size2D, TypedSize2D};
use propert... | {
pub media_queries: Vec<MediaQuery>
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf)]
pub enum Range<T> {
Min(T),
Max(T),
//Eq(T), // FIXME: Implement parsing support for equality then re-enable this.
}
impl Range<specified::Length> {
fn to_computed_range(&self, viewport_size: Size2D... | MediaQueryList | identifier_name |
media_queries.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 app_units::Au;
use cssparser::{Delimiter, Parser, Token};
use euclid::size::{Size2D, TypedSize2D};
use propert... |
impl Range<specified::Length> {
fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au> {
let compute_width = |&width| {
match width {
specified::Length::Absolute(value) => value,
specified::Length::FontRelative(value) => {
// http... | pub enum Range<T> {
Min(T),
Max(T),
//Eq(T), // FIXME: Implement parsing support for equality then re-enable this.
} | random_line_split |
heaphistogram.rs | /*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | classes: RefCell<Classes>
}
impl MockJvmti {
fn new() -> MockJvmti {
MockJvmti {
object_tagging_enabled_result: 0,
object_tagging_enabled: false,
classes: RefCell::new(Default::default())
}
}
}
impl JvmTI f... | #[derive(Clone)]
struct MockJvmti {
pub object_tagging_enabled_result: ::jvmti::jint,
pub object_tagging_enabled: bool, | random_line_split |
heaphistogram.rs | /*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | () -> MockJvmti {
MockJvmti {
object_tagging_enabled_result: 0,
object_tagging_enabled: false,
classes: RefCell::new(Default::default())
}
}
}
impl JvmTI for MockJvmti {
fn on_resource_exhausted(&mut self, _: FnResourceExha... | new | identifier_name |
heaphistogram.rs | /*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... |
}
#[cfg(test)]
mod tests {
use super::HeapHistogram;
use ::env::JvmTI;
use ::env::FnResourceExhausted;
use std::cell::RefCell;
use ::heap::tagger::Tag;
const test_error_code: ::jvmti::jint = 54;
#[test]
fn new_calls_enable_object_tagging() {
let mockJvmti = MockJvmti::new();
... | {
self.print(&mut stdout())?;
Ok(())
} | identifier_body |
display.rs | use alloc::boxed::Box;
use collections::String;
use common::event::Event;
use core::{cmp, ptr};
use core::mem::size_of;
use fs::{KScheme, Resource, ResourceSeek, Url};
use system::error::{Error, Result, EACCES, EBADF, ENOENT, EINVAL};
use system::graphics::fast_copy;
/// A display resource
pub struct DisplayResou... |
}
pub struct DisplayScheme;
impl KScheme for DisplayScheme {
fn scheme(&self) -> &str {
"display"
}
fn open(&mut self, url: Url, _: usize) -> Result<Box<Resource>> {
if url.reference() == "manager" {
let console = unsafe { &mut *::env().console.get() };
if console... | {
Ok(())
} | identifier_body |
display.rs | use alloc::boxed::Box;
use collections::String;
use common::event::Event;
use core::{cmp, ptr};
use core::mem::size_of;
use fs::{KScheme, Resource, ResourceSeek, Url};
use system::error::{Error, Result, EACCES, EBADF, ENOENT, EINVAL};
use system::graphics::fast_copy;
/// A display resource
pub struct DisplayResou... |
Ok(i)
} else {
Err(Error::new(EINVAL))
}
}
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let console = unsafe { & *::env().console.get() };
if let Some(ref display) = console.display {
let size = cmp::max(0, cmp::min(display.size as isiz... | }
} | random_line_split |
display.rs | use alloc::boxed::Box;
use collections::String;
use common::event::Event;
use core::{cmp, ptr};
use core::mem::size_of;
use fs::{KScheme, Resource, ResourceSeek, Url};
use system::error::{Error, Result, EACCES, EBADF, ENOENT, EINVAL};
use system::graphics::fast_copy;
/// A display resource
pub struct DisplayResou... | (&mut self, buf: &[u8]) -> Result<usize> {
let console = unsafe { & *::env().console.get() };
if let Some(ref display) = console.display {
let size = cmp::max(0, cmp::min(display.size as isize - self.seek as isize, (buf.len()/4) as isize)) as usize;
if size > 0 {
... | write | identifier_name |
base.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::iter::range_step;
use stb_image = stb_image::image;
use png;
// FIXME: Images must not be copied every f... | (width: u32, height: u32, color_type: png::ColorType, data: ~[u8]) -> Image {
png::Image {
width: width,
height: height,
color_type: color_type,
pixels: data,
}
}
static TEST_IMAGE: &'static [u8] = include_bin!("test.jpeg");
pub fn test_image_bin() -> ~[u8] {
TEST_IMAGE.int... | Image | identifier_name |
base.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::iter::range_step;
use stb_image = stb_image::image;
use png;
// FIXME: Images must not be copied every f... |
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
fn byte_swap(color_type: png::ColorType, data: &mut [u8]) {
match color_type {
png::RGBA8 => {
let length = data.len();
for i in range_step(0, length, 4) {
let r = data[i + 2];
... | {
TEST_IMAGE.into_owned()
} | identifier_body |
base.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::iter::range_step;
use stb_image = stb_image::image;
use png;
// FIXME: Images must not be copied every f... | color_type: color_type,
pixels: data,
}
}
static TEST_IMAGE: &'static [u8] = include_bin!("test.jpeg");
pub fn test_image_bin() -> ~[u8] {
TEST_IMAGE.into_owned()
}
// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
fn byte_swap(color_type: png::ColorType, dat... |
pub fn Image(width: u32, height: u32, color_type: png::ColorType, data: ~[u8]) -> Image {
png::Image {
width: width,
height: height, | random_line_split |
ws2spi.rs | // Copyright © 2015-2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied,... | ThreadHandle: HANDLE,
Reserved: DWORD_PTR,
}}
pub type LPWSATHREADID = *mut WSATHREADID;
ENUM!{enum WSC_PROVIDER_INFO_TYPE {
ProviderInfoLspCategories,
ProviderInfoAudit,
}}
FN!{stdcall LPNSPV2STARTUP(
lpProviderId: LPGUID,
ppvClientSessionArg: *mut LPVOID,
) -> INT}
FN!{stdcall LPNSPV2CLEANUP(
... | pub type LPWSPDATA = *mut WSPDATA;
STRUCT!{struct WSATHREADID { | random_line_split |
user32.rs | extern crate libc;
use ::types::*;
use std::string::String;
#[link(name = "user32")]
extern "stdcall" {
pub fn RegisterClassExA(
lpWndClass : *mut WNDCLASSEXA
) -> ATOM;
pub fn CreateWindowExA(
dwExStyle: DWORD,
lpClassName: &str,
lpWindowName: &str,
dwStyle: DWORD,
X: i32,
Y: i32,
nWidth: i32,
... | } |
pub fn DispatchMessageA(
lpMsg: LPMSG
) -> LRESULT; | random_line_split |
glue.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | // `future::Ready<_>` type annotation is redundant; it's here to check that
// `now_or_never` will not fail due to changes in `actix`.
let extract: future::Ready<_> = Query::<TransactionFilter>::extract(request);
extract
.now_or_never()
... | {
// Default subscription for blocks.
Self::handle_ws(
"v1/blocks/subscribe",
api_scope.web_backend(),
self.blockchain.clone(),
shared_state.clone(),
|_| SubscriptionType::Blocks,
);
// Default subscription for transactions.
... | identifier_body |
glue.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
// `future::Ready<_>` type annotation is redundant; it's here to check that
// `now_or_never` will not fail due to changes in `actix`.
let extract: future::Ready<_> = Query::<TransactionFilter>::extract(request);
extract
.now_or_never(... | {
return SubscriptionType::Transactions { filter: None };
} | conditional_block |
glue.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (&self, shared_state: SharedStateRef, api_scope: &mut ServiceApiScope) -> &Self {
// Default subscription for blocks.
Self::handle_ws(
"v1/blocks/subscribe",
api_scope.web_backend(),
self.blockchain.clone(),
shared_state.clone(),
|_| Subscripti... | wire_ws | identifier_name |
glue.rs | // Copyright 2020 The Exonum Team
// | //
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language gover... | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at | random_line_split |
test_helper.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{mock_tree_store::MockTreeStore, node_type::LeafNode, JellyfishMerkleTree};
use diem_crypto::{
hash::{CryptoHash, SPARSE_MERKLE_PLACEHOLDER_HASH},
HashValue,
};
use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
u... | }
}
HashValue::from_slice(&buf).unwrap()
}
/// Initializes a DB with a set of key-value pairs by inserting one key at each version.
pub fn init_mock_db<V>(kvs: &HashMap<HashValue, V>) -> (MockTreeStore<V>, Version)
where
V: crate::TestValue,
{
assert!(!kvs.is_empty());
let db = MockTreeSto... | buf[i] = 0;
} else {
buf[i] += 1;
break; | random_line_split |
test_helper.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{mock_tree_store::MockTreeStore, node_type::LeafNode, JellyfishMerkleTree};
use diem_crypto::{
hash::{CryptoHash, SPARSE_MERKLE_PLACEHOLDER_HASH},
HashValue,
};
use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
u... | <K, V>(btree: &BTreeMap<K, V>, key: &K) -> Option<K>
where
K: Clone + Ord,
{
btree
.range((Bound::Excluded(key), Bound::Unbounded))
.next()
.map(|(k, _v)| k.clone())
}
/// Computes the root hash of a sparse Merkle tree. `kvs` consists of the entire set of key-value
/// pairs stored in the ... | next_key | identifier_name |
test_helper.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{mock_tree_store::MockTreeStore, node_type::LeafNode, JellyfishMerkleTree};
use diem_crypto::{
hash::{CryptoHash, SPARSE_MERKLE_PLACEHOLDER_HASH},
HashValue,
};
use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
u... | else {
buf[i] += 1;
break;
}
}
HashValue::from_slice(&buf).unwrap()
}
/// Initializes a DB with a set of key-value pairs by inserting one key at each version.
pub fn init_mock_db<V>(kvs: &HashMap<HashValue, V>) -> (MockTreeStore<V>, Version)
where
V: crate::TestValue,
{
... | {
buf[i] = 0;
} | conditional_block |
take.rs | use futures_core::task::{Context, Poll};
#[cfg(feature = "read-initializer")]
use futures_io::Initializer;
use futures_io::{AsyncRead, AsyncBufRead};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
use std::{cmp, io};
use std::pin::Pin;
/// Reader for the [`take`](super::AsyncReadExt::take) method.
#[derive(Debug)]
#... | (&self) -> Initializer {
self.inner.initializer()
}
}
impl<R: AsyncBufRead> AsyncBufRead for Take<R> {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
let Self { inner, limit_ } = unsafe { self.get_unchecked_mut() };
let inner = unsafe { Pin::ne... | initializer | identifier_name |
take.rs | use futures_core::task::{Context, Poll};
#[cfg(feature = "read-initializer")]
use futures_io::Initializer;
use futures_io::{AsyncRead, AsyncBufRead};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
use std::{cmp, io};
use std::pin::Pin;
/// Reader for the [`take`](super::AsyncReadExt::take) method.
#[derive(Debug)]
#... | /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
/// ```
pub fn get_mut(&mut self) -> &mut R {
&mut self.inner
}
/// Gets a pinned mutable reference to the underlying reader.
///
/// Care should be taken to avoid modifying the internal I/O state of the
/// underlying ... | /// | random_line_split |
take.rs | use futures_core::task::{Context, Poll};
#[cfg(feature = "read-initializer")]
use futures_io::Initializer;
use futures_io::{AsyncRead, AsyncBufRead};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
use std::{cmp, io};
use std::pin::Pin;
/// Reader for the [`take`](super::AsyncReadExt::take) method.
#[derive(Debug)]
#... |
}
| {
// Don't let callers reset the limit by passing an overlarge value
let amt = cmp::min(amt as u64, self.limit_) as usize;
*self.as_mut().limit_() -= amt as u64;
self.inner().consume(amt);
} | identifier_body |
take.rs | use futures_core::task::{Context, Poll};
#[cfg(feature = "read-initializer")]
use futures_io::Initializer;
use futures_io::{AsyncRead, AsyncBufRead};
use pin_utils::{unsafe_pinned, unsafe_unpinned};
use std::{cmp, io};
use std::pin::Pin;
/// Reader for the [`take`](super::AsyncReadExt::take) method.
#[derive(Debug)]
#... |
let max = std::cmp::min(buf.len() as u64, self.limit_) as usize;
let n = ready!(self.as_mut().inner().poll_read(cx, &mut buf[..max]))?;
*self.as_mut().limit_() -= n as u64;
Poll::Ready(Ok(n))
}
#[cfg(feature = "read-initializer")]
unsafe fn initializer(&self) -> Initialize... | {
return Poll::Ready(Ok(0));
} | conditional_block |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between threads (or intra-thr... |
impl<T: DomObject> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
Trusted {
refcount: self.refcount.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from b... | assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
DomRoot::from_ref(&*(self.refcount.0 as *const T))
... | identifier_body |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between threads (or intra-thr... | LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
reflectable_table: RefCell::new(HashMap::new()),
promise_table: RefCell::new(HashMap::new()),
})
});
}
#[allow(unrooted_must_root)]
fn addref_promise(&self, prom... | }
impl LiveDOMReferences {
/// Set up the thread-local data required for storing the outstanding DOM references.
pub fn initialize() { | random_line_split |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between threads (or intra-thr... | self) -> Trusted<T> {
Trusted {
refcount: self.refcount.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
#[al... | one(& | identifier_name |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between threads (or intra-thr... | promise
}
Vacant(_) => unreachable!(),
};
promise
})
}
/// A task which will reject the promise.
#[allow(unrooted_must_root)]
pub fn reject_task(self, error: Error) -> impl TaskOnce {
let this = self;
tas... | entry.remove();
}
| conditional_block |
no-std.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![no_std]
mod libc {
pub type c_int = i32;
pub enum c_void {}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct foo {
pub a: libc::c_int,
pub b: libc:... | assert_eq!(
::core::mem::size_of::<foo>(),
16usize,
concat!("Size of: ", stringify!(foo))
);
assert_eq!(
::core::mem::align_of::<foo>(),
8usize,
concat!("Alignment of ", stringify!(foo))
);
assert_eq!(
unsafe { &(*(::core::ptr::null::<foo>())).... | pub bar: *mut libc::c_void,
}
#[test]
fn bindgen_test_layout_foo() { | random_line_split |
no-std.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![no_std]
mod libc {
pub type c_int = i32;
pub enum c_void {}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct foo {
pub a: libc::c_int,
pub b: libc:... | () {
assert_eq!(
::core::mem::size_of::<foo>(),
16usize,
concat!("Size of: ", stringify!(foo))
);
assert_eq!(
::core::mem::align_of::<foo>(),
8usize,
concat!("Alignment of ", stringify!(foo))
);
assert_eq!(
unsafe { &(*(::core::ptr::null::<foo>... | bindgen_test_layout_foo | identifier_name |
poll_token_derive.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![recursion_limit = "128"]
extern crate proc_macro;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{parse_macro_input, Data, Deri... | quote! {
impl PollToken for #enum_name {
fn as_raw_token(&self) -> u64 {
#as_raw_token
}
fn from_raw_token(data: u64) -> Self {
#from_raw_token
}
}
}
}
/// Implements the PollToken trait for a given `enum`.
///
//... | {
let variants: Vec<Variant> = match input.data {
Data::Enum(data) => data.variants.into_iter().collect(),
Data::Struct(_) | Data::Union(_) => panic!("input must be an enum"),
};
for variant in &variants {
assert!(variant.fields.iter().count() <= 1);
}
// Given our basic mo... | identifier_body |
poll_token_derive.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![recursion_limit = "128"]
extern crate proc_macro;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{parse_macro_input, Data, Deri... | (input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
poll_token_inner(input).into()
}
| poll_token | identifier_name |
poll_token_derive.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![recursion_limit = "128"]
extern crate proc_macro;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{parse_macro_input, Data, Deri... |
// The method for packing an enum into a u64 is as follows:
// 1) Reserve the lowest "ceil(log_2(x))" bits where x is the number of enum variants.
// 2) Store the enum variant's index (0-based index based on order in the enum definition) in
// reserved bits.
// 3) If there is data in the enum variant, store the dat... |
#[cfg(test)]
mod tests; | random_line_split |
sync_provider.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | impl SyncProvider for TestSyncProvider {
fn status(&self) -> SyncStatus {
self.status.read().unwrap().clone()
}
} | }
| random_line_split |
sync_provider.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
| {
self.status.read().unwrap().clone()
} | identifier_body |
sync_provider.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | {
/// Protocol version.
pub network_id: U256,
/// Number of peers.
pub num_peers: usize,
}
/// Test sync provider.
pub struct TestSyncProvider {
/// Sync status.
pub status: RwLock<SyncStatus>,
}
impl TestSyncProvider {
/// Creates new sync provider.
pub fn new(config: Config) -> Self {
TestSyncProvider {
... | Config | identifier_name |
estr-slice.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = &"hello";
let v = &"hello";
let mut y : &str = &"there";
info!(x);
info!(y);
assert_eq!(x[0], 'h' as u8);
assert_eq!(x[4], 'o' as u8);
let z : &str = &"thing";
assert_eq!(v, x);
assert!(x!= z);
let a = &"aaaa";
let b = &"bbbb";
let c = &"cccc";
l... | main | identifier_name |
estr-slice.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 ... |
info!(a);
assert!(a < b);
assert!(a <= b);
assert!(a!= b);
assert!(b >= a);
assert!(b > a);
info!(b);
assert!(a < c);
assert!(a <= c);
assert!(a!= c);
assert!(c >= a);
assert!(c > a);
info!(c);
assert!(c < cc);
assert!(c <= cc);
assert!(c!= cc);
... | {
let x = &"hello";
let v = &"hello";
let mut y : &str = &"there";
info!(x);
info!(y);
assert_eq!(x[0], 'h' as u8);
assert_eq!(x[4], 'o' as u8);
let z : &str = &"thing";
assert_eq!(v, x);
assert!(x != z);
let a = &"aaaa";
let b = &"bbbb";
let c = &"cccc";
let... | identifier_body |
estr-slice.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!(c <= cc);
assert!(c!= cc);
assert!(cc >= c);
assert!(cc > c);
info!(cc);
} | info!(c);
assert!(c < cc); | random_line_split |
reachable.rs | rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_session::config::CrateType;
use rustc_target::spec::abi::Abi;
// Returns true if the given item must be inlined because it may be
// monomorphized or it was marked with `#[inline]`. This will only return
// true for functio... | else {
match res {
// If this path leads to a constant, then we need to
// recurse into the constant to continue finding
// items that are reachable.
Res::Def(DefKind::Const | DefKind::AssocConst, _) => ... | {
self.worklist.push(def_id);
} | conditional_block |
reachable.rs | rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_session::config::CrateType;
use rustc_target::spec::abi::Abi;
// Returns true if the given item must be inlined because it may be
// monomorphized or it was marked with `#[inline]`. This will only return
// true for functio... | },
Some(Node::ImplItem(impl_item)) => {
match impl_item.kind {
hir::ImplItemKind::Const(..) => true,
hir::ImplItemKind::Fn(..) => {
let attrs = self.tcx.codegen_fn_attrs(def_id);
let generics ... | {
let hir_id = match def_id.as_local() {
Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
None => {
return false;
}
};
match self.tcx.hir().find(hir_id) {
Some(Node::Item(item)) => match item.kind {
hi... | identifier_body |
reachable.rs | rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_session::config::CrateType;
use rustc_target::spec::abi::Abi;
// Returns true if the given item must be inlined because it may be
// monomorphized or it was marked with `#[inline]`. This will only return
// true for functio... | <'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> FxHashSet<LocalDefId> {
let access_levels = &tcx.privacy_access_levels(());
let any_library =
tcx.sess.crate_types().iter().any(|ty| {
*ty == CrateType::Rlib || *ty == CrateType::Dylib || *ty == CrateType::ProcMacro
});
let mut reachable_cont... | reachable_set | identifier_name |
reachable.rs | use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_session::config::CrateType; |
// Returns true if the given item must be inlined because it may be
// monomorphized or it was marked with `#[inline]`. This will only return
// true for functions.
fn item_might_be_inlined(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>, attrs: &CodegenFnAttrs) -> bool {
if attrs.requests_inline() {
return true;
... | use rustc_target::spec::abi::Abi; | random_line_split |
lib.rs | pub mod errors;
mod keywords;
mod parser;
mod scc;
pub mod types;
use errors::{Error, Result};
use std::path::{Path, PathBuf};
use types::Config;
/// A builder for [Config]
///
/// # Example build.rs
///
/// ```rust,no_run
/// use pb_rs::{types::FileDescriptor, ConfigBuilder};
/// use std::path::{Path, PathBuf};
/// ... | (mut self, val: bool) -> Self {
self.dont_use_cow = val;
self
}
/// Generate Owned structs when the proto struct has a lifetime
pub fn owned(mut self, val: bool) -> Self {
self.owned = val;
self
}
/// Generate `#![no_std]` compliant code
pub fn nostd(mut self, v... | dont_use_cow | identifier_name |
lib.rs | pub mod errors;
mod keywords;
mod parser;
mod scc;
pub mod types;
use errors::{Error, Result};
use std::path::{Path, PathBuf};
use types::Config;
/// A builder for [Config]
///
/// # Example build.rs
///
/// ```rust,no_run
/// use pb_rs::{types::FileDescriptor, ConfigBuilder};
/// use std::path::{Path, PathBuf};
/// ... | /// let path = entry.unwrap().into_path();
/// if path.extension() == proto_ext {
/// // Re-run this build.rs if any of the files in the protos dir change
/// println!("cargo:rerun-if-changed={}", path.to_str().unwrap());
/// protos.push(path);
/// }
/// }... | /// // Find all *.proto files in the `in_dir` and add them to the list of files
/// let mut protos = Vec::new();
/// let proto_ext = Some(Path::new("proto").as_os_str());
/// for entry in WalkDir::new(&in_dir) { | random_line_split |
lib.rs | pub mod errors;
mod keywords;
mod parser;
mod scc;
pub mod types;
use errors::{Error, Result};
use std::path::{Path, PathBuf};
use types::Config;
/// A builder for [Config]
///
/// # Example build.rs
///
/// ```rust,no_run
/// use pb_rs::{types::FileDescriptor, ConfigBuilder};
/// use std::path::{Path, PathBuf};
/// ... |
/// Generate `MessageInfo` implementations
pub fn gen_info(mut self, val: bool) -> Self {
self.gen_info = val;
self
}
/// Add deprecated fields and mark them as `#[deprecated]`
pub fn add_deprecated_fields(mut self, val: bool) -> Self {
self.add_deprecated_fields = val;
... | {
self.hashbrown = val;
self
} | identifier_body |
vector_reader.rs | use ::{Context, Ptr};
use ::lang::{Value, Object, Scope, List, Vector};
use super::reader::Reader;
pub fn | (context: &Context, scope: Ptr<Object<Scope>>, args: Ptr<Object<List>>) -> Ptr<Value> {
let mut reader = args.first(context).downcast::<Object<Reader>>().unwrap();
let ch = reader.peek(0);
if ch == '[' {
reader.read();
let mut vector = context.gc.new_object(context.VectorType, Vector::new... | vector_reader | identifier_name |
vector_reader.rs | use ::{Context, Ptr};
use ::lang::{Value, Object, Scope, List, Vector};
use super::reader::Reader;
pub fn vector_reader(context: &Context, scope: Ptr<Object<Scope>>, args: Ptr<Object<List>>) -> Ptr<Value> | if first.typ() == context.BooleanType && first.downcast::<Object<bool>>().unwrap().value() == &true {
vector.push_mut(context, ret_list.last(context));
} else {
break;
}
}
}
let mut ret_list = context.gc... | {
let mut reader = args.first(context).downcast::<Object<Reader>>().unwrap();
let ch = reader.peek(0);
if ch == '[' {
reader.read();
let mut vector = context.gc.new_object(context.VectorType, Vector::new(context));
loop {
let ch = reader.peek(0);
if ch ==... | identifier_body |
vector_reader.rs | use ::{Context, Ptr}; | let mut reader = args.first(context).downcast::<Object<Reader>>().unwrap();
let ch = reader.peek(0);
if ch == '[' {
reader.read();
let mut vector = context.gc.new_object(context.VectorType, Vector::new(context));
loop {
let ch = reader.peek(0);
if ch == '... | use ::lang::{Value, Object, Scope, List, Vector};
use super::reader::Reader;
pub fn vector_reader(context: &Context, scope: Ptr<Object<Scope>>, args: Ptr<Object<List>>) -> Ptr<Value> { | random_line_split |
vector_reader.rs | use ::{Context, Ptr};
use ::lang::{Value, Object, Scope, List, Vector};
use super::reader::Reader;
pub fn vector_reader(context: &Context, scope: Ptr<Object<Scope>>, args: Ptr<Object<List>>) -> Ptr<Value> {
let mut reader = args.first(context).downcast::<Object<Reader>>().unwrap();
let ch = reader.peek(0);
... | else {
break;
}
}
}
let mut ret_list = context.gc.new_object(context.ListType, List::new(context));
ret_list.push_back_mut(context, context.true_value.as_value());
ret_list.push_back_mut(context, vector.as_value());
ret_list.as_va... | {
vector.push_mut(context, ret_list.last(context));
} | conditional_block |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Tests for parsing and serialization of values/properties
use cssparser::{Parser, ParserInput};
use style::con... |
fn parse_entirely_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
parse_input(|context, parser| parser.parse_entirely(|p| f(context, p)), input)
}
// This is a macro so that the file/line in... | {
let mut input = ParserInput::new(s);
parse_entirely_input(f, &mut input)
} | identifier_body |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Tests for parsing and serialization of values/properties
use cssparser::{Parser, ParserInput};
use style::con... | <T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
}
fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T,... | parse | identifier_name |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Tests for parsing and serialization of values/properties
use cssparser::{Parser, ParserInput};
use style::con... | let context = ParserContext::new(Origin::Author, &url, Some(CssRuleType::Style),
ParsingMode::DEFAULT,
QuirksMode::NoQuirks);
let mut parser = Parser::new(input);
f(&context, &mut parser)
}
fn parse_entirely<T, F>(f: F, s: &'static s... | random_line_split | |
expand.rs | // This file is part of the uutils coreutils package.
//
// (c) Virgile Andreani <virgile.andreani@anbuco.fr>
// (c) kwantam <kwantam@gmail.com>
// * 2015-04-28 ~ updated to work with both UTF-8 and non-UTF-8 encodings
//
// For the full copyright and license information, please view the LICENSE
// file that was di... | let nbytes = char::from(buf[byte]).len_utf8();
if byte + nbytes > buf.len() {
// don't overrun buffer because of invalid UTF-8
(Other, 1, 1)
} else if let Ok(t) = from_utf8(&buf[byte..byte + nbytes]) {
... | {
use self::CharType::*;
let mut output = BufWriter::new(stdout());
let ts = options.tabstops.as_ref();
let mut buf = Vec::new();
for file in &options.files {
let mut fh = open(file);
while match fh.read_until(b'\n', &mut buf) {
Ok(s) => s > 0,
Err(_) => bu... | identifier_body |
expand.rs | // This file is part of the uutils coreutils package.
//
// (c) Virgile Andreani <virgile.andreani@anbuco.fr>
// (c) kwantam <kwantam@gmail.com>
// * 2015-04-28 ~ updated to work with both UTF-8 and non-UTF-8 encodings
//
// For the full copyright and license information, please view the LICENSE
// file that was di... | /// ```rust,ignore
/// assert!(is_space_or_comma(' '))
/// assert!(is_space_or_comma(','))
/// assert!(!is_space_or_comma('a'))
/// ```
fn is_space_or_comma(c: char) -> bool {
c =='' || c == ','
}
/// Parse a list of tabstops from a `--tabs` argument.
///
/// This function returns both the vector of numbers appear... | random_line_split | |
expand.rs | // This file is part of the uutils coreutils package.
//
// (c) Virgile Andreani <virgile.andreani@anbuco.fr>
// (c) kwantam <kwantam@gmail.com>
// * 2015-04-28 ~ updated to work with both UTF-8 and non-UTF-8 encodings
//
// For the full copyright and license information, please view the LICENSE
// file that was di... | <'a>() -> App<'a> {
App::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.after_help(LONG_HELP)
.override_usage(format_usage(USAGE))
.setting(AppSettings::InferLongArgs)
.arg(
Arg::new(options::INITIAL)
.long(options::INITIAL)
... | uu_app | identifier_name |
oestexturefloat.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use super::{constants as webgl, WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use crate::dom::bindings::r... |
fn enable(ext: &WebGLExtensions) {
ext.enable_tex_type(webgl::FLOAT);
ext.add_effective_tex_internal_format(TexFormat::RGBA, webgl::FLOAT, TexFormat::RGBA32f);
ext.add_effective_tex_internal_format(TexFormat::RGB, webgl::FLOAT, TexFormat::RGB32f);
ext.add_effective_tex_internal_for... | {
ext.supports_any_gl_extension(&[
"GL_OES_texture_float",
"GL_ARB_texture_float",
"GL_EXT_color_buffer_float",
])
} | identifier_body |
oestexturefloat.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use super::{constants as webgl, WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use crate::dom::bindings::r... | (ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloat> {
reflect_dom_object(Box::new(OESTextureFloat::new_inherited()), &*ctx.global())
}
fn spec() -> WebGLExtensionSpec {
WebGLExtensionSpec::Specific(WebGLVersion::WebGL1)
}
fn is_supported(ext: &WebGLExtensions) -> bool {
e... | new | identifier_name |
oestexturefloat.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use super::{constants as webgl, WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use crate::dom::bindings::r... | }
impl OESTextureFloat {
fn new_inherited() -> OESTextureFloat {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for OESTextureFloat {
type Extension = OESTextureFloat;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<OESTextureFloat> {
reflect_dom_obje... | reflector_: Reflector, | random_line_split |
schema.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module provides traits that define the behavior of a schema and its associated key and
//! value types, along with helpers to define a new schema with ease.
use crate::ColumnFamilyName;
use anyhow::Result;
use std::fmt::Debug;
... | /// Ok(Value)
/// }
/// }
///
/// // And finally define a schema type and associate it with key and value types, as well as the
/// // column family name, by generating code that implements the `Schema` trait for the type.
/// define_schema!(ExampleSchema, Key, Value, "exmaple_cf_name");
///
/// // SeekKeyC... | /// fn decode_value(data: &[u8]) -> Result<Self> { | random_line_split |
schema.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module provides traits that define the behavior of a schema and its associated key and
//! value types, along with helpers to define a new schema with ease.
use crate::ColumnFamilyName;
use anyhow::Result;
use std::fmt::Debug;
... | {
{
let encoded = key.encode_key().expect("Encoding key should work.");
let decoded = S::Key::decode_key(&encoded).expect("Decoding key should work.");
assert_eq!(*key, decoded);
}
{
let encoded = value.encode_value().expect("Encoding value should work.");
let decoded... | identifier_body | |
schema.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module provides traits that define the behavior of a schema and its associated key and
//! value types, along with helpers to define a new schema with ease.
use crate::ColumnFamilyName;
use anyhow::Result;
use std::fmt::Debug;
... | <S: Schema>(key: &S::Key, value: &S::Value) {
{
let encoded = key.encode_key().expect("Encoding key should work.");
let decoded = S::Key::decode_key(&encoded).expect("Decoding key should work.");
assert_eq!(*key, decoded);
}
{
let encoded = value.encode_value().expect("Encodi... | assert_encode_decode | identifier_name |
uninstall.rs | use cargo::ops;
use cargo::util::{CliResult, Config};
#[derive(RustcDecodable)]
pub struct Options {
flag_bin: Vec<String>,
flag_root: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
arg_spec: String,
}
pub... | Ok(None)
} |
let root = options.flag_root.as_ref().map(|s| &s[..]);
ops::uninstall(root, &options.arg_spec, &options.flag_bin, config)?; | random_line_split |
uninstall.rs | use cargo::ops;
use cargo::util::{CliResult, Config};
#[derive(RustcDecodable)]
pub struct Options {
flag_bin: Vec<String>,
flag_root: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
arg_spec: String,
}
pub... | (options: Options, config: &Config) -> CliResult<Option<()>> {
config.configure(options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked)?;
let root = options.flag_root.as_ref().ma... | execute | identifier_name |
string.rs | use {ADDRESS_PATTERN, AddressLengthType};
use patterns::{Pattern, Patterns, parse_patterns};
use std::borrow::Borrow;
use std::sync::{Arc, Mutex};
use clap::ArgMatches;
use generic_array::GenericArray;
use termcolor::BufferWriter;
use rayon::prelude::*;
impl Pattern for String {
fn matches(&self, string: &str) -> ... | impl StringPatterns {
pub fn new(buffer_writer: Arc<Mutex<BufferWriter>>, matches: &ArgMatches) -> StringPatterns {
let patterns = parse_patterns::<String>(buffer_writer, matches);
let patterns_by_len: Arc<GenericArray<Mutex<Option<Vec<String>>>, AddressLengthType>> = Arc::new(arr![Mutex<Option<Vec<... | random_line_split | |
string.rs | use {ADDRESS_PATTERN, AddressLengthType};
use patterns::{Pattern, Patterns, parse_patterns};
use std::borrow::Borrow;
use std::sync::{Arc, Mutex};
use clap::ArgMatches;
use generic_array::GenericArray;
use termcolor::BufferWriter;
use rayon::prelude::*;
impl Pattern for String {
fn matches(&self, string: &str) -> ... |
item.map(|mut vec| {
vec.sort();
vec.dedup();
vec
})
});
StringPatterns { sorted_vecs }
}
}
impl Patterns for StringPatterns {
fn contains(&self, address: &String) -> bool {
//... | {
let patterns = parse_patterns::<String>(buffer_writer, matches);
let patterns_by_len: Arc<GenericArray<Mutex<Option<Vec<String>>>, AddressLengthType>> = Arc::new(arr![Mutex<Option<Vec<String>>>; Mutex::new(None), Mutex::new(None), Mutex::new(None), Mutex::new(None), Mutex::new(None), Mutex::new(None),... | identifier_body |
string.rs | use {ADDRESS_PATTERN, AddressLengthType};
use patterns::{Pattern, Patterns, parse_patterns};
use std::borrow::Borrow;
use std::sync::{Arc, Mutex};
use clap::ArgMatches;
use generic_array::GenericArray;
use termcolor::BufferWriter;
use rayon::prelude::*;
impl Pattern for String {
fn matches(&self, string: &str) -> ... | (buffer_writer: Arc<Mutex<BufferWriter>>, matches: &ArgMatches) -> StringPatterns {
let patterns = parse_patterns::<String>(buffer_writer, matches);
let patterns_by_len: Arc<GenericArray<Mutex<Option<Vec<String>>>, AddressLengthType>> = Arc::new(arr![Mutex<Option<Vec<String>>>; Mutex::new(None), Mutex::... | new | identifier_name |
string.rs | use {ADDRESS_PATTERN, AddressLengthType};
use patterns::{Pattern, Patterns, parse_patterns};
use std::borrow::Borrow;
use std::sync::{Arc, Mutex};
use clap::ArgMatches;
use generic_array::GenericArray;
use termcolor::BufferWriter;
use rayon::prelude::*;
impl Pattern for String {
fn matches(&self, string: &str) -> ... |
}
return false;
}
fn len(&self) -> usize {
self.sorted_vecs
.par_iter()
.filter(|opt| opt.is_some())
.map(|opt| opt.as_ref().unwrap().len())
.sum()
}
}
| {
let pattern_len = index + 1;
let target_address_slice = &address[0..pattern_len];
if vec.binary_search_by(|item| item.as_str().cmp(target_address_slice))
.is_ok() {
return true;
}
} | conditional_block |
stylesheets.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::iter::Iterator;
use std::ascii::StrAsciiExt;
use extra::url::Url;
use encoding::EncodingRef;
use csspar... | <'a>(rules: &[CSSRule], device: &media_queries::Device,
callback: |&StyleRule|) {
for rule in rules.iter() {
match *rule {
CSSStyleRule(ref rule) => callback(rule),
CSSMediaRule(ref rule) => if rule.media_queries.evaluate(device) {
iter_sty... | iter_style_rules | identifier_name |
stylesheets.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::iter::Iterator;
use std::ascii::StrAsciiExt;
use extra::url::Url;
use encoding::EncodingRef;
use csspar... | else {
next_state = STATE_NAMESPACES;
parse_namespace_rule(rule, &mut namespaces)
}
},
_ => {
next_state = STATE_BODY;
pars... | {
next_state = state;
log_css_error(
rule.location,
"@namespace must be before any rule but @charset and @import"
)
} | conditional_block |
stylesheets.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::iter::Iterator;
use std::ascii::StrAsciiExt;
use extra::url::Url;
use encoding::EncodingRef;
use csspar... | parse_nested_at_rule(lower_name, rule, &mut rules, &namespaces)
},
}
},
}
state = next_state;
}
Stylesheet{ rules: rules, namespaces: namespaces, encoding: encoding, base_url: base_url }
}... | next_state = STATE_BODY; | random_line_split |
attr.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::ToCss;
use parser::SelectorImpl;
use std::ascii::AsciiExt;
use std::fmt;
#[derive(Clone, Eq, Parti... | } | } | random_line_split |
attr.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::ToCss;
use parser::SelectorImpl;
use std::ascii::AsciiExt;
use std::fmt;
#[derive(Clone, Eq, Parti... | }
})
} else {
// any_str.contains("") == true,
// though these cases should be handled with *NeverMatches and never go here.
true
}
}
}
}
}
|
haystack_slice.eq_ignore_ascii_case(n_rest)
}
| conditional_block |
attr.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::ToCss;
use parser::SelectorImpl;
use std::ascii::AsciiExt;
use std::fmt;
#[derive(Clone, Eq, Parti... | }
AttrSelectorOperator::DashMatch => {
case.eq(e, s) || (
e.get(s.len()) == Some(&b'-') &&
case.eq(&e[..s.len()], s)
)
}
}
}
}
/// The definition of whitespace per CSS Selectors Level 3 § 4.
pub sta... | {
let e = element_attr_value.as_bytes();
let s = attr_selector_value.as_bytes();
let case = case_sensitivity;
match self {
AttrSelectorOperator::Equal => {
case.eq(e, s)
}
AttrSelectorOperator::Prefix => {
e.len() >= s.l... | identifier_body |
attr.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::ToCss;
use parser::SelectorImpl;
use std::ascii::AsciiExt;
use std::fmt;
#[derive(Clone, Eq, Parti... | <Impl: SelectorImpl> {
pub namespace: NamespaceConstraint<(Impl::NamespacePrefix, Impl::NamespaceUrl)>,
pub local_name: Impl::LocalName,
pub local_name_lower: Impl::LocalName,
pub operation: ParsedAttrSelectorOperation<Impl::AttrValue>,
pub never_matches: bool,
}
impl<Impl: SelectorImpl> AttrSelect... | AttrSelectorWithNamespace | identifier_name |
main.rs | #![feature(slice_patterns,convert)]
use std::collections::HashSet;
extern crate adventutils;
extern crate permutohedron;
#[derive(Clone)]
struct Entry {
pub subject: String,
pub other: String,
pub happiness: isize
}
fn main() {
let input = adventutils::read_input_file();
let mut entries : Vec<_>... | (line: &str) -> Entry {
let tokens : Vec<_> = line.split_whitespace().collect();
match tokens.as_slice() {
[ subject, "would", "gain", happiness, "happiness", "units", "by", "sitting", "next", "to", other ] => Entry {
subject: subject.into(),
other: other.trim_right_matches('.')... | parse_line | identifier_name |
main.rs | #![feature(slice_patterns,convert)]
use std::collections::HashSet;
| #[derive(Clone)]
struct Entry {
pub subject: String,
pub other: String,
pub happiness: isize
}
fn main() {
let input = adventutils::read_input_file();
let mut entries : Vec<_> = input.lines().map(&parse_line).collect();
let result = calculate_best_happiness(entries.clone());
println!("Part... | extern crate adventutils;
extern crate permutohedron;
| random_line_split |
gui.rs | // See LICENSE file for copyright and license details.
use std::collections::{HashMap};
use cgmath::{Vector3};
use common::types::{ZInt, Size2, ZFloat};
use zgl::types::{ScreenPos, MatId};
use zgl::shader::{Shader};
use zgl::font_stash::{FontStash};
use zgl::mesh::{Mesh};
use zgl::zgl::{Zgl};
#[derive(PartialEq, Eq, ... |
// TODO: context: &Context
pub fn draw(
&self,
zgl: &Zgl,
win_size: &Size2,
shader: &Shader,
mvp_mat_id: &MatId,
) {
let m = zgl.get_2d_screen_matrix(win_size);
for (_, button) in self.buttons() {
let text_offset = Vector3 {
... | {
let x = mouse_pos.v.x;
let y = win_size.h - mouse_pos.v.y;
for (id, button) in self.buttons() {
if x >= button.pos().v.x
&& x <= button.pos().v.x + button.size().w
&& y >= button.pos().v.y
&& y <= button.pos().v.y + button.size().h
... | identifier_body |
gui.rs | // See LICENSE file for copyright and license details.
use std::collections::{HashMap};
use cgmath::{Vector3};
use common::types::{ZInt, Size2, ZFloat};
use zgl::types::{ScreenPos, MatId};
use zgl::shader::{Shader};
use zgl::font_stash::{FontStash};
use zgl::mesh::{Mesh};
use zgl::zgl::{Zgl};
#[derive(PartialEq, Eq, ... | (
zgl: &Zgl,
win_size: &Size2,
label: &str,
font_stash: &mut FontStash,
pos: ScreenPos,
) -> Button {
let text_size = (win_size.h as ZFloat) / 400.0; // TODO: 400?
let (_, size) = font_stash.get_text_size(zgl, label);
Button {
pos: pos,
... | new | identifier_name |
gui.rs | // See LICENSE file for copyright and license details.
use std::collections::{HashMap};
use cgmath::{Vector3};
use common::types::{ZInt, Size2, ZFloat};
use zgl::types::{ScreenPos, MatId};
use zgl::shader::{Shader};
use zgl::font_stash::{FontStash};
use zgl::mesh::{Mesh};
use zgl::zgl::{Zgl};
#[derive(PartialEq, Eq, ... | }
// TODO: context: &Context
pub fn get_clicked_button_id(
&self,
mouse_pos: &ScreenPos,
win_size: &Size2,
) -> Option<ButtonId> {
let x = mouse_pos.v.x;
let y = win_size.h - mouse_pos.v.y;
for (id, button) in self.buttons() {
if x >= button.p... | self.last_id.id += 1;
id | random_line_split |
gui.rs | // See LICENSE file for copyright and license details.
use std::collections::{HashMap};
use cgmath::{Vector3};
use common::types::{ZInt, Size2, ZFloat};
use zgl::types::{ScreenPos, MatId};
use zgl::shader::{Shader};
use zgl::font_stash::{FontStash};
use zgl::mesh::{Mesh};
use zgl::zgl::{Zgl};
#[derive(PartialEq, Eq, ... |
}
None
}
// TODO: context: &Context
pub fn draw(
&self,
zgl: &Zgl,
win_size: &Size2,
shader: &Shader,
mvp_mat_id: &MatId,
) {
let m = zgl.get_2d_screen_matrix(win_size);
for (_, button) in self.buttons() {
let text_off... | {
return Some(id.clone());
} | conditional_block |
args.rs | // Copyright (c) 2018 Jason White
//
// 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, copy, modify, merge, publish, d... | writeln!(&mut stdout, "{}", error.backtrace())?;
Ok(())
}
impl Args {
// Delegate to a subcommand. If any errors occur, print out the error and
// its chain of causes.
pub fn main(self) -> i32 {
if let Err(error) = self.cmd.main(&self.global) {
let _ = display_error(error, self... | writeln!(&mut stdout, ": {}", cause)?;
}
| random_line_split |
args.rs | // Copyright (c) 2018 Jason White
//
// 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, copy, modify, merge, publish, d... | else {
0
}
}
}
| {
let _ = display_error(error, self.global.color);
1
} | conditional_block |
args.rs | // Copyright (c) 2018 Jason White
//
// 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, copy, modify, merge, publish, d... | (self) -> i32 {
if let Err(error) = self.cmd.main(&self.global) {
let _ = display_error(error, self.global.color);
1
} else {
0
}
}
}
| main | identifier_name |
mod.rs | #![cfg(feature = "window")]
#[phase(plugin)]
extern crate gl_generator;
use glutin;
#[cfg(not(target_os = "android"))]
mod gl {
generate_gl_bindings! {
api: "gl",
profile: "core",
version: "1.1",
generator: "struct"
}
}
#[cfg(target_os = "android")]
mod gl {
pub use self:... | self.gl.Vertex2f(0.0, 0.5);
self.gl.Color3f(0.0, 0.0, 1.0);
self.gl.Vertex2f(0.5, -0.5);
self.gl.End();
}
#[cfg(target_os = "android")]
pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
self.gl.ClearColor(color.0, color.1, color.2, color.3);
self.gl.Cle... | self.gl.Color3f(0.0, 1.0, 0.0); | random_line_split |
mod.rs | #![cfg(feature = "window")]
#[phase(plugin)]
extern crate gl_generator;
use glutin;
#[cfg(not(target_os = "android"))]
mod gl {
generate_gl_bindings! {
api: "gl",
profile: "core",
version: "1.1",
generator: "struct"
}
}
#[cfg(target_os = "android")]
mod gl {
pub use self:... |
}
#[cfg(target_os = "android")]
static VERTEX_DATA: [f32,..15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0
];
| {
self.gl.ClearColor(color.0, color.1, color.2, color.3);
self.gl.Clear(gl::COLOR_BUFFER_BIT);
self.gl.EnableClientState(gl::VERTEX_ARRAY);
self.gl.EnableClientState(gl::COLOR_ARRAY);
unsafe {
use std::mem;
self.gl.VertexPointer(2, gl::FLOAT, (mem::size_... | identifier_body |
mod.rs | #![cfg(feature = "window")]
#[phase(plugin)]
extern crate gl_generator;
use glutin;
#[cfg(not(target_os = "android"))]
mod gl {
generate_gl_bindings! {
api: "gl",
profile: "core",
version: "1.1",
generator: "struct"
}
}
#[cfg(target_os = "android")]
mod gl {
pub use self:... | (window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|symbol| window.get_proc_address(symbol));
let version = {
use std::c_str::CString;
unsafe { CString::new(gl.GetString(gl::VERSION) as *const i8, false) }
};
println!("OpenGL version {}", version.as_str().unwrap());
... | load | identifier_name |
array_const_index-1.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
const ARR: [i32; 6] = [42, 43, 44, 45, 46, 47];
const IDX: usize = 3;
const VAL: i32 = ARR[IDX];
const BLUB: [i32; (ARR[0] - 41) as usize] = [5];
}
| main | identifier_name |
array_const_index-1.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
const ARR: [i32; 6] = [42, 43, 44, 45, 46, 47];
const IDX: usize = 3;
const VAL: i32 = ARR[IDX];
const BLUB: [i32; (ARR[0] - 41) as usize] = [5];
} | identifier_body | |
array_const_index-1.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() {
const ARR: [i32; 6] = [42, 43, 44, 45, 46, 47];
const IDX: usize = 3;
const VAL: i32 = ARR[IDX];
const BLUB: [i32; (ARR[0] - 41) as usize] = [5];
} | #![allow(dead_code)]
#![allow(stable_features)]
#![feature(const_indexing)]
| random_line_split |
callback.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::call::server::{RequestContext, UnaryRequestContext};
use crate::call::{BatchContext, Call};
use crate::cq::CompletionQueue;
use crate::server::{self, RequestCallContext};
pub struct Request {
ctx: RequestContext,
}
impl Request {
p... |
}
pub struct UnaryRequest {
ctx: UnaryRequestContext,
}
impl UnaryRequest {
pub fn new(ctx: RequestContext, rc: RequestCallContext) -> UnaryRequest {
let ctx = UnaryRequestContext::new(ctx, rc);
UnaryRequest { ctx }
}
pub fn batch_ctx(&self) -> &BatchContext {
self.ctx.batch_... | {
let mut rc = self.ctx.take_request_call_context().unwrap();
if !success {
server::request_call(rc, cq);
return;
}
match self.ctx.handle_stream_req(cq, &mut rc) {
Ok(_) => server::request_call(rc, cq),
Err(ctx) => ctx.handle_unary_req(rc,... | identifier_body |
callback.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::call::server::{RequestContext, UnaryRequestContext};
use crate::call::{BatchContext, Call};
use crate::cq::CompletionQueue;
use crate::server::{self, RequestCallContext};
pub struct Request {
ctx: RequestContext,
}
impl Request {
p... | }
match self.ctx.handle_stream_req(cq, &mut rc) {
Ok(_) => server::request_call(rc, cq),
Err(ctx) => ctx.handle_unary_req(rc, cq),
}
}
}
pub struct UnaryRequest {
ctx: UnaryRequestContext,
}
impl UnaryRequest {
pub fn new(ctx: RequestContext, rc: RequestCal... | pub fn resolve(mut self, cq: &CompletionQueue, success: bool) {
let mut rc = self.ctx.take_request_call_context().unwrap();
if !success {
server::request_call(rc, cq);
return; | random_line_split |
callback.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::call::server::{RequestContext, UnaryRequestContext};
use crate::call::{BatchContext, Call};
use crate::cq::CompletionQueue;
use crate::server::{self, RequestCallContext};
pub struct Request {
ctx: RequestContext,
}
impl Request {
p... | (&self) -> &BatchContext {
self.ctx.batch_ctx()
}
pub fn request_ctx(&self) -> &RequestContext {
self.ctx.request_ctx()
}
pub fn resolve(mut self, cq: &CompletionQueue, success: bool) {
let mut rc = self.ctx.take_request_call_context().unwrap();
if!success {
... | batch_ctx | identifier_name |
lib.rs | // 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.
#![feature(asm)]
#!... | pub mod curve25519;
pub mod digest;
pub mod ed25519;
pub mod fortuna;
pub mod ghash;
pub mod hmac;
pub mod mac;
pub mod md5;
pub mod pbkdf2;
pub mod poly1305;
pub mod rc4;
pub mod ripemd160;
pub mod salsa20;
pub mod scrypt;
pub mod sha1;
pub mod sha2;
pub mod symmetriccipher;
pub mod util;
#[cfg(any(target_arch = "x86... | mod cryptoutil; | random_line_split |
specialization_graph.rs | use crate::ich::{self, StableHashingContext};
use crate::ty::fast_reject::SimplifiedType;
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_hir::def_... |
pub fn def_id(&self) -> DefId {
match *self {
Node::Impl(did) => did,
Node::Trait(did) => did,
}
}
}
#[derive(Copy, Clone)]
pub struct Ancestors<'tcx> {
trait_def_id: DefId,
specialization_graph: &'tcx Graph,
current_source: Option<Node>,
}
impl Iterator f... | {
tcx.associated_items(self.def_id())
.filter_by_name_unhygienic(trait_item_name.name)
.find(move |impl_item| {
trait_item_kind == impl_item.kind
&& tcx.hygienic_eq(impl_item.ident, trait_item_name, trait_def_id)
})
.copied()
... | identifier_body |
specialization_graph.rs | use crate::ich::{self, StableHashingContext};
use crate::ty::fast_reject::SimplifiedType;
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_hir::def_... |
Some(LeafDef { item, defining_node: node, finalizing_node })
} else {
// Item not mentioned. This "finalizes" any defaulted item provided by an ancestor.
finalizing_node = Some(node);
None
}
})
}
}
/// Walk up the spe... | {
let is_specializable = item.defaultness.is_default()
|| tcx.impl_defaultness(node.def_id()).is_default();
if !is_specializable {
finalizing_node = Some(node);
}
} | conditional_block |
specialization_graph.rs | use crate::ich::{self, StableHashingContext};
use crate::ty::fast_reject::SimplifiedType;
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_hir::def_... | (
&self,
tcx: TyCtxt<'tcx>,
trait_item_name: Ident,
trait_item_kind: ty::AssocKind,
trait_def_id: DefId,
) -> Option<ty::AssocItem> {
tcx.associated_items(self.def_id())
.filter_by_name_unhygienic(trait_item_name.name)
.find(move |impl_item| {
... | item | identifier_name |
specialization_graph.rs | use crate::ich::{self, StableHashingContext};
use crate::ty::fast_reject::SimplifiedType;
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_hir::def_... |
impl LeafDef {
/// Returns whether this definition is known to not be further specializable.
pub fn is_final(&self) -> bool {
self.finalizing_node.is_some()
}
}
impl<'tcx> Ancestors<'tcx> {
/// Finds the bottom-most (ie. most specialized) definition of an associated
/// item.
pub fn le... | /// `None`, since the most specialized impl we found still allows overriding the method
/// (doesn't finalize it).
pub finalizing_node: Option<Node>,
} | random_line_split |
main.rs | //! This expands upon the implementation defined on [Rosetta Code][element definition] and consists
//! of the relevant lines from the `LinkedList` implementation in the Rust standard library.
//!
//! [element definition]: http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
#![allow(dead_code)]
use std:... |
pub struct LinkedList<T> {
length: usize,
list_head: Link<T>,
list_tail: Rawlink<Node<T>>,
}
type Link<T> = Option<Box<Node<T>>>;
struct Rawlink<T> {
p: *mut T,
}
struct Node<T> {
next: Link<T>,
prev: Rawlink<Node<T>>,
value: T,
}
impl<T> Node<T> {
fn new(v: T) -> Node<T> {
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.