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
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let nyan: @mut noisy = @mut cat(0u, 2, ~"nyan") as @mut noisy; nyan.speak(); }
{ error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } }
identifier_body
class-cast-to-trait.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 ...
{ priv meows: uint, how_hungry: int, name: ~str, } impl noisy for cat { fn speak(&mut self) { self.meow(); } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { error!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { error!("Not hungry...
cat
identifier_name
class-cast-to-trait.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 ...
nyan.speak(); }
pub fn main() { let nyan: @mut noisy = @mut cat(0u, 2, ~"nyan") as @mut noisy;
random_line_split
class-cast-to-trait.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 ...
} } impl cat { fn meow(&mut self) { error!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub...
{ error!("Not hungry!"); return false; }
conditional_block
vm.rs
use std::collections::HashMap; use serde_json; use serde_json::value::Value; use common::{Context, Result, Error}; use common::structs::VM; use database; use handler; use backend; use remote; use net; /* * Validates the user-specified parameters for VM creation, and sets up the VM's network interfaces */ fn valida...
/* * Handle a'statusvm' command */ pub fn status(ctx: &Context, name: &str) -> Result<String> { let mut vm = try!(database::vm::get(ctx, name)); match backend::vm::script_status(ctx, &mut vm) { Ok(p) => { let mut pp: HashMap<String, Value> = HashMap::new(); for (k, v) in p {...
{ let mut vm = try!(database::vm::get(ctx, name)); match backend::vm::script_stop(ctx, &mut vm) { Ok(_) => Ok(String::new()), Err(e) => Err(e) } }
identifier_body
vm.rs
use std::collections::HashMap; use serde_json; use serde_json::value::Value; use common::{Context, Result, Error}; use common::structs::VM; use database; use handler; use backend; use remote; use net; /* * Validates the user-specified parameters for VM creation, and sets up the VM's network interfaces */ fn valida...
(ctx: &Context, name: &str) -> Result<String> { let mut vm = try!(database::vm::get(ctx, name)); match backend::vm::script_start(ctx, &mut vm) { Ok(_) => {}, Err(e) => return Err(e) }; Ok(String::new()) } /* * Handle a'stopvm' command */ pub fn stop(ctx: &Context, name: &str) -> Res...
start
identifier_name
vm.rs
use std::collections::HashMap; use serde_json; use serde_json::value::Value; use common::{Context, Result, Error}; use common::structs::VM; use database; use handler; use backend; use remote; use net; /* * Validates the user-specified parameters for VM creation, and sets up the VM's network interfaces */ fn valida...
} // TODO: Check backend, make sure it exists if vm.image.len() > 0 { if let Err(_) = database::image::get(ctx, vm.image.as_str()) { return Err(Error::new("Image not found")); } } let mut index = 0; for iface in &mut vm.interfaces { if iface.mac.len() == 0 ...
return Err(Error::new("The 'name' must be less than 11 characters long")); } if vm.backend.len() == 0 { return Err(Error::new("A 'backend' is required"));
random_line_split
testing.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ raw::{config::*, security}, testing::s2n_tls::Harness, }; use bytes::Bytes; use core::task::Poll; use std::collections::VecDeque; pub mod s2n_tls; type Error = Box<dyn std::error::Error>;...
(&mut self) -> &'static [u8] { self.cert } fn key(&mut self) -> &'static [u8] { self.key } } pub fn build_config(cipher_prefs: &security::Policy) -> Result<crate::raw::config::Config, Error> { let mut builder = Builder::new(); let mut keypair = CertKeyPair::default(); // Build ...
cert
identifier_name
testing.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ raw::{config::*, security}, testing::s2n_tls::Harness, }; use bytes::Bytes; use core::task::Poll; use std::collections::VecDeque; pub mod s2n_tls; type Error = Box<dyn std::error::Error>;...
(_, Poll::Ready(server_res)) => { server_res?; Poll::Pending } _ => Poll::Pending, } } } #[derive(Debug, Default)] pub struct MemoryContext { rx: VecDeque<Bytes>, tx: VecDeque<Bytes>, } impl MemoryContext { pub fn transfer(&m...
{ assert!( self.max_iterations > 0, "handshake has iterated too many times: {:#?}", self, ); let client_res = self.client.0.poll(&mut self.client.1); let server_res = self.server.0.poll(&mut self.server.1); self.client.1.transfer(&mut self.serv...
identifier_body
testing.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{ raw::{config::*, security}, testing::s2n_tls::Harness, }; use bytes::Bytes; use core::task::Poll; use std::collections::VecDeque; pub mod s2n_tls; type Error = Box<dyn std::error::Error>;...
let mut server = crate::raw::connection::Connection::new_server(); server .set_config(config.clone()) .expect("Failed to bind config to server connection"); server .set_client_auth_type(s2n_tls_sys::s2n_cert_auth_type::NONE) .expect("Unable to set server client auth type"); l...
pub fn s2n_tls_pair(config: crate::raw::config::Config) { // create and configure a server connection
random_line_split
htmlappletelement.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::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletEl...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub...
new_inherited
identifier_name
htmlappletelement.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::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletEl...
impl HTMLAppletElement { fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } ...
#[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement }
random_line_split
htmlappletelement.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::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletEl...
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
{ Some(self.upcast::<HTMLElement>() as &VirtualMethods) }
identifier_body
tests.rs
#[test] fn rustc_bootstrap_parsing() { let is_bootstrap = |env, krate| { std::env::set_var("RUSTC_BOOTSTRAP", env); matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat) }; assert!(is_bootstrap("1", None)); assert!(is_bootstrap("1", Some("x"))); // RUSTC_BOOTST...
use super::UnstableFeatures;
random_line_split
tests.rs
use super::UnstableFeatures; #[test] fn
() { let is_bootstrap = |env, krate| { std::env::set_var("RUSTC_BOOTSTRAP", env); matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat) }; assert!(is_bootstrap("1", None)); assert!(is_bootstrap("1", Some("x"))); // RUSTC_BOOTSTRAP allows specifying a specific c...
rustc_bootstrap_parsing
identifier_name
tests.rs
use super::UnstableFeatures; #[test] fn rustc_bootstrap_parsing()
{ let is_bootstrap = |env, krate| { std::env::set_var("RUSTC_BOOTSTRAP", env); matches!(UnstableFeatures::from_environment(krate), UnstableFeatures::Cheat) }; assert!(is_bootstrap("1", None)); assert!(is_bootstrap("1", Some("x"))); // RUSTC_BOOTSTRAP allows specifying a specific crat...
identifier_body
utils.rs
#![allow(dead_code)] extern crate ffigen; pub const HEAD: &'static str = "//! ffigen generate. #![allow(dead_code)] #![allow(non_snake_case)] #![allow(unused_attributes)] #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] use libc::*;"; pub const TAIL: &'static str = r#"#[link(name="test")] extern "C...
.arg(&format!("-I{}", ffigen::find_clang_include_path().to_string_lossy())) $( .header(&format!("{}/tests/headers/{}", env!("PWD"), $h)) )* .link($l) .format($f) .gen() }; ( $l:expr, $h:expr ) => { gen!($l, [$h], true) }; ( $...
( $l:expr, [ $( $h:expr ),* ], $f:expr ) => { GenOptions::default()
random_line_split
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
pub(crate) fn killpg(pgid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::kill(-(pgid as pid_t), signal as c_int) }).and(Ok(())) } pub(crate) fn pipe2(flags: usize) -> io::Result<(RawFd, RawFd)> { let mut fds = [0; 2]; #[cfg(not(target_os = "macos"))] cvt(unsafe { libc::pipe2(fds.as_mut_pt...
{ cvt(unsafe { libc::kill(pid as pid_t, signal as c_int) }).and(Ok(())) }
identifier_body
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
pub(crate) fn getpid() -> io::Result<u32> { cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::kill(pid as pid_t, signal as c_int) }).and(Ok(())) } pub(crate) fn killpg(pgid: u32, signal: i32) -> io::Result<()> { cvt(unsafe {...
pub unsafe fn fork() -> io::Result<u32> { cvt(libc::fork()).map(|pid| pid as u32) }
random_line_split
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
() -> bool { unsafe { libc::geteuid() == 0 } } pub unsafe fn fork() -> io::Result<u32> { cvt(libc::fork()).map(|pid| pid as u32) } pub(crate) fn getpid() -> io::Result<u32> { cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::ki...
is_root
identifier_name
mod.rs
extern crate libc; pub mod job_control; pub mod signals; use libc::{c_int, pid_t, sighandler_t}; use std::io; use std::os::unix::io::RawFd; pub(crate) const PATH_SEPARATOR: &str = ":"; pub(crate) const O_CLOEXEC: usize = libc::O_CLOEXEC as usize; pub(crate) const SIGHUP: i32 = libc::SIGHUP; pub(crate) const SIGINT:...
else { Ok(()) } } pub(crate) fn reset_signal(signal: i32) -> io::Result<()> { if unsafe { libc::signal(signal as c_int, libc::SIG_DFL) } == libc::SIG_ERR { Err(io::Error::last_os_error()) } else { Ok(()) } } pub(crate) fn tcsetpgrp(fd: RawFd, pgrp: u32) -> io::Result<()> { ...
{ Err(io::Error::last_os_error()) }
conditional_block
main.rs
extern crate typed_arena; use typed_arena::Arena; fn
() { // Memory is allocated using the default allocator (currently jemalloc). The memory is // allocated in chunks, and when one chunk is full another is allocated. This ensures that // references to an arena don't become invalid when the original chunk runs out of space. The // chunk size is configu...
main
identifier_name
main.rs
extern crate typed_arena; use typed_arena::Arena; fn main() { // Memory is allocated using the default allocator (currently jemalloc). The memory is // allocated in chunks, and when one chunk is full another is allocated. This ensures that // references to an arena don't become invalid when the original...
// TypedArena returns a mutable reference let v2 = arena.alloc(3); *v2 += 38; println!("{}", *v1 + *v2); // The arena's destructor is called as it goes out of scope, at which point it deallocates // everything stored within it at once. }
// can allocate only objects of one type. The type is determined by type inference--if you try // to allocate an integer, then Rust's compiler knows it is an integer arena. let v1 = arena.alloc(1i32);
random_line_split
main.rs
extern crate typed_arena; use typed_arena::Arena; fn main()
{ // Memory is allocated using the default allocator (currently jemalloc). The memory is // allocated in chunks, and when one chunk is full another is allocated. This ensures that // references to an arena don't become invalid when the original chunk runs out of space. The // chunk size is configurab...
identifier_body
lib.rs
//! A wonderful, fast, safe, generic radix trie implementation. //! //! To get started, see the docs for `Trie` below. // #![warn(missing_docs)] extern crate nibble_vec; extern crate endian_type; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand;
#[macro_use] mod macros; mod keys; pub mod iter; mod traversal; mod trie; mod subtrie; mod trie_node; mod trie_common; #[cfg(feature = "serde")] mod serde; #[cfg(test)] mod test; #[cfg(test)] mod qc_test; const BRANCH_FACTOR: usize = 16; /// Data-structure for storing and querying string-like keys and associated val...
pub use nibble_vec::NibbleVec; pub use keys::TrieKey; pub use trie_common::TrieCommon;
random_line_split
lib.rs
//! A wonderful, fast, safe, generic radix trie implementation. //! //! To get started, see the docs for `Trie` below. // #![warn(missing_docs)] extern crate nibble_vec; extern crate endian_type; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; pub use nibble_vec::NibbleVec; pub use keys::TrieKe...
<K, V> { /// Key fragments/bits associated with this node, such that joining the keys from all /// parent nodes and this node is equal to the bit-encoding of this node's key. key: NibbleVec, /// The key and value stored at this node. key_value: Option<Box<KeyValue<K, V>>>, /// The number of ch...
TrieNode
identifier_name
issue-23037.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 ...
() { let foo = i32x4(1,2,3,4); let bar = i32x4(40,30,20,10); let baz = foo + bar; assert!(baz.0 == 41 && baz.1 == 32 && baz.2 == 23 && baz.3 == 14); }
main
identifier_name
issue-23037.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 ...
{ let foo = i32x4(1,2,3,4); let bar = i32x4(40,30,20,10); let baz = foo + bar; assert!(baz.0 == 41 && baz.1 == 32 && baz.2 == 23 && baz.3 == 14); }
identifier_body
issue-23037.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(core)] use std::simd::i32x4; fn main() { let foo = i32x4(1,2,3,4); l...
// 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
random_line_split
bitmap.rs
// http://rosettacode.org/wiki/Basic_bitmap_storage use std::default::Default; use std::io::{Write, BufWriter, Error}; use std::fs::File; use std::ops::{Index, IndexMut}; #[derive(Copy, Clone, Default, PartialEq, Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8 } pub struct Image { ...
for y in 0..10 { for x in 5..10 { image[(x,y)] = Color { red: 255, green: 255, blue: 255 }; } } for y in 0..10 { for x in 0..10 { if image[(x,y)].red + image[(x,y)].green + image[(x,y)].blue == 0 { print!("#"); } else { ...
#[cfg(not(test))] #[allow(dead_code)] pub fn main() { let mut image = Image::new(10, 10);
random_line_split
bitmap.rs
// http://rosettacode.org/wiki/Basic_bitmap_storage use std::default::Default; use std::io::{Write, BufWriter, Error}; use std::fs::File; use std::ops::{Index, IndexMut}; #[derive(Copy, Clone, Default, PartialEq, Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8 } pub struct Image { ...
} impl Index<(usize, usize)> for Image { type Output=Color; fn index<'a>(&'a self, (x, y): (usize, usize)) -> &'a Color { &self.data[x + y*self.width] } } impl IndexMut<(usize, usize)> for Image { fn index_mut<'a>(&'a mut self, (x, y): (usize, usize)) -> &'a mut Color { & mut self.da...
{ let file = try!(File::create(filename)); let mut writer = BufWriter::new(file); try!(writeln!(&mut writer,"P6")); try!(write!(&mut writer, "{} {} {}\n", self.width, self.height, 255)); for color in &(self.data) { for channel in &[color.red, color.green, color.blue] ...
identifier_body
bitmap.rs
// http://rosettacode.org/wiki/Basic_bitmap_storage use std::default::Default; use std::io::{Write, BufWriter, Error}; use std::fs::File; use std::ops::{Index, IndexMut}; #[derive(Copy, Clone, Default, PartialEq, Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8 } pub struct Image { ...
} println!(""); } } #[cfg(test)] mod test { use super::{Color, Image}; use std::default::Default; #[test] #[should_panic] #[ignore(unused_variable)] fn out_of_bounds() { let image = Image::new(10, 10); let _ = image[(10, 11)]; assert!(false); } ...
{ print!("."); }
conditional_block
bitmap.rs
// http://rosettacode.org/wiki/Basic_bitmap_storage use std::default::Default; use std::io::{Write, BufWriter, Error}; use std::fs::File; use std::ops::{Index, IndexMut}; #[derive(Copy, Clone, Default, PartialEq, Debug)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8 } pub struct Image { ...
() { let mut image = Image::new(10, 10); for y in 0..10 { for x in 5..10 { image[(x,y)] = Color { red: 255, green: 255, blue: 255 }; } } for y in 0..10 { for x in 0..10 { if image[(x,y)].red + image[(x,y)].green + image[(x,y)].blue == 0 { ...
main
identifier_name
until_any_or_whitespace.rs
use read_token::ReadToken; use range::Range; use std::sync::Arc; use super::{ ParseResult, }; use { DebugId, MetaData, ParseError, }; use tokenizer::{ read_data, TokenizerState }; /// Stores information about reading until whitespace or any of some character. #[derive(Clone, Debug, PartialEq)] pub str...
() { let text = "fn foo()"; let mut tokens = vec![]; let s = TokenizerState::new(); let function_name: Arc<String> = Arc::new("function_name".into()); let name = UntilAnyOrWhitespace { debug_id: 0, any_characters: Arc::new("(".into()), optional...
successful
identifier_name
until_any_or_whitespace.rs
use read_token::ReadToken; use range::Range; use std::sync::Arc; use super::{ ParseResult, }; use {
}; use tokenizer::{ read_data, TokenizerState }; /// Stores information about reading until whitespace or any of some character. #[derive(Clone, Debug, PartialEq)] pub struct UntilAnyOrWhitespace { /// The characters to stop at. pub any_characters: Arc<String>, /// Whether empty data is accepted or not. ...
DebugId, MetaData, ParseError,
random_line_split
until_any_or_whitespace.rs
use read_token::ReadToken; use range::Range; use std::sync::Arc; use super::{ ParseResult, }; use { DebugId, MetaData, ParseError, }; use tokenizer::{ read_data, TokenizerState }; /// Stores information about reading until whitespace or any of some character. #[derive(Clone, Debug, PartialEq)] pub str...
} } } #[cfg(test)] mod tests { use all::*; use all::tokenizer::*; use meta_rules::UntilAnyOrWhitespace; use range::Range; use read_token::ReadToken; use std::sync::Arc; #[test] fn required() { let text = "fn ()"; let mut tokenizer = vec![]; let s = ...
{ Ok((range, state.clone(), None)) }
conditional_block
style.rs
//! Code for applying CSS styles to the DOM. //! //! This is not very interesting at the moment. It will get much more //! complicated if I add support for compound selectors. use dom::{Node, NodeType, ElementData}; use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity}; use std::collections::HashM...
{ Inline, Block, None, } impl<'a> StyledNode<'a> { /// Return the specified value of a property if it exists, otherwise `None`. pub fn value(&self, name: &str) -> Option<Value> { self.specified_values.get(name).map(|v| v.clone()) } /// Return the specified value of property `name`...
Display
identifier_name
style.rs
//! Code for applying CSS styles to the DOM. //! //! This is not very interesting at the moment. It will get much more //! complicated if I add support for compound selectors. use dom::{Node, NodeType, ElementData}; use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity}; use std::collections::HashM...
if selector.tag_name.iter().any(|name| elem.tag_name!= *name) { return false; } // Check ID selector if selector.id.iter().any(|id| elem.id()!= Some(id)) { return false; } // Check class selectors let elem_classes = elem.classes(); if selector.class.iter().any(|class|!e...
fn matches_simple_selector(elem: &ElementData, selector: &SimpleSelector) -> bool { // Check type selector
random_line_split
test_block_known.rs
// Copyright 2021 The Grin Developers // // 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 agree...
let (latest, genesis) = { let chain = mine_chain(chain_dir, 3); let genesis = chain .get_block(&chain.get_header_by_height(0).unwrap().hash()) .unwrap(); let head = chain.head().unwrap(); let latest = chain.get_block(&head.last_block_h).unwrap(); (latest, genesis) }; // attempt to reprocess latest b...
util::init_test_logger(); clean_output_dir(chain_dir); // mine some blocks
random_line_split
test_block_known.rs
// Copyright 2021 The Grin Developers // // 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 agree...
assert_eq!( res.unwrap_err().kind(), ErrorKind::Unfit("duplicate block".to_string()).into() ); } // attempt to reprocess genesis block { let chain = init_chain(chain_dir, genesis.clone()); let res = chain.process_block(genesis.clone(), chain::Options::NONE); assert_eq!( res.unwrap_err().kind(), ...
{ let chain_dir = ".grin.check_known"; util::init_test_logger(); clean_output_dir(chain_dir); // mine some blocks let (latest, genesis) = { let chain = mine_chain(chain_dir, 3); let genesis = chain .get_block(&chain.get_header_by_height(0).unwrap().hash()) .unwrap(); let head = chain.head().unwrap(); ...
identifier_body
test_block_known.rs
// Copyright 2021 The Grin Developers // // 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 agree...
() { let chain_dir = ".grin.check_known"; util::init_test_logger(); clean_output_dir(chain_dir); // mine some blocks let (latest, genesis) = { let chain = mine_chain(chain_dir, 3); let genesis = chain .get_block(&chain.get_header_by_height(0).unwrap().hash()) .unwrap(); let head = chain.head().unwrap(...
check_known
identifier_name
lib.rs
// DO NOT EDIT! // This file was generated automatically from'src/mako/api/lib.rs.mako' // DO NOT EDIT! //! This documentation was generated from *genomics* crate version *0.1.8+20150326*, where *20150326* is the exact revision of the *genomics:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code ge...
//! read by you to obtain the media. //! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. //! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making //! this call: `.param("alt", "media")`...
//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be
random_line_split
serializer.rs
is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut s).unwrap(); s } } #[inline] fn write_numeric<W>(value: f32, int_value: Option<i32>, has_sign: bool, dest: &mut W)...
<'a, W> { inner: &'a mut W, } impl<'a, W> CssStringWriter<'a, W> where W: fmt::Write, { /// Wrap a text writer to create a `CssStringWriter`. pub fn new(inner: &'a mut W) -> CssStringWriter<'a, W> { CssStringWriter { inner: inner } } } impl<'a, W> fmt::Write for CssStringWriter<'a, W> wher...
CssStringWriter
identifier_name
serializer.rs
This is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut s).unwrap(); s } } #[inline] fn write_numeric<W>(value: f32, int_value: Option<i32>, has_sign: bool, dest: &mu...
impl<W: fmt::Write> io::Write for AssumeUtf8<W> { #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { // Safety: itoa only emits ASCII, which is also well-formed UTF-8. debug_assert!(buf.is_ascii()); ...
W: fmt::Write, { struct AssumeUtf8<W: fmt::Write>(W);
random_line_split
serializer.rs
is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut s).unwrap(); s } } #[inline] fn write_numeric<W>(value: f32, int_value: Option<i32>, has_sign: bool, dest: &mut W)...
} } Ok(()) } impl<'a> ToCss for Token<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { match *self { Token::Ident(ref value) => serialize_identifier(&**value, dest)?, Token::AtKeyword(ref value) => { dest....
{ // `value.value >= 0` is true for negative 0. if has_sign && value.is_sign_positive() { dest.write_str("+")?; } let notation = if value == 0.0 && value.is_sign_negative() { // Negative zero. Work around #20596. dest.write_str("-0")?; Notation { decimal_poin...
identifier_body
managed.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 super::CanAccess; use super::CanAlloc; use super::Compartment; use super::InCompartment; use super::IsSnapshot...
} impl<'a, C, T> PartialEq for JSManaged<'a, C, T> { fn eq(&self, other: &Self) -> bool { self.raw == other.raw } } impl<'a, C, T> Eq for JSManaged<'a, C, T> { } unsafe impl<'a, C, T> JSTraceable for JSManaged<'a, C, T> where T: JSTraceable, { unsafe fn trace(&self, trc: *mut JSTracer) { ...
{ fmt.debug_struct("JSManaged") .field("js_object", &self.js_object) .field("raw", &self.raw) .finish() }
identifier_body
managed.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 super::CanAccess; use super::CanAlloc; use super::Compartment; use super::InCompartment; use super::IsSnapshot...
let raw = native as *mut _ as *mut (); // TODO: these boxes never get deallocated, which is a space leak! let boxed = Box::new(Heap::default()); boxed.set(js_object); Ok(JSManaged { js_object: Box::into_raw(boxed), raw: raw, marker: PhantomData, }) }
{ return Err(JSEvaluateErr::WrongClass); }
conditional_block
managed.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 super::CanAccess; use super::CanAlloc; use super::Compartment; use super::InCompartment; use super::IsSnapshot...
/// Check to see if the current object is in the same compartment as another. pub fn in_compartment<S, D>(self, cx: &JSContext<S>) -> Option<JSManaged<'a, D, T::ChangeCompartment>> where T: JSCompartmental<C, D>, S: InCompartment<D>, { // The jsapi rust bindings don't expose cx.compa...
random_line_split
managed.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 super::CanAccess; use super::CanAlloc; use super::Compartment; use super::InCompartment; use super::IsSnapshot...
<'b, S>(self, _: &'b JSContext<S>) -> T::Aged where S: CanAccess, C: Compartment, T: JSLifetime<'b>, T::Aged: Copy, 'a: 'b, { let result = unsafe { *(self.raw as *mut Option<T::Aged>) }; result.unwrap() } pub fn borrow<'b, S>(self, _: &'b JSContext<S>...
get
identifier_name
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
Err(msg) => println!("{}", msg) } } } fn convert_value(row: &Row, col_idx: i32) -> String { match row.get_checked::<i32, Value>(col_idx) { Ok(v) => { match v { Value::Null => "<null>".to_string(), Value::Integer(i) => i.to_string(), ...
); } println!(""); },
random_line_split
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
fn output_column(mut rows: Rows) -> () { while let Some(result_row) = rows.next() { match result_row { Ok(row) => println!("{}", convert_value(&row, 0)), Err(msg) => println!("{}", msg) } } } fn output_rows(mut rows: Rows) -> () { while let Some(result_row) = rows....
{ let mut stmt = conn.prepare(query).unwrap(); let rows = stmt.query(params).unwrap(); output(rows); }
identifier_body
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
Err(_) => "<type_fail>".to_string() } }
{ match v { Value::Null => "<null>".to_string(), Value::Integer(i) => i.to_string(), Value::Real(f) => f.to_string(), Value::Text(t) => t.to_string(), Value::Blob(_) => "<blob>".to_string() } }
conditional_block
main.rs
extern crate clap; use clap::{Arg, App}; extern crate rusqlite; use rusqlite::{Connection, Rows, Row}; use rusqlite::types::{ToSql, Value}; extern crate sqlcmdlutils; use sqlcmdlutils::dbpath::{DbPath, db_path_help, parse_db_path}; fn main() { let arg_matches = App::new("sqls - list SQLite database cont...
(mut rows: Rows) -> () { while let Some(result_row) = rows.next() { match result_row { Ok(row) => { let cc = row.column_count(); for col_idx in 0..cc { print!("{}{}" , convert_value(&row, col_idx) ,...
output_rows
identifier_name
proxyhandler.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/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
let mut proto = RootedObject::new(cx, ptr::null_mut()); if GetObjectProto(cx, proxy, proto.handle_mut()) == 0 { desc.get().obj = ptr::null_mut(); return JSTrue; } JS_GetPropertyDescriptorById(cx, proto.handle(), id, desc) } /// Defines an expando on the given `proxy`. pub unsafe exte...
{ return JSTrue; }
conditional_block
proxyhandler.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/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
(cx: *mut JSContext, proxy: HandleObject, id: HandleId, desc: MutableHandle<JSPropertyDescriptor>) -> u8 { let handler = GetProxyHandler...
get_property_descriptor
identifier_name
proxyhandler.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/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
if expando.is_null() { expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(), HandleObject::null()); assert!(!expando.is_null()); SetProxyExtra(obj.get(), JSPROXYSLOT_EXPANDO, ObjectValue(&*expando)); } expando } } /// Set the property descriptor's ob...
let mut expando = get_expando_object(obj);
random_line_split
proxyhandler.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/. */ //! Utilities for the implementation of JSAPI proxy handlers. #![deny(missing_docs)] use dom::bindings::conversi...
/// Deletes an expando off the given `proxy`. pub unsafe extern fn delete(cx: *mut JSContext, proxy: HandleObject, id: HandleId, bp: *mut ObjectOpResult) -> u8 { let expando = RootedObject::new(cx, get_expando_object(proxy)); if expando.ptr.is_null() { (*bp).code_ = 0 /* Ok...
{ //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385 let setter: *const libc::c_void = mem::transmute(desc.get().setter); let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub); if (desc.get().attrs & JSPROP_GETTER) != 0 && setter == setter_stub { (*result...
identifier_body
main.rs
use std::url::Url; use std::{cmp, mem, ptr}; use std::get_slice::GetSlice; use std::io::*; use std::process::Command; use std::ops::DerefMut; use std::syscall::SysError; use std::syscall::ENOENT; use std::to_num::ToNum; use orbital::event::Event; use orbital::Point; use orbital::Size; use self::display::Display; use ...
/// Seek pub fn seek(&mut self, pos: SeekFrom) -> Result<u64> { let end = self.window.content.size; self.seek = match pos { SeekFrom::Start(offset) => cmp::min(end as u64, cmp::max(0, offset)) as usize, SeekFrom::Current(offset) => cmp::min(end as i64, cmp::max(0, self...
{ let content = &mut self.window.content; let size = cmp::min(content.size - self.seek, buf.len()); unsafe { Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size); } self.seek += size; Ok(size) }
identifier_body
main.rs
use std::url::Url; use std::{cmp, mem, ptr}; use std::get_slice::GetSlice; use std::io::*; use std::process::Command; use std::ops::DerefMut; use std::syscall::SysError; use std::syscall::ENOENT; use std::to_num::ToNum; use orbital::event::Event; use orbital::Point; use orbital::Size; use self::display::Display; use ...
(&self) -> Result<Box<Resource>> { Ok(box Resource { window: Window::new(self.window.point, self.window.size, self.window.title.clone()), seek: self.seek, }) } /// Return the url of this resource pub fn ...
dup
identifier_name
main.rs
use std::url::Url; use std::{cmp, mem, ptr}; use std::get_slice::GetSlice; use std::io::*; use std::process::Command; use std::ops::DerefMut; use std::syscall::SysError; use std::syscall::ENOENT; use std::to_num::ToNum; use orbital::event::Event; use orbital::Point; use orbital::Size; use self::display::Display; use ...
/// Write to resource pub fn write(&mut self, buf: &[u8]) -> Result<usize> { let content = &mut self.window.content; let size = cmp::min(content.size - self.seek, buf.len()); unsafe { Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size); } ...
random_line_split
candidate.rs
use crate::bitset::Set; use crate::board::{Block, Cell, Col, Digit, Row}; /// Represents a digit in a specific cell #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct Candidate { pub cell: Cell, pub digit: Digit, } impl Candidate { /// Constructs a new ca...
(cell: u8, digit: u8) -> Candidate { assert!(cell < 81); assert!(0 < digit && digit < 10); Candidate { cell: Cell::new(cell), digit: Digit::new(digit), } } /// Returns the row of this candidate's cell #[inline] pub fn row(self) -> Row { s...
new
identifier_name
candidate.rs
use crate::bitset::Set; use crate::board::{Block, Cell, Col, Digit, Row}; /// Represents a digit in a specific cell #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct Candidate { pub cell: Cell, pub digit: Digit, } impl Candidate { /// Constructs a new ca...
#[inline] pub fn col(self) -> Col { self.cell.col() } /// Returns the field (box) of this candidate's cell #[inline] pub fn block(self) -> Block { self.cell.block() } #[inline] pub(crate) fn digit_set(self) -> Set<Digit> { self.digit.as_set() } }
/// Returns the columns of this candidate's cell
random_line_split
candidate.rs
use crate::bitset::Set; use crate::board::{Block, Cell, Col, Digit, Row}; /// Represents a digit in a specific cell #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct Candidate { pub cell: Cell, pub digit: Digit, } impl Candidate { /// Constructs a new ca...
/// Returns the columns of this candidate's cell #[inline] pub fn col(self) -> Col { self.cell.col() } /// Returns the field (box) of this candidate's cell #[inline] pub fn block(self) -> Block { self.cell.block() } #[inline] pub(crate) fn digit_set(self) -> S...
{ self.cell.row() }
identifier_body
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
fn parse_process(process_line: &str) -> Option<String> { parse(r#"users:\(\("([\w\-\+]+)""#, process_line) } fn parse_pid(process_line: &str) -> Option<String> { parse(r"pid=(\d+)", process_line) } fn parse_ip_addresses(process_line: &str) -> Option<(String, String)> { let regex = Regex::new(r"(\d{1,3}.\d...
}
random_line_split
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
let from = from_capture .unwrap() .get(1) .map_or("".into(), |s| s.as_str().into()); let to = to_capture .unwrap() .get(1) .map_or("".into(), |s| s.as_str().into()); Some((from, to)) } #[derive(Debug)] pub struct Pr...
{ return None }
conditional_block
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
(process_line: &str) -> Option<Process> { let (from, to) = match parse_ip_addresses(process_line) { Some((f, t)) => { let from = IpAddr::from_str(&f); let to = IpAddr::from_str(&t); if from.is_ok() && to.is_ok() { (from.unwrap(), to...
new
identifier_name
process_mon.rs
use std::process::Command; use regex::Regex; use std::net::IpAddr; use std::str::FromStr; fn parse(regex: &str, process_line: &str) -> Option<String> { let regex = Regex::new(regex).unwrap(); let capture = regex.captures_iter(&process_line).next(); if capture.is_none() { return None } capt...
fn parse_ip_addresses(process_line: &str) -> Option<(String, String)> { let regex = Regex::new(r"(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})+:\d+").unwrap(); let mut captures = regex.captures_iter(&process_line); let from_capture = captures.next(); let to_capture = captures.next(); if from_capture.is_none()...
{ parse(r"pid=(\d+)", process_line) }
identifier_body
board.rs
pub struct Board { sz: usize, cells: Vec<Cell> } struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hi...
(&mut self, r: usize, c: usize) -> bool { self.cells[c + r * self.sz].hit = true; self.is_ship(r, c) } fn count_ships(&self) -> usize { let mut h = 0; for i in 0..self.sz * self.sz { if self.cells[i].ship { h += 1; } } h ...
check_shot
identifier_name
board.rs
pub struct Board { sz: usize, cells: Vec<Cell> } struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hi...
else { print!("~\t"); } } println!(""); } println!("Ships: {}, Hits: {}.", self.count_ships(), self.count_hits()); } }
{ print!("*\t"); }
conditional_block
board.rs
pub struct Board { sz: usize,
struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hit: false, ship: false, }); ...
cells: Vec<Cell> }
random_line_split
board.rs
pub struct Board { sz: usize, cells: Vec<Cell> } struct Cell { hit: bool, ship: bool } impl Board { pub fn new(sz: usize) -> Board { let mut board = Board { sz: sz, cells: Vec::with_capacity(sz * sz) }; for _ in 0..sz * sz { board.cells.push(Cell { hi...
pub fn place_horizontal_ship(&mut self, x_start: usize, y: usize, len: &usize) { for x in x_start..(x_start + len) { self.cells[y * self.sz + x] = Cell { ship: true, hit: false}; } } pub fn place_vertical_ship(&mut self, x: usize, y_start: usize, len: &usize) { for y i...
{ let mut h = 0; for i in 0..self.sz * self.sz { if self.cells[i].ship { h += 1; } } h }
identifier_body
main.rs
extern crate docopt; extern crate rustc_serialize; extern crate p2j; use std::fs::File; use std::path::Path; use docopt::Docopt; use p2j::png::PNGParser; const USAGE: &'static str = " Reads png file Usage: p2j [options] <path> Options: -h --help Show this screen. -p --metadata Print PNG metadata. ...
() { let args = get_args(); let mut file = get_file(&args); PNGParser::new(&mut file) .map(|parser|{ if args.flag_metadata { p2j::png::print_chunk_headers(&parser); } }) .map_err(|_| println!("{}", "Not a valid PNG!")...
main
identifier_name
main.rs
extern crate docopt; extern crate rustc_serialize; extern crate p2j; use std::fs::File; use std::path::Path; use docopt::Docopt; use p2j::png::PNGParser; const USAGE: &'static str = " Reads png file Usage: p2j [options] <path> Options: -h --help Show this screen. -p --metadata Print PNG metadata. ...
.map(|parser|{ if args.flag_metadata { p2j::png::print_chunk_headers(&parser); } }) .map_err(|_| println!("{}", "Not a valid PNG!")); }
PNGParser::new(&mut file)
random_line_split
main.rs
extern crate docopt; extern crate rustc_serialize; extern crate p2j; use std::fs::File; use std::path::Path; use docopt::Docopt; use p2j::png::PNGParser; const USAGE: &'static str = " Reads png file Usage: p2j [options] <path> Options: -h --help Show this screen. -p --metadata Print PNG metadata. ...
}) .map_err(|_| println!("{}", "Not a valid PNG!")); }
{ p2j::png::print_chunk_headers(&parser); }
conditional_block
main.rs
//! Blinks LED1 on a msp430g2553 #![feature(intrinsics, lang_items, start, no_std)] #![no_std] #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "panic_fmt"] fn panic_fmt() ->! { loop {} } #[lang = "sized"] trait Sized {} #[lang = "copy"] trai...
($name:ident = $value:expr) => { const $name: u16 = $value as u16; } } port!(WDTCTL = 0x0120); val!(WDTPW = 0x5A00); val!(WDTHOLD = 0x0080); port!(P1OUT = 0x0021); port!(P1DIR = 0x0022); val!(BIT0 = 0x0001); #[start] #[no_stack_check] fn start(_argc: isize, _argv: *const *const u8) -> isize { unsa...
macro_rules! val {
random_line_split
main.rs
//! Blinks LED1 on a msp430g2553 #![feature(intrinsics, lang_items, start, no_std)] #![no_std] #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "panic_fmt"] fn panic_fmt() ->!
#[lang = "sized"] trait Sized {} #[lang = "copy"] trait Copy {} macro_rules! port { ($name:ident = $value:expr) => { const $name: *mut u16 = $value as *mut u16; } } macro_rules! val { ($name:ident = $value:expr) => { const $name: u16 = $value as u16; } } port!(WDTCTL = 0x0120); val!(...
{ loop {} }
identifier_body
main.rs
//! Blinks LED1 on a msp430g2553 #![feature(intrinsics, lang_items, start, no_std)] #![no_std] #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn
() {} #[lang = "panic_fmt"] fn panic_fmt() ->! { loop {} } #[lang = "sized"] trait Sized {} #[lang = "copy"] trait Copy {} macro_rules! port { ($name:ident = $value:expr) => { const $name: *mut u16 = $value as *mut u16; } } macro_rules! val { ($name:ident = $value:expr) => { const $name: u...
eh_personality
identifier_name
resolve.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } pub fn resolve_region_var(&mut self, rid: RegionVid) -> ty::Region { if!self.should(resolve_rvar) { return ty::ReInfer(ty::ReVar(rid)); } self.infcx.region_vars.resolve_var(rid) } pub fn assert_not_rvar(&mut self, rid: RegionVid, r: ty::Region) { ...
pub fn resolve_region(&mut self, orig: ty::Region) -> ty::Region { debug!("Resolve_region({})", orig.inf_str(self.infcx)); match orig { ty::ReInfer(ty::ReVar(rid)) => self.resolve_region_var(rid), _ => orig
random_line_split
resolve.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn resolve_float_var(&mut self, vid: FloatVid) -> ty::t { if!self.should(resolve_fvar) { return ty::mk_float_var(self.infcx.tcx, vid); } let node = self.infcx.get(vid); match node.possible_types { Some(t) => ty::mk_mach_float(t), None => {...
{ if !self.should(resolve_ivar) { return ty::mk_int_var(self.infcx.tcx, vid); } let node = self.infcx.get(vid); match node.possible_types { Some(IntType(t)) => ty::mk_mach_int(t), Some(UintType(t)) => ty::mk_mach_uint(t), None => { i...
identifier_body
resolve.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 ...
(&mut self, orig: ty::Region) -> fres<ty::Region> { self.err = None; let resolved = indent(|| self.resolve_region(orig) ); match self.err { None => Ok(resolved), Some(e) => Err(e) } } pub fn resolve_type(&mut self, typ: ty::t) ->...
resolve_region_chk
identifier_name
private-in-public-lint.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 ...
() {}
main
identifier_name
private-in-public-lint.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
import-glob-crate.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(globs...
random_line_split
import-glob-crate.rs
// Copyright 2012-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-M...
{ assert_eq!(size_of::<u8>(), 1); let (mut x, mut y) = (1i, 2i); swap(&mut x, &mut y); assert_eq!(x, 2); assert_eq!(y, 1); }
identifier_body
import-glob-crate.rs
// Copyright 2012-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-M...
() { assert_eq!(size_of::<u8>(), 1); let (mut x, mut y) = (1i, 2i); swap(&mut x, &mut y); assert_eq!(x, 2); assert_eq!(y, 1); }
main
identifier_name
fontchooserdialog.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
} impl_drop!(FontChooserDialog) impl_TraitWidget!(FontChooserDialog) impl gtk::ContainerTrait for FontChooserDialog {} impl gtk::BinTrait for FontChooserDialog {} impl gtk::WindowTrait for FontChooserDialog {} impl gtk::DialogTrait for FontChooserDialog {} impl gtk::FontChooserTrait for FontChooserDialog {} impl_wi...
{ let tmp = unsafe { title.with_c_str(|c_str| { ffi::gtk_font_chooser_dialog_new(c_str, match parent { Some(ref p) => GTK_WINDOW(p.get_widget()), None => GTK_WINDOW(::std::ptr::null_mut())}) }) }; if tmp.is_null...
identifier_body
fontchooserdialog.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
(title: &str, parent: Option<gtk::Window>) -> Option<FontChooserDialog> { let tmp = unsafe { title.with_c_str(|c_str| { ffi::gtk_font_chooser_dialog_new(c_str, match parent { Some(ref p) => GTK_WINDOW(p.get_widget()), None => GTK_WINDOW(::std::...
new
identifier_name
fontchooserdialog.rs
// This file is part of rgtk.
// rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but ...
//
random_line_split
main.rs
use std::fs::File; use std::io::{BufRead, BufReader}; fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; for c in s.chars() { if c < prev { return false; } prev = c; } true } fn find_longest_ordered_words(dict: Vec<String>) -> Vec<String> { let mut result ...
for s in &longest_ordered { println!("{}", s.to_string()); } }
.map(|l| l.unwrap()) .collect(); let longest_ordered = find_longest_ordered_words(lines);
random_line_split
main.rs
use std::fs::File; use std::io::{BufRead, BufReader}; fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; for c in s.chars() { if c < prev { return false; } prev = c; } true } fn find_longest_ordered_words(dict: Vec<String>) -> Vec<String> { let mut result ...
{ let lines = BufReader::new(File::open("unixdict.txt").unwrap()) .lines() .map(|l| l.unwrap()) .collect(); let longest_ordered = find_longest_ordered_words(lines); for s in &longest_ordered { println!("{}", s.to_string()); } }
identifier_body
main.rs
use std::fs::File; use std::io::{BufRead, BufReader}; fn
(s: &str) -> bool { let mut prev = '\x00'; for c in s.chars() { if c < prev { return false; } prev = c; } true } fn find_longest_ordered_words(dict: Vec<String>) -> Vec<String> { let mut result = Vec::new(); let mut longest_length = 0; for s in dict { ...
is_ordered
identifier_name
main.rs
use std::fs::File; use std::io::{BufRead, BufReader}; fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; for c in s.chars() { if c < prev { return false; } prev = c; } true } fn find_longest_ordered_words(dict: Vec<String>) -> Vec<String> { let mut result ...
} result } fn main() { let lines = BufReader::new(File::open("unixdict.txt").unwrap()) .lines() .map(|l| l.unwrap()) .collect(); let longest_ordered = find_longest_ordered_words(lines); for s in &longest_ordered { println!("{}", s.to_string()); } }
{ let n = s.len(); if n > longest_length { longest_length = n; result.truncate(0); } if n == longest_length { result.push(s.to_owned()); } }
conditional_block
grin.rs
// Copyright 2016 The Grin Developers // // 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 agree...
(server_args: &ArgMatches) { info!("Starting the Grin server..."); // just get defaults from the global config let mut server_config = GlobalConfig::default().members.unwrap().server; if let Some(port) = server_args.value_of("port") { server_config.p2p_config.as_mut().unwrap().port = port.parse().unwrap(); } ...
server_command
identifier_name
grin.rs
// Copyright 2016 The Grin Developers // // 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 agree...
} if let Some(dir) = wallet_args.value_of("dir") { wallet_config.data_file_dir = dir.to_string().clone(); } if let Some(sa) = wallet_args.value_of("api_server_address") { wallet_config.check_node_api_http_addr = sa.to_string().clone(); } match wallet_args.subcommand() { ("receive", Some(receive_args)) =...
{ let hd_seed = wallet_args.value_of("pass").expect( "Wallet passphrase required.", ); // TODO do something closer to BIP39, eazy solution right now let seed = blake2::blake2b::blake2b(32, &[], hd_seed.as_bytes()); let s = Secp256k1::new(); let key = wallet::ExtendedKey::from_seed(&s, seed.as_bytes()).expect(...
identifier_body
grin.rs
// Copyright 2016 The Grin Developers // // 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 agree...
if server_args.is_present("mine") { server_config.mining_config.as_mut().unwrap().enable_mining = true; } if let Some(wallet_url) = server_args.value_of("wallet_url") { server_config .mining_config .as_mut() .unwrap() .wallet_receiver_url = wallet_url.to_string(); } if let Some(seeds) = server_...
{ let default_ip = "127.0.0.1"; server_config.api_http_addr = format!("{}:{}", default_ip, api_port); }
conditional_block
grin.rs
// Copyright 2016 The Grin Developers // // 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 agree...
.takes_value(true)))) .get_matches(); match args.subcommand() { // server commands and options ("server", Some(server_args)) => { server_command(server_args); } // client commands and options ("client", Some(client_args)) => { match client_args.subcommand() { ("...
.index(1)) .arg(Arg::with_name("dest") .help("Send the transaction to the provided server") .short("d") .long("dest")
random_line_split
eth_filter.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....
(client: &Arc<C>, miner: &Arc<M>) -> Self { EthFilterClient { client: Arc::downgrade(client), miner: Arc::downgrade(miner), polls: Mutex::new(PollManager::new()), } } fn active(&self) -> Result<(), Error> { // TODO: only call every 30s at most. take_weak!(self.client).keep_alive(); Ok(()) } } im...
new
identifier_name
eth_filter.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....
let logs = limit_logs(logs, filter.limit); Ok(logs) }, // just empty array _ => Ok(Vec::new()), } } fn uninstall_filter(&self, index: Index) -> Result<bool, Error> { try!(self.active()); self.polls.lock().remove_poll(&index.value()); Ok(true) } }
{ let best_block = take_weak!(self.client).chain_info().best_block_number; logs.extend(pending_logs(&*take_weak!(self.miner), best_block, &filter)); }
conditional_block
eth_filter.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....
use std::sync::{Arc, Weak}; use std::collections::HashSet; use jsonrpc_core::*; use ethcore::miner::MinerService; use ethcore::filter::Filter as EthcoreFilter; use ethcore::client::{BlockChainClient, BlockID}; use util::Mutex; use v1::traits::EthFilter; use v1::types::{BlockNumber, Index, Filter, FilterChanges, Log, H2...
//! Eth Filter RPC implementation
random_line_split
01c_quick_example.rs
#[macro_use] extern crate clap; fn main()
// > A list flag // = Uses "-l" (usage is "$ myapp test -l" // > A help flag (automatically generated by clap // = Uses "-h" or "--help" (full usage "$ myapp test -h" or "$ myapp test --help") // > A version flag (automatically generated...
{ // This example shows how to create an application with several arguments using macro builder. // It combines the simplicity of the from_usage methods and the performance of the Builder Pattern. // // The example below is functionally identical to the one in 01a_quick_example.rs and 01b_quick_example....
identifier_body