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
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, } impl<'c> Command<'c> { pub fn from_args(config: &'c config::command::Config, args: &'c ...
pub fn new( config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, ) -> Self { trace!("command::service::deploy::Command::new"); Command { config: config, name: name, no_wait: no_wait, ...
{ trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_WAIT"), all: args.is_present("ALL"), } }
identifier_body
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>,
} impl<'c> Command<'c> { pub fn from_args(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self { trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_W...
no_wait: bool, all: bool,
random_line_split
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, } impl<'c> Command<'c> { pub fn
(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self { trace!("command::service::deploy::Command::from_args"); Command { config: config, name: args.value_of("NAME"), no_wait: args.is_present("NO_WAIT"), all: args.is_present("ALL")...
from_args
identifier_name
command.rs
use std::error; use clap; use crate::config; use super::executer::{Executer, ExecuterOptions}; pub struct Command<'c> { config: &'c config::command::Config, name: Option<&'c str>, no_wait: bool, all: bool, } impl<'c> Command<'c> { pub fn from_args(config: &'c config::command::Config, args: &'c ...
} } Ok(()) } }
{ for service_config in service_config_group { let mut runnable: bool = false; if let Some(name) = self.name { if name == service_config.name { runnable = true; } } if self.all { ...
conditional_block
regions-proc-bound-capture.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { }
random_line_split
regions-proc-bound-capture.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 static_proc(x: &isize) -> Box<FnMut()->(isize) +'static> { // This is illegal, because the region bound on `proc` is'static. Box::new(move|| { *x }) //~ ERROR captured variable `x` does not outlive the enclosing closure } fn main() { }
{ // This is legal, because the region bound on `proc` // states that it captures `x`. Box::new(move|| { *x }) }
identifier_body
regions-proc-bound-capture.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> { // This is legal, because the region bound on `proc` // states that it captures `x`. Box::new(move|| { *x }) } fn static_proc(x: &isize) -> Box<FnMut()->(isize) +'static> { // This is illegal, because the region bound on `proc` is'static. Box::new(...
borrowed_proc
identifier_name
html-literals.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 ...
) ); ( [$(:$tags:ident ($(:$tag_nodes:expr),*) )*]; [$(:$nodes:expr),*]; <$tag:ident> $($rest:tt)* ) => ( parse_node!( [:$tag ($(:$nodes)*) $(: $tags ($(:$tag_nodes),*) )*]; []; $($rest)* ) ); ( [$(:$tags:i...
[$(: $tags ($(:$tag_nodes),*))*]; [$(:$head_nodes,)* :tag(stringify!($head).to_string(), vec![$($nodes),*])]; $($rest)*
random_line_split
html-literals.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 _page = html! ( <html> <head><title>This is the title.</title></head> <body> <p>This is some text</p> </body> </html> ); } enum HTMLFragment { tag(String, Vec<HTMLFragment> ), text(String), }
main
identifier_name
list_devices.rs
extern crate libudev; use std::io; fn main() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()>
println!(" parent: None"); } println!(" [properties]"); for property in device.properties() { println!(" - {:?} {:?}", property.name(), property.value()); } println!(" [attributes]"); for attribute in device.attributes() { pr...
{ let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices()) { println!(""); println!("initialized: {:?}", device.is_initialized()); println!(" devnum: {:?}", device.devnum()); println!(" syspath: {:?}", device.syspath());...
identifier_body
list_devices.rs
extern crate libudev; use std::io; fn
() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()> { let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices()) { println!(""); println!(...
main
identifier_name
list_devices.rs
extern crate libudev; use std::io; fn main() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()> { let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices(...
println!(" [properties]"); for property in device.properties() { println!(" - {:?} {:?}", property.name(), property.value()); } println!(" [attributes]"); for attribute in device.attributes() { println!(" - {:?} {:?}", attribute.name(), attribut...
{ println!(" parent: None"); }
conditional_block
list_devices.rs
extern crate libudev; use std::io; fn main() { let context = libudev::Context::new().unwrap(); list_devices(&context).unwrap(); } fn list_devices(context: &libudev::Context) -> io::Result<()> { let mut enumerator = try!(libudev::Enumerator::new(&context)); for device in try!(enumerator.scan_devices(...
println!(" sysnum: {:?}", device.sysnum()); println!(" devtype: {:?}", device.devtype()); println!(" driver: {:?}", device.driver()); println!(" devnode: {:?}", device.devnode()); if let Some(parent) = device.parent() { println!(" parent: {:?}", par...
println!(" syspath: {:?}", device.syspath()); println!(" devpath: {:?}", device.devpath()); println!(" subsystem: {:?}", device.subsystem()); println!(" sysname: {:?}", device.sysname());
random_line_split
mod.rs
use std::str::Chars; use std::iter::Peekable; /// The input stream operates on an input string and provides character-wise access. pub struct InputStream<'a> { /// The input string. input: &'a str, /// The position of the next character in the input string.
pos: usize, /// The iterator over the input string. iterator: Peekable<Chars<'a>> } impl<'a> InputStream<'a> { /// Generates a new InputStream instance. pub fn new(input: &'a str) -> InputStream<'a> { InputStream{input: input, pos: 0, iterator: input.chars().peekable()} } /// Retu...
random_line_split
mod.rs
use std::str::Chars; use std::iter::Peekable; /// The input stream operates on an input string and provides character-wise access. pub struct InputStream<'a> { /// The input string. input: &'a str, /// The position of the next character in the input string. pos: usize, /// The iterator over the in...
(& mut self) -> bool { self.iterator.peek().is_none() } /// Returns the current position of the input string. pub fn get_pos(& self) -> usize { self.pos } /// Returns the input string. pub fn get_input(& self) -> & str { & self.input } }
eof
identifier_name
mod.rs
use std::str::Chars; use std::iter::Peekable; /// The input stream operates on an input string and provides character-wise access. pub struct InputStream<'a> { /// The input string. input: &'a str, /// The position of the next character in the input string. pos: usize, /// The iterator over the in...
/// Returns the character of the next position of the stream and advances the stream position. pub fn next(& mut self) -> Option<char> { match self.iterator.next() { Some(x) => { self.pos += 1; Some(x) }, None => None } } ...
{ self.iterator.peek().map(|x| *x) }
identifier_body
batch.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::pin::Pin; use std::ptr::null_mut; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use crossbeam::channel::{ self, RecvError, RecvTimeoutError, SendError, TryRecvError, Tr...
#[inline] pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> { self.receiver.recv_timeout(timeout) } } /// Creates a unbounded channel with a given `notify_size`, which means if there are more pending /// messages in the channel than `notify_size`, the `Sender` will auto...
{ self.receiver.try_recv() }
identifier_body
batch.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::pin::Pin; use std::ptr::null_mut; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use crossbeam::channel::{ self, RecvError, RecvTimeoutError, SendError, TryRecvError, Tr...
I: Fn() -> E + Unpin, C: BatchCollector<E, T> + Unpin, { /// Creates a new `BatchReceiver` with given `initializer` and `collector`. `initializer` is /// used to generate a initial value, and `collector` will collect every (at most /// `max_batch_size`) raw items into the batched value. pub fn n...
where T: Unpin, E: Unpin,
random_line_split
batch.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::pin::Pin; use std::ptr::null_mut; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use crossbeam::channel::{ self, RecvError, RecvTimeoutError, SendError, TryRecvError, Tr...
(&self) { let task = Arc::new(self.clone()); let mut future_slot = self.future.lock().unwrap(); if let Some(mut future) = future_slot.take() { let waker = task::waker_ref(&task); let cx = &mut Context::from_waker(&*waker); match future....
tick
identifier_name
alignment-gep-tup-like-1.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) -> (A, u16) { (self.a.clone(), self.b) } } fn f<A:Clone +'static>(a: A, b: u16) -> Box<Invokable<A>+'static> { box Invoker { a: a, b: b, } as (Box<Invokable<A>+'static>) } pub fn main() { let (a, b) = f(22_u64, 44u16).f(); println!("a={} b={}", a, b); assert_eq!...
f
identifier_name
alignment-gep-tup-like-1.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 (a, b) = f(22_u64, 44u16).f(); println!("a={} b={}", a, b); assert_eq!(a, 22u64); assert_eq!(b, 44u16); }
identifier_body
alignment-gep-tup-like-1.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. //
// except according to those terms. struct pair<A,B> { a: A, b: B } trait Invokable<A> { fn f(&self) -> (A, u16); } struct Invoker<A> { a: A, b: u16, } impl<A:Clone> Invokable<A> for Invoker<A> { fn f(&self) -> (A, u16) { (self.a.clone(), self.b) } } fn f<A:Clone +'static>(a: A, b: ...
// 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
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; // The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor) // creates conditions where the `generator::StateTransform` MIR...
{ let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut gen...
identifier_body
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; // The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor) // creates conditions where the `generator::StateTransform` MIR...
() { let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut ...
main
identifier_name
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin;
// creates conditions where the `generator::StateTransform` MIR transform will // drop all `Counter` `Coverage` statements from a MIR. `simplify.rs` has logic // to handle this condition, and still report dead block coverage. fn get_u32(val: bool) -> Result<u32, String> { if val { Ok(1) } else { Err(String::from("s...
// The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor)
random_line_split
_6_2_coordinate_systems_depth.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::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (ourShader, VBO, VAO, texture1, texture2) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); // build and compile our shader program // -------...
{ // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] ...
identifier_body
_6_2_coordinate_systems_depth.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; ...
} } }
{}
conditional_block
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl;
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; use cgmath::{Matrix4, vec3, Deg, Rad, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT:...
use self::gl::types::*;
random_line_split
_6_2_coordinate_systems_depth.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; ...
() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos"...
main_1_6_2
identifier_name
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
} impl TurtleAnimation { /// Build a TurtleAnimation from a canvas element and a boxed turtle program. /// /// The TurtleProgram is copied and boxed (via its `turtle_program_iter`) to to avoid /// TurtleAnimation being generic. pub fn new(ctx: CanvasRenderingContext2d, program: &dyn TurtleProgram) ...
/// that program. pub struct TurtleAnimation { turtle: CanvasTurtle, iter: TurtleCollectToNextForwardIterator,
random_line_split
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
(&mut self, _x1: f64, _y1: f64, _x2: f64, _y2: f64) -> bool { false } }
zoom
identifier_name
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
else { log::debug!("No more moves"); self.turtle.up(); false } } /// Translates a pixel-coordinate on the Canvas into the coordinate system used by the turtle /// curves. /// /// See turtle::turtle_vat for more information on the coordinate system for tu...
{ log::debug!("Rendering one move"); for action in one_move { self.turtle.perform(action); } true }
conditional_block
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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 applicab...
fn up(&mut self) { self.state.down = false; } } /// Represents everything needed to render a turtle a piece at a time to a canvas. /// /// It holds onto a turtle program, which is then used to eventually initialize an iterator over /// that program. pub struct TurtleAnimation { turtle: CanvasTurt...
{ self.state.down = true; }
identifier_body
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser; #[test] fn
() { let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new(); let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y...
parse_file
identifier_name
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser; #[test] fn parse_file()
{ let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new(); let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0...
identifier_body
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser;
let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0 }, Coord { x: -1, y: 1 }, Coord { x: 0, y: 1 }, Coord { x: 1, y: 1 }, // block 2 Coord { x: 3, y: 2...
#[test] fn parse_file() { let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new();
random_line_split
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /...
_ => return }; let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap...
{ json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadFailed".to_string(), data: DownloadFailed { update_id: id, reason: reason } }).expect("couldn't encode DownloadFailed event") }
conditional_block
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /...
<E: Encodable> { pub version: String, pub event: String, pub data: E } #[cfg(test)] mod tests { use chan; use crossbeam; use rustc_serialize::json; use std::{fs, thread}; use std::io::{Read, Write}; use std::net::Shutdown; use std::time::Duration; use datatype::{Comma...
EventWrapper
identifier_name
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write};
use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /// The `Socket` gateway is used for communication via Unix Domain Sockets. pub struct Socket { pub commands_path: String, pub events_path: String, } ...
use std::net::Shutdown; use std::sync::{Arc, Mutex};
random_line_split
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /...
let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwrap_or_else(|err| error!("couldn't close...
{ let output = match event { Event::DownloadComplete(dl) => { json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadComplete".to_string(), data: dl }).expect("couldn't encode DownloadC...
identifier_body
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)]
pub protocol_version: String, #[serde(rename = "customDependencies")] pub custom_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "customDevDependencies")] pub custom_dev_dependencies: Option<BTreeMap<String, cargo::Dependency>>, #[serde(rename = "baseTypeName")] p...
pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String, #[serde(rename = "protocolVersion")]
random_line_split
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)] pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String...
} impl Error for ConfigError { fn description(&self) -> &str { match *self { ConfigError::Io(ref e) => e.description(), ConfigError::Format(ref e) => e.description() } } fn cause(&self) -> Option<&Error> { match *self { ConfigError::Io(ref e) =>...
{ match *self { ConfigError::Io(ref e) => e.fmt(f), ConfigError::Format(ref e) => e.fmt(f) } }
identifier_body
config.rs
use std::collections::BTreeMap; use std::error::Error; use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use serde_json; use cargo; #[derive(Clone, Debug, Deserialize)] pub struct ServiceConfig { pub version: String, #[serde(rename = "coreVersion")] pub core_version: String...
(err: io::Error) -> Self { ConfigError::Io(err) } } impl From<serde_json::Error> for ConfigError { fn from(err: serde_json::Error) -> Self { ConfigError::Format(err) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ...
from
identifier_name
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
; } } } struct ErrorContext; impl glfw::ErrorCallback for ErrorContext { fn call(&self, _: glfw::Error, description: ~str) { println!("GLFW Error: {:s}", description); } } mod gl { use std::libc; #[cfg(target_os = "macos")] #[link(name="OpenGL", kind="framework")] extern {...
{ let value = 0; unsafe { gl::GetIntegerv(param, &value) }; println!("OpenGL {:s}: {}", name, value); }
conditional_block
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern mod glfw; #[link(name="glfw")] extern {} #[start] fn start(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc...
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
main.rs
// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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...
(argc: int, argv: **u8) -> int { std::rt::start_on_main_thread(argc, argv, main) } fn main() { glfw::set_error_callback(~ErrorContext); do glfw::start { glfw::window_hint::visible(true); let window = glfw::Window::create(640, 480, "Defaults", glfw::Windowed) .expect("Failed to ...
start
identifier_name
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std:...
app.stdout.flush().expect("fail to flush the stdout"); }
random_line_split
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std:...
let mut app = { let stdout = { Box::new(_stdout.lock().into_raw_mode().expect("fail to lock stdout")) }; let icon_collection: Box<Vec<IconItem>> = { let icon_manifest_string = hkg::utility::readfile(String::from("data/icon.manifest.json")); Box::new(jso...
{ // Initialize log4rs::init_file("config/log4rs.yaml", Default::default()).expect("fail to init log4rs"); info!("app start"); // Clear the screen. hkg::screen::common::clear_screen(); let _stdout = stdout(); // web background services let (tx_req, rx_req) = channel::<ChannelItem>()...
identifier_body
main.rs
extern crate hkg; extern crate termion; extern crate rustc_serialize; extern crate kuchiki; extern crate chrono; extern crate cancellation; extern crate crossbeam; #[macro_use] extern crate log; extern crate log4rs; use std::io::{stdout, stdin, Write}; use std::io::{self, Read}; use std::sync::mpsc::channel; use std:...
(state_manager: &mut StateManager, tx_req: &Sender<ChannelItem>) -> String { let ci = ChannelItem { extra: Some(ChannelItemType::Index(Default::default())), result: Default::default() }; let status_message = match tx_req.send(ci) { Ok(()) => { state_manager.set_web_requ...
list_page
identifier_name
traits.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....
block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(()) ...
if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; }
random_line_split
traits.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....
block.transaction_views().iter().foreach(|t| corpus.push(t.gas_price())); h = header.parent_hash().clone(); } } corpus.sort(); let n = corpus.len(); if n > 0 { Ok((0..(distribution_size + 1)) .map(|i| corpus[i * (n - 1) / distribution_size]) .collect::<Vec<_>>() ) } else { Err(())...
{ if corpus.is_empty() { corpus.push(20_000_000_000u64.into()); // we have literally no information - it' as good a number as any. } break; }
conditional_block
traits.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....
/// Get address balance at the given block's state. /// /// May not return None if given BlockID::Latest. /// Returns None if and only if the block's root hash has been pruned from the DB. fn balance(&self, address: &Address, id: BlockID) -> Option<U256>; /// Get address balance at the latest block's state. f...
{ self.code(address, BlockID::Latest) .expect("code will return Some if given BlockID::Latest; qed") }
identifier_body
traits.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, address: &Address, position: &H256) -> H256 { self.storage_at(address, position, BlockID::Latest) .expect("storage_at will return Some if given BlockID::Latest. storage_at was given BlockID::Latest. \ Therefore storage_at has returned Some; qed") } /// Get a list of all accounts in the block `id`, if...
latest_storage_at
identifier_name
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for Cust...
(&self) -> &str { self.0.as_str() } } fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), ...
description
identifier_name
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for Cust...
use std::error::Error; let error = throws_error_with_description().unwrap_err(); assert_eq!(error.description(), "err"); } #[test] fn test_error_description_with_key_value_pairs() { use std::error::Error; let error = throws_error_with_description_and_key_value_pairs().unwrap_err(); assert_eq!...
random_line_split
std_tests.rs
#![cfg(feature = "std")] #[macro_use] extern crate throw; use throw::Result; #[derive(Debug)] struct CustomError(String); impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "CustomError: {}", self.0) } } impl std::error::Error for Cust...
} fn throws_error_with_description() -> Result<(), CustomError> { throw!(Err(CustomError("err".to_owned()))); Ok(()) } fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> { throw!( Err(CustomError("err".to_owned())), "key" => "value" ); Ok(()) } #[te...
{ self.0.as_str() }
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/. use base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{Byt...
/// Sets a byte in the slice to a value. /// /// [argument, idx] /// The index of the byte to be set. /// /// [argument, val] /// The value of the byte. /// /// = Remarks /// /// If `val == 0`, the process is aborted. pub fn set(&mut self, idx: usize, val: u8) { a...
impl NoNullStr {
random_line_split
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/. use base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{Byt...
<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
fmt
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/. use base::prelude::*; use core::{mem}; use arch_fns::{memrchr}; use fmt::{Debug, Display, Write}; use byte_str::{Byt...
} impl Debug for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Debug::fmt(bs, w) } } impl Display for NoNullStr { fn fmt<W: Write>(&self, w: &mut W) -> Result { let bs: &ByteStr = self.as_ref(); Display::fmt(bs, w) } }
{ self.as_ref() }
identifier_body
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SI...
#[cfg(target_os = "macos")] const numname: [(&str, c_int); 27] = [ ("HUP", libc::SIGHUP), ("INT", libc::SIGINT), ("QUIT", libc::SIGQUIT), ("ILL", libc::SIGILL), ("TRAP", libc::SIGTRAP), ("ABRT", libc::SIGABRT), ("IOT", libc::SIGIOT), ("BUS", libc::SIGBUS), ("FPE", libc::SIGFPE), ...
("POLL", libc::SIGPOLL), ("PWR", libc::SIGPWR), ("SYS", libc::SIGSYS), ];
random_line_split
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SI...
{ let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s { *signum = num; ...
identifier_body
str2sig.rs
//! Convert between signal names and numbers. #[cfg(not(windows))] use libc; use libc::{c_char, c_int}; use std::ffi::CStr; use std::str::FromStr; #[cfg(not(unix))] const numname: [(&'static str, c_int); 0] = []; #[cfg(all(unix, not(target_os = "macos")))] const numname: [(&str, c_int); 30] = [ ("HUP", libc::SI...
(signame: *const c_char, signum: *mut c_int) -> c_int { let s = CStr::from_ptr(signame).to_string_lossy(); match FromStr::from_str(s.as_ref()) { Ok(i) => { *signum = i; return 0; } Err(_) => { for &(name, num) in &numname { if name == s...
str2sig
identifier_name
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self...
fn clone(&self) -> Reshape<T> { Reshape{ base: self.base.clone(), nrow: self.nrow, ncol: self.ncol } } } impl<T: MatrixRawGet + MatrixShape> fmt::Display for Reshape<T> { fn fmt(&self, buf: &mut fmt::Formatter) -> fmt::Result { write_mat(buf, self) } }
random_line_split
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self...
}
{ write_mat(buf, self) }
identifier_body
reshape.rs
use std::fmt; use traits::{MatrixGet, MatrixSet, MatrixRawGet, MatrixRawSet, MatrixShape, MatrixReshape, SameShape}; use matrix::write_mat; impl<T: MatrixShape> MatrixReshape for T { unsafe fn unsafe_reshape(self, nrow: usize, ncol: usize) -> Reshape<T> { Reshape::unsafe_new(self, nrow, ncol) } fn reshape(self...
(&self, r: usize, c: usize, val: f64) { self.base.unsafe_set(r * self.ncol() + c, val) } } impl<T> MatrixShape for Reshape<T> { fn nrow(&self) -> usize { self.nrow } fn ncol(&self) -> usize { self.ncol } } impl<T: MatrixShape> SameShape for Reshape<T> { fn same_shape(&self, nrow: usize, ncol: usize) ->...
raw_set
identifier_name
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _...
} impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value!= 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) -> bool { self.value == 0 } } i...
impl<E> QFlags<E> { pub fn to_int(self) -> c_int { self.value }
random_line_split
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _...
} impl<E> From<QFlags<E>> for c_int { fn from(flags: QFlags<E>) -> Self { flags.value } } impl<E> QFlags<E> { pub fn to_int(self) -> c_int { self.value } } impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) ...
{ Self { value, _phantom_data: PhantomData, } }
identifier_body
q_flags.rs
use std::fmt; use std::marker::PhantomData; use std::ops::{BitAnd, BitOr, BitXor}; use std::os::raw::c_int; /// An OR-combination of integer values of the enum type `E`. /// /// This type serves as a replacement for Qt's `QFlags` C++ template class. #[derive(Clone, Copy)] pub struct QFlags<E> { value: c_int, _...
(self) -> c_int { self.value } } impl<E: Into<QFlags<E>>> QFlags<E> { /// Returns `true` if `flag` is enabled in `self`. pub fn test_flag(self, flag: E) -> bool { self.value & flag.into().value!= 0 } /// Returns `true` if this value has no flags enabled. pub fn is_empty(self) -...
to_int
identifier_name
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { ...
=> { rest.iter().fold(first, |acc, &item| { let &(op, factor) = &item; match op { "*" => acc * factor, "/" => acc / factor, _ => unreachable!() } }) } ); rule!(factor:i32 ...
rest:(ws op:(["*"] / ["/"]) ws factor:factor => {(op, factor)})*
random_line_split
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str>
Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, term)})* => { rest.iter().fold(first, |acc, &item| { let &(op, term) = &item; ...
{ let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if !char.is_digit(10) { end = index; break; } }, None => { ...
identifier_body
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn digits(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { ...
, None => { end = input.len(); break; } } } if end > 0 { Ok((&input[..end], &input[end..])) } else { Err(ParseError) } } rule!(expression:i32 = first:term rest: (ws op:(["+"] / ["-"]) ws term:term => {(op, ...
{ if !char.is_digit(10) { end = index; break; } }
conditional_block
arithmetic.rs
// Adapted from PEG.js example - https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs #[macro_use] extern crate peggler; use peggler::{ParseError, ParseResult}; fn
(input: &str) -> ParseResult<&str> { let mut end : usize; let mut char_indices = input.char_indices(); loop { match char_indices.next() { Some((index, char)) => { if!char.is_digit(10) { end = index; break; } ...
digits
identifier_name
bounds.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 ...
(cx: &mut ExtCtxt, span: Span, _: &MetaItem, _: &Annotatable, _: &mut dyn FnMut(Annotatable)) { cx.span_err(span, "this unsafe trait should be implemented explicitly"); } ...
expand_deriving_unsafe_bound
identifier_name
bounds.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let trait_def = TraitDef { span, attributes: Vec::new(), path: path_std!(cx, marker::Copy), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: true, methods: Vec::new(), associated_types: Vec:...
identifier_body
bounds.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
use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::MetaItem; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; pub fn expand_deriving_unsafe_bound(cx: &mut ExtCtxt, span: Span, _: &MetaItem, ...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use deriving::path_std;
random_line_split
lib.rs
//! A wrapper for the Strava API //! //! # Organization //! //! The module layout in this crate mirrors the [Strava API documentation][]. All functions //! interacting with the strava servers will return a //! [`strava::error::Result`](error/type.Result.html) for which the `E` parameter is curried to //! [`strava::erro...
//! // Get the athlete associated with the given token //! let athlete = Athlete::get_current(&token).unwrap(); //! //! // All of the strava types implement Debug and can be printed like so: //! println!("{:?}", athlete); //! ``` //! //! [Strava API Documentation]: http://strava.github.io/api/ extern crate hyper; exte...
//!
random_line_split
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn
() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calculate_part1(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mu...
part1
identifier_name
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn part1() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calcu...
hasher.reset(); } panic!("The mining operation has failed!"); } fn calculate_part2(input: &[u8]) -> u64 { let mut hasher = Md5::new(); for i in 0..::std::u64::MAX { hasher.input(input); hasher.input(i.to_string().as_bytes()); let mut output = [0; 16]; hasher...
{ return i }
conditional_block
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn part1() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calcu...
fn test1() { assert_eq!(609043, super::calculate_part1("abcdef".as_bytes())); } #[test] fn test2() { assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes())); } }
#[cfg(test)] mod tests { #[test]
random_line_split
day4.rs
// thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7 // for the optimizations use crypto::md5::Md5; use crypto::digest::Digest; const INPUT: &'static str = "iwrupvqb"; pub fn part1() -> u64 { calculate_part1(INPUT.as_bytes()) } pub fn part2() -> u64 { calculate_part2(INPUT.as_bytes()) } fn calcu...
}
{ assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes())); }
identifier_body
specified_value_info.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/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// T...
macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { $param::co...
} }
random_line_split
specified_value_info.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/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// T...
(f: KeywordsCollectFn) { T::collect_completion_keywords(f); } } macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn c...
collect_completion_keywords
identifier_name
specified_value_info.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/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// T...
} macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { $param...
{ T::collect_completion_keywords(f); }
identifier_body
events.rs
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser. use std::fmt; use name::OwnedName; use attribute::OwnedAttribute; use common::{HasPosition, XmlVersion}; use common::Error as CommonError; use namespace::Namespace; /// An element of an XML input stream. /// /// Items of this...
/// XML standalone declaration. /// /// If XML document is not present or does not contain `standalone` attribute, /// defaults to `None`. This field is currently used for no other purpose than /// informational. standalone: Option<bool> }, /// Denotes ...
encoding: String,
random_line_split
events.rs
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser. use std::fmt; use name::OwnedName; use attribute::OwnedAttribute; use common::{HasPosition, XmlVersion}; use common::Error as CommonError; use namespace::Namespace; /// An element of an XML input stream. /// /// Items of this...
Some(::writer::events::XmlEvent::EndElement { name: name.borrow() }), XmlEvent::Comment(ref data) => Some(::writer::events::XmlEvent::Comment(data.as_slice())), XmlEvent::CData(ref data) => Some(::writer::events::XmlEvent::CData(data.as_slice())), XmlEvent::Charact...
{ match *self { XmlEvent::StartDocument { version, ref encoding, standalone } => Some(::writer::events::XmlEvent::StartDocument { version: version, encoding: Some(encoding.as_slice()), standalone: standalone ...
identifier_body
events.rs
//! Contains `XmlEvent` datatype, instances of which are emitted by the parser. use std::fmt; use name::OwnedName; use attribute::OwnedAttribute; use common::{HasPosition, XmlVersion}; use common::Error as CommonError; use namespace::Namespace; /// An element of an XML input stream. /// /// Items of this...
<'a>(&'a self) -> Option<::writer::events::XmlEvent<'a>> { match *self { XmlEvent::StartDocument { version, ref encoding, standalone } => Some(::writer::events::XmlEvent::StartDocument { version: version, encoding: Some(encoding.as_slice()...
as_writer_event
identifier_name
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_...
filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager faile...
{ let pool = CoreResourceThreadPool::new(1); let pool_handle = Arc::new(pool); let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle)); set_pref!(dom.testing.html_input_element.select_files.enabled, true); // Try to open a dummy file "components/net/tests/test.jpeg...
identifier_body
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_...
} // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken cha...
{ panic!("Invalid FileManager reply"); }
conditional_block
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_...
); }, } } } }
assert!( false, "Get unexpected response after deleting the id: {:?}", other
random_line_split
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_...
() { let pool = CoreResourceThreadPool::new(1); let pool_handle = Arc::new(pool); let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle)); set_pref!(dom.testing.html_input_element.select_files.enabled, true); // Try to open a dummy file "components/net/tests/test.j...
test_filemanager
identifier_name
client.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 // // Unl...
sc.set_incarnation(incarnation); sc.set_encrypted(encrypted); self.send(sc) } /// Create a service file and send it to the server. pub fn send_service_file<S: Into<String>>( &mut self, service_group: ServiceGroup, filename: S, incarnation: u64, ...
config: Vec<u8>, encrypted: bool, ) -> Result<()> { let mut sc = ServiceConfig::new("butterflyclient", service_group, config);
random_line_split
client.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 // // Unl...
{ socket: zmq::Socket, ring_key: Option<SymKey>, } impl Client { /// Connect this client to the address, and optionally encrypt the traffic. pub fn new<A>(addr: A, ring_key: Option<SymKey>) -> Result<Client> where A: ToString, { let socket = (**ZMQ_CONTEXT) .as_mut()...
Client
identifier_name
client.rs
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 // // Unl...
/// Send any `Rumor` to the server. pub fn send<T: Rumor>(&mut self, rumor: T) -> Result<()> { let bytes = rumor.write_to_bytes()?; let wire_msg = message::generate_wire(bytes, self.ring_key.as_ref())?; self.socket.send(&wire_msg, 0).map_err(Error::ZmqSendError) } }
{ let mut sf = ServiceFile::new("butterflyclient", service_group, filename, body); sf.set_incarnation(incarnation); sf.set_encrypted(encrypted); self.send(sf) }
identifier_body
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAlloc...
(&mut self, count: usize) -> Option<Frame> { let mut small_i = None; { let mut small = (0, 0); for i in 0..self.free.len() { let free = self.free[i]; // Later entries can be removed faster if free.1 >= count { if...
allocate_frames
identifier_name
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAlloc...
// Later entries can be removed faster if free.1 >= count { if free.1 <= small.1 || small_i.is_none() { small_i = Some(i); small = free; } } } } if let Som...
for i in 0..self.free.len() { let free = self.free[i];
random_line_split
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAlloc...
return true; } } false } } impl<T: FrameAllocator> FrameAllocator for RecycleAllocator<T> { fn set_noncore(&mut self, noncore: bool) { self.noncore = noncore; } fn free_frames(&self) -> usize { self.inner.free_frames() + self.free_count() ...
{ self.free.remove(i); }
conditional_block
recycle.rs
//! Recycle allocator //! Uses freed frames if possible, then uses inner allocator use alloc::Vec; use paging::PhysicalAddress; use super::{Frame, FrameAllocator}; pub struct RecycleAllocator<T: FrameAllocator> { inner: T, noncore: bool, free: Vec<(usize, usize)>, } impl<T: FrameAllocator> RecycleAlloc...
(free.0 + free.1 * 4096, free.1 == 0) }; if remove { self.free.remove(i); } //println!("Restoring frame {:?}, {}", frame, count); Some(Frame::containing_address(PhysicalAddress::new(address))) } else { //pr...
{ let mut small_i = None; { let mut small = (0, 0); for i in 0..self.free.len() { let free = self.free[i]; // Later entries can be removed faster if free.1 >= count { if free.1 <= small.1 || small_i.is_none() { ...
identifier_body
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless cons...
#[cfg(feature = "i128_blob")] FromSqlError::InvalidI128Size(_) => Error::InvalidColumnType( idx, self.stmt.column_name_unwrap(idx).into(), value.data_type(), ), #[cfg(feature = "uuid")] FromSqlError::InvalidUuid...
{ Error::FromSqlConversionFailure(idx as usize, value.data_type(), err) }
conditional_block
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless cons...
#[inline] fn advance(&mut self) -> Result<()> { match self.stmt { Some(ref stmt) => match stmt.step() { Ok(true) => { self.row = Some(Row { stmt }); Ok(()) } Ok(false) => { self.reset(...
type Item = Row<'stmt>;
random_line_split
row.rs
use fallible_iterator::FallibleIterator; use fallible_streaming_iterator::FallibleStreamingIterator; use std::convert; use super::{Error, Result, Statement}; use crate::types::{FromSql, FromSqlError, ValueRef}; /// An handle for the resulting rows of a query. #[must_use = "Rows is lazy and will do nothing unless cons...
<'stmt> { pub(crate) stmt: Option<&'stmt Statement<'stmt>>, row: Option<Row<'stmt>>, } impl<'stmt> Rows<'stmt> { #[inline] fn reset(&mut self) { if let Some(stmt) = self.stmt.take() { stmt.reset(); } } /// Attempt to get the next row from the query. Returns `Ok(Some...
Rows
identifier_name