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
parsing.rs
//! Utility functions for Header implementations. use std::str; use std::fmt::{self, Display}; /// Reads a single raw string when parsing a header pub fn
<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { if raw.len()!= 1 { return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. if let Ok(s) = str::from_utf8(& unsafe { raw.get_unchecked(0) }[..]) { if s!= "" { return str::FromStr::from_str(s).ok(); ...
from_one_raw_str
identifier_name
no_0977_squares_of_a_sorted_array.rs
struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } ...
pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> { if a.is_empty() { return Vec::new(); } if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let n = a.len(); // 第一个 >= 0 的索引,或者 a.len() let r = a.iter().position(|&v| v >= 0); ...
} } ans }
conditional_block
no_0977_squares_of_a_sorted_array.rs
struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a
Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let (mut l, mut r) = (0, a.len() - 1); // 选择 l 和 r 中较大的那个,逆序放入 ans 中。 ...
: Vec<i32>) ->
identifier_name
no_0977_squares_of_a_sorted_array.rs
struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } ...
pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> { if a.is_empty() { return Vec::new(); } if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let n = a.len(); // 第一个 >= 0 的索引,或者 a.len() let r = a.iter().position(|&v| v >= 0);...
random_line_split
logger.rs
//! This module is a trimmed-down copy of rtx_core::util::logger, //! which is still waiting to get released as a crate... //! maybe there is a simple logger crate that achieves this exact behavior? use ansi_term::Colour::{Green, Red, White, Yellow}; use ansi_term::Style; use chrono::Local; use log::max_level; use log:...
(&self, metadata: &Metadata) -> bool { metadata.level() <= max_level() } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { let record_target = record.target(); let details = record.args(); let category_object = if record_target.is_empty() { "" // "unknown:unkno...
enabled
identifier_name
logger.rs
//! This module is a trimmed-down copy of rtx_core::util::logger, //! which is still waiting to get released as a crate... //! maybe there is a simple logger crate that achieves this exact behavior? use ansi_term::Colour::{Green, Red, White, Yellow}; use ansi_term::Style; use chrono::Local; use log::max_level; use log:...
let painted_message = match record.level() { Level::Info => Green.paint(message), Level::Warn => Yellow.paint(message), Level::Error => Red.paint(message), Level::Debug => Style::default().paint(message), _ => White.paint(message), } .to_string() + &deta...
random_line_split
logger.rs
//! This module is a trimmed-down copy of rtx_core::util::logger, //! which is still waiting to get released as a crate... //! maybe there is a simple logger crate that achieves this exact behavior? use ansi_term::Colour::{Green, Red, White, Yellow}; use ansi_term::Style; use chrono::Local; use log::max_level; use log:...
fn log(&self, record: &Record) { if self.enabled(record.metadata()) { let record_target = record.target(); let details = record.args(); let category_object = if record_target.is_empty() { "" // "unknown:unknown"??? } else { record_target }; // Following the re...
{ metadata.level() <= max_level() }
identifier_body
main.rs
//! See <https://github.com/matklad/cargo-xtask/>. //! //! This binary is integrated into the `cargo` command line by using an alias in //! `.cargo/config`. Run commands as `cargo xtask [command]`. #![allow(clippy::exhaustive_structs)] use std::path::PathBuf;
mod cargo; mod ci; mod flags; #[cfg(feature = "default")] mod release; #[cfg(feature = "default")] mod util; use ci::CiTask; #[cfg(feature = "default")] use release::ReleaseTask; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; fn main() { if let Err(e) = try_main() { eprintln!("{}", ...
use serde::Deserialize; use serde_json::from_str as from_json_str; #[cfg(feature = "default")]
random_line_split
main.rs
//! See <https://github.com/matklad/cargo-xtask/>. //! //! This binary is integrated into the `cargo` command line by using an alias in //! `.cargo/config`. Run commands as `cargo xtask [command]`. #![allow(clippy::exhaustive_structs)] use std::path::PathBuf; use serde::Deserialize; use serde_json::from_str as from_...
() -> Result<Self> { use std::{env, path::Path}; let path = Path::new(&env!("CARGO_MANIFEST_DIR")).join("config.toml"); let config = xshell::read_file(path)?; Ok(toml::from_str(&config)?) } } #[cfg(feature = "default")] #[derive(Debug, Deserialize)] struct GithubConfig { /// Th...
load
identifier_name
main.rs
//! See <https://github.com/matklad/cargo-xtask/>. //! //! This binary is integrated into the `cargo` command line by using an alias in //! `.cargo/config`. Run commands as `cargo xtask [command]`. #![allow(clippy::exhaustive_structs)] use std::path::PathBuf; use serde::Deserialize; use serde_json::from_str as from_...
} fn try_main() -> Result<()> { let flags = flags::Xtask::from_env()?; match flags.subcommand { flags::XtaskCmd::Help(_) => { println!("{}", flags::Xtask::HELP); Ok(()) } flags::XtaskCmd::Ci(ci) => { let task = CiTask::new(ci.version)?; t...
{ eprintln!("{}", e); std::process::exit(-1); }
conditional_block
process.rs
(arr: &[u8]) -> i32 { let a = arr[0] as u32; let b = arr[1] as u32; let c = arr[2] as u32; let d = arr[3] as u32; ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32 } ...
combine
identifier_name
process.rs
pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>, out_fd: Option<P>, err_fd: Option<P>) -> IoResult<Process> where C: ProcessConfig<K, V>, P: AsInner<FileDesc>, K: BytesContainer + Eq + Hash, V: BytesContainer { use li...
{ let r = libc::funcs::posix88::signal::kill(pid, signal as c_int); mkerr_libc(r) }
identifier_body
process.rs
_ok(), "wait(0) should either return Ok or panic"); panic!("short read on the CLOEXEC pipe") } }; } // And at this point we've reached a special time in the life of the // child. The child must now b...
random_line_split
process.rs
let b = arr[1] as u32; let c = arr[2] as u32; let d = arr[3] as u32; ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32 } let p = Process{ pid: pid }; drop(output); ...
None => {} } match cfg.uid() { Some(u) => { // When dropping privileges from root, the `setgroups` call // will remove any extraneous groups. If we don't call this, // then ev...
{ if libc::setgid(u as libc::gid_t) != 0 { fail(&mut output); } }
conditional_block
fs.rs
use std::{iter}; use std::collections::{HashMap, HashSet, VecDeque}; use prelude::*; pub struct Filesystem { pub volume: Box<Volume>, pub superblock: Superblock, pub superblock_bytes: Vec<u8>, pub superblock_dirty: bool, pub groups: Vec<Group>, pub inode_cache: HashMap<u64, Inode>, pub dirty_inos: HashSe...
(&self) -> u64 { let a = self.superblock.blocks_count as u64; let b = self.superblock.blocks_per_group as u64; (a + b - 1) / b } } pub fn mount_fs(mut volume: Box<Volume>) -> Result<Filesystem> { let mut superblock_bytes = make_buffer(1024); try!(volume.read(1024, &mut superblock_bytes[..])); let s...
group_count
identifier_name
fs.rs
use std::{iter}; use std::collections::{HashMap, HashSet, VecDeque}; use prelude::*; pub struct Filesystem { pub volume: Box<Volume>, pub superblock: Superblock, pub superblock_bytes: Vec<u8>, pub superblock_dirty: bool, pub groups: Vec<Group>, pub inode_cache: HashMap<u64, Inode>, pub dirty_inos: HashSe...
Ok(()) } pub fn make_buffer(size: u64) -> Vec<u8> { iter::repeat(0).take(size as usize).collect() }
{ try!(encode_superblock(&fs.superblock, &mut fs.superblock_bytes[..])); try!(fs.volume.write(1024, &fs.superblock_bytes[..])); fs.superblock_dirty = false; }
conditional_block
fs.rs
use std::{iter}; use std::collections::{HashMap, HashSet, VecDeque}; use prelude::*; pub struct Filesystem { pub volume: Box<Volume>, pub superblock: Superblock, pub superblock_bytes: Vec<u8>, pub superblock_dirty: bool, pub groups: Vec<Group>, pub inode_cache: HashMap<u64, Inode>, pub dirty_inos: HashSe...
} try!(flush_superblock(&mut fs, false)); Ok(fs) } pub fn flush_fs(fs: &mut Filesystem) -> Result<()> { let dirty_inos = fs.dirty_inos.clone(); for dirty_ino in dirty_inos { try!(flush_ino(fs, dirty_ino)); } for group_idx in 0..fs.group_count() { try!(flush_group(fs, group_idx)); } flush_...
{ let mut superblock_bytes = make_buffer(1024); try!(volume.read(1024, &mut superblock_bytes[..])); let superblock = try!(decode_superblock(&superblock_bytes[..], true)); let mut fs = Filesystem { volume: volume, superblock: superblock, superblock_bytes: superblock_bytes, superblock_dirty: fals...
identifier_body
fs.rs
use std::{iter}; use std::collections::{HashMap, HashSet, VecDeque}; use prelude::*; pub struct Filesystem { pub volume: Box<Volume>, pub superblock: Superblock, pub superblock_bytes: Vec<u8>, pub superblock_dirty: bool, pub groups: Vec<Group>, pub inode_cache: HashMap<u64, Inode>, pub dirty_inos: HashSe...
try!(flush_group(fs, group_idx)); } flush_superblock(fs, true) } fn flush_superblock(fs: &mut Filesystem, clean: bool) -> Result<()> { let state = if clean { 1 } else { 2 }; fs.superblock_dirty = fs.superblock_dirty || fs.superblock.state!= state; fs.superblock.state = state; if fs.superblock_dirty {...
try!(flush_ino(fs, dirty_ino)); } for group_idx in 0..fs.group_count() {
random_line_split
misc.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
{ (THIS_TRACK, env!["CARGO_PKG_VERSION"], sha()) }
identifier_body
misc.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
; format!("Parity/v{}-{}{}{}{}{}/{}/rustc{}", env!("CARGO_PKG_VERSION"), THIS_TRACK, sha3_dash, sha3, date_dash, commit_date, platform(), rustc_version()) } /// Get the standard version data for this software. pub fn version_data() -> Bytes { let mut s = RlpStream::new_list(4); let v = (env!("CARGO_PKG_VER...
{ "-" }
conditional_block
misc.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
// You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Diff misc. use Bytes; use rlp::RlpStream; use target_info::Target; include!(concat!(env!("OUT_DIR"), "/version.rs")); include!(concat!(env!("OUT_DIR"), "/rustc_version.rs")); ...
// but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details.
random_line_split
misc.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() -> (&'static str, &'static str, &'static str) { (THIS_TRACK, env!["CARGO_PKG_VERSION"], sha()) }
raw_package_info
identifier_name
macro_parser.rs
exactly like the last step) //! //! Remaining input: `a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` /...
erTtFrame>, top_elts: TokenTreeOrTokenTreeVec, sep: Option<Token>, idx: usize, up: Option<Box<MatcherPos>>, matches: Vec<Vec<Rc<NamedMatch>>>, match_lo: usize, match_cur: usize, match_hi: usize, sp_lo: BytePos, } pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, ...
Vec<Match
identifier_name
macro_parser.rs
exactly like the last step) //! //! Remaining input: `a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` /...
bind_name))) } } } &TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"), &TtToken(_, _) => (), } } let mut ret_val = HashMap::new(); let mut idx = 0; for m in ms { n_rec(p...
&TtSequence(_, ref seq) => { for next_m in &seq.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtDelimited(_, ref delim) => { for next_m in &delim.tts { n_rec(p_s, next_m, res, ret_val, idx) ...
identifier_body
macro_parser.rs
&ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) -> HashMap<Ident, Rc<NamedMatch>> { fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>], ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { ...
(Box::new(panictry!(p.parse_path(LifetimeAndTypesWithoutColons)))) } "meta" => token:
conditional_block
macro_parser.rs
looks exactly like the last step) //! //! Remaining input: `a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input:...
TtToken(_, MatchNt(..)) => { // Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. match tok { token::CloseDelim(_) => {}, ...
random_line_split
commands.rs
use std::process::{Command, Child, ExitStatus, Output, Stdio}; use std::io::{Read, Write, Error as IOError}; use std::collections::BTreeSet; use branches::Branches; use error::Error; use options::Options; pub fn spawn_piped(args: &[&str]) -> Child { Command::new(&args[0]) .args(&args[1..]) .stdin(St...
} let intersection: Vec<_> = b_tree_remotes.intersection(&b_tree_branches).cloned().collect(); { xargs.stdin.unwrap().write_all(intersection.join("\n").as_bytes()).unwrap() } let mut stderr = String::new(); xargs.stderr.unwrap().read_to_string(&mut stderr).unwrap(); // Everything...
let mut b_tree_branches = BTreeSet::new(); for branch in branches.vec.clone() { b_tree_branches.insert(branch);
random_line_split
commands.rs
use std::process::{Command, Child, ExitStatus, Output, Stdio}; use std::io::{Read, Write, Error as IOError}; use std::collections::BTreeSet; use branches::Branches; use error::Error; use options::Options; pub fn spawn_piped(args: &[&str]) -> Child { Command::new(&args[0]) .args(&args[1..]) .stdin(St...
} output.join("\n") } #[cfg(test)] mod test { use super::spawn_piped; use std::io::{Read, Write}; #[test] fn test_spawn_piped() { let echo = spawn_piped(&["grep", "foo"]); { echo.stdin.unwrap().write_all("foo\nbar\nbaz".as_bytes()).unwrap() } le...
{ output.push(s.to_owned()); }
conditional_block
commands.rs
use std::process::{Command, Child, ExitStatus, Output, Stdio}; use std::io::{Read, Write, Error as IOError}; use std::collections::BTreeSet; use branches::Branches; use error::Error; use options::Options; pub fn spawn_piped(args: &[&str]) -> Child { Command::new(&args[0]) .args(&args[1..]) .stdin(St...
}
{ let echo = spawn_piped(&["grep", "foo"]); { echo.stdin.unwrap().write_all("foo\nbar\nbaz".as_bytes()).unwrap() } let mut stdout = String::new(); echo.stdout.unwrap().read_to_string(&mut stdout).unwrap(); assert_eq!(stdout, "foo\n"); }
identifier_body
commands.rs
use std::process::{Command, Child, ExitStatus, Output, Stdio}; use std::io::{Read, Write, Error as IOError}; use std::collections::BTreeSet; use branches::Branches; use error::Error; use options::Options; pub fn
(args: &[&str]) -> Child { Command::new(&args[0]) .args(&args[1..]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap_or_else(|e| panic!("Error with child process: {}", e)) } pub fn run_command_with_no_output(args: &[&str]) { Comma...
spawn_piped
identifier_name
test.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 ...
_ => { debug!("this is a test function"); let test = Test { span: i.span, path: self.cx.path.clone(), bench: is_bench_fn(i), ignore: is_ignored(self.cx, i), ...
{ let sess = self.cx.sess; sess.span_fatal(i.span, "unsafe functions cannot be used for \ tests"); }
conditional_block
test.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Code that genera...
// 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. //
random_line_split
test.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 ...
return has_bench_attr && has_test_signature(i); } fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool { i.attrs.iter().any(|attr| { // check ignore(cfg(foo, bar)) "ignore" == attr.name() && match attr.meta_item_list() { Some(ref cfgs) => attr::test_cfg(cx.config, cfgs.iter().m...
{ match i.node { ast::item_fn(ref decl, _, _, ref generics, _) => { let input_cnt = decl.inputs.len(); let no_output = match decl.output.node { ast::ty_nil => true, _ => false }; let tparm_cnt = g...
identifier_body
test.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 ...
(ids: ~[ast::Ident]) -> ast::Path { ast::Path { span: dummy_sp(), global: false, segments: ids.move_iter().map(|identifier| ast::PathSegment { identifier: identifier, lifetimes: opt_vec::Empty, types: opt_vec::Empty, }).collect() } } fn path_n...
path_node
identifier_name
ethertype.rs
use core::convert::TryFrom; use num_enum::TryFromPrimitive; use serde::{Deserialize, Serialize}; /// https://en.wikipedia.org/wiki/EtherType#Examples #[derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TryFromPrimitive, Deserialize, Serialize, )] #[repr(u16)]...
pub fn from_bytes(bytes: &[u8]) -> Self { let n = u16::from_be_bytes([bytes[0], bytes[1]]); Self::try_from(n).unwrap_or_else(|_| panic!("Unknwn EtherType {:04x}", n)) } pub fn to_bytes(self) -> [u8; 2] { u16::to_be_bytes(self as u16) } }
EthernetFlowControl = 0x8808, EthernetSlowProtocol = 0x8809, } impl EtherType {
random_line_split
ethertype.rs
use core::convert::TryFrom; use num_enum::TryFromPrimitive; use serde::{Deserialize, Serialize}; /// https://en.wikipedia.org/wiki/EtherType#Examples #[derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TryFromPrimitive, Deserialize, Serialize, )] #[repr(u16)]...
(bytes: &[u8]) -> Self { let n = u16::from_be_bytes([bytes[0], bytes[1]]); Self::try_from(n).unwrap_or_else(|_| panic!("Unknwn EtherType {:04x}", n)) } pub fn to_bytes(self) -> [u8; 2] { u16::to_be_bytes(self as u16) } }
from_bytes
identifier_name
ethertype.rs
use core::convert::TryFrom; use num_enum::TryFromPrimitive; use serde::{Deserialize, Serialize}; /// https://en.wikipedia.org/wiki/EtherType#Examples #[derive( Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TryFromPrimitive, Deserialize, Serialize, )] #[repr(u16)]...
}
{ u16::to_be_bytes(self as u16) }
identifier_body
bytes.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::types::{Intern, RawInternKey}; use fnv::FnvHashMap; use lazy_static::lazy_static; use parking_lot::RwLock; use serde::{D...
} } fn new_buffer() -> &'static mut [u8] { Box::leak(Box::new([0; Self::BUFFER_SIZE])) } pub fn get(&self, value: &[u8]) -> Option<RawInternKey> { self.table.get(value).cloned() } // Copy the byte slice into'static memory by appending it to a buffer, if there is room. ...
random_line_split
bytes.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::types::{Intern, RawInternKey}; use fnv::FnvHashMap; use lazy_static::lazy_static; use parking_lot::RwLock; use serde::{D...
() -> Self { Self { buffer: Some(Self::new_buffer()), items: Default::default(), table: Default::default(), } } fn new_buffer() -> &'static mut [u8] { Box::leak(Box::new([0; Self::BUFFER_SIZE])) } pub fn get(&self, value: &[u8]) -> Option<Raw...
new
identifier_name
bytes.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::types::{Intern, RawInternKey}; use fnv::FnvHashMap; use lazy_static::lazy_static; use parking_lot::RwLock; use serde::{D...
// Copy the byte slice into'static memory by appending it to a buffer, if there is room. // If the buffer fills up and the value is small, start over with a new buffer. // If the value is large, just give it its own memory. fn alloc(&mut self, value: &[u8]) -> &'static [u8] { let len = value.l...
{ self.table.get(value).cloned() }
identifier_body
bytes.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::types::{Intern, RawInternKey}; use fnv::FnvHashMap; use lazy_static::lazy_static; use parking_lot::RwLock; use serde::{D...
} let (mem, remaining) = buffer.split_at_mut(len); mem.copy_from_slice(value); self.buffer = Some(remaining); mem } pub fn intern(&mut self, value: &[u8]) -> RawInternKey { // If there's an existing value return it if let Some(prev) = self.get(&value) ...
{ buffer = Self::new_buffer() }
conditional_block
init-res-into-things.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 test_tup() { let i = &Cell::new(0); { let _a = (r(i), 0); } assert_eq!(i.get(), 1); } fn test_unique() { let i = &Cell::new(0); { let _a = box r(i); } assert_eq!(i.get(), 1); } fn test_unique_rec() { let i = &Cell::new(0); { let _a = box BoxR { ...
let i = &Cell::new(0); { let _a = t::t0(r(i)); } assert_eq!(i.get(), 1);
random_line_split
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a> { i: &'a Cell<int>, } struct BoxR<'a> { x: r<'a> } #[unsafe_destructor] impl<'a> Drop for r<'a> { fn drop(&mut self) { self.i.set(self.i.get() + 1) } } fn r(i: &Cell<int>) -> r { r { i: i } } fn test_rec() { let i = &Cell::new(0); { let _a = BoxR {x: r(i)}; ...
r
identifier_name
kindck-inherited-copy-bound.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = box 3is; take_param(&x); //~ ERROR `core::marker::Copy` is not implemented } fn b() { let x = box 3is; let y = &x; let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented } fn main() { }
a
identifier_name
kindck-inherited-copy-bound.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that Cop...
random_line_split
kindck-inherited-copy-bound.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 a() { let x = box 3is; take_param(&x); //~ ERROR `core::marker::Copy` is not implemented } fn b() { let x = box 3is; let y = &x; let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented } fn main() { }
{ }
identifier_body
opt_name.rs
//! Test optional prefix. extern crate flame; extern crate flamer; use flamer::{flame, noflame}; #[flame("top")] fn a() { let l = Lower {}; l.a(); } #[flame] fn b()
#[noflame] fn c() { b() } pub struct Lower; impl Lower { #[flame("lower")] pub fn a(self) { // nothing to do here } } #[test] fn main() { c(); let spans = flame::spans(); assert_eq!(1, spans.len()); let roots = &spans[0]; println!("{:?}",roots); // if more than 2 roo...
{ a() }
identifier_body
opt_name.rs
//! Test optional prefix. extern crate flame;
fn a() { let l = Lower {}; l.a(); } #[flame] fn b() { a() } #[noflame] fn c() { b() } pub struct Lower; impl Lower { #[flame("lower")] pub fn a(self) { // nothing to do here } } #[test] fn main() { c(); let spans = flame::spans(); assert_eq!(1, spans.len()); let ...
extern crate flamer; use flamer::{flame, noflame}; #[flame("top")]
random_line_split
opt_name.rs
//! Test optional prefix. extern crate flame; extern crate flamer; use flamer::{flame, noflame}; #[flame("top")] fn a() { let l = Lower {}; l.a(); } #[flame] fn b() { a() } #[noflame] fn
() { b() } pub struct Lower; impl Lower { #[flame("lower")] pub fn a(self) { // nothing to do here } } #[test] fn main() { c(); let spans = flame::spans(); assert_eq!(1, spans.len()); let roots = &spans[0]; println!("{:?}",roots); // if more than 2 roots, a() was flame...
c
identifier_name
builtin.rs
use env::UserEnv; use getopts::Options; use std::collections::HashMap; use std::env; use std::io; use std::io::prelude::*; use std::path::{Component, Path, PathBuf}; use job; const SUCCESS: io::Result<i32> = Ok(0); pub trait Builtin { fn run(&mut self, args: &[String], env: &mut UserEnv) -> io::Result<i32>; ...
(&self) -> TestList<Self> { vec![ test!("cd, no args", cd_with_no_args), test!("cd, absolute arg", cd_with_absolute_arg), test!("cd, relative arg", cd_with_relative_arg), test!("cd, previous dir", cd_previous_directory), ] }...
tests
identifier_name
builtin.rs
use env::UserEnv; use getopts::Options; use std::collections::HashMap; use std::env; use std::io; use std::io::prelude::*; use std::path::{Component, Path, PathBuf}; use job; const SUCCESS: io::Result<i32> = Ok(0); pub trait Builtin { fn run(&mut self, args: &[String], env: &mut UserEnv) -> io::Result<i32>; ...
Component::CurDir => continue, _ => normalized_path.push(c.as_os_str()), }; } normalized_path } impl Builtin for Cd { fn run(&mut self, args: &[String], env: &mut UserEnv) -> io::Result<i32> { if args.len() == 0 { let home = env.get("HOME"); ...
{ normalized_path.pop(); }
conditional_block
builtin.rs
use env::UserEnv; use getopts::Options; use std::collections::HashMap; use std::env; use std::io; use std::io::prelude::*; use std::path::{Component, Path, PathBuf}; use job; const SUCCESS: io::Result<i32> = Ok(0); pub trait Builtin { fn run(&mut self, args: &[String], env: &mut UserEnv) -> io::Result<i32>; ...
} fn pwd(_args: &[String], env: &mut UserEnv) -> io::Result<i32> { println!("{}", env.get("PWD")); SUCCESS } fn echo(args: &[String], _env: &mut UserEnv) -> io::Result<i32> { let mut opts = Options::new(); opts.optflag("n", "", "Suppress new lines"); let matches = match opts.parse(args) { ...
{ Box::new(self.clone()) }
identifier_body
builtin.rs
use env::UserEnv; use getopts::Options; use std::collections::HashMap; use std::env; use std::io; use std::io::prelude::*; use std::path::{Component, Path, PathBuf}; use job; const SUCCESS: io::Result<i32> = Ok(0); pub trait Builtin { fn run(&mut self, args: &[String], env: &mut UserEnv) -> io::Result<i32>; ...
let fixture = BuiltinTests::new(); test_fixture_runner(fixture); } }
#[test] fn builtin_tests() {
random_line_split
struct-partial-move-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// <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. #[derive(PartialEq, Debug)] pub struct Partial<T> { x: T, y: T } #[derive(PartialEq, Debug)] struct S { val: isize } impl S { fn new(v: isize) -> S { S {...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
struct-partial-move-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ val: isize } impl S { fn new(v: isize) -> S { S { val: v } } } impl Drop for S { fn drop(&mut self) { } } pub fn f<T, F>((b1, b2): (T, T), mut f: F) -> Partial<T> where F: FnMut(T) -> T { let p = Partial { x: b1, y: b2 }; // Move of `p` is legal even though we are also moving `p.y`; the // `..p` moves ...
S
identifier_name
zbytes.rs
//! The `zbyte` module contains code //! to deal with opcodes and zcode. /// A struct that holds an array of bytes and provides some convenience functions. pub struct Bytes { /// The underlying data pub bytes: Vec<u8> } impl Bytes { /// Returns the length of the byte array. pub fn len(&self) -> usize ...
/// /// `=> [index-1] == 0; [index] == nil;` pub fn write_zero_until(&mut self, index: usize) { while self.len() < index { self.bytes.push(0); } } /// Prints the underlying byte array pub fn print(&self) { debug!("bytes: {:?}", self.bytes); } }
/// Fills everything with zeros until but not including the index.
random_line_split
zbytes.rs
//! The `zbyte` module contains code //! to deal with opcodes and zcode. /// A struct that holds an array of bytes and provides some convenience functions. pub struct Bytes { /// The underlying data pub bytes: Vec<u8> } impl Bytes { /// Returns the length of the byte array. pub fn len(&self) -> usize ...
(&mut self, byte: u8) { let index: usize = self.bytes.len(); self.write_byte(byte, index); } /// Writes a u16 in two bytes with the correct byte-order for the Z-Machine at the specified /// index. pub fn write_u16(&mut self, value: u16, index: usize) { self.write_byte((value >> ...
append_byte
identifier_name
closeevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::CloseEvent...
else { EventCancelable::NotCancelable }; Ok(CloseEvent::new(global, type_, bubbles, cancelable, init.wasClean, init.code, init.reason.clone())) } } impl<'a> CloseEventMethods for &'a CloseEvent { // https://html.spec.whatwg.org/multipage/#dom-closeevent-w...
{ EventCancelable::Cancelable }
conditional_block
closeevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::CloseEvent...
// https://html.spec.whatwg.org/multipage/#dom-closeevent-reason fn Reason(self) -> DOMString { self.reason.clone() } }
{ self.code }
identifier_body
closeevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::CloseEvent...
reason: DOMString, } impl CloseEvent { pub fn new_inherited(type_id: EventTypeId, wasClean: bool, code: u16, reason: DOMString) -> CloseEvent { CloseEvent { event: Event::new_inherited(type_id), wasClean: wasClean, code: code, rea...
#[derive(HeapSizeOf)] pub struct CloseEvent { event: Event, wasClean: bool, code: u16,
random_line_split
closeevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::CloseEvent...
(global: GlobalRef, type_: DOMString, bubbles: EventBubbles, cancelable: EventCancelable, wasClean: bool, code: u16, reason: DOMString) -> Root<CloseEvent> { let event = box CloseEvent::new_inherited(EventTypeId::CloseEven...
new
identifier_name
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use prost_build::Config; fn
() -> Result<(), Box<dyn std::error::Error>> { let mut config = Config::new(); config.bytes(&["."]); tonic_build::configure() .build_client(true) .build_server(true) .compile_with_config( config, &[ "protos/bazelbuild_remote-apis/build/bazel/remote/execution/v2/remote_execution.proto...
main
identifier_name
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use prost_build::Config; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut config = Config::new(); config.bytes(&["."]); tonic_build::configure() .build_client(tru...
)?; Ok(()) }
],
random_line_split
build.rs
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use prost_build::Config; fn main() -> Result<(), Box<dyn std::error::Error>>
&[ "protos/bazelbuild_remote-apis", "protos/buildbarn", "protos/googleapis", "protos/standard", ], )?; Ok(()) }
{ let mut config = Config::new(); config.bytes(&["."]); tonic_build::configure() .build_client(true) .build_server(true) .compile_with_config( config, &[ "protos/bazelbuild_remote-apis/build/bazel/remote/execution/v2/remote_execution.proto", "protos/bazelbuild_remote-apis/...
identifier_body
lib.rs
extern crate httparse; extern crate hyper; extern crate mio; extern crate netbuf; extern crate rotor; extern crate unicase; extern crate url; extern crate time; extern crate multimap; use rotor::transports::{accept, stream}; pub use hyper::method::Method; pub use hyper::status::StatusCode; pub use hyper::version::Htt...
pub type HttpServer<C, R> = accept::Serve<C, TcpListener, stream::Stream<C, TcpStream, http1::Client<C, R>>>;
pub mod http1; mod message; mod request; mod response;
random_line_split
bind-by-move-neither-can-live-while-the-other-survives-4.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 main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
} }
random_line_split
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
identifier_body
bind-by-move-neither-can-live-while-the-other-survives-4.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) { error!("destructor runs"); } } fn main() { let x = Some((X { x: () }, X { x: () })); match x { Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
finalize
identifier_name
bind-by-move-neither-can-live-while-the-other-survives-4.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 ...
, //~ ERROR cannot bind by-move and by-ref in the same pattern None => fail!() } }
{ }
conditional_block
lib.rs
//! Binding Rust with Python, both ways! //! //! This library will generate and handle type conversions between Python and //! Rust. To use Python from Rust refer to the //! [library wiki](https://github.com/iduartgomez/rustypy/wiki), more general examples //! and information on how to use Rust in Python can also be fo...
} else { // function w/o arguments fndef.push_str("::();"); } if add { match output { syn::ReturnType::Default => fndef.push_str("type(void)"), syn::ReturnType::Type(_, ty) => { ...
});
random_line_split
lib.rs
//! Binding Rust with Python, both ways! //! //! This library will generate and handle type conversions between Python and //! Rust. To use Python from Rust refer to the //! [library wiki](https://github.com/iduartgomez/rustypy/wiki), more general examples //! and information on how to use Rust in Python can also be fo...
#[cfg(test)] mod parsing_tests { use super::*; #[test] #[ignore] fn parse_lib() { let path = std::env::home_dir() .unwrap() .join("workspace/sources/rustypy_debug/rust_code/src/lib.rs"); // let path_ori: std::path::PathBuf = std::env::current_dir().unwrap(); ...
{ match krate.iter_krate(idx as usize) { Some(val) => PyString::from(val).into_raw(), None => PyString::from("NO_IDX_ERROR").into_raw(), } }
identifier_body
lib.rs
//! Binding Rust with Python, both ways! //! //! This library will generate and handle type conversions between Python and //! Rust. To use Python from Rust refer to the //! [library wiki](https://github.com/iduartgomez/rustypy/wiki), more general examples //! and information on how to use Rust in Python can also be fo...
(krate: &KrateData) -> size_t { krate.collected.len() } #[doc(hidden)] #[no_mangle] pub extern "C" fn krate_data_iter(krate: &KrateData, idx: size_t) -> *mut PyString { match krate.iter_krate(idx as usize) { Some(val) => PyString::from(val).into_raw(), None => PyString::from("NO_IDX_ERROR").int...
krate_data_len
identifier_name
project-cache-issue-31849.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 ...
() { // More parens, more time. let it = ((((((((((),()),()),()),()),()),()),()),()),()); it.build(); }
main
identifier_name
project-cache-issue-31849.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 ...
} pub trait ToStatic { type Static:'static; fn to_static(self) -> Self::Static where Self: Sized; } impl<T, U> ToStatic for (T, U) where T: ToStatic, U: ToStatic { type Static = (T::Static, U::Static); fn to_static(self) -> Self::Static { (self.0.to_static(), self.1.to_static()) } } im...
{ () }
identifier_body
project-cache-issue-31849.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn upcast(self) -> () { () } } pub trait ToStatic { type Static:'static; fn to_static(self) -> Self::Static where Self: Sized; } impl<T, U> ToStatic for (T, U) where T: ToStatic, U: ToStatic { type Static = (T::Static, U::Static); fn to_static(self) -> Self::Static { (self.0.to_stati...
impl Upcast<()> for () {
random_line_split
tri10.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 10 nodes (cubic edges; interior node) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// 5 7, /// | ', /// | ', /// 8 9 4, /// | ', /// | (0,0) ', (1,0) /// 0-----3---...
deriv[3][0] = q2 - q7; deriv[4][0] = s * q5; deriv[5][0] = -q1; deriv[6][0] = z * q5 - q3; deriv[7][0] = q1; deriv[8][0] = -q6; deriv[9][0] = 27.0 * s * (z - r); deriv[0][1] = q8; deriv[1][1] = 0.0; deriv[2][1] = q9; deriv[3][1] = ...
{ let (r, s) = (ksi[0], ksi[1]); let z = 1.0 - r - s; let q0 = 4.5 * (6.0 * z - 1.0); let q1 = 4.5 * s * (3.0 * s - 1.0); let q2 = 4.5 * z * (3.0 * z - 1.0); let q3 = 4.5 * r * (3.0 * r - 1.0); let q4 = 4.5 * (6.0 * s - 1.0); let q5 = 4.5 * (6.0 * r - 1....
identifier_body
tri10.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 10 nodes (cubic edges; interior node) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// 5 7, /// | ', /// | ', /// 8 9 4, /// | ', /// | (0,0) ', (1,0) /// 0-----3---...
/// ``` /// /// # Local IDs of edges /// /// ```text /// |\ /// | \ /// | \ 1 /// 2| \ /// | \ /// |_____\ /// 0 /// ``` pub struct Tri10 {} impl Tri10 { pub const NDIM: usize = 2; pub const NNODE: usize = 10; pub const NEDGE: usize = 3; pub const NFACE: usize = 0; pub const EDGE_NNO...
random_line_split
tri10.rs
use russell_lab::{Matrix, Vector}; /// Defines a triangle with 10 nodes (cubic edges; interior node) /// /// # Local IDs of nodes /// /// ```text /// s /// | /// 2, (0,1) /// | ', /// | ', /// 5 7, /// | ', /// | ', /// 8 9 4, /// | ', /// | (0,0) ', (1,0) /// 0-----3---...
(deriv: &mut Matrix, ksi: &[f64]) { let (r, s) = (ksi[0], ksi[1]); let z = 1.0 - r - s; let q0 = 4.5 * (6.0 * z - 1.0); let q1 = 4.5 * s * (3.0 * s - 1.0); let q2 = 4.5 * z * (3.0 * z - 1.0); let q3 = 4.5 * r * (3.0 * r - 1.0); let q4 = 4.5 * (6.0 * s - 1.0); ...
calc_deriv
identifier_name
mono.rs
/* * Monochrome filter */ #pragma version(1) #pragma rs java_package_name(se.embargo.onebit.filter) rs_allocation gIn; rs_allocation gOut; rs_script gScript; const static float3 gMonoMult = {0.299f, 0.587f, 0.114f}; void root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) {
} void filter() { int64_t t1 = rsUptimeMillis(); rsForEach(gScript, gIn, gOut, 0); int64_t t2 = rsUptimeMillis(); rsDebug("Monochrome filter in (ms)", t2 - t1); }
float4 pixel = rsUnpackColor8888(*v_in); float3 mono = dot(pixel.rgb, gMonoMult); *v_out = rsPackColorTo8888(mono);
random_line_split
game_data.rs
use chess_pgn_parser::{Game, GameTermination}; use regex::{Captures,Regex}; use super::{GameData, MoveData}; pub struct GameMappingError {
pub error: GameError, } pub enum GameError { UnknownGameTermination, MissingComment { ply: u32 }, BadComment { ply: u32 }, } pub fn map_game_data(games: &Vec<Game>) -> Result<Vec<GameData>, GameMappingError> { let mut result: Vec<GameData> = Vec::with_capacity(games.len()); let comment_p...
pub game_number: u32,
random_line_split
game_data.rs
use chess_pgn_parser::{Game, GameTermination}; use regex::{Captures,Regex}; use super::{GameData, MoveData}; pub struct GameMappingError { pub game_number: u32, pub error: GameError, } pub enum GameError { UnknownGameTermination, MissingComment { ply: u32 }, BadComment { ply: u32 }, } pub fn map_...
{ re: Regex } impl CommentParser { pub fn new() -> CommentParser { let re = Regex::new(r"(?x) ^(?P<sign>(-|\+)?) ((?P<mate>M\d+)|((?P<eval>\d+)(\.(?P<eval_dec>\d{2})))) /\d+\s ((?P<time>\d+)(\.(?P<time_dec>\d{1,3}))?s) ").unwr...
CommentParser
identifier_name
game_data.rs
use chess_pgn_parser::{Game, GameTermination}; use regex::{Captures,Regex}; use super::{GameData, MoveData}; pub struct GameMappingError { pub game_number: u32, pub error: GameError, } pub enum GameError { UnknownGameTermination, MissingComment { ply: u32 }, BadComment { ply: u32 }, } pub fn map_...
fn get_eval(captures: &Captures) -> i32 { let mut result = 0; result += match captures.name("mate") { None | Some("") => 0, Some(_) => 10000, }; result += match captures.name("eval") { None | Some("") => 0, Some(value) => 100 * valu...
{ let captures_opt = self.re.captures(comment); if captures_opt.is_none() { return Err(()); } let captures = captures_opt.unwrap(); let eval = CommentParser::get_eval(&captures); let time = CommentParser::get_time(&captures); Ok(MoveData { eval: eva...
identifier_body
c_windows.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 ...
lpMode: libc::DWORD) -> libc::BOOL; }
pub fn SetConsoleMode(hConsoleHandle: libc::HANDLE,
random_line_split
c_windows.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 ...
{ fd_count: libc::c_uint, fd_array: [libc::SOCKET,..FD_SETSIZE], } pub fn fd_set(set: &mut fd_set, s: libc::SOCKET) { set.fd_array[set.fd_count as uint] = s; set.fd_count += 1; } #[link(name = "ws2_32")] extern "system" { pub fn WSAStartup(wVersionRequested: libc::WORD, lpWS...
fd_set
identifier_name
c_windows.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 ...
else { func }) }) } /// Macro for creating a compatibility fallback for a Windows function /// /// # Example /// ``` /// compat_fn!(adll32::SomeFunctionW(_arg: LPCWSTR) { /// // Fallback implementation /// }) /// ``` /// /// Note that...
{ fallback }
conditional_block
lib.rs
//! Board Support Crate for the bluepill //! //! # Usage //! //! Follow `cortex-m-quickstart` [instructions][i] but remove the `memory.x` //! linker script and the `build.rs` build script file as part of the //! configuration of the quickstart crate. Additionally, uncomment the "if using //! ITM" block in the `.gdbinit...
pub mod serial; pub mod frequency;
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serd...
() -> usize { 1 } #[inline] fn max_value() -> usize { ::std::usize::MAX } #[inline] fn from_usize(n: usize) -> Option<usize> { Some(n) } } /// An index type to be used by a `Range` pub trait RangeIndex: Int + fmt::Debug { type Index; fn new(x: Self::Index) -> Self; fn get(self) -> Self::Ind...
one
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serd...
#[inline] pub fn intersect(&self, other: &Range<I>) -> Range<I> { let begin = max(self.begin(), other.begin()); let end = min(self.end(), other.end()); if end < begin { Range::empty() } else { Range::new(begin, end - begin) } } } /// Method...
{ self.begin = begin; self.length = length; }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serd...
} impl ::std::ops::Sub<$Self_> for $Self_ { type Output = $Self_; #[inline] fn sub(self, other: $Self_) -> $Self_ { $Self_(self.get() - other.get()) } } impl ::std::ops::Neg for $Self_ { type Output = $Self_; ...
fn add(self, other: $Self_) -> $Self_ { $Self_(self.get() + other.get()) }
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(custom_derive)] #![feature(plugin)] #![feature(step_trait)] #![plugin(heapsize_plugin)] #![plugin(serd...
else { Range::new(begin, end - begin) } } } /// Methods for `Range`s with indices based on integer values impl<T: Int, I: RangeIndex<Index=T>> Range<I> { /// Returns an iterater that increments over `[begin, end)`. #[inline] pub fn each_index(&self) -> EachIndex<T, I> { eac...
{ Range::empty() }
conditional_block
pascal_str.rs
use std::borrow::{Cow, ToOwned}; use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ffi::{CStr, CString}; use std::str; use ::utf8::PascalString; use ::PASCAL_STRING_BUF_SIZE; #[derive(Hash, Eq, Ord)] pub struct PascalStr { string: str } impl PascalStr { #[inline] pub fn as_ptr(&self) -> *const u8 ...
(&self) -> bool { self.len() == PASCAL_STRING_BUF_SIZE } #[inline] pub fn chars(&self) -> Chars { self.string.chars() } #[inline] pub fn bytes(&self) -> Bytes { self.string.bytes() } #[inline] pub fn lines(&self) -> Lines { self.string.lines() }...
is_full
identifier_name
pascal_str.rs
use std::borrow::{Cow, ToOwned}; use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ffi::{CStr, CString}; use std::str; use ::utf8::PascalString; use ::PASCAL_STRING_BUF_SIZE; #[derive(Hash, Eq, Ord)] pub struct PascalStr { string: str } impl PascalStr { #[inline] pub fn as_ptr(&self) -> *const u8 ...
#[inline] pub fn chars(&self) -> Chars { self.string.chars() } #[inline] pub fn bytes(&self) -> Bytes { self.string.bytes() } #[inline] pub fn lines(&self) -> Lines { self.string.lines() } } impl<S: AsRef<str> +?Sized> PartialEq<S> for PascalStr { #[i...
{ self.len() == PASCAL_STRING_BUF_SIZE }
identifier_body
pascal_str.rs
use std::borrow::{Cow, ToOwned}; use std::cmp::{Ordering, PartialEq, PartialOrd}; use std::ffi::{CStr, CString}; use std::str; use ::utf8::PascalString; use ::PASCAL_STRING_BUF_SIZE; #[derive(Hash, Eq, Ord)] pub struct PascalStr { string: str } impl PascalStr { #[inline] pub fn as_ptr(&self) -> *const u8 ...
} } impl AsRef<str> for PascalStr { #[inline] fn as_ref(&self) -> &str { &self.string } } pub type Chars<'a> = str::Chars<'a>; pub type Bytes<'a> = str::Bytes<'a>; pub type Lines<'a> = str::Lines<'a>; pub struct InteriorNullError;
#[inline] fn to_owned(&self) -> Self::Owned { PascalString::from_str(self.as_str()).unwrap()
random_line_split
htmlobjectelement.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::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; u...
} pub fn is_image_data(uri: &str) -> bool { static types: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; types.iter().any(|&type_| uri.starts_with(type_)) } impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { fn Validity(self) -> Temporary<ValiditySta...
{ let elem: JSRef<Element> = ElementCast::from_ref(*self); // TODO: support other values match (elem.get_attribute(ns!(""), &atom!("type")).map(|x| x.root().Value()), elem.get_attribute(ns!(""), &atom!("data")).map(|x| x.root().Value())) { (None, Some(uri)) => { ...
identifier_body
htmlobjectelement.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::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; u...
(uri: &str) -> bool { static types: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; types.iter().any(|&type_| uri.starts_with(type_)) } impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { fn Validity(self) -> Temporary<ValidityState> { let window...
is_image_data
identifier_name
htmlobjectelement.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::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; u...
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_setter!(SetType, "type") } impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowe...
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type make_getter!(Type)
random_line_split
performance.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::PerformanceBinding; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::...
pub fn new(window: &JSRef<Window>) -> Temporary<Performance> { let performance = Performance::new_inherited(window); reflect_dom_object(box performance, window, PerformanceBinding::Wrap) } } pub trait PerformanceMethods { fn Timing(&self) -> Temporary<PerformanceTiming>; fn Now(&self)...
{ let timing = JS::from_rooted(&PerformanceTiming::new(window).root().root_ref()); Performance { reflector_: Reflector::new(), timing: timing, } }
identifier_body
performance.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::PerformanceBinding; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::...
fn Timing(&self) -> Temporary<PerformanceTiming> { Temporary::new(self.timing.clone()) } fn Now(&self) -> DOMHighResTimeStamp { let navStart = self.timing.root().NavigationStartPrecise() as f64; (time::precise_time_s() - navStart) as DOMHighResTimeStamp } } impl Reflectable for...
impl<'a> PerformanceMethods for JSRef<'a, Performance> {
random_line_split
performance.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::PerformanceBinding; use dom::bindings::js::{JS, JSRef, Temporary}; use dom::...
(&self) -> Temporary<PerformanceTiming> { Temporary::new(self.timing.clone()) } fn Now(&self) -> DOMHighResTimeStamp { let navStart = self.timing.root().NavigationStartPrecise() as f64; (time::precise_time_s() - navStart) as DOMHighResTimeStamp } } impl Reflectable for Performance ...
Timing
identifier_name
mod.rs
use std::fs; use std::io; pub mod cgroup_reader; pub mod ns_reader; pub mod process; fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> { let cgroups = Vec::<cgroup_reader::Reader>::new(); for p in procs { cgroups.push(cgroup_reader::new(p.pid)); } cgroups } pub struc...
} pub fn new(group: ns_reader::NS_Group) -> Container { let (namespaces, process) = group; return Container{ processes: process, namespaces: namespaces, cgroups: load_cgroups(process), update_intv: 1, } }
{ loop { for cgroup in self.cgroups { let kvs = cgroup.read(); for kv in kvs { let (key, val) = kv; println!("{} : {}", key, val); } } } }
identifier_body