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 |
|---|---|---|---|---|
state.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::async_client::JsonRpcResponse;
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct State {
pub chain_id: u8,
pub version: u64,
pub timestamp_usecs: u64,
}
impl State {
pub fn from_response(resp: &JsonR... | {
last_known_state: std::sync::RwLock<Option<State>>,
}
impl Default for StateManager {
fn default() -> Self {
Self {
last_known_state: std::sync::RwLock::new(None),
}
}
}
impl StateManager {
pub fn new() -> Self {
Self::default()
}
pub fn last_known_state... | StateManager | identifier_name |
decf.rs | //! formatter for %g %G decimal subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
fn get_len_fprim(fprim: &FormatPrimitive) -> usize {
let mut len = 0;
if l... |
}
| {
primitive_to_str_common(prim, &field)
} | identifier_body |
decf.rs | //! formatter for %g %G decimal subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
fn get_len_fprim(fprim: &FormatPrimitive) -> usize {
let mut len = 0;
if l... | () -> Decf {
Decf { as_num: 0.0 }
}
}
impl Formatter for Decf {
fn get_primitive(&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str)
-> Option<FormatPrimitive> {
let second_field = field.second_field.u... | new | identifier_name |
decf.rs | //! formatter for %g %G decimal subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
fn get_len_fprim(fprim: &FormatPrimitive) -> usize {
let mut len = 0;
if l... | )
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
| {
f_fl
} | conditional_block |
decf.rs | //! formatter for %g %G decimal subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
fn get_len_fprim(fprim: &FormatPrimitive) -> usize {
let mut len = 0;
if l... | }
impl Formatter for Decf {
fn get_primitive(&self,
field: &FormatField,
inprefix: &InPrefix,
str_in: &str)
-> Option<FormatPrimitive> {
let second_field = field.second_field.unwrap_or(6) + 1;
// default to scif inte... | random_line_split | |
area_frame_allocator.rs | use memory::{Frame, FrameAllocator};
use multiboot2::{MemoryAreaIter, MemoryArea};
pub struct AreaFrameAllocator {
next_free_frame: Frame,
current_area: Option<&'static MemoryArea>,
areas: MemoryAreaIter,
kernel_start: Frame,
kernel_end: Frame,
multiboot_start: Frame,
multiboot_end: Frame,
... | // the frame was not valid. try to allocate again.
self.allocate_frame()
}
else {
None // no free frames left
}
}
fn deallocate_frame(&mut self, frame: Frame) {
// not implemented yet :(
unimplemented!()
}
}
| { // if we have free frames left
let frame = Frame { number: self.next_free_frame.number };
let last_frame_of_area = Frame::containing_address((area.base_addr + area.length - 1) as usize);
if frame > last_frame_of_area {
// we've used the current area up - jump to n... | conditional_block |
area_frame_allocator.rs | use memory::{Frame, FrameAllocator};
use multiboot2::{MemoryAreaIter, MemoryArea};
pub struct AreaFrameAllocator {
next_free_frame: Frame,
current_area: Option<&'static MemoryArea>,
areas: MemoryAreaIter,
kernel_start: Frame,
kernel_end: Frame,
multiboot_start: Frame,
multiboot_end: Frame,
... | allocator
}
fn jump_to_next_area(&mut self) {
self.current_area = self.areas.clone().filter(|area| {
let address = area.base_addr + area.length - 1;
Frame::containing_address(address as usize) >= self.next_free_frame
}).min_by_key(|area| area.base_addr);
... | multiboot_start: Frame::containing_address(multiboot_start),
multiboot_end: Frame::containing_address(multiboot_end),
};
allocator.jump_to_next_area(); | random_line_split |
area_frame_allocator.rs | use memory::{Frame, FrameAllocator};
use multiboot2::{MemoryAreaIter, MemoryArea};
pub struct AreaFrameAllocator {
next_free_frame: Frame,
current_area: Option<&'static MemoryArea>,
areas: MemoryAreaIter,
kernel_start: Frame,
kernel_end: Frame,
multiboot_start: Frame,
multiboot_end: Frame,
... |
}
| {
// not implemented yet :(
unimplemented!()
} | identifier_body |
area_frame_allocator.rs | use memory::{Frame, FrameAllocator};
use multiboot2::{MemoryAreaIter, MemoryArea};
pub struct | {
next_free_frame: Frame,
current_area: Option<&'static MemoryArea>,
areas: MemoryAreaIter,
kernel_start: Frame,
kernel_end: Frame,
multiboot_start: Frame,
multiboot_end: Frame,
}
impl AreaFrameAllocator {
pub fn new(kernel_start: usize, kernel_end: usize,
multiboot_start: usiz... | AreaFrameAllocator | identifier_name |
fmt.rs | use std::fmt;
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::Colour::{Red, Green, Yellow};
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::ANSIString;
#[allow(dead_code)]
pub enum Format<T> {
Error(T),
Warning(T),
Good(T),
}
#[cfg(all(feature = "col... | else {
debugln!("There was not a separator");
s
}
} | {
debugln!("There was a separator {}", sep);
let mut ins_sep = s.len() % 3;
ins_sep = if ins_sep == 0 { 3 } else {ins_sep};
let mut ret = vec![];
for (i, c) in s.chars().enumerate() {
debugln!("iter; c={}; ins_sep={}; ret={:?}", c, ins_sep, ret);
if ins_se... | conditional_block |
fmt.rs | use std::fmt;
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::Colour::{Red, Green, Yellow};
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::ANSIString;
#[allow(dead_code)]
pub enum | <T> {
Error(T),
Warning(T),
Good(T),
}
#[cfg(all(feature = "color", not(target_os = "windows")))]
impl<T: AsRef<str>> Format<T> {
fn format(&self) -> ANSIString {
match *self {
Format::Error(ref e) => Red.bold().paint(e.as_ref()),
Format::Warning(ref e) => Yellow.pain... | Format | identifier_name |
fmt.rs | use std::fmt;
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::Colour::{Red, Green, Yellow};
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::ANSIString;
#[allow(dead_code)]
pub enum Format<T> {
Error(T),
Warning(T),
Good(T),
}
#[cfg(all(feature = "col... |
}
#[cfg(all(feature = "color", not(target_os = "windows")))]
impl<T: AsRef<str>> fmt::Display for Format<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.format())
}
}
#[cfg(any(not(feature = "color"), target_os = "windows"))]
impl<T: fmt::Display> Format<T> {
fn... | {
match *self {
Format::Error(ref e) => Red.bold().paint(e.as_ref()),
Format::Warning(ref e) => Yellow.paint(e.as_ref()),
Format::Good(ref e) => Green.paint(e.as_ref()),
}
} | identifier_body |
fmt.rs | use std::fmt;
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::Colour::{Red, Green, Yellow};
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::ANSIString;
#[allow(dead_code)]
pub enum Format<T> {
Error(T),
Warning(T),
Good(T),
}
#[cfg(all(feature = "col... | debugln!("iter; c={}; ins_sep={}; ret={:?}", c, ins_sep, ret);
if ins_sep == 0 && i!= 0 {
debugln!("Inserting the separator");
ret.push(sep);
ins_sep = 3;
}
ret.push(c);
ins_sep -= 1;
}
debugln!("... | ins_sep = if ins_sep == 0 { 3 } else {ins_sep};
let mut ret = vec![];
for (i, c) in s.chars().enumerate() { | random_line_split |
lib.rs | // Copyright 2015 Hugo Duncan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | //! }
//! }
//!
//! fn start_iron() -> Listening {
//! Iron::new(Resource).listen((address,0u16)).unwrap();
//! }
//! ```
#[macro_use] extern crate hyper;
extern crate iron;
extern crate mime;
extern crate time;
#[macro_use] extern crate log;
pub use hyper_headers::*;
pub use resource::{Resource, ResourceError,... | //! fn handle_ok(&self, req: &Request, resp: &mut Response)
//! -> IronResult<Response>
//! {
//! resp.set_mut((status::Ok, "hello"));
//! Ok(Response::new()) | random_line_split |
json.rs | #[derive(Debug, Deserialize)]
/// A user object returned from the API
pub struct User{
/// The username of the user
pub username: String
}
#[derive(Debug, Deserialize)]
/// An object containing the ID of something newly created
pub struct Id<T>
{
/// The ID
pub id: T
}
#[derive(Debug, Deserialize)]
#[... | #[serde(rename="type")]
pub code: u16,
} | pub description: String,
/// Its errorcode | random_line_split |
json.rs | #[derive(Debug, Deserialize)]
/// A user object returned from the API
pub struct User{
/// The username of the user
pub username: String
}
#[derive(Debug, Deserialize)]
/// An object containing the ID of something newly created
pub struct Id<T>
{
/// The ID
pub id: T
}
#[derive(Debug, Deserialize)]
#[... | {
/// The URI the error happened on
pub address: String,
/// A short description of the error
pub description: String,
/// Its errorcode
#[serde(rename="type")]
pub code: u16,
}
| Error | identifier_name |
static-impl.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 ... | (&self) -> ~str { self.to_str() }
fn multi(&self, f: |uint|) {
let mut c = 0u;
while c < *self { f(c); c += 1u; }
}
}
trait vec_utils<T> {
fn length_(&self, ) -> uint;
fn iter_(&self, f: |&T|);
fn map_<U>(&self, f: |&T| -> U) -> ~[U];
}
impl<T> vec_utils<T> for ~[T] {
fn length... | str | identifier_name |
static-impl.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 ... | }
}
mod b {
use plus;
impl plus for ~str { fn plus(&self) -> int { 200 } }
}
trait uint_utils {
fn str(&self) -> ~str;
fn multi(&self, f: |uint|);
}
impl uint_utils for uint {
fn str(&self) -> ~str { self.to_str() }
fn multi(&self, f: |uint|) {
let mut c = 0u;
while c < *self... | { *self as int + 20 } | identifier_body |
static-impl.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_eq!(10u.plus(), 30);
assert_eq!((~"hi").plus(), 200);
assert_eq!((~[1]).length_().str(), ~"1");
assert_eq!((~[3, 4]).map_(|a| *a + 4 )[0], 7);
assert_eq!((~[3, 4]).map_::<uint>(|a| *a as uint + 4u )[0], 7u);
let mut x = 0u;
10u.multi(|_n| x += 2u );
assert_eq!(x, 20u);
} | r
}
}
pub fn main() { | random_line_split |
render_mode.rs | use std::collections::BTreeMap;
use error::{Error, ResultExt};
use types::{
CCode, CTree, Chord, ChordSpec, Field, KmapOrder, KmapPath, ModeInfo,
ModeName, ToC,
};
use util::usize_to_u8;
pub struct ModeBuilder<'a> {
pub mode_name: &'a ModeName,
pub info: &'a ModeInfo,
pub kmap_struct_names: &'a B... | (&self) -> Result<(CTree, CCode), Error> {
self.render_chord_array_helper(&self.mod_chords, &"mod_chord".to_c())
}
fn render_chord_array_helper(
&self,
chords: &[Chord<KmapOrder>],
label: &CCode,
) -> Result<(CTree, CCode), Error> {
// TODO share code with stuff in k... | render_modifier_array | identifier_name |
render_mode.rs | use std::collections::BTreeMap;
use error::{Error, ResultExt};
use types::{
CCode, CTree, Chord, ChordSpec, Field, KmapOrder, KmapPath, ModeInfo,
ModeName, ToC,
};
use util::usize_to_u8;
pub struct ModeBuilder<'a> {
pub mode_name: &'a ModeName,
pub info: &'a ModeInfo,
pub kmap_struct_names: &'a B... | fn render_modifier_array(&self) -> Result<(CTree, CCode), Error> {
self.render_chord_array_helper(&self.mod_chords, &"mod_chord".to_c())
}
fn render_chord_array_helper(
&self,
chords: &[Chord<KmapOrder>],
label: &CCode,
) -> Result<(CTree, CCode), Error> {
// TOD... | random_line_split | |
render_mode.rs | use std::collections::BTreeMap;
use error::{Error, ResultExt};
use types::{
CCode, CTree, Chord, ChordSpec, Field, KmapOrder, KmapPath, ModeInfo,
ModeName, ToC,
};
use util::usize_to_u8;
pub struct ModeBuilder<'a> {
pub mode_name: &'a ModeName,
pub info: &'a ModeInfo,
pub kmap_struct_names: &'a B... | c_type: "KmapStruct*".to_c(),
is_extern: false,
});
Ok((CTree::Group(g), array_name, contents.len()))
}
fn render_anagram_mask(&self) -> Result<(CTree, CCode), Error> {
let array_name_out = format!("{}_anagram_mask", self.mode_name).to_c();
let tree = C... | {
let mut g = Vec::new();
let array_name = format!("{}_kmaps_array", self.mode_name).to_c();
let contents: Vec<_> = self
.info
.keymaps
.iter()
.map(|info| {
self.kmap_struct_names
.get(&info.file)
... | identifier_body |
simple.rs | use std::collections::HashMap;
use unshare::{Command, Fd};
use crate::config::command::{CommandInfo, WriteMode};
use crate::launcher::{Context, socket};
use crate::launcher::options::{ArgError, parse_docopts};
use crate::launcher::volumes::prepare_volumes;
use crate::process_util::{run_and_wait, convert_status};
use... | (cinfo: &CommandInfo, _context: &Context,
cmd: String, args: Vec<String>)
-> Result<Args, ArgError>
{
if let Some(_) = cinfo.network {
return Err(ArgError::Error(format!(
"Network is not supported for!Command use!Supervise")));
}
if let Some(ref opttext) = cinfo.options {
... | parse_args | identifier_name |
simple.rs | use std::collections::HashMap;
use unshare::{Command, Fd};
use crate::config::command::{CommandInfo, WriteMode};
use crate::launcher::{Context, socket};
use crate::launcher::options::{ArgError, parse_docopts};
use crate::launcher::volumes::prepare_volumes;
use crate::process_util::{run_and_wait, convert_status};
use... | environ: HashMap<String, String>,
}
pub fn parse_args(cinfo: &CommandInfo, _context: &Context,
cmd: String, args: Vec<String>)
-> Result<Args, ArgError>
{
if let Some(_) = cinfo.network {
return Err(ArgError::Error(format!(
"Network is not supported for!Command use!Supervise")));
... | cmdname: String,
args: Vec<String>, | random_line_split |
simple.rs | use std::collections::HashMap;
use unshare::{Command, Fd};
use crate::config::command::{CommandInfo, WriteMode};
use crate::launcher::{Context, socket};
use crate::launcher::options::{ArgError, parse_docopts};
use crate::launcher::volumes::prepare_volumes;
use crate::process_util::{run_and_wait, convert_status};
use... | }
}
pub fn prepare_containers(cinfo: &CommandInfo, _: &Args, context: &Context)
-> Result<Version, String>
{
let ver = build_container(context, &cinfo.container,
context.build_mode, false)?;
let cont = context.config.containers.get(&cinfo.container)
.ok_or_else(|| format!("Container {:?... | {
if let Some(_) = cinfo.network {
return Err(ArgError::Error(format!(
"Network is not supported for !Command use !Supervise")));
}
if let Some(ref opttext) = cinfo.options {
let (env, _) = parse_docopts(&cinfo.description, opttext,
DEFAU... | identifier_body |
simple.rs | use std::collections::HashMap;
use unshare::{Command, Fd};
use crate::config::command::{CommandInfo, WriteMode};
use crate::launcher::{Context, socket};
use crate::launcher::options::{ArgError, parse_docopts};
use crate::launcher::volumes::prepare_volumes;
use crate::process_util::{run_and_wait, convert_status};
use... |
}
return res;
}
| {
print!("{}", epilog);
} | conditional_block |
background.rs | use std::rc::Rc;
use glium::{Program, Display, VertexBuffer, Surface};
use glium::texture::Texture2d;
use glium::framebuffer::SimpleFrameBuffer;
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
use ffmpeg::frame;
use renderer::{Render, Support};
use renderer::background::{Video, Visualize... |
}
| {
self.texture.clone()
} | identifier_body |
background.rs | use std::rc::Rc;
use glium::{Program, Display, VertexBuffer, Surface};
use glium::texture::Texture2d;
use glium::framebuffer::SimpleFrameBuffer;
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
use ffmpeg::frame;
use renderer::{Render, Support};
use renderer::background::{Video, Visualize... | <'b>(display: &'b Display) -> Background<'b> {
Background {
display: display,
video: Video::new(display),
visualizer: Visualizer::new(display),
program: program!(display,
100 => {
vertex: "
#version 100
precision lowp float;
attribute vec2 position;
attribute vec2... | new | identifier_name |
background.rs | use std::rc::Rc;
use glium::{Program, Display, VertexBuffer, Surface};
use glium::texture::Texture2d;
use glium::framebuffer::SimpleFrameBuffer;
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
use ffmpeg::frame;
use renderer::{Render, Support};
use renderer::background::{Video, Visualize... |
}
// draw the internal texture to video
let uniforms = uniform! {
tex: &*self.texture,
};
target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &Default::default()).unwrap();
}
pub fn texture(&self) -> Rc<Texture2d> {
self.texture.clone()
}
}
| {
self.visualizer.render(&mut surface, support, state);
} | conditional_block |
background.rs | use std::rc::Rc;
use glium::{Program, Display, VertexBuffer, Surface};
use glium::texture::Texture2d;
use glium::framebuffer::SimpleFrameBuffer;
use glium::index::NoIndices;
use glium::index::PrimitiveType::TriangleStrip;
use ffmpeg::frame;
use renderer::{Render, Support};
use renderer::background::{Video, Visualize... | } | self.texture.clone()
} | random_line_split |
graphviz.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 ... | (&self) -> dot::Nodes<'a, Node<'a>> {
let mut v = Vec::new();
self.graph.each_node(|i, nd| { v.push((i, nd)); true });
dot::maybe_owned_vec::Growable(v)
}
fn edges(&self) -> dot::Edges<'a, Edge<'a>> {
self.graph.all_edges().iter().collect()
}
fn source(&self, edge: &Edge<... | nodes | identifier_name |
graphviz.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 target(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.target(edge) }
}
| { self.cfg.source(edge) } | identifier_body |
graphviz.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 ... |
s.to_string()
} else {
s
}
}
impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> {
fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.as_slice()) }
fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> {
dot::Id::new(format!("N{:u}", i.node_id()))
... | {
s = s.append("\\l");
} | conditional_block |
graphviz.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> dot::GraphWalk<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a>
{
fn nodes(&self) -> dot::Nodes<'a, Node<'a>> { self.cfg.nodes() }
fn edges(&self) -> dot::Edges<'a, Edge<'a>> { self.cfg.edges() }
fn source(&self, edge: &Edge<'a>) -> Node<'a> { self.cfg.source(edge) }
fn target(&self, edge: &Edge<... | } | random_line_split |
refptr.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::marker::PhantomData;
use std::mem::{forget, transmute};
use std::ptr;
use std::sync::Arc;
/// Helper tra... | () -> Strong<Self::FFIType> {
unsafe { transmute(ptr::null::<Self::FFIType>()) }
}
}
#[repr(C)]
/// Gecko-FFI-safe borrowed Arc (&T where T is an ArcInner).
/// This can be null.
pub struct Borrowed<'a, T: 'a> {
ptr: *const T,
_marker: PhantomData<&'a T>,
}
// manual impls because derive doesn't r... | null_strong | identifier_name |
refptr.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::marker::PhantomData;
use std::mem::{forget, transmute};
use std::ptr;
use std::sync::Arc;
/// Helper tra... |
}
| {
self.ptr == ptr::null()
} | identifier_body |
refptr.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::marker::PhantomData;
use std::mem::{forget, transmute};
use std::ptr;
use std::sync::Arc;
/// Helper tra... |
}
}
/// Converts an Arc into a strong FFI reference.
fn from_arc(owned: Arc<Self>) -> Strong<Self::FFIType> {
unsafe { transmute(owned) }
}
/// Artificially increments the refcount of a borrowed Arc over FFI.
unsafe fn addref(ptr: Borrowed<Self::FFIType>) {
Self::with(... | {
Some(transmute::<&Borrowed<_>, &Arc<_>>(ptr))
} | conditional_block |
refptr.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::marker::PhantomData;
use std::mem::{forget, transmute};
use std::ptr;
use std::sync::Arc;
/// Helper tra... | }
} | impl<T> Strong<T> {
pub fn is_null(&self) -> bool {
self.ptr == ptr::null() | random_line_split |
disk.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use crate::sys::{ffi, utils};
use crate::utils::to_cpath;
use crate::{Disk, DiskType};
use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease};
use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent,... |
vec.push(*x as u8);
}
file_system = Some(vec);
}
if total_space == 0 {
return None;
}
Some(Disk {
type_,
name,
file_system: file_system.unwrap_or_else(|| b"<Unknown>".to_vec()),
mount_poi... | {
break;
} | conditional_block |
disk.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use crate::sys::{ffi, utils};
use crate::utils::to_cpath;
use crate::{Disk, DiskType};
use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease};
use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent,... | (dict: CFDictionaryRef, key: &[u8]) -> Option<bool> {
get_dict_value(dict, key, |v| Some(v as CFBooleanRef == kCFBooleanTrue))
}
fn new_disk(
name: OsString,
mount_point: PathBuf,
type_: DiskType,
is_removable: bool,
) -> Option<Disk> {
let mount_point_cpath = to_cpath(&mount_point);
let mu... | get_bool_value | identifier_name |
disk.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use crate::sys::{ffi, utils};
use crate::utils::to_cpath;
use crate::{Disk, DiskType};
use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease};
use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent,... |
unsafe fn get_bool_value(dict: CFDictionaryRef, key: &[u8]) -> Option<bool> {
get_dict_value(dict, key, |v| Some(v as CFBooleanRef == kCFBooleanTrue))
}
fn new_disk(
name: OsString,
mount_point: PathBuf,
type_: DiskType,
is_removable: bool,
) -> Option<Disk> {
let mount_point_cpath = to_cpath... | {
get_dict_value(dict, key, |v| {
let v = v as cfs::CFStringRef;
let len = cfs::CFStringGetLength(v);
utils::cstr_to_rust_with_size(
cfs::CFStringGetCStringPtr(v, cfs::kCFStringEncodingUTF8),
Some(len as _),
)
})
} | identifier_body |
disk.rs | // Take a look at the license at the top of the repository in the LICENSE file.
use crate::sys::{ffi, utils};
use crate::utils::to_cpath;
use crate::{Disk, DiskType};
use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease};
use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent,... | DiskType::Unknown(-1)
};
CFRelease(dict as _);
new_disk(name, mount_point, type_, removable || ejectable)
})
.collect::<Vec<_>>()
}
}
unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>(
dict: CFDictionar... | } else {
// We just assume by default that this is a HDD
DiskType::HDD
}
} else { | random_line_split |
lib.rs | extern crate base64;
extern crate bincode;
extern crate bytes;
extern crate byteorder;
extern crate chan;
extern crate chrono;
extern crate crossbeam;
extern crate crypto;
#[cfg(feature = "rvi")]
extern crate dbus;
extern crate hex;
extern crate hmac;
extern crate hyper;
extern crate itoa;
#[macro_use]
extern crate laz... | extern crate sha2;
extern crate tar;
extern crate time;
extern crate toml;
#[cfg(feature = "websocket")]
extern crate tungstenite;
#[cfg(feature = "socket")]
extern crate unix_socket;
extern crate untrusted;
extern crate url;
extern crate uuid;
pub mod atomic;
pub mod authenticate;
pub mod broadcast;
pub mod datatype;... | extern crate serde_json as json; | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces... | {
reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflecto... | identifier_body | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces... | (reg: &mut Registry) {
reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), MultiD... | plugin_registrar | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces... | reg.register_lint_pass(box lints::ban::BanPass as LintPassObject);
reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject);
} | reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject); | random_line_split |
lifetime.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 ... |
mc::cat_static_item => {
ty::ReStatic
}
mc::cat_local(local_id) |
mc::cat_arg(local_id) => {
ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id))
}
mc::cat_deref(_, _, mc::UnsafePtr(..)) => {
t... | {
ty::ReScope(self.item_scope_id)
} | conditional_block |
lifetime.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 ... | <'a> {
bccx: &'a BorrowckCtxt<'a>,
// the node id of the function body for the enclosing item
item_scope_id: ast::NodeId,
span: Span,
cause: euv::LoanCause,
loan_region: ty::Region,
cmt_original: mc::cmt
}
impl<'a> GuaranteeLifetimeContext<'a> {
fn check(&self, cmt: &mc::cmt, discr_s... | GuaranteeLifetimeContext | identifier_name |
lifetime.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 ... |
///////////////////////////////////////////////////////////////////////////
// Private
struct GuaranteeLifetimeContext<'a> {
bccx: &'a BorrowckCtxt<'a>,
// the node id of the function body for the enclosing item
item_scope_id: ast::NodeId,
span: Span,
cause: euv::LoanCause,
loan_region: ty:... | {
debug!("guarantee_lifetime(cmt={}, loan_region={})",
cmt.repr(bccx.tcx), loan_region.repr(bccx.tcx));
let ctxt = GuaranteeLifetimeContext {bccx: bccx,
item_scope_id: item_scope_id,
span: span,
... | identifier_body |
lifetime.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 ... | // basically a special kind of category that says "if this
// value must be dynamically rooted, root it for the scope
// `match_id`".
//
// As an example, consider this scenario:
//
// let mut x = @Some(3)... | random_line_split | |
borrowck-anon-fields-variant.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 same_variant() {
let mut y = Foo::Y(1, 2);
let a = match y {
Foo::Y(ref mut a, _) => a,
Foo::X => panic!()
};
let b = match y {
Foo::Y(ref mut b, _) => b, //~ ERROR cannot borrow
Foo::X => panic!()
};
*a += 1;
*b += 1;
}
fn main() {
}
| {
let mut y = Foo::Y(1, 2);
let a = match y {
Foo::Y(ref mut a, _) => a,
Foo::X => panic!()
};
let b = match y {
Foo::Y(_, ref mut b) => b,
Foo::X => panic!()
};
*a += 1;
*b += 1;
} | identifier_body |
borrowck-anon-fields-variant.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 ... | {
X, Y(uint, uint)
}
fn distinct_variant() {
let mut y = Foo::Y(1, 2);
let a = match y {
Foo::Y(ref mut a, _) => a,
Foo::X => panic!()
};
let b = match y {
Foo::Y(_, ref mut b) => b,
Foo::X => panic!()
};
*a += 1;
*b += 1;
}
fn same_variant() {
let mut y... | Foo | identifier_name |
borrowck-anon-fields-variant.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 distinct_variant() {
let mut y = Foo::Y(1, 2);
let a = match y {
Foo::Y(ref mut a, _) => a,
Foo::X => panic!()
};
let b = match y {
Foo::Y(_, ref mut b) => b,
Foo::X => panic!()
};
*a += 1;
*b += 1;
}
fn same_variant() {
let mut y = Foo::Y(1, 2);
le... | random_line_split | |
mod.rs | //! Loaders for osci memory images.
pub mod rawloader;
pub mod hexloader;
use std::{error, fmt, io, num, result};
use std::string::String;
#[derive(Debug)]
/// Error type for all loaders.
///
/// `LoadError` is just a union-type over a couple of built-in errors with the `From` trait implemented for each of them. This... | (msg: String) -> LoadError {
LoadError::Message(msg)
}
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Loading failed")
}
}
impl error::Error for LoadError {
fn description(&self) -> &str {
match self {
&LoadErro... | from_message | identifier_name |
mod.rs | //! Loaders for osci memory images.
pub mod rawloader;
pub mod hexloader;
use std::{error, fmt, io, num, result};
use std::string::String;
#[derive(Debug)]
/// Error type for all loaders.
///
/// `LoadError` is just a union-type over a couple of built-in errors with the `From` trait implemented for each of them. This... | }
impl LoadError {
pub fn new() -> LoadError {
LoadError::None
}
pub fn from_message(msg: String) -> LoadError {
LoadError::Message(msg)
}
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Loading failed")
}
}
impl e... | IoErr(io::Error),
ParseIntErr(num::ParseIntError),
FormatErr(fmt::Error),
Message(String), | random_line_split |
mod.rs | //! Loaders for osci memory images.
pub mod rawloader;
pub mod hexloader;
use std::{error, fmt, io, num, result};
use std::string::String;
#[derive(Debug)]
/// Error type for all loaders.
///
/// `LoadError` is just a union-type over a couple of built-in errors with the `From` trait implemented for each of them. This... |
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Loading failed")
}
}
impl error::Error for LoadError {
fn description(&self) -> &str {
match self {
&LoadError::None => &"Loading failed",
&LoadError::Message(ref ... | {
LoadError::Message(msg)
} | identifier_body |
grid.rs | pub struct Grid {
pub grid: [[bool;1000];1000]
}
impl Grid {
/// Turns on all lights from x,y through x,y in the grid.
pub fn turn_on(&mut self, start: [usize;2], stop: [usize;2]) {
for x in start[0]..stop[0]+1 {
for y in start[1]..stop[1]+1 {
self.grid[x][y] = true;
... | (&mut self, start: [usize;2], stop: [usize;2]) {
for x in start[0]..stop[0]+1 {
for y in start[1]..stop[1]+1 {
self.grid[x][y] =!self.grid[x][y];
}
}
}
/// Counts the total number of lights turned on in the grid.
pub fn turned_on_count(&self) -> usize... | toggle | identifier_name |
grid.rs | pub struct Grid {
pub grid: [[bool;1000];1000]
}
impl Grid {
/// Turns on all lights from x,y through x,y in the grid.
pub fn turn_on(&mut self, start: [usize;2], stop: [usize;2]) {
for x in start[0]..stop[0]+1 {
for y in start[1]..stop[1]+1 {
self.grid[x][y] = true;
... |
/// Counts the total number of lights turned on in the grid.
pub fn turned_on_count(&self) -> usize {
self.grid.iter().map(|column| column.iter().filter(|&x| *x == true).count())
.fold(0, |total, next| total + next)
}
}
| {
for x in start[0]..stop[0]+1 {
for y in start[1]..stop[1]+1 {
self.grid[x][y] = !self.grid[x][y];
}
}
} | identifier_body |
grid.rs | pub struct Grid {
pub grid: [[bool;1000];1000]
}
impl Grid {
/// Turns on all lights from x,y through x,y in the grid. | pub fn turn_on(&mut self, start: [usize;2], stop: [usize;2]) {
for x in start[0]..stop[0]+1 {
for y in start[1]..stop[1]+1 {
self.grid[x][y] = true;
}
}
}
/// Turns off all lights from x,y through x,y in the grid.
pub fn turn_off(&mut self, start:... | random_line_split | |
build.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | () {
vergen(OutputFns::all()).unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("rustc_version.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(
format!(
"
/// Returns compiler version.
pub fn rustc_version() -> &'s... | main | identifier_name |
build.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | extern crate rustc_version;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use vergen::*;
fn main() {
vergen(OutputFns::all()).unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("rustc_version.rs");
let mut f = File::create(&dest_p... | extern crate vergen; | random_line_split |
build.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
vergen(OutputFns::all()).unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("rustc_version.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(
format!(
"
/// Returns compiler version.
pub fn rustc_version() -> &'stat... | identifier_body | |
set_mana.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone, Debug)]
pub struct SetMana {
controller_uid: UID,
mana: u8,
}
implement_for_lua!(SetMana, |mut _metatable| {});
impl SetMana {
pub fn new(controller_ui... |
}
impl Rune for SetMana {
fn execute_rune(&self, game_state: &mut GameState) {
game_state.get_mut_controller_by_uid(self.controller_uid).unwrap().set_mana(self.mana);
}
fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool {
return true;
}
fn to_json(&self) -> Stri... | {
Box::new(self.clone())
} | identifier_body |
set_mana.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone, Debug)]
pub struct SetMana {
controller_uid: UID,
mana: u8,
}
implement_for_lua!(SetMana, |mut _metatable| {});
impl SetMana {
pub fn new(controller_ui... | mana: mana,
}
}
pub fn to_rune(&self) -> Box<Rune> {
Box::new(self.clone())
}
}
impl Rune for SetMana {
fn execute_rune(&self, game_state: &mut GameState) {
game_state.get_mut_controller_by_uid(self.controller_uid).unwrap().set_mana(self.mana);
}
fn can_se... | controller_uid: controller_uid, | random_line_split |
set_mana.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone, Debug)]
pub struct SetMana {
controller_uid: UID,
mana: u8,
}
implement_for_lua!(SetMana, |mut _metatable| {});
impl SetMana {
pub fn new(controller_ui... | (&self) -> String {
json::encode(self).unwrap().replace("{", "{\"runeType\":\"SetMana\",")
}
fn into_box(&self) -> Box<Rune> {
Box::new(self.clone())
}
}
| to_json | identifier_name |
audioclient.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,... | pdwFlags: *mut DWORD,
pu64DevicePosition: *mut UINT64,
pu64QPCPosition: *mut UINT64,
) -> HRESULT,
fn ReleaseBuffer(
NumFramesRead: UINT32,
) -> HRESULT,
fn GetNextPacketSize(
pNumFramesInNextPacket: *mut UINT32,
) -> HRESULT,
}} | interface IAudioCaptureClient(IAudioCaptureClientVtbl): IUnknown(IUnknownVtbl) {
fn GetBuffer(
ppData: *mut *mut BYTE,
pNumFramesToRead: *mut UINT32, | random_line_split |
int_rect.rs | use math::IntVector;
use sdl2::rect::Rect as SdlRect;
#[derive(Debug, Copy, PartialEq, Clone)]
pub struct IntRect {
pub xy: IntVector,
pub width: u32,
pub height: u32,
}
impl IntRect {
fn new(x: i32, y: i32, width: u32, height: u32) -> IntRect {
IntRect {
xy: IntVector::new(x, y),
... | } | random_line_split | |
int_rect.rs | use math::IntVector;
use sdl2::rect::Rect as SdlRect;
#[derive(Debug, Copy, PartialEq, Clone)]
pub struct IntRect {
pub xy: IntVector,
pub width: u32,
pub height: u32,
}
impl IntRect {
fn new(x: i32, y: i32, width: u32, height: u32) -> IntRect {
IntRect {
xy: IntVector::new(x, y),
... |
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
}
impl From<SdlRect> for IntRect {
fn from(sdl_rect: SdlRect) -> IntRect {
IntRect::new(sdl_rect.x(),
sdl_rect.y(),
sdl_rect.width(),
... | {
self.xy.y
} | identifier_body |
int_rect.rs | use math::IntVector;
use sdl2::rect::Rect as SdlRect;
#[derive(Debug, Copy, PartialEq, Clone)]
pub struct IntRect {
pub xy: IntVector,
pub width: u32,
pub height: u32,
}
impl IntRect {
fn new(x: i32, y: i32, width: u32, height: u32) -> IntRect {
IntRect {
xy: IntVector::new(x, y),
... | (int_rect: IntRect) -> SdlRect {
SdlRect::new(int_rect.x(),
int_rect.y(),
int_rect.width(),
int_rect.height())
}
}
| from | identifier_name |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let result = decode_static_fields(cx,
trait_span,
path,
summary,
|cx, span, name, field| {
cx.expr_try(span,... | {
let decoder = substr.nonself_args[0].clone();
let recurse = vec!(cx.ident_of("serialize"),
cx.ident_of("Decodable"),
cx.ident_of("decode"));
// throw an underscore in front to suppress unused variable warnings
let blkarg = cx.ident_of("_d");
let blkdecoder =... | identifier_body |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt, trait_span: Span,
substr: &Substructure) -> P<Expr> {
let decoder = substr.nonself_args[0].clone();
let recurse = vec!(cx.ident_of("serialize"),
cx.ident_of("Decodable"),
cx.ident_of("decode"));
// throw an underscore in fr... | decodable_substructure | identifier_name |
decodable.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use parse::token;
use ptr::P;
pub fn expand_deriving_decodable(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
... | use ext::base::ExtCtxt; | random_line_split |
process.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 ... |
}
#[stable(feature = "process_extensions", since = "1.2.0")]
impl FromRawFd for process::Stdio {
unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio {
process::Stdio::from_inner(sys::fd::FileDesc::new(fd))
}
}
#[stable(feature = "process_extensions", since = "1.2.0")]
impl AsRawFd for process::ChildSt... | {
match *self.as_inner() {
sys::process::ExitStatus::Signal(s) => Some(s),
_ => None
}
} | identifier_body |
process.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.
// | // except according to those terms.
//! Unix-specific extensions to primitives in the `std::process` module.
#![stable(feature = "rust1", since = "1.0.0")]
use os::unix::raw::{uid_t, gid_t};
use os::unix::io::{FromRawFd, RawFd, AsRawFd};
use prelude::v1::*;
use process;
use sys;
use sys_common::{AsInnerMut, AsInner,... | // 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 | random_line_split |
process.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 ... | (&self) -> RawFd {
self.as_inner().fd().raw()
}
}
#[stable(feature = "process_extensions", since = "1.2.0")]
impl AsRawFd for process::ChildStderr {
fn as_raw_fd(&self) -> RawFd {
self.as_inner().fd().raw()
}
}
| as_raw_fd | identifier_name |
htmlolistelement.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::HTMLOListElementBinding;
use dom::bindings::js::Root;
use dom::document::Doc... |
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLOListElement> {
let element = HTMLOListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLOListElem... | {
HTMLOListElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
} | identifier_body |
htmlolistelement.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::HTMLOListElementBinding;
use dom::bindings::js::Root;
use dom::document::Doc... |
#[dom_struct]
pub struct HTMLOListElement {
htmlelement: HTMLElement,
}
impl HTMLOListElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLOListElement {
HTMLOListElement {
htmlelement: HTMLElement::new... | use dom::node::Node;
use string_cache::Atom;
use util::str::DOMString; | random_line_split |
htmlolistelement.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::HTMLOListElementBinding;
use dom::bindings::js::Root;
use dom::document::Doc... | (localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLOListElement {
HTMLOListElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
... | new_inherited | identifier_name |
deriving-copyclone.rs | // run-pass
//! Test that #[derive(Copy, Clone)] produces a shallow copy
//! even when a member violates RFC 1521
use std::sync::atomic::{AtomicBool, Ordering};
/// A struct that pretends to be Copy, but actually does something
/// in its Clone impl
#[derive(Copy)]
struct | ;
/// Static cooperating with the rogue Clone impl
static CLONED: AtomicBool = AtomicBool::new(false);
impl Clone for Liar {
fn clone(&self) -> Self {
// this makes Clone vs Copy observable
CLONED.store(true, Ordering::SeqCst);
*self
}
}
/// This struct is actually Copy... at least, ... | Liar | identifier_name |
deriving-copyclone.rs | // run-pass
//! Test that #[derive(Copy, Clone)] produces a shallow copy
//! even when a member violates RFC 1521
use std::sync::atomic::{AtomicBool, Ordering}; | struct Liar;
/// Static cooperating with the rogue Clone impl
static CLONED: AtomicBool = AtomicBool::new(false);
impl Clone for Liar {
fn clone(&self) -> Self {
// this makes Clone vs Copy observable
CLONED.store(true, Ordering::SeqCst);
*self
}
}
/// This struct is actually Copy...... |
/// A struct that pretends to be Copy, but actually does something
/// in its Clone impl
#[derive(Copy)] | random_line_split |
deriving-copyclone.rs | // run-pass
//! Test that #[derive(Copy, Clone)] produces a shallow copy
//! even when a member violates RFC 1521
use std::sync::atomic::{AtomicBool, Ordering};
/// A struct that pretends to be Copy, but actually does something
/// in its Clone impl
#[derive(Copy)]
struct Liar;
/// Static cooperating with the rogue ... | {
let _ = Innocent::new().clone();
// if Innocent was byte-for-byte copied, CLONED will still be false
assert!(!CLONED.load(Ordering::SeqCst));
} | identifier_body | |
_6_1_coordinate_systems.rs | #![allow(non_upper_case_globals)]
extern crate glfw;
use self::glfw::{Context, Key, Action};
extern crate gl;
use self::gl::types::*;
use std::sync::mpsc::Receiver;
use std::ptr;
use std::mem;
use std::os::raw::c_void;
use std::path::Path;
use std::ffi::CStr;
use shader::Shader;
use image;
use image::GenericImage;
... | gl::DeleteBuffers(1, &VBO);
gl::DeleteBuffers(1, &EBO);
}
}
fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) {
for (_, event) in glfw::flush_messages(events) {
match event {
glfw::WindowEvent::FramebufferSize(width, height) => {
... |
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
unsafe {
gl::DeleteVertexArrays(1, &VAO); | random_line_split |
_6_1_coordinate_systems.rs | #![allow(non_upper_case_globals)]
extern crate glfw;
use self::glfw::{Context, Key, Action};
extern crate gl;
use self::gl::types::*;
use std::sync::mpsc::Receiver;
use std::ptr;
use std::mem;
use std::os::raw::c_void;
use std::path::Path;
use std::ffi::CStr;
use shader::Shader;
use image;
use image::GenericImage;
... | (window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) {
for (_, event) in glfw::flush_messages(events) {
match event {
glfw::WindowEvent::FramebufferSize(width, height) => {
// make sure the viewport matches the new window dimensions; note that width and
... | process_events | identifier_name |
_6_1_coordinate_systems.rs | #![allow(non_upper_case_globals)]
extern crate glfw;
use self::glfw::{Context, Key, Action};
extern crate gl;
use self::gl::types::*;
use std::sync::mpsc::Receiver;
use std::ptr;
use std::mem;
use std::os::raw::c_void;
use std::path::Path;
use std::ffi::CStr;
use shader::Shader;
use image;
use image::GenericImage;
... | {
for (_, event) in glfw::flush_messages(events) {
match event {
glfw::WindowEvent::FramebufferSize(width, height) => {
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina... | identifier_body | |
generic-trait-generic-static-default-method.rs | // xfail-test
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print arg1
// check:$1 = 1000
// debugger:print *arg2
// check:$2 = {1, 2.5}
// debugger:continue
// debugger:finish
// debugger:print arg1
// check:$3 = 2000
// debugger:print *arg2
// check:$4 = {3.5, {4, 5, 6... | // <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.
| random_line_split |
generic-trait-generic-static-default-method.rs | // xfail-test
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... | () {()}
| zzz | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hashglobe;
extern crate smallvec;
use hashglobe::FailedAllocationError;
use smallvec::Array;
use sma... |
}
}
if new_ptr.is_null() {
return Err(FailedAllocationError::new(
"out of memory when allocating SmallVec",
));
}
let new_vec = unsafe {
Vec::from_raw_parts(new_ptr as *mut T::Item, old_len, new_cap)
};
let new_svec = SmallVec::from_vec(new_vec);
... | {
copy_nonoverlapping(old_ptr as *const u8,
new_ptr as *mut u8, old_size_bytes);
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hashglobe;
extern crate smallvec;
use hashglobe::FailedAllocationError;
use smallvec::Array;
use sma... | "capacity overflow for Vec",
))?
};
let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or(
FailedAllocationError::new("capacity overflow for Vec"),
)?;
let new_ptr = unsafe {
if old_cap == 0 {
malloc(new_size_bytes)
} else {
... | } else {
old_cap.checked_mul(2).ok_or(FailedAllocationError::new( | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hashglobe;
extern crate smallvec;
use hashglobe::FailedAllocationError;
use smallvec::Array;
use sma... | )?;
let new_size_bytes = new_cap.checked_mul(mem::size_of::<T>()).ok_or(
FailedAllocationError::new("capacity overflow for SmallVec"),
)?;
let new_ptr;
if svec.spilled() {
// There's an old block to free, and, presumably, old contents to
// copy. realloc takes care of both... | {
use std::mem;
use std::ptr::copy_nonoverlapping;
let old_ptr = svec.as_mut_ptr();
let old_len = svec.len();
let old_cap: usize = svec.capacity();
let new_cap: usize = if old_cap == 0 {
4
} else {
old_cap.checked_mul(2).ok_or(FailedAllocationError::new(
"capaci... | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hashglobe;
extern crate smallvec;
use hashglobe::FailedAllocationError;
use smallvec::Array;
use sma... | (&mut self, val: T) -> Result<(), FailedAllocationError> {
#[cfg(feature = "known_system_malloc")]
{
if self.capacity() == self.len() {
try_double_vec(self)?;
debug_assert!(self.capacity() > self.len());
}
}
self.push(val);
... | try_push | identifier_name |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2016 Connor Hilarides
//
// 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, cop... | (&mut self, num: usize) -> Option<&image::Frame> {
use image::{ImageBuffer, DynamicImage};
if self.decoder.is_none() || self.next_frame > num {
match self.setup_decoder() {
Ok(_) => {},
Err(_) => return None,
}
}
l... | load_frame | identifier_name |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2016 Connor Hilarides
//
// 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, cop... |
fn setup_decoder(&mut self) -> Result<(), gif::DecodingError> {
use gif::{ColorOutput, SetParameter};
let mut decoder = gif::Decoder::new(io::Cursor::new(self.source.clone()));
decoder.set(ColorOutput::RGBA);
let reader = try!(decoder.read_info());
self.width = reader.w... | {
if self.current_frame.is_none() || num + 1 != self.next_frame {
self.load_frame(num)
} else {
self.current_frame.as_ref()
}
} | identifier_body |
lib.rs | // The MIT License (MIT)
// Copyright (c) 2016 Connor Hilarides
//
// 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, cop... | (
frame.width as u32,
frame.height as u32,
frame.buffer.clone().into_owned(),
)
},
_ => return None,
};
self.next_frame += 1;
let raw_buf = ImageBuffer::from_raw(width, he... | self.delay = frame.delay; | random_line_split |
example.rs | extern crate itertools;
use itertools::Itertools;
/// Encrypt the input string using square cryptography
pub fn encrypt(input: &str) -> String {
let prepared = prepare(input);
if prepared.is_empty() {
return String::new();
}
let (cols, rows) = dimensions(prepared.len());
let mut output = ... | (length: usize) -> (usize, usize) {
let cols = (length as f64).sqrt().ceil() as usize;
let rows = if cols * cols == length {
cols
} else {
cols - 1
};
(rows, cols)
}
/// Iterator over the indices of the appropriate chars of the output.
///
/// For a (2, 3) (r, c) grid, yields (0, 3,... | dimensions | identifier_name |
example.rs | extern crate itertools;
use itertools::Itertools;
/// Encrypt the input string using square cryptography
pub fn encrypt(input: &str) -> String {
let prepared = prepare(input);
if prepared.is_empty() {
return String::new();
}
let (cols, rows) = dimensions(prepared.len());
let mut output = ... | ;
// now increment internal state to next value
self.cur_col += 1;
if self.cur_col >= self.cols {
self.cur_col = 0;
self.cur_row += 1;
}
output
}
}
| {
None
} | conditional_block |
example.rs | extern crate itertools;
use itertools::Itertools;
/// Encrypt the input string using square cryptography
pub fn encrypt(input: &str) -> String {
let prepared = prepare(input);
if prepared.is_empty() {
return String::new();
}
let (cols, rows) = dimensions(prepared.len());
let mut output = ... |
/// Iterator over the indices of the appropriate chars of the output.
///
/// For a (2, 3) (r, c) grid, yields (0, 3, 1, 4, 2, 5).
/// Does no bounds checking or space insertion: that's handled elsewhere.
#[derive(Debug)]
struct SquareIndexer {
rows: usize,
cols: usize,
cur_row: usize,
cur_col: usize,... | {
let cols = (length as f64).sqrt().ceil() as usize;
let rows = if cols * cols == length {
cols
} else {
cols - 1
};
(rows, cols)
} | identifier_body |
example.rs | extern crate itertools;
use itertools::Itertools;
/// Encrypt the input string using square cryptography
pub fn encrypt(input: &str) -> String {
let prepared = prepare(input);
if prepared.is_empty() {
return String::new();
}
let (cols, rows) = dimensions(prepared.len());
let mut output = ... | .filter(|&c| c.is_ascii() &&!c.is_whitespace() &&!c.is_ascii_punctuation())
.map(|c| c.to_ascii_lowercase()),
);
// add space padding to the end such that the actual string returned
// forms a perfect rectangle
let (r, c) = dimensions(output.len());
output.resize(r * c,'');
... | random_line_split | |
mod.rs | use bytes::Buf;
use futures::{Async, Future, Poll};
use h2::{Reason, SendStream};
use http::header::{
HeaderName, CONNECTION, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TE, TRAILER,
TRANSFER_ENCODING, UPGRADE,
};
use http::HeaderMap;
use body::Payload;
mod client;
pub(crate) mod server;
pub(crate) use self::cl... | }
}
}
struct SendBuf<B>(Option<B>);
impl<B: Buf> Buf for SendBuf<B> {
#[inline]
fn remaining(&self) -> usize {
self.0.as_ref().map(|b| b.remaining()).unwrap_or(0)
}
#[inline]
fn bytes(&self) -> &[u8] {
self.0.as_ref().map(|b| b.bytes()).unwrap_or(&[])
}
#[inli... | // There were no trailers, so send an empty DATA frame...
return self.send_eos_frame().map(Async::Ready);
}
}
} | random_line_split |
mod.rs | use bytes::Buf;
use futures::{Async, Future, Poll};
use h2::{Reason, SendStream};
use http::header::{
HeaderName, CONNECTION, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TE, TRAILER,
TRANSFER_ENCODING, UPGRADE,
};
use http::HeaderMap;
use body::Payload;
mod client;
pub(crate) mod server;
pub(crate) use self::cl... | <B>(Option<B>);
impl<B: Buf> Buf for SendBuf<B> {
#[inline]
fn remaining(&self) -> usize {
self.0.as_ref().map(|b| b.remaining()).unwrap_or(0)
}
#[inline]
fn bytes(&self) -> &[u8] {
self.0.as_ref().map(|b| b.bytes()).unwrap_or(&[])
}
#[inline]
fn advance(&mut self, cnt... | SendBuf | identifier_name |
mod.rs | use bytes::Buf;
use futures::{Async, Future, Poll};
use h2::{Reason, SendStream};
use http::header::{
HeaderName, CONNECTION, PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, TE, TRAILER,
TRANSFER_ENCODING, UPGRADE,
};
use http::HeaderMap;
use body::Payload;
mod client;
pub(crate) mod server;
pub(crate) use self::cl... | }
}
match try_ready!(self.stream.poll_data().map_err(|e| self.on_err(e))) {
Some(chunk) => {
let is_eos = self.stream.is_end_stream();
trace!(
"send body chunk: {} bytes, ... | {
// we don't have the next chunk of data yet, so just reserve 1 byte to make
// sure there's some capacity available. h2 will handle the capacity management
// for the actual body chunk.
self.body_tx.reserve_capacity(1);
if self.body_tx.c... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.