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 |
|---|---|---|---|---|
pair.rs | //! Hashable pair of objects implementing `HasUid`.
use data::hash;
use data::hash::HashFun;
use data::uid_remap::FastKey;
// XXX: Rename this `FastKeyPair`.
/// An unordered pair of elements implementing `HasUid`.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
pub struct Pair {
/// first object of the p... |
else {
Pair {
first: a, second: b, ifirst: ib, isecond: ia
}
}
}
}
impl PartialEq for Pair {
#[inline]
fn eq(&self, other: &Pair) -> bool {
self.ifirst == other.ifirst && self.isecond == other.isecond
}
}
/// Tomas Wang based hash functi... | {
Pair {
first: a, second: b, ifirst: ia, isecond: ib
}
} | conditional_block |
pair.rs | //! Hashable pair of objects implementing `HasUid`.
use data::hash;
use data::hash::HashFun;
use data::uid_remap::FastKey;
// XXX: Rename this `FastKeyPair`.
/// An unordered pair of elements implementing `HasUid`.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
pub struct Pair {
/// first object of the p... |
}
| {
hash::tomas_wang_hash(
hash::key_from_pair(
p.ifirst, p.isecond
)
)
} | identifier_body |
pair.rs | //! Hashable pair of objects implementing `HasUid`.
use data::hash;
use data::hash::HashFun;
use data::uid_remap::FastKey;
// XXX: Rename this `FastKeyPair`.
/// An unordered pair of elements implementing `HasUid`.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
pub struct Pair {
/// first object of the p... | (&self, other: &Pair) -> bool {
self.ifirst == other.ifirst && self.isecond == other.isecond
}
}
/// Tomas Wang based hash function for a `Pair` object.
#[derive(RustcEncodable, RustcDecodable)]
pub struct PairTWHash { unused: usize } // FIXME: ICE with zero-sized structs
impl PairTWHash {
/// Creates... | eq | identifier_name |
pair.rs | //! Hashable pair of objects implementing `HasUid`.
use data::hash;
use data::hash::HashFun;
use data::uid_remap::FastKey;
// XXX: Rename this `FastKeyPair`.
/// An unordered pair of elements implementing `HasUid`. | pub struct Pair {
/// first object of the pair
pub first: FastKey,
/// second object of the pair
pub second: FastKey,
ifirst: usize,
isecond: usize
}
impl Pair {
/// Builds a new `Pair`.
pub fn new(a: FastKey, b: FastKey) -> Pair {
let ia = a.uid();
let ib = b.uid();
... | #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] | random_line_split |
lib.rs | #[macro_use]
extern crate syntaxis;
use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl,
minify, afndl_to_afd};
#[test]
fn | () {
let vn: NonTerminalSet = charset!('S');
let vt: TerminalSet = charset!('a');
let q0: NonTerminal = 'S';
let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a"));
let gr: GR = GR::new(vt, vn, productions, q0);
let m: M = gr_to_afndl(&gr);
println!("afndl {:?}", m);
... | grammar_to_automata_min | identifier_name |
lib.rs | #[macro_use]
extern crate syntaxis;
use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl,
minify, afndl_to_afd};
#[test]
fn grammar_to_automata_min() {
let vn: NonTerminalSet = charset!('S');
let vt: TerminalSet = charset!('a');
let q0: NonTerminal... | println!("minified {:?}", min_m);
assert_eq!(m, min_m);
//TODO: improve this test
} | println!("afd {:?}", m);
let min_m: M = minify(&m); | random_line_split |
lib.rs | #[macro_use]
extern crate syntaxis;
use syntaxis::{M, GR, NonTerminalSet, TerminalSet, NonTerminal, RegularProductions, gr_to_afndl,
minify, afndl_to_afd};
#[test]
fn grammar_to_automata_min() | {
let vn: NonTerminalSet = charset!('S');
let vt: TerminalSet = charset!('a');
let q0: NonTerminal = 'S';
let productions: RegularProductions = r_productions!(('S', "aS"), ('S', "a"));
let gr: GR = GR::new(vt, vn, productions, q0);
let m: M = gr_to_afndl(&gr);
println!("afndl {:?}", m);
... | identifier_body | |
otp_mmap.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::otp_img::OtpImg;
use crate::otp::vmem_serialize::*;
use crate::util::num_de::{self, DeferredValue};
use anyhow::{anyhow, bail, Result};
use serde::Deser... |
#[derive(Deserialize, Debug)]
struct OtpMapItem {
name: String,
#[serde(with = "num_de")]
size: usize,
#[serde(default)]
isdigest: bool,
inv_default: Option<DeferredValue>,
}
#[derive(Deserialize, Debug)]
pub struct OtpMapPartition {
name: String,
secret: bool,
#[serde(default, wit... | keys: Vec<OtpMapKey>,
digests: Vec<OtpMapDigest>,
} | random_line_split |
otp_mmap.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::otp_img::OtpImg;
use crate::otp::vmem_serialize::*;
use crate::util::num_de::{self, DeferredValue};
use anyhow::{anyhow, bail, Result};
use serde::Deser... | {
name: String,
value: DeferredValue,
}
#[derive(Deserialize, Debug)]
struct OtpMapDigest {
name: String,
iv_value: DeferredValue,
cnst_value: DeferredValue,
}
#[derive(Deserialize, Debug)]
struct OtpMapScrambling {
#[serde(with = "num_de")]
key_size: usize,
#[serde(with = "num_de")]
... | OtpMapKey | identifier_name |
otp_mmap.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::otp_img::OtpImg;
use crate::otp::vmem_serialize::*;
use crate::util::num_de::{self, DeferredValue};
use anyhow::{anyhow, bail, Result};
use serde::Deser... |
}
| {
let _: OtpImg =
deser_hjson::from_str(&read_to_string(testdata!("otp_ctrl_img_dev.hjson")).unwrap())
.unwrap();
} | identifier_body |
shrink_to_fit.rs | extern crate rand;
extern crate ropey;
use rand::Rng;
use ropey::Rope;
| let mut rng = rand::thread_rng();
let mut rope = Rope::new();
// Do a bunch of random incoherent inserts
for _ in 0..(1 << 12) {
let len = rope.len_chars().max(1);
rope.insert(rng.gen::<usize>() % len, "Hello ");
rope.insert(rng.gen::<usize>() % len, "world! ");
rope.ins... | #[test]
fn shrink_to_fit() { | random_line_split |
shrink_to_fit.rs | extern crate rand;
extern crate ropey;
use rand::Rng;
use ropey::Rope;
#[test]
fn | () {
let mut rng = rand::thread_rng();
let mut rope = Rope::new();
// Do a bunch of random incoherent inserts
for _ in 0..(1 << 12) {
let len = rope.len_chars().max(1);
rope.insert(rng.gen::<usize>() % len, "Hello ");
rope.insert(rng.gen::<usize>() % len, "world! ");
rop... | shrink_to_fit | identifier_name |
shrink_to_fit.rs | extern crate rand;
extern crate ropey;
use rand::Rng;
use ropey::Rope;
#[test]
fn shrink_to_fit() |
let rope2 = rope.clone();
rope.shrink_to_fit();
assert_eq!(rope, rope2);
assert!(rope.capacity() < rope2.capacity());
// Make sure the rope is sound
rope.assert_integrity();
rope.assert_invariants();
rope2.assert_integrity();
rope2.assert_invariants();
}
| {
let mut rng = rand::thread_rng();
let mut rope = Rope::new();
// Do a bunch of random incoherent inserts
for _ in 0..(1 << 12) {
let len = rope.len_chars().max(1);
rope.insert(rng.gen::<usize>() % len, "Hello ");
rope.insert(rng.gen::<usize>() % len, "world! ");
rope.i... | identifier_body |
backend.rs | //! Abstraction around the object writing crate
use std::convert::{TryFrom, TryInto};
use rustc_data_structures::fx::FxHashMap;
use rustc_session::Session;
use cranelift_codegen::isa::TargetIsa;
use cranelift_module::FuncId;
use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct};
use object::write::*;
u... | target_lexicon::Endianness::Little => object::Endianness::Little,
target_lexicon::Endianness::Big => object::Endianness::Big,
};
let mut metadata_object = object::write::Object::new(binary_format, architecture, endian);
metadata_object.add_file_symbol(name.as_bytes().to_vec());
f(&mut m... | };
let endian = match triple.endianness().unwrap() { | random_line_split |
backend.rs | //! Abstraction around the object writing crate
use std::convert::{TryFrom, TryInto};
use rustc_data_structures::fx::FxHashMap;
use rustc_session::Session;
use cranelift_codegen::isa::TargetIsa;
use cranelift_module::FuncId;
use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct};
use object::write::*;
u... | {
let mut builder =
ObjectBuilder::new(isa, name + ".o", cranelift_module::default_libcall_names()).unwrap();
// Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size
// is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections
... | identifier_body | |
backend.rs | //! Abstraction around the object writing crate
use std::convert::{TryFrom, TryInto};
use rustc_data_structures::fx::FxHashMap;
use rustc_session::Session;
use cranelift_codegen::isa::TargetIsa;
use cranelift_module::FuncId;
use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct};
use object::write::*;
u... | (&mut self, symbol_name: String, data: Vec<u8>) {
let segment = self.segment_name(object::write::StandardSegment::Data).to_vec();
let section_id = self.add_section(segment, b".rustc".to_vec(), object::SectionKind::Data);
let offset = self.append_section_data(section_id, &data, 1);
// For... | add_rustc_section | identifier_name |
main.rs | // Copyright 2014 Nick Fitzgerald
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | (heap: &mut heap::Heap) {
println!("Welcome to oxischeme!");
println!("C-c to exit.");
println!("");
loop {
let stdin = old_io::stdio::stdin();
let reader = read::Read::new(stdin, heap, "stdin".to_string());
print!("oxischeme> ");
for (location, read_result) in reader {... | repl | identifier_name |
main.rs | // Copyright 2014 Nick Fitzgerald
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | }
}
| {
let heap = &mut heap::Heap::new();
let mut args_were_passed = false;
for file_path in env::args().skip(1) {
args_were_passed = true;
match eval::evaluate_file(heap, file_path.as_slice()) {
Ok(_) => { },
Err(msg) => {
let mut stderr = old_io::stdio... | identifier_body |
main.rs | // Copyright 2014 Nick Fitzgerald
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | #![feature(old_path)]
#![feature(test)]
#![feature(unicode)]
#![feature(unsafe_destructor)]
use std::old_io;
use std::env;
pub mod environment;
pub mod eval;
pub mod heap;
pub mod primitives;
pub mod read;
pub mod value;
/// Start a Read -> Evaluate -> Print loop.
pub fn repl(heap: &mut heap::Heap) {
println!("W... | #![feature(collections)]
#![feature(core)]
#![feature(env)]
#![feature(old_io)] | random_line_split |
compression.rs | use libc::{c_int,size_t,intptr_t};
#[link(name="libfwnt",kind="dylib")]
extern {
fn libfwnt_lzxpress_huffman_decompress(
compressed_data: *const u8,
compressed_data_size: size_t,
uncompressed_data: *mut u8,
uncompressed_data_size: *mut size_t,
error: *mut intptr_t
) -> c_... |
}
}
| {
// TODO Handle Errors. -1 == ERROR
None
} | conditional_block |
compression.rs | use libc::{c_int,size_t,intptr_t};
#[link(name="libfwnt",kind="dylib")]
extern {
fn libfwnt_lzxpress_huffman_decompress(
compressed_data: *const u8,
compressed_data_size: size_t,
uncompressed_data: *mut u8,
uncompressed_data_size: *mut size_t,
error: *mut intptr_t
) -> c_... | // TODO Handle Errors. -1 == ERROR
None
}
}
} | random_line_split | |
compression.rs | use libc::{c_int,size_t,intptr_t};
#[link(name="libfwnt",kind="dylib")]
extern {
fn libfwnt_lzxpress_huffman_decompress(
compressed_data: *const u8,
compressed_data_size: size_t,
uncompressed_data: *mut u8,
uncompressed_data_size: *mut size_t,
error: *mut intptr_t
) -> c_... | compressed_data_ptr,
compressed_data_size,
uncompressed_data_ptr,
&mut uncompressed_data_size,
&mut error
);
if result == 1 {
uncompressed_data.set_len(
uncompressed_data_size as usize
);
Som... | {
unsafe {
// Get size of compressed data
let compressed_data_size = compressed_data.len() as size_t;
// Create compressed data pointer
let compressed_data_ptr = compressed_data.as_ptr();
let mut uncompressed_data_size: size_t = uncompressed_size;
// To hold uncomp... | identifier_body |
compression.rs | use libc::{c_int,size_t,intptr_t};
#[link(name="libfwnt",kind="dylib")]
extern {
fn libfwnt_lzxpress_huffman_decompress(
compressed_data: *const u8,
compressed_data_size: size_t,
uncompressed_data: *mut u8,
uncompressed_data_size: *mut size_t,
error: *mut intptr_t
) -> c_... | (compressed_data: &[u8],uncompressed_size: usize) -> Option<Vec<u8>> {
unsafe {
// Get size of compressed data
let compressed_data_size = compressed_data.len() as size_t;
// Create compressed data pointer
let compressed_data_ptr = compressed_data.as_ptr();
let mut uncompres... | decompress | identifier_name |
js.rs | const JS_DOM_EVENT_ATTRS: &'static [&str] = &[
// From WHATWG HTML spec 8.1.5.2 "Event handlers on elements, Document objects, and Window objects": | "onauxclick",
"onblur",
"oncancel",
"oncanplay",
"oncanplaythrough",
"onchange",
"onclick",
"onclose",
"oncontextmenu",
"oncuechange",
"ondblclick",
"ondrag",
"ondragend",
"ondragenter",
"ondragexit",
"ondragleave",
"ondragover",
"ondragstart",
... | // https://html.spec.whatwg.org/#event-handlers-on-elements,-document-objects,-and-window-objects
// https://html.spec.whatwg.org/#attributes-3 (table "List of event handler content attributes")
// Global event handlers
"onabort", | random_line_split |
js.rs | const JS_DOM_EVENT_ATTRS: &'static [&str] = &[
// From WHATWG HTML spec 8.1.5.2 "Event handlers on elements, Document objects, and Window objects":
// https://html.spec.whatwg.org/#event-handlers-on-elements,-document-objects,-and-window-objects
// https://html.spec.whatwg.org/#attributes-3 (table "List... | (attr_name: &str) -> bool {
JS_DOM_EVENT_ATTRS
.iter()
.find(|a| attr_name.eq_ignore_ascii_case(a))
.is_some()
}
| attr_is_event_handler | identifier_name |
js.rs | const JS_DOM_EVENT_ATTRS: &'static [&str] = &[
// From WHATWG HTML spec 8.1.5.2 "Event handlers on elements, Document objects, and Window objects":
// https://html.spec.whatwg.org/#event-handlers-on-elements,-document-objects,-and-window-objects
// https://html.spec.whatwg.org/#attributes-3 (table "List... | {
JS_DOM_EVENT_ATTRS
.iter()
.find(|a| attr_name.eq_ignore_ascii_case(a))
.is_some()
} | identifier_body | |
main.rs | extern crate serde_json;
extern crate gossyp_base;
extern crate gossyp_toolkit;
extern crate gossyp_lang;
use serde_json::*;
use gossyp_base::*;
use gossyp_base::basic::*;
use gossyp_toolkit::io::*;
use gossyp_toolkit::io::tool::*;
use gossyp_lang::script::*;
use gossyp_lang::script::tool::*;
fn main() | let parse_script = main_env.get_json_tool(PARSE_SCRIPT).unwrap();
let eval_script = main_env.get_json_tool(EVAL_SCRIPT).unwrap();
let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt");
// Display a prompt
display_prompt
.map(|tool| tool.invo... | {
// Start up
let main_env = DynamicEnvironment::new();
main_env.import(IoTools::new_stdio());
main_env.import(ScriptTools::new());
// Display a header
let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap();
print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NA... | identifier_body |
main.rs | extern crate serde_json;
extern crate gossyp_base;
extern crate gossyp_toolkit;
extern crate gossyp_lang;
use serde_json::*;
use gossyp_base::*;
use gossyp_base::basic::*;
use gossyp_toolkit::io::*;
use gossyp_toolkit::io::tool::*;
use gossyp_lang::script::*;
use gossyp_lang::script::tool::*;
fn main() {
// Star... | break;
}
},
Err(erm) => {
// Stop if we hit an error
print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap();
print_value.invoke(erm, &main_env).unwrap();
break... | print_string.invoke(String::from("\n"), &main_env).unwrap();
// Stop on EOF
if result.eof { | random_line_split |
main.rs | extern crate serde_json;
extern crate gossyp_base;
extern crate gossyp_toolkit;
extern crate gossyp_lang;
use serde_json::*;
use gossyp_base::*;
use gossyp_base::basic::*;
use gossyp_toolkit::io::*;
use gossyp_toolkit::io::tool::*;
use gossyp_lang::script::*;
use gossyp_lang::script::tool::*;
fn | () {
// Start up
let main_env = DynamicEnvironment::new();
main_env.import(IoTools::new_stdio());
main_env.import(ScriptTools::new());
// Display a header
let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap();
print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG... | main | identifier_name |
inline-syntax.rs | // revisions: x86_64 arm
//[x86_64] compile-flags: --target x86_64-unknown-linux-gnu
//[x86_64] check-pass
//[x86_64] needs-llvm-components: x86
//[x86_64_allowed] compile-flags: --target x86_64-unknown-linux-gnu
//[x86_64_allowed] check-pass
//[x86_64_allowed] needs-llvm-components: x86
//[arm] compile-flags: --target... | .intel_syntax noprefix
nop"
);
//[x86_64]~^^^ WARN avoid using `.intel_syntax`
//[arm]~^^^^ ERROR unknown directive
}
}
global_asm!(".intel_syntax noprefix", "nop");
//[x86_64]~^ WARN avoid using `.intel_syntax`
// Assembler errors don't have line numbers, so no erro... | {
unsafe {
asm!(".intel_syntax noprefix", "nop");
//[x86_64]~^ WARN avoid using `.intel_syntax`
//[arm]~^^ ERROR unknown directive
asm!(".intel_syntax aaa noprefix", "nop");
//[x86_64]~^ WARN avoid using `.intel_syntax`
//[arm]~^^ ERROR unknown directive
asm!(... | identifier_body |
inline-syntax.rs | // revisions: x86_64 arm
//[x86_64] compile-flags: --target x86_64-unknown-linux-gnu
//[x86_64] check-pass
//[x86_64] needs-llvm-components: x86
//[x86_64_allowed] compile-flags: --target x86_64-unknown-linux-gnu
//[x86_64_allowed] check-pass
//[x86_64_allowed] needs-llvm-components: x86
//[arm] compile-flags: --target... | () {
unsafe {
asm!(".intel_syntax noprefix", "nop");
//[x86_64]~^ WARN avoid using `.intel_syntax`
//[arm]~^^ ERROR unknown directive
asm!(".intel_syntax aaa noprefix", "nop");
//[x86_64]~^ WARN avoid using `.intel_syntax`
//[arm]~^^ ERROR unknown directive
as... | main | identifier_name |
inline-syntax.rs | // revisions: x86_64 arm | //[x86_64] needs-llvm-components: x86
//[x86_64_allowed] compile-flags: --target x86_64-unknown-linux-gnu
//[x86_64_allowed] check-pass
//[x86_64_allowed] needs-llvm-components: x86
//[arm] compile-flags: --target armv7-unknown-linux-gnueabihf
//[arm] build-fail
//[arm] needs-llvm-components: arm
#![feature(no_core, l... | //[x86_64] compile-flags: --target x86_64-unknown-linux-gnu
//[x86_64] check-pass | random_line_split |
ssh.rs | use libc::{c_char, execvp};
use std::io::prelude::*;
use std::ffi::CString;
use std::ptr;
macro_rules! c_ptr {
($x:expr) => {{ CString::new($x).unwrap().as_ptr() }}; |
if verbose { println!("Running {}", ssh_command) }
let argv: &[*const c_char] = &[c_ptr!("ssh"),
c_ptr!("-t"),
c_ptr!("-o"),
c_ptr!("StrictHostKeyChecking=no"),
c_ptr!("-... | }
fn exec_ssh(ip: &str, command: &str, verbose: bool) {
let user_host: &str = &format!("rightscale@{}", ip);
let ssh_command = format!("ssh -t -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null {} \"{}\"", user_host, command); | random_line_split |
ssh.rs | use libc::{c_char, execvp};
use std::io::prelude::*;
use std::ffi::CString;
use std::ptr;
macro_rules! c_ptr {
($x:expr) => {{ CString::new($x).unwrap().as_ptr() }};
}
fn exec_ssh(ip: &str, command: &str, verbose: bool) {
let user_host: &str = &format!("rightscale@{}", ip);
let ssh_command = format!("ssh ... |
#[cfg(test)]
mod tests {
mod ssh_command_arg {
use super::super::ssh_command_arg;
#[test]
fn no_user() {
assert_eq!("pwd".to_string(),
ssh_command_arg(None, Some("pwd".to_string())));
}
#[test]
fn no_command() {
asser... | {
exec_ssh(&ip, &ssh_command_arg(user, command), verbose);
} | identifier_body |
ssh.rs | use libc::{c_char, execvp};
use std::io::prelude::*;
use std::ffi::CString;
use std::ptr;
macro_rules! c_ptr {
($x:expr) => {{ CString::new($x).unwrap().as_ptr() }};
}
fn exec_ssh(ip: &str, command: &str, verbose: bool) {
let user_host: &str = &format!("rightscale@{}", ip);
let ssh_command = format!("ssh ... | (user: Option<String>, command: Option<String>) -> String {
let user_prefix = user.and_then(|u| Some(format!("sudo -u \"{}\"", u)));
let escaped_command = command.and_then(|c| Some(c.replace("\"", "\\\"")));
match user_prefix {
Some(u) =>
match escaped_command {
Some(c) ... | ssh_command_arg | identifier_name |
errors.rs |
use std::fmt;
use std::ops::FnOnce;
error_chain! { }
pub struct | <'a> {
value: &'a Error
}
impl<'a> fmt::Display for FormattedError<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let e = self.value;
write!(f, "{}", e)?;
let mut last_error = e.to_string();
for e in e.iter().skip(1) {
let this_err: String = e.to_string... | FormattedError | identifier_name |
errors.rs |
use std::fmt;
use std::ops::FnOnce;
error_chain! { }
pub struct FormattedError<'a> {
value: &'a Error
}
impl<'a> fmt::Display for FormattedError<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let e = self.value;
write!(f, "{}", e)?;
let mut last_error = e.to_string();
... | Ok(())
}
}
impl Error {
pub fn format<'a>(&'a self) -> FormattedError<'a> {
FormattedError{value: self}
}
}
| writeln!(f, "")?;
writeln!(f, " =>: {:?}", backtrace)?;
}
| conditional_block |
errors.rs | use std::fmt;
use std::ops::FnOnce;
error_chain! { }
pub struct FormattedError<'a> {
value: &'a Error
}
impl<'a> fmt::Display for FormattedError<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let e = self.value;
write!(f, "{}", e)?;
let mut last_error = e.to_string();
... | // The backtrace is generated with environment `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
writeln!(f, "")?;
writeln!(f, " =>: {:?}", backtrace)?;
}
Ok(())
}
}
impl Error {
pub fn format<'a>(&'a self) -> FormattedError<'a> {
For... | random_line_split | |
cast.rs | /* kernel/cast.rs
*
* Copyright (c) 2014, Chris Williams (diosix.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights t... | >(var: T)
{
unsafe
{
forget(var);
}
}
/* cast::ktransmute::<L, G>
Convert a variable from one type to another.
=> var = variable of type L to convert
<= returns variable as type G
*/
#[inline]
pub fn ktransmute<L, G>(var: L) -> G
{
unsafe
{
transmute(var)
}
}
| orget<T | identifier_name |
cast.rs | /* kernel/cast.rs
*
* Copyright (c) 2014, Chris Williams (diosix.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights t... | /* cast::ktransmute::<L, G>
Convert a variable from one type to another.
=> var = variable of type L to convert
<= returns variable as type G
*/
#[inline]
pub fn ktransmute<L, G>(var: L) -> G
{
unsafe
{
transmute(var)
}
}
| unsafe
{
forget(var);
}
}
| identifier_body |
cast.rs | /* kernel/cast.rs
*
* Copyright (c) 2014, Chris Williams (diosix.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights t... | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/* allow the kernel to recast variables */
/* grab the compiler's built-in functions */
extern "rust-intrinsic"
{
pub fn forget<T>(_: T) ... | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | random_line_split |
delete.rs | use actix_identity::Identity;
use actix_web::{error, http::header, post, web, Error, HttpResponse, Result};
use crate::DbPool;
use super::actions;
use crate::uri_helpers::*;
#[post("/likes/{id}/delete")]
pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error>... |
let pool_ = pool.clone();
let like = web::block(move || {
let conn = pool_.get()?;
actions::get_like(id.into_inner(), &conn)
})
.await?
.map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?;
let _deleted = web::block(move || {
let conn = pool.g... | {
return Result::Err(error::ErrorForbidden("You have to be logged in to see this page"));
} | conditional_block |
delete.rs | use actix_identity::Identity;
use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; |
use super::actions;
use crate::uri_helpers::*;
#[post("/likes/{id}/delete")]
pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> {
if ident.identity().is_none() {
return Result::Err(error::ErrorForbidden("You have to be logged in to see this pa... |
use crate::DbPool; | random_line_split |
delete.rs | use actix_identity::Identity;
use actix_web::{error, http::header, post, web, Error, HttpResponse, Result};
use crate::DbPool;
use super::actions;
use crate::uri_helpers::*;
#[post("/likes/{id}/delete")]
pub async fn | (ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> {
if ident.identity().is_none() {
return Result::Err(error::ErrorForbidden("You have to be logged in to see this page"));
}
let pool_ = pool.clone();
let like = web::block(move || {
let conn = ... | delete | identifier_name |
delete.rs | use actix_identity::Identity;
use actix_web::{error, http::header, post, web, Error, HttpResponse, Result};
use crate::DbPool;
use super::actions;
use crate::uri_helpers::*;
#[post("/likes/{id}/delete")]
pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error>... | Ok(HttpResponse::Found()
.append_header((header::LOCATION, likes_uri()))
.finish())
}
| {
if ident.identity().is_none() {
return Result::Err(error::ErrorForbidden("You have to be logged in to see this page"));
}
let pool_ = pool.clone();
let like = web::block(move || {
let conn = pool_.get()?;
actions::get_like(id.into_inner(), &conn)
})
.await?
.map_er... | identifier_body |
ethstore.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.... |
}
try!(self.reload_accounts());
let cache = self.cache.read();
cache.get(address).cloned().ok_or(Error::InvalidAccount)
}
}
impl SecretStore for EthStore {
fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> {
let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error... | {
return Ok(account.clone())
} | conditional_block |
ethstore.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.... | import::import_geth_accounts(&*self.dir, desired.into_iter().collect(), testnet)
}
} | random_line_split | |
ethstore.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.... |
fn get(&self, address: &Address) -> Result<SafeAccount, Error> {
{
let cache = self.cache.read();
if let Some(account) = cache.get(address) {
return Ok(account.clone())
}
}
try!(self.reload_accounts());
let cache = self.cache.read();
cache.get(address).cloned().ok_or(Error::InvalidAccount)
}
... | {
let mut cache = self.cache.write();
let accounts = try!(self.dir.load());
let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect();
mem::replace(&mut *cache, new_accounts);
Ok(())
} | identifier_body |
ethstore.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) -> Result<SafeAccount, Error> {
{
let cache = self.cache.read();
if let Some(account) = cache.get(address) {
return Ok(account.clone())
}
}
try!(self.reload_accounts());
let cache = self.cache.read();
cache.get(address).cloned().ok_or(Error::InvalidAccount)
}
}
impl S... | get | identifier_name |
service.rs | // NOTE: All this code is basically copied verbatim from its previous home in
// the Launcher module. Once all the service-related functionality that we're
// going to move over to the Supervisor has been moved, we can take a look at
// perhaps refactoring some of this a bit.
use crate::{manager::ShutdownConfig,
... | // to prevent orphaned processes.
let pgid = unsafe { libc::getpgid(self.pid) };
if self.pid == pgid {
debug!("pid to kill {} is the process group root. Sending signal to process group.",
self.pid);
// sending a signal to the negative pid sends it to t... | // if it is the root process of the process group
// we send our signals to the entire process group | random_line_split |
service.rs | // NOTE: All this code is basically copied verbatim from its previous home in
// the Launcher module. Once all the service-related functionality that we're
// going to move over to the Supervisor has been moved, we can take a look at
// perhaps refactoring some of this a bit.
use crate::{manager::ShutdownConfig,
... |
// JW TODO: Determine if the error represents a case where the
// process was already exited before we return out and assume
// so.
trace!("Sending {:?} signal to process {}",
shutdown_signal,
pid_to_kill);
#[allow(clippy::question_mark)]
i... | {
debug!("pid to kill {} is the process group root. Sending signal to process group.",
self.pid);
// sending a signal to the negative pid sends it to the
// entire process group instead just the single pid
pid_to_kill = self.pid.neg();
} | conditional_block |
service.rs | // NOTE: All this code is basically copied verbatim from its previous home in
// the Launcher module. Once all the service-related functionality that we're
// going to move over to the Supervisor has been moved, we can take a look at
// perhaps refactoring some of this a bit.
use crate::{manager::ShutdownConfig,
... | {
pid: pid_t,
}
impl Process {
fn new(pid: Pid) -> Self { Process { pid } }
/// Attempt to gracefully terminate a proccess and then forcefully
/// kill it after 8 seconds if it has not terminated.
fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod {
let ShutdownConfig { si... | Process | identifier_name |
service.rs | // NOTE: All this code is basically copied verbatim from its previous home in
// the Launcher module. Once all the service-related functionality that we're
// going to move over to the Supervisor has been moved, we can take a look at
// perhaps refactoring some of this a bit.
use crate::{manager::ShutdownConfig,
... |
/// Attempt to gracefully terminate a proccess and then forcefully
/// kill it after 8 seconds if it has not terminated.
fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod {
let ShutdownConfig { signal: shutdown_signal,
timeout, } = *shutdown_config;
... | { Process { pid } } | identifier_body |
utils.rs | use crate::errors::{ParsingError, Result};
/// Try to parse the given array of bytes into an f64, by first converting
/// it to the corresponding ASCII (or even here, UTF-8) values.
pub fn parse_f64(value : &[u8]) -> Result<f64> {
let res = std::str::from_utf8(value)?;
let res_f64 = res.parse::<f64>()?;
Ok... |
#[test]
fn test_parse_byte_range() {
assert_eq!(parse_byte_range(b"1-2").unwrap(), (1., 2.));
assert_eq!(parse_byte_range(b"100-200").unwrap(), (100., 200.));
assert!(parse_byte_range(b"").err().is_some());
assert!(parse_byte_range(b"A").err().is_some());
assert!(parse_... | assert!(parse_iso_8601_duration(b"T3S").err().is_some());
assert!(parse_iso_8601_duration(b"P3S").err().is_some());
} | random_line_split |
utils.rs | use crate::errors::{ParsingError, Result};
/// Try to parse the given array of bytes into an f64, by first converting
/// it to the corresponding ASCII (or even here, UTF-8) values.
pub fn | (value : &[u8]) -> Result<f64> {
let res = std::str::from_utf8(value)?;
let res_f64 = res.parse::<f64>()?;
Ok(res_f64 as f64)
}
/// Try to parse the given array of bytes into an i64, by first converting
/// it to the corresponding ASCII (or even here, UTF-8) values.
pub fn parse_i64(value : &[u8]) -> Resul... | parse_f64 | identifier_name |
utils.rs | use crate::errors::{ParsingError, Result};
/// Try to parse the given array of bytes into an f64, by first converting
/// it to the corresponding ASCII (or even here, UTF-8) values.
pub fn parse_f64(value : &[u8]) -> Result<f64> {
let res = std::str::from_utf8(value)?;
let res_f64 = res.parse::<f64>()?;
Ok... |
/// Try to parse the given array of bytes into an u64, by first converting
/// it to the corresponding ASCII (or even here, UTF-8) values.
pub fn parse_u64(value : &[u8]) -> Result<u64> {
let res = std::str::from_utf8(value)?;
let res_u64 = res.parse::<u64>()?;
Ok(res_u64)
}
/// Try to parse the given ar... | {
let res = std::str::from_utf8(value)?;
let res_u64 = res.parse::<i64>()?;
Ok(res_u64)
} | identifier_body |
regions-glb-free-free.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 ... | <'r>(name: &'r str, desc: &'r str) -> Flag<'r> {
Flag { name: name, desc: desc, max_count: 1, value: 0 }
}
pub impl<'self> Flag<'self> {
fn set_desc(self, s: &str) -> Flag<'self> {
Flag { //~ ERROR cannot infer an appropriate lifetime
name: self.name,
... | flag | identifier_name |
regions-glb-free-free.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 f : argparse::Flag = argparse::flag(~"flag", ~"My flag");
let updated_flag = f.set_desc(~"My new flag");
assert!(updated_flag.desc == "My new flag");
} | identifier_body | |
regions-glb-free-free.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 ... | Flag { name: name, desc: desc, max_count: 1, value: 0 }
}
pub impl<'self> Flag<'self> {
fn set_desc(self, s: &str) -> Flag<'self> {
Flag { //~ ERROR cannot infer an appropriate lifetime
name: self.name,
desc: s,
max_count: self.max_cou... | }
pub fn flag<'r>(name: &'r str, desc: &'r str) -> Flag<'r> { | random_line_split |
lib.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... | {
match res {
Ok(None) => Err(Error::NotFoundErr),
Ok(Some(o)) => Ok(o),
Err(e) => Err(e),
}
} | identifier_body | |
lib.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... | <'a> {
store: &'a Store,
batch: WriteBatch,
}
impl<'a> Batch<'a> {
/// Writes a single key and its `Writeable` value to the batch. The write
/// function must be called to "commit" the batch to storage.
pub fn put_ser<W: ser::Writeable>(mut self, key: &[u8], value: &W) -> Result<Batch<'a>, Error> {
let ser_valu... | Batch | identifier_name |
lib.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... | // limitations under the License.
//! Storage of core types using RocksDB.
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
extern crate byteorder;
extern crate grin_core as core;
extern crate rocksdb;
const SEP: u8 = ':' as u8;
us... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and | random_line_split |
flags.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library 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 Fo... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "unsupported bit flag value 0b{:b} (unknown flags: 0b{:b})",
self.actual(), self.unknown())
}
}
impl fmt::Debug for UnknownFlags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "UnknownFlags {{ actual: ... | fmt | identifier_name |
flags.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library 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 Fo... |
pub fn known(&self) -> guint { self.actual & self.known_mask }
}
pub mod prelude {
pub use super::{IntrospectedFlags, FlagsType, UnknownFlags};
pub use gtype::GType;
pub use types::guint;
}
impl ErrorTrait for UnknownFlags {
fn description(&self) -> &str {
"unknown bit flags encountered"
... | { self.actual & !self.known_mask } | identifier_body |
flags.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library 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 Fo... | #[derive(Copy, Clone)]
pub struct UnknownFlags {
actual: guint,
known_mask: guint
}
impl UnknownFlags {
pub fn new(flags: guint, known_mask: guint) -> UnknownFlags {
UnknownFlags { actual: flags, known_mask: known_mask }
}
pub fn actual(&self) -> guint { self.actual }
pub fn unknown(&s... | random_line_split | |
issue-85155.rs | // This is a test with a setup similar to issue 85155, which triggers a const eval error: a const
// argument value is outside the range expected by the `stdarch` intrinsic.
//
// It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics
// only available on x64, and internal imple... | () {
// This function triggers a PME whenever the const argument does not fit in 1-bit.
post_monomorphization_error::stdarch_intrinsic::<2>();
//~^ NOTE the above error was encountered while instantiating
}
| main | identifier_name |
issue-85155.rs | // This is a test with a setup similar to issue 85155, which triggers a const eval error: a const
// argument value is outside the range expected by the `stdarch` intrinsic.
//
// It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics
// only available on x64, and internal imple... | {
// This function triggers a PME whenever the const argument does not fit in 1-bit.
post_monomorphization_error::stdarch_intrinsic::<2>();
//~^ NOTE the above error was encountered while instantiating
} | identifier_body | |
issue-85155.rs | // This is a test with a setup similar to issue 85155, which triggers a const eval error: a const
// argument value is outside the range expected by the `stdarch` intrinsic.
//
// It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics
// only available on x64, and internal imple... |
extern crate post_monomorphization_error;
fn main() {
// This function triggers a PME whenever the const argument does not fit in 1-bit.
post_monomorphization_error::stdarch_intrinsic::<2>();
//~^ NOTE the above error was encountered while instantiating
} | // depending on the const argument value, like the `stdarch` intrinsics would.
//
// aux-build: post_monomorphization_error.rs
// build-fail: this is a post-monomorphization error, it passes check runs and requires building
// to actually fail. | random_line_split |
atomic_umin_acqrel.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_umin_acqrel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
un... |
}
type T = isize;
macro_rules! atomic_umin_acqrel_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread::spawn(move || {
let dst: *mu... | {
A { v: UnsafeCell::<T>::new(v) }
} | identifier_body |
atomic_umin_acqrel.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_umin_acqrel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread; |
// pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = isize;
macro_rules! atomic_umin_acqrel_test {
($init:expr, $value:ex... | random_line_split | |
atomic_umin_acqrel.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_umin_acqrel;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T;
struct | <T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A<T> {}
impl<T> A<T> {
fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = isize;
macro_rules! atomic_umin_acqrel_test {
($init:expr, $value:expr, $result:expr) => ({
let value: T = $init;
let a: A<T> = A::<T>:... | A | identifier_name |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::... | }
// https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count
fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult {
self.ReplaceData(offset, count, DOMString::new())
}
// https://dom.spec.whatwg.org/#dom-characterdata-replacedata
fn ReplaceData(&self, offset: u32,... | self.ReplaceData(offset, 0, arg) | random_line_split |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::... | (&self) -> u32 {
self.data.borrow().encode_utf16().count() as u32
}
// https://dom.spec.whatwg.org/#dom-characterdata-substringdata
fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
let data = self.data.borrow();
// Step 1.
let mut substring = String:... | Length | identifier_name |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::... |
fn content_changed(&self) {
let node = self.upcast::<Node>();
node.dirty(NodeDamage::OtherNodeDamage);
}
}
impl CharacterDataMethods for CharacterData {
// https://dom.spec.whatwg.org/#dom-characterdata-data
fn Data(&self) -> DOMString {
self.data.borrow().clone()
}
/... | {
self.data.borrow_mut().push_str(data);
self.content_changed();
} | identifier_body |
characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::... | ,
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => {
DomRoot::upcast(Text::new(data, &document))
},
_ => unreachable!(),
}
}
#[inline]
pub fn data(&self) -> Ref<DOMString> {
self.data.borrow()
}
#[inline]
pub fn append_... | {
let pi = self.downcast::<ProcessingInstruction>().unwrap();
DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document))
} | conditional_block |
las.rs | //! Source las points.
use std::io::{Read, Seek};
use std::path::Path;
use las;
use Result;
use point::{Intensity, Point, ScanDirection};
use source::{FileSource, Source};
impl<R: Read + Seek> Source for las::Reader<R> {
fn source(&mut self, want: usize) -> Result<Option<Vec<Point>>> {
let mut points = ... | ;
impl From<las::Point> for Point {
fn from(point: las::Point) -> Point {
Point {
x: point.x,
y: point.y,
z: point.z,
intensity: Intensity::from_u16(point.intensity),
return_number: Some(point.return_number.as_u8() as usize),
number_of... | LasConfig | identifier_name |
las.rs | //! Source las points.
use std::io::{Read, Seek};
use std::path::Path;
use las;
use Result;
use point::{Intensity, Point, ScanDirection};
use source::{FileSource, Source};
impl<R: Read + Seek> Source for las::Reader<R> {
fn source(&mut self, want: usize) -> Result<Option<Vec<Point>>> {
let mut points = ... | number_of_returns: Some(point.number_of_returns.as_u8() as usize),
gps_time: point.gps_time,
scan_direction: match point.scan_direction {
las::point::ScanDirection::Forward => ScanDirection::Forward,
las::point::ScanDirection::Backward => ScanDirection... | y: point.y,
z: point.z,
intensity: Intensity::from_u16(point.intensity),
return_number: Some(point.return_number.as_u8() as usize), | random_line_split |
f64.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-MI... | let value: f64 = consts::PI;
self * (value / 180.0)
}
} | random_line_split | |
f64.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-MI... |
#[inline]
#[deprecated]
fn max_value() -> f64 { MAX_VALUE }
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut ex... | { MIN_POS_VALUE } | identifier_body |
f64.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-MI... | () -> f64 { MAX_VALUE }
/// Returns the mantissa, exponent and sign as integers.
fn integer_decode(self) -> (u64, i16, i8) {
let bits: u64 = unsafe { mem::transmute(self) };
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
... | max_value | identifier_name |
f64.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-MI... | else { -1 };
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
let mantissa = if exponent == 0 {
(bits & 0xfffffffffffff) << 1
} else {
(bits & 0xfffffffffffff) | 0x10000000000000
};
// Exponent bias + mantissa shift
exponent -= 1023 + 52;
... | { 1 } | conditional_block |
time.rs | use std::marker::PhantomData;
use chrono;
use super::Module;
use crate::{Color, Powerline, Style};
pub struct Time<S: TimeScheme> {
time_format: &'static str,
scheme: PhantomData<S>,
}
pub trait TimeScheme {
const TIME_BG: Color;
const TIME_FG: Color;
}
impl<S: TimeScheme> Time<S> {
pub fn new(... | }
impl<S: TimeScheme> Module for Time<S> {
fn append_segments(&mut self, powerline: &mut Powerline) {
let now = chrono::offset::Local::now().format(self.time_format);
powerline.add_segment(now, Style::simple(S::TIME_FG, S::TIME_BG));
}
} | random_line_split | |
time.rs | use std::marker::PhantomData;
use chrono;
use super::Module;
use crate::{Color, Powerline, Style};
pub struct Time<S: TimeScheme> {
time_format: &'static str,
scheme: PhantomData<S>,
}
pub trait TimeScheme {
const TIME_BG: Color;
const TIME_FG: Color;
}
impl<S: TimeScheme> Time<S> {
pub fn new(... | (time_format: &'static str) -> Time<S> {
Time { time_format, scheme: PhantomData }
}
}
impl<S: TimeScheme> Module for Time<S> {
fn append_segments(&mut self, powerline: &mut Powerline) {
let now = chrono::offset::Local::now().format(self.time_format);
powerline.add_segment(now, Style::... | with_time_format | identifier_name |
time.rs | use std::marker::PhantomData;
use chrono;
use super::Module;
use crate::{Color, Powerline, Style};
pub struct Time<S: TimeScheme> {
time_format: &'static str,
scheme: PhantomData<S>,
}
pub trait TimeScheme {
const TIME_BG: Color;
const TIME_FG: Color;
}
impl<S: TimeScheme> Time<S> {
pub fn new(... |
pub fn with_time_format(time_format: &'static str) -> Time<S> {
Time { time_format, scheme: PhantomData }
}
}
impl<S: TimeScheme> Module for Time<S> {
fn append_segments(&mut self, powerline: &mut Powerline) {
let now = chrono::offset::Local::now().format(self.time_format);
power... | {
Time { time_format: "%H:%M:%S", scheme: PhantomData }
} | identifier_body |
cache_tests.rs | use std::convert::TryInto;
use std::io::Write;
use std::path::PathBuf;
use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME};
use store::Store;
use tempfile::TempDir;
use testutil::data::TestData;
use testutil::relative_paths;
use workunit_store::{RunningWorkunit, WorkunitStore};
use crate::{
CommandRunner as Command... |
#[tokio::test]
async fn recover_from_missing_store_contents() {
let (_, mut workunit) = WorkunitStore::setup_for_tests();
let (local, store, _local_runner_dir) = create_local_runner();
let (caching, _cache_dir) = create_cached_runner(local, store.clone());
let (process, _script_path, _script_dir) = create_sc... | {
let (_, mut workunit) = WorkunitStore::setup_for_tests();
let results = run_roundtrip(1, &mut workunit).await;
assert_ne!(results.uncached, results.maybe_cached);
assert_eq!(results.uncached.unwrap().exit_code, 1);
assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not... | identifier_body |
cache_tests.rs | use std::convert::TryInto;
use std::io::Write;
use std::path::PathBuf;
use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME};
use store::Store;
use tempfile::TempDir;
use testutil::data::TestData;
use testutil::relative_paths;
use workunit_store::{RunningWorkunit, WorkunitStore};
use crate::{
CommandRunner as Command... | () {
let (_, mut workunit) = WorkunitStore::setup_for_tests();
let (local, store, _local_runner_dir) = create_local_runner();
let (caching, _cache_dir) = create_cached_runner(local, store.clone());
let (process, _script_path, _script_dir) = create_script(0);
// Run once to cache the process.
let first_res... | recover_from_missing_store_contents | identifier_name |
cache_tests.rs | use std::convert::TryInto;
use std::io::Write;
use std::path::PathBuf;
use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME};
use store::Store;
use tempfile::TempDir;
use testutil::data::TestData;
use testutil::relative_paths;
use workunit_store::{RunningWorkunit, WorkunitStore};
use crate::{
CommandRunner as Command... | let (caching, _cache_dir) = create_cached_runner(local, store.clone());
let uncached_result = caching
.run(Context::default(), workunit, process.clone().into())
.await;
assert_eq!(local_result, uncached_result);
// Removing the file means that were the command to be run again without any caching, it wo... | .await;
| random_line_split |
du.rs | #![crate_name = "du"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#![allow(non_snake_case)]
extern crate getopts;
extern ... | {
path: PathBuf,
is_dir: bool,
size: u64,
blocks: u64,
nlink: u64,
created: u64,
accessed: u64,
modified: u64,
}
impl Stat {
fn new(path: &PathBuf) -> Stat {
let metadata = safe_unwrap!(fs::metadata(path));
Stat {
path: path.clone(),
is_dir: ... | Stat | identifier_name |
du.rs | #![crate_name = "du"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#![allow(non_snake_case)]
extern crate getopts;
extern ... | if!summarize || (summarize && index == len-1) {
let time_str = tm.strftime(time_format_str).unwrap();
print!("{}\t{}\t{}{}", convert_size(size), time_str, stat.path.display(), line_separator);
}
} else {
if!summarize || ... | random_line_split | |
lib.rs | extern crate ratel;
extern crate ratel_codegen;
extern crate serde_json;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use ratel::error::{Error, ParseError};
fn format_errors(errors: Vec<Error>, source: &str) -> String {
let error = errors
.into_iter()
.map(|err| {
match err { | ParseError::UnexpectedToken { start, end, source: source.to_string() }
}
}
})
.map(|err| format!("{}", err))
.collect::<Vec<String>>()
.join("\n");
format!("Error: {}", error)
}
#[wasm_bindgen]
pub fn transform(data: &str, minify: bool) -> String {
match ratel::parse(... | Error { start, end, .. } => { | random_line_split |
lib.rs | extern crate ratel;
extern crate ratel_codegen;
extern crate serde_json;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use ratel::error::{Error, ParseError};
fn | (errors: Vec<Error>, source: &str) -> String {
let error = errors
.into_iter()
.map(|err| {
match err {
Error { start, end,.. } => {
ParseError::UnexpectedToken { start, end, source: source.to_string() }
}
}
})
.map(|err| format!("{}", err))
.co... | format_errors | identifier_name |
lib.rs | extern crate ratel;
extern crate ratel_codegen;
extern crate serde_json;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use ratel::error::{Error, ParseError};
fn format_errors(errors: Vec<Error>, source: &str) -> String |
#[wasm_bindgen]
pub fn transform(data: &str, minify: bool) -> String {
match ratel::parse(&data) {
Ok(module) => {
ratel_codegen::codegen(&module, minify)
},
Err(errors) => format_errors(errors, data)
}
}
#[wasm_bindgen(js_name = generateAST)]
pub fn generate_ast(data: &str, minify: bool) -> String {
mat... | {
let error = errors
.into_iter()
.map(|err| {
match err {
Error { start, end, .. } => {
ParseError::UnexpectedToken { start, end, source: source.to_string() }
}
}
})
.map(|err| format!("{}", err))
.collect::<Vec<String>>()
.join("\n");
... | identifier_body |
lib.rs | use ini::Ini;
use ini::Properties;
use postgres::config::Config;
fn build_from_section(section: &Properties)
-> Config
{
let mut username: Option<String> = None;
let mut password: Option<String> = None;
let mut builder = Config::new();
let mut options = String::new();
for (k,v) in section.iter()
{
match k
... | }
None
}
| {
if let Ok(home) = std::env::var("HOME")
{
if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf")
{
if let Some(section) = ini.section(Some(service_name.clone()))
{
return Some(build_from_section(section));
}
}
}
let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgre... | identifier_body |
lib.rs | use ini::Ini;
use ini::Properties;
use postgres::config::Config;
fn build_from_section(section: &Properties)
-> Config
{
let mut username: Option<String> = None;
let mut password: Option<String> = None;
let mut builder = Config::new();
let mut options = String::new();
for (k,v) in section.iter()
{
match k
... |
}
None
}
| {
return Some(build_from_section(section));
} | conditional_block |
lib.rs | use ini::Ini;
use ini::Properties;
use postgres::config::Config;
fn | (section: &Properties)
-> Config
{
let mut username: Option<String> = None;
let mut password: Option<String> = None;
let mut builder = Config::new();
let mut options = String::new();
for (k,v) in section.iter()
{
match k
{
"host" =>
{ builder.host(v); },
"hostaddr" =>
{ builder.host(v); },
... | build_from_section | identifier_name |
lib.rs | use ini::Ini;
use ini::Properties;
use postgres::config::Config;
fn build_from_section(section: &Properties)
-> Config
{
let mut username: Option<String> = None;
let mut password: Option<String> = None;
let mut builder = Config::new();
let mut options = String::new();
for (k,v) in section.iter()
{
match k
... | if let Some(section) = ini.section(Some(service_name.clone()))
{
return Some(build_from_section(section));
}
}
}
let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into());
if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf")
{
if let Some(section) =... | { | random_line_split |
main.rs | &[&img]).unwrap();
Ok(view)
}
// this abstraction is provided to get a slightly better API around
// input handling
/* TODO: input, blocked by `winit`
pub struct InputHandler {
key_map: HashMap<VirtualKeyCode, bool>,
key_list: Vec<VirtualKeyCode>
}
impl InputHandler {
pub fn new() -> InputHandler {
... |
pub fn set_tile(&mut self, xpos: usize, ypos: usize, data: [f32; 4]) {
let idx = self.calc_idx(xpos, ypos);
self.tiles[idx] = TileMapData::new(data);
}
}
fn populate_tilemap<R>(tilemap: &mut TileMap<R>, tilemap_size: [usize; 2]) where R: gfx::Resources {
// paper in with dummy data
fo... | {
(ypos * self.tilemap_size[0]) + xpos
} | identifier_body |
main.rs | , &[&img]).unwrap();
Ok(view)
}
// this abstraction is provided to get a slightly better API around
// input handling
/* TODO: input, blocked by `winit`
pub struct InputHandler {
key_map: HashMap<VirtualKeyCode, bool>,
key_list: Vec<VirtualKeyCode>
}
impl InputHandler {
pub fn new() -> InputHandler {
... | pos: [vertex_x, vertex_y, 0.0],
buf_pos: [tilemap_x as f32, tilemap_y as f32]
}
})
.collect();
let index_data: Vec<u32> = plane.indexed_polygon_iter()
.triangulate()
.vertices()
.map(|i| i as u32)
... | VertexData { | random_line_split |
main.rs | &[&img]).unwrap();
Ok(view)
}
// this abstraction is provided to get a slightly better API around
// input handling
/* TODO: input, blocked by `winit`
pub struct InputHandler {
key_map: HashMap<VirtualKeyCode, bool>,
key_list: Vec<VirtualKeyCode>
}
impl InputHandler {
pub fn new() -> InputHandler {
... | (&mut self, xpos: usize, ypos: usize, data: [f32; 4]) {
let idx = self.calc_idx(xpos, ypos);
self.tiles[idx] = TileMapData::new(data);
}
}
fn populate_tilemap<R>(tilemap: &mut TileMap<R>, tilemap_size: [usize; 2]) where R: gfx::Resources {
// paper in with dummy data
for ypos in 0.. tilema... | set_tile | identifier_name |
main.rs | &[&img]).unwrap();
Ok(view)
}
// this abstraction is provided to get a slightly better API around
// input handling
/* TODO: input, blocked by `winit`
pub struct InputHandler {
key_map: HashMap<VirtualKeyCode, bool>,
key_list: Vec<VirtualKeyCode>
}
impl InputHandler {
pub fn new() -> InputHandler {
... |
if self.proj_dirty {
encoder.update_constant_buffer(&self.params.projection_cb, &self.proj_stuff);
self.proj_dirty = false;
}
if self.tm_dirty {
encoder.update_constant_buffer(&self.params.tilemap_cb, &self.tm_stuff);
self.tm_dirty = false;
... | {
encoder.update_buffer(&self.params.tilemap, &self.data, 0).unwrap();
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.